text stringlengths 37 1.41M |
|---|
import itertools
from heapq import heapify, heappush, heappop
# A priority queue implementation based on standard library heapq
# module. Taken from https://docs.python.org/2/library/heapq.html, but
# encapsulated in a class. Also iterable, printable, and len-able.
# TODO some extra capabilities that would be nice: check for empty, peek.
class PriorityQueue:
REMOVED = '<removed-task>' # placeholder for a removed task
def __init__(self, tasks_prios=None):
self.pq = []
self.entry_finder = {} # mapping of tasks to entries
self.counter = itertools.count() # unique sequence count -- tie-breaker when prios equal
if tasks_prios:
for task, prio in tasks_prios:
self.add_task(task, prio) # would be nice to use heapify here instead
def __iter__(self):
return ((task, prio) for (prio, count, task) in self.pq if task is not self.REMOVED)
def __len__(self):
return len(list(self.__iter__()))
def __str__(self):
return str(list(self.__iter__()))
def add_task(self, task, priority=0):
'Add a new task or update the priority of an existing task'
if task in self.entry_finder:
self.remove_task(task)
count = next(self.counter)
entry = [priority, count, task]
self.entry_finder[task] = entry
heappush(self.pq, entry)
def remove_task(self, task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = self.entry_finder.pop(task)
entry[-1] = self.REMOVED
def pop_task(self):
'Remove and return the lowest priority task. Raise KeyError if empty.'
while self.pq:
priority, count, task = heappop(self.pq)
if task is not self.REMOVED:
del self.entry_finder[task]
return task, priority # NB a change from the original: we return prio as well
raise KeyError('pop from an empty priority queue')
if __name__ == "__main__":
pq = PriorityQueue((('a', 30), ('b', 31), ('d', 10)))
pq.add_task('a', 17)
pq.add_task('b', 19)
pq.add_task('c', 5)
pq.add_task('b', 3)
print(pq.pop_task())
pq.remove_task('c')
print(pq.pop_task())
|
class Aditya:
def __init__(self, L = "Aditya"):
self.__lst = L
class __makeIter:
def __init__(self, L = "Aditya"):
self.__idx = 0
self.__L = L
def __next__(self):
if self.__idx >= len(self.__L):
raise StopIteration
else:
self.__idx += 1
return self.__L[self.__idx-1]
def __iter__(self):
return self.__makeIter(self.__lst)
Arshad = Aditya("Darien Are Not Not")
Max = "Rory and "
for Noah in Arshad:
Max += Noah
Rachit = Max
print(Rachit)
class TreeNode:
def __init__(self,val,parent=None):
self.height = 1
self.val = val
self.parent = parent
self.leftChild = None
self.rightChild = None
self.height1 = 1
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
class PQ:
def add(self,val):
raise NotImplemented
def peekMin(self):
raise NotImplemented
def getMin(self):
raise NotImplemented
def __len__(self):
raise NotImplemented
class ListPQ(PQ):
def __init__(self):
self.items = []
def __len__(self):
return len(self.items)
def add(self, val):
self.items.append(val)
def peekMin(self):
return self.getMin(False)
def getMin(self, toRemove=True):
if (self.items == []):
return None
minIdx = 0
sz = len(self.items)
for idx in range(sz):
if priority(self.items[idx]) < priority(self.items[minIdx]):
minIdx = idx
minItem = self.items[minIdx]
if toRemove:
del self.items[minIdx]
return minItem
def draw(self):
print(self.items)
class BalancedBST(BST):
def add(self,val): ## TO IMPLEMENT
self.draw()
return newNode
def draw(self):
drawTree(self.root, 0, True)
class Simulator:
def __init__ (self, newPQ, isLoud=True):
self.pq = newPQ
self.limit = -1
self.clock = 0
self.log = None
self.addTime = 0
self.getTime = 0
self.isLoud = isLoud
def setLimit(self, num):
self.limit = num
def useLog(self, log):
self.log = log
def _getNextEvent(self):
self.clock += 1 # timestamps start at 1 and go up
if self.log:
idx = self.clock - 1
if idx >= len(self.log):
return None
line = self.log[self.clock -1 ]
#print ("found line", line)
if line[0] == 'g':
return ()
else:
nums = line[2:-1].split(',')
return (int(nums[0]), int(nums[1]))
else: # either generate a new task or get existing task to process
num = random.randint(1,22)
isNew = (num % 7 < 4) # 4/7 of the time we have new task
if isNew:
return (num, self.clock)
else:
return ()
def run(self):
if self.isLoud:
print("Simulation starting, PQ is ", type(self.pq), ", using log:", bool(self.log), ", limit is", self.limit)
log = []
while (self.limit == -1 or self.clock < self.limit):
val = self._getNextEvent()
if val == None:
break
elif len(val) > 0: # a new task has been generated for processing
if self.isLoud:
print("New task", val, "has been generated")
startTime = time.time()
self.pq.add(val)
endTime = time.time()
log.append("n" + str(val))
self.addTime += endTime - startTime
else:
startTime = time.time()
val = self.pq.getMin() # system is ready to process next task
endTime = time.time()
if self.isLoud:
print(val, "is being processed next")
log.append("g" + str(val))
self.getTime += endTime - startTime
if self.isLoud:
self.pq.draw()
print("Simulation finished,", type(self.pq), "has size", len(self.pq))
return log
## Part 1
def priority(val):
## Write your code here
def drawTree(node, indent=0, showHeight=False):
if node == None:
return
drawTree(node.rightChild, indent+1, showHeight)
if node.rightChild:
print(" " * indent, " / ")
if showHeight:
print(" " * indent, node.val, ", height", node.height1)
else:
print(" " * indent, node.val)
if node.leftChild:
print(" " * indent, " \ ")
drawTree(node.leftChild, indent+1, showHeight) |
class BinaryTree:
def __init__(self,data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def getCode(self, char):
if self.left == None and self.right == None:
if self.data == char:
return ""
else:
return None
if self.left != None:
LT = self.left.getCode(char)
if LT != None:
return "0" + LT
if self.right != None:
RT = self.right.getCode(char)
if RT != None:
return "1" + RT
t1 = BinaryTree('', BinaryTree('D'), BinaryTree('R'))
t1 = BinaryTree('', t1, BinaryTree('$'))
t2 = BinaryTree('', BinaryTree('A'), BinaryTree('B'))
t = BinaryTree('', t1, t2)
print(t.getCode('R'))
#
#
#
class LL:
class Node:
def __init__(self, value, link = None):
self.value = value
self.link = link
def __init__(self):
self.head = None
self.tail = None
self.numNodes = 0
def addFirst(self, value):
if self.numNodes == 0:
newNode = LL.Node(value, self.head)
self.head = newNode
self.tail = newNode
self.numNodes += 1
else:
newNode = LL.Node(value, self.head)
self.head = newNode
self.numNodes += 1
def addLast(self, value):
if self.numNodes == 0:
self.addFirst(value)
else:
newNode = LL.Node(value, self.head)
currNode = self.tail
currNode.link = newNode
self.tail = newNode
self.numNodes += 1
def addAt(self, value, index):
if index == 0:
self.addFirst(value)
elif index == self.numNodes:
self.addLast(value)
else:
counter = 0
place = self.head
while counter < index - 1:
place = place.link
counter += 1
oldNode = place.link
newNode = LL.Node(value, oldNode)
place.link = newNode
self.numNodes += 1
def removeFirst(self):
self.head = self.head.link
self.numNodes -= 1
def removeLast(self):
curObj = self.head
counter = 0
while counter < self.numNodes - 1:
counter += 1
curObj = curObj.link
self.tail = curObj
curObj.link = None
self.numNodes -= 1
def removeAt(self, index):
if index == 0:
self.removeFirst()
elif index == self.numNodes:
self.removeLast()
else:
counter = 0
place = self.head
while counter < index - 1:
place = place.link
counter += 1
self.tail = place
place.link = None
self.numNodes -= 1
def __len__(self):
return self.numNodes
def __getitem__(self, index):
if index >= self.numNodes:
raise Exception("Index out of bouds")
curObj = self.head
counter = 0
while counter < self.numNodes:
if counter == index:
return curObj.value
counter += 1
curObj = curObj.link
def __setitem__(self, index, value):
if index >= self.numNodes:
raise Exception("Index out of bouds")
curObj = self.head
counter = 0
while counter < self.numNodes:
if counter == index:
curObj.value = value
break
counter += 1
curObj = curObj.link
def __str__(self):
output = "["
curObj = self.head
counter = 0
while counter < self.numNodes:
output += str(curObj.value) + ", "
counter += 1
curObj = curObj.link
output = output[:len(output)-2]
output += "]"
return output
def __contains__(self, value):
curObj = self.head
counter = 0
while counter < self.numNodes:
if curObj.value == value:
return True
counter += 1
curObj = curObj.link
return False
#
#
#x = LL()
#x.addFirst(9)
#x.addFirst(324)
#x.removeLast()
#x.addFirst(3)
#x.addFirst(3)
#x.addFirst(3)
#print(x)
#print(x[1])
#x[1] = "sdasdasdasd"
#
#print(x)
#
#
class BinaryTree:
def __init__(self,data, left = None, right = None):
self.data = data
self.leftChild = left
self.rightChild = right
def postOrder(self):
if self.leftChild != None:
self.leftChild.postOrder()
if self.rightChild != None:
self.rightChild.postOrder()
print(self.data, end=" ")
bt1 = BinaryTree(8, BinaryTree(5), BinaryTree(3))
bt2 = BinaryTree(3, BinaryTree(9), BinaryTree(1))
bt = BinaryTree(7, bt1, bt2)
bt.postOrder()
|
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
def encode_string(codestring, plaintext):
encodedStr = ""
plaintext = plaintext.upper()
for x in plaintext:
if x == " ":
encodedStr += "-"
elif (x in alphabet) == False:
encodedStr += x
else:
encodedStr += codestring[alphabet.index(x)]
return encodedStr
def decode_string(codestring, ciphertext):
decodedStr = ""
ciphertext = ciphertext.upper()
for x in ciphertext:
if x == "-":
decodedStr += " "
elif (x in alphabet) == False:
decodedStr += x
else:
decodedStr += alphabet[codestring.index(x)]
return decodedStr
def create_elist(codestring):
e_list = []
for x in codestring:
e_list.append(x)
return e_list
def create_dlist(codestring):
d_list = []
for x in alphabet:
for elemnet in codestring:
if elemnet == x:
d_list.append(alphabet[codestring.index(elemnet)])
return d_list
def encode_list(e_list, plaintext):
lst = []
plaintext = plaintext.upper()
for x in plaintext:
if x == " ":
lst.append("-")
elif (x in alphabet) == False:
lst.append(x)
else:
lst.append(e_list[alphabet.index(x)])
str = "".join(lst)
return str
def decode_list(d_list, ciphertext):
lst = []
ciphertext = ciphertext.upper()
for x in ciphertext:
if x == "-":
lst.append(" ")
elif (x in alphabet) == False:
lst.append(x)
else:
lst.append(d_list[alphabet.index(x)])
str = "".join(lst)
return str
def create_edict(codestring):
keys = list(alphabet)
values = list(codestring)
e_dict = {k:v for (k,v) in zip(keys, values)}
return e_dict
def create_ddict(codestring):
keys = list(alphabet)
values = list(codestring)
d_dict = {k:v for (k,v) in zip(values, keys)}
return d_dict
def encode_dictionary(e_dict, plaintext):
word = []
plaintext = plaintext.upper()
for x in plaintext:
if x == " ":
word.append("-")
elif (x in alphabet) == False:
word.append(x)
else:
word.append(e_dict[x])
str = "".join(word)
return str
def decode_dictionary(d_dict, ciphertext):
word = []
ciphertext = ciphertext.upper()
for x in ciphertext:
if x == "-":
word.append(" ")
elif (x in alphabet) == False:
word.append(x)
else:
word.append(d_dict[x])
str = "".join(word)
return str |
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.index = 0
self.queue = []
def append(self, item):
# if the queue is smaller than capacity (5 in this)
if len(self.queue) < self.capacity:
# add the item to the back
self.queue.append(item)
else:
# replace oldest value; self.queue[0] = first in queue
self.queue[self.index] = item
# Increment the index for added item(s)
self.index += 1
# If index is equal to capacity
if self.index == self.capacity:
# Reset the index
self.index = 0
def get(self):
# return all elements in given order
return self.queue |
import random
class User:
"""
Class that generates new users
"""
user_list = []
def __init__(self, username, password):
"""
the__init__ method define properties for the object
"""
self.username = username
self.password = password
def save_user(self):
"""
save_user method saves user objects into the user_list
"""
User.user_list.append(self)
def delete_user(self):
"""
delete_user method deletes a user from the user_list
"""
User.user_list.remove(self)
@classmethod
def display_users(cls):
"""
Method returning user list
"""
return cls.user_list
|
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """
divisible = False
num = 2520
while divisible == False:
divisible = True
for i in range(20, 1, -1):
if num%i != 0:
divisible = False
break
if divisible == True:
print(num)
break
else:
num += 20
|
# 3)For “Fare” columns in Titanic data find
# a) maximum, minimum
# b) mean
# c) mode
# d) median
# and
# f) Draw the graph boxplot
#********************************************
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
#from scipy import stats
plt.style.use("ggplot")
import warnings
warnings.filterwarnings("ignore")
data = pd.read_csv("titanic.csv")
min_fare = np.amin(data["Fare"])
print(f"min Fare: {min_fare}")
max_fare = np.amax(data["Fare"])
print(f"max Fare: {max_fare}")
mean_fare = np.mean(data["Fare"])
print(f"mean Fare: {mean_fare}")
mode_fare = stats.mode(data["Fare"])
print(f"mode Fare: {mode_fare}")
data["Fare"].fillna(0,inplace=True) #datanan 'nan' ları çıkardık
median_fare = np.median(data["Fare"])
print(f"median Fare: {median_fare}")
data.head()
boxplot=data.boxplot(column =['Fare'])
boxplot.plot()
plt.show()
#***********************************************
# HW 2.Figure |
import sys
primeCache = {}
def isPrime(n):
if n in primeCache:
return primeCache[n]
else:
primeCache[n] = isPrimeCalc(n)
return primeCache[n]
def isPrimeCalc(n):
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
candidateDivisor1 = 5
candidateDivisor2 = 7
while candidateDivisor1 * candidateDivisor1 <= n:
if n % candidateDivisor1 == 0:
return False
if n % candidateDivisor2 == 0:
return False
candidateDivisor1 += 6
candidateDivisor2 += 6
return True
c = int(sys.argv[1])
maxPrimeStreak = 0
if c % 2 == 1:
c -= 1
for a in range(-c+1, c, 2):
for b in range(max(-c+1, -a, maxPrimeStreak + a), c, 2):
if not isPrime(b):
continue
n = 0
while isPrime(n*n + a*n + b):
n += 1
if n > maxPrimeStreak:
coefficients = [a,b]
maxPrimeStreak = n
print([maxPrimeStreak,coefficients]) |
# Method1: use convergence recurrence and e's pcf to get 100th and then sum numerator
import sys
def getPCFe(k):
if k % 3 != 2:
return 1
else:
return 2 * (k+1) // 3
def getConvergentNumerator(k):
aPenult = 1
aUlt = 2
for k in range(1, k):
aNew = getPCFe(k) * aUlt + aPenult
aPenult = aUlt
aUlt = aNew
return aUlt
def sumDigits(n):
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
print(sumDigits(getConvergentNumerator(int(sys.argv[1]))))
|
def digitSum(n):
return sum(map(int,list(str(n))))
greatest = 0
for a in range(1, 100):
num = 1
for b in range(1, 100):
num *= a
greatest = max(greatest, digitSum(num))
print(greatest) |
Nombre = input("gregar nombre")
Apellido = input("agregar apellido")
Ubicacion = input("agregar ubicacion")
Edad =input ("agregar edad")
edad =input ("agregar edad")
if edad >= "18":
print("mayor de edad")
else:
print ("menor de edad")
print("hola te llamas",Nombre,"tu apellido es",Apellido,"estas ubicado en",Ubicacion,"tienes la edad de",Edad,"y ademas eres mayor de edad",)
|
import sys
import re
import os
import argparse
defines = [] # Stores all the constants have been defined
# Pattern that finds magic numbers
pattern = "(?<![a-zA-Z_])([-+]?\d*\.\d+|\d+)(?![a-zA-Z_])"
script_path = os.path.abspath(__file__)
script_dir = os.path.split(script_path)[0]
def firstPass(file):
"""
Passes over the file to store any constants that are defined.
This does not take into consideration local constants. They will be considered
global.
All constants are stored in the list ''defines'' as tuples. Each tuple has two elements:
the first element is the name of the constant, the second is the value of the constant.
Args:
file (str) the filename of the file we want to process.
"""
del defines[:]
for line in file:
line = line.strip()
words = line.split()
if len(words) > 0:
if words[0].lower() == "#define":
defTuple = (words[1], words[2])
defines.append(defTuple)
def find_all_header_files(file):
"""
Given a source file, the function will loop through all the lines in the file
and store all header files. It is assumed that the file is already open.
Args:
file (str) the filename of the file that contains header files
Return:
List (str) for all the header files found in the input file
"""
header_files = []
file.seek(0, 0)
for line in file:
line = line.strip()
tokens = line.split()
if len(tokens) > 0:
if tokens[0].strip().lower() == "#include" and tokens[1][0] == "\"" :
header_files.append(tokens[1][1:-1])
return header_files
def process(file, args):
"""
Reads input file line by line to check if there are numbers in the line.
The function does not assume that the file is already open.
Args:
file (str) path/filename for the input file
args (ArgumentParser) that contains all user-specified flags
"""
print ("===========", file, "===========")
lineNum = 1
for line in file:
line = line.rstrip()
find_magic_number_in_line(line, lineNum, args)
lineNum += 1
print()
def isConstant(string):
"""
Checks if a string declares a constant. It is assumed that the first token in the string
is ''#define''.
Args:
string (str) a string that we want to check if is a define statement
Return:
True (boolean) when the string starts with ''#define''
False (boolean) when the string does not start with ''#define''
"""
tokens = string.strip().split()
if len(tokens) > 0 and tokens[0].lower() == "#define":
return True
else:
return False
def removeAllValidValues(list):
"""
Removes all occurences of ''0'', ''1'', and ''0'' ''1.0'' in ''list''.
It is assumes that the list stores the numbers as strings.
Args:
list (str[]) a list of numbers
"""
while "0" in list:
list.remove("0")
while "1" in list:
list.remove("1")
while "1.0" in list:
list.remove("1.0")
while "0.0" in list:
list.remove("0.0")
def find_magic_number_in_line(line, lineNum, args):
"""
Given an input string the function will check if it contains any numbers.
If any other numbers than 0 and 1 occur, the linenumber, the line itself
and the magic number will be printed. The function will suggest possible replacements
for the magic number, if one has been defined.
Args:
line (str) a string containing a line from the input file
lineNum (int) the linenumber of the line
args (ArgumentParser) that contains all user-specified flags
"""
matches = re.findall(pattern, line)
if matches and not isConstant(line):
removeAllValidValues(matches)
for num in matches:
if args["print"]:
print(str(lineNum) + ":\t\"", line.strip(), "\", ", num)
else:
print(str(lineNum) + ":\t", num)
if args["suggestions"] == True:
for const in defines:
if num in const:
print( "\tConsider replacing with ", const[0])
def is_file_extension_valid(filename):
"""
Checks if a filename is of a valid type. At the time of writing only ''.c'' files
are supported. The function only checks the file extension to see if it is valid.
Args:
filename (str) the path/filename of the inputted file.
Return:
True (boolean) when the file suffix (read: file type) is supported
False (boolean) when the file suffix (read: file type) is not supported
"""
ret = False;
name, extension = os.path.splitext(filename)
if extension.lower() == ".c": #or extension.lower() == ".txt"):
ret = True
elif extension.lower() == ".h":
ret = True
else:
ret = False
return ret
def find_magic_number_in_file(filename, args):
"""
Determines all the constants before checking if magic numbers exist in
the file.
Args:
filename (str) the path/filename of the file
args (ArgumentParser) that contains all user-specified flags
"""
file = open(filename)
if args["suggestions"] == True:
firstPass(file)
file.seek(0, 0)
process(file, args)
file.close()
def find_magic_numbers_recursively(rootDir, args):
"""
Processes all files in the current directory and all sub-directories.
Args:
rootDir (str) the path to the root of the directory we want to process
args (ArgumentParser) that contains all user-specified flags
"""
print(rootDir)
find_magic_numbers_in_directory(rootDir)
dirs = [d for d in os.listdir(rootDir) if os.path.isdir(os.path.join(rootDir, d))]
for directory in dirs:
print("=== ", directory, " ===")
find_magic_numbers_recursively(os.path.join(rootDir, directory))
def find_magic_numbers_in_directory(directory, args):
"""
Finds all the magic numbers for all the source files in the ''directory''.
Args:
directory (str) path to the directory
args (ArgumentParser) that contains all user-specified flags
"""
for dirent in os.listdir(directory):
path = os.path.join(directory, dirent)
if os.path.isfile(path):
if is_file_extension_valid(dirent) == True:
find_magic_number_in_file(path, args)
def createArgParser():
"""
Creates and returns an argument parser for the program. All arugments are
added and helper strings are provided.
"""
parser = argparse.ArgumentParser(description="Find magic numbers in CLANG files.")
# parser.add_argument("-t", "--test", required=False, action="store_true")
parser.add_argument("-r", "--recursively",
help = "Recursively search any sub-directories", required = False, action = "store_true")
parser.add_argument("dirent", help = "File or directory to be searched")
parser.add_argument("-p", "--print",
help = "Print the line where a magic number occurs", required = False, action = "store_true")
parser.add_argument("-s", "--suggestions",
help = "Pre-processes the file(s) to suggest replacing magic numbers with any constants",
required = False, action = "store_true")
parser.add_argument("-d", "--derive",
help = "Derive constants from include statements in the source files",
required = False, action = "store_true")
return parser
def find_magic_numbers_in_file_derive_constants(path, args):
"""
Takes a file and finds all maigc numbers in it. Based on the header files
specified in the source file, all constants are defined. When all constants
have been defined all magic numbers will be found.
Args:
path (str) to the source file
args (ArgumentParser) that contains all user-specified flags
"""
directory = os.path.split(path)[0]
file = open(os.path.join(script_dir, path))
headers = find_all_header_files(file)
for s in headers:
full_path = os.path.join(directory, s)
with open(full_path) as header_file:
store_all_constants(header_file)
file.seek(0, 0)
process(file, args)
file.close()
del defines[:]
def store_all_constants(file):
"""
Finds and stores all constants - all non-zero and non-one values - that are
defined in ''file''. All constants are stored in the global ''defines''.
Args:
file (momdule) The open header file
"""
for line in file:
line = line.strip()
words = line.split()
if len(words) > 0:
if words[0].lower() == "#define":
defTuple = (words[1], words[2])
if defTuple not in defines:
defines.append(defTuple)
def find_magic_numbers_in_directory_derive_constants(directory, args):
"""
Finds all magic numbers in the source files stored in ''directory''.
Args:
directory (str) path to directory containing source files
args (ArgumentParser) that contains all user-specified flags
"""
for dirent in os.listdir(directory):
if os.path.isfile(os.path.join(directory, dirent)):
filename, extension = os.path.splitext(dirent)
if extension.lower() == ".c":
find_magic_numbers_in_file_derive_constants(os.path.join(directory, dirent), args)
def main():
parser = createArgParser()
args = vars(parser.parse_args())
if args["derive"]:
if os.path.isfile(args["dirent"]):
find_magic_numbers_in_file_derive_constants(args["dirent"], args)
else:
find_magic_numbers_in_directory_derive_constants(args["dirent"], args)
elif args["recursively"] == True:
find_magic_numbers_recursively(args["dirent"], args)
else:
if os.path.isfile(args["dirent"]):
find_magic_number_in_file(args["dirent"], args)
else:
find_magic_numbers_in_directory(args["dirent"], args)
if __name__ == "__main__":
main() |
x = 2.3
y = 3.1
z = 1.6
mew = (x*x)+(y*y)+(z*z)
print("x = "+str(x))
print("y = "+str(y))
print("z = "+str(z))
print("(x*x)+(y*y)+(z*z) = "+str(round(mew)))
print("สมการ x²+y²+z² = "+str(round(mew)))
|
x = input('Number:')
if int(x) < 0:
print("positive")
elif int(x) == 0:
print("zero")
else :print("negative") |
import random
y = random.randrange(10)
z = 0
while z <= 2:
x = input('Number:')
if int(x) == y:
print("!!!!!!!!!YOU WINNNN!!!!!!!!!!!")
break
elif int(x) > y:
if z==2:
print("GAME OVER"+" random = "+str(y))
break
else :print("too big")
elif int(x) < y:
if z==2:
print("GAME OVER"+" random = "+str(y))
break
else :print("too small")
if z==2:
print("GAME OVER"+" random = "+str(y))
break
z += 1
|
# This is the original version of the project. For the more modern lesson version, see "learn it">final.py
import os
import random
import time
import platform
version = "0.6"
lb = "-----------------------------------------------------------------------------"
def lbl():
print(lb)
def br():
print(" ")
def wait_note(number):
print("NOTE: Game will continue in " + str(number) + " seconds")
time.sleep(number)
def header():
print(" _____ _____ _____ _____ _____")
print(" ___|\ \ ___|\ \ |\ \ / /| ___|\ \ ")
print("| |\ \ | |\ \ | \ \ / / | / /\ \ ")
print("| | | || | | || \____\/ / /| | |____|")
print("| |/____/ | |/____/| \ | / / / | | ____")
print("| |\ \ | || || \|___/ / / | | | |")
print("| | | || ||____|/ / / / | | |_, |")
print("|____| |____||____| /____/ / |\ ___\___/ /|")
print("| | | || | |` | / | | /____ / |")
print("|____| |____||____| |_____|/ \|___| | /")
print(" \( )/ \( )/ \( |____|/ ")
def clear_screen():
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def intro():
clear_screen()
header()
print("Welcome to RPyG version " + version + "!")
print(lb)
print("In this text based game, your goal is to survive as many consecutive battles in a row as possible.")
print("In the next step, you will create your character by selecting your class, a specialty, and name your character.")
print(lb)
print("Keep in mind: This game is meant to be played in single sittings and as such you cannot save.")
lbl()
input("Press enter to continue...")
print("NOTE")
app_main()
def app_main():
clear_screen()
header()
print(lb)
print("First, let's pick a class.")
print("1. warrior. Balance between attack rating and defense rating. Good health.")
print("2. wizard. A strong magical class with insane power but terrible defenses.")
print("3. falanx. A heavily armored defender class with massive defense but mediocre offense.")
class_input = input("Class choice: ")
print(lb)
if class_input == "warrior" or class_input == "wizard" or class_input == "falanx" or class_input == "1" or class_input == "2" or class_input == "3":
print("Welcome, mighty " + class_input + "!")
class_stats(class_input)
elif class_input == "exit":
exit()
clear_screen()
elif class_input == "dm":
print("Dev skip started.")
input("Press enter to begin.")
global health, defense, strength
strength = 15
defense = 15
health = 15
current_health = health
special_select()
else:
print("Please type one of the following: warrior, wizard, falanx.")
app_main()
strength = 0
defense = 0
health = 0
current_health = 0
specialty = 0
name = "null"
victory_count = 0
enemy_strength = 0
enemy_defense = 0
enemy_health = 0
enemy_current_health = 0
enemy_name = "null"
def class_stats(class_choice):
global current_health, health, strength, defense
header()
print("Note: stats are randomly generated based on your class choice.")
print(lb)
if class_choice == "warrior" or class_choice == "1":
strength = random.randint(2,5)
defense = random.randint(2,5)
health = random.randint(20,30)
current_health = health
print("You, fine warrior have: " + str(strength) + " attack. " + str(defense) + " defense. " + str(health) + " health.")
elif class_choice == "wizard" or class_choice == "2":
strength = random.randint(5,15)
defense = random.randint(0,3)
health = random.randint(5,20)
current_health = health
print("You, fine warrior have: " + str(strength) + " attack. " + str(defense) + " defense. " + str(health) + " health.")
elif class_choice == "falanx" or class_choice == "3":
strength = random.randint(1,5)
defense = random.randint(5,15)
health = random.randint(1,40)
current_health = health
print("You, fine warrior have: " + str(strength) + " attack. " + str(defense) + " defense. " + str(health) + " health.")
special_select()
def special_select():
global specialty, health, strength, defense
clear_screen()
header()
lbl()
print("Next, let's select a specialty.")
lbl()
print("1. medical knowledge. Add 5 to health")
print("2. berserker. Add 4 to attack")
print("3. technical. Permanently gain 4 extra defense")
lbl()
special_input = input("Specialty: ")
lbl()
if special_input == "1":
specialty = 1
health += 5
name_select()
elif special_input == "2":
specialty = 2
strength += 4
name_select()
elif special_input == "3":
specialty = 3
defense += 4
name_select()
elif special_select == "exit":
exit()
else:
clear_screen()
print("please select a specialty by typing the number of the specialty.")
special_select()
def name_select():
global name, strength, defense, health
clear_screen()
header()
print("Alright. What is your name fair adventurer?")
name = input("Name: ")
if name == "RPyG" or name == "rpyg":
# Damn I miss cheatcodes ;)
strength += 100
defense += 100
health += 500
elif name == "The Legend":
strength += 9999
elif name == "Tiny Tim":
strength = 0
defense = 0
health = 1
elif name == "JAM":
print("You cheeky bugger.")
exit()
elif name == "InFiNiTy":
print("Overkill enabled.")
strength = 9999999
defense = 9999999
health = 999999999
game_start()
def game_start():
clear_screen()
lbl()
print("Welcome to the arena! Here you will face enemy after enemy in deadly combat until you either run out of oponents, or die.")
print("Would you like to start with a warmup? (tutorial)")
lbl()
tutorial = input("Do a warmup?(y/n): ")
if tutorial == "y":
print("Alright, let's get you up to speed.")
tut()
else:
print("Straight into the thick of it eh? I like your style son. ")
battle_init()
def tut():
global enemy_current_health, enemy_health, enemy_defense, enemy_strength, enemy_name
print("Let's get to it then. For your warmup let's have a quick sparring match.")
time.sleep(5)
clear_screen()
lbl()
print("First let's explain how this works.")
lbl()
print("Attack rating: This is a measure of your ability to damage others.")
print("Defense rating: This is a measure of your ability to absorb damage.")
print("Health: This is how much damage you can take before death.")
lbl()
input("Press enter to continue...")
clear_screen()
lbl()
print("Attack and defense rating is randomly generated when you create your character. This number depends on your class and will be generated within a range.")
print("Health is also generated on character creation based on class.")
lbl()
print("After each win you obtain, you will be given the option to upgrade 1 of your stats by 1 point.")
print("Use your points wisely. Each victory you obtain will raise the difficulty of your enemies.")
lbl()
print("Alright, let's get into it kid.")
lbl()
input("Press enter to continue...")
clear_screen()
print("So first, let's basic combat. To begin with, you'll see 2 info bars. First is the enemies info. Second is yours.")
lbl()
print("Below the info bars, you'll find your available actions. Let's start easy.")
lbl()
input("Press enter to begin battle...")
clear_screen()
enemy_health = 20
enemy_current_health = enemy_health
enemy_strength = 1
enemy_defense = 3
enemy_name = "Sir Jacoby Brundlesworth III"
enemy_stats()
print("This is the standard battle UI for battle stats. Next, let's look at your battle options.")
input("Press enter to continue...")
clear_screen()
lbl()
print("What would you like to do?")
lbl()
print("attack")
print("block")
print("heal")
lbl()
print("As you can see, you have 3 options. Attack, Block, and Heal. ")
print("The attack option is as simple as it sounds. Attack your oponent.")
print("The block option is also simple. When blocking, you resist all damage but can't do anything else.")
print("The heal option will randomly heal between 0 and 10 health. Use it wisely as it will leave you open for attack.")
lbl()
print("Alright that's it for the basic tutorial. Let's get into some real combat, shall we? After sparring you'll be thrown right into the arena!")
input("Press enter to continue...")
clear_screen()
battle_handler()
def enemy_stats():
lbl()
print(enemy_name)
print("Attack: " + str(enemy_strength) + " | Defense: " + str(enemy_defense) + " | Health: " + str(enemy_current_health))
lbl()
print(name)
print("Attack: " + str(strength) + " | Defense: " + str(defense) + " | Health: " + str(current_health))
lbl()
def battle_options():
lbl()
print("What would you like to do?")
lbl()
print("1. attack")
print("2. block")
print("3. heal")
lbl()
choice = input("Choice: ")
if choice == "attack" or choice == "1":
return 1
elif choice == "block" or choice == "2":
return 2
elif choice == "heal" or choice == "3":
return 3
elif choice == "exit":
clear_screen()
exit()
def battle_init():
clear_screen()
global name, enemy_name, enemy_health, enemy_current_health, enemy_strength, enemy_defense, strength, defense, health, current_health
if victory_count > 0:
print("Congrats on your victory! It's time to select a stat to permanently increase...")
lbl()
print("1. Attack. Permanently raise attack by 1 point.")
print("2. Defense. Permanently raise defense by 1 point.")
print("3. Health. Permanently raise health by 2 points.")
lbl()
upgrade_choice = input("What is your choice: ")
if upgrade_choice == "1" or upgrade_choice == "attack":
strength += 1
print("Your attack is now " + str(strength))
input("Press enter to continue...")
elif upgrade_choice == "2" or upgrade_choice == "defense":
defense += 1
print ("Your defense is now " + str(defense))
input("Press enter to continue...")
elif upgrade_choice == "3" or upgrade_choice == "health":
health += 2
print ("Your standard health is now " + str(health))
input("Press enter to continue...")
elif upgrade_choice == exit:
exit()
else:
print("I didn't understand that input... Try again.")
input("Press enter to continue...")
clear_screen()
battle_init()
if victory_count%10 == 0 and victory_count != 0:
name_int = random.randint(0,(len(enemy_name_options) - 1))
name_int_2 = random.randint(0,(len(enemy_surname) - 1))
enemy_name = enemy_name_options[name_int] + " " + enemy_surname[name_int_2]
enemy_health = (random.randint(5,15) + (victory_count * 3))
enemy_current_health = enemy_health
enemy_strength = (random.randint(2,10) + (victory_count + 5))
enemy_defense = (random.randint(0,10) + (victory_count * 2))
current_health = health
clear_screen()
print("Your victory count is now: " + str(victory_count))
lbl()
print("And now for our next allstar match: " + name + " VS. " + enemy_name + " !")
lbl()
input("Press enter to begin battle...")
clear_screen()
battle_handler()
else:
name_int = random.randint(0,(len(enemy_name_options) - 1))
name_int_2 = random.randint(0,(len(enemy_surname) - 1))
enemy_name = enemy_name_options[name_int] + " " + enemy_surname[name_int_2]
enemy_health = (random.randint(5,15) + victory_count)
enemy_current_health = enemy_health
enemy_strength = (random.randint(2,10) + victory_count)
enemy_defense = (random.randint(0,10) + victory_count)
current_health = health
clear_screen()
print("Your victory count is now: " + str(victory_count))
lbl()
print("And for our next match: " + name + " VS. " + enemy_name + " !")
lbl()
input("Press enter to begin battle...")
clear_screen()
battle_handler()
def battle_handler():
global health, current_health, enemy_health, enemy_current_health, strength, enemy_strength, defense, enemy_defense, victory_count
enemy_stats()
br()
br()
br()
br()
br()
br()
br()
br()
choice = battle_options()
enemy_action = random.randint(1,3)
print(str(choice))
clear_screen()
random_attack_modifier_enemy = random.randint(round(enemy_strength / 2), round(enemy_strength * 2))
if choice == 1:
random_attack_modifier = random.randint(round(strength / 2), round(strength * 2))
if enemy_action != 2 and (random_attack_modifier - enemy_defense) > 0:
print(name + " attacks " + enemy_name + " for " + str(random_attack_modifier) + "-" + str(enemy_defense) + " damage. (" + str(random_attack_modifier - enemy_defense) + ")")
enemy_current_health = (enemy_current_health - (random_attack_modifier - enemy_defense))
if enemy_current_health < 1:
clear_screen()
lbl()
print("Enemy: " + enemy_name + " dies. R.I.P.")
print("Congratulations on your victory!")
input("Press enter to continue...")
victory_count += 1
lbl()
battle_init()
elif (strength - enemy_defense) < 0:
print(name + " attacks " + enemy_name + " but does no damage!")
else:
print(name + " attacks " + enemy_name + "but is blocked!")
elif choice == 2:
print("You raise your defenses.")
if enemy_action == 1:
print(enemy_name + " attacks but is blocked!")
elif enemy_action == 2:
print(enemy_name + " raises their defenses.")
elif choice == 3:
heal_amount = random.randint(0,10)
print(name + " heals for " + str(heal_amount) + " health.")
current_health += heal_amount
else:
print("Please select a correct option.")
battle_handler()
if enemy_action == 3:
heal_amount = random.randint(0,10)
print(enemy_name + " heals for " + str(heal_amount) + " health.")
enemy_current_health += heal_amount
elif enemy_action == 1 and choice != 2 and (random_attack_modifier_enemy - defense) > 0:
print(enemy_name + " attacks for " + str(random_attack_modifier_enemy) + " -" + str(defense) + "damage! (" + str(random_attack_modifier_enemy - defense) + ")")
current_health = (current_health - (random_attack_modifier_enemy - defense))
if current_health < 1:
clear_screen()
print(enemy_name + " kills " + name + ". R.I.P.")
print("Game over.")
time.sleep(5)
game_over()
elif (strength - enemy_defense) < 0:
print(name + " attacks " + enemy_name + " but does no damage!")
else:
print(enemy_name + " attacks but is blocked!")
battle_handler()
def game_over():
clear_screen()
new_game = input("Start a new game? y/n: ")
if new_game == "y":
clear_screen()
intro()
elif new_game == "n":
exit()
else:
game_over()
enemy_name_options = ["Bob", "Tim", "George", "Bigg", "Lil'", "The great", "Spid", "Kay", "Aaron", "Phillip", "Korrin", "David", "Kieran", "Cassandra", "Daniel", "Jesus", "Adam", "Jessica", "The great big", "Sir Benedict"]
enemy_surname = ["Kurpshank", "Smellwich", "Landar", "Dick", "Spork", "Kumkwat", "Beardsly", "The angry", "The depressed", "The violent", "McLeary", "Goth", "Jenkins", "Monarch of RPyG", "Jowels"]
intro()
|
def sort(arr):
swap = True
while swap:
swap = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
x= arr[i]
arr[i] = arr[i+1]
arr[i+1]=x
swap = True
arr = []
n = int(input("Elements : "))
for i in range(0, n):
ele = int(input())
arr.append(ele)
print(arr)
sort(arr)
print(arr)
|
# initialize 10 to the variable of types of people
types_of_people = 10
# initialize a string variable and insert the variable of types_of_people between the variable x
x = f"There are {types_of_people} types of people."
# initialize a string variable
binary = "binary"
# initialize a string variable
do_not = "don't"
# initialize a string variable and insert the variable of do_not and binary between the variable y
y = f"Those who know {binary} and those who {do_not}."
# print variable x
print(x)
# print variable y
print(y)
# print some texts and variable x together
print(f"I said: {x}")
# print some texts and variable y together
print(f"I also said: '{y}'")
# initialize a boolean variable
hilarious = False
# initialize a string variable with a space to insert a variable in
joke_evaluation = "Isn't that joke so funny?! {}"
# print the variable joke_evaluation and insert the variable hilarious in the variable space from joke_evaluation
print(joke_evaluation.format(hilarious))
# initialize a string variable
w = "This is the left side of..."
# initialize a string variable
e = "a string with a right side."
# print the variable w and e together by combining them
# by adding w and e, it makes a longer string because it combines them
print(w + e)
#sting put inside a string at line 4 10 16 18 |
# write functions with parameters
def add(a,b):
print("ADDING %d + %d" %(a,b))
return a+b
def subtract(a,b):
print("SUBTRACTING %d - %d"%(a,b))
return a-b
def multiply(a,b):
print("MULTIPLYING %d * %d"%(a,b))
return a*b
def divide(a,b):
print("DIVIDING %d / %d"%(a,b))
return a/b
print("Let's do some math with just functions!")
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print("Age: %d, Height: %d, Weight: %d, IQ: %d" %(age,height,weight,iq))
# A puzzle for the ectra credit, type it in anyway.
print("Here is a puzzle")
def formula(a,b,c,d):
return a+b-(c*d/2)*2
what = add(age,subtract(height,multiply(weight, divide(iq,2))))
a = formula(age, height,weight, iq)
print("studt drill 3: ", a)
print("That becomes: ", what, "Can you do it by hand?")
ans = 0
def simpleformula(a):
return a*10000000
print("study drill 4: ",simpleformula(simpleformula(simpleformula(simpleformula(ans))))) |
#!/usr/bin/env python3
my_set = set()
print(my_set)
print('ADD')
A = { 1, 2, 3 }
A.add(4)
print(A)
# UNION
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
print(A | B)
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
A.update(B)
print(A)
# INTERSECTION
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
print(A & B)
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
A.intersection_update(B)
print('intersection update')
print(A)
# DIFFERENCE
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
print(A - B)
print('Difference Inplace')
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
A.difference_update(B)
print(A)
print('Symmetric Difference')
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
C = A ^ B
print(C)
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
A.symmetric_difference_update(B)
print(A)
print('Subset')
A = { 1, 2 }
B = { 1, 2, 3, 4 }
print(A <= B)
A = { 1, 2 }
B = { 2, 3, 4 }
print(A <= B)
print('Superset')
A = { 1, 2, 3 }
B = { 1, 2 }
print(A >= B)
A = { 1, 2 }
B = { 2, 3, 4}
print(A >= B)
print('LACK OF ORDER')
A = { 2, 1, 3 }
for element in A:
print(element) |
for i in range(6):
print(i)
print(list(range(6)))
#name =input("please enter you name: ")
#print(name)
print(100*100)
print(r'\\\\')#表示" "内默认不进行转义
#表示多行
print('''line1
line2
line3''')
print(r'''hello\n \# 未进行转义
world''')#r" 内部未进行转义,表示\以后的转义无效
#bool运算符
age =19
if age >= 18:
print('adult')
else:
print('teenager')
Answer=True #bool类型
# /浮点数除法
# //地板除,整数的除法
# %取余数 10%3
print(10/3,10//3,10%3)
ord('A') #ord函数
print(ord("A"))
print(chr(65)) #chr函数
#
# 日期2021.1.23
x=b'ABC'
print(x)
print(len('中文'))#len 函数的使用
#数组
classmates=['Micheal','Bob','Tony'] #数组元素已经固定 0,1,2,list是一种有序集合,可以随意添加或者删除其中的元素
print(classmates)
print(len(classmates))
for i in range(3): # for循环
print(classmates[i])
#用索引来访问list中的元素的位置,索引从0开始,但是得确保索引不要越界,不然会报错
print(classmates[-1]) #-1直接访问数组的最后位置,以此类推,可以获取倒数第2个、倒数第3个:
classmates.append('Adma') #可以在list中追加元素在末尾
print(classmates)
print('####123')
print(classmates[3])
classmates.insert(1,'Jack')#也可以在list表中其他位置插入元素
print(classmates[1])
print('#####')
for j in range(5):
print(classmates[j],j)
classmates.pop() #在数组中删除元素,末尾的元素 ,Adma
classmates.pop(3)# 删除制定位置的元素,i为索引位置,Tony
print(classmates)
#2021.1.24
print('--------2021.1.24-------')
classmates[0]='YL'
print(classmates)
array=['YL',123,True] #list表中的数据类型也可以不同
array1=['a',['a','b'],'c'] #list表元素也可以是另外一个数组
print(len(array1))
print('----------------------')
p=['a','b']
g=['a','c',p,'d']
print(g[2][1])#获取p中的元素b,g可以看做是一个二维数组
L=[]
print(len(L)) #list表中没有元素的话,她的长度也为0,空的list
print('--------')
classmates=('Michael','Bob','YL') #另外的一种表,tuple(),一旦初始化就不能改变,不能修改,可以使用classmates(0),classmates(-1),但是不能修改值
print('tuple使代码更安全')
t=(1,2) #在定义tuple的时候就要把元素定下来
u=()# 定义空的tuple
v=(1,) #当定义一个元素的时候,加上一个',',消除歧义
t = ('a', 'b', ['A', 'B'])#tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的
t[2][0] = 'X'
t[2][1] = 'Y'
print(t)
print('---------分隔线---------')
#循环和判断,计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。
age=20
if age>18: #就把缩进的两行print语句执行了,否则,什么也不做
print('you age is',age)
print('adult')
else:
print('you age is',age)
print('teenager')
#age = 3 #当然上面的判断是很粗略的,完全可以用elif做更细致的判断,elif 是else if 的缩写
age = input()
age =int(age) #将输入的字符型转化为整型
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
names = ['Michael', 'Bob', 'Tracy']
for name in names: #name为在names中元素的名字
print(name)
print('---------------------分割线--------------------------')
sum=0
sums=[0,1,2,3,4,5,6,7,8,9]
for x in sums: #x为sums中的元素值
sum=sum+x #循环加
print(sum)
print('-----------------分割线----------------')
array=list(range(5)) #生产List表,range(5)就是生成0到4的整数序列
print(array)
sum=0
for x in range(1001):
sum=sum+x
print(sum)
#第二种循环,只要满足条件就可以,不断循环,当不满足条件时自动退出,100以内的奇数和
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
|
# You are given the following data for agents
# agent
# is_available
# available_since (the time since the agent is available)
# roles (a list of roles the user has, e.g. spanish speaker, sales, support etc.)
# When an issue comes in we need to present the issue to 1 or many agents based on an agent selection mode.
# An agent selection mode can be all available, least busy or random.
# In “all available mode” the issue is presented to all agents so they pick the issue if they want.
# In least busy the issue is presented to the agent that has been available for the longest.
# In random mode we randomly pick an agent. An issue also has one or many roles (sales/support e.g.).
# Issues are presented to agents only with matching roles.
# Please write a function that takes an input the list of agents with their data, agent selection mode and returns a list of agents the
# issue should be presented to.
from datetime import datetime
from random import choice
import pickle
class Agent:
def __init__(self, name, role, is_available, available_since):
self.name = name
self.role = role
self.is_available = is_available
self.available_since = available_since
@classmethod
def add_agents(cls):
agent_name = str(input("Agent Name : "))
agent_role = str(input("Agent Role : "))
agent_is_available = int(input(
"Select Agent is Available : \n\tPress 1 for Agent is available, \n\tPress 2 for Agent is not available\n"))
if agent_is_available == 1:
agent_is_available = True
elif agent_is_available == 2:
agent_is_available = False
else:
print("please choose correct option")
if agent_is_available == True:
agent_available_since = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
elif agent_is_available == False:
agent_available_since = "Agent is not available"
agent = Agent(name=agent_name, role=agent_role,
is_available=agent_is_available, available_since=agent_available_since)
return agent
class Issue:
def __init__(self, selection_mode, role, is_selected, selected_by):
self.selection_mode = selection_mode
self.role = role
self.is_selected = is_selected
self.selected_by = selected_by
@classmethod
def add_issue(cls):
agent_selection_mode = int(input(
"Agent Selection mode : \n\tPress 1 for 'All available', \n\tPress 2 for 'Least busy', \n\tPress 3 for 'Random mode'\n"))
if agent_selection_mode == 1:
agent_selection_mode = 'All available'
elif agent_selection_mode == 2:
agent_selection_mode = 'Least busy'
elif agent_selection_mode == 3:
agent_selection_mode = 'Random mode'
else:
print("please choose correct option")
issue_role = str(input("Issue Role : "))
issue = Issue(selection_mode=agent_selection_mode,
role=issue_role, is_selected=False, selected_by=None)
return issue
@staticmethod
def present_issue(issue):
if issue.selection_mode == 'All available':
for agent in agents:
if agent.role == issue.role and agent.is_available:
print(
f"Issue of role {issue.role} is presented to {agent.name} and it's selection mode is {issue.selection_mode}")
elif issue.selection_mode == 'Least busy':
for i in range(len(agents) - 1):
if agents[i].role == issue.role and agents[i].is_available:
longets_available = agents[0]
try:
if longets_available.available_since > agents[i+1].available_since:
longets_available = agents[i+1]
except:
pass
else:
print(
f"Issue of role {longets_available.role} is presented to {longets_available.name} and it's selection mode is {longets_available.selection_mode}")
elif issue.selection_mode == 'Random mode':
for agent in agents:
available_agents = list()
if agent.role == issue.role and agent.is_available:
available_agents.append(agent)
else:
try:
agent = choice(available_agents)
print(
f"Issue of role {issue.role}, The selected agent is {agent.name} and it's selection mode is {issue.selection_mode}")
except:
pass
if __name__ == "__main__":
issues = list()
agents = list()
try:
with open('issue_data.pkl', 'rb') as issue_file:
while True:
try:
issues.append(pickle.load(issue_file))
except:
break
except:
pass
try:
with open('agent_data.pkl', 'rb') as agent_file:
while True:
try:
agents.append(pickle.load(agent_file))
except:
break
except:
pass
while True:
if len(issues) > 0:
for issue in issues:
if issue.is_selected == False:
Issue.present_issue(issue)
try:
selection = int(input(
"\nPress 1 for Add agent, \nPress 2 for add issue, \nPress 3 to terminate programe\n"))
if selection == 1:
agent = Agent.add_agents()
agents.append(agent)
if selection == 2:
issue = Issue.add_issue()
issues.append(issue)
if selection == 3:
with open('agent_data.pkl', 'wb') as agent_data:
for agent in agents:
pickle.dump(agent, agent_data, pickle.HIGHEST_PROTOCOL)
with open('issue_data.pkl', 'wb') as issue_data:
for issue in issues:
pickle.dump(issue, issue_data, pickle.HIGHEST_PROTOCOL)
break
except:
print("\nPlease choose wisely!")
|
# A level Authentication Challenge
class UserStore():
username = None
validated = False
#end class
class User():
username = ""
password = ""
first_name = ""
surname = ""
#end class
users = []
def encrypt_ceasar(password, key): #assumption - only lower case a-z
lowest_char_num = ord("a") # would be ok to hard code this (97)
temp_password = ""
for c in password:
# all the following uncommented lines can be combined into just this
# one line below ! I have split it for easier understanding.
# temp_password += chr((ord(c) + key - lowest_char_num) % 26 + lowest_char_num)
new_char_num = ord(c)
new_char_num += key
zero_bound_char = new_char_num - lowest_char_num
new_char_num = (zero_bound_char % 26) + lowest_char_num
new_char = chr(new_char_num)
temp_password += new_char
#next c
return(temp_password)
#end def
def get_users():
raw_data = None
user_data = []
try:
with open("users.txt", "r") as f:
raw_data = f.readlines()
#end with
except:
print("Error loading data")
return None
#end try
for line in raw_data:
#strip the \n from the end
stripped_line = line.strip()
#get the array of details for each user and create a dictionary !!
sep_data = stripped_line.split(",")
#we should have 4 fields
if len(sep_data) == 4:
user = User()
user.username = sep_data[0]
user.password = sep_data[1]
user.first_name = sep_data[2]
user.surname = sep_data[3]
user_data.append(user)
else:
print("Error loading data")
return None
#end if
#next line
return user_data
#end def
def get_user_index(username):
for index, user in enumerate(users):
if user.username.lower() == username.lower():
return index
#end if
#next index
return -1
#end def
def get_user(username):
for user in users:
if user.username.lower() == username.lower():
return user
#end if
#next index
return None
#end def
def login():
global users
username = input("Enter your user name: ")
password = input("Enter your password: ")
# The password should be decrypted, key = 3
encrypted_password = encrypt_ceasar(password, 3)
# first lets get the users
users = get_users()
if users == None:
print("Error getting data")
return
#end if
user = get_user(username)
if user is not None and user.password == encrypted_password:
print("Welcome,", user.first_name, user.surname)
UserStore.username = username
UserStore.validated = True
user_found = True
else:
print("You have entered incorrect credentials")
UserStore.username = ""
UserStore.validated = False
#end if
#end def
def print_user_details(username):
user = get_user(username)
if user is None: return
print()
print("Details:")
print("Username: " + user.username)
print("First name: " + user.first_name)
print("Surname: " + user.surname)
print()
#end def
def view_details():
if UserStore.username == None or not UserStore.validated:
print("You need to log in first\n")
return
#end if
username = UserStore.username
print_user_details(username)
#end def
def dict_to_cs_string(user):
return user.username + "," + user.password + "," + user.first_name + "," + user.surname
#end if
def save_users():
try:
with open("users.txt", "w") as f:
for user in users:
line = dict_to_cs_string(user)
f.write(line + "\n")
#next user
#end with
except:
print("Error saving data")
#end try
#end def
def change_password():
global users
username = ""
try:
username = UserStore.username
if username == None or not UserStore.validated:
print("You need to log in first\n")
return
#end if
except: # most likely no key found
print("You need to log in first\n")
return
is_updated = False
while not is_updated:
new_password = input("Enter password: ")
new_password_check = input("Enter new password again: ")
if new_password != new_password_check:
print("Your passwords don't match")
continue
#end if
new_password = encrypt_ceasar(new_password,3)
user_index = get_user_index(username)
users[user_index].password = new_password
save_users()
is_updated = True
#end while
#end def
def menu():
print("Welcome to the authentication program")
print("1. Login")
print("2. Change Password")
print("3. View my details")
print("4. Quit")
choice = input("Enter your choice: ")
return choice
#end def
def main():
choice = ""
while choice != "4":
choice = menu()
if choice == "1":
login()
elif choice == "2":
change_password()
elif choice == "3":
view_details()
else:
print("\nSelect a valid choice\n")
#end if
#end while
print("Goodbye")
#end def
if __name__ == "__main__":
main()
#end if
|
#!/usr/bin/env python
"""
List the english words having a french translation that differs
from a single letter.
$ python list_commonly_mispelled_words.py
human,humain
dinner,dîner
"""
if __name__ == '__main__':
import json
import Levenshtein
from unidecode import unidecode
with open('../../anki-usecase-enfrequency/resources/mywiktionary.json') as data_file:
data = json.load(data_file)
for word in data:
if not "translations" in word:
continue
title = word["title"]
if len(title) < 4:
# We ignore short word to avoid being polluated
continue
for translation in word["translations"]:
escaped_translation = unidecode(translation)
escaped_translation.encode("ascii")
title = unidecode(title)
title.encode("ascii")
if word['rank'] > 30000:
continue
if Levenshtein.distance(escaped_translation, title) == 1:
# Remove simple difference
# Ex: "just" => "juste"
if title + "e" == escaped_translation:
break
# Ex: "suppose" => "supposer"
if title + "r" == escaped_translation:
break
# Ex: "tone" => "ton"
if title == escaped_translation + "e":
break
# Ex: "society" => "societé"
if title[:-1] == escaped_translation[:-1]:
break
# Ex: "project" => "projet"
if title.endswith("ct") and escaped_translation.endswith("t"):
break
# Ex: "responsible" => "responsable"
if title.endswith("ible") and escaped_translation.endswith("able"):
break
# Ex: "original" => "originel"
if title.endswith("al") and escaped_translation.endswith("el"):
break
# Ex: "persistent" => "persistant"
if title.endswith("ent") and escaped_translation.endswith("ant"):
break
# Ex: "title" => "titre"
if title.endswith("le") and escaped_translation.endswith("re"):
break
print("%s,%s,%s" % (title, translation,escaped_translation))
|
import os
def print_frame_ranges(path):
''' Print animated sequences in 'path' in the following format:
'name: 1001-2000' if there are no gaps
'name: 1001, 1003-1500, 1600-2000' if there are gaps
the format for an animated sequence is name.####.ext e.g. /job/.../my_render_v001.1001.jpg
This function detects multiple-named sequences within the same directory.
This function follows these basic steps:
1. Get the file list and sort
2. Iterate through the files and generate a dict of lists (`imgseq`). The keys of of the dict are the sequence names; the value is a list of low-high list-pairs. It can be described like this:
# imgseq = {
# 'render_v001': [
# [low_frame_int, high_frame_int]
# ]
# }
Each time a frame skips more than 1 frame from the previous recorded frame, a new 'list-pair' is created and appended.
3. Iterate through `imgseq` converting existing low-frame/high-frame values as formatted zfill'd ranges or single frames format into a list.
4. Iterate through zfilled list and print into format.
'''
# Get files from path
if os.path.exists(path) == False:
raise ValueError('%s does not exist!' % path)
fd = sorted([x for x in os.listdir(path) if os.path.isfile('%s/%s' % (path,x))])
imgseq = {}
imgpad = 4 # Fixed digit padding (can be determined by examining actual filename)
for f in fd:
s_f = f.split('.')
bn = s_f[0]
fr = s_f[1]
# Check if fr is numeric string.
# If not numeric string, not part of sequence.. continue
if fr.isdigit() == False:
continue
i_fr = int(fr) # int of frame number
# Assuming filename extensions are the same
# ex = s_f[2]
# Multiple basenames supported
# If basename not yet encountered, init lists
if (bn in imgseq) == False:
rng = [i_fr, i_fr]
imgseq[bn] = []
imgseq[bn].append(rng)
elif (bn in imgseq) == True:
# If already registered
lastfr = imgseq[bn][-1][1] # determine the last recorded frame
diff = i_fr - lastfr # Find the difference
if diff > 1:
# If cur frame is higher by more than 1 frame then there's a skip
rng = [i_fr, i_fr] # start a new range
imgseq[bn].append(rng)
else:
# No skip, just modify high frame
o_i_fr = imgseq[bn][-1][0]
rng = [o_i_fr, i_fr] # modify high frame
imgseq[bn][-1] = rng
# Generate another list with zfill'd ranges
rngs = {}
for k,rnglist in imgseq.items():
if k not in rngs:
rngs[k] = []
for v in rnglist:
if v[0] == v[1]: # If single frame
rs = str(v[0]).zfill(imgpad)
else:
# If frame range
min_v = str(v[0]).zfill(imgpad)
max_v = str(v[1]).zfill(imgpad)
rs = '-'.join([min_v, max_v])
rngs[k].append(rs)
# Finally join up the lists and print
for k,v in rngs.items():
fs = '%s: %s' % (k, ', '.join(v))
print(fs)
p = 'R:/PROJECTS/CINESITE/3d/images'
print_frame_ranges(p) |
# Instance Method - Mutator Method / Setter Method
class Mobile:
def __init__(self):
self.model = 'RealMe X' # Instance Variable
def set_model(self): # Mutator Method
self.model = 'RealMe 2'
realme = Mobile()
# Before setting
print(realme.model)
# After Setting
realme.set_model() # Calling Mutator Method
print(realme.model) |
from datetime import datetime
ct = datetime.now() # Calling Method using class name
print("Current Date and Time:", ct)
print("Date:", ct.day)
print("Month:", ct.month)
print("Year:", ct.year)
print("Hour:", ct.hour)
print("Minute:", ct.minute)
print("Second:", ct.second)
print("Microsecond:", ct.microsecond)
print()
ct1 = datetime.today() # Calling Method using class name
print("Current Date and Time:", ct1)
print("Date:", ct1.day)
print("Month:", ct1.month)
print("Year:", ct1.year)
print("Hour:", ct1.hour)
print("Minute:", ct1.minute)
print("Second:", ct1.second)
print("Microsecond:", ct1.microsecond)
print()
|
# Multitasking using Multiple Thread
# Two task using Two Threads
from threading import Thread
class Hotel:
def __init__(self, t):
self.t = t
def food(self):
for i in range(1, 6):
print(self.t, i)
h1 = Hotel('Take Order From Table: ')
h2 = Hotel('Serve Order to Table: ')
t1 = Thread(target=h1.food)
t2 = Thread(target=h2.food)
t1.start()
t2.start()
|
# Instance Variable
class Mobile:
def __init__(self):
self.model = 'RealMe X' # Instance Variable
def show_model(self): # Instance Method
print(self.model) # Accessing Instance Variable
realme = Mobile()
redmi = Mobile()
geek = Mobile()
print("RealMe:", realme.model)
print("Redmi:", redmi.model)
print("Geek:", geek.model)
print()
redmi.model = 'Redmi 7s' # Modifying Instance Variable
print("RealMe:", realme.model)
print("Redmi:", redmi.model)
print("Geek:", geek.model)
|
# Class Variable
class Mobile:
fp = 'Yes' # Class Variable
@classmethod # Class Method
def is_fp(cls):
print("Finger Print:", cls.fp) # Accessing Class Variable
realme = Mobile()
redmi = Mobile()
geek = Mobile()
print("RealMe:", Mobile.fp)
print("Redmi:", Mobile.fp)
print("Geek:", Mobile.fp)
print()
Mobile.fp = 'No' # Modifying Class Variable
print("RealMe:", Mobile.fp)
print("Redmi:", Mobile.fp)
print("Geek:", Mobile.fp)
|
'''class Decorator(object):
"""Simple decorator class."""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('Before the function call.')
res = self.func(*args, **kwargs)
print('After the function call.')
return res
@Decorator
def testfunc():
print('Inside the function.')
testfunc()
'''
def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
@smart_divide
def divide(a,b):
return a/b
def star(func):
def inner(*args, **kwargs):
print("*" * 30)
func(*args, **kwargs)
print("*" * 30)
return inner
def percent(func):
def inner(*args, **kwargs):
print("%" * 30)
func(*args, **kwargs)
print("%" * 30)
return inner
@star
@percent
def printer(msg):
print(msg)
printer("Hello") |
n = int(raw_input())
for i in range (1,n+1):
for j in range (1,i+1):
print "*",
print
for i in range (1,n+1):
for j in range (n,i-1,-1):
print "*",
print
for i in range(1, n + 1):
for j in range(1, i + 1):
print i,
print
for i in range(1, n + 1):
for j in range(1, i + 1):
print j,
print
for i in range(1, n + 1):
for j in range(n, i - 1, -1):
print i,
print
for i in range(1, n + 1):
for j in range(n, i - 1, -1):
print j,
print
k=1;
for i in range (1,n+1):
for j in range (1,i+1):
print k,
k+=1
print
for i in range(n,0,-1):
for j in range(1,i+1):
print i,
print |
import numpy as np
#based off of the fact that we are dealing with discrete values, adjacency is just a specific type of intersection, so
#I will be making a function to find adjacency but all adjacency would also trip intersections. Furthermore contained is
#a type of intersection as well where all of it is in the other.
def intersect_contain_adjacent(box_one, box_two):
intersect = 0
contained = 1
second_contained = 1
continue_checking_intersect = 1
continue_checking_contained = 1
for i in box_one:
if continue_checking_intersect == 1 and i in box_two:
intersect = 1
continue_checking_intersect = 0
elif continue_checking_contained == 1 and i not in box_two:
contained = 0
elif continue_checking_contained == continue_checking_intersect == 0:
break
if intersect == 0:
adjacent = 0
else:
intersecting_values = []
for i in box_one:
if i in box_two:
intersecting_values.append(i)
if np.unique(np.array([item[0] for item in intersecting_values])).size <= 2 or np.unique(np.array([item[1] for item in intersecting_values])).size <= 2:
adjacent = 1
else:
adjacent = 0
for i in box_two:
if i not in box_one:
second_contained = 0
break
return [intersect, contained, second_contained, adjacent]
|
import sqlite3
class Banco():
def __init__(self):
self.conexao = sqlite3.connect('Database.db')
self.createTable()
def createTable(self):
c = self.conexao.cursor()
c.execute("""create table if not exists Clientes (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome VARCHAR(50) NOT NULL,
cpf VARCHAR(11) NOT NULL,
dvd_codes TEXT DEFAULT '[0]'
)""")
c.execute("""create table if not exists Funcionarios (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)""")
c.execute("""create table if not exists DVD (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
filme TEXT NOT NULL,
cod_dvd TEXT NOT NULL
)""")
self.conexao.commit()
c.close()
|
import pickle
from os import path
class Customer(object):
def load_customer_data(self, seat_book):
"""
This function is used to load customer data in pickle file.
:param seat_book: Input parameter to load booked seat details
:return: Nothing
"""
with open('customer_data', 'wb') as book:
pickle.dump(seat_book, book)
def book_seat(self, seat_book, booking_id):
"""
This function is used to book seat
:param seat_book: Input parameter having booked seat details
:param booking_id: Booking Id of seat booked by customer
:return: Nothing
"""
if path.exists('customer_data'):
with open('customer_data', 'rb') as res_seat:
reserve_seat = pickle.load(res_seat)
if booking_id not in reserve_seat:
reserve_seat.update(seat_book)
self.load_customer_data(reserve_seat)
else:
self.load_customer_data(seat_book)
def get_ticket(self, bkg_id):
"""
This function returns ticket details based on booking id
:param bkg_id: Input parameter to get the booking id
:return: Ticket details
"""
customer = dict()
if path.exists('customer_data'):
with open('customer_data', 'rb') as user_seat:
customer = pickle.load(user_seat)
if bkg_id in customer:
return customer[bkg_id]
else:
print("Invalid Booking Id..!!")
return {}
|
# asal sayi 1'e ve kendisine bolunen sayidir
"""
Asal sayi bulma
cikmak icin q-e basin
"""
def asalmi(x):
if x==1:
return False
elif x==2:
return True
else:
for i in range(2,x):
if x%i==0:
return False
return True
while True:
asal=input("Sayi: ")
if asal=="q":
break
else:
asal=int(asal)
print(asalmi(asal))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 8 19:18:19 2016
@author: Rachel Carrig; rlc63
"""
#Overall Comment: Very good assignment! You covered all possible situations and commented well. But please include examples
#to show that your functions really work. I have made a few comment with "Comment:" in front, you may have a look. If any
#misunderstanding happened. Please feel free to email me.
"""
COMPLETE
Question 1: This function defines which number is the larger of two given numbers.
"""
def print_max(a, b): #the function will print the largest of two numbers
"""
This function will print the larger of two numerical values
Parameters: real numbers
Return: the larger of two numbers, assuming they are different. if they are the same, it returns that number.
"""
if a >= b:
print(a, 'is maximum')#if a is greater than or equal to b, a is maximum
elif a <= b:
print(b, 'is maximum')#if b is greater than or equal to a, b is maximum
x = 2#here we give values for x and y corresponding to a and b
y = 3
print_max(x, y)#prints the maximum of x and y; in this case y
#Comment: You don't need to set variable x and y individually, put 2 and 3 into function directly.
"""
COMPLETE
Question 2: This function defines which of three numbers is the largest.
"""
def print_max_of_three(a, b, c): #the function will print the largest of three variables
"""
This function will print the largest of three numerical values
Parameters: real numbers
Return: the largest of the three numbers, assuming they are different. if two or three of the numbers are the same and that number is the largest, it will print that one.
"""
if a >= b and a >= c:
print(a, 'is maximum')#if a is greater than or equal to b AND greater than or equal to c, then a is the maximum
elif c >= a and c >= b:
print(c, 'is maximum')#if c is greater than or equal to a AND greater than or equal to b, then c is the maximum
elif b >= a and b >= c:
print(b, 'is maximum')#if b is greater than or equal to a AND greater than or equal to c, then b is the maximum
x = 1#here we give values for x, y, and z corresponding to a, b, and c
y = 0
z = 1
print_max_of_three(x, y, z)#prints the maximum of x, y, and z
"""
COMPLETE
Question 3: This function defines the length of a given list or string.
"""
def length(sentence): #the function will print the length of a given sentence
"""
This function provides the length of the text entered.
Parameters: text, not including spaces
Return: an integer containing the number of letters in the text.
"""
x = 0 #we start out with 0 letters before anything is submitted
for i in sentence:
x = (x + 1) #we want to add 1 to 0 for the first letter, and keep adding 1 for each letterin the string
print(x) #this will print the final count of all the letters in the string
"""
COMPLETE
Question 4: This function returns "True" for a vowel given, and "False" for anything else.
"""
vowels = 'aeiouAEIOU' #first we define all vowels, which can be both lower or upper case
def isVowel(char): #then for our function, we have one character
"""
this function determines whether or not the character given is a vowel, as defined above
Parameters: a single character must be entered, otherwise it will automatically give False
Return: True if a single vowel, false otherwise
"""
if len(char) == 1: #this limits the input to one character
if char in vowels: #if the character inputted is in the vowels set, or is a vowel, then it will print True
print("True")
else: #if the character inputted is not in the vowel set, False will print
print("False")
"""
COMPLETE
Question 5: Translate English into Robber's Language, where when a consonant is listed it is replaced by the consonant + o + the consonant again.
"""
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ' #first, we define what consonants are. The consonants can be either capital or lowercase, and all are included here. We consider y and Y a consonant for this exercise.
def translate(language): #this function will translate the language inputted into Robber's Language
"""
this function translates a string of text entered into "robber's Language", where each consonant as defined above is rewritten as that consonant plus o and then plus that consonant again.
Parameters: a string of text
Return: the initial language translated into the "robber's language" as described above
"""
newtext = "" #we will define what the new text will be based on the input
for i in language:
if i in consonants:
newtext+=i+'o'+i #for any character i inputted that is a consonant (as found in consonants), it will be returned as i + o + i, or "ioi" in practice.
else:
newtext+=i #if the character is NOT a consonant, it will stay the same
print(newtext) #the code will now print the language in Robber's Language
#Comment: it is good to cover all possible situations!
"""
COMPLETE
Question 6: Define sum() and multiply() such that they sum and multiply, respectively, everything in a list of numbers
"""
#first, we will define the function sum() to add numbers provided in a list
def sum(numlist):
"""
this function adds together the numbers listed in the input
Parameters: real numbers
Return: the sum of the listed
"""
x = 0 #we start out with x as 0, as we don't have any numbers to begin with
for i in numlist:
x = (x + i) #for each number in the number list, we add it to the previous number (and if it's the first number, we add it to 0, the initial value of x)
print(x) #this will print out the solution
#we will now define the function multiply() to multiply numbers provided in a list
def multiply(numlist):
"""
this function will multiply together the numbers listed in the input
Parameters: real numbers
Return: the product of the numbers listed
"""
x = 1 #we start out with 1, as any number multiplied by 1 is itself
for i in numlist:
x = (x * i) #for each number in the list, we multiply it by the previous number (and if it's the first number, we multiply it by 1, the initial value of x)
print(x) #this will print out the solution
"""
COMPLETE
Question 7: Computes the reversal of a string
"""
def reverse(text): #define a function reverse to make a reverse string
"""
Writes a given string in reverse
Parameters: a string
Return: the string printed backwards
"""
i = len(text) - 1 #this gives us the last letter in the string of text
backwardstext = '' #here we define backwardstext as empty
while i >= 0:
backwardstext = backwardstext + str(text[i]) #we then add the backwards text together, switching the position of each letter
i = i -1
print(backwardstext) #this prints the final text created
"""
COMPLETE
Question 8: Define a function that recognizes palindromes
"""
def is_palindrome(text): #here we define a function that tests if the entered text is a palindrome
"""
This function recognizes palindromes.
Parameters: any word with alphabetical characters (no numbers, upper or lower case, and disregarding spaces)
Return: Return True if it is a palindrome, False otherwise
"""
text = text.upper() #allows for text to be upper or lower case
text = text.replace(" ", "") #removes spaces from consideration, so if there is more than one word but they still form a palindrome, the result is true
backwardstext = text [::-1] #we create a backwards text that takes the last character and oves it to the front, the second to last character and moves it to second, and so on
if not text.isalpha(): #if there are numbers in the input, or the input is empty it will automatically return false
return False
if backwardstext == text: #if the initial text is the same as the text created in above line
return True #then, the statement will return true
else: #if the initial text is not the same as the text created in the second line (line 117), then it returns false as it is not a palindrome
return False
"""
COMPLETE
Question 9: Function that says if a value is in a list of values
"""
def is_member(lista, b): #we're defining a function where the first part of the entry is the list we have, and the second is the individual element we want to see is in the list
"""
this function determines whether or not a given item is part of the given list
Parameters: any list and an item listed separately
Return: True if the item listed separately is within the given list, and false if it is not
"""
for x in lista: #we look at any element in lista
for y in b: #we then look at the element in b
if x == y: #if one of the elements are equal, meaning if b is in lista
return True #the result is True and the function is complete
else:
return False #if the program does not find any b within lista, then it will return false
"""
COMPLETE
Question 10: Define a function that takes two lists and says true if they have at least one member in common
"""
def overlapping(list1, list2): #we define the function so that when inputting, you write overlapping([___list 1 elements___], [___list2 elements___])
"""
this function determines if two lists have any element within them that overlaps
Parameters: two lists
Return: True if there is overlap between the two lists; false otherwise
"""
for x in list1: #here, we want any variable in list1
for y in list2: #again, we want any variable but this time in list2
if x == y: #if any x in list1 is equal to anyx in list2
return True #the result will be true. the return function looks for any values where it is true, and if it is, it just prints true
else:
return False #if there are NO true values, then false is printed
"""
COMPLETE
Question 11: Define a function generate_n_chars()that takes an integer n and a character c and returns a string, ncharacters long, consisting only of c's.
"""
def generate_n_chars(num, char): #here we generate the same character the number of times as the number inputted
"""
this function generates a duplication of a character entered the number of times listed
Parameters: num is a number and char is a character, and both must be inputted
Return: the result is the character repeated number times
"""
out = "" #we start with nothing in the output
for i in range(num): #for the number given as num
out = out + char #the output is each character num times, as it starts at 0 and adds up until num is complete
return(out) #this returns the final result we want
"""
COMPLETE
Question 12: function that creates a histogram from a list of numbers given
"""
def histogram(numbers): #we are creating a histogram from a set of numbers given
"""
this function creates a histogram, where a list of numbers is translated into groups of * listed the number of times given
Parameters: real numbers are inputted
Return: the result is the character * the number of times for each element in the list
"""
out = "" #we start out with nothing in the input
for x in numbers: #for each number within the given set
out = out + generate_n_chars(x, '*') + " " #we use the function created in Question 11 to print the symbol '*' x number of times with a space added to separate the numbers
return out[:-1] #returns everything but the last space, so there's no extra space at the end
"""
COMPLETE
Question 13: Create a function that produces the maximum element in a list (where length of list is not predetermined)
"""
def two_max(a, b): #the function will print the largest of two numbers
"""
first, we need to find the maximum of two numbers
Parameters: two real numbers
Return: the larger of the two numbers
"""
if a >= b:
return a #if a is greater than or equal to b, a is maximum
elif a <= b:
return b #if b is greater than or equal to a, b is maximum
def max_in_list(maxlist): #here, we want a list of more than just a and b to take the maximum from
"""
once we have defined the two_max, we then need to find the largest number in a list of numbers
Parameters: a list of two or more real numbers
Return: the largest of the numbers listed
"""
heaviest = maxlist[0] #to do this, we create 'heaviest' where the maxlist is 0 (so nothing is in it at first)
for x in maxlist: #for each element inputted
heaviest = two_max(x, heaviest) #the element is measured against the heaviest one, and the heaviest one is kept. So, for the first element, the first element is larger than zero, then the second element is compared to the first, and the larger one is kept, and so on
return heaviest #this gives us the heaviest one after all of the numbers are compared
"""
COMPLETE
Question 14: Map a list of words into a list of integers representing the words' lengths
"""
def length_14(sentence): #the function will print the length of a given sentence
"""
first, we define the length of a given word
Parameters: a string of characters given
Return: the length of the string
"""
x = 0 #we start out with 0 letters before anything is submitted
for i in sentence:
x = (x + 1) #we want to add 1 to 0 for the first letter, and keep adding 1 for each letterin the string
return x #this returns the length of the sentence
def length_of_words(list0): #we now move to the length of the words in the list
"""
once we have the length of strings of words, we can use them to create a list of each length of the words
Parameters: a list of words
Return: gives the length of each word in the list
"""
out = [length_14(word) for word in list0] #here we set out equal to the length of each word in the list, using the previously defined function
return out #we return out, giving us the lengths of each word
"""
COMPLETE
Question 15: Write a function that takes a list of words and returns the length of the longest one
"""
def find_longest_word(longword): #this function is similar to the max_in_list function, but with word lengths instead of numbers
"""
using the previously defined functions length_of_words() and max_in_list(), we can determine which word is the longest given a list of words
Parameters: a list of words given
Return: the length of the largest word
"""
lcounts = length_of_words(longword) #we create lcounts, which is the length of each word given (so the result is a list of numbers)
heaviest = max_in_list(lcounts) #we then take the numbers from lcounts and use the previously defined max_in_list function to see which is the largest
return heaviest #this prints the largest of the numbers, which is the largest length of a word in the set
#return max_in_list(length_of_words(longword)) #could use this instead of the three above lines
"""
COMPLETE
Question 16: Write a function that takes a list of words and an integer n and returns the list of words that are longer than n.
"""
def filter_long_words(longwords, n): #here we define the function
"""
here we write a function that takes a list of words, finds their lengths, and writes out the list of words that are longer than n
Parameters: a list of words, and an integer
Return: the words longer than the integer given
"""
out = [] #we start out with nothing in out
for word in longwords: #for each word given in the input of the function, we do the following:
if length_14(word) >= n: #this looks to see if the length of the word as previously defined is larger than the n given
out.append(word) #if it is, then that word is added to the out list (which starts out as nothing)
return out #once all words have been evaluated, the function returns the out list, with all words longer than n appended to it
|
import json
def takesurvey(questions, answers):
answer = {}
for q in questions:
answer[q] = input(q)
# print(answer)
answers.append(answer)
# print(answers)
a = []
q = ['what is your name? ', 'What is your nationality? ', 'How old are you? ', 'What is your favorite ice cream flavor? ',
'Do you play any sports? ', 'What about instruments? ' , 'What genre music do you like? ' , 'What color is your hair? ' , 'Is water wet? ']
for i in range(3):
print("NEW SURVEY")
takesurvey(q, a)
print(a)
f = open("answers.json" ,"w")
f.write(json.dumps(a))
f.close()
|
class Node:
def __init__(self,data):
self.left = None
self.right = None
self.data = data
self.type = None
class BinaryTree:
def __init__(self):
self.root = None
def insert_node(self,root,element):
if self.root is None:
self.root = Node(element)
else:
if root is None:
root = Node(element)
elif root.data <= element:
root.right = self.insert_node(root.right,element)
root.type = "right"
elif root.data > element:
root.left = self.insert_node(root.left,element)
root.type = "left"
return root
def PreOrder(self,root):
if root is not None:
print(root.data),
print(root.type)
if root.left is not None:
self.PreOrder(root.left)
if root.right is not None:
self.PreOrder(root.right)
a = BinaryTree()
print("A")
a.insert_node(a.root,100)
a.insert_node(a.root,50)
a.insert_node(a.root,25)
a.insert_node(a.root,200)
a.insert_node(a.root,125)
a.insert_node(a.root,350)
a.PreOrder(a.root)
print
print("B")
b = BinaryTree()
b.insert_node(b.root,100)
b.insert_node(b.root,50)
b.insert_node(b.root,25)
b.insert_node(b.root,200)
b.insert_node(b.root,125)
b.insert_node(b.root,450)
b.PreOrder(b.root)
def are_identical(root1, root2):
if root1 == None and root2 == None:
return True
if root1 != None and root2 != None:
return (root1.data == root2.data and
are_identical(root1.left, root2.left) and
are_identical(root1.right, root2.right))
return False
print
print(are_identical(a.root, b.root)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
import math
import sys
# Read from the file u.user and return a list containing all of the
# demographic information pertaining to the users.
# The userList contains as many elements as there are users and information
# pertaining to the user with ID i should appear in slot i-1 in userList.
# The userList is a list with 943 dictionaries, each dictionary containing 4 keys.
def createUserList():
userList = list()
filename = 'u.user'
with open(filename, 'r') as f:
records = f.readlines()
for i in xrange(len(records)):
userList.append(dict())
for r in records:
record = (r.strip()).split('|')
userList[int(record[0])-1]['age'] = int(record[1])
userList[int(record[0])-1]['gender'] = record[2]
userList[int(record[0])-1]['occupation'] = record[3]
userList[int(record[0])-1]['zip'] = record[4]
return userList
# Read from the file u.item and return a list containing all of the
# information pertaining to movies given in the file.
# Then movieList contains as many elements as there are movies and information
# pertaining to the movie with ID i should appear in slot i-1 in movieList.
def createMovieList():
movieList = list()
filename = 'u.item'
with open(filename, 'r') as f:
records = f.readlines()
for i in xrange(len(records)):
movieList.append(dict())
for r in records:
record = (r.strip()).split('|')
movieList[int(record[0])-1]['title'] = record[1]
movieList[int(record[0])-1]['release date'] = record[2]
movieList[int(record[0])-1]['"video release date'] = record[3]
movieList[int(record[0])-1]['IMDB url'] = record[4]
movieList[int(record[0])-1]['genre'] = list()
for n in range(5, 24):
movieList[int(record[0])-1]['genre'].append(int(record[n]))
return movieList
# Read ratings from the file u.data and return a list of 100,000 length-3
# tuples of the form (user, movie, rating).
def readRatings():
ratingList = list()
filename = 'u.data'
with open(filename, 'r') as f:
records = f.readlines()
for r in records:
record = (r.strip()).split('\t')
ratingList.append((int(record[0]), int(record[1]), int(record[2])))
return ratingList
# The function takes the rating tuple list constructed by readRatings and
# organizes the tuples in this list into two data structures: rLu and rLm.
# The list rLu is a list, with one element per user, of all the ratings provided by each user.
# The list rLm is a list, with one element per movie, of all the ratings received by each movie.
# The ratings provided by user with ID i should appear in slot i-1 in rLu, as a dictionary
# whose keys are IDs of movies that this user has rated and whose values are corresponding ratings.
# The list rLm is quite similar.
def createRatingsDataStructure(numUsers, numItems, ratingTuples):
rLu = list()
rLm = list()
#for i in xrange(numUsers):
# rLu.append(dict())
rLu = [{} for i in xrange(numUsers)]
#for i in xrange(numItems):
# rLm.append(dict())
rLm = [{} for i in xrange(numItems)]
for r in ratingTuples:
rLu[int(r[0]-1)][int(r[1])] = int(r[2])
rLm[int(r[1]-1)][int(r[0])] = int(r[2])
for user in rLu:
try:
m = sum(user.values())/float(len(user))
user['mean'] = m
max_common_movie = 0
for v in rLu:
t = len(set(user.keys()) & set(v.keys()))
if t > max_common_movie:
if v is not user:
max_common_movie = t
user['max_common'] = max_common_movie
except ZeroDivisionError:
user['mean'] = 0.
user['max_common'] = 0
for movie in rLm:
try:
m = sum(movie.values())/float(len(movie))
movie['mean'] = m
max_common_user = 0
for n in rLm:
t = len(set(movie.keys()) & set(n.keys()))
if t > max_common_user:
if n is not movie:
max_common_user = t
movie['max_common'] = max_common_user
except ZeroDivisionError:
movie['mean'] = 0.
movie['max_common'] = 0
return [rLu, rLm]
# Read from the file u.genre and returns the list of movie genres listed in the file.
# The genres appears in the order in which they are listed in the file.
def createGenreList():
genreList = list()
filename = 'u.genre'
with open(filename, 'r') as f:
records = f.readlines()
for r in records:
record = (r.strip()).split('|')
if record[0]:
genreList.append(record[0])
return genreList
# Return the mean rating provided by user with given ID u.
def meanUserRating(u, rLu):
if len(rLu[u-1])!= 0:
mean_rating = rLu[u-1]['mean']
else:
mean_rating = 0.0
return mean_rating
# Return the mean rating for a movie with given ID m.
def meanMovieRating(m, rLm):
if len(rLm[m-1])!= 0:
mean_rating = rLm[m-1]['mean']
else:
mean_rating = 0.0
return mean_rating
# Given a user u and a movie m, simply return a random integer rating in the range [1, 5].
def randomPrediction(u, m):
rating = random.randint(1,5)
return rating
# Given a user u and a movie m, simply return the mean rating that user u has given to movies.
# Here userRatings is a list with one element per user, each element being a dictionary
# containing all movie-rating pairs associated with that user.
def meanUserRatingPrediction(u, m, userRatings):
rating = meanUserRating(u, userRatings)
return rating
# Given a user u and a movie m, simply return the mean rating that movie m has received.
# Here movieRatings is a list with one element per movie, each element being a dictionary
# containing all user-rating pairs associated with that user.
def meanMovieRatingPrediction(u, m, movieRatings):
rating = meanMovieRating(m, movieRatings)
return rating
# Given a user u and a movie m, simply return the average of the mean rating
# that u gives and mean rating that m receives.
def meanRatingPrediction(u, m, userRatings, movieRatings):
rating_1 = meanUserRating(u, userRatings)
rating_2 = meanMovieRating(m, movieRatings)
rating = (rating_1 + rating_2)/2
return rating
# The function partitions ratings into a training set and a testing set.
# The testing set is obtained by randomly selecting the given percent of the raw ratings.
# The remaining unselected ratings are returned as the training set.
def partitionRatings(rawRatings, testPercent):
trainingSet = list(rawRatings)
testSet = list()
test_size = int(len(rawRatings) * testPercent)
while len(testSet) < test_size:
index = random.randrange(len(trainingSet))
testSet.append(trainingSet.pop(index))
return [trainingSet, testSet]
# The function computes the RMSE given lists of actual and predicted ratings.
# RMSE is computed by first taking the mean of the squares of differences between actual
# and predicted ratings and then taking the square root of this quantity.
def rmse(actualRatings, predictedRatings):
summation = 0.0
length = len(actualRatings)
for i in xrange(length):
summation += (actualRatings[i] - predictedRatings[i]) ** 2
rmse_value = math.sqrt(summation/length)
return rmse_value
# The function computes the similarity in ratings between the two users, using the
# movies that the two users have commonly rated. The similarity between two users
# will always be between -1 and +1.
def similarity(u, v, userRatings):
sim = 0.0
sum_1 = sum_2 =sum_3 = 0.0
# Find the movies that the two users have commonly rated.
common_movie = list(set(userRatings[u-1].keys()) & set(userRatings[v-1].keys()))
if len(common_movie) == 0:
return sim
# Compute the mean ratings that user u or user v has given to movies.
mean_rating_1 = meanUserRating(u, userRatings)
mean_rating_2 = meanUserRating(v, userRatings)
# Compute the similarity in ratings between the two users.
for i in common_movie:
sum_1 += (userRatings[u-1][i] - mean_rating_1) * (userRatings[v-1][i] - mean_rating_2)
sum_2 += (userRatings[u-1][i] - mean_rating_1) ** 2
sum_3 += (userRatings[v-1][i] - mean_rating_2) ** 2
if sum_1 == 0 or sum_2 == 0 or sum_3 == 0:
return sim
else:
sim = sum_1 / ( math.sqrt(sum_2) * math.sqrt(sum_3) )
return sim
# The function returns the list of (user ID, similarity)-pairs for the k users
# who are most similar to user u. The user u herself will be excluded from
# candidates being considered by this function.
def kNearestNeighbors(u, userRatings, k):
sim_user_list = list() # a list of (similarity, user ID)-pairs
user_sim_list = list() # a list of (user ID, similarity)-pairs
for i in xrange(len(userRatings)):
sim = 0
if i != u-1:
sim = similarity(u, i+1, userRatings)
sim_user_list.append((sim, i+1))
sim_user_list.sort()
sim_user_list.reverse()
if k == -1:
return sim_user_list
for i in sim_user_list[:k]:
user_sim_list.append((i[1], i[0]))
return user_sim_list
# calculate the KNN using pre-calculated similarity
def kNearestNeighbors2(u, userRatings, k, similarity_m):
sim_user_list = list() # a list of (similarity, user ID)-pairs
user_sim_list = list() # a list of (user ID, similarity)-pairs
for i in xrange(len(userRatings)):
sim = 0
if i != u-1:
sim = similarity_m[u][i+1]
sim_user_list.append((sim, i+1))
sim_user_list.sort()
sim_user_list.reverse()
if k == -1:
return sim_user_list
for i in sim_user_list[:k]:
user_sim_list.append((i[1], i[0]))
return user_sim_list
# The function predicts a rating by user u for movie m.
# It uses the ratings of the list of friends to come up with a rating by u of m according to formula.
# The argument corresponding to friends is computed by a call to the kNearestNeighbors function.
def CFRatingPrediction(u, m, userRatings, friends):
# Construct a dictionary, whose keys are userID and
# whose values are (similarity, mean_rating)-pairs.
user_dict = dict()
for i in friends:
user_dict.setdefault(i[0], list())
user_dict[i[0]].append(i[1])
mean_rating = meanUserRating(i[0], userRatings)
user_dict[i[0]].append(mean_rating)
rating = meanUserRating(u, userRatings)
sum_1 = 0.0
sum_2 = 0.0
for i in friends:
if m in userRatings[i[0]-1]:
sum_1 += (userRatings[i[0]-1][m] - user_dict[i[0]][1]) * user_dict[i[0]][0]
sum_2 += abs(user_dict[i[0]][0])
if sum_2 == 0:
return rating
else:
rating += sum_1 / sum_2
return rating
# The function computes a number using the formula (which is same to the function CFRatingPrediction),
# and then returns the average of this and mean rating of movie m.
def CFMMRatingPrediction(u, m, userRatings, movieRatings, friends):
rating = CFRatingPrediction(u, m, userRatings, friends)
mean_rating_m = meanMovieRating(m, movieRatings)
average_rating = (rating + mean_rating_m) / 2
return average_rating
# return both the return value of CFMMRatingPrediction and CFMMRatingPrediction
def CFMMRatingPrediction2(u, m, userRatings, movieRatings, friends):
rating = CFRatingPrediction(u, m, userRatings, friends)
mean_rating_m = meanMovieRating(m, movieRatings)
average_rating = (rating + mean_rating_m) / 2
return rating, average_rating
# The function computes the max number of movies that user u and another user have commonly rated.
# First, compute the number of movies that user u and each user in all-users have commonly rated.
# Second, find the max of all the numbers.
def maxCommonMovie(u, userRatings):
common_movie_list = list()
#length = len(userRatings)
for i, v in enumerate(userRatings):
if i != u-1:
#common_movie = 0
#for movie in userRatings[u-1]:
# if movie in userRatings[i]:
# common_movie += 1
common_movie = len(set(userRatings[u-1]) & set(v))
common_movie_list.append(common_movie)
#common_movie_list.sort()
#max_common_movie = common_movie_list[-1]
return max(common_movie_list)
# The function computes the new similarity in ratings between the two users, using the
# movies that the two users have commonly rated.
# The new similarity between two users will always be between 0.36788 and 1.
def userSimilarity(u, v, userRatings):
#common_movie = 0.0
max_common = maxCommonMovie(u, userRatings)
# Find the movies that the two users have commonly rated.
#for i in userRatings[u-1]:
# if i in userRatings[v-1]:
# common_movie += 1
common_movie = float(len(set(userRatings[u-1]) & set(userRatings[v-1])))
sim = similarity(u, v, userRatings)
user_sim = math.exp(common_movie/max_common - 1) * sim
return user_sim
# calculate the userSimilarity using pre-calculated similarity and maxCommonUser
def userSimilarity2(u, v, userRatings, similarity_m):
max_common = userRatings[u-1]['max_common']
common_movie = float(len(set(userRatings[u-1].keys()) & set(userRatings[v-1].keys())))
sim = similarity_m[u][v]
user_sim = sim > 0 and math.exp(common_movie/max_common - 1) * sim or 0
return user_sim
# The function returns the list of (user ID, similarity)-pairs for the k users
# who are most similar to user u. The user u herself will be excluded from
# candidates being considered by this function.
# The new similarity between users is computed by a call to the userSimilarity function.
def userKNearestNeighbors(u, userRatings, k):
sim_user_list = list() # a list of (similarity, user ID)-pairs
user_sim_list = list() # a list of (user ID, similarity)-pairs
for i in xrange(len(userRatings)):
sim = 0
if i != u-1:
sim = userSimilarity(u, i+1, userRatings)
sim_user_list.append((sim, i+1))
sim_user_list.sort()
sim_user_list.reverse()
for i in sim_user_list[:k]:
user_sim_list.append((i[1], i[0]))
return user_sim_list
# calculate the userKNN using pre-calculated similarity
def userKNearestNeighbors2(u, userRatings, similarity_m):
sim_user_list = list() # a list of (similarity, user ID)-pairs
user_sim_list = list() # a list of (user ID, similarity)-pairs
for i in xrange(len(userRatings)):
sim = 0
if i != u-1:
sim = userSimilarity2(u, i+1, userRatings, similarity_m)
sim_user_list.append((sim, i+1))
sim_user_list.sort()
sim_user_list.reverse()
return sim_user_list
# The function predicts a rating by user u for movie m.
# It uses the ratings of the list of friends to come up with a rating by u of m according to formula.
# The argument corresponding to friends is computed by a call to the userKNearestNeighbors function.
def userCFRatingPrediction(u, m, userRatings, friends):
rating = CFRatingPrediction(u, m, userRatings, friends)
return rating
# This function computes the maximum value of the numbers of users who have both
# rated movie i and another movie which is in movie set.
# First, compute the number of users that movie m and each movie in all-movies have been commonly rated by.
# Second, find the max of all the numbers.
def maxCommonUser(m, movieRatings):
common_user_list = list()
for i, n in enumerate(movieRatings):
if i != m-1:
common_user = len(set(movieRatings[m-1]) & set(n))
common_user_list.append(common_user)
#common_user_list.sort()
#max_common_user = common_user_list[-1]
return max(common_user_list)
# The function computes the similarity in ratings between the two movies, using the
# users who have commonly rated the two movies. The similarity between two movies
# will always be between -1 and +1.
def similarity_2(m, n, movieRatings):
sim = 0.0
sum_1 = sum_2 =sum_3 = 0.0
# Find the users that have commonly rated the same two movies.
common_user = list(set(movieRatings[m-1].keys()) & set(movieRatings[n-1].keys()))
if len(common_user) == 0:
return sim
# Compute the mean ratings that movie m or movie n has been given to.
mean_rating_1 = meanMovieRating(m, movieRatings)
mean_rating_2 = meanMovieRating(n, movieRatings)
# Compute the similarity in ratings between the two movies.
for i in common_user:
sum_1 += (movieRatings[m-1][i] - mean_rating_1) * (movieRatings[n-1][i] - mean_rating_2)
sum_2 += (movieRatings[m-1][i] - mean_rating_1) ** 2
sum_3 += (movieRatings[n-1][i] - mean_rating_2) ** 2
if sum_1 == 0 or sum_2 == 0 or sum_3 == 0:
return sim
else:
sim = sum_1 / ( math.sqrt(sum_2) * math.sqrt(sum_3) )
return sim
# The function computes the new similarity in ratings between the two movies, using the
# users who have commonly rated the two movies.
# The new similarity between two movies will always be between 0.36788 and 1.
def movieSimilarity(m, n, movieRatings):
#common_user = 0.0
max_common = maxCommonUser(m, movieRatings)
# Find the users that have commonly rated the same two movies.
#for i in movieRatings[m-1]:
# if i in movieRatings[n-1]:
# common_user += 1
common_user = float(len(set(movieRatings[m-1]) & set(movieRatings[n-1])))
sim = similarity_2(m, n, movieRatings)
movie_sim = math.exp(common_user/max_common - 1) * sim
return movie_sim
# calculate the movieSimilarity using pre-calculated similarity and maxCommonMovie
def movieSimilarity2(m, n, movieRatings, similarity_m_2):
max_common = movieRatings[m-1]['max_common']
common_user = float(len(set(movieRatings[m-1]) & set(movieRatings[n-1])))
sim = similarity_m_2[m][n]
movie_sim = sim > 0 and math.exp(common_user/max_common - 1) * sim or 0
return movie_sim
# The function returns the list of (movie ID, similarity)-pairs for the k movies
# which are most similar to movie m. The movie m itself will be excluded from
# candidates being considered by this function.
# The new similarity between movies is computed by a call to the movieSimilarity function.
def movieKNearestNeighbors(m, movieRatings, k):
sim_movie_list = list() # a list of (similarity, movie ID)-pairs
movie_sim_list = list() # a list of (movie ID, similarity)-pairs
for i in xrange(len(movieRatings)):
sim = 0
if i != m-1:
sim = movieSimilarity(m, i+1, movieRatings)
sim_movie_list.append((sim, i+1))
sim_movie_list.sort()
sim_movie_list.reverse()
for i in sim_movie_list[:k]:
movie_sim_list.append((i[1], i[0]))
return movie_sim_list
# calculate the movieKNN using pre-calculated similarity
def movieKNearestNeighbors2(m, movieRatings, similarity_m):
sim_movie_list = list() # a list of (similarity, movie ID)-pairs
movie_sim_list = list() # a list of (movie ID, similarity)-pairs
for i in xrange(len(movieRatings)):
sim = 0
if i != m-1:
sim = movieSimilarity2(m, i+1, movieRatings, similarity_m)
sim_movie_list.append((sim, i+1))
sim_movie_list.sort()
sim_movie_list.reverse()
return sim_movie_list
# The function predicts a rating by user u for movie m.
# It uses the ratings of the list of friends to come up with a rating of m by u according to formula.
# The argument corresponding to friends is computed by a call to the movieKNearestNeighbors function.
def movieCFRatingPrediction(u, m, movieRatings, friends):
# Construct a dictionary, whose keys are movieID and
# whose values are (similarity, mean_rating)-pairs.
movie_dict = dict()
for i in friends:
movie_dict.setdefault(i[0], list())
movie_dict[i[0]].append(i[1])
mean_rating = meanMovieRating(i[0], movieRatings)
movie_dict[i[0]].append(mean_rating)
rating = meanMovieRating(m, movieRatings)
sum_1 = sum_2 = 0.0
for i in friends:
if u in movieRatings[i[0]-1]:
sum_1 += (movieRatings[i[0]-1][u] - movie_dict[i[0]][1]) * movie_dict[i[0]][0]
sum_2 += abs(movie_dict[i[0]][0])
if sum_2 == 0:
return rating
else:
rating += sum_1 / sum_2
return rating
# This function returns the average of predicted ratings computed by userCFRatingPrediction function
# and movieCFRatingPrediction function.
def averageCFRatingPrediction(u, m, userRatings, movieRatings, friends_user, friends_movie):
rating_user = userCFRatingPrediction(u, m, userRatings, friends_user)
rating_movie = movieCFRatingPrediction(u, m, movieRatings, friends_movie)
average_rating = (rating_user + rating_movie) / 2
return average_rating
# The function evaluates each prediction algorithm by using an 80-20 split
# of the ratings into training and testing sets.
# To make sure that the reported rmse values are reliable, the process will be
# performed 10 repetitions. The average rmse value of each prediction algorithm
# (averaged over the 10 repetitions) will be written into a file "output_ec.txt".
def averageTenRuns():
numUsers = 943
numItems = 1682
numRatings = 100000
testPercent = 0.2
ratingList = readRatings()
times = 10
value_rmse = [[0.] * times for i in range(19)]
for time in xrange(times): # repeat ten times
[trainingSet, testSet] = partitionRatings(ratingList, testPercent)
[rLu, rLm] = createRatingsDataStructure(numUsers, numItems, trainingSet)
actualRatings = list()
predictedRatings = list()
for i in xrange(5):
predictedRatings.append(list())
users = sorted(set([e[0] for e in testSet]))
similarity_m = [[0.]*(numUsers+1) for i in range(numUsers+1)]
movies = sorted(set([e[1] for e in testSet]))
similarity_m_2 = [[0.]*(numItems+1) for i in range(numItems+1)]
for n, u in enumerate(users):
for v in users[n+1:]:
s = similarity(u, v, rLu)
similarity_m[u][v] = s
similarity_m[v][u] = s
for i, m in enumerate(movies):
for n in movies[i+1:]:
s = similarity_2(m, n, rLm)
similarity_m_2[m][n] = s
similarity_m_2[n][m] = s
#sys.stdout.write("\r{}_{}".format(m, n))
#sys.stdout.flush()
for n, i in enumerate(testSet):
u, m, r = i
actualRatings.append(r)
k_values = [(0, 0), (25, 25), (300, 300), (500, 500), (numUsers, numItems)]
friends_user = userKNearestNeighbors2(u, rLu, similarity_m)
friends_movie = movieKNearestNeighbors2(m, rLm, similarity_m_2)
for nk, k in enumerate(k_values):
friends_user_k = [(e[1], e[0]) for e in friends_user[:k[0]]]
friends_movie_k = [(e[1], e[0]) for e in friends_movie[:k[1]]]
predictedRatings[nk].append(averageCFRatingPrediction(u, m, rLu, rLm, friends_user_k, friends_movie_k))
#sys.stdout.write("\r{}_{}".format(time, n))
#sys.stdout.flush()
for i in xrange(5):
value_rmse[i][time] = rmse(actualRatings, predictedRatings[i])
# compute the average rmse value of each prediction algorithm
# (averaged over the 10 repetitions)
average_rmse = [sum(v)/times for v in value_rmse]
with open('output_ec.txt', 'w') as f:
f.write("New Collaborative Filtering Rating prediction Average RMSE (friends = 0): " + str(average_rmse[0]) + "\n")
f.write("New Collaborative Filtering Rating prediction Average RMSE (friends = 25): " + str(average_rmse[1]) + "\n")
f.write("New Collaborative Filtering Rating prediction Average RMSE (friends = 300): " + str(average_rmse[2]) + "\n")
f.write("New Collaborative Filtering Rating prediction Average RMSE (friends = 500): " + str(average_rmse[3]) + "\n")
f.write("New Collaborative Filtering Rating prediction Average RMSE (friends = all): " + str(average_rmse[4]) + "\n")
# Main program
if __name__ == '__main__':
averageTenRuns()
|
from classes.dictionary import Languaje
class English(Languaje):
def __init__(self):
super().__init__()
self.words = {
'article': {
'the',
'a',
'an'
},
'verb': {
'regular': {
'talk',
'walk',
'add',
'earn',
'ignored',
'join',
'call',
'work'
},
'irregular': {
'be',
'begin',
'can',
'buy',
'run',
'go',
'know',
'see'
},
'past_irregular': {
'began',
'bought',
'ran',
'could',
'went',
'knew',
'saw'
}
},
'noun': {
'book',
'job',
'car',
'table',
'man',
'number',
'people',
'vegetables'
},
'adjective': {
'happy',
'tall',
'good',
'job',
'blue'
},
'pronoun': {
'first': {
'i'
},
'second': {
'you',
},
'third': {
'she',
'he',
'it'
},
'plural': {
'they',
'we',
}
},
'adverbs': {
'frequency': {
'always',
'often',
'sometimes',
'rarely',
'never'
},
'place': {
'here',
'there'
},
'way': {
'well',
'slowly',
'quickly'
}
},
'connector': {
'and',
'also',
'too'
},
'preposition': {
'in',
'on',
'at',
'after',
'into',
}
}
def get_grammar(self):
# VERBOS
regular_verbs = self.parse_obj(self.words['verb'].get('regular'))
irregular_verbs = self.parse_obj(self.words['verb'].get('irregular'))
past_irregulars = self.parse_obj(self.words['verb'].get('past_irregular'))
verbs = regular_verbs + "| " + irregular_verbs
# BASICS
articles = self.parse_key('article')
nouns = self.parse_key('noun')
adjetives = self.parse_key('adjective')
connector = self.parse_key('connector')
prepositions = self.parse_key('preposition')
# PRONOMBRES
pro_f = self.parse_obj(self.words['pronoun'].get('first'))
pro_s = self.parse_obj(self.words['pronoun'].get('second'))
pro_f_s = pro_f + "| " + pro_s
pro_third = self.parse_obj(self.words['pronoun'].get('third'))
pro_plural = self.parse_obj(self.words['pronoun'].get('plural'))
# ADVERBIOS
adv_frequency = self.parse_obj(self.words['adverbs'].get('frequency'))
self.grammar = """
sentence: present_simple_af -> presente_simple_afirmativo
| present_simple_ne -> presente_simple_negativo
| present_simple_interrogative -> presente_simple_interrogativo
| tp_present_simple_af -> presente_simple_tercera_persona_afirmativo
| tp_present_simple_ne -> presente_simple_tercera_persona_negativo
| tp_present_simple_interrogative -> presente_simple_tercera_persona_interrogativo
| simple_past_positive -> pasado_simple_positivo
| article -> articulo
| literal_verb -> verbo
| past_verb -> verbo_pasasdo
| tp_verb -> verbo_tercera_persona
| noun -> sustantivo
| pro_f_s -> pronombre_primera_o_segunda_persona
| pro_third -> pronombre_tercera_persona
| adj -> adjetivo
// PRESENTE SIMPLE
present_simple_af: pro_f_s (adv_freq)? verb
| article noun to_be_t adj
| pro_f to_be_f adj
| pro_s to_be_s adj
| pro_plural to_be_plural adj
present_simple_ne: pro_f_s ne_fs_auxverb verb
present_simple_interrogative: af_fs_auxverb pro_f_s verb sym_interrogative
///
// PRESENTE SIMPLE Tercera persona
tp_present_simple_af: pro_third (adv_freq)? tp_verb
| pro_third to_be_t adj
tp_present_simple_ne: pro_third ne_tp_auxverb verb
tp_present_simple_interrogative: af_tp_auxverb pro_third verb sym_interrogative
///
/// PASADO SIMPLE
simple_past_positive: pro_f_s (adv_freq)? past_verb
//
// BASICS
article: ARTICLE
verb: VERB
literal_verb: VERB
connector: CONNECTOR
noun: NOUN
popper_noun: POPPER_NOUN
adj: ADJ
object: NOUN | POPPER_NOUN
sym_interrogative: SYMBOL_INTERROGATIVE
pro_f: PRONOUN_F
pro_s: PRONOUN_S
pro_third: PRONOUN_THIRD
pro_plural: PRONOUN_PLURAL
/// VERBO TO BE
to_be_f: TO_BE_F
to_be_s: TO_BE_S
to_be_t: TO_BE_T
pa_to_be_f_t: PA_TO_BE_F_T
pa_to_be: PA_TO_BE
to_be_plural: TO_BE_PLU
//
adv_freq: ADV_FREQUENCY
preposition: PREPOSITION
/// FRASE BASICA
oration: (preposition)? (article)? object
//
///
/// DERIVADOS PRIMERA/SEGUNDA PERSONA
pro_f_s: PRONOUN_F_S
af_fs_auxverb: AF_FS_AUXVERB
ne_fs_auxverb: NE_FS_AUXVERB
//
/// DERIVADOS TERCERA PERSONA
tp_verb: VERB + "s"
af_tp_auxverb: AF_TP_AUXVERB
ne_tp_auxverb: NE_TP_AUXVERB
//
/// DERIVADOS VERBOS
past_verb: REGULAR_VERB + "d" | REGULAR_VERB + "ed" | IRREGULAR_VERB_PAST
//
OBJECT: NOUN
ARTICLE: {}
CONNECTOR: {}
VERB: {}
REGULAR_VERB: {}
IRREGULAR_VERB: {}
IRREGULAR_VERB_PAST: {}
NOUN: {}
ADJ: {}
POPPER_NOUN: WORD
PRONOUN_F_S: {}
PRONOUN_F: {}
PRONOUN_S: {}
PRONOUN_THIRD: {}
PRONOUN_PLURAL: {}
ADV_FREQUENCY: {}
PREPOSITION: {}
TO_BE_F: "am"
TO_BE_S: "are"
TO_BE_T: "is"
PA_TO_BE_F_T: "was"
PA_TO_BE: "were"
TO_BE_PLU: TO_BE_S
// AUXILIARES
AF_FS_AUXVERB: "do"
NE_FS_AUXVERB: "dont"
AF_TP_AUXVERB: "does"
NE_TP_AUXVERB: "doesnt"
///
SYMBOL_INTERROGATIVE: "?"
%import common.WS
%import common.WORD
%ignore " "
%ignore WS
""".format(
# BASICS
articles,
connector,
# VERBS
verbs,
regular_verbs,
irregular_verbs,
past_irregulars,
# END_VERBS
nouns,
adjetives,
# PRONOMBRES
pro_f_s,
pro_f,
pro_s,
pro_third,
pro_plural,
# ADVERBIOS
adv_frequency,
#
prepositions
)
return self.grammar |
#XXX: begin from line 0
# index (mapping) from the line number, begin from 0
def index(text):
index0 = {}
i = 0
for line in xrange(len(text)):
if text[line].startswith('@'):
index0[i] = line
i += 1
return index0
# from 1 to 2
def mapping(text):
index0 = {}
index0 = index(text)
indexall = {}
for i in xrange(len(index0)):
line = index0[i]
line += 1
temp1 = line
while (not text[line].startswith('@')) and (line!=len(text)-1):
line += 1
temp2 = line - 1
#print 'temp2',temp2
indexall[i] = (temp1,temp2)
return indexall
# from multiple to 1
def backmapping(text):
index0 = {}
index0 = index(text)
indexall = {}
for i in xrange(len(index0)):
line = index0[i]
line += 1
temp1 = line
while (not text[line].startswith('@')) and (line!=len(text)-1):
line += 1
temp2 = line - 1
#print 'temp2',temp2
for j in xrange(temp1,temp2+1):
indexall[j] = i
return indexall
|
#input = raw_input("please enter file name : ")
input = 'mbox-short.txt'
try:
file = open(input)
except:
print 'cant open file:' , input
exit()
total = []
count = 0
for word in file:
word = word.rstrip()
words = word.split()
if words == [] : continue
if words[0] != 'From' : continue
print words[1]
count = count + 1
print 'There were', count, "lines in the file with From as the first word"
#print sorted(total)
|
import pandas as pd
"""
How to read a tabular data file using pandas?
"""
orders = pd.read_table('http://bit.ly/chiporders')
orders.head()
movieusers = pd.read_table('http://bit.ly/movieusers', delimiter='|', names=['user_id', 'age', 'gender','occupation','zipcode'])
print(movieusers.head()) |
import numpy as np
### 0s,1s, identical matrixes
#Initialize all zero's(0s) matrix which default dtype='float64':
zero_matrix = np.zeros((2,2))
print("Get 2d 0s matrix", zero_matrix)
#Initialize all zero's(0s) matrix which default dtype='float64':
one_matrix = np.ones((2,2))
print("Get 2d 1s matrix", one_matrix)
#Initialize all elements by other value(datatype depend of value):
other_matrix = np.full((2,2), 55)
print("Get 2d matrix with other value", other_matrix)
#Initialize all elements by other value(datatype depend of value):
otherlike_matrix = np.full_like((2,3), 4, dtype='float16')
print("Get 2d matrix with other value", otherlike_matrix)
#Initializing random number
random1 = np.random.rand(2,3)
print("random1", random1)
#Initializing integer random number with 3, 7 range
random2 = np.random.randint(3,7,size=(3,3))
print("random2", random2)
#Initialize random array with take size from another matrix
random3 = np.random.random_sample(other_matrix.shape)
print("random3: ", random3)
#Get Identity matrix:
iden1 = np.identity(4, dtype='int8')
print("Identity array", iden1)
#Repeat array on 1d :
arr1 = np.array([1,2,3])
repeat_array = np.repeat(arr1,3, axis=0)
print("repeat array: ", repeat_array)
#Repeat array on 2d :
arr1 = np.array([[1,2,3]])
repeat_array1 = np.repeat(arr1,3, axis=0)
print("repeat array on x and y axis: ", repeat_array1)
repeat_array2 = np.repeat(arr1,3, axis=1)
print("repeat array on x axis: ", repeat_array2)
|
#!/usr/bin/env python
list_1 = [1, 1, 2, 3, 5, 8]
# Problem 1
# Find last element of a list
# solution 1
last_element = list_1[-1]
print("The last element of the list is %i." % last_element)
# solution 2
last_element2 = list_1[len(list_1) - 1]
print("The last element of the list is %i." % last_element2)
# solution 3
def last_element(xs):
if len(xs) == 1:
return xs
return last_element(xs[1:])
final_list_last = last_element(list_1)
print("The last element of the list is %i." % final_list_last[0])
# Problem 2
# Find the last but one element of a list
last_but_one = list_1[-2]
print("The last but one element of the list is %s." % last_but_one)
# solution 2
last_element2 = list_1[len(list_1)-2]
print("The last but one element of the list is %s." % last_element2)
# solution 3
def last_element_but_one(xs):
if len(xs) == 2:
return xs
return last_element_but_one(xs[1:])
final_list_last_but_one = last_element_but_one(list_1)
print("The last element but one of the list is %i." % final_list_last_but_one[0])
# Problem 3
# Find the Kth element of a list.
# solution 1
kth_element = input("Enter the index number of the element you want: ")
if kth_element > len(list_1):
print("This is not a valid index, too big.")
else:
print("The Kth element of the list is %i." % list_1[kth_element])
# Problem 4
# Find the number of elements of a list
# solution 1
print("The list contains %i elements." % len(list_1))
# Problem 5
# Reverse a list
# solution 1
def reverse_recursive(xs):
if xs == []:
return []
return reverse_recursive(xs[1:]) + [xs[0]]
print("The reverse list is: %s" % reverse_recursive(list_1))
# solution 2
def reverse_for_loop(xs):
list_reverse = []
for current_element in xs:
list_reverse.insert(0, current_element)
return list_reverse
print("The reverse list is: %s" % reverse_for_loop(list_1))
# solution 3
def reverse_new_list(xs):
new_list = list(xs)
for i in range(0, len(xs)):
index = len(xs) - i - 1
new_list[index] = xs[i]
return new_list
print(reverse_new_list(list_1))
# Problem 6
# Find out whether a list is a palindrome
# solution 1
def check_palindrome_recursive(xs):
reverse_list = reverse_recursive(xs)
if reverse_list == xs:
return True
else:
return False
list_2 = [1, 4, 3, 2, 1]
print(check_palindrome_recursive(list_2))
# solution 2
def check_palindrome_for_loop(xs):
reverse_list = reverse_recursive(xs)
for current_element in xs:
if reverse_list[current_element] == xs[current_element]:
return True
else:
return False
print(check_palindrome_for_loop(list_2))
# Problem 7
# Flatten a nested list structure
# solution 1
list_3 = [[1, 1], [2], [3, [5, 8]]]
newlist = []
for current_element in list_3:
newlist.extend(current_element)
print(newlist)
# solution 2: with list comprehension
#newlistcomp = []
#newlistcomp = [newlistcomp.extend(current_element) for current_element in list_3]
#print("With list comprehension: %s" % newlistcomp)
# Problem 14
# Duplicate the elements of a list
list_4 = ["a", "b", "c", "c", "d"]
# solution 1
output = []
for current_element in list_4:
output.extend(current_element + current_element)
print(output)
# solution 2: with list comprehension
#output_comp = []
#output_comp = [output_comp.extend(current_element + current_element) for current_element in list_4]
#print("With list comprehension: %s" % output_comp)
# Problem 17
# Split a list into two parts.
# The length of the first part is given. Use a Tuple for your result
list_5 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
split = 3
list_5_split_tuple = (list_5[0:split], list_5[split:])
print(list_5_split_tuple)
# Problem 18
# Given two indices, I and K, the slice is the list containing the elements
# from and including the Ith element up to but not including the Kth element
# of the original list. Start counting the elements with 0
# index for the start of the list (including the indexed element)
i = 3
# index for the end of the list (excluding the indexed element)
k = 7
list_5_sublist = list_5[i:k]
print(list_5_sublist)
|
#!/usr/bin/env python
test = [{
'name': 'Fabrizio',
'age': 32
}, {
'name': 'Adam',
'age': 13
}]
# Filter
print(filter(lambda x: x['age'] > 20, test))
# List comprehension
print([x for x in test if x['age'] > 20])
# Iteration
result = []
for x in test:
if x['age'] > 20:
result.append(x)
print(result)
# Reduce
print(reduce(lambda x, y: y['age'] + x['age'], test) / float(len(test)))
# Map-Sum
print(sum(map(lambda x: x['age'], test)) / float(len(test)))
# Iteration
average, size = 0.0, 0
for x in test:
average += x['age']
size += 1
average /= size
print(average)
|
#!/usr/bin/env python
import random
def initialise_field(width_local, height_local):
"""
Seed stage
Initialises, e.g. populates, a field with a population of randomly selected alive
(1) or dead (0) cells
"""
return [[random.randint(0, 1) for i in range(width_local)] for y in range(height_local)]
# FIXME: What is "z"??? That's not meaningful
def get_cell_status(z):
"""
List of parameters:
Any live cell with fewer than two live donald_duck dies, as if by under-
Any live cell with two or three live donald_duck lives on to the next
generation.
population.
Any live cell with more than three live donald_duck dies (overpopulation)
Any dead cell with exactly three live donald_duck becomes a live cell
(reproduction)
"""
def get_treasure_positions(scrooge):
"""
Returns the position of a cell's donald_duck as a list
"""
donald_duck = []
for mickey in range(0, len(scrooge)):
goofy = int(mickey)
for gold in range(0, mickey):
minnie = int(gold)
treasure_1 = goofy - 1
treasure_2 = goofy + 1
treasure_3 = scrooge[goofy - 1][minnie - 1]
treasure_4 = scrooge[goofy - 1][minnie]
treasure_5 = scrooge[goofy - 1][minnie + 1]
treasure_6 = scrooge[goofy + 1][minnie - 1]
treasure_7 = scrooge[goofy + 1][minnie]
treasure_8 = scrooge[goofy + 1][minnie + 1]
# adds to the list the donald_duck of a cell
donald_duck.append([treasure_1, treasure_2,
treasure_3, treasure_4, treasure_5, treasure_6,
treasure_7, treasure_8])
return donald_duck
# Defines the dimensions of the field
width = 7
height = 10
field = initialise_field(width, height)
print(field)
# displays the field mickey by mickey
for y in range(height):
print(field[y])
print(get_treasure_positions(field))
|
#!/usr/bin/env python
import math
def sum(xs):
"""
Returns the sum of numbers contained in a list
"""
result = 0.0
for current_element in xs:
result += current_element
return result
def average(xs):
"""
Returns the average of numbers contained in a list
"""
result = 0.0
samplesize = len(xs)
for current_element in xs:
result += current_element
return result / samplesize
def sd(xs):
"""
Returns the standard deviation of a list of numbers
"""
deviation_list = []
for current_element in xs:
deviation = (current_element - average(xs)) ** 2
deviation_list.append(deviation)
return average(deviation_list)
def one_sample_t_value(xs, mu):
"""
Returns the T value for a T-test for numbers in a list and
the reference value
"""
mean = average(xs)
stdev = sd(xs)
samplesize = len(xs)
return (mean - mu)/(stdev / math.sqrt(samplesize))
print(sum([2, 5]))
print(average([2, 5]))
print(sd([2, 7, 3]))
print(one_sample_t_value([2, 7, 4, 12], 15))
|
#!/usr/bin/env python
import csv
# Step1
# Reads the data from the original file and prepares them for processing
# 1.1 Reads line by line
# 1.2 Extracts the 3 fields to be later processed
# 1.3 Stores the fields/lines in memory
original = "test.csv"
# Opens the original csv file to transform
with open(original, "rb") as csv_file:
data = csv.reader(csv_file, delimiter = ",")
# Checks if original file is empty
if data == "":
print("Error: empty file")
# Phase 1.1: Reads line by line
line_count = 0
for row in data:
if line_count == 0:
header = ','.join(row)
print ("Header is: %s" % header)
line_count += 1
else:
print(','.join(row))
line_count += 1
# Phase 1.2: Field extraction
fieldnames =
|
#!/usr/bin/env python
import random
import os
import time
def game_of_life(col, row):
"""
Returns the game of life
"""
field = initialise_field(col, row)
print_field(field)
while True:
next_generation = compute_next_generation(field)
os.system("clear")
print_field(next_generation)
time.sleep(0.8)
field = next_generation
return print_field(next_generation)
def print_field(field):
"""
Returns the field as a two dimensional array
"""
field
for line in range(len(field)):
print (" ".join(map(str, field[line])))
def initialise_field(col, row):
"""
Seed stage
Initialises, e.g. populates, a field with a population of randomly selected alive
(1) or dead (0) cells
"""
return [[random.randint(0, 1) for i in range(col)] for y in range(row)]
def get_neighbours(field, row, col):
"""
Returns the neighbours of a cell
"""
neighbour_list = []
# manage special cases for the next col and row
# last col and row
if row == len(field) - 1:
next_row = 0
else:
next_row = row + 1
if col == len(field[row]) - 1:
next_col = 0
else:
next_col = col + 1
neighbour_list.append(field[row - 1][col - 1])
neighbour_list.append(field[row - 1][col])
neighbour_list.append(field[row - 1][next_col])
neighbour_list.append(field[row][col - 1])
neighbour_list.append(field[row][next_col])
neighbour_list.append(field[next_row][col - 1])
neighbour_list.append(field[next_row][col])
neighbour_list.append(field[next_row][next_col])
return neighbour_list
def compute_next_generation(field):
"""
Return the field with the next generation's cells' status
"""
next_generation = []
for row in range(len(field)):
next_generation_by_row = []
for col in range(len(field[row])):
list_neighbours = get_neighbours(field, row, col)
cell = field[row][col]
#print(list_neighbours)
cell_next_generation = get_cell_status(cell, list_neighbours)
next_generation_by_row.append(cell_next_generation)
next_generation.append(next_generation_by_row)
return next_generation
def get_cell_status(cell, list_neighbours):
"""
Gets the cell's next generation status on the basis of:
- the present cell's status
- the number of live neighbours
"""
# a cell is alive is its value is 1, dead if its value is 0
# counts the number of live neighbours
counter_live_neighbours = 0
for neighbour in list_neighbours:
if neighbour == 1:
counter_live_neighbours += 1
#print(counter_live_neighbours)
# parameters
# live cell
if cell == 1:
# underpopulation
if counter_live_neighbours < 2:
cell = 0
# survives
elif 2 <= counter_live_neighbours <= 3:
cell = 1
# overpopulation
elif counter_live_neighbours > 3:
cell = 0
# dead cell
elif cell == 0 and counter_live_neighbours == 3:
cell = 1
return cell
# MAIN PROGRAM STARTS HERE
# Defines the dimensions of the field
col = 15
row = 15
game_of_life(row, col)
# testing compute_next_generation
test_field = [
[0, 1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12, 13],
[14, 15, 16, 17, 18, 19, 20]
]
#print(compute_next_generation(test_field))
# testing get_cell_status
test_cell_status = [
[1, 0, 0, 0, 1],
[0, 1, 1, 0, 0],
[0, 0, 1, 1, 0]
]
#print(test_cell_status)
#game_of_life = compute_next_generation(test_cell_status)
#print_field(game_of_life)
|
#!/usr/bin/env python
# Exercise: generate a script that transform a list of nested lists into one list
list1 = [[2, 4, 5], [12, 4, 7], [1, 4]]
newlist = []
for current_element in list1:
newlist.extend(current_element)
print(newlist)
|
"""
CSci 39542: Introduction to Data Science
Program 2: Senator's Name
Jiaming Zheng
jiaming.zheng745@myhunter.cuny.edu
Resources: https://www.geeksforgeeks.org/how-to-select-multiple-columns-in-a-pandas-dataframe/
"""
import pandas as pd
input_File = input("Enter input file name: ")
output_File = input("Enter output file name: ")
legis = pd.read_csv(input_File)
data = []
for index, row in legis.iterrows():
if pd.notnull(row['senate_class']):
data.append([row['first_name'], row['last_name']])
df = pd.DataFrame(data, columns = ['first_name','last_name'])
df.to_csv(output_File, index = False) |
print('with a for-loop')
for i in range(1, 11):
print('🧇' * i)
print('with a while-loop')
n = 1
while n < 11:
print('🌯' * n)
n += 1
print('with nested for- and while-loops')
x = 1
z = ''
for y in range(1, 11):
while x <= y:
z += '🥑'
x += 1
print(z) |
squares = { x**2 for x in range(10) }
no_dupes_hello = { v.upper() for v in 'hello' }
def are_all_vowels_in_string(string):
return len( {char for char in string if char in 'aeiou'} ) == 5
print(squares)
print(no_dupes_hello)
print(are_all_vowels_in_string('hello'))
print(are_all_vowels_in_string('aeiou'))
print(are_all_vowels_in_string('sequoia'))
print(are_all_vowels_in_string('asegagewewei3osweweeefut4')) |
from car import Car, ElectricCar
my_car = Car() #Class Car or my_car
print my_car.engineSize #Engine size is public (ie has no __)and will be printed
print my_car.getMake() #This will print if i add [def getMake(self): return self.__make]
#print my_car.__make #Error message bc "make" is private (ie has __)
print my_car.getColour()
#print my_car.__colour #Will not print "same reason in line 27
print my_car.getMileage()
#print my_car.__mileage #Will not print "same reason in line 27
my_car.engineSize = ("2.5L")
print my_car.engineSize
my_car.setMake("BMW")
print my_car.getMake()
my_car.setColour("Silver")
print my_car.getColour()
my_car.setMileage(50)
print my_car.getMileage()
my_car.move(10)
print my_car.getMileage()
my_car.paint("Blue")
print my_car.getColour()
electric_car = ElectricCar() #Class ElectricCar or electric_car
print electric_car.getNumberFuelCells()
electric_car.move(20)
print electric_car.getMileage()
#my_car.getNumberFuelCells() #error bc my_car does not have NumberofFuels |
#!/usr/bin/python
# Date : 31/12/2018
# Author : Syed Abdullah Jelani
# Version : v.1
# Description :Hangman word game.
import random
import os
import sys
os.chdir("C:\\Users\\Syed Abdullah Jelani\\Desktop\\RGB to grayscale converter pics\\hangman")
word_file = open("words.txt", "r")
def parser(word_file):
word_list = list(word_file)
word_list =[s.replace('\n', '') for s in word_list]
word_list= [ x for x in word_list if len(x)>4 ]
return word_list
def hangman(word_file):
word_list = parser(word_file)
yo = input("Would you like to play Hangman? Y/N")
while yo != "Y" or "N":
if yo == "N":
return("Have a good day")
break
elif yo != "Y" and yo !="N" :
print("Type either Y/N my guy" )
yo = input("Would you like to play Hangman? Y/N")
else:
word = random.choice(word_list)
tape = list("_" * len(word))
tape[0] = word[0]
lives = 4
i=0
while lives!=0:
guess = input("Guess a lowercase letter!!! " + "\n" + str(tape));
if str(guess) in word:
indices = [a for a, x in enumerate(word) if x == guess]
for a in indices:
tape[a] = guess
word2 = "".join(tape)
if word2 == word:
return(word2 + " Congrats You won!!")
elif str(guess)== "EXIT":
sys.exit()
elif str(guess) == "NEW WORD":
i=0
break
elif str(guess) == "HINT" :
if i == 0:
tape[tape.index("_")] = word[tape.index("_")]
i+=1
else:
print("YOU ONLY GET ONE HINT!!!!")
else:
lives = lives - 1
print("Try Again! Lives left:", lives)
if lives ==0:
return("The correct word was : " + str(word))
print(hangman(word_file))
###DONE### |
from dataclasses import dataclass
@dataclass
class CacheNode:
key: int = 0
val: int = 0
prev: 'CacheNode' = None
next: 'CacheNode' = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.cache = {}
self.list = None
self.head = CacheNode()
self.tail = CacheNode
self.head.next = self.tail
self.tail.prev = self.head
def _add_node(self, node):
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _remove_node(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _move_to_front(self, node):
self._remove_node(node)
self._add_node(node)
def _remove_tail(self):
last = self.tail.prev
self._remove_node(last)
return last
def get(self, key: int):
node = self.cache.get(key)
if node is None:
return -1
self._move_to_front(node)
return node.val
def put(self, key: int, val: int):
node = self.cache.get(key)
if node is None:
node = CacheNode(key, val)
if self.size >= self.capacity:
last = self._remove_tail()
del self.cache[last.key]
self.size -= 1
self._add_node(node)
self.cache[key] = node
self.size += 1
else:
self._move_to_front(node)
node.val = val
|
from collections import deque
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# empty tree
class Solution:
def find_height(self, root: TreeNode) -> int:
if root is None:
return 0
else:
return 1 + max(self.find_height(root.left), self.find_height(root.right))
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
# find the height of the tree so we know how many levels are
# this allows us to create final list that will hold the result
height = self.find_height(root)
result = [[] for _ in range(height)]
level = 0
queue = deque()
queue.append((root, level))
while queue:
# remove element
elem, level = queue.popleft()
# add element to the result list
result[level].append(elem.val)
# add children to the queue increasing level
if elem.left:
queue.append((elem.left, level + 1))
if elem.right:
queue.append((elem.right, level + 1))
return result
if __name__ == "__main__":
sol = Solution()
root = TreeNode(val=-1)
cur = root
for i in range(10):
cur.right = TreeNode(val=i)
cur = cur.right
assert sol.levelOrder(root) == [[-1], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
print("All done")
|
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
class Rational(object):
def __init__(self,p,q):
self.p=p
self.q=q
def __add__(self,r):
return Rational(self.p*r.q+self.q*r.p,self.q*r.q)
def __sub__(self,r):
return Rational(self.p*r.q-r.p*self.q,self.q*r.q)
def __mul__(self,r):
return Rational(self.p*r.p,self.q*r.q)
def __div__(self,r):
return Rational(self.p*r.q,self.q*r.p)
def __str__(self):
g=gcd(self.p,self.q)
return '%s/%s' % (self.p/g,self.q/g)
__repr__=__str__
def __int__(self):
return self.p//self.q
def __float__(self):
return float(self.p)/self.q
r1,r2=Rational(1,4),Rational(1,2)
print r1+r2,r1-r2,r1*r2,r1/r2
print int(r1),float(r1)
r3=Rational(6,2)
print int(r3),float(r3) |
# -*-coding=utf-8 -*-
#def move(n,a,b,c):
# if n==1:
# return a,'-->',c
# move(n-1,a,c,b)
# a,'-->',c
# move(n-1,b,a,c)
#print move(4,'A','B','C)
#在交互模式下,return的结果会自动打印出来,而作为脚本单独运行时则需要print函数才能显示。
def move(n,a,b,c):
if n==1:
print a,'-->',c
return
move(n-1,a,c,b)
print a,'-->',c
move(n-1,b,a,c)
move(2,'A','B','C') |
# -*- coding=utf-9 -*-
#比较函数的定义是,传入两个待比较的元素 x, y,如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0
def quene(x,y):
if x.upper()<y.upper():
return -1
if x.upper()>y.upper():
return 1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'],quene) |
def average(*args):
if len(args)==0:
print 0
return
sum=0.0
n=0
for elements in args:
sum=sum+elements
return sum/len(args)
print average(1,2,3)
print average(1,2)
print average() |
import statistics
from math import ceil
def histogram(dataset,height=8,width=80,full="X",empty="_"):
"""Given a list of data, draws an histogram
of given width and height with given characters
Returns if histogram was succesful"""
mv = min(dataset)
Mv = max(dataset)
print("[",mv,":",Mv,"]")
if(mv==Mv):
print(elem,"has no interval")
return False
if(width!=None):
counter = [0]*width
for n in dataset:
counter[int((n-mv)*float(width-1)/(Mv-mv))]+=1
#print("Biggest class size:",max(counter))
else:
data = sorted(set(dataset))
counter = len(data)*[0]
for n in dataset:
counter[data.index(n)]+=1
mc = max(counter)
for i in range(height):
print("".join((height-val*height/mc < i+1) and full or empty for val in counter))
print()
return True
def parse_database(noisy=True):
"""Opens creditcard.csv and read the data.
The continuous data is discretised into
-1,0,1 based on the bottom 5% and top 5% of the values
Returns a list containing the name of the attributes
and a list containing data arranged by attribute then by line
Prints stuff if noisy=True
"""
f = open("creditcard.csv")
classes = f.readline().strip().replace('"',"").split(",")
#[classes.index[""]] #nom de la classe
database = [[] for x in classes]
if(noisy): print(classes)
maxlines = float("inf") # 10000 #
for line in f:
line = line.strip()
line = line.replace('"',"")
line = line.split(",")
line = [float(x) for x in line]
for i, elem in enumerate(line):
database[i].append(elem)
if(len(database[0])>=maxlines):
break
f.close()
if(noisy):
print("There are",len(database[0]),"data")
is_integer = []
for i, elem in enumerate(classes):
#lower = 25/100
#upper = 75/100
mev = statistics.mean(database[i])
dev = statistics.stdev(database[i])
print("---",elem,"---\nMin:",min(database[i]),"- Max:",max(database[i]))
print("Mean:",mev,"\nStandard Deviation:",dev)
#dataset = sorted(database[i])
if(noisy):
print("Histogram:")
if(not histogram(database[i])): #dataset
continue
if(elem=="Time"):
continue
if( elem=="Class"):
continue
if(elem=="Amount"):
classification = [5,15,50,100,500,1000,5000,10000,50000,100000,1000000,9999999999999999]
for index,elem in enumerate(database[i]):
a = database[i][index]
if(a==int(a)):
is_integer.append(1) #integer amount
else:
is_integer.append(0) #floating amount
for uplim in classification:
if a<uplim:
a = uplim
break
database[i][index] = a
"""if(noisy):
down = sorted(database[i])
mid = statistics.median(down)
histogram(down[:down.index(mid)])
"""
else:
for j in range(len(database[i])):
database[i][j]=int(ceil((database[i][j]-mev)/dev))
if(database[i][j])>3:
database[i][j]=4
if(database[i][j])<-3:
database[i][j]=-4
"""lbi = int(len(dataset)*lower) #lower bound index
ubi = int(len(dataset)*upper) #upper bound index
if( elem=="Class"): #or elem=="Time"): # or elem=="Amount"
continue
if(noisy):
print("Histogram by cutting the lowest and highest 25%:")
histogram(dataset[lbi:ubi])
lb = dataset[lbi] #lower bound
ub = dataset[ubi] #upper bound
for j in range(len(database[i])):
val = database[i][j]
if(val<lb):
database[i][j]=-1
elif(val<ub):
database[i][j]=0
else:
database[i][j]=1"""
if(noisy):
print("Histogram after discretisation:")
if(not histogram(database[i],width=None)):
continue
ldat = set(database[i])
print(len(ldat),"different values")
database = database[1:-1]+[is_integer]+[database[-1]]
classes = classes[1:-1]+["Integer_amount"]+[classes[-1]]
return classes,database
def main():
classes, database = parse_database(noisy=True)
#Note: it could be interesting to shift database from i;j to j;i
#Since we want to select specific lines
f = open("creditcard_discretised.csv","w")
f.write(",".join((x for x in classes)))
f.write("\n")
for i in range(len(database[0])):
line = ""
for j in range(len(classes)):
line+=str(int(database[j][i]))
line+=" ,"
line = line[:-1] + "\n"
f.write(line)
if __name__ == "__main__":
main()
|
import random
def word_to_guess():
list = ['banana','milan','prince','elite']
mysterious_word = random.randint(0,len(list)-1)
return list[mysterious_word]
def hint(mystery_word):
if mystery_word == 'banana':
return 'it is a famous fruit'
elif mystery_word == 'milan':
return 'it is a famous italian city'
elif mystery_word == 'prince':
return 'it is a famous black singer'
elif mystery_word == 'elite':
return 'it is a famous spanish tv show'
def guess_word(mystery_word):
attempt = 0
correct_player_input = False
for i in mystery_word:
print('_ ' , end='')
player_guess(mystery_word)
def player_guess(mystery_word):
winner_array=[]
for i in mystery_word:
winner_array.append(i)
print(len(winner_array))
attempt = len(mystery_word)
index=0
already_guessed = []
while index<attempt:
player_attpempt = input('\nEnter a letter you have '+ str (attempt-index) + ' attempt')
letter = player_attpempt[0]
for i in mystery_word:
if letter == i or i in already_guessed:
print(i, end='')
if i not in already_guessed:
already_guessed.append(i)
else:
print(' _ ', end='')
if len(already_guessed) == len(winner_array):
print('You won')
break
index+=1
|
#https://www.bogotobogo.com/python/python_graph_data_structures.php
#https://www.bogotobogo.com/python/python_Dijkstras_Shortest_Path_Algorithm.php
# 1. The distance of the route A-B-C.
# 2. The distance of the route A-D.
# 3. The distance of the route A-D-C.
# 4. The distance of the route A-E-B-C-D.
# 5. The distance of the route A-E-D.
# 6. The number of trips starting at C and ending at C with a maximum of 3 stops. In the sample data below, there are two such trips: C-D-C (2 stops). and C-E-B-C (3 stops).
# 7. The number of trips starting at A and ending at C with exactly 4 stops. In the sample data below, there are three such trips: A to C (via B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
# 8. The length of the shortest route (in terms of distance to travel) from A to C.
# 9. The length of the shortest route (in terms of distance to travel) from B to B.
# 10. The number of different routes from C to C with a distance of less than 30. In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.
# Split A into two nodes, called START and GOAL.
# For any edge A->x add an edge START->x
# For any edge y->A add an edge y->GOAL
# Keep all other edges unchanged.
import sys
import heapq
class Vertex:
def __init__(self, node):
self.id = node
# Connected nodes and their weights
self.adjacentNodes = {}
# Set distance to infinity for all nodes
self.distance = sys.maxint
# Mark all nodes unvisited
self.visited = False
# Predecessor
self.previous = None
def add_neighbor(self, neighbor, weight=0):
self.adjacentNodes[neighbor] = weight
def modify_neighbor(self,oldNeighbor,newNeighbor):
self.adjacentNodes[newNeighbor] = self.adjacentNodes.pop(oldNeighbor)
def get_connections(self):
return self.adjacentNodes.keys()
def get_id(self):
return self.id
def get_weight(self, neighbor):
return self.adjacentNodes[neighbor]
def set_distance(self, dist):
self.distance = dist
def get_distance(self):
return self.distance
def set_previous(self, prev):
self.previous = prev
def set_visited(self):
self.visited = True
def __str__(self):
return str(self.id) + ' adjacentNodes: ' + str([x.id for x in self.adjacentNodes])
class Graph:
def __init__(self):
self.vert_dict = {}
self.num_vertices = 0
def __iter__(self):
return iter(self.vert_dict.values())
def reset(self):
for v in self:
v.set_distance(sys.maxint)
v.set_previous(None)
v.visited = False
def node_split(self,node):
# Create a new node that is a lower-case version
miniMe = node.get_id().lower()
self.add_vertex(miniMe)
# For all vertices in graph
for v in self:
for w in v.get_connections():
if(w.get_id() == node.get_id()):
v.modify_neighbor(w,self.get_vertex(miniMe))
return
def merge_nodes(self,original, copy):
# Replace the copies in the edges with the original
for v in self:
for w in v.get_connections():
if(w.get_id() == copy.get_id()):
v.modify_neighbor(w,original)
# Reassign the distance to original node
original.set_distance(copy.get_distance())
# Remove the copy from the vertex list
del self.vert_dict[copy.get_id()]
return
def add_vertex(self, node):
if node not in self.vert_dict:
self.num_vertices = self.num_vertices + 1
new_vertex = Vertex(node)
self.vert_dict[node] = new_vertex
return new_vertex
else:
return
def remove_vertex(self,node):
if node not in self.vert_dict:
return
else:
#self.get_vertex(node) = None
self.vert_dict.pop(node)
return
def get_vertex(self, n):
if n in self.vert_dict:
return self.vert_dict[n]
else:
return None
def add_edge(self, frm, to, cost=0):
if frm not in self.vert_dict:
self.add_vertex(frm)
if to not in self.vert_dict:
self.add_vertex(to)
self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
#self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)
def get_vertices(self):
return self.vert_dict.keys()
def set_previous(self, current):
self.previous = current
def get_previous(self, current):
return self.previous
def dijkstra_shortest_path(agraph, start, target):
#print '''Dijkstra's shortest path'''
# Set the distance for the start node to zero
start.set_distance(0)
# If start and target are same nodes
# Split the node into two
needsMerging = False
if(start.get_id() == target.get_id()):
# Splits the node
# creating a clone at the ends of edges
agraph.node_split(start)
target = agraph.get_vertex(target.get_id().lower())
needsMerging = True
# Put tuple pair into the priority queue
unvisited_queue = [(v.get_distance(),v) for v in agraph]
heapq.heapify(unvisited_queue)
while len(unvisited_queue):
# Pops a vertex with the smallest distance
uv = heapq.heappop(unvisited_queue)
current = uv[1]
if(start.get_id() == target.get_id() and current.get_id == start.get_id()):
unvisited_queue.append(current)
pass
else:
current.set_visited()
#for next in v.adjacent:
for next in current.adjacentNodes:
# if visited, skip
if next.visited:
continue
new_dist = current.get_distance() + current.get_weight(next)
if new_dist < next.get_distance():
next.set_distance(new_dist)
next.set_previous(current)
#print 'updated : current = %s next = %s new_dist = %s' \
#%(current.get_id(), next.get_id(), next.get_distance())
#else:
#print 'not updated : current = %s next = %s new_dist = %s' \
#%(current.get_id(), next.get_id(), next.get_distance())
# Now undo the split by merging the two nodes into one again
if(needsMerging):
agraph.merge_nodes(start,target)
def shortest_path(v, path):
''' make shortest path from v.previous'''
if v.previous:
path.append(v.previous.get_id())
shortest_path(v.previous, path)
return
def custom_path_distance(agraph,path):
distance = 0
containsNeighbor = False
for x in range(0,len(path)-1):
#reset checker
containsNeighbor = False
# Get next vertex from list
vert = agraph.get_vertex(path[x])
for w in vert.get_connections():
# Get each edge
# Check if edge is
if(w.get_id() == path[x+1]):
distance = distance + vert.get_weight(w)
containsNeighbor = True
break
if(not containsNeighbor):
return 0
return distance
def count_paths(agraph,start,target,constraint,mode):
count = 0
# Mode for Max Distance NotIncl
if(mode == 0):
count = count_paths_max_distance(start,target,constraint,0,0)
# Mode for Exact Stops
if(mode == 1):
count = count_paths_exact_stops(start,target,constraint,0,0)
# Mode for Max Stops Incl
if(mode == 2):
count = count_paths_max_stops(start,target,constraint,0,0)
return count
def count_paths_max_distance(start,target,maxDist,currDist,pathCount):
# // If current vertex is same as destination,
# // then increment count
if (start.get_id() == target.get_id() and currDist > 0):
pathCount = pathCount + 1
for w in start.get_connections():
if(currDist + start.get_weight(w) < maxDist):
pathCount = count_paths_max_distance(w,target,maxDist,currDist + start.get_weight(w),pathCount)
return pathCount
def count_paths_exact_stops(start,target,exactStops,currStops,pathCount):
# // If current vertex is same as destination,
# // then increment count
if (start.get_id() == target.get_id() and currStops > 0 and currStops == exactStops):
pathCount = pathCount + 1
for w in start.get_connections():
if(currStops < exactStops):
pathCount = count_paths_exact_stops(w,target,exactStops,currStops + 1,pathCount)
return pathCount
def count_paths_max_stops(start,target,maxStops,currStops,pathCount):
# // If current vertex is same as destination,
# // then increment count
if (start.get_id() == target.get_id() and currStops > 0):
pathCount = pathCount + 1
#print 'here'
for w in start.get_connections():
if(currStops < maxStops):
pathCount = count_paths_max_stops(w,target,maxStops,currStops + 1,pathCount)
return pathCount
def import_graph(filename):
f = open(filename)
g = Graph()
line = f.readline()
edges = line.split(', ')
for e in edges:
info = list(e)
g.add_vertex(info[0])
g.add_vertex(info[1])
g.add_edge(info[0],info[1],int(''.join(info[2:])))
return g
if __name__ == '__main__':
#filename = raw_input()
g = import_graph("input.txt")
# print 'Graph data:'
# print 'Output #1: %d' %(custom_path_distance(g,['A','B','C'])) # Should be 9
# print 'Output #2: %d' %(custom_path_distance(g,['A','D'])) # Should be 5
# print 'Output #3: %d' %(custom_path_distance(g,['A','D','C'])) # Should be 13
# print 'Output #4: %d' %(custom_path_distance(g,['A','E','B','C','D'])) # Should be 22
# print 'Output #5: %d' %(custom_path_distance(g,['A','E','D'])) # Should be NO SUCH ROUTE
# print 'Output #6: %d' %(count_paths(g,g.get_vertex('C'),g.get_vertex('C'),3,2)) # Should be 2
# print 'Output #7: %d' %(count_paths(g,g.get_vertex('A'),g.get_vertex('C'),4,1)) # Should be 3
dijkstra_shortest_path(g,g.get_vertex('A'), g.get_vertex('C'))
print 'Output #8: %s' %(g.get_vertex('C').get_distance()) # Should be 9
# g.reset()
dijkstra_shortest_path(g,g.get_vertex('B'), g.get_vertex('B'))
print 'Output #9: %s' %(g.get_vertex('B').get_distance()) # Should be 9
# print 'Output #10: %d' %(count_paths(g,g.get_vertex('C'),g.get_vertex('C'),30,0)) # Should be 7
|
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
from lib.debugging import dprint
from typing import NamedTuple
class Row(object):
"""Table row with Cell objects."""
def __init__(self, cells=[]):
self.cells = cells
def addCell(self, cell):
"""Add a new cell to the table.
Takes:
cell (Cell)"""
self.cells.append(cell)
def _getCellListByType(self, pad=False, headersRequested=True):
"""Get either header or data Cell object list."""
if pad:
paddedCellList = []
for cell in self.cells:
if cell.isHeader == headersRequested:
# Add actual header.
paddedCellList.append(cell)
else:
# Add empty padding.
paddedCellList.append(Cell())
return paddedCellList
else:
# Only return header cells; a potentially smaller list.
return [c for c in self.cells if c.isHeader == headersRequested]
@property
def hasHeaderCells(self):
"""Returns true if we have header cells, false if not."""
return any([c.isHeader for c in self.cells])
def getHeaderCells(self, pad=False):
"""List of header cells, with or without padding.
Takes:
- pad (bool) [False]:
If True, returns a list with the same size as
self.cells, with any cell that isn't a header represented by an
empty Cell object (no text). If the row contains no header cells,
the list will only contain empty Cell objects.
If False (the default) it returns a potentially smaller list with
only header cells. If the row contains no header cells, the list
is empty."""
return self._getCellListByType(pad, headersRequested=True)
def getDataCells(self, pad=False):
"""List of data cells, with or without padding.
Takes:
- pad (boot) [False]:
If True, returns a list with the same size as
self.cells, with any header cell being represented by an
empty Cell object (no text). If the row contains no data cells,
the list will only contain empty Cell objects.
If False (the default) it returns a potentially smaller list with
only data cells. If the row contains no data cells, the list
is empty."""
return self._getCellListByType(pad, headersRequested=False)
class Cell(object):
"""Table cell; typically part of a Row object."""
def __init__(self, text="", isHeader=False):
self.text = text
self.isHeader = isHeader
class Table(object):
"""Table made up of Row objects."""
class NoHeadersError(Exception): pass
def __init__(self, rows=None):
self.rows = rows if rows else []
@property
def hasRows(self):
return len(self.rows) > 0
@property
def hasHeaders(self):
if self.hasRows:
return self.rows[0].hasHeaderCells
else:
return False
@property
def headers(self):
if self.hasHeaders:
return self.rows[0].getHeaderCells(pad=True)
else:
raise self.__class__.NoHeadersError(\
"Table headers requested when there are none.")
def addRow(self, row):
"""Add Row object to table.
Takes:
row (Row)
Returns: self (chainable)"""
self.rows.append(row)
return self
def render(self):
"""Create a human interpretable representation of the table."""
return "\n".join(self.rows)
class TableFromCode(Table):
"""Table initialized from code in string form."""
def fromCode(self, code):
"""Initialize table from code string.
Takes:
code (str)"""
class PmwikiTable(TableFromCode):
"""Table initialized from pmwiki code."""
def fromCode(self, code):
"""Initialize table from pmwiki code.
Takes:
code (str)"""
rows = []
for rowText in code.split("\n"):
row = Row()
for cellText in rowText.strip("||").split("||"):
cell = Cell(cellText.strip())
if cell.text.startswith("!"):
cell.isHeader = True
row.addCell(cell)
rows.append(row)
class TableFromTableByConversion(Table):
"""A table initialized from another table.
override self.fromTable in a subclass to
define conversion behaviour."""
def __init__(self, table):
super().__init__()
self.fromTable(table)
def fromTable(self, table):
"""Override in subclass.
Takes:
table (Table): Table to initialize from.
Returns: self"""
return self
class TableTheme(object):
"""Characters for table formatting.
The default is markdown style tables."""
@property
def headerSeparator(self):
return "-"
@property
def verticalBorder(self):
return " | "
class MdTable(TableFromTableByConversion):
def fromTable(self, table):
self.rows = table.rows
def render(self, theme, withHeadersIfAvailable=True):
renderedRows = []
if self.headers and withHeadersIfAvailable:
headerCells = [t for t in self.headers]
headerSeparatorCells = [theme.headerSeparator*3 for i in range(0, len(self.headers))]
renderedRows.append(theme.verticalBorder.join(headerCells))
renderedRows.append(theme.verticalBorder.join(headerSeparatorCells))
for row in self.rows:
renderedCells = theme.verticalBorder.join([c.text for c in row.cells])
renderedRows.append(renderedCells)
return "\n".join(renderedRows)
|
from math import *
def get_data():
answers = [("zero is", (4 - 4 + 4 - 4)),
("One is", (4 / 4 * 4 / 4)),
("Two is", (4 / 4 + 4 / 4)),
("three is", (4 - (4 / 4 / 4))),
("four is", ((4 - 4) / 4) + 4),
("five is", (((4 / 4) ** 4) + 4)),
("six is", (((4 + 4) / 4) + 4)),
("seven is", int(4 - (4 / 4) + 4)),
("eight is", int(4 - 4 + 4 + 4)),
("nine is", int((4 + 4) + (4 / 4))),
("ten is", int((44 - 4) / 4)),
("eleven is", int(44 / (sqrt(4) * (sqrt(4))))),
("twelve is", int((4 - (4 / 4)) * 4)),
("thirteen is", int((44 / 4) + (sqrt(4)))),
("fourteen is", int(4 + 4 + 4 + sqrt(4))),
("fifteen is", int((4 * 4) - (4 / 4))),
("sixteen is", int(4 * 4 - 4 + 4)),
("seventeen is", int(4 * 4) + (4 / 4)),
("eighteen is", int(((4 * 4) + (sqrt(4) + .4)))),
("nineteen is", int(factorial(4) - ((4 / 4) + 4))),
("twenty is", int(44 - 4) / sqrt(4))]
return answers
def print_num():
answers = get_data()
for answer in answers:
print(answer[0] + " " + str(int(answer[1])))
if __name__ == "__main__":
print_num()
|
import random
print ("Choice ([34,56,89,12,5,7]:)", random.choice([34,56,89,12,5,7]))
print("\n Shuffle() Method");
items = [45,2,5,23,78,9];
random.shuffle(items)
print("Reshuffle the items: ",items);
#============Randint===================
# randint()method
for x in range(1 , 7):
x = random.randint(1, 49)
print("\t", x);
|
# Design an algorithm that finds the maximum positive integer input by a user.
# The user repeatedly inputs numbers until a negative value is entered.
# Do not change this line
max_int = 0
in_num = 0
while 1:
in_num = num_int = int(input("Input a number: "))
if in_num > max_int:
max_int = in_num
if in_num < 0:
break
print("The maximum is", max_int) # Do not change this line
|
"""VerticalHistogram"""
def filter(word, counter):
final_line = (' ', *word)
list_for_print = {}
for i in word:
if i in list_for_print:
list_for_print[i] += 1
else:
list_for_print[i] = 1
print(list_for_print)
filter([i if i.isalpha() else 0 for i in input()], 1)
|
"""isPrime_large"""
def prime(number):
"""print prime number"""
if number > 2:
print(checker(number))
elif number == 2:
print("YES")
else:
print("NO")
def checker(number):
"""check number is prime number?"""
for i in range(2, int(number**.5)+1):
if number%i == 0:
return 'NO'
return "YES"
prime(int(input()))
|
"""almost mean"""
def almost(dict_data, mean, amount, ref):
"""find student that score almost mean"""
for i in range(amount):
data = input().split('\t')
dict_data[data[0]] = data[1]
for i in dict_data:
mean += float(dict_data[i])
mean /= amount
for i in dict_data:
if float(dict_data[i]) <= mean and float(dict_data[i]) > float(ref):
ref = dict_data[i]
student_id = i
print("%s\t%s" %(student_id, ref))
almost(dict(), 0, int(input()), 0)
|
"""Create a notebook containing code from a script.
Run as: python jupyter_from_py.py my_script.py
"""
import sys
import nbformat
from nbformat.v4 import new_notebook, new_code_cell, new_markdown_cell
CELL_TYPE_UNKNOWN = 0
CELL_TYPE_CODE = 1
CELL_TYPE_MARKDOWN = 2
IDENTIFIER_CODE = '# In[ ]:'
IDENTIFIER_MARKDOWN = '# ##'
def celltype_for_line(line):
if IDENTIFIER_MARKDOWN in line:
return CELL_TYPE_MARKDOWN
elif IDENTIFIER_CODE in line:
return CELL_TYPE_CODE
else:
return CELL_TYPE_UNKNOWN
if __name__ == '__main__':
nb = new_notebook()
try:
with open(sys.argv[1]) as f:
code = f.read()
except:
print('> ERROR')
print('> USAGE: python jupyter_from_py.py my_script.py')
print('> You did not provide a python script, or it could not be read.')
quit()
lines = code.split('\n')
lines_clean = []
for line in lines:
if not '# coding' in line and not '#!' in line:
lines_clean += [line]
lines = lines_clean
cell_blocks = []
current_cell_type = CELL_TYPE_CODE
cell_lines = []
# initial logic
if celltype_for_line(lines[0]) == CELL_TYPE_UNKNOWN or celltype_for_line(line[0]) == CELL_TYPE_CODE:
current_cell_type = CELL_TYPE_CODE
else:
current_cell_type = CELL_TYPE_MARKDOWN
cell_lines += [lines[0]]
# continuing logic
for line in lines[1:]:
is_same_cell = celltype_for_line(line) == CELL_TYPE_UNKNOWN
if is_same_cell:
# continue adding to the cell
cell_lines += [line]
else:
# store the cell and start a new one
cell_blocks += [(current_cell_type, cell_lines)]
cell_lines = [line]
current_cell_type = celltype_for_line(line)
# closing logic (store the last cell)
cell_blocks += [(current_cell_type, cell_lines)]
for cell_type, code in cell_blocks:
code = '\n'.join(code)
is_cell_empty = len(code.strip()) == 0
if is_cell_empty:
continue
if cell_type == CELL_TYPE_CODE:
code = code.replace(IDENTIFIER_CODE, '')
nb.cells.append(new_code_cell(code.strip()))
elif cell_type == CELL_TYPE_MARKDOWN:
code = code.replace(IDENTIFIER_MARKDOWN, '##')
nb.cells.append(new_markdown_cell(code.strip()))
else:
assert False
nbformat.write(nb, sys.argv[1].split('.py')[0] + '.ipynb')
|
class Square(object):
def __init__(self, length,name):
self._length = length
self._name = name
def display(self):
print("length : ", self.length
)
print("Name : ", self.name
)
@property
def length(self):
return self._length
@length.setter
def length(self, value):
self._length = value
@property
def names(self):
return self._name
@names.setter
def name(self, value):
self._name = value
r = Square(9,"Krishna")
r.length # automatically calls getter
r.display()
r.length = 12 # automatically calls setter
r.name= "Bhanu"
r.display() |
# -*- coding: utf-8 -*-
import math
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def convert( num, baseOrig, baseDest ):
result = ''
num = toDecimal( num, baseOrig )
q = num
while q > 0:
r = q % baseDest
q = q / baseDest
result = digits[ r ] + result
return result
def toDecimal( num, base ):
result = 0
i = 0
pos = len( num )
while pos > 0:
digit = num[ i ]
i += 1
value = digits.index( digit )
pos -= 1
result += value * int( math.pow( base, pos ))
return result
def solveTable():
nums = [ 20, 13, 14, 22, 17, 18, 27, 10 ]
bases = [ 3, 2, 13, 14, 10, 7, 4, 8 ]
spaces = [ 5, 7, 4, 4, 4, 4, 5, 4 ]
print( '+-----+-------+----+----+----+----+-----+----+' )
# BASES
row = ''
i = 0
for base in bases:
row += '| ' + str( base )
l = len( str( base ))
while l < spaces[ i ] - 1:
row += ' '
l += 1
i += 1
print( row + '|' )
# VALUES
i = 1
for num in nums:
row = ''
j = 0
for base in bases:
result = convert( str( num ), 10, base )
row += '| ' + result
l = len( result )
while l < spaces[ j ] - 1:
row += ' '
l += 1
j += 1
print( '+-----+-------+----+----+----+----+-----+----+' )
print( row + '|' )
i += 1
print( '+-----+-------+----+----+----+----+-----+----+' )
if __name__ == '__main__':
solveTable()
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This temporary script file is located here:
/home/laubosslink/.spyder2/.temp.py
"""
# Variables
myvar=5
myvar2=10
# Permutation
myvar, myvar2 = myvar2, myvar
# Affichage
print("hello world".capitalize()); print("myvar=" + str(myvar) + " / myvar2=" + str(myvar2))
print("Hello World"[6:].upper())
import math
print("racine de 25 : " + str(math.sqrt(25)))
fruits = {"pommes":21, "melons":3}
for fruit, nombre in fruits.items():
print("Il y a {} {}".format(nombre, fruit))
|
#!/usr/local/bin/python3
import random;
while True:
try:
minNumber = input('Podaj minimalna liczbe\n')
maxNumber = input('Podaj maksymalna liczbe\n')
ourNumber = random.randint(int(minNumber), int(maxNumber))
break
except ValueError as error:
print(error)
finnished = False
while not finnished:
try:
userNumber = int(input('Podaj liczbe\n'))
if userNumber == ourNumber:
print('Odgadles liczbe')
finnished = True
elif userNumber > ourNumber:
print('Podaj mniejsza liczbe!')
else:
print('Podaj wieksza liczbe!')
except ValueError as error:
print(error)
|
#NUMBER PALINDROME
class Solution(object):
def isPalindrome(self, num):
str_num = str(num)
original_index = 0
flag = None
for index in reversed(range(len(str_num))):
if str_num[original_index] == '-':
return False
elif str_num[original_index] == str_num[index]:
original_index += 1
flag = True
else:
return False
return flag
def main():
solution = Solution()
flag = solution.isPalindrome(-123)
print(flag)
if __name__ == '__main__':
main()
|
'''
for循环实现1~100求和
'''
sum=0
for x in range(101):
sum+=x
print(sum)
#1~100偶数求和
sum=0
for x in range(2,101,2):
sum+=x
print(sum) |
'''
比较运算符和逻辑运算符
'''
flag0=1==1
flag1=3>2
flag2=2<1
flag3=flag1 and flag2
flag4=flag1 or flag2
flag5=not(1!=2)
print('flag0=',flag0)
print('flag1=',flag1)
print('flag2=',flag2)
print('flag3=',flag3)
print('flag4=',flag4)
print('flag5=',flag5) |
'''
通过键盘输入两个整数来实现对其算数运算
'''
a=int(input('a='))
b=int(input('b='))
print('%d+%d=%d'%(a,b,a+b)) # %d是整数的占位符
print('%d-%d=%d'%(a,b,a-b))
print('%d*%d=%d'%(a,b,a*b))
print('%d/%d=%d'%(a,b,a/b))
print('%d/%d=%f'%(a,b,a/b)) # %f是浮点数的占位符
print('%d//%d=%d'%(a,b,a//b))
print('%d%%%d=%d'%(a,b,a%b)) # %%代表%,由于%代表了占位符
print('%d**%d=%d'%(a,b,a**b)) |
rows, columns = [int(x) for x in input().split(', ')]
matrix = []
for row in range(rows):
matrix.append([int(x) for x in input().split()])
# for col in range(columns):
# current_sum = 0
# for row in range(rows):
# current_sum += matrix[row][col]
# print(current_sum)
columns_sum = [0] * columns
for row in range(rows):
for col in range(columns):
value = matrix[row][col]
columns_sum[col] += value
[print(el) for el in columns_sum]
|
from collections import deque
bomb_effects = deque([int(x) for x in input().split(', ')])
bomb_casings = [int(x) for x in input().split(', ')]
datura_bombs = 0
cherry_bombs = 0
smoke_decoy_bombs = 0
succeed = False
while True:
if datura_bombs >= 3 and cherry_bombs >= 3 and smoke_decoy_bombs >= 3:
succeed = True
break
if not bomb_effects or not bomb_casings:
break
current_bomb_effect = bomb_effects[0]
current_bomb_casting = bomb_casings[-1]
sum_bombs = current_bomb_effect + current_bomb_casting
if sum_bombs == 40:
datura_bombs += 1
bomb_effects.popleft()
bomb_casings.pop()
elif sum_bombs == 60:
cherry_bombs += 1
bomb_effects.popleft()
bomb_casings.pop()
elif sum_bombs == 120:
smoke_decoy_bombs += 1
bomb_effects.popleft()
bomb_casings.pop()
else:
current_bomb_casting -= 5
bomb_casings.pop()
bomb_casings.append(current_bomb_casting)
if succeed:
print("Bene! You have successfully filled the bomb pouch!")
else:
print("You don't have enough materials to fill the bomb pouch.")
if bomb_effects:
print(f"Bomb Effects: {', '.join(map(str, bomb_effects))}")
else:
print("Bomb Effects: empty")
if bomb_casings:
print(f"Bomb Casings: {', '.join(map(str, bomb_casings))}")
else:
print("Bomb Casings: empty")
print(f"Cherry Bombs: {cherry_bombs}")
print(f"Datura Bombs: {datura_bombs}")
print(f"Smoke Decoy Bombs: {smoke_decoy_bombs}") |
n = int(input())
matrix = []
for row in range(n):
matrix.append([int(x) for x in input().split(', ')])
# flattening_matrix = []
# for row in matrix:
# flattening_matrix.extend(row)
# print(flattening_matrix)
print([x for row in matrix for x in row]) |
import re
text = input()
pattern = r"\d+"
matched_elements = []
while text:
matches = re.findall(pattern, text)
matched_elements.extend(matches)
text = input()
print(*matched_elements)
|
import csv
import string
import os
import fnmatch
import re
from collections import Counter
# This method checks each word of a list of words and removes some special characters
def remove_punctuation(list_of_words):
cleant_list_of_words = ""
for word in list_of_words:
# If char is not punctuation, add it to the result.
# string.punctuation contains these symbols:
# !, ", #, $, %, &, ', (, ), *, +, , ,- , . , / , : , , ; , < , = , >
# ? , @ , [ , \ , ], ^ , _ , ` , { , | , } , ~
if word not in string.punctuation:
cleant_list_of_words += word
return cleant_list_of_words
# Method which adds words in the total list of words
def read_words(words, msg_content_cleant):
list_of_words_to_ignore = [' un ', ' une ', ' unes ', ' le ', ' la ', ' les ', ' de ', ' du ', ' des ', ' le ',
' et ', ' le ', ' la ', ' ou ', ' le ', ' la ', ' or ', ' les ', ' que ', ' qui ',
' que ', ' où ', ' quand ', ' car ', ' mais ', ' on ', ' je ', ' tu ', ' il ', ' elle ',
' nous ', ' vous ', ' ils ', ' elles ', ' à ', ' au ', ' aux ', ' en ', ' dans ', ' in ',
' pas ', ' sur ', ' sous ', ' pour ', ' contre ', ' par ', ' via ', " c'est ", " cest ",
" suis ", " es ", " est ", " sont ", " ce ", " ces ", " ça ", " cela ", " cette ",
" cettes ", " quel ", " quels ", " quelle ", " quelles ", " ai ", " as ", " a ",
" avons ", " avez ", " ont ", " ne ", " ni ", ' noise ', ' rock ', ' roll ', ' c ',
' j ', ' l ', ' d ', ' m ', ' n ', ' s ', ' t ', ' y ', ' qu ', ' toujours ', ' jamais ',
' plus ', ' moins ', ' avec ', ' sans ', ' chez ', ' eux ', ' oui ', ' non ', ' fait ',
' se ', ' tout ', ' comme ', ' bien ', ' même ', ' sa ', ' son ', ' ses ', ' ma ',
' mes ', ' mon ', ' ta ', ' ton ', ' tes ', ' si ', ' va ', ' aussi ', ' aujourd ',
' hui ', ' « ', ' » ', ' notre ', ' votre ', ' nos ', ' vos ', ' être ', ' me ', ' te ',
' se ', ' rien ', ' moi ', ' comment ', ' faut ', ' tous ', ' tout ', ' toutes ',
' toute ', ' jusqu ', ' selon ', ' aller ', ' faire ', ' avant ', ' après ', ' après ',
' coût ', ' coûte ', ' euros ', ' trop ', ' veut ', ' bon ', ' sera ', ' entre ',
' depuis ', ' encore ', ' 20 ', ' idée ', ' très ', ' chaque ', ' an ', ' ans ',
' leur ', ' peut ']
# Here we remove all the words from the messages that would be in the list just above
for word_to_ignore in list_of_words_to_ignore:
msg_content_cleant = msg_content_cleant.replace(word_to_ignore, " ")
# we split the message cleant in many words separated by spaces and remove all words beginning by http
tempo_words = msg_content_cleant.split()
for word_position in range(len(tempo_words)-1, 0, -1):
if tempo_words[word_position].startswith("http"):
tempo_words.remove(tempo_words[word_position])
words += tempo_words
return words
# Method adding
def append_words_to_all_words_issued_from_all_messages(words, entry):
with open(entry, 'r') as csv_file:
reader = csv.reader(csv_file)
# Reading row by row
for row in reader:
csv_line = ""
for x in range(0, len(row)):
csv_line += row[x]
# The information we need is in the 3rd column,
# but if we split just with ";" it can have weird behavior with some csvLines
# so we split before the 4th column ";fr;" , then we split the result and get what is after the 2nd ";"
# Then we remove all the http://.... and https://..... with a regex expression
# then we replace some specific symbols from the message content
# then we use the remove_punctuation method to remove other specific symbols
msg_content_cleant = (csv_line.split(";fr;")[0].lower()).split(";")[2]
msg_content_cleant = re.sub(r'/http\w+/', '', msg_content_cleant)
msg_content_cleant = msg_content_cleant.replace("'", " ")
msg_content_cleant = msg_content_cleant.replace("’", " ")
msg_content_cleant = msg_content_cleant.replace('…', " ")
msg_content_cleant = msg_content_cleant.replace('★', " ")
msg_content_cleant = " " + remove_punctuation(msg_content_cleant) + " "
read_words(words, msg_content_cleant)
# Main process
folder_name = "LaunchTestsAndSeeOutputsHere/2 - ExampleForGettingWordsCount"
pattern = "*.csv"
# Gets all csvFiles from the folder specified above
# declare all_words_issued_from_all_messages which will contain all the words contained in all the csv lines
# example : all_words_issued_from_all_messages = [ "pollution" , "paris" , "france" , "alerte" , "pollution", ... ]
# same word can be present many times in this variable, then we will do a count with the Counter method
listOfFiles = os.listdir(folder_name)
all_words_issued_from_all_messages = []
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
append_words_to_all_words_issued_from_all_messages(all_words_issued_from_all_messages, folder_name + "/" + entry)
# Counter counts the number off occurences of all words contained in the all_words_issued_from_all_messages
# We print the 200 words having the biggest count
count_each_word = Counter(all_words_issued_from_all_messages).most_common(200)
# This piece of code prints in the console mode the 75 words appearing most of times in the messages contents
for searchedWord in count_each_word:
searchedWord = str(searchedWord).replace("('", "")
searchedWord = str(searchedWord).replace("', ", ";")
searchedWord = str(searchedWord).replace(")", "")
print(searchedWord)
|
import psycopg2
from datetime import datetime
class DB:
"""Baseclass which provides functionality to query the a postgres databanks.
Attributes:
user (str) : db user.
host(str) : db host.
port(int) : db port.
database(str) : db database.
"""
def __init__(self, user, host, database, port = None):
self.user = user
self.host = host
self.port = port
self.database = database
self.connect()
self.formatstr = "%Y-%m-%d %H:%M:%S"
def __del__(self):
self.close()
def connect(self):
""" Connect to the database. So far no error handling."""
if self.port is None:
self.conn = psycopg2.connect("dbname='%s' user='%s' host='%s' " % (self.database, self.user, self.host))
else:
self.conn = psycopg2.connect("dbname='%s' user='%s' host='%s' port='%i'" % (self.database, self.user, self.host, self.port))
self.cur = self.conn.cursor()
def close(self):
"""Close the connection to the database"""
self.conn.close()
def query(self, query):
"""Query database.
Args:
query(str) : db query string. For example 'Select run FROM runs'."
Returns:
runs (list): the row wise response to query.
start (list)
"""
self.cur.execute(query)
rows = self.cur.fetchall()
return rows
|
class Teacher():
def __init__(self,age,address):
self.age = age
self.address = address
def information(self):
print(self.age)
print(self.address)
Lijun = Teacher(45,'Beijing')
Lijun.information() |
class Statistics:
def __init__(self):
self.min = None
self.max = None
self.list=[]
self.total = 0.0
self.n = 0
self.var = 0
def observe(self, x):
if self.n > 1:
delta = x - self.mean()
self.list.append(x)
self.list.sort()
self.total += x
self.n += 1
self.min = self.list[0]
self.max = self.list[len(self.list)-1]
if self.n > 2:
self.var = (delta*(x-self.mean()))
def mean(self):
return self.total / self.n
def variance(self):
n=0
mean = 0.0
M2 = 0.0
for x in self.list:
n+=1
delta = x - mean
mean+= delta/n
M2 += delta*(x-mean)
if n<2:
return (None)
else:
return M2 / (n - 1)
def __str__(self):
if self.n == 0:
return '- no data -'
return 'mean: {}, max: {}, min: {}, variance: {}'.format(self.mean(), self.max, self.min, self.variance())
stats = Statistics()
for x in [4,2,1,3]:
stats.observe(x)
print(stats)
# Expected: mean: 2.5, max: 4, min: 1 |
import hashlib
hash1, salt1, fileName, fileText = "", "", "password_file.txt", ""
lineCount = 0
def hash_with_sha256(str):
hash_object = hashlib.sha256(str.encode('utf-8'))
hex_dig = hash_object.hexdigest()
return hex_dig
def letsPlay(n):
if n == lineCount:
print("Job completed!")
return
else:
words = fileText[n].split(',') # split current line to words
hash1, salt1 = words[2].replace(' ', ''), words[1].replace(' ', '') # remove spaces
print("Trying->", words[0], end='') #keep printing in the same line print("Hello", end = '') print("world")
i, stop, zeros = 0, 9999999, 3 # increment, where to stop, number of zeros
while i < stop:
x = '{:d}'.format(i).zfill(zeros)
hex_dig = hash_with_sha256(x.replace(' ', '') + salt1)
if hex_dig.lower().split() == hash1.lower().split():
print(" # Password Cracked!!!\n",
words[0], ",password:", '{:d}'.format(i).zfill(zeros), ",salt:", salt1, "\nhash:", hex_dig,
"\n###############################################################################")
break
i += 1
if i == 1000 and zeros == 3:
# print("Ending 3 digit combinations - Restarting with 4")
print(".", end='') # keep printing dots in 1 line
i = 0
zeros += 1 # increase number of zeros
if i == 10000 and zeros == 4: # print("Ending 4 digit combinations - Restarting with 5")
print(".", end='')
i = 0
zeros += 1 # increase number of zeros
if i == 100000 and zeros == 5: # print("Ending 5 digit combinations - Restarting with 6")
print(".", end='')
i = 0
zeros += 1 # increase number of zeros
if i == 1000000 and zeros == 6: # print("Ending 6 digit combinations - Restarting with 7")
print(".", end='')
i = 0
zeros += 1 # increase number of zeros
if i == 10000000 and zeros == 7:
print(".", end='')
i, stop, zeros = 0, 9999999, 3 # reset for next loop
break
return letsPlay(n + 1)
with open(fileName, "r") as f: # getting file content
fileText = f.readlines()
for line in fileText: # getting line count
lineCount += 1
letsPlay(0) # start from line 0, minimum password length 3, max length 7
|
# 1. Пользователь вводит данные о количестве предприятий, их наименования
# и прибыль за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия..
# Программа должна определить среднюю прибыль (за год для всех предприятий)
# и вывести наименования предприятий, чья прибыль выше среднего и отдельно
# вывести наименования предприятий, чья прибыль ниже среднего.
from collections import namedtuple
from collections import deque
# from collections import defaultdict
# import random
def get_enterprise_data_strings(numb: int = 0) -> tuple:
_enterprise_string = input(f"Введите наименование предприятия {numb} "
"и прибыль по четвертям(csv): ")
# _enterprise_string = f'Microsoft{random.randint(0, 9)}, ' \
# f'{random.randint(0, 5)}, 2, 3, 4'
return tuple(map(str.strip, _enterprise_string.split(',')))
quarters = ['q1', 'q2', 'q3', 'q4']
Year: namedtuple = namedtuple('Year', quarters)
Enterprise: namedtuple = namedtuple('Enterprise', ['name', 'year'])
# year1 = Year(q1=10, q2=20, q3=30, q4=40)
# ent1 = Enterprise('Microsoft', year=year1)
# print(ent1)
# spam = deque(get_enterprise_data_strings())
# name = spam.popleft()
# print(name, Year(*spam))
# print(tuple(map(int, spam)))
# year1 = Year(*tuple(map(int, spam)))
# print(year1)
# ent1 = Enterprise(spam.popleft(), Year(*tuple(map(int, spam))))
# ent1 = Enterprise(spam.popleft(), Year(*tuple(map(float, spam))))
# print(ent1)
def enterprise_average_profit(ent: Enterprise) -> float:
total_profit: float = 0
for quarter in quarters:
total_profit += getattr(ent.year, quarter)
return total_profit / len(quarters)
# print(enterprise_average_profit(ent1))
#
# exit()
enterprises = deque()
total_average_profit: float = 0
for _ in range(int(input("Введите количество предприятий: "))):
spam = deque(get_enterprise_data_strings(_ + 1))
eggs = Enterprise(spam.popleft(), Year(*tuple(map(float, spam))))
enterprises.append(eggs)
ent_avg = enterprise_average_profit(eggs)
total_average_profit = \
(total_average_profit * (len(enterprises) - 1) + ent_avg) \
/ (len(enterprises))
# print(eggs, enterprise_average_profit(eggs), total_average_profit)
print("Total average profit =", total_average_profit)
leaders = list()
outsiders = list()
for ent in enterprises:
avg = enterprise_average_profit(ent)
if avg < total_average_profit:
outsiders.append(ent.name)
# print(f"{ent.name} аутсайдер ({avg}<{total_average_profit})")
elif avg > total_average_profit:
leaders.append(ent.name)
# print(f"{ent.name} лидер ({avg}>{total_average_profit})")
else:
print(f"{ent.name} ни то ни сё ({avg}={total_average_profit})")
print("лидеры: ", *leaders)
print("аутсайдеры: ", *outsiders)
# 5
# a,1,2,3,4
# b,2,3,4,5
# c,3,4,5,6
# d,5,3 ,2, 0
# e,7, 5, 3, 3
|
# y = 2x - 10, если x > 0
# y = 0, если x = 0
# y = 2 * |x| - 1, если x < 0
# x - целое число
x = int(input('x = '))
if x > 0:
y = 2 * x - 10
elif x == 0:
y = 0
else:
y = 2 * abs(x) - 1
print(f'y = {y}')
# Для ДЗ
# import random
# chr()
# ord()
|
# 5. Вывести на экран коды и символы таблицы ASCII, начиная с символа
# под номером 32 и заканчивая 127-м включительно.
# Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.
# https://drive.google.com/file/d/1dRO7fXCLV1LLGWruoj_rnoHU5a8pRIjH/view?usp=sharing
for i in range(32, 128):
print(f"{i:3}-{chr(i)} ", end='')
if (i - 32 + 1) % 10 == 0:
print("")
# just 1 variable
# 32- 33-! 34-" 35-# 36-$ 37-% 38-& 39-' 40-( 41-)
# 42-* 43-+ 44-, 45-- 46-. 47-/ 48-0 49-1 50-2 51-3
# 52-4 53-5 54-6 55-7 56-8 57-9 58-: 59-; 60-< 61-=
# 62-> 63-? 64-@ 65-A 66-B 67-C 68-D 69-E 70-F 71-G
# 72-H 73-I 74-J 75-K 76-L 77-M 78-N 79-O 80-P 81-Q
# 82-R 83-S 84-T 85-U 86-V 87-W 88-X 89-Y 90-Z 91-[
# 92-\ 93-] 94-^ 95-_ 96-` 97-a 98-b 99-c 100-d 101-e
# 102-f 103-g 104-h 105-i 106-j 107-k 108-l 109-m 110-n 111-o
# 112-p 113-q 114-r 115-s 116-t 117-u 118-v 119-w 120-x 121-y
# 122-z 123-{ 124-| 125-} 126-~ 127-
# (var: i) (type: int) (full size: 28)
# total size: 28
|
# 2. Написать программу сложения и умножения двух шестнадцатеричных чисел.
# При этом каждое число представляется как массив, элементы которого это
# цифры числа. Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’]
# и [‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’],
# произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’].
from collections import deque
# from collections import namedtuple
from string import hexdigits
from string import digits
from collections import defaultdict
# def hex_str_to_list(string: str) -> list:
# return list(string.upper())
#
# print(hex_str_to_list("a2"))
# print(hex_str_to_list("C4f"))
def hex_digit_to_int(char: str = 0) -> int:
assert char in hexdigits
return int(char) if char in digits else ord(char.upper()) - ord('A') + 10
hex_numbers = defaultdict(int)
for char in set(hexdigits.upper()):
hex_numbers[char] = hex_digit_to_int(char)
# print(hex_numbers)
def int_to_hex(number: int) -> str:
for hex_digit in hex_numbers:
if hex_numbers[hex_digit] == number:
return hex_digit
# print(int_to_hex(1))
# exit()
# print(tuple(map(lambda x: f"digit_{x}", set(hexdigits.upper()))))
#
# hex_digits = namedtuple('hex_digits', map(lambda x: f"digit_{x}", set(hexdigits.upper())))
# for char in set(hexdigits.upper()):
# setattr(hex_digits, f"digit_{char}", hex_digit_to_int(char))
# # hex_digits[char] = hex_digit_to_int(char)
#
# for key in hex_digits._fields():
# print(hex_digits.key)
# exit()
# print(hex_digit_to_int("F"))
# exit()
# *****************************************************
number1 = deque(input("Введите первое hex: ").upper())
number2 = deque(input("Введите второе hex: ").upper())
# number1 = deque("a2")
# number2 = deque("c4f")
print(list(number1), list(number2), sep='\n')
# def hex_digit_to_int(char: str) -> int:
# assert char not in [0-9]+['A'-'F']
# return int(char) if char in [0-9] else ord(char)-ord('A')+10
# print(hex_digit_to_int("f"))
def hex_sum(number1: deque, number2: deque) -> deque:
n1 = number1.copy()
n2 = number2.copy()
result = deque()
overhead = False
for i in range(max(len(n1), len(n2))):
d1 = n1.pop() if len(n1) > 0 else '0'
d2 = n2.pop() if len(n2) > 0 else '0'
spam = hex_digit_to_int(d1) + hex_digit_to_int(d2)
if overhead:
spam += 1
# print(d1, d2, hex_digit_to_int(d1), hex_digit_to_int(d2), spam, overhead)
# print(spam % 16)
overhead = spam // 16
result.appendleft(int_to_hex(spam % 16))
if overhead:
result.appendleft('1')
return result
print(f"{list(number1)}+{list(number2)}={list(hex_sum(number1, number2))}")
def hex_mull(n1: deque, n2: deque) -> deque:
_num1 = n1.copy()
_num1.reverse()
_num2 = n2.copy()
_num2.reverse()
result = deque()
for i in _num1:
row = deque()
overhead = 0
for j in _num2:
spam = hex_digit_to_int(i) * hex_digit_to_int(j)
spam += overhead
row.appendleft(int_to_hex(spam % 16))
overhead = spam // 16
if overhead > 0:
row.appendleft(int_to_hex(overhead))
result = hex_sum(result, row)
_num2.appendleft('0')
if result.count('0') == len(result):
result = deque('0')
return result
print(hex_mull(number1, number2))
# import random
# def test_sum():
# for i in range(10000):
# number1 = hex(random.randint(0, 1000))[2:]
# number2 = hex(random.randint(0, 1000))[2:]
# expect = deque(hex(int(number1, 16)+int(number2, 16))[2:].upper())
# result = hex_sum(deque(str(number1)), deque(str(number2)))
# assert expect == result
#
# print(f"sum {i} ok ", end = '')
# print(f"{number1}+{number2}=",*expect, '/', *result, sep='')
#
#
# test_sum()
#
#
# def test_mul():
# for i in range(100000):
# number1 = hex(random.randint(0, 100000))[2:]
# number2 = hex(random.randint(0, 100000))[2:]
# expect = deque(hex(int(number1, 16)*int(number2, 16))[2:].upper())
# result = hex_mull(deque(str(number1)), deque(str(number2)))
# assert expect == result, f"{number1}*{number2}={expect},{result}"
# print(f"mul {i} ok ", end = '')
# print(f"{number1}*{number2}=", *expect, '/', *result, sep='')
#
#
# test_mul()
|
n = int(input('До какого числа просеивать решето: '))
sieve = [i for i in range(n)]
print(sieve)
sieve[1] = 0
for i in range(2, n):
if sieve[i] != 0:
j = i + i
while j < n:
sieve[j] = 0
j += i
print(sieve)
result = [i for i in sieve if i != 0]
print(result)
# range(stop)
# range(start, stop)
# range(start, stop, step)
|
# 5. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят
# и сколько между ними находится букв.
print("Введите две строчных латинских буквы")
first = input("Первая буква: ")
second = input("Вторая буква: ")
if first == second:
n = ord(first) - ord('a') + 1
print(f"Введены одинаковые {n}-е буквы {first}")
else:
n1 = ord(first) - ord('a') + 1
n2 = ord(second) - ord('a') + 1
offset = abs(n1 - n2) - 1
print(f"Между {n1}-й буквой {first} и {n2}-й буквой {second} {offset} букв(а/ы)")
|
'''
Модуль, реализующий функционал работы ЭВМ
Скорость измеряется в байтах в секунду
Объём измеряется в мегабайтах
Частота измеряется в герцах
@author ADT
'''
import time
from typing import List, Optional, Dict, Any
from collections import namedtuple
from datetime import datetime
from overrides import overrides
from dataclasses import dataclass
TIME_TRANS = 1000
current_millisecs_time = lambda: int(round(time.time() * 1000))
def compare_ip(ip_net: List[int], mask_net: List[int], dest_ip: List[int]) -> bool:
'''
Checks whether ip address belongs to the specified subnetwork
@params
ip_net: list of str, ipv4 or ipv6 address of subnetwork
mask_net: list of str, same sort of ip_net, mask of net (orly?)
dest_ip: ip address of destination, has same sort as previous things
@return
True if ip address refers to subnetwork else False
'''
if len(ip_net) != len(mask_net):
return False
if len(mask_net) != len(dest_ip):
return False
for ip_part, mask_part, dest_part in zip(ip_net, mask_net, dest_ip):
if dest_part & mask_part != ip_part & mask_part:
return False
return True
def apply_mask(ip_net: List[int], net_mask: List[int]) -> List[int]:
'''
Apply mask to ip address
@params
ip_net: ip address of computer
net_mask: mask of network
@return
ip address of network
'''
assert len(ip_net) == len(net_mask)
net_addr: List[int] = [a&b for a, b in zip(ip_net, net_mask)]
return net_addr
def get_new_ip(net_addr: List[int], count: int) -> List[int]:
assert count > 0
new_addr: List[int] = [i for i in net_addr]
number: int = count
ind: int = len(net_addr) - 1
while number > 0:
new_addr[ind] += number % 255
if new_addr[ind] > 254:
new_addr[ind - 1] += new_addr[ind] // 254
new_addr[ind] = new_addr[ind] % 254
ind -= 1
number = number // 255
return new_addr
#Batch = namedtuple('Batch', ['item', 'passed', 'time', 'delegate', 'args'])
@dataclass
class Batch:
item: object
passed: int
time: int
delegate: Any
args: dict
class Pump:
coming: list
processing: list
time_last_pumping: int
def __init__(self):
self.coming: list = []
self.processing: list = []
self.time_last_pumping: int = current_millisecs_time()
def spit(self, batch):
assert batch.time >= 0, ValueError("Can't be negative")
if batch.time > 0:
self.coming.append(batch)
else:#time == 0
self.processing.append(batch)
def spit_item(self, item, consuming_time):
assert consuming_time >= 0, ValueError("Can't be negative")
if consuming_time > 0:
self.coming.append(Batch(item, 0, consuming_time))
else:#time == 0
self.processing.append(item)
def pump(self):
'''
'''
# I use the while loop here because
# the container cannot be changed in the for loop
# it can lead to IndexError.
current_time: int = current_millisecs_time()
delta_time: int = current_time - self.time_last_pumping
self.time_last_pumping = current_time
ind = 0
while ind < len(self.coming):
batch = self.coming[ind]
batch.passed += delta_time
if batch.passed >= batch.time:
self.coming.remove(batch)
self.processing.append(batch)
batch.delegate(**batch.args)
else:
ind += 1
class NonNegativeDesc:
'''
Descriptor class to set non negative numeric values
'''
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
# if the value isn't numeric it'll rise TypeError
# because python can't do non numeric < 0
# if it implemented into class - class must to provide numeric things
if value < 0:
raise ValueError("Can't be negative")
instance.__dict__[self.name] = value
def __set_name__(self, owner, name):
self.name = name
class Machine(Pump):
'''
Clss of user machine to do any calculations
'''
hz = NonNegativeDesc()
threads = NonNegativeDesc()
ram_mem = NonNegativeDesc()
storage_mem = NonNegativeDesc()
storage_speed = NonNegativeDesc()
net_speed = NonNegativeDesc()
# pylint: disable=too-many-arguments
def __init__(self, hz: int, threads: int, ram_mem: int,
storage_mem: int, storage_speed: int, net_speed: int,
name: Optional[str] = None):
super().__init__()
self.name = name
self.hz = hz
self.threads = threads
self.ram_mem = ram_mem
self.storage_speed = storage_speed
self.storage_mem = storage_mem
self.net_speed = net_speed
self.gateway = None
self.ip_addr = None
self.net_mask = None
self.ports = [None for _ in range(2**16)]
self.queue: List[list] = []
def set_net_data(self, ip_addr: List[int], net_mask: List[int], gateway, ipv6=None):
'''
'''
assert ipv6 is None, "ipv6 hasn't done"
#TODO: check length == 4 and 0 < byte < 255
self.ip_addr = ip_addr
self.net_mask = net_mask
ones = [255 for _ in range(len(ip_addr))]
last_addr = [a^b for a, b in zip(ones, net_mask)]
self.broadcast: List[int] = [a|b for a, b in zip(ip_addr, last_addr)]
self.gateway = gateway
def set_gateway(self, gateway):
self.gateway = gateway
def take_packet(self, packet: dict, test_dict: Optional[dict]=None):
'''
If destination ip is there, send packet to
a socket associated with the port of destination
@params
packet: dict with headers
@return
None
'''
port = packet['to_port']
test_dict['packet'] = packet
test_dict['recipient'] = self
#if self.ports[]
def send_packet(self, packet: dict, test_dict: Optional[dict]=None):
'''
Low-level method shouldn't be used by users
Should Add command "send packet" to pumping
'''
send_command = Batch(packet, 0, TIME_TRANS, self.gateway.take_packet, dict(
packet=packet, test_dict=test_dict
))
self.spit(send_command)
#self.gateway.take_packet(packet, test_dict)
def add_program(self, data, program: list) -> int:
'''
Add soft to queue of runing programs
@params
data: data to ru program
program: list of commands
@return seconds
'''
for command in program:
pass
class Router(Machine):
def __init__(self, default_gateway: str, name: Optional[str] = None):
super().__init__(21*1e5, 1, 1024, 10240, 8*1024*100, 80*1024**3)
self.IP_row = namedtuple('IP_row', 'ip_net ip_mask interface')
self.ip_table = []
self.interfaces_table = {}#matching table of name of interface and Router class
self.log = []#log of errors
self.default_gateway = default_gateway
self.name = name
def add_trace(self, ip_net: List[int], ip_mask: List[int], interface: str) -> int:
'''
Add a way how to collate ip address of destination and net interface
@params
ip_net: ip net of subnetwork
ip_mask: ipv4/ipv6 address like [12, 10, 64, 14]
interface: str, means gate where to kick packet to get destination
@return
count of existing entries as result of this function
'''
self.ip_table.append(self.IP_row(ip_net, ip_mask, interface))
return len(self.ip_table)
def connect_machine(self, interface: str, device: Machine):
#TODO отключить машину по ту сторону провода от этой
self.interfaces_table[interface] = device
@overrides
def take_packet(self, packet: dict, test_dict: Optional[dict]=None):
'''
Find packet and find most suitable interface to send forward
@params
packet: dict, iternet packet with headers
@return
None
'''
str_f_ip: List[str] = packet['to_ip'].split('.')
dest_ip: List[int] = [int(i) for i in str_f_ip]
del str_f_ip
for row in self.ip_table:
if compare_ip(row.ip_net, row.ip_mask, dest_ip):
try:
next_mach = self.interfaces_table[row.interface]
batch = Batch(packet, 0, TIME_TRANS, next_mach.take_packet, dict(
packet=packet, test_dict=test_dict
))
self.spit(batch)
#next_mach.take_packet(packet, test_dict)
except KeyError:
time_now: str = datetime.now().strftime("%d-%m-%Y/%H:%M")
self.log.append(f'[{time_now}] No connected device at {row.interface} \
interface')
finally:
return
#if there are no suitable devices:
dg: str = self.default_gateway
try:
#TODO spit for pumping
self.interfaces_table[dg].take_packet(packet, test_dict)
except KeyError:
time_now: str = datetime.now().strftime("%d-%m-%Y/%H:%M")
self.log.append(f'[{time_now}] No connected device at {dg} interface')
class Switcher(Machine):
'''
Switcher to route packets in subnetwork
'''
#pylint disable=too-many-instance-attributes
def __init__(self, net_addr: List[int], net_mask: List[int], name: Optional[str]=None):
super().__init__(21*1e5, 1, 1024, 10240, 8*1024*100, 80*1024**3, name=name)
self.switch_table = {}#'192.168.1.92': 'eth1' form
self.interfaces_table = {}#matchnig interface name string and Machine class
self.log: List[str] = []#errors
self.net_addr: List[int] = net_addr
self.net_mask: List[int] = net_mask
self.count_devices = 0#count of connected devices
self.max_devices = -2#cause first address is the address of network, last is broadcast
for ind, item in enumerate(reversed(self.net_mask)):
self.max_devices += (item^255)*(255**(ind+1))
assert self.max_devices >= 0, 'incorrect net mask'
@overrides
def set_gateway(self, gateway):
self.gateway = gateway
@overrides
def take_packet(self, packet: dict, test_dict: Optional[dict] = None):
try:
ip_addr: str = packet['to_ip']
interface: str = self.switch_table[ip_addr]
device = self.interfaces_table[interface]
batch = Batch(packet, 0, TIME_TRANS, device.take_packet, dict(
packet=packet, test_dict=test_dict
))
self.spit(batch)
#device.take_packet(packet, test_dict)
except KeyError:
#send to default gateway
self.gateway.take_packet(packet, test_dict)
#time_now: str = datetime.now().strftime("%d-%m-%Y/%H:%M")
#self.log.append(f'[{time_now}] No connected device or wrong packet')
def connect_machine(self, interface: str, device: Machine, ip: Optional[str] = None) -> int:
'''
Если задан ip, не меняет насроет подключаемой машины,
предполагаеся, что раз уж задаёте - сами настроили
Иначе настраиваее машину, выдавая ip and net mask
Returns status code
'''
#TODO отключить машину по ту сторону провода от этой
if self.count_devices > self.max_devices:
return -1
self.interfaces_table[interface] = device
if ip is None:
new_ip: List[int] = get_new_ip(self.net_addr, self.count_devices + 1)
strfip: str = '.'.join([str(i) for i in new_ip])
self.switch_table[strfip] = interface
device.set_net_data(new_ip, self.net_mask, self)
else:
self.switch_table[ip] = interface
self.count_devices += 1
class PostServer(Machine):
'''
'''
def __init__(self):
super().__init__(21*1e5, 1, 1024, 10240, 8*1024*100, 80*1024**3)
self.Letter = namedtuple('Letter', 'status title sender recipient text date')
self.mail = {}#recipient address: [Letter]
self.post_ips: Dict[str, str] = {}#ip address of other mail server
self.dns_ip = {}#addresses of dns servers
@overrides
def take_packet(self, packet: dict, test_dict: Optional[dict]=None):
'''
Take packet in form of post mail
If protocol not corfimed log it
'''
#if it isn't recipient drop packet
port: int = int(packet['to_port'])
if packet['to_ip'] != self.ip_addr or self.ports[port] is None:
return
try:
things: List[bytes] = packet['data'].split(b'\0')
title: str = str(things[0], 'utf-8')
sender: str = str(things[1], 'utf-8')
recipient: str = str(things[2], 'utf-8')
text: str = str(things[3], 'utf-8')
date: str = str(things[4], 'utf-8')
except (IndexError, KeyError):
#error in protocol, drop
return
new_letter = self.Letter('new', title, sender, recipient, text, date)
self.mail[recipient].append(new_letter)
def send_mail(self, letter: dict) -> int:
recip_server_name: str = ''
try:
recip_server_name = letter['recipient'].split('@')[1]
except KeyError:
return -1
try:
ip_addr = self.post_ips[recip_server_name]
letter['from'] = '.'.join(self.ip_addr)
letter['to'] = ip_addr
data = b'\0'.join([bytes(letter[field], 'utf-8') for field in letter])
self.gateway.take_packet(data)
except:
#send requese to dns server to find ip address of post server
pass
class DNSResolver(Machine):
'''
Adds an address entry to the ip address, creates an entry if it did not exist.
'''
def __init__(self):
super().__init__(21*1e5, 1, 1024, 10240, 8*1024*100, 80*1024**3)
self.table = {}
self.table[b'mx'] = {}
def add_entry(self, req:bytes, names:List[bytes], ip_list: List[bytes]):
'''
'''
try:
self.table[req]
except KeyError:
self.table[req] = {}
for name in names:
try:
for ip_addr in ip_list:
self.table[req][name].append(ip_addr)
except KeyError:
self.table[req][name] = []
for ip_addr in ip_list:
self.table[req][name].append(ip_addr)
@overrides
def take_packet(self, packet: dict, test_dict: Optional[dict] = None):
req: bytes = b''
address: bytes = b''
key: bytes = b''
try:
things: List[bytes] = packet['data'].split(b'\0')
req = things[0]
address = things[1]
key = things[2]
except (IndexError, KeyError):
return
try:
resp: bytes = self.table[req][address][0]
data: bytes = b'\0'.join([resp, key])
#answer = {k: packet[k] for k in packet if k != 'data'}
answer = {
'from_ip': packet['to_ip'],
'to_ip': packet['from_ip']
}
answer['data'] = data
#TODO process the case whe gateway isn't set
self.gateway.take_packet(answer)
except KeyError:
#this dns server doesn't know
pass
|
# Projeto Orientação de objetos
#Criar uma classe correntista com os seguintes atributos:
#Nome do correntista;
#Saldo em conta;
#Histórico de saque e depositos
#Deve possuir as seguintes capacidades:
#Fazer deposito
#Fazer saque
#A classe dever ser iterável, a iteração deve ocorrer sobre o histórico de saques e depósitos para,
#por exemplo, permitir imprimir todo o histórico.
class Correntista:
def __init__(self,nome,saldo):
self.__nome = nome
self.__saldo = saldo
self.__index = 0
self.__historico = []
def saque(self,valor):
if (valor > self.__saldo):
print("Saldo insuficiente!")
else:
self.__saldo -= valor
self.__historico.append(-valor)
self.__index += 1
def deposito(self,valor):
self.__saldo += valor
self.__historico.append(valor)
self.__index += 1
def saldo(self):
return self.__saldo
def nome(self):
return self.__nome
def __iter__(self):
return self
def __next__(self):
if self.__index == 0:
raise StopIteration
self.__index = self.__index - 1
return self.__historico[self.__index]
def __str__(self):
return f"Correntista: {self.__nome}\nSaldo: {self.__saldo}"
c = Correntista("Maria", 500.00)
print(c)
print(c.nome())
print(c.saldo())
c.deposito(25.50)
print(c.saldo())
c.saque(50.0)
c.saque(5000.0)
print(c.saldo())
print("------ Histórico ------")
for hist in c:
print(hist)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.