text stringlengths 37 1.41M |
|---|
a=input("the interger number is:")
b=int(a)
c=b*b
print('the square value of interger is:',c)
|
def add(a,b):
c=a+b
return c
def mult(a,b):
c=a*b
return c
def addition (a,b):
c=a-b
return c
def div (a,b):
c=a/b
return c |
import turtle
def read_coords(file):
henrydraper = []
coords = []
magnitudes = []
names = {}
# Opens file and creates lists for HD number, coordinates, and magnitudes
data = open(file, 'r')
for line in data:
data_list = line.split(' ', maxsplit=6)
henrydraper ... |
from tkinter import *
window=Tk()
def fun1():
grams=float(e1_value.get())*1000
pounds=float(e1_value.get())*2.20462
ounces=float(e1_value.get())*35.274
t1.insert(END,grams)
t2.insert(END,pounds)
t3.insert(END,ounces)
b1=Label(window,text="kg")
b1.grid(row=0,column=0)
b2=But... |
#%%
import random
from math import *
import matplotlib.pyplot as plt
# 구 설정
R = int(input("구의 반지름 : "))
nExp = int(input("입자의 갯수 : "))
x_list, y_list, z_list = [], [], []
for i in range(nExp):
r = random.uniform(0, R)
r = r ** (1 / 2)
theta = random.uniform(0, 180)
phi = random.uniform(0, 360)
x = ... |
"""
Dada a seqüência, calcular o cos:
"""
cos = fatorial = n = 1.0
fator = -1.0
while n % 2 != 0:
x = float(input("Digite o ângulo em radianos: "))
n = int(input("Digite o N: "))
for i in range(2,n+1):
fatorial *= i
if i % 2 == 0:
cos += fator*((x**i) / fatorial)
fator *= -1
print(cos... |
"""
Dada uma seqüência de letras terminada pelo caracter Z. Imprima a quantidade
de vogais lidas.
"""
status = True
sequencia = vogais = 0
while status:
letra = input("Digite uma letra: ")
if letra == "z":
status = False
elif letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra ==... |
"""
Dados dois números inteiros positivos x e y, fazer a divisão de x por y sem usar
o operador de divisão.
"""
x = int(input("Digite um número inteiro para x: "))
y = int(input("Digite um número inteiro para y: "))
x_temporario = x
i = 0
while x_temporario >= y:
i += 1
x_temporario -= y
print("O quociente ... |
"""
Dada uma lista de números reais terminada pelo número 99.99, imprima cada
número lido. No final, imprima a média aritmética de todos os números da lista
(É claro que o nº 99.99 não faz parte da média).
"""
lista = n = cont = 0
while n != 99.99:
n = float(input("Digite um elemento para lista (caso queira parar... |
"""
Dado um número inteiro N, divida-o por 2 (sucessivamente) enquanto o resultado
for maior que 0. No final, imprima o nº de divisões necessárias para zerar o
quociente.
"""
n = int(input("Digite um número inteiro: "))
i = 0
while n != 0:
n = n // 2
i += 1
print("O número de divisões necessário para zerar o... |
import traceback
print('test')
a = input()
if (a == 'e'):
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorinfo.txt', 'w')
errorFile.write('error on line')
errorFile.close()
print('The traceback info was written to errorinfo.txt')
|
# Calculator
# Creating function for Addition.
def Add(x,y):
return x + y
# Creating function for Subtraction.
def Sub(x,y):
return x - y
# Creating function for Multiplication.
def Mult(x,y):
return x * y
# Creating function for Division.
def Div(x,y):
return x / y
print ("Select... |
#!/usr/bin/env python
# coding=utf-8
class A(object):
"""docstring for A."""
def __init__(self, cantidad):
self.cantidad = cantidad
def porciento(self,p):
return self.cantidad * (p/100)
def main():
a = A(100)
print(a.cantidad)
print(a.porciento(85))
if __name__ == '__main__'... |
print('3 x 1 = {}'.format(3*1))
print('3 x 2 = ', 3*2)
print('3 x 3 = ', 3*3)
print('3 x 8 = ', 3*8)
print('3 x 9 = ', 3*9)
print('3 x 10 = ', 3*10)
|
import speech_recognition as sr
import win32api
def recognize_speech_from_mic(recognizer, microphone):
"""Transcribe speech from recorded from `microphone`.
Returns a dictionary with three keys:
"success": a boolean indicating whether or not the API request was
successful
"error": `... |
# -*- coding: utf-8 -*-
"""
THE PROBLEM:
The purpose of the project is to create a python program that could rate a comment or review of a restaurant
in the number of stars. It could be between 1-5 depending upon the performance of the restaurant. In this
case the program will be able to classify the comment give... |
def showMenu():
print "A: Convert celsius to fahrenheit"
print "B: Convert fahrenheit to celsius"
print "X: Exit"
def celsiusToFahrenheit(celsiusTemperature):
"This function converts Celsius temps to Fahrenheit temps"
fahrenheit = celsiusTemperature * (9.0 / 5.0) + 32.0
return fahrenhei... |
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
print(num1 + num2)
# numm1 = 5
# num2 = 4
# nu1 + num2 = 5 + 4 = 9
|
'''
Надо написать функцию которая возвращает N-мерный массив с ширинами заданными в аргументе списком из N элементов:
n_arr([2,2])
>> [[“”,“”],[“”,“”]]
n_arr([2,2,2])
>> [[[“”,“”],[“”,“”]], [[“”,“”],[“”,“”]]]
'''
def array(lst):
if len(lst) == 1:
return ['' for i in range(0, lst[0])]
sp = [array(lst[1... |
import sys
import csv as csv
from bs4 import BeautifulSoup
import os
def main():
stop_words = get_common_english_words('common-english-words.csv')
# if no filenames were given as input it would try to run on the default 'train.csv' and 'test.csv'
if len(sys.argv)==1:
pre_process_csv('train.csv',st... |
#Crie um programa que leia um número inteiro e mostre na tela se ele é par ou Ímpar
num = int(input("Digite um número inteiro: "))
if num%2 == 0:
print("O número {} é par".format(num))
else:
print("O número {} é ímpar".format(num)) |
#Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz
num = int(input('Digite um número: '))
print("O dobro do número {0} é {1}, o triplo é {2} e a raiz é {3}".format(num, (num * 2), (num * 3), (num ** (1 / 2)))) |
#O mesmo professor do desafio anterior quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada
from random import shuffle
var1 = input("Nome do primeiro alunos: ")
var2 = input("Nome do segundo alunos: ")
var3 = input("Nome do terceiro... |
#Faça um progrmama que leia a largura e a altura de uma parede em metros, calucele a sua área e aquantidade de tinta necessãria para pintá-la, sabendo que casa litro de tinta pinta uma área de 2m².
import math
width = float(input('Type the wall width: '))
height = float(input('Type the wall height: '))
size = width*h... |
#Desenvolva um programa que pergunte a distância de uma viagem em km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de até 200km e R$0,45 para viagens mais longas
distancia = int(input("Digite a distância em km da viagem: "))
if distancia <= 200:
print("O preço da passagem é R${}".format(distan... |
cars = ['bmw', 'audi', 'toyota', 'subaru']
# print("Here is the orginal list: ")
# print(cars)
#
# print("\nHere is the sorted list: ")
# print(sorted(cars))
#
# print("\nHere is the orginal list again: ")
# print(cars)
cars.reverse()
# print(cars)
l = len(cars)
# print(l)
cars = ['bmw', 'audi', 'toyota', 'subaru... |
# Задача 8. Вариант 23.
# Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4)
# так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право на
# подсказку в том случае, если у него нет никаких предположений. Разработайте
# систему начисления очков, по которой бы игроки, отгадавшие... |
def hello(s):
print("Hello " + s)
def sestevanje(a, b):
rezultat = 0
rezultat += a
rezultat += a
return rezultat
hello("student")
print(sestevanje(1, 3))
def switch(a, b)
return (b, a)
|
import tkinter as tk
window = tk.Tk()
label = tk.Label(text = 'Hello, Tkinter', foreground = 'white', background = 'blue', width = 10, height = 10) # Can also use hexidecimal color codes
label.pack()
button = tk.Button(text = 'Click Me', width = 25, height = 5, fg = 'black', bg = 'blue')
button.pack()
entry = tk.En... |
# LIST STRING METHODS
def get_all_letters(string):
return list(string)
print(get_all_letters('Radagast'))
print('\n')
#======================================================================================================================
def get_all_words(string):
return string.split()
print(get_all_words(... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def max_index(arr):
... |
import math
class Solution:
def judgeSquareSum(self, c: int) -> bool:
lo = 0
hi = int(math.sqrt(c))
while lo <= hi:
summ = lo * lo + hi * hi
if summ > c:
hi -= 1
elif summ < c:
lo += 1
else:
re... |
from turtle import*
shape("turtle")
color("blue")
speed(0)
for i in range(15):
forward(20)
left(90)
forward(20)
left(90)
forward(20)
left(90)
forward(20)
right(90)
forward(20)
right(90)
forward(20)
right(90)
forward(20)
mainloop() |
a = int(input("Xin hãy nhập n từ bàn phím"))
b = int(input("Xin hãy nhập m từ bàn phím"))
while (a >= b):
print(a)
a = a - 1
|
a=12
b=3
print(a+b) #15
print(a-b) #9
print(a*b) #36
print(a/b) #4.0
print(a//b) # 4 integer division, rounded down towards minus infinity
print(a%b) #0 modulo: the remainder after integer division
print()
print(a + b /3 - 4 *12)
print(a+(b/3)-(4*12))
print((((a+b)/3)-4)*12)
print(((a+b)/3 -4)*12)
c=a+b
... |
import random
answer = random.randint(1,10)
print("please enter the number between 1 and 10: ")
guess =0
guess = int(input())
while guess!=answer and guess != 0:
if(guess>answer):
print("please guess lower")
else:
print("please guess higher")
guess = int(input())
if guess == 0:
print... |
numero = int(input("Dame un numero mayor a 5: "))
if numero >= 5:
print("Bien hecho!") #la sangria indica el bloque
else:
print("No sabes contar jeje")
#cuando se quita la sangria se sale del bloque
input("\nPresiona cualquier tecla para continuar")
|
flotante = 1.5
entero = 25
print("Tu entero es:", entero)
print("Tu flotante es:", flotante)
enteroDos = int(flotante)
flotanteDos = float(entero)
print("Tu entero es:", enteroDos)
print("Tu fltante es:", flotanteDos)
input("\n Presiona cualquier tecla para continuar")
|
iNumero = 15
sCadena = "hola"
fNumero = 1.56
bEstado = True
"""type(iNumero) #Esto nos va a decir enla cosola qué tipo de dato es la variable"""
numero = 234
numeroL = 37564263454265774
print("El numero corto es:", numero, "Su tipo es:", type(numero))
print("\n")
print("El numero largo es:", numeroL, "Su... |
#7/15/2013
#Find the largest palindrome made from the product of two 3-digit numbers.
three_digits = range( 100, 999 )
three_digit_mult = []
while len(three_digits) > 1:
mult_digit = three_digits[0]
three_digits.remove(mult_digit)
for left_digit in three_digits:
three_digit_mult.append(mult_digit ... |
#!/usr/bin/python
# Copyright (C) 1015
# Author: Vinod NK
"""
Script to copy images from origin to target path.
When an image is created in target path, the creation date of this image is
the creation date of the origin directory. This is because if exists a new folder
in the origin path, all photos has highest pr... |
# Taking input and displaying it as a list and tuple
a = input("Enter the numbers")
print(a)
a = a.split(",")
b = []
for i in a:
b.append(int(i))
print(b)
c = tuple(b)
print(c) |
# coding: utf-8
# In[ ]:
def getMax(data):
""" Find the maximum number of steps in the data and the date it was achieved.
Parameters:
data: Pandas DataFrame containing Apple Health data imported from a
.csv file.
Return:
The row of values for when the ma... |
import numpy as np
import utils
import velocity
import curvature
import angle
import friction as friction_module
import normal_force as normal_force_module
"""
Calculate the absolute value of the ratio between friction and normal force in each of the 1400 steps
|Friksjon / Normalkraft|
"""
def calculate():
"""... |
# Read an integer:
a = input("Pls enter the string ")
try:
result = a.index('f')
result1 = a.rindex('f')
if result == result1:
print(result)
elif result != result1:
print(result, result1)
except ValueError:
print("")
# chudo code
# s = input()
# if s.count('f') == 1:
# print(s.find('f'))... |
import random
class dice:
def __init__(self, top = 6):
self.top = top
self.score = 1
def roll(self):
self.score = random.randint(1,self.top)
def __repr__(self):
return(str(self.score))
dices = [dice(), dice(4), dice(12)]
playing = True
while playing:
p... |
import unittest # Importing the unittest module
from accounts import Account # Importing the user class
class TestAccounts(unittest.TestCase):
'''
Test class that defines test cases for the accounts class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
... |
#build list of primes from 2 up to and including integer x and compute sum
def isPrime(x,prime_array):
n=0
if x%2==0:
return False
for j in str(x):
n+=int(j)
if n%3==0:
return False
else:
for k in prime_array:
if x%k==0:
return False
... |
import numpy as np
import pandas as pd
class Node:
def __init__(self, value, children, branch_value=None):
"""
:param value: split attribute or, if leaf node, class label
:param children: array of child nodes
:param branch_value: value of branch coming from parent node
"""
... |
#Common Elements in Two Sorted Arrays
#Write a function that returns the common elements (as an array) between two sorted arrays of integers (ascending order).
#Example: The common elements between [1, 3, 4, 6, 7, 9] and [1, 2, 4, 5, 9, 10] are [1, 4, 9].
#O(max(n,m)) where n is the number of items of the first array a... |
#import OS and CSV
import os
import csv
from collections import Counter
#import the csv and show the csv
with open('Resources/election_data.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# print(csvreader)
csv_header = next(csvreader)
# print(f"pybank: {csv_header}... |
"""Reference: https://docs.python-guide.org/writing/logging/
"""
import logging
def get_logger(name: str, level: int = logging.DEBUG):
"""Sets up a logger.
Parameters
----------
name: str
The module name
level: int, optional
The logging level, by default logging.DEBUG
"""
... |
# Написать функцию которая принимает на вход число от 1 до 100. Если число равно 13,
# функция поднимает исключительную ситуации ValueError иначе возвращает введенное число,
# возведенное в квадрат.
# Далее написать основной код программы. Пользователь вводит число. Введенное число передаем
# параметром в написанную фу... |
# Дан список, заполненный произвольными числами. Получить список из элементов исходного, удовлетворяющих следующим условиям:
# Элемент кратен 3,
# Элемент положительный,
# Элемент не кратен 4.
#
# Примечание: Список с целыми числами создайте вручную в начале файла.
# Не забудьте включить туда отрицательные числа. 10-20... |
# Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(num1, num2, num3):
sum1 = num1 + num2
sum2 = num2 + num3
sum3 = num1 + num3
result = max(sum1, sum2, sum3)
print(result)
my_func(19,14,29) |
# Игра угадай число
import random
def game():
# Компьютер загадывает число
comp_num = random.randint(1, 100)
# print(comp_num)
# Выбираем количество пользователей
num_players = 0
while num_players < 1 or num_players > 4:
num_players = int(input("Введите количество игроков: "))
# З... |
'''Helper functions for machine learning.'''
import numpy as np
def angle_to_cos_sin(angle):
'''Convert an angle in radian to its cos and sin.
This useful to preserve the topology of periodic features.
'''
return [np.cos(angle), np.sin(angle)]
def cos_sin_to_angle(cos, sin):
'''Get an angle from its cos a... |
import numpy as np
from PIL import Image
class GreyImage:
""" Класс, преобразующий картинку в черно-белый пиксель-арт
Тест значения градации изображения
>>> res = GreyImage(np.array(Image.open('picture.jpg')), 10, 100)
>>> res.grad
2
Тест размера блока
... |
from math import exp
from functions import Differentiable
class Sigmoid(Differentiable):
"""The Sigmoid activation function."""
@staticmethod
def f(x):
return 1.0 / (1.0 + exp(-x))
@staticmethod
def df(x):
return Sigmoid.f(x) * (1 - Sigmoid.f(x))
class ReLU(Differentiable):
"""... |
while(1):
num = input()
if(num == '0 0'):
break
num = num.split()
result = int(num[0])+ int(num[1])
print(result) |
class Warrior:
health = 50
attack = 5
is_alive = True
class Knight():
health = 50
attack = 7
is_alive = True
def fight(unit_1, unit_2):
while True :
unit_2.health -= unit_1.attack
print(unit_2.health)
if(unit_2.health <= 0):
unit_2.is_... |
import math
import random
class Point :
def __init__(self, X, Y):
self.X = X
self.Y = Y
def distanceFrom(self, B):
return math.sqrt((self.X - B.X)**2 + (self.Y - B.Y)**2)
def distanceFromOrigin(self):
O = Point(0, 0)
return self.distanceFrom(O)
def display(sel... |
"""
VKİ 18 ile < 25 aralığındaysa normal,
VKİ 25 ile <30 aralığındaysa kilolu,
VKİ 30 ve daha yüksekse obez,
VKİ 35 ve daha fazlaysa ciddi obez olarak kabul edilir.
VKİ’ni hesaplayarak kişinin durumunu yazdırınız
(VKİ=ağırlık/(boy*boy), boymetre cinsinden verilmeli)
try:
hata oluşabilecek satıralr
except:
hata... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 15:05:42 2018
Chromosomes are a list of genes, in this case each element in the list represents a morphologial operator:
0: No operator
1: Erosion
2: Dilation (opposite of erosion)
3: Opening (erosion followed by dilation)
4: Closing (dilation ... |
from tetrimino import *
rows, colns = 20, 10
board = create_board(rows, colns)
tet = O
tet["pos"] = (18, 0)
place(tet, board)
tet["pos"] = (8, 0)
place(tet, board)
tet["pos"] = (0, 8)
place(tet, board)
print(board)
move_left(tet, board)
place(tet, board)
print(board)
tet["pos"] = (0, 0)
place(tet, board)
print(boar... |
x=input("enter number to check")
for i in range(2,x):
if x%i==0:
print"it is not a prime number"
break
else:
print"its a prime number"
break |
# class Users:
# name="Sunday"
# location="Okeho"
# def __init__(self):
# self.name="Sunday"
# self.age=12
# self.address="32 Asiwaju Omidiran Way, Orita-Sabo"
# person = Users()
# print(person.location)
# print(person.name)
class Users:
def __in... |
'''
- Leia a idade do usuário e classifique-o em:
- Criança – 0 a 12 anos
- Adolescente – 13 a 17 anos
- Adulto – acima de 18 anos
-Se o usuário digitar um número negativo, mostrar a mensagem que a idade é inválida
2- Calcular a média de um aluno que cursou a disciplina de Programação I, a
partir da leitura das notas... |
money=int(input("Beloppet som ska betalas : "))
if 500<=money :
print(f"Det är {int(money/500)} 500 lappar, {int((money%500)/100)} 100 lappar och {money%100} kronor")
elif money>=100 :
print(f"Det är {int(money/100)} 100 lappar, och {money%100} kronor")
else :
print(f"Det är {money} kronor") |
country = input("Mata in landet där du bor : ")
if country == "Sverige" or country == "Danmark" or country == "Norge" :
print ("Du bor i Skandinavien")
else :
print("Du bor inte i Skandinavien")
|
#!/usr/bin/python3.8
import numpy as np
import pandas as pd
class Labelling:
@staticmethod
def _compute_threshold(stable_to_crypto, fees):
"""
compute threshold for going stable to crypto or crypto to stable given fees.
Parameters
----------
stable_to_crypto : bo... |
from program2_2 import Dmatrix
ROW = 3 # 行の要素数
COLUMN = 4 # 列の要素数
def main():
global ROW, COLUMN
a = Dmatrix(1, ROW, 1, COLUMN) # 行列 a[1...ROW][1...COLUMN]
b = Dmatrix(1, ROW, 1, COLUMN) # 行列 b[1...ROW][1...COLUMN]
# 行列の定義
for i in range(1, ROW+1):
for j in range(1, COLUMN+1):
... |
def main():
n = 100
print(f"2.0/(x*x) を [1,2] で積分します. 分割数は{n}です")
print("結果は{:20.15f} です".format(trapezoidal(1.0, 2.0, n, func1)))
print(f"4.0/(1+x*x) を [0,1] で積分します. 分割数は{n}です")
print("結果は{:20.15f} です".format(trapezoidal(0.0, 1.0, n, func2)))
# 台形公式
def trapezoidal(a: float, b: float, n: int, f... |
import itertools
import string
import typing
# Chunk iterators
def chunk(iterable: typing.Iterable[typing.Any], chunk_size: int) -> typing.Iterator[typing.List[typing.Any]]:
'''Splits the given iterable into chunks of a fixed size'''
iterator = iter(iterable)
while True:
chunk_iterator = itertools.... |
from collections import defaultdict
class CastleKilmereMember:
"""
Creates a member of the Castle Kilmere School of Magic
"""
def __init__(self, name: str, birthyear: int, sex: str):
self._name = name
self.birthyear = birthyear
self.sex = sex
self._traits = defaultdict(... |
import numpy as np
#arr = np.array([1,2,3,])
#print(arr)
#arr = np.array([[1,2,3],[4,5,6]])
#print(arr)
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr) |
#https://www.geeksforgeeks.org/python-programming-examples/#simple
#max of numbers
num1=input("enter num1")
num2=input("enter num2")
if num1 > num2:
print("{0} is bigger number than {1}".format(num1,num2))
elif num1 < num2:
print("{0} is bigger number than {1}".format(num2, num1))
else:
print("{0} is equ... |
# NameComics.py
""" This Python Script Will re-name Comic files """
# Import Statement
import os
import re
def main():
"""
Main Function, which will re-name comics to desired format.
### Comic Name.pdf
"""
directory = "/Users/ramanmehat/Desktop/Re-name Comics"
remove_unwanted_stings(director... |
def solution(phoneBook):
phoneBook = sorted(phoneBook)
#리스트 for을 하면 어차피 다은꺼 가져오니깐 zip으로 묶음
for p1, p2 in zip(phoneBook, phoneBook[1:]):
if p2.startswith(p1):
return False
return True |
# def solution(priorities, location):
# answer = list()
# # 1. 가장 큰 위치 찾기 (index)
# # 2. 그 전까지의 위치를 위로 땡기기
# _get = priorities[location]
# big_index = priorities.index(max(priorities))
# answer = priorities[big_index:] + priorities[:big_index]
# if big_index <= location:
# b=answer.i... |
#이거 안된다고 합니다... 왜 안됐는지는 잘 모르겠습니다 ㅠㅠ
def solution(numbers, hand):
#누른 것 위치 저장 필요
left_save_current = 10
right_save_current = 12
answer = ''
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
]
for i in numbers:
if i in (1, 4, 7, '*'):
ans... |
class No:
def __init__(self, valor):
self.dado = valor
self.proximo = None
self.anterior = None
def __str__(self):
if self.proximo is None and self.anterior is None:
return f"|\t Anterior: {self.anterior} \t|\t Nó: {self.dado} \t|\t Próximo: {self.proximo} \t| "
... |
def Indent( elem, level=0, indent=' ' ):
"""
Function used to 'prettify' output xml from cElementTree's tree.getroot()
method into lines so it's easily read.
"""
i = "\n" + level * indent
if len( elem ):
if not elem.text or not elem.text.strip():
elem.text = i + indent
... |
class WrappedFunction( object ):
def __init__( self, fn=None ):
self.fns = []
# Add base function
if fn is not None:
self.Add( fn )
def __call__( self, *args, **kwargs ):
return self.fn( *args, **kwargs )
def Add( self, fn ):
""... |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
total = 0
for num in xrange(1000):
if num % 3 == 0 or num % 5 == 0:
total += num
print total
# >>> 233168
|
students=[20,10,35]
total=sum(students)
print("Total marks obtained",total)
length=len(students)
print("Length is:",length)
mean=total/length
print("Mean is:",mean) |
def weather(temp):
if temp <= 10:
result = "COLD"
elif temp > 10 and temp <= 25:
result = "WARM"
else:
result = "HOT"
return result
user_input = float(input("Please enter a temperature: "))
print("The weather is",weather(user_input)) |
# Requirements: Instead of a Fibonacci sequence, we'll make a TRI-bonacci sequence
#
# Your function will be given a signature array of 3 numbers and a positive integer n
# it must return an array of size n, where the n-th number is the sum of the previous 3
#
# For n < 3, we have our base cases, so if n == 1, we retu... |
from math import sqrt
# We'll recall that anytime we're working with number methods we
# should utilize Python's large math library. In this case, the only one that
# comes to mind is the sqrt() function
def findNextSquare(sq):
# First we check the square root of the given number against mod 1
# since this wi... |
#!/usr/bin/python
#-*-coding:utf8-*-
# a = 2
# def fun(x,y=100):
# a = 10
# print id(a)
# return x*y*a
# print fun(3,30)
# print a,id(a)
# x = "my is string"
# def fun():
# global y
# y = 100
# global x
# x = 10
# # fun()
# print x,id(x)
# # print y,id(y)
# try:
# print y,id(y)
# except NameError:
# 'a... |
from typing import List
def generate_10_numbers_from_0_until_100() -> List[int]:
import random
List = [random.randint(0, 99) for k in range(10)]
return List
def print_list(numbers: List[int]):
for i in range(10):
print(numbers[i])
def sort_in_ascending_order(numbers: List[int]) -> List[int... |
class Node(object):
"""docstring for Node"""
__slots__ = ('data', 'next')
def __init__(self, data, next):
self.data = data
self.next = next
class Stack(object):
"""docstring for Stack"""
def __init__(self):
self.head = Node(None, None) # sentinel node
... |
#!/usr/bin/python
#Javier Alegria
ProteinSeq = raw_input("Enter a protein sequence: ")#this function will allow to input data
ProteinSeq = ProteinSeq.upper()#becomes everything in uppercase letters so that the program can still read it (the opposite would be lower()"
AminoDict = {#this is a dictionary of the aminoa... |
# node:
# - metadata: [int]
# - children: [nodes]
data = open('input_08.txt').read()
from collections import namedtuple
TreeNode = namedtuple('TreeNode', 'children, metadata')
def fetch_node(numbers):
n_children = numbers.pop()
n_metadata = numbers.pop()
child_nodes = [fetch_node(numbers) for _ in ran... |
def part_1(print_result: bool = True) -> int:
pk_card, pk_door = 1614360, 7734663
size = 20201227
looked_pks = pk_card, pk_door
for loop_size in range(size):
estimated_pk = pow(7, loop_size, size)
if estimated_pk not in looked_pks:
continue
if estimated_pk == pk_card... |
from dataclasses import dataclass
from typing import Optional
@dataclass
class Marble:
value: int
next_cw: Optional['Marble']
next_ccw: Optional['Marble']
class MarbleCircle:
def __init__(self):
self.current = None
self.first = None
def next_cw(self):
return self.curr... |
import math
from fractions import Fraction
from common import read_data
def parse_spacemap(map_data):
spacemap = {}
for y, line in enumerate(map_data):
for x, char in enumerate(line.strip()):
spacemap[(x, y)] = char == '#'
return spacemap
################
# ## PART 1 ## #
##########... |
# This example demonstrates:
# - creation of the Model object
# - creation of training instances of features
# - training a model
# - creation of testing instances of features
# - testing the tesiing instances against the trained model
# - accessing the predictions
from wekapy import *
# CREATE NEW MODEL... |
def choice_sort(A: list):
for i in range(len(A)):
for j in range(i + 1, len(A)):
if (A[j] < A[i]):
A[i], A[j] = A[j], A[i]
def test_choice_sort():
A = [4, 2, 5, 1, 3, 0, 5, 3, -1, -2, 17, 10]
print(A)
choice_sort(A)
print(A)
test_choice_sort() |
def reverse_list(List):
""" Reverse list List
LoL :D
"""
lenght = len(List)
for i in range(lenght // 2):
List[i], List[lenght - 1 - i] = List[lenght - 1 - i], List[i]
def test_reverse_list():
List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(List)
reverse_list(List)
print(List)
test_reverse_list() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.