text stringlengths 37 1.41M |
|---|
'''
Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6.
Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. Объяснить полученный результат
Начало
5 & 6
5 | 5
5 ^ 5
5 << 2
5 >> 2
Вывод результатов операций
Конец
https://drive.google.com... |
'''
Creating a multiplication table with all the elements in the array. So
if your array is [2, 3, 7, 8, 10], you first multiply every element by 2,
then multiply every element by 3, then by 7, and so on.
'''
# To generate sample input arrays
import random
def mulArr(array):
if len(array) < 2:
return a... |
'''
Excerpts from the book "Grokking Algorithms" by Aditya Bhargava:
D&C algorithms are RECURSIVE algorithms.
To solve a problem using D&C, there are two steps:
1. Figure out the base case. This should be the simplest possible case.
2. Divide or decrease your problem until it becomes the base case.
... |
import sys
def show_sizeof(x,level=0):
print "\t"*level,x.__class__, sys.getsizeof(x), x
if hasattr(x,'__iter__'):
if hasattr(x,'items'):
print "iterating items..."
for xx in x.items():
show_sizeof(xx,level+1)
else:
print "iterating a l... |
def print_board(board):
#impressão dos índices das colunas:
print(" ",end='')
for coluna in range(len(board)):
if coluna!=0:
print(" | %4d " %(coluna), end='')
print(" | %4d |" %(coluna+1))
print(" ",end='')
for coluna in range(len(board)+1):
print("+... |
def seperator():
for i in range(100):
print("*", end = '')
print()
def count_instances(string, letter):
step = len(letter)
choice = input("Enter \'y\' if cases are to be considered: ")
if choice == 'y':
pass
else:
string = string.lower()
l... |
print ("This will be a number comparison.")
print ("first number.")
userinput1 = input ()
print ("Second number.")
userinput2 = input ()
if userinput1 > userinput2:
print ("first number is bigger.")
elif userinput1 < userinput2:
print ("first number is smaller.")
else:
print ("Both are equal") |
print ("How many bars should be charged")
chargebars = int(input())
charged = 0
print()
while (charged < chargebars ):
charged = charged + 1
print ("Charging", "█" * charged)
print ("done charging")
|
def observed():
observations = []
for count in range(7):
print("Please enter an observation:")
observations.append(input())
return observations
def run():
print("Counting observations...")
observations = observed()
# populate set
observations_set = set()
for observation in observations:
... |
print ("How Far are we from the cave")
steps = int (input ())
# Display count down
print ()
for count in range(steps, 0, -1):
print(count, "steps remaining")
print("We have reached the cave!")
|
print("Towards which direction should I paint (up, down, left or right)?")
direction = input ()
if (direction == "up"):
print ("you are painting up")
elif (direction == "down"):
print ("you are painting down")
elif (direction == "left"):
print ("you are painting left")
elif (direction == "right"):
print ("you... |
'''
a decorator function accepts a function as an argument and returns a modified function
without syntactic sugar, we pass our function to the decorator and get an
enhanced function returned back; we can then run this new function
with syntactic sugar, we run in one line
'''
# ======================================... |
import unittest
from decorators import accepts
@accepts(str, int)
def acceptTestFunc(string, integer):
return f'{string} {integer}'
class TestDecorators(unittest.TestCase):
def test_accept_raises_exception_when_args_types_do_not_match_the_decorator_args(self):
with self.subTest('Second arg type doe... |
import re
import os
from money_tracker import MoneyTracker
class MoneyTrackerMenu:
def __init__(self):
os.system('clear')
self._user_name = input('Enter user name:')
self.initialize_file_and_money_tracker()
self.initialize_options()
self.date_message = '(Format of the date ... |
class Bill:
def __init__(self, amount):
if isinstance(amount, int) is False:
raise TypeError("Amount must be integer!")
if amount < 0:
raise ValueError("Amount must be positive!")
self.amount = amount
def __str__(self):
return str(self.amount)
def __... |
import sys
sys.path.insert(0, '/home/anton/HackBulgaria/week01')
from firstDay import to_digits
from secondDay import group
def is_number_balanced(number):
digits = to_digits(number)
if (len(digits) % 2 == 0):
return (sum(digits[0: len(digits) // 2]) ==
sum(digits[len(digits) // 2:]))
... |
import unittest
from client import Client
from exceptions import InvalidPassword
class ClientTests(unittest.TestCase):
def setUp(self):
self.test_client = Client(1, "Ivo", 200000.00,
'Bitcoin mining makes me rich', "ivo@abv.bg")
def test_client_id(self):
se... |
def count_substrings(haystack, needle):
counter = 0
x = 0
while x <= len(haystack) - len(needle):
if haystack[x: x + len(needle)] == needle:
counter += 1
x += len(needle)
else:
x += 1
return counter
# print("count_substrings tests:")
# print(count_su... |
import camelCase # Name of file
from unittest import TestCase
class TestCamelCase(TestCase):
def test_camelcase_sentance(self):
self.assertEqual('helloWorld', camelCase.camelcase('Hello World'))
self.assertEqual('minnesotaVikings', camelCase.camelcase(' MInnesota vIKINGS '))
... |
import random
class zipf():
"""
This class implement some methods for zipf distribution.
"""
def __init__(self, d=10):
"""
The constructor for zipf class.
Attributes:
category (int): How many category that want to be generated.
"""
self.d =... |
# Link to tthe problem
# https://www.hackerrank.com/challenges/angry-professor/problem
def angryProfessor(k, a):
count = 0
for time in a:
if time <= 0:
count += 1
if count >= k:
return "NO"
return "YES"
total = 3
times = [-1,-3,4,2]
print(angryProfessor(total, times)) |
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
# Not a real way to store data for an actual project.
# Using a global dicitonary just for an example.
users = {
"Nick": {"name": "Nick", "age": 42, "job": "programmer"},
"Elvin": {"name": "Elvin", "... |
#!/usr/local/bin/python3
# Can use 'in' to check if value is in a list.
# Use 'not in' to see if value is missing from list.
def check_for_ringo(band):
if "Ringo" in band:
print("I'm a real drummer!")
elif "ringo" in band:
print("I guess I can call .capitalize() on myself.")
else:
... |
def continue_example():
try:
for i in range(10):
continue
finally:
print("This prints for continue")
def break_example():
try:
for i in range(10):
break
finally:
print("This prints for break")
def return_example():
try:
for i in range... |
from stack import Stack
class UniqueStack(Stack):
"""
UniqueStack has the same methods and functionality as Stack, but will only store one
copy of a particular item at a time.
If push is called with an item that is already in the UniqueStack, a ValueError should be raised
with an appropriate error... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv("numbers.csv")
# Can select individual columns
print("col x:", data['x'], sep='\n')
print("col y:", data['y'], sep='\n')
# Can get basic stats for columns with describe
print("data stats:", data.describe(), sep='\n')
# Can a... |
#!/usr/local/bin/python3
# Can return single values.
def add(a, b):
return a + b
# Can return multiple values.
# They are returned as a tuple.
def get_coordinates(a, b, c):
x = add(a, b)
y = add(b, c)
return x, y # Or, return (x, y)
# A function can return multiple different types.
#... |
def ChemSplit(a):
#To let my string ends with a capital letter:
a=a+'A'
s=0
blist=[]
for ii in range(1,len(a)):
if str(a[ii]).isupper():
blist.append(a[s:ii])
s=ii
#print(blist,'\n')
clist=[]
dlist=[]
for ii in range(len(blist)):
strtemp = blist[ii]
#Case 1: o... |
print("enter a value")
x = int(input())
print("enter another value")
y = int(input())
print("enter the operation: ex: +,-,*,/")
o = input()
if (o == '+'):
print("your answer is:", x+y)
elif(o == '-'):
print("your answer is:", x-y)
elif(o == '*'):
print("your answer is:", x*y)
elif(o == '/'):
if (y == 0)... |
# Here is a new proposed method of compressing strings :
# "Anywhere in the string if a character c occurs k number of times consecutively, it can be written as c"
# Using this algorithm, your task is to compress the string such that its final length is minimum.
# Note that it is not compulsory for you to compress ev... |
# Exclusive OR
# Find the XOR of two numbers and print it.
# Hint : Input the numbers as strings.
# Input Format
# First line contains first number X and second line contains second number Y.
# The numbers will be given to you in binary form.
# Constraints
# 0 <= X <= 2^1000
# 0 <= Y <= 2^1000
# Output Format
#... |
# Given an array, Mister Arr the owner of the array wants to move each element k places
# to its left. I.E. the array a[0],a[1],a[2],...a[n] becomes a[1],a[2]...a[n],a[0]
# after moving one place to the left.
# Note that the first element becomes the last element after each rotation.
# Input Format
# The first line c... |
# Count the number of pairs in an array having the given sum
# Given an array of integers, and a number ‘sum’, chef wants to find the number of pairs of integers in the array whose sum is equal to ‘sum’.
# Examples:
# Input : arr[] = {1, 5, 7, -1},
# sum = 6
# Output : 2
# Pairs with sum 6 are (1, 5) a... |
# Pyramid by Numericals
# Identify the logic behind the series
# 6 28 66 120 190 276....
# The numbers in the series should be used to create a Pyramid. The base of the Pyramid will be the widest and will start converging towards the top where there will only be one element. Each successive layer will have one numbe... |
# Contacts Application
# Your task is to design a contacts application that supports two features :
# add name where name is a string that denotes the name of the contact. This operation must store a new contact by the name name.
# find partial where partial is a string denoting a part of the name to search for in t... |
MAX_WRONG = len(HANGMAN)
WORDS = ("powershell","python","animal","didacticum")
wrong = 0
word = random.choice(WORDS)
#word ="pow"
your_guess = len(word) * "_"
print(your_guess)
guess = input("Raad een letter: ")
#Write code that will continue to ask you to guess a letter
#If a letter is in the word the program should... |
names = ["bla","flap","flop"]
print (range(len(names)))
guess = input()
for i in range(len(names)):
if guess == names[i]:
print("gevind")
word = "hangman"
guess = input()
for i in range(len(word)):
if guess == word[i]:
print("found something") |
number = int(input("Enter a number:"))
primeFlag = True
for i in range(2, number):
if number % i == 0:
primeFlag = False
break
if primeFlag == True:
print(number, " is prime.")
else:
print(number, " is not prime.") |
class PasswordException(Exception):
def __init__(self, msg):
self.msg = msg
try:
ps = input("Enter your Password")
if (len(ps)) < 8:
raise PasswordException("Enter Password more than eight digit")
except PasswordException as obj:
print(obj)
else:
print("Password set") |
import game_logic as game
from random import randint
class AI:
name = "Default"
team = -1
def __init__(self,team):
self.name="Default"
self.team=team
def make_move(self,board):
return 0
class InputPlayer(AI):
name = "Player"
def __init__(self, team):
super().__... |
#Grading Students
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def transformGrade(grade):
remainder = grade%5
... |
#import modules
from datetime import datetime
from time import sleep
from pytz import timezone
#set CONSTANTS
TIME_ZONE = timezone('US/Central')
START_TIME = datetime.strptime('1555','%H%M').time() #enter the time of day to begin the cycle
RUN_TIME = 1 #enter the le... |
m=input()
if m==str(m)[::-1]:
print("yes")
else:
print("no")
|
import random
# game levels
level_one = random.randint(1, 10)
level_two = random.randint(1, 20)
level_three = random.randint(1, 50)
guess_count = 0 # used to keep track of guess attempts
print('''
Hi, Welcome to the number guessing game.
Here are the available levels:
E --- Easy
M --- Medium
H --- Hard
''')
difficul... |
#!/usr/bin/python
# AUTHOR: JASON CHEN (cheson@stanford.edu)
# DATE: July 31, 2017
# The find_votesmart_id function takes a list of targets with each target
# structured as the format "firstname_lastname".
# If you call this function, you will get in return a map from the target
# name to the votesmart id associated ... |
a = int(input()) - 1
b = 1
while a > -1:
print(' '*a + "@"*b)
b+=2
a-=1
|
# Question:
#------------------------------------------------------------------------------
# tags:
'''
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The ans... |
#------------------------------------------------------------------------------
# Question: 0096_unique_binary_search_trees.py
#------------------------------------------------------------------------------
# tags: #trees #medium
'''
Given n, how many structurally unique BST's (binary search trees) that store
values 1 ... |
#------------------------------------------------------------------------------
# Question: 043_Multiply_Strings.py
#------------------------------------------------------------------------------
# tags:
'''
Given two non-negative integers num1 and num2 represented as strings, return
the product of num1 and num2.
Note... |
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags: #tree
'''
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
... |
#------------------------------------------------------------------------------
# Questions: 0103_binary_tree_zigzag_level_order_traversal.py
#------------------------------------------------------------------------------
# tags: Binary, Traversal
'''
Given a binary tree, return the zigzag level order traversal of its ... |
# **************************************************************************** #
# #
# ::: :::::::: #
# 106_construct_binary_tree_from_inorder_an :+: :+: :+: ... |
# **************************************************************************** #
# #
# ::: :::::::: #
# 198_House_Robber.py :+: :+: :+: ... |
# **************************************************************************** #
# #
# ::: :::::::: #
# 070_Climbing_Stairs.py :+: :+: :+: ... |
# **************************************************************************** #
# #
# ::: :::::::: #
# 518_CoinChange_2-Combinations.py :+: :+: :+: ... |
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
Given a non-empty array of integers, every element appears twice except for
one. Find that single one.
Note:
Your algorithm should hav... |
# ------------------------------------------------------------------------------
# Question:
# ------------------------------------------------------------------------------
# tags: #binarytree
'''
'''
# ------------------------------------------------------------------------------
# Solutions
# ---------------------... |
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
'''
#------------------------------------------------------------------------------
# Solutions
#-------------------------------------... |
#------------------------------------------------------------------------------
# Question: 027_course_schedule.py
#------------------------------------------------------------------------------
# tags: medium
'''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisit... |
#------------------------------------------------------------------------------
# Question: 1048_longest_string_chain.py
#------------------------------------------------------------------------------
# tags:
'''
Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor o... |
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
Given an array of unique characters arr and a string str, Implement a function
getShortestUniqueSubstring that finds the smallest substr... |
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
There is a new alien language which uses the latin alphabet. However, the
order among letters are unknown to you. You receive a list of ... |
'''
Created on May 15, 2010
@author: Dr. Rainer Hessmer
'''
import math
def GetBaseAndExponent(floatValue, resolution=4):
'''
Converts a float into a tuple holding two integers:
The base, an integer with the number of digits equaling resolution.
The exponent indicating what the base ne... |
from string import ascii_lowercase
for letter in ascii_lowercase:
filename = 'ex_45/'+letter+'.txt'
with open(filename, 'w') as file:
file.write(letter)
|
from math import pi
def sphere_volume(h, r=10):
vol = (4 * pi * (r**3)) / 3
air_vol = (pi * (h**2) * (3 * r - h)) / 3
return vol - air_vol
print(sphere_volume(2)) |
import pandas as pd
df = pd.read_csv('countries-by-area.txt', index_col='rank')
df['density']=df['population_2013']/df['area_sqkm']
df = df.sort_values(by='density', ascending=False)
for index, row in df[:5].iterrows():
print(row['country'])
|
digitsInString = input( "Entrez une liste de chiffres :" )
digitsInTab = []
for i in range( len( digitsInString ) ) :
if (digitsInString[i].isdigit()) :
digitsInTab.append( int(digitsInString[i] ))
atLeastOneDigitLeft = True
while (atLeastOneDigitLeft) :
atLeastOneDigitLeft = False
for i in range ... |
arr=[54,67,13,21,90,32]
def selectionsort(arr):
for i in range(len(arr)):
minidx=i
for j in range(i+1,len(arr)):
if arr[minidx]>arr[j]:
minidx=j
arr[i],arr[minidx]=arr[minidx],arr[i]
for i in range(0,len(arr)):
print(arr[i])
selectionsort(arr)
|
# TIE-02107: Programming 1: Introduction
# MAHABUB HASAN, mahabub.hasan@student.tut.fi, Student No.: 281749
# Solution of Task - 3.6.3
# Parasetamol
def calculate_dose(weight, time, total_doze_24):
amount_applicable = weight*15
if time > 5:
remain_dose = 4000-total_doze_24
if remain_dose > amo... |
def print_dict_order(input_dict):
copy_dict = []
copy_dict.clear()
for key, value in input_dict.items():
copy_dict.append((str(key)).strip()+ " " +(str(value)).strip())
copy_dict.sort()
print("Contestant score:")
count=0
for i in copy_dict:
count+=1
print(i)
#print(i... |
# TIE-02107: Programming 1: Introduction
# MAHABUB HASAN, mahabub.hasan@student.tut.fi, Student No.: 281749
# Solution of Task - 5.4.4
def main():
performance1 = float(input('Enter the time for performance 1: '))
performance2 = float(input('Enter the time for performance 2: '))
performance3 = floa... |
# TIE-02107: Programming 1: Introduction
# Solution of Task - 6.3
# A program that shows stats from recorded step counts
"""
group members:
prasun biswas(267948)
Mahbub hasan(281749)
"""
"""this returns the count number withing certain limits(low & high)
from a input list"""
def filter_by_steps(... |
'''
Python Program to Display the multiplication Table
'''
#Taking Input From User
num = int(input("Enter The number to display the multiplication table "))
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
|
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
def dictionaryToTuple(dic):
newList = []
for k, v in dic.iteritems():
newList.append((k, v))
print newList
dictionaryToTuple(my_dict)
|
# Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
raio = float(input("Digite o raio do círculo:\n"))
pi = 3.1415
area = (raio * raio) * pi
resultado = round(area, 2)
print(f"O valor do raio do círculo é: {resultado}")
|
while True:
print "enter -1 to break and 2 to continue "
x=int(raw_input("enter the choice"))
if x==-1:
break
#print "hello i have breaked it "
if x==2:
continue
#print "hello i am in continue"
print "hello i am in while loop"
print "hello i am outside of the loop "
|
n = raw_input("5")
if n >0:
print ("hello i am an interger number")
else:
print ("i am not an integer") |
#!/usr/bin/python3
"""
Design and implement a data structure for Least Recently Used (LRU) cache. It
should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists
in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the ... |
class BookShelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"Bookshelf with {len(self.books)} books"
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Book {self.name}"
book = Book("Harry Potter")
book2 ... |
### args collects everything being passed
def multiply(*args):
total = 1
for arg in args:
total = total *arg
return total
print(multiply(1,3,5))
def add(x,y):
return x+y
nums = [4,5]
print(add(*nums))
nums = {"x": 15, "y": 25}
print(add(x=nums["x"], y=nums["y"]))
print(add(**nums))
def... |
# Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista,
# depois do dado inserido, pergunte ao usuário se ele quer continuar,
# se ele não quiser pare o programa. No final mostre:
# Quantas pessoas foram cadastradas
# Mostre o maior peso
# Mostre o menor peso
people = list()
... |
pessoas = list()
cont = cont2 = cont3 = 0
while True:
pessoas.append(str(input('Insira o nome: ')))
pessoas.append(int(input('Insira sua idade: ')))
pessoas.append(str(input('Insira seu gênero[Homem/Mulher]: ').strip().upper()[0]))
if pessoas[1] > 18:
cont +=1
if pessoas[2] == 'H':
... |
temp = list()
par = list()
impar = list()
lista = par,impar
for i in range(0,7):
temp.append(int(input('Insira um número: ')))
for i in temp:
if i % 2 == 0:
lista[0].append(i)
else:
lista[1].append(i)
par.sort()
impar.sort()
print(f'Resultado: {lista}')
|
def func(NOTA):
if NOTA >=0 and NOTA <=10:
if NOTA >=9:
return 'A'
elif NOTA >=8:
return 'B'
elif NOTA >=7:
return 'C'
elif NOTA >=6:
return 'D'
elif NOTA <=4:
return 'F'
else:
return 'INVÁLIDO!!!'
nota... |
temp = list()
mta = list()
cont = 0
while cont != 3:
for i in range(0,3):
temp.append(int(input('Insira um número: ')))
mta.append(temp[:])
cont +=1
temp.clear()
print(f'[{mta[0][0]}] [{mta[0][1]}] [{mta[0][2]}]')
print(f'[{mta[1][0]}] [{mta[1][1]}] [{mta[1][2]}]')
print(f'[{mta[2][0]}] [{mta... |
temp = list()
mta = list()
cont2 = cont3 = cont4 = 0
for cont in range(0,3):
for i in range(0,3):
temp.append(int(input('Insira um número: ')))
for i in temp:
if i % 2 == 0:
cont2 += i
if cont == 2:
for i in temp:
cont3 += i
if cont == 1:
for i in... |
import time
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0) # to enable control screen update instead of auto
home_position = [(0, 0), (-20, 0), (-40, 0)]
snake_squares = []
for position in home_position:
... |
#! /bin/python3
with open('input.txt') as f:
sum = 0
cnt = 0
for num in f:
sum += int(num)
cnt += 1
print('The average of the numbers in input.txt is ' + str(sum/cnt))
|
#!/bin/python3
import os
import sys
from functools import reduce
import operator
#
# Complete the connectingTowns function below.
#
def connectingTowns(n, routes):
#
# Write your code here.
# The code here.
if (len(routes)+1 == n):
out = reduce(operator.mul,routes,1)
return (out%123456... |
import threading
import time
balance = 0
lock_k = threading.Lock()
def change(n):
global balance
with lock_k:
balance = balance + n
time.sleep(2)
balance = balance - n
time.sleep(1)
print("Thread name: {} ---> var n : {} var balance : {}".format(threading.current_thr... |
import time
import threading
from multiprocessing.dummy import Pool
def thread_run(n):
# 线程执行的任务
time.sleep(2)
print('start thread "{}" duty'.format(threading.current_thread().name))
print("the number n : {}".format(n))
print('stop thread "{}" duty'.format(threading.current_thread().name))
def ... |
"""
event.wait(timeout=None):调用该方法的线程会被阻塞,如果设置了timeout参数,超时后,线程会停止阻塞继续执行;
event.set():将event的标志设置为True,调用wait方法的所有线程将被唤醒;
event.clear():将event的标志设置为False,调用wait方法的所有线程将被阻塞;
event.isSet():判断event的标志是否为True。
"""
import threading
from time import sleep
def test_event(n, event):
while not event.isSet():
... |
# coding: utf-8
# # Weeks 13-14
#
# ## Natural Language Processing
# ***
# Read in some packages.
# In[2]:
# Import pandas to read in data
import numpy as np
import pandas as pd
# Import models and evaluation functions
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import Bernoulli... |
from random import randrange
def create_array(size_of_array: int) -> []:
array = [randrange(1, 50) for i in range(size_of_array)]
return array
array = create_array(10)
def quick_sort(array):
size_of_array = len(array) - 1
pivot_index = randrange(0, size_of_array)
pivot = array[pivot_index... |
from datetime import datetime
class Message:
DATE_FORMAT = '%Y.%m.%d'
TIME_FORMAT = '%H:%M:%S'
DATE_SEPARATOR = '.'
TIME_SEPARATOR = ':'
DATETIME_SEPARATOR = ' '
DATE_TIME_FORMAT = DATE_FORMAT + DATETIME_SEPARATOR + TIME_FORMAT
def __init__(self, date, time, sender, text):
self.dat... |
def checkio(numbers_array):
result_array = []
for i in numbers_array:
if type(i)== int:
result_array.append(i)
else:
while type(i)!=int:
list(i)
result_array.append(i)
result_array = sorted(result_array, key= lambda v : -v if v<0 e... |
# Implementation of binary search algorithm
# We will prove that binary search is faster than naive search
# naive search: scan the entire list and ask if it's equal to the target
# if yes, return the index
# if no, then return -1
def naive_search(l, target):
for i in range(len(l)):
if l[i] == target:
... |
def gradient_descent(X, Y, learning_rate=0.3, m=0, b=0, iterations=5):
for i in range(iterations):
b_gradient = - (2 / len(X)) * sum([Y[i] - (m * X[i] + b)
for i in range(len(X))])
m_gradient = - (2 / len(X)) * sum([X[i] * (Y[i] - (m * X[i] + b))
... |
#Whats your name ?
import time
name = input('What is your name? ')
if len(name) < 3:
print("Name must be at least 3 characters long")
elif len(name) > 50:
print("Name must be maximum of 50 characters")
print('Hi ' + name + " \U0001F60A")
time.sleep(.70)
#favourite Color
favourite_color = input(... |
"""
Dagobert Main file
"""
import pygame
import game_classe
import menu_classe
# -------- Main Program -----------
menu = menu_classe.Menu()
game = game_classe.Game()
done = False
pygame.init()
print('Initialized ! Launching ...')
while not done:
res_m = menu.launch()
print(res_m)
if res_m == 'QUIT':
done = T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.