text stringlengths 37 1.41M |
|---|
from itertools import product
import operator as op
from functools import reduce
def argmax(*iterables, key=None):
""" Maximizes the key function over iterables and returns
the corresponding argument. """
return max(product(*iterables), key=lambda args: key(*args))
def prod(iterable):
... |
from math import sqrt
import heapq
# Grid data structure is represented as a two dimensional array
# but it can also be thought as a graph where each node is linked to at most four adjacent nodes and
# where each link has a default weight of 1.
# Each grid element is defined as a tuple called `point` intersecting the... |
# Implement a Linked List
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# ref to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
... |
import math
import random
import time
from datetime import datetime
# programmer tells us, make sure this animals array is always .... 7 elements long/big/ in-it
animals = ["Giraffe", "Lion", "Dude", "AwesomePossum",
"Doggy", "Cat", "Cuddlefish"]
numbers = [n for n in range(1, 100)]
# print(numbers)
#######... |
# Feel free to add more classes/helper functions if you like, code quality counts!
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
... |
"""
In this kata, you should calculate type of triangle with three given sides a,
b and c (given in any order).
If all angles are less than 90°, this triangle is acute and
function should return 1.
If one angle is strictly 90°, this triangle is right and
function should return 2.
If one angle more than 90°, this tri... |
'''
description:
https://www.codewars.com/kata/55327e12f5363713200000e4
'''
regex="" #your regex here or...
def is_jojo(name):
s1=name.split(' ')
s=[s1[0],s1[len(s1)-1]]
if (s[0].startswith('Jo') and s[1].startswith('Jo') or s[0].startswith('Gio') and s[1].startswith('Gio') or s[0].startswith('Jo') and s[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 21:27:05 2019
@author: shruti
"""
# K-Means Clustering
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import scatter_matrix
# Importing the dataset
da... |
import math
import os
import random
import re
import sys
#
# Complete the 'compute_sum' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING x
# 2. STRING y
#
def sum_num(x,y,res,add):
if (x == "" and y == ""):
return str(add) + res i... |
# HACKER RANK PROBLEM: Caesar Cipher
# Julius Caesar protected his confidential information by encrypting it using a cipher.
# Caesar's cipher shifts each letter by a number of letters.
# If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet.
# In the case of a rotation b... |
#!/bin/python3
import math
import os
import random
import re
import sys
class BinarySearchTreeNode:
def __init__(self, node_data):
self.data = node_data
self.left = None
self.right = None
def insert_node_into_binary_search_tree(node, node_data):
if node == None:
node = BinaryS... |
# Power processing for RoboMagellan2012
#
# This module handles the power interfaces. As this is a quad steering
# robot, steering commands will also be handled here
#
import time,threading,serial
import roboconfig
from robocomms import log
from roboutils import *
# Speed values
target_speed = 0
current_speed =... |
from turtle import Turtle
# Make Paddle class
class Paddle(Turtle):
def __init__(self, x_pos):
super().__init__()
# Makes a stretched white box to emulate a pong paddle
self.y_pos = 0
self.x_pos = x_pos
self.penup()
self.speed(0)
self.shape("square")... |
# Selection sorting in python.
n=int(input())
a=list(map(int,input("Enter array value: ").split()))[:n]
for i in range(n-1):
for j in range(i+1,n,1):
if a[i]>a[j]:
a[i],a[j]=a[j],a[i]
print(a) |
from abc import ABCMeta, abstractmethod
class Employee(metaclass=ABCMeta):
def __init__(self,job_band,employee_name,basic_salary,qualification):
self.__job_band=job_band
self.__employee_name=employee_name
self.__basic_salary=basic_salary
self.__qualification=qualification
... |
"""
Controller for behavior layers with the subsumtion layer.
The first layers added with add_layer() are the layers that
are the least prioritised.
"""
class BehaviorController(object):
def __init__(self, robot=None):
self.robot = robot
self.layers = []
def add_layer(self, layer... |
# for variables in 변수할당가능한 자료:
# 문장1
# 문장2
for i in "테스트123":
print(i) #문자 하나씩 받아와서 차례대로 반복출력
l =['test',1,2,3] #4개의 요소를 가지고 있음
for i in l:
print(i)
tp1=(1,2,3)
for i in tp1:
print(i)
tp2=[(1,2),(2,3),(4,5)]
for i in tp2:
print(i)
# 구간의 범위를 알려준다
for i in range(3): #0부터 3전까지 반복해준다
p... |
"""
Shared URL Mapping
"""
class URLMap(object):
"""
URLMap is a mapping of URLs to functions.
"""
def add_route(self, url, func):
"""
Adds a route to the mapping
:param str url: URL the func should be associated with.
:param callable func: Function URL will be associ... |
'''program to calculate factorals of a given value'''
def factorialcalc(origin_num):
#number to calculate factorals of
factoral_num = origin_num
#value keeper
factoral_value = factoral_num
#calculates factoral with range and prints total
for i in range ((factoral_num -1), 0, -1):
facto... |
#!/usr/bin/env python3
# imports
from collections import defaultdict
from string import ascii_uppercase
import networkx
import sys
# check if input arg is provided
if len(sys.argv) < 2:
print("Santa is not happy, some of the arguments are missing")
sys.exit(1)
# parse input
input = []
with open(sys.argv[1]... |
# Question B
def checkVersion(v1,v2):
try:
if float(v1) < float(v2):
return v1 + ' is less than ' + v2
if float(v1) > float(v2):
return v1 + ' is greater than ' + v2
if float(v2) == float(v2):
return v1 + ' and ' + v2 + ' are equal.'
except:
r... |
#Métodos para utilização de lista.
#Inserindo elementos - OBJETO.APPEND(ELEMENTO)
#append() adiciona ao final da lista o elemento desejado. O append() adiciona elemento por elemento, e quando é utilizado para inserção
# de lista de elementos, ele o insere como um único elemento.
lista = [1,5,2,90,4,2,5]
lista.appen... |
class ciclo:
def __init__(self, inicio, final):
self.inicio = inicio
self.final = final
def imprimirnumero(self):
while self.inicio < self.final:
print(f"{self.inicio}")
self.inicio += 1
objetonumero = ciclo(int(input("inicio: ")), int(input("hasta: ")))
objetonumero.imprimirnu... |
nm = input("Ingrese su nombre: ")
ed = input("Ingrese su edad: ")
cl = input("Ingrese su numero de telefono: ")
print ("Sus datos fueron los siguientes: ")
print ("Nombre: " + str(nm))
print ("Edad: " + str(ed))
print ("Numero de telefono: " + str(cl))
|
# -*- coding: utf-8 -*-
from random import randint
MIN_VALUE = 1
MAX_VALUE = 100
def game():
guess_num = randint(MIN_VALUE,MAX_VALUE)
count = 0
while True:
x = input("num: ")
count += 1
if x.isdigit():
x = int(x)
if x == guess_num:
print("Число угадано. Количество попыток: %s" % count)
bre... |
# -*- coding: utf-8 -*-
"""
Числа Фибоначчи — элементы числовой последовательности
в которой каждое последующее число равно сумме двух предыдущих чисел.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946
"""
COUNTER = 0;
def fibo(n):
global COUNTER
COUNTER = CO... |
#takes myNum, an integer
#returns True if myNum is prime
#returns false if myNum is composite
def isPrime(myNum):
for num in range(2,myNum):
if myNum % num == 0:
return False
return True
# 11 should be true because it is a prime number
print("This should be true:")
print(isPrime(11))
# 9 is false because it is ... |
import turtle
def drawTee(myTurtle):
myTurtle.forward(90)
myTurtle.left(45)
myTurtle.forward(90)
def drawFourTees(myTurtle):
pass
# make your turtle down here and pass it to te appropriate places
shawn = turtle.Turtle()
turtle.exitonclick()
|
# import turtle too be able to draw the cubes
import turtle
# this will draw the top part of the cube
# only needs to draw that part only one time
# the top part of the cube will be dark blue
def drawTopRhombus(myTurtle):
count = 0
while count < 1:
myTurtle.fillcolor("dark blue")
myTurtle.begin_fill()
m... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [ 'runoob',786,2.23,'john',70.2]
tinylist = [123,'john']
print list
print list [0]
print list [1:3]
print list [2:]
print tinylist *2
print list + tinylist
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
i=2
while(i<100):
j=2
while (j<=(i/j)):
if not (i%j): break
j = j+1
if (j > i/j) : print i,"是素数"
i = i +1
print "Good bye !" |
#28.2.18
#Multiple Linear Regression of 50 startups data set
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn as sklearn
fifty = pd.read_csv("E:/OUTPUTPYTHON/50_Startups.csv")
fifty.columns #Displays the columns in the data
#To describe the type of data and its varia... |
"""
TSP
"""
class Mundo:
def __init__(self,lugares):
self. lugares=[]
with open(lugares,'r') as lugares:
posicion = lugares.read()
self.lugares.append(Lugar(**lugar))
pass
class Lugar:
def_ init__(self,x,y):
self.x = x
self.y = y
def __repr(Self):
r... |
# Chapter1 problem 2
import collections
def check_if_strings_are_permutations(input_string1: collections.Iterable, input_string2: collections.Iterable):
alphabet = {}
for character in input_string1:
alphabet[character] = 0
for character in input_string2:
alphabet[character] = 0
for ... |
# Chapter 1 problem 5
import collections
def one_way(input_string1, input_string2):
string1_length = len(input_string1)
string2_length = len(input_string2)
size_difference = abs(string1_length - string2_length)
if 1 < size_difference:
return False
if string1_length > string2_length:
... |
import random
import sys
sys.setrecursionlimit(1000000)
def busqueda_binaria(lista, comienzo, final, objetivo, counter):
if comienzo > final:
return False
medio = (comienzo + final) // 2
counter += 1
if lista[medio] == objetivo:
return True, counter
elif lista[medio] < ... |
from sys import exit
ans = True
while ans:
miles = raw_input("\nPlease enter a speed in miles/hours: ")
miles_org = int(miles)
yards_mile = 1760
meters_hour = miles_org * 1609.34
feet_hour = miles_org * 5280
meters_day = meters_hour * 24
barleycorns_day = meters_day * 117.647
yards_... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run chess-knight
# https://py.checkio.org/mission/chess-knight/
# Your friend loves chess very much, but he's not a strong player. You can help him by using your programming skills.
# If this mission is too simple for you, try another o... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run rectangles-union
# https://py.checkio.org/mission/rectangles-union/
# Your mission is to calculate the area covered by a union of rectangles. The rectangles can have a non-empty intersection, which means that a simple sum of given r... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run voice-tv-control
# https://py.checkio.org/mission/voice-tv-control/
# The technologies are rapidly evolving - only 50 years ago a simple black-and-white TV was a luxury! And now even a cool big color TV with remote control is a comm... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run robot-sort
# https://py.checkio.org/mission/robot-sort/
# The spaceship reactors contains several (no more than ten) nuclear fuel rods. These rods should be sorted by size to ensure the reactor’s stability, but as usual the fu... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run seven-segment
# https://py.checkio.org/mission/seven-segment/
# You have a device that uses aSeven-segment displayto display 2 digit numbers.However, some of the segments aren't working and can't be displayed.
#
# You will be given... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run inside-block
# https://py.checkio.org/mission/inside-block/
# When it comes to city planning it's import to understand the borders of various city structures. Parks, lakes or living blocks can be represented as closed polygon and... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run reverse-roman-numerals
# https://py.checkio.org/mission/reverse-roman-numerals/
# .numeral-table { margin: auto; border-collapse: collapse; text-align: center; } .numeral-table * { border: 1px solid black; padding: ... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run time-converter-12h-to-24h
# https://py.checkio.org/mission/time-converter-12h-to-24h/
# You are the modern man who prefers the 24-hour time format. But the 12-hour format is used in some places. Your task is to convert the time from... |
import datetime
class TodoList:
def __init__(self):
self.lista = ['task', 'data', 'persoana', 'categ_task']
self.lista_task = []
self.lista_to_do = []
# lista folosita la sortare in functie de anumiti param asc/desc
self.lista_cu_sortare = []
# lista folo... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
"""
Create a database connection to a SQLite database.
Parameters:
db_file: The name of the database file
"""
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.versi... |
# classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
POS_SHIFT = HAL... |
"""
Olivia Kim
Shut the Box
Last Updated: 12/14/2015
"""
import random
tile = [1,2,3,4,5,6,7,8,9,10,11,12]
def printTile(tile):
"""input: tile
output: none
prints a fancy version of the tiles
"""
s ="|-------------------------------------------------|\n"
for i in range(0,len(tile)... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 20:46:01 2021
@author: sy ibrahima
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
# create datasets
X, y = make_regression(n_samples =1000, n_features=1 , noise = 100)
plt.figure()
plt.scatter(X... |
# Для списка реализовать обмен значений соседних элементов,
# т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
list = ['a', 'b', 'c', 'd', 'e']
if len(... |
# 리스트에서 아스키코드가 가장 큰 값을 찾는 알고리즘을 만들기
# ord() 이용
class MaxAlgorithm:
def __init__(self, cs):
self.chars = cs
self.maxChar = ''
def getMaxChar(self):
self.maxChar = self.chars[0]
for c in self.chars:
if ord(self.maxChar) < ord(c):
se... |
counties_dict = {"Arapahoe": 422289, "Denver": 463353, "Jefferson": 432438}
for county, voters in counties_dict.items():
#print(county,"county has", voters, "registered voters")
#print(county + " county has " + str(voters) + " registered voters")
print(f"{county} county has {voters:,} registered voters.") #... |
#!/usr/bin/python
import sys
from collections import namedtuple
Item = namedtuple('Item', ['index', 'size', 'value'])
def knapsack_solver(items, capacity):
# Greedy algorithm:
# at each step take the item with the best value/size ratio
# Passes small and medium tests. Fails large test with just 1 item d... |
def add(a,b):
c=a+b
return c;
result=add(5,7)
print("the result is",result) |
def dupl(str):
name=[]
for i in range(0,len(str)-1,1):
if str[i] not in name:
name.append(str[i])
print (name)
str="Arjit Srivastava"
dupl(str)
|
numbers = [3,6,40,2,10,7]
max = numbers[0]
for nu in numbers:
if nu > max:
max = nu
print("The highest number is",max) |
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
# using naive method
# to remove duplicated
# from list
res = []
for i in test_list:
if i not in res:
res.append(i)
# printing list after removal
print("The list after removing duplicates : " + str(res)) |
secret=9
count=0
guess_limit=3
while count < guess_limit:
num= int (input("Enter the number "))
count=count+1
remain= guess_limit-count
print (str(remain) +" Remaining attempts")
if num==secret:
print("You guesses it correctly")
break
else:
print ("Sorry ! you failed") |
class Inventory(object):
#manages the player's inventory
#creates a dictionary using an item's label as the key
#linked to the Item-class object
def __init__(self):
self.inv_list = {}
def add(self, item):
self.item = item
if self.has(self.item):
self... |
def fib_iterative(n):
# import pdb; pdb.set_trace()
breakpoint()
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
def fib_recursive(n):
if n == 1 or n == 0:
return 1
return fib_recursive(n - 1) + fib_recursive(n - 2)
def fib_sequence(n):
result = [0, 1]
for... |
"""
files.py - Common file handling routines.
"""
import os
def ensure_file_exists_and_open(filename):
"""
Returns a file descriptor with write/append permissions for the passed-in
filename. Handles creating the file if need be.
filename - The absolute path of the file to be opened.
"""
if not os.pa... |
name = 'Daniel C. Lucas'
age = 26
height = 73 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
height_cm = height * 2.54
weight_kg = weight * 0.453592
print "Let's talk about %s." % name
print "He's %d centimeters tall." % height_cm
print "He's %.1f kilos heavy." % weight_kg
print "Actually th... |
vproduto= float(input('Digite o valor do produto R$:'))
desconto = float(input('Digite o valor do desconto em %:'))
res = vproduto - ((vproduto * desconto)/100)
print('O produto custa R${} \n Aplicando um desconto de {}% \n O valor final é : R${:.2f}'.format(vproduto,desconto,res)) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Dog:
def __init__(self,dog_name):
self.name=dog_name
self.type='Dog'
class Cat:
def __init__(self,cat_name):
self.name=cat_name
self.type='Cat'
class AnimalShelter:
... |
def reverse_array(arr):
"""Reverses a list
Args:
arr (list): python list
Returns:
[list]: list in reversed form
"""
# put your function implementation here
returnedArr =[]
lengthOfArray=len(arr)
while lengthOfArray :
returnedArr.append(arr[lengthOfArray-1])
... |
# Multi Bracket Validation
def multi_bracket_validation(input):
stack = []
brackets ={
'{':'}',
'(':')',
'[':']'
}
for char in input:
if char in brackets:
stack.append(char)
if char in brackets.values():
# print(stack)
# prin... |
# Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных,
# практических и лабораторных занятий по этому предмету и их количество.
# Важно, чтобы для каждого предмета не обязательно были все типы занятий.
# Сформировать словарь, содержащий название предмета и... |
# Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
# Ссылка на диаграммы: https://drive.google.com/file/d/1Kan7g8csDHBAmjAHwLhqaUU-Xc_Z3rWJ/view?usp=sharing
place = int(input('Введите номер любой из букв английского алфавита: '))
if place <= 26:
num = place + 96
letter = chr(num)
p... |
# Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек,
# или убыток — издержки больше выручки). Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение пр... |
# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
from random import randint # экономим память :)
SIZE = 10
MIN_ITEM = - 100
MAX_ITEM = 100
array = [randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
min_value_ind = 0
max_value_ind = 0
print(f'первоначальный список {array}')
fo... |
# Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
number = int(input('Это программа найдет наибольшую цифру в числе, которую вы введете: '))
a = 0
while number > 0:
residue = number % 10
number //= 10
if r... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse
import re
import parse_html
def clean_title(text_to_clean):
toto = re.sub('[^0-9]', '', text_to_clean)
return toto
def search_by_isbn(isbn_t):
isbn_t = str(isbn_t)
... |
year=input("enter number"):
if (year % 4)==0
if (year % 100)==0
if (year % 400)==0
print({0} "is an leap year:".format(year))
else:
print({0} "is not an leap year:".format(year))
else:
print({0} "is not an leap year:".format(year))
else:
prin... |
#coding:utf-8
import sqlite3
from config import sqlite_db
command = """
BEGIN;
CREATE TABLE IF NOT EXISTS user(
"userid" integer PRIMARY KEY AUTOINCREMENT,
"username" varchar(25) NOT NULL,
"password" varchar(50) NOT NULL,
"registed_time" datetime NOT NULL,
"usertype" smallint DEFAULT 0,
"email" varchar(30),... |
#! usr/bin/env python3
num1 = int(input("choose your first number"))
num2 = int(input('choose second number'))
operation = input("What operation are we performing( +, -, *, /)? ")
answer = int(input('What is the answer? '))
if operation == '+':
sum = num2 + num1
correct = answer == sum
print('Yo... |
#!usr/bin/env python3
import math
def main():
rad = float(input("Please enter the length of the radius. "))
volume = (4/3) * (math.pi * rad ** 3)
surface_area = 4 * (math.pi * rad ** 3)
print(f'Volume is {round(volume, 2)}')
print(f'Surface area is {round(surface_area, 2)}')
if __nam... |
"""
This module sets up the question model and all it's functionality
"""
import os
from flask import jsonify
from app.api.v2.models.base_model import BaseModel, AuthenticationRequired
from app.api.v2.models.user import User
class Question(BaseModel):
def __init__(self, question={}, database=os.getenv('FLAS... |
import tkinter as tk
from googletrans import Translator
win = tk.Tk()
win.title("translator")
win.geometry("200x70")
def translator():
word = entry.get()
translator = Translator(service_urls=["translate.google.com"])
translation = translator.translate(word, dest="es")
label1 = tk.Label(
win, ... |
username = input("Please enter you first name! ")
number1 = input("Enter you favorite number! ")
try:
number1 = int(number)
except:
print("Okay! Processing")
try:
number1 = float(number)
except:
print("Just confirming your number....")
print(username + "\'s favorite number is " ... |
#퀵정렬 O(NlogN) 시간복잡도, O(N) 공간복잡도
def quicksort(lst):
if len(lst) == 0: return []
elif len(lst) == 1: return lst
pivot = len(lst)//2
leftlst = []
rightlst = []
for i in range(len(lst)):
if i == pivot: continue
if lst[i] <= lst[pivot]:
leftlst.append(lst[i])
eli... |
# create a class
class Song():
# define constructor method with 1 param
def __init__(self, lyrics):
# create attribute
self.lyrics = lyrics
# define method
def sing_me_a_song(self):
# for loop that prints each line from constructor param
for line in self.lyrics:
... |
from sys import exit
def gold_rm():
print('This room is full of gold. How much do you take?')
choice = input('> ')
if '0' in choice or '1' in choice:
qty = int(choice)
else: dead('Man, learn to type a number.')
if qty > 50:
print('Nice, you\'re not greedy, you win!')
exit... |
def cheese_and_crackers(cheese_count, boxes_of_crackers):
"""
str, str > None
input 2 str and call print w/str formatting to print input strings
"""
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
... |
grade_inp = input('Type in an integer from 0-100 >')
try:
grade = int(grade_inp)
if grade > 100:
print(grade)
raise ValueError('Please only input an int between 0-100')
except:
raise TypeError('Please only input an int between 0-100')
def grade_converter(num):
if num < 55:
ret... |
# TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
for i in range (0, len(arr) - 1):
current_index = i
smallest_index = i
for j in range (i + 1, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
if current_index ... |
from tkinter import messagebox as msg
def formatar_expressao(expressao):
if '**' in expressao:
return expressao.replace('**', '^')
elif '*' in expressao:
return expressao.replace('*', 'x')
return expressao
def expressao_ok(expressao):
if expressao.find('-') == 0:
somente_num_... |
import numpy as np
Array = []
Loop =int(input("Enter Your loop : "))
while(Loop%3 != 0):
print('Please Enter Again')
Loop = int(input("Enter yoour loop : "))
print("Enter Your Array: ")
for i in range(Loop):
Array += [int(input(""))]
NewArray = np.asarray(Array)
NewArrayNumpy = NewArray.reshape(int(Loop/3)... |
i = float(input('ใส่คะแนน : '))
while i != -1:
print(i)
i = int(input('ใส่คะแนน : '))
if i == -1:
break
|
# import the library module
import hashlib
def sha256 (text):
# encode the string
encoded_str = text.encode()
# create a sha1 hash object initialized with the encoded string
hash_obj = hashlib.sha256(encoded_str)
# convert the hash object to a hexadecimal value
hexa_value = hash_obj.hexdigest... |
from SimpleCV import *
cam = Camera() # Initialize Camera
img = cam.getImage() # get a sample image to know the screen size
display = Display() # Creates an object of Display Class
width, height = img.width, img.height # Gets width and height of the Image captured
screensize = width*height # initiali... |
class HeapTransformer:
def __init__(self, heap):
self.heap = heap
def transform(self):
for i in range((len(self.heap)-2)//2, -1, -1):
self.fix_down(i)
def fix_down(self, index):
index_left = 2 * index + 1
index_right = 2 * index + 2
# in a max heap ... |
def selection_sort(nums):
# we make N-1 iterations
# N-1 x O(N) = O(NxN)
for i in range(len(nums)-1):
# linear search and the index stores the index
# of the min item
index = i
# THIS IS THE LINEAR SEARCH - O(N)
for j in range(i, len(nums)):
if nums[in... |
import math
class Node(object):
def __init__(self, name):
self.name = name
self.predecessor = None
self.adjacency_list = []
self.min_distance = float('inf')
class Edge(object):
def __init__(self, weight, start_vertex, target_vertex):
self.weight = weight
sel... |
from collections import deque
class MazeSolver:
def __init__(self, matrix):
self.matrix = matrix
# D(0,1) U(0,-1) L(-1,0) R(1,0)
self.move_x = [1, 0, 0, -1]
self.move_y = [0, -1, 1, 0]
self.visited = [[False for _ in range(len(matrix))] for _ in range(len(matrix))]
... |
# -*- coding: utf-8 -*-
# Import Modules/Dependencies
import os
import csv
# Establish Variables for the upcoming analysis
total_mos = 0
Total_PNL = 0
Profit_incr_Max = 0
avg_chg = 0
Net_chg_List = []
Profit_Incr_Max = ["", 100]
Profit_Decr_Max = ["", 0.0]
Monthly_Chg=[]
Month_Count=0
# Set Path For File
csvpath... |
import operator as Operator
from functools import reduce
#start=time.time()
S,K=map(int,input().split())
entiers=list(map(int,input().split()))
def factorielle(entier):
res=1
while entier>1:
res=res*entier
entier-=1
return res
def combinaison(n, p):
p = min(p, n-p)
numerator = r... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
if not self.root:
self.root = Node(data)
else:
self.inse... |
class Node:
def __init__(self, data):
self.data = data
self.nextNode = None
class Linked_List:
def __init__(self):
self.head = None
def insert(self, data):
newNode = Node(data)
if self.head is None:
self.head = newNode
else:
curr... |
import math
def cesar(d, text):
text = list(text)
for i in range(len(text)):
temp = ord(text[i])+d
if (temp > 122):
temp = temp - 122 + 96
if (temp < 97):
temp = temp + 26
text[i] = chr(temp)
return("".join(text))
def check(phrase, con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.