content stringlengths 7 1.05M |
|---|
"""
Problem Statement:
Given a non-empty array of integers,
every element appears twice except for one.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
"""
def single_number(integers):
unique = 0
for integer in integers:... |
#define the main
def main():
i = 0 #declare an integer i
x = 119.0 #declare a float x
for i in range(120): #loop i from 0 to 119
if ((i%2)==0): #if i is even
x += 3. #add 3
else: #if i is odd
x -= 5. #subtract 5 from x
s = "%3.2e" % x #make a string containing x
print(s)
if __... |
#class memorySetting():
global packet_db
packet_db = {}
# Schema
# Key for access is MAC Address/IP Address
# * Initially had mac address (assuming unique) as the only key
# - CTF problems sometime cause a scenario of same mac with different IP address so segregated this
# * Otherwise each key holds
# - Mac Vend... |
def test():
assert "learner.summary()" in __solution__, "summary() 메서드를 사용하셨나요?"
assert "learner.unfreeze()" in __solution__, "unfreeze() 메서드를 사용하셨나요?"
__msg__.good("잘 하셨습니다!")
|
# -*- coding: Latin-1 -*-
# pycrc -- parametrisable CRC calculation utility and C source code generator
#
# Copyright (c) 2006-2011 Thomas Pircher <tehpeh@gmx.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software... |
sm = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
sm2 = [[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]]
def snail(snail_map):
ans = []
c = 0
nMtx = snail_map
l = len(snail_map)
for i in snail_map[0]:
ans.append(i)
for i in range(l):
if... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019, Gianluca Fiore
#
###############################################################################
__author__ = "Gianluca Fiore"
class Node(object):
def __init__(sel... |
class A(object):
val = 1
class B(A):
pass
class C(A):
pass
print(A.val, B.val, C.val)
B.val = 2
print (A.val, B.val, C.val)
A.val = 3
print (A.val, B.val, C.val)
"""
Explanation:
In Python,{{{{ class variables are internally handled as dictionaries}}}}.
If a variable name is not found in the dictionary of the curr... |
##This program finds all the numbers between 1500 and 2700 that are
##divisible by 5 and 7.
n = range(1500, 2700)
newlist = []
for i in n:
if (i%7==0) and (i%5==0):
newlist.append(str(i))
print(newlist)
|
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d={}
for i,x in enumerate(s):
if x in d:
continue
elif s[i:].count(x)==1:
return i
else:
d[x]=1
... |
def test_augassign():
r: i32
s: i32
r = 0
r += 4
s = 5
r *= s
r -= 2
s = 10
r /= s
a: str
a = ""
a += "test"
|
'''
Descripttion:
version:
Author: HuSharp
Date: 2021-02-09 11:34:48
LastEditors: HuSharp
LastEditTime: 2021-02-09 11:42:18
@Email: 8211180515@csu.edu.cn
'''
def count(s, val):
'''cnt the val 's nums in s
>>> count([1,2,3,4,1], 1)
2
'''
total = 0
for element in s:
if element == val:
... |
__title__ = 'krnl'
__url__ = 'https://github.com/cens6r/krnl.py/'
__author__ = 'Cens6r'
__email__ = 'cens6r@no-email-yet'
__license__ = 'MIT License'
__version__ = '1.0.0'
__description__ = 'Utilize the KRNL Api easily from python'
|
class Solution(object):
def minTimeToVisitAllPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
t = 0
for i in range(len(points) - 1):
t += self._time(points[i], points[i + 1])
return t
def _time(self, pa, pb):
t1 ... |
class DiffLineState:
INSERT = 0
DELETE = 1
UNCHANGED = 2
class DiffLine():
def __init__(self):
self.text = None
self.state = DiffLineState.UNCHANGED
class DiffChange():
def __init__(self):
self.oldStartLine = None
self.newStartLine = None
self.description = ... |
# 3 Sum
# Medium
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
# print(nums)
result_list = set()
for i, num in enumerate(nums):
if i < len(nums) - 2... |
def binary_search(sorted_list, key):
if type(key) is not int:
raise TypeError('Argument invalid. Must be int.')
left = 0
right = len(sorted_list) - 1
while left != right:
# import pdb; pdb.set_trace()
if (left + right) % 2:
if sorted_list[int((left + right) / 2)] == k... |
# -*- coding: utf-8 -*-
log_file = "autogreeter.log" # Fill this out for a logging. P.S It's a must!
slack_token = "" # token for slack bot
welcomemessagedm = "" # what the bot should dm the person
welcomemessagechannel = "" # what should the bot post on a channel, leave empty to not post
|
# 讀取檔案內容
files = open("stores.txt","r", encoding='utf-8')
# 建立一個空的串列,準備接收檔案的每一行文字
stores = []
# 利用迴圈將每一行文字,放入串列
for i in files:
stores.append(i)
print(stores)
print("第五家店:",stores[4])
# 關閉檔案
files.close() |
table = [
'Feature | This Lib | Classical Singleton | [herpe] | [ugrif] | [xytis] | [aworx] | [fwolt] | [zyf38] | [cheno] | [cppma]',
'supports instance replacement for testing | X | - | - | - | - | - | - | - | X | X',
'2-phase initialization avoidable| X | - | - | - | - | - | - | - | - | -',
'control ... |
print('Conversor de medidas')
n1 = float(input('Digite o valor em metros que deseja converter: '))
n2 = n1*100
n3 = n1*1000
print('Seu valor em centímetros vale {:.0f}cm,'
' \n seu valor em milímetros vale {:.0f}mm'.format(n2, n3))
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 15:37:04 2020
@author: CHANGE WITH YOUR NAME
This is a blablabla..
"""
print(3+4)
print(3, 4, 3+4)
print("3 4 3+4")
print()
print("The answer is 3+4")
|
def cross(u, v):
"""
return the cross product of 2 vectors.
"""
dim = len(u)
s = []
for i in range(0, dim):
if i == 0:
j,k = 1,2
s.append(u[j]*v[k] - u[k]*v[j])
elif i == 1:
j,k = 2,0
s.append(u[j]*v[k] - u[k]*v[j])
else:
j,k = 0,1
... |
"""
instance.py contains the basic classes of the items in a study plan card,
like university, faculty, major, and course. This was made to 'objectify' the
data fetched from the courses.json file
"""
class University:
"""Wrapper for University item"""
def __init__(self, name=None, faculties=[], aliases=[]):
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
dummy_head = ListNode()
dummy_head.nex... |
# -*- coding: utf-8 -*-
"""Top-level package for cui_okinawa."""
__author__ = """anosillus"""
__email__ = "anosillus@gmail.com"
__version__ = "0.1.0"
|
class Node:
def __init__(self, value=""):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
self.values=[]
def insert(self, value):
self.values.append(value)
node = Node(value)
if self.head:
n... |
#
# PySNMP MIB module NetWare-Host-Ext-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NetWare-Host-Ext-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:16:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
#!/user/bin/python
# -*-coding:UTF-8-*-
"""使用列表实现优先队列,
优先队列的特点是存入队列中的每项数据都另外附有一个值,表示这项的优先程度,称为优先级。
优先队列保证,任何时刻出队或访问的都是这个结构中优先级最高的一项。
"""
class PrioQueueError(ValueError):
pass
class PrioQueue:
def __init__(self, elist=[]):
self._elems = list(elist)
self._elems.sort(reverse=True)
def i... |
def notas(*nums, sit=False):
"""
--> Função para verificar as notas do aluno:
:param nums: Notas que o usuário tem que digitar
:param sit: [opcional] Se True, a situação em que o aluno está é indicada
:return: Dicionário com todas as informações
"""
infos = {'qntd_notas': len(nums), 'maior ... |
""" Mime type data
"""
MIME_TYPES = {
'png': "image/png",
'svg': "image/svg+xml",
'eps': "application/postscript",
'dw': "text/plain",
}
|
# config.py
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_path():
return "doc_classes"
def get_doc_classes():
return [
"MySQL",
]
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/nvidia/catkin_ws/src/my_pkg3/msg/MABX.msg;/home/nvidia/catkin_ws/src/my_pkg3/msg/a.msg"
services_str = ""
pkg_name = "my_pkg3"
dependencies_str = "std_msgs"
langs = ""
dep_include_paths_str = "my_pkg3;/home/nvidia/catkin_ws/src/my_pkg3/msg;std_m... |
# greet.py| prints hello world to the console
message = 'Hello World'
print(message)
|
"""
PASSENGERS
"""
numPassengers = 30585
passenger_arriving = (
(6, 7, 5, 12, 5, 4, 3, 0, 3, 0, 0, 1, 0, 12, 9, 9, 3, 5, 2, 3, 2, 3, 0, 1, 2, 0), # 0
(8, 12, 2, 2, 8, 3, 3, 1, 2, 2, 1, 0, 0, 14, 10, 7, 6, 5, 4, 4, 3, 6, 3, 2, 2, 0), # 1
(7, 11, 10, 8, 6, 2, 4, 4, 5, 1, 2, 1, 0, 10, 7, 6, 9, 7, 5, 3, 4, 4, 4, 0,... |
#!/usr/bin/env python
class HashImpl(object):
def __init__(self):
self._tree = {}
def insert(self, word):
if word:
t = self._tree
for a in list(word):
if a in t:
t = t[a]
else:
t[a] = {}
... |
mqtt_broker = "192.168.10.254"
mqtt_client_id = b"esp_kitchen_servo_switch"
mqtt_topic = b"kitchen/light1"
mqtt_user = "homeassistant"
mqtt_password = "internetofthings"
|
# Define Class/ Properties
class IO: # Class
supportedSrcs=["console","file"] #attributes
def read(src): #attributes
if src not in IO.supportedSrcs:
print("Not supported")
else:
print("Read from", src)
# Use class
print(IO.supportedSrcs)
IO.read("file")
IO.read("i... |
n = int(input())
time = []
for i in range(n):
time.append(hour+minute)
hour, minute = input().split()
count_max = 1
count = 1
for i in range(1,n):
if time[i] == time[i-1]:
count += 1
else:
count = 1
if count > count_max:
count_max = count
print(count_max) |
lst = [int(i) for i in input().split()]
x = int(input())
k = []
q = 0
for i in lst:
if i == x:
k += [q]
q +=1
if len(k) == 0:
print('Отсутствует')
else:
print(*k)
|
class Project:
def __init__(self, name, status="development", inherit=True, view_status="public", description="default"):
self.name = name
self.status = status
self.inherit = inherit
self.view_status = view_status
self.description = description
def __eq__(self, other):
... |
nota1 = float(input('digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2)/2
if media >= 6:
print('Sua media é exelente!! {} '.format('\U0001F496'))
else:
print('Sua media é ruin ESTUDE MAIS {} '.format('\U0001F4A2'))
# o codigo ->\U0001F4A2<- e o codigo ->\U0001F49... |
custom_values = {"name": "pinto", "default_code": "p001", "default_value": 100}
new_values = {}
for key, value in custom_values.items():
if 'default_' in key:
new_key = key[8::]
new_values[new_key] = value
else:
new_values[key] = value
print(new_values)
|
class BoardPrecinct():
precinct_map = (
'Upload a PDF file that represent the boundaries of this precinct.'
)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test module '
__author__ = 'Ahrli Tao'
IP_URL = 'http://127.0.0.1:6868/proxies/random'
def get_proxies():
url = IP_URL
response = requests.get(url=url)
if response is None:
time.sleep(1)
get_proxies()
proxies_ip = response.text
pro... |
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
# O(n) time | O(n) space - where n is the number of nodes in the Linked List
def linkedListPalindrome(head):
isPalindromeResults = isPalindrome(head, head)
return isPalindromeResults.outerNodesA... |
_base_ = './htc_r50_fpn_1x_coco.py'
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='torchvision://resnet101')))
# learning policy
lr_config = dict(step=[16, 19])
runner = dict(type='EpochBasedRunner', max_epochs=20)
|
"""Songs that people need to play back.
"""
class Song:
def get_note_time(self):
""" returns a list of [[note, time], ...]
"""
def load(self, fname):
""" load a song from the given name.
"""
raise NotImplementedError("need to load stuff from s... |
"""
ChatterBot constants
"""
'''
The maximum length of characters that the text of a statement can contain.
This should be enforced on a per-model basis by the data model for each
storage adapter.
'''
STATEMENT_TEXT_MAX_LENGTH = 400
|
# https://www.hackerrank.com/challenges/triple-sum/problem?isFullScreen=true
def triplets(a, b, c):
a = list(sorted(set(a)))
b = list(sorted(set(b)))
c = list(sorted(set(c)))
ai = 0
bi = 0
ci = 0
ans = 0
while bi < len(b):
while ai < len(a) and a[ai] <= b[bi]:
... |
def parse(a):
a = a.split("\n")
a = [x+", " for x in a]
a = [''.join(a[i:i+6])+"\n" for i in range(0, len(a), 6)]
print(''.join(a))
|
def string_handler(words: str) -> str:
length = len(words)
pos = length // 2
left = words[:pos]
right = words[pos + 1 if length % 2 else pos::][::-1]
return "yes" if left == right else "no"
def main():
while True:
try:
data = input()
print(string_handler(data))
... |
#!/usr/bin/env python
#title :busy_load.py
#description :Get the busiest or the most loaded disk from a trace
#author :Vincentius Martin
#date :20150203
#version :0.1
#usage :
#notes :
#python_version :2.7.5+
#precondition :ordered
#===================... |
def count_variants(event_log,return_variants=False):
current_case = ""
current_variant = ""
caseIDColName = "Case ID"
activityColName = "Activity"
variants = set()
for index, row in event_log.iterrows():
activity = row[activityColName]
if row[caseIDColName] != current_case:
... |
#
# PySNMP MIB module TIARA-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIARA-QOS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
'''
builtin functions
'''
def main():
o = ord('x')
TestError( o == 120 )
#n = float('1.1')
#TestError( n==1.1 )
#n = float('NaN')
#TestError( isNaN(n)==True )
#r = round( 1.1234, 2)
#print(r)
#TestError( str(r) == '1.12' )
#r = round( 100.001, 2)
#TestError( r == 100 )
#i = int( 100.1 )
#TestError( ... |
#
# PySNMP MIB module ASCEND-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:09:57 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, 09:... |
def solution(A):
B = []
best_dif = 100000000000
sum = 0
for i in A:
sum += i
sum_left = 0
sum_right = sum
for i in A[:-1]:
sum_left += i
sum_right -= i
dif = abs(sum_left - sum_right)
if dif < best_dif:
best_dif = dif
return best_dif
|
def long_usage_messenger():
return """
PDB.py
optional arguments:
-h, --help show this help message and exit
-rftf text_file_with_PDB.tsv, --renumber_from_text_file text_file_with_PDB.tsv
This option will download and renumber specified files
usage $ python3 PDB.py -rftf text_file_with_PDB_in_it.tsv -mm... |
my_list = [1, 2.0, "three", 4]
my_tup = (1, 2.0, "three", 4)
my_set = {1, 2.0, "three", 4}
my_str = "1, 2.0, three, 4"
# Subscripting ordered datatypes
print(my_list[0]) # indexing
print(my_tup[0:2]) # slicing
print(my_str[-8:]) # negative index and slice
# Adding elements
my_list.append(5.0)
print("my_l... |
'''
nimpy module created for working with nimrod using python
Main dependencies are:
numpy
scipy
h5py
struct
os
argparse
subprocess
This module was developed for simulations run at WiPAL in
the physics department at UW-Madison. The main nimrod build
used to test features was nimuw 3.4.10, a... |
TASKS = []
class Context:
def __init__(self, sources, target):
self.sources = sources
self.target = target
@property
def source(self):
return self.sources[0]
class Task:
def __init__(self, matcher, handler, phony=False):
self.matcher = matcher
self.handler = ... |
def reversort(lst):
n = len(lst)
cnt = 0
for i in range(n - 1):
j = min(range(i, n), key=lambda j: lst[j])
cnt += j - i + 1
lst[i : j + 1] = lst[i : j + 1][::-1]
return cnt
t = int(input())
for i in range(t):
input()
(*lst,) = map(int, input().split())
cnt = reverso... |
greater = 0
one = int(input())
two = int(input())
three = int(input())
while inp := input():
current = int(inp)
last_sum = one + two + three
current_sum = two + three + current
if current_sum > last_sum:
greater += 1
one = two
two = three
three = current
print(greater)
|
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
class EmptyInputException(Exception):
def __init__(self, *args, **kwargs):
super().__init__('Input path must be non-empty')
class InvalidInputException(Exception):
def __init__(self, *args, **kwargs):
super().__init__('Input path is invalid')
class InvalidURLException(Exception):
def ... |
# 返回值代码
class RET:
OK = 200
CREATED = 201
ACCEPTED = 202
NO_CONTENT = 204
UNAUTHORIZED = 401
FORBBIDEN = 403
NOT_FOUND = 404
NOT_ACCEPTABLE = 406
GONE = 410
UNPROCESA... |
def convert_bytes(byte):
units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB'
'YiB', 'BiB', 'NiB', 'DiB', 'CiB']
for x in units:
if divmod(byte, 1024)[0] == 0:
break
else:
byte /= 1024
return ('%.2lf%s' % (byte, x))
|
def test_function(some_value):
"""This is just a test function to show the issues
with PyCharm text."""
if some_value <= 10:
print('{} is below 10'.format(some_value))
else:
print('{} at least 10'.format(some_value))
test_function(4)
test_function(12) |
soma=produtos_mais_de_mil=preco_produto_caro=0
produto_mais_caro=''
while True:
produto=str(input('Digite o nome do produto: ')).strip()
valor_produto=float(input('Digite o valor do produto: $'))
saida=str(input('Deseja continuar? [S/N] ')).strip().upper()
while saida != 'S' and saida != 'N':
sa... |
# M6 #7
# the list in the module assignment is only 19 names, I have added the 20th
famous_list = ''' \
Marilyn Monroe (1926 – 1962) American actress, singer, model
Abraham Lincoln (1809 – 1865) US President during American civil war
Nelson Mandela (1918 – 2013) South African President anti-apartheid campaigner
Joh... |
def read_sender_input():
try:
input_data = input()
return classify_input(input_data)
except EOFError:
return None,None
def classify_input(input_data):
attribute = input_data.split(' ')
if ValidInput(attribute):
temperature = float(attribute... |
def configure(conf):
conf.recurse('armv7a.py', once=False)
conf.env.VALID_ARCHITECTURES = ['armv7s'] + conf.env.VALID_ARCHITECTURES
conf.env.append_unique('DEFINES', ['_ARM_V7S'])
|
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:r... |
"""
Custom exceptions
"""
class ImproperlyConfigured(Exception):
"""Raised when demosys is configured incorrectly"""
pass
|
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
n = len(A)
left = [0]*n
# max left slice
for i in range(1, n-1):
left[i] = max(0, left[i-1] + A[i])
right = [0]*n
# max righ... |
######################################################################
# Author: Dr. Patrick Shepherd TODO: Change this to your names
# Username: shepherdp TODO: Change this to your usernames
#
# Assignment: T5: Buggy Fruit
# Purpose: A flawed birthday program
########################################... |
waf_checker = [ " '",
" AND 1",
" /**/AND/**/1",
" AND 1=1",
" AND 1 LIKE 1",
" ' AND '1'='1",
"<img src=x onerror=alert('XSS')>",
"<img onfoo=f()>",
"<script>alert('intrusion')</script>"
... |
'''
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must b... |
class SearchList(list):
def find(self, name):
items = []
for child in self:
if child.__class__ == self.__class__:
items += child.find(name)
else:
if child == name:
items.append(child)
if len(items) == 1:
... |
#
# PySNMP MIB module ALCATEL-IND1-STACK-MANAGER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-STACK-MANAGER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:19:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... |
class Solution:
def maxArea(self, height):
left, right, mx = 0, len(height) - 1, 0
while left < right:
mx = max(mx, (right - left) * min(height[left], height[right]))
if height[left] < height[right]:
left += 1
else:
right -= 1
... |
'''input
-1000000000 1000000000
Zero
-1 0
Zero
1 3
Positive
-3 -1
Negative
-4 -1
Positive
-1 1
Zero
0 1
Zero
'''
# -*- coding: utf-8 -*-
# AtCoder Grand Contest
# Problem A
if __name__ == '__main__':
a, b = list(map(int, input().split()))
if a * b <= 0:
print('Zero')
elif (a >= 1) or ((b... |
class OctaveCycle:
Length = 12# 1オクターブあたりのノート数
def __init__(self, length=12):
self.Length = length
# self.__toneLength = length
"""
1オクターブあたりの音に識別番号(0〜Length-1)を振る。
"""
@classmethod
def Cycle(cls, keyId, pitch):
p = pitch + (keyId // 12)
if 0 <= keyId:
... |
# Для заданих n та a обчислити суму s = 1 + 2²a + ... + n²aⁿ⁻¹ = ∑(i=1, n) i²aⁱ⁻¹.
if __name__ == "__main__":
n, a = map(int, input("n, a = ").split()) # ввід n, a
s = sum(i ** 2 * a ** (i - 1) for i in range(1, n + 1)) # до s в циклі додаємо i²aⁱ⁻¹ від 1 до n
print(f"\n{n = }, {a = }\n{s = }")
|
"""
Module: 'gc' on esp32_LoBo 3.2.9
"""
# MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.9', version='ESP32_LoBo_v3.2.9 on 2018-04-12', machine='ESP32 board with ESP32')
# Stubber: 1.1.2
def collect():
pass
def disable():
pass
def enable():
pass
def isenabled():
pass
def mem_alloc(... |
"""3. 将列表中的数字累减
list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
提示:初始为第一个元素"""
list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
start=list02[0]
for i in list02[1:len(list02)]:
start-=int(i)
print(start)
|
# Can 31 dominoes cover all but two opposite corners of a chess board?
def dominoes():
# Each dominoe must cover one black and one white square.
# But there are different numbers of black and white squares.
# Read up on such parity arguments here:
# http://ihxrelation.blogspot.com/2015/10/tiling-problems.html
... |
def merger_first_into_second(arr1, arr2):
p1 = len(arr1) - 1
runner = len(arr2) - 1
# Assuming arr2 is the padded
p2 = len(arr2) - len(arr1) - 1
while p1 >= 0 or p2 >= 0 and p1 != runner and p2 != runner:
if p1 >= 0 and p2 >= 0:
if arr1[p1] > arr2[p2]:
arr2[runne... |
def f(x):
# Primera operación
respuesta = 0
# Segunda operacion. Sin importar de x este loop correrá 1000 veces.
for i in range(1000):
respuesta += 1
# Tercera operación. Este loop correrá el valor de x
for i in range(x):
respuesta += x
# Cuarta operación. Esta parte esta... |
# strings_with_backspaces
# given strings with backspace character '#'
# check if they are equal
def strings_with_backspaces(str1, str2):
p = len(str1)-1
q = len(str2)-1
while p >= 0 and q >= 0:
# handle backspace character
if str1[p] == '#':
p = p - 2
if str2[q] == '... |
expected_output = {
"interfaces": {
"Ethernet1/1": {
"interface": "Ethernet1/1",
"statistics": {
"txreq": 0,
"rxlogoff": 0,
"txtotal": 3,
"txreqid": 0,
"lastrxsrcmac": "00:00:00:ff:00:00",
... |
FreeSerifBold18pt7bBitmaps = [
0x7B, 0xEF, 0xFF, 0xFF, 0xF7, 0x9E, 0x71, 0xC7, 0x0C, 0x20, 0x82, 0x00,
0x00, 0x07, 0x3E, 0xFF, 0xFF, 0xDC, 0x60, 0x37, 0x83, 0xFC, 0x1F, 0xE0,
0xFF, 0x07, 0xB8, 0x3D, 0xC0, 0xCC, 0x06, 0x20, 0x31, 0x01, 0x80, 0x03,
0x8E, 0x00, 0xC3, 0x80, 0x30, 0xE0, 0x1C, 0x38, 0x07, 0x0... |
class ImportedJvmLib:
_imported_libs = []
@classmethod
def has_library(cls, library: str) -> bool:
return library in cls._imported_libs
@classmethod
def import_lib(cls, library: str) -> bool:
if library not in cls._imported_libs:
cls._imported_libs.append(library)
... |
"""
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
找到最长的子串
create by swm 2018/06/08
"""
class Solution(object):
def longestCommonPrefix(self, strs):
... |
# Load modules
load_modules = {
'hw_fakeIO' : {'bus': 31},
'gen_ping' : {'debug': 2, 'bus': 32},
'gen_ping~1' : {'debug': 2},
'mod_stat' : {'debug': 2}
}
# Scenario
actions = [
{'gen_ping' : {'pipe': 2}},
{'gen_ping~1' : {'pipe': 1}},
{'hw_fakeIO' : {'action':'wri... |
# Copyright 2013 VMware, Inc.
#
# 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,... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'AND CLOSE_B COLUMN_FUNCTION_NAME COMMA DIVIDE EQUALITY FROM_T GREATER_THAN LESS_THAN MINUS NOT NUMBER OPEN_B OR PLUS SELECT_T SEMICOLON TIMES WHERE_TSQLselect : SELECT_... |
# nlantau, 2002-11-08
def spin_words(s):
# s = s.split(" ")
# for i, word in enumerate(s):
# if len(word) >= 5:
# s[i] = word[::-1]
# return " ".join(s)
return " ".join([i[::-1] if len(i) >= 5 else i for i in s.split(" ")])
print(spin_words("hey my name is Niklas Welcome")) |
# Exercicio 2 - for
#Escreva um programa que leia um numero inteiro
numero = int(input('Digite um numero:'))
#Calcule a taboada do número informado
for i in range(0,11):
print(f'{i} x {numero} = { i * numero}')
#Imprima a taboada com a conta completa (n * i = r) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.