text stringlengths 37 1.41M |
|---|
import random
class Account:
# 클래스를 완성하세요
"""
- 보안문제로 외부에서 내부의 정보를 수정할 수 없도록 변수를 설정해야함
- 계좌번호와 잔고의 경우 표시된 결과와 다를 수 있음
- def __init__(name: str, birthday: str)
- def __str__() -> 계좌정보
- def deposit(amount:int) :입금 함수
- def withdraw(amount:int) 출금 함수
- 필요시 random() 함수 사용 가능
-... |
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
cv = tkinter.Canvas(root, width = 500, height = 300)
def click(event):
print("Click Location: ", event.x, event.y)
r, g, b = img.getpixel((event.x, event.y))
print("R:%d, G:%d, B:%d" % (r,g,b))
cv.bind("<Button-1>", click)
cv.p... |
"""
Задача на программирование: точки и отрезки
"""
import random
import bisect
def partition(array, start, end):
x = array[start]
# j
# | x | <= x | > x |
j = start
for i in range(start + 1, end + 1):
if array[i] <= x:
j += 1
array[i], array[j] = array[j... |
# -*-coding:Latin-1 -*
"""Classe Etudiant"""
class Etudiant:
# Attributs
nom = ""
prenom = ""
numCarte = 0
# constructeur
def __init__(self, nom, prenom):
self.nom = nom
self.prenom = prenom
""" Ajout des tudiants du fichier la liste """
def importFichier(liste, fichier):
... |
# -*-coding:Latin-1 -*
"""Classe Etudiant"""
class Etudiant:
# Attributs
nom = ""
prenom = ""
numCarte = 0
# constructeur
def __init__(self, nom, prenom):
self.nom = nom
self.prenom = prenom
""" Ajout des tudiants du fichier la liste """
def importFichier(liste, fichier):
... |
ten=int(input("Enter the Ten Rs. coins quantity: "))
five=int(input("Enter the Five Rs. coins quantity: "))
two=int(input("Enter the Two Rs. coins quantity: "))
one=int(input("Enter the One Rs. coins quantity: "))
total=((10*ten)+(5*five)+(2*two)+(1*one))
print("Total amount of money: ",total)
|
from tkinter import *
from tkinter import messagebox
import random as playerfind
def button(window):
b = Button(window, padx=1, bg="#856ff8", width=3, text=" ", font=('times new roman', 60, 'bold'))
return b
def change_a():
global turn
for i in ['O', 'X']:
if not (i == turn):
tu... |
def test(n,e):
if e>1 and e<n:
ct=int(input("Enter the cipher test ct = "))
if e<=5:
sm_e(ct,n,e)
else:
test2(ct,n,e)
else:
print("Wrong values Exiting")
def sm_e(ct,n,e):
from resources.nthroot import nth
res=nth(ct,e)
while(res!... |
def biggest_collatz(x):
longest_seq, test = [], []
for i in range(1, x+1):
test.append(i)
while i > 1:
if i % 2 == 0:
i //= 2
else:
i = i*3+1
test.append(i)
if len(test) > len(longest_seq):
longest_seq = test... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 16 19:45:00 2018
@author: Yahia Bakour, OOG
"""
def find_Median(A,B):
if(len(A) > len(B)):
Arr1 , n = B, len(B)
Arr2 , m = A, len(A)
else:
Arr1 , n = A, len(A)
Arr2 , m = B, len(B)
Min, Max = 0 , n
while(Min <= Max):
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 18:00:53 2018
@author: yahia
"""
def DictionarySearch(A,Left,Right,key):
if (Right >= Left):
y = (key - A[Left]) / (A[Right] - A[Left])
mid = Left + y * (Right - Left)
mid = int(mid)
if (A[mid] == key):
return mid
... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.parent = None
self.data = data
self.color = 'R'
class RB_Tree:
def __init__(self,N):
self.root = N
self.root.color = 'B'
def search(self,currnode, data):
... |
__author__ = 'Eder Xavier Rojas'
from collections import Counter
events = []
fechas = []
events_file = raw_input("Nombre del archivo: ")
print "you entered", events_file
try:
f = open(events_file,'r')
line = f.readline()
while line:
try :
#Set the whole string
#remove ent... |
import turtle
from random import *
for i in range(0,100,1):
turtle.right(randint(0,360))
turtle.forward(randint(0,100))
|
# 1. List Comprehensions
print('--' * 40)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f"Numbers: {numbers}")
print('--' * 40)
def square():
squares = []
for i in numbers:
squares.append(i ** 2)
print(f"Squares - Traditional way: {squares}")
print('--' * 40)
squares = list(map(lambda... |
# --------------------------------------------------------------------------
""" Root Class: object
Every class in Python is inherited directly or indirectly from Root class i.e 'object'.
"""
# --------------------------------------------------------------------------
class NewPerson(object):
def __init__... |
def func():
nums = [1, 2, 3, 4, 5]
a = list(map(lambda num: num ** 2, nums))
print(a)
# func()
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def execute(f... |
'''
Basic Operations Exercise in Matrix Operations
'''
import numpy as np
gene_list = np.array([['a2m', 'fos', 'brca2', 'cpox']])
times_list = np.array(['4h','12h','24h','48h'])
values0 = np.array([[.12,0.08,0.06,0.02]])
values1 = np.array([[0.01,0.07,0.11,0.09]])
values2 = np.array([[0.03,0.04,0.04,0.02]])
values3... |
from math import sqrt
maximum = 0
def prime(num): #tests if the number is prime
p = True
for i in range(2, int(sqrt(num))+1):
if num % i == 0:
p = False
break
return p
for a in range(-991, 1000, 2): #looping through all possible values of a and b
for b in range(-991... |
from math import sqrt
from time import time
start = time()
def prime(n):
if n == 1:
return False
for i in range(3, int(sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
side, primes = 3, 0
diagonal = [1]
while True:
for i in range(4):
n = diagonal[-1] + ... |
from math import sqrt
def tree(n):
pf = []
while n % 2 == 0:
pf.append(2)
n = n / 2
for i in range(3, int(sqrt(n)) + 1, 2):
while n % i == 0:
pf.append(i)
n = n / i
if n > 2:
pf.append(int(n))
return pf
con = 0
for n in range(100000, 100000... |
class Solution:
def bitwiseComplement(self, N: int) -> int:
value = N
if(N==0) : return 1
result=""
while value >= 1:
if(value%2 == 0):
result="0"+result
else:
result = "1"+result
value//=2
result2="... |
sal = float(input('Digite seu salário:'))
aumento10 = (sal/100 * 10) + sal
aumento15 = (sal/100 * 15) + sal
if sal > 1250.00:
print('Você vai ter um aumento de 10% e seu salário vai passar a ser R${}'.format(aumento10))
if sal <= 1250.00:
print('Você vai ter um aumento de 15% e seu salário vai passar a ser R${}... |
n = int(input('digite um número?'))
ant = (n-1)
suc = (n+1)
print('analisando o valor {}, o antecessor dele é {} e o sucessor é {}.'.format(n,ant,suc)) |
temperatura = float(input("Qual é a temperatura:"))
resultado = ((temperatura * 1.8) + 32)
print('A temperatura {}C para Fahrenheit é {}F'.format(temperatura,resultado))
|
v = int(input('Digite a velocidade do seu carro em KM/h:'))
a = v - 80
if v > 80:
print('MULTADO! ,o senhor estava a {}km/h acima do limite'.format(a))
print('Sua multa custará R${} reais'.format(a*7))
print('TENHA UM BOM DIA DIRIJA COM SEGURANÇA!')
else:
print('Parabéns você estava dentro do limite de ... |
# 二つの整数値を昇順にソート(その3)
a = int(input('整数a:'))
b = int(input('整数b:'))
a,b = sorted([a,b]) # 昇順にソート
print('a≦bとなるようにソートしました。')
print('変数aの値は',a,'です。')
print('変数bの値は',b,'です。')
|
# 文字列に含まれる文字列を探索
txt = input('文字列txt:')
ptn = input('文字列ptn:')
c = txt.count(ptn)
if c == 0:
print('ptnはtxtに含まれません')
elif c ==1:
print('ptnがtxtに含まれるインデックス:',txt.find(ptn))
else:
print('ptnがtxtに含まれる先頭インデックス:',txt.fint(ptn))
print('ptnがtxtに含まれる末尾インデックス:',txt.rfind(ptn))
|
# 点数を読み込んで合計点・平均点を表示(その1)
print('合計点と平均点を求めます。')
number = int(input('学生の人数:'))
tensu = [None] * number
for i in range(number):
tensu[i] = int(input('{}番の点数:'.format(i+1)))
total = 0
for i in range(number):
total += tensu[i]
print('合計は{}点です。'.format(total))
print('平均は{}点です。'.format(total/num... |
# 読み込んだ整数値以下の全約数を列挙
n = int(input('整数値:'))
for i in range (1,n+1):
if n % i == 0:
print(i,end=' ')
print()
|
# 人数と点数を読み込んで最低点・最高点を表示(その2:組み込み関数を利用)
print('最低点と最高点を求めます。')
number = 0
tensu = []
while True:
s = input('{}番の点数:'.format(number+1))
if s == 'End':
break
tensu.append(int(s))
number += 1
minimum = min(tensu)
maximum = max(tensu)
print('最低点は{}点です。'.format(minimum))
print(... |
# 小さいほうの値と大きいほうの値を求めて表示(その2)
a=int(input('整数a'))
b=int(input('整数b'))
if a < b:
min2 = a; max2 = b;
else:
min2 = b; max2 = a;
print('小さいほうの値は',min2,'です。')
print('大きいほうの値は',max2,'です。')
|
# 5人の点数を読み込んで合計点と平均点を求めます。
print('5人の点数の合計点と平均点を求めます。')
tensu1 = int(input('1番の点数:'))
tensu2 = int(input('2番の点数:'))
tensu3 = int(input('3番の点数:'))
tensu4 = int(input('4番の点数:'))
tensu5 = int(input('5番の点数:'))
total = 0
total += tensu1
total += tensu2
total += tensu3
total += tensu4
total += tensu5
pri... |
# 小さいほうの値と大きいほうの値を求めて表示(その5:min関数とmax関数)
a = int(input('整数a'))
b = int(input('整数b'))
min2 = min(a,b)
max2 = max(a,b)
print('小さいほうの値は',min2,'です。')
print('大きいほうの値は',max2,'です。')
|
#!/usr/bin/env python
# coding=utf-8
# @file solve.py
# @brief solve
# @author Anemone95,x565178035@126.com
# @version 1.0
# @date 2019-05-10 16:08
def solve():
with open('./Welcome.txt') as f:
content=f.read()
table={
'蓅烺計劃': 'A',
'洮蓠朩暒': 'B',
'戶囗': 'C',
'萇條': 'D',
... |
#!/usr/bin/env python3
"""
Class NeuralNetwork
Defines a neural network with one hidden
"""
import numpy as np
class NeuralNetwork:
"""
Performing binary classification
On 2 layers Neural Network
"""
def __init__(self, nx, nodes):
if not isinstance(nx, int):
raise TypeError("nx ... |
#!/usr/bin/env python3
"""
Class DeepNeuralNetwork
Defines a deep multiple layers neural network
"""
import numpy as np
import matplotlib.pyplot as plt
class DeepNeuralNetwork:
def __init__(self, nx, layers):
if not isinstance(nx, int):
raise TypeError("nx must be a integer")
if nx < 1... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
student_grades = np.random.normal(68, 15, 50)
bin = np.arange(0, max(student_grades), 10)
plt.hist(student_grades, bins=bin, edgecolor='black')
ybin = np.arange(0, len(student_grades), 5)
plt.yticks(ybin)
plt.xlabel('Grades')
p... |
#!/usr/bin/env python3
"""
Calculates the weighted moving average of a data set
"""
import numpy as np
def moving_average(data, beta):
"""
Returns: a list containing the moving averages of data
"""
# beta - weight
avg_list = []
mov_avg = 0
for i in range(len(data)):
mov_avg = ((mov_... |
#!/usr/bin/env python3
"""
performs matrix multiplication
"""
def mat_mul(mat1, mat2):
"""
Return a new matrix
Multiplication of all elements of 2 matricies
"""
if len(mat1[0]) != len(mat2):
return None
res = [[0 for i in range(len(mat2[0]))] for j in range(len(mat1))]
for i in r... |
#!/usr/bin/env python3
"""
Calculates the accuracy of a prediction
"""
import tensorflow as tf
def calculate_accuracy(y, y_pred):
"""
Returns a tensor containing the decimal accuracy
"""
pred = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(pred, tf.float32))
... |
NofP = eval(input())
for i in range(NofP):
line = input()
stringList = line.split()
number1 = eval(stringList[0])
number2 = eval(stringList[2])
number3 = eval(stringList[4])
operator = stringList[1]
if operator == "+":
answer = number1 + number2
elif operator == "-":
answ... |
x=eval(input())
if x == 1:
y=eval(input())
if 0<=y<=100:
if y>=60:
print("pass")
else:
print("fail")
else:
print("score error")
elif x==2:
y=eval(input())
if 0<=y<=100:
if y>=70:
print("pass")
else:
... |
n=input()
n=n.lower()
lst=[]
while True:
m=input()
if m=="q":
break
lst.append(m)
if n in lst:
a=lst.index(n)+1
print('Yes',a)
else:
b=len(lst)
print('No',b)
|
n=eval(input())
for j in range(1,n,2):
a=int((n-j)/2)
print(" "*(a)+"*"*j,end='')
print()
for j in range(n,0,-2):
a=int((n-j)/2)
print(" "*(a)+"*"*j,end='')
print()
|
#2.Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.
nome = input("Informe seu nome: ")
senha = input("Informe sua senha: ")
while (nome == senha):
print("O nome não pode ser igual a senha")
n... |
#9.Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50.
for i in range (1, 51):
if(i%2 != 0):
print(i)
for i in range (1, 51, 2):
print(i) |
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
valorHora = float(input("Informe o valor que você ganha por hora: "))
horaMes = float(input("Informe quantas horas foram trabalhadas esse mês: "))
salario = round(v... |
#Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00.
#Inform... |
print("Multiplicação de Dois Números")
print("=============================\n")
num1 = int(input("Por favor, informe um número: "))
num2 = int(input("Agora informe outro número: "))
multiplicacao = num1 * num2;
print(num1, " x ", num2, " = ", multiplicacao, sep="") |
#5.Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar:
#A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
#A mensagem "Reprovado", se a média for menor do que sete;
#A mensagem "Aprovado com Distinção", se a média fo... |
#!/usr/bin/python3
"""
Queries Reddit API and prints the titles of the first 10 hot posts
a given subreddit
"""
import requests
def top_ten(subreddit):
"""Prints titles of first 10 hot posts of a given subreddit"""
url = 'https://api.reddit.com/r/{}/hot?limit=10'.format(subreddit)
headers = {'user-agent':... |
Name = input("Enter your full name: ")
print("You are welcome" + "," + Name)
variable = input("Enter number of inputs: ")
if variable >= "3":
repr("Enter another number:")
number1 = float(input("Enter first number: "))
sign = input("Operator: ")
number2 = float(input("Enter another number: "))
if sign =... |
# n^2 solution
# def h_index(A):
# index = 0
# prev_index = 0
# while True:
# curr_papers = 0
# for i in A:
# if i >= index:
# curr_papers += 1
# if curr_papers < index:
# return prev_index
# else:
# prev_index = index
# ... |
total_attempt=0
while total_attempt<3:
username=input(“enter your user name: ”)
password=input(“enter your password ”)
If username==’Michal' and password==’e3$WT89x':
print(“you are successfully loged in")
else:
print(“you ent... |
attempt=0
while attempt<3:
user_name=input("Enter the username: ")
password =input("Enter the password :")
if user_name =="Micheal" and password =="e3$WT89x":
print("You have successfully logged in")
else:
attempt+1
print("Invalid username or password")
print("Account... |
"""Statistics and out-of-vocabulary words identification"""
import re
# Author: Thales Bertaglia <thalesbertaglia@gmail.com>
def identify_oov(lex, tokens, force_list=[]):
"""Returns a list containing all indexes of out-of-vocabulary words in ``text``.
Args:
lex (dict): The lexicon dictionary.
... |
year=int(input())
if(year%400==0):
print ("yes")
elif(year%4==0):
print ("yes")
else:
print ("no")
|
from __future__ import division
import sys
sys.path.append(r"C:\Users\dhruv\Documents\Learning\Data\Data-Science-Scratch\Chapter_3")
from linear_algebra import sum_of_squares
from linear_algebra import dot
from collections import Counter
import matplotlib.pyplot as plt
import random
import math
num_friends = random.c... |
import numpy as np
from helpers import sigmoid
def learn_complex_net(X, y):
# This function learns the weights for a neural net that calculates one set
# of "intermediate inputs" and then uses those inputs to make a prediction.
# The multiplications are set up so that in each iteration, the weights are
... |
class Termometro():
def __init__(self):
self.__unidadM = 'C'
self.__temperatura = 0
def __str__(self):
return"{}º {}".format(self.__temperatura, self.__unidadM)
def unidadMedida(self, uniM=None): # Aquí hay un getter y un setter
if uniM == None:
return ... |
# should_continue = True
# if should_continue:
# print("hello")
#
# known_people = ["John", "Ana", "Mary"]
# person = input("Enter the name of the person you know:\n")
#
# if person in known_people:
# print("Você conhece alguem")
# else:
# print("Você conhece ngm")
## Exercise
def who_do_you_know():
... |
from xml.dom import minidom
# Open XML document using minidom parser
DOMTree = minidom.parse("bookstore.xml")
# print(DOMTree.toxml())
print("Node type is: ", DOMTree.nodeType) # Number 9 means DOCUMENT_NODE
print("The list of nodes for the root:")
print(DOMTree.firstChild.childNodes)
print("")
for node in DOMTre... |
# Author : Harrison Toppen-Ryan
# Description : Password Checker, HW5, CSCI 141
# Date : November 21st, 2020
#Function to create a list and check if each password is valid or not
def validatePassword():
#empty list
passwordList = [ ]
#length of the password list
lenthPasswordList = len(pas... |
# Student ID : 1201201025
# Student Name : Tai Jun Ping
litre = 0.15
print("Natural Mineral Water Dispener")
print("------------------------------\n")
amount = int(input("Enter amount of liters : "))
print("\nPrice per litre : RM 0.15")
print("Number of litre :",amount)
total = amount * 0.15
print("Total... |
'''
start = 0
stop = 5 (n-1) = 4
step = +1
'''
for var in range(5):
#print(var)
print(var, end=', ')
print("Inside Loop")
print("Outside Loop")
|
num = int(input("Enter a number : "))
reverse = 0
temp = num
while(num > 0) {
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
if(temp == reverse):
print("Palindrome Number")
else:
print("Not Palindrome")
|
a,b,c = 10,20,30
# Logical Operators - and (&), or (|), not (!)
if a > b and a > c:
print("A is greatest")
elif b > a and b > c:
print("B is greatest")
else:
print("C is greatest")
print("Odd Even Program...............")
num = 10
if num % 2 == 0:
print("Even")
else:
print("Odd")
... |
min_range = int(input("Enter the min range : "))
max_range = int(input("Enter the max range : "))
for num in range(min_range, max_range):
for i in range(2, num//2):
if num % i == 0:
#print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
|
# las excepciones son errores que se producen en tiempo de ejecución
# estas provocan que el programa se detenga si no se controlan
# las excepciones son causadas por comportamientos inesperados en el programa
# de los cuales el programa mismo no se puede recuperar por si mismo si no se le ha programado para ello
def ... |
# tenemos estructuras para repetir código conocidas como ciclos
number = 5
list_numbers = [45, 51, 87, 72, 18, 62, 5, 38, 21, 19]
# while
# esta estructura repite n bloque de código mientras se cumpla la condición evaluada
while number > 0:
print('se cumple')
number -= 1
# for
# esta estructura repite el códi... |
# ya observamos el poder de las funciones
# sin embargo eso no es lo único que tienen por ofrecernos
#
# python también soporta el paradigma de programación funcional
# este paradigma se centra en las funciones para transformar datos de entrada en datos de salida
# y una de las características mas versátiles son las fu... |
# crear un programa que pida una lista de números al usuario desde la linea de comandos
# cada numero debera ir separado por una coma ","
# después de ingresar su lista de números al usuario se le pedirá que elija
# entre 4 opciones
# 1) quiere sumarlos todos
# 2) quiere multiplicarlos todos
# 3) quiere imprimirlos tod... |
import csv
voter_id = []
candidate = []
with open("election_data.csv.csv") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
voter_id.append(row[0])
candidate.append(row[2])
#Write "Election Results" with total votes done
print("Election Results")
print("-------------------... |
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
def area(radius):
temp = math.pi * radius**2
return temp
def circle_area(xc, yc, xp, yp):
print(area(distance(xc, yc, xp, yp)))
return
circle... |
from PyPDF2 import PdfFileMerger
import os
from tkinter import *
from tkinter import filedialog
root = Tk()
root.columnconfigure(0, weight=1)
root.title("PDF Merger")
root.resizable(False, False)
def mergePDF():
DIRECTORY_NAME = filedialog.askdirectory()
if(len(DIRECTORY_NAME)>1):
locEr... |
import turtle
colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange']
pen = turtle.Pen()
pen.speed(10)
turtle.bgcolor('black')
for x in range(200):
pen.pencolor(colors[x%6])
pen.width(x/100 + 1)
pen.forward(x)
pen.left(59)
turtle.done() |
def sawp(s1, s2):
return (s2, s1)
a = float(input('a=:'))
b = float(input('b=:'))
print(sawp(a,b)) |
import argparse
def gumarum(a,b):
c = a+b
return c
def Main():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v","--verbose",action="store_true")
group.add_argument("-q","--quiet",action="store_true")
parser.add_argument("num",help="th... |
'''
Moduuli, jonka funktioilla tarkistetaan syötteen järkevyys
Sisältää joukon funktioita, jota käyttämällä saadaan:
1. virhekoodi (int),2. virhesanoma (string) ja 3. arvo (float)
Funktiot palauttavat nämä tiedot listana
'''
# Kirjastojen lataukset
# Luokkien ja funktioiden määritykset
def liukuluku_syote(syote):
... |
"""
This is a controller that instantiates a SharedMemory core and builds a wrapper
around it to make it programmable. This is exposed to the programmer.
The function calls accepted:
load <src> <dst>
store <src> <dst>
"""
import Queue
import sys
from shared_memory import SharedMemory
class SharedMemor... |
turns=0
board = [["0", "0", '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0']]
board[int(random(0,5))][int(random(0,5))] = "1"
def setup():
size(500,500)
background(0)
img = loadImage("CarltonDance.gif")
def draw():
global img
... |
"""
fibonacci_algorithm.py
Returns the reduced uncertainty interval containing the minimizer of the function
func - anonimous function
interval0 - initial uncertainty interval
N_iter - number of iterations
"""
import numpy as np
def fibonacci_algorithm_calc_N_iter(interval0, uncertainty_range_desired):
F = ... |
# LCD Test Script
# Script to test the input and output of the Raspberry Pi GPIO
#
# Author: Kevin Wong
# With some code from a Raspberry Pi tutorial from:
# http://www.youtube.com/watch?v=KM4n2OtwGl0
#
# Date: 11/10/2013
# The wiring for the LCD is as follows:
# 1 : GND
# 2 : 5V
# 3 : Contrast (0-5V)*
# 4 : RS (R... |
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the powerSum function below.
def powerSum(X, N):
return recursion(X,N,1)
def recursion(X,N,num):
if pow(num,N)==X:
return 1
elif pow(num,N)<X:
return recursion(X,N,num+1) + recursion(X-pow(num,N),N,num+1)
... |
def func(number):
if number // 10 == 0:
return f"{number}"
if number // 10 != 0:
return f"{number % 10}{func(number // 10)}"
number_entered = int(input("Введите число: "))
print(int(func(number_entered)))
|
"""A simple python module to add a retry function decorator"""
import functools
import itertools
import logging
import signal
import time
from decorator import decorator
class _DummyException(Exception):
pass
class MaximumRetriesExceeded(Exception):
pass
class MaximumTimeoutExceeded(Exception):
pass
... |
# Load csv with no additional arguments
data = pd.read_csv("vt_tax_data_2016.csv")
# Print the data types
print(data.dtypes)
# Create dict specifying that 0s in zipcode are NA values
null_values = {'zipcode':0}
# Load csv using na_values keyword argument
data = pd.read_csv("vt_tax_data_2016.csv",
... |
#-*- coding: utf-8 -*-
from scipy.special import j1
def f(x):
return j1(2*x)
a = 0
b = 10
funa = f(a)
funb = f(b)
if ( funa * funb > 0.0):
print "Dotajaa intervaalaa [%s, %s] saknju nav"%(a,b)
sleep(1); exit()
else:
print "Dotajaa intervaalaa sakne(s) ir!"
deltax = 0.0001
while ( fabs(b-a) > delta... |
x = 5
if x < 10:
print('Smaller')
if x > 20:
print('Bigger')
print('Finis')
if x == 5:
print('Equals 5')
if x > 3:
print('Ģreater than 3')
if x > 5 :
print('Ģreater than 5')
if x >= 5:
print('Ģreater than or Equals')
if x <6:
print('Less than 6')
if x <= 5:
print('Less than or Equals... |
def bank(a, years):
i = 0
while i !=years:
a = a * 1.1
i = i + 1
return(a)
a = int(input('skolko deneg polozhit? '))
years = int(input("na skolko let? "))
print("za ", years, "goda u tebia budet ", bank(a, years), "deneg") |
# bubble sort per le liste
list = []
swapped = True
num = int(input("How many element do you want to sort?: "))
for i in range(num):
val = float(input("Enter next element: "))
list.append(val)
while swapped:
swapped = False
for i in range(len(list)-1):
if list[i] > list[i+1]:
swapp... |
def Fib(n):
if n < 1:
return None
if n < 3:
return 1
return Fib(n -1) + Fib(n - 2)
print("Serie Fibonacci del numero 6:\n")
print(Fib(6)) |
max = -999999999
number = int(input("Enter the value or -1 to stop while: "))
while number != -1 :
if number > max :
max = number
number = int(input("Enter the value or -1 to stop while: "))
print("The largest number is ", max)
|
# calcola il massimo tra due numeri interi passati come input
numero_1 = input('Inserire il primo numero intero:\n')
numero_2 = input('Inserire il secondo numero intero: \n')
#confronto
if numero_1 >= numero_2:
print('Il massimo e\' = ' + str(numero_1))
else:
print('Il massimo e\' = ' + str(numero_2))
|
def divisione(a,b):
try:
risultato = a / b
print("Il risultato della divisione = " + str(risultato))
except ZeroDivisionError:
print("Non posso dividere per 0")
divisione(10,0) |
# ciclo while
contatore = 0
if contatore <= 10:
print(contatore)
contatore = contatore + 1
while contatore <= 10:
print(contatore)
contatore = contatore + 1
# ciclo infinito
#while 15 == 15:
# print("ciclo infinito!")
|
# Il risultato è = 1 perché non entra nel while in quanto i = 0, però poi
# passa nel ramo else per forza e i si incrementa a +1 quindi i = 1
i=0
while i !=0:
i = i - 1
else:
i = i + 1
print(i)
|
my_list=(1,2,3,4,5,6,7,8,9,10)
for i in my_list:
print(i)
for num in range(0,10):
print(num+1)
|
#Print reverse of a string
def reverse(strng):
if len(strng) == 1:
return strng[0]
return strng[-1] + reverse(strng[:-1])
#Return true if string is palindrome (same from start or end example - tacocat)
def isPalindrome(strng):
if len(strng) == 1:
return True
if strng[0] == strng[-1]:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.