text
stringlengths 37
1.41M
|
---|
'''
https://www.hackerrank.com/challenges/chocolate-feast/problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the chocolateFeast function below.
def chocolateFeast(n, c, m):
if n<c:
return 0
cho = n//c
wrap = cho
while True:
if wrap//m>0:
cho+=wrap//m
wrap=wrap//m + wrap%m
else:
break
return cho
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
ncm = input().split()
n = int(ncm[0])
c = int(ncm[1])
m = int(ncm[2])
result = chocolateFeast(n, c, m)
fptr.write(str(result) + '\n')
fptr.close()
|
'''
https://www.hackerrank.com/challenges/electronics-shop/problem
'''
import os
import sys
from itertools import product
def getMoneySpent(keyboards, drives, b):
allout = list(product(keyboards, drives))
new_sum = -1
for val in allout:
if new_sum<sum(val)<=b:
new_sum = sum(val)
return new_sum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
bnm = input().split()
b = int(bnm[0])
n = int(bnm[1])
m = int(bnm[2])
keyboards = list(map(int, input().rstrip().split()))
drives = list(map(int, input().rstrip().split()))
moneySpent = getMoneySpent(keyboards, drives, b)
fptr.write(str(moneySpent) + '\n')
fptr.close()
|
'''
https://www.hackerrank.com/challenges/np-sum-and-prod/problem?h_r=next-challenge&h_v=zen
You are given a 2-D array with dimensions X.
Your task is to perform the tool over axis and then find the of that result.
Input Format
The first line of input contains space separated values of and .
The next lines contains space separated integers.
Output Format
Compute the sum along axis . Then, print the product of that sum.
Sample Input
2 2
1 2
3 4
Sample Output
24
'''
import numpy
n, m = tuple(map(int, input().split()))
vals = []
for a in range(n):
i = tuple(map(int, input().split()))
vals.extend(i)
vals = numpy.array(vals)
vals = vals.reshape((n,m))
vals = vals.sum(axis=0)
print(vals.prod())
|
class decorateClass(object):
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
print(f"do something before calling function {self.f.__name__}")
self.f(*args, **kwargs)
print(*args, **kwargs)
print("AAA")
@decorateClass
def myFunc():
A=1+1
A=str(A)
return A
# print("運算結果: "+str(A))
if __name__ == '__main__':
myFunc() |
import math
result = 420
# selection of approximate root a,b
def eqn(x):
return (math.pow(x, 3))-2*x+ 3
for i in range(-3,3):
print(str(i)+"="+str(eqn(i)))
print("Enter the value of a")
a=int(input())
print("Enter the value of b")
b=int(input())
#Finding root
while( result != 0.00 ) :
x=(a+b) / 2
rootChk =(math.pow(x, 3))-2*x+3
result=rootChk
print("(",a,"+",b,")/2 =" , x, " f(x)=",rootChk)
if (result== 0.00):
break
elif( result > 0 ):
a=x
else :
b=x
print("Answer is :" ,x)
|
from datetime import datetime
# import datetime what is the difference
# ######################## 函数别名(指针)与调用 #########################################
def hi(name='Knight'):
return "hi {}".format(name)
greet = hi # 这里没有加(),因为不是调用函数
# print(greet) # <function hi at 0x0000000002043E18>
# print(hi) # <function hi at 0x0000000002043E18>
# print(greet()) # hi Knight
# print(hi()) # hi Knight
del hi
# print(hi()) # NameError: name 'hi' is not defined
# print(greet()) # hi Knight
# ######################## 函数作为返回对象 #########################################
def hello(name="Knight"):
def greet_():
return "Now U are visiting greet fun"
def welcome():
return "Now U are visiting welcome fun"
if name == "Knight":
return greet_
else:
return welcome
a = hello()
# print(a) # <function hello.<locals>.greet at 0x000000000BBA7048>
# print(a()) # Now U are visiting greet fun
# ######################## 函数作为参数 #########################################
def hi(name='Knight'):
return "hi {}".format(name)
def doSomethingBeforeHi(func):
print("do some interesting thing before Hi")
print(func())
# doSomethingBeforeHi(hi) # do some interesting thing before Hi # hi Knight
# ######################## 第一个装饰器 #########################################
# 就像decorate名字一样,为函数加一些装饰的内容
def peo_info(name='Knight'): # 被装饰的函数
print("name: {}".format(name))
def decorate_info(func_name):
def wrapTheFunc():
print("school: {}".format("SEU"))
func_name()
now_time = datetime.now()
time_str = datetime.strftime(now_time, '%y-%m-%d_%H:%M:%S')
print("Time: {}".format(time_str))
return wrapTheFunc
# peo_info() # name: Knight
# peo_info = decorate_info(peo_info)
# peo_info() # school: SEU # name: Knight # Time: 19-11-30_19:34:16
# print(peo_info.__name__) # wrapTheFunc
# ############################### @ 装饰器 #########################################
@decorate_info
def soldier_info(): # 等价于在此处定义一个函数,然后把函数名作为参数传输到装饰器中
print("soldier_name: {}".format("Knight"))
# soldier_info() # school: SEU # soldier_name: Knight # Time: 19-11-30_19:53:07, 相当于免去了前一个实验的 redundant/verbose step
# print(soldier_info.__name__) # wrapTheFunc
# ############################### 被装饰函数__name__保持 #########################################
# 导包
# 定义一个装饰器 并用@wrap(a_fun)注释
# 定义被装饰函数
# 调用被装饰函数
from functools import wraps
def output_info(func_name):
@ wraps(func_name)
def more_info():
print("位置:{}".format("东北亚"))
func_name()
print("首都:{}".format("北京"))
return more_info
@output_info
def nation_info(name="China"):
print("Nation: {}".format(name))
# nation_info()
# print(nation_info.__name__) # nation_info
# ############################### 使用规范 #########################################
from functools import wraps
def wave_display(wave_name):
@wraps(wave_name)
def show_name():
if show:
return wave_name() + "_decorated"
else:
return "can not show the name"
return show_name
show = True
@wave_display
def sine_curve():
name = "sine_curve"
return name
print(sine_curve())
# 相当于什么:@wave_display 等价于 sine_curve=wave_display(sine_curve) #这就是装饰器@的作用
|
print("{:>4.4f}".format(3.1415926))
print("{:<10.4f},{}".format(3.1415926, 3.1415926))
print("{:<20.4f},{}".format(3.1415926, 3.1415926)) # 对齐方式,宽度,小数位数
print("{:1>20}".format(3.1415926)) # 补齐用的数据,补齐数据的位置,总宽度
print("{:0<20.2}".format(3.1415926)) # 补齐用的数据,补齐数据的位置,总宽度
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, operator
nameTab = []
classTab = []
unique = None
optPath = False
class People:
def __init__(self, name):
self.name = name;
self.listName = []
def getName(self):
return (self.name)
def addRelation(self, name):
if not (name in self.listName):
self.listName.append(name)
def getRelation(self):
for tmp in self.listName:
print (" Relation: %s" % tmp)
return 0
def getRelationName(self):
return(self.listName)
### Parsing Function ###
def checkArray(name):
global nameTab
if (name in nameTab):
return (False)
else:
nameTab.append(name)
return (True)
def newClass(name):
global classTab
tmp_class = People(name)
classTab.append(tmp_class)
def addRelationship(people, friends):
global classTab
for elem in classTab:
if (elem.getName() == people):
elem.addRelation(friends)
def printClass():
global classTab
for elem in classTab:
print("People: %s" % elem.getName())
elem.getRelation()
def checkPeople(name1, name2, tmp):
global nameTab
if ((name1 in nameTab) and (name2 in nameTab)):
if (name1 == name2):
print("degree of separation between %s and %s: 0" % (name1, name2))
else:
makeDico(tmp, name1, name2)
else:
print("degree of separation between %s and %s: -1" % (name1, name2))
exit(0)
### HELP ###
def printUsage():
sys.stdout.write('\n')
print("USAGE:\n\t./302separation [file p1 p2 [-p]] [nb] [-m]\n")
print("DESCRIPTION:\n\tfile\tThe file you want to check.\n\tp1 p2\tPeople you want to know their connection.")
print("\tnb\tThe maximum size of the paths.")
print("\t-m\tDisplays the incidence matrix.")
print("\t-p\tDisplays the optimized path taken")
sys.stdout.write('\n')
### SORT NAME ###
def sortName(tmp):
global nameTab
count = 1
nameTab.sort()
for elem in nameTab:
print ("%s" % elem)
print("")
### FIND DEGREE ###
def makeDico(tmp, start, end):
global unique
count = 1
graph = {}
for i in range(len(tmp)):
if (count == 1):
if tmp[i] in graph:
graph[tmp[i]].append(tmp[i+1])
else:
graph[tmp[i]] = [tmp[i+1]]
if (count == 2):
if tmp[i] in graph:
graph[tmp[i]].append(tmp[i-1])
else:
graph[tmp[i]] = [tmp[i-1]]
count = 0
count = count + 1
unique = start
findPath(graph, start, end)
def findPath(graph, start, end, path=[]):
global i
global unique
path = path + [start]
if (start == end):
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if (node not in path):
newpath = findPath(graph, node, end, path)
if (newpath):
if (optPath == True):
print("degree of separation between %s and %s: %d" % (unique, end, (len(newpath)-1)))
print newpath
else:
print("degree of separation between %s and %s: %d" % (unique, end, (len(newpath)-1)))
exit(0)
return None
### INCIDENCE MATRIX ###
def matrixOption(tmp):
global nameTab
count = 1
nameTab.sort()
l_map = []
ct = 1
line = 0
for i in range(0, len(tmp)):
if (ct == 1):
line = line + 1
if (ct == 2):
ct = 0
ct = ct + 1
for i in range(len(nameTab)):
l_map.append([0] * line)
a = 0
b = 0
for elem in nameTab:
for i in range(0, len(tmp)):
if (count == 1):
if ((tmp[i] == elem) or (tmp[i+1] == elem)):
l_map[b][a] = 1
a = a + 1
if (count == 2):
count = 0
count = count + 1
a = 0
b = b + 1
for i in range(len(nameTab)):
print l_map[i]
### SIMPLE MATRIX ###
def adjacencyMatrix():
global nameTab
global classTab
nameTab.sort();
classTab.sort(key=operator.attrgetter("name"))
for c in classTab:
relation = c.getRelationName()
counter = 0
for n in nameTab:
counter += 1
boule = False
for r in relation:
if (n == r):
boule = True
if boule:
sys.stdout.write('1')
else:
sys.stdout.write('0')
if (counter < len(nameTab)):
sys.stdout.write(' ')
sys.stdout.write('\n')
### PRINCIPAL FUNCTIONS ###
def checkfile():
global optPath
if len(sys.argv) >= 3:
if not os.path.isfile(sys.argv[1]):
printUsage()
exit(84)
file = open(sys.argv[1], "r")
content = file.read()
file.close()
rep = content.replace('\n', ' is friend with ')
tmp = rep.split(" is friend with ")
if (len(sys.argv) == 3):
if (sys.argv[2] == "-m"):
makePeople(tmp)
matrixOption(tmp)
else:
makePeople(tmp)
sortName(tmp)
adjacencyMatrix()
elif (len(sys.argv) == 4):
makePeople(tmp)
checkPeople(sys.argv[2], sys.argv[3], tmp)
elif (len(sys.argv) == 5):
if (sys.argv[4] == "-p"):
makePeople(tmp)
optPath = True
checkPeople(sys.argv[2], sys.argv[3], tmp)
else:
printUsage()
exit(84)
else:
printUsage()
exit(84)
else:
printUsage()
exit(84)
def makePeople(tmp):
counter = 0
i = 1
for elem in tmp:
if (i == 3):
i = 1
if (checkArray(elem)):
newClass(elem)
if (i == 1):
addRelationship(tmp[counter], tmp[counter + 1])
else:
addRelationship(tmp[counter], tmp[counter - 1])
i += 1
counter += 1
### Parsing Function ###
checkfile()
exit(0)
|
"""
***************************************************************
* Class: MaxHeap Validation
* Author: Brogan Avery
* Created : 2021-04-13
***************************************************************
"""
class HeapValidator:
def __init__(self, arr, size, i = 0):
self.arr = arr # heap to validate
self.size = size
self.i = i
def isHeap(self): # method that sorts the heap to validate it, makes sure all children are smaller than parent
if self.i >= int((self.size - 2) / 2):
return True
if (self.arr[self.i] >= self.arr[2 * self.i + 1] and self.arr[self.i] >= self.arr[2 * self.i + 2] and self.isHeap() and self.isHeap()):
return True
return False
|
''''
Author: Brogan Avery
Date: 2020/09/12
Project Title: numPy demo
'''
from numpy import *
#————————————————————————————————————————————————————————————————————————————————————
if __name__ == '__main__':
arr1 = array([[10,15,20],[2,3,4],[9,14.5,18]])
arr2 = array([[1,2,5],[8,0,12],[11,3,22]])
print('Here is arr1: \n', arr1)
print('\nThe shape of arr1: \n', arr1.shape)
print('\nA 2x2 slice: \n', arr1[0:2,0:2],'\n') # [startrow:endrow, starcol:endcol]
even = True
odd = False
for row in arr1:
for item in row:
if(item % 2 ==0):
print('The value in index ', item, ' is', even )
else:
print('The value in index ', item, ' is', odd)
print('\nThe sum of arr1 and arr2:\n',add(arr1,arr2) )
print('\nThe product of arr1 and arr2:\n', multiply(arr1, arr2))
print('\nThe sum of all elements in arr2:\n', arr2.sum())
print('\nThe product of all elements in arr2:\n', prod(arr2))
print('\nThe largest number in arr2:\n', arr2.max())
print('\nThe smallest number in arr2:\n', arr2.min()) |
"""
***************************************************************
* Title: Stack Class
* Author: Brogan Avery
* Created : 2021-02-06
* Course: CIS 152 - Data Structure
* Version: 1.0
* OS: macOS Catalina
* IDE: PyCharm
* Copyright : This is my own original work based on specifications issued by the course instructor
* Description : An app that demonstrates stacks
* Academic Honesty: I attest that this is my original work.
* I have not used unauthorized source code, either modified or
* unmodified. I have not given other fellow student(s) access
* to my program.
***************************************************************
"""
from Stack import Stack
from LabCode.StackLab.StackEmptyException import StackEmptyException
from LabCode.StackLab.StackFullException import StackFullException
# MAIN--------------------------------------------------------------------
if __name__ == '__main__':
# empty stack
stack1 = Stack(3)
print("\nSTACK IS EMPTY: ")
print("is empty: ", stack1.is_empty())
print("is full: ", stack1.is_full())
print("size: ", stack1.size())
# try to print empty stack
try:
print("print string: ", stack1.print_stack_up())
except StackEmptyException:
print("Stack is empty")
# try to print peek
try:
print("peek: ", stack1.peek())
except StackEmptyException:
print("Stack is empty")
# try to print pop
try:
print("pop: ", stack1.pop())
except StackEmptyException:
print("Stack is empty")
# add to it
print("\nADD TO STACK: ")
stack1.push("item 1")
stack1.push("item 2")
stack1.push("item 3")
# try to add to a full list
try:
stack1.push("item 4")
except StackFullException:
print("Stack is full")
print("print string: ", stack1.print_stack_up())
print("is empty: ", stack1.is_empty())
print("is full: ", stack1.is_full())
print("size: ", stack1.size())
print("peek: ", stack1.peek())
print("print string: ", stack1.print_stack_up())
print("item popped: ", stack1.pop())
print("print string after pop: ", stack1.print_stack_up())
|
"""
***************************************************************
* Class Name: Node
* Author: Brogan Avery
* Created: 2021-03-18
***************************************************************
"""
from queue import Queue
class Node:
def __init__(self, iData = None, sData = None):
self.sData = sData # string data
self.iData = iData # int data
self.left = None # left child
self.right = None # right child
# compares the in-value node to the "current root" node
def insert(self,node): # New node that is not yet on tree
if self.iData: # currentRootNode.iData
if node.iData < self.iData: # uses pre order to traverse left branch first
if self.left is None: # self.left = the left child of the "current root" node
self.left = node # sets the left child to the data of the new node
else:
self.left.insert(node) # method calls self using the left child of the "current root" node as the new "current root" node
elif node.iData > self.iData:
if self.right is None: # self.right = the right child of the "current root" node
self.right = node # sets the right child to the data of the new node
else:
self.right.insert(node) # method calls self using the right child of the "current root" node as the new "current root" node
else:
self = node # node becomes root node(self node) (top of a child-parent node triangle)
def search(self,searchFor): # string of a name user is looking for
if searchFor == self.sData: # compares the string being searched for to the string value of the "current root" node
return self
else:
if self.left: # if this "current root" node has a left child that exists:
leftResult = self.left.search(searchFor) # calls this method for the left child, saves return value to var
if leftResult == None:
pass
else:
return leftResult
if self.right:
rightResult = self.right.search(searchFor)
if rightResult == None:
pass
else:
return rightResult
return None
def printTree(self):
if self.left:
self.left.printTree()
print("idata:", self.iData, " sdata:", self.sData)
if self.right:
self.right.printTree()
def dfs(self,list): # recursive in order DFS traversal
if self.left:
self.left.dfs(list)
#print("idata:", self.iData, " sdata:", self.sData)
list.append(self)
if self.right:
self.right.dfs(list)
return list
def bfs(self, list): # recursive BFS traversal
if not list: # to add first root node if list is empty
list.append(self)
# if the node has a left child it will add it to the list, if it has a right child, it will add it to the list
if self.left:
if self.left != None:
list.append(self.left)
if self.right:
if self.right != None:
list.append(self.right)
self.left.bfs(list)
self.right.bfs(list)
elif self.right:
if self.right != None:
list.append(self.right)
self.right.bfs(list)
return list
def decision_tree_results(self,list):
list = self.dfs(list) # gets the list in order of the the nodes
for response in list:
if response.sData == "no": # if a response to a question is no, it returns false because the object is not a planet
return False
# if response is yes, returns true
return True
|
"""
***************************************************************
* Title: first come first serve tickets
* Author: Brogan Avery
* Created : 2021-02-21
* Course: CIS 152 - Data Structure
* Version: 1.0
* OS: macOS Catalina
* IDE: PyCharm
* Copyright : This is my own original work based on specifications issued by the course instructor
* Description : An app that uses a queue to give tickets to customers until they run out
* Academic Honesty: I attest that this is my original work.
* I have not used unauthorized source code, either modified or
* unmodified. I have not given other fellow student(s) access
* to my program.
***************************************************************
"""
from Queue import Queue
from random import randrange
# MAIN--------------------------------------------------------------------
if __name__ == '__main__':
# the instructions did not specify to use the language built in queue or not so I am taking the safe route and using my custom queue class
maxSize = 1000 # up to 1000 people are allowed to stand in line.
numPeople = randrange(1,maxSize + 1) # the range in python stops one before the second number, so to end at 1000, i have to put 1001
theLine = Queue(maxSize) # make the queue of 1000 to put up to 1000 people in
unhappyCustomers = 0 # used to track the people who leave the line from not being able to get enough tickets
for person in range(1,numPeople): # fills the line with how ever many people get in line
theLine.enqueue(person)
theLineStartSize = theLine.get_size() # how many people got in line
print(theLineStartSize, "people are in the line ")
# ===== SCENARIO 1 =====
numTicketsLeft = 10 # total available tickets left to purchase
for person in range(1,numPeople):
while numTicketsLeft != 0:
numTicketsWanted = randrange(1, 5) # for each person
print("The next person in line wants", numTicketsWanted)
if numTicketsLeft >= numTicketsWanted:
numTicketsLeft = numTicketsLeft - numTicketsWanted
print("The person was given", numTicketsWanted)
print("There are now ", numTicketsLeft, "left to sell")
theLine.dequeue()
else:
print("Sorry, we do not have the number of tickets you requested. Get Lost.") # i am assuming that if a person wants 4 tickets and only 2 are left they will just leave and not buy only 2 since that would leave out their friends and thats mean :(
theLine.dequeue()
unhappyCustomers = unhappyCustomers + 1 # so I can subtract from the total number of people served since they leave the line but do not buy tickets. We just assume they are angry and leave.
if numTicketsLeft == 0:
print("SOLD OUT")
theLineEndSize = theLine.get_size() # how many people were left in line
numPeopleSoldTo = theLineStartSize - theLineEndSize - unhappyCustomers # gets the number of people that bought tickets (removes the people who left because they could not buy enough)
print(numPeopleSoldTo, "people bought tickets")
print("there are",numTicketsLeft, "left unsold")
# ==== SCENARIO 2 ====
numTicketsLeft = 100 # total available tickets left to purchase
for person in range(1, numPeople):
while numTicketsLeft != 0:
numTicketsWanted = randrange(1, 5) # for each person
print("The next person in line wants", numTicketsWanted)
if numTicketsLeft >= numTicketsWanted:
numTicketsLeft = numTicketsLeft - numTicketsWanted
print("The person was given", numTicketsWanted)
print("There are now ", numTicketsLeft, "left to sell")
theLine.dequeue()
else:
print(
"Sorry, we do not have the number of tickets you requested. Get Lost.") # i am assuming that if a person wants 4 tickets and only 2 are left they will just leave and not buy only 2 since that would leave out their friends and thats mean :(
theLine.dequeue()
unhappyCustomers = unhappyCustomers + 1 # so I can subtract from the total number of people served since they leave the line but do not buy tickets. We just assume they are angry and leave.
if numTicketsLeft == 0:
print("SOLD OUT")
theLineEndSize = theLine.get_size() # how many people were left in line
numPeopleSoldTo = theLineStartSize - theLineEndSize - unhappyCustomers # gets the number of people that bought tickets (removes the people who left because they could not buy enough)
print(numPeopleSoldTo, "people bought tickets")
print("there are", numTicketsLeft, "left unsold")
# ==== SCENARIO 3 ====
numTicketsLeft = 1000 # total available tickets left to purchase
for person in range(1, numPeople):
while numTicketsLeft != 0:
numTicketsWanted = randrange(1, 5) # for each person
print("The next person in line wants", numTicketsWanted)
if numTicketsLeft >= numTicketsWanted:
numTicketsLeft = numTicketsLeft - numTicketsWanted
print("The person was given", numTicketsWanted)
print("There are now ", numTicketsLeft, "left to sell")
theLine.dequeue()
else:
print(
"Sorry, we do not have the number of tickets you requested. Get Lost.") # i am assuming that if a person wants 4 tickets and only 2 are left they will just leave and not buy only 2 since that would leave out their friends and thats mean :(
theLine.dequeue()
unhappyCustomers = unhappyCustomers + 1 # so I can subtract from the total number of people served since they leave the line but do not buy tickets. We just assume they are angry and leave.
if numTicketsLeft == 0:
print("SOLD OUT")
theLineEndSize = theLine.get_size() # how many people were left in line
numPeopleSoldTo = theLineStartSize - theLineEndSize - unhappyCustomers # gets the number of people that bought tickets (removes the people who left because they could not buy enough)
print(numPeopleSoldTo, "people bought tickets")
print("there are", numTicketsLeft, "left unsold")
|
"""
***************************************************************
* Class Name: Graph
* Author: Brogan Avery
* Created: 2021-03-25
***************************************************************
"""
class Graph:
def __init__(self, numNodes):
self.numNodes = numNodes # number of nodes on the graph
self.graph = [] # empty list to store lists that contain 2 nodes and an edge
def add_edge(self, nodeA, nodeB, edgeBetween): # an edge can also be like a row of a graph/dict
self.graph.append([nodeA, nodeB, edgeBetween]) # add a list that represents node A, Node B, and the distance or weight between
def find(self, nodeCountList, i):
if nodeCountList[i] == i:
return i
return self.find(nodeCountList, nodeCountList[i])
def apply_union(self, nodeCountList, rank, x, y): # adds parents to children
xroot = self.find(nodeCountList, x)
yroot = self.find(nodeCountList, y)
if rank[xroot] < rank[yroot]:
nodeCountList[xroot] = yroot
elif rank[xroot] > rank[yroot]:
nodeCountList[yroot] = xroot
else:
nodeCountList[yroot] = xroot
rank[xroot] += 1
def kruskals_algo(self):
result = []
i, i2 = 0, 0 # index places
# print(self.graph)
self.graph = sorted(self.graph, key=lambda item: item[2])
nodeCountList = [] # will be a count for the number of nodes on graph, ex: [0,1,2,3,4,5,6,7,8,9]
rank = [] # will fill with 0s
for node in range(self.numNodes):
nodeCountList.append(node)
rank.append(0)
while i2 < self.numNodes - 1:
nodeA, nodeB, edgeBetween = self.graph[i] # adds edge list to graph list
i = i + 1
x = self.find(nodeCountList, nodeA.iData)
y = self.find(nodeCountList, nodeB.iData)
if x != y:
i2 = i2 + 1
result.append([nodeA.sData, nodeB.sData, edgeBetween]) # adds lists to list
self.apply_union(nodeCountList, rank, x, y)
return result
|
"""
***************************************************
Title: file IO
Author: Brogan Avery
Created: 2020-02-25
Description :
OS: macOS Catalina
Copyright : This is my own original work based on specifications issued by the course instructor
***************************************************
"""
def write_to_file(some_tuple):
with open("student_info.txt", "a") as file:
file.write(str(some_tuple))
file.write('\n')
def get_student_info(name):
score_list = []
score = 0
while (score > -1 ):
try:
score = int(input("Enter (next) test score. Enter -1 when finished: "))
score_list.append(score)
except ValueError:
print("Enter test score. When fisnished, enter -1")
score_list.remove(-1)
name_score_tuple = (name, score_list)
write_to_file(name_score_tuple)
def read_from_file():
with open("student_info.txt") as file:
for line in file:
print(line)
if __name__ == '__main__':
count = 0
open("student_info.txt","w").close()
first_tuple = (1,2,3,4,5)
write_to_file(first_tuple)
while (count <5):
student_name = input("Enter your name:")
get_student_info(student_name)
count = count + 1
read_from_file()
|
# isomorphism example
test_case = 3
if test_case == 1:
g = {
'A': ['B', 'C'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D', 'F'],
'D': ['B', 'C'],
'E': ['F'],
'F': ['C', 'E']
}
h = {
'1': ['2', '3'],
'2': ['1', '3'],
'3': ['1', '2']
}
elif test_case == 2:
g = {
'A': ['B', 'C'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D', 'F'],
'D': ['B', 'C', 'E', 'F'],
'E': ['D', 'F'],
'F': ['C', 'D', 'E']
}
h = {
'1': ['2', '5'],
'2': ['1', '3'],
'3': ['2', '4'],
'4': ['3', '5'],
'5': ['4', '1']
}
elif test_case == 3:
g = {
'u': ['v', 'w'],
'v': ['u', 'w'],
'w': ['u', 'v', 'z'],
'z': ['w']
}
h = {
'a': ['b', 'f'],
'b': ['a', 'c'],
'c': ['b'],
'd': ['e'],
'e': ['d', 'f'],
'f': ['a', 'e', 'g'],
'g': ['f', 'h'],
'h': ['g']
}
else:
g = {
'1': ['2'],
'2': ['1', '3'],
'3': ['2']
}
h = {
'A': ['B', 'C', 'D', 'E'],
'B': ['A', 'C', 'D', 'E'],
'C': ['A', 'B', 'D', 'E'],
'D': ['A', 'B', 'C', 'E'],
'E': ['A', 'B', 'C', 'D']
}
degree_g = {}
degree_h = {}
candidates_g = {}
candidates_h = {}
# O(|V|)
for node in g:
degree_g[node] = len(g[node])
candidates_g[node] = []
for node in h:
degree_h[node] = len(h[node])
# print 'List of degrees in G'
# for t in degree_g:
# print t, degree_g[t]
# print 'List of degrees in H'
# for t in degree_h:
# print t, degree_h[t]
# Check candidates of G and H with the vertex degree similarity
# O(|V|^2)
for node in h:
for nodeg in g:
if degree_h[node] >= degree_g[nodeg]:
candidates_g[nodeg].append(node)
# Refine M
# O(|V|^2 x |E|^2)
for nodeg in g:
for candidate in candidates_g[nodeg]:
for neighboor in g[nodeg]:
aux = False
if len(candidates_g[neighboor]) > 0:
for neighboor_candidate in candidates_g[neighboor]:
if neighboor_candidate in h[candidate]:
aux = True
if aux == False:
candidates_g[nodeg].remove(candidate)
for nodeg in g:
print nodeg, candidates_g[nodeg]
def ullmann(G, H, candidates, assignments):
print G
print H
print candidates
print assignments
assignments = 0
ullmann(g, h, candidates_g, assignments) |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 25 18:41:32 2020
https://towardsdatascience.com/natural-language-processing-count-vectorization-with-scikit-learn-e7804269bb5e
@author: acorso
"""
from sklearn.feature_extraction.text import CountVectorizer
# To create a Count Vectorizer, we simply need to instantiate one.
# There are special parameters we can set here when making the vectorizer, but
# for the most basic example, it is not needed.
vectorizer = CountVectorizer()
# For our text, we are going to take some text from our previous blog post
# about count vectorization
sample_text = ["One of the most basic ways we can numerically represent words "
"is through the one-hot encoding method (also sometimes called "
"count vectorizing)."]
# To actually create the vectorizer, we simply need to call fit on the text
# data that we wish to fix
vectorizer.fit(sample_text)
# Now, we can inspect how our vectorizer vectorized the text
# This will print out a list of words used, and their index in the vectors
print('Vocabulary: ')
print(vectorizer.vocabulary_)
# If we would like to actually create a vector, we can do so by passing the
# text into the vectorizer to get back counts
vector = vectorizer.transform(sample_text)
# Our final vector:
print('Full vector: ')
print(vector.toarray())
# Or if we wanted to get the vector for one word:
print('Hot vector: ')
print(vectorizer.transform(['hot']).toarray())
# Or if we wanted to get multiple vectors at once to build matrices
print('Hot and one: ')
print(vectorizer.transform(['hot', 'one']).toarray())
# We could also do the whole thing at once with the fit_transform method:
print('One swoop:')
new_text = ['Today is the day that I do the thing today, today']
new_vectorizer = CountVectorizer()
print(new_vectorizer.fit_transform(new_text).toarray())
|
# In this section I am studying reading and writing files using python.
# I downloaded the first gene from E. coli and saved it as gene.fa
# reading files
my_file = open("gene.fa")
# It is not the same interaction of strings.
print(my_file)
# <open file 'gene.fa', mode 'r' at 0x10a7ac660>
# So working with files need different commands like:
file_contents = my_file.read()
print(file_contents)
# working with fasta or fastq files will bring an issue. How to deal with newlines?
my_file = open("gene.fa")
my_file_contents = my_file.read()
# then remove the newline from the end of the file contents
my_dna = my_file_contents.rstrip("\n")
dna_lentgh = len(my_dna)
print("sequence is " + my_dna + " and lentgh is " + str(dna_lentgh))
# or you can do it in only one line:
# my_dna = my_file.read().rstrip("\n")
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author:sisul
# time: 2020/7/7 17:39
# file: 数学运算、逻辑运算和进制转化相关的 16 个内置函数.py
'''数学运算'''
#len(s)
dic = {'a':1,'b':3}
print(len(dic))
#max(iterable,*[,key,default])
print(max(3,1,4,2,1))
print(max((), default=0))
di = {'a':3,'b1':1,'c':4}
print(max(di))
a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'xiaohong','age':20,'gender':'female'}]
print(max(a, key=lambda x: x['age']))
def max_length(*lst):
return max(*lst, key=lambda x:len(x))
print(max_length([1, 2, 3], [4, 5, 6, 7], [8]))
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author:sisul
# time: 2020/7/14 9:27
# file: Python对象间的相等性比较等使用总结.py
'''
Python,对象相等性比较相关关键字包括is、in,比较运算符有==。
is判断两个对象的标识号是否相等
in用于成员检测
==用于判断值或内容是否相等,默认是基于两个对象的标识号比较
也就是说,如果a is b为 True且如果按照默认行为,意味着a == b也为True
'''
'''
is判断标识号是否相等
is比较的是两个对象的标识号是否相等,python中使用id()函数获取对象的标识号
'''
a = [1,2,3]
print(id(a))
b = [1,2,3]
print(id(b))
#创建的两个列表实例位于不同的内存地址,所以它们的标识号不等
print(a is b)
#即便对于两个空列表实例,它们is比较的结果也是False
a, b = [], []
print(a is b)
#对于序列类、字典型、集合型对象,一个对象实例指向另一个对象实例,is比较才返回真值
a, b = {'a':[1,2,3]},{'id':'book id', 'price':'book price'}
a = b
print(a == b, '---')
print(id(a))
print(id(b))
'''
对于值类型而言,不同的编译器可能会做不同的优化。从性能角度考虑,它们会缓存一些值类型的对象实例。
所以,使用is比较时,返回的结果看起来会有些不太符合预期。如:
'''
a = 123
b = 123
print(a is b)
c = 123456
d = 123456
print(c is d) #pycharm结果是True,但是shell显示False
'''
Python解释器,对位于区间[-5, 256]内的小整数,会进行缓存,
不在该范围内的不会缓存
'''
#Python中的None对象是一个单例类的实例,具有唯一的标识符
print(id(None))
#在判断某个对象是否为None时,最便捷的做法:variable is None
a = None
print(a is None)
print(id(a))
'''
in 用于成员检测
如果元素i是s的成员,则i in s为True:
若不是s的成员,则返回False,也就是i not in s为True
'''
#对于字符串类型, i in s为True,意味着i是s的子串,也就是s.find(i)返回大于-1的值
print('ab' in 'abc')
print('abc'.find('ab'))
print('ab' in 'acb')
print('acb'.find('ab'))
#内置的序列类型、字典类型和集合类型,都支持in操作。对于字典类型,in操作判断i是否是字典的键
print([1, 2] in [[1,2], 'str'])
print('apple' in {'orange':1.5,'banana':2.3,'apple':5.2})
'''
对于自定义类型,判断是否位于序列类型中,需要重写序列类型的魔法函数__contains__。
具体操作步骤如下:
自定义Student类,无特殊之处
Students类继承list,并重写__contains__方法
'''
class Student:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, val):
self._name = val
class Students(list):
def __contains__(self, item):
for s in self:
if s.name == item.name:
return True
return False
s1 = Student('xiaoming')
s2 = Student('xiaohong')
a = Students()
a.extend([s1, s2])
s3 = Student('xiaoming')
print(s3 in a)
s4 = Student('xiaoli')
print(s4 in a)
'''
==判断值是否相等
对于数值型、字符串、列表、字典、集合,默认只要元素值相等,==比较结果就是True
'''
str1 = "alg-channel"
str2 = "alg-channel"
print(str1 == str2)
'''
对于自定义类型,当所有属性取值完全相同的两个实例,判断==时,返回False。
但是,大部分场景下,我们希望这两个对象相等的,这样不用重复添加到列表中。
例如,判断用户是否已经登入时,只要用户所有属性与登入列表中某个用户完全一致时,就认为已经登入。
如下所示,需要重写方法__eq__,使用__dict__获取实例的所有属性
'''
print('*'*100)
class Student:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, val):
self._name = val
@property
def age(self):
return self._age
@age.setter
def age(self, val):
self._age = val
def __eq__(self, val):
print(self.__dict__)
return self.__dict__ == val.__dict__
a = []
xiaoming = Student('xiaoming', 29)
if xiaoming not in a:
a.append(xiaoming)
xiaohong = Student('xiaohong', 30)
if xiaohong not in a:
a.append(xiaohong)
xiaoming2 = Student('xiaoming', 29)
if xiaoming2 == xiaoming:
print('对象完全一致,相等')
if xiaoming2 not in a:
a.append(xiaoming2)
print(len(a)) |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author:sisul
# time: 2020/7/14 15:07
# file: yield关键字和生成器.py
'''
yield
理解yield,可结合函数的返回值关键字return,yield是一种特殊的return。说是特殊的return,是因为执行遇到yield时,立即返回,这是与return的相似之处。
不同之处在于:下次进入函数时直接到yield的下一个语句,而return后再进入函数,还是从函数的第一行代码开始执行。
带yield的函数是生成器,通常与next函数结合用。下次进入函数,意思是使用next函数进入到函数体内
'''
def f():
print('enter f...')
return 'hello'
ret = f()
print(ret)
print('*'*100)
'''
send函数
'''
def f():
print('enter f...')
while True:
result = yield 4
if result:
print('send me a value is:%d'%(result,))
return
else:
print('no send')
g = f()
print(next(g))
print('ready to send')
# print(g.send(10))
print('*'*100)
'''
更多使用yield案例
1.完全展开list
'''
def deep_flatten(lst):
for i in lst:
if type(i) == list:
yield from deep_flatten(i)
else:
yield i
gen = deep_flatten([1, ['s', 3], 4,5])
print(gen)
for i in gen:
print(i)
'''
列表分组
'''
from math import ceil
def divide_iter(lst, n):
if n <= 0:
yield lst
return
i, div = 0, ceil(len(lst) / n)
while i < n:
yield lst[i * div: (i+1) * div]
i += 1
print(list(divide_iter([1, 2, 3, 4, 5], 0)))
print(list(divide_iter([1, 2, 3, 4, 5], 2)))
'''
nonlocal关键字,声明为非局部变量
'''
def f():
i = 0
def auto_increase():
nonlocal i
if i >= 10:
i = 0
i += 1
ret = []
for _ in range(28):
auto_increase()
ret.append(i)
print(ret)
f()
|
## The script asks a number from the user, and prints all the numbers smaller than this number that are primes:
def is_number_prime(number):
'''
Checks whether a number is prime (returns True) or not (returns False).
'''
is_prime = True
for i in range(2,number):
if number%i==0:
is_prime = False
break
return(is_prime)
## Ask for user input:
number = int(input("Give an integer number greater than 1: \n"))
while True:
if number <1:
number = int(input("The number should be an integer greater than 1. Try again: \n"))
else:
break
## Store all the prime numbers in a list:
all_prime_numbers = list()
for candidate_prime in range(2, number):
if is_number_prime(candidate_prime):
all_prime_numbers.append(candidate_prime)
## Print the output:
print("Below are all the numbers that are smaller than {} and are primes: ".format(number))
print("\t {}".format(all_prime_numbers))
|
mylist = [1,2,3,4,5,6,7,8]
mylist.append(9)
print(mylist)
mylist.pop()
print(mylist)
#functions
def say_hello(name='Name'):
"""
:return:this function will print hello...just that nothing else...this is a stupid function..this is for
people who does not understand my code
"""
return 'hello ' +name
#you can use both print and return the result using return to you later in the code
result = say_hello('Trishla')
print(result)
def adding(a,b):
"""
:param a:can be any number
:param b:this can also be any number
:return:the sub of both
"""
return a+b
result = adding(1.32,4.33)
print(result)
print('Pig Latin')
def pig_latin(word):
"""
:param word: can be any word. if start with vovel add 'ay' to the end, if does not start with vovel
add first letter to the end and add 'ay' after that
:return:Funny!!
"""
if word[0] in 'aeiou':
pig_word = word+'ay'
else:
pig_word = word[1:]+word[0]+'ay'
result = pig_word
print(result)
pig_latin('abhishek')
pig_latin('trishla')
pig_latin('asha')
pig_latin('akshat')
pig_latin('bhanu')
print('*args and *kwargs')
#Arguments and Keyword Arguments
#*args return a Tuple
def myfunc(*args): #you can use any word in place of args
return sum(args) * 3.75
myfunc(10,20,30,40,50)
print(result)
#**kwards return a dictionary
def myfunc2(**kwargs):#you can use any work in place of kwargs
print(kwargs)
myfunc2(fruit='apple',veggie='Lettuce',game='Basketball')
#We can use args and kwargs in combination also
def myfunc3(*args,**kwargs ):
print(args)
print(kwargs)
print('I would like to have {} {}'.format(args[1],kwargs['food']))
myfunc3(10,20,30,food='Pizza',fruit='I like only Juice',meat='chorizo')
#We can use any number of variables without defining in advance
def myfunc4(name):
res = ''
for i in range(len(name)):
if not i % 2:
res = res + name[i].upper()
else:
res = res + name[i].lower()
print(res)
#how to print only once ?? Need to check
myfunc4('Abhishek')
|
# Ard van Balkom, 9-2-19
# Problem 4. Asks user for a positive integer. then output the successive value.
# If current value is even, then it is divided by 2. If current value is odd, it is multiplied by 3 and 1 is added. If current value is 1, the program ends.
while True: # Run a while loop that will run indefinitely.
try: # Test the next block of code for errors
num = int( input("Please enter a positive integer: ")) # Ask the user to input a positive integer. The input from the user is the variable 'num'.
except ValueError: # Don't run the rest of the program if the user makes a ValueError (enters a non-integer), instead run the following print command.
print("That is not an integer, try again") # If the user enters a non numeric input, a message will show and program runs again.
continue # Return to the beginning of the loop, so user can try again to enter an integer.
if num <= 0: # If the user enters a number that is 0 or lower than 0, a message will show and program runs again.
print("That is not a positive integer, try again")
continue # Return to the beginning of the loop, so user can try again to enter an integer.
# Adapted from: https://stackoverflow.com/questions/23326099/how-can-i-limit-the-user-input-to-only-integers-in-python
# Used page 82 of http://spronck.net/pythonbook/pythonbook.pdf to learn about the infinite while loop.
total = 0 # Create a variable 'total', starting at 0, that will be calculated after user enters 'num' and will be printed.
while num != 1 and num >= 0: # Keep running the loop until num == 1
if num %2 == 0: # Check if 'num' is an even number by using the modulo operator. If it is, divide it by 2.
total = int((num /2)) # Calculate the new total as an integer.
print(total, end= " ") # Print the new total, and display it with a space between the numbers.
num = total # When starting the loop again the new value of 'num' will be the value of 'total'.
else:
total = int((num * 3 +1)) # If 'num' is an odd number, multiply it by 3 and add 1.
print(total, end= " ") # Print the new total, and display it with a space between the numbers.
num = total # When starting the loop again the new value of 'num' will be the value of 'total'.
break # The program ends after ending this the while loop. |
'''Define political office model and its methods. '''
import datetime
OFFICE_DB = []
class OfficeModel:
"""
Description:Handle all the operations related to political offices.\n
"""
def __init__(self,office_name, office_type):
"""
Description:Define the instance variables.\n
"""
self.office_id = len(OFFICE_DB)+1
self.office_name = office_name
self.office_type = office_type
self.created_on = datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
def create_political_office(self):
"""
Description:Create a political office.\n
"""
try:
new_office = dict(
office_id = self.office_id,
office_name = self.office_name,
office_type = self.office_type,
created_on = self.created_on
)
OFFICE_DB.append(new_office)
return new_office
except Exception as error:
raise Exception(error)
@classmethod
def get_all_offices(cls):
"""
Description:Return a list of all political parties.\n
"""
return OFFICE_DB
@classmethod
def check_office_exists(cls,office_id):
"""
Description:Check if a specific political office does exist.\n
Required Args: office_id.\n
"""
for office in OFFICE_DB:
if office['office_id'] == office_id:
return office
return None
@classmethod
def get_office_by_id(cls,office_id):
"""
Description:Return a specific political office given the office id if it does exist.\n
"""
the_office = OfficeModel.check_office_exists(office_id)
return the_office
@classmethod
def update_office(cls,office,*args, **kwargs):
"""
Description:Updates a political office with the user defined information.\n
"""
for key, value in kwargs.items():
office[key] = value
return OFFICE_DB
@classmethod
def delete_office(cls,office):
"""
Description:Delete a political office if it exists.\n
"""
OFFICE_DB.remove(office)
return 'Successfully deleted political office.' |
class MPNeuron:
def __init__(self):
self.w = []
self.x = []
for i in range(3):
self.w.append(1)
self.x.append(1)
self.threshold = 2.5
def MP_Neuron_Input(self,n,threshold):
self.w = []
self.x = []
for i in range(n):
win = input()
self.w.append(int(win))
for i in range(n):
xin = input()
self.x.append(int(xin))
self.threshold = threshold
def MP_Neuron_Evaluate(self):
final_value = 0
for i in range(len(self.w)):
final_value += self.w[i]*self.x[i]
if(final_value>self.threshold):
return 1
else:
return 0
Test = MPNeuron()
print(Test.MP_Neuron_Evaluate())
#For Three input NAND Gate, we have weights as [1,1,1] and Threshold of 2.
Test.MP_Neuron_Input(3,2)
print(Test.MP_Neuron_Evaluate()) |
list1=[1,2,3,4,5]
list2=[8,9,10,11,12]
list1.append(6)
print(list1)
list2.append(13)
print(list2)
print(list1+list2)
|
import random
def headOrTail(max):
head = False
tail = False
headCount = 0
tailCount = 0
for num in range(1, max):
coin = random.randint(0, 1)
isHead = ""
isTail = ""
if coin == 0:
head = True
tail = False
isHead = "It's a head!"
headCount+=1
print "Attempt #{} Throwing a coin... {} ... Got {} heads so far and {} tails so far".format(num, isHead, headCount, tailCount)
elif coin == 1:
head = False
tail = True
isTail = "It's a tail!"
tailCount+=1
print "Attempt #{} Throwing a coin... {} ... Got {} heads so far and {} tails so far".format(num, isTail, headCount, tailCount)
headOrTail(5001)
|
#This is a program which will tell the age
age =input("Please enter your age or the year you borned: ")
count = len(age)
if(count==2 or count==3):
age = int(age)
if(age==0 or age<0):
print("What the fuck man! You are not born yet.")
elif(age>100 and age<200):
print("You might be the oldest man alive on earth")
elif(age>200):
print("Man I have no words to say. You might be immortal")
else:
years_need = 100-age
print(f"You will be 100 years old in {2019+years_need}")
elif(count==4):
age = int(age)
if(age>2019):
print("What the fuck man! you are not borned yet.")
elif(age<1920 and age>1850):
print("You might be the oldest man alive on earth")
elif(age<1850):
print("Man you might be immortal!")
else:
age_now = 2019-age
years_need = 100 - age_now
print(f"You will be 100 years old in {2019+years_need}")
|
# Summation of primes
from math import sqrt
# using check primes algorithm
def check_primes(n):
for i in range(2, int(sqrt(n))+1):
if n % i == 0:
return False
return True
# using Sieve of Eratosthenes algorithm
def getPrimes(limit):
numList = [x for x in range(2, limit+1)]
primeIdx = 0
while primeIdx < len(numList):
if numList[primeIdx] != 0:
multipleIdx = primeIdx + numList[primeIdx]
while multipleIdx < len(numList):
numList[multipleIdx] = 0
multipleIdx += numList[primeIdx]
primeIdx += 1
return numList
def main():
primeList = getPrimes(2*(10**6))
return sum(primeList)
if __name__ == "__main__":
print(main())
|
class LinkedList:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __init__(self):
self.head = None
self.count = 0
def prepend(self, value):
self.head = LinkedList.Node(value, next=self.head)
self.count += 1
def append(self, value):
if len(self) == 0:
self.prepend(value)
else:
n = self.head
while n.next:
n = n.next
n.next = LinkedList.Node(value, next=None)
self.count += 1
def del_head(self):
assert(len(self) > 0)
if self.head:
self.head = self.head.next
self.count -= 1
def __len__(self):
return self.count
def __iter__(self):
n = self.head
while n:
yield n.val
n = n.next
def __repr__(self):
return '[' + ', '.join(str(x) for x in self) + ']'
|
def binarySearch(lst, target):
left, right = 0, len(lst)-1
while left <= right:
mid = (right - left)//2 + left
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
|
# Amicable number
from math import sqrt
def divisors(n):
div = [1]
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
if n // i == i:
div.append(i)
else:
div.extend([i, n//i])
return div
def isAmicable(n):
divSum = sum(divisors(n))
if sum(divisors(divSum)) == n:
return True
return False
def main():
result = 0
for i in range(10000):
if isAmicable(i):
result += i
return result
if __name__ == "__main__":
print(main())
|
#In this section We are going to learn about Objects or Dictonary
# If you have Previous Progaming background you have learn something about objects
# if not dont woory you will learn in this section
myObj = {'name':'Ghayyas','age':21,'study':'Software Engeering'};
print myObj; #Return all the objects
#let says we want just property of name
print myObj['name']; #it prints Ghayyas
#to clear all objects we typed
myObj.clear();
print myObj; # returns empty objects
# has_key in python
findTheKey = {'name':'ghayyas','age':21,'ocupation':'software engeenier'};
print findTheKey.has_key('name'); # returns true
|
"""
Module: Snake Iteration 7
Author: Koby (Beaulieu|Soden)
University of San Diego
Description:
A Python implementation of Greedy Snake, using Tkinter, and implemented
using the model-view-controller design pattern.
Iteration 6:
Final iteration of the snake program. This last iteration implements the event
handler functions in the controller (the Snake class) that were created
as stub functions in iteration 4.
"""
import tkinter as tk
from tkinter.font import Font
from enum import IntEnum
import unittest
import random as rand
import collections
from datetime import datetime
import math
class GameOver(Exception):
pass
class snake:
""" This is the controller """
def __init__(self):
""" Initializes the snake game """
#define parameters
self.NUM_ROWS = 30
self.NUM_COLS = 30
self.model = None
self.mode = Mode.Norm
self.GameState = GameState.Initial
self.DEFAULT_STEP_TIME_MILLIS = 500
# Create view
self.view = SnakeView(self.NUM_ROWS, self.NUM_COLS) #initialize snakeview object
#create model
self.model = SnakeModel(self.NUM_ROWS, self.NUM_COLS)
#time step length variable
self.step_time_millis = self.DEFAULT_STEP_TIME_MILLIS
# Start
self.view.set_start_handler(self.start_handler)
# Pause
self.view.set_pause_handler(self.pause_handler)
# Reset
self.view.set_reset_handler(self.reset_handler)
# Quit
self.view.set_quit_handler(self.quit_handler)
# Step speed
self.view.set_step_speed_handler(self.step_speed_handler)
#Wrap around
self.view.set_wraparound_handler(self.wraparound_handler)
#up key
self.view.set_up_arrow_handler(self.up_handler)
#down key
self.view.set_down_arrow_handler(self.down_handler)
#right Key
self.view.set_right_arrow_handler(self.right_handler)
#left key
self.view.set_left_arrow_handler(self.left_handler)
self.time_elapsed = 0
# Start the simulation
self.view.window.mainloop()
def start_handler(self):
if self.GameState != GameState.Playing and self.GameState != GameState.Ended:
self.GameState = GameState.Playing
self.view.schedule_next_step(self.step_time_millis,
self.continue_simulation)
print("Start simulation")
def pause_handler(self):
""" Pause simulation """
if self.GameState == GameState.Playing:
self.GameState = GameState.Paused
self.view.cancel_next_step()
print("Pause simulation")
def reset_handler(self):
""" Reset simulation """
self.pause_handler()
self.view.reset()
self.mode = self.model.mode #save game mode for after reset
self.model = SnakeModel(self.NUM_ROWS, self.NUM_COLS)
self.model.mode = self.mode
self.GameState = GameState.Initial
self.view.time_diff.set('Time: 00.00')
self.time_elapsed = 0
self.view.score_per_second.set('Points per second: 0.00')
print("Reset simulation")
def quit_handler(self):
""" Quit life program """
self.view.window.destroy()
def step_speed_handler(self, value):
""" Adjust simulation speed"""
self.step_time_millis = int(self.DEFAULT_STEP_TIME_MILLIS/int(value))
print("Step speed: Value = %s" % self.step_time_millis)
def wraparound_handler(self):
"""Enables wraparound mode"""
if self.mode == Mode.Wrap:
self.mode = Mode.Norm
elif self.mode == Mode.Norm:
self.mode = Mode.Wrap
if self.model == None:
pass
else:
self.model.mode = self.mode
def up_handler(self, event):
"""up button"""
if self.model.direction != DirectionState.down or len(self.model.snake) == 1:
self.model.direction = DirectionState.up
def down_handler(self, event):
"""down button"""
if self.model.direction != DirectionState.up or len(self.model.snake) == 1:
self.model.direction = DirectionState.down
def left_handler(self, event):
"""left button"""
if self.model.direction != DirectionState.right or len(self.model.snake) == 1:
self.model.direction = DirectionState.left
def right_handler(self, event):
"""right button"""
if self.model.direction != DirectionState.left or len(self.model.snake) == 1:
self.model.direction = DirectionState.right
def continue_simulation(self):
""" Perform another step of the simulation, and schedule the next step."""
if self.GameState == GameState.Playing:
self.one_step()
self.view.schedule_next_step(self.step_time_millis, self.continue_simulation)
self.time_elapsed += self.step_time_millis/1000
def one_step(self):
""" Simulate one step """
try:
# Update the model
self.model.one_step()
# Update the view
for row in range(self.NUM_ROWS):
for col in range(self.NUM_COLS):
#print(row, col)
if self.model.state[row][col] == CellState.Snake:
self.view.make_snake_body(row, col)
#check for snake head
elif self.model.state[row][col] == CellState.Food:
self.view.make_food(row, col)
else:
self.view.make_nothing(row, col)
head = self.model.snake[-1]
self.view.make_snake_head(head[0], head[1])
self.view.points_earned.set('Points: ' + str(self.model.points_earned))
if self.time_elapsed != 0:
self.view.score_per_second.set('Points per second: ' + str(round(self.model.points_earned/self.time_elapsed, 2)))
self.view.time_diff.set('Time: ' + str(round(self.time_elapsed, 2)) + 's')
except GameOver:
self.GameState = GameState.Ended
self.view.game_over.set('Game Over')
class SnakeView:
def __init__(self, num_rows, num_cols):
""" Initialize view of the game """
# Constants
self.cell_size = 20
self.control_frame_height = 100
self.score_frame_width = 200
# Size of grid
self.num_rows = num_rows
self.num_cols = num_cols
# Create window
self.window = tk.Tk()
self.window.title("Greedy Snake")
#string variables for time and points
self.points_earned = tk.StringVar()
self.points_earned.set("Points: 0 ")
self.game_over = tk.StringVar()
self.game_over.set(" ")
self.time_diff = tk.StringVar()
self.time_diff.set("Time: 00:00")
self.current_time = tk.StringVar()
self.score_per_second = tk.StringVar()
self.score_per_second.set('Points per second: ')
# Create frame for grid of cells
self.grid_frame = tk.Frame(self.window, height = num_rows * self.cell_size,
width = num_cols * self.cell_size)
self.grid_frame.grid(row = 1, column = 1) # use grid layout manager
self.cells = self.add_cells()
# Create frame for controls
self.control_frame = tk.Frame(self.window, width = 800,
height = self.control_frame_height)
self.control_frame.grid(row = 2, column = 1, columnspan = 2) # use grid layout manager
self.control_frame.grid_propagate(False)
(self.start_button, self.pause_button, self.step_speed_slider,
self.reset_button, self.quit_button, self.wraparound_check) = self.add_control()
#Create frame for score
self.score_frame = tk.Frame(self.window, width = self.score_frame_width,
height = num_rows * self.cell_size)
self.score_frame.grid(row = 1, column = 2) # use grid layout manager
self.score_frame.grid_propagate(False)
(self.score_label, self.points_frame, self.time_frame,
self.points_per_second_frame, self.gameover_label) = self.add_score()
def add_cells(self):
""" Add cells to the grid frame """
cells = []
for r in range(self.num_rows):
row = []
for c in range(self.num_cols):
frame = tk.Frame(self.grid_frame, width = self.cell_size,
height = self.cell_size, borderwidth = 1,
relief = "solid")
frame.grid(row = r, column = c) # use grid layout manager
row.append(frame)
cells.append(row)
return cells
def add_control(self):
"""Create control buttons and slider, and add them to the control frame"""
start_button = tk.Button(self.control_frame, text="Start")
start_button.grid(row=1, column=1, padx = 20)
pause_button = tk.Button(self.control_frame, text="Pause")
pause_button.grid(row=1, column=2, padx = 20)
step_speed_slider = tk.Scale(self.control_frame, from_=1, to=10,
label="Step Speed", showvalue=0, orient=tk.HORIZONTAL)
step_speed_slider.grid(row=1, column=4, padx = 20)
reset_button = tk.Button(self.control_frame, text="Reset")
reset_button.grid(row=1, column=5, padx = 20)
quit_button = tk.Button(self.control_frame, text="Quit")
quit_button.grid(row=1, column=6, padx = 20)
wraparound_check = tk.Checkbutton(self.control_frame, text = 'Wraparound')
wraparound_check.grid(row = 1, column = 7, padx = 20)
# Vertically center the controls in the control frame
self.control_frame.grid_rowconfigure(1, weight = 1)
# Horizontally center the controls in the control frame
self.control_frame.grid_columnconfigure(0, weight = 1)
self.control_frame.grid_columnconfigure(7, weight = 1)
return (start_button, pause_button, step_speed_slider,
reset_button, quit_button, wraparound_check)
def add_score(self):
"""Create labels and small frames and add them to the score frame"""
score_label = tk.Label(self.score_frame, text = 'Score', font = ("Times", 18) )
score_label.grid(row = 0, column = 1, pady = 30, padx = 25, sticky = 'N')
points_frame = tk.Frame(self.score_frame, highlightbackground = 'black', highlightthickness = 1)
points_frame.grid(row = 2, column = 1, columnspan = 5, sticky = 'N')
points_frame_label = tk.Label(points_frame, textvariable = self.points_earned)
points_frame_label.grid(row = 1, column = 1, sticky = 'W')
time_frame = tk.Frame(self.score_frame, highlightbackground = 'black', highlightthickness = 1)
time_frame.grid(row = 3, column = 1, pady = 30, columnspan = 3, sticky = 'N')
time_frame_label = tk.Label(time_frame, textvariable = self.time_diff)
time_frame_label.grid(row = 1, column = 1, sticky = 'W')
points_per_second_frame = tk.Frame(self.score_frame, highlightbackground = 'black', highlightthickness = 1)
points_per_second_frame.grid(row = 4, column = 1, columnspan = 3, sticky = 'N')
points_per_second_frame_label = tk.Label(points_per_second_frame, textvariable = self.score_per_second)
points_per_second_frame_label.grid(row = 1, column = 1, sticky = 'W')
gameover_label = tk.Label(self.score_frame, textvariable = self.game_over, font = ("Times", 18) )
gameover_label.grid(row = 5, column = 1, pady = 30, sticky = 'N')
#horizontally center the labels and frames in the score frame
self.score_frame.grid_columnconfigure(0, weight = 1)
self.score_frame.grid_columnconfigure(7, weight = 1)
return(score_label, points_frame, time_frame,
points_per_second_frame, gameover_label)
def make_snake_body(self, row, column):
""" Make cell in row, column into snake """
self.cells[row][column]['bg'] = 'blue'
def make_snake_head(self, row, column):
""" Make cell in row, column into snake head """
self.cells[row][column]['bg'] = 'black'
def make_nothing(self, row, column):
""" Make cell in row, column nothing"""
self.cells[row][column]['bg'] = 'white'
def make_food(self, row, column):
""" Make cell in row, column food """
self.cells[row][column]['bg'] = 'red'
def reset(self):
"""reset all cells to nothing"""
for r in range(self.num_rows):
for c in range(self.num_cols):
self.make_nothing(r, c)
self.game_over.set(" ")
self.points_earned.set("Points: 0")
def schedule_next_step(self, step_time_millis, step_handler):
""" schedule next step of the simulation """
self.start_timer_object = self.window.after(step_time_millis, step_handler)
def cancel_next_step(self):
""" cancel the scheduled next step of simulation """
self.window.after_cancel(self.start_timer_object)
def set_up_arrow_handler(self, handler):
""" set handler for pressing on the up key to the function handler """
self.window.bind('<Up>', handler)
def set_down_arrow_handler(self, handler):
""" set handler for pressing on the down key to the function handler """
self.window.bind('<Down>', handler)
def set_right_arrow_handler(self, handler):
""" set handler for pressing on the right key to the function handler """
self.window.bind('<Right>', handler)
def set_left_arrow_handler(self, handler):
""" set handler for pressing on the left key to the function handler """
self.window.bind('<Left>', handler)
def set_start_handler(self, handler):
""" set handler for clicking on start button to the function handler """
self.start_button.configure(command = handler)
def set_pause_handler(self, handler):
""" set handler for clicking on pause button to the function handler """
self.pause_button.configure(command = handler)
def set_reset_handler(self, handler):
""" set handler for clicking on reset button to the function handler """
self.reset_button.configure(command = handler)
def set_quit_handler(self, handler):
""" set handler for clicking on quit button to the function handler """
self.quit_button.configure(command = handler)
def set_step_speed_handler(self, handler):
""" set handler for dragging the step speed slider to the function handler """
self.step_speed_slider.configure(command = handler)
def set_wraparound_handler(self, handler):
"""set handler for clicking the wraparound check box to the function handler"""
self.wraparound_check.configure(command = handler)
class SnakeModel:
""" The model """
def __init__(self, num_rows, num_cols):
""" initialize the snake model """
self.num_rows = num_rows
self.num_cols = num_cols
self.points_earned = 0
self.mode = Mode.Norm
self.food_location = ()
self.open_cells = []
self.snake = collections.deque()
self.state = [[CellState.Nothing for c in range(self.num_cols)]
for r in range(self.num_rows)]
#random food and snake start positions
self.col = rand.randrange(0,self.num_cols)
self.row = rand.randrange(0,self.num_rows)
self.state = self.make_snake(self.row, self.col, self.state)
self.snake.append((self.row, self.col))
for c in range(self.num_cols):
for r in range(self.num_rows):
if r != self.row and c != self.col:
self.open_cells.append((r,c))
self.state = self.make_food(self.state)
#choose direction
self.direction = None
self.first_direction()
def first_direction(self):
'''Chooses an initial direction based on starting position of snake'''
distance_edge = 0
if self.col > distance_edge:
self.direction = DirectionState.left
distance_edge = self.col
if (self.num_cols-self.col) > distance_edge:
self.direction = DirectionState.right
distance_edge = self.num_cols-self.col
if self.row > distance_edge:
self.direction = DirectionState.up
distance_edge = self.row
if (self.num_rows-self.row) > distance_edge:
self.direction = DirectionState.down
distance_edge = self.num_rows-self.row
def make_snake(self, row, col, state):
"make square into snake"
state[row][col] = CellState.Snake
if row != self.row and col != self.col:
if (row, col) in self.open_cells:
self.open_cells.remove((row, col))
return state
def make_food(self, state):
"make square into food"
randcell = rand.randrange(len(self.open_cells))
row = self.open_cells[randcell][0]
col = self.open_cells[randcell][1]
self.food_location = (row, col)
state[row][col] = CellState.Food
return state
def make_nothing(self, row, col, state):
"make square into nothing"
state[row][col] = CellState.Nothing
self.open_cells.append((row, col))
return state
def reset(self):
""" Resets all cells to nothing"""
for r in range(self.num_rows):
for c in range(self.num_cols):
self.make_nothing(r, c, self.state)
def one_step(self):
""" Simulates one time step of simulation """
# Make array for state in next timestep
next_state = [[CellState.Nothing for c in range(self.num_cols)]
for r in range(self.num_rows)]
snake_head = self.snake[-1]
if self.direction == DirectionState.up and snake_head[0] != 0:
r = -1
c = 0
elif self.direction == DirectionState.down and snake_head[0] != self.num_rows-1:
r = 1
c = 0
elif self.direction == DirectionState.left and snake_head[1] != 0:
r = 0
c = -1
elif self.direction == DirectionState.right and snake_head[1] != self.num_cols-1:
r = 0
c = 1
elif self.mode == Mode.Wrap: #check for wraparound
if self.direction == DirectionState.up and snake_head[0] == 0:
r = self.num_rows -1
c = 0
if self.direction == DirectionState.down and snake_head[0] == self.num_rows - 1:
r = -self.num_rows +1
c = 0
if self.direction == DirectionState.left and snake_head[1] == 0:
r = 0
c = self.num_cols -1
if self.direction == DirectionState.right and snake_head[1] == self.num_cols - 1:
r = 0
c = -self.num_cols + 1
else:
pass
else:
raise GameOver #you lose
if self.state[snake_head[0]+r][snake_head[1]+c] == CellState.Snake:
raise GameOver #end game
if self.state[snake_head[0]+r][snake_head[1]+c] == CellState.Food:
next_state = self.make_snake(snake_head[0]+r, snake_head[1]+c, next_state)
self.snake.append((snake_head[0]+r, snake_head[1]+c))
next_state = self.make_food(next_state)
self.points_earned +=1
if self.state[snake_head[0]+r][snake_head[1]+c] == CellState.Nothing:
next_state = self.make_snake(snake_head[0]+r, snake_head[1]+c, next_state)
next_state = self.make_nothing(self.snake[0][0], self.snake[0][1], next_state)
self.snake.append((snake_head[0]+r, snake_head[1]+c))
a = self.snake.popleft()
next_state[self.food_location[0]][self.food_location[1]] = CellState.Food
for i in self.snake: #updates snake squares into next state
next_state = self.make_snake(i[0], i[1], next_state)
self.state = next_state
class CellState(IntEnum):
"""
Use IntEnum so that the test code below can
set cell states using 0's 1's and 2's
"""
Nothing = 0
Snake = 1
Food = 2
class DirectionState(IntEnum):
up = 0
down = 1
right = 2
left = 3
class Mode(IntEnum):
Norm = 0
Wrap = 1
class GameState(IntEnum):
Initial = 0
Playing = 1
Paused = 2
Ended = 3
class SnakeModelTest(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.model = SnakeModel(5, 5)
self.model.snake = LL()
def test_one_step(self):
# Test just one step of the snake simuation
self.model.snake.addFirst((3,2))
self.model.state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,1,0,0],
[0,0,0,0,0]]
self.model.direction = DirectionState.left
self.correct_next_state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,1,0,0,0],
[0,0,0,0,0]]
self.model.one_step()
self.assertEqual(self.model.state, self.correct_next_state)
def test_one_step_b(self):
# Test just one step of the snake simuation
self.model.snake.addFirst((3,2))
self.model.state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,1,0,0],
[0,0,0,0,0]]
self.model.direction = DirectionState.up
self.correct_next_state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
self.model.one_step()
self.assertEqual(self.model.state, self.correct_next_state)
def test_one_step_c(self):
# Test just one step of the snake simuation
self.model.snake.addFirst((2,2))
self.model.snake.addLast((2,1))
self.model.state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,1,1,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
self.model.direction = DirectionState.right
self.correct_next_state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,1,1,0],
[0,0,0,0,0],
[0,0,0,0,0]]
self.model.one_step()
self.assertEqual(self.model.state, self.correct_next_state)
def test_one_step_d(self):
# Test just one step of the snake simuation
self.model.snake.addFirst((2,4))
self.model.state = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,1],
[0,0,0,0,0],
[0,0,0,0,0]]
self.model.direction = DirectionState.right
self.model.mode = Mode.Wrap
self.correct_next_state = [[0,0,0,0,0],
[0,0,0,0,0],
[1,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
self.model.one_step()
self.assertEqual(self.model.state, self.correct_next_state)
if __name__ == "__main__":
#play of the game
snake_game = snake()
#unittest.main()
|
#########################类
'''class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print(self.name.title()+'is now sitting')
def roll_over(self):
print(self.name.title()+'rolled over!')'''
'''def city_s(city,country,population=''):
if population:
return city+','+country+'- population'+str(population)
else:
return city+','+country'''
'''class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self,question):
self.question=question
self.responses=[]
def show_question(self):
"""显示调查问卷"""
print(self.question)
def store_responses(self):
"""存储单份调查问卷"""
self.responses.append(new_responses)
def show_results(self):
"""显示所有问卷"""
print("所有问卷为:")
for response in self.responses:
print("-"+response)'''
'''class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self, question):
"""存储一个问题,并为存储答案做准备"""
self.question = question
self.responses = []
def show_question(self):
"""显示调查问卷"""
print(question)
def store_response(self, new_response):
"""存储单份调查答卷"""
self.responses.append(new_response)
def show_results(self):
"""显示收集到的所有答卷"""
print("Survey results:")
for response in self.responses:
print('- ' + response)'''
'''class Employee():
def __init__(self,firstname,lastname,job=0):
self.firstname=firstname
self.lastname=lastname
self.job=job
def give_raise(self,salary=5000):
self.job+=salary
return salary
import unittest
class TestEmployee(unittest.TestCase):
def setUp(self) -> None:
self.longwj=Employee('long','wj',5000)
def test_give_default_raise(self):
names=self.longwj.give_raise()
self.assertEqual(names,5000)
def test_give_custom_raise(self):
ournames=self.longwj.give_raise(6000)
self.assertEqual(ournames,16000)
unittest.main()'''
|
import re
def snake_case(text):
"""
Used for converting paths and such to a snake case format.
"""
no_symbol = re.sub('[^A-Za-z0-9]', '_', text)
no_duplicate = re.sub('[_]{2,}', '_', no_symbol.lower())
return re.sub('(^_|_$)', '', no_duplicate)
|
inputRow = int(input("Enter row : "))
star = 1
space = " "
for i in range(inputRow):
print(space*(inputRow-(i+1))+"*"*(i+star))
star += 1
|
"""Helper methods for formatting and manipulating tracebacks"""
import traceback
def format_exception_info(exception_info_tuple, formatter=None):
if formatter is None:
formatter = traceback.format_exception
exctype, value, tb = exception_info_tuple
# Skip test runner traceback levels
while tb and is_relevant_tb_level(tb):
tb = tb.tb_next
if exctype is AssertionError:
# Skip testify.assertions traceback levels
length = count_relevant_tb_levels(tb)
return formatter(exctype, value, tb, length)
if not tb:
return "Exception: %r (%r)" % (exctype, value)
return formatter(exctype, value, tb)
def is_relevant_tb_level(tb):
return '__testify' in tb.tb_frame.f_globals
def count_relevant_tb_levels(tb):
length = 0
while tb and not is_relevant_tb_level(tb):
length += 1
tb = tb.tb_next
return length
|
#Code for disabling sys modules that will be inserted into the beginning of the data the user inputs
insert = """
import sys
for x in sys.modules:
sys.modules[x] = None
"""
#Keywords that are not allowed
badList = [
'__builtins__', 'open', 'eval', 'execfile', 'import', 'exec','write', 'read',
]
#place the file in the folder of this code and then type in it's name at the prompt
def input():
file = raw_input("what is your file name? you can type 'testpy.py' "
"for fibonacci numbers or 'testpy2.py' for the powers of 2\n")
test = open(file, 'r')
return test.read()
code = input()
# looks through the blacklisted word list and if the input file contains it then it's it asks for a different file
for x in badList:
if x in code:
print 'not allowed, resetting'
code = input()
#inserts the disabling of the sys module into the inputted code
code = insert + code
#executes the code
exec(code)
|
#fibonacci numbers from 1-10.
def fib(x):
if x == 0:
return 0
elif x == 1 or x == 2:
return 1
else:
return fib(x-1)+ fib(x-2)
for x in range (0,10):
print fib(x)
|
class Parent():
def __init__(self, last_name, eye_color):
print "Parent constructor called"
self.last_name = last_name
self.eye_color = eye_color
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
print "Child constructor called"
Parent.__init__(self, last_name, eye_color)
self.number_of_toys = number_of_toys
Bill_Bing = Parent('Bing', 'Blue')
Milly_Bing = Child('Bing', 'Blue', 15)
|
#create integer set from list
list1=[1,2,3,4,5]
b=[4,5]
s=set(list1)
print("integer set of list is : ")
print(s)
#character set
ch=set("Hello, how are you 5?")
print("character set of list is : ")
print(ch)
#set operation
print("Original Set")
print(s)
print("After removing an element from : ")
s.remove(1)
print(s)
print("After poping an element from : ")
s.pop()
print(s)
print("After discarding an element from : ")
s.discard(3)
print(s)
print("Intersection of both set : ")
print(s.intersection(b))
#string
str1="Hello ujala, how are you"
str2="i hope you did well today"
print("\nString is ")
print(str1)
print("Replace :")
print(str1.replace('ujala','gaurav'))
print("Count a :")
ch="a"
print(str1.count(ch,0,10))
print("Capitalize :")
print(str2.capitalize())
print("Join :")
print(" ".join(str2))
|
from tkinter import *
class myscrollbar:
def __init__(self, root):
#text widget
self.t=Text(root,width=70,height=15,wrap=NONE)
#text crowd
for i in range(50):
self.t.insert(END,"This is some text")
#text to root window at top
self.t.pack(side=TOP,fill=X)
#create scroll bar and attach to text widget
self.h=Scrollbar(root ,bg='green',orient=HORIZONTAL,command=self.t.xview)
#attach text widget to horizontal scroll bar
self.t.configure(xscrollcommand=self.h.set)
#scroll to root window at bottom
self.h.pack(side=BOTTOM,fill=X)
root=Tk()
ms=myscrollbar(root)
root.mainloop()
|
#class
class Car:
def __init__(self, components):
self.components = components
def __repr__(self):
return f'Car({self.components!r})'
@classmethod
def carA(cls):
return cls(['suzuki','duccatti'])
@classmethod
def carB(cls):
return cls(['Maruti','Hyundai'])
#static method
import math
class Pizza:
def __init__(self, radius, ingredients):
self.radius = radius
self.ingredients = ingredients
def __repr__(self):
return (f'Pizza({self.radius!r}, '
f'{self.ingredients!r})')
def area(self):
return self.circle_area(self.radius)
@staticmethod
def circle_area(r):
return r ** 2 * math.pi
p = Pizza(4, ['mozzarella', 'tomatoes'])
print(p.area())
print(Pizza.circle_area(45))
#innerclass
class Human:
def __init__(self):
self.name = 'Ujala'
self.head = self.Head()
class Head:
def talk(self):
return 'talking...'
if __name__ == '__main__':
guido = Human()
print (guido.name)
print (guido.head.talk())
|
#zero division
a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
try:
c=a/b
print(c)
except ZeroDivisionError as args:
print("Exception:- ",args)
else:
print("Successfully division done")
#value error
try:
a=int(input("Enter no : "))
except ValueError as args:
print("Exception:- ",args)
else:
print("Successfully done")
#syntax error
try:
a=eval(input("Enter date: "))
except SyntaxError as args:
print("Exception:- ",args)
else:
print("Successfully done")
#IOError
try:
name=input("Enter filename : ")
f=open(name,'r')
except IOError as args:
print("Exception:- ",args)
else:
print("Successfully done")
#asserterror
try:
x=int(input("Enter no between 5 and 10 : "))
assert x>=5 and x<=10, "wrong input"
except AssertionError as args:
print("Exception:- ",args)
else:
print("Successfully done")
#import error
try:
import abclib
except ImportError as args:
print("Exception:- ",args)
else:
print("Successfully done")
|
class Error(Exception):
"""Base class for exception"""
class ValueSmallError(Exception):
"""Raised for very small value"""
pass
class ValueLargeError(Exception):
"""Raised for very large value"""
pass
number=10
while True:
try:
num=int(input("Enter Number : "))
if num<number:
raise ValueSmallError
elif num>number:
raise ValueLargeError
except ValueSmallError:
print("This value is too small, try again!")
print()
except ValueLargeError:
print("This value is too large, try again!")
print()
else:
print("Congratulations! You guessed it correctly.")
|
def print_two(*args):
for word in args:
print(word)
print_two("AAA","BBB","CCC","DDD")
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
print_two_again("Zed","Shaw")
def print_none():
print("I got nothin'.")
print_none() |
"""
順列とはモノの順番付きの並びのことである. たとえば, 3124は数 1, 2, 3, 4 の一つの順列である. すべての順列を数の大小でまたは辞書式に並べたものを辞書順と呼ぶ. 0と1と2の順列を辞書順に並べると
012 021 102 120 201 210
になる.
0,1,2,3,4,5,6,7,8,9からなる順列を辞書式に並べたときの100万番目はいくつか?
"""
import math
# 最初の数字を決定させ、その値とそうなるための下限値を返す関数
def check_first_digit(number_list, order):
first_digit_rank = 0
for i in range(1, len(number_list) + 1):
if order <= i * math.factorial(len(number_list) - 1):
lower = (i - 1) * math.factorial(len(number_list) - 1)
break
first_digit_rank += 1
return number_list[first_digit_rank], lower
if __name__ == '__main__':
order = 1000000
target_list = []
number_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# 左から順にリスト内の数字を決定していき、決定した数字を元のリストから取り除いて別リストに移す
while len(number_list) != 0:
first_digit_number = check_first_digit(number_list, order)[0]
current_lower = check_first_digit(number_list, order)[1]
target_list.append(first_digit_number)
# 決まった数字を取り除いて、その中での順列を考える
number_list.remove(first_digit_number)
order = order - current_lower
# リストの中の文字列を結合させてintに直す
answer = int(''.join(target_list))
print(answer)
|
"""
ピタゴラス数(ピタゴラスの定理を満たす自然数)とは a < b < c で以下の式を満たす数の組である.
a^2 + b^2 = c^2
例えば, 32 + 42 = 9 + 16 = 25 = 52 である.
a + b + c = 1000 となるピタゴラスの三つ組が一つだけ存在する.
これらの積 abc を計算しなさい.
"""
import math
if __name__ == '__main__':
a = 1
b = 2
summary = 0
combination_list = []
# aは最小のため、333までを考えればよく、bはcより小さいため、500までで十分
for a in range(1, 333):
for b in range(a + 1, 500):
c = math.sqrt(a ** 2 + b ** 2)
# cが自然数かどうかの判定を行い、自然数の場合、総和を算出する
if c.is_integer():
c = int(c)
summary = a + b + c
# 総和が1000かどうかを判定し、1000の場合はa,b,cの組み合わせリストに追加する
if summary == 1000:
combination_list.append([a, b, c])
# abcの積を求める
answer = a * b * c
print(combination_list, answer)
break
|
# Problem Statement
#
#
# Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}.
#
#
# make_pi() → [3, 1, 4]
def make_pi():
import math
return [int(num) for num in str(int(math.pi * 100))]
print(make_pi()) |
# user_search_books.py
# --------------------
# list books in books table in project1 database where title contains 'irl'
"""
Example:
Enter anything you might know about the book
Just his 'Enter' to skip any field you don't know anything about
title: irl
author: ian
year: 2012
3264, 0297859382, Gone Girl, Gillian Flynn, 2012.
4272, 0385534795, The Sandcastle Girls, Chris Bohjalian, 2012.
"""
# get os package
import os
# get functions from sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
# DATBASE_URL variable
# DATABASE_URL is an environment variable that indicates where the database lives
# Do this before running search_books.py:
# $ export DATABASE_URL="postgresql://rwg:sql@localhost:5432/project1"
engine = create_engine(os.getenv("DATABASE_URL"))
# create a 'scoped session' that ensures different users' interactions with the
# database are kept separate
db = scoped_session(sessionmaker(bind=engine))
# define the main() function
def main():
title = ''
author = ''
year = ''
# Menu
print("Enter anything you might know about the book.")
print("Just his 'Enter' to skip any field you don't know anything about.")
title = input("title: ")
author = input("author: ")
year = input("year: ")
# execute SQL command and get all data with user constraintes
selections = db.execute("SELECT * FROM books WHERE title LIKE '%"+title+"%' and author LIKE '%"+author+"%' and year LIKE '%"+year+"%' ").fetchall()
# for every selection that has string in the title, print all data
for book in selections:
print(f"{book.id}, {book.isbn}, {book.title}, {book.author}, {book.year}.")
# run the main() function
if __name__ == "__main__":
main() |
import re
# Class User
class User():
Name = "John Doe" # Default name is John Doe starting out
email = "[email protected]" # email address of user
Nickname = "Slick" # Nickname of user
# constructor of the Character object.
def __init__(self, name, email, nickname):
self.Name = name
self.email = email
self.Nickname = nickname
# Getter Methods
def getName(self):
return self.Name
def getEmail(self):
return self.email
def getNickname(self):
return self.Nickname
# Setter Methods
def setName(self, name):
if( input("Do you really want to change your name Y/n?") == "Y"):
self.Name = name
else:
print("Ok we won't change your name then")
# Converts object to be stored as JSON format in text
def toJson(self):
return "{{Name:{0}, email:{1}, Nickname:{2} }}".format(self.Name, self.email, self.Nickname)
def importUsers():
"""Imports User List from disk
Looks for savedUsers.txt file and creates a list of Class objects
Returns a list of User class objects"""
with open("savedUsers.txt", "r") as fp:
Users = []
for line in fp:
#expload string on comma
lineArray = line.split(",")
#Split each var up
name = lineArray[0].split(":")[1]
email = lineArray[1].split(":")[1]
nickname = lineArray[2].split(":")[1].strip(" }")
# clean up end of nickname string
nickname = nickname.strip(" }\n")
Users.append(User(name, email, nickname))
return Users
def checkEmail(email):
"""Checks if the user input a valid email address.
Takes in a string and uses regex to make sure it is a valid email.
Returns boolean True/False"""
isValid = re.search('^\w+@\w+.\w+$', email)
if isValid:
return True
else:
return False
def createUser():
"""Creates new user prompting for values.
Takes in nothing and returns a new User class.
"""
print("--------------Creating User--------------")
name = input("Enter a name:")
# Loop until they enter a valid email then store and go onto the next index
while(True):
email = input("Enter a valid email. [email protected]: ")
if(not checkEmail(email)):
print("You didn't enter a correct type of email")
continue
else:
break
nickname = input("Enter a nickname:")
usr = User(name, email, nickname)
return usr |
import tkinter as tk
from tkinter import ttk, N, E, W, S
class Display:
def __init__(self, rows, columns):
self.root = tk.Tk()
self.root.title("Robot Playground")
for c in range(columns):
self.root.columnconfigure(c, weight=1)
for r in range(rows):
self.root.rowconfigure(r, weight=1)
self.board = {}
for r in range(rows):
for c in range(columns):
lbl = tk.Button(self.root, text=" ")
lbl["bg"] = "white"
lbl["font"] = ("Consolas", 12)
lbl.grid(row=r, column=c, sticky=(N, E, W, S))
self.board[r,c] = lbl
def set_cr_action(self, action):
self.root.bind("<Return>", action)
def hide(self, robot):
self.board[robot.row - 1, robot.column - 1]["bg"] = "white"
def show(self, robot):
self.board[robot.row - 1, robot.column - 1]["bg"] = robot.colour
def run(self):
self.root.mainloop()
|
#!/usr/bin/python3
"""JSON Class"""
class Student:
"""Class student json"""
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
if attrs is None:
return self.__dict__
if type(attrs) == list:
for atribute in attrs:
if type(atribute) != str:
return self.__dict__
dictionary = {}
for key in self.__dict__:
for atribute in attrs:
if key == atribute:
dictionary[key] = self.__dict__[key]
return dictionary
|
#!/usr/bin/python3
"""Append to a file"""
def append_write(filename="", text=""):
"""function that append in a file and return the number of chars written"""
with open(filename, mode='a', encoding='utf-8') as a_file:
written = a_file.write(text)
return written
|
#!/usr/bin/python3
from sys import argv
def check_sol(list_s, queen, n):
"""check if the queen position is validate to the list_s"""
cnt = 0
if len(list_s) == 0:
return(True)
while cnt < len(list_s):
f, c = list_s[cnt][0], list_s[cnt][1]
if f == queen[0] or c == queen[1]:
return(False)
else:
p_ddc = c
p_df = f
p_ic = c
while p_df < queen[0]:
p_ddc += 1
p_df += 1
p_ic -= 1
if p_ddc < n and p_df == queen[0] and p_ddc == queen[1]:
return(False)
elif p_ic >= 0 and p_df == queen[0] and p_ic == queen[1]:
return(False)
cnt += 1
return(True)
def generator(list_s, test_b, result, n):
"""generate the next queen position to set according to:
if the previus queen fail, send next column position, if
no more position exist, send 0.
if the previus queen pass, send next row position with 0 column.
if no more position exist, send backtrace signal (-1)
"""
if len(list_s) == 0 and result is True:
return (test_b)
if result is True:
if test_b[0] + 1 == n:
return(0)
test_b[0] += 1
test_b[1] = 0
return (test_b)
else:
if test_b[1] + 1 == n:
if len(list_s) == 0:
return ("exit")
return (-1)
test_b[1] += 1
return (test_b)
list_s = []
s = 0
n = 0
status = True
solutions = []
queen = [0, 0]
if len(argv) != 2:
print("Usage: nqueens N")
exit(1)
try:
n = int(argv[1])
except ValueError:
print("N must be a number")
exit(1)
if n < 4:
print("N must be at least 4")
exit(1)
while len(list_s) < n+1:
queen = generator(list_s, queen, status, n)
if queen == "exit":
exit()
if queen == 0:
if len(solutions) != 0:
for i in solutions:
if i == list_s:
queen = -1
break
print(list_s)
if queen != -1:
solutions.append(list_s)
list_s = list_s[:]
queen = -1
if queen == -1:
queen = list_s.pop()
status = False
else:
if check_sol(list_s, queen, n):
list_s += [queen[:]]
status = True
else:
status = False
|
#Justin Farquharson
#8/31/2021
#Day 3 - Review, Math, Control Statements
print(3%2)
print(4%2)
print(5%2)
print(6%2)
print(7%2)
number = 12.3456789
print("The value:", "%.2f"%number)
money = int(input("How much money do you have?\n"))
#Interger Division - Always rounds down.
tickets = money//10
# // = Interger Division
print("The number of tickets you can buy are:", tickets)
leftover = money%10
# Modulus(%) = remainder
print("You have", leftover, "dollars left over.")
import random
isStudent = input("Are You A Student?\n")
if(isStudent == "Yes" or isStudent == "yes"):
print("Free or Discount?")
chances = random.randint(0,100)
print(chances)
if(chances < 70):
print("You in for Free!")
else:
print("You must pay the discounted ticket price.")
else:
print("You must pay full price")
|
#Justin Farquharson
#09/26/2021
#COP 2500C
#Video Game
import random
games = 0
groups = 0
while(games < 20):
size = random.randint(1,4)
#print(size)
groups = groups+1
print("Visiting Group #", groups)
#This will determine if there's space for user to play with this group
if (size < 4 and games < 20):
print("Played Game")
games = games+1
chance = random.randint(1,10)
#print("c:",chance)
#This section will determine if they will play again with the same group
for a in range(chance):
if (chance <= 5 and games < 20):
#for a in range(chance):
print("Played Game")
games = games+1
|
run = int(input("How many days would you like to track?\n"))
x = 0
while(run != 0 and run >= 0):
run = run - 1
miles = int(input("How many miles did you run?\n"))
if(miles < 0):
print("Please use positive whole numbers")
run = run + 1
miles = miles - miles
x = x + miles
print("Total Miles:",x)
|
#!/usr/bin/env python
'''
Created by Oleksandra Baga
Write a PID-controller which makes sure that the model car is able to achieve and maintain a
certain velocity, which comes as an input and is specified in meters per second. Use the
pulse-sensor in the vehicle as a sensory feedback. The output of the controller shall be an
rpm-amount.
1 rpm: wheel rotates exactly once every minute
Rpm stands for rotations per minute and is used to quantify the speed at which an object spins,
such as a motor or a centrifuge. Linear speed measures the actual distance traveled,
often in meters per minute. Because a rotation always covers the same distance,
you can convert from rpm to linear distance if you can find the distance per rotation.
To do so, all you need is the diameter of the rotation.
PID:
We have the P controller for fast system response (improve rise time),
I controller to correct the steady state error and
D controller to dampen the system and reduce overshoot.
'''
import sys
import rospy
import cv2
from matplotlib import pyplot as plt
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from sklearn import linear_model
from std_msgs.msg import Int32, Int16, UInt8, Float32
from std_msgs.msg import String
import math
import time
import ticks_subscriber as ticks
#from assignment8_velocity_pid_controller.src.ticks_subscriber import slope_speed,\
# intercept_speed
global slope_distance, intercept_distance, slope_speed, intercept_speed, slope_command, intercept_command
CONTROLLER_SKIP_RATE = 2
PI = 3.14159265
WHEEL_DIAMETER = 0.06 # meter
class Speedometer:
def __init__(self, aggregation_period):
self.aggregation_period = aggregation_period
self.ticks = []
self.ticks_sub = rospy.Subscriber("/ticks", UInt8, self._tick, queue_size=1)
def get_speed(self):
"Return average RMP reported by /ticks for the last aggregation_period secods"
n_ticks = len(self.ticks)
if n_ticks == 0:
return 0
return float(sum(t[1] for t in self.ticks))/n_ticks
def _tick(self, msg):
now = rospy.get_time()
reading = msg.data
self.ticks.append((now, reading))
too_old = lambda t: now-t[0] > self.aggregation_period
self.ticks = [tick for tick in self.ticks if not too_old(tick)]
class PIDController:
def __init__(self):
# Get the ticks im rpm
# self.ticks_pub = rospy.Subscriber("/ticks_per_minute", UInt8, self.callback, queue_size=1)
self.ticks_sub = rospy.Subscriber("/ticks", UInt8, self.callback, queue_size=1)
# Speedometer will report average RPM for the last two seconds
#self.speedometer = Speedometer(2)
#CONTROL_DELAY = 1
# Launch self._callback every CONTROL_DELAY second
#self.control_timer = rospy.Timer(CONTROL_DELAY, self._callback)
# Solution: publish direct the steering command
self.pub_speed = rospy.Publisher("speed", Int16, queue_size=100)
# Parameters of PID Controller
# Matlab Simulation used for PID Controller with pidTuner()
self.kp = 0.07
self.ki = 0.001
self.kd = 1.8
self.target_speed = 0.4 # mps
# ===========================
self.start = time.time()
self.ticks = []
self.pid_error = 0
self.integral = 0
self.derivative = 0
self.control_variable = 0
self.counter = 0
self.projected_speed = 0.0
def get_speed_command(self):
measured_rpm = np.array([[0.17, 150], [0.3, 200], [0.427, 250]])
ransac = linear_model.RANSACRegressor()
n = measured_rpm.shape[0]
ransac.fit(measured_rpm[:,0].reshape((n, 1)), measured_rpm[:,1].reshape(n, 1))
global slope_command, intercept_command
intercept_command = ransac.estimator_.intercept_
slope_command = ransac.estimator_.coef_
def get_velocity(self):
measured_rpm = np.array([[150, 0.17], [200, 0.3], [250, 0.427]])
ransac = linear_model.RANSACRegressor()
n = measured_rpm.shape[0]
ransac.fit(measured_rpm[:,0].reshape((n, 1)), measured_rpm[:,1].reshape(n, 1))
global slope_speed, intercept_speed
intercept_speed = ransac.estimator_.intercept_
slope_speed = ransac.estimator_.coef_
def get_distance(self):
# array of measured ticks to
measured_rpm = np.array([[209, 2.05], [227, 2.1], [241, 2.13]])
ransac = linear_model.RANSACRegressor()
n = measured_rpm.shape[0]
ransac.fit(measured_rpm[:,0].reshape((n, 1)), measured_rpm[:,1].reshape(n, 1))
global slope_distance, intercept_distance
intercept_distance = ransac.estimator_.intercept_
slope_distance = ransac.estimator_.coef_
def callback(self, event):
# the current rpm got from encoder sensor
current_rpm = event.data
# current_rps = self.speedometer().get_speed()
if current_rpm == 0:
return
elif current_rpm != 0 and self.start == 0:
self.start = time.time()
stop = time.time()
diff = stop - self.start
if diff <= 2:
self.ticks.append(current_rpm)
return
self.get_distance() # wait period is 2 sec
# print("slope_distance" + str(slope_distance.shape))
current_speed = (slope_distance * len(self.ticks) + intercept_distance) / 2
print("intercept_distance" + str(intercept_distance.shape))
print("current_speed" + str(current_speed.shape))
#current_speed = current_speed * PI * WHEEL_DIAMETER
# PID CONTROLLER
last_pid_error = self.pid_error
self.pid_error = self.target_speed - current_speed
self.integral = self.integral + self.pid_error
self.derivative = self.pid_error - last_pid_error
control_variable = self.kp * self.pid_error + self.ki * self.integral + self.kd * self.derivative
#control_variable = current_speed + control_variable
#speed_command = control_variable / (PI * WHEEL_DIAMETER)
#self.target_speed(speed_command)
self.get_velocity()
self.get_speed_command()
#current_speed = slope_speed * control_variable + intercept_speed
current_speed = self.target_speed + control_variable
speed_command = slope_command * current_speed + intercept_command
message = "Target: {}, Speed: {}, error: {}, integral: {}, derivative: {}, control var: {}, speed_command {}"
info = message.format(self.target_speed, current_speed, self.pid_error, self.integral, self.derivative, control_variable, speed_command)
print(info)
with open('/home/oleksandra/Documents/catkin_ws_user/src/assignment8_velocity_pid_controller/src/pid_output.txt', 'a') as out:
out.write(info)
self.start = time.time()
self.ticks = []
# Publish the speed
# Warning: Use this publisher only if you have tested the speed and sure what you do
self.pub_speed.publish(speed_command)
# The global PID Controller
pid_controller = PIDController()
def main(args):
print("PID Velocity Controller Node launched")
rospy.init_node('pid_controller', anonymous=True)
rospy.loginfo(rospy.get_caller_id() + ": started!")
#ticks.calibrate_velocity()
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
if __name__ == '__main__':
main(sys.argv)
|
def specialMultiply(n, m):
#This function makes adjustments for big multiplications.
#It is just AWESOME. Wrapping up the answer everytime it crosses the given limit.
if n > 1000000007:
n = n % 1000000007
n = n * m
n = n % 1000000007
return n
def possibilities(W):
#For the given word, this function calculates the total number of possibilities (modulo 1000000007 of course)
length = len(W)
if length <= 1:
return 1
n = 1
if W[0] != W[1]:
n = 2
if W [length - 1] != W[length - 2]:
n = n * 2
for i in range(1, length - 1):
m = 3
if W[i] == W[i + 1]:
m = m - 1
if W[i] == W[i - 1]:
m = m - 1
if W[i - 1] == W[i + 1]:
m = 2
if W[i - 1] == W[i + 1] and W[i - 1] == W[i]:
m = 1
n = specialMultiply(n, m)
n = n % 1000000007
return n
#Open the file for reading input.
f = open("A-large-practice.in", "r")
#Open a file to write answer into it.
O = open("Answer.out", "w")
#Read the number of inputs from the input file.
T = int(f.readline())
#for every word in the input file do the stuff in the loop.
for i in range(1, T + 1):
#Read the word and store it in W
W = f.readline()
#Strip the \n from the back of the word. I know there must be a better way to do this.
W = W[0:len(W) - 1]
#Write the answer in the desired format in the output file.
O.write("Case #" + str(i) + ": " + str(possibilities(W)) + "\n")
#Close everything.
f.close()
O.close()
|
#Вариант, если сравниваемое значение равно одному символу
def get_less(seq=0,number=0):
seq = str(seq)
sm = " "
for i in range(len(seq)):
if int(seq[i]) < number:
sm += seq[i]
return int(sm)
a = int(input("Enter sequence: "))
b = int(input("Enter number for compare: "))
newseq = get_less(a,b)
print("The new sequence is:",newseq)
|
def ask_yes_no(question):
response = None
while response not in ("y","n"):
response = input(question).lower()
return response
#answer = ask_yes_no("\nPlease, enter 'y' or 'n': ")
#print("Thnx for ypur answer ",answer)
def birthday(name, age):
print("Happy birthday", name, ". Now you are",age, "old")
birthday(name1 = "Dasha", age1 = 22)
|
#Вариант, если сравниваемое значение более одного символа
def get_less(seq=0,number=0):
seq = str(seq)
number = str(number)
sm = " "
for i in range(0, len(seq), len(number)):
c = i + len(number)
if int(seq[i:c]) < int(number):
sm += seq[i:c]
return int(sm)
a = int(input("Enter sequence: "))
b = int(input("Enter number for compare: "))
newseq = get_less(a,b)
print("The new sequence is:",newseq)
|
print("Enter numbers")
mx = 0
'''
while True:
a = int(input("Enter number: "))
if a == 13:
break
elif a > mx:
mx = a
'''
a = 0
while a != 13:
a = int(input("Enter number: "))
if a > mx:
mx = a
print("Maximum:", mx)
|
# functions
myString = "Hello World"
print(myString)
x = len(myString)
print(x)
# this is a procedure because nothng is returned
def myprocedure(printme) :
print(printme)
myprocedure("Hello World")
def xtimesprint(printme, howoften) :
returnstring = ""
for x in range(howoften) :
returnstring = returnstring + printme
return returnstring
printme = "Hello World "
printme = xtimesprint(printme, 3)
print(printme)
|
# If ... Elif ... Else ... EndIf
a = 5
b = 4
print(a,b)
if a > b :
print(a, " is greater than ", b)
elif a == b :
print(a, " equals ", b)
else :
print(a, " is less than ", b)
|
with open("input.txt", "r") as input_file:
data = input_file.readlines()
# Strip \n and stuff from the lines
data = [s.strip() for s in data]
count = 0
# https://stackoverflow.com/questions/38138842/how-to-check-whether-two-words-are-anagrams-python
def is_anagram(a, b):
return sorted(a.lower()) == sorted(b.lower())
for line_index, line in enumerate(data):
splitted_line = line.split()
valid_line = True
for word_index, word in enumerate(splitted_line):
for word_index2, word2 in enumerate(splitted_line):
if word_index != word_index2:
if is_anagram(word, word2):
print("Found anagram in line", str(line_index) + ":", word)
valid_line = False
if valid_line:
count += 1
print("Amount of non-anagrams:", count)
|
import array
data = None
with open("input.txt", "r") as input_file:
data = input_file.read().replace("\n", "")
print("Received data from input file:", data)
index = 0
length = len(data)
arrayList = array.array('i')
for number in data:
number = int(number)
print("Character:", number)
try:
nextValid = int(data[index + (length / 2)])
print("Next valid:", nextValid)
if nextValid == number:
arrayList.append(nextValid + number)
except IndexError:
continue
index += 1
print(arrayList)
result = 0
for resultNumber in arrayList:
result = result + resultNumber
print("Result:", result)
|
#!/usr/bin/env python
""" Extract data from EXCEL to fill-in JINJA2 template
This script is a tool to convert data from Excel file to YAML to fill-in a Jinja2 template.
YAML structure is the following:
SHEET_NAME:
- COLUMN#1: value ROW#1 / COLUMN#1
COLUMN#2: value ROW#1 / COLUMN#2
...
- COLUMN#1: value ROW#2 / COLUMN#1
COLUMN#2: value ROW#2 / COLUMN#2
...
Usage:
python python-tools/tools.python.read.excel.py -e topology.xlsx -s Topology -t topology.j2
* Reading excel file: topology.xlsx
* Template rendering
> Use template: topology.j2
> Output file: output.txt
Keyword arguments:
excel -- path to excel file to read data
sheet -- Sheet name within Excel file to extract data
template -- Jinja2 template to use for rendering
output -- File to create for the rendering
Return Value:
Text file
"""
import argparse
import sys
import os.path
import yaml
import urllib2
import inetsix
from inetsix.excel import ExcelSerializer
from jinja2 import Template
if __name__ == "__main__":
### CLI Option parser:
parser = argparse.ArgumentParser(description="Excel to text file ")
parser.add_argument('-e', '--excel', help='Input Excel file',type=str, default=None)
parser.add_argument('-u', '--url', help='URL for remote Excel file',type=str, default=None)
parser.add_argument('-s', '--sheet', help='Excel sheet tab',type=str, default="Sheet1")
parser.add_argument('-m', '--mode', help='Serializer mode: table / list',type=str, default="table")
parser.add_argument('-n', '--nb_columns', help='Number of columns part of the table', type=int, default=6)
parser.add_argument('-t', '--template', help='Template file to render',default=None)
parser.add_argument('-o', '--output', help='Output file ',default="output.txt")
parser.add_argument('-v', '--verbose',action='store_true', help='Increase verbositoy for debug purpose', default=False)
options = parser.parse_args()
# Start Engine checklist
if options.excel is None and options.url is None:
sys.exit("Excel file is missing please provide it with option -e or -u")
elif options.excel is not None and options.url is not None:
sys.exit("These options are mutually exclusive, please use -e OR -u")
elif options.sheet is None:
sys.exit("Sheet tab is not define, please provide it with option -s")
# elif options.template is None:
# sys.exit("Jinja 2 Template file is missing please provide it with option -t")
# Download Excel file from Webserver:
if options.url is not None:
print " * Downloading Excel file from "+ options.url
options.excel = inetsix.download_file(remote_file= options.url, verbose= options.verbose)
# Serialize EXCEL file
print " * Reading excel file: "+options.excel
table = ExcelSerializer(excel_path=options.excel)
if options.mode == "table":
table.serialize_table( sheet=options.sheet, nb_columns=int(options.nb_columns))
elif options.mode == "list":
table.serialize_list( sheet=options.sheet)
else:
sys.exit("Error: unsuported serializer mode")
if options.verbose is True:
print " ** Debug Output **"
if table.get_yaml(sheet=options.sheet) is None:
print " -> Sheet has not been found in the structure"
else:
print yaml.safe_dump(table.get_yaml(sheet=options.sheet), encoding='utf-8', allow_unicode=True)
print " ** Debug Output **"
# Jinja2 template file.
# Open JINJA2 file as a template
if options.template is not None and options.output is not None:
print " * Template rendering"
print " > Use template: "+ options.template
print " > Output file: "+ options.output
with open( options.template ) as t_fh:
t_format = t_fh.read()
template = Template( t_format )
# Create output file
confFile = open( options.output,'w')
confFile.write( template.render( table.get_yaml() ) )
confFile.close()
else:
if table.get_yaml(sheet=options.sheet) is None:
print " -> Sheet has not been found in the structure"
else:
print yaml.safe_dump(table.get_yaml_all(), encoding='utf-8', allow_unicode=True)
|
import unittest
from src.game.game import *
from src.game.map import *
from src.game.tests.test_game import create_players
class TestMap(unittest.TestCase):
def setUp(self) -> None:
self.game = Game()
create_players(self.game, 3)
self.game.start_game()
def test_at_game_start_every_player_is_placed_in_a_room_and_is_alone(self):
for room in self.game.map.rooms:
self.assertTrue(len(room.players) <= 1)
for player in self.game._players.values():
self.assertTrue(player.current_room is not None)
def test_every_starting_area_is_not_connected_to_another_starting_area1(self):
for room in self.game.map.rooms:
if room.room_difficulty == 'starting_area':
for connected_room in room.neighboring_rooms:
self.assertNotEqual(connected_room.room_difficulty, 'starting_area')
def test_every_starting_area_is_not_connected_to_another_starting_area2(self):
for room in self.game.map.rooms:
if room.players:
for connected_room in room.neighboring_rooms:
self.assertEqual(connected_room.players, set())
def test_at_game_start_all_players_are_placed_in_starting_areas(self):
for player in self.game._players.values():
self.assertEqual(player.current_room.room_difficulty, 'starting_area')
def test_no_isolated_rooms(self):
queue = [self.game.map.rooms[0]]
visited_rooms = set()
while queue:
room = queue.pop()
visited_rooms.add(room)
for connected_room in room.neighboring_rooms:
if connected_room not in visited_rooms:
queue.append(connected_room)
self.assertEqual(len(visited_rooms), len(self.game.map.rooms))
def test_every_starting_area_is_the_same(self):
starting_areas = list(filter(lambda room: room.room_difficulty == 'starting_area', self.game.map.rooms))
nb_players = [len(room.players) for room in starting_areas]
self.assertTrue(len(set(nb_players)) == 1)
click_bonuses = [room.click_bonus for room in starting_areas]
self.assertTrue(len(set(click_bonuses)) == 1)
income_bonuses = [room.income_bonus for room in starting_areas]
self.assertTrue(len(set(income_bonuses)) == 1)
room_sizes = [room.room_size for room in starting_areas]
self.assertTrue(len(set(room_sizes)) == 1)
if __name__ == '__main__':
unittest.main()
|
import random
from src.game.room import Room
from src.game.zone import Zone
class Map:
def __init__(self, players, rooms_per_player=3, room_connections=2):
self.rooms_per_player = rooms_per_player
self.nb_generate_room_connections = room_connections
self.rooms = self.generate_rooms(players)
self.connect_rooms()
self.zone = Zone(random.choice(self.rooms))
def generate_rooms(self, players):
nb_players = len(players)
nb_starting_area_rooms = nb_players
nb_other_rooms = self.rooms_per_player * nb_players - nb_players
non_starting_area_rooms = self.create_non_starting_area_rooms(nb_other_rooms)
starting_area_rooms = self.create_starting_area_rooms(nb_starting_area_rooms, non_starting_area_rooms, players)
return non_starting_area_rooms + starting_area_rooms
@staticmethod
def create_starting_area_rooms(nb_rooms, non_starting_area_rooms, players):
starting_area_rooms = []
for i in range(nb_rooms):
room_difficulty = 'starting_area'
room = Room(room_difficulty)
other_room = random.sample(non_starting_area_rooms, 1)[0]
room.connect_with(other_room)
players[i].enter_room(room)
room._add_player(players[i])
starting_area_rooms.append(room)
return starting_area_rooms
@staticmethod
def create_non_starting_area_rooms(nb_rooms):
non_starting_area_rooms = []
for i in range(nb_rooms):
room_difficulty = random.choice(['medium_area', 'hard_area'])
room = Room(room_difficulty)
# Make sure that it is reachable
if i != 0:
other_room = random.sample(non_starting_area_rooms, 1)[0]
room.connect_with(other_room)
non_starting_area_rooms.append(room)
return non_starting_area_rooms
def connect_rooms(self):
other_rooms = list(filter(lambda room: room.room_difficulty != 'starting_area', self.rooms))
for room in self.rooms:
if room.room_difficulty == 'starting_area':
connections = random.sample(other_rooms, self.nb_generate_room_connections)
for other_room in connections:
room.connect_with(other_room)
else:
connections = random.sample(self.rooms, self.nb_generate_room_connections)
for other_room in connections:
if other_room != room:
room.connect_with(other_room)
|
class BlackjackHand:
# Creates Hand List
def __init__(self):
self.hand = []
# Adds card to hand
def add_card(self, new_card):
self.hand.append(new_card)
# Prints Cards as a string
def __str__(self):
cards = ""
for card in self.hand:
cards += str(card) + ", "
return cards[:-2]
# Gets Card Values
def get_value(self):
self.value = 0
for card in self.hand:
self.value += card.get_value()
if self.value > 21:
for card in self.hand:
if card.get_rank() == "Ace":
self.value -= 10
return self.value
class Blackjack:
# Creates Deck
def __init__(self, starting_dollars):
self.deck = []
for i in range(52):
card = Card(i)
card.face_up()
self.deck.append(card)
shuffle(self.deck)
self.bank = ChipBank(starting_dollars)
# Draws Card from deck
def draw(self):
if self.deck == []:
for i in range(52):
card = Card(i)
card.face_up()
self.deck.append(card)
shuffle(self.deck)
else:
self.x = self.deck[0]
self.deck.remove(self.deck[0])
return self.x
# Creates hands for both the player and the dealer.
def start_hand(self, wager):
self.playerHand = BlackjackHand()
self.dealerHand = BlackjackHand()
self.wager = wager
for i in range(2):
x = self.draw()
self.playerHand.add_card(x)
self.y = self.draw()
if i == 0:
self.y.face_down()
self.dealerHand.add_card(self.y)
# Prints hands for both dealer and player
print("Your starting hand: " + str(self.playerHand))
print("Dealer's starting hand: " + str(self.dealerHand))
if (self.playerHand.get_value() == 21 and
self.dealerHand.get_value() != 21):
self.end_hand("win")
elif (self.playerHand.get_value() == 21 and
self.dealerHand.get_value() == 21):
self.end_hand("push")
self.bank.withdraw(self.wager)
# Hits the deck if player decides to hit.
def hit(self):
x = self.draw()
print("You draw: " + str(x))
self.playerHand.add_card(x)
print("Your hand is now: " + str(self.playerHand))
if self.playerHand.get_value() == 21:
self.stand()
elif self.playerHand.get_value() > 21:
print("You bust!")
self.end_hand("lose")
# Gives the option for the player to stand
def stand(self):
self.dealerHand.hand[0].face_up()
print("Dealer's hand is now: " + str(self.dealerHand))
while self.dealerHand.get_value() <= 16:
x = self.draw()
print("Dealer draws: " + str(x))
self.dealerHand.add_card(x)
print("Dealer's hand is now: " + str(self.dealerHand))
if self.dealerHand.get_value() > 21:
self.end_hand("win")
print("Dealer bust, you win!")
elif self.playerHand.get_value() > self.dealerHand.get_value():
self.end_hand("win")
print("You beat dealer's hand!")
elif self.playerHand.get_value() < self.dealerHand.get_value():
self.end_hand("lose")
print("Dealer beats your hand!")
elif self.playerHand.get_value() == self.dealerHand.get_value():
self.end_hand("push")
print("Push!")
# Returns the outcome strings of the hands.
def end_hand(self, outcome):
if outcome.lower() == "win":
self.bank.deposit(self.wager * 2)
elif outcome.lower() == "push":
self.bank.deposit(self.wager)
elif outcome.lower() == "lose":
self.bank.deposit(0)
self.playerHand = None
self.playerHand = None
# Returns true or false if a game is happening.
def game_active(self):
if self.playerHand is None:
return False
else:
return True
# Provided sample code
if __name__ == "__main__":
blackjack = Blackjack(250)
while blackjack.bank.get_balance() > 0:
print("Your remaining chips: " + str(blackjack.bank))
wager = int(input("How much would you like to wager? "))
blackjack.start_hand(wager)
while blackjack.game_active():
choice = input("STAND or HIT: ").upper()
if choice == "STAND":
blackjack.stand()
elif choice == "HIT":
blackjack.hit()
print()
print("Out of money! The casino wins!")
|
initial_balance = 1000
interest_rate = .05
balance_after_first_year = initial_balance + (initial_balance * interest_rate)
balance_after_second_year = balance_after_first_year + (balance_after_first_year * interest_rate)
balance_after_third_year = balance_after_second_year + (balance_after_second_year * interest_rate)
print("With the initial balance being 1000, the balance after the first year is " + str(balance_after_first_year))
print("The balance after the second year is " + str(balance_after_second_year))
print("The balance after the third year is " + str(balance_after_third_year))
|
###############################
# PROGRAMMING ASSIGNMENT #2 #
###############################
# IMPLEMENTING QUICKSORT
# The file QuickSort.txt contains all of the integers between 1 and 10,000 (inclusive, with no repeats) in unsorted
# order. The integer in the ith row of the file gives you the ith entry of an input array.
# Your task is to compute the total number of comparisons used to sort the given input file by QuickSort. As you
# know, the number of comparisons depends on which elements are chosen as pivots, so we'll ask you to explore three
# different pivoting rules.
# You should not count comparisons one-by-one. Rather, when there is a recursive call on a subarray of length m,
# you should simply add m−1 to your running total of comparisons. (This is because the pivot element is compared to
# each of the other m−1 elements in the subarray in this recursive call.)
# WARNING: The Partition subroutine can be implemented in several different ways, and different implementations can
# give you differing numbers of comparisons. For this problem, you should implement the Partition subroutine exactly
# as it is described in the video lectures (otherwise you might get the wrong answer).
def read_array(path):
# Read in input file
f = open(path, mode='r')
array = f.readlines()
f.close()
for i in range(len(array)):
# Remove newline characters and convert to integer
array[i] = int(array[i].split()[0])
return array
def partition(A, l, r):
p = A[l]
i = l + 1
for j in range(l+1, r):
if A[j] < p:
A[i], A[j] = A[j], A[i]
i += 1
A[l], A[i-1] = A[i-1], A[l]
return i
def quickSort(A, n, left=0, right=-1):
if right < 0:
right = n
if right - left <= 1:
pass
else:
# p = choosePivot(A, n)
p = A[0]
mid = partition(A, l=left, r=right)
quickSort(A=A, n=n, left=left, right=mid)
quickSort(A=A, n=n, left=mid, right=right)
# PROBLEM #1
# For the first part of the programming assignment, you should always use the first element of the array as the pivot
# element.
class QuickSort:
def __init__(self, A, ptype='first', vb=False):
self.array = A
self.comparisons = 0
self.recursions = 0
self.pivot_type = ptype
self.verbose = vb
def partition(self, left, right):
if self.pivot_type == 'last':
# If using the last element, swap it into place
self.array[left], self.array[right] = self.array[right], self.array[left]
elif self.pivot_type == 'median':
midpoint = (right - left)//2
arr = {left: self.array[left],
midpoint: self.array[midpoint],
right: self.array[right]}
median = sorted(arr, key=arr.get)[2]
# Swap the leftmost element with the median element of arr
self.array[left], self.array[median] = self.array[median], self.array[left]
# Select pivot point (now in leftmost position)
p = self.array[left]
i = left + 1
for j in range(left + 1, right + 1):
self.comparisons += 1
if self.array[j] < p:
self.array[i], self.array[j] = self.array[j], self.array[i]
i += 1
self.array[left], self.array[i-1] = self.array[i-1], self.array[left]
return i
def sort(self, left, right):
if right - left <= 1:
pass
else:
mid = self.partition(left=left, right=right)
if self.verbose:
print(left, mid, right)
print(self.array)
# Sort left half of array
# print(left, right)
self.sort(left=left, right=max(mid-1, 0))
# self.comparisons += (mid-1) - left
# Sort right half of array
# print(left, right)
self.sort(left=mid, right=right)
# self.comparisons += right - mid
self.recursions += 1
# Tests
array10 = read_array('week-2/test10.txt')
n = len(array10)
q = QuickSort(array10, 'first', vb=True)
q.sort(left=0, right=n-1)
q.array
q.comparisons
array = read_array('week-2/QuickSort.txt')
n = len(array)
q = QuickSort(array, 'first')
q.sort(left=0, right=n-1)
print(q.comparisons)
# PROBLEM #2
# Compute the number of comparisons (as in Problem 1), always using the final element of the given array as the pivot
# element. Again, be sure to implement the Partition subroutine exactly as it is described in the video lectures.
# Recall from the lectures that, just before the main Partition subroutine, you should exchange the pivot element
# (i.e., the last element) with the first element.
array = read_array()
n = len(array)
q = QuickSort(array, 'last', vb=True)
q.sort(left=0, right=n-1)
print(q.comparisons)
# PROBLEM #3
# Compute the number of comparisons (as in Problem 1), using the "median-of-three" pivot rule. [The primary motivation
# behind this rule is to do a little bit of extra work to get much better performance on input arrays that are nearly
# sorted or reverse sorted.] In more detail, you should choose the pivot as follows. Consider the first, middle,
# and final elements of the given array. (If the array has odd length it should be clear what the "middle" element
# is; for an array with even length 2k, use the kth element as the "middle" element. So for the array 4 5 6 7, the
# "middle" element is the second one ---- 5 and not 6!) Identify which of these three elements is the median (i.e., the
# one whose value is in between the other two), and use this as your pivot. As discussed in the first and second parts
# of this programming assignment, be sure to implement Partition exactly as described in the video lectures (including
# exchanging the pivot element with the first element just before the main Partition subroutine).
# Example: For the input array 8 2 4 5 7 1 you would consider the first (8), middle (4), and last (1) elements; since
# 4 is the median of the set {1,4,8}, you would use 4 as your pivot element.
# A careful analysis would keep track of the comparisons made in identifying the median of the three candidate
# elements. You should NOT do this. That is, as in the previous two problems, you should simply add m−1 to your
# running total of comparisons every time you recurse on a subarray with length m.
array = read_array()
q = QuickSort(array, 'median')
q.sort()
print(q.comparisons) |
###########################
# WEEK 4: SHORTEST PATH #
###########################
# This is my own attempt to compute the shortest path between two vertices of a graph using Breadth-First Search (
# BFS). I will use an adjacency list representation of a graph.
# NOTE: This is NOT Dijkstra's Algorithm, but it's sort of a precursor to it (from what I gathered reading Wikipedia)
# We will do Dijkstra's Algorithm in week 5 of the course
import itertools
import random
# Adjacency list representation of a graph I just came up with
adj_list = {
1: [2, 5],
2: [1, 3],
3: [2, 4, 10],
4: [3, 5, 6, 7],
5: [1, 4],
6: [4, 7, 8, 10],
7: [4, 6, 8, 9],
8: [6, 9],
9: [7, 8],
10: [3, 6]
}
# Another adjacency list representation of a random graph I create
# NOTE: This graph is NOT connected!
adj_list2 = {
1: [5],
2: [4, 6, 7],
3: [5, 9],
4: [2],
5: [3, 9],
6: [2, 7],
7: [2, 8],
8: [7, 10],
9: [3, 5],
10: [8]
}
class Queue:
def __init__(self):
self.queue_list = []
def enqueue(self, item):
# Enqueue item to the front of the queue list
self.queue_list = [item] + self.queue_list
def dequeue(self):
# Dequeue the "oldest" item from the back of the list (FIFO)
if len(self.queue_list) > 0:
# First-In First-Out (FIFO), remove first element added to queue (which is at the END of the list!)
out = self.queue_list[-1]
# Remove element from list
self.queue_list = self.queue_list[:-1]
return out
else:
return None
def __repr__(self):
# The __repr__ method determines what is printed to the console when you just "type" the Queue object
return str(self.queue_list)
def isEmpty(self):
# Check if Queue is
return len(self.queue_list) == 0
class UndirectedGraph:
def __init__(self, adjacency_list):
self.adj_list = adjacency_list
self.explored = {key: False for key in self.adj_list.keys()}
def __getitem__(self, item):
return self.adj_list[item]
def __repr__(self):
return str(self.adj_list)
def exploreVertex(self, vertex):
# Mark vertex as explored
self.explored[vertex] = True
def isExplored(self, vertex):
# Check if vertex has been explored
return self.explored[vertex]
def vertices(self):
# Get vertex set V of graph G = (V, E)
return self.adj_list
def generate_random_graph(n, m):
# Generates a Graph object with n vertices and m edges
# Have n vertices labeled 1, 2, ... , n
vertices = list(range(1, n+1))
# Now randomly create m edges
# NOTE: No self-loops or parallel edges for now
all_edges = [e for e in itertools.combinations(iterable=vertices, r=2)]
edges = random.sample(population=all_edges, k=m)
# List of "doubled" edges (i.e. now have (v, u) for every (u, v) in edges)
edges_double = edges + [(e[1], e[0]) for e in edges]
# Turn these into an adjacency list
adj_list = {}
for v in vertices:
adjlist[v] = [e[1] for e in edges_double if e[0] == v]
# Generate an UndirectedGraph object from the the adjacency list
graph = UndirectedGraph(adjacency_list=adj_list)
return graph
def shortest_path(graph, s, v):
# Calculates the shortest path between vertices s and v in UndirectedGraph graph
# Mark s as explored
graph.exploreVertex(s)
# Initialize distances for each vertex u to infinity if u != s and 0 if u = s
dist = {key: float('inf') for key in graph.vertices()}
dist[s] = 0
# Create a Queue
q = Queue()
# Enqueue s as the first item in q
q.enqueue(item=s)
while not q.isEmpty():
# Pop the front element of the queue
t = q.dequeue()
neighbors = graph[t]
print(t, graph[t])
for w in neighbors:
if not graph.isExplored(vertex=w):
# If w is not yet explored, mark is as explored and add it to the queue
graph.exploreVertex(vertex=w)
q.enqueue(item=w)
# Update the distance
dist[w] = dist[t] + 1
return dist[v]
g = UndirectedGraph(adj_list2)
shortest_path(g, 10, 2) |
"""
Date: 2/27/2020 5:59 PM
Author: Achini
"""
def check_negation(text, NEGATION_MAP):
"""
Utility function to check negation of an emotion
:param text: text chunk with the emotion term
:return: boolean value for negation
"""
neg_word_list = NEGATION_MAP
neg_match = False
for neg_word in neg_word_list:
if neg_word.strip() in text:
neg_match = True
return neg_match
def check_intensifiers(text, INTENSIFIER_MAP):
"""
Utility function to check intensifiers of an emotion
:param text: text chunk with the emotion term
:return: boolean value for intensifiers
"""
intensity_word_list = INTENSIFIER_MAP
has_intensity = False
for int_word in intensity_word_list:
if int_word.strip() in text:
has_intensity = True
return has_intensity
def get_opposite_emotion(key):
"""
Utility function to get the opposite emotion of a given emotion
:param key: emotion to be processed
:return: opposite emotion, None if no opposite emotion is found
"""
opposite_emotions = {"joy": "anger",
"sad": "joy",
"anticipation": "anger",
"trust": "fear",
'fear': 'trust',
'anger' : 'joy',
'afraid': 'trust'
}
if opposite_emotions.keys().__contains__(key):
return opposite_emotions[key]
else:
return None
def get_sentiment_of_emotions(emotion):
"""
Utility function to get the POS/NEG categorization of an emotion
:param emotion: emotion to be processed
:return: POS, NEG category
"""
POS = ['joy', 'trust', 'anticipation', 'surprise']
NEG = ['sad', 'fear', 'disgust', 'anger', 'hopelessness', 'loneliness', 'distress']
if emotion in POS:
return 'POS'
elif emotion in NEG:
return 'NEG'
else:
return None
|
x = input("enter the alp:")
if(x=='A' or x=='a' or x=='E' or x=='e' or x=='I' or x=='i' or x=='O' or x=='o' or x=='U' or x=='u' ):
print(x, "Vowels")
else:
print(x, "Consonant")
|
intro = input("Write Something About Your Self: ")
chrcount = 0
wordcount = 1
for i in intro :
chrcount = chrcount + 1
if(i==" "):
wordcount = wordcount + 1
print("No Of Words in Your indtroduction")
print(wordcount)
print(chrcount) |
# Weather Forecasting Assignment
class Weather:
# grid properties
grid = []
width = 0
height = 0
max_label = '@'
storm_label = '&'
cloud_label = '.'
default_label = '#'
# what we need
clusters = []
def __init__(self, user_input=''):
# Get user input
if not user_input:
user_input = input('Filename Cloud_Size: ')
self.filename, self.cloud_size = user_input.split()
self.cloud_size = int(self.cloud_size)
self.read_contents(self.filename)
print('Current Grid:')
print(f'height: {self.height}, width: {self.width}')
self.print_grid(self.grid)
self.find_clusters()
print('\nCluster Locations:')
for cluster in self.clusters:
print(f'Size: {cluster[0]}, Cluster: {cluster[1]}')
new_grid = self.make_new_grid()
print('\nNew Grid with Clusters!')
self.print_grid(new_grid)
def get_max_coords(self):
max_size = 0
max_coords = []
for cluster in self.clusters:
if cluster[0] > max_size:
max_size = cluster[0]
max_coords = cluster[1]
elif cluster[0] == max_size:
max_coords += cluster[1]
return max_coords
def threshold_coords(self):
threshold_coords = []
for cluster in self.clusters:
if cluster[0] >= self.cloud_size:
threshold_coords += cluster[1]
return threshold_coords
def cluster_coords(self):
coords = []
for cluster in self.clusters:
coords += cluster[1]
return coords
# Finds a single cluster based on coord. Returns a list of coords in a cluster
def find_cluster(self, coord):
stack = [coord]
cluster = []
while stack:
current = stack.pop()
if current not in cluster:
cluster.append(current)
neighbors = [x for x in self.get_neighbors(current) if x not in cluster]
for neighbor in neighbors:
stack.append(neighbor)
return cluster
def find_clusters(self):
# Find the clusters and store the coordinates in a list
visited = []
for i in range(self.height):
for j in range(self.width):
if self.grid[i][j] == '.':
coord = (i,j)
if coord not in visited:
cluster = self.find_cluster(coord)
visited += cluster
self.clusters.append([len(cluster), cluster])
# returns neighbors that are '.'
def get_neighbors(self, coord):
neighbors = []
y = coord[0]
x = coord[1]
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
pass
else:
new_coord = (y + i, x + j)
if self.in_bounds(new_coord):
if self.grid[new_coord[0]][new_coord[1]] == self.cloud_label and new_coord != coord:
neighbors.append(new_coord)
return neighbors
# checks if a coordinate is within bounds of grid
def in_bounds(self, coord):
if coord[0] < 0 or coord[0] >= self.height:
return False
if coord[1] < 0 or coord[1] >= self.width:
return False
return True
# After clusters have been found, make a new grid with proper symbols
def make_new_grid(self):
max_coords = self.get_max_coords()
threshold_coords =self.threshold_coords()
cluster_coords = self.cluster_coords()
new_grid = []
for i in range(self.height):
line = ''
for j in range(self.width):
coord = (i,j)
if coord in max_coords:
line += self.max_label
elif coord in threshold_coords:
line += self.storm_label
elif coord in cluster_coords:
line += self.cloud_label
else:
line += self.default_label
new_grid.append(line)
return new_grid
# Fix Print
def print_grid(self, grid):
for row in range(self.height - 1):
print(grid[row])
def read_contents(self, filename):
f = open(filename, 'r+')
line = f.readline()
while line:
if '\n' in line:
line = line[:-1]
self.grid.append(line)
line = f.readline()
self.height = len(self.grid)
self.width = len(self.grid[0]) # -1 because we are reading the null character
def main():
filename = 'file.txt'
cloudsize = '4'
test_input = filename + ' ' + cloudsize
Weather(test_input)
if __name__ == '__main__':
main() |
#! /usr/bin/env python
import numpy as np
import matplotlib as mpl
def show_array (x):
""" Display the basic properties of the array.
"""
print '-- Array dimensions =', x.ndim
print '-- Array shape =', x.shape
print '-- Array datatype =', x.dtype
print '-- Array data =\n', x
## Generate arrays used for testing
arr2d = np.random.rand(4,4)
arr3d = np.random.rand(4,4,4)
## Summary of array properties
show_array(arr2d)
show_array(arr3d)
## Test slicing of arrays
print '\nTest slicing of arrays:'
print '\n-- arr2d[:2,:2]\n', arr2d[:2,:2]
print '\n-- arr2d[1:3,1:3]\n', arr2d[1:3,1:3]
print '\n-- arr3d[:2,:2]', arr3d[:2,:2].shape, '\n', arr3d[:2,:2]
print '\n-- arr3d[:2,:2,:2]', arr3d[:2,:2,:2].shape, '\n', arr3d[:2,:2,:2]
print '\n-- arr3d[1,:2,:2]', arr3d[1,:2,:2].shape, '\n', arr3d[1,:2,:2]
## Test working with masked arrays
print '\nTest masking of arrays:'
arrMask = np.zeros(arr2d.shape, int)
ma = np.ma.masked_array(arr2d, arrMask)
#print '-- Data array =', arr2d
print '-- Masked array ', ma
print '-- Masked array mean ', ma.mean()
for n in range(ma.shape[1]):
print 'Column', n, '=', ma[:,n], '-> mean =', ma[:,n].mean()
|
def max_profit(prices):
"""Given an array with prices of a given stock per day, if you are
only permited to complete one transaction (buy one and sell one share of stock), design an algorithm to find the maximum profit
Example:
input = [7,1,5,3,6,4]
output = 5
"""
#My first attempt at the problem:
#corner cases
if prices == [] or prices == None:
return 0
#I am looking for an interval where there's a minimum in the left and a maximum in the right. To do this I create two functions: one that slices the list in the first min, and another that slices the list in the firts max
def profit_right(prices):
while prices.index(max(prices))< prices.index(min(prices)):
if prices.index(min(prices)) == len(prices)-1:
return 0
prices = prices[prices.index(min(prices)):]
return max(prices) - min(prices)
def profit_left(prices):
while prices.index(max(prices))< prices.index(min(prices)):
if prices.index(max(prices)) == 0:
return 0
prices = prices[:prices.index(max(prices))+1]
return max(prices) - min(prices)
return max(profit_right(prices), profit_left(prices))
def max_profit_redux(prices):
"""second attempt at the problem. Another way is to always look for the min and the difference between each point and said min. And finally keeping the maximun difference"""
if prices == [] or prices == None:
return 0
min_here = prices[0]
max_diff = 0
for num in prices:
min_here = min(min_here, num)
max_diff = max(num - min_here, max_diff)
return max_diff
|
#imports the ability to get a random number (we will learn more about this later!)
from random import *
#Create the list of words you want to choose from.
aList = ["carrot", "orange", "yellow", "blue", "water", "apple", "lollypop", "cake", "fruit", "mango"]
adjetives = ["kind", "smart", "loving", "caring", "mean", "funny", "stinky", "controling", "angry", "clumsy"]
#Generates a random integer.
aRandomIndex = randint(0, len(aList)-1)
aRandomad = randint(0, len(aList)-1)
print(adjetives[aRandomad])
print(aList[aRandomIndex])
|
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(2))
def calc_total(list):
sum = sum(list)
for num in list:
sum += num
return sum
|
from unittest import TestCase
from accounting_stats import AccountingStats
class TestAccountingStats(TestCase):
"""This is a test class to test the AccountingStats class"""
def setUp(self):
"""Initialize setup object"""
self.stats = AccountingStats(5, 100, 150000)
def test_valid_constructor(self):
"""Test an object is created correctly"""
self.assertIsNotNone(self.stats)
self.assertIsInstance(self.stats, AccountingStats)
def test_invalid_constructor(self):
"""Test an object with invalid parameters"""
with self.assertRaises(ValueError):
stats_4 = AccountingStats(-1, 100, 200000)
with self.assertRaises(TypeError):
stats_1 = AccountingStats("5", 100, 150000)
with self.assertRaises(ValueError):
stats_5 = AccountingStats(5, -1, 200000)
with self.assertRaises(TypeError):
stats_2 = AccountingStats(5, "100", 150000)
with self.assertRaises(TypeError):
stats_3 = AccountingStats(5, 100, "150000")
with self.assertRaises(ValueError):
stats_6 = AccountingStats(5, 100, 800000)
def test_get_released_patient_num(self):
"""Test to get the total number of released patients"""
self.assertEqual(self.stats.get_released_patient_num(), 5)
self.assertIsNotNone(self.stats.get_released_patient_num())
def test_get_not_released_patient_num(self):
"""Test to get the total number of current patients"""
self.assertEqual(self.stats.get_not_released_patient_num(), 100)
self.assertIsNotNone(self.stats.get_not_released_patient_num())
def test_get_total_bill_amount_released_patients(self):
"""Test to get the total amount of all released patients"""
self.assertEqual(self.stats.get_total_bill_amount_released_patients(), 150000)
self.assertIsNotNone(self.stats.get_total_bill_amount_released_patients()) |
print("input a number")
number = int(raw_input("number: "))
for x in xrange(1,13):
result = number * x
print(str(number) + " x " + str(x) + " = " + str(result))
|
class node:
def __init__(self,val):
self.val =val
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert(self,val):
x = self.head
if(x==None):
self.head = node(val)
else:
while(x.next!=None):
x = x.next
x.next = node(val)
def remove(self,val):
x = self.head
if(x.val == val):
self.head = x.next
else:
while(x.next!=None and x.next.val!=val):
x=x.next
if(x.next==None):
print("no such value")
else:
x.next = x.next.next
print("deleted")
def print(self):
x= self.head
while(x!=None):
print(x.val)
x=x.next
l = Linkedlist()
l.insert(1)
l.insert(2)
l.insert(3)
l.insert(4)
l.print()
l.remove(2)
l.remove(4)
l.remove(10)
l.print()
|
from decimal import Decimal
def rmb(x):
return float(Decimal(x).quantize(Decimal("0.00")))
def calculate(base_commission_percent=0.13, buy_stock_num=100, buy_price=1, sell_price=2):
base_commission = 5
base_commission_percent = base_commission_percent / 1000
stamp_duty = 0.1 / 100
# 印花税费
transfer_fee_percent = 0.002 / 100
# 过户费
buy_stock_num = buy_stock_num
buy_price = buy_price
sell_price = sell_price
buy_total_price = buy_stock_num * buy_price
sell_total_price = sell_price * buy_stock_num
buy_commission = 5 if rmb(buy_total_price * base_commission_percent) < 5 else rmb(
buy_total_price * base_commission_percent)
sell_commission = 5 if rmb(sell_total_price * base_commission_percent) < 5 else rmb(
buy_total_price * base_commission_percent)
stamp_num =rmb(sell_total_price * stamp_duty) # 印花税 卖出收取
transfer_fee_buy = rmb(buy_total_price * transfer_fee_percent)
transfer_fee_sell = rmb(sell_total_price * transfer_fee_percent)
transfer_fee = rmb(transfer_fee_buy + transfer_fee_sell)
# 过户费
total_commission = buy_commission + sell_commission
handling_fee = rmb(stamp_num + transfer_fee + total_commission)
# print("数量:",buy_stock_num)
# print("买入价:",buy_price)
# print("卖出价",sell_price)
# print("差价:",sell_total_price-buy_total_price)
# print("印花税:",stamp_num)
# print("买入过户费:",transfer_fee_buy)
# print("卖出过户费:",transfer_fee_sell)
# print("过户费:",transfer_fee)
# print("总手续费:",handling_fee)
# print("盈利:",rmb((sell_price-buy_price)*buy_stock_num-handling_fee))
res = {}
res["buy_stock_num"]=buy_stock_num
res["buy_price"]=buy_price
res["sell_price"]=sell_price
res["stamp_num"]=stamp_num
res["transfer_fee_buy"]=transfer_fee_buy
res["transfer_fee_sell"]=transfer_fee_sell
res["transfer_fee"]=transfer_fee
res["handling_fee"]=handling_fee
res["benefit"]=rmb((sell_price-buy_price)*buy_stock_num-handling_fee)
return res
if __name__ == '__main__':
calculate() |
import numpy as np
from .ReadData import readMatrix, readVector
import time
'''
Método que calcula (haciendo uso del paralelismo) la solución a un sistema de ecuaciones lineales por medio del método iterativo de Jacobi.
Entradas: Matriz Diagonalmente Dominante A, vector independiente b, tolerancia y maximo de iteraciones.
Salida: Vector de solución x.
'''
def jacobi(a, b, x, tolerance, kmax):
t0 = time.time()
n = a.shape[0]
k = 1
while k < kmax:
x_old = x.copy()
for i in range(n):
suma = 0
for j in range(n):
if j != i:
suma += a[i,j]*x[j]
x[i] = (b[i] - suma) / a[i,i]
k += 1
if np.linalg.norm(x - x_old, ord=np.inf) / np.linalg.norm(x, ord=np.inf) < tolerance: #se verifica la tolerancia para ver si hubo convergencia
break
t1 = time.time()
total = t1-t0
print(total)
return total
# return x
def start(direccionA, direccionB, tolerancia=1e-10, iteraciones=500):
#Se crea la matriz A
A = readMatrix(direccionA)
#Se crea el vector independiente b
b = readVector(direccionB)
x = np.zeros_like(b, dtype=np.double)
for i in range(0,10):
result = jacobi(A,b,x, float(tolerancia), int(iteraciones))
f = open("valoresPuntoPy.csv", "a")
f.write("Jacobi #,"+str(i)+","+str(result)+"\n")
f.close() |
from heapq import heapify, heappop, heappush
def solution(jobs):
answer = 0
cur, cnt = 0, len(jobs)
heap = []
heapify(jobs)
while jobs or heap:
while jobs:
if jobs[0][0] > cur:
break
enter, processing = heappop(jobs)
heappush(heap, (processing, enter))
if not heap: # 남은 작업이 현재 시간 후에 들어오는 작업들만 남음
enter, processing = jobs[0]
cur = enter
continue
p, e = heappop(heap)
answer += cur - e + p
cur += p
return answer//cnt |
from itertools import combinations
def isPrime1(n): # 무식 소수
if(n<2):
return 0
for i in range(2,n):
if(n%i==0):
return 0
return 1
def isPrime2(n): # 에라토스테네스의 체
a = [False,False] + [True]*(n-1)
primes=[]
for i in range(2,n+1):
if a[i]:
primes.append(i)
for j in range(2*i, n+1, i):
a[j] = False
return(primes)
def solution1(nums): # 처음푼거
n = len(nums)
result = 0
temp = [0,0,0]
for i in range(n-2):
temp[0] = nums[i]
for j in range(i+1,n-1):
temp[1] = nums[j]
for k in range(j+1,n):
temp[2] = nums[k]
print(sum(temp))
result += isPrime1(sum(temp))
return result
def solution2(nums): # 두번째
re_arr = list(combinations(nums,3))
re_arr = list(map(lambda x: sum(x) , re_arr))
result = 0
for i in re_arr:
result += isPrime1(i)
return result
def solution3(nums): # 에라토스테네스의 체 사용 속도 up!
re_arr = list(combinations(nums,3))
re_arr = list(map(lambda x: sum(x) , re_arr))
result = isPrime2(max(re_arr))
cnt = 0
for i in re_arr:
if i in result:
cnt += 1
return cnt
print(solution3([1,2,3,4]))
# print(solution([1,2,7,6,4])) |
import heapq
def solution(n, s, a, b, fares):
graph = {}
minFare = float('inf')
for i in range(n):
graph[i+1] = {}
for node1, node2, weight in fares:
graph[node1][node2] = weight
graph[node2][node1] = weight
for i in range(1,n+1):
middle_distance = dijkstra(graph,s,i)
if middle_distance == float('inf'):
continue
middleA_distance = dijkstra(graph,i,a)
middleB_distance = dijkstra(graph,i,b)
curFare = middle_distance + middleA_distance + middleB_distance
minFare = min(minFare, curFare)
return minFare
def dijkstra(graph, start, end):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = []
heapq.heappush(queue, [start, distances[start]])
while queue:
current_destination, current_distance = heapq.heappop(queue)
if distances[current_destination] < current_distance:
continue
for new_destination, new_distance in graph[current_destination].items():
distance = current_distance + new_distance
if distance < distances[new_destination]:
distances[new_destination] = distance
heapq.heappush(queue, [new_destination, distance])
return distances[end] |
def operate(a, b, c):
if c == '*':
return a*b
elif c == '-':
return a-b
else:
return a+b
def solution(expression):
number_list = []
operate_list = []
index = 0
for idx, val in enumerate(expression):
if idx == len(expression)-1:
number_list += [int(expression[index:idx+1])]
if val == '*' or val == '-' or val == '+':
operate_list += val
number_list += [int(expression[index:idx])]
index = idx+1
priority_operate = [['*', '-', '+'], ['*', '+', '-'], ['-', '*', '+'], ['-', '+', '*'],
['+', '*', '-'], ['+', '-', '*']]
answer = 0
for i in range(len(priority_operate)):
operate_ex = operate_list.copy()
number_ex = number_list.copy()
k = 0
idx = 0
while operate_ex:
if priority_operate[i][k] == operate_ex[idx]:
add = operate(number_ex[idx],
number_ex[idx+1], operate_ex[idx])
number_ex[idx] = add
del number_ex[idx+1]
del operate_ex[idx]
else:
idx += 1
if idx == len(operate_ex):
idx = 0
k += 1
if answer < abs(number_ex[0]):
answer = abs(number_ex[0])
return answer
|
def solution(s):
answer = 0
l = len(s)
for i in range(l):
after = s[:i]
before = s[i:]
string = before+after
if iscorrect(string):
answer += 1
return answer
def iscorrect(s):
symbols = {
'(': ')',
'{': '}',
'[': ']',
}
openS = list(symbols.keys())
stack = []
for symbol in s:
if symbol in openS:
stack.append(symbol)
else:
if not stack or symbols[stack[-1]] != symbol:
return False
else:
stack.pop()
return False if stack else True |
def dfs(numbers,index,result,target):
if len(numbers) == index:
return 1 if target == result else 0
return dfs(numbers, index+1, result + (numbers[index]*-1),target) + dfs(numbers, index+1, result + (numbers[index]),target)
def solution(numbers, target):
return dfs(numbers, 1, numbers[0]*-1, target) + dfs(numbers, 1, numbers[0], target)
if __name__ == '__main__':
print(solution([1,1,1,1,1],3))
|
record = ["Enter uid1234 Muzi", "Enter uid4567 Prodo",
"Leave uid1234", "Enter uid1234 Prodo", "Change uid4567 Ryan"]
def solution(record):
answer = []
order_list = []
people_list = {}
for i in record:
temp = i.split()
if temp[0] == "Change":
people_list[temp[1]] = temp[2]
else:
if temp[0] == "Enter":
people_list[temp[1]] = temp[2]
order_list.append((temp[0], temp[1]))
for j in order_list:
if j[0] == "Enter":
answer.append("{0}님이 들어왔습니다.".format(people_list[j[1]]))
else:
answer.append("{0}님이 나갔습니다.".format(people_list[j[1]]))
return answer
print(solution(record))
|
def solution(s):
s_list = []
answer = 0
for i in range(len(s)):
s_list.append(s)
s = s[1:]+s[0]
for i in s_list:
stack = []
for j in i:
if j == '[' or j == '{' or j == '(':
stack.append(j)
else:
if stack:
if stack and (stack[-1] == '[' and j == ']') or (stack[-1] == '{' and j == '}') or (stack[-1] == '(' and j == ')'):
stack.pop()
else:
stack.append(j)
else:
stack.append(j)
if not stack:
answer += 1
return answer
s = "[](){}"
print(solution(s))
|
from heapq import heappush, heappop
from collections import defaultdict
def solution(N, road, K):
graph = defaultdict(lambda: {})
answer = 0
for a, b, c in road:
print(a, b, c)
graph[a][b] = c
graph[b][a] = c
for a, b, c in road:
if graph[a][b] > c:
graph[a][b] = c
if graph[b][a] > c:
graph[b][a] = c
print(graph)
start = 1
distances = {node: float('inf') for node in range(1, N+1)}
distances[start] = 0
queue = []
heappush(queue, [distances[start], start])
while queue:
current_distance, current_destination = heappop(queue)
if distances[current_destination] < current_distance:
continue
for new_destination, new_distance in graph[current_destination].items():
distance = current_distance + new_distance
if distance < distances[new_destination]:
distances[new_destination] = distance
heappush(queue, [distance, new_destination])
for i in distances.values():
if i <= K:
answer += 1
return answer
N = 5
road = [[1, 2, 1], [2, 3, 3], [5, 2, 2], [1, 4, 2], [5, 3, 1], [5, 4, 2]]
k = 3
print(solution(N, road, k))
|
import random
import tkinter
class Snake(tkinter.Canvas):
def __init__(self, master=None):
#Lamada al constructor de su padre
super().__init__(master)
#Identifica si se movio de posicion recientemente
self.movio = False
#Caracter usado para la cabeza de snake
self.head_sprite = "☻"
#Objecto de texto de la cabeza
self.head = None
#Posicion de la cabeza
self.head_pos = 0, 0
#Letras validas
self.letras = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r","s","t", "u", "v","w","x", "y", "z")
#Palabras validas
self.palabras_validas = ["al", "ol"]
#Palabra actual
self.palabra = None
#Letras por palabra
self.num_letras = 8
#Esta snake en movimiento
self.is_corriendo = False
#Puntaje basado en cantidad de letras de la palabra
self.puntaje = 0
#Vidas actuales
self.vidas = 3
#Letras capturadas de la palabra actual (Diccionario de tipo string:Container)
self.letras_capturadas = []
#Posicion actual de las letras en la pantalla ( Diccionario de tipo string:Container)
self.letras_pos = {}
#Inicializacion de el canvas y creacion de objectos
self.grid(sticky=tkinter.NSEW)
#Casilla para la palabra completa
self.entry_p_completa = tkinter.Entry(self.master, text ="", state = "disabled", justify=tkinter.CENTER)
self.entry_p_completa.grid(sticky=tkinter.N)
#Casilla para las vidas
self.entry_vidas = tkinter.Entry(self.master, text="", state="disabled", justify=tkinter.CENTER)
self.entry_vidas.grid(sticky=tkinter.N)
#Casilla para las letras
self.entry_palabra = tkinter.Entry(self.master, text="", state="disabled", justify=tkinter.CENTER)
self.entry_palabra.grid(sticky=tkinter.N)
#Boton de inicia
self.start_button = tkinter.Button(self.master, text='COMENZAR', command=self.start_bt)
self.start_button.grid(sticky=tkinter.EW)
#Funcionamiento de teclas de movimiento
self.master.bind('w', self.up)
self.master.bind('a', self.left)
self.master.bind('s', self.down)
self.master.bind('d', self.right)
#Evento al presionar el boton
def start_bt(self):
if(self.is_corriendo):
self.is_corriendo = False
self.start_button["text"] = "Iniciar"
else:
self.delete("all")
ancho = self.winfo_width()
altura = self.winfo_height()
self.create_rectangle(10, 10, ancho - 10, altura - 10)
self.dir = random.choice('wasd')
#Inicia a snake en la posicion media y asigna su valor a otra variable
self.head_pos = [round(ancho // 2, -1), round(altura // 2, -1)]
self.head = self.create_text(tuple(self.head_pos), text=self.head_sprite)
#Inicializa las vidas
self.entry_vidas["state"] = "normal"
self.entry_vidas.delete(0, tkinter.END)
self.entry_vidas.insert(0, self.head_sprite + "x" + str(self.vidas))
self.entry_vidas["state"] = "disabled"
#Elige una palabra al azar
self.palabra = random.choice(self.palabras_validas)
#Asigna palabra ek Etnty de la palabra completa
self.entry_p_completa["state"] = "normal"
self.entry_p_completa.delete(0, tkinter.END)
self.entry_p_completa.insert(0, self.palabra)
self.entry_p_completa["state"] = "disabled"
#Asigna espacios vacios al entrey de las letras de la palabra
self.entry_palabra["state"] = "normal"
self.entry_palabra.delete(0, tkinter.END)
self.entry_palabra.insert(0, "_"*len(self.palabra))
self.entry_palabra["state"] = "disabled"
#Hace aparecer una nueva secuencia de letras
self.spawn_letras()
self.is_corriendo = True
self.start_button["text"] = "Detener"
#Representacion de una iteracion del juego
self.tick()
#Representa una iteracion del juego
def tick(self):
ancho = self.winfo_width()
altura = self.winfo_height()
# pos_previa = self.head_pos
#Movimiento
if self.dir == 'w':
self.head_pos[1] -= 10
elif self.dir == 'a':
self.head_pos[0] -= 10
elif self.dir == 's':
self.head_pos[1] += 10
elif self.dir == 'd':
self.head_pos[0] += 10
self.coords(self.head, self.head_pos)
self.movio = True
#Verifica si snake a colisionado con su cola o alguna de las paredes, en cuyo case acaba el juego
if (self.head_pos[0] < 10 or self.head_pos[0] >= ancho - 10 or
self.head_pos[1] < 10 or self.head_pos[1] >= altura - 10
):
self.end()
return
#Verifica colicion con una letra y realiza acciones appropiadas
for letra in self.letras_pos:
data = self.letras_pos[letra]
d_p = data.get_pos()
if self.head_pos[1] == d_p[1] and self.head_pos[0] == d_p[0]:
#Evalua si se eligio la letra incorrecta
if letra in self.letras_capturadas or letra not in self.palabra:
self.vidas-=1
if(self.vidas == 0):
self.end()
return
self.entry_vidas["state"] = "normal"
self.entry_vidas.delete(0, tkinter.END)
self.entry_vidas.insert(0, self.head_sprite + "x" + str(self.vidas))
self.entry_vidas["state"] = "disabled"
else:
#Entrega de puntos y actualizacion del marcador
self.puntaje += 10
self.letras_capturadas.append(letra)
self.update_entry()
#Evaluacion por palabra completa y reemplazo en caso lo este + asignacion de bono por palabra completa
if self.is_palabra_completa():
#Añade una vida y actualiza las entradas
self.vidas+=1
self.entry_vidas["state"] = "normal"
self.entry_vidas.delete(0, tkinter.END)
self.entry_vidas.insert(0, self.head_sprite+"x"+str(self.vidas))
self.entry_vidas["state"] = "disabled"
#Añade el puntaje
self.puntaje += (len(self.palabra) * 2)
#Elige otra palabra al azar y actualiza las entradas en tkinter
ch = random.choice(self.palabras_validas)
while (ch == self.palabra):
ch = random.choice(self.palabras_validas)
self.entry_p_completa["state"] = "normal"
self.entry_p_completa.delete(0, tkinter.END)
self.entry_p_completa.insert(0, self.palabra)
self.entry_p_completa["state"] = "disabled"
self.entry_palabra["state"] = "normal"
self.entry_palabra.delete(0, tkinter.END)
self.entry_palabra.insert(0, "_" * len(self.palabra))
self.entry_palabra["state"] = "disabled"
#Reinicia las letras capturadas
self.letras_capturadas.clear()
#Reinicia las posiciones
for l in self.letras_pos:
parte = self.letras_pos[l]
self.delete(parte.get_id())
self.letras_pos.clear()
self.spawn_letras()
break
#Temporizador
if self.is_corriendo:
self.after(50, self.tick)
#Identifica si ya se completo la palabra
def is_palabra_completa(self):
self.entry_palabra["state"] = "normal"
for l in self.entry_palabra.get():
if l == "_":
self.entry_palabra["state"] = "disabled"
return False
self.entry_palabra["state"] = "disabled"
return True
#Actualiza la entrada para ver la palabra
def update_entry(self):
l_pos = ""
for l in self.palabra:
if l in self.letras_capturadas:
l_pos += l
else:
l_pos+="_"
self.entry_palabra["state"] = "normal"
self.entry_palabra.delete(0, tkinter.END)
self.entry_palabra.insert(0, l_pos)
self.entry_palabra["state"] = "disabled"
#Hace aparecer x letras en el tablero
def spawn_letras(self):
ancho = self.winfo_width()
altura = self.winfo_height()
#Letra al azar de la palabra que no se haya añadido todabia
current_letra = self.sig_letra()
pos = self.sig_pos(ancho, altura)
self.letras_pos[current_letra] = Container(pos[0], pos[1], current_letra, self.create_text(pos[0], pos[1], text=current_letra))
#Elige una letra escogida, crea u contenedor y la añade al canvas
letras_escogidas = []
for i in range(0, self.num_letras):
letra_r = random.choice(self.letras)
while any(letra_r == self.letras_pos[le].get_name() for le in self.letras_pos) or letra_r in self.letras_capturadas or letra_r in letras_escogidas:
letra_r = random.choice(self.letras)
pos = self.sig_pos(ancho, altura)
letras_escogidas.append(letra_r)
self.letras_pos[letra_r] = Container(pos[0], pos[1], letra_r, self.create_text(pos[0], pos[1], text = letra_r))
#Retorna una letra al azar de la palabra que falte
def sig_letra(self):
l = random.choice(self.palabra)
while l in self.letras_capturadas:
l = random.choice(self.palabra)
return l
#Final del juego
def end(self):
ancho = self.winfo_width()
alto = self.winfo_height()
#Reinicia las variables
self.palabra = None
self.letras_capturadas.clear()
self.letras_pos.clear()
self.head_pos = 0,0
#Cambia los botones y muestra el puntaje
self.corriendo = False
self.start_button["text"]='Reiniciar'
self.create_text((round(ancho // 2, -1), round(alto// 2, -1)), text='Fin! Tu Puntaje es: ' + str(self.puntaje))
self.puntaje = 0
#Eventos de movimiento que basado en a direccion cambia a donde se mueve
def up(self, event):
if self.movio and not self.dir == 's':
self.dir = 'w'
self.movio = False
def down(self, event):
if self.movio and not self.dir== 'w':
self.dir = 's'
self.movio = False
def left(self, event):
if self.movio and not self.dir == 'd':
self.dir = 'a'
self.movio = False
def right(self, event):
if self.movio and not self.dir == 'a':
self.dir = 'd'
self.movio = False
#Nos da la siguiente posicion valida
def sig_pos(self, ancho, altura):
invalid_pos = []
invalid_pos.append(self.head_pos)
# Añade las posiciones actualmente ocupadas
for index in self.letras_pos:
invalid_pos.append(self.letras_pos[index].get_pos())
#Calcula una posicion al azar dentro de el canvas
pos = (round(random.randint(20, ancho - 20), -1), round(random.randint(20, altura - 20), -1))
while pos in invalid_pos:
pos = (round(random.randint(20, ancho - 20), -1), round(random.randint(20, altura - 20), -1))
return pos
#Contenedor para una posicion
class Container:
def __init__(self, x, y, name, id=0):
self.x = x
self.y = y
self.id = id
self.name = name
def get_pos(self):
return self.x, self.y
def get_name(self):
return self.name
def get_id(self):
return self.id
#Crea la instancia de tk y le da sus tamaños
root = tkinter.Tk()
root.title("Snake")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.resizable(width=False, height=False)
root.minsize(500, 500)
root.maxsize(500, 500)
#Inicia la clase
app = Snake(root)
app.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.