text stringlengths 37 1.41M |
|---|
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
pReversedHead = None
pNode = pHead
pPrev = None
while(pNode != None):
... |
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if not sequence:
return False
root = sequence[-1]
left = []
right = []
# 在二叉搜索树中左子树节点的值小于根节点的值
for i in range(len(sequence)):
if sequence[i... |
import speech_recognition as sr
from gtts import gTTS
import os
import playsound
import requests
import time
import random
import wikipedia
import webbrowser
def hearing():
r = sr.Recognizer()
voice_data = " "
with sr.Microphone() as source:
print("Listening: ")
audio = r.lis... |
#By Prathyusha Theerdhala
import random
from time import sleep
choice=["Charmander","Bulbasaur","Squirtle"]
cpu=random.choices(choice)
player=False
while player ==False:
print("Welcome to the Pokémon Battleground!")
print("\nAre you ready to choose your Pokémon?")
player=str(input("Which Pokémon do you want to ch... |
class Botilleria:
def __init__(self,marca,litros,precio):
self.marca = marca
self.litros = litros
self.precio = precio
def __str__(self):
return "{} de {} litro, tiene un precio de {} pesos.".format(self.marca,self.litros,self.precio)
class Cerveza(Botilleria):
tipo = "... |
str=input("Enter word")
c=0
n=input("enter letter to be count")
for item in str:
if item!=n:
continue
else:
c=c+1
print(c) |
from abc import ABC,abstractmethod
class shape(ABC):
@abstractmethod
def area(self):
return 0
class rectange():
def __init__(self,l,b):
self.l=l
self.b=b
def area(self):
return self.l*self.b
class square():
def __init__(self,s):
self.s=s
def ... |
list = [2, 4, 6, 8, 10]
for item in list:
if item > 4:
print("grater then 2")
list2 = ['Elton', 'Souza']
for name in list2:
if not name == "Elton":
print(name) |
"""
4. Given dictionary representing a student name as a key and corresponding value is a grade which
he obtained in different subjects. WAP update each dict value with average score obtained by
each student respectively.
scores = {Student1: [65, 68, 59, 52, 69, 65, 55, 59],
Student2: [60, 64, 60, 60, 88, 64, 68, ... |
"""
13. Given a string of even length and print the output as string contains last half added with first half of the given string
"""
Input_str = raw_input("Enter a given length string: ")
length = len(Input_str)
print length
num = 0
first = ' '
last = ' '
for ch in Input_str:
if ((length/2)-1) > num:
... |
#!/usr/bin/env python
import json,sys
json_file = open(sys.argv[1], "r+")
doc = json.load(json_file)
keys = sys.argv[2].split('.')
def search(d, keys):
if len(keys) == 1:
return d[keys[0]]
else:
return search(d[keys[0]], keys[1:])
print search(doc, keys)
|
# Given a matrix representation of plot of land,
# find the sizes of all the ponds in the matrix
# 0 indicates water. Pond is the region of water connected vertically, horizontally, or diagonaly
def pond_region(grid, x, y):
print(x,y)
if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]):
return 0
... |
''' find the k smallest integers froma given array'''
'''
Solution 1: Sort the array and return the first k elements
Solution 2: Use a BST and do in order traversal to find first k elements
Solution 3: Selection rank algorithm
Selection Rank
1. Pickarandomelementinthearrayanduseitasa"pivot:'Partitionelementsaroundthe... |
# given two sorted arrays find the median of these two sorted arrays (combined)
'''
solution: Median is the middle element
1. divide the arrays as left part and right part
2. criteria for the left part and right part (includes both A and B's left part)
a. len(left_part) = len(right_part)
b. max(left_part) <= m... |
# implement multiply, subtract and divide operations for integers
# use only the add operator
import os
def negate(num):
neg = 0
if num < 0:
newsign = 1
else:
newsign = -1
while (num != 0):
neg += newsign
num += newsign
return neg
def subtract(a, b):
ret... |
### peaks and valleys
# sort an input array into an alternating sequence of peaks and valleys
import os
import sys
def swap(arr, left, right):
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
# Approach One:
# Sort the array and swap every element with its right neighbor starting index 1 and i... |
''' given an array of number and a value, find all subsequences that add up to that value '''
# NP complete problem Subset sum
# Dynamic programming can also be used
import os
import numpy as np
def isSubsetSumDP(array, sum):
n = len(array)
# The value of subset[i][j] will be true if there is a subset of... |
# you are given an array of integers (both +ve and -ve). Find the contiguous sequence with the largest sum
# idea is to sum up subsequences of positive and negative numbers
# example: (2, 3, -8, -1, 2, 4, -2, 3)'s sum array is (5, -9, 6, -2, 3)
# now examine this array from first element
# 1. take 5 as maxSum and sum.... |
# a=[3,34,1,55,23,49]
# print(34 in a)
# a =(True and False)
# b =(True and True)
# c =(False or True)
# c1 =(True or False)
# print(a,b,c1,c)
list1=[]
list2=[]
list3=list1
if(list1==list2):
print(True)
else:
print(False)
if(list1 is list2):
print(True)
else:
print(False)
if(list1 is l... |
a = 50
b = 100
avg =(a+b)/2
avg = (int(avg))
c = ("the average between a and b is:")
print (c,avg)
print (type(c),type(avg)) |
sent=('ahsan','omer','king')
a = (input("Enter a word you want to find:\n"))
if(a.lower in sent):
print("it is in the list")
else:
print("it is not in the list") |
letter='''Dear NAME
DATE
From
"Dear Omar Ahsan Khan, from abc house we are promoting you for your performance this year
our regards have a good day.
Thank you,from bill'''
Name = input('your name')
Date = input('date')
From =... |
# use python3
import sys
import threading
import queue
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Tree:
def __init__(self, index, depth=None):
self.val = index
self.child = []
self.depth = depth
d... |
import matplotlib
#绘制一个plot折线图,取别名plt
import matplotlib.pyplot as plt
# %matplotlib inline
#绘制y = x^2 (x,1,2,3,4...)/列表自身具有索引【0....】/数据为列表
squares = [x**2 for x in range(1,10)]
#绘图/
# plt.plot(squares)
# plt.show()
#改变线条的样式,线条的粗细linewidth
plt.plot(squares,linewidth=2)
plt.show()
#给图标题标题大小 fontsize,图中写中文:... |
#Embedded file name: eve/common/script/planet\surfacePoint.py
"""
Surface point
"""
import math
MATH_2PI = math.pi * 2
class SurfacePoint:
"""
Represents a point on the surface of a sphere, both in cartesian and spherical coordiantes.
A surface point can be created by specifying the cartesian coordinates:
... |
import unittest
from ..node import Node
class NodeTest(unittest.TestCase):
def test_ctor(self):
"""Test some variants of the Node __init__ method"""
node = Node("name", "data")
self.assertEqual("name", node.name)
self.assertEqual("data", node.data)
node = Node("name", att... |
import pandas as pd
from topics import *
from clean import stats
def calc_age_stats(df):
'''
Take in cleaned and processed data, remove cities with less than 50 data points
Calculate statistics per city - display top 5
- % that advertise IG
- % that advertise SC
- % that mention Coivd
- %... |
from flask import Flask
import json
import os
app = Flask(__name__)
@app.route("/")
def reverse_slicing(s):
return s[::-1]
input_str = 'ABç∂EF'
if __name__ == "__main__":
print('Reverse String using slicing =', reverse_slicing(input_str)) |
'''
DEFAULT -- interpretter -- when there is no other constructor in a class
No-arg -- user has defined a constructor without parameter
paramaterized --user has defined a constructor with parameter
max -- there will one contstructor in class -- last one
'''
class Person :
def method1(self,**a):
sum =... |
# This is created by sugan😎😍😀
'''First enter your equations and press run'''
print("this program is created by sugan under MIT lisence 2.0")
def find(a):
num1 = a[0] # instead use x1 ,1
num2 = a[1] # y1 ,1
num3 = a[2] # c2 ,5
num4 = a[3] # x2 ,2
num5 = a[4] # y2 ,2
num6 = a[5] # c2 ,... |
"""
File: asteroids.py
Original Author: Br. Burton
Designed to be completed by others
This program implements the asteroids game.
"""
import arcade
import math
import random
from abc import ABC, abstractmethod
import pyglet
# These are Global constants to use throughout the game
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600... |
"""
File: ta10-solution.py
Author: Br. Burton
This file demonstrates the merge sort algorithm. There
are efficiencies that could be added, but this approach is
made to demonstrate clarity.
"""
from random import randint
MAX_NUM = 100
def merge(left, right):
left_i = 0
right_i = 0
result = []
while le... |
count = {}
with open("census.csv", "r") as f:
for line in f:
words = line.split(',')
key = words[3]
if key not in count:
count[key] = 1
else:
count[key] += 1
for key in count:
print(count[key], "--", key)
|
import arcade
SCREEN_WIDTH = 1080
SCREEN_HEIGHT = 600
class Point:
def __init__(self):
self.x = 0
self.y = 0
class Velocity:
def __init__(self):
self.dx = 0
self.dy = 0
class FlyingObjects:
"""
Creates class for Flying Objects. This is a base class for other
fl... |
print('What type of Dungeons and Dragons character are you? Answer this short personality test to find out.')
birthday = str(input('Please enter your astrology sign, Ex. aquarius, sagittarius, et.,: '))
print()
name_birth = ('Cupcake', 'Krusk', 'Gimble', 'Hennet', 'Tordek', 'Ragnara', 'Sandharrow', 'Eulad', 'Xerxe... |
'''
Society is an econmicics game/simulator in which the player can control meny aspects of life within a "society" of
one hundered people. Consequences of a player's actions will be as real as possible.
Title: Society
Arthor: third-meow
Date:
'''
# ## #
'''
Goals
include tax low wage cut off
include math for find l... |
print('Hello world')
def main():
pass
#łańcuch znaków
imie = "Adam"
print (imie)
print(type(imie))
print(type(5))
print(type(5.7))
print(type(True))
print(type(None))
# <class 'str'>
# <class 'int'>
# <class 'float'>
# <class 'bool'>
# <class 'NoneType'>
print(imie[2])
imie ="Damam"
imie = imie.lower()
print(... |
#!/usr/bin/env python
import numpy as np
import math as m
def angle_between_vectors(va = 'vector1' , vb = 'vector2'):
'''
Finds the angle between two vectors in degrees
(Internal Function)
Args:
va: first vector numpy array [x, y, z]
vb: second vector numpy array [x, y, z]
Returns:
Angle: angle between... |
#!/usr/bin/env python
def inverse_parabola(alpha, theta):
'''
Applies Inverse Parabola Scalling
Returns a number between 1 and 0.5
'''
return 1 - (2.0*alpha*alpha)/(theta*theta)
|
"""String"""
import pprint
def nicely_print(dictionary,print=True):
"""Prints the nicely formatted dictionary - shaonutil.strings.nicely_print(object)"""
if print: pprint.pprint(dictionary)
# Sets 'pretty_dict_str' to
return pprint.pformat(dictionary)
def change_dic_key(dic,old_key,new_key):
"""Change diction... |
from random import randint
from datetime import *
import time
def end_buble(buble):
def wrap(b):
print(f"{buble(b)}\n array is sorted by buble sort")
return wrap
def end_stupid(stupid):
def wrap(data):
print(f"""{stupid(data)}\narray is sorted by stupid sort""")
return wrap
def ti... |
from sqlite3 import *
#объект коонекта
conn = connect("Exercise_DB.db") #Создание / Подключение к базе данных с указанным названием
#Создание объекта курсора (уникальный указатель на данные)
cursor = conn.cursor()
#Создание таблици
"""
CREATE TABLE name_table
(name_column_1, surname_column_2, age_column_3)
"""
#... |
"""код_договора код_клиента код_кредита дата_выдачи сумма
1 ItSorce 23 04.10.2018 1000000
2 —odewars 3 17.01.2019 20000
3 ItCraft 17 31.12.2017 340000
4 SoftVerse 1 25.07.2020 900000
5 ItLand 44 06.06.2016 3000000
6 22 11.08.2011 440000
7 PostCode 22 830000
8 CraftSource 13 31.12.2017 340000
9 SoftVerse 1 25.07.2020 ... |
def me(x,y):
if x==y:
print("Yup!!")
else:
print("nope!!")
use_input = input("enter your favourite number:".upper())
user_input = input("enter your brother's favourite number:".upper())
me(use_input,user_input) |
# Use gradient descent to build linear regression model for predicting
# height, age, weight
# output alpha, num_iters, bias, b_age, b_weight
import pandas as pd
import sys
import numpy as np
import csv
from pandas import DataFrame
learning_rates = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10]
# add vector co... |
#Text of challenge: "Have the function LetterCapitalize(str) take the
#str parameter being passed and capitalize the first letter of each
#word. Words will be separated by only one space."
def LetterCapitalize(str):
return str.title()
print LetterCapitalize(raw_input()) |
#Using Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it
def FirstFactorial(num):
factorial = 1
for i in range(1,num+1):
factorial=factorial*i
return factorial
print FirstFactorial(raw_input()) |
import sys
import datetime
Feb = 2
TwentyNine = 29
def dayOfDate(date):
days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
dayNumber = date.weekday()
return days[dayNumber]
def checkLeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
... |
import math
import sys
import random
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
def read_input(filename):
with open(filename) as f:
cities = []
for line in f.readlines()[1:]: # Ignore the first line.
xy = line.split(',')
... |
# -*- coding: utf-8 -*-
def error(S,w):
''' renvoie l'erreur quadratique commis par le perceptron,
avec le vecteur de pondération w,
l'échantillon S.
'''
err = 0
for i in range(len(S)):
err += 0.5 * (S[i][1] - output_perceptron(S[i][0],w))**2
return err
def errorDeriva... |
is_male = False
is_tall = False
if is_male and is_tall:
print("You are a male and tall or both")
elif is_male and not(is_tall):
print("Your are a male but not tall")
elif not(is_male) and is_tall:
print("Your are not a male but you are tall")
else:
print("You neither male or tall")
# comparator> !=, ==... |
def check(x):
try:
num2=int(x) #an to num den einai int den einai oyte to num2 ara epistrefei false
calc(num2)
return True
except:
return False
def calc(y):
a=2 #dinei mia timh diaforh toy 1 sth metavlhth a gia na ksekinhsei h diadikasia
while a!=1: #oso o teli... |
# https://www.hackerrank.com/contests/world-codesprint-8/challenges/prime-digit-sums
import math
import time
primes = []
nav_map = {} # connect graph for groups of five
soln_cache = [] # solution cache
limit = 10 ** 9 + 7 # as per requirements
def primesieve(n):
primes = []
limit = int(n ** 0.5 + 1)
... |
x=input('enter x')
z= input('enter z')
sum=x+z
print(sum)
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = input()
arr = [int(i) for i in raw_input().strip().split()]
mean = float (sum(arr)) / n
print mean
def calc_median(input_list):
sorted_list = sorted(input_list)
l = len(sorted_list)
if(l%2 == 0):
med = float (sorted_list[l/2... |
import turtle
turtle.width(8)
turtle.color("green")
for i in range(18):
turtle.penup()
turtle.goto(0,0)
turtle.seth(i*20)
turtle.pendown()
for j in range(5):
turtle.circle(40,80)
turtle.circle(-40,80)
|
n1 = 34
n2 = 34.4
n3 = 100
s1 = 'Hello'
s2 = 'World'
total_n = n1 + n2 + n3
print(total_n)
n1 = n1 + 1
print(n1 + 1)
n2 = n2 + 10
print(n2)
n3 = n3 - 50
print(n3)
n3 = n3 * 50
print(n3)
n3 = n3 / 50
n1 += n1 + 1
print(n1)
n2 += 10
print(n2)
n3 *= 50
print(n3)
n3 /= 50
print(n3)
concat_string = s1 + s2
print(c... |
from arrays import Array
def mergeSort(lyst):
# lyst list being sorted
for i in xrange(1, 10)
# copyBuffer temporary space needed during merge
copyBuffer = Array(len(lyst))
mergeSortHelper(lyst, copyBuffer, 0, len(lyst) - 1)
def mergeSortHelper(lyst, copyBuffer, low, high):
... |
#Convolution applied on images
#Edge Detection
#download standard image
#wget --quiet https://ibm.box.com/shared/static/cn7yt7z10j8rx6um1v9seagpgmzzxnlz.jpg --output-document bird.jpg
#already downloaded
#1. load image (.jpg format)
#2. convert image to grayscale
#3. convolve image with edge detector kernel, store r... |
def authenticate(pwd1,pwd2):
if (pwd1 != pwd2):
return False
else:
return True
def getName():
name = raw_input("Please Enter Your Name:\n")
return name
def getPassword():
pwd2 = raw_input("Please Enter Your Password:\n")
return pwd2
if __name__=="__main__":
usr=getName()... |
import sys
import csv
str_max = []
def main():
# checks to validate usage
argv = sys.argv
argc = len(sys.argv)
if argc != 3:
print("Usage: dna.py input/File.csv input/File.txt")
exit(1)
# opens data file and saves the headers and number of headers
with open(argv[1], "r") as df:... |
lado=input("Ingrese el lado del cuadrado:")
lado=int(lado)
superficie= lado*lado
print("La superficie el cuadrado es: ")
print(superficie) |
class Stack:
def __init__(self):
self.values = []
def isEmpty(self):
Empty = False
if self.values == []:
Empty = True
return Empty
def push(self, value):
self.values.append(value)
def pop(self):
return self.values.pop()
def pee... |
def add(tree, value):
if tree == None:
newNode = {"data":value, "left":None, "right":None}
return newNode
elif tree["data"] == value:
return tree
elif value < tree["data"]:
tree["left"] = add(tree["left"], value)
return tree
elif value > tree["data"]:
tree... |
############################################### Linked list functions with recursion
def createTestList():
lastNode = {"data":"C", "next":None}
secondNode = {"data":"B","next":lastNode}
firstNode = {"data":"A", "next":secondNode}
return firstNode
def linkedListToString(LL):
stringResult = "|"
... |
import pandas as pd
import numpy as np
import time
from .neighborhoods import solution_generator, aux_neighborhoods, LS_neighborhoods
from .auxiliaries import calculatecosts
def VND(df, costs, n = 2, n1 = 10, n2 = 10, alpha = 0.3, nsol = 20):
"""
VND algorithm.
Args:
df: Dataframe that specifies... |
import random
import itertools
values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
deck = list(itertools.product(values, suits))
def shuffle_deck(deck):
count = 0
while count < len(deck):
current = deck[random.rand... |
int_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in int_list:
num = num + 1
print(num)
|
age = input('Enter your age: ')
def define_age(age):
age = int(age)
if 3 <= age < 7:
return 'Kindergarten'
elif 7 <= age <= 18:
return 'School'
elif 18 < age <= 23:
return 'College'
else:
return 'Some job'
res = define_age(age)
print(res)
|
# encoding-UTF-8
# AUTOR: José Antonio Vázquez Gabián
# Este programa imprime tu indice de masa corporal
#Calcula tu peso y estatura
def calcularIMC (peso,estatura):
x = (peso)/(estatura**2)
return x
def saberEstado(imc):
if imc<18.5:
p= ("Bajo Peso")
if imc>=18.5 and imc<=25:
p= ("Peso ... |
##################################################################################
# Step 1: Create tables in our database to hold trip info, pickups and dropoffs
#
# DEPRECATED: Initially wrote this to setup the backend. However, quickly found out that
# Heroku uses Postgresql so used this to play with da... |
#
# When creating a camera you need to specify the map's width and height and the
# screen's width and height.
#
# When you want to calculate the offset of everything call calculate_position()
# with the player/character's x and y coordinates and it returns the camera's
# coordinates. To use those the best idea (probab... |
'''
@author: whuan
@contact:
@file: lesson2.py
@time: 2018/10/20 19:47
@desc:控制语句,文件操作
'''
# 条件语句
import math
import time
num = 5
if num == 3:
print("3")
elif num == 5:
print("5")
else:
print("no")
# 循环
a = 1
while (a <= 10):
print(a)
a += 1
else:
print("结束")
for letter in "Ilovepython":
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 20 15:09:52 2016
@author: Kazuma Wittick
"""
maxMode = 0
array = [12, 3, 4, 5, 6, 7, 8, 9, 1, 4,4, 6, 2,1, 5, 76, 6, 6, 6 ]
for i in array:
getMode = array.count(i)
if getMode > maxMode:
maxMode = getMode
modeNumber = i
print modeNumber
|
exam_st_date = (11, 12, 2014)
(day,month,year) = exam_st_date
#it's tuple unpacking exercise :) how fun :) needed to refresh how to do it
print("The examination will start from : ",day,"/",month,"/",year)
|
import os
import sys
from csv import reader
class CompanyInfo(object):
""" The company info is stored in it """
def __init__(self, company_name):
"""called when object isntance is created"""
self.__company_price__list = []
self.__company_time_list = []
self.__name = company_name
... |
# python3
import sys
def compute_min_refills(distance, tank, stops):
start = 0
noOfStops = 0
stops.append(distance)
for i in range(len(stops)):
if (start + tank) >= distance:
return noOfStops
for j in range(i, len(stops)):
if (start + tank) < stops[j]:
... |
from random import randint
spock= int(1)
lagarto= int(2)
pedra= int(3)
papel= int(4)
tesoura= int(5)
jogador_contagem=0
computador_contagem=0
jogador=0
computador=0
while computador_contagem<3 and jogador_contagem<3:
computador= randint(1,5)
jogador= int(input("Vamos jogar! Para isso, é necessário que você ... |
from tkinter import *
import wikipedia
def search_me():
entery_value=e.get()
text.delete(1.0,END)
try:
answer_value=wikipedia.summary(entery_value)
text.insert(INSERT,answer_value)
except:
text.insert(INSERT,'please check your input or internet connection')
scr=Tk()
scr.tit... |
import numpy as np
from query import *
from config import *
def add_quotes(str):
"""Adds quotes on the end and returns the output"""
return f'\'{str}\''
def csv_reader(address, list_size, quotes):
""" Address is the csv file location,
list_size is the size of the row in the table to be inserted,... |
# Littel Machine Learning Test
#
# Using the popular Iris flower data set and sklearn along with Python
# http://scikit-learn.org/stable/
# https://en.wikipedia.org/wiki/Iris_flower_data_set
# The iris flower dataset is like the "hello world" program of datasets.
# It's not meant to be used in practical applications,... |
def main():
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
if __name__ == '__main__':
main()
|
array = []
count = 0
try:
n = int(input('Введите количество элементов в массиве: '))
for i in range(n):
array.append(int(input('Введите элемент массива: ')))
delta = int(input('Введите DELTA: '))
except ValueError:
print('Ошибка, введите целое число')
else:
for j in range(len(array) - 1):
... |
import turtle
import datetime
import time
def draw_hour(t, hour):
t.color("blue")
t.width(3)
t.right((360/12) * hour)
t.forward(150)
t.forward(-150)
t.setheading(90)
def draw_min(t, min):
t.color("lightblue")
t.width(3)
t.right((360/60) * min)
t.forward(150)
t.forward(-150)
t.setheading(90)
d... |
def is_sorted(string):
"""Returns True if string is sorted from least to greatest False otherwise."""
largest = 0
for char in string.lower():
if ord(char) > largest:
largest = ord(char)
else:
return False
return True
print(is_sorted("abed"))
def funny(asdf):
p... |
''' Write a function that will return the number of digits in an integer. '''
def len_of_int(number):
''' returns the number of digits in an integer '''
return len(str(number))
def remove_first_occurrence(substring, original_string):
''' returns string '''
return original_string.replace(substring, '',... |
from random import randint
while True:
s = int(input('Отгадай число:'))
a = randint(0, 11)
# обращай внимание на предупреждения PEP8
# между значениями и операторами должен быть пробел
# между именем функции и оператором вызова пробела нет
if s > 10:
print('Я загадываю числа от 1 до 10'... |
## helper functiont o find nearest neightbor respect to extracted target phrase
tokenized_lists = [nltk.pos_tag(word_tokenize(i)) for i in dataset['statement']]
## helper function to find nearest adjective respect to target phrase
def search_adj(word_list, target, text_tag):
"""
Search for a part of speech (P... |
import datetime
def gettime():
return datetime.datetime.now()
def take(k):
if k==1:
a=int(input("Enter 1 for Food and 2 for Exercise"))
if b==1:
value=input("Type here...")
with open("Harry Food.txt","a") as op:
op.write(str([str(gettime())])+":" +va... |
import numpy as np
'''
x + 2*y + z = 2
3*x + 8y + z = 12
4*y + z = 2
'''
A = np.matrix([[1,2,1], [3,8,1], [0,4,1]])
b = np.array([2,12,2])
# level 1: substract 2 * row1 from row2:
E_2_1 = np.matrix([[1,0,0], [-3,1,0], [0,0,1]])
print('level1: E_1_1 * A:')
u_2_1 = np.matmul(E_2_1, A)
print(u_2_1)... |
import unittest
from mock import Mock
from machine import Machine
from ..node import Node
from address import Address
class AddressTest(unittest.TestCase):
def setUp(self):
self.m = Machine('foo')
self.n = Node('TestNode')
def test_make_machine_address(self):
'''
An address it... |
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
return is_BST(root.left, -1, root.data) and is_BST(root.right, root.data, 10001)
def is_BST(current_node, min_data, max_data):
if current... |
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.neural_network.multilayer_perceptron import MLPRegressor
import matplotlib.pyplot as plt
from nn_regression_plot import plot_mse_vs_neurons, plot_mse_vs_iterations, plot_learned_function, \
plot_mse_vs_alpha, plot_bars_early_stopping_ms... |
#In this program we are trying to answer question 2. which mainly involve creating a exponential distrubition then
#"messing" it up by adding to it a number of uniform disturbition numbers. We will test when the exponential fit will no
#longer be a valid approximation with the chi sqaure function.
from ROOT import gRO... |
r1 = int(input ("введи r1 "))
r2 = int(input ("введи r2 "))
r3 = int(input ("введи r3 "))
s1 = int(input ("введи s1 "))
s2 = int(input ("введи s2 "))
s3 = int(input ("введи s3 "))
x1 = r1/s1
x2 = r2/s2
x3 = r3/s3
if (x1>x2) and (x1>x3):
print ('1')
if (x2>x1) and (x2>x3):
print ('2')
if (x3>x1) and (x3>x... |
n = int(raw_input("Please enter a number: "))
builder = "*"
line = ''
for amount in range(0, n):
line = line + builder
for x in range(0, n):
print line
def square(n):
for i in xrange(0, n):
print '*' * n
n = int(raw_input("Enter a number: "))
square(n)
|
# 这个模块显示了类的继承顺序。
class A:
def __init__(self):
self.n = 2
def add(self, m):
print('self is {0} @A.add'.format(self))
self.n += m
class B(A):
def __init__(self):
self.n = 3
def add(self, m):
print('self is {0} @B.add'.format(self))
super().add(m)
... |
from double_queue import DoubleQueue
class Node(object):
"""定义树的节点"""
def __init__(self, item=None):
self.item = item
self.lchild = None
self.rchild = None
class Tree(object):
def __init__(self):
node = Node()
self.root = node
self.q = DoubleQueue()
def ... |
# This Program finds the smallest positive number
# that is evenly divisible by all of the numbers from 1 to 20
from math import log, floor, sqrt
def lcm(n, primes):
limit = sqrt(n) # square root of n
a = {} # exponents
check = True
i = 0
result = 1
while primes[i] <= n:
a[i] = 1
... |
#!/usr/bin/env python
# coding: utf-8
# ### References:
# https://machinelearningmastery.com/how-to-perform-face-recognition-with-vggface2-convolutional-neural-network-in-keras/
#
# https://github.com/rcmalli/keras-vggface/
# In[1]:
import matplotlib.pyplot as plt
import numpy as np
import dlib
import cv2
from s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.