text
stringlengths 37
1.41M
|
---|
"""Generates URLs for factorio icons."""
import os.path
_NAME_TO_ICON = {}
def init(icon_directory_path):
"""Initializes the factorio icon manager.
Args:
icon_directory_path: The path of the factorio-data icon directory. Must
be relative to the directory containing app.yaml.
"""
for root, _, file_names in os.walk(icon_directory_path):
for file_name in file_names:
item_name = os.path.splitext(file_name)[0]
_NAME_TO_ICON[item_name] = (
'/' + os.path.relpath(os.path.join(root, file_name)))
def get_icon_for_item(name):
"""Return the url of the best icon for the given icon or recipe name.
Args:
name: The name of a factorio item (e.g. 'iron-gear-wheel' or recipe
(e.g. 'basic-oil-processing').
Returns:
A URL refering to the icon of the requested item (e.g.
'/factorio-data/icons/assembling-machine-3.png') or a default icon if
no icon could be found.
"""
if name in _NAME_TO_ICON:
return _NAME_TO_ICON[name]
else:
return '/img/missing-item.png'
|
"""
Modifiers
a function modifies the objects it gets as parameters
the changes are visible to the caller
"""
def increment(time, seconds):
time.second += seconds
if time.second >= 60:
time.second -= 60
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1
|
"""
Time
"""
class Time(object):
"""Represents the time of day.
attributes: hour, minute, second
"""
#create a new Time object and assign attributes
def print_time(object):
print("%.2d : %.2d : %.2d" % (object.hour, object.minute, object.second))
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
print_time(time)
|
"""
Create a dictionary of parameters
"""
from typing import Dict
from .... import tk
def preprocess(user_dict, default_dict):
# type: (Dict, Dict) -> Dict
"""Create a new parameter dictionary
Create a new parameter dictionary based on
user inputs and defaults.
Args:
user_dict (dict): user input parameters
default_dict (dict): default parameters
Returns:
an internal parameter dictionary
"""
return tk.dictTK.convert_to_internal(
tk.dictTK.update(
tk.dictTK.wrap_value(user_dict),
default_dict
)
)
|
"""
A function returning a color string given an index
and a list of color options
"""
from typing import List, AnyStr
def choose_color(i, color_list):
# type: (int, List[AnyStr]) -> AnyStr
"""Return a color
Return a color given a integer index
and a list of color options.
If index is greater than the number of
color options, periodicity will be applied.
Args:
i (int): index of the color
color_list (list): a list of color strings
Returns:
a color string
"""
if i < 0:
return color_list[0]
else:
return color_list[i % len(color_list)]
|
"""
Read a file or just a number.
This allow user to specify either a single number
or a file that contains a number
"""
import numpy
def readFileOrNumber(x):
"""Read a file or just a number
Args:
x: file name or just a number
Returns:
a number (float)
"""
if isinstance(x, str):
return numpy.loadtxt(x)
else:
return x
|
"""
Transpose data
"""
from numpy import ndarray
import numpy
def transpose(data, act=True):
# type:(ndarray) -> ndarray
"""Transpose data
Args:
data (ndarray): input data
act=True (bool): whether to do the transposing
Returns:
a new ndarray
"""
if act:
return numpy.transpose(data)
else:
return data
|
# -*- coding: utf-8 -*-
"""
Using the Python language, have the function ArrayRotation(arr)
take the arr parameter being passed which will be an array of
non-negative integers and circularly rotate the array starting
from the Nth element where N is equal to the first integer in
the array. For example: if arr is [2, 3, 4, 1, 6, 10] then your
program should rotate the array starting from the 2nd position
because the first element in the array is 2. The final array will
therefore be [4, 1, 6, 10, 2, 3], and your program should return
the new array as a string, so for this example your program would
return 4161023. The first element in the array will always be an
integer greater than or equal to 0 and less than the size of the array.
Input:3,2,1,6
Output:6321
Input:4,3,4,3,1,2
Output:124343
"""
def ArrayRotation(array):
r = array[0]
return "".join([str(a) for a in array[r:len(array)]] + [str(a) for a in array[:r]])
|
sum = 0
# 轮子轴距的实现
class Whell:
def __init__(self, delta_left, delta_right,angu,rad):
self.delta_left = delta_left
self.delta_right = delta_right
self.angu =angu
self.rad=rad;
def displayCount(self):
length_one_fram_ang = 12.03*3.1415926/450
whell_rounds=(self.delta_left + self.delta_right)/2;
wb=(self.angu*whell_rounds*length_one_fram_ang*2.0)/(self.rad*360*3.1415926/180)
print("Whell.wbCountb %f" % wb)
return wb
def displayWhell(self):
print("delta_left : ", self.delta_left, ", delta_right: ", self.delta_right, ", angu: ", self.angu)
print("请按顺序输入delta_left,delta_right,angu,rad")
num1=float(input("输入delta_left:"))
num2=float(input("输入delta_right:"))
num3=float(input("输入angu:"))
num4=float(input("输入rad:"))
"创建 Employee 类的第一个对象"
# emp1 = Whell(4413.00, 4414.00,-1,3)
emp1 = Whell(num1,num2,num3,num4)
emp1.displayWhell()
emp1.displayCount()
|
# 实例属性和类属性
# 给实例绑定属性的方法是通过实例变量,或者通过self变量:
class Students(object):
def __init__(self, name):
self.name = name
s = Students('Bob')
s.score = 90
# 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有:
class Student(object):
name = 'Student'
s = Student() # 创建实例s
print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
print(Student.name) # 打印类的name属性
s.name = 'Michael' # 给实例绑定name属性
print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
del s.name # 如果删除实例的name属性
print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
# 从上面的例子可以看出,在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,
# 因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。 |
# 排序算法
'''
Python内置的sorted()函数就可以对list进行排序:
'''
print(sorted([36, 5, -12, 9, -21]))
print(sorted([36, 5, -12, 9, -21], key=abs)) # 按照绝对值排序
# 对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
'''
我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法,不必对现有代码大加改动,只要我们能用一个
key函数把字符串映射为忽略大小写排序即可。忽略大小写来比较两个字符串,实际上就是先把字符串都变成大写(或者都变成小写),再比较。
'''
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # 按字母排序
# 要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True:
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
|
lines_seen = set() # holds lines already seen
with open("Output_file.txt", "w") as output_file:
for each_line in open("Input_file.txt", "r"):
if each_line not in lines_seen: # check if line is not duplicate
output_file.write(each_line)
lines_seen.add(each_line)
|
#!/usr/bin/env python
# La primera letra de cada palabra. Por ejemplo, si recibe Universal Serial Bus debe devolver USB.
def iniciales(cadena):
lista=cadena.split(" ")
return "".join(palabra[0] for palabra in lista)
# Dicha cadena con la primera letra de cada palabra en mayúsculas. Por ejemplo, si recibe república argentina debe devolver República Argentina.
def capitalizar(cadena):
lista = cadena.split(" ")
return "".join(palabra.capitalize() + " " for palabra in lista)
# Las palabras que comiencen con la letra A. Por ejemplo, si recibe Antes de ayer debe devolver Antes ayer.
def palabras_comienzan_a(cadena):
lista = cadena.split(" ")
return "".join(
palabra + " "
for palabra in lista
if palabra.startswith("a") or palabra.startswith("A")
)
cad=input("Cadena:")
print(iniciales(cad))
print(capitalizacion(cad))
print(palabras_comienzan_a(cad))
|
# MSSERG | 13:00 MSC 20.01.2018
print('''Калькулятор:
\nРасчёт зарплаты производиться по формуле
N/100*80.5 для нахождения чистой зарплаты,
и N+(N/100*19.5) для нахождения оклада, где
N=Одно из значений зарплаты (чистая или оклад),
коэффициенты: ставка НДФЛ-18%, военный сбор-1.5%.\n''')
check = int(input('Желаете узнать чистую зарплату (1) или оклад (2): '))
if check == 1:
N = float(input('Введите значение оклада (N): '))
result = N/100*80.5
print('Размер чистой зарплаты =', result, 'руб.')
elif check == 2:
N = float(input('Введите значение чистой зарплаты (N): '))
result = N+(N/100*19.5)
print('Размер оклада составит =', result, 'руб.')
input('\nПауза для консоли.') |
#! /usr/bin/env python
# -*- encoding:utf-8 -*-
"""This module will be used to filte the word from input file with the stopword file.
Usage: python SEFilter.py filename """
import sys
import codecs
import __init__
from SEPreprocess.ReadConfig import ReadConfig
from SEUtility.File_RW import DictPrint,ReadIntoDict
def ImportStopword():
_dict = ReadConfig()
_fr = codecs.open(_dict['stopwordsFile'],'r','utf-8')
word_set = set()
for word in _fr:
word_set.add(word.rstrip())
_fr.close()
return word_set
def FileFilter(filename):
_word_set = ImportStopword()
_dict = ReadIntoDict(filename)
_dict = StopwordFilter(_dict,_word_set)
_fw = codecs.open(filename,"w","utf-8")
DictPrint(_dict,out_file = _fw)
_fw.close()
def StopwordFilter(_dict,_stopword_set):
for key in _dict.keys():
if key in _stopword_set:
_dict.pop(key)
return _dict
def main():
reload(sys)
sys.setdefaultencoding('utf-8')
if len(sys.argv) < 2:
print __doc__
sys.exit(0)
FileFilter(sys.argv[1])
if __name__ == "__main__":
main()
|
"""
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
"""
class Solution:
# @return an integer
def numTrees(self, n):
if n == 0:
return 1
elif n == 1:
return 1
elif n == 2:
return 2
#elif n == 3:
# return 5
else:
result = 0
for i in range(0, n):
result += self.numTrees(i) * self.numTrees(n - 1 - i)
return result
if __name__ == "__main__":
s = Solution()
print s.numTrees(3)
print s.numTrees(4) |
"""
How to use draw_graph3D to create a tridimensional grid connected graph
"""
import numpy as np
import maxflow
from examples_utils import plot_graph_3D
def create_graph(width=6, height=5, depth=2):
I = np.arange(width*height*depth).reshape(depth, height, width)
g = maxflow.Graph[float]()
nodeids = g.add_grid_nodes(I.shape)
structure = np.array([[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]],
[[0, 1, 0],
[1, 0, 1],
[0, 1, 0]],
[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]]])
g.add_grid_edges(nodeids, structure=structure)
X, Y = np.mgrid[:I.shape[0], :I.shape[1]]
X, Y = X.reshape(1, np.prod(X.shape)), Y.reshape(1, np.prod(Y.shape))
# Source node connected to leftmost non-terminal nodes.
left_most = np.concatenate((X, Y, np.zeros_like(X))).astype(np.uint64)
left_most = np.ravel_multi_index(left_most, I.shape)
g.add_grid_tedges(left_most, np.inf, 0)
# Sink node connected to rightmost non-terminal nodes.
right_most = left_most + I.shape[2] - 1
g.add_grid_tedges(right_most, 0, np.inf)
return I, g
if __name__ == '__main__':
nodeids, g = create_graph()
plot_graph_3D(g, nodeids.shape)
g.maxflow()
print g.get_grid_segments(nodeids)
|
a=str(input("enter ur name:"))
b=int(input("enter ur age:"))
c=str(input("enter ur address:"))
print(a,"\n",b,"\n",c) |
amt=int(input("enter the amount"))
note=int(input("enter the sample notes"))
no=amt//note
print("no of notes :", no)
|
n = int(input())
d ={}
for i in range(n):
text = input().split()
d[text[0]]=int(text[1])
for i in d:
print(i)
for i in d.values():
print(i)
|
#Python program to add a key to a dictionary
car={"brand":"ford",
"model":"mustang"}
print(car)
car.update({"year":2009})
print(car) |
#Python program to add an item in a tuple
a=input().split(",")
b=tuple(a)
print(b)
b=b+(9,0)
print(b) |
d1={'a':1,'b':2}
d2={}
for i in(d1,d2):
if(len(i)>0): print("the dictionary is not empty")
else: print("the dictionary is empty")
|
import queue
class Node:
id = -1
pai = None
def __init__(self,id):
self.id = id
class Grafo:
matriz = []
n = 0
direcionado = False
def __init__(self,n):
self.n = n
for i in range(n):
self.matriz.append([0]*n)
def addAresta(self,s,t):
self.matriz[s][t]=1
def printMatriz(self):
print()
print('-------------------')
for i in range(self.n):
# print("i",i)
for j in range(self.n):
# print("j",j)
print(self.matriz[i][j],end = ' ')
print()
print('-------------------')
print()
if __name__ == "__main__":
g = Grafo(27)
g.addAresta(0, 1)
g.addAresta(1, 2)
g.addAresta(1, 3)
g.addAresta(1, 4)
g.addAresta(2, 3)
g.addAresta(3, 4)
g.addAresta(4, 5)
g.addAresta(5, 6)
g.addAresta(6, 7)
g.addAresta(5, 7)
g.addAresta(4, 7)
g.addAresta(7, 8)
g.addAresta(8, 9)
g.addAresta(7, 16)
g.addAresta(8, 16)
g.addAresta(9, 10)
g.addAresta(9, 16)
g.addAresta(16, 10)
g.addAresta(10, 11)
g.addAresta(11, 12)
g.addAresta(12, 13)
g.addAresta(11, 14)
g.addAresta(10, 14)
g.addAresta(16, 14)
g.addAresta(16, 15)
g.addAresta(15, 14)
g.addAresta(15, 7)
g.addAresta(18, 7)
g.addAresta(18, 4)
g.addAresta(17, 7)
g.addAresta(18, 17)
g.addAresta(18, 1)
g.addAresta(15, 17)
g.addAresta(18, 19)
g.addAresta(19, 17)
g.addAresta(19, 20)
g.addAresta(17, 20)
g.addAresta(20, 21)
g.addAresta(20, 26)
g.addAresta(20, 23)
g.addAresta(20, 22)
g.addAresta(23, 22)
g.addAresta(22, 26)
g.addAresta(22, 25)
g.addAresta(22, 24)
g.addAresta(24, 25)
g.addAresta(25, 26)
g.addAresta(26, 14)
g.addAresta(26, 15)
g.printMatriz() |
from numpy import genfromtxt
import numpy as np
from scipy import optimize
# loosely adopted from Welch labs tutorial
class NeuralNetwork(object):
def __init__(self):
#Define Hyperparameters
self.inputLayerSize = 7
self.hiddenLayerSize = 3
self.outputLayerSize = 1
#Weights (parameters)
self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize)
self.W2 = np.random.randn(self.hiddenLayerSize,self.outputLayerSize)
def forward(self, X):
#Propogate inputs though network
self.z2 = np.dot(X, self.W1)
self.a2 = self.z2
self.z3 = np.dot(self.z2, self.W2)
yHat = self.z3
return yHat
def sigmoid(self, z):
#Apply sigmoid activation function to scalar, vector, or matrix
return 1/(1+np.exp(-z))
def sigmoidPrime(self,z):
#Gradient of sigmoid
return self.sigmoid(z)*(1 - self.sigmoid(z))
def costFunction(self, X, y):
#Compute cost for given X,y, use weights already stored in class.
self.yHat = self.forward(X)
J = 0.5*sum((y-self.yHat)**2)
return J
def costFunctionPrime(self, X, y):
#Compute derivative with respect to W and W2 for a given X and y:
self.yHat = self.forward(X)
delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3))
dJdW2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)
dJdW1 = np.dot(X.T, delta2)
return dJdW1, dJdW2
#Helper Functions for interacting with other classes:
def getParams(self):
#Get W1 and W2 unrolled into vector:
params = np.concatenate((self.W1.ravel(), self.W2.ravel()))
return params
def setParams(self, params):
#Set W1 and W2 using single paramater vector.
W1_start = 0
W1_end = self.hiddenLayerSize * self.inputLayerSize
self.W1 = np.reshape(params[W1_start:W1_end], (self.inputLayerSize , self.hiddenLayerSize))
W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize
self.W2 = np.reshape(params[W1_end:W2_end], (self.hiddenLayerSize, self.outputLayerSize))
def computeGradients(self, X, y):
dJdW1, dJdW2 = self.costFunctionPrime(X, y)
return np.concatenate((dJdW1.ravel(), dJdW2.ravel()))
def computeNumericalGradient(N, X, y):
paramsInitial = N.getParams()
numgrad = np.zeros(paramsInitial.shape)
perturb = np.zeros(paramsInitial.shape)
e = 1e-4
for p in range(len(paramsInitial)):
#Set perturbation vector
perturb[p] = e
N.setParams(paramsInitial + perturb)
loss2 = N.costFunction(X, y)
N.setParams(paramsInitial - perturb)
loss1 = N.costFunction(X, y)
#Compute Numerical Gradient
numgrad[p] = (loss2 - loss1) / (2*e)
#Return the value we changed to zero:
perturb[p] = 0
#Return Params to original value:
N.setParams(paramsInitial)
return numgrad
from scipy import optimize
class Trainer(object):
def __init__(self, N):
#Make Local reference to network:
self.N = N
def callbackF(self, params):
self.N.setParams(params)
self.J.append(self.N.costFunction(self.X, self.y))
def costFunctionWrapper(self, params, X, y):
self.N.setParams(params)
cost = self.N.costFunction(X, y)
grad = self.N.computeGradients(X,y)
print(cost)
return cost, grad
def train(self, X, y):
#Make an internal variable for the callback function:
self.X = X
self.y = y
#Make empty list to store costs:
self.J = []
params0 = self.N.getParams()
options = {'maxiter': 200, 'disp' : True}
_res = optimize.minimize(self.costFunctionWrapper, params0, jac=True, method='BFGS', \
args=(X, y), options=options, callback=self.callbackF)
self.N.setParams(_res.x)
self.optimizationResults = _res
def MAPEfunction(results, y):
numerator = results - y
numerator = numerator / y
result = np.sum(numerator)
return abs(result) / 2000
def main():
training_X = genfromtxt("train_X.csv", delimiter = ",", )
training_y = genfromtxt("train_y.csv", delimiter = ",")
test = genfromtxt("test.csv", delimiter = ",")
# batch testing took too long, split arrays here
training_X = training_X.reshape((2000, 7))
training_y = training_y.reshape((2000, 1))
test = test.reshape((460, 7))
NN = NeuralNetwork()
trainer = Trainer(NN)
trainer.train(training_X, training_y)
error = 0
error += MAPEfunction(NN.forward(training_X), training_y)
error = error.sum()
print(error)
# now that the net is trained, we can test it
results = NN.forward(test)
# results = np.asarray(results)
# print this array into the results file
np.savetxt("results.csv", results, delimiter = ",")
main()
|
import unittest
import pythoncode
location = './input/itcont.txt'
class TestCalc(unittest.TestCase):
def test_nsubs(self):
result1, result2 = pythoncode.summarize(location)
self.assertEqual(result1,1)
print("Only " + str(result1) + " unique prescriber - his name is Amir")
def test_totalcost(self):
result1, result2 = pythoncode.summarize(location)
self.assertEqual(result2,81124.05)
print("Amir has a total cost of " + str(result2))
if __name__=="__main__":
unittest.main()
|
#!/usr/bin/python3
"""Unittest for max_integer([..])"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""unittest class for max_integer"""
def test_max_integer(self):
""" tests"""
self.assertEqual(max_integer(""), None)
self.assertEqual(max_integer([]), None)
self.assertEqual(max_integer(), None)
self.assertEqual(max_integer("azerty"), "z")
self.assertEqual(max_integer([3, 5, 8]), 8)
self.assertEqual(max_integer([14, -1, 13]), 14)
self.assertEqual(max_integer([0, 7, 7, -3]), 7)
self.assertEqual(max_integer([5, 5, 9, 8, 9, 5]), 9)
self.assertEqual(max_integer([[9, 0], [2, 18]]), [9, 0])
self.assertEqual(max_integer([5]), 5)
self.assertEqual(max_integer([-1, -82, -43, -45]), -1)
str1 = ["a", "b", "c"]
self.assertEqual(max_integer(str1), "c")
str = [1, 8, "Hello", 7, 5]
with self.assertRaises(TypeError):
max_integer(str)
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
dic = {}
for key, value in a_dictionary.items():
dic[key] = (value * 2)
return dic
|
#!/usr/bin/python3
"""
containes class Rectangle
"""
from models.rectangle import *
class Square(Rectangle):
""" class square """
def __init__(self, size, x=0, y=0, id=None):
"""constructor"""
super().__init__(size, size, x, y, id)
def __str__(self):
""" toString"""
return "[Square] ({:d}) {:d}/{:d} - {:d}"\
.format(self.id, self.x, self.y, self.height)
@property
def size(self):
"""size.get()"""
return self.width
@size.setter
def size(self, size):
"""size.set()"""
self.width = size
self.height = size
def update(self, *args, **kwargs):
"""Update the class Rectangle by adding the public method """
if len(args):
for i, x in enumerate(args):
if i == 0:
self.id = x
elif i == 1:
self.size = x
elif i == 2:
self.x = x
elif i == 3:
self.y = x
else:
for i, x in kwargs.items():
setattr(self, i, x)
def to_dictionary(self):
"""dictionary representation"""
dec = {}
dec["id"] = self.id
dec["x"] = self.x
dec["size"] = self.height
dec["y"] = self.y
return dec
|
#!/usr/bin/python3
"""number_of_lines"""
def number_of_lines(filename=""):
"""number of lines of file"""
with open(filename, 'r', encoding='utf8') as file:
i = 0
for l in file:
i += 1
return i
|
"""
This files defines all the different maps and the map class
"""
import images
import pygame
import os
main_dir = os.path.split(os.path.abspath(__file__))[0] + "//maps//" #The directory to the saved maps, in folder maps
map_list = {} #All maps will be saved here
class Map:
""" An instance of Map is a blueprint for how the game map will look. """
def __init__(self, width, height, boxes, start_positions, flag_position):
""" Takes as argument the size of the map (width, height), an array with the boxes type,
the start position of tanks (start_positions) and the position of the flag (flag_position).
"""
self.width = width
self.height = height
self.boxes = boxes
self.start_positions = start_positions
self.flag_position = flag_position
def rect(self):
return pygame.Rect(0, 0, images.TILE_SIZE*self.width, images.TILE_SIZE*self.height)
def boxAt(self, x, y):
""" Return the type of the box at coordinates (x, y). """
return self.boxes[y][x]
def get_map(path, map_name):
"""Creates map objects from a folder containing text files"""
map_data = [] #To be filled with map information
with open(path) as file: #Opens the map with the name file
for line in file:
map_data.append(line)
map_info_list = search_through_textlist(map_data, 0) #map_info_list contains all the information about a map
map_list[map_name] = Map(map_info_list[0], map_info_list[1], map_info_list[2], map_info_list[3],map_info_list[4][0]) #Saves the maps from textfiles into a dictionary
def search_through_textlist(data, sep_index):
"""Retrieves values from a list and returns a list containing map information in right format"""
map_list = [] #All the map information is stored here
sep_index = 0 #To keep track of where you are in the text document. For example sep_index = 2 means that the box type values is being converted to the right format
map_row = []
for line in data: #Goes through every line in the text document
temp_list = []
if sep_index < 2:
map_list.append(int(line)) #The width and height from the textdocument is made to ints from a string
sep_index += 1
elif line[0] == "*": #* used to seperate arguments to map object
sep_index += 1
map_list.append(map_row)
map_row = []
elif sep_index >= 2:
separated_list = line.split(",") #map values without ,
if sep_index == 2: #Used to separete ints from flotes in map*.txt
for element in separated_list:
elem = int(element)
temp_list.append(elem) #List filled with only ints
map_row.append(temp_list)
if sep_index > 2:
for element in separated_list:
elem = float(element)
temp_list.append(elem) #List filled with only floats
map_row.append(temp_list)
return map_list
def load_maps():
"""Loads all map files from the maps directory."""
filenames = os.listdir(main_dir) #List of all maps names
for filename in filenames:
name = filename.split(".")[0] #Cuts out .txt from the name of the map
try:
get_map(main_dir + "//" + filename, name) #sends in path to map and name of map to function
except pygame.error:
raise SystemExit('Could not load mapfile "%s" %s'%(filename, pygame.get_error()))
def load_map(name):
"""Loads given map file from the maps directory."""
try:
get_map(main_dir + "//" + name + ".txt", name)
except pygame.error:
raise SystemExit('Could not load mapfile "%s" %s'%(filename, pygame.get_error()))
|
"""
This file defines the class A.I and declares its methods.
"""
import math
import pymunk
from pymunk import Vec2d
import gameobjects
from collections import defaultdict, deque
import sounds
# NOTE: use only 'map0' during development!
MIN_ANGLE_DIF = math.radians(3) # 3 degrees, a bit more than we can turn each tick
def angle_between_vectors(vec1, vec2):
""" Since Vec2d operates in a cartesian coordinate space we have to
convert the resulting vector to get the correct angle for our space.
"""
vec = vec1 - vec2
vec = vec.perpendicular()
return vec.angle
def periodic_difference_of_angles(angle1, angle2):
return (angle1% (2*math.pi)) - (angle2% (2*math.pi))
def turn_decider(rad):
'''If function returns True -> turn left, if function returns False -> turn right'''
if (rad >= 0 and rad < (math.pi)) or (rad >= (-3*math.pi/2) and rad <= (-math.pi)):
return 1 #Left
else:
return 2 #Right
class Ai:
""" A simple ai that finds the shortest path to the target using
a breadth first search. Also capable of shooting other tanks and or wooden
boxes. """
def __init__(self, tank, game_objects_list, tanks_list, space, currentmap):
self.tank = tank
self.game_objects_list = game_objects_list
self.tanks_list = tanks_list
self.space = space
self.currentmap = currentmap
self.flag = None
self.MAX_X = currentmap.width - 1
self.MAX_Y = currentmap.height - 1
self.allow_metalbox = False
self.path = deque()
self.move_cycle = self.move_cycle_gen()
self.update_grid_pos()
def update_grid_pos(self):
""" This should only be called in the beginning, or at the end of a move_cycle. """
self.grid_pos = self.get_tile_of_position(self.tank.body.position)
def decide(self):
""" Main decision function that gets called on every tick of the game. """
next(self.move_cycle)
self.maybe_shoot()
def update_on_death(self, tank):
"""Called upon when tank is destroyed"""
self.tank = tank
self.allow_metalbox = False#After the tank hase died, it are not allowed to find a path using metalbox
self.flag = None
def maybe_shoot(self):
""" Makes a raycast query in front of the tank. If another tank
or a wooden box is found, then we shoot.
"""
angle = self.tank.body.angle + (math.pi/2) #Same angle as tank but added pi/2 because math library and pymunk does not match
radius = 0.3 #Tank has lengh 0.25 from center to edge. By making radius 0.3 the ray begins at the tip of the tank and doesn't collide with tank
map_length = self.currentmap.width #The lengh of ray is as long as the map is wide. Could be set to 100 but map width is nicer
first_x_coord = math.cos(angle) * radius #makes x coordinate with right lenght and angle that can be attached to the tank
first_y_coord = math.sin(angle) * radius #makes y coordinate with right lenght and angle that can be attached to the tank
first_x_bullet = self.tank.body.position[0] + first_x_coord #Attaches the x coordinate to tank so the ray always is 0.3 lenght from tank and with the same angle as tank
first_y_bullet = self.tank.body.position[1] + first_y_coord #Attaches the y coordinate to tank
ray_start_pos = (first_x_bullet, first_y_bullet) #x and y where ray begins
second_x_coord = math.cos(angle) * map_length #Same as above
second_y_coord = math.sin(angle) * map_length
second_x_bullet = self.tank.body.position[0] + second_x_coord
second_y_bullet = self.tank.body.position[1] + second_y_coord
ray_end_pos = (second_x_bullet, second_y_bullet) #x and y where ray ends
res = self.space.segment_query_first(ray_start_pos, ray_end_pos, 0, pymunk.ShapeFilter()) #0 for radius of ray, returns first object ray hits
if hasattr(res, 'shape'): #If the returned object from raycast has an attribute named 'shape' we enter if statement
if not isinstance(res.shape, pymunk.Segment): #As long as ray didn't hit invicible segment enter if statement
if isinstance(res.shape.parent, gameobjects.Tank) or (isinstance(res.shape.parent, gameobjects.Box) and res.shape.parent.boxmodel.destructable): #If returned object from ray is either a tank or woddenbox
if self.tank.next_shoot < 1: #Delay between shots
self.tank.next_shoot = 1000
sounds.play_tank_shot()
bullet = self.tank.shoot(self.space) #Add bullet to space and game_objects_list
self.game_objects_list.append(bullet)
def correct_angle(self):
'''
Checks if tank is lined up correctly if not return False,
Used for pathfinding
'''
vector_angle = angle_between_vectors(self.grid_pos, self.next_coord)
self.angle_btw_vec = periodic_difference_of_angles(self.tank.body.angle, vector_angle)
if self.angle_btw_vec < MIN_ANGLE_DIF and self.angle_btw_vec > -MIN_ANGLE_DIF:
return True
else: #angle_btw_vec > MIN_ANGLE_DIF or angle_btw_vec < -MIN_ANGLE_DIF:
return False
def correct_pos(self):
'''
Returns True if we are standing on the correct coordinate
Used for pathfinding
'''
if self.tank.tile_dist < self.tank.body.position.get_distance(self.target_coord):
self.ready_to_turn = True
return True
else:
return False
def move_cycle_gen (self):
"""
The brain of the A.I, decides what the A.I should do next, called upon every tick
"""
while True:
shortest_path = self.find_shortest_path() #Hitta kortaste vägen till target
if not shortest_path: #Hittar vi ingen väg så körs loopen om
self.allow_metalbox = True
yield
continue
self.allow_metalbox = False
self.next_coord = shortest_path.popleft() #Fösta delmålet för att komma till target
self.target_coord = self.next_coord + [0.5, 0.5]
self.tank.tile_dist = self.tank.body.position.get_distance(self.target_coord) #Avståndet mellan target_coord och tankens position
yield
self.tank.accelerate()
if not self.correct_pos():
self.ready_to_turn = False
while not self.correct_angle() and self.ready_to_turn == True:
self.tank.stop_moving()
direction = turn_decider(self.angle_btw_vec)
if direction == 1:
self.tank.turn_left()
elif direction == 2:
self.tank.turn_right()
yield
self.tank.stop_turning()
yield
def find_shortest_path(self):
""" A simple Breadth First Search using integer coordinates as our nodes.
Edges are calculated as we go, using an external function.
"""
#-- Initialisation of the things we need --# #Need to update grid_pos for the tank
self.update_grid_pos()
source_tile = self.grid_pos
target_tile = self.get_target_tile()
visited_set = set()
deck = deque()
deck.append(source_tile)
shortest_path = []
parent = {} #Maps neighbor to source
parent[source_tile.int_tuple] = -1 #Stop condition
while deck: #While deck contains some form of information
left_tile = deck.popleft() #Removes the first node from the queue
visited_set.add(left_tile.int_tuple)
if left_tile == self.get_target_tile(): #Is True if the node removed from the queue is the target tile
shortest_path.insert(0, left_tile) #Adds the target tile to shortest_path list
while parent[left_tile.int_tuple] != -1:
shortest_path.insert(0, parent[left_tile.int_tuple])
left_tile = parent[left_tile.int_tuple]
shortest_path.remove(left_tile) #Removes the tile the tank started on
break
for neighbor in self.get_tile_neighbors(left_tile):
if not neighbor.int_tuple in visited_set: #If the neighbor node has not already been visited
deck.append(neighbor) #Adds it to the queue
visited_set.add(neighbor.int_tuple) #Add it to our set of visited nodes
parent[neighbor.int_tuple] = left_tile #Saves the path to this node in the dict parent
return deque(shortest_path)
def get_target_tile(self):
""" Returns position of the flag if we don't have it. If we do have the flag,
return the position of our home base.
"""
if self.tank.flag != None:
x, y = self.tank.start_position
else:
self.get_flag() # Ensure that we have initialized it.
x, y = self.flag.x, self.flag.y
return Vec2d(int(x), int(y))
def get_flag(self):
""" This has to be called to get the flag, since we don't know
where it is when the Ai object is initialized.
"""
if self.flag == None:
# Find the flag in the game objects list
for obj in self.game_objects_list:
if isinstance(obj, gameobjects.Flag):
self.flag = obj
break
return self.flag
def get_tile_of_position(self, position_vector):
""" Converts and returns the float position of our tank to an integer position. """
x, y = position_vector
return Vec2d(int(x), int(y))
def get_tile_neighbors(self, coord_vec):
""" Returns all bordering grid squares of the input coordinate.
A bordering square is only considered accessible if it is grass
or a wooden box.
"""
neighbors = [coord_vec + delta for delta in [(0, 1), (0, -1), (1, 0), (-1, 0)]] # Find the coordinates of the tiles' four neighbors
return filter(self.filter_tile_neighbors, neighbors) #The built-in python function filter applies the first argument funtion onto the second arguments iterable
def filter_tile_neighbors (self, coord):
"""
Checks if the given tile coordinates is a valid path for the tank
"""
#-- If the coord is out of the maps boundary --#
if coord[0] >= 0 and coord[0] <= self.MAX_X and coord[1] >= 0 and coord[1] <= self.MAX_Y:
box = self.currentmap.boxAt(coord[0], coord[1])
if box == 0 or box == 2 or (box == 3 and self.allow_metalbox == True):
return True
return False
SimpleAi = Ai # Legacy
|
import Traductores.condiciones
from Traductores.variables import variables
from Traductores.funciones import funciones
from Traductores.comentarios import comentarios
class ciclos(object):
def __init__(self, ast, anidado):
self.ast = ast['Ciclo']
self.exec_string = ""
self.anidado = anidado
def traducir(self):
# Variables con el valor del AST
nombreValor = ""
valorInicial = ""
comparador = ""
incremento = ""
valorFinal = ""
cuerpo = []
# Loop para guardar las variables
for val in self.ast:
try: nombreValor = val['NombreValorInicial']
except: pass
try: valorInicial = val['ValorInicial']
except: pass
try: comparador = val['Comparacion']
except: pass
try: valorFinal = val['ValorFinal']
except: pass
try: incremento = val['Incremental']
except: pass
try: cuerpo = val['cuerpo']
except: pass
# Si el aumnto tiene un + lo elimina (sintáxis de Python)
if incremento[0] == "+": incremento = incremento[1:len(incremento)]
# Añade la línea a la sintaxis de Python
self.exec_string += "for " + nombreValor + " in range(" + str(valorInicial) + ", " + str(valorFinal) + ", " + incremento + "):\n"
# Añade a la sintaxis de python con identación
self.exec_string += self.traducir_cuerpo(cuerpo, self.anidado)
return self.exec_string
def traducir_cuerpo(self, cuerpo_ast, anidado):
cuerpo_exec_string = ""
for ast in cuerpo_ast:
# Parse declaracion
if self.check_ast('DeclaracionVariable', ast):
var_obj = variables(ast)
traducir = var_obj.traducir()
cuerpo_exec_string += (" " * anidado) + traducir + "\n"
# Funciones
if self.check_ast('Funcion', ast):
gen_funciones = funciones(ast)
traducir = gen_funciones.traducir()
cuerpo_exec_string += (" " * anidado) + traducir + "\n"
# Comentarios
if self.check_ast('Comentario', ast):
gen_comentario = comentarios(ast)
traducir = gen_comentario.traducir()
cuerpo_exec_string += (" " * anidado) + traducir + "\n"
return cuerpo_exec_string
def check_ast(self, nombreAst, ast):
try:
if ast[nombreAst] == []: return True
if ast[nombreAst]: return True
except: return False |
"""
Author: Phạm Thanh Nam
Date: 30/10/21
File: savingsaccount.py
This module defines the SavingsAccount class.
"""
class SavingsAccount(object):
"""This class represents a savings account
with the owner's name, PIN, and balance."""
RATE = 0.02 # Single rate for all accounts
def __init__(self, name, pin, balance=0.0):
self.name = name
self.pin = pin
self.balance = balance
def __str__(self):
"""Returns the string rep."""
result = 'Name: ' + self.name + '\n'
result += 'PIN: ' + self.pin + '\n'
result += 'Balance: ' + str(self.balance)
return result
def getBalance(self):
"""Returns the current balance."""
return self.balance
def getName(self):
"""Returns the current name."""
return self.name
def getPin(self):
"""Returns the current pin."""
return self.pin
def deposit(self, amount):
"""Deposits the given amount and returns None."""
self.balance += amount
return None
def withdraw(self, amount):
"""Withdraws the given amount.Returns None if successful, or an
error message if unsuccessful."""
if amount < 0:
return "Amount must be >= 0"
elif self.balance < amount:
return "Insufficient funds"
else:
self.balance -= amount
return None
def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self.balance * SavingsAccount.RATE
self.deposit(interest)
return interest
class Bank(object):
def __init__(self):
self.accounts = {}
def __str__(self) :
"""Return the string rep of the entire bank."""
return '\n'.join(map(str, self.accounts.values()))
def makeKey(self, name, pin):
"""Makes and returns a key from name and pin."""
return name + "/" + pin
def add(self, account):
"""Inserts an account with name and pin as a key."""
key = self.makeKey(account.getName(),
account.getPin())
self.accounts[key] = account
def remove(self, name, pin):
"""Removes an account with name and pin as a key."""
key = self.makeKey(name, pin)
return self.accounts.pop(key, None)
def get(self, name, pin):
"""Returns an account with name and pin as a key
or None if not found."""
key = self.makeKey(name, pin)
return self.accounts.get(key, None)
def computeInterest(self):
"""Computes interest for each account and
returns the total."""
total = 0.0
for account in self.accounts.values():
total += account.computeInterest()
return total
def test_Bank():
bank = Bank()
bank.add(SavingsAccount("Wilma", "1001", 4000.00))
bank.add(SavingsAccount("Fred", "1002", 1000.00))
print(bank)
print(f"bank.computeInterest:",bank.computeInterest())
if __name__ == '__main__':
test_Bank()
|
import faiss
import numpy as np
from scipy import sparse, special
def estimate_pdf(target, emb, C=0.1):
"""Estimate the density of entities at the given target locations in the
embedding space using the density estimator based on the k-nearest
neighbors.
:param target: Target location at which the density is calculated.
:type target: numpy.array, shape=(num_target, dim)
:param emb: Embedding vectors for the entities
:type emb: numpy.ndarray, (num_entities, dim)
:param C: Bandwidth for kernels. Ranges between (0,1]. Roughly C * num_entities nearest neighbors will be used for estimating the density at a single target location.
:type C: float, optional
:return: Log-density of points at the target locations.
:rtype: numpy.ndarray (num_target,)
Reference
https://faculty.washington.edu/yenchic/18W_425/Lec7_knn_basis.pdf
.. highlight:: python
.. code-block:: python
>>> import emlens
>>> import numpy as np
>>> emb = np.random.randn(100, 20)
>>> target = np.random.randn(10, 20)
>>> density = emlens.estimate_pdf(target=target, emb = emb)
"""
if len(emb.shape) != 2:
raise TypeError(
"emb should be 2D numpy array of size (number of points, dimensions)"
)
if len(target.shape) != 2:
raise TypeError(
"target should be 2D numpy array of size (number of points, dimensions)"
)
n = emb.shape[0]
dim = emb.shape[1]
k = np.maximum(1, np.round(C * np.power(n, 4 / 5)))
k = int(k)
# Construct the knn graph
index = faiss.IndexFlatL2(dim)
index.add(emb.astype(np.float32))
distances, indices = index.search(target.astype(np.float32), k=k)
#
# KNN density estimator
# https://faculty.washington.edu/yenchic/18W_425/Lec7_knn_basis.pdf
#
logVd = np.log(np.pi) * (dim / 2.0) - special.loggamma(dim / 2.0 + 1)
Rk = np.max(distances, axis=1)
density = np.log(k) - np.log(n) - dim * np.log(Rk) - logVd
return density
|
# This function reads text data from a text file
def readFile(file_name):
data = ""
file = open(file_name, "r")
for line in file:
data = data + line.strip("\n")
return data
# This function prints the frequency dictionary
def printFreqsDict(freqs_dict):
for key, val in freqs_dict.items():
print(key,"-->", val)
def ComputingFrequencies(data, k):
data_dict = {}
data_len = len(data)
for i in range(data_len - k+1):
kmer_data = data[i:i+k]
if kmer_data in data_dict:
data_dict[kmer_data] = data_dict[kmer_data] + 1
else:
data_dict[kmer_data] = 1
return data_dict
pattern = "atgatcaag"
k = 9
genome_data = readFile("VibrioOriC.txt")
frequencies_dict = ComputingFrequencies(genome_data, k)
printFreqsDict(frequencies_dict)
print("Freq for '" + pattern + "' is", frequencies_dict[pattern])
|
# CalculateDistancePatternDna.py
#
# Written by: Steven Parker and Lynn Bui
#
#
#########################################
# Upload the Dna file
def readFile(file_name):
data = []
file = open(file_name, "r")
for line in file:
data.append(line.strip("\n"))
return data
# Hamming Distance function
def HammingDistance(pat1,pat2):
count=0
for i in range(len(pat1)): # Check for differences in patterns
if pat1[i] != pat2[i]:
count += 1
return count # Return the hamming distance
# Calculate Distance Pattern Dna function
def CDPD(data,pattern):
motif=[]
count=[]
for i in range(len(data)):
bestPattern = ""
dist_score = len(pattern) # The maximum dist_score
for j in range(len(data[i])-len(pattern)+1):
possiblePattern=data[i][j:j+len(pattern)]
ds=HammingDistance(pattern,possiblePattern)
if ds < dist_score:
dist_score = ds #update the dist_score
bestPattern = possiblePattern
motif.append(bestPattern)
count.append(dist_score) # Return an array of count
return str(motif)+'\n'+'Score: '+str(sum(count)) # To concatenate, outputs should have the same type
pattern = "AAA"
DNA_data = readFile("Dna.txt")
print(CDPD(DNA_data,pattern))
|
'''
Return fibonacci No. for given no. M
'''
'''
To run: python denominations.py 6
Output: 8
'''
import sys
m = int(sys.argv[1])
def fib(n):
if n == 0 or n == 1:
return n
return fib(n-1) + fib(n-2)
print fib(m)
|
print('Введите число:')
a = int(input())
if a > 0:
print('Ваше число больше нуля - оно положительное )')
elif a < 0:
print('Ваше число меньше нуля - оно отрицательное (')
elif a == 0:
print('Ваше число равняется нулю - оно нейтрально')
|
balance = 0
drinks = [
{'name': '可樂', 'price': 20},
{'name': '雪碧', 'price': 20},
{'name': '茶裏王', 'price': 25},
{'name': '原萃', 'price': 25},
{'name': "純粹喝", 'price': 30},
{'name': '水', 'price': 20},
]
def add(x, y):
"""
數字相加
:param x: 數字1
:param y: 數字2
:return: 相加結果
"""
def deposit():
"""
儲值功能
:return:nothing
"""
global balance
value = eval(input("儲值金額:"))
while value < 1:
print("====儲值金額需大於零====")
value = eval(input("儲值金額:"))
balance += value
print(f"儲值後金額為{balance}元")
def buy():
global balance, drinks
# 印出品項
print('\n請選擇商品')
# for item in drinks :
# print(f"{item['name']} {item['price']}元')
for i in range(0, len(drinks)):
print(f'{i + 1}, {drinks[i]["name"]} {drinks[i]["price"]}')
choose = eval(input('請選擇編號:'))
while choose < 1 or choose > 6:
print('====請輸入1-6之間====')
choose = eval(input('請選擇:'))
buy_drink = drinks[choose - 1]
while balance < buy_drink['price']:
print('====餘額不足,需要儲值嗎?')
want_deposit = input('y/n?')
if want_deposit == 'y' :
deposit()
elif want_deposit == 'n' :
break
else:
print('====請重新輸入====')
#儲值後餘額大於商品金額在購買
if balance >= buy_drink['price']:
print(f"已購買{buy_drink['name']} {buy_drink['price']}")
balance -= buy_drink['price']
print(f"購買後餘額{balance}元")
#變更
|
#customized utils
import math
import json_utils
import graphspace_utils
def parse_input(edgefile, delimiter, isDirected=False, isWeighted=False):
"""
Input file parser that takes in a file full of edges and parses them according to a modular delimiter. Can handle edge files that have weights, but the setting is off by default.
Returns a graph object.
Throws out self loops.
"""
edge_set = set()
node_set = set()
if not isWeighted:
max_edge_size = 2
else:
max_edge_size = 3
with open(edgefile, 'r') as f:
for line in f:
ls = line.strip('\n').split(delimiter)
if (len(ls) != max_edge_size) and (len(ls) != max_edge_size-1):
print("Something went wrong during input_parser(). There were " + str(len(ls)) + " columns in line:\n" + line.strip('\n') + "\nExpected " + str(max_edge_size) + " or " + str(max_edge_size-1) + " columns.")
return -1
handleData(ls, edge_set, node_set, isDirected, isWeighted)
nodes = set_to_list(node_set)
edges = set_to_list(edge_set)
g = Graph(nodes, edges, isDirected, isWeighted)
return g, nodes, edges
def handleData(ls, edge_set, node_set, isDirected, isWeighted):
#helper function for parse_input
#updates edge_set and node_set according to the number of elements in the data list and isDirected, isWeighted
if not isWeighted:
if len(ls) == 2: #wont add self loops to the edge list, but adds nodes in self loops to the node list
if not isDirected:
new_edge = tuple(ls)
edge_set.add(new_edge)
else:
new_edge = (ls[0],ls[1])
edge_set.add(new_edge)
for node in ls:
node_set.add(node)
else:
if len(ls) == 3: #wont add self loops to edge list, but adds nodes in self loops to the node list
if not isDirected:
new_edge = tuple(ls)
edge_set.add(new_edge)
else:
new_edge = (ls[0],ls[1],ls[2])
edge_set.add(new_edge)
node_set.add(ls[0])
node_set.add(ls[1])
if len(ls) == 2:
node_set.add(ls[0])
def set_to_list(s):
#helper function
#converts a set to a list
ls = []
for item in s:
ls.append(item)
return ls
'''
#uncomment this and comment out all the code below to get parse_input() to run if it's currently throwing an error.
class Graph:
#dummy graph class so that parse_input() doesn't throw an error during testing
def __init__(self, nodes, edges):
pass
'''
class Graph:
"""
This class will provide all the planned functionality. The basic idea is to be able to scale a given visual attribute (on graphspace) by a given data attribute as easily as possible without loss of customization power.
We do this by keeping a directory of data attributes which can be updated by the user on the fly. (Though the directory kept in the Graph object is mostly superficial at the moment. The Node class does all of the heavy lifting when it comes to actually enforcing the directory rules.)
Additionally, a basic adjacency list method is included if a user doesn't want to deal with the hassle of learning my framework.
Now has a working method normNodeAttr() that returns a normalized dictionary for any node attribute. Pretty snazzy.
"""
########################################################
#INFRASTRUCTURE METHODS (not for user)##################
########################################################
def __init__(self, nodes, edges, isDirected=False, isWeighted=False):
self.isDirected = isDirected
self.isWeighted = isWeighted
self.node_dir = set()
self.edge_dir = set()
self.naive_nodes = nodes
self.naive_edges = edges
self.nodes = self.init_nodes(nodes)
self.edges = self.init_edges(edges)
self.GSnodeAttrs = self.initGSnodeAttrs()
self.GSedgeAttrs = self.initGSedgeAttrs()
self.GStitle = None
self.GSdesc = None
self.GStags = None
def __dir__(self):
return [set_to_list(self.node_dir), set_to_list(self.edge_dir)]
#
#infrastructure methods for nodes
#
def init_nodes(self,nodes):
self.init_node_dir()
node_ls = []
for n in nodes:
node_ls.append(Node(n))
node_ls.sort(key=lambda x: x.get('ID')) #sorts the node list by ID
return node_ls
def init_node_dir(self):
self.node_dir.add('ID')
def newNodeAttr(self,attrName,loud=False):
#helper function for installNodeAttr
#installs attrName in the directory of each node in the graph.
for n in self.nodes:
n.newAttr(attrName,loud)
self.node_dir.add(attrName)
def putNodeAttrs(self,attrName, attrDict, loud=False):
#helper function for installNodeAttr
#give a dictionary whose keys are node IDs and whose values are the values for the desired attribute as attrDict
#this function uses put() to update the values of the given attribute for each node.
for n in self.nodes:
n.put(attrName,attrDict[n.get('ID')],loud)
#
#infrastructure methods for edges
#
def init_edges(self,edges):
self.init_edge_dir()
edge_ls = []
for e in edges:
if self.isWeighted and self.isDirected:
edge_ls.append(Edge(e[0],e[1],e[2],directed=True))
elif self.isWeighted:
edge_ls.append(Edge(e[0],e[1],e[2]))
elif (not self.isWeighted) and self.isDirected:
edge_ls.append(Edge(e[0],e[1],directed=True))
else:
edge_ls.append(Edge(e[0],e[1]))
return edge_ls
def init_edge_dir(self):
self.edge_dir.add('nodes')
self.edge_dir.add('ID')
self.edge_dir.add('source')
self.edge_dir.add('target')
if self.isWeighted:
self.edge_dir.add('weight')
def newEdgeAttr(self,attrName,loud=False):
for e in self.edges:
e.newAttr(attrName,loud)
self.node_dir.add(attrName)
def putEdgeAttrs(self, attrName, attrDict, loud=False):
for e in self.edges:
e.put(attrName, attrDict[e.get('ID')],loud)
#########################################################
#DATA INPUT/RETRIEVAL METHODS############################
#########################################################
def installNodeAttr(self, attrName, attrDict, loud=False):
#this method works a new attribute into the dynamic framework of the Node class
#give the desired name of the new attribute, along with a dictionary whose keys are node IDs and whose values are the values for the new attribute
#run this method and all the nodes in the graph will now have that attribute and the associated value from the dictionary.
self.newNodeAttr(attrName, loud)
self.putNodeAttrs(attrName, attrDict, loud)
def installEdgeAttr(self, attrName, attrDict, loud=False):
#same as installNodeAttr() but for edges
self.newEdgeAttr(attrName, loud)
self.putEdgeAttrs(attrName, attrDict, loud)
def getAttr(self, attrName, n_or_e, loud=False):
#returns a dictionary whose keys are IDs and whose values are values of the given attribute
d = {}
if n_or_e == 'n':
working_group = self.nodes
elif n_or_e == 'e':
working_group = self.edges
else:
raise NameError('n_or_e must be either \'n\' for nodes or \'e\' for edges.')
for x in working_group:
d[x.get('ID',loud)] = x.get(attrName,loud)
return d
def getNodeAttr(self, attrName, loud=False):
#returns a dictionary whose keys are node IDs and whose values are the given attribute
return self.getAttr(attrName, 'n', loud)
def getEdgeAttr(self, attrName, loud=False):
#returns a dictionary whose keys are edge IDs and whose values are the given attribute
return self.getAttr(attrName, 'e', loud)
#########################################################
#UTILITY METHODS#########################################
#########################################################
def normNodeAttr(self,attrName,loud=False):
#normalizes the values for the given node attribute and returns the normalized values as a dictionary
return self.normByAttr(attrName, 'n', loud)
def normEdgeAttr(self,attrName,loud=False):
#normalizes the values for the given edge attribute and returns the normalized values as a dictionary
return self.normByAttr(attrName, 'e', loud)
def normByAttr(self, attrName, n_or_e='n', loud=False):
#generalized method for getting a dictionary with normalized values according to the given attribute
d = {}
if n_or_e == 'n':
working_group = self.nodes
elif n_or_e == 'e':
working_group = self.edges
else:
raise NameError('n_or_e must be either \'n\' for nodes or \'e\' for edges.')
for x in working_group:
d[x.get('ID')] = float('nan')
for x in working_group:
if x.get(attrName,loud) != None:
a_max = x.get(attrName,loud)
max_x = x
break
else:
raise TypeError('Could not normalize by attribute ' + str(attrName) + 'because all nodes have None for that attribute.')
for x in working_group:
if x.get(attrName,loud) != None and x.get(attrName,loud) > a_max:
a_max = x.get(attrName,loud)
max_x = x
for x in working_group:
if x.get(attrName,loud) != None:
d[x.get('ID')] = x.get(attrName,loud)/float(a_max)
return d
def get_adj_ls(self):
#returns a naive adjacency list based on the data given by parse_input()
d = {}
for n in self.naive_nodes:
d[n] = []
for e in self.naive_edges:
if not self.isDirected:
d[e[0]].append(e[1])
d[e[1]].append(e[0])
else:
d[e[0]].append(e[1])
return d
def better_adj_ls(self):
d = {}
for n in self.nodes:
d[n.get('ID')] = []
for e in self.edges:
if not self.isDirected:
d[e.get('source')].append(e.get('target'))
d[e.get('target')].append(e.get('source'))
else:
d[e.get('source')].append(e.get('target'))
return d
###############################################
#GRAPHSPACE METHODS############################
###############################################
def initGSnodeAttrs(self):
attrs = {}
for n in self.nodes:
attrs[n.get('ID')] = {}
attrs[n.get('ID')]['id'] = n.get('ID')
attrs[n.get('ID')]['content'] = n.get('ID')
return attrs
def initGSedgeAttrs(self):
attrs = {}
for e in self.edges:
s = e.get('source')
t = e.get('target')
if s not in attrs:
attrs[s] = {}
attrs[s][t] = {}
return attrs
def GSnodeAttrsUpdate(self,GSattr,attrDict):
attrs = self.GSnodeAttrs
for n in attrDict:
attrs[n][GSattr] = attrDict[n]
self.GSnodeAttrs = attrs
def GSedgeAttrsUpdate(self,GSattr,edgeAttrDict):
attrs = self.GSedgeAttrs
for sDict in edgeAttrDict:
for t in sDict:
attrs[s][t][GSattr] = edgeAttrDict[s][t]
self.GSedgeAttrs = attrs
def uploadGraph(self, title=None, graphID=None, desc=None, tags=None):
json_filename = 'graphspace_upload.json'
user = input("Graphspace username: ")
pw = input("Graphspace password: ")
if title == None and self.GStitle == None:
title = input("Graph title: ")
if graphID == None:
graphID = input("Graph ID: ")
if desc == None and self.GSdesc == None:
desc = input("Graph description: ")
if tags == None and self.GStags == None:
tag_str = input("Graph tags (separated by comma): ")
tags = tag_str.strip().split(',')
n_ls = [x.get('ID') for x in self.nodes]
e_ls = []
for e in self.edges:
e_ls.append([e.get('source'), e.get('target')])
data = json_utils.make_json_data(n_ls, e_ls, self.GSnodeAttrs, self.GSedgeAttrs, title, desc, tags)
json_utils.write_json(data,json_filename)
graphspace_utils.postGraph(graphID, json_filename, user, pw)
class Node:
#node class for the graph with attributes that can be dynamically updated by a user(!)
#we do this by keeping track of a set of terms called the directory (accessible using the Python inbuilt dir() function) and a dictionary which holds all the information
#to make a new attribute, run newAttr() to install a new term in the directory. Only then is put() able to add a key value pair to the dictionary for that attribute.
#to access data from this node class, use the accession function get()
def __init__(self, ID):
self.d = {}
self.dir_set = set()
self.newAttr('ID')
self.put('ID', ID)
def put(self, attrName,val,loud=False):
#inputs a value for an existing attribute
if attrName not in dir(self):
raise NameError(str(self.__class__.__name__) + ' object contains no attribute called ' + str(attrName))
else:
self.d[attrName] = val
def get(self,attrName,loud=False):
#gets a value for an existing attribute
#if the attribute exists in the directory, but no value has been put, returns None (prints a warning if the loud argument is True)
if attrName not in dir(self):
raise NameError(str(self.__class__.__name__) +' object contains no attribute called ' + str(attrName))
elif attrName not in self.d:
if loud:
print("Warning! Attempting to get() attribute " + str(attrName) + " value from " + str(self.__class__.__name__) + " " + str(self.get('ID')) + ". A value for this attribute has not been set. (returns None)")
return None
else:
return self.d[attrName]
def newAttr(self, attrName,loud=False):
#installs a new attribute in the directory for recognition by the put() and get() methods.
#uses a set to avoid adding the same attribute multiple times (prints a warning when this happens if loud=True)
if loud and (attrName in self.dir_set):
print("Warning! Attempting to add a new attribute " + str(attrName) + " to " + str(self.__class__.__name__) + " " + str(self.get('ID')) + " but that attribute already exists in the directory.")
self.dir_set.add(attrName)
def __dir__(self):
#gives the directory in list form.
#this is magic class syntax. access this method via the Python inbuilt function dir()
#for example, if you made a node whose variable name is a, then to see the directory you would give dir(a) in python interactive.
return set_to_list(self.dir_set)
class Edge(Node):
#as it turns out the Node class is so generalizeable that edges are exactly the same except with a different init() statement
def __init__(self, s, t, weight=None, directed=False):
self.d = {}
self.dir_set = set()
self.newAttr('source')
self.newAttr('target')
if directed:
self.put('source', s)
self.put('target', t)
else: #if the edges are not directed, then the source and target are determined by alphabetical order (just for the sake of consistency)
first = max(str(s),str(t))
second = min(str(s),str(t))
self.put('source',first)
self.put('target',second)
if weight:
self.newAttr('weight')
self.put('weight', weight)
self.newAttr('nodes')
self.put('nodes',set([s,t]))
self.newAttr('ID')
if directed:
self.put('ID',str(s)+";"+str(t))
else: #if the edges are not directed, then the ID is the two strings, alphabetatized with a ; delimiter
self.put('ID',first+";"+second)
|
def calculator():
num1 = float(input("Enter a number:"))
op = input("Enter a operator:")
num2 = float(input("Enter a number:"))
if op == '+':
return round(num1 + num2)
elif op == '-':
return round(num1 - num2)
elif op == '*':
return round(num1 + num2)
elif op == '/':
return round(num1 + num2)
else:
return print('Enter a valid operator')
print(calculator()) |
auction = {}
def max_offer(auction):
max = -1
winner = ''
for bidder in auction:
if auction[bidder]>max:
max = auction[bidder]
winner=bidder
return winner
print("Welcome to the secret auction")
while True:
name = input("Input your name: \n")
offer = float(input("Your offer: \n"))
auction[name] = offer
exit = input("Are there any more offers? type 'yes' or 'no'")
if exit == 'no':
break
win = max_offer(auction)
print(f"The winner of the auction is {win} with ${auction[win]}") |
def add(x,y):
return x+y
def substrac(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
operations={
"+":add,
"-":substrac,
"*":multiply,
"/":divide
}
carry = 'no'
print("Simple calculator")
while True:
if carry == 'no':
num1 = int(input("Input the first number \n"))
num2 = int(input("Input the second number \n"))
symbol = input("What operation? '+','-','*','/'\n")
function_c = operations[symbol]
num1 = function_c(num1,num2)
print(f"Calculator output: {num1}")
exit = input("Exit? type 'yes' or 'no'\n")
if exit == 'yes':
break
carry = input("Save the output for another operation? types 'yes' or 'no'\n") |
from calculate.calculate import Calculate
cal = Calculate()
print("Currently IOTA/USD --->" + str(cal.GotIOT2USD()))
print("Currently IOTA/BTC ---> " + str(cal.GotIOT2BTC()))
print("Currently BTC/TWD --->" + str(cal.GotSellPrice()))
try:
select = input("choose you want \n1. Mi to TWD \n2.TWD to Mi\n")
if select == 1:
mi = input("your current Mi : ")
total = cal.CountCurrentlyTWD(mi)
print ("Count to TWD = "+str(total))
elif select == 2:
TWD = input("your want TWD : ")
total = cal.WantGot(TWD)
print ("Need total "+str(total) + " Mi")
except ValueError:
print('Not this function')
|
# -*- coding: utf-8 -*-
import Utils
import BaseThreadedModule
import Decorators
import re
import sys
@Decorators.ModuleDocstringParser
class Math(BaseThreadedModule.BaseThreadedModule):
"""
Execute arbitrary math functions.
Simple example to cast nginx request time (seconds with milliseconds as float) to apache request time
(microseconds as int):
- Math:
filter: if $(server_type) == "nginx"
target_field: request_time
function: int(float($(request_time)) * 1000)
If interval is set, the results of <function> will be collected for the interval time and the final result
will be calculated via the <results_function>.
function: the function to be applied to/with the event data.
results_function: if interval is configured, use this function to calculate the final result.
interval: Number of seconds to until.
target_field: event field to store the result in.
Configuration template:
- Math:
function: # <type: string; is: required>
results_function: # <default: None; type: None||string; is: optional if interval is None else required>
interval: # <default: None; type: None||float||integer; is: optional>
target_field: # <default: None; type: None||string; is: optional>
receivers:
- NextModule
"""
module_type = "modifier"
"""Set module type"""
def configure(self, configuration):
# Call parent configure method
BaseThreadedModule.BaseThreadedModule.configure(self, configuration)
self.results = []
function_str = "lambda event: " + re.sub('%\((.*?)\)s', r"event.get('\1', False)", self.getConfigurationValue('function'))
self.function = self.compileFunction(function_str)
if self.getConfigurationValue('results_function'):
function_str = "lambda results: "+ re.sub('%\((.*?)\)s', r"results", self.getConfigurationValue('results_function'))
self.results_function = self.compileFunction(function_str)
self.target_field = self.getConfigurationValue('target_field')
self.interval = self.getConfigurationValue('interval')
def compileFunction(self, function_str):
try:
lambda_function = eval(function_str)
except:
etype, evalue, etb = sys.exc_info()
self.logger.error("Failed to compile function: %s. Exception: %s, Error: %s." % (function_str, etype, evalue))
self.gp.shutDown()
return lambda_function
def getEvaluateFunc(self):
@Decorators.setInterval(self.interval)
def timedEvaluateFacets():
if self.results:
self.evaluateResults()
return timedEvaluateFacets
def initAfterFork(self):
if self.interval:
self.evaluate_facet_data_func = self.getEvaluateFunc()
self.timed_func_handler_a = Utils.TimedFunctionManager.startTimedFunction(self.evaluate_facet_data_func)
BaseThreadedModule.BaseThreadedModule.initAfterFork(self)
def evaluateResults(self):
results = self.results
self.results = []
try:
result = self.results_function(results)
except:
etype, evalue, etb = sys.exc_info()
self.logger.error("Failed to evaluate result function %s. Exception: %s, Error: %s." % (self.getConfigurationValue('results_function'), etype, evalue))
return
if self.target_field:
event_dict = {self.target_field: result}
else:
event_dict = {'math_result': result}
event = Utils.getDefaultEventDict(event_dict, caller_class_name=self.__class__.__name__, event_type='math')
self.sendEvent(event)
def handleEvent(self, event):
try:
result = self.function(event)
except:
etype, evalue, etb = sys.exc_info()
self.logger.error("Failed to evaluate function %s. Exception: %s, Error: %s." % (self.getConfigurationValue('function'), etype, evalue))
if self.interval:
self.results.append(result)
elif self.target_field:
event[self.target_field] = result
yield event |
# v1: Ordenacao para "arrays alvo" -> Com QuickSort para array "incial", com InsertionSort para array com os elementos finais
# INPUT-PALAVRAS: SEM ordenacao por insercao NEM pesquisa binaria no array_palavras e no array auxiliar dos IDs para eficiencia
# #### BIBLIOTECAS ####
import sys
# #### CONSTANTES ####
CMD_IN_GLOBAL = "PESQ_GLOBAL\n"
CMD_IN_UTILIZADORES = "PESQ_UTILIZADORES\n"
CMD_IN_TERMINADO = "TCHAU\n"
CMD_IN_TERMINADO2 = "TCHAU"
CMD_IN_PALAVRAS = "PALAVRAS\n"
CMD_IN_FIM = "FIM.\n"
CMD_OUT_GUARDADO = "GUARDADAS"
PARAGEM_CORTE = 30
# #### FUNCOES ####
def main():
# ### FUNCAO ### Funcao Principal
array_palavras = [] # [omg, xd, a, ahah] | Input "palavra + ID"
array_count_global = [] # [3, 1, 10, 2] ou [[3, 0], [1, 1], [10, 2], [2, 3]] [Count, Indice]
array_count_utilizadores = [] # [2, 1, 5, 2] > [[Count, Indice], ...]
# array_utilizadores = [] # [[109, 114], [109], [455,677,232,124,345], [098,345]] , IDs - Diferentes
if sys.stdin.readline() == CMD_IN_PALAVRAS:
array_palavras, array_count_global, array_count_utilizadores = input_palavras(array_palavras, array_count_global, array_count_utilizadores)
else:
sys.exit("Erro - Sem Comando Incial: " + CMD_IN_PALAVRAS)
input_cmd(array_palavras, array_count_global, array_count_utilizadores)
return 0
def input_palavras(array_palavras, array_count_global, array_count_utilizadores):
# ### FUNCAO ### Le e manipula o texto do stdin ate CMD_IN_FIM
array_ids_utilizadores = [] # [[109, 114], [109], [455,677,232,124,345], [098,345]] , IDs - Diferentes
for linha in sys.stdin:
if linha == "\n" or linha == "":
sys.exit("Erro - Sem Texto para input")
if linha == CMD_IN_FIM:
break
palavras = linha.split(" ")
palavras[0] = palavras[0].upper()
palavras[1] = palavras[1][:-1]
if palavras[0] in array_palavras:
indice = array_palavras.index(palavras[0])
array_count_global[indice][0] += 1
if not int(palavras[1]) in array_ids_utilizadores[indice]:
array_ids_utilizadores[indice].append(int(palavras[1]))
array_count_utilizadores[indice][0] += 1
else:
array_palavras.append(palavras[0])
indice = len(array_palavras)-1
array_ids_utilizadores.append([int(palavras[1])])
array_count_global.append([1, indice])
array_count_utilizadores.append([1, indice])
print(CMD_OUT_GUARDADO)
return array_palavras, array_count_global, array_count_utilizadores
def input_cmd(array_palavras, array_count_global, array_count_utilizadores):
# ### FUNCAO ### Le, executa e escreve no stdout os comandos no stdin, ate CMD_IN_TERMINADO
for linha in sys.stdin:
if linha == CMD_IN_TERMINADO2:
break
elif linha == CMD_IN_TERMINADO:
break
elif linha == "":
break
elif linha == CMD_IN_GLOBAL:
array_count_global = ordenacao(array_count_global)
string = ""
valor = array_count_global[-1][0]
start = len(array_palavras) - 1
for i in range(len(array_palavras)-1, -1, -1):
if valor == array_count_global[i][0]:
start = i
else:
break
alvo = []
for i in range(start, len(array_palavras)):
indice = array_count_global[i][1]
alvo.append(array_palavras[indice])
alvo.sort()
for i in range(len(alvo)):
string = string + str(alvo[i]) + " "
print(string[:-1])
elif linha == CMD_IN_UTILIZADORES:
array_count_utilizadores = ordenacao(array_count_utilizadores)
string = ""
valor = array_count_utilizadores[-1][0]
start = len(array_palavras)-1
for i in range(len(array_palavras)-1, -1, -1):
if valor == array_count_utilizadores[i][0]:
start = i
else:
break
alvo = []
for i in range(start, len(array_palavras)):
indice = array_count_utilizadores[i][1]
alvo.append(array_palavras[indice])
alvo.sort()
for i in range(len(alvo)):
string = string + str(alvo[i]) + " "
print(string[:-1])
else:
sys.exit("Erro - Interpretacao dos comandos pos-palavras")
return 0
def insertion_sort(array, indice_baixo, indice_alto):
for i in range(indice_baixo, indice_alto + 1):
temp = array[i] # Elemento a comparar
j = i - 1 # Começa com o elemento a baixo do temp
while j >= indice_baixo and temp[0] < array[j][0]: # ORDEM CRESCENTE, enquanto temp MENOR array[j] ->> os elementos sobem um degrau
array[j + 1] = array[j]
j = j - 1
array[j + 1] = temp # temp fica abaixo dos demais que subiram 1 degrau
return array
def quick_sort(array, indice_baixo, indice_alto):
# ### FUNCAO ### Quick Sort para Inteiros
if PARAGEM_CORTE > (indice_alto - indice_baixo): # Array < 30 elementos -> Insertion
array = insertion_sort(array, indice_baixo, indice_alto)
else:
indice_meio = int((indice_baixo + indice_alto) / 2)
if array[indice_alto][0] < array[indice_baixo][0]: # Mediana
temp = array[indice_alto]
array[indice_alto] = array[indice_baixo]
array[indice_baixo] = temp
if array[indice_meio][0] < array[indice_baixo][0]:
temp = array[indice_meio]
array[indice_meio] = array[indice_baixo]
array[indice_baixo] = temp
if array[indice_meio][0] < array[indice_alto][0]:
temp = array[indice_meio]
array[indice_meio] = array[indice_alto]
array[indice_alto] = temp
pivot = array[indice_meio][0] # Nomeia PIVOT
temp = array[indice_meio] # Troca pivot com (ultimo_elemento - 1)
array[indice_meio] = array[indice_alto - 1]
array[indice_alto - 1] = temp
ptr_baixo = indice_baixo
ptr_alto = indice_alto - 1
while True: # Percorre parte-do-array com ponteiros, a semelhanca nos slides 72 a 80 - Cap 6A ORD COM CHAVES
ptr_alto = ptr_alto - 1
ptr_baixo = ptr_baixo + 1
while array[ptr_alto][0] > pivot:
ptr_alto = ptr_alto - 1
while array[ptr_baixo][0] < pivot:
ptr_baixo = ptr_baixo + 1
if ptr_baixo < ptr_alto: # Troca
temp = array[ptr_alto]
array[ptr_alto] = array[ptr_baixo]
array[ptr_baixo] = temp
else:
break
temp = array[indice_meio] # Troca NOVAMENTE pivot no (ultimo_elemento - 1) com ptr_baixo =aprox= meio (backup)
array[indice_meio] = array[indice_alto - 1]
array[indice_alto - 1] = temp
array = quick_sort(array, indice_baixo, ptr_baixo - 1) # Parte o array em dois
array = quick_sort(array, ptr_baixo + 1, indice_alto)
return array
def ordenacao(array):
# ### FUNCAO ### *Abstracao* -> Chama a funcao de ordenamento
array = quick_sort(array, 0, len(array) - 1)
return array
if __name__ == '__main__':
# ### START ###
main()
|
for i in range(0, 10): #Number of rows
for j in range(0, i): #Blank spaces before the stars
print(' ', end = ' ')
for k in range(0, 19 - 2 * i): #Number of stars per row
print('*', end = ' ')
print('') #New line after each row
|
# a prompt series that displays different prompts based on user input, choose-your-own-adventure style
# prepare to receive yes/no resposes from the user
affirmativeResponses = ['yes', 'y', 'yep', 'affirmative']
negativeResponses = ['no', 'n', 'nope', 'negative']
def getYNResponses(x): # forces yes/no response from user
if (x) in affirmativeResponses:
return "yes"
elif (x) in negativeResponses:
return "no"
else:
x = input('Please respond "yes" or "no".\n')
return getYNResponses(x)
# collect the major structural info for the scene
POVCharacter = input("What's the name of the point-of-view character?\n")
goal = input('What is ' + POVCharacter + "'s goal during this scene?\n")
def getAdversaryYN(): # check if there's an adversary
return input("Will another person get in " + POVCharacter + "'s way?\n")
def getObstacle(): # learn the adversary or obstacle name
if getYNResponses(getAdversaryYN()) == "yes":
return input("Who will it be?\n")
else:
return input("What will get in their way instead?\n")
obstacle = getObstacle()
# print the scene plan
print("...\n")
print("Scene plan:\n")
print('Point of view character: ' + POVCharacter)
print(POVCharacter, "'s goal: " + goal)
print('Obstacle: ' + obstacle)
|
'''
Created on Jun 1, 2013
@author: Nenad
Blackjack is a simple, popular card game that is played in many casinos.
Cards in Blackjack have the following values:
an ace may be valued as either 1 or 11 (player's choice),
face cards (kings, queens and jacks) are valued at 10 and
the value of the remaining cards corresponds to their number.
During a round of Blackjack, the players plays against a dealer with the goal of building a hand (a collection of cards)
whose cards have a total value that is higher than the value of the dealer's hand, but not over 21.
(A round of Blackjack is also sometimes referred to as a hand.)
The game logic for our simplified version of Blackjack is as follows.
The player and the dealer are each dealt two cards initially with one of the dealer's cards being dealt faced down
(his hole card). The player may then ask for the dealer to repeatedly "hit" his hand by dealing him another card.
If, at any point, the value of the player's hand exceeds 21, the player is "busted" and loses immediately.
At any point prior to busting, the player may "stand" and the dealer will then hit his hand until the value of his hand
is 17 or more. (For the dealer, aces count as 11 unless it causes the dealer's hand to bust).
If the dealer busts, the player wins. Otherwise, the player and dealer then compare the values of their hands and
the hand with the higher value wins. The dealer wins ties in our version.
http://www.codeskulptor.org/#user15_6h1xzMh89f_0.py
'''
# Mini-project #6 - Blackjack
import simplegui
import random
# load card sprite - 949x392 - source: jfitz.com
CARD_SIZE = (73, 98)
CARD_CENTER = (36.5, 49)
card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")
CARD_BACK_SIZE = (71, 96)
CARD_BACK_CENTER = (35.5, 48)
card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png")
# initialize some useful global variables
in_play = False
score = 0
outcome = "Hit or Stand?"
sMessage = ""
# define globals for cards
SUITS = ('C', 'S', 'H', 'D')
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}
# define card class
class Card:
def __init__(self, suit, rank):
if (suit in SUITS) and (rank in RANKS):
self.suit = suit
self.rank = rank
else:
self.suit = None
self.rank = None
print "Invalid card: ", suit, rank
def __str__(self):
return self.suit + self.rank
def get_suit(self):
return self.suit
def get_rank(self):
return self.rank
def draw(self, canvas, pos):
card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank),
CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))
canvas.draw_image(card_images, card_loc, CARD_SIZE,
[pos[0] + CARD_CENTER[0],
pos[1] + CARD_CENTER[1]],
CARD_SIZE)
def drawBack(self, canvas, pos):
card_loc = (CARD_BACK_CENTER[0], CARD_BACK_CENTER[1])
canvas.draw_image(card_back, card_loc, CARD_BACK_SIZE,
[pos[0] + CARD_BACK_CENTER[0] + 1,
pos[1] + CARD_BACK_CENTER[1] + 1],
CARD_BACK_SIZE)
# define hand class
class Hand:
def __init__(self):
self.cards = []
def __str__(self):
sCards = ""
for card in self.cards:
sCards = sCards + str(card) + " "
return "Hand contains " + sCards.strip()
def add_card(self, card):
self.cards.append(card)
def get_value(self):
nValue = 0
bAce = False
for card in self.cards:
nValue += VALUES[card.get_rank()]
if card.get_rank() == 'A':
bAce = True
if bAce and nValue < 12:
nValue += 10
return nValue
def draw(self, canvas, pos):
for card in self.cards:
pos[0] = pos[0] + CARD_SIZE[0] + 20
card.draw(canvas, pos)
# define deck class
class Deck:
def __init__(self):
self.cards = []
for suit in SUITS:
for rank in RANKS:
self.cards.append(Card(suit, rank))
def shuffle(self):
random.shuffle(self.cards)
def deal_card(self):
return self.cards.pop()
def __str__(self):
sCards = ""
for card in self.cards:
sCards = sCards + str(card) + " "
return "Deck contains " + sCards.strip()
#define event handlers for buttons
def deal():
global in_play, myDeck, hPlayer, hDealer, outcome, score, sPlayer, sDealer, sMessage
if in_play:
score -= 1
in_play = False
deal()
else:
myDeck = Deck()
hPlayer = Hand()
hDealer = Hand()
myDeck.shuffle()
hPlayer.add_card(myDeck.deal_card())
hPlayer.add_card(myDeck.deal_card())
hDealer.add_card(myDeck.deal_card())
hDealer.add_card(myDeck.deal_card())
outcome = "Hit or Stand?"
sPlayer = "Player"
sDealer = "Dealer"
sMessage = ""
in_play = True
def hit():
global in_play, myDeck, hPlayer, score, outcome, sPlayer, sMessage
if in_play:
if hPlayer.get_value() < 22:
hPlayer.add_card(myDeck.deal_card())
if hPlayer.get_value() > 21:
sPlayer = "Busted!"
sMessage = "You've busted! You loose!"
score -= 1
outcome = "New deal?"
in_play = False
def stand():
global in_play, hDealer, hPlayer, score, outcome, sDealer, sMessage
if in_play:
while (hDealer.get_value() < 17):
hDealer.add_card(myDeck.deal_card())
if hDealer.get_value() > 21:
sDealer = "Busted!"
sMessage = "Dealer busted! You win!"
score += 1
outcome = "New deal?"
in_play = False
elif hPlayer.get_value() > hDealer.get_value():
sMessage = "Your hand's stronger! You win!"
score += 1
outcome = "New deal?"
in_play = False
else:
sMessage = "Your hand's weaker! You loose!"
score -= 1
outcome = "New deal?"
in_play = False
# draw handler
def draw(canvas):
canvas.draw_text("Blackjack", (60, 100), 40, "Aqua")
lDealer = canvas.draw_text(sDealer, (60, 185), 33, "Black")
lPlayer = canvas.draw_text(sPlayer, (60, 385), 33, "Black")
lOutcome = canvas.draw_text(outcome, (250, 385), 33, "Black")
lMessage = canvas.draw_text(sMessage, (250, 185), 25, "Black")
lScore = canvas.draw_text("Score: " + str(score), (450, 100), 33, "Black")
hDealer.draw(canvas, [-65, 200])
hPlayer.draw(canvas, [-65, 400])
if in_play:
hDealer.cards[0].drawBack(canvas, [28, 200])
# initialization frame
frame = simplegui.create_frame("Blackjack", 600, 600)
frame.set_canvas_background("Green")
#create buttons and canvas callback
frame.add_button("Deal", deal, 200)
frame.add_button("Hit", hit, 200)
frame.add_button("Stand", stand, 200)
frame.set_draw_handler(draw)
# get things rolling
frame.start()
deal() |
# tree data structure
from graphviz import Digraph, Source
import rospkg
class Tree:
"""
A class to represent the structure of a node
...
Attributes
----------
name : str
Name of the state.
nodeType : str
Type of state machine - state, parallel state machine, sequential state machine.
children : list
A list of the children, or substates, of the state.
daemon : list
A list of the UNIMPORTANT children, or substates, of the state.
depth : int
Represents the depth of the node of the tree within the state machine.
number : int
A unique integer value assigned to each state to easily differentiate between states.
Methods
-------
renderTree(path : str):
Renders the structure of the state machine tree to the specified path in the form of a .pdf file.
renderGraph(path : str):
Renders the flowchart of the state machine to the specified path in the form of a .pdf file.
size() -> int:
returns the number of nodes within the state machine
"""
@staticmethod
def create_flowchart(state, file_name='test'):
# path to destination of flowchart (PDF)
path = rospkg.RosPack().get_path('path_planning') + '/node_flowcharts/' + file_name
state.get_tree().render_graph(path)
print('Flowchart generated!')
def __init__(self, name, nodeType, children=None, daemon=None, depth=0, number=1):
if nodeType != "State" and children is None:
raise ValueError("Parallel or Sequential State has no Children: " + name)
self.name = name
self.children = children
self.daemon = daemon
self.nodeType = nodeType
self.depth = depth
self.number = number
self.__assign_nums()
# assigns numbers to each node of the tree
def __assign_nums(self, freqArr=None):
if freqArr is None:
freqArr = list(range(1, self.size() + 1))
self.number = freqArr[0]
freqArr.pop(0)
if self.children is not None:
for child in self.children:
child.__assign_nums(freqArr)
if self.daemon is not None:
for child in self.daemon:
child.__assign_nums(freqArr)
# returns handles for graph
def __return_handle(self, parent=None) -> str:
if self.nodeType == "State":
return parent.name + str(self.depth) + str(self.number)
else:
return 'cluster_{}'.format(str(self.depth)) + str(self.number)
# create graph
def __create_graph(self, parent: Digraph, unimportant=False):
# lowest level state
if self.nodeType == "State":
# graph only has one node
parent.node(self.name, label=self.name)
# sequential or parallel state machine
else:
with parent.subgraph(name=self.__return_handle(parent)) as g:
# is unimportant
if unimportant:
g.attr('node', style='filled', fillcolor='#d67272')
else:
g.attr('node', style='filled', fillcolor='white')
g.attr(label=self.name)
# declaring children nodes
for child in self.children:
if child.nodeType == "State":
g.node(child.__return_handle(self), label=child.name)
elif child.nodeType == "SequentialState" or child.nodeType == "ParallelState":
child.__create_graph(g)
# sequential state
if self.nodeType == "SequentialState":
# connecting children nodes
for i in range(len(self.children) - 1):
child1 = self.children[i]
child2 = self.children[i + 1]
parent1 = self
parent2 = self
while child1.nodeType != "State":
parent1 = child1
child1 = child1.children[0]
while child2.nodeType != "State":
parent2 = child2
child2 = child2.children[0]
# we are going from a non-basic state to non-basic state
if self.children[i].nodeType != "State" and self.children[i + 1].nodeType != "State":
g.edge(child1.__return_handle(parent1), child2.__return_handle(parent2),
ltail=parent1.__return_handle(), lhead=parent2.__return_handle())
# we are going from a basic state to non-basic state
elif self.children[i].nodeType == "State" and self.children[i + 1].nodeType != "State":
g.edge(child1.__return_handle(parent1), child2.__return_handle(parent2),
lhead=parent2.__return_handle())
# we are going from a non-basic state to basic state
elif self.children[i].nodeType != "State" and self.children[i + 1].nodeType == "State":
g.edge(child1.__return_handle(parent1), child2.__return_handle(parent2),
ltail=parent1.__return_handle())
# we are going from a basic state to basic state
else:
g.edge(child1.__return_handle(parent1), child2.__return_handle(parent2))
# parallel state
elif self.nodeType == "ParallelState" and self.daemon is not None:
# declaring unimportant nodes
for child in self.daemon:
if child.nodeType == "State":
g.attr('node', style='filled', fillcolor='#d67272')
g.node(child.__return_handle(self), label=child.name)
g.attr('node', style='filled', fillcolor='white')
elif child.nodeType == "SequentialState" or child.nodeType == "ParallelState":
child.__create_graph(g, unimportant=True)
else:
raise NotImplementedError(self.nodeType + " is not implemented yet")
# renders only current tree
def __render_curr_tree(self, dot: Digraph):
if self.children is not None:
for child in self.children:
dot.node(child.__return_handle(self), label=child.name)
dot.edge(self.__return_handle(), child.__return_handle(self))
child.__render_curr_tree(dot=dot)
if self.daemon is not None:
for child in self.daemon:
dot.node(child.__return_handle(self), label=child.name, style='filled', fillcolor='#d67272')
dot.edge(self.__return_handle(), child.__return_handle(self))
child.__render_curr_tree(dot=dot)
# returns number of nodes
def size(self) -> int:
total = 1
if self.children is not None:
for child in self.children:
total += child.size()
if self.daemon is not None:
for child in self.daemon:
total += child.size()
return total
# renders tree structure
def render_tree(self, path: str):
dot = Digraph(name=self.name, comment='Structure', engine='dot')
dot.node(self.__return_handle(), label=self.name)
self.__render_curr_tree(dot)
Source(dot.source).render(path, view=True)
# render graph
def render_graph(self, path: str):
dot = Digraph(name=self.name, comment='Flowchart', engine='dot')
self.__create_graph(dot)
dot.attr('graph', compound='True', nodesep='1')
Source(dot.source).render(path, view=True)
|
import numpy as np
from scipy.spatial.transform import Rotation
from matplotlib import pyplot as plt
"""
This file is a toy example to understand and test using Quaternion for rotations and PID controllers.
"""
class Quaternion:
def __init__(self, q_0=0, q_1=0, q_2=0, q_3=1):
self.q_0 = q_0
self.q_1 = q_1
self.q_2 = q_2
self.q_3 = q_3
@staticmethod
def from_real_imag(q_0, q_vec):
return Quaternion(q_0, q_vec[0], q_vec[1], q_vec[2])
@staticmethod
def from_array(arr):
return Quaternion(arr[0], arr[1], arr[2], arr[3])
@staticmethod
def from_scipy(rotation):
x, y, z, w = rotation.as_quat()
return Quaternion.from_array([w, x, y, z])
def real(self):
return self.q_0
def imag(self):
return np.array([self.q_1, self.q_2, self.q_3])
def conj(self):
return Quaternion.from_real_imag(self.real(), -self.imag())
def rotate(self, x_vec):
return self.conj() * Quaternion.from_real_imag(0, x_vec) * self
def unrotate(self, x_vec_prime):
return self * Quaternion.from_real_imag(0, x_vec_prime) * self.conj()
def E(self):
return np.array([[-self.q_1, self.q_0, -self.q_3, self.q_2],
[-self.q_2, self.q_3, self.q_0, -self.q_1],
[-self.q_3, -self.q_2, self.q_1, self.q_0]])
def G(self):
return np.array([[-self.q_1, self.q_0, self.q_3, -self.q_2],
[-self.q_2, -self.q_3, self.q_0, self.q_1],
[-self.q_3, self.q_2, -self.q_1, self.q_0]])
def as_scipy(self):
return Rotation.from_quat(np.array([self.q_1, self.q_2, self.q_3, self.q_0]))
def as_array(self):
return np.array([self.q_0, self.q_1, self.q_2, self.q_3])
def as_matrix(self):
return self.as_scipy().as_matrix()
def normalize(self):
arr = self.as_array()
return Quaternion.from_array(arr / np.linalg.norm(arr))
def as_rpy(self):
rpy = self.as_scipy().as_euler('ZYX')[::-1]
rpy[1] *= -1
return rpy
def __mul__(self, other):
if type(other) is Quaternion:
real = self.real() * other.real() - np.sum(self.imag() * other.imag())
imag = self.real() * other.imag() + other.real() * self.imag() + np.cross(self.imag(), other.imag())
return Quaternion.from_real_imag(real, imag)
if type(other) is int or type(other) is float:
return Quaternion(other * self.q_0, other * self.q_1, other * self.q_2, other * self.q_3)
raise NotImplemented
def __add__(self, other):
if type(other) is Quaternion:
return Quaternion(self.q_0 + other.q_0, self.q_1 + other.q_1,
self.q_2 + other.q_2, self.q_3 + other.q_3)
raise NotImplemented
def __str__(self):
return f'[{self.q_0}, {self.q_1}, {self.q_2}, {self.q_3}]'
def __repr__(self):
return f'Quaternion({self.q_0}, {self.q_1}, {self.q_2}, {self.q_3})'
@staticmethod
def get_omega(q, q_dot):
# noinspection PyCallingNonCallable
return (2 * q_dot * q.conj()).imag()
@staticmethod
def get_omega_prime(q, q_dot):
# noinspection PyCallingNonCallable
return (2 * q.conj() * q_dot).imag()
@staticmethod
def get_q_dot_from_omega(q, omega_vec):
return (1/2) * Quaternion.from_real_imag(0, omega_vec) * q
@staticmethod
def get_q_dot_from_omega_prime(q, omega_vec_prime):
return (1 / 2) * q * Quaternion.from_real_imag(0, omega_vec_prime)
def test_controller():
"""
Attempt to implement a Quaternion-based PD controller.
The system is numerically integrated to see if the controller successfully stabilizes to the target orientation.
The notation used is based off of this paper:
https://drive.google.com/file/d/12m8hsQJ-EKk8vDQYVwyyOT0U7RaDDAJw/view?usp=sharing
"""
data = []
target_quat = Quaternion.from_scipy(Rotation.from_euler('ZYX', np.array([0, 0, 0])))
dt = 0.001
# inertia matrix based on SolidWorks model
J = np.array([[2850, 1, -25],
[1, 3800, 200],
[-25, 200, 2700]])
J_inv = np.linalg.inv(J)
# Create starting quaternion and angular velocity
q = Quaternion.from_array(np.random.random(4)).normalize()
omega_vec_prime = np.random.random(3)
# PID coefficients
k_p = np.array([75, 75, 40])
k_d = np.array([150, 1000, 2000])
for _ in range(int(400 / dt)):
# calculate torque based on roll, pitch, yaw
# tau_vec_prime = np.dot(q.as_matrix(), -k_p * (q.as_rpy() - target_quat.as_rpy()) - k_d * omega_vec_prime)
# calculate torque directly from quaternions
# based on this paper: https://drive.google.com/file/d/1E2Oj3E-XInCSGpyhnBP0luWHWV0s0z9m/view?usp=sharing
quat_error = target_quat * q.conj()
axis_error = quat_error.imag() * (1 if (quat_error.real() > 0) else -1)
tau_vec_prime = -k_p * axis_error - k_d * omega_vec_prime
q_dot = Quaternion.from_array((-1/2) * np.dot(q.G().transpose(), omega_vec_prime))
omega_vec_prime_dot = np.dot(J_inv, tau_vec_prime) - \
np.dot(J_inv, np.cross(omega_vec_prime, np.dot(J, omega_vec_prime)))
q += q_dot * dt
q = q.normalize()
omega_vec_prime += omega_vec_prime_dot * dt
data.append(q.as_array())
if np.linalg.norm(q_dot.as_array()) > 100_000:
print('Warning: unstable!')
break
for i in range(4):
plt.plot(dt * np.arange(len(data)), [elem[i] for elem in data], label=f'$q_{i}$')
plt.xlabel('Time (s)')
plt.legend()
plt.show()
print('Target Quaternion:', target_quat)
print('Final Quaternion Achieved:', q)
if __name__ == '__main__':
test_controller()
|
import hashlib
str = "String"
result = hashlib.md5(str.encode())
print(f"The hexadecimal equivalent of hash is : result.hexdigest()")
|
def reverse(str1):
i=0
j=(len(str1)-1)
while (i<j):
temp2=str1[i]
str1 = str1[:i]+str1[j]+str1[i+1:]
str1 = str1[:j]+temp2+str1[j+1:]
i+=1
j-=1
return str1
str2 = input('Enter the string:')
print("String before reverse: {}".format(str2))
print("String after reverse: {}".format(reverse(str2))) |
ss=input()
c=0
for i in range(len(ss)):
if (ss[i].isalpha() or ss[i].isnumeric() or ss[i]==" "):
continue
c=c+1
else:
print(c)
|
u=input()
y=set(u)
if(y=={"0","1"}):
print("yes")
else:
print("no")
|
n=int(input())
sum=0
for i in range(1,n+1):
sum+=i
print(sum)
|
import math
#What is the largest prime factor of the number 600851475143?
n=raw_input('Enter the integer you wish to find the prime factors of: ')
n = int(float(n))
L=[]
def too_small():
"""to be called for int < 4"""
L.append(n)
if n>0:
L.append(1)
return L
if n < 4: #alg only works for int > 4
L = too_small()
print L
exit()
if n == 4: #because I'm lazy
L.append(2)
L.append(2)
print L
exit()
def primefactor():
"""prints list of all prime factors for int > 4"""
test=True
b=n
while(test):
i=2
while((b%i!=0)&(i<(b/2))): #find next prime
i=i+1
if i>=(b/2): #number is prime
L.append(b)
L.append(1)
test=False
else: #number is not prime
a=(b/i)
L.append(i)
b=a
return L
L = primefactor()
print L
exit() |
#!/usr/bin/env python3
'''
Mediator is a behavioral design pattern
that lets you reduce chaotic dependencies
between objects. The pattern restricts direct
communications between the objects and
forces them to collaborate only via
a mediator object.'''
class Mediator:
def __init__(self):
self._colleague_1 = Colleague1(self)
self._colleague_2 = Colleague2(self)
class Colleague1:
''' communicate with mediator whenever it want
otherwise with other colleauge'''
def __init__(self, mediator):
self._mediator = mediator
class Colleague2:
def __init__(self, mediator):
self._mediator = mediator
def main():
mediator = Mediator()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = int(input("введите число:"))
if a < 0:
print("Neg")
elif a == 0:
print("Zero")
else:
print("Pos") |
from __future__ import division
import math
import json
class TargetLoc:
# Generates new points along the line between drone and target using drones current x,y position and Line of Bearing
def locate(self, tc):
# inputs are JSON Records a set of three points in the form of 'lat', 'lon' 'aob'(angle of bearing), 'angleUnit'
# angleUnit is a string that thought be set to either 'deg' if bearing is in degrees or 'rad' if bearing is in radians
pt = []
ln = []
for p in tc["coords"]:
lat_lon = (p["lat"], p["lon"], p["aob"])
pt = self.addPoint(lat_lon, p["angleUnit"])
ln.append(self.extendLine(lat_lon, pt))
crossing = []
crossing.append(self.intersection(ln[0], ln[1]))
crossing.append(self.intersection(ln[1], ln[2]))
crossing.append(self.intersection(ln[0], ln[2]))
[isect, tloc] = self.intersectedCheck(crossing)
resp = {
"hasIntersect": isect,
"targetLoc": {
"lat": tloc[0],
"lon": tloc[1]
}
}
return resp
# Converts Line of Bearing into Radians if LOB was given in degrees
def LOB_to_theta(self, LOB, rad_or_deg):
if rad_or_deg == 'deg':
return -(LOB - 90)
elif rad_or_deg == 'rad':
return -(LOB - (math.pi/2))
# Generates a second pair of x,y coordinates for line intersection
def addPoint(self, p, rad_or_deg):
theta = self.LOB_to_theta(p[2], rad_or_deg)
# Will only convert theta to radians if using degrees - math.tan requires radians
if rad_or_deg == 'deg':
theta = math.radians(theta)
# By default, generate new point at x=1
# if p[0] = 1, generate new point at x=2
if p[0] != 1:
x = 1
y = (math.tan(theta) * (x - p[0]) + p[1])
else:
x = 2
y = (math.tan(theta) * (x - p[0]) + p[1])
new_point = [x, y]
return new_point
# Generates A, B and C from line equation Ax + By = C to be used in intersection method
# to calculate the Differential, Dx and Dy in intersection function
def extendLine(self, p1, p2):
A = (p1[1] - p2[1])
B = (p2[0] - p1[0])
C = (p1[0]*p2[1] - p2[0]*p1[1])
return A, B, -C
# Given 2 lines, determines if they intersect. Returns point of intersection if they do and False if the do not
def intersection(self, L1, L2):
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return (x, y)
else:
return False
# Determines whether intersection points are int same position or different
def intersectedCheck(self, intersectPoints):
# If all 3 lines intersect one another at some point, checks for relative distance from one intersections' x & y
# coordinates. Returns average coordinates if found, false otherwise.
I1 = intersectPoints[0]
I2 = intersectPoints[1]
I3 = intersectPoints[2]
if I1 and I2 and I3:
if abs(I1[0] - I2[0]) < 0.03 and abs(I2[0] - I3[0]) < 0.03 and abs(I1[0] - I3[0]) < 0.03:
if abs(I1[1] - I2[1]) < 0.03 and abs(I2[1] - I3[1]) < 0.03 and abs(I1[1] - I3[1]) < 0.03:
midpoint = ((I1[0] + I2[0] + I3[0])/3, (I1[1] + I2[1] + I3[1])/3)
return [True, midpoint]
else:
return [False, (None, None)]
else:
return [False, (None, None)]
else:
return [False, (None, None)]
|
def control_equal(*variables):
for variable0 in variables:
for variable1 in variables:
if variable0 != variable1:
return False
return True
def control_not_equal(*variables):
n = 0
for variable0 in variables:
n += 1
for variable1 in variables[n:]:
if variable0 == variable1:
return False
return True
def coff_control_function(C, O, F, T, H, E, R):
coff = F + 10 * F + 100 * O + 1000 * C
theor = R + 10 * O + 100 * E + 1000 * H + 10000 * T
if 3 * coff == theor and control_not_equal(C, O, F, T, H, E, R):
return True
return False
def coff_function():
list_of_solutions = []
for C in range(10):
for O in range(10):
for F in range(10):
for T in range(10):
for H in range(10):
for E in range(10):
for R in range(10):
if coff_control_function(C, O, F, T, H, E, R):
answer = {'C': C, 'O': O, 'F': F, 'T': T,
'H': H, 'E': E, 'R': R}
list_of_solutions.append(answer)
return list_of_solutions
def coffee_control_function(C, O, F, T, H, E, R, M):
coffee = 11 * E + 1100 * F + 10000 * O + 10**5 * C
theorem = M + 10010 * E + 100 * R + 10**3 * O + 10**5 * H + 10**6 * T
if 3 * coffee == theorem and control_not_equal(C, O, F, T, H, E, R, M):
return True
return False
def coffee_function():
list_of_solutions = []
for C in range(10):
for O in range(10):
for F in range(10):
for T in range(10):
for H in range(10):
for E in range(10):
for R in range(10):
for M in range(10):
if coffee_control_function(C, O, F, T, H,
E, R, M) \
and C < 3:
answer = {'C': C, 'O': O, 'F': F,
'T': T, 'H': H, 'E': E,
'R': R, 'M': M}
list_of_solutions.append(answer)
return list_of_solutions
answer = coff_function()
print(answer)
answer = coffee_function()
print(answer)
|
# Задание №1
# Пользователь вводит с клавиатуры 4 целых числа.
# Напишите функцию следующим образом: если первое число больше второго,
# то выводится среднее арифметическое всех четырех чисел,
# иначе надпись 'Ошибка'.
#
# Выполнил
# Петров Данил Анатольевич
# Mail: [email protected]
# Определяем функцию
def average_or_error(a, b, c, d):
if a > b:
print((a + b + c + d) / 4)
else:
print("Ошибка")
# Принимаем переменные
x = int(input("Введите первое число: "))
y = int(input("Введите второе число: "))
z = int(input("Введите третье число: "))
t = int(input("Введите четвертое число: "))
# Вызываем функию
average_or_error(x, y, z ,t)
|
import pandas as pd
import numpy as np
print('====what is a dataframe====')
# df is a 2-dim labeled data structure with columns of potentially different types
print('====create a dataframe====')
# use a dictionary(1D ndarrays, lists, dicts, or Series)
d = {"Math": [100, 99, 89],
"Chemistry": [98, 80, 78],
"Physics": [90, 77, 87]
}
df = pd.DataFrame(d, index=['Mike', 'Kara', 'Lucy'])
print(df)
print('====Random initialization====')
df2 = pd.DataFrame(np.random.rand(3, 5), columns=list("ABCDE"))
print(df2)
# df3 = pd.DataFrame(np.random.randint(-30, 90, 15).reshape(3, 5)) # 2D numpy.ndarray
# print(df3.iloc[:, [0]])
# print(df3.iloc[:, [0]].diff(-1))
print('===index and columns===')
# the resulting index will be the union of the indexes of the various Series, the dict's key will be the columns
d = {
"one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
"two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df4 = pd.DataFrame(d)
print(df4)
# index 行索引
print(df4.index)
# columns 列索引
print(df4.columns)
# df取一个columns的数据类型是什么?
# print(df4.one)
print('====row and column====')
'get a column'
# method1
print(df['Math'])
# method2
print(df[['Math', 'Chemistry']])
# method3
print(df.loc[:, ['Physics']])
# method4
print(df.iloc[:, [1]])
# method5
print(df2.B)
'get a row'
# method1
print(df.loc[['Mike', 'Kara']])
# method2
print(df.iloc[[0]])
# method3
# 切片取行必须是范围,切片取列
# df2[-1:] df2[:][-1:]# 取最后一行
# df2[:1] df2[:][:1]# 取第一行
# loc works on labels in the index
# iloc works on positions in the index
print('===from structured or record array===')
# np.zeros(shape, dtype=float, order='C') 返回一个给定形状和类型的用0填充的数组
# i:整数 f浮点数 a字符串
# this will return a ndarray
data = np.zeros((2,), dtype=[("A", "i4"), ("B", "f4"), ("C", "a10")])
data = [(1, 2.0, "Hello"), (2, 3.0, "World")]
print(data)
print(data[:1]) # 对data中的元素个数切片[(1, 2.0, 'Hello')]
# 给df添加index & columns
# 可以同时添加也可以分开添加,!columns
df5 = pd.DataFrame(data, index=('a1', 'a2'), columns=('b1', 'b2', 'b3'))
print(df5)
print('===from a list of dicts===')
# the new df's columns will union the key, one dict will be one index
# i could change the index and the columns, but it must be the right number
data2 = [{'m': 15, "n": 16, "f": 31}, {"f": 1, "y": 45, "r": 4, "u": 2}]
df6 = pd.DataFrame(data2, index=(1, 2))
df6.columns = ["A", "B", "C", "D", "E", 'F']
print(df6)
'===from a dict of tuples==='
data3 = [('a', 'b', 'c'), ('d', 'e', 'f'), ('d', 'g', 's')]
df7 = pd.DataFrame(data3, index=("row1", 'row2', 'row3'), columns=("col1", 'col2', 'col3'))
|
# ======variables======
string = 'hello, let\'s learn python'
string1 = '--test the strip()---'
# ======Escape character======
print('doesn\'t')
print("doesn't")
# ======Common functions======
string.replace(",", "")
# 把所有的','去掉
string.split(" ")
# 以" "为分隔符,分割成列表的形式.
# split(str="", num=string.count(str)) (分隔符,要分割成几个默认-1即所有)
string1.strip('-')
# 去掉字符串两头的指定字符
# ======字符串格式化======
A = 'pdf'
print(f'this is a {A}')
|
def hello_name(name):
return("Hello " + name + "!")
def make_abba(a, b):
return(a + b + b + a)
def make_tags(tag, word):
return("<" + tag + ">" + word + "</" + tag + ">")
def make_out_word(out, word):
return(out[0:2] + word + out[2] + out[3])
def extra_end(str):
return(str[-2]+str[-1]+str[-2]+str[-1]+str[-2]+str[-1])
def first_two(str):
return(str[0:2])
def first_half(str):
half = len(str)/2
return(str[0:half])
def without_end(str):
return(str[1:-1])
def combo_string(a, b):
if len(a) >= len(b):
return(b + a + b)
else:
return(a + b +a)
def non_start(a, b):
if len(a) == 1:
aval = ""
else:
aval = a[1:-1] + a[-1]
if len(b) == 1:
bval = ""
else:
bval = b[1:-1] + b[-1]
return(aval+bval)
def left2(str):
if len(str) > 2:
return(str[2:-1] + str[-1] + str[0:2])
else:
return(str[0:2])
value = int(input("What is the number you would like to test?: "))
if 0 == (value % 2):
print("The number is even")
else:
print("The number is odd")
humyears = int(input("How many years old is your dog?: "))
dogage = 4*(humyears-2)+21
if (humyears == 1):
print("Your dog is 10.5 in dog years")
else:
print("Your dog is " + str(dogage) + " in dog years")
letter = input("input a letter: ").lower()
if letter in ["a", "e", "i", "o", "u"]:
print("letter is a vowel")
elif letter == "y":
print("letter is sometimes a vowel")
else:
print("letter is not a vowel")
sides = int(input("How many sides does your shape have?: "))
if sides == 3:
print("it's atriangle")
elif sides == 4:
print("it's a quadrilateral")
elif sides == 5:
print("it's a pentagon")
elif sides == 6:
print("it's a hexagon")
elif sides == 7:
print("it's a heptagon")
elif sides == 8:
print("it's a octagon")
elif sides == 9:
print("it's a nonagon")
elif sides == 10:
print("it's a decagon")
else:
print("Error, invalid #")
month = input("Input a month: ").lower()
if month in ["january", "march", "may", "july", "august"]:
print("There are 31 days in this month")
elif month in ["april", "june", "september"]:
print("There are 30 days in this month")
elif month == "february":
print("There are 28 days in this month, 29 on leap years")
else:
print("invalid input")
noiselvl = int(input("How many decibels is the sound?: "))
if noiselvl < 10:
print("invalid, too silent")
elif noiselvl <= 40:
print("As quiet as a silent room")
elif noiselvl < 70:
print("Between quiet room and alarm clock")
elif noiselvl == 70:
print("As loud as a alarm clock")
elif noiselvl < 106:
print("Between alarm clock and gas lawnmower")
elif noiselvl == 106:
print("As loud as a gas lawnmower")
elif noiselvl < 130:
print("Between gas lawnmower and jackhammer")
elif noiselvl == 130:
print("As loud as a jackhammer")
elif noiselvl >= 185:
print("You are dead")
elif noiselvl >= 140:
print("Louder than a jackhammer")
side1 = int(input("What is the length of side #1 in meters: "))
side2 = int(input("What is the length of side #2 in meters: "))
side3 = int(input("What is the length of side #3 in meters: "))
if (side1 == side2) and (side2 == side3):
print("It is an equalateral triangle")
elif (side1 == side2) or (side2 == side3) or (side3 == side1):
print("It is an isosceles triangle")
else:
print("It is a scalar triangle")
alval = input("What is the alphabetical value for the note?: ").lower()
numval = int(input("What is the octive's numerical value?: "))
if alval == "c":
basefre = 32.5
elif alval == "d":
basefre = 36.5
elif alval == "e":
basefre = 41
elif alval == "f":
basefre = 43.5
elif alval == "g":
basefre = 49
elif alval == "a":
basefre = 55
elif alval == "b":
basefre = 61.5
else:
print("Invalid input")
freq = basefre*(2**(numval-1))
print("The note's frequency is around " + str(freq) + "Hz")
freq = int(input("What is the frequency of the note in hertz?: "))
if (freq % 261.63) <= 1 or (261.63 % freq) <= 1:
print("The note is C4")
elif (freq % 293.66) <= 1 or (293.66 % freq) <= 1:
print("The note is D4")
elif freq % 329.63 <= 1 or 329.63 % freq <= 1:
print("The note is E4")
elif freq % 349.23 <= 1 or 349.23 % freq <= 1:
print("The note is F4")
elif freq % 392 <= 1 or 392 % freq <= 1:
print("The note is G4")
elif freq % 440 <= 1 or 440 % freq <= 1:
print("The note is A4")
elif freq % 493.88 <= 1 or 493.88 % freq <= 1:
print("The note is B4")
else:
print("Unknown")
prez = input("Input the first initial of the first name then first initial of the last name of the person on your bill: ").lower()
if prez == "gw":
print("The value of the bill is $1")
elif prez == "tj":
print("The value of the bill is $2")
elif prez == "al":
print("The value of the bill is $5")
elif prez == "ah":
print("The value of the bill is $10")
elif prez == "aj":
print("The value of the bill is $25")
elif prez == "ug":
print("The value of the bill is $50")
elif prez == "bf":
print("The value of the bill is $100")
else:
print("No bill exists")
mon = input("What month is it?: ").lower()
day = input("What day on the month is it?: ")
if (mon + day) == "january1":
print("Happy new year!")
elif (mon + day) == "july1":
print("Happy Canada day!")
elif (mon + day) == "december25":
print("Merry Christmas!")
else:
print("No holiday or invalid input")
num = input("What is the y coordinate (intiger)?: ")
alp = input("What is the x coordinate (letter)?: ").lower()
if num in ["1", "3", "5", "7"]:
trunum = 1
elif num in ["2", "4", "6", "8"]:
trunum = 2
else:
print("invalid input")
if alp in ["a", "c", "e", "g"]:
trualp = 1
if alp in ["b", "d", "f", "h"]:
trualp = 2
final = trualp*trunum
if final == 2:
print("The tile is white")
else:
print("The tile is black")
|
import pandas as pd
df = pd.read_csv('olympics.csv',index_col=0,skiprows=1)
df.head()
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#'+col[1:]}, inplace=True)
names_ids = df.index.str.split('\s\(') # split the index by '('
df.index = names_ids.str[0] # the [0] element is the country name (new index)
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)
df = df.drop('Totals')
df
# You should write your whole answer within the function provided. The autograder will call
# this function and compare the return value against the correct solution value
def answer_zero():
# This function returns the row for Afghanistan, which is a Series object. The assignment
# question description will tell you the general format the autograder is expecting
return df.iloc[1]
#Q1 = Which country has won the most gold medals in summer games?
def answer_one():
return df['Gold'].argmax()
#Sol= 'United States'
#Q2: Which country had the biggest difference between their summer and winter gold medal counts?
def answer_two():
wint_gold = df['Gold.1']
summ_gold = df['Gold']
diff = (summ_gold - wint_gold).abs()
return diff.argmax()
#Sol = 'United States'
#Q3: Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count?
#Only include countries that have won at least 1 gold in both summer and winter.
def answer_three():
wint_gold = df['Gold'][df['Gold']>=1]
summ_gold = df['Gold.1'][df['Gold.1']>=1]
tot_gold = df['Gold.2']
reldiff = (summ_gold - wint_gold).abs()/tot_gold
return reldiff.argmax()
#Sol = 'Bulgaria'
#Q4: Write a function that creates a Series called "Points" which is a weighted value where each gold medal (Gold.2) counts for 3 points,
#silver medals (Silver.2) for 2 points, and bronze medals (Bronze.2) for 1 point.
#The function should return only the column (a Series object) which you created, with the country names as indices.
def answer_four():
totgold = df['Gold.2']*3
totsilv = df['Silver.2']*2
totbron = df['Bronze.2']*1
return totgold+totsilv+totbron
points = answer_four()
points.count()
#Sol:146
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 21 10:35:56 2021
check whether a number is a huppay number
"""
def numSquareSum(n):
squareSum = 0
n = str(n)
l = list(n)
l = list(map(int,l))
for i in l:
squareSum += i**2
return squareSum
def main():
n = int(input("Check whether is happy number or not: "))
origin = n
sumlist = []
while True:
if numSquareSum(n) not in sumlist:
if numSquareSum(n) == 1:
print(f"{origin} is a Happy number")
break
else:
sumlist.append(numSquareSum(n))
n = numSquareSum(n)
else:
print(f"{origin} is not a Happy number")
break
if __name__ == '__main__':
main() |
from .Die import Die
class DiceSet:
""" Simple set of dice with custom number of sides.
Any dice set can have any number of dice and each dice having the same number of sides.
Attributes:
dice (int) representing the number of dice in the box
sides (int) representing the number of sides each die has
"""
def __init__(self, dice=1, sides=6):
self.dice = self.create_dice_box(dice, sides)
self.sides = sides
def create_dice_box(self, dice, sides):
""" Function to create a list of Die objects.
To be used to store the list of dice in the DiceSet object.
Args:
dice (int): number of dice in the dice set
sides (int): number of sides each die has
Returns:
list(Die): list of Die objects in the dice set
"""
dice_list = []
for i in range(dice):
die = Die(sides)
dice_list.append(die)
return dice_list
def roll(self, verbose=False):
""" Function to roll the dice set.
Args:
verbose (optional): if True, verbose will also print the list of outcomes
Returns:
list(int): list of outcomes for each die roll
"""
rolls = [die.roll() for die in self.dice]
if verbose:
print(rolls)
return rolls
def __repr__(self):
""" Function to output the characteristics of the dice set
Args:
None
Returns:
string: characteristics of the dice set
"""
return "dice set of {} dice with {} sides".format(len(self.dice), self.sides) |
from tkinter import *
from random import randrange
def drawline():
"Tracé d'une ligne dans le canevas can1"
global x1, y1, x2, y2, coul
can1.create_line(x1,y1,x2,y2,width=2,fill=coul)
y2, y1 = y2+10, y1-10
def changecolor():
"Changement aléatoire de la couleur du tracé"
global coul
pal=['purple','cyan','marron','green','red','blue','orange','yellow']
c = randrange(8)
coul = pal[c]
x1, y1, x2, y2 = 10, 190, 190, 10
coul = 'dark green'
fen1 = Tk()
can1 = Canvas(fen1, bg='dark grey',height=200,width=200)
can1.pack(side=LEFT)
bou1 = Button(fen1,text='Quitter',command=fen1.quit)
bou1.pack(side=BOTTOM)
bou2 = Button(fen1,text='Tracer une ligne',command=drawline)
bou2.pack()
bou3 = Button(fen1,text='Autre couleur',command=changecolor)
bou3.pack()
fen1.mainloop()
fen1.destroy()
|
a=5
b=10
print("This file tests conditional statements")
print("a: ")
print(a)
print("b: ")
print(b)
# test <
print("a < b:")
print(a < b)
# test <=
print("a <= b:")
print(a <= b)
# test >
print("a > b:")
print(a > b)
# test >=
print("a >= b:")
print(a >= b)
# test ==
print("a == b:")
print(a == b)
# test !=
print("a != b:")
print(a != b) |
"""
Purpose
Recover wasted disk space, by finding duplicate files. Their removal could potentially free a lot of disk space.
Two things:
1. what image has the most duplicates
2. what image takes the most space
Searches deep inside a directory structure, looking for duplicate file.
Duplicates aka copies have the same content, but not necessarily the same name.
"""
__author__ = ""
__email__ = ""
__version__ = "1.0"
# noinspection PyUnresolvedReferences
from os.path import getsize, join
from time import time
# noinspection PyUnresolvedReferences
from p1utils import all_files, compare
def search(file_list):
'''Looking for duplicate files in the provided list of files:
returns a list of lists, where each list contains files with the same content'''
lol = [] #empty list of lists
while 0 < len(file_list):
dups = [x for x in file_list if compare(file_list[0], x)] #copy duplicates of first file in list to dups
file_list = [x for x in file_list if not compare(file_list[0], x)] #files that don't compare stays in file list
if 1 < len(dups):
lol.append(dups)
return lol
def faster_search(file_list):
"""Looking for duplicate files in the provided list of files:
returns a list of lists, where each list contains files with the same content"""
file_sizes = list(map(getsize, file_list))
file_list = list(filter(lambda x: 1 < file_sizes.count(getsize(x)), file_list))
return(search(file_list))
def report(lol):
""" Prints a report
:param lol: list of lists (each containing files with equal content)
:return: None
Prints a report:
- longest list, i.e. the files with the most duplicates
- list where the items require the largest amount or disk-space
"""
if 0 < len(lol):
print("== == Duplicate File Finder Report == ==")
ll = max(lol, key = len) #gets max of length of list
ll.sort() #sorts ll
print(f"The file with the most duplicates is: {ll[0]}")
print(f"Here are its {len(ll) - 1} copies:")
for i in range(1, len(ll)):
print(ll[i])
ll = max(lol, key=lambda x: len(x) * getsize(x[0]))
print('\n')
print(f"The Most Disk space ({getsize(ll[0]) * (len(ll)-1)}) could be recovered, by deleting copies of this file: {ll[0]}")
print(f"Here are its {len(ll)-1} copies:")
for i in range(1, len(ll)):
print(ll[i])
else:
print("No duplicates found")
print('\n')
if __name__ == '__main__':
path = join(".", "images")
# measure how long the search and reporting takes:
t0 = time()
report(search(all_files(path)))
print(f"Runtime: {time() - t0:.2f} seconds")
print("\n\n .. and now w/ a faster search implementation:")
# measure how long the search and reporting takes:
t0 = time()
report(faster_search(all_files(path)))
print(f"Runtime: {time() - t0:.2f} seconds")
|
print('My name is')
for ii in range(5):
print('Jimmy Five Times (' + str(ii) + ')')
sum = 0
for i in range(101):
sum = sum + i
print(sum)
for i in range(1, 10, 3):
print(i)
for i in range(0, -10, -2):
print(i) |
v = list()
def s(val, list_v):
list_v.append(val)
for i in range(10):
print(v)
s(i, v)
print(v)
|
while True:
import pyfiglet # pyfiglet lib
ascii_banner = pyfiglet.figlet_format("Ascii-Py")
print(ascii_banner)
print("Text to convert below...")
inp = input()
ascii_result = inp
if ascii_result.isalpha:
print(pyfiglet.figlet_format(ascii_result))
|
'''Creating a machine learning model for sentiment analysis.
Training data will be the New_sentiment_train.csv file created with the original stanford sentiment Treebank.
Then, apply the ML model on web scraped data containing amazon reviews of 10 mobile phones.
'''
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.linear_model import LogisticRegression
data = pd.read_csv('New_sentiment_train.csv', usecols = ['Phrase','Probability'])
# we can classify the review as :-
#[0, 0.2], (0.2, 0.4], (0.4, 0.6], (0.6, 0.8], (0.8, 1.0]
# very negative, negative, neutral, positive, very positive, respectively.
# let each class is represented as:-
# very negative ---> 1
# negative ---> 2
# neutral ---> 3
# positive ---> 4
# very positive ---> 5
for i in range(0,len(data['Probability'])):
if(data['Probability'][i]<=0.2):
data['Probability'][i]=1
elif (data['Probability'][i] > 0.2 and data['Probability'][i] <= 0.4 ):
data['Probability'][i] = 2
elif (data['Probability'][i] > 0.4 and data['Probability'][i] <= 0.6 ):
data['Probability'][i] = 3
elif (data['Probability'][i] > 0.6 and data['Probability'][i] <= 0.8 ):
data['Probability'][i] = 4
elif (data['Probability'][i] > 0.8 and data['Probability'][i] <= 1.0 ):
data['Probability'][i] = 5
else:
None
X = data['Phrase']
#converting x to TFidf vector
def identity_tokenizer(text):
return text
tfidf = TfidfVectorizer(tokenizer=identity_tokenizer, max_features=100000, lowercase=False)
X= tfidf.fit_transform(X)
y= data['Probability']
#to evaluate model, we will need test data
#split X,y in train test data
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
#creating a SVM model for sentiment analysis
clf = LogisticRegression(random_state=0)
clf.fit(X_train, y_train)
#testing and evaluating model
y_pred = clf.predict(X_test)
print(classification_report(y_test,y_pred))
#saving the model
import pickle
pickle.dump(clf, open('MODEL_LR', 'wb'))
#Applying the model on the scraped amazon reviews
#Sentiment score of reviews for different mobile will be saved in different csv file
#It will be saved in SentimentResult dir
Sphones_dir = ['MOBILE_OnePlus 7T Pro (Haze Blue, 8GB', 'MOBILE_OnePlus Nord 5G (Gray Onyx, 8G',
'MOBILE_OPPO F17 Pro (Magic Blue, 8GB ', 'MOBILE_Redmi 9 Prime (Space Blue, 4GB',
'MOBILE_Redmi Note 9 (Pebble Grey, 4GB', 'MOBILE_Samsung Galaxy M01 (Blue, 3GB ',
'MOBILE_Samsung Galaxy M21 (Blue, 4GB ', 'MOBILE_Samsung Galaxy M31 (Ocean Blue',
'MOBILE_Samsung Galaxy M31s (Mirage Bl', 'MOBILE_Vivo Y91i (Ocean Blue, 2GB RAM']
Sphones_names = ['OnePlus 7T Pro', 'OnePlus Nord', 'OPPO F17', 'Redmi 9 Prime', 'Redmi Note 9',
'Samsung Galaxy M01', 'Samsung Galaxy M21', 'Samsung Galaxy M31', 'Samsung Galaxy M31s',
'Vivo Y91i']
#var k to track the Sphone_names
#These names will be used for file names for result
k=0
for Sph_dir in Sphones_dir:
df_Sphone = pd.read_csv(Sph_dir+'.csv')
#Using the model to predict sentiment for Scraped Amazon reviews
#converting the review to tfidf vector
review_vector = tfidf.transform(df_Sphone['Customer Review'])
sentiment_score = clf.predict(review_vector)
sentiment = []
#Converting sentiment score (1-5) in sentiments like positive or negative
#For better representation
for i in range(0,len(sentiment_score)):
if(sentiment_score[i] == 1):
sentiment.append('Very Negative')
elif(sentiment_score[i] == 2):
sentiment.append('Negative')
elif (sentiment_score[i] == 3):
sentiment.append('Neutral')
elif (sentiment_score[i] == 4):
sentiment.append('Positive')
else:
sentiment.append('Very Positive')
result = pd.DataFrame()
result['Customer Name'] = df_Sphone['Customer Name']
result['Customer Review'] = df_Sphone['Customer Review']
result['Sentiment Score'] = sentiment_score
result['Sentiment'] = sentiment
result.to_csv(r'D:\Strings\Scraping&NLP\SentimentResult\Result_' + Sphones_names[k] + '.csv')
k=k+1
|
import shelve
def create():
shelf = shelve.open("mohit.raj", writeback=True)
shelf['desc'] ={}
shelf.close()
print "Dictionary is created"
def update():
shelf = shelve.open("mohit.raj", writeback=True)
data=(shelf['desc'])
port =int(raw_input("Enter the Port: "))
data[port]= raw_input("\n Enter the description\t")
shelf.close()
def del1():
shelf = shelve.open("mohit.raj", writeback=True)
data=(shelf['desc'])
port =int(raw_input("Enter the Port: "))
del data[port]
shelf.close()
print "\nEntry is deleted"
def list1():
print "*"*30
shelf = shelve.open("mohit.raj", writeback=True)
data=(shelf['desc'])
for key, value in data.items():
print key, ":", value
print "*"*30
print "\t Program to update or Add and Delete the port number detail\n"
while(True):
print "Press"
print "C for create only one time create"
print "U for Update or Add \nD for delete"
print "L for list the all values "
print "E for Exit "
c=raw_input("Enter : ")
if (c=='C' or c=='c'):
create()
elif (c=='U' or c=='u'):
update()
elif(c=='D' or c=='d'):
del1()
elif(c=='L' or c=='l'):
list1()
elif(c=='E' or c=='e'):
exit()
else:
print "\t Wrong Input"
|
import unittest
from unittestfile.count import Count
#必须要继承TestCase类
class CountTest(unittest.TestCase):
#每条用例开始执行setup和结束teardown都会执行
def setUp(self):
print("start")
def tearDown(self):
print("end")
#必须要以test_开头
def test_sub(self):
c = Count(13,5)
result = c.sub()
self.assertEqual(result, 8)
def test_sub2(self):
c = Count(3, 5)
result = c.sub()
self.assertEqual(result, -2)
def test_sub3(self):
c = Count(8, 5)
result = c.sub()
self.assertEqual(result, 3)
if __name__ == '__main__':
unittest.main() |
from multiprocessing.pool import Pool
class Menu:
def __init__(self):
self.title = '网易云音乐'
if __name__ == '__main__':
select = ['1,爬取热门歌单','2,爬取歌单详细','3,爬取歌曲评论']
while True:
for s in select:
print(s)
key = input("选择操作:")
# 爬取歌单
if key == '1':
|
#!/usr/bin/python
'''USAGE: fq2fa.py fastq
Converts a fastq to a fasta
'''
import sys
fasta = str(sys.argv[1]).rstrip('fastq') + 'fasta'
fasta = open(fasta, 'w')
with open(sys.argv[1], 'r') as fastq:
current = 1
for line in fastq:
if current == 1:
line = line.replace('@','>')
line = line.replace(' ','|')
fasta.write(line)
current += 1
continue
elif current == 2:
fasta.write(line + '\n')
current += 1
continue
elif current == 4:
current = 1
continue
else:
current += 1
fasta.close()
|
# записать в список только положительные числа
numbers = [1, 2, 3, 4, 5, -1, -2, -3, -4, -5]
# классический случай
result = [] # переменная для результата
for number in numbers: # в цикле перебираем наши числа
if number > 0: # если число > 0
result.append(number) # то добавляем в результат это число
print(result)
# через функцию filter
# на входе number, на выходе number > 0
result = filter(lambda number: number > 0, numbers) # функция из двух частей
print(list(result))
# через генератор
result = [number for number in numbers if number > 0] # перебираем список и записываем по условию (>0)
print(result)
# генератор словаря
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
# классический способ
result = {}
for pair in pairs: # перебираем пары
key = pair[0]
val = pair[1]
result[key] = val # по ключу сохраняем значение
print(result)
# через генератор словаря
result = {pair[0]: pair[1] for pair in pairs} # слева ключ [0], справа значение [1]
print(result) |
import random
words_list = ('автострада', 'бензин', 'инопланетянин', 'самолет',
'библиотека', 'шайба', 'олимпиада', 'зима', 'пальма')
secret_word = random.choice(words_list)
print(secret_word)
gamer_word = ['*'] * len(secret_word)
print(''.join(gamer_word))
# gamer_word[2] = 'г'
# print(''.join(gamer_word))
while True:
letter = input('введите ОДНУ русскую букву: ')
if len(letter) != 1 or not letter.isalpha():
# print('....')
continue
print('вы ввели:', letter)
print('играйте еще!')
|
# Функция - map
# Набор чисел
numbers = [5, 3, 4, 7, 8]
# Получить список квадратов чисел
print(list(map(lambda x: x**2, numbers))) # Получаем [25, 9, 16, 49, 64]
# Привести числа к строке
print(list(map(lambda x: str(x), numbers))) # Получаем ['5', '3', '4', '7', '8']
|
def my_f(my_var):
my_var = 999
print('Внутри функции:', my_var)
a = 1
my_f(a)
print('После выполнения функции: ', a)
global_var = 1
def my_f2():
# Локальная переменная
local_var = 100
# Используем ее внутри функции
print(local_var)
# Глобальная переменная, объявлена в модуле (изменить нельзя)
print(global_var)
my_f2()
print(global_var)
# Локальная переменная тут недоступна
# print(local_var)
# Здесь пробуем изменить глобальную переменную (не рекомендуется)
def my_f3():
global global_var
# Локальная переменная
local_var = 100
# Используем ее внутри функции
print(local_var)
# Глобальная переменная, объявлена в модуле
global_var = 999
print(global_var)
my_f3()
print(global_var)
|
# 2: Дан список, заполненный произвольными числами.
# Получить список из элементов исходного, удовлетворяющих следующим условиям:
# Элемент кратен 3,
# Элемент положительный,
# Элемент не кратен 4.
numbers = [1, 5, -9, 10, 27, 0, 17, 45, 100, 11, -7, 12, -27]
result = [number for number in numbers if number > 0 and number % 3 == 0 and number % 4 != 0]
print(result) |
'''Exercise : how many'''
# write a procedure, called how_many, which returns the
#sum of the number of values associated with a dictionary.
def how_many(animals):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
# Your Code Here
sum1 = 0
values = animals.values()
for words in values:
sum1 = sum1 + len(words)
return sum1
def main():
'''dist'''
number = input()
animals = {}
for i in range(int(number)):
entries = input()
list1 = entries.split()
if list1[0][0] not in animals:
animals[list1[0][0]] = [list1[1]]
else:
animals[list1[0][0]].append(list1[1])
#animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
#animals['d'] = ['donkey']
#animals['d'].append('dog')
#animals['d'].append('dingo')
print(animals)
print(how_many(animals))
if __name__ == "__main__":
main()
|
'''define the simple_divide function here'''
def simple_divide(item, denom):
'''start a try-except block'''
try:
return item / denom
except ZeroDivisionError:
return 0
def fancy_divide(list_of_numbers, index):
'''fun'''
denom = list_of_numbers[index]
return [simple_divide(item, denom) for item in list_of_numbers]
def main():
'''a'''
data = input()
line = data.split()
line1 = []
for j in line:
line1.append(float(j))
san = input()
index = int(san)
print(fancy_divide(line1, index))
if __name__ == "__main__":
main()
|
x = 2
for x in range(2,11,2):
print("print"+" "+str(x))
print("print Goodbye!") |
'''
Write a python program to read multiple lines of text input and store the input into a string.
'''
def newlines(newline):
'''printing new line'''
newl = newline
return newl
def main():
'''f
'''
documents = ""
lines = int(input())
for i in range(lines):
i += 1
documents += input()
documents += '\n'
print(newlines(documents))
if __name__ == '__main__':
main()
|
#! /usr/bin/python2.7
#'''
#####################################################################
# function: find how many same character in array.
# input = ['a', 'b', 'c', 'd', 'e', 'a', 'a', 'b', 'e']
class soluTion(object):
def searchDuplicate(self, arrayA):
lenGth = len(arrayA)
result = []
rstDict = {}
for i in range(lenGth):
if arrayA[i] not in result:
result.append(arrayA[i])
else:
if arrayA[i] not in rstDict:
tmp = {arrayA[i]: 2}
rstDict.update(tmp)
else:
rstDict[arrayA[i]] += 1
return result, rstDict
in_arr = ['a', 'b', 'c', 'd', 'e', 'a', 'a', 'b', 'e']
a = soluTion()
print(in_arr)
rst = a.searchDuplicate(in_arr)
print(rst)
#####################################################################
#'''
#'''
#####################################################################
# function: find how many same character in array.
print("===================================================================")
class soluTion(object):
def searchDuplicate(self, inputCharArr):
lenGth = len(inputCharArr)
res = []
resdup ={}
for inp in inputCharArr:
if inp not in res:
res.append(inp)
else:
if inp not in resdup:
tmp = {inp : 1}
resdup.update(tmp)
else:
resdup[inp] += 1
return resdup
in_arr = ['a', 'b', 'c', 'd', 'e', 'a', 'a', 'b', 'e']
a = soluTion()
print(in_arr)
rst = a.searchDuplicate(in_arr)
print(rst)
#####################################################################
#'''
|
#! /usr/bin/python2.7
#'''
#####################################################################
# function: LeetCode:Easy 26. return number of array after removing Duplicates from Sorted Array
# Input: [1,1,2]
# Output: [1,2] -> 2
# Input: [0,0,1,1,1,2,2,3,3,4]
# Output: [0,1,2,3,4] -> 5
print("===========================================================")
def numofdeleteduplicate(arrayIn):
lenGth = len(arrayIn)
i = 0
j = 1
while(j < lenGth):
if(arrayIn[i] == arrayIn[j]):
j += 1 #1:j=2
else:
i += 1 #2:i=1 #3:i=2
arrayIn[i] = arrayIn[j]
j += 1 #2:j=3 #3:j=4
return i+1
a = [0,0,1,1,1,2,2,3,3,4]
a = ['a', 'b', 'c', 'a', 'b', 'c']
rst = numofdeleteduplicate(a)
print(rst)
#####################################################################
#'''
#'''
#####################################################################
# function: LeetCode:Easy 26. return number of array after removing Duplicates from Sorted Array
# Input: [1,1,2]
# Output: [1,2] -> 2
# Input: [0,0,1,1,1,2,2,3,3,4]
# Output: [0,1,2,3,4] -> 5
print("===========================================================")
def numofdeleteduplicate1(arrayIn):
lenGth = len(arrayIn)
result = []
for i in arrayIn:
if i not in result:
result.append(i)
return len(result)
a = [0,0,1,1,1,2,2,3,3,4]
rst = numofdeleteduplicate1(a)
print(rst)
#####################################################################
#'''
#'''
#####################################################################
# function: LeetCode:Easy 26. return number of array after removing Duplicates from Sorted Array
# Input: [1,1,2]
# Output: [1,2] -> 2
# Input: [0,0,1,1,1,2,2,3,3,4]
# Output: [0,1,2,3,4] -> 5
print("===========================================================")
def deleteduplicate(arrayIn):
lenGth = len(arrayIn)
result = []
for i in arrayIn:
if i not in result:
result.append(i)
return result
a = ['a', 'b', 'c', 'a', 'b', 'c']
#a = [0,0,1,1,1,2,2,3,3,4]
rst = deleteduplicate(a)
print(rst)
#####################################################################
#'''
#'''
#####################################################################
# function: delete duplicate in string
# Input: ("abcabc") -> Output: ('a', 'b', 'c')
# convert tuple to list because string needs to be converted to char
# list = list(tuple), tuple = tuple(list)
# list to dictionary
# 1) res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
# 2) it = iter(lst)
# res_dct = dict(zip(it, it))
print("===========================================================")
class soluTion(object):
def deleteduplicate2(self, inPut):
res = []
for i in inPut:
if i not in res:
res.append(i)
res = tuple(res)
return res
a=soluTion()
inPutVar = ("abcabc")
print("input ", inPutVar)
tmp = list(inPutVar)
inPutVar = tmp
rst = a.deleteduplicate2(inPutVar)
result=""
for i in rst:
result+=i
print("output ", result)
#'''
#'''
#####################################################################
# function: find first duplicate
# Input: ['a', 'b', 'c', 'a', 'b', 'd'] -> a
print("===========================================================")
class soluTion(object):
def find1stduplicate(self, inPut):
res = []
dupres = []
k = 0
for i in inPut:
#print(i)
if i not in res:
res.append(i)
else:
dupres.append(i)
break
return dupres[0]
inPutVar = ['a', 'b', 'c', 'a', 'b', 'd']
a = soluTion()
print("input ", inPutVar)
rst = a.find1stduplicate(inPutVar)
print(rst)
#'''
#'''
#####################################################################
# function: find second duplicate
# Input: ['a', 'b', 'c', 'a', 'b', 'd'] -> b
print("===========================================================")
def find2ndduplicate(arrayIn):
res = []
dupres = []
for i in arrayIn:
if i not in res:
res.append(i)
else:
dupres.append(i)
return dupres[1]
a = ['a', 'b', 'c', 'a', 'b', 'd']
rst = find2ndduplicate(a)
print(rst)
#####################################################################
#''' |
#! /usr/bin/python2.7
#'''
#####################################################################
def appendFile(text, filename):
with open(filename, "a") as f:
f.write(text)
f.write("\n")
f.close()
#infile = "a3"+".out"
#appendFile("hahaha", infile)
appendFile("hahaha", "a3.out")
appendFile("hohoho", "a3.out")
#####################################################################
#'''
outFile = open("a4.out", "w")
outFile.write("HAHAHA\n")
outFile.write("HoHoHo\n")
outFile.close()
|
def MisterRobot(n, data):
sort_data = data[:]
sort_data.sort()
flag = True
while flag:
flag = False
for i in range(n - 2):
if (data[i + 1] > data[i] > data[i + 2] or
data[i] > data[i + 1] and data[i + 1] < data[i + 2]):
data[i], data[i + 1], data[i + 2] = data[i + 1], data[i + 2], data[i]
flag = True
if data == sort_data:
return True
else:
return False
|
# import statements.
from globals import friends,Spy
from termcolor import colored
from spy_details import spy
# add new friends.
import re
def add_friend():
new_friend =Spy(" "," ",0,0.0,False)
tempcheck=True#temporary variable
#Validation Using Regex
patternsalutation='^Mr|Ms$'
patternname='^[A-Za-z][A-Za-z\s]+$'
patternage='^[0-9]+$'
patternrating='^[0-9]+\.[0-9]$'
#Validating Each Values Using Regular Expression
while tempcheck:
salutation = raw_input("Mr. or Ms.? : ")
if (re.match(patternsalutation, salutation) != None):
tempcheck = False
else:
print colored("Enter Again!!!!",'red')
tempcheck=True
while tempcheck:
new_friend.Name=raw_input("Enter Name: ")
if(re.match(patternname,new_friend.Name)!=None):
tempcheck=False
else:
print colored("Enter Again!!!!",'red')
# concatenation.
new_friend.Name = salutation + "."+new_friend.Name
tempcheck=True
while tempcheck:
new_friend.Age = raw_input("Age?")
if (re.match(patternage, new_friend.Age) != None):
tempcheck = False
new_friend.Age=int(new_friend.Age)
else:
print colored("Enter Again!!!!",'red')
tempcheck=True #temporary variable
while tempcheck:
new_friend.Rating = raw_input("Spy rating?")
if (re.match(patternrating, new_friend.Rating) != None):
tempcheck = False
new_friend.Rating=float(new_friend.Rating)
else:
print colored("Enter Again!!!!",'red')
# validating input:: AGE and RATING,i.e.,
#Age b/w 12 and 50
#Rating b/w 0.0 to 5.0
#Friends Rating must be greater than or equal to User Rating
if new_friend.Rating <= 5.0 and new_friend.Age > 12 and new_friend.Age < 50 and new_friend.Rating>=spy.Rating:
# add_friend
friends.append(new_friend)
print colored("Friend Added",'green')
else:
print colored("Sorry invalid entry!!!!",'red')
# returning number of friends
return len(friends) |
import re
#
# Funcion para crear un objeto de tipo TimeCode a partir de un string ("08:37:45:17" o "08:37:45;17") y de un entero con el Frame Rate
#
# Emiliano A. Billi 2011
#
class TimeCodeError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class TimeCode(object):
def __init__(self):
self.frames = 0 # Frames desde cero del objeto TC
self.frameRate = 30 # FrameRate asociado al TC
def __add__(self, other):
if self.frameRate == other.frameRate:
frames = self.frames + other.frames
ret = TimeCode()
ret.frameRate = self.frameRate
ret.frames = frames
return ret
else:
raise TimeCodeError('FrameRate does not match')
def __sub__(self, other):
if self.frameRate == other.frameRate:
frames = self.frames - other.frames
ret = TimeCode()
ret.frameRate = self.frameRate
ret.frames = frames
return ret
else:
raise TimeCodeError('FrameRate does not match')
def __eq__(self, other):
if self.frameRate == other.frameRate:
if self.frames == other.frames:
return True
else:
return False
else:
raise TimeCodeError('FrameRate does not match')
def __ne__(self, other):
if self.frameRate == other.frameRate:
if self.frames != other.frames:
return True
else:
return False
else:
raise TimeCodeError('FrameRate does not match')
def __lt__(self, other):
if self.frameRate == other.frameRate:
if self.frames < other.frames:
return True
else:
return False
else:
raise TimeCodeError('FrameRate does not match')
def __le__(self, other):
if self.frameRate == other.frameRate:
if self.frames <= other.frames:
return True
else:
return False
else:
raise TimeCodeError('FrameRate does not match')
def __ge__(self, other):
if self.frameRate == other.frameRate:
if self.frames >= other.frames:
return True
else:
return False
else:
raise TimeCodeError('FrameRate does not match')
def __gt__(self, other):
if self.frameRate == other.frameRate:
if self.frames > other.frames:
return True
else:
return False
else:
raise TimeCodeError('FrameRate does not match')
def __str__(self):
if self.frameRate == 29.97:
hh, ff = divmod(self.frames, 107892)
mm = int((self.frames + (2 * int(ff / 1800)) - (2 * (int(ff / 18000))) - (107892 * hh)) / 1800)
ss = int((self.frames - (1798 * mm) - (2 * int(mm / 10)) - (107892 * hh)) / 30)
ff = int(self.frames - (30 * ss) - (1798 * mm) - (2 * int(mm / 10)) - (107892 * hh))
lastcolon = ';'
elif self.frameRate == 30:
ss, ff = divmod( int(self.frames), int(self.frameRate) )
mm, ss = divmod( ss, 60 )
hh, mm = divmod( mm, 60 )
lastcolon = ':'
else:
pass
hhstr = str(hh) if hh > 9 else '0' + str(hh)
mmstr = str(mm) if mm > 9 else '0' + str(mm)
ssstr = str(ss) if ss > 9 else '0' + str(ss)
ffstr = str(ff) if ff > 9 else '0' + str(ff)
return ('%s:%s:%s%s%s' % (hhstr,mmstr,ssstr,lastcolon,ffstr))
def splitedvalues(self):
if self.frameRate == 29.97:
hh, ff = divmod(self.frames, 107892)
mm = int((self.frames + (2 * int(ff / 1800)) - (2 * (int(ff / 18000))) - (107892 * hh)) / 1800)
ss = int((self.frames - (1798 * mm) - (2 * int(mm / 10)) - (107892 * hh)) / 30)
ff = int(self.frames - (30 * ss) - (1798 * mm) - (2 * int(mm / 10)) - (107892 * hh))
lastcolon = ';'
elif self.frameRate == 30:
ss, ff = divmod( int(self.frames), int(self.frameRate) )
mm, ss = divmod( ss, 60 )
hh, mm = divmod( mm, 60 )
lastcolon = ':'
else:
pass
return hh,mm,ss,ff,self.frameRate
def __repr__(self):
return str(self)
def msstring(self):
if self.frameRate == 29.97:
hh, ff = divmod(self.frames, 107892)
mm = int((self.frames + (2 * int(ff / 1800)) - (2 * (int(ff / 18000))) - (107892 * hh)) / 1800)
ss = int((self.frames - (1798 * mm) - (2 * int(mm / 10)) - (107892 * hh)) / 30)
ff = int(self.frames - (30 * ss) - (1798 * mm) - (2 * int(mm / 10)) - (107892 * hh))
elif self.frameRate == 30:
ss, ff = divmod( int(self.frames), int(self.frameRate) )
mm, ss = divmod( ss, 60 )
hh, mm = divmod( mm, 60 )
else:
pass
lastcolon = ','
hhstr = str(hh) if hh > 9 else '0' + str(hh)
mmstr = str(mm) if mm > 9 else '0' + str(mm)
ssstr = str(ss) if ss > 9 else '0' + str(ss)
ffstr = str(int (( ff * 1000) / 30))
return ('%s:%s:%s%s%s' % (hhstr,mmstr,ssstr,lastcolon,ffstr))
def fromSplitedValues(hh,mm,ss,ff, frameRate):
if frameRate == 29.97:
totalMinutes = 60 * int(hh) + int(mm)
totalFrames = 108000 * int(hh) + 1800 * int(mm) + 30 * int(ss) + int(ff) - 2 * (totalMinutes - int(totalMinutes / 10))
elif frameRate == 30:
totalSeconds = (int(hh) * 3600) + (int(mm) * 60) + int(ss)
totalFrames = (totalSeconds * frameRate) + int(ff)
else:
raise TimeCodeError('Invalid Frame Rate')
timecode = TimeCode()
timecode.frames = totalFrames
timecode.frameRate = frameRate
return timecode
def fromString(string):
if re.search(";", string):
frameRate = 29.97
string = re.sub(";", ":", string)
else:
frameRate = 30
tc = re.match("([0-9][0-9]):([0-5][0-9]):([0-5][0-9]):([0-2][0-9])", string)
if tc:
hh = tc.group(1)
mm = tc.group(2)
ss = tc.group(3)
ff = tc.group(4)
return fromSplitedValues(hh,mm,ss,ff,frameRate)
|
# -#- coding: utf-8 -*-
#sys是一个包,argv是这个包中的一个模块
from sys import argv
script,filename = argv
#使用open函数可以找到文件,并返回一个file对象给txt变量
txt = open(filename)
print "Here's your file %r:" % filename
#file.read([size])函数是读取文件内容,如果不写size,则一直读到文件末尾(EOF),否则读入size字节的内容
#file对象调用read函数后文件指针不会回溯到文件头
print txt.read()
#读完文件就关闭文件对象是个好习惯
txt.close()
#python不会限制同一个文件被多次打开
txt2 = open(filename)
print txt2.read()
txt2.close()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt_again.close() |
import math
def olympic_ring(string):
li='ADOPQRabdegopq'
count=0
for x in string:
if x in li:
count=count+1
elif x=='B':
count=count+2
count=math.floor(count/2)
if count<2:
return 'Not even a medal!'
elif count==2:
return 'Bronze!'
elif count==3:
return 'Silver!'
else:
return 'Gold!'
|
def find_outlier(integers):
index=[]
for i in range(len(integers)):
index.append((integers[i])%2)
if (sum(index))==1:
return(integers[(index.index(1))])
return(integers[(index.index(0))])
|
def countBits(n):
bitstring = ""
n=int(n)
bit=0
ans=0
while n>0:
bit=int(n%2)
quotient=int(n/2)
bitstring=str(bit)+bitstring
n=quotient
for i in range(len(bitstring)):
ans=ans+int(bitstring[i])
return(ans)
|
def is_divisible(n,x,y):
if n%x==n%y==0:
return True
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.