text stringlengths 37 1.41M |
|---|
"""
An implementation of gaussian processes.
Author: Ben Ellis
"""
from functools import partial
from typing import Callable, Dict
import numpy as np
import pandas as pd
class GaussianProcess:
def __init__(
self,
kernel: Callable[[np.array, np.array, Dict[str, float]], np.array],
sigma: f... |
"""Utilities for working with sequence i/o.
"""
from collections import OrderedDict
import re
import textwrap
import numpy as np
__author__ = 'Hayden Metsky <hayden@mit.edu>'
def read_fasta(fn, data_type='str', replace_degenerate=False):
"""Read a FASTA file.
Args:
fn: path to FASTA file to read
... |
# https://math.stackexchange.com/questions/442459/for-the-fibonacci-numbers-show-for-all-n-f-12f-22-dotsf-n2-f-nf-n1
def fibonacci_sum_squares_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
... |
import random
class GeneticAlgorithm:
def __init__(self, population_size = 8, mutation_rate = 0.001, number_iterations = 1000):
self.population_size = population_size
self.number_iterations = number_iterations
self.mutation_rate = number_iterations
# generates binary initial population
def generate... |
"""
CMPS 2200 Assignment 1.
See assignment-01.pdf for details.
"""
# no imports needed.
def foo(x):
if x <= 1:
return x
else:
return foo(x-1) + foo(x-2)
def longest_run(mylist, key):
#iterative sequential version
tempcounter = 0
finalcount = 0
for i in mylist:
if i != ... |
# -*- coding:utf-8 -*-
"""
@author: timkhuang
@contact: timkhuang@icloud.com
@software: PyCharm
@file: View.py.py
@time: 06/07/2020 21:24
@description: This is the abstract class for all the rendering/visualisation of the game/board.
"""
from abc import ABC, abstractmethod
class View(ABC):
"""
An Abstract c... |
from numpy import abs as ABS
def absolute(xi, xf):
'''
Calculates absolute error
params:
- xi: previous value
- xf: current value
'''
if xi == None or xf == None:
raise AttributeError("values xi and xf cannot be None")
return ABS(xi - xf)
def relative(xi, xf):
''... |
X=int(input("Enter the value for holder 1:"))
Y=int(input("Enter the value for holder 1:"))
Z=int(input("Enter the value for jug:"))
x=0
y=0
while Z<X<Y:
print(x,y)
if x==0:
for i in range(0,X):
if x==X:
break
x+=1
if not(y==0):
print(x, ... |
import datetime
import calendar
from enum import IntEnum
class Weekday(IntEnum):
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY = 5
SUNDAY = 6
def meetup_date(year, month, nth=None, weekday=None):
day = 1
if weekday is None:
nth = 4
weekday =... |
# -*- coding: utf-8 -*-
"""Basic tests for the binary search tree"""
import unittest
from structures.binary_tree import BinaryTree
class TestBinaryTree(unittest.TestCase):
"""Basic test class for binary tree"""
def test_empty(self):
"""Basic test method for binary tree"""
self.assertTrue(Bi... |
# -*- coding: utf-8 -*-
'''Singly linked list implementation
Author: Larsen Close
Version: Completed through extra credit level work with implementation and
tests for extra methods
Outline and initial tests provided in class by Professor Dr. Beaty at
MSU Denver
Todo:
* Make runnable from file
* Also also us... |
"""
Basic TSP Example
file: Individual.py
"""
import collections
import random
import math
import uuid
class Individual:
def __init__(self, _size, _data, cgenes):
"""
Parameters and general variables
"""
self.fitness = 0
self.genes = []
self.genSize = ... |
# coding=utf-8
import time
from com.igitras.algorithm.libs import swap_element, random_list
__author__ = 'mason'
# 直接插入排序
def direct_insertion(list_to_sort):
length = len(list_to_sort)
index = 1
while index < length:
inner_index = index
while inner_index >= 1:
if list_to_sort[... |
from tkinter import *
top=Tk()
top.geometry("400x400")
def rst():
chkbx1.set(0)
chkbx2.set(0)
rbvr1.set(0)
rbvr2.set(0)
def chk():
print("Your Interests are :")
if chkbx1.get()==1:
print("Data Strcut and Algo")
if chkbx2.get()==1:
print("Distributed Systems")
print("\n")
result="Gender is : "+rbvr1.get(... |
class EvaluationFunction(object):
"""Store evaluation functions"""
def __init__(self, data, factory):
self.data = data
self.factory = factory
def evaluate(self, timetable):
"""Return sum of penalties"""
penalty = self.countRoomCapacityPenalty(timetable)
penalty += s... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i... |
l = float(input('Largura da parede:'))
a = float(input('Altura da parede:'))
m = (l*a)
print('Sua parede tem a dimensao de {}x{} e a sua area e de {}m²'.format(l,a,m))
print('Para pintar essa parede, voce precisara de {}L de tinta'.format(m/2))
|
'''resposta = contador = media = maior = menor = dividido = 0
while resposta != 'N':
contador += 1
numero = int(input('Digite um número: '))
if maior > numero:
maior = maior
else:
maior = numero
if contador < 2:
menor = maior
elif menor < numero:
menor = menor
... |
print('Gerador de PA')
print('-='*10)
primeirotermo = int(input('Primeiro Termo: '))
razao = int(input('Razão: '))
cont = 1
termo = primeirotermo+razao
while cont != 10:
print('{} '.format(termo), end=' ')
termo += razao
cont += 1
print('FIM')
|
soma = 0
for c in range(1, 7):
num = int(input('Digite o {} valor: '.format(c)))
if num % 2 == 0:
soma = soma + num
print('A soma dos números pares foi {}'.format(soma))
|
dinheiro = float(input('Quanto de dinheiro voce tem na carteira? R$'))
d = (dinheiro / 5.36)
print('Com R${:.2f} voce pode comprar US${:.2f}'.format(dinheiro,d))
|
medida = float(input('Digite a medida:'))
km = (medida / 1000)
cm = (medida * 100)
mm = (medida * 1000)
print('A medida {} corresponde a {}km, {}cm, {}mm'.format(medida,km,cm,mm))
|
'''p1 = float(input('Peso da 1ª pessoa: '))
p2 = float(input('Peso da 2ª pessoa: '))
p3 = float(input('Peso da 3ª pessoa: '))
p4 = float(input('Peso da 4ª pessoa: '))
p5 = float(input('Peso da 5ª pessoa: '))
if p1 > p2 and p1 > p3 and p1 > p4 and p1 > p5:
print('O maior peso lido foi de {}Kg'.format(p1))
elif p2 > ... |
def leiaint(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[0:31mERRO! Digite um número inteiro válido.\033[m')
continue
except KeyboardInterrupt:
print('\033[31mUsuário preferiu não digitar esse número.\0... |
p = float(input('Digite o peso da pessoa: (KG)'))
a = float(input('Digite a altura da pessoa: (m)'))
imc = p / (a * a)
if imc < 18.5:
print('Abaixo do peso')
elif imc >= 18.5 and imc < 25:
print('Peso ideal')
elif imc >= 25 and imc < 30:
print('Sobrepeso')
elif imc >= 30 and imc < 40:
print('Obesidade')... |
def removeDuplicates(nums):
if nums == []:
return nums
noDupePtr = 1
store = nums[0]
for item in nums:
if (item != store):
nums[noDupePtr] = item
noDupePtr+=1
store = item
return nums
print(removeDuplicates([1,1,2])) #2
print(removeDuplicates([]))... |
print('Hello, Django girls!')
if 3>2:
print ('To działa!')
if 5>2:
print ('5 jest jednak większe od 2')
else:
print ('5 nie jest większe od 2')
name = 'Sonja'
if name == 'Ola':
print ('Hej Ola!')
elif name == 'Sonja':
print ('Hej Sonja!')
else:
print ('Hej anonimie!')
volume ... |
# 1. Create a Python Program to find Body Mass Index. (Formula. weight/height squared)
# 2. Create a Python Program to find the Simple Interest. (Formula. PRT/100).
#question 1
weight = float(input("Please Input your weight:"))
height = float(input("Please input your height:"))
BMI = weight/(height * height)
print(... |
# if else, elif statements
student_name = input("Input your name:")
student_average_mark = float(input("Please input your average mark:"))
if 0 <= student_average_mark <= 30:
print("You scored an E")
elif 30 < student_average_mark <= 40:
print("You scored a D")
elif 40 < student_average_mark <= 50:
print("Y... |
import sys
from os import system
import time
def main():
print("Welcome to your Todo list app.\nEnter your name to continue.")
cmd = input()
todo = ToDoList(cmd)
while(1):
clear()
show_actions()
cmd = input()
if(cmd=="1"):
print("Enter date in dd/mm/yyyy form... |
# -*- coding: utf-8 -*-
# Projenin Adi : list veri tipi
# Tarih : 13-03-2011
# Yazar : pythontr.org ekibi
# Kontak : pythontr@pythontr.org
# Web : http://pythontr.org
# Python Versiyonu : 2.6-2.7
# Amaci : pythontr.org sitesi uzerinde Python kodlarindan
# olusan bir kod kutuphanesi olusturmak. Yazilan programla... |
i=["a","1","c","b","f","z","b","5","2",1977,"2"]
print i
i.sort()
print i
print type("2")
print i.index("c")
print i.count("2")
print i[3:6]
print i[:5]
print i[5:]
i[2:4]=["sahin","mersin"]
print i
|
class Contact:
def __init__(self,first_name, last_name, phone_number, address):
self.first_name = first_name.lower()
self.last_name = last_name.lower()
self.phone_number = str(phone_number)
self.address = address.lower()
def __repr__(self):
return f"first name :{self.fi... |
import math
def comp_midpoint(f, a, b, n):
sum = 0
h = (b - a) / n
x = h/2
for i in range(n):
sum += f(x) * h
x += h
return sum
print comp_midpoint(lambda x:math.sin(x), 0.0, math.pi / 2, 120)
|
# manipulate the contents of variables.
# lower, upper, swapcase are different string functions.
message="Hello world"
print(message.swapcase()) # change cases.
print(message.lower()) # all letter is in lower case.
print(message.upper()) # all letter is in upper case.
print(message.capitalize()) # capitalize the firs... |
n=eval(input("Enter a number to check if it's even or odd "))
if n%2==0:
print("Even")
else:
print("Odd")
|
class trie_node(object):
def __init__(self, char = '*'):
self.char = char
self.children = []
self.data = None
def add(self,key:str,data):
node = self
for letter in key:
found = False
for child in node.children:
if letter == child.... |
# Author and Email:
# Thomas Lux (tchlux@vt.edu)
#
# Modifications:
# 2018 April -(TL)- Created 'regular_simplex' function.
#
# Given "d" categories that need to be converted into real space,
# generate a regular simplex in (d-1)-dimensional space. (all points
# are equally spaced from each other and the origin)... |
block = """
In our everyday lives we have grown accustomed to computers being a
constant. Computers solve problems that require years for a human in
just seconds. Yet, there is variance in how long it takes a computer
to do the same task multiple times. This variance in performance is a
pervasive problem across compute... |
'''
Author: Devansh Jain (190100044)
Lab 11 2 - Defining Permutation Function
'''
def perm(arr):
'''
List of all Permutations of arr
'''
# If empty then only one permutation - phi
if len(arr) == 0:
return [[]]
# Initialize result
res = []
for n in range(len(arr)):
# ... |
l = [1, 2, 3]
l2 = l
if l is l2:
print("it's the same object")
l2.append(10)
print(l)
|
import numpy as np
import pandas as pd
import nltk
import dialogflow
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
snowball_stemmer = SnowballStemmer('english')
def remove_stopwords(text):
words = text.split()
meaningful_words = [w for w in words if w not in stopwords.words("englis... |
def read_audio_input():
'''This method takes user voice as
input and returns a string as output.
Uses Google audio API to convert audio to text
NOTE: number of request per day is limited to 100.'''
import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
try:
print("Starting up. Please remain ... |
# Write a method that takes an array of numbers in. Your method should
# return the third greatest number in the array. You may assume that
# the array has at least three numbers in it.
#
# Difficulty: medium.
def third_greatest(nums):
first = None
second = None
third = None
for i in range (0, len(nums... |
# Write a method that takes in a string of lowercase letters and
# spaces, producing a new string that capitalizes the first letter of
# each word.
#
# You'll want to use the `split` and `join` methods. Also, the String
# method `upcase`, which converts a string to all upper case will be
# helpful.
#
# Difficulty: medi... |
from bs4 import BeautifulSoup
import pandas as pd
import codecs
html_doc = codecs.open("whatsapptest.htm", 'r', 'utf-8')
soup = BeautifulSoup(html_doc, 'html.parser')
selector = 'span._3NWy8 > *'
found = soup.select(selector)
# Extract data from the found elements
data = [x.text.split(';')[-1].strip() for x in f... |
#!/usr/bin/env python3
"""
defines Neuron class that defines
a single neuron performing binary classification
"""
import numpy as np
class Neuron:
"""
class that represents a single neuron performing binary classification
class constructor:
def __init__(self, nx)
private instance attribute... |
#!/usr/bin/env python3
"""
Defines class Yolo that uses the Yolo v3 algorithm to perform object detection
"""
import tensorflow.keras as K
class Yolo:
"""
Class that uses Yolo v3 algorithm to perform object detection
class constructor:
def __init__(self, model_path, classes_path, class_t, nms_t... |
#!/usr/bin/env python3
"""
Defines a function to create a layer for neural network
"""
import tensorflow as tf
def create_layer(prev, n, activation):
"""
Creates a layer for neural network
parameters:
prev [tensor]: tensor output of the previous layer
n [int]: the number of nodes in the... |
#!/usr/bin/env python3
""" defines function that performs matrix multiplication """
def mat_mul(mat1, mat2):
""" returns new matrix that is the product of two 2D matrices """
mat1_columns = len(mat1[0])
mat2_rows = len(mat2)
if mat1_columns != mat2_rows:
return None
new_matrix = []
for... |
#!/usr/bin/env python3
"""
Defines function that calculates the symmetric P affinities
"""
import numpy as np
P_init = __import__('2-P_init').P_init
HP = __import__('3-entropy').HP
def P_affinities(X, tol=1e-5, perplexity=30.0):
"""
Calculates the symmetric P affinities of a data set
parameters:
... |
#!/usr/bin/env python3
"""
Defines function that calculates the determinant of a matrix
"""
def determinant(matrix):
"""
Calculates the determinant of a matrix
parameters:
matrix [list of lists]:
matrix whose determinant should be calculated
returns:
the determinant of ma... |
#!/usr/bin/env python3
"""
Defines a function that calculates the positional encoding for a transformer
"""
import numpy as np
def get_angle(pos, i, dm):
"""
Calculates the angles for the following formulas for positional encoding:
PE(pos, 2i) = sin(pos / 10000^(2i / dm))
PE(pos, 2i + 1) = cos(pos ... |
#!/usr/bin/env python3
"""
Updates function that trains a model using mini-batch gradient descent
to train using early stopping with Keras library
"""
import tensorflow.keras as K
def train_model(network, data, labels, batch_size, epochs,
validation_data=None, early_stopping=False,
p... |
#!/usr/bin/env python3
""" defines function that concatenates two arrays """
def cat_arrays(arr1, arr2):
""" returns new list that is the concatenation of two arrays """
cat_array = []
for i in arr1:
cat_array.append(i)
for i in arr2:
cat_array.append(i)
return cat_array
|
#!/usr/bin/env python3
"""
Defines a function that performs forward propagation
over a convolutional neural network
"""
import numpy as np
def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)):
"""
Performs forward propagation over a convolutional neural network
parameters:
... |
#!/usr/bin/env python3
"""
Defines the class GRUCell that represents a gated recurrent unit
"""
import numpy as np
class GRUCell:
"""
Represents a gated recurrent unit
class constructor:
def __init__(self, i, h, o)
public instance attributes:
Wz: update gate weights
bz: upd... |
#!/usr/bin/env python3
"""
Defines function that changes the hue of an image
"""
import tensorflow as tf
def change_hue(image, delta):
"""
Changes the hue of an image
parameters:
image [3D td.Tensor]:
contains the image to change
delta [float]:
the amount the hue... |
#!/usr/bin/env python3
"""
Defines a function that builds a dense block
using Keras
"""
import tensorflow.keras as K
def dense_block(X, nb_filters, growth_rate, layers):
"""
Builds a dense block using Keras
parameters:
X: output from the previous layer
nb_filters [int]:
repr... |
#!/usr/bin/env python3
"""
Defines a function that makes a prediction using neural network
using Keras library
"""
import tensorflow.keras as K
def predict(network, data, verbose=False):
"""
Makes a prediction using a neural network
parameters:
network [keras model]: model to make prediction wi... |
#!/usr/bin/env python3
"""
Defines a function that tests a neural network
using Keras library
"""
import tensorflow.keras as K
def test_model(network, data, labels, verbose=True):
"""
Tests a neural network
parameters:
network [keras model]: model to test
data: input data to test the mo... |
#!/usr/bin/env python3
"""
Defines function that updates the learning rate
using inverse time decay in numpy
"""
import numpy as np
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""
Updates the learning rate using inverse time decay in numpy
parameters:
alpha [float]: ori... |
#!/usr/bin/env python3
"""
Defines a function that saves a model's configuration in JSON format
and defines a function that loads a model with specific configuration
using Keras library
"""
import tensorflow.keras as K
def save_config(network, filename):
"""
Saves a model's configuration in JSON format
... |
#!/usr/bin/env python3
""" defines a function that calculates a summation """
def summation_i_squared(n):
"""
calculates summation of i^2 from i=1 to n
utilizes Faulhaber's formula for power of 2:
sum of i^2 from i=1 to n = (n * (n + 1) * (2n + 1)) / 6
or ((n^3)... |
#!/usr/bin/env python3
"""
defines DeepNeuralNetwork class that defines
a deep neural network performing binary classification
"""
import numpy as np
class DeepNeuralNetwork:
"""
class that represents a deep neural network
performing binary classification
class constructor:
def __init__(sel... |
#!/usr/bin/env python3
"""
Defines function that randomly changes the brightness of an image
"""
import tensorflow as tf
def change_brightness(image, max_delta):
"""
Randomly changes the brightness of an image
parameters:
image [3D td.Tensor]:
contains the image to change
ma... |
#!/usr/bin/env python3
""" defines function that adds two matrices """
def matrix_shape(matrix):
""" returns list of integers representing dimensions of given matrix """
matrix_shape = []
while type(matrix) is list:
matrix_shape.append(len(matrix))
matrix = matrix[0]
return matrix_sha... |
def get_fibonacci_last_digit_sq_sum(n):
if n <= 1:
return n
previous = 0
current = 1
z = []
for _ in range(n + 1):
z.append(previous**2)
previous, current = current, (previous + current)%10
if previous == 0 and current == 1:
break
return ((n//len(z))*(... |
import random
n = [0,1,2,3,4,5]
e = int(input('digite um número entre 0 e 5: '))
r = random.choice(n)
print('O numero era {}'.format(r))
if e == r:
print('Você acertou!')
else:
print('Tente novamente.')
|
nome = str(input('Digite seu nome completo: ')).strip()
maiusculo = nome.upper()
print('Seu nome em maiúsculo é: {}'.format(maiusculo))
minusculo = nome.lower()
print('Seu nome minúsculo é: {}'.format(minusculo))
print('Seu nome tem {} letras'.format(len(nome) - nome.count(' ')))
#p = int(nome.find(' '))
#print(... |
import sys
users = [
(0,"Bob", "password"),
(1,"Rolf", "bob123"),
(2,"Jose", "longp4ssword"),
(3,"username", "1234"),
]
user_map = {user[1] : user for user in users}
print(user_map)
print(user_map["Jose"])
user_input = sys.argv[1]
passwd_input = sys.argv[2]
#destructuring Tuple
_,username,passwo... |
import sys
import timeit
# 실행 속도에 중점을 두고 만들었다.
# start_time = timeit.default_timer()
sys.stdin = open('sort_input.txt')
def merge_sort(li):
half = len(li)//2
if half:
lft = merge_sort(li[:half])
rgt = merge_sort(li[half:])
li=[]
while lft and rgt:
if lft[0] < rgt[0]... |
# -*- coding: utf-8 -*-
def findMatch (itemsList, userInput):
isValid = False
counter = 0
possibilities = []
while (isValid == False and counter < len(itemsList)):
item = itemsList[counter]
if userInput == item :
isValid = True
return counter
... |
def remove_digit(string):
st_res = ""
for ch in string:
if not ch.isdigit():
st_res +=ch
return st_res
def remove_let(string):
st_res = ""
for ch in string:
if not ch.isalpha():
st_res +=ch
return st_res
def parse_matrix(file):
matri... |
largura = int(input("Digite a largura:"))
altura = int(input("Digite a altura:"))
guardaLargura = largura
guardaAltura = altura
while altura > 0:
larguraLimite = largura
while larguraLimite > 0:
if larguraLimite == 1 or larguraLimite == guardaLargura:
print("#", end="")
elif... |
n = int(input("Digite um numero positivo inteiro e descubra se é primo:"))
def primo(numero):
i, cont = 1, 0
while i <= numero:
if (numero % i == 0):
cont += 1
i += 1
if cont == 2:
print('primo')
else:
print('não primo')
while n >= 0:
... |
def fatorial(num):
fat = 1
while num > 1:
fat *= num
num -= 1
return fat
def numBionominal(n, k):
return fatorial(n) // (fatorial(k) * fatorial(n-k))
def testaBinomial():
if numBionominal(5,2) == 10:
print("Ta funcionando para 5,2")
else:
print("N... |
"""
@author:YJM
@Date:20160408
"""
def FindingLeapYear():
print "DO you want Leapyear, Please input year"
year=raw_input("Input the year:")
year=int(year)
if(year%4 == 0) and (year % 100 !=0 or year % 400==0):
res="LeapYear"
else:
res="NormalYear"
print res
... |
"""
Vizcaino Lopez Fernando
13/03/2020
15/03/2020
reference https://www.geeksforgeeks.org/python-program-for-dynamic-programming-set-10-0-1-knapsack-problem/
"""
def knapSack(W , wt , val , n):
if n == 0 or W == 0 :
return 0
if (wt[n-1] > W):
return knapSack(W,wt,val,n-1)
else:
... |
import numpy as np
import pandas as pd
df = pd.read_csv("foo.csv")
print df
df2 = pd.read_csv("foo.csv", index_col=0)
print df2
print df2.ix['tom']
print df2['age']
print df2['age'].values
print df2['age']['tom']
|
import re #正则表达式操作库
#match与serch 匹配
# mach()从字符串起始位置开始匹配,匹配成功返回匹配对象,失败则返回None
# search()不要求从起始位置开始匹配
print(re.match('book','books'))
print(re.search('book','sbooks'))
#findall 在爬虫中使用最频繁,用于查找字符串中所有符合正则表达式的字符串,返回一个列表
python = 'python2 python3 are all python'
print(re.findall('python',python))
... |
import random
class Encryptor(object):
def __init__(self):
self.substitution = {}
self.reverse_substitution = {}
self.generate_substitution()
def generate_substitution(self):
russian_alpha_lower = [chr(x) for x in range(ord('а'), ord('а') + 32)] + ['ё', ]
russian_alpha... |
"""
Simple functions, Chapter 2
"""
def square(x):
"""
:param x:
:return: square of imput number
"""
return x**2
#####
def evalQuadratic(a, b, c, x):
'''
a, b, c: numerical values for the coefficients of a quadratic equation
x: numerical value at which to evaluate the quadratic.... |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
given_num = x
num = 0
while (x > 0):
rem = x % 10
x = x/10
num = num*10 +rem
if (given_num == num):
return True
... |
n = int(input("Введите первое число: "))
m = int(input("Введите второе число: "))
s = n + m
print("Сумма чисел: " + str(s))
n = int(input("Введите количество секунд: "))
h = n // 3600
a = n % 3600
m = a // 60
s = a % 60
print(f"{h} часов, {m} минут, {s} секунд")
n = input("Введите произвольное число: ... |
'''
Given six real numbers – a, b, c, d, e, f. Solve the following system of linear equations:
a*x + b*y = e
c*x + d*y = f
Output format
If the system has no solution, then the program should print a single number 0.
If the system has infinitely many solutions, each of which looks like y=kx+b, then the program should p... |
#!/usr/bin/python
from audio_file import AudioFile
import argparse
import os
import shutil
parser = argparse.ArgumentParser(description='Audio file information printer.')
parser.add_argument('filepath', metavar='filepath', type=str, help='prints audio information from file')
parser.add_argument('--overwrite', action=... |
"""Useful miscellaneous functions."""
from typing import Callable
def get_linear_anneal_func(
start_value: float, end_value: float, start_step: int, end_step: int
) -> Callable:
"""Create a linear annealing function.
Parameters
----------
start_value : float
Initial value for linear annea... |
palavra = 'paralelepipedo'
for letra in palavra:
print(letra, end='\n')
print('Fim')
# -------------------------------------------------------------------------------------------------
aprovados = ['Jefferson', 'Derico', 'Dirlayne', 'Denise', 'Sergio', 'Leiri', 'Lilian', 'Pedro', 'Giuliano', 'Felipe']
for nome i... |
# a = 10
# b = 5.2
# print(a + b)
# ------------------------------- #
a = 'Agora sou uma string'
print(a)
|
nota = 10
if nota == 10:
print('Excelente, você foi aprovado com a nota máxima!!! ')
elif nota >= 7:
print('Parabéns, você foi aprovado!!! ')
elif nota >= 6:
print('Faltou muito pouco para sua aprovação. Você ficou de recuperação!!! ')
else:
print('Você está reprovado!!')
|
#!/usr/bin/env python
# coding: utf-8
# # Chapter 3: Sequence objects
# * Sequences are essentially strings of letters like AGTACACTGGT, which seems very natural since this is the most common way that sequences are seen in biological le formats
# * The most important dierence between Seq objects and standard Python... |
import numpy as np
### Functions for you to fill in ###
def polynomial_kernel(X, Y, c, p):
"""
Compute the polynomial kernel between two matrices X and Y::
K(x, y) = (<x, y> + c)^p
for each pair of rows x in X and y in Y.
Args:
X - (n, d) NumPy array (n datapoint... |
#!/usr/bin/python
import sys
import csv
csv_reader = csv.reader(sys.stdin)
for s in csv_reader:
if s[16] == 'NY':
print("NY\t1")
else:
print("Other\t1")
|
number = int(input("Please enter a number: "))
sum_of_odd_nums = 0
sum_of_even_nums = 0
even_num_counter = 0
for i in range(1, number+1):
if i % 2 != 0:
sum_of_odd_nums += i
else:
sum_of_even_nums += i
even_num_counter += 1
print("sum of odd numbers: ", sum_of_odd_nums)
print(... |
# asdfasdfasdfasdfasdfasdfasdf
# input de usuário
nome = input("Digite seu nome: ") # input de usuário
idade = int(input(f"Qual a sua idade {nome}?"))
nascimento = 2020 - idade
print(f"{nome} você nasceu em {nascimento}")
num1 = int(input("Digite um numero: "))
num2 = int(input("Digite outro numero: "))
resultado =... |
from __future__ import print_function
''' Introduction '''
# A line of text is called a string because it is similar to a string of characters
# connected together.
''' ''' ''' ''' ''' '''
''' Procedure '''
#5 The data type long can be used to represent 6 million because it is an integer
# with a very l... |
while True:
nums = input().split(' ')
if (nums.count('0') == 2):
break
nums_sorted = sorted(nums)
print(' '.join(nums_sorted))
|
"""The police department of your city has just started its journey. Initially,
they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police
force can investigate only one crime during his/her lifetime. If there is no
police ... |
"""«One dragon. Two dragon. Three dragon», — the princess was counting.
She had trouble falling asleep, and she got bored of counting lambs when she
was nine. However, just counting dragons was boring as well, so she entertained
herself at best she could. Tonight she imagined that all dragons were here to
steal her... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.