text stringlengths 37 1.41M |
|---|
"""
给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
示例:
输入: s = "abcdefg", k = 2
输出: "bacdfeg"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-string-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def reverseStr(... |
from random import uniform, gauss, choice, randint
from math import pow, sin
import numpy as np
class DataGenerator():
func = ("uniform", "linear", "power", "sin")
def __init__(self, len, count):
self.len = len
self.count = count
def noise(self):
noise_avg = 0
noise_std =... |
N, H, x = list(map(int, input().split()))
T = list(map(int, input().split()))
time_zone = max(T)
if (time_zone + x) >= H:
print("YES")
else:
print("NO")
|
# Assignment Operators
# 1. = -> It will assign the value to the rhs to the variable on left
a = 10
b = 30
c = b
print(a, b, c)
# 2. += -> It will act same as a = a + 1
a += 1 # Instead of writing a = a + 1, we write this
b += a # Instead of writing a = a + b, we write this
print(a, b)
# 3. -= -> It will act same as... |
n = int(input())
sum = 1
for i in range(2, int(n**0.5) + 1):
if (n % i == 0):
sum += i
sum += n//i
if n**0.5 is int:
sum -= n**0.5
if sum == n:
print("YES")
else:
print("NO")
|
"""
Example =>
n = 36
factors:-
1,36
2,18
3,12
4,9
6,6
9,4
12,3
18,2
36,1
"""
from math import floor
def check_prime(n):
if n == 2:
return True
for i in range(2, floor(n**0.5) + 1):
if (n % i) == 0:
return False
return True
n = int(input())
result = check_prime(n)
if (result == True):
print("Yes it is ... |
def prime_factorization(n):
i = 2
factors = {}
while i * i <= n:
if n % i != 0:
i += 1
else:
n //= i
if i not in factors.keys():
factors[i] = 1
else:
factors[i] += 1
if n > 1:
if n not in factors.ke... |
def count_consonants(str):
consonants = "bcdfghjklmnpqrstvwxz"
consonants_count = 0
for ch in str.lower():
if ch in consonants:
consonants_count += 1
return consonants_count
if __name__ == '__main__':
print(count_consonants("Github is the second best thing that happend to prog... |
import sqlite3
from client import Client
class Database:
def __init__(self):
self._conn = sqlite3.connect("bank.db")
self._cursor = self._conn.cursor()
@property
def conn(self):
return self._conn
@property
def cursor(self):
return self._cursor
def create_cli... |
def to_digits(n):
result = []
while n > 0:
result.append(n % 10)
n //= 10
return result[::-1]
if __name__ == '__main__':
print(to_digits(123))
print(to_digits(99999))
print(to_digits(123023))
|
def fibonacci(n):
result = []
fib1 = 1
fib2 = 1
fib = fib1 + fib2
if n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
result.append(fib1)
result.append(fib2)
result.append(fib)
while n > 3:
fib1 = fib2
fib2 = fib
... |
import unittest
from song import Song
class TestSong(unittest.TestCase):
def setUp(self):
self._song = Song(title="Odin", artist="Manowar",
album="The Sons of Odin", length="3:44")
def test_init(self):
self.assertTrue(isinstance(self._song, Song))
with self... |
hrs = input("""Enter number of working hours""")
rate = input("Enter rate per hour")
wages = float(hrs*rate*52)
print("Your gross pay is ", wages) |
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# It's mention - we don't need to use the Extra memory
# Also, we need to remove / replace the elements IN_PPLACE.
# Approach:
# take a Two pointers i & j (i at 0 and j at 1)
# one is slow pointer and other is fast pointer (we can say)
# So we will ... |
# https://leetcode.com/problems/longest-common-prefix/
# Method-1
# Find Longest common prefix of first 2 string
# Then find longest common prefix between output of 1st and 3rd string
# Then find longest common prefix between output of 2nd and 4th string and so on...
# in this way - at the end - we have Longest commo... |
import unittest
def divide(x, y):
if x and y:
return (x / y)
else:
return -1
class TestMath(unittest.TestCase):
def test_divide_returns_correct_result(self):
# Arranage - setup the environment
test_x = 20
test_y = 10
# Act
result = divide(test_x, ... |
# First thing we'll do is import the requests library
import requests
# Define a variable with the URL of the API
api_url = "http://shibe.online/api/shibes?count=1"
# Call the root of the api with GET, store the answer in a response variable
# This call will return a list of URLs that represent dog pictures
response ... |
T = int(input())
data={}
for i in range(0,T):
string = str(input()).split(" ")
data[string[0]] = string[1]
for j in range(0,T):
name = str(input())
if name in data:
print(name + "=" + data[name])
else:
print("Not found") |
#--# Python Calculator ENGLISH: By TheRealCodeGamer #--#
import sys
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
#opties
print("Choose an option:")
print("---------------")
print("1. +")
print("2. -... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
current = head
if(!current):
return current
while current.next:
... |
import fisika
def main():
#membuat judul program
print("program mencari BERAT BENDA")
#memninta user memasukkan bilangan
w=float(input("Masukkan w: "))
g=float(input("Masukkan g: "))
massa = fisika.massaBenda(w, g)
#menampilkan hasil
print("MASSA BENDA")
print("bera... |
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
start_idx = 0
end_idx = len(input_list) - 1
while start_idx <= ... |
import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Lin... |
# Project Euler
# Problem 12
# Solution by Ewen Bramble
# How many distinct terms are in the sequence generated by a**b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
terms = set()
for a in range(2,101):
for b in range(2,101):
terms.add(a**b)
print("Number of distinct terms: {}".format(len(terms))) |
# Project Euler
# Problem 28
# Solution by Ewen Bramble
# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral?
# Idea: write function to populate grid from middle outward. Function takes dimension(s)
# Grid full of zeros initially
# Turn right if zero in grid, else go straight
# While loop with t... |
from sys import argv
script, user_name = argv
prompt = ">"
print "Hi %s, I am the %s script. Excuse the silliness of this set-up" % (
user_name, script
)
print "I need to ask you a few questions."
print "Are you comfortable with me, %s?" % user_name
likes = raw_input(prompt)
print "Please tell me where you liv... |
import numpy as np
import sys
from gym.envs.toy_text import discrete
from lib.utils import *
actions = ['NW','N','NE','W','X','E','SW','S','SE']
def categorical_sample(prob_n, np_random = None):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarra... |
"""
questions to ask:
- will we have empty arrays? yes
- all are numbers? yes
"""
"""
naive approach: put all of the numbers into a single array
Time O(n) when construct
Space O(n)
104 ms, faster than 17.66%
"""
class Vector2D(object):
def __init__(self, v):
self.nums = []
... |
import numpy as np
"""
Used Alpha-Beta Pruning to optimize Minimax algorithm.
The algorithm checks the maximizers and minimizers and when it isn't possible to beat a better option,
it stops searching and moves onto the next options.
"""
BOARD_COLS = BOARD_ROWS = 3
AI = 1
PLAYER = -1
state = [['1', '2', '3'],
... |
#database.py
#use python 3.4
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
pid = input('Enter unique ID number: ')
person = {}
person['name'] = input('Enter name: ')
person['age'] = input('Enter age: ')
person['phone'] = input('Enter phone number: ')
d... |
# a simple markup program
# aim:
# 1. print some beginning markup
# 2. for each block, print the block enclosed in paragraph tags.
# 3. print some ending markup
#
# python simple_markup.py <test_input.txt> test_output.html
import sys, re
from util import *
print('<html><head><title>...</title><body>')
tit... |
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint
curses.initscr()
window = curses.newwin(30, 60, 0, 0)
window.keypad(True)
curses.noecho()
curses.curs_set(0)
window.nodelay(True)
key = KEY_RIGHT
score = 0
snake = [[5, 8], [5, 7], [5, 6]]
food = [10, 25]... |
from karel.stanfordkarel import *
"""
File: TripleKarel.py
--------------------
When you finish writing this file, TripleKarel should be
able to paint the exterior of three buildings in a given
world, as described in the Assignment 1 handout. You
should make sure that your program works for all of the
Triple sample w... |
x = 3
password = 'a123456'
while x > 0:
code = input('type your password: ')
if code == password:
print('accessed')
break
else:
x = x - 1
if x == 0:
break
print('u still have', x, 'chance')
|
# Problem: A car dealer earns a base wage of $36.25 per hour up to their normal work week of 37 hours.
# Only whole hours are counted. If he works more hours than that (overtime) he gets paid at 1.5 times his normal rate for the overtime.
# If he sells more than 5 cars in a week, he gets a bonus of $200 per car from ... |
#program converts kilometres to Miles
km = float(input("Enter kilometres: "))
miles = 0.621771 * km
print(f'{km} kilometres is equal to {miles} miles') |
'''
class newlist(list):
def __init__(self,aname):
list.__init__([])
self.name=aname
a=newlist(333)
print(a)
print(a.name)
class bird():
def __init__(self):
self.hurgy=True
def eat(self):
if self.hurgy:
print('hahahahah')
self.hurgy=False
... |
"""Test Vector identities using numpy"""
import numpy as np
import random
def main():
#create three random arrays called v_1, v_2, v_3 whose entries are random real numbers in range (-100,100)
v_1=np.array([random.uniform(-100,100) for i in range(3)])
v_2=np.array([random.uniform(-100,100) for i in range... |
# coding 1 neuron
# count these as outputs from previous neuron layer
inputs = [1, 2, 3, 2.5]
weights = [0.2, 0.8, -0.5, 1.0]
# this is for neuron that we are currently coding. Bias - зміщення
bias = 2
# output of our neuron
output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + inputs[3]... |
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
3-2-19
WAP to accept a string from user and print count of consonants in it.
'''
def count(s):
l = len(s)
cnt = 0
v = 0
for x in s:
if x in "aeiouAEIOU":#x=='a' or x=='e' or x=='i' or x=='o' or x=='u':
... |
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
3-2-19
"Foundation"
WAP to accept a number for user and a bit position to turn off from the given
number. Print number in decimal after turning off the bit. If already off then let
it be
Example: 16 bit=5 answer:0
Note: turn off always lsb to... |
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
WAP to count the number of 0's in the given number.
Example:
i/p: 64 o/p:7
i/p: 63 o/p:3
'''
def count0(n):
cnt = 0
while n!=0:
cnt+=1
n = n&(n-1)
return cnt
def main():
n = eval(input("Enter a numbe... |
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
WAP to add two numbers using bitwise operators.
'''
def bit_add(a,b):
while b!=0:
t = a & b
a = a ^ b
b = t << 1
return a
def main():
a,b = eval(input("Enter two numbers: "))
ans = bit_add(a,b)
... |
numero = int(input('Digite um número: '))
if numero > 8:
print('O número digitado divido por 2 é: ', (numero/2))
else:
print('O número ao cubo é: ', (numero**2))
input()
|
import math
numero = float(input('Digite um número: '))
if numero > 0:
print('O número é positivo e sua raiz quadrada é: ', round(math.sqrt(numero)))
else:
print('O número é negativo ')
input()
|
lista1 = [0,0,0,0,0,0,0,0,0,0]
lista2 = [0,0,0,0,0,0,0,0,0,0]
lista3 = [0,0,0,0,0,0,0,0,0,0]
n = 0
while n < 10:
lista1[n] = int(input('Digite os números da primeira lista: '))
lista2[n] = int(input('Digite os números da segunda lista: '))
lista3[n] = lista1[n] * lista2[n]
n = n + 1
print('\n')
print(... |
class Customer:
def __init__(self,x,y,rd,id):
self.coordinate = (x,y)
self.release = rd
self.id = id
def getData(self):
return [self.coordinate[0], self.coordinate[1], self.release]
def __str__(self):
return 'CustomerRD ' + str(self.release)
def __repr__(self... |
#Write your code below this row 👇
total = 0
for number in range(2, 101):
if number % 2 == 0:
total += number
print(total)
jumlah = 0
for nomor in range(2, 101, 2):
jumlah += nomor
print(jumlah) |
#Look for #IMPLEMENT tags in this file. These tags indicate what has
#to be implemented.
import random
import itertools
'''
This file will contain different variable ordering heuristics to be used within
bt_search.
var_ordering == a function with the following template
ord_type(csp)
==> returns Variable
csp is... |
'''
Suraj Kumar Saini
www.linkedin.com/in/suraj-saini-8a1027143/
https://github.com/surya3217
'''
# my generic solution to update dictionary
def recurse_dict(dd, d2):
for key in d2.keys(): # finding the key from d2 dict to update
print(key)
if type(d2[key])==dict: # checking the data type of di... |
"""
Name:
Height Calculator
Problem Statement:
Lets assume your height is 5 Foot and 11 inches
Convert 5 Foot into meters and Convert 11 inch into meters and
print your total height in meters and print your total heigjt in centimetres also
Extension:
Take the height of the user from inpu... |
import csv
import string
unfiltered = []
filtered = []
valid = 0
with open('input.csv') as csvfile:
reader = csv.reader(csvfile, delimiter = ",")
for x in reader:
unfiltered.append(x)
unfiltered.pop(0)
for x in range(len(unfiltered)):
filtered.append(unfiltered[x][0].split(":"))
for x in filtere... |
import math
def bus_time(bus, time):
bus = int(bus)
time = int(time)
if time % bus == 0:
return time
else:
return bus_time(bus, time + 1)
def check_time(bus, time):
if bus == 'x':
return True
else:
bus = int(bus)
time = int(time)
if time % bus ==... |
# initialise list
assignments = []
# read input file
with open('adventofcode2022/day4/day4input.txt', 'r') as input:
for line in input:
line = line.strip()
assignments.append(line.split(','))
# calculate number of pairs with overlapping ranges
contains = 0
for pair in assignments:
elf1... |
with open('adventofcode2020\day3\day3input.txt', 'r') as input:
hilltop = [line.rstrip() for line in input]
def treeCounter(right_slope, down_slope):
x,y,trees = 0,0,0
while y < len(hilltop):
if(x >= len(hilltop[0])):
x -= len(hilltop[0])
if(hilltop[y][x] == '#'):
... |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for row in board:
if not self.isValid(row):
return False
for col in zip(*board):
if not self.isValid(col):
return False
for i in (0... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def traverse(self, root, num):
for i in range(num):
root = root.next
return root
def count(self,root):
cnt =... |
import random
class Rulet:
def __init__(self):
self.money = 100
self.limit = 5000
def display_title_bar(self):
print("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RULET ~~~~~~~~~... |
from datetime import datetime
def pad_zero(n):
if len(n) == 2:
return n
if len(n) == 1:
return '0' + n
raise Exception('Received a value with too many digits')
class Clock(object):
def get(self):
now = datetime.now()
hour = pad_zero(str(now.hour))
minute = pad... |
class Complex:
def __init__(self, numb):
self.numb = numb
def __add__(self, other):
if self.numb.count('+'):
num_1 = self.numb.split('+')
else:
num_1 = self.numb.split('-')
if len(num_1) > 2:
num_1.remove('')
num_1[0] =... |
class Car:
def __init__(self, speed, color, name, is_police=False):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
print('Машина поехала')
def stop(self):
print('Машина остановилась')
def turn(self, direc... |
# For loops allow you to iterate over a sequence of values
# by default, the value in range starts with x = 0
# the range number is not inclusive
for x in range(5):
print(x)
# you can loop through strings in an array
friends = ['Taylor', 'Alex', 'Pat', 'Eli']
for friend in friends:
print("Hi "+ friend)
# whe... |
"""
Minimal req:
Publisher tracks list of subscribers (adds/removes).
Subscriber implement update method.
"""
class Subscriber:
def __init__(self, name):
self.name = name
def update(self, article, publisher):
print(f'{self.name} received article from publisher: {publisher.name}.')
class... |
#lists
array = [1,2,3,4]
print(array)
print(array[0])
print(array[-1])
print(array[3:])
print(array[:3])
print(array[:-2])
print(array[-2:])
|
#comparison operators
#
'''
print(1==1)
print(1==2)
print(2>1)
print(1>2)
print(2>2)
print(2<=2)
'''
#combining comparison and boolean expressions
'''
print(1==1 and 2==1)
print(2>1 and 5<10)
'''
|
class Persona:
def __init__(self, nombre, edad, apellido):
self.name = nombre
self.age = edad
self.last_name = apellido
def __str__(self):
return "Nombre: " + self.name + ", edad: " + str(self.age)
class Empleado(Persona):
def __init__(self, nombre, edad, su... |
import math
def func(m,s,p):
return 0.5*(1+math.erf((p-m)/(s*2**0.5)))
m=20
s=2
p1=19.5
p2=20
p3=22
res1=func(m,s,p1)
res2=func(m,s,p3)-func(m,s,p2)
print('%.3f\n%.3f'%(res1,res2))
|
def median(l):
n=len(l)
if n%2==0:
return (l[n//2-1]+l[n//2])//2
else:
return(l[n//2])
n=int(input())
l=sorted(list(map(int,input().split())))
a=[]
b=[]
c=[]
if n%2==0:
b.append(l[n//2-1])
b.append(l[n//2])
a=l[:n//2]
c=l[n//2:]
else:
b.append(l[n//2])
a=l[:n//2]
... |
#-*- coding: utf-8 -*-
import numpy as np
import random
names = np.array(['Bob', 'joe', 'will','Bob', 'will', 'joe', 'joe'])
data = np.random.randn(7, 4)
print names
print data
print names == 'Bob'
arr = np.empty((8, 4))
print 'arr is \n ', arr
for i in range(8):
arr[i]=i
print arr
|
# Generate a formatted full name including a middle name
def get_full_name(first_name: str, last_name: str, middle_name='', greeting='Hello Master: ') -> str:
if len(middle_name) > 0:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
... |
print('Поддерживаемые операторы: +, -, *, /, %, **')
print('Вводи через пробел')
while True:
inp = input(">> ")
inp.split(' ')
ar_len = len(inp)
print(inp)
if ar_len == 1 and inp.isdigit() is True:
first_num = inp
elif ar_len == 2 and inp[0].isdigit() is False:
operator = inp[0]
... |
print "Programa para Calcular el Area de un Triangulo"
base = float(raw_input("Medida de la Base: "))
altura = float(raw_input("Medida de la Altura: "))
area = (base * altura) / 2.0
print "La base es %6.2f, y el Area es %6.2f" %(base,area)
#Salida Con Formato |
opcion = "z"
while opcion < "a" or opcion > "c":
print "a) Adoro Python"
print "b) Detesto Python"
print "c) No se lo que es Python"
opcion = raw_input("Elija una Opcion: ")
if opcion == "a":
print "Me Alegro."
elif opcion == "b":
print "Que Mal."
elif opcion == "c":
... |
import string
def change(chararray):
intarray = [int(index) for index in chararray]
return intarray
lawer_case = string.ascii_uppercase
charlist = list(lawer_case)
countlist = []
try:
while(True):
val = input()
# Enter values separated by comma: x,y,z
if val:
... |
""" Módulo de contas """
class ContaCorrente:
""" Cria classe de conta corrente """
def __init__(self, numero, nome_correntista, saldo=0.0):
""" Inicializa atributos da classe """
self.numero = numero
self.alterar_nome(nome_correntista)
self.saldo = saldo
def alterar_nome(... |
# 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(arg_a, arg_b, arg_c):
try:
arg_a = float(arg_a)
arg_b = float(arg_b)
arg_c = float(arg_c)
except ValueError:
return 'Invalid value detect... |
# 5. Реализовать формирование списка,
# используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from functools import reduce
def ... |
# 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских бук... |
# 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль.
# Проверьте его работу на данных, вводимых пользователем.
# При вводе пользователем нуля в качестве делителя
# программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
import time
class NUL_DIVISION(Exception):... |
d={}
print('Welcome#')
print('Using this system you will becom a english pro')
while True:
print('=>')
print('1.Choose words')
print('2.list out all thw words')
print('3.English translate to Chinese')
print('4.Chinese tranlate to English')
print('5.Test skills that you learn')... |
import time
def DrawBoard(board):
print(" %c | %c | %c " % (board[1],board[2],board[3]))
print("___|___|___")
print(" %c | %c | %c " % (board[4],board[5],board[6]))
print("___|___|___")
print(" %c | %c | %c " % (board[7],board[8],board[9]))
print(" | | ")
board=... |
number = input('Enter a value: ')
alpha = [chr(i) for i in range(65, 91)]
alpha.extend([chr(i) for i in range(97, 123)])
n_list = list(number)
print(n_list)
flag_p = False
flag_n = False
flag = False
if number == '0':
print('Zero')
flag = True
elif '.' in n_list:
print('Float number')
flag = True
el... |
slices = int(input('Enter the number of slices you want: '))
price = 0
if slices%2 == 0:
price += slices*120.00
else:
price += slices*123.00
print('Number of slices: {}\nPrice you have to pay: {}'.format(slices, price))
|
"""
Задача 4.
Поработайте с обычным словарем и OrderedDict.
Выполните различные операции с каждым из объектов и сделайте замеры.
Опишите полученные результаты, сделайте выводы.
"""
from collections import OrderedDict
from timeit import repeat
my_dict = {str(i): i for i in range(100)}
my_order_dict = OrderedDict([(str(... |
"""
Задание 3 *.
Сделать профилировку для скриптов с рекурсией и сделать,
можно так профилировать и есть ли 'подводные камни'
"""
from memory_profiler import profile, memory_usage
from time import process_time
@profile
def sum_number(a):
if a == 1:
return 1
return a + sum_number(a-1)
... |
"""
6. В программе генерируется случайное целое число от 0 до 100.
Пользователь должен его отгадать не более чем за 10 попыток. После каждой
неудачной попытки должно сообщаться больше или меньше введенное пользователем
число, чем то, что загадано. Если за 10 попыток число не отгадано,
то вывести загаданное число.
Реши... |
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> tup = (1,2,3,4,5,6,7,10)
>>> tup = (1,2,3,4,5,6,7,10,'hi','hello')
>>> tup[0]
1
>>> tup[-1]
'hello'
>>> tup[0:5]
(1, 2, 3, 4, 5)
>>> tup[0] = 'Hi'
Tra... |
import time # This is required to include time module.
from email.utils import localtime
import calendar # This is required to include calendar module
from _datetime import datetime
import datetime
# The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).
... |
#a = 17
a = int(input("Enter the number : "))
if a % 2 == 0:
print("{} is even".format(a))
else:
print("%d is odd"%(a))
|
# Internationalization - I18N
userName = input("क्या नाम ह आपका : ")
userAge = input("कृपया अपनी उम्र बताये : ")
print("Hello",userName)
print("Your age is",userAge) |
km = int(input("Digite a velocidade atual do seu carro:"))
if km > 110:
calc = km - 110
multa = calc * 5
print("Você foi multado e terá que pagar %.2f reais." %multa)
|
import turtle_square_using_function;
your_input = 300;
if(your_input>0):
turtle_square_using_function.square();
else:
print("number : "+ str(your_input))
|
# https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
import collections
def connect(root):
levels = []
next_level = [root]
while len(next_level):
levels.append(next_level)
new_next_level = []
for node in next_level:
if node.left is not None:
... |
# Because the file name starts with a number, normal from ... import ... is not
# working. So the following are two ways to get around that:
# importlib (recommended)
# ref -> https://docs.python.org/3/library/importlib.html#importlib.import_module
import importlib
zero = importlib.import_module('0')
SinglyListNode =... |
# Specification:
# Create a class LeaderBoard whose interface includes the following methods:
# Method Name: add_score
# - Add a new score to the player's average. If a player doesn't exist in the
# LeaderBoard, they will be automatically added.
# Args:
# player_id(Integer... |
# Compute the intersection of two sorted arrays
# Prompt
# Takes two sorted arrays and returns a new array containing elements that are present in both of the input arrays.
# The input arrays may have duplicate entries, but the returned array should be free of duplicates.
# Example
# Input -> [2,3,3,5,5,6,7,7,8,12], ... |
import importlib
zero = importlib.import_module('0')
BinaryTree = zero.BinaryTree
traversal = zero.traversal
# Reconstruct a binary tree from traversal data
# Prompt:
# Given an inorder and preorder traversal sequence of a binary tree write a program to reconstruct the tree.
# Assume each node has a unique key
def ... |
# Binary - at most 2 children
# full - 0 or all children at every node
# perfect - all leafs at same level
# complete - all levels expect the bottom are filled with max number of childrens
# AND bottom level should be filled left to right
# Tree - no cycles
# Balanced - difference between height of left and ... |
# Buy and sell a stock once
# Prompt:
# An algorithm that determines the maximum profit that could have been made by
# buying and then selling a single share over a given day range, subject to the
# constraint that the buy and the sell have to take plae at the start of the day
# Example:
# [310, 315, 275, 295, 260, 2... |
# Generate all nonattacking placements of n-Queens
# Background: A nonattacking placement of queens is one in which no two queens are in the same row, column, or diagonal
# Prompt: A program that returns all distinct nonattacking placements of n queens on an n x n chessboard, where n is an input
# Time Complexity:
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.