text stringlengths 37 1.41M |
|---|
import numpy as np
def knn(vector, matrix, k=10):
"""
Finds the k-nearest rows in the matrix with comparison to the vector.
Use the cosine similarity as a distance metric.
Arguments:
vector -- A D dimensional vector
matrix -- V x D dimensional numpy matrix.
Return:
nearest_idx -- A n... |
#Protein Translation Problem: Translate an RNA string into an amino acid string.
#Input: An RNA string "Pattern"
#Output: The translation of "Pattern" into an amino acid string "Peptide"
def translate(pattern):
translation_table = create_translation_table()
peptide = ""
i = 0
while i < len(pattern) - 2... |
# class Solution:
# def climbStairs(self, n: int) -> int:
# if n == 1 or n == 2:
# return n
# l = [1 for i in range(n)]
# l[1] = 2
# for i in range(2, n):
# l[i] = l[i - 1] + l[i - 2]
# print(l)
# return l[n - 1]
class Solution:
def climbS... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root == None:
return []
now_nodes = [root]
n... |
class Solution:
def exist(self, board, word: str):
n = len(board)
m = len(board[0])
def get_ans(board, i, j, t):
if t == len(word):
return True
if i < 0 or i >= n or j < 0 or j >= m:
return False
if board[i][j] == word[t]:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 20:50:55 2020
@author: john
"""
class net():
def __init__(self):
self.encoder = Encoder()
self.model = self.create_model()
def create_model(self):
"""function to create a model for making prediction"... |
import copy
class Grid():
def __init__(self, gridSize):
try:
gridSize = int(gridSize)
except ValueError:
raise ValueError("Error: gridSize is not a number!")
if gridSize <= 1:
raise ValueError("Error: gridSize must be greater then 1!")
self.gri... |
# tuples using filter
def Remove(tuples):
tuples = filter(None, tuples)
return tuples
# Driver Code
tuples = [(), ('ram', '15', '8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('', ''), ()]
print(Remove(tuples)) |
# To find next gap from current
def getNextGap(gap):
# Shrink gap by Shrink factor
gap = (gap * 10) / 13
if gap < 1:
return 1
return gap
# Function to sort arr[] using Comb Sort
def combSort(arr):
n = len(arr)
# Initialize gap
gap = n
swapped = True
while gap != 1 or swap... |
from collections import defaultdict
def end_check(word):
sub1 = word.strip()[0]
sub2 = word.strip()[-1]
temp = sub1 + sub2
return temp
def front_check(word):
sub = word.strip()[1:-1]
return sub
# initializing string
test_str = 'best and bright'
# printing original string
print("The origin... |
def check(string):
if len(set(string).intersection("AEIOUaeiou")) >= 5:
return ('accepted')
else:
return ("not accepted")
# Driver code
if __name__ == "__main__":
string = "geeksforgeeks"
print(check(string)) |
# list of numbers
list1 = [-10, -21, -4, -45, -66, 93, 11]
pos_count, neg_count = 0, 0
num = 0
# using while loop
while (num < len(list1)):
# checking condition
if list1[num] >= 0:
pos_count += 1
else:
neg_count += 1
# increment num
num += 1
print("Positive numbers in the list: ... |
def shellSort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n / 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
... |
# Returns length of string
def findLen(str):
if not str:
return 0
else:
some_random_str = 'py'
return ((some_random_str).join(str)).count(some_random_str) + 1
str = "geeks"
print(findLen(str)) |
def cocktailSort(a):
n = len(a)
swapped = True
start = 0
end = n - 1
while (swapped == True):
swapped = False
for i in range(start, end):
if (a[i] > a[i + 1]):
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
# if nothing moved, th... |
l = [l for l in input("List:").split(",")]
print("The list is ", l)
# Assign first element as a minimum.
min1 = l[0]
for i in range(len(l)):
# If the other element is min than first element
if l[i] < min1:
min1 = l[i] # It will change
print("The smallest element in the list is ", min1) |
import numpy as np
from gensim.models import Word2Vec
def create_word2vec_matrix(data_loader, min_count=20, size=100, window_size=3):
"""
Arguments
---------
`data_loader`: `list`-like
A `list` (or `list` like object), each item of which is itself a list of tokens.
For example:
... |
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print(abs(10))
10
>>> print(abs(-10))
10
>>> steps = -3
>>> is abs(steps) > 0:
SyntaxError: invalid syntax
>>> steps = -3
>>> if abs(steps) > 0... |
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> age = 13
>>> if age > 20:
print('You are too old!')
>>> age = 25
>>> if age > 20:
print('You are too old!')
print('Why are you here?')
pri... |
"""
Example: Specific cancer that occurs to 1% of population P(c) = 0.01
Test for this cancer with a 90% chance is positive if you have this cancer (this is sensitivity of the test)
But the test is sometimes is positive even if you don't have a cancer C.
Let's say with another 90% chance is negative if you don't have c... |
from typing import List
##################################################
# BINARY SEARCH
def search(nums: List[int], target: int) -> int:
"""
704. Binary Search
Given an array of integers nums which is sorted in ascending order,
and an integer target, write a function to search target in nums.
... |
#1. Merge sort
def MergeSort(array):
temp=[0]*len(array) #new a temp list to store temporary result in the merge process
def sort(a,left,right,temp):
if left<right:
mid=(left+right)//2
sort(a,left,mid,temp) #sort the left side
sort(a,mid+1,righ... |
"""
Various functions for finding/manipulating silence in AudioSegments
"""
import itertools
from .utils import db_to_float
def detect_silence(audio_segment, min_silence_len=1000, silence_thresh=-16, seek_step=1):
"""
Returns a list of all silent sections [start, end] in milliseconds of audio_segment.
In... |
'''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
@author: Matt
'''
def multiples(n):
for i in range(2,20): # increment by 20, so no need to check for 20... |
def add(num1, num2):
return num1+num2
def subs(num1, num2):
return num1-num2
def multi(num1 , num2):
return num1*num2
def div(num1, num2):
return num1/num2
select = input("Select the operation of Calci:")
num1 = int(input("Enter the number 1:"))
num2 = int(input("Enter the number 2:"))
if... |
#For loop learning
cars = ['Toyota', 'Honda']
for car in cars: #bring Toyota & Honda out
print(car)
names = ['Thomas', 'Jakc', 'Tom']
for name in names:
print(name)
#exercise
students = ['Allen', 'Tom', 'Mayday', 'JJ', 'Jolin', 'Jay', 'Jam']
for student in students:
print('Hi ', student)
#str as list
book = '... |
__author__ = 'Sergey Khrul'
from math import sqrt
def solve (a, b, c):
d = b * b - 4 * a * c
if d < 0:
return "No solution"
elif d == 0:
return "One solution: {}".format(-b / (2 * a))
elif d > 0:
x1 = (-b + sqrt(d)) / (2 * a)
x2 = (-b - sqrt(d)) / (2 * a)
retur... |
#!/usr/bin/python
#coding=utf-8
import sys
import os
#python3只有input,由于input返回是string,所以需要用int转
try:
lin1=int(input('请输入第一条边:'))
lin2=int(input('请输入第二条边:'))
lin3=int(input('请输入第三条边:'))
# {}是占位符,format函数对数据格式化
except Exception:
print ("不支持小数")
else:
print('周长是{}'.format(lin1+lin2+lin3)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions for cleaning up text, typically from bad OCR scans."""
import itertools
import string
from typing import Tuple, List, Dict, Set, Iterable, TypeVar
from text_cleanup import parse
from text_cleanup import utils
A = TypeVar('A') # pylint: disable=invalid-name... |
"""
Conversion Utilities
====================
Contains a number of conversion utilities for converting objects.
For example, ``from_dict_to_csv`` will convert a sorted dictionary to a csv file
Notes
------
#. Should These be in files.py?
"""
import csv
import pandas as pd
# ------------- #
# - CSV Files - #
# -----... |
# Currency converter by Urmil Shroff
import bs4
import requests
res = requests.get("http://dollarrupee.in/")
soup = bs4.BeautifulSoup(res.text, "lxml")
rate = soup.select(".item-page p strong") # selects the ruppee value
rupee = float(rate[0].text)
print("Today's rate: $1 = ₹{}".format(rupee))
print("What do you w... |
"""
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Displays the Graphical User Interface (GUI) and communicates with the robot.
Authors: Your professors (for the framework)
and Zixin Fan.
Spring term, 2018-2019.
"""
# DONE 1: Put your name in the above.
import tkinter
from tkinter import tt... |
# 示例
# a = 1
# while a != 0:
# print("please input")
# a = int(input())
# print("over")
#升级版猜数字
num = 10
print('Guess what I think?')
bingo = False
while bingo == False:
answer = int(input())
if answer < num:
print("Too small!")
elif answer > num:
print("Too big!")
else:
... |
'''
http://projecteuler.net/problem=191
Prize Strings
Problem 191
'''
'''
Notes on problem 191():
Combinatorics should be done along the lines of:
http://jsomers.net/blog/project-euler-problem-191-or-how-i-learned-to-stop-counting-and-love-induction
Can't be late twice:
(L,L,*,*,*,...,*) and all it's permutations mus... |
#!/usr/local/bin/python3.3
'''
Prime square remainders
Problem 123
Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn−1)n + (pn+1)n is divided by pn2.
For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25.
The least value of n for which the remainder first exceeds 109 is 7037.
... |
'''
Problem 24
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 20... |
'''
Problem 94
It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units.
We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no... |
'''
Problem 172
How many 18-digit numbers n (without leading zeros) are there such that no digit occurs more than three times in n?
'''
def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
# There are 9*10**17 possible 18 digits number
total = 9... |
#!/usr/local/bin/python3.3
'''
Problem 87
The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way:
28 = 2^2 + 2^3 + 2^4
33 = 3^2 + 2^3 + 2^4
49 = 5^2 + 2^3 + 2^4
47 = 2^2 + 3^3 + 2^4... |
#!/usr/local/bin/python3.3
'''
Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6.
The number 1... |
'''
http://projecteuler.net/problem=122
Efficient exponentiation
Problem 122
'''
'''
Notes on problem 122():
'''
def problem122():
m = {}
seen = set()
def gen(current, maximum):
if maximum > 200:
return
if current in seen:
return
if maximum not in m:
... |
#!/usr/local/bin/python3.3
'''
It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five thousand different ways?
'''
'''
Notes on problem 77():
'''
from PE_pr... |
'''
http://projecteuler.net/problem=232
The Race
Problem 232
'''
'''
Notes on problem 232():
'''
from itertools import count, combinations
import random
import math
def problem232():
games = 0
while True:
A_score = 0
B_score = 0
for r in count():
if A_score >= 100 or B_score >= 100:
print(A_score, B_s... |
#!/usr/local/bin/python3.3
'''
Summation of primes
Problem 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
from pe.primes import primesUpTo
def problem10():
return sum(primesUpTo(2*10**6))
from cProfile import run
if __name__ == "__main__":
print(prob... |
'''
Problem 117
Using a combination of black square tiles and oblong tiles chosen from: red tiles measuring two units, green tiles measuring three units, and blue tiles measuring four units, it is possible to tile a row measuring five units in length in exactly fifteen different ways.
How many ways can a row measuri... |
#!/usr/local/bin/python3.3
'''
Problem 53
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr =
n!
r!(n−r)!
,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, th... |
#!/usr/local/bin/python3.3
'''
http://projecteuler.net/problem=115
Counting block combinations II
Problem 115
'''
'''
Notes on problem 115():
'''
def problem115():
def numberOfSolutions(minlength,numBlocks,soFar=0,d={}):
if (minlength,numBlocks) not in d:
count = 1 # Everything is blank
for length in range(... |
#!/usr/local/bin/python3.3
'''
http://projecteuler.net/problem=127()
abc-hits
Problem 127
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
GCD(a, b) = ... |
'''
http://projecteuler.net/problem=128
Notes on problem 128():
'''
from PE_primes import isPrime
def problem128():
count = 1
limit = 2000
n = 0
number = 0
while count < limit:
n += 1
if (isPrime(6 * n - 1) and isPrime(6 * n + 1) and isPrime(12 * n + 5)):
count += 1;
... |
'''
Problem 116
A row of five black square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four).
If red tiles are chosen there are exactly seven ways this can be done.
If green tiles are chosen there are three ways.
... |
import unittest
class YearTestCase(unittest.TestCase):
def test_year_leap(self):
for year in (2000, 2016, 1916):
with self.subTest(year=year):
self.assertTrue(is_year_leap(year),
"{} на самом деле високосный".format(year))
def ... |
"""Используйте names.txt, текстовый файл размером 46 КБ, содержащий
более пяти тысяч имен. Начните с сортировки в алфавитном порядке. Затем
подсчитайте алфавитные значения каждого имени и умножьте это значение на
порядковый номер имени в отсортированном списке для получения количества
очков имени.
Какова сумма о... |
a = list()
a.append(list(input()))
a.append(list(input()))
while a[-1][0] != "-":
a.append(list(input()))
ans = 0
for i in range(len(a)):
for j in range(len(a[0])):
if a[i][j] == "#" and a[i-1][j] != "#" and a[i][j-1] != "#":
ans += 1
print(ans)
|
#This code is from cisco PRNE course
from pprint import pprint
import re
#create regular expression to match ethernet interface names
eth_pattern = re.compile('Ethernet[0-9]')
routes = {}
#read all lines of IP routing information
file = open('ip-routes','r')
for line in file:
match = eth_pattern.search(line... |
#模块 放在 包 下面
#文件夹 一般存放 一些配置文件等。
def sum(a,b):
print (a+b)
#内置变量 __name__
#运行本模块,该模块的__name__ 就是 __main__ 相当于程序的入口
# print (__name__) #打印结果为: __main__
#如果模块被其他模块调用, __name__ 就是该模块的模块名
if __name__ == '__main__': #这条语句的作用:1、程序的入口 2、调试时使用 #这条语句 在本模块被其他模块调用时也不需要删除。
sum(2,3) |
import time
import threading
def foo(something):
for i in range(10):
time.sleep(1)
print (something)
#创建线程 --本质是 创建了一个实例,因为 Thread() 是一个类。
t1 = threading.Thread(target=foo,args=('看电影',))
t2 = threading.Thread(target=foo,args=('听音乐111111',))
#声明守护线程
t1.setDaemon(True)
# t2.setDaemon(True)
#启动线程
t1... |
#!/usr/local/bin/python
# encoding=utf-8
file_obj = open('a.txt', 'r')
line1 = file_obj.readline() # 读取一行
line1 = line1.rstrip() #strip() 函数的作用是去掉
print(line1)
line2 = file_obj.readlines() # 读取多行
#lines2 = line2.strip() #readlines has no attribute of 'strip()'
print(type(line2))
boys = ['Mike', 'Jhon', 'Tom'... |
import threading,time
def foo(something,num):
for i in range(num):
time.sleep(1)
'''写上面这行代码的原因是 2个线程是并发执行,且因为 资源竞争,导致 2 个线程之间,
其中一个线程还没有执行完,CPU就被另外一个线程抢走了,
所以会出现 打印结果为 “CPU正在CPU正在 处理迅雷的任务处理Pycharm的任务”这样的情况。
如何解决 资源竞争,这里就用到了 同步锁 。'''
print ('CPU正在',something)
... |
# Diagonal Difference
# n = int(input().strip())
# arr = []
# for _ in range(n):
# arr.append(list(map(int, input().rstrip().split())))
def diagonalDifference(arr):
""" Calculates the absolute difference between
the sums of its diagonals """
sum1 = 0
sum2 = 0
counter = 0
for i in arr... |
# %%
# Compare the Triplets
def compareTriplets(a, b):
""" Determines their respective comparison points """
alice = 0;
bob = 0;
for i in range(len(a)):
if a[i] > b[i]:
alice += 1
elif a[i] < b[i]:
bob += 1
return alice,bob
# Running some tests..
print(compa... |
# Mini-Max Sum
# arr = list(map(int, input().rstrip().split()))
def miniMaxSum(arr):
""" Finds the minimum and maximum values that can be
calculated by summing exactly four of the five integers """
sum_min = 0
sum_max = 0
for i in range(4):
sum_min += sorted(arr)[i]
sum_max += sor... |
import time
import pygame
from datetime import date
import keyboard
#Get Todays Date And Weekday Number
today = date.today()
day = date.isoweekday(today)
#Get Current Time In Hours And Minutes
def currentTime():
hour = time.strftime("%H")
current_hour = int(hour)
minutes = time.strftime("%M")
... |
#!/usr/bin/env python
import sys
g_sqSize = -1 # the board size, passed at runtime
g_board = [] # the board will be constructed as a list of lists
def main():
global g_sqSize
if len(sys.argv) != 2:
g_sqSize = 8 # Default: Fill the normal 8x8 chess board
else:
try: g_sqSize = int(sys.... |
import numpy as np
print("3)")
s = [2, 3.6667, 5, 7.2, 10]
n = [50, 100, 200, 500, 1000]
def dzeta_f_single(s, n):
total_sum = np.float32(0)
for k in range(1, n + 1):
total_sum += np.float32(1) / np.float32(k) ** np.float32(s)
return total_sum
def dzeta_b_single(s, n):
tota... |
#!/usr/bin/env python3
""" Find a given entry_name in the given or stored index
"""
def show_map(name_2_path):
""" Show the whole name_2_path index of this collection.
"""
from pprint import pprint
pprint(name_2_path)
def byquery(query, name_2_path, collections_searchpath, __entry__=None, __kernel... |
# The try block will raise an error when trying to write to a read-only file:
try:
f = open("demoFile.txt")
f.write("Welcome")
except Exception as e:
print(e)
print("Something went wrong when writing to the file")
finally:
f.close()
# The program can continue, without leaving the file objec... |
def test(temperature):
assert(temperature > 0), "Colder than absolute zero!"
return (temperature - 273)*1.8 + 32
def fun(level):
if level < 0:
raise Exception(level)
return level
try:
print(test(10))
print(test(-10))
except Exception as arg:
print('hhh', arg)
try:
print(fun(... |
#Developer: Gabriel Yugo Nascimento Kishida
#Contact: gabriel.kishida@usp.br
#Date: January/2021
#Description : Algorithm that applies the method of LU decomposition to solve linear systems.
import numpy as np
#Functionality: this function calculates the sum of a multiplication, a value useful to the decomposition.
... |
"""
It takes a url and get that page. From that page it gets all the links that start with start_str.
"""
def getPage(url):
"""
it returns the page data
"""
import urllib2
f = urllib2.urlopen(url)
return f.read().decode('utf-8')
def getLinks(string):
from BeautifulSoup import BeautifulSoup... |
# Python3 program to swap first and last element of a list
Examples:
Input : [12, 35, 9, 56, 24]
Output : [24, 35, 9, 56, 12]
Input : [1, 2, 3]
Output : [3, 2, 1]
----------------------------------------
Approach #1: Find the length of the list and simply swap the first element with (n-1)th element.
# Swap function ... |
Python code using ord function :
ord() : It coverts the given string of length one, return an integer representing the unicode code point of the character. For example, ord(‘a’) returns the integer 97.
# Python program to print
# ASCII Value of Character
# In c we can assign different
# characters of which we wa... |
def recursion(k):
if(k > 0):
result = k + recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
recursion(6)
OUTPUT:
Recursion Example Results
1
3
6
10
15
21 |
from PIL import Image
nb=int(input("How much red or blue do you want ? -0 : total blue, 250 : total red and 100 the middle"))
img = Image.open("avantages-quil-y-a-a-grandir-dans-un-petit-village.jpg")
pixels = img.load()
for i in range(img.width):
for j in range(img.height):
r, g, b = pixels[i, j]
... |
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if target not in nums:
return [-1,-1]
else:
where = []
# Search from the left side
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 21:47:23 2019
"""
import time
import asyncio
import cozmo
from cozmo.util import degrees, Pose
from cozmo.util import distance_mm, speed_mmps
def find_face(robot: cozmo.robot.Robot):
global pose
print ("cozmo is looking for a human fa... |
def get_tokens(file_name="res/02.txt"):
with open(file_name) as f:
lines = f.readlines()
tokens = [l.strip() for l in lines]
return [t for t in tokens if t]
def hash(token: str):
letters = set(token)
counts = {
letter: len([l for l in token if l == letter]) for letter in letters
... |
#function to get initials of name.
def to_initials(name):
li = name.split(" ")
initials = ""
for ele in li:
initials += ele[0][0]
return initials
#print(to_initials("Kelvin Bridges"))
#print(to_initials("Michaela Yamamoto"))
#print(to_initials("Mary La Grange"))
# finding the element that appears first in the ... |
#Class to represent a Room object
class Room:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
print("-> Room generated with dimensions x: {0}, y: {1}, z: {2}".format(x, y, z)) |
import geopandas as gpd
from shapely.geometry import Point
def spatial_join_zipcode(df, communities):
"""
Function to spatially join communities data to a dataframe with latitude and longitude.
Note: "lat_long" column must be of tuple type with first element being latitude
and second element bein... |
import random
class Esqueleto():
'''Representa el esqueleto interno del Gunpla.'''
def __init__(self):
'''Inicializa los atributos de un Esqueleto'''
self.velocidad = random.randint(-25, 50)
self.energia = random.randint(1000,2000)
self.movilidad = random.randint(1000,1500)
... |
import sys
import turtle
wn = turtle.Screen()
s = turtle.Turtle()
mylist=[-3,-5,0,2,3,7,11,12]
wordlist=["How", "many" ,"fish" ,"does" ,"the" ,"little", "child", "kid", "have"]
samlist={"How", "sam", "many", "fish", "does", "the", "little" ,"kid","have?"}
def test(did_pass):
""" Print the result of a test. """... |
"""1. Add some new key bindings to the first sample program:
Pressing keys R, G or B should change tess’ color to Red, Green or Blue.
Pressing keys + or - should increase or decrease the width of tess’ pen. Ensure that the pen size stays between 1 and 20 (inclusive).
Handle some other keys to change some attributes of... |
revenue = [14574.49, 7606.46, 8611.41, 9175.41, 8058.65, 8105.44, 11496.28, 9766.09, 10305.32, 14379.96, 10713.97, 15433.50]
expense = [12051.82, 5695.07, 12319.20, 12089.72, 8658.57, 840.20, 3285.73, 5821.12, 6976.93, 16618.61, 10054.37, 3803.96]
profit = []
for i in range(12):
profit.append(revenue[i]-expense[i])... |
def fib_rec (n):
if n<=1:
return n
else:
return fib_rec(n-1)+fib_rec(n-2)
n=int(input("Enter a number : "))
while n <=0:
n=int(input("Please enter a positive integer : "))
print("Fibonacci series of",n,"is :")
for i in range(n):
print(fib_rec(i)) |
import random
import hashlib
def main():
print('starting the search')
searches = 0
matches = list()
try:
while True:
searches += 1
string = makeString()
if isMatch(string):
print('We have success! ' + string + ' is the winner!')
matches.append(string, searches)
else:
print
if searche... |
import re
from functools import reduce
def doCode():
m = re.compile("(\w+):")
soln = 0
x = 0
d = set()
f = open("input", "r+")
lines = f.readlines()
for i in lines:
if i.strip() == "":
x += 1
if not checkValid(d):
print(f"invalid: {d}")
... |
from homework1.task05 import find_maximal_subarray_sum
def test_empty_list_case():
"""Testing that function returns 0 if list is empty"""
assert find_maximal_subarray_sum([], 3) == 0
def test_all_negative_case():
"""Testing that function returns correct answer with negative only"""
assert find_maxim... |
"""
Необходимо создать 3 класса и взаимосвязь между ними (Student, Teacher,
Homework)
Наследование в этой задаче использовать не нужно.
Для работы с временем использовать модуль datetime
1. Homework принимает на вход 2 атрибута: текст задания и количество дней
на это задание
Атрибуты:
text - текст задания
dead... |
EMPTY_CELL = ' '
class Field:
def __init__(self):
self._field = [[EMPTY_CELL for _ in range(3)] for _ in range(3)]
def __str__(self):
return '\n'.join('|'.join(cell for cell in row) for row in self._field)
def set_symbol(self, x, y, symbol):
"""
>>> f = Field()
>>... |
class A:
def __init__(self):
self.__a = 1
def f(self):
return self.__a
a = A()
print(vars(a))
class B(A):
def __init__(self):
super().__init__()
self.__a = 2
b = B()
print(b.f()) |
import streamlit as st
from model import get_model
import numpy as np
from PIL import Image
import cv2
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
model = get_model(pretrained=True, dataset_name="RAFDB")
basic_emotions = ['surprise', 'fear', 'disgust',
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 17:37:47 2020
@author: singh
"""
# 2. Read or convert the columns ‘Created Date’ and Closed Date’ to datetime datatype and create a new column ‘Request_Closing_Time’ as the time elapsed between request creation and request closing.
import datetime as dt
imp... |
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
df=pd.read_csv("C:/Users/mahid/ML LAB/Logistic Regression/insurance_data.csv")
plt.scatter(df.age,df.bought_insurance)
data_train,data_test,tar_train,tar_tes... |
#!/usr/bin/python
#!encoding: UTF-8
import matplolib,pyplot as pl
import sys
import modulo
import time
startubuntu=time.time()
startcpu=time.clock()
t=[]
argumentos = sys.argv[1:]
if (len(argumentos) == 8):
n = int (argumentos[0])
aproximaciones = int (argumentos[1])
umbral = []
for i in range (2,7):
umb... |
import coffee_shop
from coffee_shop import add_milk
print("Welcome to", coffee_shop.shop_name)
print("Available sizes: \n", "\n".join(coffee_shop.coffee_sizes))
print("Available roasts: \n", "\n ".join(coffee_shop.coffee_roasts))
print("Available milks: \n", "\n".join(coffee_shop.milk_type))
order_size = input("What s... |
from copy import deepcopy
class Queue:
"""A basic Stack implementation using lists""" # docstring
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0) # If no index is specified, a.pop() re... |
"""
剑指 Offer 26. 树的子结构
输入两棵二叉树 A和 B,判断 B是不是 A的子结构。(约定空树不是任意一个树的子结构)
B是 A的子结构, 即 A中有出现和 B相同的结构和节点值。
例如:
给定的树 A:
3
/ \
4 5
/ \
1 2
给定的树 B:
4
/
1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
示例 1:
输入:A = [1,2,3], B = [3,1]
1 3
/ \ /
2 3 1
输出:false
示例 2:
输入:A = [3,4,5,1,2], B = [... |
"""
面试题03. 题目2: 不修改数组找出重复的数字
在一个长度为 n + 1 的数组中所有的数字都在 1 ~ n 的范围内,所以数组中至少存在一个重复数字。
请找出数组中的任意一个重复数字,但不能修改输入的数组。
例如,如果输入长度为 8 的数组 [2, 3, 5, 4, 3, 2, 6, 7], 那么对应的输出是重复的数字 2 或 3
date : 9-17-2020
"""
def findDuplication(nums, length):
box = set()
repeat = None
for i in range(length):
if not box.add(nu... |
"""
51. N 皇后
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
提示:
皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。
示例
输入:4
输出:[
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".... |
"""
剑指 Offer 55 - I. 二叉树的深度
输入一棵二叉树的根节点,求该树的深度。
从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
date: 2021年2月26日
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.