content stringlengths 7 1.05M |
|---|
a, b, c, d = 1, 2, 3, 4
print(a, b, c, d)
a, b, c, d = d, c, b, a
print(a, b, c, d)
|
def test_metadata(system_config) -> None:
assert system_config.provider_code == "system"
assert system_config._prefix == "TEST"
def test_prefixize(system_config) -> None:
assert system_config.prefixize("key1") == "TEST_KEY1"
assert system_config.unprefixize("TEST_KEY1") == "key1"
def test_get_variab... |
# -- coding: utf-8 --
#セット設定
set_a = {1,2,3,1,'a',4,'a'}
set_b = {2,3,5,'a',4,'a'}
set_c = {2,5,'b'}
#union(重複分を除いたセットを作成)
print(set_a.union(set_b))
"""
[出力]
set(['a', 1, 2, 3, 4, 5])
"""
print(set_a.union(set_b,set_c))
"""
[出力]
set(['a', 1, 2, 3, 4, 5, 'b'])
"""
#intersection(セットすべてで重複する要素のセットを作成)
print(set_a.inte... |
def read_matrix():
rows_count = int(input())
matrix = []
for _ in range(rows_count):
row = [int(r) for r in input().split(' ')]
matrix.append(row)
return matrix
def get_primary_diagonal_sum(matrix):
p_d_sum = 0
for i in range(len(matrix)):
p_d_sum += matrix[i][i]
... |
'''
1. The algorithm is a substitution cipher. It shifts each letter by a certain key.
2. Python Library Functions used :
a) ord() : Converts a character to its equivalent ASCII value.
b) chr() : Converts an ASCII value to its equivalent character.
3. What are 65 and 97?
a) 65 is the ASCII value of 'A'.
... |
#!/usr/bin/env python3
#!/usr/bin/python3
dict1 = {
'a': 1,
'b': 2,
}
dict2 = {
'a': 0,
'b': 2,
}
if dict1 == dict2:
print("FAIL")
else:
print("PASS")
dict1 = {
'a': {
'c': 'bake'
},
'b': 2,
}
dict2 = {
'a': {
'c': 'shake'
},
'b': 2,
}
if dict1 == di... |
## Grasshopper - Summation
## 8 kyu
## https://www.codewars.com/kata/55d24f55d7dd296eb9000030
def summation(num):
return sum([i for i in range(num+1)])
|
LEFT_ALIGNED = 0
RIGHT_ALIGNED = 1
CENTER_ALIGNED = 2
JUSTIFIED_ALIGNED = 3
NATURAL_ALIGNED = 4 |
score_1 = float(input('Type your 1st score: '))
score_2 = float(input('Type your 2nd score: '))
average = (score_1 + score_2) / 2
print(f'Your average is {average}, therefore you...')
print('Pass. Congrats.') if average > 6 \
else print('Fail. Study again, you\'ll get it. :)')
|
class NoDataError(Exception):
def __init__(self, field, obj, module):
message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module
super(NoDataError, self).__init__(message)
|
"""
Should specifically use:
touchtechnology.common.backends.auth.UserSubclassBackend
touchtechnology.common.backends.auth.EmailUserSubclassBackend
"""
|
""" ``mixin`` module.
"""
class ErrorsMixin(object):
"""Used primary by service layer to validate business rules.
Requirements:
- self.errors
Example::
class MyService(ValidationMixin):
def __init__(self, repository, errors, locale):
# ...
def authe... |
class Event():
def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None):
self.guild_id = guild_id
self.event_type = event_type
self.target_id = target_id
self.target_name = target_name
... |
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda']
nintendo_games.remove('Zelda')
print(nintendo_games)
if 'Wario' in nintendo_games:
nintendo_games.remove('Wario')
|
class Test:
def initialize(self):
self.x = 42
t = Test()
t.initialize()
def calc(self, n):
return self.x + n
Test.calc = calc
assert t.calc(4) == 46
|
# Time: O(n)
# Space: O(1)
#
# 123
# Say you have an array for which the ith element
# is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit.
# You may complete at most two transactions.
#
# Note:
# You may not engage in multiple transactions at the same time
# (ie, you must sell t... |
def firstDuplicateValue(array):
for n in array:
n = abs(n)
if array[n - 1] < 0:
return n
array[n - 1] *= -1
return -1
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def read_gowalla_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
for i in open(file_path):
line = train_file.readline()
# line = line.strip('\n')
if len(line) == 0:
continue
items = line.split("\t")
... |
# Which environment frames do we need to keep during evaluation?
# There is a set of active environments Values and frames in active environments consume memory
# Memory that is used for other values and frames can be recycled
# Active environments:
# Environments for any functions calls currently being evaluated ... |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
return [[nums[j] for j in range(len(nums)) if i&2**j] for i in range(2**len(nums))]
|
def viralAdvertising(n):
return
if __name__ == '__main__':
n = int(input())
viralAdvertising(n)
|
# This is just a demo file
print("Hello world")
print("this is update to my previous code") |
n = int(input())
# n = 3
sum1 = 0
sum2 = 0
for i in range(1, n + 1):
# print("i = ", i)
if i % 2 == 0:
sum1 += i
else:
sum2 += i
if sum1 == 0:
print(sum2)
else:
print(sum2 - sum1)
|
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
length = len(num)
# use dict: value: index + 1
# since there is only one solution, the right value must not be duplicated
dic = {}
for i in xrange(0, length):
val = num[i]
... |
#Tree Size
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def sizeTree(node):
if node is None:
return 0
else:
return (sizeTree(node.left) + 1 + sizeTree(node.right))
# Driver program to test above function
root = Node(1)
ro... |
'''
One Away: There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit (or zero edits) away.
Example:
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> false
b... |
max_n = 10**17
fibs = [
(1, 1),
(2, 1),
]
while fibs[-1][0] < max_n:
fibs.append(
(fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1])
)
print(fibs)
counts = [
1,
1
]
for i in range(2, len(fibs)):
fib = fibs[i]
counts.append(fib[1] + sum(counts[j] for j in range(i - 1)))
... |
# Declare a count_of_a function that accepts a list of strings.
# It should return a list with counts of how many “a” characters appear per string.
# Do NOT use list comprehension.
#
# EXAMPLES:
# count_of_a(["alligator", "aardvark", "albatross"]) => [2, 3, 2]
# count_of_a(["plywood"]) ... |
class StateMachine:
def __init__(self, initialState):
self.currentState = initialState
self.currentState.run()
# Template method:
def runAll(self, inputs):
self.currentState = self.currentState.next_state(inputs)
self.currentState.run()
|
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if not matrix: return res
x = y = i = 0
delta = ((0, 1), (1, 0), (0, -1), (-1, 0))
pos = [0, 0, len(matrix[0])-1, len(matrix)-1] # 左、上、右、下。后面懒得判断推出来的。
while pos[0] <= pos[2] and pos[... |
krediler = ["Hızlı Kredi", "Maaşını Halkbank'tan alanlara özel", "Mutlu emekli ihtiyaç kredisi"]
for kredi in krediler:
print(kredi)
for i in range(len(krediler)):
print(krediler[i])
for i in range(3,10): #3 dahil 10 dahil değil
print(i)
for i in range(0,11,2): #0'dan başla 2'şer 2'şer arttır
print(i) |
def palindrome(word : str) -> int:
"""
Given a string, calculates the amount of palindromes that exist within that string
Parameters
----------
word : str
String that may contain palindrome sub-strings
Returns
-------
int
number of palindromes in string
"""
... |
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2]
def pancake_sort(array):
target_index = len(array)-1
while target_index > 0:
max_value = array[target_index]
max_index = target_index
for number in range(0, target_index):
if array[number] > max_value:
max_value = array[number]
max_index = num... |
# Following are the basic concepts to get started with Python 3.7
"""This is a sample Python
multiline docstring"""
# Display
print("Let's get started with Python")
print("Let's understand", end=" ")
print("The Basic Concepts first")
print("**********************************************************")
# Variables
# I... |
print("Enter the name of the file along with it's extension:-")
a=str(input())
if('.py' in a):
print("The extension of the file is : python")
else:
print("The extension of the file is not python")
|
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2018
# All rights reserved
__author__ = 'Wu Dong <wudong@eastwu.cn>'
__time__ = '2018/9/6 11:07'
|
"""
`EqualizeStrings <http://community.topcoder.com/stat?c=problem_statement&pm=10933>`__
"""
def solution (s, t):
out = ""
for i in range(len(s)):
x = s[i]
y = t[i]
diff = abs(ord(x) - ord(y))
if diff < 26 / 2:
# values are close by, use minimum
out += m... |
# ABC167B - Easy Linear Programming
def main():
# input
A, B, C, K = map(int, input().split())
# compute
kotae = A+(K-A)*0-(K-A-B)
# output
print(kotae)
if __name__ == '__main__':
main()
|
def lin():
print('-'*20)
lin()
def msg(m):
lin()
print(m)
lin()
msg('SISTEMA')
def s(a,b):
print(a+b)
s(2,3)
def cont(*num):
for v in num:
print(v,end=' ')
print('\nfim')
cont(2,3,7)
def dobra(lst):
pos = 0
while pos < len(lst):
lst[pos] *= 2
pos += 1
valo... |
inst = set()
with open('tools/write_bytecode.py') as file:
for line in file:
if line.strip().startswith('#'):
continue
if '$' in line:
instruction = line.split('$')[1].strip()
print(instruction)
inst.add(instruction.split()[0].strip().replace('32',... |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
i = j = 0 # j records number of '0' and '1', and i records number of '0'
for k in range(len(input_list)):
v = i... |
input = """
q(X) :- p(f(X)).
p(f(X)) :- r(X), q(X).
q(a).
r(a).
"""
output = """
q(X) :- p(f(X)).
p(f(X)) :- r(X), q(X).
q(a).
r(a).
"""
|
################################################################
# compareTools.py
#
# Defines how nodes and edges are compared.
# Usable by other packages such as smallGraph
#
# Author: H. Mouchere, Oct. 2013
# Copyright (c) 2013-2014 Richard Zanibbi and Harold Mouchere
################################################... |
"""Define the abstract class for similarity search service controllers"""
class SearchService:
"""Search Service handles all controllers in the search service"""
def __init__(self):
pass
def load_index(self):
pass
def load_labels(self):
pass
def similar_search_vectors(s... |
# -*- coding: utf-8 -*-
def main():
n = int(input())
s = list()
t = list()
for i in range(n):
si, ti = map(str, input().split())
s.append(si)
t.append(int(ti))
x = input()
index = s.index(x)
print(sum(t[index + 1:]))
if __name__ == '__main__':
... |
### Alternating Characters - Solution
def alternatingCharacters():
q = int(input())
while q:
s = input()
del_count = 0
for i in range(len(s)-1):
if s[i] == s[i+1]:
del_count += 1
print(del_count)
q -= 1
alternatingCharacters() |
class FileWarning(Exception):
def __init__(self, file, message, *args, **kwargs):
file.warn(message, *args, **kwargs)
super().__init__(message % args)
class FileError(Exception):
def __init__(self, file, message, *args, **kwargs):
file.error(message, *args, **kwargs)
super().... |
'''
排序算法汇总:
bucket sort 桶排序
插入排序 insertion:
1. insertion sort 直接插入排序 stable
2. shell sort 希尔排序/分组插入排序 unstable
选择排序 selection:
1. selection sort 简单选择排序 unstable
2. heap sort 堆排序 unstable
交换排序 swap:
1. bubble sort 冒泡排序 stable
2. quick sort 快排 unstable
归并排序 merge sort
快速排序 quick sort
'''
def bucket_sort(nums):
... |
class RenderedView(object):
def __init__(self, view_file: str, data):
self.view_file = view_file
self.data = data
|
# PART 1
def game_of_cups(starting_sequence,num_of_moves,min_cup=None,max_cup=None):
# create a "linked list" dict
cups = {
starting_sequence[i] : starting_sequence[i+1]
for i in range(len(starting_sequence)-1)
}
cups[starting_sequence[-1]] = starting_sequence[0]
#
current_cup = ... |
txt = 'asdf;lkajsdf,as;lfkja'
for i in txt:
txt = txt[1:]
if i == ",":
break
print(txt) |
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
... |
description = 'Email and SMS notifiers'
group = 'lowlevel'
devices = dict(
email = device('nicos.devices.notifiers.Mailer',
mailserver = 'mailhost.frm2.tum.de',
sender = 'kws1@frm2.tum.de',
copies = [
('g.brandl@fz-juelich.de', 'all'),
('a.feoktystov@fz-juelich.de',... |
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height > 120:
print("you can ride the rollercoaster!")
age = int(input("What is your age? "))
if age <= 18:
print("$7")
else:
print("$12")
else:
print("no")
|
# "Config.py"
# - config file for ConfigGUI.py
# This is Python, therefore this is a comment
# NOTE: variable names cannot start with '__'
ECGColumn = True
HRColumn = False
PeakColumn = True
RRColumn = True
SeparateECGFile = True
TCP_Host = "localhost"
TCP_Port = 1000
TCPtimeout = 3
TimeColumn = True
UDPConnectTimeo... |
'''
Exercise 1:
Write a Python function display_dico(dico) that takes a dictionary as parameter and print the
content of the dictionary, one paired element per line as follow:
Key --> Value
For example:
>>> display_dico({“un”:1, “deux”:2, “trois”:3})
un --> 1
deux --> 2
trois --> 3
Note: if the order in which the mappe... |
"""
Names scores
Using problem_22.txt, a 46K text file containing over five-thousand first
names, begin by sorting it into alphabetical order. Then working out the
alphabetical value for each name, multiply this value by its alphabetical
position in the list to... |
class Dictionary(object):
def __init__(self):
self.my_dict = {}
def look(self, key):
return self.my_dict.get(key, "Can't find entry for {}".format(key))
def newentry(self, key, value):
""" new_entry == PEP8 (forced by Codewars) """
self.my_dict[key] = value
|
hidden_dim = 128
dilation = [1,2,4,8,16,32,64,128,256,512]
sample_rate = 16000
timestep = 6080
is_training = True
use_mulaw = True
batch_size = 1
num_epochs = 10000
save_dir = './logdir'
test_data = 'test.wav' |
#! /root/anaconda3/bin/python
score = 88
result = '及格了' if score >= 60 else '没及格了'
print(result)
a = 7
b = 1
print('a > b' if a > b else ('a < b' if a < b else 'a == b'))
|
# This file provides an object for version numbers.
class Version:
def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=""):
self.major = major
self.minor = minor
self.patch = patch
self.tag = tag
def __repr__(self):
return "Version(" + str(self.major... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
self.result = []
self.wft([root])
return self.resu... |
class airQuality:
def __init__(self, bus):
self.iaq = 0
self.bus = bus
self.address = 0x5A
self.datablock = 9
self.data = 0
def read(self):
data = self.bus.read_i2c_block_data(self.address, 0x00, self.datablock)
#WIP
# Convert the data
#if... |
#You are given a list of n-1 integers and these integers are in the range of 1 to n.
#There are no duplicates in the list.
#One of the integers is missing in the list. Write an efficient code to find the missing integer
ar=[ 1, 2, 4, 5, 6 ]
def missing_(a):
print("l",l)
for i in range(1,l+2):
if(i not in a):
... |
class Utils():
""" This is just methods stored as methods of a class.
It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy.
(It is nice, as in this case, to separate constants from methods.)
"""
def __init__(self):
self.species = {'canines' : ['Doggy', 'Hyena'],... |
print('Enter a text and when finished press Enter twice: ')
text = ''
while True:
line = input()
if line:
text += line + '\n '
else:
break
def wc(text):
n_words = len(text.split(' ')) - 1
n_lines = len(text.split('\n')) - 1
n_characters = len(text) - 2*n_lines
... |
nota1 = int(input('Nota 1: '))
nota2 = int(input('Nota 2: '))
media = (nota1 + nota2) / 2
print('Média: {:.2f}'.format(media))
|
def sample_anchors_pre(df, n_samples= 256, neg_ratio= 0.5):
'''
Sample total of n samples across both BG and FG classes.
If one of the classes have less samples than n/2, we will sample from majority class to make up for short.
Args:
df with column named labels_anchors, containing 1 for f... |
ansOut = []
coin = [10, 50, 100, 500]
while True:
price = int(input())
if price == 0:
break
cash = list(map(int, input().split()))
sumCash = sum(c * n for c, n in zip(coin, cash))
change = sumCash - price
changeCoins = [(change % 50) // 10, (change % 100) // 50, (change % 500) // 100, ch... |
# Desenvolva um programa que leia o comprimento de 3 reretas e diga se
# elas podem ou nao formar um triângulo
l1 = float(input("Diga o primeiro lado"))
l2 = float(input("Diga o segundo lado"))
l3 = float(input("Diga o terceiro lado"))
if (l1 + l2 < l3) or (l1 + l3 < l2) or (l1 > l2 + l3):
print("Não é triângulo"... |
def isBalanced(expr):
if len(expr)%2!=0:
return False
opening=set('([{')
match=set([ ('(',')'), ('[',']'), ('{','}') ])
stack=[]
for char in expr:
if char in opening:
stack.append(char)
else:
if len(stack)==0:
return False
... |
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 0, x
while left <= right:
mid = left + (right - left) // 2
square = mid ** 2
if square <= x:
left = mid + 1
elif squ... |
In [18]: my_list = [27, "11-13-2017", 84.98, 5]
In [19]: store27 = salesReceipt._make(my_list)
In [20]: print(store27)
salesReceipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022/1/8 8:01 下午
# @Author: zhoumengjie
# @File : BondBuilder.py
class BondPage:
def __init__(self):
# 申购评测
self.apply_bonds = []
# 证监会核准/同意注册
self.next_bonds = []
# 已申购完,即将上市的
self.ipo_bonds = []
# 隔日... |
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []}
def dfs_topsort(graph): # recursive dfs with
L = [] # additional list for order of nodes
color = { u : "white" for u in graph }
found_cycle = [False]
for u in graph:
if color[u] == "white":
dfs_visit(graph,... |
#!/usr/bin/env python3
flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacb... |
#!/usr/bin/python3.5
def fib(n: int):
fibs = [1, 1]
for _ in range(max(n-2, 0)):
fibs.append(fibs[-1] + fibs[-2])
return fibs[n-1]
print("%s" % fib(38))
|
M,N,K = [int(x) for x in input().split()]
a = [int(input()) for i in range(K)]
supporter = [N] + [0] * M
#supporter[i]は立候補者iを支持している有権者の人数を表す
#i=0は誰も支持していない人数を表す
for a_item in a:
count = 0
for x in range(len(supporter)):
#立候補者a_itemが演説するとき,他の立候補者の支持者状況を確認する
if x != a_item and supporter[x] != ... |
"""
Sponge Knowledge Base
Remote API
"""
class UpperCase(Action):
def onConfigure(self):
self.withArg(StringType("text").withLabel("Text to upper case")).withResult(StringType().withLabel("Upper case text"))
def onCall(self, text):
self.logger.info("Action {} called", self.meta.name)
re... |
# SOMENTE GÊNEROS CORRETOS!
# um pouco mais inclusivo do q o original :)
g = str(input('Insira seu gênero [M|F|T|Q|N]: _ ')).strip().upper()[0]
while g not in 'MFTQN':
g = str(input('Formato incorreto! Tente novamente.\nInsira seu gênero [M|F|T|Q|N]: _ ')).strip().upper()[0]
print('Obrigado. Gênero {} registrado c... |
def method1(str1: str, str2: str) -> int:
def compare(str1, str2):
for i in range(256):
if str1[i] != str2[i]:
return False
return True
def search(pat, txt):
m = len(pat)
n = len(txt)
count_p = [0] * 256
count_t = [0] * 256
f... |
# coding=utf8
class Error(Exception):
pass
class TitleRequiredError(Error):
pass
class TextRequiredError(Error):
pass
class APITokenRequiredError(Error):
pass
class GetImageRequestError(Error):
pass
class ImageUploadHTTPError(Error):
pass
class FileTypeNotSupported(Error):
pass... |
class Tree(object):
def __init__(self):
self.children = []
self.metadata = []
def add_child(self, leaf):
self.children.append(leaf)
def add_metadata(self, metadata):
self.metadata.append(metadata)
def sum_metadata(self):
metasum = sum(self.metadata)
for... |
print("RENTAL MOBIL ABCD")
print("-------------------------------")
#Input
nama = input("Masukkan Nama Anda : ")
umur = int(input("Masukkan Umur Anda : "))
if umur < 18:
print("Maaf", nama, "anda belum bisa meminjam kendaraan")
else:
ktp = int(input("Masukkan Nomor KTP Anda : "))
k_mobil = in... |
def func_that_raises():
raise ValueError('Error message')
def func_no_catch():
func_that_raises()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 07:34:02 2020
@author: krishan
"""
class BaseClass:
num_base_calls = 0
def call_me(self):
print("Calling method on Base Class")
self.num_base_calls += 1
class LeftSubclass(BaseClass):
num_left_calls = 0
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2017 JiNong Inc. All right reserved.
#
__title__ = 'python-pyjns'
__version__ = '0.40'
__author__ = 'Kim, JoonYong'
__email__ = 'joonyong.jinong@gmail.com'
__copyright__ = 'Copyright 2016-2017 JiNong Inc.'
|
"""
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
... |
extensions = [
"cogs.help",
"cogs.game_punishments.ban",
"cogs.game_punishments.kick",
"cogs.game_punishments.unban",
"cogs.game_punishments.warn",
"cogs.settings.setchannel",
"cogs.verification.verify"
]
|
def __getitem__(self,idx):
if idx < self.lastIndex:
return self.myArray[idx]
else:
raise LookupError('index out of bounds')
def __setitem__(self,idx,val):
if idx < self.lastIndex:
self.myArray[idx] = val
else:
raise LookupError('index out of bounds')
|
__author__ = "Amane Katagiri"
__contact__ = "amane@ama.ne.jp"
__copyright__ = "Copyright (C) 2016 Amane Katagiri"
__credits__ = ""
__date__ = "2016-12-07"
__license__ = "MIT License"
__version__ = "0.1.0"
|
'''
https://www.guazi.com/huzhou/buy/o2/#bread
第一页:o1
第二页:o2
……
第n页:on
'''
url='https://www.guazi.com/huzhou/buy/o{}/#bread'
for page in range(1,51):
page_url=url.format(page)
print(page_url) |
example_dict = {}
for idx in range(0, 10):
example_dict[idx] = idx
for key, value in example_dict.items():
formmating = f'key is {key}, value is {value}'
print(formmating) |
def minimumSwaps(arr):
a = dict(enumerate(arr,1))
b = {v:k for k,v in a.items()}
count = 0
for i in a:
x = a[i]
if x!=i:
y = b[i]
a[y] = x
b[x] = y
count+=1
return count
n = int(input())
arr = list(map(int,input(... |
class TMVError(Exception):
""" Base exception """
class CameraError(Exception):
"""" Hardware camera problem"""
class ButtonError(Exception):
""" Problem with (usually hardware) buttons """
class VideoMakerError(Exception):
""" Problem making images into a video """
class ImageError(Exception):
... |
"""
@Pedro Santana Abreu (https://linktr.ee/pedrosantanaabreu)
@Icev (https://somosicev.com)
PT-BR:
Faça um programa que receba a quantidade de dinheiro em reais que uma pessoa que vai viajar possui.
Ela vai passar por vários países e precisa converter seu dinheiro em dólares, euros e libra esterlina.
Sabe-se que a co... |
year = 2022
if year%4==0 and year%100!=0 or year%400==0:
print(year,"是闰年")
else:
print(year,"不是闰年")
|
def extract_characters(*file):
with open("file3.txt") as f:
while True:
c = f.read(1)
if not c:
break
print(c)
extract_characters('file3.txt') |
class MTUError(Exception):
pass
class MACError(Exception):
pass
class IPv4AddressError(Exception):
pass
|
def cyclesort(lst):
for i in range(len(lst)):
if i != lst[i]:
n = i
while 1:
tmp = lst[int(n)]
if n != i:
lst[int(n)] = last_value
lst.log()
else:
lst[int(n)] = None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.