text stringlengths 37 1.41M |
|---|
#Двмерный массив
'''
def show_matrix(matrix):
for row in matrix: # запускает цикл каждый раз и у нас получается каждая строка
for x in row: # выводит строку
print(x, end=" ")
print()
m = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
show_matrix(m)
# print(m)
# print(m[0])
# print(m[0][1])
'''
import random
def init_matrix(matrix, min_n, max_n):
for i in range(len(matrix)):
for j in range(len(len(matrix[0]))):
matrix[i][j] = random.randint(min_n, max_n)
def show_matrix(matrix):
for row in matrix:
for x in row:
print(x, end=" ")
print()
n = 10
a = [[0]* n for i in range(n)]
init_matrix(a, 1, 101)
show_matrix(ф)
|
import random
def init_matrix(matrix, min_n, max_n): # заполняем случаными числами матрицу
for i in range(len(matrix)): # проходим по след строке (запоняем)
for j in range(len(matrix[0])): # проходим по строке (запоняем)
matrix[i][j] = random.randint(min_n, max_n)
def show_matrix(matrix): # выводим каждую строку матрицы
for row in matrix:
for x in row:
print(x, end=" ")
print()
def min_max(matrix): # Находим максимальное и минимальное значение каждой строки:
i = 0
for row in matrix:
my_min = matrix[i][0]
my_max = matrix[i][0]
for l in row:
if my_min > l:
my_min = l
if my_max < l:
my_max = l
i = i + 1
print("Your number max:", my_max)
print("Your number min:", my_min)
print()
def min_max_in_all_matrix(matrix): # Находим максимальное и минимальное значение всей матрицы:
my_min = matrix[0][0]
my_max = matrix[0][0]
for row in matrix:
for l in row:
if my_min > l:
my_min = l
if my_max < l:
my_max = l
print("Your number max in all matrix:", my_max)
print("Your number mix in all matrix:", my_min)
print()
n = 10
matrix = [[0] * n for i in range(n)] # заполняем матрицу нулями
init_matrix(matrix, 1, 101)
show_matrix(matrix)
min_max(matrix)
min_max_in_all_matrix(matrix) |
# printing pattern for pyramid
#
# #
# # #
# # # #
# # # # #
a = 6
for i in range(1, a):
print(a*" " + "# "*i)
a -= 1 |
import random
class Creature:
def __init__(self, creature_name, lvl):
"""
Constructor method.
Class fields are defined here, it is discourage to do this outside the __init__ function.
:param creature_name:
:param lvl:
"""
self.name = creature_name
self.level = lvl
def __repr__(self):
"""
"toString" function.
:return: String representation of the object.
"""
return "Level {} {} creature.".format(self.level, self.name)
def get_defensive_roll(self):
return random.randint(1, 12) * self.level
class Wizard(Creature): # Inheriting from the Creature class.
def __init__(self, wizard_name, lvl):
"""
Constructor method.
Class fields are defined here, it is discourage to do this outside the __init__ function.
:param wizard_name:
:param lvl:
"""
super().__init__(wizard_name, lvl)
def attack(self, creature):
print("The wizard {} attacks the {}!".format(self.name, creature.name))
# Using the D&D concept of a 12-sided die and levels to determine who wins.
# my_roll = random.randint(1, 12) * self.level
# creature_roll = random.randint(1, 12) * creature.level
my_roll = self.get_defensive_roll()
creature_roll = creature.get_defensive_roll()
print("{} rolls a(n) {} and {} rolls a(n) {}.".format(self.name, my_roll, creature.name, creature_roll))
if my_roll >= creature_roll:
print("{} kills the {}!".format(self.name, creature.name))
return True
else:
print("{} wins the fight!".format(creature.name))
return False
class SmallAnimal(Creature): # Unlike Java, you don't need to call the super constructor.
# Override this function in the Creature class.
def get_defensive_roll(self):
base_roll = super().get_defensive_roll()
return base_roll / 2 # Small creature is easier to defeat than others, hence the nerf.
class Dragon(Creature):
def __init__(self, dragon_name, lvl, scaliness, breaths_fire):
super().__init__(dragon_name, lvl)
self.scaliness = scaliness
self.breaths_fire = breaths_fire
def get_defensive_roll(self):
base_roll = super().get_defensive_roll()
# Traditional way.
fire_modifier = None
if self.breaths_fire:
fire_modifier = 5
else:
fire_modifier = 1
# 1 line Pythonic way: var = TRUE_VAL if TEST else FALSE_VALUE
fire_modifier = 5 if self.breaths_fire else 1
scale_modifier = self.scaliness / 10 # 10% of the scaliness affects the roll.
return base_roll * fire_modifier * scale_modifier
|
"""
Author: Andrew Siu (andrewjsiu@gmail.com)
-------------------------------------------------
Detecting Large Purchases within a Social Network
-------------------------------------------------
This program detects a significantly large purchase compared to previous
purchases made by one's social network. The purpose is to help the e-commerce
company flag up these large purchases for their friends to see, hoping that
they will be influenced to make similarly large purchases.
My approach is to first create a social network graph, which is characterized
as a set of user ids and a set of edges that indicate first-degree friendships.
There are many ways to represent this graph in Python, but I think the most
efficient way is to create a dictionary mapping each user id to a set of his
or her first-degree friends' user ids. It will then only take one step to find
all the first-degree friends given any user. Based on this network graph, I
can find the set of all second-degree friends by looping through the user's
first-degree friends and collecting all of the their first-degree friends
(not including the user himself of course). Similarly, all friends within
three degrees of separation are found by looping through one's second-degree
friends and collecting all their first-degree friends. We can do this for any
higher-degree of separation, but research has shown that almost everyone is
found within 6 degrees of separation.
As new events stream in from active users, I update the existing social network
graph if the event is 'befriend' or 'unfriend' and append the new purchase
data to the pandas dataframe of all purchases. Given a buyer's purchase event,
pandas allows me to select all previous purchases made by all neighbors within
D degrees of separation to the buyer. I then compute the mean and standard
deviation of the T most recent purchases made within this buyer's social network.
The next step is to detect and flag up any purchases that are more than 3
standard deviations above the mean and save them into the output file as
flagged_purchases.json. The hope is that showing these buyers' significantly
large purcahses to their friends will increase sales through peer influence.
"""
import sys
import json
import numpy as np
import pandas as pd
from network import network
batch_filepath = sys.argv[1]
stream_filepath = sys.argv[2]
output_filepath = sys.argv[3]
# A network graph consists of a set of vertices (user ids)
# and a set of edges (first-degree friendships)
# This network graph can then be used to compute higher-degree friendships
# To represent a network graph in Python, I create a dictionary
# mapping each user id to a set of first-degree friends user ids
graph = {}
list_purchases = []
with open(batch_filepath) as f:
for index, line in enumerate(f):
if index == 0:
param = json.loads(line)
D = np.int(param['D']) # D: number of degrees in social network
T = np.int(param['T']) # T: # of purchases in the user's network
else:
e = json.loads(line)
if e['event_type'] == 'purchase':
list_purchases.append(e)
elif e['event_type'] == 'befriend':
if e['id1'] not in graph.keys():
graph[e['id1']]={e['id2']}
else:
graph[e['id1']].add(e['id2'])
if e['id2'] not in graph.keys():
graph[e['id2']]={e['id1']}
else:
graph[e['id2']].add(e['id1'])
elif e['event_type'] == 'unfriend':
graph[e['id1']].remove(e['id2'])
graph[e['id2']].remove(e['id1'])
f.close()
# Create a dataframe of all previous purchases, which are then used for
# detecting a significantly large purchase among the new purchases
df_purchases = pd.DataFrame(list_purchases)
df_purchases['amount'] = df_purchases['amount'].astype(float)
df_purchases['timestamp'] = pd.to_datetime(df_purchases['timestamp'])
# As new events stream in from the users, we need to update the existing
# social network graph and the data of all previous purchases
# The most important task is to check whether a purchase is
# more than 3 standard deviations above the mean of
# T tracked purachses made by one's network of friends within
# D degrees of separation.
# Create and open a new file in write mode to collect flagged purchases
with open(output_filepath, 'w') as flagged_file:
# Read in the stream of new events one by one
with open(stream_filepath) as stream_file:
for event in stream_file:
e = json.loads(event)
if e['event_type'] == 'purchase':
# Select all purchases made by friends within
# D degrees of separation
rows = df_purchases['id'].isin(list(network(graph, e['id'], D)))
history = df_purchases[rows].sort_values(by='timestamp').amount
# Update the dataframe of all previous purchases
e['amount'] = np.float(e['amount'])
e['timestamp'] = pd.to_datetime(e['timestamp'])
df_purchases = df_purchases.append(e, ignore_index=True)
# Check if there are at least two previous purchases
# Compute the mean and standard deviation of T tracked purchases
if len(history)>=2:
mean = history.tail(T).mean()
std = history.tail(T).std(ddof=0)
if np.float(e['amount']) >= mean + 3 * std:
e['mean'] = '{:.2f}'.format(mean)
e['sd'] = '{:.2f}'.format(std)
e['amount'] = '{:.2f}'.format(e['amount'])
e['timestamp'] = str(e['timestamp'])
json.dump(e, flagged_file)
flagged_file.write('\n')
# Update the existing social network of frienships
elif e['event_type'] == 'befriend':
graph[e['id1']] = graph[e['id1']].union({e['id2']})
graph[e['id2']] = graph[e['id2']].union({e['id1']})
elif e['event_type'] == 'unfriend':
graph[e['id1']] = graph[e['id1']].difference({e['id2']})
graph[e['id2']] = graph[e['id2']].difference({e['id1']})
stream_file.close()
flagged_file.close()
|
class Node :
def __init__(self, idx, data = 0) : # Constructor
"""
id : Integer (1, 2, 3, ...)
"""
self.id = idx
self.data = data
self.connectedTo = dict()
def addNeighbour(self, neighbour , weight = 0) :
"""
neighbour : Node Object
weight : Default Value = 0
adds the neightbour_id : wt pair into the dictionary
"""
if neighbour.id not in self.connectedTo.keys() :
self.connectedTo[neighbour.id] = weight
# setter
def setData(self, data) :
self.data = data
#getter
def getConnections(self) :
return self.connectedTo.keys()
def getID(self) :
return self.id
def getData(self) :
return self.data
def getWeight(self, neighbour) :
return self.connectedTo[neighbour.id]
def __str__(self) :
return str(self.data) + " Connected to : "+ \
str([x.data for x in self.connectedTo])
class Graph :
totalV = 0 # total vertices in the graph
def __init__(self) :
"""
allNodes = Dictionary (key:value)
idx : Node Object
"""
self.allNodes = dict()
def addNode(self, idx) :
""" adds the node """
if idx in self.allNodes :
return None
Graph.totalV += 1
node = Node(idx=idx)
self.allNodes[idx] = node
return node
def addNodeData(self, idx, data) :
""" set node data acc to idx """
if idx in self.allNodes :
node = self.allNodes[idx]
node.setData(data)
else :
print("No ID to add the data.")
def addEdge(self, src, dst, wt = 0) :
"""
Adds edge between 2 nodes
Undirected graph
src = node_id = edge starts from
dst = node_id = edge ends at
To make it a directed graph comment the second line
"""
self.allNodes[src].addNeighbour(self.allNodes[dst], wt)
self.allNodes[dst].addNeighbour(self.allNodes[src], wt)
def isNeighbour(self, u, v) :
"""
check neighbour exists or not
"""
if u >=1 and u <= 81 and v >=1 and v<= 81 and u !=v :
if v in self.allNodes[u].getConnections() :
return True
return False
def printEdges(self) :
""" print all edges """
for idx in self.allNodes :
node = self.allNodes[idx]
for con in node.getConnections() :
print(node.getID(), " --> ",
self.allNodes[con].getID())
# getter
def getNode(self, idx) :
if idx in self.allNodes :
return self.allNodes[idx]
return None
def getAllNodesIds(self) :
return self.allNodes.keys()
# methods
def DFS(self, start) :
"""
start is an id of the start node
"""
# STACK
visited = [False]*Graph.totalV
if start in self.allNodes.keys() :
self.__DFSUtility(node_id = start, visited=visited)
else :
print("Start Node not found")
def __DFSUtility(self, node_id, visited) :
visited = self.__setVisitedTrue(visited=visited, node_id=node_id)
#print
print(self.allNodes[node_id].getID(), end = " ")
#Recursive Stack
for i in self.allNodes[node_id].getConnections() :
if visited[self.allNodes[i].getID()] == False :
self.__DFSUtility(node_id = self.allNodes[i].getID(),
visited=visited)
def BFS(self, start) :
"""
start is an id of the start node
"""
#Queue
visited = [False]*Graph.totalV
if start in self.allNodes.keys() :
self.__BFSUtility(node_id = start, visited=visited)
else :
print("Start Node not found")
def __BFSUtility(self, node_id, visited) :
queue = []
visited = self.__setVisitedTrue(visited=visited, node_id=node_id)
queue.append(node_id)
while queue != [] :
x = queue.pop(0)
#print
print(self.allNodes[x].getID(), end = " ")
for i in self.allNodes[x].getConnections() :
idx = self.allNodes[i].getID()
if visited[idx] == False :
queue.append(idx)
visited = self.__setVisitedTrue(visited=visited,
node_id=idx)
def __setVisitedTrue(self, visited, node_id) :
"""
Utility function for BFS and DFS
Through this function we will set visited[id] = True
Preprocessing node_id if required
Since now node_id is an integer it is not required to preprocess it
"""
visited[node_id] = True
return visited
"""
TESTING
"""
def test() :
g = Graph()
for i in range(6) :
g.addNode(i)
print("Vertices : ",g.getAllNodesIds())
g.addEdge(src = 0, dst = 1, wt = 5)
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
g.addEdge(5,4,8)
g.addEdge(5,2,1)
g.printEdges()
print("DFS : (starting with 0)")
g.DFS(0)
print()
print("BFS : (starting with 0)")
g.BFS(0)
print()
if __name__ == "__main__" :
test()
|
#!usr/bin/python
import sys
def reducer():
current_word=None
current_year=None
current_occurs=0
current_pages=0
for line in sys.stdin:
word,year,occurs,pages=line.split('\t')
if word==current_word and year==current_year:
current_occurs +=int(occurs)
current_pages +=int(pages)
else:
if current_word != None and current_year != None:
avg=current_occurs/current_pages
print "word: %s\tyear: %s\tavg: %d" % (current_word,current_year,avg)
current_word=word
current_year=year
current_occurs=int(occurs)
current_pages=int(pages)
avg=current_occurs/current_pages
print "word: %s\tyear: %s\tavg: %d" % (current_word,current_year,avg)
if __name__=="__main__":
reducer()
|
"""Simple functions to encode and decode an input string with an input password.
"""
import random
random_map = {}
q = random.randint(1,32)
def maplist():
"""Create a dictionary whose values and keys are all range from 32 to 127.
Values have shift right for some positions, which is generated randomly from 1 to 32
Return the generated map."""
global q
p = {}
for i in range(32+q,128):
p[i] = i-q-1
for i in range (32,32+q+1):
p[i] = i+127-32-q
return p
def reverse_maplist(dic):
"""Used to reverse a dictionary, of whose every value is unique.
Return the reversed dictionary after having checked the values to be unique.
"""
li = []
n = 0
for k in dic.values():
li.append(k)
n = n+1
for i in range(0,n):
k = li[i]
if li.count(k) != 1:
print "The value of the dic is not unique! can not reverse"
return
p = { v:k for k, v in dic.items()}
return p
def fill_pwd_len(password,length):
"""Modify the password to make the length of the password as specified.
Return the modified password.
"""
pw = ""
#If password is shorter than that is specified, cycle the password until it is as long as it.
if len(password) < length:
for i in range(0,length):
pw = pw+password[i%(len(password))]
#If the length of password is longer than that is specified, cut it as required.
else:
pw = password[:length]
return pw
def encode(str1, pwd):
"""Encode the input string with the input password.
All the characters whose ascii code range from 32 to 127 is valid for composing
the string and password.
"""
global random_map
result = ""
#generate the maplist
random_map = maplist()
#modify the password to make it to have the same length as the string
pwd2 = fill_pwd_len(pwd, len(str1))
#find the values in the maplist using the ascii code of every character as the key for both the string and password
#for every character in the string, the related values of the character and that of the characters at the same position in password
#will be added to the encoded string.
for i in range (0, len(str1)):
result = result + chr(random_map[ord(str1[i])]) + chr(random_map[ord(pwd2[i])])
i = i + 1
return result
def decode(str1,pwd):
"""Decode the encoded string with the input password.
Encoded string can be decoded to the original string only if the same password is used.
All the characters whose ascii code range from 32 to 127 is valid for composing
the string and password.
"""
str2 = ""
global random_map
#reverse the maplist
p2 = reverse_maplist(random_map)
#extract the useful part and get the original character using the reversed maplist
for i in range (0,len(str1)):
if i%2 == 0:
str2 = str2 + chr(p2[ord(str1[i])])
i = i+1
return str2
if __name__ == "__main__":
teststring = "a~s!sd fa^0sd"
testpwd = "^ sadf*!(("
encoded = encode(teststring,testpwd)
decoded = decode(encoded,testpwd)
assert(teststring != encode(teststring,testpwd))
assert(testpwd != encode(teststring,testpwd))
assert(encode(teststring,"wrongpwd") != encode(teststring,testpwd))
assert(teststring == decode(encoded,testpwd))
#print encoded
#print decoded
print "Success!"
|
def encode(input, password):
encoded_input = ''
for i in range(max(len(input),len(password))):
idxa = i % len(input)
idxb = i % len(password)
encoded_input += chr((ord(input[idxa]) + ord(password[idxb])) % 256)
return encoded_input
def decode(encoded_input, password):
decoded_input = ''
for i in range(max(len(encoded_input),len(password))):
idxa = i % len(encoded_input)
idxb = i % len(password)
decoded_input += chr((ord(encoded_input[idxa]) - ord(password[idxb])) % 256)
return decoded_input
if __name__ == "__main__":
teststring = "The quick brown 4356 jumped over the lazy dog."
testpwd = "password"
encoded = encode(teststring,testpwd)
assert(teststring != encode(teststring,testpwd))
assert(testpwd != encode(teststring,testpwd))
# assert(encode(testpwd,teststring) != encode(teststring,testpwd))
assert(encode(teststring,"wrongpwd") != encode(teststring,testpwd))
assert(teststring == decode(encoded,testpwd))
print "Success!"
|
"""
Assignment 1 by Yue Han
Create January 27, 2013
My algorithm is very simple. It is a mirror reverse of the unicode.
"""
def encode(input, password):
""" Takes two strings and transforms them into a third, encoded string """
encodeword = input + password
encodelist = list (encodeword)
for i in range(0, len(encodelist)):
encodelist[i] = 32+127-ord(encodelist[i])
for i in range (0,len(encodelist)):
encodelist[i] = chr(encodelist[i])
encoded_string = ''.join(encodelist)
return encoded_string
def decode(encoded, password):
""" Takes an encoded string (from encode function) and a password and returns the orginal string"""
decodelist = list(encoded)
for i in range(0,len(decodelist)):
decodelist[i] = 32+127-ord(decodelist[i])
for i in range (0,len(decodelist)):
decodelist [i] = chr (decodelist[i])
decodeword = ''.join(decodelist)
decoded_string = decodeword[0:(len(decodeword)-len(password))]
return decoded_string
if __name__ == "__main__":
teststring = "This is some text to be encoded"
testpwd = "Password"
encoded= encode(teststring,testpwd)
assert(teststring != encode(teststring,testpwd))
assert(testpwd != encode(teststring,testpwd))
assert(encode(teststring,"wrongpwd") != encode(teststring,testpwd))
assert(teststring == decode(encoded,testpwd))
print "Success!" |
#Alireza Louni
def encode(user, password):
encoded = []
for i in range(len(user)):
index_password= password[i % len(password)] # we need to obtain remainder (%) since "password" and "user" might have different letter long.
mixed = (ord(user[i]) + ord(index_password)) % 256 #each element of string for both of the user and the password are added together.
mixed_char=chr(mixed)
#should be less than 256, so we need to find remainder of 256.
encoded.append(mixed_char)#and then put together.
encoded="".join(encoded)#the output of the last stage is a list, so we need to put together each element of the list to get an encoded string(or list to string conversion)
return encoded
def decode(encoded, password):
decoded= [] #decoded = user
for i in range(len(encoded)):
index_password= password[i % len(password)]
mixed = (ord(encoded[i]) - ord(index_password)) % 256 #each element of string for both of the encoded and the password are added together.
#should be less than 256, so we need to find remainder of 256.
mixed_char=chr(mixed)
decoded.append(mixed_char)#and then put together.
decoded="".join(decoded)#list to string
return decoded #returns original user name.
if __name__ == '__main__':
teststring = "This is some text to be encoded"
testpwd = "Password"
encoded = encode(teststring,testpwd)
assert(teststring != encoded)
assert(testpwd != encode(teststring,testpwd))
assert(encode(teststring,"wrongpwd") != encode(teststring,testpwd))
assert(teststring == decode(encoded,testpwd))
print "Success!"
|
def get_indices_of_item_weights(weights, length, limit):
"""
YOUR CODE HERE
"""
# dict to store total weight and which indices
d = {}
# store the index numbers for answer
indices = []
# loop through list and add each weight to the list
# along with the index number
for i in range(length):
if weights[i] not in d:
d[weights[i]] = i
# check each weight. if (limit - weight) is in d we have
# another weight that adds up to the limit
for i in range(length):
if limit - weights[i] in d:
indices.append(i)
# if the list is not empty sort it in reverse order
# and return tuple of index nums
if len(indices) >= 1:
indices = sorted(indices, reverse=True)
return tuple(indices)
else:
return None
|
#!/usr/bin/env python
# coding: utf-8
print("This is a C' to F' converter.")
temp_in_celsius = input("Please enter a temperature, in C\n--> ")
temp_in_fahrenheit = float(temp_in_celsius) *9/5 + 32
print("The temperature in Fahrenheit is: {:.2f}".format(temp_in_fahrenheit))
|
from sys import exit
def_reason = "You died for unknown reason"
def die(why = def_reason):
""" Function for clean exit, printing the reason.
Default reason is unknown."""
print why, "Game over!"
exit(0)
def def_input(prompt = '> '):
return raw_input(prompt)
|
class BinaryTree:
def __init__(self,objkey):
self.key=objkey
self.leftChild=None
self.rightChild=None
def insertLeft(self,newNode):
if self.leftChild==None:
self.leftChild=BinaryTree(newNode)
else:
temp=BinaryTree(newNode)
temp.leftChild=self.leftChild
self.leftChild=temp
def insertRight(self,newNode):
if self.rightChild==None:
self.rightChild=BinaryTree(newNode)
else:
temp=BinaryTree(newNode)
temp.rightChild=self.rightChild
self.rightChild=temp
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootVal(self,obj):
self.key=obj
def getRootVal(self):
return self.key
'''
r=BinaryTree('a')
print (r.getRootVal())
print(r.getLeftChild())
r.insertLeft('b')
print(r.getLeftChild().getRootVal())
r.insertRight('c')
print(r.getLeftChild().getRootVal())
print(r.getRightChild().getRootVal())
'''
|
from pythonds.graphs import Graph
from pythonds.basic import Queue
def pathExists(start,end):
vertexQueue=Queue()
vertexQueue.enqueue(start)
while (vertexQueue.size()>0):
item=vertexQueue.dequeue()
if item.getId()==end.getId():
print ("path exists")
return True
else:
for vertex in item.getConnections():
if vertex.getColor()=="white":
vertex.setColor("gray")
vertexQueue.enqueue(vertex)
return False
g=Graph()
data=True
while data!=1000:
data=input("enter tuple")
if data!=1000:
g.addEdge(data[0],data[1])
while(True):
tuple=input("Please enter tuple u want to know the path")
print pathExists(g.getVertex(tuple[0]),g.getVertex(tuple[1]))
for vertex in g.getVertices():
g.getVertex(vertex).setColor("white")
|
# binary tree or not
from pythonds.trees.binaryTree import BinaryTree
prev=None
def isBinarySearchTree(root):
global prev
if root:
if not isBinarySearchTree(root.leftChild):
return False
if (prev and prev.key>root.key):
return False
prev=root
if not isBinarySearchTree(root.rightChild):
return False
return True
tree=BinaryTree(4)
tree.insertLeft(2)
tree.insertRight(5)
ls=tree.getLeftChild()
ls.insertLeft(1)
ls.insertRight(3)
print isBinarySearchTree(tree)
|
#!/usr/bin/python3
# run this script by: python3 -i build_pyramid_medium_v1.py
# the -i stands for interactive
# when you run the above command you will be greated by a python3 prompt ">>>"
# type in make_pyramid(n); sustitute an odd, not even, number for n
# this number will be the amount of stars on the bottom row of the pyramid
# you can keep trying numbers and building pyramids by calling the make_pyramid(n) function, again.
# use CTRL + D to quit python3 prompt and go back to BASH prompt ( or type quit() )
def make_pyramid(n):
count = 1 # this number is equal to the number of stars that will be printed
# this loop will run for as many times as needed in order for stars to reach (but not surpass) the
# number of stars specified by n, which is the max stars allowed in one row (in other words, stars in the bottom row)
# In the bottom row, there will not be any extra spaces. In other words, the bottom row is all stars
# all other rows need spaces on either side of the stars equal to the empty spaces needed to center
# the stars. There will only be an odd number of stars on every row [1, 3, 5, 7, ...... so on]
# now, iterate (n+1) number of times (n+1 as to count n because remember that range(n) is everything up to but not including n)
for row in range(n + 1):
# remember that stars will only be printed in medium amounts, so we can iterate n number of times
# only printing some stars if row is an odd number
# first iteration through, row = 1 and conditional runs
# second iteration through, row = 2 and conditinal (row % 2 == 1) is False so..
# third iteration through, row = 3 and conditional runs, sets stars = "***" and spaces = " " <-- 3 spaces
if row % 2 == 1:
# make stars equal to the row number
stars = "*" * row
# spaces are figured by the number of spaces left in a row after stars are made with equal amounts on both sides
# so for 3 stars in the row and 9 total spaces, 9 total spaces - 3 stars = 6 spaces left over. Use
# 3 spaces on either side of the stars in order to center the row!
spaces = " " * int((n - row) / 2)
# print out the row
print(spaces + str(stars) + spaces)
|
a = input()
b = input()
a = int(a)
b = int(b)
if a > 0 and b > 0:
print('1')
elif a < 0 and b > 0:
print('2')
elif a < 0 and b < 0:
print('3')
else:
print('4')
|
'''
Created on 27-Sep-2012
@author: Arvind Krishnaa Jagannathan
@author: Ramitha Chitloor
'''
from core.game.model.Pawn import Pawn
class Player(object):
'''
Defines the class player which will have
1. The list of pawns belonging to the player
2. The name of the player
3. Path array indicating
path[x] = the position of a pawn of the player after x moves
4. Indicates if the player is a computer or a human
'''
__pawnLists = []
__pathArray = []
__playerName = ""
__numberOfPawns = 4
__isSmartComputerPlayer = True
def __init__(self, playerName, pathArray, numberOfPawns, isComputerPlayer):
'''
Constructor
'''
self.__playerName = playerName
self.__pathArray = pathArray
self.__numberOfPawns = numberOfPawns
self.__isSmartComputerPlayer = isComputerPlayer
self.__pawnLists = []
for i in range(0,numberOfPawns):
pawnName = (self.__playerName, i)
self.__pawnLists.insert(i,Pawn(pawnName, self.__pathArray[0],True))
def getIsSmartComputerPlayer(self):
return self.__isSmartComputerPlayer
def printValue(self):
print "Player Name is: ", self.__playerName
print "Path Array is: ", self.__pathArray
print "Number of pawns are: ", len(self.__pawnLists)
for i in range(0,len(self.__pawnLists)):
pawn = self.__pawnLists[i]
print "Details of the pawn "+ str(pawn.getName()) + "\n Current Position: "+ str(pawn.getPosition()) + "\n Cumulative Dice Value: " + str(pawn.getCumulativeDiceValue())
def getPlayerName(self):
return self.__playerName
def getPawnList(self):
return self.__pawnLists
def setPawnList(self, pawnList):
self.__pawnLists = pawnList
def getPathArray(self):
return self.__pathArray
def getPawnWithPawnName(self, pawnName):
for pawn in self.__pawnLists:
if pawn.getName()[1] == pawnName:
return pawn |
'''
Created on 27-Sep-2012
@author: Arvind Krishnaa Jagannathan
@author: Ramitha Chitloor
'''
class Pawn(object):
'''
Class to define the attributes and properties of a pawn
1. Name of the pawn in the format (PlayerName, i)
2. The cumulative dice value
3. Position the pawn is on (x,y)
'''
@classmethod
def empty(self):
'''
Empty constructor
'''
return Pawn("",(0,0))
def __init__(self, name, position, isActive):
'''
Initializes the starting position of the pawn for a given player
position = player.path[0]
'''
self.__position = position
self.__name = name
self.__cumulativeDiceValue = 0
self.__isActive = isActive
def __eq__(self, other):
return self.getName() == other.getName()
def setName(self, name):
self.name = name
def getName(self):
return self.__name
def printDetail(self):
return self.__name[1], "at ", self.__position
def forceSet(self, value):
self.__cumulativeDiceValue = value
def setCumulativeDiceValue(self,diceValue,isHit):
if isHit:
self.__cumulativeDiceValue = 0
else:
self.__cumulativeDiceValue+= diceValue
def getCumulativeDiceValue(self):
return self.__cumulativeDiceValue
def setPosition(self, position):
self.__position = position
def getPosition(self):
return self.__position
def getIsActive(self):
return self.__isActive
def setIsActive(self, isActive):
self.__isActive = isActive
def setIsMovable(self, isMovable):
self.__isMovable = isMovable
def setHasBeenBlocked(self, hasBeenBlocked):
self.__hasBeenBlocked = hasBeenBlocked
def getIsMovable(self):
return self.__isMovable
def getHasBeenBlocked(self):
return self.__hasBeenBlocked
__name = ("", 0)
__cumulativeDiceValue = 0
__position = (0,0)
__isActive = True
__isMovable = True
__hasBeenBlocked = False |
#!/usr/bin/python
# Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
result = chr(ord(letter)+1)
if result > 'z': return 'a'
return result
print shift('a')
#>>> b
print shift('n')
#>>> o
print shift('z')
#>>> a
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 14:37:06 2021
@author: wooihaw
"""
# Challenge 3
alist = ['Python', 'Java', 'Perl', 'PHP', 'JavaScript', 'C++', 'C#', 'Ruby', 'R']
# Method 1 - Using for loop
blist = []
for i in alist:
if i[0].upper()=='P':
blist.append(i)
print(f'{blist=}')
# Method 2 - Using list comprehension
clist = [i for i in alist if i[0].upper()=='P']
print(f'{clist=}')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 14:47:23 2021
@author: wooihaw
"""
# Challenge 4
s1 = set(range(1, 101)) # number from 1 to 100
s2 = set(range(5, 101, 5)) # numbers divisible by 5
s3 = set(range(7, 101, 7)) # number divisible by 7
s = s1 - (s2 | s3) # numbers that are not divisible by 5 or 7
print(f'{s=}') |
def printm(A,n):
i=0
while i<n:
j=0
while j<n:
print(A[i][j], end=" ")
j+=1
i+=1
print()
def copym(A,B,n):
i=0
while i<n:
j=0
B.append([])
while j<n:
B[i].append(A[i][j])
j+=1
i+=1
def minor(A,i,j,n):
M = []
copym(A,M,n)
del M[i]
for i in range(len(A[0])-1):
del M[i][j]
return M
def det(A):
m = len(A)
n=len(A[0])
if m != n:
return None
if n == 1:
return A[0][0]
sig = 1
deter = 0
for j in range( n ):
deter += A[0][j]*sig*det(minor(A,0,j,n))
sig *= -1
return deter
mass=[]
i=0
n=int(input("Введите размерность матрицы "))
while i<n:
mass.append([])
j=0
while j<n:
num=int(input("Введите число "))
mass[i].append(num)
j+=1
i+=1
printm(mass,n)
print("определитель матрицы = "+str(det(mass)))
|
from turtle import Turtle, Screen
import random
def assign_colors(list_of_turtles):
for i in list_of_turtles:
color = random.choice(colors)
i.color(color)
colors.remove(color)
return list_of_turtles
def assign_position(list_of_turtles):
y = -120
for i in list_of_turtles:
i.penup()
i.goto(x=-240, y=y)
y += 40
screen = Screen()
colors = ['red', 'orange', 'gold', 'green', 'blue', 'deep sky blue', 'purple']
screen.setup(width=500, height=400)
finish = False
user_bet = screen.textinput(title="Bet Decision",
prompt="Who's gonna win the race? Choose between 'red', 'orange', 'gold', 'green', 'blue', 'deep sky blue', 'purple'")
# creating turtles that will race
turtles = []
for new_turtle in range(0, 7):
new_turtle = Turtle(shape="turtle")
new_turtle.shapesize(2, 2, 4)
turtles.append(new_turtle)
assign_colors(turtles)
assign_position(turtles)
if user_bet:
finish = False
while not finish:
for turtle in turtles:
if turtle.xcor() > 230:
finish = True
if user_bet == turtle.pencolor():
print(f"Congrats! The {turtle.pencolor()} turtle won! You're lucky :) ")
else:
print(f"The winner is {turtle.pencolor()}! Not your best shot, dude :( Try again.")
jump_distance = random.randint(0, 15)
turtle.forward(jump_distance)
screen.exitonclick()
|
def bmi_check(bmi):
if bmi <=18.5:
print("Your bmi is " + str(round(bmi, 2)) + ", which means you're underweight.")
elif bmi > 18.5 and bmi <= 25:
print("Your bmi is " + str(round(bmi, 2)) + ", which means have normal weight.")
elif bmi > 25 and bmi <= 30:
print("Your bmi is " + str(round(bmi, 2)) + ", which means you're slightly overweight.")
elif bmi > 30 and bmi <= 35:
print("Your bmi is " + str(round(bmi, 2)) + ", which means you're obese.")
else:
print("Dude, your bmi is " + str(round(bmi, 2)) + ", which means you're clinically obese. Lose some weight!")
def calculate_bmi(height, weight):
return weight/(height**2)
again = "y"
while again.lower() == 'y':
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
bmi = calculate_bmi(height, weight)
bmi_check(bmi)
again = input("Again? y/n ")
|
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
coffee_machine = CoffeeMaker()
menushka = Menu()
money = MoneyMachine()
def machine_in_operation():
off = False
while not off:
options = menushka.get_items()
user_input = input(f"What would you like to drink today? ({options}): ")
try:
if user_input == "off":
off = True
elif user_input == "report":
coffee_machine.report()
money.report()
else:
drink = menushka.find_drink(user_input)
is_enough_resources = coffee_machine.is_resource_sufficient(drink)
is_money_good = money.make_payment(drink.cost)
if is_enough_resources and is_money_good:
coffee_machine.make_coffee(drink)
except:
print("ERROR! Try again")
machine_in_operation()
|
#################################
# IML_T3 #
#################################
#
# File Name: main.py
#
# Course: 252-0220-00L Introduction to Machine Learning
#
# Authors: Adrian Esser (aesser@student.ethz.ch)
# Abdelrahman-Shalaby (shalabya@student.ethz)
import pandas as pd
import tensorflow as tf
import numpy as np
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt
#################################
# 1) Import and preprocess data #
#################################
train_data = pd.read_hdf("train.h5", "train")
test_data = pd.read_hdf("test.h5", "test")
# Load
y_train = np.array(train_data)[:,0]
X_train = np.array(train_data)[:,1:]
X_test = np.array(test_data)
N = np.shape(X_train)[1] # number of features in input vector
# Convert classes to one hot encodings
#print(y_train) # before
lb = preprocessing.LabelBinarizer()
lb.fit(y_train)
y_train = lb.transform(y_train)
L = np.shape(y_train)[1] # the number of labels
#print(y_train) # after
# Mean remove the training and test data
X_train = (X_train - np.mean(X_train, axis=0))/(np.std(X_train, axis=0))
X_test = (X_test - np.mean(X_test, axis=0))/(np.std(X_train, axis=0))
# Split training data further into training and validation sets
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.10, random_state=42)
# NOTE: uncomment if you want to see plot of histogram
#plt.hist(X_train[:,0])
#plt.show()
#################################
# 2) Set up Network Structure #
#################################
RANDOM_SEED = 42
tf.set_random_seed(RANDOM_SEED)
alpha = 1 # learning rate
inputs = tf.placeholder(tf.float32, (None, N))
y_true = tf.placeholder(tf.float32, (None, L))
def init_weights(shape):
""" Weight initialization """
weights = tf.random_normal(shape, stddev=0.1)
bias = tf.random_normal((1,shape[1]), stddev=0.1)
return tf.Variable(weights), tf.Variable(bias)
# First hidden layer
nhu1 = 200
w1, b1 = init_weights((N, nhu1))
o1 = tf.nn.relu(tf.matmul(inputs, w1) + b1)
nhu2 = 200
w2, b2 = init_weights((nhu1, nhu2))
o2 = tf.nn.relu(tf.matmul(o1, w2) + b2)
nhu3 = 200
w3, b3 = init_weights((nhu2, nhu3))
o3 = tf.nn.relu(tf.matmul(o2, w3) + b3)
#nhu4 = 200
#w4, b4 = init_weights((nhu3, nhu4))
#o4 = tf.nn.relu(tf.matmul(o3, w4) + b4)
# Second hidden layer
nhuO = L
wO, bO = init_weights((nhu3, nhuO))
out = tf.nn.relu(tf.matmul(o3, wO) + bO)
# Softmax function
y_hat = tf.nn.softmax(out)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_true, logits=y_hat))
opt = tf.train.GradientDescentOptimizer(alpha).minimize(cost)
acc = tf.metrics.accuracy(labels=tf.argmax(y_true,1), predictions=tf.argmax(y_hat,1))
#################################
# 3) Train Network! #
#################################
sess = tf.Session()
init_g = tf.global_variables_initializer()
init_l = tf.local_variables_initializer()
sess.run(init_g)
sess.run(init_l)
k = 20 # number of batches
kf = KFold(n_splits=k, shuffle=True)
epochs = 10
acc_val_vect = []
acc_train_vect = []
for e in range(epochs):
print("Epoch {}/{}".format(e+1, epochs))
# First evaluate performance on validation set
acc_val = sess.run(acc, feed_dict={inputs: X_val, y_true: y_val})[0]
acc_train = sess.run(acc, feed_dict={inputs: X_train, y_true: y_train})[0]
acc_val_vect.append(acc_val)
acc_train_vect.append(acc_train)
# Split data into batches and train
for _, t_idx in kf.split(X_train):
X_b = X_train[t_idx,:]
y_b = y_train[t_idx,:]
_ = sess.run(opt, feed_dict={inputs:X_b, y_true:y_b})
# Final performance on both sets
acc_val = sess.run(acc, feed_dict={inputs: X_val, y_true: y_val})[0]
acc_train = sess.run(acc, feed_dict={inputs: X_train, y_true: y_train})[0]
acc_val_vect.append(acc_val)
acc_train_vect.append(acc_train)
e_vect = range(epochs+1)
plt.plot(e_vect, acc_train_vect, 'b')
plt.plot(e_vect, acc_val_vect, 'm')
plt.show()
|
# Import the GPIO library
import RPi.GPIO as IO
# Define motor pin on Raspberry Pi
motor_pin = 12
# Set the mode as IO
IO.setmode(IO.BOARD)
IO.setup(motor_pin, IO.OUT)
# Set PWM frequency
pwm = IO.PWM(motor_pin, 100)
# Define the function that reverses the PWM value for a human readable format.
def true_pwm (num):
true_pwm = abs(num - 100.0)
return true_pwm
while True:
try:
value = float(input("Motor percentage float: "))
pwm.start(true_pwm(value))
print("Motor speed set to {}%".format(true_pwm(value))
except KeyboardInterrupt:
pwm.stop()
IO.cleanup()
print("Ctl C pressed - ending program")
except ValueError:
print("Error! Not a usable value.")
# better try again... Return to the start of the loop
continue
|
#HYERICA 19년 1학기 컴퓨팅적 사고 기말고사 예상문제(학생제공용)
#1번 문제 <점수 입력 후 성적 출력하기>
print("점수를 입력하세요:")
score = int(input())
if score>=90:
print("A")
elif score>=80:
print("B")
elif score>=70:
print("C")
elif score>=60:
print("D")
else:
print("F")
|
x = int(input("Enter the 1st number: "))
y = int(input("Enter the 2nd number: "))
temvariable = x
x = y
y = temvariable
print('The value of x after swapping: {}', x)
print('The value of y after swapping: {}', y) |
from random import randrange
number=randrange(1,1000)
secret=int(raw_input("We are going to play higher and lower, guess a number from 1 to 1000.\n>"))
while(secret!=number):
if(secret<number):
print("Guess Higher")
secret=int(raw_input("Enter another number.\n>"))
elif(secret>number):
print("Guess Lower")
secret=int(raw_input("Enter another number.\n>"))
print("Congrats you got it, the right number was {}!".format(number))
|
# coding=utf-8
# author='HopePower'
# time='2020/8/27 23:17'
# 列表推导支持多重循环
matrix = [[1, 2, 3], [4, 5, 5], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print flat
squared = [[x**2 for x in row] for row in matrix]
print squared
# 超过两个表达式的列表推导是很难理解的,应该尽量避免 |
import pygame
import piece as p
#definition of the class responsible for the board and all behaviour of pieces inside it
class table:
def __init__(self):
#creator of the class table
self.pieceEliminated = False
self.comboPossible = False
#the two variables above are used to indicate characteristics of one particular move
#below is the creation of the board - the variable grid is a matrix that
#keeps all the information neeeded (which positions are occupied and what is the kind
#of piece occupying it)
self.size = 8
self.grid = [[0 for x in range(self.size)] for y in range(self.size)]
#below the initial conditions of the match are set
for y in range(self.size):
for x in range(self.size):
if ((y % 2 == 0) and (x % 2 != 0)):
if (y < 3):
self.grid[x][y] = p.piece("white", False)
elif (y > 4):
self.grid[x][y] = p.piece("red", False)
elif ((y % 2 != 0) and (x % 2 == 0)):
if (y < 3):
self.grid[x][y] = p.piece("white", False)
elif (y > 4):
self.grid[x][y] = p.piece("red", False)
def drawTable(self, gameDisplay):
#function responsible for drawing the board at each movement.
#first it draws the checkered background and then it draws the pieces according to their
#positions on the matrix grid
pygame.draw.rect(gameDisplay, (255, 255, 255), (0,0,480,480), 0)
for y in range(self.size):
for x in range(self.size):
#draws the background board
if ((y % 2 == 0) and (x % 2 != 0)):
pygame.draw.rect(gameDisplay, (0,0,0), (x*60, y*60, 60, 60), 0)
elif ((y % 2 != 0) and (x % 2 == 0)):
pygame.draw.rect(gameDisplay, (0,0,0), (x*60, y*60, 60, 60), 0)
#drawing the pieces in the table
if self.grid[x][y] != 0:
self.grid[x][y].drawPiece(gameDisplay, x, y)
def isGameOver(self):
#checks if the game is over by counting all the pieces in the table
#if one color has no pieces, the match has ended
redPieces = 0
whitePieces = 0
for y in range (self.size):
for x in range (self.size):
if self.grid[x][y] != 0:
if self.grid[x][y].getColorTag() == "red":
redPieces += 1
elif (self.grid[x][y].getColorTag() == "white"):
whitePieces += 1
if ((redPieces == 0) or (whitePieces == 0)):
return True
else:
return False
def isValidMove(self, x, y, newX, newY, turn):
#checks if a given move is valid and returns true if it is and false if it is not
#if a move should eliminate a piece, it does so already
auxX = x
auxY = y
foundPiece = False
#first check: new position chosen by user is a "black" box
if (newY % 2 == 0 and not(newX % 2 != 0)):
return False
if (newY % 2 != 0 and not(newX % 2 == 0)):
return False
#second check: new position is not already occupied by another piece
if (self.grid[newX][newY] != 0):
return False
#from here on out, there are two possibilites
#possibility 1: the piece the user is trying to move is not a king, therefore it can only
#move one square at a time (except when eliminating opposing pieces) and it can only move forward
#possibility 2: the piece the user is trying to move is a king, therefore it can move more than
#one square at a time and it can move backwards
if not (self.grid[x][y].isKing):
#implementation of possibility 1
if (newY > y):
if (turn == 'red'):
print("Move not possible.")
return False
print ("Piece going down.")
if newX > x:
print("Piece going right.")
if (newX - x == 1) and (newY - y == 1) and (self.grid[newX][newY] == 0):
print("Move possible!")
return True
elif (newX - x == 2) and (newY - y == 2) and (self.grid[newX-1][newY-1] != 0):
if(self.grid[newX-1][newY-1].getColorTag() != turn):
print("Move possible, piece eliminated!")
self.grid[newX-1][newY-1] = 0
self.pieceEliminated = True
return True
else:
print("Move not possible.")
return False
else:
print("Move not possible.")
return False
else:
print("Piece going left.")
if (x - newX == 1) and (newY - y == 1) and (self.grid[newX][newY] == 0):
print("Move possible!")
return True
elif (x - newX == 2) and (newY - y == 2) and (self.grid[newX+1][newY-1] != 0):
if (self.grid[newX+1][newY-1].getColorTag() != turn):
print("Move possible, piece eliminated!")
self.grid[newX+1][newY-1] = 0
self.pieceEliminated = True
return True
else:
print("Move not possible.")
else:
print("Move not possible.")
return False
else:
if (turn == "white"):
print("Move not possible.")
return False
print ("Piece going up.")
if newX < x:
print("Piece going left.")
if (x - newX == 1) and (y - newY == 1) and (self.grid[newX][newY] == 0):
print("Move possible!")
return True
elif (x - newX == 2) and (y - newY == 2) and (self.grid[newX+1][newY+1] != 0):
if (self.grid[newX+1][newY+1] != turn):
print("Move possible, piece eliminated!")
self.grid[newX+1][newY+1] = 0
self.pieceEliminated = True
return True
else:
print("Move not possible.")
return False
else:
print("Move not possible.")
return False
else:
print("Piece going right.")
if (newX - x == 1) and (y - newY == 1) and (self.grid[newX][newY] == 0):
print("Move possible!")
return True
elif (newX - x == 2) and (y - newY == 2) and (self.grid[newX-1][newY+1] != 0):
if (self.grid[newX-1][newY+1].getColorTag() != turn):
print("Move possible, piece eliminated!")
self.grid[newX-1][newY+1] = 0
self.pieceEliminated = True
return True
else:
print("Move not possible.")
return False
else:
print("Move not possible.")
return False
else:
#implementation of possibility 2
if (newY > y):
print ("Piece going down.")
if newX > x:
print("Piece going right.")
while newY > auxY:
auxY += 1
auxX += 1
if (self.grid[auxX][auxY] != 0):
print("Found a piece of the color " + self.grid[auxX][auxY].getColorTag() + " on the way.")
if (self.grid[auxX][auxY].getColorTag() == turn):
print("The color of both pieces are the same")
return False
foundPiece = True
if (foundPiece):
if (self.grid[auxX+1][auxY+1] != 0):
print("The space next to the piece on the trajectory is not empty.")
return False
else:
auxY += 1
auxX += 1
if ((auxY == newY) and (auxX == newX)):
print("Move possible, piece eliminated.")
self.pieceEliminated = True
self.grid[auxX-1][auxY-1] = 0
return True
else:
print("Move incorrect.")
return False
print("Move possible.")
return True
else:
print("Piece going left.")
while newY > auxY:
auxY += 1
auxX -= 1
if (self.grid[auxX][auxY] != 0):
print("Found a piece of the color " + self.grid[auxX][auxY].getColorTag() + " on the way.")
if (self.grid[auxX][auxY].getColorTag() == turn):
print("The color of both pieces are the same")
return False
foundPiece = True
if (foundPiece):
if (self.grid[auxX-1][auxY+1] != 0):
print("The space next to the piece on the trajectory is not empty.")
return False
else:
auxY += 1
auxX -= 1
if ((auxY == newY) and (auxX == newX)):
print("Move possible, piece eliminated.")
self.pieceEliminated = True
self.grid[auxX+1][auxY-1] = 0
return True
else:
print("Move incorrect.")
return False
print("Move possible.")
return True
else:
print ("Piece going up.")
if newX < x:
print("Piece going left.")
while newY < auxY:
auxY -= 1
auxX -= 1
if (self.grid[auxX][auxY] != 0):
print("Found a piece of the color " + self.grid[auxX][auxY].getColorTag() + " on the way.")
if (self.grid[auxX][auxY].getColorTag() == turn):
print("The color of both pieces are the same")
return False
foundPiece = True
if (foundPiece):
if (self.grid[auxX-1][auxY-1] != 0):
print("The space next to the piece on the trajectory is not empty.")
return False
else:
auxY -= 1
auxX -= 1
if ((auxY == newY) and (auxX == newX)):
print("Move possible, piece eliminated.")
self.pieceEliminated = True
self.grid[auxX+1][auxY+1] = 0
return True
else:
print("Move incorrect.")
return False
print("Move possible.")
return True
else:
print("Piece going right.")
while newY < auxY:
auxY -= 1
auxX += 1
if (self.grid[auxX][auxY] != 0):
print("Found a piece of the color " + self.grid[auxX][auxY].getColorTag() + " on the way.")
if (self.grid[auxX][auxY].getColorTag() == turn):
print("The color of both pieces are the same.")
return False
foundPiece = True
if (foundPiece):
if (self.grid[auxX+1][auxY-1] != 0):
print("The space next to the piece on the trajectory is not empty.")
return False
else:
auxY -= 1
auxX += 1
if ((auxY == newY) and (auxX == newX)):
print("Move possible, piece eliminated.")
self.pieceEliminated = True
self.grid[auxX-1][auxY+1] = 0
return True
else:
print("Move incorrect.")
return False
print("Move possible")
return True
def isComboPossible(self, gameDisplay, turn, x, y):
#after a piece has eliminated an opposing piece, it might be able to do a "combo"
#this function checks whether that's the case for a given situation and it basically
#has two outpus: one is through the class variable comboPossible and the other is
#through an array, which informs what "kinds" of combos are possible (here, kind refers
#to the direction of the combo)
print("Verifying possibility of combo.")
comboType = [False, False, False, False]
if (x > 0 and x < 7 and y > 0 and y < 7 and self.pieceEliminated):
#find a way to store possibilities of combos
if (self.grid[x-1][y-1] != 0 and self.grid[x-1][y-1].getColorTag() != turn):
if (x >= 2 and y >= 2):
if (self.grid[x-2][y-2] == 0):
print("Possibility of type 1 combo found.")
comboType[0] = True
if (self.grid[x+1][y-1] != 0 and self.grid[x+1][y-1].getColorTag() != turn):
if (x <= 5 and y >= 2):
if (self.grid[x+2][y-2] == 0):
print("Possibility of type 2 combo found.")
comboType[1] = True
if (self.grid[x+1][y+1] != 0 and self.grid[x+1][y+1].getColorTag() != turn):
if (x <= 5 and y <= 5):
if (self.grid[x+2][y+2] == 0):
print("Possibility of type 3 combo found.")
comboType[2] = True
if (self.grid[x-1][y+1] != 0 and self.grid[x-1][y+1].getColorTag() != turn):
if (x >= 2 and y <= 5):
if (self.grid[x-2][y+2] == 0):
print("Possibility of type 4 combo found")
comboType[3] = True
if (comboType == [False, False, False, False]):
print("No combo possibility found.")
return comboType
def handleCombo(self, gameDisplay, comboType, x, y, xCombo, yCombo, turn):
#if a combo is possible and the user chooses to do it, this function handles it
#this function basically continues the movement of a piece, after it has already eliminated
#an opposing piece in its "base movement"
print("Entered function handleCombo!")
choiceCombo = [False, False, False, False]
comboType_aux = [False, False, False, False]
validChoiceFound = False
done = False
if ((xCombo == x - 2) and (yCombo == y - 2)):
print("Type 1 combo selected")
choiceCombo[0] = True
validChoiceFound = True
elif ((xCombo == x + 2) and (yCombo == y - 2)):
print("Type 2 combo selected")
choiceCombo[1] = True
validChoiceFound = True
elif((xCombo == x + 2) and (yCombo == y + 2)):
print("Type 3 combo selected")
choiceCombo[2] = True
validChoiceFound = True
elif((xCombo == x - 2) and (yCombo == y + 2)):
print("Type 4 combo selected")
choiceCombo[3] = True
validChoiceFound = True
if validChoiceFound:
if(choiceCombo[0] and comboType[0]):
self.grid[xCombo][yCombo] = p.piece(turn, self.grid[x][y].getKing())
self.grid[x][y] = 0
self.grid[xCombo+1][yCombo+1] = 0
elif(choiceCombo[1] and comboType[1]):
self.grid[xCombo][yCombo] = p.piece(turn, self.grid[x][y].getKing())
self.grid[x][y] = 0
self.grid[xCombo-1][yCombo+1] = 0
elif(choiceCombo[2] and comboType[2]):
self.grid[xCombo][yCombo] = p.piece(turn, self.grid[x][y].getKing())
self.grid[x][y] = 0
self.grid[xCombo-1][yCombo-1] = 0
elif(choiceCombo[3] and comboType[3]):
self.grid[xCombo][yCombo] = p.piece(turn, self.grid[x][y].getKing())
self.grid[x][y] = 0
self.grid[xCombo+1][yCombo-1] = 0
comboType_aux = self.isComboPossible(gameDisplay, turn, xCombo, yCombo)
done = True
self.crownAKing(xCombo, yCombo, turn)
return comboType_aux
def crownAKing(self, x, y, turn):
#this function turns a regular piece into a "king" peace when it has reached the opposing
#end of the table
if (turn == "red"):
if (y == 0):
self.grid[x][y].setKing()
else:
if (y == 7):
self.grid[x][y].setKing()
def movePiece(self, gameDisplay, event, turn):
#this function is called by main.py every time a use chooses a piece he wishes to move
#it aggregates the functions drawTable(), isValidMove(), isComboPossible(), handleCombo()
# and crownAKing()
#it is the backbone of the game's functionality
x = event.pos[0]//60
y = event.pos[1]//60
hasMoved = False
if (self.grid[x][y] != 0):
if (turn == self.grid[x][y].getColorTag()):
pygame.draw.rect(gameDisplay, (255,0,0), (x*60, y*60, 60, 60), 2)
pygame.display.update()
done = False
while not done:
for event in pygame.event.get():
if (event.type == pygame.QUIT):
done = True
if (event.type == pygame.KEYDOWN and event.key == 27):
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
newX = event.pos[0]//60
newY = event.pos[1]//60
if (newX == x) and (newY == y):
done = True
else:
print("Trying to move a piece of the color: " + turn)
self.pieceEliminated = False
if (self.isValidMove(x, y, newX, newY, turn)):
self.grid[newX][newY] = p.piece(turn, self.grid[x][y].getKing())
self.grid[x][y] = 0
self.crownAKing(newX, newY, turn)
done = True
hasMoved = True
self.comboPossible = False
comboType = self.isComboPossible(gameDisplay, turn, newX, newY)
if not (comboType == [False, False, False, False]):
self.comboPossible = True
pygame.draw.rect(gameDisplay, (0,0,0), (x*60, y*60, 60, 60), 2)
self.drawTable(gameDisplay)
pygame.display.update()
while self.comboPossible:
if comboType[0]:
pygame.draw.rect(gameDisplay, (255,0,0), ((newX-2)*60, (newY-2)*60, 60, 60), 2)
if comboType[1]:
pygame.draw.rect(gameDisplay, (255,0,0), ((newX+2)*60, (newY-2)*60, 60, 60), 2)
if comboType[2]:
pygame.draw.rect(gameDisplay, (255,0,0), ((newX+2)*60, (newY+2)*60, 60, 60), 2)
if comboType[3]:
pygame.draw.rect(gameDisplay, (255,0,0), ((newX-2)*60, (newY+2)*60, 60, 60), 2)
pygame.display.update()
self.comboPossible = False
done = False
while not done:
for event in pygame.event.get():
if (event.type == pygame.QUIT):
done = True
if (event.type == pygame.KEYDOWN and event.key == 27):
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
xCombo = event.pos[0]//60
yCombo = event.pos[1]//60
comboType = self.handleCombo(gameDisplay, comboType, newX, newY, xCombo, yCombo, turn)
if not (comboType == [False, False, False, False]):
self.comboPossible = True
print(self.comboPossible)
self.drawTable(gameDisplay)
pygame.display.update()
newX = xCombo
newY = yCombo
done = True
if not hasMoved:
return turn
else:
if (turn == "red"):
return "white"
else:
return "red" |
"""Calculate the Hamming difference between two DNA strands."""
def hamming(strand1, strand2):
count = 0
if len(strand1) != len(strand2):
raise ArgumentError("The lists are different lengths")
if strand1 == "" or strand2 == "":
raise Arugument("The strings are empty.")
return sum([count + 1 for i, letter in enumerate(strand1) if letter != strand2[i]])
|
# Decorator that registers processors to Detectors
def register_proc(*classes):
"""
A simple decorator that attaches the registered functions
to the appropriate classes
"""
def decorated(f):
for cls in classes:
if hasattr(cls, 'processors'):
cls.processors.append(f)
else:
setattr(cls, 'processors', [f])
return f
return decorated
class colors:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
import inspect
def whoami():
""" Returns the name of the calling function """
return inspect.stack()[1][3]
class UserLog:
def info(self, format_string):
print("{0}[*] {1}{2}".format(colors.GREEN,format_string,colors.END))
def warn(self, format_string, bold=True):
if bold:
print("{0}{1}[*] {2}{3}".format(colors.YELLOW,colors.BOLD,format_string,colors.END))
else:
print("{0}[*] {1}{2}".format(colors.YELLOW,format_string,colors.END))
def error(self, format_string):
print("{0}[*] {1}{2}".format(colors.RED,format_string,colors.END))
|
# Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
# 0 <= a, b, c, d < n
# a, b, c, and d are distinct.
# nums[a] + nums[b] + nums[c] + nums[d] == target
# You may return the answer in any order.
# Example 1:
# Input: nums = [1,0,-1,0,-2,2], target = 0
# Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
# Example 2:
# Input: nums = [2,2,2,2,2], target = 8
# Output: [[2,2,2,2]]
# Constraints:
# 1 <= nums.length <= 200
# -109 <= nums[i] <= 109
# -109 <= target <= 109
# Solution in Python 3 (beats 100.00%) (48 ms) ( O(n³) ) (Asymptotic Analysis)
# Asymptotic Worst Case Analysis:
# For ease of analysis, we will assume that the input list is sorted since sorting only takes O(n log n) time. The worst case occurs if the target is equal to the sum of the four greatest elements in the list. This is because the search would have to continue until the very end to find the desired quadruplet (a,b,c,d). For example, a list of the form N = [1,2,3,4,5,6,7,8,9,10] with target = 34 would require a complete run through all iterations of the three nested for loops. Note that the reason that there are only three nested for loops even though we are looking for a quadruplet is because finding the triplet (a,b,c) determines a unique value of d which will lead to a sum of target. Thus, we only need to search for triplets (a,b,c) such that target - (a+b+c) is in the original list.
# Observe that in the worst case, there is only one valid solution and that is found by adding the last
# four (i.e. the largest four) elements of the input list. Specifically, the desired quadruplet will be ( N[n-4], N[n-3], N[n-2], N[n-1] ),
# where N is the sorted input list and n is its length. The outer for loop will have to iterate from i = 1 to i = n-5 with a guarantee of
# failure in finding the desired quadruplet since the lowest element in the desired quadrauplet occurs at index n-4. For each iteration of
# the outer for loop, the remaining two nested inner for loops iterate through the remaining elements to the right of index i, looking at
# all possible ordered pairs (b,c) such that target - (a+b+c) is in the original list. This is an O(n²) search that occurs within each
# iteration of the outer for loop. It is guaranteed to fail in the worst case for outer loop indices from i = 1 to i = n-5. Thus in the
# worst case this algorithm is O(n³).
class Solution:
def fourSum(self, n: List[int], t: int) -> List[List[int]]:
if not n: return []
n.sort()
L, N, S, M = len(n), {j:i for i,j in enumerate(n)}, set(), n[-1]
for i in range(L-3):
a = n[i]
if a + 3*M < t: continue
if 4*a > t: break
for j in range(i+1,L-2):
b = n[j]
if a + b + 2*M < t: continue
if a + 3*b > t: break
for k in range(j+1,L-1):
c = n[k]
d = t-(a+b+c)
if d > M: continue
if d < c: break
if d in N and N[d] > k: S.add((a,b,c,d))
return S
|
'''
Author: Michele Alladio
es:
An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.
For example:
9 is an Armstrong number, because 9 = 9^1 = 9
10 is not an Armstrong number, because 10 != 1^2 + 0^2 = 1
153 is an Armstrong number, because: 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
154 is not an Armstrong number, because: 154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190
Write some code to determine whether a number is an Armstrong number.
'''
def armstrongNumber(number):
powsSum = 0
powValue = 0
for value in str(number):
powValue += 1 #calcola il valore della potenza in base alle cifre del numero
for value in str(number): #somma delle potenze
powsSum += int(value) ** powValue
if powsSum == number: #se la somma delle potenze è = al numero
print(f"{number} is an Armstrong number")
else: #se la somma delle potenze è != dal numero
print(f"{number} isn't an Armstrong number")
def main():
number = int(input("Inserisci un numero > 0: "))
if number < 0: #controllo inserimento del numero
print("Il numero dev'essere positivo.")
return
else:
armstrongNumber(number)
if __name__ == "__main__":
main() |
'''
Author: Michele Alladio
es:
A Pythagorean triplet is a set of three natural numbers, {a, b, c}, for which,
a**2 + b**2 = c**2
and such that,
a < b < c
For example,
3**2 + 4**2 = 9 + 16 = 25 = 5**2.
Given an input integer N, find all Pythagorean triplets for which a + b + c = N.
For example, with N = 1000, there is exactly one Pythagorean triplet for which a + b + c = 1000: {200, 375, 425}.
'''
def pythagoreanTriplet(number):
numberList = [k for k in range(1, number)] #lista dei numeri da 1 alla soglia
#triplo ciclo per sommare insieme chiascun numero con altri due numeri nella lista
for a in numberList:
for b in range(a+1, len(numberList)+1):
for c in range(b+1, len(numberList)+1):
#notare: con questi 3 cicli sarà sempre vera la condizione a<b<c
if a+b+c == number and a**2 + b**2 == c**2: #se i tre numeri sommati danno la soglia ed i quadrati di a e b sommati danno il quadrato di c
print(a,b,c) #Pythagoric triplet
def main():
number = int(input("Insert a number: "))
pythagoreanTriplet(number)
if __name__ == "__main__":
main()
|
'''
In this exercise, let's try to solve a classic problem.
Bob is a thief. After months of careful planning, he finally manages to crack the security systems of a high-class apartment.
In front of him are many items, each with a value (v) and weight (w). Bob, of course, wants to maximize the total value he can get; he would gladly take all of the items if he could. However, to his horror, he realizes that the knapsack he carries with him can only hold so much weight (W).
Given a knapsack with a specific carrying capacity (W), help Bob determine the maximum value he can get from the items in the house. Note that Bob can take only one of each item.
All values given will be strictly positive. Items will be represented as a list of pairs, wi and vi, where the first element wi is the weight of the ith item and vi is the value for that item.
For example:
Items: [ { "weight": 5, "value": 10 }, { "weight": 4, "value": 40 }, { "weight": 6, "value": 30 }, { "weight": 4, "value": 50 } ]
Knapsack Limit: 10
For the above, the first item has weight 5 and value 10, the second item has weight 4 and value 40, and so on.
In this example, Bob should take the second and fourth item to maximize his value, which, in this case, is 90. He cannot get more than 90 as his knapsack has a weight limit of 10.
'''
Items = [{ "weight": 5, "value": 10 }, { "weight": 4, "value": 40 }, { "weight": 6, "value": 30 }, { "weight": 4, "value": 50 }]
def kidnapp(limit):
valueSum = 0 #somma del valore rubato
weightSum = 0 #somma del peso
while weightSum < limit and Items: #fino a quando il peso è minore del limite e ci sono ancora oggetti
ok = False
maxValue = 0 #valore massimo presente
for element in Items:
if element['weight'] + weightSum > limit: #se il peso dell'oggetto + la somma dei pesi rubati super il limite
Items.remove(element) #l'oggetto viene scartato
#individuo l'oggetto con il valore massimo
elif element['value'] > maxValue:
maxValue = element['value']
position = element
ok = True #l'oggetto è cambiato
if ok: #se l'oggetto è cambiato
Items.remove(position) #viene rubato
weightSum += position['weight'] #si incrementa il peso totale
valueSum += maxValue #si incrementa il valore totale
return valueSum
def main():
limit = int(input("Inserisci un limite alla sacca di Bob: "))
print(f"Con un limite di peso a {limit} Bob può rubare {kidnapp(limit)} di valore totale")
if __name__ == "__main__":
main() |
'''
Author: Michele Alladio
es:
Correctly determine the fewest number of coins to be given to a customer such that the sum of the coins' value would equal the correct amount of change.
For example
An input of 15 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) or [5, 10]
An input of 40 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) and one quarter (25) or [5, 10, 25]
'''
moneyValues = [1, 5, 10, 25, 100]
def calculateChange(change):
changeList = []
while change != 0: #fino a quando il resto da dare non equivale a 0
position = -1 #variabile per il posizionamento nella lista delle valute
for value in moneyValues: #cicla le valute
if value > change: #se la valuta è maggiore del resto
changeList.append(moneyValues[position]) #viene inserita nella lista la valuta precedente
change -= moneyValues[position] #viene decrementato il resto
break #si interompe il ciclo
else: #se la valuta è minore del resto
position += 1 #incremento della posizione nella lista
return changeList[::-1] #lista delle valute al contrario
def main():
change = int(input("Inserisci il resto: "))
print(f"Resto: {calculateChange(change)}")
if __name__ == "__main__":
main()
|
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
house_price = [245,312,279,308,199,219,405,324,319,255]
size = [1400,1600,1700,1875,1100,1550,2350,2450,1425,1700]
size2 = np.array(size).reshape((-1,1))
regr = linear_model.LinearRegression()
regr.fit(size2,house_price)
print("Coefficients: " ,regr.coef_)
print("intercept: " ,regr.intercept_)
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x,y)
graph('regr.coef_*x + regr.intercept_', range(1000, 2700))
plt.scatter(size, house_price, color='black')
plt.ylabel('house price')
plt.xlabel('size of house')
plt.show()
|
'''
#Code : Removing node from Circular Linked List:
Condition : 1) Deleting head node
2) delete any other node
'''
# Code
class Node:
def __init__(self,data=None,next=None):
self.data = data
self.next = next
class Circularlinkedlist:
def __init__(self):
self.head = None
#Utility Function(print function):
def printlist(self):
itr = self.head
while itr:
print(itr.data)
itr = itr.next
if itr==self.head:
break
#Insertion at Beginning:
def insert_at_beg(self,data):
new_node = Node(data)
itr = self.head
new_node.next = self.head
if not self.head: # list is Empty
new_node.next = new_node
else:
while itr.next!=self.head:#[list has values]
itr = itr.next
itr.next = new_node
self.head = new_node
#Insertion at end:
def insert_at_end(self,data):
if not self.head:
self.head = Node(data)
self.head.next = self.head
else:
new_node = Node(data)
itr = self.head
while (itr.next!=self.head):
itr = itr.next
itr.next = new_node
new_node.next = self.head
# Removing Node from Circular Linked list:
def remove(self,key):
if self.head.data == key: # Condition 1 = del head node
itr = self.head
while itr.next != self.head:# End node
itr = itr.next
itr.next = self.head.next
self.head = self.head.next
else: # To delete any other node
itr = self.head
prev = None
while itr.next!=self.head : # End node
prev = itr
itr = itr.next
if itr.data == key:
prev.next = itr.next
itr = itr.next
# Execution of Program:
if __name__ == '__main__':
cll = Circularlinkedlist()
print("The Given Circular linked list: ")
cll.insert_at_beg("a")
cll.insert_at_end("b")
cll.insert_at_end("c")
cll.insert_at_end("d")
cll.insert_at_end("e")
cll.insert_at_beg("x")
cll.printlist()
print("Circular Linked list after removing nodes: ")
cll.remove("a")
cll.remove("d")
cll.remove("x")
cll.printlist()
|
import time
print("How many digits that you want to calculate?")
print("2 Digits (Example: 2 + 2)")
print("3 Digits (Example: 2 + 2 + 2)")
print("4 Digits (Example: 2 + 2 + 2 + 2)")
digits = input("Digits: ")
if digits == "2":
print("What calculation do you want?")
print("addition")
print("subtraction")
print("division")
print("multiplication")
calculation1 = input()
if calculation1 == "addition":
num1 = input("Insert first number: ")
num2 = input("Insert second number: ")
result1 = float(num1) + float(num2)
print("Calculating...")
time.sleep(2)
print(result1)
elif calculation1 == "subtraction":
num3 = input("Insert first number: ")
num4 = input("insert second number: ")
result2 = float(num3) - float(num4)
print("Calculating...")
time.sleep(2)
print(result)
elif calculation1 == "division":
num5 = input("Insert first number: ")
num6 = input("Insert second number: ")
result3 = float(num5) / float(num6)
print("Calculating...")
time.sleep(2)
print(result3)
elif calculation1 == "multiplication":
num7 = input("Insert first number: ")
num8 = input("Insert second number: ")
result4 = float(num7) * float(num8)
print("Calculating...")
time.sleep(2)
print(result4)
else:
print("Error: Invalid Commands. Re-open this file to reset.")
elif digits == "3":
print("What calculation do you want?")
print("addition")
print("subtraction")
print("division")
print("multiplication")
calculation1 = input()
if calculation1 == "addition":
num1 = input("Insert first number: ")
num2 = input("Insert second number: ")
num3 = input("Insert third number: ")
result1 = float(num1) + float(num2) + float(num3)
print("Calculating...")
time.sleep(2)
print(result1)
elif calculation1 == "subtraction":
num3 = input("Insert first number: ")
num4 = input("Insert second number: ")
num5 = input("Insert third number: ")
result2 = float(num3) - float(num4) - float(num5)
print("Calculating...")
time.sleep(2)
print(result2)
elif calculation1 == "division":
num5 = input("Insert first number: ")
num6 = input("Insert second number: ")
num7 = input("Insert third number: ")
result3 = float(num5) / float(num6) / float(num7)
print("Calculating...")
time.sleep(2)
print(result3)
elif calculation1 == "multiplication":
num7 = input("Insert first number: ")
num8 = input("Insert second number: ")
num9 = input("Insert third number: ")
result4 = float(num7) * float(num8) * float(num9)
print("Calculating...")
time.sleep(2)
print(result4)
else:
print("Error: Invalid Commands. Re-open this file to reset.")
elif digits == "4":
print("What calculation do you want?")
print("addition")
print("subtraction")
print("division")
print("multiplication")
calculation1 = input()
if calculation1 == "addition":
num1 = input("Insert first number: ")
num2 = input("Insert second number: ")
num3 = input("Insert third number: ")
num4 = input("Insert forth number: ")
result1 = float(num1) + float(num2) + float(num3) + float(num4)
print("Calculating...")
time.sleep(2)
print(result1)
elif calculation1 == "subtraction":
num3 = input("Insert first number: ")
num4 = input("Insert second number: ")
num5 = input("Insert third number: ")
num6 = input("Insert forth number: ")
result2 = float(num3) - float(num4) - float(num5) - float(num6)
print("Calculating...")
time.sleep(2)
print(result2)
elif calculation1 == "division":
num5 = input("Insert first number: ")
num6 = input("Insert second number: ")
num7 = input("Insert third number: ")
num8 = input("Insert forth number: ")
result3 = float(num5) / float(num6) / float(num7) / float(num8)
print("Calculating...")
time.sleep(2)
print(result3)
elif calculation1 == "multiplication":
num7 = input("Insert first number: ")
num8 = input("Insert second number: ")
num9 = input("Insert third number: ")
num10 = input("Insert forth number: ")
result4 = float(num7) * float(num8) * float(num9) * float(num10)
print("Calculating...")
time.sleep(2)
print(result4)
else:
print("Error: Invalid Commands. Re-open this file to reset.")
else:
print("Error: Invalid Commands. Re-open this file to reset.")
input("Press Enter to exit")
print("wow, you get the secret messege. if you see this, get out. you can't just edit or copy this code just like that, so go away. this is my copyright.")
|
import time
def sleeptime(hour,min,sec):
return hour*3600 + min*60 + sec;
second = sleeptime(0,0,2);
for i in range(5):
time.sleep(second);
print(123) |
"""Dataframe used as input by many estimator checks."""
from typing import Tuple
import pandas as pd
from sklearn.datasets import make_classification
def test_df(
categorical: bool = False, datetime: bool = False
) -> Tuple[pd.DataFrame, pd.Series]:
"""
Creates a dataframe that contains only numerical features, or additionally,
categorical and datetime features.
Parameters
----------
categorical: bool, default=False
Whether to add 2 additional categorical features.
datetime: bool, default=False
Whether to add one additional datetime feature.
Returns
-------
X: pd.DataFrame
A pandas dataframe.
"""
X, y = make_classification(
n_samples=1000,
n_features=12,
n_redundant=4,
n_clusters_per_class=1,
weights=[0.50],
class_sep=2,
random_state=1,
)
# transform arrays into pandas df and series
colnames = [f"var_{i}" for i in range(12)]
X = pd.DataFrame(X, columns=colnames)
y = pd.Series(y)
if categorical is True:
X["cat_var1"] = ["A"] * 1000
X["cat_var2"] = ["B"] * 1000
if datetime is True:
X["date1"] = pd.date_range("2020-02-24", periods=1000, freq="T")
X["date2"] = pd.date_range("2021-09-29", periods=1000, freq="H")
return X, y
|
"""HTTP Requests with Python
================= Using urllib: ==================
import urllib
urlhandler = urllib.urlopen('http://www.py4inf.com/code/romeo.txt')
for line in urlhandler:
print line.strip()
======================================================
"""
import socket
def make_socket():
"""Create a socket to a host, port."""
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.connect(('www.pythonlearn.com', 80))
my_socket.send('GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n')
return my_socket
def main():
"""Main function. Really"""
my_socket = make_socket()
print('/n')
while True:
data = my_socket.recv(512)
if len(data) < 1:
break
print(data)
my_socket.close()
if __name__ == '__main__':
main()
|
"""distplot, kdeplot, rugplot, jointplot, pairplot"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
from scipy.integrate import trapz
sns.set()
x = np.random.normal(size=100)
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
tips = sns.load_dataset("tips")
iris = sns.load_dataset("iris")
x2, y2 = np.random.multivariate_normal(mean, cov, 1000).T
x3, y3 = np.random.randn(2, 300)
"""
The most convenient way to take a quick look at a univariate distribution in seaborn
is the distplot() function. By default, this will draw a histogram and fit a kernel
density estimate (KDE).
"""
# sns.distplot(x)
# plt.savefig("distribution_images\image1")
"""
Histograms are likely familiar, and a hist function already exists in matplotlib.
A histogram represents the distribution of data by forming bins along the range
of the data and then drawing bars to show the number of observations that fall in each bin.
To illustrate this, let’s remove the density curve and add a rug plot, which draws
a small vertical tick at each observation. You can make the rug plot itself with
the rugplot() function, but it is also available in distplot():
"""
# sns.distplot(x, kde=False, rug=True)
# plt.savefig("distribution_images\image2")
"""
When drawing histograms, the main choice you have is the number of bins to
use and where to place them. distplot() uses a simple rule to make a good
guess for what the right number is by default, but trying more or fewer
bins might reveal other features in the data:
"""
# sns.distplot(x, bins=20, kde=False, rug=True)
# plt.savefig("distribution_images\image3")
"""
The kernel density estimate may be less familiar, but it can be a useful
tool for plotting the shape of a distribution. Like the histogram, the KDE
plots encode the density of observations on one axis with height along the other axis:
"""
# sns.distplot(x, hist=False, rug=True)
# plt.savefig("distribution_images\image4")
"""
Drawing a KDE is more computationally involved than drawing a histogram.
What happens is that each observation is first replaced with a normal
(Gaussian) curve centered at that value:
"""
# y = np.random.normal(0, 1, size=30)
# bandwidth = 1.06 * y.std() * y.size ** (-1 / 5.)
# support = np.linspace(-4, 4, 200)
# kernels = []
# for y_i in y:
# kernel = stats.norm(y_i, bandwidth).pdf(support)
# kernels.append(kernel)
# plt.plot(support, kernel, color="r")
# sns.rugplot(y, color=".2", linewidth=3)
# plt.savefig("distribution_images\image5")
"""
Next, these curves are summed to compute the value of the density at each
point in the support grid. The resulting curve is then normalized so that
the area under it is equal to 1:
"""
# y = np.random.normal(0, 1, size=30)
# bandwidth = 1.06 * y.std() * y.size ** (-1 / 5.)
# support = np.linspace(-4, 4, 200)
# kernels = []
# for y_i in y:
# kernel = stats.norm(y_i, bandwidth).pdf(support)
# kernels.append(kernel)
# density = np.sum(kernels, axis=0)
# density /= trapz(density, support)
# sns.lineplot(support, density)
# plt.savefig("distribution_images\image6")
"""
We can see that if we use the kdeplot() function in seaborn, we get the same curve.
This function is used by distplot(), but it provides a more direct interface with
easier access to other options when you just want the density estimate:
"""
# sns.kdeplot(x, shade=True)
# plt.savefig("distribution_images\image7")
"""
The bandwidth (bw) parameter of the KDE controls how tightly the estimation is fit
to the data, much like the bin size in a histogram. It corresponds to the width of
the kernels we plotted above. The default behavior tries to guess a good value using
a common reference rule, but it may be helpful to try larger or smaller values:
"""
# sns.kdeplot(x)
# sns.kdeplot(x, bw=.2, label="bw: 0.2")
# sns.kdeplot(x, bw=2, label="bw: 2")
# plt.legend()
# plt.savefig("distribution_images\image8")
"""
As you can see above, the nature of the Gaussian KDE process means that estimation
extends past the largest and smallest values in the dataset. It’s possible to control
how far past the extreme values the curve is drawn with the cut parameter; however,
this only influences how the curve is drawn and not how it is fit:
"""
# sns.kdeplot(x, shade=True, cut=0)
# sns.rugplot(x)
# plt.savefig("distribution_images\image9")
"""
You can also use distplot() to fit a parametric distribution to a dataset and
visually evaluate how closely it corresponds to the observed data:
"""
# z = np.random.gamma(6, size=200)
# sns.distplot(z, kde=False, fit=stats.gamma)
# plt.savefig("distribution_images\image10")
"""
Change the color of all the plot elements:
"""
# sns.distplot(x, kde_kws={'kernel': 'gau'}, color="y")
# plt.savefig("distribution_images\image11")
"""
Pass specific parameters to the underlying plot functions:
"""
# sns.distplot(x,
# rug=True,
# bins=6,
# rug_kws={"color": "g"},
# kde_kws={"color": "k",
# "lw": 3,
# "label": "KDE"},
# hist_kws={"histtype": "step",
# "linewidth": 3,
# "alpha": 1,
# "color": "g",
# "rwidth": (-3, 3)})
# plt.savefig("distribution_images\image12")
########################################################################################################################
########################################################################################################################
########################################################################################################################
"""
The most familiar way to visualize a bivariate distribution is a scatterplot,
where each observation is shown with point at the x and y values. This is
analgous to a rug plot on two dimensions. You can draw a scatterplot with
the matplotlib plt.scatter function, and it is also the default kind of plot
shown by the jointplot() function:
"""
# sns.jointplot(x="x", y="y", data=df)
# plt.savefig("distribution_images\image13")
"""
Add regression and kernel density fits:
"""
# sns.jointplot("total_bill", "tip", data=tips, kind="reg")
# plt.savefig("distribution_images\image14")
"""
Draw a smaller figure with more space devoted to the marginal plots:
"""
# sns.jointplot("total_bill", "tip", data=tips, height=5, ratio=3, color="g")
# plt.savefig("distribution_images\image15")
"""
Pass keyword arguments down to the underlying plots:
"""
# sns.jointplot("petal_length",
# "sepal_length",
# data=iris,
# marginal_kws=dict(bins=15, rug=True),
# annot_kws=dict(stat="r"),
# s=40,
# edgecolor="w",
# linewidth=1)
# plt.savefig("distribution_images\image16")
"""
The bivariate analogue of a histogram is known as a “hexbin” plot, because it shows
the counts of observations that fall within hexagonal bins. This plot works best with
relatively large datasets. It’s available through the matplotlib plt.hexbin function
and as a style in jointplot(). It looks best with a white background:
"""
# with sns.axes_style("white"):
# sns.jointplot(x=x2, y=y2, kind="hex", color="k")
# plt.savefig("distribution_images\image17")
"""
Pass vectors in directly without using Pandas, then name the axes:
"""
# with sns.axes_style("white"):
# sns.jointplot(x3, y3, kind="hex").set_axis_labels("x", "y")
# plt.savefig("distribution_images\image18")
"""
It is also possible to use the kernel density estimation procedure described above to
visualize a bivariate distribution. In seaborn, this kind of plot is shown with a
contour plot and is available as a style in jointplot():
"""
# g = sns.jointplot(x="x", y="y", data=df, kind="kde")
# g.ax_joint.collections[0].set_alpha(0)
# plt.savefig("distribution_images\image19")
"""
You can also draw a two-dimensional kernel density plot with the kdeplot() function.
This allows you to draw this kind of plot onto a specific (and possibly already existing)
matplotlib axes, whereas the jointplot() function manages its own figure:
"""
# f, ax = plt.subplots(figsize=(6, 6))
# sns.kdeplot(df.x, df.y, ax=ax)
# sns.rugplot(df.x, color="g", ax=ax)
# sns.rugplot(df.y, vertical=True, ax=ax)
# plt.savefig("distribution_images\image20")
"""
If you wish to show the bivariate density more continuously, you can simply
increase the number of contour levels:
"""
# f, ax = plt.subplots(figsize=(6, 6))
# cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True)
# sns.kdeplot(df.x, df.y, cmap=cmap, n_levels=100, shade=True)
# plt.savefig("distribution_images\image21")
"""
The jointplot() function uses a JointGrid to manage the figure. For more flexibility,
you may want to draw your figure by using JointGrid directly. jointplot() returns the
JointGrid object after plotting, which you can use to add more layers or to tweak other
aspects of the visualization:
"""
# g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="m")
# g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
# g.ax_joint.collections[0].set_alpha(0)
# g.set_axis_labels("$X$", "$Y$")
# plt.savefig("distribution_images\image22")
"""
Replace the scatterplots and histograms with density estimates and align the
marginal Axes tightly with the joint Axes:
"""
# with sns.axes_style("white"):
# g = sns.jointplot("sepal_width",
# "petal_length",
# data=iris,
# kind="kde",
# space=0,
# color="g")
# g.ax_joint.collections[0].set_alpha(0)
# plt.savefig("distribution_images\image23")
"""
Draw a scatterplot, then add a joint density estimate:
"""
# with sns.axes_style("white"):
# sns.jointplot("sepal_length",
# "sepal_width",
# data=iris,
# color="k").\
# plot_joint(sns.kdeplot, zorder=0, n_levels=6)
# plt.savefig("distribution_images\image24")
########################################################################################################################
########################################################################################################################
########################################################################################################################
"""
To plot multiple pairwise bivariate distributions in a dataset, you can use the pairplot()
function. This creates a matrix of axes and shows the relationship for each pair of columns
in a DataFrame. by default, it also draws the univariate distribution of each variable
on the diagonal Axes:
"""
# sns.pairplot(iris)
# plt.savefig("distribution_images\image25")
"""
Much like the relationship between jointplot() and JointGrid, the pairplot() function
is built on top of a PairGrid object, which can be used directly for more flexibility:
"""
# g = sns.PairGrid(iris)
# g.map_diag(sns.kdeplot)
# g.map_offdiag(sns.kdeplot, n_levels=6)
# plt.savefig("distribution_images\image26")
"""
Show different levels of a categorical variable by the color of plot elements:
"""
# sns.pairplot(iris, hue="species")
# plt.savefig("distribution_images\image27")
"""
Use a different color palette:
"""
# sns.pairplot(iris, hue="species", palette="husl")
# plt.savefig("distribution_images\image28")
"""
Use different markers for each level of the hue variable:
"""
# sns.pairplot(iris, hue="species", markers=["o", "s", "D"])
# plt.savefig("distribution_images\image29")
"""
Plot a subset of variables:
"""
# sns.pairplot(iris, vars=["sepal_width", "sepal_length"])
# plt.savefig("distribution_images\image30")
"""
Draw larger plots:
"""
# sns.pairplot(iris, height=3, vars=["sepal_width", "sepal_length"])
# plt.savefig("distribution_images\image31")
"""
Plot different variables in the rows and columns:
"""
# sns.pairplot(iris, x_vars=["sepal_width", "sepal_length"], y_vars=["petal_width", "petal_length"])
# plt.savefig("distribution_images\image32")
"""
Use kernel density estimates for univariate plots:
"""
# sns.pairplot(iris, diag_kind="kde")
# plt.savefig("distribution_images\image33")
"""
Pass keyword arguments down to the underlying functions (it may be easier to use PairGrid directly):
"""
# sns.pairplot(iris,
# diag_kind="kde",
# markers="+",
# plot_kws=dict(s=50, edgecolor="p", linewidth=2),
# diag_kws=dict(shade=False))
# plt.savefig("distribution_images\image34")
plt.show()
sns.scatterplot() |
first_name = "Prashanth"
last_name = "S"
str1 = []
for i in range(1, len(first_name) + 1):
str1.append(first_name[-i])
str1.append(" ")
for i in range(1, len(last_name) + 1):
str1.append(last_name[-i])
print("".join(str1))
|
# Your code here
def finder(files, queries):
"""
YOUR CODE HERE
"""
# Your code here
# Loop through list of file paths and create dictionary where each key is
# the file (last entry in the path) and each value a list of file path(s)
path_dict = {}
for path in files:
file = path.split("/")[-1]
if file not in path_dict:
path_dict[file] = [path]
else:
path_dict[file] += [path]
result = []
# Loop through every file in the query
# If the file exists in our dictionary:
# record the filepath(s) for that file
for file in queries:
if file in path_dict:
result += (path_dict[file])
return result
if __name__ == "__main__":
files = [
'/bin/foo',
'/bin/bar',
'/usr/bin/baz'
]
queries = [
"foo",
"qux",
"baz"
]
print(finder(files, queries))
|
#!/usr/bin/env python3
# -*-encoding: utf-8-*-
import re
def valid_mail(mail: str) -> bool:
"""
validation mail name
using regex
"""
success = False
pattern = re.compile(r'[\w.]+@([\w-]+\.)+[\w-]{2,4}')
matched = pattern.match(mail) # None if isn't matched
if matched is not None:
# if matched
# checking matched length
success = matched.start() == 0 and matched.end() == len(mail)
return success
def valid_message(msg: str) -> bool:
"""
validation msg text
must not be empty
length < 100
"""
return bool(msg.replace(' ', '')) and len(msg) < 100
|
"""
This module checks if board is correct and ready for game.
"""
def check_rows(board):
"""
Returns False if there are two identical numbers in row and True otherwise
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
True
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
True
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 5 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
False
"""
uniqueness = True
for i,row in enumerate(board):
if i not in (0, len(board) - 1):
for j,number in enumerate(row):
if j > row.index(number) and number not in("*", " "):
uniqueness = False
break
return uniqueness
def empty_columns(board):
"""Returns list of "" with length equal to length of expected column.
>>> empty_columns(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
['', '', '', '', '', '', '', '', '']
"""
columns = []
while len(columns)!= len(board[0]):
columns.append("")
return columns
def fill_columns(columns,board):
"""Returns list of columns of the board.
>>> fill_columns(['', '', '', '', '', '', '', '', ''],\
["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
['**** 3 ', '*** 6 ', '** 4 82', '*1 ',\
' 31 82 ', '****93 2*', '**** **', '****5 ***', '**** ****']
"""
for i in range(len(columns)):
for row in board:
columns[i]+=row[i]
return columns
def check_columns(board):
"""
Returns False if there are two identical numbers in row and True otherwise
>>> check_columns(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
True
>>> check_columns(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
False
>>> check_columns(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 5 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
True
"""
columns_empt = empty_columns(board)
columns = fill_columns(columns_empt,board)
uniqueness = check_rows(columns)
return uniqueness
def check_color(board):
"""
Returns False if there are two identical numbers in one color and True otherwise.
>>> check_color(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
True
>>> check_color(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
True
>>> check_color(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 5 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
False
"""
columns_empt = empty_columns(board)
columns = fill_columns(columns_empt,board)
colors = []
for i in range(len(columns)):
color = columns[i][:-(i+1)] + board[-(i+1)][i:]
colors.append(color)
uniqueness = check_rows(colors)
return uniqueness
def validate_board(board):
"""
Returns True if board is correct and ready for game and False otherwise.
>>> validate_board(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
True
>>> validate_board(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
False
>>> validate_board(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 5 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
False
"""
rows_uniqueness = check_rows(board)
columns_uniqueness = check_columns(board)
colors_uniqueness = check_color(board)
return rows_uniqueness and colors_uniqueness and columns_uniqueness
|
from math import atan, fabs
from time import sleep
def f(x):
return atan(x)
k = 0
a = -3
b = 3
funa = f(a)
funb = f(b)
if (funa*funb>0.0):
print("Funkcijas atan(x) dotaja intervala [%s, %s] saknju nav" %(a,b))
sleep(1); exit()
else:
print("Funkcijas atan(x) dotaja intervala sakne(s) ir!")
deltax = 0.0001
while (fabs(b-a)>deltax):
k = k+1
x = (a+b)/2; funx = f(x)
if (funa*funx < 0.):
b = x
else:
a = x
print ("atan(x) sakne ir:", x)
print("f(x)=", atan(x))
print("k=", k)
|
class Queue(object):
def __init__(self):
self.q = list()
def is_empty(self):
return self.q == []
def size(self):
return len(self.q)
def add_to_queue(self, data):
if self.is_empty():
self.q.append(data)
elif self.size() == 1:
temp = self.q[0]
self.q[0] = data
self.q.append(temp)
else:
for k in range(len(self.q)-1):
self.q[k+1] = self.q[k]
self.q[0] = data
def remove_from_queue(self):
if self.is_empty():
print("Cannot dequeue an empty queue")
else:
return self.q.pop()
class Deque(Queue):
def add_to_queue_right(self, data):
self.q.append(data)
def remove_from_left(self):
if self.is_empty():
print("Cannot remove from an empty deque")
else:
temp = self.q[0]
for k in range(len(self.q)-1):
self.q[k] = self.q[k+1]
return temp |
import os
import csv
#path to collect data
csvpath = os.path.join("./Resources/budget_data.csv")
# assigning variables...
netProfit = 0
monthProfit = 0
counter = 0
previous = 0
change = 0
# .. and lists
changesList = []
months = []
# read file data w csv module
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvreader)
for row in csvreader:
# count the lines of data for the month
counter = counter + 1
# collect the dates into a list
months.append(str(row[0]))
# Add all the profits in column 2 to the profit/loss list
netProfit += int(row[1])
# Calulate changes in month to month profit
# if there is previous data then...
if change != 0:
# set value of monthProfit to 2nd column in row
monthProfit = int(row[1])
# Subtract current profit from previous month
change = monthProfit - change
# take the change value and store it in a list
changesList.append(change)
# reset the change variable
change = int(row[1])
# if there is no previous data set the variable to the value in the first row, column 2
elif change == 0:
change = int(row[1])
# remove first month from list since there is no change there
months.pop(0)
# find the greatest increase and decrease in profits in the change list
max_in = max(changesList)
max_de = min(changesList)
# use index positions to find the months for those numbers
maxIncDate = months[changesList.index(max_in)]
maxDecDate = months[changesList.index(max_de)]
# get the average of the changeList
ave = sum(changesList)/float(len(changesList))
ave = round(ave, 2)
# calculate year
years = float(counter/12)
years = round(years, 2)
# Print in terminal and to a txt file
print(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(" FINANCIAL ANALYSIS")
print(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(" Total Months: " + str(counter))
print(" Total Years: " + str(float(years)))
print(" Total Profits: " + "$" + str(netProfit))
print(" Average Change: " + "$" + str(float(ave)))
print(" Greatest Increase in Profits: $" + str(max_in) + " " + str(maxIncDate))
print(" Greatest Decrease in Profits: $" + str(max_de) + " " + str(maxDecDate))
print(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
with open('Pybank.txt', "w") as text_file:
print(f" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", file=text_file)
print(f" FINANCIAL ANALYSIS", file=text_file)
print(f" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", file=text_file)
print(f" Total Months: " + str(counter), file=text_file)
print(f" Total Years: " + str(int(years))+ "ish", file=text_file)
print(f" Total Profits: " + "$" + str(netProfit), file=text_file)
print(f" Average Change: " + "$" + str(float(ave)), file=text_file)
print(f" Greatest Increase in Profits: $" + str(max_in) + " " + str(maxIncDate), file=text_file)
print(f" Greatest Decrease in Profits: $" + str(max_de) + " " + str(maxDecDate), file=text_file)
print(f" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", file=text_file)
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#to use select in dropdown
from selenium.webdriver.support.ui import Select
import time
driver=webdriver.Chrome(executable_path="C:\Program Files (x86)\chromedriver_win32\chromedriver.exe")
driver.maximize_window()
driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407")
#select one option
#capture options from dropdown
#count how many options ae pressent
driver.execute_script("window.scrollTo(0,600)")
drop=driver.find_element_by_id("RESULT_RadioButton-9")
drp=Select(drop)
#select by visible text
drp.select_by_visible_text('Morning')
time.sleep(5)
#select by index
drp.select_by_index(2)
time.sleep(5)
#select by value
drp.select_by_value("Radio-2")
time.sleep(5)
#count nummber of options
print(len(drp.options))
#print all the options and print them as output
all_options=drp.options
for option in all_options:
print(option.text)
|
"""
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes. OK
3. Of the programmer and the person who bought the droid,
one is Wilkes and the other is Hamming.
4. The writer is not Minsky. OK
5. Neither Knuth nor the person who bought the tablet is the manager.
6. Knuth arrived the day after Simon. OK
7. The person who arrived on Thursday is not the designer. OK
8. The person who arrived on Friday didn't buy the tablet.
9. The designer didn't buy the droid.
10. Knuth arrived the day after the manager.
11. Of the person who bought the laptop and Wilkes,
one arrived on Monday and the other is the writer.
12. Either the person who bought the iphone or the person who bought the tablet
arrived on Tuesday.
You will write the function logic_puzzle(), which should return a list of the
names of the people in the order in which they arrive. For example, if they
happen to arrive in alphabetical order, Hamming on Monday, Knuth on Tuesday, etc.,
then you would return:
['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes']
(You can assume that the days mentioned are all in the same week.)
"""
import itertools
def day_after(a,b):
if b+1 == a:
return True
return False
def solve_puzzle():
days = Monday, Tuesday, Wednesday, Thursday, Friday = [0,1,2,3,4]
orderings = list(itertools.permutations(days))
return next([Hamming,Knuth,Minsky,Simon,Wilkes]
for [Hamming,Knuth,Minsky,Simon,Wilkes] in orderings
if day_after(Knuth,Simon)
for [programmer, writer, manager, designer, _] in orderings
if programmer != Wilkes
and writer != Minsky
and Thursday != designer
and day_after(Knuth,manager)
for [tablet, laptop, droid, iphone, _] in orderings
if Wednesday == laptop
if (programmer == Wilkes and droid == Hamming) or (programmer == Hamming and droid == Wilkes)
if manager != Knuth and manager != tablet
and Friday != tablet
and designer != droid
and ((laptop == Monday and Wilkes == writer) or (laptop == writer and Wilkes == Monday))
and ((iphone == Tuesday) or (tablet == Tuesday))
)
def logic_puzzle():
"Return a list of the names of the people, in the order they arrive."
## your code here; you are free to define additional functions if needed
solve_result = solve_puzzle()
people = ['Hamming','Knuth','Minsky','Simon','Wilkes']
result = range(5)
count = 0
for i in solve_result:
result[i]=people[count]
count+=1
return result
print logic_puzzle()
|
# -*- coding: utf-8 -*-
# Print List of Country Host of FIFA World Cup on Century 21
world_cup_21th = {
'2002': ['South Korea', 'Japan'],
'2006': 'Germany',
'2010': 'South Africa',
'2014': 'Brazil',
'2018': 'Russia',
}
def find_country(year):
if year in world_cup_21th:
val = world_cup_21th[year]
else:
val = "NONE"
return val
if __name__ == '__main__':
# read users input
worldCupYear = raw_input("Please input FIFA World Cup year: ")
# print the output
print(find_country(worldCupYear))
|
def main():
b = int(input("How many degrees fahrenheit today? "))
sum = 0
print("temperature today in celsius is",(b-32)*5/9)
main() |
import urllib
from BeautifulSoup import *
#url = raw_input('Enter - ')
#url = 'http://python-data.dr-chuck.net/comments_42.html'
url = 'http://python-data.dr-chuck.net/comments_260258.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
sumTotal = []
# Retrieve all of the span tags
tags = soup('span')
for tag in tags:
# Look at the parts of a tag
#print 'TAG:',tag
#print 'URL:',tag.get('span', None)
#print 'Contents:',tag.contents[0]
#print 'Attrs:',tag.attrs
num = int(tag.contents[0])
sumTotal.append(num)
print sum(sumTotal) |
from nltk.corpus import wordnet
import itertools as IT
list1 = input("set the first sentences: ").split()
list2 = input("set the second sentences: ").split()
def f(word1, word2):
wordFromList1 = wordnet.synsets(word1)[0]
wordFromList2 = wordnet.synsets(word2)[0]
s = wordFromList1.wup_similarity(wordFromList2)
return(wordFromList1.name, wordFromList2.name, wordFromList1.wup_similarity(wordFromList2))
for word1 in list1:
similarities=(f(word1,word2) for word2 in list2)
print(max(similarities, key=lambda x: x[2]))
|
from util import Queue
from graph import Graph
def earliest_ancestor(ancestors, starting_node):
graph = Graph()
for pair in ancestors:
graph.add_vertex(pair[0])
graph.add_vertex(pair[1])
graph.add_edge(pair[1], pair[0])
q = Queue()
q.enqueue([starting_node])
max_path_length = 1
earliest_ancestor = -1
while q.size() > 0:
path = q.dequeue()
vert = path[-1]
if (len(path) >= max_path_length and vert < earliest_ancestor) or (len(path) > max_path_length):
earliest_ancestor = vert
max_path_length = len(path)
for neighbor in graph.vertices[vert]:
path_copy = list(path)
path_copy.append(neighbor)
q.enqueue(path_copy)
return earliest_ancestor
# Tests:
print(earliest_ancestor([(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)], 2))
print(earliest_ancestor([(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)], 6))
print(earliest_ancestor([(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)], 8)) |
# The problem is:
# Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
# Example 1:
# Input: "Hello"
# Output: "hello"
# Example 2:
# Input: "here"
# Output: "here"
# Example 3:
# Input: "LOVELY"
# Output: "lovely"
# My code beats 100% of others:
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
out_str = ''
for i in range(len(str)):
if 97<=ord(str[i])<=122:
out_str += str[i]
elif 65<=ord(str[i])<=90:
out_str += chr(ord(str[i]) + 32)
else:
out_str += str[i]
return out_str
# return str.lower() #SLOWER
|
# Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
# To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
# To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].
# Example 1:
# Input: [[1,1,0],[1,0,1],[0,0,0]]
# Output: [[1,0,0],[0,1,0],[1,1,1]]
# Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
# Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
# Example 2:
# Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
# Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
# Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
# Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
# Notes:
# 1 <= A.length = A[0].length <= 20
# 0 <= A[i][j] <= 1
# My answer beats 25% of submissions:
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
A_out = []
for i in range(len(A)):
B = []
for j in range(len(A[i])):
B.append(1-A[i][len(A[i]) - j - 1])
A_out.append(B)
return A_out
# There is a code beats 70% of others
class Solution:
def flipAndInvertImage(self, A):
res = []
for i in A:
res.append([0 if x == 1 else 1 for x in i][::-1])
return res
# and to explain [::-1]:
# Assumming a is a string. The Slice notation in python has the syntax -
# list[<start>:<stop>:<step>]
# So, when you do a[::-1] , it starts from the end, towards the first, taking each element. So it reverses a. This is applicable for lists/tuples as well.
# Example:
# >>> a = '1232'
# >>> a[::-1]
# '2321'
|
# 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
# n<=39
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
elif n == 1:
return 1
else:
p1 = 0
p2 = 1
for i in range(2, n+1): # 依次取2,3,4,5,...,n
out = p1+p2
p1 = p2
p2 = out
return out
|
# Given an n-ary tree, return the preorder traversal of its nodes' values.
# The 1st solution:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root is None:
return []
stack, output = [root, ], []
while stack:
root = stack.pop()
output.append(root.val)
stack.extend(root.children[::-1])
# extend children的顺序是反过来的,因为堆栈是先进后出,我们为了保证pop的顺序而将其颠倒
return output
# The 2nd solution:
# """
# # Definition for a Node.
# class Node(object):
# def __init__(self, val, children):
# self.val = val
# self.children = children
# """
# class Solution(object):
# def preorder(self, root):
# """
# :type root: Node
# :rtype: List[int]
# """
# def dfs(root):
# if not root:
# return
# res.append(root.val)
# for c in root.children:
# dfs(c)
#
# res = []
# dfs(root)
# return res
|
# PRIMEIRO: SELECTION SORT
"""
Algoritmo de classificação de seleção simples.
O algoritmo divide a entrada em duas partes: a sublista de itens
já classificado, que é construído da esquerda para a direita na frente (esquerda)
da lista, e a sublista de itens restantes a serem classificados que ocupam o
resto da lista.
O algoritmo prossegue encontrando o menor elemento na sublista não classificada,
trocando-o com o elemento não classificado mais à esquerda.
"""
def selectionSort(lista):
n = len(lista)
for i in range(0, n):
min_index = i
for e in range(i + 1, n):
if lista[e] < lista[min_index]:
min_index = e
lista[i], lista[min_index] = lista[min_index], lista[i]
# 1 + (n)*[3 + x] ---> 1 + 3n + nx |
import random
import copy
import time
N = 2
class Cell:
def __init__(self, pos):
# A cell initially can have N*N possible answers
self.possibleAnswers = list(range(1, N*N+1))
# The answer is initially None
self.ans = None
# the position of ca cell is a tuple of three integer
# first and second number represents row and column
# the third number represents in which `box` the cell is in
self.pos = pos
# a cell also has an index, that is, the index of the cell if the board is a 1D array
# it can be obtained from row and column
self.i = pos[0]*N*N + pos[1]
def __str__(self):
return f'({self.ans} {self.possibleAnswers})'
def show(self):
# return self.ans or f'({self.possibleLen()})'
return self.ans or 0
def solved(self):
return self.ans != None
def remove(self, num):
# if `num` in the list of possibleAnswers, remove it from there
if num not in self.possibleAnswers:
return False
self.possibleAnswers.remove(num)
# if after removing it, the possibleAnswers contain only one element, the cell is solved
if len(self.possibleAnswers) == 1:
self.ans = self.possibleAnswers[0]
return True
return False
def setRandomAns(self):
# select a random element from the possibleAnswers and set it as the answer
x = random.choice(self.possibleAnswers)
self.ans = x
return x
def reset(self):
# rest the cell, set answer to None and possible answer to N*N number
self.ans = None
self.possibleAnswers = list(range(1, N*N+1))
def possibleLen(self):
# returns length of the possible answers array
return len(self.possibleAnswers)
def sameDomain(self, other):
# checks if two cells is in the same domain, that is if they are in the same row, column or `box`
p1 = self.pos
p2 = other.pos
return p1[0] == p2[0] or p1[1] == p2[1] or p1[2] == p2[2]
def emptyBoard():
# returns and empty board of size N*N as an 1D array
return [Cell((i, j, (i//N)*N+j//N)) for i in range(N*N) for j in range(N*N)]
def printBoard(b):
# prints a board
for i in range(N):
for k in range(N):
for j in range(N):
start = ((i*N)+k)*N*N + j*N
print([c.show() for c in b[start:start+N]], end=' ')
print('')
print('')
def check(board):
# Checks if a board is completed and correct
for c1 in board:
if not c1.solved():
# A cell is not solved. So, not complete
return False
for c2 in board:
if c1 is c2:
continue
if c1.sameDomain(c2) and c1.ans == c2.ans:
# Two cells in same domain but have same answer. So, not correct
return False
return True
def checkEqual(b1, b2):
# checks if two boards are exactly same
for c in b1:
if c.ans != b2[c.i].ans:
return False
return True
def genCompleted():
# generates and returns a completed board
# first take an empty board
board = emptyBoard()
# make a `shallow` copy of all the cells, these cells are unfinished
cells = board.copy()
while cells: # until the list of unifinshed cells is empty,
# see which unfinished cells have the minimum number of possible answers
# then select a random one from them, set a random answer to it from it's possible answers, let it be x
# remove this cell from the list of unfinished cells
# now go to every cell of the board, if a cell is in the same domain as the cell we just set a random
# answer to, remove x from it's possible answer
mn = min(c.possibleLen() for c in cells)
lowestCells = []
for c in cells:
if c.possibleLen() == mn:
lowestCells.append(c)
choiceCell = random.choice(lowestCells)
cells.remove(choiceCell)
# if the cell is already solved, no need to set random answer
if not choiceCell.solved():
choiceCell.setRandomAns()
x = choiceCell.ans
for c in board:
if c is choiceCell:
continue
if choiceCell.sameDomain(c):
c.remove(x)
# if the algorithm is finished, but we dont get a completed board, we have to try again
if not check(board):
return genCompleted()
return board
def solve(board, t=0):
# takes a board and number of previous attempts `t`
# returns number of guesses (which we assume as difficulty) and the solved board
# if the number of previous attempts is more than 900, we assume the board is unsolvable
if t > 900:
return (-1, None)
# make a deep copy of the board, the copy has to be deep because we would want to try different solutions
# without changing the original board first
board_copy = copy.deepcopy(board)
# number of guesses is zero at start
guesses = 0
# take the solved and unsolved cells in different lists
solvedCells = []
unsolvedCells = []
for c in board_copy:
if c.possibleLen() == 1:
solvedCells.append(c)
else:
unsolvedCells.append(c)
# for each solved cell, remove it's ans from the list of possibleAnswers of all the unsolved cells in it's domain
while solvedCells: # do this until the list of solved cells is empty
# doing so, might solve some cells, keep them in this list
newlySolved = []
for c1 in solvedCells:
for c2 in unsolvedCells:
if c1.sameDomain(c2):
c2.remove(c1.ans)
if c2.possibleLen() == 1:
# removing the number solved this cell, now set it's ans
# this will merely set the only element of it's possibleAnswers as it's ans
c2.setRandomAns()
# now that the cell is solved, remove it from unsolved cells
unsolvedCells.remove(c2)
# add it to the newly solved cells
newlySolved.append(c2)
# the new list of solved cells would be the newlySolved cells
solvedCells = newlySolved
if solvedCells == [] and unsolvedCells != []:
# we have done the above process for all the solved cells (the solvedCells list is empty)
# but still some cells are unsolved
# now we take the cells with minimum number of unsolved cells
# select a random one and set a random answer to it
mn = min(c.possibleLen() for c in unsolvedCells)
choice = random.choice(
list(filter(lambda c: c.possibleLen() == mn, unsolvedCells)))
choice.setRandomAns()
# add it to the solved cells and remove it from the unsolved cells
solvedCells.append(choice)
unsolvedCells.remove(choice)
# now we have made a guess here, so increase a `guesses`
guesses += 1
if check(board_copy):
# the board is solved, return guesses and the solved board
return (guesses, board_copy)
else:
# the board is not solved, try again with number of previous attempt increased by one
return solve(board, t+1)
def genPuzzle():
# generates a puzzle and returns it's difficulty, the puzzle itself and it's solution as a tuple
# generate a completed board first, then we will reset a random cell from a `deep copy` of the board
# if the board still has a unique solution, we will reset the same cell in the original board and continue
# doing this
# otherwise, we return the original board in it's current state
board = genCompleted()
board_copy = copy.deepcopy(board)
# list of all the solved cells
cells = board_copy.copy()
while cells: # obviously, `cells` will never be empty, we will find a puzzle before that
# choose a random cell and reset it
choice = random.choice(cells)
cells.remove(choice)
choice.reset()
# solve the board_copy to see if it still has a unique solution
r0, s0 = solve(board_copy)
if r0 == -1:
# it doesn't have a solution, so we can't reset this or any other cell from the original board
r, solution = solve(board)
return r, board, solution
elif checkEqual(s0, solve(board_copy)[1]):
# the board_copy still has a unique solution, so reset the cell in the original board
board[choice.i].reset()
else:
# it has a solution, but the solution is not unique, so we have to return
r, solution = solve(board)
return r, board, solution
def genPuzzleWithDifficulty(d):
# generates a puzzle with a desired difficulty `d`.
while True: # keep generating puzzles until we find a puzzle with our desired difficulty
r, puzzle, solution = genPuzzle()
print('Found puzzle with difficulty: ', r+1)
if r == d-1 or (d == 5 and r >= 5):
return puzzle, solution
def main():
global N
N = int(input('Enter value of N (>1): '))
d = int(input('Enter difficulty (1-5): '))
puzzle, solution = genPuzzleWithDifficulty(d)
print('Puzzle:')
printBoard(puzzle)
print('Solution:')
printBoard(solution)
if __name__ == '__main__':
main()
|
import math
# -------------------------------------------------------------
# --------------------- DATA FUNCTIONS ------------------------
# -------------------------------------------------------------
SOLVEDSET = set(range(1,10))
ROWS,COLS,BOXS = 0,1,2
whatRowColOrBox = [lambda cell: whatRow(cell),\
lambda cell: whatCol(cell),\
lambda cell: whatBox(cell)]
def whatRow(unknown):
# Returns row number
return unknown[0]
def whatCol(unknown):
# Returns col number
return unknown[1]
def whatBox(unknown):
# Returns box number based on index of row and column
boxNumber = 3*math.floor(whatRow(unknown)/3) + math.floor(whatCol(unknown)/3)
return int(boxNumber)
def sameGroup(unknown1,unknown2):
results = []
for test in whatRowColOrBox:
results.append(test(unknown1) == test(unknown2))
return results
def findZeros(inputList):
# Returns list of (row index, col index) of 0's in a nested list
zeros = []
for rowNumber,rowEntry in enumerate(inputList):
for colNumber, colEntry in enumerate(rowEntry):
# Locate zeros:
if colEntry == 0:
zeros.append([rowNumber, colNumber])
return zeros
def getSets(inputList):
# Form sets of numbers entered into the rows, colums, and boxes:
# (possible expand to be able to adjust dimensions?)
rowSets = []
colSets = [set()]*9
boxSets = [set()]*9
for rowNumber,rowEntry in enumerate(inputList):
# Assemble row set first:
rowSets.append(set(rowEntry))
for colNumber, colEntry in enumerate(rowEntry):
# Enter column set next:
colSets[colNumber] = colSets[colNumber] | {colEntry}
# Lastly determine box set:
boxNumber = whatBox([rowNumber, colNumber])
boxSets[boxNumber] = boxSets[boxNumber] | {colEntry}
sets = [rowSets,colSets,boxSets]
return sets
def getOptions(sets,unknowns):
# Determines options for unknown cells by set differences
possibleOptions = []
for cell in unknowns:
solvedCells = sets[ROWS][whatRow(cell)].union(sets[COLS][whatCol(cell)].union(sets[BOXS][whatBox(cell)]))
possible = SOLVEDSET.difference(solvedCells)
possibleOptions.append(possible)
return possibleOptions
def insertKnown(unsolved,index,known):
# Insert solved number into cell, does not enter if incorrect
sets = getSets(unsolved)
if ( known not in sets[ROWS][whatRow(index)] and
known not in sets[COLS][whatCol(index)] and
known not in sets[BOXS][whatBox(index)]):
# Insert the number!
unsolved[whatRow(index)][whatCol(index)] = known
return False,unsolved
else:
print str(known)+" cannot go in row "+str(whatRow(index))+", column "+str(whatCol(index))
print "\nI MADE A MISTAKE.\n"
return True,unsolved
|
h = 100
l = 0
g = (h+l)//2
print('Please think of a number between 0 and 100')
print('Is your secret number ' + str(g) + '?')
x = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.')
while not x == 'c':
if x != 'h' and x!= 'l':
print('Sorry, I did not understand your input. Please try again.')
x = input('h, l, or c?')
elif x == 'h':
h = g
g = (h+l)//2
print('Is yor secret number ' + str(g))
x = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.')
elif x == 'l':
l = g
g = (h+l)//2
print('Is yor secret number ' + str(g))
x = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.')
if x == 'c':
print('Game over. Your secret number is ' + str(g))
|
from game import Game
from player import BlackjackDealer
class Blackjack(Game):
def __init__(self):
Game.__init__(self)
self.name = 'Blackjack'
self.dealer = BlackjackDealer(self)
self.winner = []
self.init_deck()
def deal(self):
''' deals 2 cards to every player in the game '''
for player in self.players:
self.hit(player)
self.hit(player)
self.hit(self.dealer)
self.hit(self.dealer)
def hit(self, player):
''' pulls card from deck to player hand '''
card = self.deck.cards.pop()
self.card_to_hand(player, card)
def card_to_hand(self, player, card):
''' adds a card to players hand'''
player.hand.append(card)
self.add_card(player, card)
def add_card(self, player, card):
''' adds value of card to players total '''
if card.value == 'Ace' and player.total + 11 > 21:
player.total += 1
card.is_used = True
elif card.value == 'Ace' and player.total + 11 <= 21:
player.total += 11
elif card.value == 'Jack' or card.value == 'Queen' or card.value == 'King':
player.total += 10
else: player.total += card.value
self.bust_check(player)
def bust_check(self, player):
''' determines if player is busted, calls busted_aces '''
self.busted_aces(player)
if player.total > 21:
player.is_busted = True
def busted_aces(self, player):
''' if player is over 21 and has ace in hand -10 '''
for card in player.hand:
if card.value == 'Ace' and card.is_used == False:
if player.total <= 21: break
player.total -= 10
card.is_used = True
def evaluate_payout_all(self):
for player in self.players:
self.evaluate_payout(player)
def evaluate_payout(self, player):
if player.is_busted == True:
player.reward = 0
elif player.total > self.dealer.total:
player.reward = int(player.wager) * 2
elif self.dealer.is_busted == True and player.is_busted == False:
player.reward = int(player.wager) * 2
elif player.total == self.dealer.total:
player.reward = player.wager
def reset(self):
for player in self.players:
player.hand = []
player.total = 0
player.is_busted = False
self.dealer.hand = []
self.dealer.total = 0
self.dealer.is_busted = False
def reset_wager(self, player, bet):
player.wager = bet
|
def enque(data):
s1.append(data)
def deque():
if len(s1) == 0:
print("queue is empty")
return
while len(s1) > 0:
s2.append(s1.pop())
d = s2.pop()
while len(s2) > 0:
s1.append(s2.pop())
return d
def length():
return len(s1)
s1 = []
s2 = []
for i in range(9):
s1.append(i+1)
enque(10)
enque(12)
#print(s1)
while len(s1)>0:
print(deque())
|
numero1 = int(input("Digite o primeiro numero: "))
numero2 = int(input("Digite o segundo numero: "))
if numero1 > numero2:
print("Maior número = " + str(numero1))
if numero2 > numero1:
print("Maior número = " + str(numero2))
if numero1 == numero2:
print("Numeros identicos ") |
def compare(num1, num2):
if num1 > num2:
return f"{num1} is greater than {num2}"
elif num1 < num2:
return f"{num1} is less than {num2}"
else:
return f"{num1} is the same as {num2}"
|
def square_sum(nr):
return (nr*(nr+1)*(2*nr +1))/6
def sum_square(nr):
return ((nr*(nr +1))/2)**2
print(square_sum(100)-sum_square(100))
|
# coding:utf-8
def get_train():
# 输入训练样本的特征以及目标值,分别存储在变量X_train与y_train之中。
X_train = [[6], [8], [10], [14], [18]]
y_train = [[7], [9], [13], [17.5], [18]]
return X_train, y_train
# 导入numpy并且重命名为np。
import numpy as np
def get_tezt_xx():
# 在x轴上从0至25均匀采样100个数据点。
xx = np.linspace(0, 26, 100)
xx = xx.reshape(xx.shape[0], 1)
return xx
# 从sklearn.linear_model中导入LinearRegression。
from sklearn.linear_model import LinearRegression
def get_LR():
return LinearRegression()
def classification_LR(X_train, y_train, xx):
# 使用默认配置初始化线性回归模型。
regressor = get_LR()
# 直接以披萨的直径作为特征训练模型。
regressor.fit(X_train, y_train)
yy = regressor.predict(xx)
# 输出线性回归模型在训练样本上的R-squared值。
print 'The R-squared value of Linear Regressor performing on the training data is', regressor.score(X_train,y_train)
return regressor, yy
# 对回归预测到的直线进行作图。
import matplotlib.pyplot as plt
def figure1(X_train, y_train, xx, yy):
plt.scatter(X_train, y_train)
plt1, = plt.plot(xx, yy, label="Degree=1")
plt.axis([0, 25, 0, 25])
plt.xlabel('Diameter of Pizza')
plt.ylabel('Price of Pizza')
plt.legend(handles=[plt1])
plt.show()
# 从sklearn.preproessing中导入多项式特征产生器
from sklearn.preprocessing import PolynomialFeatures
def get_poly(degree):
return PolynomialFeatures(degree)
def polynominal_2(X_train, xx):
# 使用PolynominalFeatures(degree=2)映射出2次多项式特征,存储在变量X_train_poly2中。
poly2 = get_poly(2)
X_train_poly2 = poly2.fit_transform(X_train)
# 从新映射绘图用x轴采样数据。
xx_poly2 = poly2.transform(xx)
return X_train_poly2, xx_poly2
# 和 上 一个 函数, 仅参数 不一样, 可以和并成一个,进行传参 degree
def polynominal_4(X_train, xx):
# 初始化4次多项式特征生成器。
poly4 = PolynomialFeatures(degree=4) # get_poly(4)
X_train_poly4 = poly4.fit_transform(X_train)
# 从新映射绘图用x轴采样数据。
xx_poly4 = poly4.transform(xx)
return X_train_poly4, xx_poly4
def classification_LR_2(X_train_poly2, y_train, xx_poly2):
# 以线性回归器为基础,初始化回归模型。尽管特征的维度有提升,但是模型基础仍然是线性模型。
regressor_poly2 = LinearRegression() # get_LR()
# 对2次多项式回归模型进行训练。
regressor_poly2.fit(X_train_poly2, y_train)
# 使用2次多项式回归模型对应x轴采样数据进行回归预测。
yy_poly2 = regressor_poly2.predict(xx_poly2)
# 输出2次多项式回归模型在训练样本上的R-squared值。
print 'The R-squared value of Polynominal Regressor (Degree=2) performing on the training data is', regressor_poly2.score(
X_train_poly2, y_train)
return regressor_poly2,yy_poly2
def classification_LR_4(X_train_poly4, y_train, xx_poly4):
# 使用默认配置初始化4次多项式回归器。
regressor_poly4 = LinearRegression()
# 对4次多项式回归模型进行训练。
regressor_poly4.fit(X_train_poly4, y_train)
# 使用2次多项式回归模型对应x轴采样数据进行回归预测。
yy_poly4 = regressor_poly4.predict(xx_poly4)
print 'The R-squared value of Polynominal Regressor (Degree=4) performing on the training data is', regressor_poly4.score(
X_train_poly4, y_train)
return regressor_poly4, yy_poly4
def figure2(X_train, y_train, xx, yy, yy_poly2):
# 分别对训练数据点、线性回归直线、2次多项式回归曲线进行作图。
plt.scatter(X_train, y_train)
plt1, = plt.plot(xx, yy, label='Degree=1')
plt2, = plt.plot(xx, yy_poly2, label='Degree=2')
plt.axis([0, 25, 0, 25])
plt.xlabel('Diameter of Pizza')
plt.ylabel('Price of Pizza')
plt.legend(handles=[plt1, plt2])
plt.show()
def figure3(X_train, y_train, xx, yy,yy_poly2, yy_poly4):
# 分别对训练数据点、线性回归直线、2次多项式以及4次多项式回归曲线进行作图。
plt.scatter(X_train, y_train)
plt1, = plt.plot(xx, yy, label='Degree=1')
plt2, = plt.plot(xx, yy_poly2, label='Degree=2')
plt4, = plt.plot(xx, yy_poly4, label='Degree=4')
plt.axis([0, 25, 0, 25])
plt.xlabel('Diameter of Pizza')
plt.ylabel('Price of Pizza')
plt.legend(handles=[plt1, plt2, plt4])
plt.show()
def get_tezt_x_y():
# 准备测试数据。
X_test = [[6], [8], [11], [16]]
y_test = [[8], [12], [15], [18]]
return X_test, y_test
def regressor_score_tezt(regressor):
print("---regressor---")
X_test, y_test = get_tezt_x_y()
regressor.score(X_test, y_test)
def regressor_poly2_score_tezt(X_train, regressor_poly2):
print("---regressor_poly2---")
X_test, y_test = get_tezt_x_y()
poly2 = get_poly(2)
X_train_poly2 = poly2.fit_transform(X_train)
# 使用测试数据对2次多项式回归模型的性能进行评估。
X_test_poly2 = poly2.transform(X_test)
regressor_poly2.score(X_test_poly2, y_test)
return X_test_poly2, y_test
def regressor_poly4_score_tezt(X_train, regressor_poly4):
print("---regressor_poly4---")
X_test, y_test = get_tezt_x_y()
poly4 = get_poly(4)
X_train_poly4 = poly4.fit_transform(X_train)
# 使用测试数据对4次多项式回归模型的性能进行评估。
X_test_poly4 = poly4.transform(X_test)
regressor_poly4.score(X_test_poly4, y_test)
# 回顾普通4次多项式回归模型过拟合之后的性能。
print regressor_poly4.score(X_test_poly4, y_test)
# 回顾普通4次多项式回归模型的参数列表。
print regressor_poly4.coef_
# 输出普通4次多项式回归模型的参数列表。
print regressor_poly4.coef_
# 输出上述这些参数的平方和,验证参数之间的巨大差异。
print np.sum(regressor_poly4.coef_ ** 2)
return X_test_poly4, y_test
# 从sklearn.linear_model中导入Lasso。
from sklearn.linear_model import Lasso
def classification_Lasso(X_train_poly4, y_train, X_test_poly4, y_test):
# 从使用默认配置初始化Lasso。
lasso_poly4 = Lasso()
# 从使用Lasso对4次多项式特征进行拟合。
lasso_poly4.fit(X_train_poly4, y_train)
# 对Lasso模型在测试样本上的回归性能进行评估。
print lasso_poly4.score(X_test_poly4, y_test)
# 输出Lasso模型的参数列表。
print lasso_poly4.coef_
# 从sklearn.linear_model导入Ridge。
from sklearn.linear_model import Ridge
def classification_Ridge(X_train_poly4, y_train, X_test_poly4, y_test):
# 使用默认配置初始化Riedge。
ridge_poly4 = Ridge()
# 使用Ridge模型对4次多项式特征进行拟合。
ridge_poly4.fit(X_train_poly4, y_train)
# 输出Ridge模型在测试样本上的回归性能。
print ridge_poly4.score(X_test_poly4, y_test)
# 输出Ridge模型的参数列表,观察参数差异。
print ridge_poly4.coef_
# 计算Ridge模型拟合后参数的平方和。
print np.sum(ridge_poly4.coef_ ** 2)
def main():
print("===========start===========")
X_train, y_train = get_train()
xx = get_tezt_xx()
regressor, yy = classification_LR(X_train, y_train, xx)
print("===========running===========")
figure1(X_train, y_train, xx, yy)
print("===========running===========")
X_train_poly2, xx_poly2 = polynominal_2(X_train, xx)
regressor_poly2, yy_poly2 = classification_LR_2(X_train_poly2, y_train, xx_poly2)
print("===========running===========")
figure2(X_train, y_train, xx, yy, yy_poly2)
print("===========running===========")
X_train_poly4, xx_poly4 = polynominal_4(X_train, xx)
regressor_poly4, yy_poly4 = classification_LR_4(X_train_poly4, y_train, xx_poly4)
print("===========running===========")
figure3(X_train, y_train, xx, yy, yy_poly2, yy_poly4)
print("===========running===========")
regressor_score_tezt(regressor)
print("===========running===========")
regressor_poly2_score_tezt(X_train, regressor_poly2)
print("===========running===========")
X_test_poly4, y_test = regressor_poly4_score_tezt(X_train, regressor_poly4)
print("===========running===========")
classification_Lasso(X_train_poly4, y_train, X_test_poly4, y_test)
print("===========running===========")
classification_Ridge(X_train_poly4, y_train, X_test_poly4, y_test)
print("===========end===========")
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# Python 3.8.6
numberOfStudents = int(input("Enter the number of students enrolled in "
"this course: "))
print()
if numberOfStudents > 0:
listOfNames = []
marksObtained = []
for x in range(numberOfStudents):
print("Enter the name of student no. ", x+1, ": ", sep = "", end = "")
dummyVariable1 = input()
listOfNames.append(dummyVariable1)
print()
for y in listOfNames:
print("Enter the marks obtained by ", y, ": ", sep = "", end = "")
dummyVariable2 = int(input())
marksObtained.append(dummyVariable2)
print()
print("The name(s) of the student(s) enrolled in this course is(are) :-")
listOfNames.sort()
# To print the list like a, b, c & d instead of like ['a', 'b', 'c', 'd'].
for z in range(numberOfStudents):
if z+1 == numberOfStudents:
print(listOfNames[z], end = " ")
elif z+2 == numberOfStudents:
print(listOfNames[z], end = " & ")
else:
print(listOfNames[z], end = ", ")
print("(in ascending alphabetical order).")
listOfNames.reverse()
# To print the list like a, b, c & d instead of like ['a', 'b', 'c', 'd'].
for w in range(numberOfStudents):
if w+1 == numberOfStudents:
print(listOfNames[w], end = " ")
elif w+2 == numberOfStudents:
print(listOfNames[w], end = " & ")
else:
print(listOfNames[w], end = ", ")
print("(in descending alphabetical order).\n")
print("The marks obtained by the student(s) enrolled in this course",
"is(are) :-")
marksObtained.sort()
# To print the list like 1, 2, 3 & 4 instead of like [1, 2, 3, 4].
for u in range(numberOfStudents):
if u+1 == numberOfStudents:
print(marksObtained[u], end = " ")
elif u+2 == numberOfStudents:
print(marksObtained[u], end = " & ")
else:
print(marksObtained[u], end = ", ")
print("(in ascending order).")
marksObtained.reverse()
# To print the list like 1, 2, 3 & 4 instead of like [1, 2, 3, 4].
for v in range(numberOfStudents):
if v+1 == numberOfStudents:
print(marksObtained[v], end = " ")
elif v+2 == numberOfStudents:
print(marksObtained[v], end = " & ")
else:
print(marksObtained[v], end = ", ")
print("(in descending order).")
else:
print("The number of students should be greater than 0!")
# /* Trivia - 15-A.py
#
# * listName.sort() sorts the specified list in ascending order.
# [This doesn't work for lists containing numerical and string elements both]
# * listName.reverse() reverses the order of the specified list.
#
# * listName[unsignedInt1 : unsignedInt2+1 : positiveInt] returns a subset of
# the specified list containing those items whose indices are in the range
# unsignedInt1 to unsignedInt2, including them both. This is known as
# slicing. positiveInt sets the incrementation. The default values of
# unsignedInt1, unsignedInt2+1 and positiveInt are 0, len(listName) and 1,
# respectively.
# [Similarly for other sequences]
#
# For negative incrementations,
# a[::-1] returns all items (reversed),
# a[1::-1] returns the first two items (reversed),
# a[:-3:-1] returns the last two (not four) items (reversed),
# a[-3::-1] returns all items except the last two (reversed), and so on.
# [For s[i:j], (i) if i is omitted/'None', then it is treated like 0.
# (ii) if j is omitted/'None', then it is treated like len(s).
# For s[i:j:k], (i) if i or j are omitted/'None', then they become the 'end'
# values (which end (i.e. left end / right end) depends on
# the sign of k).
# i and j will always represent the start and stop values,
# respectively. Only their ends will change depending on
# the sign of k.
# (ii) if k is omitted/'None', then it is treated as 1.]
# [Slices like s[2:5:-1] don't work. They return an empty sequence.]
#
# * End of Trivia */
|
# -*- coding: utf-8 -*-
# Python 3.8.6
n = 0
while n not in [1,3,5,7,9]:
n = int(input("Enter the order of the desired magic square (1/3/5/7/9): "))
print()
# To add zeroes to every position.
magicSquare = [[0 for x in range(n)] for y in range(n)]
number = 1
i = int(n/2); j = n-1
while number < (n*n)+1:
magicSquare[i][j] = number
# In case there is already a number at the calculated position.
a = i; b = j
i = i-1; j = j+1
if i == -1:
i = n-1
else:
pass
if j == n:
j = 0
else:
pass
if magicSquare[i][j] != 0:
i = a
j = b-1
else:
pass
number = number+1
for i in magicSquare:
for j in i:
if j < 10:
print(0, j, sep = "", end = " ")
else:
print(j, end = " ")
print()
# /* Trivia - 23.py
#
# * A square array of numbers, usually distinct positive integers, is called a
# magic square if the sums of the numbers in each row, each column and both
# main diagonals are the same. The order of the magic square is the number of
# integers along one side (n) and the constant sum is called the magic
# constant (M). M = (n(n^2+1))/2, if the numbers are 1,2,3,4,5,...,n^2.
# * An algorithm for the construction of odd-ordered magic squares with the
# numbers being 1,2,3,4,5,...,n^2 is as follows:
# (1) The position of 1 is (int(n/2), n-1).
# (2) If (i,j) is the position of a number, then the position of the next
# number is given by (i-1, j+1) (with appropriate wrapping, i.e. row -1
# becomes row n-1 and column n becomes column 0), unless
# (a) there is already a number at the calculated position, in which case
# the position of the next number is given by (i, j-1).
# (b) the calculated position comes out to be (-1, n), in which case the
# position of the next number is given by (0, n-2).
# [This is probably redundant]
# [In simple words, starting with 1, numbers are filled diagonally up and
# right, with appropriate wrapping. If a filled position is encountered,
# then the position of the next number becomes immediately left to that of
# the current number.]
#
# * 2-dimensional arrays/lists can be thought of as lists within a list. The
# multiple lists within a larger list can be thought of as rows, with their
# elements' indices representing the column numbers.
# For eg., list = [[1,2,3],[4,5,6],[7,8,9]]; list[1][2] returns 6.
#
# * End of Trivia */
|
# -*- coding: utf-8 -*-
# Python 3.8.6
a = int(input("Enter the integer value for which you want to know the "
"multiplication table: "))
for x in range(1,10):
print(a, "x", x, " = ", a*x, sep = "") |
# -*- coding: utf-8 -*-
# Python 3.8.6
n = int(input())
num = 1
for i in range (1, n+1):
for j in range (1, i+1):
print(num*num, end = " ")
num = num+1
print() |
# -*- coding: utf-8 -*-
# Python 3.8.6
import turtle
turtle.bgcolor("black")
myTurtle = turtle.Turtle(); myTurtle.setpos(-250,250); myTurtle.color("white")
distanceToMoveWhenCalled = 25
rows = 20; columns = 22;
rowCounterForSpiral = rows; columnCounterForSpiral = columns
while rowCounterForSpiral > 0 and columnCounterForSpiral > 0:
for x in range(rowCounterForSpiral):
myTurtle.forward(distanceToMoveWhenCalled)
myTurtle.right(90)
rowCounterForSpiral = rowCounterForSpiral-1
for y in range(columnCounterForSpiral):
myTurtle.forward(distanceToMoveWhenCalled)
myTurtle.right(90)
columnCounterForSpiral = columnCounterForSpiral-1
turtle.Screen().exitonclick()
# /* Trivia - 46.py
#
# * turtle.bgcolor(color) sets the background color of the TurtleScreen.
# * myTurtle = turtle.Turtle() creates a variable named myTurtle and assigns it
# a turtle object, which comes from the turtle module.
# * myTurtle.pendown()/myTurtle.pd()/myTurtle.down() makes the turtle draw when
# moving.
# myTurtle.penup()/myTurtle.pu()/myTurtle.up() makes the turtle not draw when
# moving.
# [The default mode is pen down]
# * myTurtle.setpos(x,y)/myTurtle.setposition(x,y)/myTurtle.goto(x,y) moves the
# turtle to the specified position.
# Initially, the bgcolor and the turtle's color are both black, so the line
# drawn when going from (0,0) to (-250,250) isn't visible.
# * myTurtle.color(color) sets the pen color of the turtle.
# * myTurtle.forward(distance)/myTurtle.fd(distance) moves the turtle forward
# by the specified distance.
# * myTurtle.backward(distance)/myTurtle.bk(distance)/myTurtle.back(distance)
# moves the turtle backward by the specified distance, opposite to the
# direction in which the turtle is headed.
# * myTurtle.right(angle)/myTurtle.rt(angle) turns the turtle right by the
# specified angle.
# * myTurtle.left(angle)/myTurtle.lt(angle) turns the turtle left by the
# specified angle.
#
# * End of Trivia */
|
# -*- coding: utf-8 -*-
# Python 3.8.6
import speech_recognition as sr
SAMPLE_AUDIO = ("sample.wav")
r = sr.Recognizer()
with sr.AudioFile(SAMPLE_AUDIO) as sourceFile:
audio = r.record(sourceFile)
try:
print("The audio file says that", r.recognize_google(audio))
except sr.UnknownValueError:
print("Google's Speech Recognition couldn't understand the audio file")
except sr.RequestError:
print("Couldn't get the results from Google's Speech Recognition")
# /* Trivia - 31.py
#
# * File formats such as mp3, aac, etc. aren't recognised by Python's
# SpeechRecognition.
# * An internet connection is required for SpeechRecognition to work.
#
# * The try block lets the user test a block of code for errors.
# The except block lets the user handle an error.
#
# * End of Trivia */
|
# -*- coding: utf-8 -*-
# Python 3.8.6
sum = 1
for x in range(2,10):
sum = sum+x
print("The sum of the first", x, "positive integers is", sum)
# /* Trivia - 07.py
#
# * for x in range(unsignedInt1, unsignedInt2+1, positiveInt) assigns a new
# value to x every time, beginning with unsignedInt1 and ending with
# unsignedInt2, no matter x's previous value. positiveInt sets the
# incrementation. The default values of unsignedInt1 and positiveInt are 0
# and 1, respectively.
# [The arguments of range() can be negative numbers as well]
# * When only one value is specified in the for loop's range, it is taken to be
# unsignedInt2+1. When two values are specified in the for loop's range, they
# are taken to be unsignedInt1 and unsignedInt2+1, respectively.
#
# * End of Trivia */
|
## Will need to test this file
## In addition will need to add sanity checks and type checks
class SrtFileCreator():
""" Constructs an SRT FILE. File name needed upon declaration of object """
def __init__(self, srt_file_name):
self.subtitle_count = 0
self.srt_file_name = srt_file_name
self.srt_file_contents = []
def addSubtitle(self, start_time_code, end_time_code, subtitle_text):
""" Adds a subtitle that will eventually be in the SRT FILE
@param a start time(string), a end time(string), the subtitle text that will be added (list whose max length is two) """
self.subtitle_count+=1
subtitle_data = {"subtitle_count": self.subtitle_count, "start_time_code":start_time_code, "end_time_code":end_time_code, "subtitle_text":subtitle_text}
self.srt_file_contents.append(subtitle_data)
def compileSRTFileContents(self):
""" Compiles the contents of the SRT file in the correct format
@return a string which is the contents of the SRT file """
srt_file_as_string = ""
for subtitle in self.srt_file_contents:
srt_file_as_string += str(subtitle["subtitle_count"])
srt_file_as_string += "\n"
srt_file_as_string += subtitle["start_time_code"]
srt_file_as_string += " --> "
srt_file_as_string += subtitle["end_time_code"]
srt_file_as_string += "\n"
for subtitle_text in subtitle["subtitle_text"]:
srt_file_as_string += subtitle_text
srt_file_as_string += "\n"
srt_file_as_string += "\n"
return srt_file_as_string
def createSRTFile(self):
""" Creates an srt file based on the information (file name and srt file content) the object holds
@return True value upon success, False value otherwise"""
try:
file_extension = ".srt"
srt_file_as_string = self.compileSRTFileContents()
srt_file = open(self.srt_file_name+file_extension,"w")
srt_file.write(srt_file_as_string)
srt_file.close()
return True
except:
return False
def main():
srt_file = SrtFileCreator("Justin Bieber Subtitle")
srt_file.addSubtitle("00:01:02.000", "00:01:04.000", ["Sade is pretty awesome I think"])
srt_file.addSubtitle("00:01:05.000", "00:01:06.000", ["Sade is pretty awesome I actually know so", "she is a boss"])
results = srt_file.compileSRTFileContents()
print results
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
"""
print bs4 object
run executable ./printSoup.py
"""
if __name__ == "__main__":
from bs4 import BeautifulSoup as soupy
myfile = open('python.html')
soup = soupy(myfile, "lxml")
print("BeautifulSoup Object: {}\na: {}\nstrong: {}".format
(type(soup), soup.find_all('a'), soup.find_all('strong')))
print("id: {}\ncss/class: {}\ncssprint: {}".format
(soup.find('div', {"id":"inventor"}),
soup.select('#inventor'), soup.select('.wow')))
"""
notice how the print statements return single item lists
$ ./printSoup.py
BeautifulSoup Object: <class 'bs4.BeautifulSoup'>
a: [<a href="https://facebook.com">here</a>]
strong: [<strong>Friends</strong>]
id: <div id="inventor">Mark Zuckerberg</div>
css/class: [<div id="inventor">Mark Zuckerberg</div>]
=========================================================
=========================================================
Lets get the actual content now
"""
print("===============================================")
print("================================================")
fbUrl = soup.find_all('a')[0]['href']
inventor = soup.find('div', {"id":"inventor"}).text
spanContent = soup.select('span')[0].getText()
# select(<class-name>)
# try-> select(<divId>)
print("Facebook URL: {}\nInventor: {}\nSpan content: {}".format
(fbUrl, inventor, spanContent))
"""
Much better! now we can easily ready the cleaned data
that should look exactly like
$ ./printSoup.py
BeautifulSoup Object: <class 'bs4.BeautifulSoup'>
a: [<a href="https://facebook.com">here</a>]
strong: [<strong>Friends</strong>]
id: <div id="inventor">Mark Zuckerberg</div>
css/class: [<div id="inventor">Mark Zuckerberg</div>]
cssprint: [<p class="wow"> Your gateway to social web! </p>]
===============================================
================================================
Facebook URL: https://facebook.com
Inventor: Mark Zuckerberg
Span content: You know it's easy to get intouch with
yourFriends on web!
"""
|
import argparse
from geo_utils import calculate_distance
STANFORD_LATITUDE =
STANFORD_LONGITUDE =
def calculate_distance_from_stanford(ref_longitude, ref_latitude):
"""
Arguments:
`records` is a list of dictionaries with `latitude` and `longitude` keypairs
`ref_longitude` is a float representing the longitude coordinate of
reference point
`ref_latitude` is a float representing the latitude coordinate of
reference point
Return value:
A list (of tuples), e.g.
[
(12.45, {'location': 'Somewhere', 'latitude': 55, 'longitude': -42}),
(555.01, {'location': 'Elsewhere', 'latitude': -2, 'longitude': -82}),
]
The first value of the tuple-pair is:
a Float: the calculated distance of the record to the reference point
The second value is:
a dict: the record from which the distance was calculated
"""
# this is an internal function in which we use to wrap up
# the work of calling calculate_distance on some object
# and using the ``ref_longitude`` and ``ref_latitude`` points
#
# the `sorted` function's key parameter...
# note that this internal function
# "knows" about ref_longitude and ref_latitude
def __calc_distance_from_obj(obj):
lng = obj['longitude']
lat = obj['latitude']
return calculate_distance(lng, lat, ref_longitude, ref_latitude)
s_records = sorted(records, key=__calc_distance_from_obj)
return s_records
|
"""
Abstract base class for all Interfaces.
:Author: Maded Batara III
:Version: v20181126
"""
from engine import ViewEvents
class Interface:
"""A view for the three-four-three game engine.
"""
def __init__(self):
"""
Initializes an Interface.
When subclassing Interface, always make sure to call super().__init__()
so the controller can communicate with your interface.
"""
self.view_events = ViewEvents()
self.controller = None
@property
def current_game(self):
"""Game: Current game on the controller."""
return self.controller.current_game
def initialize_event_handlers(self):
"""Bind all event handlers to the controller."""
if self.controller is None:
raise RuntimeError("Controller not registered in the view yet")
else:
self.controller.controller_events.won += self.on_won
self.controller.controller_events.lost += self.on_lost
def on_won(self):
"""
Event handler when the game has been judged as won by the controller.
"""
raise NotImplementedError
def on_lost(self):
"""
Event handler when the game has been judged as lost by the controller.
"""
raise NotImplementedError
def run(self):
"""
Event loop, where your interface should be started. The controller
will call this function to start your interface up.
"""
raise NotImplementedError
|
"""
Controller class for the threefourthree game.
:Author: Maded Batara III
:Version: v20181126
"""
from engine import Game, ControllerEvents
class Controller:
def __init__(self, interface):
"""
Initializes a new Controller.
"""
self.current_game = None
self.interface = interface
# Enable two-way comms between interface and view
self.interface.controller = self
self.controller_events = ControllerEvents()
# register view event handlerrs
self.interface.view_events.create += self.on_create
self.interface.view_events.move += self.on_move
self.interface.view_events.keep_playing += self.on_keep_playing
self.interface.view_events.end += self.on_end
def game_state(self):
if self.current_game is None:
return {}
return self.current_game.game_state()
def on_create(self, *args, **kwargs):
self.current_game = Game(*args, **kwargs)
def on_move(self, direction):
self.current_game.move_board(direction)
if self.current_game.is_lost():
self.controller_events.lost()
if self.current_game.is_won():
self.controller_events.won()
def on_keep_playing(self):
self.current_game.keep_playing()
def on_end(self):
self.current_game = None
def run_interface(self):
self.interface.run()
|
#Lists
X=[]
Y=[]
input('Enter list of X: ')
input('Enter list of Y: ')
#Defining function
def fizzbuzz(X,Y)
if ((len(X)+len(Y))%3)==0:
print('Fizz')
elif ((len(X)+len(Y))%5)==0:
print('Buzz')
elif ((len(X)+len(Y))%((3 and 5)or (len(X)+len(Y))):
print('fizzbuzz')
else:
print('Not applicable)
|
class Link:
empty = ()
def __init__(self, value, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.value = value
self.rest = rest
def __getitem__(self, i):
if i == 0:
return self.value
else:
return self.rest[i - 1]
def __len__(self):
return 1 + len(self.rest)
def __repr__(self):
if self.rest:
rest_str = ', ' + repr(self.rest)
else:
rest_str = ''
return 'Link {0}{1}'.format(self.value, rest_str)
def __add__(self, other):
if self == Link.empty:
return other
elif self.rest == Link.empty:
return Link(self.value, other)
else:
return Link(self.value, self.rest + other)
def expression(self):
if not self.rest:
return ''
else:
expr = str(self.value) + ' ' + self.rest.expression()
return expr.strip()
class Exp(object):
"""A call expression in Calculator."""
def __init__(self, operator, operand):
self.operator = operator
self.operand = operand
def __repr__(self):
return '({0} {1})'.format(self.operator, self.operand.expression())
|
from math import sqrt
from math import ceil
# Exercise 1. Implement the algorithm covered in lectures (and not any other algorithm) that determines if an integer n is prime. Your function should return True, if n is prime, and False otherwise. Your algorithm has to be effective for n ~ 1,000,000,000,000. A description of the algorithm covered in class appears on page 258 of the Rosen textbook.
def isPrime(n):
# Provide a correct implementation for this function
if n==2 or n==3:
return True
if n%2==0 or n<2 or n%3==0:
return False
for i in range(3, int(n**0.5)+2, 2):
if n%i==0:
return False
return True
result1 = isPrime(99999999999999999989)
expected1 = True
print "7 is prime:\t\t\t\t", result1
|
userId = 0
amountAtHand = 50000
accountNumber = 0
pin = 0
name = ''
mainArray = []
accountNotPresent = False
isLoggedIn = False
loggedInUser = {}
def registration():
global name
name = input('Input your name')
print('name has been saved')
numberAndPin()
def numberAndPin():
global accountNumber, pin, amountAtHand, name
try:
accountNumber = int(input('Type your account Number'))
except:
notANumber()
else:
checkInArray()
if accountNotPresent:
print('account number has been saved')
else:
print('account number already exists')
numberAndPin()
return
try:
pin = int(input('Input your preferred pin'))
except:
notANumber()
else:
print('pin saved successfully')
newUser = {'name': name, 'accountNumber': accountNumber, 'pin': pin,
'amountAtHand': amountAtHand}
mainArray.append(newUser)
print('You can now proceed to login')
signIn()
def checkInArray():
global mainArray
global accountNumber
global accountNotPresent
if not any(val['accountNumber'] == accountNumber for val in mainArray):
accountNotPresent = True
else:
accountNotPresent = False
def notANumber():
print('Type in a number')
numberAndPin()
def signIn():
verifyContinue= ['continue with login', 'Register']
for x in verifyContinue:
print(str(verifyContinue.index(x) + 1) + ' '+ x)
loginChoose = selectOne()
print(loginChoose)
if loginChoose == '1':
login()
elif loginChoose== '2':
registration()
else:
print('Invalid entry')
signIn()
def login():
global accountNumber, pin, loggedInUser, userId, mainArray
userNumber = input('input your account number')
userPin = input('input your pin')
for i, val in enumerate(mainArray):
if str(val['accountNumber']) == userNumber and str(val['pin']) == userPin:
loggedInUser = val
userId = i
print('Logged in')
mainMenu()
return
print('incorrect login details')
signIn()
def mainMenu():
homeSelect = ['withdrawal', 'transfer', 'enquiries']
for x in homeSelect:
print(str(homeSelect.index(x) + 1) + ' '+ x)
menuSelect = selectOne()
if menuSelect == '1':
withdrawFunc()
elif menuSelect == '2':
transferfunc()
elif menuSelect == '3':
enquiriesFunc()
else:
returnToHome()
def returnToHome():
print('invalid entry')
returnHome = ['Main Menu', 'logout']
print(str(returnHome.index(x) + 1) + ' '+ x)
chooseReturnHome = selectOne()
if chooseReturnHome == '1':
mainMenu()
elif chooseReturnHome == '2':
print('You have successfully logged out')
signIn()
else:
returnToHome()
def selectOne():
return input('select one')
def withdrawFunc():
amountToWithdraw = [1000, 5000, 10000, 'other Amount']
for x in amountToWithdraw:
print(str(amountToWithdraw.index(x) + 1) + ' '+ str(x))
withdrawAmount = selectOne()
if withdrawAmount == '1' or withdrawAmount == '2' or withdrawAmount == '3':
checkWithdrawAmount(amountToWithdraw[convertIntToString(withdrawAmount)-1])
elif withdrawAmount == '4':
try:
amountTyped = int(input('input the amount you want to withdraw'))
except:
print('Only Numbers are accepted')
withdrawFunc()
else:
checkWithdrawAmount(amountTyped)
else:
returnToHome()
def convertIntToString(param):
params = int(param)
return params
def anotherTransaction():
global loggedInUser
print('Do you want to perform another transaction')
newTransaction = ['yes', 'no']
for x in newTransaction:
print(str(newTransaction.index(x) + 1) + ' '+ str(x))
verifyTransaction = selectOne()
if verifyTransaction == '1':
mainMenu()
elif verifyTransaction == '2':
print('Thank you for banking with us {}'.format(loggedInUser['name']))
signIn()
else:
returnToHome()
def checkWithdrawAmount(amount):
global amountAtHand
if amount <= loggedInUser['amountAtHand']:
loggedInUser['amountAtHand'] -= amount
mainArray[userId] = loggedInUser
val = '''You have successfully withdrawn {} from your account,
your current balance is {}'''
print(val.format(amount, loggedInUser['amountAtHand']))
anotherTransaction()
else:
insufficient('withdraw')
def insufficient(transactType):
print('insufficient funds')
myStr = transactType + " lesser amount"
myArr = [myStr, 'Go back to the main menu']
for x in myArr:
print(str(myArr.index(x) + 1) + ' '+ x)
menuOrAmount = selectOne()
if menuOrAmount == '2':
mainMenu()
elif menuOrAmount == '1' and transactType=='withdraw':
withdrawFunc()
elif menuOrAmount == '1' and transactType=='transfer':
transferfunc()
else:
returnToHome()
def enquiriesFunc():
global loggedInUser
accountType = ['savings', 'current']
for x in accountType:
print(str(accountType.index(x) + 1) + ' '+ x)
selectedAccountType = selectOne()
if selectedAccountType == '1' or selectedAccountType == '2':
print('Your account balance is #{}'.format(loggedInUser['amountAtHand']))
anotherTransaction()
else:
returnToHome()
def transferfunc():
global loggedInUser
global mainArray
transferAccount = int(input('Input receiver\'s account number'))
amountToTransfer = int(input('Input the amount you want to transfer'))
if loggedInUser['amountAtHand'] >= amountToTransfer:
if not any(l['accountNumber'] == transferAccount for l in mainArray):
print('This account does not exist')
transferfunc()
return
else:
for i, val in enumerate(mainArray):
if transferAccount == val['accountNumber']:
val['amountAtHand'] += amountToTransfer
mainArray[i] = val
print('Your transfer of #{} to {} was successful'.format(amountToTransfer, val['name']))
loggedInUser['amountAtHand'] -= amountToTransfer
mainArray[userId] = loggedInUser
anotherTransaction()
else:
insufficient('transfer')
registration() |
#!/usr/bin/env python3
"""
Creating a Workbook object with OpenPyXL
Adding, deleting and renaming sheets
Saving the workbook to disk
"""
from openpyxl import Workbook
def main():
#Creating the Workbook object
wb = Workbook()
# Create s new sheets
ws = wb.create_sheet("A sheet", 0) # insert at first position
# Change the name of the sheet
ws.title = "Hello World!"
#Create another sheet
ws2 = wb.create_sheet("Sheet nr 2") # Insert the new sheet at the end
#Create what sheets exists in the workbook
print("Sheets in workbook:")
for sheet in wb:
print(sheet.title)
print("-"*20)
# Delete sheet "Sheet"
wb.remove(wb["Sheet"])
#del wb["Sheet"] also works
# Check what sheets are left
print("Sheets in workbook after deletion:")
for sheet in wb:
print(sheet.title)
# Save the workbook to discard
wb.save('2.3_Hello_sheets.xlsx')
print("Existing main()")
if __name__ == " __main__":
main()
|
#crear un codigo que calcule las soluciones de la ecuacion cuadratica de
# ax^2 + bx + c = 0
#para resolver se usa:
# x1 = (-b + math.sqrt(bˆ2 - 4ac)) / 2a
# x2 = (-b - sqrt(bˆ2 - 4ac)) / 2a
# sqrt es raiz cuadrada
# 2 ** 2 es para hacer potencia
import math
a = float(input('Ingrese el valor de "a" ')) #1
b = float(input('Ingrese el valor de "b" ')) #2
c = float(input('Ingrese el valor de "c" ')) #1
#mi solucion:
#x1 = (-b + math.sqrt((b ** 2) - 4 *(a * c))) / (2 * a)
# print('x1: ', x1)
# x2 = (-b - math.sqrt((b ** 2) - 4 *(a * c))) / (2 * a)
# print('x2: ', x2)
#OTRA SOLUCION (profe)
discriminante = b ** 2 - 4*a*c #no hace falta parentesis, python entiende ordenes aritmeticos
if discriminante < 0:
raiz = math.sqrt(-discriminante) * complex(0, 1) #numeros complejos i, j... se usan cuando hay raices negativas
else:
raiz = math.sqrt(discriminante)
x1= (-b + raiz) / 2*a
x2= (-b - raiz) / 2*a
print(x1, x2)
|
'''
TAREA1
Estudiante: Veronica Morera
Crear un archivo llamado tarea_1.py
Escribir un código en Python que imprima en pantalla lo siguiente:
* 3.1415926 ** 3.141592 *** 3.14159 **** 3.1415 ***** 3.141 ****** 3.14
usando el operador % para definir la cantidad de digitos decimales de PI y la cantidad de asteriscos.
'''
# SOLUCION 1:
#variables
pi = 3.1415926
asteriscos = '******'
#formateo usando % para pi y slices para los asteriscos
print()
print('#SOLUCION 1')
print ( asteriscos[:1], '%.7f' % pi , asteriscos[:2], '%.6f' % pi, asteriscos[:3], '%.5f' % pi,
asteriscos[:4], '%.4f' % pi, asteriscos[:5], '%.3f' % pi, asteriscos[:6], '%.2f' % pi )
#==============================================================================================================#
#SOLUCION 2: Usando solo formateo, reduccion de codigo
print()
print('#SOLUCION 2')
print ( '%.1s %.7f' % (asteriscos, pi), '%.2s %.6f' % (asteriscos, pi), '...etc, etc') #etc, aqui el problema es
# que el formateo de floats me redondea el numero (Igual que en solucion1)
#==============================================================================================================#
#SOLUCION 3: Convertir pi a cadena de texto:
#variables
piStr = '3.1415926'
asteriscos = '******'
print()
print('#SOLUCION 3')
print ( '%.1s %.9s' % (asteriscos, piStr), '%.2s %.8s' % (asteriscos, piStr), '%.3s %.7s' % (asteriscos, piStr),
'%.4s %.6s' % (asteriscos, piStr), '%.5s %.5s' % (asteriscos, piStr), '%.6s %.4s' % (asteriscos, piStr) )
|
'''
Crear líneas de código en Python que calcule el promedio de los valores contenidos en una lista.
Ejemplo
mis_valores = [5, 6, 10, 13, 3, 4]
Pueden usar cualquier estrategia pero que sea simple.
Considere si se tiene una lista que contiene las alturas de grupos de personas
todos = [
[177,145,167,190,140,150,180,130], # grupo 1
[165,176,145,189,170,189,159,190], # grupo 2
[145,136,178,200,123,145,145,134], # grupo 3
[201,110,187,175,156,165,156,135] # grupo 4
]
Escriba un código en python que determine cual grupo de personas contiene la mayor de todas las alturas de todas las personas
'''
#PRIMERA PARTE:
mis_valores = [5, 6, 10, 13, 3, 4]
mayor_valor = max(mis_valores)
print( 'El numero mayor de la lista "mis_valores" es', mayor_valor)
#SEGUNDA PARTE:
todos = [
[177,145,167,190,140,150,180,130], # grupo 1
[165,176,145,189,170,189,159,190], # grupo 2
[145,136,178,200,123,145,145,134], # grupo 3
[201,110,187,175,156,165,156,135] # grupo 4
]
def mayorDeVariasListas(listaCompleta):
mayor_cada_grupo = [] #contenedor del mayor de cada grupo
for lista in listaCompleta:
mayor = max(lista) #sacar el mayor de cada grupo
mayor_cada_grupo.append(mayor) #agregar a la lista el mayor de cada grupo
return mayor_cada_grupo
print('Los mayores de cada grupo en la lista "todos" son:', mayorDeVariasListas(todos))
mayor_de_todos = max(mayorDeVariasListas(todos))
print('El numero mayor de la lista "todos" es:', mayor_de_todos)
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
# In[4]:
my_list = [-17, 0, 4, 5, 9]
my_array_from_list = np.array(my_list)
my_array_from_list
# In[5]:
my_array_from_list * 10
# In[6]:
my_array_from_list + 1
# In[ ]:
#SLICING ARRAY
# In[15]:
my_vector = np.array([-17, -4, 0, 2, 21, 37, 105])
# In[16]:
my_vector[0]
# In[19]:
my_vector[0] = 3333
# In[24]:
my_vector
# In[23]:
my_vector.size
# In[25]:
#matrix
my_array = np.arange(35) #cantidad de elementos en la matriz
my_array.shape = (7,5) #si queremos que sea matriz de 7x5
my_array
# In[26]:
my_array[2]
# In[27]:
my_array[2][0]
# In[28]:
my_array[-2]
# In[29]:
my_array[5,2]
# In[31]:
np.arange(10, 23)
# In[32]:
np.arange(10, 23) -10 #le resta 10 a todos
# In[33]:
np.arange(10, 23).size
# In[34]:
#para hacer saltos, en este caso de cada 5
np.arange(10, 23, 5)
# In[36]:
#otra forma
np.arange(26, step=5)
# In[ ]:
|
'''
1- crear una tupla de mango, uvas, manzana, pera
'''
#mis_frutas = ('mango', 'uvas', 'manzana', 'pera')
#print(mis_frutas)
#-----------------------------------------------------------------
#2- agregar piña a la tupla de frutas
mis_frutas = ('mango', 'uvas', 'manzana', 'pera') + ('piña', )
#print(mis_frutas)
#-----------------------------------------------------------------
#3- indice (numero primos)
lista_pares = mis_frutas[1::2]
print('lista de pares ', lista_pares)
lista_impares = mis_frutas[0::2]
print('lista de impares ', lista_impares) |
def solution() :
N = int(input())
result = 0
for i in range(int(N/2), N) :
#print("i : ", i)
temp = i
sum_temp = i
while True :
sum_temp += temp % 10
if int(temp / 10) == 0 :
break
temp = int(temp / 10)
if sum_temp == N :
result = i
break
print(result)
solution()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.