text stringlengths 37 1.41M |
|---|
#!/bin/python
"""
Authors:
Brett Creeley
Matty Baba Allos
"""
from Config import set_pwm
import warnings
class Servo(object):
"""
Servo stores the following values:
channel: The channel the Servo is connected to
min_pulse: The minimum pulse the Servo allows
max_p... |
############################## PART A ##############################
def find_matches(team):
match_schedule = open("Scouting_2019_Match_Schedule.csv", "r")
print(team + ": ", end = '')
for line in match_schedule.readlines():
# Turn each line into a list of all the numbers
line ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 3 18:50:05 2020
@author: william
"""
def two_sets(n):
if (n+1)%4==0 or n%4==0 or n==3:
print("YES")
th1 = 0
th2 = 1 if n%4==0 else 3
seq_1 = []
seq_2 = []
for i in range(n+1):
if i>0:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 18:09:47 2020
@author: william
"""
def missing_number(n, numbers):
res = (set(range(1, n+1))-numbers).pop()
print(res)
return None
def main():
n = int(input())
numbers = set(map(int, input().split()))
missing_number(n, ... |
# Una forma de recorrer la cadena de caracteres en busca de '@'
miEmail = input('Ingrese su email: ')
email = False
for i in miEmail:
if (i == '@'):
email = True
if (email == True): # Esto se puede simplificar escribiendo: if email ---Esto automaticamente es lo mismo (email == True)
print('E... |
# Plantear una clase llamada Jugador.
# Definir en la clase Jugador los atributos nombre y puntaje, y los métodos __init__,
# imprimir y pasar_tiempo (que debe reducir en uno la variable de clase).
# Declarar dentro de la clase Jugador una variable de clase que indique cuantos minutos falta
# para el fin de juego (in... |
# Realizar un programa que imprima en pantalla los números del 1 al 100.
"""
Modificar el programa para que resuelva:
1 - Imprimir los números del 1 al 500.
2 - Imprimir los números del 50 al 100.
3 - Imprimir los números del -50 al 0.
4 - Imprimir los números del 2 al 100 pero de 2 en 2 (2,4,6,8 ....100).
"""... |
# Definir una serie de listas y tuplas anidadas
empleados = ['Ignacio', 26, (18, 9, 2021)]
print(empleados)
empleados.append((19, 9, 2021))
print(empleados)
alumnos = ('Ignacio', [10, 8])
print(alumnos)
# La tupla no se puede modificar
# Pero podemos agregar elementos a la lista
alumnos[1].append(6)
p... |
# Crear y cargar una lista con 5 enteros. Implementar un algoritmo que identifique el mayor valor de la lista.
entero = []
for f in range(5):
entero.append(int(input('Cargar valor: ')))
print('La lista: {}'.format(entero))
# Basicamente toma un elemento cualquiera de la lista y lo compara con los demas
... |
# Confeccionar una clase que permita carga el nombre y la edad de una persona.
# Mostrar los datos cargados. Imprimir un mensaje si es mayor de edad (edad>=18)
class Persona:
def inicializar(self):
self.nombre = input('Escriba el nombre de la persona: ')
self.edad = int(input('Ingrese edad:... |
# Confeccionar un módulo que implemente dos funciones, una que retorne el mayor de dos enteros
# y otra que retorne el menor de dos enteros.
def mayor(x1, x2):
if (x1 > x2):
return x1
else:
return x2
def menor(x1, x2):
if (x1 < x2):
return x1
else:
retur... |
# Crear una lista y almacenar los nombres de 5 países. Ordenar alfabéticamente la lista e imprimirla
pais = []
print('Escribir 5 paises')
for f in range(5):
pais.append(input("Nombre pais: "))
print('Lista paises -sin ordenar-\n{}'.format(pais))
for k in range(len(pais)-1): # Ordena la lista conform... |
# Cargar una cadena por teclado luego:
# 1) Imprimir los dos primeros caracteres.
# 2) Imprimir los dos últimos
# 3) Imprimir todos menos el primero y el último caracter.
cadena = input('Ingrese un texto: ')
# LOS DOS PRIMEROS CARACTERES:
print(cadena[:2])
# LOS DOS ULTIMOS
print(cadena[(len(cadena)-2):])... |
# Confeccionar un programa que permita:
# 1) Cargar una lista de 10 elementos enteros.
# 2) Generar dos listas a partir de la primera.
# En una guardar los valores positivos y en otra los negativos.
# 3) Imprimir las dos listas generadas.
def cargar_enteros():
lista = []
print('INGRESE 10 VALORES EN... |
# Desempaquetar una lista o tupla
# Puede ser que tengamos una función que recibe una cantidad fija
# de parámetros y necesitemos llamarla enviando valores que se
# encuentran en una lista o tupla. La forma más sencilla es anteceder
# el caracter * al nombre de la variable:
def sumar(v1, v2, v3):
sumar =... |
# Desarrollar una clase que represente un punto en el plano y tenga los siguientes métodos:
# inicializar los valores de x e y que llegan como parámetros, imprimir en que cuadrante se
# encuentra dicho punto (concepto matemático, primer cuadrante si x e y son positivas,
# si x<0 e y>0 segundo cuadrante, etc.)
cla... |
# Una empresa tiene dos turnos (mañana y tarde) en los que trabajan 8 empleados
# (4 por la mañana y 4 por la tarde) Confeccionar un programa que permita almacenar
# los sueldos de los empleados agrupados en dos listas.
# Imprimir las dos listas de sueldos.
manana = []
tarde = []
print('Ingrese sueldo de lo... |
# Crear un diccionario en Python para almacenar los datos de empleados de una empresa.
# La clave será su número de legajo y en su valor almacenar una lista con el nombre, profesión
# y sueldo.
# Desarrollar las siguientes funciones:
# 1) Carga de datos de empleados.
# 2) Permitir modificar el sueldo de un emple... |
# Realizar la carga del nombre de una persona y luego mostrar el primer caracter del nombre
# y la cantidad de letras que lo componen.
nombre = input('Ingrese su nombre: ')
print('La primera letra del nombres es:')
print(nombre[0])
print('La cantidad de letras que tiene el nombre: ')
print(len(nombre)) |
# Crear dos listas paralelas. En la primera ingresar los nombres de empleados y en la
# segunda los sueldos de cada empleado.
# Ingresar por teclado cuando inicia el programa la cantidad de empleados de la empresa.
# Borrar luego todos los empleados que tienen un sueldo mayor a 10000 (tanto el sueldo como su nombre... |
# Confeccionar un programa que permita cargar un número entero positivo de hasta tres cifras
# y muestre un mensaje
# indicando si tiene 1, 2, o 3 cifras. Mostrar un mensaje de error si el número de cifras es mayor.
num = int(input('Ingrese un numero entero positivo: '))
if (num <= 99):
if (num <= 9):
... |
# Plantear una clase Operaciones que solicite en el método __init__ la carga de dos enteros
# e inmediatamente muestre su suma, resta, multiplicación y división. Hacer cada operación
# en otro método de la clase Operación y llamarlos desde el mismo método __init__
class Operaciones():
def __init__(self):
... |
# Almacenar en una lista los sueldos (valores float) de 5 operarios. Imprimir la lista y el promedio de sueldos.
sueldos = []
suma = 0
for f in range(5):
sueldos.append(float(input('Ingrese sueldo: ')))
suma = suma + sueldos[f]
prom = suma / 5
print('La lista de sueldo es:\n{}'.format(sueldos))
pr... |
# Plantear una clase Club y otra clase Socio.
# La clase Socio debe tener los siguientes atributos: nombre y la antigüedad en el club
# (en años).
# En el método __init__ de la clase Socio pedir la carga por teclado del nombre y su
# antigüedad.
# La clase Club debe tener como atributos 3 objetos de la clase Soc... |
# Desarrollar un programa que cargue una lista con 10 enteros.
# Cargar los valores aleatorios con números enteros comprendidos entre 0 y 1000.
# Mostrar la lista por pantalla.
# Luego mezclar los elementos de la lista y volver a mostrarlo.
import random
def cargar():
lista = []
for x in range(10):
... |
# Cargar por teclado y almacenar en una lista las alturas de 5 personas (valores float)
# Obtener el promedio de las mismas. Contar cuántas personas son más altas que el promedio y cuántas más bajas.
altura = []
suma = 0
for f in range(5):
altura.append(float(input('Ingrese altura: ')))
suma = suma ... |
# Resolveremos el mismo problema anterior pero definiendo dos alias para las funciones
# sqrt y pow del módulo math.
from math import sqrt as raiz, pow as elevar
# Definición de alias para una funcionalidad
valor = int(input('Ingrese un valor: '))
valor1 = raiz(valor)
print('La raiz cuadrada de {} es {}'.... |
# De un operario se conoce su sueldo y los años de antigüedad.
# Se pide confeccionar un programa que lea los datos de entrada e informe:
# a) Si el sueldo es inferior a 500 y su antigüedad es igual o superior a 10 años,
# otorgarle un aumento del 20 %, mostrar el sueldo a pagar.
# b)Si el sueldo es inferior a 50... |
# Confeccionar una función que cargue por teclado una lista de 5 enteros y la retorne.
# Una segunda función debe recibir una lista y mostrar todos los valores mayores a 10.
# Desde el bloque principal del programa llamar a ambas funciones.
def cargar_lista():
lista = []
for k in range(5):
lis... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def optional_introduce(func):
def wrapper (*args, introduce=False, **kwargs):
if introduce is True:
print(func.__name__)
func(*args, **kwargs)
return wrapper
@optional_introduce
def print_given(*args, **kwar... |
# Isaac Padberg
# 11.14.2019
"""Radix Sort"""
class Radix:
def __init__(self, array):
# Take the users input and copy it into our own array
self.unsortedArray = array.copy()
# Call radix sort and store its return value
sortedArray = self.radixSort()
self.sortedArray = []... |
import pygame
from UIComponents import Placeholder, Colors, Button, Slider
# ---------- PYGAME SETUP ----------
pygame.init()
size = (400, 700)
surface = pygame.display.set_mode(size)
clock = pygame.time.Clock()
stop = False
# ----------------------------------
# ----- CREATING A PLACEHOLDER -----
placeholder = Place... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 21:01:08 2019
@author: Admin
"""
import matplotlib.pyplot as plt
import numpy as np
import math
## Create functions and set domain length
x = np.arange(-5.0, 5.0, 0.01)
y = x**x
z=0
## Plot functions and... |
num = int(input('Введите число \n'))
i = num
for i in range (num, 0, -1):
if num % i == 0:
print(i)
|
#1.
def sortwithloops(input):
length = len(input)
for i in range(length):
for k in range(i, length):
if input[i] > input [k]:
tempList = input[i]
input[i] = input[k]
input[k] = tempList
return input
#2.
def sortwithoutloo... |
import timeit
setup = '''
import copy
import numpy as np
def sortwithloops(input):
length = len(input)
for i in range(length):
for k in range(i, length):
if input[i] > input [k]:
tempList = input[i]
input[i] = input[k]
input[k]... |
#!/usr/bin/python
word = "21^^CV^^baby^you think?^"
#word = "^^21CV^^"
result = []
level = 0
incrementing = False
decrementing = False
escaped = False
sequence = ""
for letter in word:
if letter != "^":
sequence = sequence + letter
if incrementing:
incrementing = False
esca... |
"""Write a function that takes an (unsigned) integer as input, and returns the number of bits that are
equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case"""
def countBits(n):
return sum(1 for c in bin(n... |
from collections import defaultdict
def frequency(l):
d=defaultdict(int)
for k in l:
d[k]+=1
for k in set(l):
print(k,"occurec",d[k],"times")
|
import functools
def log(text):
def decorator(fun):
@functools.wraps(fun) #wrapper.__name__ = fun.__name__
def wrapper(*args, **kwargs):
print("我就是想装饰一下%s, %s" % (fun.__name__, text))
return fun(*args, **kwargs)
return wrapper
return decorator
# sum2num = log(... |
'''
实现类似cp的功能
python mycp.py ./mysys.py ps
'''
import sys
def mycp(src_path, dest_path):
f1 = open(src_path)
f2 = open(dest_path, "w")
while True:
rtext = f1.read(50)
if rtext == "":
break
f2.write(rtext)
f1.close()
f2.close()
def main():
if not(len(sys.argv) >= 3):
print("至少需要两个参数")
else:
mycp(s... |
'''
递归函数:
调用本函数
实现递归:
1.找递归点
2.找递归终止条件
'''
# 求给定整型数的前n项和
def sumn(n):
if n == 0:
return 0
return n + sumn(n-1)
print(sumn(100))
'''
汉诺塔问题
'''
cnt = 0
def move(m, n):
global cnt
cnt += 1
print(m,"--->", n)
def hano(n, a, b, c): # 将a上的n个圆盘移动到b
if n == 1:
move(a, b)
return None
hano(n-1, a, c, b)
... |
'''
循环:
循环变量初始化
while 条件:
循环体
循环变量改变
else:
执行体
for 循环变量 in 序列:
循环体
else:
执行体
'''
s = "Python"
i = 0 # 循环变量
while i < len(s):
if s[i] == 't':
# break
i += 1
continue # 终止本次循环,继续下一次循环(循环条件)
print(s[i], end='')
i += 1
else: # 当循环的终止是由于循环条件不满足而终止的,不是break终止的
print("执行结束")
print('') # 换行
for i in s:
if i ... |
from tkinter import *
# 移动
def moveToAnother():
selections = list1.curselection()
for i in selections:
name = list1.get(i)
list2.insert(END, name)
list1.delete(i)
# 添加
def addItem():
s = var.get()
list1.insert(END, s)
var.set("")
root = Tk()
list1 = Listbox(root)
list2 =... |
import random
def qipan(pan):
'''展示棋盘'''
for hang in range(3):
lie = hang * 3
print("{} {} {}".format(pan[lie], pan[lie + 1], pan[lie + 2]))
def win(pan):
'''判断是否胜利'''
winls = ["012", "345", "678", "036", "147", "258", "048", "246"]
for win in winls:
i = 0
j = ... |
from tkinter import *
def hello(event):
print(event.char)
print("hello, x:%d, y:%d" % (event.x, event.y))
def hello_all(event):
print("→→", event)
root = Tk()
root.geometry("200x200")
# 绑定事件
root.bind('<Button-1>', hello)
root.bind('<Return>', hello)
root.bind('<Key>', hello)
f1 = Frame(root, height=100... |
import os #Functions to handle operating system
print(__file__)#__file__ is a constant that has the location of this script
print(os.getcwd()) #gets current working directory
print(os.path.realpath(__file__))#gets the directory of the file
print(os.path.abspath(__file__))#does the same thing as above
os.chdir(os.path.... |
x = int(input())
value_one = 0
value_two = x*(x+1)
value_three = x-1
var = str()
value_two = (value_two - value_three)*10
print(value_one,value_two)
i = 0
while i < x:
star,tri2,tri3 = '*',str(),''
star = star*i*2
k = 0
y = value_two
while k<x-i:
tri3 = tri3 + str(y)
y += ... |
"""
Ejercicio 02
finanzas personales (ingresos y egresos)
hacer un programa python para consola que le permita al usuario:
1. iniciar un proyecto de finanzas personales con cuenta a 0.00
2. dar opcion para registrar un ingreso o un egreso
3. si es un ingreso sumarlo a la cuenta
4. si es un egreso restarlo a la cuent... |
label = ["Name", "Price", "Type", "Category"]
def getByCat(items, category):
return [item for item in items if item['Category'] == category]
def readInput():
itemList = []
count = input()
for x in range(count):
item = [x.strip() for x in raw_input().split(",")]
itemPair = zip(label, item)
itemList.append(di... |
#outputs 1 to 10 all on different lines
counter = 1
#loops so counter prints 10 times
while counter >0 and counter <11:
print(counter)
#increases counter by 1
counter = counter + 1
#endwhile
## ACS Good work |
#takes three numbers and prints from highest to lowest
num1 = int(input("enter the first integer"))
num2 = int(input("enter the second integer"))
num3 = int(input("enter the third integer"))
#finds the order of the sixe of the three numbers
if num1 > num2 and num2 > num3:
print(num1, num2, num3)
elif num1 > num3 ... |
somestring = "here is a string"
substring = "string"
if substring in somestring:
newstring = somestring.replace(substring, "")
print(newstring) |
class School():
def __init__(self, name):
self.SchoolName = name
self.programList = []
self.staffList = []
self.budgetIncome = float(0)
self.budgetExpenses = float(0)
self.budgetResult = float(0)
def setSchoolName(self, name):
self.name = name
... |
def multiply(x,y):
return x*y
if __name__=='__main__':
print 'Enter first number: ',
x = int(raw_input())
print 'Enter second number: ',
y = int(raw_input())
print 'Multi: ',multiply(x,y)
|
# dijkstra.py
# Afnan Enayet
def dijkstra(graph, src):
""" Dijkstra's algorithm with a regular queue
:type graph: dict
:type src: int
"""
dist = dict() # the distances from src to dist[x]
prev = dict() # the previous node for node x
visited = set()
q = list()
# Initialize Dijkst... |
class Node(object):
def __init__(self, val):
self.val = val
self.children = dict()
class Trie(object):
def __init__(self):
self.root = Node(None)
def autocomplete(prefix: str, possible: list) -> list:
""" Given a prefix string and a set of possibilities,
returns a list of pos... |
# -*- coding: utf-8 -*-
# functions that use the trained model to classify a sample or a batch
from data_loader import get_one_sample, get_random_sample
from data_validation import validate_sample
from model_validation import validate_model
from train import load_model
def classify_sample(sample) -> bool:
""" cl... |
from random import choice
import time
import twl
# def get_dictionary(file):
# dictionary = {}
# with open(file) as whole_dictionary:
# lines = whole_dictionary.readlines()
# del lines[:lines.index("-START-\n")+1]
# del lines[lines.index("-END-\n"):]
# for line in lines:
# ... |
'''
Jacob Tyson
10/1/2019
Title: Average Rainfall document.
Description: This program will calculate the average rainfall over a certain amount of years, and then calculates the
total average yearly rainfall and total average monthly rainfall. The input function will take in the users input, and the
processing fu... |
#Jacob Tyson
""""""
import math
# cut off 7.89 to 7
print('7 with the .89 cut off = ' + str(round(7.89)))
# round 54.345395 to 54.345
print('54.345395 rounded to 3 decimal places' + str(round(54.345395, 3))
# calculate the square root of 2
print(math.sqrt(2))
# calculate the sin of 7
print('The sin of 7 = ' +... |
'''
Jacob Tyson
credit card validator
This program will ask user to input creditcard number, and validates it using different formats.
12/12/2019
'''
import re
def main():
getCardNumber = inputs() # calls inputs
getCardNumber = processing(getCardNumber) # calls proccessing
outputs(getCardNu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 18:42:08 2021
@author: gabri
"""
import urllib.parse
import requests
main_api = "https://www.mapquestapi.com/directions/v2/route?"
key = "QvrROLQbeGnXmsgha3A7O4tiYI5XHBUo"
#The "while True" construct creates an endless loop.
while True:
orig = inpu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 18:34:18 2021
@author: gabri
"""
aclNum=int(input("What is the IPv4 ACL number? "))
if aclNum>= 1 and aclNum<=99:
print("\n This is a standard IPv4 ACL.")
elif aclNum>= 100 and aclNum<=199:
print("\n This is a extended IPv4 ACL.")
else:
print(... |
from pygame import draw, image, transform
from nn import NeuralNet
import random
class Environment:
def __init__(self, display_height, display_width, unit_size):
"""Creates an object of type Environment.
Args:
display_height (int): Height of display in pixels.
display_widt... |
def rea(f):
with open(f) as d:
w = d.read()
words = w.split()
return words
#выдаёт список слов из текста в файле
def d(a):
words = rea(a)
unw = []
for word in words:
if len(word) > 1 and word[0] == 'u' and word[1] == 'n':
unw.append(word)
return un... |
import re
m = input()
rig = re.search(r'(\+7|8)\d{10}$',m)
if rig:
print('ya')
else:
print('no')
|
# Your task is to create a Python script that analyzes the records to calculate each of the following:
#Importing operating software and csv module
import os
import csv
#Creating lists
dates = []
profit = []
#Declaring variable value
total_profit = 0
#Set path for the csv file
csvpath = "../Resources/budget_data.... |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
#4. Create a function showEmployee() in such a way that it should accept employee name, and it’s salary and display both, and if the salary is missing in function call it should show it as 50000
def showEmployee(name,salary=50000):
print("Employee ",name," salary is... |
# 斐波那契数列
def fib(n):
a, b = 0, 1
while b < n:
print(b, end=" ")
a, b = b, a + b
print()
def fib02(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
return result
|
############类的对象############
# class PyClass:
# i=12345
# def f(self):
# return "hello world"
#
# #实例化类
# x=PyClass()
#
# #访问类的属性和方法
# print("访问属性",x.i)
# print("访问方法:",x.f())
############单继承################
# 类定义
class people:
# 定义基本属性
name = ''
age = 0
# 定义私有属性
__weight = 0
# 定义构造方法
def __init... |
"""
str(): 函数返回一个用户易读的表达形式
repr(): 产生一个解释器易读的表达形式
字符串对象的 rjust() 方法, 它可以将字符串靠右, 并在左边填充空格。 ljust() center()
"""
for x in range(1, 11):
print(repr(x).rjust(6), repr(x * x).rjust(6), end=" ")
# 注意end的使用
print(repr(x * x * x).rjust(6))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * ... |
class parent:
def myMethod(self):
print("调用父类方法")
class child(parent):
def myMethod(self):
print("调用子类方法")
def __myPrivateMethod(self):
print("这个是我的私有方法")
# 调用
c = child() # 子类实例
c.myMethod() # 子类调用重写方法
super(child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
# c.myPrivateMethod() # 报错,外部不能调用私有方法
|
class Iterator:
"""
Protocol for iterating over an object.
"""
def __init__(self, _iterable):
"""
Store iterable and initialize count.
Args:
_iterable (iterable object) - must have a 'length' and be indexable
"""
self._iterable = _iterable
... |
import turtle
import random
CELL_SIZE = 8 #size in pixels
class Grid:
def __init__(self, height, width):
self.height, self.width = height, width #dimensions of the grid
self.state = set() #state of the grid
def isValidMove(self, x, y):
return (0<=x<self.width) and (0<=y<self.height)
def genGrid(self):
se... |
'''
This function will filter two lists, removing duplicates from the first list
It sums up the values of the removed duplicates and puts those in the new list
Values in the first list and second list coorespond to each other
-------------------
Application
-------------------
Can be used with data from finici... |
def add(a,b):
return str(a+b)
def sub(a,b):
return str(a-b)
def mul(a,b):
return str(a*b)
def div(a,b):
return str(a/b)
print("selectt operation")
print("1.Add")
print("2.subtraction")
print("3.multiply")
print("4.div")
choice=input("enter the choice(1 or 2 or 3 or 4)=")
a=int(input("enter the fst... |
def quicksort(arr):
if len(arr) <= 2:
return arr
else:
pivot = arr[0]
less = [n for n in arr[1:] if n < pivot]
greater = [n for n in arr[1:] if n >= pivot]
return quicksort(less) + [pivot] + quicksort(greater)
arr = [1,3,4,5,3,7,8,1,2]
arr2= [9,9,1,3,4,5,3,7,8,1,2]
prin... |
"""
Tests for tree
"""
import unittest
from tree import BSTNode
from tree import Tree
class TestBSTNode(unittest.TestCase):
def test_init(self):
test_node = BSTNode(5)
self.assertEqual(test_node.value, 5)
def test_append(self):
test_node = BSTNode(5)
test_node.append(BSTNode(3... |
"""
Write code to find the nth to last element of a linked list
"""
import unittest
from linked_list import LinkedList
class TestNthToLast(unittest.TestCase):
def test_nth_to_last(self):
ll_with_dups = LinkedList()
ll_with_dups.append(2)
ll_with_dups.append(3)
ll_with_dups.append(2... |
from time import sleep
class Maze(object):
"""
draw : print current board
am_i_out : not very usefull
Playing :
can_i_move
move : perform move in the current dir
turn_left
turn_right
Building the Maze :
add_wall_horiz
... |
import random
EMPTY_CELL = 0
DIMENSION = 4
NEW_CELL_IS_2 = 2
NEW_CELL_IS_4 = 4
PROBABILITY_OF_4 = .25
def create_field():
'''
Get number of rows and columns in game field (N rows == N columns)
and value that marks empty cell. Return game field as a list of lists.
>>> create_field()
[[0, 0, 0, 0], [... |
#!/usr/bin/env python3
import sys
insurance_dict = {'endowment_insurance':0.08,
'medical_insurance':0.02,
'unemplotment_insurance':0.005,
'injury_insurance':0,
'maternity_insurance':0,
'provient_found':0.06}
staff_dict = {}
def get_input():
if len(sys.argv) == 1:
print("Parameter Error")
return None ... |
#Q1
def mult(s,n=6):
return s*n
#Q2
def greeting(name,greeting="Hello ", excl="!"):
return greeting + name + excl
print(greeting("Bob"))
print(greeting(""))
print(greeting("Bob", excl="!!!"))
#Q3
def sum( intx,intz=5):
return intz + intx
#Q4
def test(int,boole=True,dict... |
class Module():
"""
Class representing modules.
"""
def __init__(self, name=None, parent=None):
self.name = name
self.submodules = []
self.wires = []
self.parent = self if (parent == None) else parent
def setName(self, name):
self.name = name
def addMod... |
'''
Finnian Wengerd
Algorithms
Daniel Showalter
Eastern Mennonite University
Job Scheduling: Stress Level and Optimum Value (BOTTOM-UP)
'''
'''
....................................................................................................................................................
Given a sequence o... |
#The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to... |
# This program shows implementation of stack data stucture in python using list
class Stack :
def __init__(self):
self.list_of_items = []
def push(self,item):
self.list_of_items.append(item)
def pop(self):
self.list_of_items.pop() #inbuilt pop operation for li... |
import datetime
# Health Management System.
# 3 clients - Harry , Rohan and Hmmad
def gettime(): # to add date and time in log
return datetime.datetime.now()
def storedata(userinput): # for input Data for User.
if userinput == 1: # Harry
c = int(input("Enter 1 for Exercise and 2 for Food"))
... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
# added count to function definition so that it may increment as it rec... |
#imports
import csv
#Variables
current_ID = 1
new_additions = []
filename = "library.csv"
fields = ['ID', 'Title', 'Author', 'Genre', 'Year', 'Location']
data = []
#Code
print("------Welcome to the Python Library organiser------")
choice = ""
while choice.lower() != "x":
print("""What would you like to do?... |
""" This script will extract the customer service offering information that is stored in SNOW
"""
from openpyxl import load_workbook
def get_worksheet_table(worksheet, table_name):
""" Get all tables from a given workbook. Returns a dictionary of tables.
Requires a filename, which includes the file path a... |
def insertion_sort(A):
for i in range(1, len(A)):
key = A[i]
j = i-1
while j >= 0 and key < A[j]:
A[j+1] = A[j]
j -= 1
A[j+1] = key
def recurse_insertion(A, n):
if n == 1:
A[0] = A[0]
elif n > 1:
recurse_insertion(A, n-1)
key =... |
def merge(A, p, q, r):
L = [0] * (q-p+1)
R = [0] * (r-q)
for i in range(len(L)):
L[i] = A[p+i]
for j in range(len(R)):
R[j] = A[q+j+1]
i = 0
j = 0
for k in range(p, r+1):
if i >= len(L):
A[k] = R[j]
j += 1
elif j >= len(R):
... |
"""
matrixes and conditions example - Michael
"""
import numpy as np
import scipy as sp
from scipy.linalg import hilbert
# matrix definition
A = np.matrix(([2, 3, 4], [1, 1, 1], [3, 4, 4]))
AA = np.array(([2, 3, 4], [1, 1, 1], [3, 4, 4]))
print('A=', A)
print('AA=', AA)
print('A*AA=', A*AA) # multiplaction matrix
in... |
import numpy as np
import sympy as sy
x = sy.Symbol('x') # x is symbol varible so in f varible we can change the function and it will work because f is also symbol
print('π = ', np.pi) # pi check
def PI(n):
i = 1
sum = 0
while i <= n:
sum = sum + ((-1)**(i-1)*1/(2*i-1))
i = i + 1
sum ... |
#Author:黄国栋
age=23
num=0
while num<3:
age1=int(input("请输入年龄:"))
if age==age1:
print("猜对了")
break
elif age<age1:
print("猜大了")
else:
print("猜小了")
num+=1
if num==3:
print("您已经超过三次机会。。。不好意思,小爷不陪你玩了")
|
'''
This script is just to study the
basics of colour manipulations.
Pretty self explanatory.
'''
from SimpleCV import *
def main():
img = Image("simplecv")
#Playing with Scaling
thumbnail = img.scale(90,90)
thumbnail = thumbnail.show()
#Playing with erosion
eroded = img.erode()
eroded.show()
#Effe... |
# LEVEL 23
# www.pythonchallenge.com/pc/hex/bonus.html
import this
# ROT13
first = ord('a')
last = ord('z')
str1 = "".join([chr(x) for x in range(first, last + 1)])
str2 = "".join([chr(first + x + 13 - last - 1) if x + 13 > last else chr(x + 13) for x in range(first, last + 1)])
print(str1)
print(str2)
table = str.ma... |
# LEVEL 15
# http://www.pythonchallenge.com/pc/return/uzi.html
import calendar
import datetime
for year in range(2016, 1582, -1):
if calendar.isleap(year):
if datetime.date(year, 1, 1).weekday() == 3: # 3=Thursday
if str(year)[0] == '1' and str(year)[3] == '6':
print(year)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.