text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cpp3.py
#
def main(args):
a = int(input("Podaj liczbe a: "))
b = 0
for a in range(a+1):
b = a*a
print(b)
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import turtle
def rysuj(bok, kat, przyrost, warunek):
turtle.forward(bok)
turtle.right(kat)
if kat <= warunek:
rysuj(bok, kat, przyrost, warunek-przyrost)
def main(args):
bok = int(input("Podaj bok: "))
kat = int(input("Podaj kat: "))
przyrost = 30
warunek = 180
turtle.setup(1000.800)
turtle.color('black', 'red')
turtle.begin_fill()
turtle.speed(5)
rysuj(bok, kat, przyrost, warunek)
turtle.end_fill()
turtle.done()
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
# Practica6.py-P6E4
#Escribe un programa que te pida dos numeros, de manera que el segundo sea
#mayor que el primero. El programa termina escribiendo los dos numeros tal y como
# pide:
#Escribe un numero: 6
#Escribe un numero mayor que 6: 6
#6 no es mayor que 6. Vuelve a introducir un numero: 1
#1 no es mayor que 6. Vuelve a introducir un numero: 8
#Los numeros que has escrito son 6 y 8
numero1=int(input("Escribe un numero "))
print("Escribe un numero mayor que", numero1,end=": ")
numero2=int(input())
while (numero1>=numero2):
print(numero2, "no es mayor que", numero1)
numero2=int(input("Vuelve a introducir un numero: "))
print("Los numeros que has escrito son",numero1,"y",numero2) |
# Practica6.py-P6E6
#Escribe un programa que pida primero dos numeros (maximo y minimo) y que despues
#te pida numeros intermedios. Para terminar de escribir numeros, escribe un numero
#que no este comprendido entre los dos valores iniciales. El programa termina escribiendo la lista de numeros.
#Escribe un numero: 6
#Escribe un numero mayor que 6: 4
#4 no es mayor que 6. Vuelve a probar: 50
#Escribe un numero entre 6 y 50: 45
#Escribe otro numero entre 6 y 50: 13
#Escribe otro numero entre 6 y 50: 4
#Los numeros situados entre 6 y 50 que has escrito son: 45, 13
numeroMinimo=int(input("Escribe un numero: "))
print("Escribe un numero mayor que",numeroMinimo,end=": ")
numeroMaximo=int(input())
listaIntermedios=[]
while numeroMaximo<=numeroMinimo:
print(numeroMaximo,"no es mayor que", numeroMinimo, end=". ")
numeroMaximo=int(input("Vuelve a probar:"))
print("Escribe un numero entre %s y %s: " %(numeroMinimo,numeroMaximo),end="")
numeroIntermedio=int(input())
while numeroMinimo<numeroIntermedio<numeroMaximo:
listaIntermedios.append(numeroIntermedio)
print("Escribe otro numero entre %s y %s: " %(numeroMinimo,numeroMaximo),end="")
numeroIntermedio=int(input())
print("Los numeros situados entre %s y %s que has escrito son: " %(numeroMinimo,numeroMaximo),end="")
for i in range(len(listaIntermedios)):
if i==len(listaIntermedios)-1:
print(listaIntermedios[i])
else:
print(listaIntermedios[i],end=", ")
|
"""
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
"""
class Solution:
def isValid(self, s: str) -> bool:
"""
This method will take in a string containing only '(', ')', '{', '}', '[' and ']' and
determines if the string is valid not
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
:param s: String will only '(', ')', '{', '}', '[' and ']' characters
:return: True if string is valid. Otherwise, False
"""
val_par = []
for each in list(s):
try:
if each in ['(', '{', '[']:
val_par.append(each)
elif each == ')' and val_par[-1] == '(':
val_par.pop()
elif each == '}' and val_par[-1] == '{':
val_par.pop()
elif each == ']' and val_par[-1] == '[':
val_par.pop()
else:
return False
except IndexError:
return False
if len(val_par) == 0:
return True
else:
return False |
import pygame
class Player():
def __init__(self, screen, settings):
self.width = 12
self.height = 60
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.screen = screen
self.screenRect = screen.get_rect()
self.settings = settings
self.movingUp = False
self.movingDown = False
self.movingLeft = False
self.movingRight = False
self.rect.centerx = self.screenRect.right - 50
self.rect.y = self.screenRect.bottom / 2
self.y = float(self.rect.y)
self.x = 3 * self.screenRect.width/4
self.rect2 = pygame.Rect(0, 0, self.height, self.width)
self.rect2.y = self.screenRect.top + 50
self.rect3 = pygame.Rect(0, 0, self.height, self.width)
self.rect2.x, self.rect3.x = self.x, self.x
self.rect3.y = self.screenRect.bottom - 50
def update(self):
if self.movingUp and self.y > self.screenRect.top + 5:
self.y -= self.settings.playerSpeed
elif self.movingDown and self.y < self.screenRect.bottom - self.height - 5:
self.y += self.settings.playerSpeed
self.rect.y = self.y
if self.movingLeft and self.x > self.screenRect.width / 2:
self.x -= self.settings.playerSpeed
elif self.movingRight and self.x < self.screenRect.right - self.rect.height - 5:
self.x += self.settings.playerSpeed
self.rect2.x, self.rect3.x = self.x, self.x
def drawPlayer(self):
pygame.draw.rect(self.screen, (255, 255, 255), self.rect)
pygame.draw.rect(self.screen, (255, 255, 255), self.rect2)
pygame.draw.rect(self.screen, (255, 255, 255), self.rect3)
def reset(self):
self.y = self.screenRect.bottom/2
self.rect.y = self.y
self.x2 = self.screenRect.width / 2
self.rect2.x, self.rect3.x = self.x, self.x
|
print("Welcome to Tip Calcultor")
totalbill = float(input("Whats the total bill $"))
tippercent = float(input("What percent tip you want to give 5,10,15 and 20 ?"))
splitbill = float(input("How many people the bill need to be split across?"))
tippercent = (totalbill*tippercent)/100
grandtotalbill = totalbill + tippercent
personbill = grandtotalbill/splitbill
print("The total bill value including tip %f" %(grandtotalbill))
print("Each person should pay bill off {:.2f}".format(round(personbill,2))) |
def division(n,m):
if(m==0):
return "division por 0"
if(m>n):
return 0
else:
return division(n-m,m)+1
print(division(10,5))
|
#!/usr/bin/python
# coding: utf8
"""
Contains range related data structures
List of data structures:
- VariableRangeValue
"""
class VariableRangeValue(object):
"""
Contains the range [lower_bound, 0, upper_bound]
Initialize the range to [-inf, 0, +inf]
"""
identifier = ""
bit_vector_size = 0
value = None
range = [-float("inf"), 0, float("inf")]
LOWER_BOUND = 0
UPPER_BOUND = 2
def __init__(self, size, variable_name, default_range):
self.bit_vector_size = size
self.identifier = variable_name
self.value = None
self.range = default_range
def set_lower_bound(self, new_bound):
"""
Sets the lower bound value
"""
self.range[VariableRangeValue.LOWER_BOUND] = new_bound
def set_upper_bound(self, new_bound):
"""
Sets the upper bound value
"""
self.range[VariableRangeValue.UPPER_BOUND] = new_bound
|
class Dice:
'''
this class emulates a six sided dice with numbers 1 to 6 on each side such that the sum of numbers on two
opposite sides is always 1.
'''
__slots__ = 't', 'd', 'l', 'r', 'f', 'b'
def __init__(self):
self.t = 1
self.d = 6
self.l = 4
self.r = 3
self.f = 5
self.b = 2
def __eq__(self, other):
return self.t == other.t and self.f == other.f
def __str__(self):
# north/ up = back, right/ east = right
return "Die Orientation: Top = {} North = {} East = {}".format(self.t, self.b, self.r)
def __repr__(self):
return str(self)
|
#problem 1
##names = []
##ages = []
##towns = []
##for i in range(5):
## name = input("Enter the name of person ")
## names.append(name)
## age = input("Enter the age of person ")
## ages.append(age)
## hometown = input("Enter the hometwon of person ")
## towns.append(hometown)
##
##
##print(names)
##print(ages)
##print(towns)
##
##print("Name Age Hometown")
##print("-----------------------")
#problem 2
#algorithm
#create a empty list
#index through the list, and put the smallest number in the new list
numbers = [6,3,2,5,7,1,1,2]
sorted_list = []
while numbers:
min = numbers[0]
for x in numbers:
if x < min:
min = x
sorted_list.append(min)
numbers.remove(min)
print(sorted_list)
|
#颜色映射
import matplotlib.pyplot as plt
x_values = list(range(1, 6))
y_values = [x ** 3 for x in x_values]
plt.scatter(x_values, y_values, c = y_values, cmap = plt.cm.Reds, s = 60)
plt.title('Cube of Value', fontsize = 22)
plt.xlabel('value', fontsize = 12)
plt.ylabel('cube', fontsize = 12)
plt.tick_params(axis = 'both', which = 'major', labelsize = 10)
plt.show()
#5000
import matplotlib.pyplot as plt
x_values = list(range(1, 5001))
y_values = [x ** 3 for x in x_values]
plt.scatter(x_values, y_values, c = y_values, cmap = plt.cm.Greens, s = 60)
plt.title('Cube of Value', fontsize = 22)
plt.xlabel('value', fontsize = 12)
plt.ylabel('cube', fontsize = 12)
plt.tick_params(axis = 'both', which = 'major', labelsize = 10)
plt.show()
|
# prompt = "Do you have girlfriend ?"
# print(prompt)
# active = True
# while active:
# y_n = input("Please input y/Y or n/N:\n")
# if y_n == 'y' or y_n == 'Y':
# print("Congratulation! you isn't single dog\n")
# elif y_n == 'n' or y_n == "N":
# print("It is shame that you are still a single dog\n")
# else:
# active = False
#
# prompt = "Tell me something. and I will repeat it back to you:\n"
# prompt += "Enter 'quit' to end the program.\n"
# message = ""
# while message != 'quit':
# message = input(prompt)
# print(message)
# message_1 = ""
# prompt = "Please choose your topping:\n"
# while input(prompt) != 'quit':
# print("Thanks for your order we will finish your pizza soon")
# # 使用while实现列表之间移动元素
# prompt = "Please choose confirmed user"
# prompt += "\nInput number 1 or 2 or 3"
# prompt += "\nEnter 'quit' to end the program"
# unconfirmed_users = ['eugene', 'xu', 'fu']
# confirmed_users = []
#
# # 存储输入
# message = ""
#
# # 判断未验证用户列表是否为空
# while unconfirmed_users:
# print("Which user was confirmed in The flowing users ")
# print(prompt)
#
# # 遍历未验证用户列表
# for unconfirmed_user in unconfirmed_users:
# print("\t" + unconfirmed_user)
#
# # 用户输入
# message = input()
# print("\n" + prompt)
# if message == '1':
#
# # 弹出未验证用户列表末尾元素
# current_user = unconfirmed_users.pop()
#
# # 将元素添加到验证用户列表末尾
# confirmed_users.append(current_user)
# for unconfirmed_user in unconfirmed_users:
# print("\n" + unconfirmed_user + " was't confirmed")
# elif message == '2':
# current_user = unconfirmed_users.pop()
# confirmed_users.append(current_user)
# for unconfirmed_user in unconfirmed_users:
# print("\n" + unconfirmed_user + " was't confirmed\n")
# elif message == '3':
# current_user = unconfirmed_users.pop()
# confirmed_users.append(current_user)
# for unconfirmed_user in unconfirmed_users:
# print("\n" + unconfirmed_user + " was confirmed")
# else:
# print("Please input 1 or 2 or 3:\n")
# print("\n confirmed users are")
# print(confirmed_users)
# print(unconfirmed_users)
# 7-8练习
sandwich_orders = ['tuna', 'tune', 'tun']
finished_sandwiches = []
# while sandwich_orders:
# for sandwich_order in sorted(sandwich_orders):
# print("\nI made your " + sandwich_order + " sandwich")
# current_order = sandwich_orders.pop()
# finished_sandwiches.append(current_order)
# print("\n" + str(finished_sandwiches))
# 7-9练习
# print("Sorry, Pastrami is all sell")
# for _ in range(1, 4):
# sandwich_orders.append('pastrami')
# a = 'pastrami'
# active = True
# while active:
# if a in sandwich_orders:
# sandwich_orders.remove('pastrami')
# else:
# active = False
# print(sandwich_orders)
|
'''
Дано действительное положительное число a и целоe число n.
Вычислите a^n. Решение оформите в виде функции power(a, n).
Стандартной функцией или операцией возведения в степень
пользоваться нельзя.
Входные данные
Вводится действительное положительное число a и целоe число n.
Выходные данные
Выведите ответ на задачу.
Примеры
входные данные
2
1
выходные данные
2
входные данные
2
2
выходные данные
4
TEST 100%
'''
def power(a, n):
answer = 1
if n < 0: a=1 / a
for _ in range(abs(n)):
answer *= a
return answer
print(power(float(input()), int(input())))
|
'''Дана строка, возможно, содержащая пробелы.
Определите количество слов в этой строке.
Слово — это несколько подряд идущих букв латинского алфавита
(как заглавных, так и строчных).
Решение оформите в виде функции CountWords (S),
возвращающее значение типа int.
При решении этой задачи нельзя пользоваться дополнительными строками
и списками.
Примеры
входные данные
Yesterday, all my troubles seemed so far away
выходные данные
8
mink 100%
'''
def IsLetter(letter):
return ('A'<=letter<='Z') or ('a'<=letter<='z')
def CountWords(a):
cnt = 0
for i in range(1,len(a)):
if IsLetter(a[i-1]) and not IsLetter(a[i]): # end of the word.
cnt += 1
return cnt+1 if IsLetter(a[-1]) else cnt
print(CountWords(input())) # seperating functions and main programm
|
'''
Даны два натуральных числа n и m. Сократите дробь n/m,
то есть выведите два других числа p и q таких, что n/m=p/q и
дробь p/q — несократимая.
Решение оформите в виде функции ReduceFraction(n, m),
получающая значения n и m и возвращающей кортеж из двух чисел.
Входные данные
Вводятся два натуральных числа.
Выходные данные
Выведите ответ на задачу.
Примеры
входные данные
12
16
выходные данные
3 4
'''
import math
def ReduceFraction(n, m):
k = math.gcd(n, m)
return n//k, m //k
n, m = int(input()), int(input())
print(*ReduceFraction(n, m))
|
'''Заданы две клетки шахматной доски.
Если они покрашены в один цвет, то выведите слово YES,
а если в разные цвета – то NO.'''
y1=int(input('введите номер строки: '))
x1=int(input('введите номер столбца: '))
y2=int(input('введите конечный номер строки: '))
x2=int(input('введите конечный номер столбца: '))
print('YES' if (x1+y1+y2+x2)%2==0 else 'NO')
|
"""A dead-simple implementation of a graph data structure in Python."""
class DiGraph:
"""A simple directed graph data structure."""
def __init__(self):
self.adj = dict()
def add_node(self, label):
self.adj[label] = set()
def add_edge(self, u_label, v_label):
for x in {u_label, v_label}:
if x not in self.adj:
self.adj[x] = set()
self.adj[u_label].add(v_label)
def nodes(self):
yield from self.adj.keys()
def edges(self):
for u, neighbors in self.adj.items():
for v in neighbors:
edge = frozenset((u, v))
yield (u, v)
def neighbors(self, u_label):
for v in self.adj[u_label]:
yield v
def has_node(self, label):
return label in self.adj
def has_edge(self, u_label, v_label):
return v_label in self.adj[u_label]
class Graph:
"""A simple graph data structure."""
def __init__(self):
self.adj = dict()
def add_node(self, label):
self.adj[label] = set()
def add_edge(self, u_label, v_label):
for x in {u_label, v_label}:
if x not in self.adj:
self.adj[x] = set()
self.adj[u_label].add(v_label)
self.adj[v_label].add(u_label)
def nodes(self):
yield from self.adj.keys()
def edges(self):
seen = set()
for u, neighbors in self.adj.items():
for v in neighbors:
edge = frozenset((u, v))
if edge not in seen:
seen.add(edge)
yield (u, v)
else:
continue
def neighbors(self, u_label):
for v in self.adj[u_label]:
yield v
def has_node(self, label):
return label in self.adj
def has_edge(self, u_label, v_label):
return v_label in self.adj[u_label]
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from xml.dom import minidom
def parseXmlFile(fileName):
xmldoc = minidom.parse(fileName)
booklist = xmldoc.getElementsByTagName('book')
for i in booklist:
for attrName, attrValue in i.attributes.items():
print("%s = %s" % (attrName, attrValue))
print i.getElementsByTagName("author")[0].childNodes[0].toxml()
print i.getElementsByTagName("title")[0].childNodes[0].toxml()
print i.getElementsByTagName("genre")[0].childNodes[0].toxml()
print i.getElementsByTagName("price")[0].childNodes[0].toxml()
print i.getElementsByTagName("publish_date")[0].childNodes[0].toxml()
print i.getElementsByTagName("description")[0].childNodes[0].toxml()
print "----------------------------"
if __name__ == "__main__":
parseXmlFile('Books.xml')
|
def divBy2(decNumber):
binary = []
while decNumber > 0:
rem = decNumber % 2
binary.append(rem)
decNumber = decNumber // 2
return binary[::-1]
def toDecNumber(binary):
decNumber = 0
index = 0
while index < len(binary):
print(decNumber)
decNumber = decNumber + (2**index * binary[index])
index = index + 1
return decNumber
def toInfix(string):
ops = {}
ops["*"] = 2
ops["/"] = 2
ops["+"] = 1
ops["-"] = 1
ops["("] = 0
postfix = []
opStack = []
list_string = list(string)
for x in list_string:
print opStack
if x.isalnum():
postfix.append(x)
elif x == '(':
opStack.append(x)
elif x == ')':
topToken = opStack.pop()
while topToken != '(':
postfix.append(topToken)
topToken = opStack.pop()
elif x in ops:
while len(opStack) != 0 and ops[opStack[-1]] >= ops[x]:
postfix.append(opStack.pop())
opStack.append(x)
print opStack
while len(opStack) != 0:
postfix.append(opStack.pop())
return postfix
|
from random import choice as choose
from random import randint
def displayBoard(board):
"""The Skeleton of the board and displaying of it"""
print('\n'*20)
print('''
| |
{0} | {1} | {2}
_____|_____|_____
| |
{3} | {4} | {5}
_____|_____|_____
| |
{6} | {7} | {8}
| |
'''.format(*board))
def playerInput():
"""Take player input and set appropriate variables"""
Identity1 = ''
while Identity1.lower() != 'x' and Identity1.lower() != 'o':
Identity1 = input("Do you want to be X or O: ")
if Identity1.lower() == "o":
return ("O","X")
else:
return ("X","O")
def play(Identity,board):
"""set the board based on player input"""
choice=0
while not 0<choice<=9:
choice = int(input("\tChoose position(1-9): "))
try:
assert 0<choice<=9
except AssertionError: continue
if board[choice-1] == ' ':
board[choice-1]=Identity
else:
print('taken!')
choice=0
displayBoard(board)
def won(b,Identity):
"""check if the game have been won"""
#Return true if "any" of the possible combinations is true
#ACROSS,DIAGONAL,VERTICAL
return any([b[0]==b[1]==b[2]==Identity,b[3]==b[4]==b[5]==Identity,\
b[6]==b[7]==b[8]==Identity,b[1]==b[4]==b[7]==Identity,\
b[2]==b[5]==b[8]==Identity,b[0]==b[3]==b[6]==Identity,\
b[0]==b[4]==b[8]==Identity,b[2]==b[4]==b[6]==Identity])
def wannaPlay():
"""confirm if player want to play again"""
confirmation = input('wanna play again?(Y or N) ')
if confirmation.lower() == 'y':
return True
else:
return False
def isNextWin(board,identity,possibilities):
"""Check if a next move can be a winning move"""
for i in possibilities:
copyb = board[:]
copyb[i]=identity
if won(copyb,identity):
return i+1
else:
return False
def RandomMov(identity1,identity2,board):
"""The Computer AI Logic"""
choice = 4
#list of indices of empty spots,hence a possible moving position
possibilities = [x for x,y in enumerate(board) if y ==' ']
#to prevent replacing of already taken spots
while board[choice].lower() != ' ':
#to prevent calling the function 4 times,save the result to variables
#check if The player can win on his next move and block that road!
#check if we can win on our next move and take that chance
Pwinning = isNextWin(board,identity1,possibilities)
Cwinning = isNextWin(board,identity2,possibilities)
if Cwinning:
choice = Cwinning-1
elif Pwinning:
choice = Pwinning-1
else:
if possibilities:
choice = choose(possibilities)
board[choice]=identity2
displayBoard(board)
def main():
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
identity1,identity2 = playerInput()
Turn = randint(1,2)
displayBoard(board)
if Turn==1:
print('Player Goes First!')
else: print('Computer Goes First!')
while not (won(board,identity1) or won(board,identity2)):
if Turn==1:
print('Player:')
play(identity1,board)
if won(board,identity1):
print('Player won!')
again = wannaPlay()
Turn=2
else:
print('Computer:')
RandomMov(identity1,identity2,board)
if won(board,identity2):
print('Computer won!')
again = wannaPlay()
Turn=1
draw = all(list(map(lambda x: x != ' ',board)))
if draw:
print("Draw!")
again = wannaPlay()
try:
if again:
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
Turn = randint(1,2)
del again
displayBoard(board)
else:
break
except NameError:
pass
if __name__=="__main__":
main() |
##############################
## 2 # COMMAND LINE PARSING ## -> @CMD <-
##############################
import sys, logging, os, inspect
import DOC
def str2atom(a):
""" Helper function to parse atom strings given on the command line:
resid, resname/resid, chain/resname/resid, resname/resid/atom,
chain/resname/resid/atom, chain//resid, chain/resname/atom """
a = a.split("/")
if len(a) == 1: # Only a residue number:
return (None, None, int(a[0]), None)
if len(a) == 2: # Residue name and number (CYS/123):
return (None, a[0], int(a[1]), None)
if len(a) == 3:
if a[2].isdigit(): # Chain, residue name, residue number
return (None, a[1], int(a[2]), a[0])
else: # Residue name, residue number, atom name
return (a[2], a[0], int(a[1]), None)
return (a[3], a[1], int(a[2]), a[0])
def option_parser(args, options, lists, version=0):
# Check whether there is a request for help
if '-h' in args or '--help' in args:
DOC.help()
# Convert the option list to a dictionary, discarding all comments
options = dict([i for i in options if not type(i) == str])
# This information we would like to print to some files,
# so let's put it in our information class
options['Version'] = version
options['Arguments'] = args[:]
while args:
ar = args.pop(0)
options[ar].setvalue([args.pop(0) for i in range(options[ar].num)])
## LOGGING ##
# Set the log level and communicate which options are set and what is happening
# If 'Verbose' is set, change the logger level
logLevel = options["-v"] and logging.DEBUG or logging.INFO
logging.basicConfig(format='%(levelname)-7s %(message)s', level=logLevel)
logging.info('MARTINIZE, script version %s'%version)
logging.info('If you use this script please cite:')
logging.info('de Jong et al., J. Chem. Theory Comput., 2013, DOI:10.1021/ct300646g')
# To make the program flexible, the forcefield parameters are defined
# for multiple forcefield. We first check for a FF file in the current directory.
# Next we check for the FF in globals (for catenated scripts).
# Next we check in at the location of the script and the subdiretory FF.
try:
options['ForceField'] = globals()[options['-ff'].value.lower()]()
except KeyError:
try:
_tmp = __import__(options['-ff'].value.lower()+"_ff")
options['ForceField'] = getattr(_tmp, options['-ff'].value.lower())()
except ImportError:
try:
# We add the directory where the script resides and a possible "ForceFields" directory to the search path
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.dirname(inspect.getfile(inspect.currentframe())))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.dirname(inspect.getfile(inspect.currentframe()))) + "/ForceFields"
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
_tmp = __import__(options['-ff'].value.lower()+"_ff")
options['ForceField'] = getattr(_tmp, options['-ff'].value.lower())()
except:
logging.error("Forcefield '%s' can not be loaded." % (options['-ff']))
sys.exit()
# if os.path.exists(options['-ff'].value.lower()+'_ff.py'):
# _tmp = __import__(options['-ff'].value.lower()+"_ff")
# options['ForceField'] = getattr(_tmp, options['-ff'].value.lower())()
# elif os.path.exists('ForceFields/'+options['-ff'].value.lower()+'_ff.py'):
# _tmp = __import__("ForceFields."+options['-ff'].value.lower()+'_ff',fromlist="ForceFields")
# options['ForceField'] = getattr(_tmp, options['-ff'].value.lower())()
# elif options['-ff'].value.lower() in globals():
# options['ForceField'] = globals()[options['-ff'].value.lower()]()
# else:
# logging.error("Forcefield '%s' can not be found."%(options['-ff']))
# sys.exit()
#except:
# logging.error("Forcefield '%s' can not be loaded."%(options['-ff']))
# sys.exit()
# Process the raw options from the command line
# Boolean options are set to more intuitive variables
options['Collagen'] = options['-collagen']
options['chHIS'] = options['-his']
options['ChargesAtBreaks'] = options['-cb']
options['NeutralTermini'] = options['-nt']
options['ExtendedDihedrals'] = options['-ed']
options['RetainHETATM'] = False # options['-hetatm']
options['SeparateTop'] = options['-sep']
options['MixedChains'] = False # options['-mixed']
options['ElasticNetwork'] = options['-elastic']
# Parsing of some other options into variables
options['ElasticMaximumForce'] = options['-ef'].value
options['ElasticMinimumForce'] = options['-em'].value
options['ElasticLowerBound'] = options['-el'].value
options['ElasticUpperBound'] = options['-eu'].value
options['ElasticDecayFactor'] = options['-ea'].value
options['ElasticDecayPower'] = options['-ep'].value
options['ElasticBeads'] = options['-eb'].value.split(',')
options['PosResForce'] = options['-pf'].value
options['PosRes'] = [i.lower() for i in options['-p'].value.split(",")]
if "none" in options['PosRes']: options['PosRes'] = []
if "backbone" in options['PosRes']: options['PosRes'].append("BB")
if options['ForceField'].ElasticNetwork:
# Some forcefields, like elnedyn, always use an elatic network.
# This is set in the forcefield file, with the parameter ElasticNetwork.
options['ElasticNetwork'] = True
# Merges, links and cystines
options['mergeList'] = "all" in lists['merges'] and ["all"] or [i.split(",") for i in lists['merges']]
# Process links
linkList = []
linkListCG = []
for i in lists['links']:
ln = i.split(",")
a, b = str2atom(ln[0]), str2atom(ln[1])
if len(ln) > 3: # Bond with given length and force constant
bl, fc = (ln[2] and float(ln[2]) or None, float(ln[3]))
elif len(a) == 3: # Constraint at given distance
bl, fc = float(a[2]), None
else: # Constraint at distance in structure
bl, fc = None, None
# Store the link, but do not list the atom name in the
# atomistic link list. Otherwise it will not get noticed
# as a valid link when checking for merging chains
linkList.append(((None, a[1], a[2], a[3]), (None, b[1], b[2], b[3])))
linkListCG.append((a, b, bl, fc))
# Cystines
# This should be done for all special bonds listed in the _special_ dictionary
CystineCheckBonds = False # By default, do not detect cystine bridges
CystineMaxDist2 = (10*0.22)**2 # Maximum distance (A) for detection of SS bonds
for i in lists['cystines']:
if i.lower() == "auto":
CystineCheckBonds = True
elif i.replace(".", "").isdigit():
CystineCheckBonds = True
CystineMaxDist2 = (10*float(i))**2
else:
# This item should be a pair of cysteines
cysA, cysB = [str2atom(j) for j in i.split(",")]
# Internally we handle the residue number shifted by ord(' ')<<20.
# We have to add this to the cys-residue numbers given here as well.
constant = 32 << 20
linkList.append((("SG", "CYS", cysA[2]+constant, cysA[3]),
("SG", "CYS", cysB[2]+constant, cysB[3])))
linkListCG.append((("SC1", "CYS", cysA[2]+constant, cysA[3]),
("SC1", "CYS", cysB[2]+constant, cysB[3]), -1, -1))
# Now we have done everything to it, we can add Link/cystine related stuff to options
# 'multi' is not stored anywhere else, so that we also add
options['linkList'] = linkList
options['linkListCG'] = linkListCG
options['CystineCheckBonds'] = CystineCheckBonds
options['CystineMaxDist2'] = CystineMaxDist2
options['multi'] = lists['multi']
logging.info("Chain termini will%s be charged"%(options['NeutralTermini'] and " not" or ""))
logging.info("Residues at chain brakes will%s be charged"%((not options['ChargesAtBreaks']) and " not" or ""))
if 'ForceField' in options:
logging.info("The %s forcefield will be used."%(options['ForceField'].name))
else:
logging.error("Forcefield '%s' has not been implemented."%(options['-ff']))
sys.exit()
if options['ExtendedDihedrals']:
logging.info('Dihedrals will be used for extended regions. (Elastic bonds may be more stable)')
else:
logging.info('Local elastic bonds will be used for extended regions.')
if options['PosRes']:
logging.info("Position restraints will be generated.")
logging.warning("Position restraints are only enabled if -DPOSRES is set in the MDP file")
if options['MixedChains']:
logging.warning("So far no parameters for mixed chains are available. This might crash the program!")
if options['RetainHETATM']:
logging.warning("I don't know how to handle HETATMs. This will probably crash the program.")
return options
|
#!/usr/bin/env python3
# Head ends here
def next_move(posr, posc, board):
if board[posr][posc] == 'd':
output = "CLEAN"
elif posr % 2 == 0:
if posc < 4:
output = "RIGHT"
else:
output = "DOWN"
elif posr % 2 == 1:
if posc > 0:
output = "LEFT"
else:
output = "DOWN"
else:
output = "I don't know what to do."
print(output)
# Tail starts here
if __name__ == "__main__":
pos = [int(i) for i in input().strip().split()]
board = [[j for j in input().strip()] for i in range(5)]
next_move(pos[0], pos[1], board)
|
#!/usr/bin/env python3
import re
tests = int(input())
excel = re.compile("^([A-z]+)(\d+)$")
rc = re.compile("^R(\d+)C(\d+)$")
for test in range(tests):
coords = input()
if excel.match(coords):
print("Case {0} is excel.".format(test))
elif rc.match(coords):
print("Case {0} is rc.".format(test))
else:
print("Could not determine type for case {0}".format(test))
|
#!/usr/bin/env python3
MAX = 2000000
def applySieve(prime, sieve):
return [x for x in sieve if x % prime != 0]
prime = 3
sum_primes = 5
sieve = list(range(3, MAX + 1, 2))
while prime < MAX:
sieve = applySieve(prime, sieve)
try:
prime = sieve[0]
except IndexError:
break
sum_primes += prime
print("{0}: {1}".format(prime, sum_primes))
|
num1 = 10
num2 = 30
num3 = 5
if num1>num2 and num1>num3:
print(num1)
elif num2>num1 and num2>num3:
print(num2)
else:
print(num3)
#=============check vowel or consonant =================
ch = 'a'
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':
print("vowel.")
else:
print("Consonant.") |
num1 = {1,2,3,4,5}
num2 = set([4,5,6])
num2.add(7)
num2.remove(7)
print(7 in num2)
print(num1 | num2)
print(num1 & num2)
print(num1 - num2)
print(num2 - num1) |
num =5
if num%2 == 0:
print("Even number..")
elif num%3==0:
print("divisible by 3")
else:
print("Odd number")
if 7>3:
if 7>8:
print("Hi")
else:
print("Hello")
num1 = 30
num2 = 20
num3 = 40
if num1 > num2:
if num1 > num3:
print(num1)
else:
print(num3)
if num2 > num1:
if num2>num3:
print(num2)
else:
print(num3)
""""
Ternary operator
"""
a = -20
b = 10
print(a if a>b else b)
|
# map function()
def square(x):
return x*x
num = [10,20,30,40]
a = list(map(square,num))
print(a)
# filter()
num = [1,2,3,4,5]
result = list(filter(lambda x:x%2==0,num))
print(result) |
#Introduction to Function
def add(x,y):
sum = x + y
print(sum)
def addition(x,y,z):
sum = x + y + z
print(sum)
add(5,10)
addition(5,10,15)
|
import itertools
from collections import deque
def part2():
stream = []
with open("in.txt") as f:
for line in f:
stream.append(line.strip())
def is_possible(previous_items, item):
# Returns the boolean answer to the query "can the given item occur in the stream after the given list of previous items?"
for i in itertools.combinations(previous_items, 2):
if sum(map(int, i)) == int(item):
return True
return False
def get_subarray_with_anomaly_sum(stream, anomaly):
# Given the stream and anomaly, return the contiguous subarray of elements that sum up to the anomaly value
low, high, L = 0, 1, len(stream)
running_sum = sum(map(int, stream[low : high + 1]))
while high < L:
if running_sum == anomaly:
return list(map(int, stream[low : high + 1]))
if running_sum < anomaly:
high += 1
if high < L:
running_sum = running_sum + int(stream[high])
if running_sum > anomaly:
running_sum = running_sum - int(stream[low])
low += 1
print(f"No subarray found that sums up to anomaly value of {anomaly}")
preamble_size = 25
preamble = deque(stream[:preamble_size])
# print(preamble)
for i in stream[preamble_size:]:
if is_possible(preamble, i):
preamble.popleft()
preamble.append(i)
else:
anomaly = int(i)
break
x = get_subarray_with_anomaly_sum(stream, anomaly)
print(min(x) + max(x))
part2()
|
import sys
def part2():
program = []
with open("in.txt") as f:
for line in f:
program.append(line.strip())
# Append a custom instruction to the program to signify end of execution has been reached
program.append("end +0")
def run_instruction(program, index, acc):
# Given a program, index and accumulator, return the new index and accumulator values after running the given instruction
instruction, val = program[index].split()
val = int(val)
if instruction == "nop":
return index + 1, acc
if instruction == "acc":
return index + 1, acc + val
if instruction == "jmp":
return index + val, acc
if instruction == "end":
return None, acc
def try_running(program):
# Run the given program. Return None if the program gets stuck in an infinite loop.
# If the supplied program terminates, print the accumulator value and exit
# instrction pointer and accumulator
ip, acc = 0, 0
# set of already visited instructions
visited = set()
while ip is not None and ip not in visited:
visited.add(ip)
ip, acc = run_instruction(program, ip, acc)
if ip is None:
# Program terminated successfully!
print(acc)
sys.exit(1)
i = len(program) - 1
while i >= 0:
if "nop" in program[i]:
program[i] = program[i].replace("nop", "jmp")
try_running(program)
program[i] = program[i].replace("jmp", "nop")
elif "jmp" in program[i]:
program[i] = program[i].replace("jmp", "nop")
try_running(program)
program[i] = program[i].replace("nop", "jmp")
i = i - 1
part2()
|
from collections import Counter, deque
def play(a, b):
while len(a) > 0 and len(b) > 0:
if a[0] < b[0]:
b.append(b.popleft())
b.append(a.popleft())
else:
a.append(a.popleft())
a.append(b.popleft())
return b if len(b) else a
def score(x):
return sum(i * j for i, j in zip(range(len(x), 0, -1), x))
def part1():
p1, p2 = open("in.txt").read().strip().split("\n\n")
p1 = deque(map(int, p1.strip().split("\n")[1:]))
p2 = deque(map(int, p2.strip().split("\n")[1:]))
print(score(play(p1, p2)))
part1()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
####################################
# AES in ECB mode - set 1/ chall 7 #
####################################
from base64 import b64decode
from Crypto.Cipher import AES
key = 'YELLOW SUBMARINE'
with open('file3.txt', 'r') as f:
cipher = b64decode(f.read())
def decryptAES_ECB(cipher):
aes = AES.new(key, AES.MODE_ECB)
return aes.decrypt(cipher)
print decryptAES_ECB(cipher)
#_EOF |
import sys
import board
import operator
class Player:
BOARD_NAME = 'board.txt'
__board = None
playerNumber = None
def __init__(self, playerNumber, remainingTime):
self.__board = board.readBoard(self.BOARD_NAME)
self.playerNumber = playerNumber
def playGreedyAddStrategy(self):
# Moves are (location, weight, torque1, torque2)
moves = self.__board.getPlayableAddMoves(self.playerNumber)
# Sort the torques so that (torque1, torque2) torque1 goes from highest to lowest. This means of
# course that torque2 will go fomr lowest to highest.
sortedMoves = sorted(moves, key = operator.itemgetter(2), reverse = True)
# Remove the torques
sortedMoves = [(x,y) for (x,y,a,b) in sortedMoves]
if len(sortedMoves) > 0:
bestMove = self.balancePlayerOneTorque(sortedMoves)
else:
bestMove = self.playRandomAddStrategy()
return bestMove
def balancePlayerOneTorque(self, sortedMoves):
(playerOneTorque1, playerOneTorque2) = self.__board.getTorque(self.__board.playerOneMoves)
if self.playerNumber == 1:
# We want to balance the weights that player one placed as much as possible.
if abs(playerOneTorque1) > abs(playerOneTorque2):
bestMove = sortedMoves[-1]
else:
bestMove = sortedMoves[0]
else:
# Otherwise we want to unbalance the weights that player one placed as much as possible.
bestMove = sortedMoves[0]
return bestMove
def playRandomAddStrategy(self):
weight = self.__board.getRandomWeightToAdd(self.playerNumber)
location = self.__board.getRandomUnoccupiedLocation()
bestMove = (location, weight)
return bestMove
def playGreedyRemoveStrategy(self):
remainingPlayerOneMoves = set(self.__board.playerOneMoves)
# This tells us to not remove player two's weights if we are player one, unless we are forced
# to do so.
if remainingPlayerOneMoves == {0}:
# This tells us to not remove player two's weights if we are player one, unless we are forced
# to do so.
playerNumber = None
else:
playerNumber = self.playerNumber
# Moves are (location, weight, torque1, torque2)
moves = self.__board.getPlayableRemoveMoves(playerNumber)
# Sort the torques so that (torque1, torque2) torque1 goes from highest to lowest. This means of
# course that torque2 will go fomr lowest to highest.
sortedMoves = sorted(moves, key = operator.itemgetter(2), reverse = True)
# Remove the torques
sortedMoves = [(x,y) for (x,y,a,b) in sortedMoves]
if len(sortedMoves) > 0:
#bestMove = sortedMoves[0]
bestMove = self.balancePlayerOneTorque(sortedMoves)
else:
bestMove = self.playRandomRemoveStrategy(playerNumber)
return bestMove
def playRandomRemoveStrategy(self, playerNumber):
location = self.__board.getRandomOccupiedLocation(playerNumber)
weight = self.__board.getWeightAtLocation(location)
bestMove = (location, weight)
return bestMove
def play(self, mode):
if mode == 1:
(location, weight) = self.playGreedyAddStrategy()
elif mode == 2:
(location, weight) = self.playGreedyRemoveStrategy()
else:
raise Exception("Invalid Mode")
return (location, weight)
if __name__ == '__main__':
if len(sys.argv) < 4:
remainingTime = float('Inf')
else:
remainingTime = float(sys.argv[3])
mode = int(sys.argv[1])
playerNumber = int(sys.argv[2])
thisPlayer = Player(playerNumber, remainingTime)
(location, weight) = thisPlayer.play(mode)
print(str(location) + ' ' + str(weight))
|
# --------------
import pandas as pd
import numpy as np
import math
#Code starts here
class complex_numbers:
'''
The Complex Number Class
Attributes:
real: real part of complex number
imag: imaginary part of complex number
'''
def __init__(self,real,imag):
self.real=real
self.imag=imag
def __repr__(self):
if self.real == 0.0 and self.imag == 0.0:
return "0.00"
if self.real == 0:
return "%.2fi" % self.imag
if self.imag == 0:
return "%.2f" % self.real
return "%.2f %s %.2fi" % (self.real, "+" if self.imag >= 0 else "-", abs(self.imag))
def __add__(self,other):
'''
'+' operator overloading
complex number addition
params:
other:- other complex number for addition
return:
result of addition
'''
a=self.real+other.real
b=self.imag+other.imag
return complex_numbers(a,b)
def __sub__(self,other):
'''
'-' operator overloading
complex number subtraction
params:
other:- other complex number for subtraction
return:
result of subtraction
'''
a=self.real-other.real
b=self.imag-other.imag
return complex_numbers(a,b)
def __mul__(self,other):
'''
'*' operator overloading
complex number multiplication
params:
other:- other complex number for multiplication
return:
result of multiplication
'''
a=self.real*other.real - self.imag*other.imag
b=self.real*other.imag + self.imag*other.real
return complex_numbers(a,b)
def __truediv__(self,other):
'''
'/' operator overloading
complex number division
params:
other:- other complex number for division
return:
result of division
'''
a=(self.real*other.real+self.imag*other.imag)/(other.real*other.real+other.imag*other.imag)
b=(self.imag*other.real-self.real*other.imag)/(other.real*other.real+other.imag*other.imag)
return complex_numbers(a,b)
def absolute(self):
'''
Absolute value of Complex number
return:
absolute value
'''
return np.sqrt((self.real**2)+(self.imag**2))
def argument(self):
'''
argument value of Complex number
return:
argument value
'''
return math.degrees(math.atan(self.imag/self.real))
def conjugate(self):
'''
conjugate value of Complex number
return:
conjugate value
'''
a,b=self.real,self.imag*-1
return complex_numbers(a,b)
comp_1=complex_numbers(3,5)
print(comp_1)
comp_2=complex_numbers(4,4)
print(comp_2)
comp_sum=comp_1+comp_2
print(comp_sum)
comp_diff=comp_1-comp_2
print(comp_diff)
comp_prod=comp_1*comp_2
print(comp_prod)
comp_quot=comp_1/comp_2
print(comp_quot)
comp_abs=comp_1.absolute()
print(comp_abs)
comp_conj=comp_1.conjugate()
print(comp_conj)
comp_arg=comp_1.argument()
print(comp_arg)
|
# The function is_triangle takes three integer parameters, a, b, and c, and
# and prints either 'Yes' or 'No,' depending on whether or not a triangle can
# be formed from lines with the given integer lengths.
def is_triangle(a, b, c):
if a + b < c or b + c < a or a + c < b:
print 'No'
else:
print 'Yes'
# The function get_input_and_check_triangle prompts the user for input values for
# a, b, and c, and converts the input into integers, and uses check_triangle to
# determine whether or not a triangle can be formed from the given values.
def get_input_and_check_triangle():
a = int(raw_input("Please enter a positive integer values for 'a.':\n"))
b = int(raw_input("Please enter a positive integer values for 'b.':\n"))
c = int(raw_input("Please enter a positive integer values for 'c.':\n"))
is_triangle(a, b, c)
get_input_and_check_triangle()
|
# The funciton right_justify takes a string, s, as a parameter, and prints the
# string with enough leading spaces so that the last letter of the string is in
# column 70 of the output display.
def right_justify(s):
display_width = 70
string_length = len(s)
leading_spaces = (70 - string_length) * ' '
print leading_spaces + s
right_justify('allen') |
# The function square_root takes an integer, a, as a parameter,
# and returns an estimate of the square root of a.
def square_root(a):
x = a / 2
epsilon = 0.000001
while True:
print x
y = (x + (a / x)) / 2
if abs(y - x) < epsilon:
break
x = y
print square_root(25) |
from swampy.TurtleWorld import *
from math import pi
world = TurtleWorld()
bob = Turtle()
print bob
bob.delay = 0.1
# The function polygon takes a parameter named t, which is a turtle,
# a parameter named length, which is the length of a side, and a
# a parameter n, which is the number of sides. It uses the turtle to
# draw a polygon with n sides of length length.
def polygon(t, length, n):
degrees = 360.0 / n
for i in range(n):
fd(t, length)
lt(t, degrees)
# The function circle takes a turtle, t, and radius, r, as parameters, and
# draws an approximate circle by invoking polygon with an appropriate length
# and number of sides.
def circle(t, r):
length = 2 * pi * r
polygon(t, length, 100)
circle(bob, 0.5)
circle(bob, 0.75)
circle(bob, 1)
|
# The function histogram takes a string as a parameter, and returns
# a histogram of the characters in the string.
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
# The function has_duplicates takes a list as a parameter, and returns
# True if there is any element that appears more than once.
def has_duplicates(list):
dictionary = histogram(list)
for key in dictionary:
if dictionary[key] > 1:
return True
return False
print has_duplicates([1, 2, 4, 2, 1])
print has_duplicates(['car', 'bus', 'train'])
print has_duplicates([1, 2, 3, 4, 5])
print has_duplicates(['car', 'car', 'van']) |
print("你好,世界")
# 默认情况下python被视为UTF-8编码
if 3 < 10:
print("判断正确")
# for item in [1,3,4,5,6]:
# print(item)
# for i in range(8):
# print(i, end=' ')
# print(range(10)) #这是一个对象,并不是一个列表,可迭代
# try:
# pass
# except ValueError:
# pass
# except OSError:
# pass
# finally:
# pass
def fun(arguments):
pass
class ClassName:
pass
class FirstClass:
className = '这是一个类变量' #实例之间共享的变量
# 类初始化函数
def __init__(self):
self.name = '王雪迪'
self.age = '23'
c = FirstClass()
print(c.name + " " + c.age)
|
s=input()
l=list(s)
a=''
for i in l:
if i.isnumeric():
a+=i
print(a)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
from functools import reduce
count = itertools.count(1)
for i in range(5):
print(next(count))
cycle = itertools.cycle('ABC')
for i in range(5):
print(next(cycle))
repeat = itertools.repeat('ABC')
for i in range(5):
print(next(repeat))
takewhile = itertools.takewhile(lambda x: x < 10, itertools.count(1))
for i in takewhile:
print(i)
chain = itertools.chain('ABC', 'XYZ')
for i in chain:
print(i)
group = itertools.groupby('AaaBBbCcC', lambda c: c.upper())
for k, g in group:
print(k, list(g))
def pi(N):
""" 计算pi的值 """
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
odd = itertools.count(1, 2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
odd_n = itertools.takewhile(lambda x: x <= 2 * N - 1, odd)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
sign = itertools.cycle((1, -1))
series = map(lambda x, y: 4 * x / y, sign, odd_n)
# step 4: 求和:
return reduce(lambda x, y: x + y, series)
# 测试:
print(pi(10))
print(pi(100))
print(pi(1000))
print(pi(10000))
assert 3.04 < pi(10) < 3.05
assert 3.13 < pi(100) < 3.14
assert 3.140 < pi(1000) < 3.141
assert 3.1414 < pi(10000) < 3.1415
print('ok')
|
x = 1
y = 2
#
# print(x > 1)
# print(y > 1)
#
# # #and,or, not
# print(x > 1 and y > 1)
# print(x > 1 or y > 1)
# print(not x > 1)
# print(not y > 1)
print(True and True)
print(True or True)
print(not True)
print(False and False)
print(True or True)
print(not False)
print(True and False)
print(True or False)
name = 'John'
age = 13
is_married = False
if age > 18 or is_married == False:
print('Hi {}! You can find a girl of yuor dream here!'.format(name))
|
def tiger():
print "wow,the fastest animal.\n"
def cat():
print "The cutest animal\n"
def monkey():
print "The smartest animal\n"
def dog():
print"The most loyal animal\n"
def horse():
print "The royal animal\n"
print "#####Welcome to Short GK ! \n"
print "Animals are the dearest creation of god\n"
print "Here are 5 animals listed below.\n"
print "1. Tiger\n"
print "2. Cat\n"
print "3. Monkey\n"
print "4. Dog\n"
print "5. Horse\n"
print "Choose one of them.\n"
animal = input("> ")
if animal == 1:
tiger()
elif animal == 2:
cat()
elif animal == 3:
monkey()
elif animal == 4:
dog()
else:
horse()
|
def longest(tree):
return _helper(tree)[0]
def _helper(tree):
if tree == []:
return 0, 0
else:
l, i, r = tree
l_result = _helper(l)
r_result = _helper(r)
combined_depths = l_result[1] + r_result[1]
if combined_depths > l_result[0] and combined_depths > r_result[0]:
path = combined_depths
elif l_result[0] > r_result[0]:
path = l_result[0]
else:
path = r_result[0]
if l_result[1] > r_result[1]:
return path, l_result[1] + 1
else:
return path, r_result[1] + 1
|
file=open("file.txt","a") #file is created
file.write("Welcome To Computer Department\n")
file=open("file.txt","r") #open it to read mode
newFile=open("newFile.txt","a") #new file created
for i in file: #to copy text from one file to another
print("file.txt content")
print(i)
print("newFile.txt content")
for j in i:
newFile.write(j)
newFile=open("newFile.txt","r")
print(newFile.read())
|
from numpy import *
def compute_error_for_given_points(m, b, points):
totalError = 0
for point in points:
totalError += (point[1] - (m * point[0] + b))**2
return totalError / float(size(points))
def step_gradient(current_b, current_m, points, learning_rate):
gradient_m = 0
gradient_b = 0
N = float(len(points))
for point in points:
x = point[0]
y = point[1]
gradient_m += -(2/N) * x *(y - ((current_m * x) + current_b))
gradient_b += -(2/N) * (y - ((current_m * x) + current_b))
new_b = current_b - (learning_rate * gradient_b)
new_m = current_m - (learning_rate * gradient_m)
return [ new_b, new_m]
def gradient_descent_runner(points, initial_b, initial_m,
learning_rate, num_iterations ):
b = initial_b
m = initial_m
for i in range(num_iterations):
b,m = step_gradient(b, m, array(points), learning_rate)
return [b, m]
def run():
points = genfromtxt('data.csv', delimiter = ',')
#hyperparameters
learning_rate = 0.0001
#y = mx + b
initial_b = 0
initial_m = 0
num_iterations = 1000
print("Starting gradient descent at b = {0}, m = {1}, error = {2}".format(
initial_b, initial_m,
compute_error_for_given_points(initial_b, initial_m, points)))
print("Running...")
[b, m] = gradient_descent_runner(points, initial_b, initial_m,
learning_rate, num_iterations )
print("After {0} iterations b = {1}, m = {2}, error = {3}".format(
num_iterations, b, m, compute_error_for_given_points(b, m, points)))
if __name__ == '__main__':
run() |
"""
Item module for the McGyver game
It contain the class 'Item'
"""
from random import randrange
import pygame
from .util import load_image
from .game_config import CELL_WIDTH, CELL_HEIGHT
# For now, there is no public methods for 'Item' so we disable warnings for pylint
class Item: # pylint: disable=too-few-public-methods
"""
Define an item in the game
And define a list of all items
"""
# List of items
items = list()
def __init__(self, image_name, maze_cells):
"""
Create each attributes for the item:
- 'image'
- 'position'
"""
self.image = load_image(image_name)
# Create 'image' with transparency
if "ether" in image_name:
self.image.set_colorkey((1, 1, 1))
elif "needle" in image_name:
self.image.set_colorkey((0, 0, 0))
else:
self.image.set_colorkey((255, 255, 255))
# Transform images to fit cell width and height
self.image = pygame.transform.scale(self.image, (CELL_WIDTH, CELL_HEIGHT))
# Define item position
self.maze_cells = maze_cells
self.cell = False
self._find_position()
Item.items.append(self)
def _find_position(self):
"""
Private method to find a position for each items
"""
while not self.cell:
self.cell = self.maze_cells[randrange(len(self.maze_cells))]
# If the cell is'nt a floor
if self.cell["name"] != "floor":
self.cell = False
# If there already items stored we compare them
if Item.items:
for item in Item.items:
# If its the same cell, we rand choose another one
if self.cell == item.cell:
self.cell = False
self.rect = self.cell["rect"]
if __name__ == "__main__":
print("Error, not the main file.")
|
import sys
def main():
args = sys.argv
if len(args) < 2:
print(f'{args[0]}: file name not given')
return
for i in range(len(args)):
if i == 0:
continue
do_cat(args[i])
def do_cat(filename):
try:
data = open(filename, "r")
for line in data:
print(line, end="")
except:
print(f'{filename} is not file');
else:
data.close()
if __name__ == "__main__":
main()
|
import math
import random
#github test
def searchHelp(a,v,l,h):
m=math.floor(((h-l)/2))
mPrime=m+l
printSearch(a,v,l,h,m,mPrime)
if l>h:
return False
elif v==a[mPrime]:
return True
elif v<a[mPrime]:
return searchHelp(a,v,l,mPrime-1)
else:
return searchHelp(a,v,mPrime+1,h)
def printSearch(a,v,l,h,m,mPrime):
i=0
for num in a:
if num == v:
print(" "+'\033[41m'+str(v)+'\033[0m',end="")
elif l==i:
print(" "+'\033[42m'+str(l)+'\033[0m',end="")
elif m==num:
print(" "+'\033[43m'+str(m)+'\033[0m',end="")
elif mPrime==num:
print(" "+'\033[45m'+str(mPrime)+'\033[0m',end="")
elif h == i:
print(" "+'\33[104m'+str(h)+'\033[0m',end="")
else:
print(' '+str(num),end="")
i+=1
print("")
def search(a,v):
return searchHelp(a,v,0,len(a)-1)
def searchWhile(a,v):
l=0
h=len(a)-1
while l<=h:
m = math.floor(((h - l) / 2))
mPrime = m + l
printSearch(a, v, l, h, m, mPrime)
if v == a[mPrime]:
return True
elif v < a[mPrime]:
h= mPrime - 1
else:
l= mPrime + 1
return False
def sumComp(n1,n2,x):
return (n1+n2)==x
def printSearchSum(a,v,l,h,sumC):
i=0
for num in a:
if l==i:
print(" "+'\033[45m'+str(num)+'\033[0m',end="")
elif h == i:
print(" "+'\33[46m'+str(num)+'\033[0m',end="")
else:
print(' '+str(num),end="")
i+=1
if sumC== v:
print(" = " + '\033[41m' + str(sumC) + '\033[0m')
else:
print(" = "+'\033[43m'+str(sumC)+'\033[0m')
def sortedHasSumHelp(a,v,l,h,acc):
sumC=a[l]+a[h]
printSearchSum(a,v,l,h,sumC)
if l > h:
return False , acc
elif v == sumC:
return True,l,h,acc
elif v < sumC:
return sortedHasSumHelp(a, v, l, h - 1,acc+1)
else:
return sortedHasSumHelp(a, v, l + 1, h,acc+1)
def sortedHasSum(s,x):
return sortedHasSumHelp(s,x,0,len(s)-1,0)
# found=False
# for num in s:
# for num2 in s[s.index(num)+1:]:
# print(num,num2)
# if num is not num2 and sumComp(num,num2,x):
# found=True
# #print(num,num2)
# return found
def hasSum(s,x):
return sortedHasSum(sorted(s),x)
def partition(a,l,h):
x=a[h]
i=l-1
j=l
while j<h:
if a[j]<=x:
i+=1
temp=a[i]
a[i]=a[j]
a[j]=temp
j+=1
temp = a[i+1]
a[i+1] = a[h]
a[h] = temp
return i+1
def quicksortHelper(a,l,h):
if l<h:
m=partition(a,l,h)
quicksortHelper(a,l,m-1)
quicksortHelper(a,m+1,h)
return a
def quicksort(a):
return quicksortHelper(a,0,len(a)-1)
def main():
a=[7,8,9,10,11,12,13,14,15,16,17,18,19,20]
#print(sortedHasSum(a, 25))
a=sorted(a, key = lambda x: random.random() )
print(a)
# for i in range(-10,10):x
# a.append(i)
#print(search(a,19))
#printColors()
#print(hasSum(a,25))
#print(searchWhile(a,5))
print(quicksort(a))
main() |
import datetime
class DataNode():
'''
Hold a key, value, and the time of most recent use.
'''
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
self.last_used_time = datetime.datetime.now()
def get(self):
'''
Return the current value and update the time
'''
self.last_used_time = datetime.datetime.now()
return self.value
def time_since_use(self):
'''
In seconds
'''
return (datetime.datetime.now() - self.last_used_time).seconds
class DLL():
'''
Doubly-Linked List
* ordered from most recently used (head) to least recently used (tail)
* when the list reaches MAX_SIZE, the least-recently used is evicted
* nodes can expire; if a node is not called within TIMEOUT, it and all
following nodes are deleted on the next get request
* iterable for debugging, testing
'''
def __init__(self, MAX_SIZE, TIMEOUT):
self.head = None
self.tail = None
self.size = 0
self.MAX_SIZE = MAX_SIZE
self.TIMEOUT = TIMEOUT
def __iter__(self):
self.current = self.head
return self
def __next__(self):
if self.current is None:
raise StopIteration
else:
result = self.current
self.current = self.current.next
return result
def add(self, key, value):
'''
Add a node to the head of the list.
'''
if self.size >= self.MAX_SIZE:
self.removeLRU()
new = DataNode(key, value)
self.size += 1
self.insert_at_head(new)
def insert_at_head(self, node):
'''
Place a node at the head of the list.
'''
if self.head is None:
self.head = node
self.head.next = None
self.head.prev = None
self.tail = self.head
else:
node.prev = None
node.next = self.head
node.next.prev = node
self.head = node
def removeLRU(self):
'''
Remove the least-recently used node (the tail).
'''
self.size -= 1;
self.tail = self.tail.prev
self.tail.next = None
def get(self, key):
'''
Returns: value of DataNode if found, otherwise None
If it hits a node that has timed out, it and all nodes after it are
deleted.
'''
# Empty list
if self.head is None:
return None
# Non-empty list
index = 0
for node in self:
if node.key == key:
# Move node to the front and return value
if node != self.head:
if node == self.tail:
node.prev.next = None
self.tail = node.prev
else:
node.next.prev = node.prev
node.prev.next = node.next
self.insert_at_head(node)
return node.get()
elif node.time_since_use() > self.TIMEOUT:
# All further entries are timed out
if node == self.head:
self.head = None
self.tail = None
else:
node.prev.next = None
self.tail = node.prev
self.size = index
return None
index += 1
|
list=[45,56,58,95,32,67,59]
total = sum(list)
print("Sum of all numbers in given list:" , total)
|
"""Calculates the average time of when a sensors turned on.
For example, to track your average bed time.
# Example `apps.yaml` config:
```
average_bed_time:
module: average_time
class: AverageTime
to_watch: input_boolean.sleep_mode
result_senor: sensor.average_sleep_time
from: "13:00"
to: "02:00"
```
"""
import cmath
import datetime
import math
from dateutil import tz
from dateutil.parser import isoparse, parse
import hassapi as hass
DEFAULT_TO_WATCH = "input_boolean.sleep_mode"
DEFAULT_TO_WATCH_STATE = "on"
DEFAULT_FROM_TIME = "19:00"
DEFAULT_TO_TIME = "02:00"
DEFAULT_RESULT_SENSOR = "sensor.average_sleep_time"
DEFAULTS = {
"to_watch": DEFAULT_TO_WATCH,
"to_watch_state": DEFAULT_TO_WATCH_STATE,
"from_time": DEFAULT_FROM_TIME,
"to_time": DEFAULT_TO_TIME,
"result_senor": DEFAULT_RESULT_SENSOR,
}
def in_between(now, start, end):
if start <= end:
return start <= now < end
else: # over midnight e.g., 23:30-04:15
return start <= now or now < end
def mean_angle(deg):
deg_imag = sum(cmath.rect(1, math.radians(d)) for d in deg) / len(deg)
argument = cmath.phase(deg_imag)
return math.degrees(argument)
def mean_time(times):
seconds = (t.second + t.minute * 60 + t.hour * 3600 for t in times)
day = 24 * 60 * 60
to_angles = [s * 360 / day for s in seconds]
mean_as_angle = mean_angle(to_angles)
mean_seconds = mean_as_angle * day / 360
if mean_seconds < 0:
mean_seconds += day
h, m = divmod(mean_seconds, 3600)
m, s = divmod(m, 60)
return f"{int(h):02d}:{int(m):02d}:{int(s):02d}"
class AverageTime(hass.Hass):
def initialize(self):
self.to_watch = self.args.get("to_watch", DEFAULT_TO_WATCH)
self.to_watch_state = self.args.get("to_watch_state", DEFAULT_TO_WATCH_STATE)
self.from_time = parse(self.args.get("from_time", DEFAULT_TO_WATCH)).time()
self.to_time = parse(self.args.get("to_time", DEFAULT_TO_WATCH)).time()
self.result_sensor = self.args.get("result_sensor", DEFAULT_RESULT_SENSOR)
self.tz = tz.gettz("Europe/Amsterdam")
# Update every time the sensor is updated
self.listen_state(self.start_cb, self.to_watch, new=self.to_watch_state)
# And update once this app is started
self.start()
def maybe_defaults(self, kwargs):
for key in set(DEFAULTS) | set(self.args):
if key in kwargs:
continue
elif key in self.args:
kwargs[key] = self.args[key]
else:
kwargs[key] = DEFAULTS[key]
def start_cb(self, entity, attribute, old, new, kwargs):
self.start()
def _times_on_day(self, days_ago):
start_of_today = datetime.datetime.now().replace(hour=0, minute=0, second=0)
start = start_of_today - datetime.timedelta(days=days_ago)
hist = self.get_history(entity_id=self.to_watch, start_time=start)
if len(hist) == 0:
return []
hist_filtered = [entry for entry in hist[0] if entry["state"] == self.to_watch_state]
times = [
isoparse(entry["last_changed"]).astimezone(self.tz).time()
for entry in hist_filtered
]
times_between = [
t for t in times if in_between(t, self.from_time, self.to_time)
]
return times_between
def start(self, **kwargs):
self.maybe_defaults(kwargs)
times = []
for days_ago in range(14):
times.extend(self._times_on_day(days_ago))
if not times:
return
average_time = mean_time(times)
self.set_state(self.result_sensor, state=average_time)
|
import unittest
from battleship import *
from ship import *
class BattleShipTestCase(unittest.TestCase):
def test_A_empty_grid(self):
rows = 2
cols = 4
bs = BattleShip(rows, cols)
bs.show_board_no_ships() # expect 2 rows 4 cols
def test_B_coordinate_conversions(self):
rows = 5
cols = 5
bs = BattleShip(rows, cols)
bs.show_board_no_ships()
zero_based_xy = bs.trans_to_python_coords('E1') # should yield (0, 4)
letter_based_xy = bs.trans_to_board_coords((0, 4)) # should yield 'E5'
self.assertEqual(zero_based_xy, (0, 4))
self.assertEqual(letter_based_xy, 'E1')
zero_based_xy = bs.trans_to_python_coords('A3') # should yield (2, 0)
letter_based_xy = bs.trans_to_board_coords((2, 0)) # should yield 'E5'
self.assertEqual(zero_based_xy, (2, 0))
self.assertEqual(letter_based_xy, 'A3')
def test_C_marked_position(self):
rows = 3
cols = 6
bs = BattleShip(rows, cols)
bs.mark_position('X', 'A1')
bs.mark_position('X', 'A2')
self.assertEqual(bs.board.grid[0][0], 'X')
self.assertEqual(bs.board.grid[1][0], '.')
bs.show_board_no_ships()
def test_D_desired_positions(self):
rows = 5
cols = 3
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
wanted = bs.desired_positions(s1) # calls desired_positions
self.assertEqual(wanted, [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)])
s2 = Ship.create_ship('submarine', 'A5', 'SE')
wanted = bs.desired_positions(s2) # calls desired_positions
self.assertEqual(wanted, [(4, 0), (3, 0), (2, 0)])
s3 = Ship.create_ship('destroyer', 'B1', 'SS')
wanted = bs.desired_positions(s3) # calls desired_positions
self.assertEqual(wanted, [(0, 1), (0, 0)])
s4 = Ship.create_ship('submarine', 'A1', 'SW')
wanted = bs.desired_positions(s4) # calls desired_positions
self.assertEqual(wanted, [(0, 0), (1, 0), (2, 0)])
def test_E_fire_missile(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
bs.place_ship(s1)
bs.show_board_with_ships()
print(bs.fire_missile('A2'))
print(bs.fire_missile('A1'))
bs.show_board_with_ships()
print(bs.fire_missile('B1'))
bs.show_board_with_ships()
print(bs.fire_missile('C1'))
bs.show_board_with_ships()
print(bs.fire_missile('D1'))
bs.show_board_with_ships()
print(bs.fire_missile('E1'))
bs.show_board_with_ships() # game won at this point
def test_F_random_shots(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
bs.place_ship(s1)
bs.show_board_with_ships()
print(bs.random_shot())
print(bs.fire_missile('A1'))
def test_G_play_to_sink(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
bs.place_ship(s1)
result = 'continue'
while result != 'hit':
shot_result = bs.random_shot()
result = shot_result[0]
shot_xy = shot_result[1]
print('Hit with shot at {}'.format(shot_xy))
def test_H_move(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
pos_n = bs.move((1, 1), 'north')
pos_s = bs.move((1, 1), 'south')
pos_e = bs.move((1, 1), 'east')
pos_w = bs.move((1, 1), 'west')
print(pos_n, pos_s, pos_e, pos_w)
def test_I_target_shot(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
bs.place_ship(s1)
shot_result = bs.fire_missile('C1')
bs.target_shots(shot_result)
def test_J_play_to_sink(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
bs.place_ship(s1)
bs.play_to_sink()
def test_H_play_to_win(self):
rows, cols = 5, 5
bs = BattleShip(rows, cols)
s1 = Ship.create_ship('carrier', 'A1', 'SN')
bs.place_ship(s1)
bs.play_to_win()
if __name__ == '__main__':
unittest.main()
|
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--binary", action="store_true",
help="convert to binary")
parser.add_argument("filename", type=str,
help="the filename to convert")
args = parser.parse_args()
filename = args.filename
is_binary = args.binary
with open(filename, "rb") as f:
data = f.read()
for i in range(0, len(data), 2):
byte2 = data[i]
byte1 = 0 if i + 1 == len(data) else data[i + 1]
if is_binary:
print("%s%s" %\
(bin(byte1)[2:].zfill(8),
bin(byte2)[2:].zfill(8)))
else:
print("%s%s" %\
(hex(byte1)[2:].zfill(2),
hex(byte2)[2:].zfill(2)))
if __name__ == "__main__":
main()
|
# clock2.py - Creates clock2.gif, and animated GIF of a clock (minutes only) showing two rounding modes
# Maarten Pennings 2020 feb 29
import math
from PIL import Image, ImageDraw, ImageFont
# Angle factor (degree to radian)
Rad = 2*math.pi/360
# Size of the generated image
img_width= 800
img_height= 500
# Clock size
clk_radius= 200
clk_hand1_short= 30*clk_radius/100 # hand1 is the "real clock" (red in drawing)
clk_hand1_long= 75*clk_radius/100
clk_dial_radius= 80*clk_radius/100
clk_tick_size= 8*clk_radius/100
clk_hand2_short= 85*clk_radius/100 # hand2 is the clock quatized to 5 min intervals (green in drawing)
clk_hand2_long= 99*clk_radius/100
# Font, might need adaptation on you system
fnt = ImageFont.truetype('C:\Windows\Fonts\consola.ttf', 40)
# Draws a clock on `draw`, at position `cx`,`cy`. The time is `minute` (hours ignored). `mode` is either "round" or "floor"
def draw_clock(draw,cx,cy,minute, mode):
if mode=="floor" :
delta1= 0.0 # arc length, in minutes, before tick
delta2= 4.6 # arc length, in minutes, after tick
delta3= 0.0 # offset, in minutes, fro quantized hand
elif mode=="round":
delta1=-2.3 # arc length, in minutes, before tick
delta2=+2.3 # arc length, in minutes, after tick
delta3= 2.5 # offset, in minutes, fro quantized hand
else:
print("Mode must be 'floor' or 'round'")
# Draw clock circle segments
for min in range(0,60,5):
alpha1=(min+delta1)*6 # segment (arc) start (degree)
alpha2=(min+delta2)*6 # segment (arc) end (degree)
draw.arc( (cx-clk_dial_radius, cy-clk_dial_radius, cx+clk_dial_radius, cy+clk_dial_radius), alpha1, alpha2, fill='black', width=5)
# draw clock ticks
for min in range(0,60,5):
alpha= (min*6)*Rad # tick angle (radian)
p1=( cx+(clk_dial_radius-clk_tick_size/2.0)*math.cos(alpha), cy+(clk_dial_radius-clk_tick_size/2.0)*math.sin(alpha) )
p2=( cx+(clk_dial_radius+clk_tick_size/2.0)*math.cos(alpha), cy+(clk_dial_radius+clk_tick_size/2.0)*math.sin(alpha) )
draw.line( [p1,p2], fill="black", width=5 )
# draw the real hand
alpha= (minute*6-90)*Rad # hand angle (radian) # note: 0deg is horizontal, so -90
p1=( cx+clk_hand1_short*math.cos(alpha), cy+clk_hand1_short*math.sin(alpha) )
p2=( cx+clk_hand1_long *math.cos(alpha), cy+clk_hand1_long *math.sin(alpha) )
draw.line( [p1,p2], fill="red", width=5 )
# draw the real time
str= "XX:%02d" % minute
(w,h)=draw.textsize(str, font=fnt)
h=(h+2)//4*4 # stabilize height
draw.text((cx-w/2,cy-h/2), str, font=fnt, fill="red")
# draw the quantized hand
min5= 5*((minute+delta3)//5) # quantize time
alpha= (min5*6-90)*Rad # quantized hand angle (radian)
p1=( cx+clk_hand2_short*math.cos(alpha), cy+clk_hand2_short*math.sin(alpha) )
p2=( cx+clk_hand2_long *math.cos(alpha), cy+clk_hand2_long *math.sin(alpha) )
draw.line( [p1,p2], fill="green", width=5 )
# draw the quantized time
str= "XX:%02d" % min5
(w,h)=draw.textsize(str, font=fnt)
h=(h+2)//4*4 # stabilize height
draw.text((cx-w/2,cy-clk_radius-h*1.2), str, font=fnt, fill="green")
# draw the quantized time
str= "(" + mode + ")"
(w,h)=draw.textsize(str, font=fnt)
draw.text((cx-w/2,cy+clk_radius), str, font=fnt, fill="green")
# Create a list of frames for the animated GIF
list= []
for minute in range(0,60):
# Create a white frame
img= Image.new('RGB', (img_width,img_height), (255,255,255) )
draw= ImageDraw.Draw(img)
# Draw the two clocks
draw_clock( draw, img_width/4, img_height/2, minute, "floor" )
draw_clock( draw, 3*img_width/4, img_height/2, minute, "round" )
# Append new frame to frame list
list.append(img)
# Save frame list
list[0].save('clocks2.gif', save_all=True, append_images=list[1:], optimize=True, duration=500, loop=0)
|
import maze
import random
# Create maze using Pre-Order DFS maze creation algorithm
def create_dfs(m):
# TODO: Implement create_dfs
cell_stack = []
current_cell = random.randint(0, m.total_cells - 1)
visited_cells = 1
while visited_cells < m.total_cells:
neighbors = m.cell_neighbors(current_cell)
if neighbors:
new_cell, dir = random.choice(neighbors)
m.connect_cells(current_cell, new_cell, dir)
cell_stack.append(current_cell)
current_cell = new_cell
visited_cells += 1
else:
current_cell = cell_stack.pop()
m.refresh_maze_view()
m.state = 'solve'
def main():
current_maze = maze.Maze('create')
create_dfs(current_maze)
while 1:
maze.check_for_exit()
return
if __name__ == '__main__':
main()
|
unsorted_list = [3, 1, 0, 9, 4]
sorted_list = []
while unsorted_list:
minimum = unsorted_list[0]
for item in unsorted_list:
if item < minimum:
minimum = item
sorted_list.append(minimum)
unsorted_list.remove(minimum)
print(sorted_list)
|
valid_dna = "ACGT"
sequence = input('pane üks järjestus: ').upper()
condition = all(i in valid_dna for i in sequence)
print('kehtiv järjestus') if condition else print ('ei ole kehtiv järjestus')
|
# -*- coding:utf-8 -*-
# 格式化当前时间
import time
def myTime():
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
myTime()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 19:38:58 2020
@author: NTellaku
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 14:22:40 2020
@author: NTellaku
"""
import requests
import pandas as pd
import numpy as np
import scipy.stats as stats
import seaborn as sns
import matplotlib.pyplot as plt
def team_win_loss(dataset, i):
"""
Adding the win-loss record
dataset: which dataset to use?
i: iterator
"""
team = dataset[dataset["Team"] == team_ids[i]]
team_wins = sum(n > 0 for n in team["Margin"])
team_ties = sum(n == 0 for n in team["Margin"])
team_loss = sum(n < 0 for n in team["Margin"])
points = np.sum(team.PointsFor)
wl_info = pd.DataFrame([[team_ids[i], team_wins, team_loss,
team_ties, points]],
columns = ["Team", "Wins", "Losses", "Ties", "Points"])
return wl_info
def matchup(home_team, away_team, week):
"""
Input: home_team: home team number
away_team: away team number
week: which week for the matchup
calculates who wins each individual matchup.
assuming each team scores assumes a gaussian distribution
"""
#getting the summaries for each team
summary_stats = (pd.DataFrame([analysis.sort_values(by = ["Team"])
.Team
.unique(),
analysis.groupby("Team")
.mean()["PointsFor"],
analysis.groupby("Team")
.std()["PointsFor"]]).T)
#cleaning the data set
colnames = ["Team", "AvgPoints", "StDPoints"]
summary_stats.columns = colnames
#find each team's scores
home = np.random.normal(summary_stats[summary_stats.Team == home_team].AvgPoints,
summary_stats[summary_stats.Team == away_team].StDPoints,
1) #only one score "Any given Sunday"
away = np.random.normal(summary_stats[summary_stats.Team == home_team].AvgPoints,
summary_stats[summary_stats.Team == away_team].StDPoints,
1)
#make same format as analysis data set
home_row = np.array([week, home_team, home[0], (home - away)[0], away[0]])
away_row = np.array([week, away_team, away[0], (away - home)[0], home[0]])
#apped these rows to the analysis data set
extra_matchup = (pd.DataFrame([home_row, away_row],
columns = analysis.columns))
return extra_matchup
#team number to name Dictionary
mapping = {1: "Mount",
2: "Alec",
3: "Sirpi",
4: "Oatman",
5: "Babcock",
9: "Jordan",
11: "Casey",
12: "Badillo",
13: "Naki",
14: "Kooper"}
league_id = 298982
year = 2018
url = "https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory/" + str(league_id) + "?seasonId=" + str(year)
r = requests.get(url, params = {"view": "mMatchup"})
d = r.json()[0]
maximum = max(pd.DataFrame(d["schedule"]).index.tolist()) #how many obs?
length_df = pd.DataFrame([[d["schedule"][i]["winner"]] for i in range(maximum)])
length_df = length_df[length_df[0] != "UNDECIDED"]
length = range(len(length_df))
#Selecting weeks, points, data
source = pd.DataFrame([[d["schedule"][i]["matchupPeriodId"],
d["schedule"][i]["home"]["teamId"],
d["schedule"][i]["home"]["totalPoints"],
d["schedule"][i]["away"]["teamId"],
d["schedule"][i]["away"]["totalPoints"]] for i in length],
columns = ["Week", "Team1", "Score1", "Team2", "Score2"])
#add margin of defeat/victory
margins = source.assign(Margin1 = source["Score1"] - source["Score2"],
Margin2 = source["Score2"] - source["Score1"])
#only first 9 weeks of data
source_9 = margins[margins.Week < 10]
#transform from wide to long
source_long = (source_9.loc[:, ("Week", "Team1", "Score1", "Margin1")]
.rename(columns = {"Team1": "Team",
"Score1": "Score",
"Margin1": "Margin"})
.append(source_9.loc[:, ("Week", "Team2", "Score2", "Margin2")]
.rename(columns = {"Team2": "Team",
"Score2": "Score",
"Margin2": "Margin"})))
source_long = (source_long.assign(PA = source_long.Score - source_long.Margin)
.rename(columns = {"Score": "PointsFor",
"PA": "Points Against"}))
#simming 1000 times
sim_standings = pd.DataFrame()
for l in range(1000):
analysis = source_long.copy()
#Outer loop to create the weekly object
for i in range(10, 14):
weekly_matchups = margins[margins.Week == i].loc[:, ["Team1", "Team2"]]
week = i
#inner loop to do the matchup
for j in range(5):
home_team = weekly_matchups.iloc[j, 0]
away_team = weekly_matchups.iloc[j, 1]
result = matchup(home_team, away_team, i)
analysis = analysis.append(result)
#creating record from values
team_ids = source_long.Team.unique()
#initialize an empty dataframe to append to
win_loss = []
#loop through all the teams and have the rows append
for j in range(len(team_ids)):
row = team_win_loss(analysis, j)
win_loss.append(row)
win_loss = (pd.concat(win_loss)
.sort_values(by = ["Wins", "Ties", "Points"], ascending = False)
.assign(Standing = np.arange(1, 11))
.sort_values(by = ["Team"])
.reset_index(drop = True))
sim_standings[l] = win_loss.Standing
#keeping a separate copy to avoid computation time
sim_standings2 = sim_standings.copy()
sim_standings.insert(loc = 0, value = win_loss.Team, column = "Team")
#adding team name, making it the index
final = sim_standings.replace({"Team": mapping}).set_index("Team")
#how many at each rank?
final.loc["Mount", :].value_counts()
counts = pd.DataFrame([final.loc[i, :].value_counts() for i in mapping.values()])
#replace NA with 0
counts.fillna(0, inplace = True)
#where are the teams most likely to place based on the sim?
predicted_ranks = (pd.DataFrame([counts.max(), counts.idxmax()])
.T
.assign(Rank = np.arange(1, 11)))
colnames = ["Count", "Team", "Rank"]
predicted_ranks.columns = colnames
predicted_ranks = predicted_ranks.set_index("Team")
#Observed ranks
#transform from wide to long
source_13 = margins[margins.Week <= 13]
margins_long = (source_13.loc[:, ("Week", "Team1", "Score1", "Margin1")]
.rename(columns = {"Team1": "Team",
"Score1": "PointsFor",
"Margin1": "Margin"})
.append(source_13.loc[:, ("Week", "Team2", "Score2", "Margin2")]
.rename(columns = {"Team2": "Team",
"Score2": "PointsFor",
"Margin2": "Margin"})))
#initialize an empty dataframe to append to
final_win_loss = []
#loop through all the teams and have the rows append
for j in range(len(team_ids)):
row = team_win_loss(margins_long, j)
final_win_loss.append(row)
final_win_loss = (pd.concat(final_win_loss)
.sort_values(by = ["Wins", "Ties", "Points"], ascending = False)
.assign(Standing = np.arange(1, 11))
.sort_values(by = ["Team"])
.reset_index(drop = True))
comparison = (final_win_loss.replace({"Team": mapping})
.set_index("Team")
.merge(how = "right",
right = predicted_ranks,
left_index = True,
right_index = True)
.loc[:, ["Rank", "Standing"]]
.rename(columns = {"Rank": "Predicted",
"Standing": "Observed"}))
tau, p_value = stats.kendalltau(comparison.Predicted,
comparison.Observed)
#heatmap of the percentages
counts2 = counts.reindex(predicted_ranks.index) / 10
cmap = sns.diverging_palette(10, 150, as_cmap = True)
sns.heatmap(counts2, cmap = cmap, cbar = False,
annot = counts2, linewidth = 0.5)
plt.title("1000 Simulations - Percentage of Each Final Standing") |
def absolute(num):
if num < 0:
return num * (-1)
return num
a = 3.0
b = 4.0
c = 1
print(absolute(a * (b / a - c) - c))
|
Shit_words = ['tangina', 'bobo', 'hayop','gago', 'ulol', 'putangina', 'pakyu', 'fuck', ]
sentence = input('Enter your sentence: ')
new = [x for x in sentence.lower().split()]
text = ''
for word in new:
if word in Shit_words:
a = len(word)
text += '*' * a + ' '
else:
text += word + ' '
print(text)
|
string=input("Enter string:")
print("Original String:",string)
res=""
for ch in string:
if ch not in "!@#$%^&*()_-=+{}[]<>,./?';:\|":
res+=ch
print("String without punctuations:"+res) |
string=input("Enter String:")
count=0
for ch in string:
if ch.isupper():
count+=1
print("Number of capital letters in "+string+" is "+str(count)) |
st=input("Enter string")
if st==st[::-1]:
print("String is palindrome")
else:
print("String is not palindrome")
|
import time
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self):
student = []
possible_numbers = []
for m in self.children:
possible_numbers.append(m.value[0])
student_identity = input('Please enter their student number: ' )
if not student_identity in possible_numbers:
student_name = input('Please enter the student\'s name:' )
grade = input('Please enter their grade: ')
identity = TreeNode([student_identity, student_name, grade])
self.children.append(identity)
else:
print('That ID is already in the database')
def remove_child(self):
student_re = input('Please enter their student number: ')
student_index = None
checker = []
for i in self.children:
if student_re == i.value[0]:
checker.append(student_re)
else:
pass
if len(checker) == 0:
print('That ID is not valid ')
else:
for j in self.children:
if student_re == j.value[0]:
student_index = student_re
continue
self.children = [k for k in self.children if k.value[0] != student_index]
def traverse(self):
node = self
student = input('Please enter student ID: ')
descriptions = ['Student ID', 'Name', 'Mark']
descriptions_index = 0
checker = []
for i in node.children:
if student == i.value[0]:
checker.append(i)
if len(checker) >= 1:
while len(node.children) > 0:
for l in range(len(node.children)):
if student == node.children[l].value[0]:
for i in node.children[l].value:
print('{}: '.format(descriptions[descriptions_index]) + i)
if descriptions_index == 2:
descriptions_index = 0
else:
descriptions_index += 1
#print(node.children[0].value)
node.children = node.children[0].children
break
else:
continue
#node.value = node.children[0].value
else:
print('That ID seems to be invalid')
def edit(self):
node = [self]
student = input('Please enter a student ID: ')
while len(node) > 0:
current_node = node.pop()
if current_node.value[0] == student:
grade_updated = input('Please enter a new grade: ')
current_node.value = [current_node.value[0], current_node.value[1], grade_updated]
return
break
node += current_node.children
class Prompt:
def gameplay(self):
print('Welcome to your student database! ')
database = TreeNode('Students: ')
num_students = input('Please enter the amount of students you have in your school: ')
for i in range(int(num_students)):
database.add_child()
time.sleep(0.5)
print('-----------------------------------------------------------------------')
print('You can now do 3 actions: ')
print('You can view your database using /traverse')
print('You can remove a student using /remove')
print('You can edit a student\'s mark using /edit')
print('You can also add a new student using /add')
print('-----------------------------------------------------------------------')
playing = True
while playing:
user = input()
if user == '/traverse':
database.traverse()
elif user == "/remove":
database.remove_child()
print(database.children)
elif user == "/edit":
database.edit()
elif user == "/add":
database.add_child()
elif user == "/quit":
break
else:
print('That command is not valid ')
test = Prompt()
print(test.gameplay())
|
from math import pi
def func(x,n=5):
c_list = [1]
for i in range(1,n):
term = -c_list[-1]*((x*x)/(2*i*(2*i - 1)))
c_list.append(term)
return sum(c_list)
def table():
print("%-7s %-16d %-16d %-16d %-16d %d" % ("x",5,25,50,100,200))
for x in [2,4,6,8,10]:
print("%-7.3f" % (pi*x), end ='')
for n in [5,25,50,100,200]:
print(" %-15.3f " % func(x*pi,n), end ='')
print()
if __name__ == '__main__':
table()
from math import pi
def func(x,n=5):
c_list = [1]
for i in range(1,n):
term = -c_list[-1]*((x*x)/(2*i*(2*i - 1)))
c_list.append(term)
return c_list
def table():
print("%-7s %-16d %-16d %-16d %-16d %d" % ("x",5,25,50,100,200))
for x in [2,4,6,8,10]:
print("%-7.3f" % (pi*x), end ='')
c_list_x = func(pi*x,200)
for n in [5,25,50,100,200]:
print(" %-15.3f " % sum(c_list_x[:n:]), end ='')
print()
if __name__ == '__main__':
table()
|
from numpy import *
from matplotlib.pyplot import *
def f(t,x):
return (-x*sin(t))+sin(t)
def eulers(t_k,x_k,h):
return x_k+h*f(t_k,x[-1])
def eulers_midpoint(t_k,x_k,h):
x_midpoint_value = x_k+0.5*h*f(t_k,x_k)
return x_k+h*f(t_k+0.5*h,x_midpoint_value)
for n in [1,2,5,10,100]:
#t values
t = linspace(0,2*pi,n+1)
#initial values
h = t[1]; x0 = 2 + exp(1)
#starting solution lists
x_midt = [x0];x = [x0];
for t_k in t[:-1:]:
#euler
x.append(eulers(t_k,x[-1],h))
#eulers midtpunkt
x_midt.append(eulers_midpoint(t_k,x_midt[-1],h))
if n == 1 or n == 5:
print("-"*40)
plot(t,x,label="n=%d"%n)
print("%-15s n=%-10d f_eval=%-10d" % ("euler",n,n))
plot(t,x_midt,label="n=%d midpoint"%n)
print("%-15s n=%-10d f_eval=%-10d" % ("midpoint",n,2*n))
elif n == 100:
plot(t,x_midt,label="n=%d midpoint"%n)
else:
print("-"*40)
plot(t,x,label="n=%d"%n)
print("%-15s n=%-10d f_eval=%-10d" % ("euler",n,n))
print("-"*40)
legend()
ylim(1,5)
show() |
from numpy import *
from matplotlib.pyplot import *
def f(x):
return sin(x)
def df(x):
return cos(x)
#notice that pi/2 will not give an answer, why?
#notice that our answer is 4 pi, while the closest zero is at pi, why?
#how can we get pi? HINT: better starting point, aka closer to the zero point
x_start = pi/1.9
x_n = x_start
#variables for while loop
n = 100; i = 0; exact = pi; tol = 1e-15
#important part for exam
while i < n and abs(x_n%exact) > tol:
x_n -= (f(x_n)/df(x_n))
i +=1
print("%-4d %-7.2f %.2f" % (i,x_n,abs(x_n%exact)))
print("%-4d %-7.2f %.2f" % (i,x_n,abs(x_n%exact)))
x_list = linspace(0,4.5*pi,1000)
plot(x_n,0,"o",label="Newton")
plot(x_start,f(x_start),"o",label="Start")
plot(x_list,f(x_list),label="exact function")
legend(loc="best")
show() |
"""
Binary heaps are used a special kind of binary trees
they need to fulfill 2 properties
- complete tree --> all lvls except the last lvl need to be filled
- all vals of child node need to be smaller than parent node val for max heap, & larger for min heap
heaps can perform insertion & removal in worst case lg(n) time which is the height of the tree
can be implemented with a list due to the property of a complete tree
for a 1-indexed array, node at index P has left child at 2P and right child at 2P+1
appending new node at the end of list
replacing elements with last element of the list, both operations maintain the complete tree structure
up-heapify/down-heapify operations need to be done to satisfy the heap property
"""
class MinHeap:
def __init__(self):
# start with an empty root node so that indexing can be performed easier
self.heap = [0]
self.size = 0
def insert(self, item):
# insert using append preserves the complete tree property
# but may not respect the ordered heap property
# need to swap nodes till the heap is ordered
self.heap.append(item)
self.size += 1
self.heapify_up(self.size)
def heapify_up(self, i):
while i // 2 > 0:
if self.heap[i] < self.heap[i//2]:
temp = self.heap[i//2]
self.heap[i//2] = self.heap[i]
self.heap[i] = temp
i = i//2
def remove(self):
# remove the root node
retval = self.heap[1]
# replace with the smallest node
self.heap[1] = self.heap.pop()
self.size -= 1
# swap nodes till ordering is preserved
self.heapify_down(1)
return retval
def heapify_down(self, i):
# check if we can still go down one lvl
left = i * 2
right = left + 1
smallest = i
if left <= self.size and self.heap[left] < self.heap[i]:
smallest = left
if right <= self.size and self.heap[right] < self.heap[i]:
smallest = right
if smallest != i:
self.heap[i], self.heap[smallest] = self.heap[smallest], self.heap[i]
self.heapify_down(smallest)
|
from decimal import *
from builtins import *
# Sets decimal to 50 digits of precision
getcontext().prec = 50
def factorial(n): # Function to find the factorial of a number
if n < 1:
return 1
else:
return n * factorial(n - 1) # Calling the same function recursively
def scratch_pi(n): # Bailey–Borwein–Plouffe formula to calculate Pi
pi = Decimal(0)
i = 0
while i < n:
pi += (Decimal(1) / (16**i)) * ((Decimal(4) / (8 * i + 1)) - (Decimal(2) /
(8 * i + 4)) - (Decimal(1) / (8 * i + 5)) - (Decimal(1) / (8 * i + 6)))
i += 1
return pi
for j in range(1, 20):
#print( j, " ", scratch_pi(j))
pi = scratch_pi(19)
def scratch_sine(theta): # computing Sine of the theta (in radians) from scratch
x = theta
m = 0
for k in range(0, 10, 1):
y = ((-1)**k) * (x**(1 + 2 * k)) / \
factorial(1 + 2 * k) # Taylor Expansion of Sine
m += y
return Decimal(m) # Returning Sine of theta
def scratch_cosine(theta): # computing Cosine of the theta (in radians) from scratch
x = theta
m = 0
for k in range(0, 10, 1):
# Taylor Expansion of Cosine
y = ((-1)**k) * (x**(2 * k)) / factorial(2 * k)
m += y
return Decimal(m) # Returning Cosine of theta
def checkSign(a, b): # This function is to check weather the two numbers have the same polarity
return a * b > 0
def bisection(function, negative, positive):
# This function calculates the midpoint by performing number of iterations of getting the midpoints.
# of the two numbers with when substituted in the function, returns opposite polarity.
assert not checkSign(function(negative), function(positive))
for i in range(100): # For 100 iterations
midpoint = (negative + positive) / 2.0 # Getting the midpoint
if checkSign(function(negative), function(midpoint)): # Checking the polarity
negative = midpoint # setting the arguments for next iterations.
else:
positive = midpoint # setting the arguments for next iterations.
return midpoint # Returning the midpoint which is most precise answer.
def UserInput(): # function for getting input from the user.
try:
# Getting float input from the user
r = Decimal(input("Enter Radius: "))
if(r < 0): # Filtering out the negative number by raising the exception
raise Exception
return Decimal(r)
except Exception: # Filtering the string and special characters out
print("Invalid Input")
UserInput() # Recursively calling the same function
|
class Student:
def __init__(self, name, birthday, courses):
# public attributes
self.full_name = name
self.first_name = name.split(' ')[0]
self.courses = courses
# protected attributes
self._grades = dict([(course, 0.0) for course in courses])
# birthday is now a protected attribute.
self._birthday = birthday
# private attributes
self.__attendance = []
# class public methods
@property
def birthday(self):
print(f'{self.first_name} birthday accessed!')
return self._birthday
@birthday.setter
def birthday(self, new_value):
if new_value < '1899':
print('Vampires are not allowed.')
return
if new_value > '2100':
print('Time travellers are not allowed.')
return
print(f'Changing {self.first_name} birthday.')
self._birthday = new_value
# Objects
john = Student('John Schneider', '2010-04-05', {'German', 'Arts', 'History'})
mary = Student('Mary von Neumann', '2010-05-06',
{'German', 'Math', 'Geography', 'Science'})
lucy = Student('Lucy Schwarz', '2010-07-08', {'English', 'Math', 'Dance'})
# The code that uses does not does not change.
print(john.birthday)
# John birthday accessed!
# 2010-04-05
john.birthday = '1880-11-21'
# Vampires are not allowed.
mary.birthday = '2100-05-23'
# Time travellers are not allowed.
# The assignment failed and the attribute didn't change.
print(mary.birthday)
# Mary birthday accessed!
# 2010-05-06
lucy.birthday = '2000-01-01'
# Changing Lucy birthday.
print(lucy.birthday)
# Lucy birthday accessed!
# 2000-01-01
|
class Student:
def __init__(self, name, birthday, courses):
# public attributes
self.full_name = name
self.first_name = name.split(' ')[0]
self.birthday = birthday
self.courses = courses
# protected attributes
self._grades = dict([(course, 0.0) for course in courses])
# private attributes
self.__attendance = []
# class public methods
# As the __init__ method, __str__ is a reserved name used to convert an
# object to string.
def __str__(self):
return f'{self.full_name}: {self.birthday} - {self.courses}'
# Objects
john = Student('John Schneider', '2010-04-05', {'German', 'Arts', 'History'})
mary = Student('Mary von Neumann', '2010-05-06',
{'German', 'Math', 'Geography', 'Science'})
lucy = Student('Lucy Schwarz', '2010-07-08', {'English', 'Math', 'Dance'})
# It can be called as simple as:
print(john)
# John Schneider: 2010-04-05 - {'German', 'Arts', 'History'}
# explicitly as a method
print(mary.__str__())
# Mary von Neumann: 2010-05-06 - {'German', 'Math', 'Science', 'Geography'}
# or via the class syntax.
print(Student.__str__(lucy))
# Lucy Schwarz: 2010-07-08 - {'English', 'Math', 'Dance'}
# It will be called always when python needs to make the string conversion.
john_str = str(john)
mary_str = f'Hello, {mary}'
lucy_str = 'Welcome %s' % lucy
print(john_str, mary_str, lucy_str, sep='\n')
# John Schneider: 2010-04-05 - {'History', 'Arts', 'German'}
# Hello, Mary von Neumann: 2010-05-06 - {'Math', 'Geography', 'Science', 'German'}
# Welcome Lucy Schwarz: 2010-07-08 - {'English', 'Dance', 'Math'}
|
"""This Module contains functions that I don't know where to put anywhere else, that are usable in all modules"""
def relative_position(position, dx, dy, xsize, ysize):
''' Returns the position x distance and y distance from the player's square,
in the form [chunk, x, y]
dx and dy are the distance from the player in the x and y directions
xsize and ysize are the width and height of each chunk in the world
>>> print relative_position([(0,0), 0, 0], 0, 10, 10, 10 )
[(0, 1), 0, 0]
>>> print relative_position([(0,0), 0, 0], 0, -1, 10, 10 )
[(0, -1), 0, 9]
'''
block_chunk = position[0] #the current chunk
x = position[1]
y = position[2]
if x + dx < 0: #If the position is to the left of the current chunk
block_chunk = (block_chunk[0]-1, block_chunk[1])
x = xsize + dx + x #Doesn't work if you try dx > either size variable
elif x + dx > (xsize-1): #If the position is to the right
block_chunk = (block_chunk[0]+1, block_chunk[1])
x = (dx + x)%xsize #Adding one to a position at the chunk boundry makes the position 0, in the next chunk
else:
x = x + dx
if y + dy < 0: #Position in chunk below
block_chunk = (block_chunk[0], block_chunk[1]-1)
y = ysize + dy + y
elif y + dy > (ysize-1): #Position in chunk above
block_chunk = (block_chunk[0], block_chunk[1]+1)
y = (dy + y)%ysize
else:
y = y + dy
return [block_chunk, x, y]
if __name__ == '__main__':
import doctest
doctest.testmod() |
a=int(input("entrez un nombre"))
if a%2==0:
print("le nombre est pair")
else:
print("le nombre est impaire") |
"""
Was originally this monstrosity below
[l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)),
s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
"""
import socket
from re import compile
def local_ip_address(incorrect_address=compile(r'^127\..*$'), public_dst='8.8.8.8'):
"""Get the local IP address of this host.
:param incorrect_address: compiled regular expression matching unacceptable addresses.
For example, the default filters out loopback addresses like 127.0.0.1
You might want to use ``re.compile(r'^(127|172)\..*$')`` to match either
127.0.* or 172.*, which will be produced by Docker networks.
:param public_dst: if the local IP address cannot be determined without the network,
then try connecting to the given public_dst ip address.
This host's local IP address is discovered from the route.
"""
# list of ip addresses of this host
ip_list = socket.gethostbyname_ex(socket.gethostname())[2]
# might contain loopback address 127.0.0.1
ip_list = list(filter(lambda ip: not incorrect_address.match(ip), ip_list))
if len(ip_list) > 0:
return ip_list[0]
# try to find IP address from a route
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((public_dst, 53))
return s.getsockname()[0]
if __name__ == '__main__':
print(local_ip_address())
|
import sys
sys.path.insert(0, '../linked_list')
from link_list import LinkList
# ********************************
class Stack():
_data = None
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def pop(self) -> object:
b, val = self._data.peekHead()
if b:
self._data.remove(val)
return val
def push(self, val: object) -> bool:
self._data.insert(val)
return True
def peek(self) -> [bool, object]:
return self._data.peekHead()
# *********************************
class Queue():
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def toStr(self) -> str:
return self._data.toStr()
def enqueue(self, val) -> bool:
# Add a value to the queue
return self._data.append(val)
def dequeue(self, val) -> bool:
# Remove entry from queue with a given value
# NOTE: will only remove the first element found with val
return self._data.remove(val)
def peek(self) -> [bool, object]:
# Get value from the head of the queue (without removing it)
return self._data.peekHead()
|
from random import randrange
print("Integer Divisions")
while(True):
quit_option=input("Please enter q to quit or enter any other input")
if(quit_option=="q"):
break
a=randrange(5)
b=randrange(5)
try:
query=int(input("what is the value of "+str(a)+"/"+str(b)+"="))
if(query==int(a/b)):
print("Correct!")
else:
print("Incorrect!")
except ZeroDivisionError:
print("Number can't be Divided by zero")
except ValueError:
print("Please enter only integers")
##Integer Divisions
##Please enter q to quit or enter any other inputa
##what is the value of 2/1=2
##Correct!
##Please enter q to quit or enter any other inputa
##what is the value of 4/4=1
##Correct!
##Please enter q to quit or enter any other inputa
##what is the value of 1/4=4
##Incorrect!
##Please enter q to quit or enter any other inputa
##what is the value of 1/0=1
##Number can't be Divided by zero
##Please enter q to quit or enter any other inputa
##what is the value of 3/4=w
##Please enter only integers
##Please enter q to quit or enter any other inputq
|
# tuple is a structure where we can store multiple pieces of information
# similar to a list but a little different
coordinates = (4,5) #use () instead of [] to make a tuple. [] makes a list.
#tuples are immutable (cannot be changed or modified)
#if you try to reassign values in tuple, python will throw error
print(coordinates[0]) #can call an element at an index using []
#in practical use, you use tuple for data that never changes (think final)
#we CAN create a list of tuples and change those values
coordinates2 = [(4,5),(6,7),(80,34)]
print(coordinates2)
coordinates2[1] = (3,2)
print(coordinates2)
|
# following tutorial found on YT, using scikit learn
import numpy as np
import matplotlib.pyplot as pt
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
data = pd.read_csv("train.csv").as_matrix()
clf = DecisionTreeClassifier()
xtrain = data[0:21000, 1:] # takes data from rows 0 to 21000, starting from column 1 (ignoring first column)
train_label = data[0:21000, 0] # takes only column 0, which is the training label
clf.fit(xtrain,train_label)
# testing data
xtest = data[21000: , 1:]
actual_label = data[21000:, 0]
d = xtest[8]
d.shape = (28, 28)
pt.imshow(255 - d, cmap = 'gray')
print(clf.predict([xtest[8]]))
pt.show() |
fruitsList = ["Mango", "Watermelon", "Strawberries", "Kiwi"]
print(fruitsList[0])
fruitsList[0] = "Coconut"
print(fruitsList[0])
# 0, 1, 2, 3
# 1, 2, 3, 4
# fruitsTuple = ("Mango", "Watermelon", "Strawberries", "Kiwi")
#A tuple can hold a collection of different data types
# myTuple = (24, True, "String", (1, 2, 3, ("String" (123))))
# print(myTuple[-1])
# Matrix
# [[0,1], [2,2]] => Multidimensional list/array
# print(myTuple[-1])
# Set: a collection of data that is unordered and unindexed. NO DUPLICATE VALUES.
mySet = {"Mango", "Watermelon", "Strawberries", "Kiwi", "Mango", "Kiwi", "Strawberries"}
print(mySet) |
i = 0
name = "*"
userinput = int(input("How many layers of \"*\" do you want me to print?"))
while i <= userinput:
print(i * name)
i += 1 |
"""
张量 类似numpy
"""
import torch
x = torch.empty(5, 3) # 构建5*3的未初始化矩阵
print(x)
x = torch.rand(5, 3) # 构建5*3的随机[0-1]初始化矩阵
print(x)
x = torch.zeros(5, 3, dtype=torch.long) # 构建5*3全为0的矩阵,数据类型为long
print(x)
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
x = torch.randn_like(x, dtype=torch.float) # 使用矩阵构建一个类似的随机矩阵
print(x)
print(x.size()) # 数据为元组
# 加法操作
y = x.new_ones(5, 3, dtype=torch.double)
print(x+y)
print(torch.add(x, y))
z = torch.empty(5, 3)
torch.add(x, y, out=z)
print(z)
y.add_(x)
print(y)
# 索引操作
print(x[:, 1])
# 矩阵形状改变
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
# 获取单个元素的值
x = torch.randn(1)
print(x)
print(x.item())
|
"""
PyQt的部分组件,比如勾选框,按钮,滑动条,进度条,日历组件
"""
import sys
def checkbox():
"""
"""
from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
cb = QCheckBox('Show title', self)
cb.move(20, 20)
cb.toggle() # 使用setChecked 也会被触发
cb.stateChanged.connect(self.changeTitle)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('QCheckBox')
self.show()
def changeTitle(self, state):
if state == Qt.Checked:
self.setWindowTitle('QCheckBox')
else:
self.setWindowTitle(' ')
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
def toggle_button():
"""
可以长按的按钮
"""
from PyQt5.QtWidgets import (QWidget, QPushButton,
QFrame, QApplication)
from PyQt5.QtGui import QColor
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.col = QColor(0, 0, 0)
redb = QPushButton('Red', self)
redb.setCheckable(True) # 使按钮可以保持在 pressed 的状态
redb.move(10, 10)
redb.clicked[bool].connect(self.setColor)
greenb = QPushButton('Green', self)
greenb.setCheckable(True)
greenb.move(10, 60)
greenb.clicked[bool].connect(self.setColor)
blueb = QPushButton('Blue', self)
blueb.setCheckable(True)
blueb.move(10, 110)
blueb.clicked[bool].connect(self.setColor)
# 初始化颜色框
self.square = QFrame(self)
self.square.setGeometry(150, 20, 100, 100)
self.square.setStyleSheet("QWidget { background-color: %s }" %
self.col.name())
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Toggle button')
self.show()
def setColor(self, pressed):
"""
修改颜色
"""
source = self.sender() # 获取触发源
if pressed:
val = 255
else:
val = 0
if source.text() == "Red":
self.col.setRed(val)
elif source.text() == "Green":
self.col.setGreen(val)
else:
self.col.setBlue(val)
self.square.setStyleSheet("QFrame { background-color: %s }" %
self.col.name())
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
def slider():
"""
滑动条的组件
"""
from PyQt5.QtWidgets import (QWidget, QSlider,
QLabel, QApplication)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
sld = QSlider(Qt.Horizontal, self)
sld.setFocusPolicy(Qt.NoFocus) # 配置获取焦点的策略,没有焦点
sld.setGeometry(30, 40, 100, 30)
sld.valueChanged[int].connect(self.changeValue)
self.label = QLabel(self)
self.label.setPixmap(QPixmap('resources/speaker__easy_0.png'))
self.label.setGeometry(160, 40, 80, 32)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QSlider')
self.show()
def changeValue(self, value):
"""
根据滑动的值修改图片展示
"""
if value == 0:
self.label.setPixmap(QPixmap('resources/speaker__easy_0.png'))
elif value > 0 and value <= 30:
self.label.setPixmap(QPixmap('resources/speaker__easy_1.png'))
elif value > 30 and value < 80:
self.label.setPixmap(QPixmap('resources/speaker__easy_2.png'))
else:
self.label.setPixmap(QPixmap('resources/speaker__easy_3.png'))
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
def progress_bar():
"""
进度条
"""
from PyQt5.QtWidgets import (QWidget, QProgressBar,
QPushButton, QApplication)
from PyQt5.QtCore import QBasicTimer
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建进度条
self.pbar = QProgressBar(self)
self.pbar.setGeometry(30, 40, 200, 25)
# 创建开始按钮
self.btn = QPushButton('Start', self)
self.btn.move(40, 80)
self.btn.clicked.connect(self.doAction)
# 创建计时器,初始化计数
self.timer = QBasicTimer()
self.step = 0
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QProgressBar')
self.show()
def timerEvent(self, e):
if self.step >= 100:
self.timer.stop()
self.btn.setText('Finished')
return
self.step = self.step + 1
self.pbar.setValue(self.step)
def doAction(self):
if self.timer.isActive():
self.timer.stop()
self.btn.setText('Start')
else:
self.timer.start(100, self)
self.btn.setText('Stop')
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
def calendar():
"""
日历组件
"""
from PyQt5.QtWidgets import (QWidget, QCalendarWidget,
QLabel, QApplication, QVBoxLayout)
from PyQt5.QtCore import QDate
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout(self) # 创建布局
cal = QCalendarWidget(self) # 创建日历组件
cal.setGridVisible(True) # 设置日历网格可见
cal.clicked[QDate].connect(self.showDate)
vbox.addWidget(cal)
self.lbl = QLabel(self)
date = cal.selectedDate()
self.lbl.setText(date.toString())
vbox.addWidget(self.lbl)
self.setLayout(vbox)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Calendar')
self.show()
def showDate(self, date):
self.lbl.setText(date.toString())
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
# checkbox()
# toggle_button()
# slider()
# progress_bar()
calendar()
|
def pascal_jesse(lookup_line):
append_one = [1]
if lookup_line == 1:
# First line needs special treatment since it is just a value of "1" in a list. It doesn't follow any calculations.
return [1]
else:
pascal_line = []
for iteration in range(2,lookup_line+1):
# iteration doesn't actually do anything. We just want the program to calculate each line of Pascal's triangle until the desired line is hit.
# We also use range 2 to lookup_line + 1 for a more intuitive approach. In a literal sense, it means from the second line to the last line. We do this because first line is already accounted for.
pascal_line = append_one+[pascal_line[i]+pascal_line[i+1] for i in range(len(pascal_line)-1)]+append_one
# List comprehension to continuously updating the pascal_line variable until the desired line is hit. Then we return the last line.
return pascal_line
import time
start_time = time.time()
line = 500
print(pascal_jesse(line))
print("--- %s seconds ---" % (time.time() - start_time))
|
'''How to work with bits and bytes in python'''
test = "aklsjdf;alksjdf;alksdjfa;lk++sdjf"
test = test.encode('UTF-8')
length = len(test)
print(length)
length_in_bytes = length.to_bytes(4, 'big')
print(length_in_bytes)
length_again = int.from_bytes(length_in_bytes, 'big')
print(length_again)
|
##################################################################################
# Name: Benjamin Tate
# Date: 11/24/2016
# Class: CS 344
# Assignment: Program 5
# Description: A simple python program that will create 3 new text files, write 10
# random lowercase letters and a newline to each, print the random strings of
# each, and finally print 2 random integers [1, 42] and compute and print their
# product.
# Note: Please run program with 'python mypython.py'
##################################################################################
import sys
import random
import string
#Seed psuedo-random generator
random.seed()
#Initialize 3 strings to hold be written to the 3 files
f1string = ''
f2string = ''
f3string = ''
#Get string containing list of all letters and remove uppercase letters
letters = string.letters
letters = letters[:-26]
#Making first file:
for i in range(0, 10):
#Add 10 random characters from lowercase letter string to f1string
letter = random.choice(letters)
f1string += letter
#Add newline
f1string += '\n'
#Open a file for writing and write string to it
f1 = open('foo.txt', 'w')
f1.write(f1string)
#Making second file:
for j in range(0, 10):
#Add 10 random characters from lowercase letter string to f2string
letter = random.choice(letters)
f2string += letter
#Add newline
f2string += '\n'
#Open a file for writing and write string to it
f2 = open('bar.txt', 'w')
f2.write(f2string)
#Making third file:
for k in range(0, 10):
#Add 10 random characters from lowercase letter string to f3string
letter = random.choice(letters)
f3string += letter
#Add newline
f3string += '\n'
#Open a file for writing and write string to it
f3 = open('baz.txt', 'w')
f3.write(f3string)
#Print contents of f1
print '\nContents of foo.txt:'
print f1string
#Print contents of f2
print 'Contents of bar.txt:'
print f2string
#Print contents of f3
print 'Contents of baz.txt:'
print f3string
#Create 2 random integers from 1 to 42
i1 = random.randint(1, 42)
i2 = random.randint(1, 42)
#Print integers and their product
print 'First integer = {0}'.format(i1)
print 'Second integer = {0}'.format(i2)
print 'Product = {0}'.format(i1 * i2)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Napisz funkcję days_in_year zwracającą liczbę dni w roku (365 albo 366).
"""
def days_in_year(year):
if (year % 4 == 0 and year % 100 != 0 ) or year % 400==0:
num=366
else:
num=365
return num
input = 2019
output = 365
print(days_in_year(input)) |
#!/usr/bin/python3
for s in range(0, 99):
print("{:02d}, ".format(s), end="")
print(99)
|
#!/usr/bin/python3
def divisible_by_2(my_list=[]):
lista = []
for i in my_list:
if i % 2 == 0:
lista.append(True)
else:
lista.append(False)
return lista
|
# -*- coding: utf-8 -*-
"""
Katherine Lamoureux
MET CS 521
9/8/2019
Homework 1.5
Description: Program that displays the result of an equation
"""
# This section assigns tags
numerator = (9.5 * 4.5 - 2.5 * 3)
denominator= (45.5 - 3.5)
# This section computes the equation
result = numerator / denominator
# This section will print the result of the equation
print( "The result of the equation is", result ) |
def sortList(data):
newList = []
while data:
minimum = data[0] # arbitrary number in list
for x in data:
if x < minimum:
minimum = x
newList.append(minimum)
data.remove(minimum)
return newList
print(sortList([67, 45, 2, 13, 1, 998]))
print(sortList([89, 23, 33, 45, 10, 12, 45, 45, 45]))
|
# import needed modules
import tkinter as tk
from tkinter import messagebox
import logic as log
import sys
# creates snake and apple object
s = log.snake()
a = log.apple()
# main app class
class App(tk.Tk):
# creates tkinter window
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# creates a canvas on which game is displayed
self.canvas = tk.Canvas(self, width=500, height=500, borderwidth=0, highlightthickness=0)
self.canvas.pack(side="top", fill="both", expand="true")
self.cell_width = 25
self.cell_height = 25
self.rect = {}
self.oval = {}
self.turns = 0
# creates grid needed for displaying snake and apple
for column in range(20):
for row in range(20):
x1 = column * self.cell_width
y1 = row * self.cell_height
x2 = x1 + self.cell_width
y2 = y1 + self.cell_height
self.rect[row, column] = self.canvas.create_rectangle(x1, y1, x2, y2, fill="black", tags="rect")
self.oval[row, column] = self.canvas.create_oval(x1 + 2, y1 + 2, x2 - 2, y2 - 2, fill="black",
tags="oval")
self.canvas.itemconfig(self.oval[row, column], state="hidden")
# new position for apple is generated
a.new_pos(s.snake_parts_list)
# snake is given head and 2 body parts to start with
s.grow()
s.grow()
# set speed at which game runs, delay of 100ms before updating
self.re_draw(100)
# class for drawing snake and apple positions
def re_draw(self, delay):
# sets every rectangle to black to start with
for y in range(0, 20):
for x in range(0, 20):
self.canvas.itemconfig(self.rect[y, x], fill="black")
# runs game play function, sets new snake position
self.game_play()
# sets the oval at specified coordinates to show an apple based on apple objects coordinates
self.canvas.itemconfig(self.oval[a.y, a.x], state="normal", fill="green")
# draws orange rectangle for head and red for body part, loops through each part
to_draw = []
for i in s.snake_parts_list:
to_draw.append((self.rect[i.get_y(), i.get_x()], i.is_head()))
for i in to_draw:
if i[1]:
self.canvas.itemconfig(i[0], fill="orange")
else:
self.canvas.itemconfig(i[0], fill="red")
# recursively runs re_draw method after specified delay in ms
self.after(delay, lambda: self.re_draw(delay))
# game play method
def game_play(self):
# due to bug of the game registering a death at the start the turns attributes is used
self.turns += 1
head_x = s.snake_parts_list[0].get_x()
head_y = s.snake_parts_list[0].get_y()
# if at any point the head coordinates are equal to apple coordinates the snake grows and new apple position
# is generated
if (head_x, head_y) == (a.x, a.y):
self.canvas.itemconfig(self.oval[a.y, a.x], state="hidden", fill="black")
a.new_pos(s.snake_parts_list)
s.grow()
# checks through every body part of snake if the head and body part have equal coordinates
for i in range(1, len(s.snake_parts_list)):
if self.turns > 1:
if (s.snake_parts_list[i].get_x(), s.snake_parts_list[i].get_y()) == (head_x, head_y):
# if yes the game is over as the snake has died and the exit_application method runs
self.exit_application()
break
# direction is determined
s.direction = s.control(s.direction)
# snake moves with movement method
s.movement()
def exit_application(self):
# displays ask question message box with the answers yes or no
# score is displayed and is user is asked is they want to play again
msg_box = messagebox.askquestion("Game Over",
'Do you want to play again?' + '\n' + (
"You Scored: " + str(len(s.snake_parts_list) - 1)),
icon='warning')
# if they choose to play again
if msg_box == 'yes':
# all variables and lists used are reset to their defaults and the game starts from the beginning
self.turns = 0
self.deiconify()
s.snake_parts_list = []
s.direction = "n"
s.snake_parts_list.append(log.snake_parts(True, 9, 9))
a.new_pos(s.snake_parts_list)
s.grow()
s.grow()
a.new_pos(s.snake_parts_list)
else:
# otherwise the script closes down
sys.exit()
if __name__ == "__main__":
app = App()
app.mainloop()
|
# Micah Scott 3/21/19
# imports
import random
import winsound
import time
# define some values
list = []
odetobogo = [329, 329, 349, 392, 392, 349, 329, 293, 261, 261, 293, 329, 293, 261, 261]
i = 0
p = 0
# get user input to append to list
print("Type numbers to be sorted:")
while i < 5:
list.append(input())
i += 1
# create a sorted copy of this list to check later
list2 = list.copy()
list2.sort()
# print function
def printList(list):
for i in range(len(list)):
print(list[i], end = " ")
print()
# bogo sort
while True:
winsound.Beep(odetobogo[p], 90)
time.sleep(.1)
printList(list)
p += 1
# reset Beethoven
if p >= 14:
p = 0
# check to if list is sorted
if list == list2:
print("list has been sorted.")
winsound.Beep(880, 200)
break
# shuffle and repeat
else:
random.shuffle(list)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 13:50:44 2018
@author: jinyanliu
"""
class IntSet(object):
def __init__(self):
self.vals = []
def insert(self,e):
if e not in self.vals:
self.vals.append(e)
def __str__(self):
self.vals.sort()
result = ""
for e in self.vals:
result =result + str(e) + ','
return '{' +result[:-1] + '}'
myIntSet = IntSet()
myIntSet.insert(4)
IntSet.insert(myIntSet, 6)
print(myIntSet)
print (myIntSet.__str__())
print (IntSet.__str__(myIntSet))
print(str(myIntSet))
print(hash(myIntSet))
print()
myIntSet.insert(8)
print(hash(myIntSet))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 11:41:48 2019
@author: jinyanliu
"""
def intToStr(i):
digits='0123456789'
if i == 0:
return '0'
result = ''
while i>0:
x = i%10
result = digits[x] + result
i = i//10
return result
print (intToStr(25))
def addDigits(n):
stringRep = intToStr(n)
val = 0
for c in stringRep:
val += int(c)
return val
print (addDigits(25))
print (2**20) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 13:44:52 2019
@author: jinyanliu
"""
L = [[1, 2, 3], (3, 2, 1, 0), 'abc']
print(sorted(L, key=len, reverse=True))
L = [1, 2, 6, 5]
print(sorted(L))
L = [1, 'b', 2, 6, 5, 'a']
print(sorted(L))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.