text stringlengths 37 1.41M |
|---|
import re
txt = list("abcdefghijklmnopqrstuvwxyz")
cip = list("zyxwvutsrqponmlkjihgfedcba")
def encode(plain_text: str) -> str:
output = ""
for i in re.sub("[^0-9a-zA-Z]", "", plain_text.lower()):
if i.isdigit():
output += i
else:
index = txt.index(i)
output += cip[index]
return space(output)
def decode(ciphered_text: str) -> str:
output = ""
for i in re.sub("[^0-9a-zA-Z]", "", ciphered_text.lower()):
if i.isdigit():
output += i
else:
index = cip.index(i)
output += txt[index]
return output
def space(string: str) -> str:
return " ".join(string[i:i + 5] for i in range(0, len(string), 5))
|
''' Spillet ble i første omgang laget for å kunne kjøre på et GUI.
Det er derfor ikke implementert funksjoner som kan ta input fra brukeren
for å kunne endre tilstanden i spillet.
Det er kun opprettet et testklasse for å se at logikken i spillet fungerer
som den skal. Her ville man bare ha laget funksjoner som kunne ta input fra
brukeren (r_rawinput) som igjen kalte på de eksisterende metodene, men dette
ble ikke implementert grunnet dårlig tid, og større ønske om å få til GUI.
For å se at logikken i spillet fungerer som den skal kjører man test.py
'''
from sm import State
class RiverGame():
def __init__(self):
self.state = State()
def play(self):
self.getGameStatus()
def moveBoat(self):
# validate that man is in boat
# self.validateLand(name)
# self.validateBoat(name)
self.state.moveBoat()
self.getGameStatus()
def putInBoat(self, name):
self.validateBoat(name)
self.validateLand(name)
self.state.putInBoat(name)
def putOnLand(self, name):
self.validateLand(name)
self.validateBoat(name)
self.state.putOnLand(name)
def validateBoat(self, name):
stuffInBoatList = self.state.getStuffInBoat()
if name == "chicken":
if ("fox" in stuffInBoatList) or ("bagOfGrains" in stuffInBoatList):
if not "man" in stuffInBoatList:
print "Game over"
elif name == "fox":
if "chicken" in stuffInBoatList:
if not "man" in stuffInBoatList:
print "Game over"
elif name == "bagOfGrains":
if "chicken" in stuffInBoatList:
if not "man" in stuffInBoatList:
print "Game over"
print "boat success"
def validateLand(self, name):
stuffInBoatList = self.state.getStuffInBoat()
stuffOnLandList = self.state.getStuffOnRightSide()
boatPos = self.state.getBoatPosition()
if boatPos == "left":
stuffOnLandList = self.state.getStuffOnLeftSide()
if name != "chicken":
if name == "fox":
if ("chicken" in stuffOnLandList) and ("bagOfGrains" in stuffOnLandList) and ("man" not in stuffOnLandList):
print "Game over" + name
if name == "bagOfGrains":
if ("chicken" in stuffOnLandList) and ("man" not in stuffOnLandList):
print "Game over" + name
if name == "man":
if (("chicken" in stuffOnLandList) and
(("fox" in stuffOnLandList) or ("bagOfGrains" in stuffOnLandList))):
print "Game over" + name
def getGameStatus(self):
print "On the left side: " + ", ".join(self.state.getStuffOnLeftSide())
print "On the right side: "
print self.state.getStuffOnRightSide()
print "Boat is at: "
print self.state.getBoatPosition()
print "Stuff in boat: "
print self.state.getStuffInBoat()
|
#!/usr/bin/python3
# encoding: utf-8
# @Time : 2020/2/21 11:28
# @author : zza
# @Email : 740713651@qq.com
# @File : 动态修改.py
import types
class A:
def __init__(self):
self.a = 1
def p(self, num):
print("A", self.a)
print("num", num)
print("*" * 20)
def p(num):
print("B", None)
print("num", num)
print("*" * 20)
def p1(self, num):
print("C", self.a)
print("num", num)
print("*" * 20)
a = A()
a.p = p
a.p(1)
a.p = types.MethodType(p1, a)
a.p(2)
b = A()
b.__class__.p = p1
b.p(3)
def init_2(self):
print("init_2")
self.a = 1
A.__init__ = init_2
c = A()
c.p(3)
|
def gen_primes(a, b):
"""
Copied from stackoverflow
Generate an infinite sequence of prime numbers.
"""
D = {}
q = a
result = []
while q <= b:
if q not in D:
result.append(q)
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
return result
def solve(N, L, cyphered):
pangram = [0] * (L+1)
for i in range(0, L-1):
for p in PRIMES:
if cyphered[i] % p == 0 and cyphered[i+1] % p == 0:
pangram[i+1] = p
break
pangram[0] = cyphered[0] / pangram[1]
pangram[-1] = cyphered[-1] / pangram[-2]
alphabet = sorted(set(pangram))
d = {}
ordinal = 65
for letter in alphabet:
d[letter] = chr(ordinal)
ordinal = ordinal +1
result = ""
for j in pangram:
result = result + d[j]
return result
def run():
n_tests = int(raw_input())
for i in xrange(1, n_tests + 1):
line1 = raw_input().split()
N = int(line1[0])
L = int(line1[1])
primes = [int(x) for x in raw_input().split()]
result = solve(N, L, primes)
print "Case #%d: %s" % (i,result)
PRIMES = gen_primes(2, 10000)
run()
|
# petla while, for
# lista = ["a", "b", "d", "e", "f", "g", "h", "i", "j"]
#
# for litera in lista:
# print(litera)
# if litera == "e":
# print("to jest e!")
# range genereuje liste na podstawie liczby podanej
# for i in range(0, 51,2):
# print(i)
# ____________________________________________________________________9
# fruits = ['apple', 'orange', 'pear', 'banana', 'apple']
#
#
# i = 0
# print ("start pętli {} {}".format("yollo", "elo"))
# for i, fruit in enumerate(fruits):
# if i==3:
# break
# print(i)
# print("{} jest git".format(fruit))
# print("koniec")
# ____________________________________________________________________10
# fruits = ['apple', 'orange', 'pear', 'banana', 'apple']
# print("start")
#
# for fruit in fruits:
# print(fruit)
# if fruit == 'orange':
# continue
# if fruit == 'banana':
# break
#
# print("koniec")
# ____________________________________________________________________11
# fruits = ['apple', 'orange', 'pear', 'banana', 'apple', 'strawberry', 'apple', 'berry']
#
# if "appaa" in fruits:
# print ("jest japko")
# elif 'orange' in fruits:
# print("uraaa")
# #jeśli nie
# if 'orange' in fruits:
# print ('jes pomarancza')
# else:
# print("ni ma nic")
# operatory logiczne___________________11
|
""""The variance allows us to see how widespread the grades
were from the average.
the grades varied against the average. This is called computing the variance.
A very large variance means that the students' grades were all over the place,
while a small variance (relatively close to the average)
means that the majority of students did fairly well.
The standard deviation is the square root of the variance. You can calculate
the square root by raising the number to the one-half power."""
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print (grade)
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average
def grades_variance(scores):
average = grades_average(scores)
variance = 0
for score in scores:
variance = variance + (average - score) ** 2
total_variance = variance / len(scores)
return total_variance
#print grades_variance(grades)
def grades_std_deviation(variance):
return variance ** 0.5
variance = grades_variance(grades)
print (print_grades(grades))
print (grades_sum(grades))
print (grades_average(grades))
print (grades_variance(grades))
print (grades_std_deviation(variance))
|
BagOfHolding={'rope':1, 'tourch':6 , 'gold coin':42, 'dagger':1, 'arrow': 12}
dragonLoot=['gold coin','gold coin', 'dagger', 'gold coin', 'ruby']
#addToInventory(inventory, additem)
def displayInventory(BagOfHolding):
print ('Your inventory includes the following:' )
item=0
for k, v in BagOfHolding.items():
print (k,v)
item = item + v
print('Your total inventory includes: '+ str(item) + ' items')
def addToInventory(inventory, additem):
for i in additem:
inventory.setdefault(i,0)
inventory[i] = inventory[i] + 1
return inventory
newloot= addToInventory(BagOfHolding, dragonLoot)
displayInventory (newloot)
|
import random
messages = ('It is certain', 'It is decidedly so', 'Yes definitely','Reply hazy try again',
'ask again later','Concentrate and ask again', 'NO!', 'Outlook is not so good', 'Very doubtful')
print(messages[random.randint(0,len(messages)-1)])
#produces random number to use for index. The number will be determined by the length of the list
|
print ("Pick a number:")
spam=input()
if spam == 0:
print ("Howdey")
if spam == 2:
print("greetings")
else:
print("spam")
|
#! /usr/bin/python3
#
# Strip superfluous commas and spaces from register file
# Libreoffice adds lots of commas to pad out to the number of columns
import sys
inputfile = open(sys.argv[1], "r")
while True:
line = inputfile.readline()
if not line:
break
output_line = line.rstrip().rstrip(',')
print(output_line)
|
from enum import Enum
class TokenType(Enum):
# Arithmetic Operators
PLUS = '+'
MINUS = '-'
MUL = '*'
FLOAT_DIV = '/'
POWER = '^'
MODULO = '%'
# Relational Operators
GREATER_THAN = '>'
LESS_THAN = '<'
EQUALITY = '=='
LESS_OR_EQUAL = '<='
GREAT_OR_EQUAL= '>='
NOT_EQUAL = '!='
# Logical Operators
AND = '&'
OR = '|'
NOT = '!'
LOGIC_AND = '&&'
LOGIC_OR = '||'
# Assignment Operators
ASSIGN = '='
# Syntax
CVECTOR = 'c'
VECTOR = 'start'
LPAREN = '('
RPAREN = ')'
SEMI = ';'
DOT = '.'
COLON = ':'
COMMA = ','
LCURLY = '{'
RCURLY = '}'
LBRACKET = '['
RBRACKET = ']'
STRDOUBLE = '"'
STRSINGLE = "'" # marks the end of the block
# Control Structures
IF = 'IF'
ELSE = 'ELSE'
WHILE = 'WHILE'
FOR = 'FOR'
# block of reserved words
NUMERIC = 'NUMERIC'
BOOLTRUE = 'TRUE'
BOOLFALSE = 'FALSE'
FUNCTION = 'FUNCTION'
BREAK = 'BREAK'
CONTINUE = 'CONTINUE'
# misc
ID = 'ID'
IN = 'IN'
EOF = 'EOF'
class Token:
def __init__(self, type, value, lineno=None, column=None):
self.type = type
self.value = value
self.lineno = lineno
self.column = column
def __str__(self):
"""String representation of the class instance.
Example:
>>> Token(TokenType.INTEGER, 7, lineno=5, column=10)
Token(TokenType.INTEGER, 7, position=5:10)
"""
return 'Token({type}, {value}, position={lineno}:{column})'.format(
type=self.type,
value=repr(self.value),
lineno=self.lineno,
column=self.column,
)
def __repr__(self):
return self.__str__()
def _build_reserved_keywords():
"""Build a dictionary of reserved keywords.
The function relies on the fact that in the TokenType
enumeration the beginning of the block of reserved keywords is
marked with IF and the end of the block is marked with
the EOF keyword.
"""
# enumerations support iteration, in definition order
tt_list = list(TokenType)
start_index = tt_list.index(TokenType.IF)
end_index = tt_list.index(TokenType.EOF)
reserved_keywords = {
token_type.value: token_type
for token_type in tt_list[start_index:end_index + 1]
}
return reserved_keywords
RESERVED_KEYWORDS = _build_reserved_keywords()
MAX_STRING_LENGTH = 65535 |
import random
# Get a noun.
def get_nouns(num_nouns):
nouns_list = []
for i in range(num_nouns):
noun = input("Type a noun: ")
nouns_list.append(noun)
return nouns_list
def get_verbs(num_verbs):
verbs_list = []
for v in range(num_verbs):
verb = input("give me a verb: ")
verbs_list.append(verb)
return verbs_list
def get_adj(num_adj):
adj_list = []
for a in range(num_adj):
adj = input("give me an adjective: ")
adj_list.append(adj)
return adj_list
random.randint(0, 9)
word_dict = {}
word_dict["verbs"] = get_verbs(1)
num_nouns = 4
word_dict["nouns"] = get_nouns(num_nouns)
print ("""%s quickly %s at %s.""" % (word_dict["nouns"][random.randint(0, num_nouns - 1)],
word_dict["verbs"][0],
word_dict["nouns"][random.randint(0, num_nouns - 1)]))
#
# noun_list_1 = get_nouns(2)
# # VARIABLES
#
#
#
# materials = ["aluminum"]
# item = input("type an item:")
#
# def add_to_list (x):
# materials.append(item)
# add_to_list(item)
#
# print (materials)
# THE STORY
# print (""" ~ A Memoir ~
#
# Every once in a while,
# My """ + material + " slippers end up on the " + noun + ". " +
# name.upper() + """ knows EXACTLY
# How they got there,
# But won't spill the beans.
# Life is hard enough.
# This keeper of """ + adjective + """ beans
# Has been a bee in my bonnet for """ + number + " years too long!." +
# """You know what they say, """ + plural_noun + """ will Always come back to haunt you.
# I never should have let """ + name.title() +
# """back into my life.
# I knew that """ + adjective + """ weasel would steal
# my <3 AND my """ + noun + """.
# That's all for now.
# 'Til 'morrow.""")
# Tests
|
#!/usr/bin/env python3
# Created by Brian Musembi
# Created on May 2021
# This program calculates the factorial of a user input
def main():
# this function will calculate the factorial of a user input
print("This program calculates the factorial of the given user input.")
# loop counter variable
loop_counter = 1
# sum of positive integers variable
product_num = 1
# input
user_input = input("Enter a positive integer: ")
print("")
# process
try:
user_input_int = int(user_input)
if user_input_int > 0:
# loop statement
while loop_counter <= user_input_int:
# calculations
product_num = product_num * loop_counter
loop_counter = loop_counter + 1
# output
print("{0} factorial is {1}"
.format(user_input_int, product_num))
elif user_input_int == 0:
# output
print("0 factorial is 1.")
else:
# output
print("{} is not a positive integer!"
.format(user_input_int))
except Exception:
# output
print("That's not a number! Try again.")
finally:
print("")
print("Thanks for playing!")
if __name__ == "__main__":
main()
|
# The file contains the edges of a directed graph. Vertices are labeled as positive integers from 1 to 875714. Every
# row indicates an edge, the vertex label in first column is the tail and the vertex label in second column is the
# head (recall the graph is directed, and the edges are directed from the first column vertex to the second column
# vertex). So for example, the 11th row looks liks : "2 47646". This just means that the vertex with label 2 has an
# outgoing edge to the vertex with label 47646
# Your task is to code up the algorithm from the video lectures for computing strongly connected components (SCCs),
# and to run this algorithm on the given graph.
# Output Format: You should output the sizes of the 5 largest SCCs in the given graph, in decreasing order of sizes,
# separated by commas (avoid any spaces). So if your algorithm computes the sizes of the five largest SCCs to be 500,
# 400, 300, 200 and 100, then your answer should be "500,400,300,200,100" (without the quotes). If your algorithm finds
# less than 5 SCCs, then write 0 for the remaining terms. Thus, if your algorithm computes only 3 SCCs whose sizes are
# 400, 300, and 100, then your answer should be "400,300,100,0,0" (without the quotes). (Note also that your answer
# should not have any spaces in it.)
# WARNING: This is the most challenging programming assignment of the course. Because of the size of the graph you may
# have to manage memory carefully. The best way to do this depends on your programming language and environment, and we
# strongly suggest that you exchange tips for doing this on the discussion forums.
import numpy as np
def build_adjacency_list(gg, n):
Graph = [[i] for i in range(1,n+1)]
i = 1
k = 0
while k < len(gg):
if gg[k][0] == i:
Graph[i-1].append(gg[k][1])
k += 1
else:
i += 1
#Graph = [item for item in Graph if len(item) > 1]
return Graph
def DFSLoop(G, n, stack, leaders, finishing_times, debug=False):
# global variable t = 0 # number of nodes processed so far/for finishing times in 1st pass
t = 0
# global variable s = NULL # current source vertex/ for leaders in 2nd pass
s = 0
# Assume nodes are labeled 1 to n.
explored = {i+1:False for i in range(0,n)}
# In the second pass, we have to start by checking the node with finishing time equal do n
while stack:
print(len(stack))
ind = stack[-1]
if not explored[ind]:
s = ind
[t, explored, stack, leaders, finishing_times] = DFS(G, ind, t, s, explored, stack, leaders, finishing_times, debug=debug)
return finishing_times, leaders
def DFS(G, i, t, s, explored, stack, leaders, finishing_times, debug=False):
# mark i as explored (for the rest of DFS-Loop)
explored[i] = True
stack.remove(i)
leaders[i-1] = s
tree = [arc for arc in G if arc[0] == i]
for arc in tree:
if not explored[arc[1]]:
[t, explored, stack, leaders, finishing_times] = DFS(G, arc[1], t, s, explored, stack, leaders, finishing_times)
t += 1
finishing_times[i-1] = t
return t, explored, stack, leaders, finishing_times
def DFSIterative(G, n, stack, leaders, finishing_times):
#print("stack = {}".format(stack))
explored = {i+1: False for i in range(0,n)}
finished = {i+1: False for i in range(0,n)}
# t accounts for the finishing times
t = 0
# s accounts for the leaders
leader = stack[-1]
while stack:
node = stack[-1]
#print("Current node: {}".format(node))
#print("Current leader: {}".format(leader))
finished[node] = True
if not explored[node]:
#print("This node has not yet been explored")
explored[node] = True
leaders[node-1] = leader
# Start exploring
#adj = [arc[1] for arc in G if arc[0]==node and not explored[arc[1]]]
########################
# Some nodes might not have any connections in this direction
#if node-1 is not in G[:][0]:
# print("node not in graph")
#adj = [item for item in G[node-1][1:] if not explored[item]]
adj = G[node-1][1:]
if not adj:
# This is a sink.
#print("Node {} has no adjacent nodes".format(node))
# This could be a disconnected node. We need to prune those because they are not "leaders"
pass
else:
#print("Adjacent nodes: {}".format(adj))
for adjnode in adj:
if not explored[adjnode]:
leaders[adjnode - 1] = leader
# Push it into the stack
stack.append(adjnode)
finished[node] = False
if finished[node]:
stack.pop()
else:
# This is the second time we have seen this node; this means that it is finished
stack.pop()
#print("Current leaders: {}".format(leaders))
# We mark a node as finished if the only outgoing arcs from this node have all been explored.
if finished[node]:
#print("Node {} has been finished.".format(node))
t += 1
finishing_times[node-1] = t
#print("f({}) = {}".format(node, t))
#print(finished)
#print("Current stack: {}".format(stack))
if not stack:
# Check if there are still unexplored nodes in the graph
unexplored = [node for node,status in explored.items() if not status]
if unexplored:
# Push the first unexplored note do the stack
#print("Pushing unexplored nodes to the stack:")
stack.append(max(unexplored))
#print("Current stack: {}".format(stack))
leader = stack[-1]
return leaders, finishing_times
if __name__ == "__main__":
with open("SCC.txt", "r") as infile:
data = infile.readlines()
graph = [list(map(int, line.rstrip(" \n").split(" "))) for line in data]
n = 875714
graph_reverse = [arc[::-1] for arc in graph]
recursive = False
print("Calling DFSLoop on first graph...")
G = graph_reverse.copy()
leaders = list(np.zeros(n, dtype=int))
finishing_times = list(np.zeros(n, dtype=int))
if recursive:
stack = [i+1 for i in range(0,n)]
DFSLoop(G, n, stack, leaders, finishing_times)
#print("finishing_times = {}".format(finishing_times))
stack = [finishing_times.index(i)+1 for i in range(n,0,-1)]
stack = stack[::-1]
else:
stack = [n]
print(" Running iterative DFS 1/2:")
DFSIterative(G, n, stack, leaders, finishing_times)
#print(" -> Finishing times: {}".format(finishing_times))
stack = [finishing_times.index(n)+1]
print("Calling DFSLoop on second graph...")
G = graph.copy()
leaders = list(np.zeros(n, dtype=int))
finishing_times = list(np.zeros(n, dtype=int))
if recursive:
DFSLoop(G, n, stack, leaders, finishing_times)
else:
print("Running iterative DFS 2/2:")
DFSIterative(G, n, stack, leaders, finishing_times)
# print("**************")
# print("Finishing times for first (reversed) graph:")
# print(finishing_times)
# print("Leaders for second graph:")
# print(np.unique(leaders))
answer = []
for item in np.unique(leaders):
answer.append(leaders.count(item))
print("*****************************")
print("Answer: {}".format(sorted(answer, reverse=True)))
print("*****************************") |
import numpy as np
# Create vectors
v1 = np.array([1,2])
v2 = np.array([0,5])
# Vector arithmetic
v1 + v2
v1 * v2 # element-wise product
np.dot(v1, v2) # dot product
2.0 * v1
print "v1 = " + repr(v1)
print "v2 = " + repr(v2)
print "v1 + v2 = " + repr(v1 + v2)
print "v1 * v2 = " + repr(v1 * v2) # element-wise product
print "v1 dot v2 = " + repr(np.dot(v1, v2)) # dot product
print "2 * v1 = " + repr(2.0 * v1)
|
"""Get the best option for buying all product in one place."""
# Python modules imports
from operator import getitem
# Comparator functions imports
from .basics import get_location
def get_products_length(df, market):
"""Get the number of products that a supermarket offers."""
length = 0
for i in range(0, len(df.loc[market].values)-1):
if df.loc[market].values[i] != 0.0:
length += 1
return length
def get_sorted_values(df, all_in_one, supermarkets, user_loc, markets_loc, products):
"""Get the sorted values of every supermarket."""
length = []
for i in range(len(supermarkets)):
length.append(all_in_one[supermarkets[i]]['total_products'])
# If all supermarkets have the same number of products
if len(set(length)) == 1:
aux = dict(sorted(
all_in_one.items(),
key=lambda x: getitem(x[1],'total_sum')
))
# If not all supermarkets have the same number of products
else:
sort = dict(sorted(
all_in_one.items(),
key=lambda x: getitem(x[1], 'total_products'), reverse=True
))
max_products = all_in_one[next(iter(all_in_one))]['total_products']
aux = {}
for key, value in all_in_one.items():
if value['total_products'] == max_products:
aux[key] = value
sort_aux = dict(sorted(
aux.items(),
key=lambda x: getitem(x[1], 'total_sum')
))
aux = {}
for key, value in sort.items():
if sort_aux:
aux[list(sort_aux.keys())[0]] = sort_aux[next(iter(sort_aux))]
del sort_aux[next(iter(sort_aux))]
else:
aux[key] = value
# Check if there are more than one first-place supermarkets with the same total
count = 0
for _, value in aux.items():
if value['total_products'] == aux[next(iter(aux))]['total_products']:
count += 1
# If there are more than two supermarkets with the same total
if count >= 2:
locations = []
for key, value in aux.items():
if value['total_products'] == aux[next(iter(aux))]['total_products']:
locations.append(key)
# Get the location and select the nearest supermarket
best_loc = []
for loc in locations:
best_loc.append([loc, get_location(user_loc, markets_loc[loc])])
sort_aux = {}
for key, value in aux.items():
if best_loc:
sort_aux[best_loc[0][0]] = aux[best_loc[0][0]]
del best_loc[0]
else:
sort_aux[key] = aux[key]
return sort_aux
else:
return aux
def get_all_in_one(df, supermarkets, user_loc, markets_loc, products, quantity, products_images, products_ids):
"""Generate the "all in one list" data."""
total_prod = {}
total_aux = []
for market in supermarkets:
for i in range(len(products)):
if df.loc[market].values[i] != 0:
total_aux.append({
'id': products_ids[products[i]],
'name': products[i],
'urlImage': products_images[products[i]],
'price': df.loc[market].values[i],
'count': quantity[products[i]]
})
total_prod[market] = total_aux
total_aux = []
all_in_one = {}
for i in range(len(supermarkets)):
length = get_products_length(df, supermarkets[i])
all_in_one[supermarkets[i]] = {
'total_products': length,
'total_sum': df.loc[supermarkets[i]].values[-1],
'products': total_prod[supermarkets[i]]
}
all_in_one = get_sorted_values(
df,
all_in_one,
supermarkets,
user_loc,
markets_loc,
products
)
return all_in_one
|
# Program of simple calculaton;
print("+ for addition")
print("- for subtraction")
print("* for multiplication")
print("/ for division")
choice = input("enter choice : ")
num_1 = float(input("enter the num_1= "))
num_2 = float(input("enter the num_2= "))
if choice == "+":
addition = num_1 + num_2
print("addition", addition)
elif choice == "-":
subtraction = num_1 - num_2
print("subtraction", subtraction)
elif choice == "*":
multiplication = num_1 * num_2
print("multiplication", multiplication)
elif choice == "/":
division =num_1 / num_2
print("division", division)
else:
print("Invalid Input") |
'''
Help Text:
Before Running the script please read the help text below
To run the script use the command:
python move_and_hash.py --scramble
Please make sure the directory structure is the same as it is.
Do not change the directory structure or move files from one place to another.
The Scripts starts below...
'''
#All the libraries needed in the program
import os
import shutil
import hashlib
import argparse
#Checking the hash before the file has been copied
def sha256HashCheck(path):
with open(path,'rb') as f:
bytes = f.read()
result = hashlib.sha256(bytes).hexdigest()
return result
#function used to scramble the byte and check the hashes again
def scrambleByte(path):
with open(path,'rb') as f:
file = f.read()
# Scrambling a byte by swapping two characters
byteArray = [elem.encode("hex") for elem in file]
byteArray[0],byteArray[1] = byteArray[1],byteArray[0]
asciiArray = [int(elem,16) for elem in byteArray]
file = ''.join(chr(elem) for elem in asciiArray)
f.close()
with open(path,'w') as f1:
f1.write(file)
f1.close()
#Checking the hashes after scrambling the byte
hashBefore = sha256HashCheck(srcPath)
hashAfter = sha256HashCheck(destPath)
if (hashBefore == hashAfter):
print("Hashes Match")
else:
print("Hashes doesn't match")
#Intialising the argument parser
parser = argparse.ArgumentParser(
description="Argument for scrambling a byte in the file"
)
#Adding argument to the parser
parser.add_argument(
"--scramble",
action="store_true",
help = "Scramble Argument"
)
args = parser.parse_args()
src = './a'
dest = './b'
#Using Shitil Library to copy the file
srcPath = os.path.join(src,'file.txt')
destPath = os.path.join(dest,'file.txt')
shutil.copyfile(srcPath,destPath)
#Checking hashes after Copying the file
shaHashBefore = sha256HashCheck(srcPath)
shaHashAfter = sha256HashCheck(destPath)
if (shaHashBefore == shaHashAfter):
print("Hashes Match")
else:
print("Hashes Doesn't Match")
if (args.scramble):
print("Srambling the byte and checking hashes again")
scrambleByte(destPath) #Calling Scramble Byte Function
|
#!/usr/bin/env python
# coding: utf-8
from unittest import TestCase
from eight_puzzle import Board, distance
class TestBoard(TestCase):
def test_extend(self):
expected = [Board([1, 0, 2, 3, 4, 5, 6, 7, 8]),
Board([3, 1, 2, 0, 4, 5, 6, 7, 8])]
board = Board(range(9))
result = board.extend()
self.assertTrue(result == expected)
class TestCost(TestCase):
def test_cost(self):
expected = 1
result = distance(Board(range(9)), Board([4, 1, 2, 3, 0, 5, 6, 7, 8]))
self.assertTrue(result == expected)
class TestDistance(TestCase):
a = Board([2, 0, 3,
1, 8, 4,
7, 6, 5])
b = Board([2, 8, 3,
0, 1, 4,
7, 6, 5])
def test_distance(self):
expected = 4
result = distance(self.a, self.b)
self.assertTrue(result == expected) |
# Author: Alan Tort
# Date: 7/3/2021
# Description: Project 4b
# A function named fib that takes a positive integer parameter and returns the number at that position of the
# Fibonacci sequence
def fib(positive_integer):
"""Fib takes a positive integer parameter and returns the number at the position of the Fibonacci sequence"""
# first number is 0 (initially)
preceding_num = 0
# second number is 1 (initially)
following_num = 1
# current number is 0 (initially)
current_num = 0
# loop runs positive_integer times
for each_number in range(positive_integer):
preceding_num = following_num
following_num = current_num
current_num = preceding_num + following_num
return current_num
|
listePieces = [ ];
# [ Valeur Piece , Quantité dans machine ]
listePieces.append( [ 0.5, 6 ] );
listePieces.append( [ 0.05, 2 ] );
listePieces.append( [ 1.0, 1] );
listePieces.append( [ 0.01, 2 ] );
listePieces.append( [ 2.0, 3 ] );
listePieces.append( [ 0.1, 2 ] );
listePieces.append( [ 0.02, 0 ] );
listePieces.append( [ 0.2, 2 ] );
# Trie de la liste par valeur de piece croissante
listePieces.sort();
# Trie de la liste par valeur de piece décroissante (Pourquoi est-ce important de trier ?)
listePieces.reverse();
print( "Voici la liste des couples [Valeur - Quantité] de pièces", listePieces )
# Un client désire se payer un café.
# Un café coûte 0.30 €.
prix = 0,30;
print( "Le café coûte %s €" % prix);
# Le client paie en insérant une pièce de 2 € ( paiment = 2 ).
paiement = 2;
print( "Le client a payé %s €" % paiement);
# On détermine la somme à rembourser
aRendre = round((paiement - prix), 2);
print( "Nous devons donc rembourser %s €" % aRendre);
# On rembourse ensuite l'utilisateur avec les pièces dont on dispose.
# Rq: Si pas assez d'argent, on rembourse l'utilisateur autant qu'on le peut et on lui affiche un message d'excuse.
# On stockera la liste des pièces à rendre dans listePiecesARendre.
listePiecesARendre = [ ];
for (valeur, quantite) in listePieces :
while True:
if valeur <= aRendre and round(quantite) > 0:
# On rajoute la pièce courante aux pièces à rendre
listePiecesARendre.append( valeur );
# On cherche la position du couple [ valeur piece, quantite ]
positionCouple = listePieces.index( ([valeur, quantite]));
# et on modifie ce couple (on décrémente la quantité de la pièce courante de 1).
quantite-=1;
listePieces[ positionCouple ] = [ valeur, quantite];
# On décrémente le montant à rendre au client
# Rq: On arrondi afin d'éviter les soucis de précision ( Retirez le round vous verrez)
aRendre = round(aRendre - valeur, 2) ;
else:
break;
print( "Voici les pièces rendues: ",listePiecesARendre );
# Si nous n'avons pas pu rembourser totalement
if aRendre != 0:
print( "Nous sommes désolé, nous n'avons pas assez de pièces afin de vous rembourser totalement. (Manque ", aRendre, " €)");
print("Bonne dégustation !");
|
"""
File: bank.py
This module defines the Bank class.
"""
import pickle
import random
from csc131.ch09.savings_account import SavingsAccount
class Bank:
"""This class represents a bank as a collection of savnings accounts.
An optional file name is also associated
with the bank, to allow transfer of accounts to and
from permanent file storage."""
# The state of the bank is a dictionary of accounts and
# a file name. If the file name is None, a file name
# for the bank has not yet been established.
def __init__(self, file_name=None):
"""Creates a new dictionary to hold the accounts.
If a file name is provided, loads the accounts from
a file of pickled accounts.
:param file_name a file containing serialized pickled accounts
"""
self._accounts = {}
self._file_name = file_name
if file_name != None:
file_obj = open(file_name, 'rb')
while True:
try:
account = pickle.load(file_obj)
self.add(account)
except Exception:
file_obj.close()
break
def __str__(self):
"""Returns the string representation of the bank."""
return "\n".join(map(str, self._accounts.values()))
def _make_key(self, name, pin):
"""Returns a key for the account.
:param name: the name of the owner of the account
:param pin: the pin number of the account
"""
return name + "/" + pin
def add(self, account):
"""Adds the account to the bank.
:param account: the account to add to this Bank
"""
key = self._make_key(account.getName(), account.getPin())
self._accounts[key] = account
def remove(self, name, pin):
"""Removes the account from the bank and
and returns it, or None if the account does
not exist."""
key = self._make_key(name, pin)
return self._accounts.pop(key, None)
def get(self, name, pin):
"""Returns the account from the bank,
or returns None if the account does
not exist."""
key = self._make_key(name, pin)
return self._accounts.get(key, None)
def compute_interest(self):
"""Computes and returns the interest on
all accounts."""
total = 0
for account in self._accounts.values():
total += account.compute_interest()
return total
def get_keys(self):
"""Returns a sorted list of keys."""
# Exercise
return []
def save(self, fileName=None):
"""Saves pickled accounts to a file. The parameter
allows the user to change file names."""
if fileName != None:
self._file_name = fileName
elif self._file_name == None:
return
fileObj = open(self._file_name, 'wb')
for account in self._accounts.values():
pickle.dump(account, fileObj)
fileObj.close()
# Functions for testing
def create_bank(num_accounts=1):
"""Returns a new bank with the given number of
accounts."""
names = ("Brandon", "Molly", "Elena", "Mark", "Tricia",
"Ken", "Jill", "Jack")
bank = Bank()
upper_pin = num_accounts + 1000
for pin_number in range(1000, upper_pin):
name = random.choice(names)
balance = float(random.randint(100, 1000))
bank.add(SavingsAccount(name, str(pin_number), balance))
return bank
def test_account():
"""Test function for savings account."""
account = SavingsAccount("Ken", "1000", 500.00)
print(account)
print(account.deposit(100))
print("Expect 600:", account.get_balance())
print(account.deposit(-50))
print("Expect 600:", account.get_balance())
print(account.withdraw(100))
print("Expect 500:", account.get_balance())
print(account.withdraw(-50))
print("Expect 500:", account.get_balance())
print(account.withdraw(100000))
print("Expect 500:", account.get_balance())
def main(number=10, fileName=None):
"""Creates and prints a bank, either from
the optional file name argument or from the optional
number."""
test_account()
## if fileName:
## bank = Bank(fileName)
## else:
## bank = create_bank(number)
## print(bank)
if __name__ == "__main__":
main()
|
def listSearch(L, x):
""" Searches through a list L for the element x"""
for item in L:
if item == x:
return True # We found it, so return True
return False # Item not found |
# ---------Bài 10: Viết hàm đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n cho trước.
# Ví dụ: Hàm trả về 4 nếu n là 19922610 (do n có 4 số lẻ là 1, 9, 9, 1)
# ---------------------------------------------------------------
print("Đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n cho trước")
i=0
def count_odd(n,i):
if i==len(n) or n[i].isnumeric==False:
return 0
if int(n[i])%2!=0:
return 1+count_odd(n,i+1)
else:
return 0+count_odd(n,i+1)
n=input("Nhập số kiểm tra: ")
print(count_odd(n,i))
|
import math
n = int(input("Nhập bán kính : "))
def DienTichHinhTron(r):
s=math.pi*r*r
return s
print(f"Dien tich hinh trong co ban kinh {n}: {DienTichHinhTron(n)}") |
import sqlite3
import pandas as pd
import datetime
def fire_count(df, interest_date, day_range=7):
"""
Parameters:
df: dataframe of interest. dataframe comes from geo table in fire.db and must already be
parsed for the area of interest
interest_date: date to look forward from
day_range: # of days into the future
returns a count of the number of fires looking forward a specified # of days from a specified date
"""
fires = len(df.loc[(df.report_date > interest_date) & (df.report_date < interest_date + datetime.timedelta(day_range))])
return fires
# TODO: will be able to be smarter and consolidate the fire count and fire df dataframes
def location_fire_df(latitude, longitude, db_file='fire.db'):
"""
Parameters:
latitude (float): latitude of area of interest
longitude (float): longitude of area of interest
db_file: location of db file
returns dataframe of fires within 0.5 degrees of latitude and longitude
"""
fire_con = sqlite3.connect(db_file)
# make this a count query in the future
fire_query = 'SELECT * FROM geo WHERE latitude < ? + 0.5 AND latitude > ? - 0.5 AND longitude < ? + 0.5 AND longitude > ? - 0.5'
fire_df = pd.read_sql(fire_query, con=fire_con, params=[latitude, latitude, longitude, longitude], parse_dates=['report_date'])
return fire_df
|
"""
Course: CS 2302 [MW 1:30-2:50]
Author: Kimberly Morales
Assignment: Lab 8
Instructor: Olac Fuentes
TA(s): Anindita Nath , Maliheh Zargaran
Date: 5/9/2019
Date of last modification: 5/9/2019
Purpose of program:
To implement interesting algorithms to solve problems that often require a
more efficient algorithm with faster times.
These two problems are to discover trig identities with a randomized algorithm
and to find two equal subsets of a set with backtracking.
"""
import random
import numpy as np
import math
import mpmath
from math import *
#################################################################################################
#TRIG DISCOVERY METHODS
#################################################################################################
#Finds equivalent identiites and is modified to accomodate sec
def equal(f1, f2, tries=1000,tolerance=0.0001):
for i in range(tries):
x = random.uniform(-math.pi,math.pi)
if f1 == 'sec(x)':
f1 = 'mpmath.sec(x)'
if f2 == 'sec(x)':
f2 = 'mpmath.sec(x)'
y1 = eval(f1)
y2 = eval(f2)
if np.abs(y1-y2)>tolerance:
return False
return True
#Gets list of strings read from the file and inserts random values where x is
def gen_rand_trig(exp,x):
for l in exp:
if l == "x":
exp = exp.replace(l,str(x))
return exp
def discover_trig(fx):
found = 0 #found: Counts the total number of identities found
allE = [] #allE: All expressions
E = [] #Contains only indentities
print('Equivalent Identities')
#Goes through each trig function read from the file
for i in range(len(fx)):
for j in range(len(fx)-1):
#Make sure no functions are repeated
if i != j:
f1 = fx[i]
f2 = fx[j]
allE.append([f1,f2])
#If the functions are equal then add to E and count
if equal(f1,f2):
print(f1, ' = ', f2)
E.append([f1,f2])
found += 1
#Returns the number of identities found, equivalent identities, and all expressions
return found,E,allE
#Tests each expression with randomized values
def test_equals(stmt,tries=1000,tolerance=0.0001):
for e in stmt:
b = True #b: boolean flag to see if expression is equal
x = random.uniform(-math.pi,math.pi)
#Replaces x with random value for both functions
t1 = gen_rand_trig(e[0],x)
t2 = gen_rand_trig(e[1],x)
#Concatenates strings for sec functions
if t1 == 'sec(' + str(x) + ')':
t1 = 'mpmath.sec(' + str(x) + ')'
if t2 == 'sec(' + str(x) + ')':
t2 = 'mpmath.sec(' + str(x) + ')'
y1 = eval(t1)
y2 = eval(t2)
if np.abs(y1-y2)>tolerance:
b = False
#Identities are printed if true with '='
# '!=' indicates it is not equivalent
if b:
print(t1, ' = ', t2)
else:
print(t1, ' != ', t2)
#Reads in trig functions from a text file and appends to a string list
def read_file(filename):
fx = []
with open(filename) as f:
for line in f:
fx.append(line.replace('\n',''))
return fx
#################################################################################################
#PARTITION SUBSETSUM METHODS
#################################################################################################
def subsetsum(S,last,goal):
if goal ==0:
return True, []
if goal<0 or last<0:
return False, []
res, subset = subsetsum(S,last-1,goal-S[last]) # Take S[last]
if res:
subset.append(S[last])
return True, subset
else:
return subsetsum(S,last-1,goal) # Don't take S[last]
#Finds two equal subsets of set S
def partition(S):
p_exist = False #p_exist: If a subset can exist
#If the sum of the set is even then a solution is possible
if sum(S) % 2 == 0 :
#The goal is half of the set since the two subsets will equal to S
p_exist,s = subsetsum(S,len(S)-1,sum(S)/2)
if p_exist:
print("Partition Exists for ",S)
#Since subsetsum gets one solution, look through other half of list for second solution
for se in s:
index = 0
for se2 in S:
if se == se2:
S.pop(index)
index += 1
return s, S
else:
print("There are no equal subsets")
else:
print("Partition does not exist")
return p_exist
#################################################################################################
#MAIN
#################################################################################################
if __name__ == "__main__":
#Reads in file with trig identities and prints list
print("DISCOVER TRIG IDENTITIES")
fx = read_file('t.txt')
#If the file cannot be read due to OS then here is the hardcoded list
"""
fx = ['sin(x)', 'cos(x)', 'tan(x)', 'sec(x)', '-sin(x)', '-cos(x)', '-tan(x)',
'sin(-x)', 'cos(-x)', 'tan(-x)', 'sin(x)/cos(x)', '2*sin(x/2)*cos(x/2)',
'sin(x)*sin(x)', '1-(cos(x) * cos(x))', '(1-cos(2*x))/(2)', '(1)/(cos(x))']
"""
print('Identities read from file: ')
print(fx)
print()
results = discover_trig(fx)
#Prints results and equality test
print('Found: ', results[0])
#If you do not want to see the dump then comment out here
#########################################################
#print('\nTest Equalties: ')
#test_equals(results[2])
#########################################################
print()
#Answers question two with partitions
print("PARTITION SUBSETSUM")
S = [20,0,10,10]
print("Sum of S: ", sum(S))
print(partition(S))
|
a = int(input("First Term: "))
b = int(input("Second Term: "))
c = int(input("Third Term: "))
for factors in range (1, a):
factors = a % factor == 0
if factors == True:
print factor
else print
print ('No integer factors')
|
import calendar
from datetime import timedelta, date
def gen_calendar(year, month):
month_first = date(year, month, 1)
calendar_first = month_first - timedelta(days=month_first.weekday())
calendar_dates = []
for i in range(6):
week_dates = []
for j in range(7):
week_date = calendar_first + timedelta(days=j + i * 7)
date_items = [week_date.year, week_date.month, week_date.day]
week_dates.append(date_items)
calendar_dates.append(week_dates)
return calendar_dates
def add_months(source_date, months):
month = int(source_date.month) - 1 + months
year = int(source_date.year + month / 12)
month = month % 12 + 1
day = min(source_date.day, calendar.monthrange(year, month)[1])
return date(year, month, day) |
from random import randint
comparisons = 0
def quickSort(arr):
quickSortHelper(arr, 0, len(arr) - 1)
def quickSortHelper(arr, leftIndex, rightIndex):
global comparisons
if leftIndex < rightIndex:
comparisons += rightIndex - leftIndex
print(comparisons, rightIndex, leftIndex, arr)
pivot = partition(arr, leftIndex, rightIndex)
quickSortHelper(arr, leftIndex, pivot - 1)
quickSortHelper(arr, pivot + 1, rightIndex)
def partition(arr, leftIndex, rightIndex):
# -------------------------------------- random pivot method ------------------------------------------------------------------------
# randPivot(arr, leftIndex, rightIndex)
# -------------------------------------- last element pivot method -------------------------------------------------------------------
# rightPivot(arr, leftIndex, rightIndex)
# -------------------------------------- median of three pivot method ----------------------------------------------------------------
# medianPivot(arr, leftIndex, rightIndex)
# -------------------------------------- first element pivot method if none of the above are uncommented -----------------------------
pivot = leftIndex + 1
# partitioning
for index in range(pivot, rightIndex + 1):
if arr[index] < arr[leftIndex]:
arr[index], arr[pivot] = arr[pivot], arr[index]
pivot += 1
#reswap the pivot
pivot -= 1
arr[leftIndex], arr[pivot] = arr[pivot], arr[leftIndex]
return pivot
def rightPivot(arr, leftIndex, rightIndex):
# swapping the first and the last element
arr[leftIndex], arr[rightIndex] = arr[rightIndex], arr[leftIndex]
def randPivot(arr, leftIndex, rightIndex):
# randomly generated pivot
randIndex = randint(leftIndex, rightIndex)
# swap if the above line is uncommented
arr[leftIndex], arr[randIndex] = arr[randIndex], arr[leftIndex]
def medianPivot(arr, leftIndex, rightIndex):
mid = arr[((rightIndex - leftIndex) // 2) + leftIndex]
median = [arr[leftIndex], mid, arr[rightIndex]]
median = sorted(median)
return median[1]
if __name__ == "__main__":
A = [3, 8, 2, 5, 1, 4, 4]
# quickSort(A)
# print(A)
# print(comparisons)
medianPivot(A, 0, len(A) - 1) |
TERMINAL = 'TERMINAL'
FUNCTION = 'FUNCTION'
class Node:
def __init__(self, data, type: str):
self.children = [Node]
self.data = data
self.type = type
def PrintTree(self):
print(self.data)
for child in self.children:
child.PrintTree()
def insert(self, data, fatherId: int):
if id(self) == fatherId:
self.children.append(data)
else:
for child in self.children:
self.insert(data, fatherId)
def evaluate(self):
# Recurtion cases
# Base case 1
# I am a terminal
if self.type == 'TERMINAL':
return
# Base case 2
# All my nodes are terminals
hasFunctions = False
for child in self.children:
if child.type == FUNCTION:
hasFunctions = True
# Can evaluate now
if hasFunctions == False:
if self.data == '>=':
return self.children[0].data >= self.children[1].data
elif self.data == 'if':
if self.children[0]:
return self.children[1].data
else:
return self.children[2].data
else:
for child in self.children:
if type == FUNCTION:
return child.evaluate()
|
positivos=0
cero=0
negativos=0
for x in range(0,10):
x=int(input("ingrese un numero "))
if x==0:
cero=cero + 1
else:
if x>0:
positivos= positivos + 1
else:
negativos= negativos + 1
print("la cantidad de ceros es: " , cero)
print("la cantidad de positivos es: " , positivos)
print("la cantidad de negativos es: " , negativos)
|
## Exercise 3:
# You are the parent of 3 teenage children, and you have no idea what they are saying in their texts. You decided to write a program to translate the abbreviations they use in their texts to plain english. You will write a program that prompts the user to enter a text message, translate the text message to plain english, and print out the results. Example usage:
#
# ```
# $ python txt_xlator.py
# What is the text?
# > jk lol
# Just kidding Laughing out loud
# ```
#
# You have access to a dictionary of abbreviations. Use the built-in json module to read in the abbv.json file. Like so:
#
import json
file = open('abbv.json', 'r')
abbreviations = json.loads(file.read())
# print abbreviations
text_message = raw_input("What is the txt? ").upper()
text_message = text_message.split(" ")
print text_message
for word in text_message:
if word in abbreviations:
print abbreviations[word]
else:
print word.lower()
file.close()
|
#Note:state is always a 2d list
#this method find all unassigned cells in the initial state and return a list containing coordinates(e.g (3,4))
def getUnassigned(state):
result=[]
for i in range(len(state)):
for j in range(len(state[0])):
if not isinstance(state[i][j],int):
result.append((i, j))
return result
##this method find all bulbs and return a list containing coordinates(e.g (3,4))
def getBulbs(state):
result = []
for i in range(len(state)):
for j in range(len(state[0])):
if state[i][j]=='b':
result.append((i, j))
return result
#this method find all numbered cells and return a list containing their coordinates(e.g (3,4))
def getNumbers(state):
result = []
for i in range(len(state)):
for j in range(len(state[0])):
if isinstance(state[i][j],int):
result.append((i, j))
return result
#when searching, the number of bulbs around a numbered cell should be at most that number
#this method receives a state and returns boolean variable indicating the state is ok?
def numberConstrain(state):
row,col=len(state),len(state[1])
for (i,j) in getNumbers(state):
count=0
if i+1<=row-1 and state[i+1][j]=='b':count+=1
if i-1>=0 and state[i-1][j]=='b':count+=1
if j+1<=col-1 and state[i][j+1]=='b':count+=1
if j-1>=0 and state[i][j-1]=='b':count+=1
if count>state[i][j]:
return False
return True
#this method is used to check whether the number of bulbs around a numbered cell is exactly the same? should use this method
#when all empty cells have been assigned a value
def numberCheck(state):
row,col=len(state),len(state[1])
for (i,j) in getNumbers(state):
count=0
if(i+1<=row-1 and state[i+1][j]=='b'):count+=1
if(i-1>=0 and state[i-1][j]=='b'):count+=1
if(j+1<=col-1 and state[i][j+1]=='b'):count+=1
if(j-1>=0 and state[i][j-1]=='b'):count+=1
if(count!=state[i][j]):
return False
return True
#this method returns a set containing coordinates which are lit(the bulbs' coordinates are also included)
def findLit(state):
bulbs=getBulbs(state)
result=[]
if(len(bulbs)>0):
for(i,j) in bulbs: #for each bulb the first 2 while loops find cells which are lit horizontally by that bulb(i is fixed)
k=0 #the last 2 find cells which are lit vertically(j is fixed) (till the light hits a number cell)
while j+k<len(state[1]) and (not isinstance(state[i][j+k],int)):
result.append((i,j+k))
k+=1
k=0
while j-k>=0 and (not isinstance(state[i][j-k],int)):
result.append((i,j-k))
k+=1
k=0
while i+k<len(state) and (not isinstance(state[i+k][j],int)):
result.append((i+k,j))
k+=1
k=0
while i-k>=0 and (not isinstance(state[i-k][j],int)):
result.append((i-k,j))
k+=1
result.append((i,j))
return set(result)
#this is one of the constrains
#this method returns a list containing cells that are neither lit (note that we assume the bulbs' cells are lit) nor numbered
def goodCells(state):
row,col=len(state),len(state[0])
result=[]
lit=findLit(state) #note that lit and numbers are both list
numbers=getNumbers(state)
for i in range(row):
for j in range (col):
if (i,j) not in lit and (i,j) not in numbers:
result.append((i,j))
return set(result)
#this method checks whether a solution is valid(i.e. every cell is lit and the number condition is satisfied)
#only use this method when every empty cell has been assigned a value(either '_' or 'b')
def solutionCheck(state):
return len(goodCells(state))==0 and numberCheck(state)
#when #bulbs around the numbered cell is greater, we should exit the current loop and do backtracking
#use this method when the searching has not been done(there is still some empty cell)
#when searching, if we always choose the next cell from goodCells(), then we are guaranteed that the light
#from two bulbs will not overlap
#another constrain
def constraintsCheck(state):
return numberConstrain(state)
|
# Write a function is_even that will return true if the passed-in number is even.
# YOUR CODE HERE
def is_even(x):
return True if x%2 == 0 else False
while True:
# Read a number from the keyboard
num = input("Enter a number: ")
num = int(num)
# Print out "Even!" if the number is even. Otherwise print "Odd"
# YOUR CODE HERE
eval = is_even(num)
if eval:
print('Even!')
else:
print('Odd')
stop = input("Again? (y/n)")
if str(stop) == 'n':
break |
#_*_ coding:utf-8 _*_
"""
线性回归算法:
寻找一条直线, 最大程度的 "拟合" 样本特征和样本输出标记之间的关系
分类问题的横纵坐标都是样本特征, 而回归问题横轴是样本特征,
纵轴是样本的 label(比如房屋的面积和价格).
线性回归算法的评测:
如果使用均方误差 MSE 的话, 量纲上可能会有问题, 所以, 一般使用
1. 根均方误差: RMSE (Root Mean Squared Error)
sqrt(MSE)
2. 平均绝对误差: MAE(Mean Absolute Error)
1/m sum_{1}^{m} |yi - yi_predict|
3. R Squared:
"""
"""
实现 simple linear regression
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1., 2., 3., 4., 5.])
y = np.array([1., 3., 2., 3., 5.])
fig1 = plt.figure()
plt.scatter(x, y)
plt.axis([0, 6, 0, 6])
x_mean = np.mean(x)
y_mean = np.mean(y)
numerator = np.dot((x - x_mean), (y - y_mean))
denominator = np.dot((x - x_mean), (x - x_mean))
a = numerator / denominator
b = y_mean - a * x_mean
print(a.dtype, b)
y_hat = a * x + b
plt.plot(x, y_hat, color='r')
"""
衡量回归算法的标准
"""
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import r2_score
boston = load_boston()
x = boston.data[:, 5] # 只使用房间数量的特征
y = boston.target
x = x[y < np.max(y)]
y = y[y < np.max(y)]
fig2 = plt.figure()
plt.scatter(x, y)
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=666)
x_train = x_train.reshape(-1, 1)
y_train = y_train.reshape(-1, 1)
x_test = x_test.reshape(-1, 1)
y_test = y_test.reshape(-1, 1)
reg = LinearRegression()
reg.fit(x_train, y_train)
score1 = reg.score(x_test, y_test)
y_predict = reg.predict(x_test)
score2 = r2_score(y_test, y_predict)
print("R^2 Score 1: ", score1)
print("R^2 Score 2: ", score2)
"""
多元线性回归模型
"""
X = boston.data # 使用所有的特征
Y = boston.target
X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state=666)
lin_reg = LinearRegression()
lin_reg.fit(X_train, y_train)
score1 = lin_reg.score(X_test, y_test)
y_predict = lin_reg.predict(X_test)
score2 = r2_score(y_test, y_predict)
print("R^2 Score 1: ", score1)
print("R^2 Score 2: ", score2)
"""
kNN Regressor
"""
from sklearn.neighbors import KNeighborsRegressor
knn_reg = KNeighborsRegressor(n_neighbors=5)
knn_reg.fit(X_train, y_train)
print("kNN Score: ", knn_reg.score(X_test, y_test))
"""
对 KNN 使用网格搜索
"""
from sklearn.model_selection import GridSearchCV # CV 表示 Cross Validation
param_grid = [
{
"weights": ["uniform"],
"n_neighbors": [i for i in range(1, 11)]
},
{
"weights": ["distance"],
"n_neighbors": [i for i in range(1, 11)],
"p": [i for i in range(1, 6)]
}
]
knn_reg = KNeighborsRegressor()
grid_search = GridSearchCV(knn_reg, param_grid, n_jobs=-1, verbose=1)
grid_search.fit(X_train, y_train)
print(grid_search.best_params_)
print("cv_best_score: ", grid_search.best_score_)
print("r2_score: ", grid_search.best_estimator_.score(X_test, y_test))
|
'''
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)
HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
'''
def make_readable(seconds):
SS = seconds % 60
HH = seconds // 60 % 60
MM = seconds // 60 // 60
li = [MM,HH,SS]
for i in li:
if len(str(i)) == 1 :
li[li.index(i)] = '0'+str(i)
print(li)
else:
li[li.index(i)] = str(i)
return ":".join(li)
'''
很简单的题,大神们写的代码都好短
'''
|
import json
from collections import defaultdict
import config
import requests
import pandas as pd
from pandas import DataFrame
# Storing the API Keys
API_KEY = config.api_key
class NYTimes:
"""
This program uses the NY Times API to check relevant articles that
for a specifc time period on a specific topic
The StructuredString cleans up the data from the API on the specific
information on the subsection and given dates
Make sure to use the print to see the output
"""
def __init__(self, *args):
self.month, self.day, self.year, self.subsection_key = args
self.apikey = API_KEY
self.all_articles = self.SetupClient(self.year, self.month, self.apikey)
self.completed_articles = self.SpecificTimeframe(self.all_articles, self.day)
self.clean_articles = self.StructuredString(self.completed_articles)
def __str__(self):
return self.clean_articles
def StructuredString(self, clean_data):
struct_string = "These are the relevant topics: \n"
for data in clean_data:
headline, topic, website = data
struct_string = struct_string + "Headline: {0:.50s} \n Website can be found: {1} \n\n".format(headline, website)
return struct_string
def SetupClient(self, year, month, apikey):
url = "http://api.nytimes.com/svc/archive/v1/"+str(year)+"/"+str(month)+".json?api-key="+apikey
rdata = requests.get(url).text
jdata = json.loads(rdata)
all_articles = jdata['response']['docs']
return all_articles
def SpecificTimeframe(self, all_data, day):
# Will store all the dates in the list
list_of_dates = []
for i, data in enumerate(all_data):
# Only want the dates that align with the debate nights
published_date = data['pub_date']
published_date = int(published_date[8:10])
if (published_date == int(day)):
main_title = all_data[i+1]['headline']['main']
subsection = all_data[i+1]['subsection_name']
url = all_data[i+1]['web_url']
list_of_dates.append([main_title, subsection, url])
return self.SpecificSubsection(list_of_dates)
def SpecificSubsection(self, data_of_dates):
# List of all the values that we have to focus on the given topic
list_subsection = []
# List of the given dates
for i, article in enumerate(data_of_dates):
title, subsection, url = article
# Extracting the specific subtopics
if subsection == self.subsection_key:
list_subsection.append(article)
return list_subsection
def main():
try:
data = NYTimes()
return data
except:
return "Information on the given date and topic were not found"
if __name__ == "__main__":
sys.exit(main())
|
# Crear un codigo que calcule las soluciones de la ecuacion cuadratica.
# ax2+bx+c
# x2+b+1
#x1= -b + b2-4.a.c / 2a #primero el descriminante
#x2= -b-b2 -4.a.c/2a
#importar paquete math
import math
a = float(input('favor ingresar a'))
b = float(input('favor ingresar b'))
c = float(input('favor ingresar c'))
discriminante = b ** 2 -4*a*c
if discriminante < 0: #espacio normalmente se pide despues de dos puntos
raiz = math.sqrt(-discriminante)* complex(0,1) #por ser negativo
else:
raiz = math.sqrt(discriminante)
x1 = (-b + raiz)/ (2*a)
x2 = (-b - raiz) / (2*a)
print (x1, x2)
#math.sqrt(2) #raiz cuadrada, la raiz del valor dentro del parentesis 2**2 doble asterisco. 100** 11
#depurar con la cuca,
#clic derecho evaluar expresiones
# alfanumericos , no se complique la vida, no caracter extrño, no tildes, lo mas simple posible
|
"""
After saving Christmas five years in a row, you've decided to take a vacation
at a nice resort on a tropical island. Surely, Christmas will go on without you.
The tropical island has its own currency and is entirely cash-only. The gold
coins used there have a little picture of a starfish; the locals just call them
stars. None of the currency exchanges seem to have heard of them, but somehow,
you'll need to find fifty of these coins by the time you arrive so you can pay
the deposit on your room.
To save your vacation, you need to get all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each
day in the Advent calendar; the second puzzle is unlocked when you complete the
first. Each puzzle grants one star. Good luck!
Before you leave, the Elves in accounting just need you to fix your expense
report (your puzzle input); apparently, something isn't quite adding up.
Specifically, they need you to find the two entries that sum to 2020 and then
multiply those two numbers together.
For example, suppose your expense report contained the following:
1721
979
366
299
675
1456
In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying
them together produces 1721 * 299 = 514579, so the correct answer is 514579.
Of course, your expense report is much larger. Find the two entries that
sum to 2020; what do you get if you multiply them together?
"""
import os
def find_target_sum_by_two(nums):
for i in range(len(nums)):
for k in range(i+1, len(nums)):
if nums[i] + nums[k] == 2020:
return nums[i], nums[k]
return None
def find_target_sum_by_three(nums):
nlen = len(nums)
for i in range(nlen):
for k in range(i+1, nlen):
for j in range(k+1, nlen):
if nums[i] + nums[k] + nums[j] == 2020:
return nums[i], nums[k], nums[j]
return None
def main():
with open(os.path.join(os.path.dirname(__file__), '01.txt')) as reader:
nums = [int(n) for n in reader.readlines()]
n1, n2 = find_target_sum_by_two(nums)
print(n1 * n2)
nums.sort()
n1, n2, n3 = find_target_sum_by_three(nums)
print(n1 * n2 * n3)
if __name__ == "__main__":
main()
|
class Stack:
def __init__(self):
self.container = []
def push(self, data):
self.container.append(data)
def pop(self):
return self.container.pop()
def stackSize(self):
return len(self.container)
def isEmpty(self):
return self.container == []
def peek(self):
return self.container[len(self.container) - 1]
def showStack(self):
return self.container
class LinkedList(object):
def __init__(self, value):
self.value = value
self.next = None
|
class Class03:
"""A Sample Calss01"""
def __init__(self):
print("Created object for Class03...!!!")
class Class04:
"""A Sample Calss02"""
def __init__(self):
print("Created object for Class04...!!!")
def main():
""" To give access to this code from outside of this module"""
Class03()
Class04()
if __name__ == "__main__":
# O1 = Class03()
# O2 = Class04()
print("The module1 is being run directly..")
main()
else:
print("The module1 is import to current module ")
# When we import this module into other modules, init will call 2 times , to avoid use if __name__ = __main__
|
def dateTwoDaysLater(month, day, year):
M1 = {4, 6, 9, 11}
M2 = {1, 3, 5, 7, 8, 10}
M3 = {12}
M4 = {2}
D1 = set(list(range(1, 27)))
D2 = {27}
D3 = {28}
D4 = {29}
D5 = {30}
D6 = {31}
state = 0 #state表示是否是闰年,0表示不是,1表示是闰年
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
state = 1
if month in M1 and day in D1 | D2 | D3:
day = day + 2
elif month in M1 and day in D4:
day = 1
month = month + 1
elif month in M1 and day in D5:
day = 2
month = month + 1
elif month in M2 and day in D1 | D2 | D3 | D4:
day = day + 2
elif month in M2 and day in D5:
day = 1
month = month + 1
elif month in M2 and day in D6:
day = 2
month = month + 1
elif month in M3 and day in D1 | D2 | D3 | D4:
day = day + 2
elif month in M3 and day in D5:
day = 1
month = 1
year = year + 1
elif month in M3 and day in D6:
day = 2
month = 1
year = year +1
elif month in M4 and day in D1:
day = day + 2
elif month in M4 and day in D2 and state == 1:
day = day + 2
elif month in M4 and day in D2 and state == 0:
day = 1
month = month + 1
elif month in M4 and day in D3 and state == 1:
day = 1
month = month + 1
elif month in M4 and day in D3 and state == 0:
day=2
month = month + 1
elif month in M4 and day in D4 and state == 1:
day = 2
month = month + 1
else:
return "输入错误"
return "{}年{}月{}日".format(year, month, day)
testlist = [[1, 4, 27, 2005, "2005年4月29日"],
[2, 4, 29, 2005, "2005年5月1日"],
[3, 6, 30, 2000, "2000年7月2日"],
[4, 6, 31, 2000, "输入错误"],
[5, 3, 29, 2005, "2005年3月31日"],
[6, 5, 30, 2005, "2005年6月1日"],
[7, 5, 31, 2005, "2005年6月2日"],
[8, 12, 20, 2005, "2005年12月22日"],
[9, 12, 30, 2000, "2001年1月1日"],
[10, 12, 31, 2000, "2001年1月2日"],
[11, 2, 26, 2000, "2000年2月28日"],
[12, 2, 27, 2000, "2000年2月29日"],
[13, 2, 27, 2005, "2005年3月1日"],
[14, 2, 28, 2000, "2000年3月1日"],
[15, 2, 28, 2005, "2005年3月2日"],
[16, 2, 29, 2000, "2000年3月2日"],
[17, 2, 29, 2005, "输入错误"],
[18, 2, 31, 2000, "输入错误"]] #判定表测试用例
print("{:^12}{:^18}{:^18}{:^18}{:^18}".format("用例编号", "输入条件", "预期结果", "实际结果", "结论"))
for i in testlist:
temp = dateTwoDaysLater(i[1], i[2], i[3])
conclusion = "fail"
if temp == i[4]:
conclusion = "pass"
print("{:^18d}{:^6}{:^6}{:^6}{:^18}{:^18}{:^18}".format(i[0], i[1], i[2], i[3], i[4], temp, conclusion))
|
# 1- (started, end, step calculate)
# 2- we can do for inside for
# 3- we can do if inside for
for x in range(1, 10, 2):
print(x)
class open_doors():
def __init__(self, status, open, closed):
self.open_doors = open_doors
self.status = status
self.open = open
self.closed = closed
# SEQUENCE FindCallButton USING Direction AND Floor
# FOR EACH Button IN CallButtons
# IF Floor = Button Floor AND Direction = Button Direction THEN
# RETURN Button
# END FOR
# END SEQUENCE |
# Binary Search
def binary_search(data, elem):
low = 0
high = len(data) - 1
while low <= high:
middle = (low + high) // 2
if data[middle] == elem:
print("Your desired element ", elem, "is at position ", middle)
return middle
elif data[middle] > elem:
print("This position's values is too high, still searching...")
high = middle - 1
elif data[middle] < elem:
print("This position's values is too low, still searching...")
low = middle + 1
else:
print("Your desired element does not exist in this list of data")
return -1
data_values = [1, 3, 4, 6, 7, 8, 10, 13, 14, 18, 19, 21, 24, 37, 40, 45, 71]
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
desired_element = int(input("Enter your desired element here: "))
binary_search(data_values, desired_element)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
#New Adventure style game.
#Trapped at the zoo
'''Player gets trapped at zoo after dark. Various scenes follow where player:
travels to different areas,
enters different enclosures, and
meets new animal friends.
Animals can:
talk to player,
help player, or
harm player.
There will be challenges throughout where player must:
identify friends and foes,
decide which direction to go,
solve a puzzle,
etc.
'''
'''Object structure:
Character
-name
-health
-speak()
Player
Animal
snake
giraffe
monkey
tiger
penguin
bugs
beetle
ant
bee
Zoo [map]
Scene
Enclosure
polar
safari/jungle
monkey
marine
Impasse [obstacles]
'''
class Character(object):
def __init__(self, name):
self.name = name
self.health = 100
def speak(self, sentence):
print(self.name, "\b:", sentence)
miket = Character("Michael T")
miket.speak("Daz wuz up!")
|
#Class-based programming quiz. Importing quiz functions
import random
import ex27v2
oop_phrases = {
#word_drills = {
'class': 'Tell Python to make a new type of thing.',
'object': 'Two meanings: the most basic type of thing, and any instance of some thing.',
'instance': 'What you get when you tell Python to create a class.',
'def': 'How you define a function inside a class.',
'self': 'Inside the functions in a class, self is a variable for the instance/object being accessed.',
'inheritance': 'The concept that one class can inherit traits from another class, much like you and your parents.',
'composition': 'The concept that a class can be composed of other classes as parts, much like how a car has wheels.',
'attribute': 'A property classes have that are from composition and are usually variables.',
'is-a': 'A phrase to say that something inherits from another, as in a "salmon" is-a "fish."',
'has-a': 'A phrase to say that something is composed of other things or has a trait, as in "a salmon has-a mouth."',
#}
#phrase_drills = {
'class X(Y)': '"Make a class named X that is-a Y."',
'class X(object): def __init__(self, J)': '"class X has-a __init__ that takes self and J parameters."',
'class X(object): def M(self, J)': '"class X has-a function named M that takes self and J parameters."',
'foo = X()': '"Set foo to an instance of class X."',
'foo.M(J)': '"From foo get the M function, and call it with parameters self, J."',
'foo.K = Q': '"From foo get the K attribute and set it to Q."'
#}
}
oop_list = ex27v2.listmaker(oop_phrases)
def answer_this():
response = input("> ")
response = response.lower()
if response == 'q':
ex27v2.endgame("User quit")
else:
return response
def flashcards(x):
print("Use this as a chance to test your OOP knowledge.")
turns = x
while turns > 0:
print("-" * 15, "\nTurns left: %d\
\nWhat is the plain English meaning of this?" % turns)
flash = random.choice(oop_list)
print(flash)
answer_this()
print("-" * 5, "\nHere is the correct answer:",
"\n%s" % oop_phrases[flash])
turns -= 1
ex27v2.endgame("Out of turns")
if __name__ == '__main__':
flashcards(5)
|
# dictionary of recognized words
# words are matched with their type and sent to parser.py
# where they become sentences that the app can understand
def scan(userinput):
# create list or dictionary of parts of speech, maybe expected
# words for input
vocab = {'north': 'direction', 'south': 'direction', 'east': 'direction',
'west': 'direction', 'down': 'direction', 'up': 'direction',
'left': 'direction', 'right': 'direction', 'back': 'direction',
'forward': 'direction', 'eat': 'verb', 'go': 'verb', 'kill': 'verb',
'place': 'verb', 'run': 'verb', 'set': 'verb', 'stop': 'verb',
'tell': 'verb', 'throw': 'verb', 'the': 'stop', 'in': 'stop', 'of': 'stop',
'from': 'stop', 'door': 'noun', 'bear': 'noun',
'princess': 'noun', 'cabinet': 'noun'
}
words = userinput.lower().split()
#split userinput into separate words and punctuation
#make list of tuples containing userinput words and their types
matchedwords = []
for word in words:
if word in vocab:
matchedwords.append((vocab[word], word))
else:
try:
word = int(word)
matchedwords.append(('number', word))
except ValueError:
matchedwords.append(('error', word))
#create sentence by using putting tuple list words in order by type
return matchedwords
|
import os
import datetime
import PIL.Image
ASCII_chars = ['@', '#', 'S', '%', '*', '+', ';', ':', ',', '.', '`']
def resize_image(image, new_height=90):
width, height = image.size
ratio = width / height * 1.5
new_width = int(new_height * ratio)
resized_image = image.resize((new_width, new_height))
return resized_image
def greyify(image):
greyscale_image = image.convert('L')
return greyscale_image
def pixels_to_ascii(image):
pixels = image.getdata()
characters = ''.join([ASCII_chars[pixel // 25] for pixel in pixels])
return characters
def date_stamp():
return datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# c:\Users\Michael\Desktop\illum.jpg
def main(path, desired_height):
try:
image = PIL.Image.open(path)
except:
return path, ' is not a valid pathname to an image.'
new_width, new_height = resize_image(image, desired_height).size
new_image_data = pixels_to_ascii(greyify(resize_image(image, desired_height)))
pixel_count = len(new_image_data)
ascii_image = '\n'.join(new_image_data[i:(i + new_width)] for i in range(0, pixel_count, new_width))
return ascii_image
if __name__ == "__main__":
path = input("Choose an image (filepath): ")
desired_height = int(input("Desired height in lines (e.g. 90): "))
print(main(path, desired_height))
|
from decimal import Decimal
a = 4.2
b = 2.1
print(a + b)
print((a+b) == 6.3)
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b)
|
import numpy as np
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
print(x * 2)
ax = np.array([1, 2, 3, 4])
ay = np.array([5, 6, 7, 8])
print(ax * 2) |
x = 1234.5678
print(format(x, '0.2f'))
print(format(x, '>10.1f'))
print(format(x, ','))
"""
% operation is less powerful than modern format()
""" |
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
data = zip(list1, list2)
print(data)
data = sorted(data)
print(data)
#parallel sorting list
list1, list2 = map(lambda t: list(t), zip(*data))
print(list1)
print(list2)
|
# List basic
empty = []
empty = list()
sodas = ["Coke", "Pepsi", "Dr. Pepper"]
print(len(sodas))
print("fast" in "breakfast")
meals = ["breakfast", "lunch", "dinner"]
print("lunch" in meals)
print("lunch" not in meals)
test_scores = [99.0, 35.0, 23.5]
print(99.0 in test_scores)
print("organic"[5])
web_browsers = ["Chrome", "Firefox", "Safari", "Opera", "Edge"]
print(web_browsers[0])
print(web_browsers[2][4])
print(web_browsers[-2])
print("programming"[3:6])
muscles = ["Biceps", "Triceps", "Deltoid", "Sartorius"]
print(muscles[1:3])
print(muscles[::2])
print(muscles[0:1:2])
|
rmb_str_valur = input('请输入人民币金额:')
print('您输入的金额为:', rmb_str_valur)
rmb_value = eval(rmb_str_valur)
usd_vs_rmb = 6.77
usd_value=rmb_value / usd_vs_rmb
print('美元金额为:', usd_value)
a1 = 34
a2=str(34)
print(a1+eval(a2)) |
USD_VS_RMB = 6.77
mmb_str_valur = input('请输入带符号的金额:')
print('您输入的金额为:', mmb_str_valur)
unit = mmb_str_valur[-3:]
input_value = mmb_str_valur[0:-3]
input_value = eval(input_value)
print(unit)
print(input_value)
if unit == 'RMB':
usd_value = input_value / USD_VS_RMB
print("美元金额为 : ",usd_value)
elif unit == 'USD':
rmb_value = input_value * USD_VS_RMB
print("人民币金额为 : ", rmb_value)
|
# Reinforcement Learning
Watch this video:
<iframe width="560" height="315" src="https://www.youtube.com/embed/kopoLzvh5jY" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<hr>
:::{admonition} Assignments:
:class: hint
1. *Individual* -- Find a real-life business application of reinforcement learning
2. *Team* -- Gather all applications and discuss what the shared characteristics are
3. *Team* -- Develop a concept for a new application that is based on reinforcement learning
:::
## An example
We will have the computer play a coin tossing game. The coin is biased and lands 80% of time on heads. First we'll let the computer bet randomly.
We will start by defining the state space which tells what the possible states of the coin can be (1 = heads, 0 = tails). We'll do the same for the action space which is the set of possible bets (1 = bet on heads, 0 = bet on tails).
import numpy as np
ssp = [1, 1, 1, 1, 0]
asp = [1, 0]
Next we'll define a function `epoch()` that plays the game a hundred times and let it run 15 times. As expected the average reward is around 50.
def epoch():
tr = 0
for _ in range(100):
a = np.random.choice(asp)
s = np.random.choice(ssp)
if a == s:
tr += 1
return tr
rl = np.array([epoch() for _ in range(15)])
rl
round(rl.mean(), 2)
Now we'll let the computer remember the states of the coin by adding them to the action set each time a game has been played.
def epoch():
tr = 0
asp = [1, 0]
for _ in range(100):
a = np.random.choice(asp)
s = np.random.choice(ssp)
if a == s:
tr += 1
asp.append(s)
return tr
rl = np.array([epoch() for _ in range(15)])
rl
round(rl.mean(), 2)
:::{admonition} Assignments:
:class: hint
- *Individual* -- Try to change the parameters and understand the mechanics of the separate functions
::: |
from simplecrypt import encrypt, decrypt
import base64
import random
from Account import *
import sys
def welcome():
print("Welcome to Cardiff ATM!")
print("1. Login into your account")
print("2. Create new account ")
print("3. Exit")
answer = input("- ")
print()
try:
if int(answer) == 1:
loginAccount()
elif int(answer) == 2:
print("Let's create a new account for you. Please enter your password!")
createAccount()
elif int(answer) == 3:
print("Goodbye!")
sys.exit()
else:
welcome()
except ValueError:
welcome()
def createAccount():
answer = input("- ")
if len(answer) >= 6:
# save card number, 0 balance, enrypted password
encryptedPassword = encrypt(answer, answer)
cardNumber = random.randint(1000000,9999999)
with open("accounts.txt", "a") as fileObjc:
fileObjc.write(str(cardNumber) + " " + str(base64.b64encode(encryptedPassword),'utf-8') + " " + "0\n")
account = Account(str(cardNumber), 0)
mainMenu(account)
else:
print("Your password must have at least 6 characters")
createAccount()
def loginAccount():
print("Enter your card number!")
cardNumber = input("- ")
print("Enter your password")
password = input("- ")
found = False
balance = 0
with open("accounts.txt") as fileObjc:
for line in fileObjc.readlines():
line = line.split()
if line[0] == cardNumber:
try:
decryptedPassword = decrypt(password, base64.b64decode(line[1])).decode("utf8")
except:
print("Incorrect password! Try again!")
loginAccount()
if decryptedPassword == password:
print("You logged in successfully!\n")
found = True
balance = int(line[2])
account = Account(line[0], balance)
mainMenu(account)
break
else:
break
if found == False:
print("Authenticatin failed!")
print()
welcome()
def mainMenu(account):
print("Main menu")
print("1. Check balance")
print("2. Deposit")
print("3. Withdrawal")
print("4. Send money")
print("5. Lottery")
print("6. Exit")
answer = input("- ")
print()
try:
if int(answer) == 1:
checkBalance(account)
elif int(answer) == 2:
deposit(account)
elif int(answer) == 3:
withdrawal(account)
elif int(answer) == 4:
sendMoney(account)
elif int(answer) == 5:
lottery(account)
elif int(answer) == 6:
sys.exit()
else:
mainMenu(account)
except ValueError:
mainMenu(account)
def updateDatabase(account):
newFileLines = []
with open("accounts.txt", "r") as fileObjc:
lines = fileObjc.readlines()
for index, item in enumerate(lines):
data = item.split()
if data[0] == account.cardNumber:
data[2] = str(account.balance) + "\n"
lines[index] = " ".join(data)
break
newFileLines = lines
with open("accounts.txt", "w") as fileObjc:
for each in newFileLines:
fileObjc.write(each)
def checkBalance(account):
print("Your account has $" + str(account.balance))
print()
mainMenu(account)
def deposit(account):
print("Enter the amount for deposit!")
try:
amount = int(input("- "))
print()
account.addBalance(amount)
updateDatabase(account)
mainMenu(account)
except ValueError:
deposit(account)
def withdrawal(account):
print("Enter the amount for withdrawal!")
try:
amount = int(input("- "))
if account.balance - amount < 0:
print("The maximum you can withdraw is $" + str(abs(0-account.balance)))
withdrawal(account)
print()
account.subtractBalance(amount)
updateDatabase(account)
mainMenu(account)
except ValueError:
withdrawal(account)
def sendMoney(account):
print("Enter the amount for transfer")
try:
amount = int(input("- "))
if account.balance - amount < 0:
print("The maximum you can withdraw is $" + str(abs(0-account.balance)))
sendMoney(account)
print("\nEnter the card number of the recipient")
cardNumber = input("- ")
found = False
with open("accounts.txt") as fileObjc:
for each in fileObjc.readlines():
data = each.split()
if data[0] == cardNumber:
found = True
recipient = Account(cardNumber, int(data[2]))
recipient.addBalance(amount)
account.subtractBalance(amount)
updateDatabase(recipient)
updateDatabase(account)
print("Transfer success!\n")
mainMenu(account)
break
if found == False:
print("Recipient not found in the database!")
sendMoney(account)
except:
sendMoney(account)
def lottery(account):
print("Welcome to Lottery! Choose a ticket!")
print("1. $10: Maximum win is $1,000")
print("2. $20: Maximum win is $20,000")
print("3. $50: Maximum win is $100,000")
print("4. Main menu")
try:
answer = int(input("- "))
if answer == 1:
if account.balance - 10 < 0:
print("You don't have enough money to buy this ticket!")
mainMenu(account)
else:
account.subtractBalance(10)
randomNumber1 = random.randint(0,20)
randomNumber2 = random.randint(0,20)
if randomNumber1 == randomNumber2:
print("CONGRATS YOU WON $1,000")
account.addBalance(1000)
updateDatabase(account)
print()
mainMenu(account)
else:
print("Sorry you didn't win!")
updateDatabase(account)
print()
mainMenu(account)
elif answer == 2:
if account.balance - 20 < 0:
print("You don't have enough money to buy this ticket!")
mainMenu(account)
else:
account.subtractBalance(20)
randomNumber1 = random.randint(0,30)
randomNumber2 = random.randint(0,30)
if randomNumber1 == randomNumber2:
print("CONGRATS YOU WON $20,000")
account.addBalance(20000)
updateDatabase(account)
print()
mainMenu(account)
else:
print("Sorry you didn't win!")
updateDatabase(account)
print()
mainMenu(account)
elif answer == 3:
if account.balance - 50 < 0:
print("You don't have enough money to buy this ticket!")
mainMenu(account)
else:
account.subtractBalance(50)
randomNumber1 = random.randint(0,1)
randomNumber2 = random.randint(0,1)
if randomNumber1 == randomNumber2:
print("CONGRATS YOU WON $100,000")
account.addBalance(100000)
updateDatabase(account)
print()
mainMenu(account)
else:
print("Sorry you didn't win!")
updateDatabase(account)
print()
mainMenu(account)
elif answer == 4:
mainMenu(account)
except ValueError:
lottery(account)
welcome()
|
name = "marton zeisler"
print("Welcome " + name.title())
print(name.upper())
lang = " python "
print(lang.lstrip() + "!")
print(lang.strip() + "!")
# comment
print(str(3**2)+".")
|
def formatYou(first, last):
return (first + " " + last).title()
print(formatYou("marton", "zeisler"))
def squareList(list):
del list[0]
list = [each**2 for each in list]
return list
myList = [1,2,3,4,5]
myList = squareList(myList[:]) # passing list by
print(myList)
|
# user input and while loop
age = int(input("Enter your name: "))
if age >= 18:
print("You can drink")
else:
print("You cannot drink")
while True:
age += 1
print("You're " + str(age))
if age < 18:
print("You still can't drink buddy")
else:
print("yay go get drunk quick")
break |
#nonlocal,global关键字
def outer():
b=10
def inner():
nonlocal b #申明外部函数的局部变量
print("inner b:",b)
b=20
global a #申明全局变量
a=1000
inner()
print("outer b:",b)
outer()
print("outer b:",a)
|
#测试选择结构的嵌套
score = int(input("请输入一个在0-100之间的数字:"))
grade = ""
if score>100 or score<0:
score = int(input("输入有误!请重新输入一个在0-100之间的数字"))
else:
if score >= 90:
grade = "A"
elif score >=80:
grade ="B"
elif score>=70:
grade ="C"
elif score >=60:
grade = "D"
else:
grade ="E"
print("分数为{0},等级为{1}".format(score,grade))
print("**********************************************")
score = int(input("请输入一个在 0-100 之间的数字: "))
degree = "ABCDE"
num = 0
if score>100 or score<0:
score = int(input("输入错误! 请重新输入一个在 0-100 之间的数字: "))
else:
num = score // 10
if num<6:
num =5
print("分数是{0},等级是{1}".format(score,degree[9-num])) |
r1={"name":"高一","age":"18","salary":"3000","city":"北京"}
r2={"name":"高二","age":"19","salary":"4000","city":"上海"}
r3={"name":"高三","age":"20","salary":"5000","city":"广州"}
tb=[r1,r2,r3]
#获高小二的薪资
print(tb[1].get("salary"))
#获取表中所有人的薪资
for i in range(len(tb)):#i--->0 1 2
print(tb[i].get("salary"))
#打印所有的数据
for i in range(len(tb)):
print(tb[i].get("name"),tb[i].get("age"),tb[i].get("salary"),tb[i].get("city"))
|
#测试for循环
for x in (20,30,40):
print (x*3)
for y in "abcdef":
print(y)
#遍历字典
d={"name":"SKY","age":"18","address":"陕西西安"}
for x in d:
print (x)
for x in d.keys():
print(x)
for x in d.values():
print(x)
for x in d.items():
print(x)
#range对象
for i in range(10):
print (i)
for j in range(3,10,2):
print (j)
|
class ShortException(Exception):
def __init__(self, word, length):
Exception.__init__(self)
self.word = word
self.length = length
try:
text = input('Введите что нибудь:')
if len(text) < 3:
raise ShortException(len(text), 3)
except EOFError:
print('EOF')
except ShortException as ex:
print('ShortException: длина строки {0}; \
ожидалось минимум {1}'.format(ex.word, ex.length))
else:
print('не было исключений')
|
zoo = ('питон', 'слон', 'пингвин')
print('Количество животных в зоопарке:', len(zoo))
new_zoo = ('обезьяна', 'крокодил', zoo)
print('количество клеток в зоопаре:', len(new_zoo))
print('все животные в новом зоопарке:', new_zoo)
print('животные привезенные из старого зоопарка:', new_zoo[2])
print('последнее животное привезённое из старого зоопарка:', new_zoo[2][2])
print('количество животных в новом зоопарке', len(new_zoo)-1 + len(new_zoo[2]))
|
#this program says hello and asks for my name and age and my age in 5 years time
#intro
print('Hello Dude!')
#asks my name
print('What is your name?')
myName = input()
print('Nice to meet you, ' + myName)
print('The length of your name is: ')
print(len(myName))
#asks my age
print('what is your age?')
myAge = input()
print('you are '+ myAge + '!')
print('you will be ' + (str(int(myAge) + 5)) + ' in 5 years.') |
########## CALCULATOR ###########
print("######CALCULATOR######")
##operators = ['+', '-', '/', '*', '**', '%']
# Create a list of functions you want to use for your calculator
def add_(x,y):
return(x+y)
def sub_(x,y):
return(x-y)
def mult_(x,y):
return(x*y)
def div_(x,y):
return(x/y)
def pow_(x,y):
return(x**y)
def flo_(x,y):
return(x//y)
#We create a dictionary relating the operation to each function
# add_ points to where the function is that you can call later
# for example: If we type Love = add_
# we can then do Love(3,4)
# which returns 7
operator_dic = {'+':add_, '-':sub_, '/':div_, '*':mult_, '**':pow_, '%':flo_}
while True:
# inputs & invalids
##num1 = input("-number1: ")
num1 = input("What's your operation!")
try:
num1 = num1.replace(" ","") #We remove all spaces in the string
# Strings are immutible lists btw
x = int(num1[0]) # we presume the form x + y where the first string entry is a number
operator = num1[1:-1] # since the operator can be of any size either * or **,
# we try to collect the entire operator
y = int(num1[-1]) # we select for the last number in the list
(operator in operator_dic) == True # always nice to test if the operator exists
except:
print("Invalid input! must be in the form of (x * y)")
continue
#operator_dic[operator] returns the function
#once we have the function, we apply the arguments that then return a values
result = operator_dic[operator](x,y)
#we return the printed result
print("\nYour result is: \n", str( result), "\n")
'''
if num1 == 'q':
break
try:
int(num1)
except:
print("Invalid Input, Try Again1")
print("####################1")
continue
operator = input("operator: ")
if operator == 'q':
break
if operator not in operators:
print("Invalid Input, Try Again2")
print("####################2")
continue
num2 = input("-number2: ")
if num2 == 'q':
break
try:
int(num2)
except:
print("Invalid Input, Try Again3")
print("####################3")
continue
# operators
if operator == '+':
plus = float(num1) + float(num2)
result = "Result: " + str(plus)
elif operator == '-':
subtract = float(num1) - float(num2)
result = "Result: " - str(subtract)
elif operator == '/':
divide = float(num1) / float(num2)
result = "Result: " + str(divide)
elif operator == '*':
times = float(num1) * float(num2)
result = "Result: " + str(times)
elif operator == '**':
power = float(num1) ** float(num2)
result = "Result: " + str(power)
else:
print("--" + result)
print("####################")
continue
# results
print("--" + result)
print("####################")
# prints this out, when out of the while loop
print("################################")
print("# You have quit the Calculator #")
print("################################")
''' |
# Priority (Non-Pre-emptive) CPU SCheduling algorithm
# for processes with same arrival time (Arrival Time = 0).
def waitingTime(process, wt):
n=len(process)
wt[0]=0
for i in range(1, n):
wt[i]=process[i-1][2]+wt[i-1]
def turnAroundtime(process, wt, tat):
for i in range(len(process)):
tat[i]=process[i][2]+wt[i]
def avgTime(process):
n=len(process)
wt=[0]*n
tat=[0]*n
total_wt=0
total_tat=0
waitingTime(process, wt)
turnAroundtime(process, wt, tat)
for i in range(n):
total_wt=total_wt+wt[i]
for i in range(n):
total_tat=total_tat+tat[i]
avg_wt=total_wt/n
avg_tat=total_tat/n
display(process, wt, tat, avg_wt, avg_tat)
def findOrder(process):
process.sort(key= lambda process:process[3])
return process
def display(process, wt, tat, avg_wt, avg_tat):
print('Process\t Arrival Time\t Burst Time\t Priority\t Waiting Time\t Turn Around Time')
for i in range(len(process)):
print('{}\t {}\t\t {}\t\t {}\t\t {}'.format(process[i][0], process[i][1], process[i][2], process[i][3], wt[i], tat[i]))
print('\nAverage Waiting Time: ', avg_wt)
print('Average Turn Around: ', avg_tat)
def main():
'''
process=input('Enter the process: ')
process=process.split()
'''
process=[[1, 0, 3, 4], [2, 0, 4, 2], [3, 0, 5, 3], [4, 0, 1, 1], [5, 0, 2, 5]]
'''
at=input('Enter Arrival Time of the respective process: ')
at=at.split()
bt=input('Enter Burst Time of the respective process: ')
bt=bt.split()
'''
process=findOrder(process)
avgTime(process)
if __name__=='__main__':
main()
|
"""
Metacharacters are what make regular expressions more powerful than normal string methods.
They allow you to create regular expressions to represent concepts like "one or more repetitions of a vowel".
The existence of metacharacters poses a problem if you want to create a regular expression (or regex) that matches a
literal metacharacter, such as "$". You can do this by escaping the metacharacters by putting a backslash in front of them.
However, this can cause problems, since backslashes also have an escaping function in normal Python strings.
This can mean putting three or four backslashes in a row to do all the escaping.
To avoid this, you can use a raw string, which is a normal string with an "r" in front of it.
We saw usage of raw strings in the previous lesson.
The first metacharacter we will look at is . (dot).
This matches any character, other than a new line.
"""
# 1
import re
pattern = r"gr.y"
if re.match(pattern, "grey"):
print("Match 1") # Match 1
if re.match(pattern, "gray"):
print("Match 2") # Match 2
if re.match(pattern, "blue"):
print("Match 3")
"""
The next two metacharacters are ^ and $.
These match the start and end of a string, respectively.
"""
# 1
import re
pattern = r"^gr.y$"
if re.match(pattern, "grey"):
print("Match 1") # Match 1
if re.match(pattern, "gray"):
print("Match 2") # Match 2
if re.match(pattern, "stingray"):
print("Match 3")
"""
The pattern "^gr.y$" means that the string should start with gr,
then follow with any character, except a newline, and end with y.
"""
"""
Some more metacharacters are *, +, ?, { and }.
These specify numbers of repetitions.
The metacharacter * means "zero or more repetitions of the previous thing".
It tries to match as many repetitions as possible. The "previous thing" can be a single character, a class,
or a group of characters in parentheses.
"""
# 2
import re
pattern = r"egg(spam)*"
if re.match(pattern, "egg"):
print("Match 1") # Match 1
if re. match(pattern, "eggspamspamegg"):
print("Match 2") # Match 2
if re.match(pattern, "spam"):
print("Match 3")
# The example above matches strings that start with "egg" and follow with zero or more "spam"s.
"""
The metacharacter + is very similar to *, except it means "one or more repetitions", as opposed to
"zero or more repetitions".
"""
# 2.1
import re
pattern = r"g+"
if re.match(pattern, "g"):
print("Match 1") # Match 1
if re.match(pattern, "ggggggggggggg"):
print("Match 2") # Match 2
if re.match(pattern, "abc"):
print("Match 3")
"""
To summarize:
* matches 0 or more occurrences of the preceding expression.
+ matches 1 or more occurrence of the preceding expression.
"""
# The metacharacter ? means "zero or one repetitions".
# 2.2
import re
pattern = r"ice(-)?cream"
if re.match(pattern, "ice-cream"):
print("Match 1") # Match 1
if re.match(pattern, "icecream"):
print("Match 2") # Match 2
if re.match(pattern, "sausages"):
print("Match 3")
if re.match(pattern, "ice-ice"):
print("Match 4")
"""
Curly braces can be used to represent the number of repetitions between two numbers.
The regex {x,y} means "between x and y repetitions of something".
Hence {0,1} is the same thing as ?.
If the first number is missing, it is taken to be zero. If the second number is missing, it is taken to be infinity.
"""
# 3
import re
pattern = r"9{1,3}$"
if re.match(pattern, "9"):
print("Match 1") # Match 1
if re.match(pattern, "9999"):
print("Match 2")
if re.match(pattern, "999"):
print("Match 3") # Match 3
# "9{1,3}$" matches string that have 1 to 3 nines.
|
The module itertools is a standard library that contains several functions that are useful in functional programming.
One type of function it produces is infinite iterators.
The function count counts up infinitely from a value.
The function cycle infinitely iterates through an iterable (for instance a list or string).
The function repeat repeats an object, either infinitely or a specific number of times.
from itertools import count
#1 count
for i in count(3):
print(i) # 3 4 5 6 7
if i >= 7:
break
#1.1 count
for i in count(3):
print(i) # 3
if i >= 1:
break
#2 cycle
from itertools import cycle
for i in cycle("5"):
print(i) # 5
break # without break it will be infinite
#3 repeat
from itertools import repeat
for i in repeat("5"):
print(i) # 5
break # without break it will be infinite
#4
There are many functions in itertools that operate on iterables, in a similar way to map and filter.
#4.1
accumulate - returns a running total of values in an iterable.
from itertools import accumulate
nums = list(accumulate(range(5)))
print(nums) # [0, 1, 3, 6, 10]
nums = list(accumulate(range(9)))
print(nums) # [0, 1, 3, 6, 10, 15, 21, 28, 36]
#4.2
takewhile - takes items from an iterable while a predicate function remains true.
from itertools import takewhile, accumulate
nums = list(accumulate(range(9)))
print(list(takewhile(lambda x: x <= 13, nums))) # [0, 1, 3, 6, 10]
from itertools import takewhile
nums = [2, 4, 3, 6, 7, 9, 8, 6, 4]
a = takewhile(lambda x: x % 2 == 0, nums)
print(list(a)) # [2, 4]
#4.3
chain - combines several iterables into one long one.
from itertools import chain
numbers = list(range(5))
cmd = ['ls', '/some/dir']
my_list = list(chain(['foo', 'bar'], cmd, numbers))
print(my_list) # ['foo', 'bar', 'ls', '/some/dir', 0, 1, 2, 3, 4]
#5 product, permutations
There are also several combinatoric functions in itertool, such as product and permutation.
These are used when you want to accomplish a task with all possible combinations of some items.
#5.1
from itertools import product, permutations
letters = ("A", "B")
print(list(product(letters, range(2)))) # [('A', 0), ('A', 1), ('B', 0), ('B', 1)]
print(list(permutations(letters))) # [('A', 'B'), ('B', 'A')]
#5.2
from itertools import product
a = {1, 2}
print(list(product(range(3), a))) # [(0, 1), (0, 2), (1, 1), (1, 2), (2, 1), (2, 2)]
print(len(list(product(range(3), a)))) # 6
|
#1 To find the maximum or minimum of some numbers or a list, you can use max or min.
print(min(0, -2, 3, 15,78)) # -2
print(max(0, -2, 3, 15,78)) # 78
#2 To find the distance of a number from zero (its absolute value), use abs.
print(abs(0, -2, 3, 15,78)) # TypeError: abs() takes exactly one argument (5 given)
print(abs(2)) # 2
print(abs(-2)) # 2
#3 To round a number to a certain number of decimal places, use round.
print(round(2.8)) # 3
print(round(2.2)) # 2
print(round(2.5)) # 2
print(round(2.500000000000001)) # 3 (13 zeroes) ?????
print(round(2.5000000000000001)) # 2 (14 zeroes) ?????
#4 To find the total of a list, use sum.
print(sum(1, 2, 3, 4, 5)) # TypeError: sum() takes at most 2 arguments (5 given)
print(sum([1, 2, 3, 4, 5])) # 15
print(sum([1, 2, 3, 4, 5] + [1, 2])) # 18
print(sum([1, 2, 3, 4, 5] + 1)) # TypeError: can only concatenate list (not "int") to list
|
# 1
temperature = 21
if temperature > 21:
print("It's a warm day") # False
elif temperature < 21:
print("It's a cold day") # False
else:
print("It's a lovely day") # Will print -> It's a lovely day
#2
price = 1000000
salary = 120000
if price / salary > 8:
print("We can give you credit in 10% per year") # True -> We can give you credit in 10% per year
elif price / salary < 8:
print("We can give you credit in 20% per year")
else:
print("We can give you credit in 15% per year")
#3
price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print(f"Down payment: ${down_payment}") # Down payment: $100000.0
|
#1 append()
numbers = [5, 2, 1, 7, 4]
numbers.append(13)
print(numbers) # [5, 2, 1, 7, 4, 13]
#2 insert()
numbers = [5, 2, 1, 7, 4]
numbers.insert(2, 10)
print(numbers) # [5, 2, 10, 1, 7, 4]
# remove()
numbers = [5, 2, 1, 7, 4]
numbers.remove(5)
print(numbers) # [2, 1, 7, 4]
# clear()
numbers = [5, 2, 1, 7, 4]
numbers.clear()
print(numbers) # []
# pop()
numbers = [5, 2, 1, 7, 4]
numbers.pop()
print(numbers) # [5, 2, 1, 7]
# index()
numbers = [5, 2, 1, 7, 4]
print(numbers.index(7)) # 3
# count()
numbers = [5, 2, 1, 7, 4]
print(numbers.count(5)) # 1
# sort()
numbers = [5, 2, 1, 7, 4]
numbers.sort()
print(numbers) # [1, 2, 4, 5, 7]
# reverse()
numbers = [5, 2, 1, 7, 4]
numbers.reverse()
print(numbers) # [4, 7, 1, 2, 5]
# copy()
numbers = [5, 2, 1, 7, 4]
numbers2 = numbers.copy()
numbers.append(15)
print(numbers2) # [5, 2, 1, 7, 4]
print(numbers) # [5, 2, 1, 7, 4, 15]
|
#1
customer = {
"name": "Hayk Ekizyan",
"age": 30,
"is_verified": True
}
print(customer["name"]) # Hayk Ekizyan
print(customer.get("name")) # Hayk Ekizyan
customer["birthdate"] = "Dec 7 1989"
print(customer["birthdate"]) # Dec 7 1989
#2 When the key does not exist
primary = {
"red": [255, 0, 0],
"green": [0, 255, 0],
"blue": [0, 0, 255]
}
print(primary.get("red")) # [255, 0, 0]
print(primary["yellow"]) # KeyError: 'yellow'
#2.1
test = { }
print(test[0]) # KeyError: 0
#2.3 Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can't be changed.
bad_dict = {
[1, 2, 3]: "one two three"
}
print(bad_dict[[1, 2, 3]]) # TypeError: unhashable type: 'list'
#3 We can change values
squares = {
1: 1,
2: 4,
3: "error",
4: 16
}
squares[8] = 64
squares[3] = 9
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 8: 64}
#4 To determine whether a key is in a dictionary...
nums = {
1: "one",
2: "two",
3: "three"
}
print(1 in nums)
print("three" in nums)
print(4 not in nums)
"""
True
False
True
"""
#5 "get" method. if the key is not found in the dictionary it returns another specified value instead...
pairs = {
1: "apple",
"orange": [2, 3, 4],
True: False,
None: "True"
}
print(pairs.get("orange"))
print(pairs.get(7))
print(pairs.get(12345, "not in dictionary"))
print(pairs.get(1 in pairs))
"""
[2, 3, 4]
None
not in dictionary
False
"""
|
from random import sample
def dfs_generator(self, v:int, visited:list, road_used:list, parent:int):
'''
Recursive Randomized Depth First Search Algorithm with Backtracking
Parameters:
self (Maze): maze class
v (int): current vertex
visited (list): list of visited vertices
road_used (list): history of previous path for backtracking
parent (int): parent of current vertex
'''
# Check if there are still vertices to visit
c = 0
for i in range(self.total):
if visited[i]:
c += 1
if c == self.total:
return
# Add edge to graph representation of maze
if parent != -1 and not visited[v]:
self.maze.add_edge(parent, v)
# Mark vertex as visited
if not visited[v]:
visited[v] = True
# Turtle draws toward current vertex
self.turtle.goto(((v % self.rows) - 0.5 * self.rows) * self.scale,
((v // self.rows) - 0.5 * self.columns) * self.scale)
# Track the current edge
road_used.append([parent, v])
# Choose random available path
for x in sample(self.graph.graph[v], len(self.graph.graph[v])):
if not visited[x]:
dfs_generator(self, x, visited, road_used, v)
# Backtrack through the last visited vertices
for y in road_used:
if y[1] == v:
dfs_generator(self, y[0], visited, road_used, v)
def it_dfs_generator(self, s):
'''
Iterative Randomized Depth First Search Algorithm with Backtracking
Parameters:
self (Maze): maze class
s (int): starting vertex
'''
visited = [False] * self.total
road_used = []
parent = -1
stack = [s]
c = 0
# While there are still vertices to visit
while len(stack) and c < self.total:
# Pop a vertex from stack
v = stack[-1]
stack.pop()
# Turtle draws toward current vertex
self.turtle.goto(((v % self.rows) - 0.5 * self.rows) * self.scale,
((v // self.rows) - 0.5 * self.columns) * self.scale)
# Add edge to graph representation of maze
if parent != -1 and not visited[v]:
self.maze.add_edge(parent, v)
if not visited[v]:
visited[v] = True
c += 1
# Track the current edge
road_used.append([parent, v])
parent = v
# Choose random available path
any_adj = 0
for w in sample(self.graph.graph[v], len(self.graph.graph[v])):
if not visited[w]:
any_adj += 1
stack.append(w)
break
# Backtrack through the last visited vertices
if any_adj == 0:
for y in road_used:
if y[1] == v:
stack.append(y[0])
break
|
#!/usr/bin/env python3
import sys
try:
from math import gcd
except Exception:
from fractions import gcd
YES = "Yes" # type: str
NO = "No" # type: str
def solve(N: int):
return NO if bool(N % (sum([int(v) for v in str(N)]))) else YES
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
result = solve(N)
print(result)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
def merge_sort( data ):
l = len( data )
if l <= 1:
return data
left_data = merge_sort( data[:(l//2)] )
right_data = merge_sort( data[(l//2):] )
res = []
li = 0
ri = 0
while left_data[li:] and right_data[ri:]:
if left_data[ li ] <= right_data[ ri ]:
res.append( left_data[ li ] )
li += 1
else:
res.append( right_data[ ri ] )
ri += 1
res += left_data[li:]
res += right_data[ri:]
return res
def main():
org_data = [ random.randint( 0, 10000 ) for i in range( 20 ) ]
print( org_data )
res_data = merge_sort( org_data )
print( res_data )
return
if __name__ == '__main__':
main()
|
import os, sys, re, math
class StreetParking:
# int freeParks(String street)
def freeParks(self, street):
ok = 0
for i in range( len( street ) ):
if 'B' in street[ i : min( i + 3, len( street ) ) ]:
continue
if 'D' == street[i]:
continue
if 'S' in street[ max( i - 1 , 0 ) : min( i + 2, len( street ) ) ]:
continue
ok += 1
return ok
# BEGIN CUT HERE
def eq(n, have, need):
if isinstance(have, list) and isinstance(need, list):
if len(have) != len(need):
sys.stdout.write("Test Case #%d...FAILED: returned %d elements; expected %d elements." % (n, len(have), len(need)))
printerror(have, need)
else:
for i in range(0, len(have)):
if not eqval(have[i], need[i]):
sys.stdout.write("Test Case #%d...FAILED: Expected and returned array differ in position %d.\n" % (n, i))
printerror(have, need)
return
sys.stdout.write("Test Case #%d...PASSED\n" % n)
else:
if eqval(have, need):
sys.stdout.write("Test Case #%d...PASSED\n" % n)
else:
sys.stdout.write("Test Case #%d...FAILED\n" % n)
printerror(have, need)
def printerror(have, need):
sys.stdout.write("\tExpected: " + printval(need) + "\n")
sys.stdout.write("\tRecieved: " + printval(have) + "\n")
def printval(a):
if isinstance(a, str):
return '"' + a + '"'
elif isinstance(a, long):
return str(a) + 'L'
else:
return str(a)
def eqval(a, b):
if isinstance(a, float) or isinstance(b, float):
return (abs(a - b) < 1e-9 or (abs(a) >= 1 and abs((a - b) / a) < 1e-9))
else:
return (a != None and b != None and a == b)
if __name__ == "__main__":
eq(0, StreetParking().freeParks("---B--S-D--S--"), 4)
eq(1, StreetParking().freeParks("DDBDDBDDBDD"), 0)
eq(2, StreetParking().freeParks("--S--S--S--S--"), 2)
eq(3, StreetParking().freeParks("SSD-B---BD-DDSB-----S-S--------S-B----BSB-S--B-S-D"), 14)
# END CUT HERE
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
import sys
def heap_sort( data ):
length = len( data )
heap = []
for d in data:
heap.append( d )
l = len( heap ) - 1
while True:
if l == 0:
break
parent = ( l - 1 ) // 2
if heap[ l ] < heap[ parent ] :
tmp = heap[ l ]
heap[ l ] = heap[ parent ]
heap[ parent ] = tmp
l = parent
for i in range( length ):
v = heap[ 0 ]
data[ i ] = v
l = 0
heap[ l ] = sys.maxsize
while l <= length / 2:
child1 = min( length - 1, l * 2 + 1 )
child2 = min( length - 1, l * 2 + 2 )
child = ( ( heap[ child1 ] < heap[ child2 ] ) and child1 ) or child2
tmp = heap[ child ]
heap[ child ] = heap[ l ]
heap[ l ] = tmp
l = child
def main():
org_data = [ random.randint( 0, 10000 ) for i in range( 20 ) ]
print( org_data )
heap_sort( org_data )
print( org_data )
return
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import sys
from math import *
from itertools import *
from collections import *
from functools import *
try:
from math import gcd
except Exception:
from fractions import gcd
def solve(x: "List[int]", y: "List[int]"):
d = (x[1] - x[0], y[1] - y[0])
x2 = x[1] - d[1]
y2 = y[1] + d[0]
x3 = x[0] - d[1]
y4 = y[0] + d[0]
return ' '.join([str(z) for z in [x2, y2, x3, y4]])
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
x = [int()] * (2) # type: "List[int]"
y = [int()] * (2) # type: "List[int]"
for i in range(2):
x[i] = int(next(tokens))
y[i] = int(next(tokens))
result = solve(x, y)
print(result)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import collections
import heapq
import sys
def find_dijkstra( g, src ):
min_cost = {}
node_heap = []
heapq.heapify( node_heap )
heapq.heappush( node_heap, ( 0, src ) )
while node_heap:
cost,node = heapq.heappop( node_heap )
if node in min_cost:
continue
min_cost[ node ] = cost
for neighbor,w in zip( g[ node ].keys(), g[ node ].values() ):
neighbor_cost = min_cost[ node ] + w
heapq.heappush( node_heap, ( neighbor_cost, neighbor ) )
return min_cost
pass
def main():
g = collections.defaultdict( dict )
g[ 0 ][ 1 ] = 1
g[ 1 ][ 3 ] = 1
g[ 3 ][ 4 ] = 1
g[ 0 ][ 2 ] = 4
g[ 2 ][ 4 ] = 5
res = find_dijkstra( g, 0 )
return
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import itertools
def is_prime( vv ):
i = 2;
while i * i <= vv:
if vv % i == 0:
return False
i += 1
return True
def main():
max_prime = 0
for i in range( 9, 0, -1 ):
for v in itertools.permutations( '123456789'[:i], i ):
vv = int( ''.join( v ) )
if is_prime( vv ) and max_prime < vv:
max_prime = vv
print( max_prime )
return
if __name__ == '__main__':
main()
|
class Node:
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self._head = None
self.count = 0
def insert(self, value, index=None):
if self._head is None:
self._head = Node(value, None)
else:
index = (self.count - 1) if index is None else index
cur = self._get(index)
new = Node(value, cur.next)
cur.next = new
self.count += 1
def delete(self, value):
cur = self._head
if cur.value == value:
self._head = cur.next
else:
while cur.next is not None:
if cur.next.value == value:
break
cur = cur.next
cur.next = cur.next.next
self.count -= 1
def get(self, index):
return self._get(index).value
def _get(self, index):
if self.count <= index or index < 0:
raise ValueError('given illegal index')
cur_index = 0
cur = self._head
while (cur_index != index):
cur = cur.next
cur_index += 1
return cur
if __name__ == '__main__':
l = LinkedList()
assert l.count == 0
l.insert(10)
l.insert(11)
l.insert(9)
assert l.count == 3
assert l.get(0) == 10
assert l.get(1) == 11
assert l.get(2) == 9
l.delete(11)
assert l.count == 2
assert l.get(0) == 10
assert l.get(1) == 9
l.delete(10)
assert l.count == 1
assert l.get(0) == 9
try:
l.get(1)
except ValueError as e:
assert str(e) == 'given illegal index'
try:
l.get(-1)
except ValueError as e:
assert str(e) == 'given illegal index'
l.delete(9)
assert l.count == 0
try:
l.get(0)
except ValueError as e:
assert str(e) == 'given illegal index'
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def binary_search( values, target ):
left = 0
right = len( values )
while left < right:
mid = ( left + right ) // 2
if target == values[ mid ]:
return True
elif values[ mid ] < target:
left = mid + 1
else:
right = mid
return False
def main():
data = sorted( [ 23, 43, 1, 33, 8 ] )
print( binary_search( data, 43) )
return
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import math
import random
def isPrime( q, k=50 ):
q = abs( q )
if q == 2:
return True
if q < 2 or q & 1 == 0 :
return False
d = ( q - 1 ) >> 1
while d & 1 == 0:
d >>= 1
ass = [ x for x in [ 2, 7, 61] if x < q ]
for a in ass:
#a = random.randint( 1, q -1 )
t = d
y = pow( a, t, q )
while t != q - 1 and y != 1 and y != q - 1:
y = pow( y, 2, q )
t <<= 1
if y != q - 1 and t & 1 == 0 :
return False
return True
def isEven( n ):
return map(lambda x: ( int(x) & 1 ) == 0 , list( str( n ) ) ).count( True ) == 0
if __name__=='__main__':
primes = [2]
for n in xrange(3, 1000000, 2):
if isEven( n ):
if isPrime( n ):
primes.append( n )
count = 0
for n in primes:
list_n = list( str(n) )
try:
for i in range( len( list_n ) ) :
if( not ( int( ''.join( list_n ) ) in primes ) ):
raise
list_n.append( list_n.pop( 0 ) )
count += 1
except:
continue
print count
|
#!/usr/bin/env python
# -*- cofing:utf-8 -*-
import math
def fibo( n ):
golden_ratio = ( 1 + math.sqrt( 5 ) ) / 2
return int( math.floor( math.pow( golden_ratio , n ) / math.sqrt( 5 ) + 0.5 ) )
def digits( n ):
return len( str( n ) )
def main():
val0 = fibo( 1100 )
val1 = fibo( 1101 )
index = 1101
while( digits( val1 ) < 1000 ):
tmp = val1
val1 = val1 + val0
val0 = tmp
index += 1
print index
if __name__ == "__main__":
main();
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from .money import Money
class Bank:
def __init__(self):
self.rates = {}
def reduce(self, source, to):
return source.reduce(self, to)
def addRate(self, original, to, rate):
self.rates[(original, to)] = rate
def rate(self, original, to):
if original == to:
return 1
return self.rates[(original, to)]
|
import timeit
print('#'*67)
print(""" Fibonacci programına hoşgeldiniz!
| Aşağıda yapmak istediğiniz işlemin numarasını giriniz. |
| Yazdığınız sayıya kadar olan fibonacci sonuçları = 1 |
| Belirli bir adımdaki fibonacci sayısı = 2 |
| Yazdığınız sayıya kadar geçen işlemci süresi = 3 |
| Belirli adımdaki fibonacci sayısında geçen işlemci süresi = 4|
| İteratif kod için "1" , Özyinelemeli kod için "2" |
| yanına ekleyiniz . ( "11" ya da "22" gibi) |
| Fibonacci tarihçesi için yukarıdaki sayılar dışında bir şey |""")
print('#'*67)
istemci = int(input('İşlem numarasını giriniz : '))
def fr(m):
if ( m == 0 ):
return 0
elif( m == 1 ):
return 1
else:
return fr(m-1) + fr(m-2)
def fi(n):
a , b = 0, 1
for i in range(0, n):
a , b = b, a + b
return a
if ( istemci == 11):
k = int(input('Kaçıncı adıma kadar ? :'))
a = []
for i in range(0,k):
a += [fi(i)]
print(a)
elif( istemci == 12):
k = int(input('Kaçıncı adıma kadar ? :'))
a = []
for i in range(0, k):
a += [fr(i)]
print(a)
elif (istemci == 21):
p = int(input('Hangi adım ? :'))
print(fi(p))
elif (istemci == 22):
p = int(input('Hangi adım ? :'))
print(fr(p))
elif (istemci == 31):
k = int(input('Kaçıncı adıma kadar ? :'))
a = []
for i in range(0, k):
a += [fi(i)]
print(a)
print('Geçen süre : {}'.format(timeit.timeit()))
elif (istemci == 32):
k = int(input('Kaçıncı adıma kadar ? :'))
a = []
for i in range(0, k):
a += [fr(i)]
print(a)
print('Geçen süre : {}'.format(timeit.timeit()))
elif (istemci == 41):
p = int(input('Hangi adım ? :'))
fi(p)
print('İşlem süresi : {} '.format(timeit.timeit()))
elif (istemci == 42):
p = int(input('Hangi adım ? :'))
fr(p)
print('İşlem süresi : {} '.format(timeit.timeit()))
else:
print("""Fibonacci (diğer bilinen adlarıyla Leonardo Bonacci, Pisalı Leonardo, Leonardo Bigollo Pisano d. 1170, ö. 1250), orta çağın en yetenekli Batılı matematikçisi olarak kabul edilen İtalyan matematikçi.
Leonardo 1170 yılında İtalya'nın Pisa şehrinde doğdu.Fibonacci Hint-Arap sayıları ile aritmetik işlemler yapmanın Roma rakamları ile hesap yapmaktan çok daha basit ve verimli olduğunu gördü. Leonardo bütün Akdeniz bölgesini gezdi ve dönemin önde gelen Arap matematikçiler ile çalışma olanağı buldu. Leonardo yaklaşık olarak 1200 yıllarında bu seyahatinden döndü. 1202 yılına gelindiğinde 32 yaşında, öğrendiklerini "abaküs kitabı" veya "hesaplama kitabı" anlamına gelen Liber Abaci isimli eserinde topladı.
Yayınladığı bu eserinde Hint-Arap Sayı Sistemi'ni Avrupa'ya duyurdu.
Kaynak:https://tr.wikipedia.org/wiki/Leonardo_Fibonacci """)
|
while True:
num = float(input("Enter a number: "))
if num.is_integer():
if num % 2 == 0:
print("Even")
else:
print("Odd")
for x in range(0,21,2):
print(x+int(num),end=' ')
break
else:
print("Number is not a whole number ")
|
import matplotlib.pyplot as plt
def draw_graph(x, y):
plt.plot(x, y, marker='x')
plt.xlabel("Distance in metres")
plt.ylabel("Force in Newton")
plt.title("Plot of gravitational force against distance")
plt.show()
def gen_fr(m1 = 1000, m2 = 1000):
r = list(range(100, 1001, 50))
F = []
for x in r:
F.append((6.674*(10**-11)) * m1 * m2 / x**2)
draw_graph(r, F)
if __name__ == '__main__':
gen_fr() |
import sympy
print("McLaurin expansion of sin(x)")
x = sympy.Symbol('x')
def series(x):
val = int(input("Enter number of terms: "))
series = x
for i in range(1, val + 1):
if i % 2 == 1:
series -= x ** (i*2 + 1)/ sympy.factorial(i*2 + 1)
else:
series += x ** (i * 2 + 1) / sympy.factorial(i * 2 + 1)
sympy.pprint(series, order='rev-lex')
graph = sympy.plot(series, title="graph of sin(x) using the first 50 terms of the McLaurin Series")
graph.save('mclaurin-series-sin_x.png')
#graph.show()
if __name__ == '__main__':
series(x)
|
import argparse
from cv2_tools.Management import ManagerCV2
from cv2_tools.Selection import SelectorCV2
import cv2
'''
Check first ManagerCV2 examples, here I assume that you know how it works.
'''
vertex = []
def mouse_drawing(event, x, y, flags, params):
global vertex
if event == cv2.EVENT_LBUTTONDOWN:
vertex.append((x,y))
if event == cv2.EVENT_RBUTTONDOWN:
vertex = []
def simple_selector(video, stream, fps):
manager_cv2 = ManagerCV2(cv2.VideoCapture(video), is_stream=stream, fps_limit=fps)
manager_cv2.add_keystroke(27, 1, exit=True)
manager_cv2.add_keystroke(ord('c'), 1, 'close') # It will manage if we want to close the polygon or not
manager_cv2.add_keystroke(ord('b'), 1, 'box') # It will add or not the surrounding box
cv2.namedWindow("Polygon")
cv2.setMouseCallback("Polygon", mouse_drawing)
for frame in manager_cv2:
# The best way to make it works is creating the selection inside the loop
# You can specify lot of optional parameters like:
# alpha, color, polygon_color, normalized, thickness, filled, peephole, closed_polygon and show_vertexes
# Check documentation for more information of each one
selector = SelectorCV2(
color=(0,100,220), filled=True, thickness=3,
closed_polygon=manager_cv2.key_manager.close,
polygon_color=(170,25,130), show_vertexes=True
)
# We add the polygon specifying the vertexes (list of touples of two elements)
# Also optionaly, we decide to add a surrounding box to the polygon if we press the box key,
# and for this example we also add a tag, but this is not necessary
selector.add_polygon(vertex, surrounding_box=manager_cv2.key_manager.box, tags='This is the first\nPolygon')
# Finally when you execute the draw function it actually prints all the selections
# until now it didn't print anything, only store the data.
frame = selector.draw(frame)
cv2.imshow("Polygon", frame)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--video', default=0,
help='input video/stream (default 0, it is your main webcam)')
parser.add_argument('-s', '--stream',
help='if you pass it, it means that the video is an streaming',
action='store_true')
parser.add_argument('-f', '--fps', default=0,
help='int parameter to indicate the limit of FPS (default 0, it means no limit)',
type=int)
args = parser.parse_args()
if type(args.video) is str and args.video.isdigit():
args.video = int(args.video)
simple_selector(args.video, args.stream, args.fps)
|
# MIT License
# Copyright (c) 2019 Fernando Perez
import cv2
from cv2_tools.Utils import *
class SelectorCV2():
""" SelectorCV2 helps to select information in frames.
This is the original idea of the library, being capable to select multiple
zones with enough intelligence to decide how to show as much information as
possible without covering relevant data.
It has two important functionalities:
- add_zone: To draw a rectangle (with tags)
- add_polygon: To draw a polygon (if you add a zone to it, you can also add tags,
in next versions, we will be capable to add tags without a zone).
"""
def __init__(self, alpha=0.9, color=(110,70,45), polygon_color=(110,45,93), color_by_tag={}, normalized=False,
thickness=2, filled=False, peephole=True, margin=5, closed_polygon=False,
show_vertexes=False):
""" SelectorCV2 constructor.
Keyword arguments:
alpha -- transparency of the selected zone on the image (default 0.9)
1 means totally visible and 0 totally invisible
color -- color of the selected zones, touple with 3 elements BGR (default (110,70,45) -> dark blue)
BGR = Blue - Green - Red
polygon_color -- color of the polygons, same structure as color
color_by_tag -- dict from string to color (BGR). The string is the first tag of a selection.
So, if you want to draw a class with a color, you can easily do it. (default {})
normalized -- boolean parameter, if True, position provided normalized (between 0 and 1)
else you should provide concrete values (default False)
thickness -- thickness of the drawing in pixels (default 2)
filled -- boolean parameter, if True, it will draw a filled rectangle with one-third opacity compared to the rectangle (default False)
peephole -- boolean parameter, if True, it also draws additional effects, so it looks like a peephole
margin -- extra margin in pixels to be separeted with the selected zone (default 5)
closed_polygon -- boolean parameter, if True, when you pass a polygon, it will draw the polygon closing it (default False)
show_vertexes -- boolean parameter, if True, when you pass a polygon, it will draw small circles on each vertex (default False)
"""
self.zones = []
self.polygon_zones = []
self.all_tags = []
self.free_tags = []
# Visual parameters: It is going to be all the default values
self.alpha = alpha
self.color = color
self.polygon_color = polygon_color
self.color_by_tag = color_by_tag
self.normalized = normalized
self.thickness = thickness
self.filled = filled
self.peephole = peephole
self.margin = margin
self.show_vertexes = show_vertexes
# Polygon
self.closed_polygon = closed_polygon
# From index (polygon_zones) -> {
# 'alpha': alpha,
# 'color': color,
# 'filled': filled,
# 'peephole': peephole,
# }
self.specific_properties = {}
def set_properties(self, alpha=None, color=None, polygon_color=None, color_by_tag=None,
normalized=None, thickness=None, filled=None, peephole=None,
margin=None, closed_polygon=None, show_vertexes=None):
""" Set default properties.
Note: All parameters are setted to None, but this is because, this method
doesn't change an attribute if the parameter is None. So if you want to change
only one attribute, you don't need to pass the other ones.
Keyword arguments:
alpha -- transparency of the selected zone on the image (default None)
1 means totally visible and 0 totally invisible
color -- color of the selected zones, touple with 3 elements BGR (default None)
BGR = Blue - Green - Red
polygon_color -- color of the polygons, same structure as color
color_by_tag -- dict from string to color (BGR). The string is the first tag of a selection.
So, if you want to draw a class with a color, you can easily do it. (default {})
normalized -- boolean parameter, if True, position provided normalized (between 0 and 1) (default None)
else you should provide concrete values (default None)
thickness -- thickness of the drawing in pixels (default None)
filled -- boolean parameter, if True, it will draw a filled rectangle with one-third opacity compared to the rectangle (default None)
peephole -- boolean parameter, if True, it also draws additional effects, so it looks like a peephole (default None)
margin -- extra margin in pixels to be separeted with the selected zone (default None)
closed_polygon -- boolean parameter, if True, when you pass a polygon, it will draw the polygon closing it (default None)
"""
if alpha is not None:
self.alpha = alpha
if color is not None:
self.color = color
if polygon_color is not None:
self.polygon_color = polygon_color
if color_by_tag is not None:
self.color_by_tag = color_by_tag
if normalized is not None:
self.normalized = normalized
if thickness is not None:
self.thickness = thickness
if filled is not None:
self.filled = filled
if peephole is not None:
self.peephole = peephole
if margin is not None:
self.margin = margin
if closed_polygon is not None:
self.closed_polygon = closed_polygon
if show_vertexes is not None:
self.show_vertexes = show_vertexes
def add_zone(self, zone, tags=None, specific_properties={}):
""" Add a new zone.
Arguments:
zone -- tuple with 4 elements (x1, y1, x2, y2)
This elements should be between 0 and 1 in case it is normalized
or between 0 and frame height/width (it value not in the margins,
it will show a warning, unless you set the variable IGNORE_ERRORS
to True in Utils.py).
Keyword arguments:
tags -- Tags to attach to the selection (default None)
specific_properties -- Optional parameter. If you want to change specifically
how to draw the current zone, you can pass a dictionary with all the
attributes you want to change (from the previously setted as default).
specific_properties should follow the next structure (ignoring as much
keys as you want):
{
'alpha': value, (transparency of the selected zone on the image)
'color': value, (color of the selected zones, touple with 3 elements BGR)
'filled': value, (boolean parameter, if True, it will draw a filled rectangle with one-third opacity compared to the rectangle)
'peephole': value, (boolean parameter, if True, it also draws additional effects, so it looks like a peephole)
'thickness': value (int parameter, you can specify the thickness of the selection)
}
Note: You can't specify some attributes as: normalized or closed_polygon (we are considering add some of them)
"""
if not self.normalized:
zone = [int(x) for x in zone]
self.zones.append(zone)
if tags and type(tags) is not list:
tags = [tags]
elif not tags:
tags = []
self.all_tags.append(tags)
# Add specific_properties if there are someone
if specific_properties:
index = len(self.zones)-1
self.specific_properties[index] = {}
for attribute in ['alpha', 'color', 'filled', 'peephole', 'thickness']:
if attribute in specific_properties:
self.specific_properties[index][attribute] = specific_properties[attribute]
def add_polygon(self, polygon, surrounding_box=False, tags=None):
""" Add a new polygon.
Arguments:
polygon -- list of points. Each point is a touple (x1, y1)
This elements should be between 0 and 1 in case it is normalized
or between 0 and frame height/width (if value not in the margins,
and variable IGNORE_ERRORS in Utils.py was set to False, it will
show a warning.
Keyword arguments:
surrounding_box -- boolean parameter. If it is True, it will draw a
rectangle around the polygon
tags -- Tags to attach to the selection. (default None)
"""
if not polygon:
return
self.polygon_zones.append(polygon)
# If we don't have any tags and we don't want to add a surrounding box
# just skip all of this stuff (this will do our system faster)
if tags or surrounding_box:
min_x, min_y, max_x, max_y = polygon[0][0], polygon[0][1], 0, 0
for position in polygon:
if position[0] < min_x:
min_x = position[0]
if position[0] > max_x:
max_x = position[0]
if position[1] < min_y:
min_y = position[1]
if position[1] > max_y:
max_y = position[1]
self.zones.append((min_x, min_y, max_x, max_y))
if tags and type(tags) is not list:
tags = [tags]
elif not tags:
tags = []
self.all_tags.append(tags)
# We specify not to show the surrounding box
if not surrounding_box:
index = len(self.zones)-1
self.specific_properties[index] = {
'thickness':0
}
def add_free_tags(self, coordinates, tags, alpha=0.75, color=(20,20,20),
font=cv2.FONT_HERSHEY_COMPLEX_SMALL, font_scale=0.75,
font_color=(255,255,255), thickness=1, **kwargs):
""" Add tags not asociated with selections.
Arguments:
coordinates -- touple of two ints (x1,y1).
tags -- string or list of strings with all the tags to write.
It supports \n character.
Keyword Arguments:
alpha -- transparency of the tags background on the image (default 0.75)
1 means totally visible and 0 totally invisible
color -- color of the tags background, touple with 3 elements BGR (default (20,20,20) -> almost black)
BGR = Blue - Green - Red
font -- opencv font (default cv2.FONT_HARSHEY_COMPLEX_SMALL)
font_scale -- scale of the fontm between 0 and 1 (default 0.75)
font_color -- color of the tags text, touple with 3 elements BGR (default (255,255,255) -> white)
BGR = Blue - Green - Red
thickness -- thickness of the text in pixels (default 1)
kwargs -- We have added this field to avoid compatibility errors with previous
and future versions, but it is not really used,
we use it to ignore extra fields
"""
font_info = (font, font_scale, font_color, thickness)
if type(tags) == str:
tags = [tags]
self.free_tags.append({
'coordinates':coordinates,
'tags':tags,
'color':color,
'font_info':font_info,
'alpha':alpha
})
def set_range_valid_rectangles(self, origin, destination):
""" It is going to be proably a deprecated method """
self.zones = self.zones[origin:destination]
self.all_tags = self.all_tags[origin:destination]
def set_valid_rectangles(self, indexes):
""" It is going to be proably a deprecated method """
# This if is just for efficiency
if not indexes:
self.zones = []
self.all_tags = []
return
for i in range(len(self.zones)):
if i not in indexes:
self.zones.pop(i)
self.all_tags.pop(i)
def draw(self, frame, coordinates=(-1,-1), draw_tags=True, fx=1, fy=1, interpolation=cv2.INTER_LINEAR):
""" Draw all selections.
Arguments:
frame -- opencv frame object where you want to draw
Keyword arguments:
coordinates -- if indicated, the system will draw tags inside the selected
coordinates. If not passed, the system will draw all the
tags (default (-1,-1))
draw_tags -- boolean value, if false, the system won't draw any tag
(default True)
fx -- frame horizonal scale (default 1)
fy -- frame vertical scale (default 1)
interpolation -- cv2 default scaling algorithm (default cv2.INTER_LINEAR)
"""
if coordinates != (-1,-1):
all_tags = []
for zone, tags in zip(self.zones, self.all_tags):
# zone = (x1,y1,x2,y2)
if coordinates[0] >= zone[0] and coordinates[0] <= zone[2] and \
coordinates[1] >= zone[1] and coordinates[1] <= zone[3]:
all_tags.append(tags)
else:
all_tags.append([])
else:
all_tags = self.all_tags
# Step 1: Draw polygons
next_frame = select_polygon(
frame.copy(),
all_vertexes=self.polygon_zones,
color=self.polygon_color,
thickness=self.thickness,
closed=self.closed_polygon,
show_vertexes=self.show_vertexes
)
# Step 2: Draw selections
next_frame = select_multiple_zones(
next_frame,
self.zones,
all_tags=all_tags,
alpha=self.alpha,
color=self.color,
normalized=self.normalized,
thickness=self.thickness,
filled=self.filled,
peephole=self.peephole,
margin=self.margin,
color_by_tag=self.color_by_tag,
specific_properties=self.specific_properties)
# Step 3: Draw free tags
for free_tag in self.free_tags:
next_frame = draw_free_tag(
next_frame,
free_tag['coordinates'],
free_tag['tags'],
alpha=free_tag['alpha'],
color=free_tag['color'],
font_info=free_tag['font_info']
)
return cv2.resize(next_frame, (0,0), fx=fx, fy=fy, interpolation=interpolation)
|
import os
import csv
# Import reference data file - assuming residing in same directory
bank_csv = 'budget_data.csv'
with open(bank_csv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# Initialize variables to proper type after reading as strings
header = next(csvfile)
firstStr = next(csvfile)
firstArr = firstStr.split(",")
first = int(firstArr[1])
total = int(first)
greatInc = int(first)
greatDec = int(first)
count = 1
# Iterate through rows, total changes
for row in csvreader:
last = int(row[1])
total = total + last
count = count + 1
# Check for max and min values, populate corresponding variables
if last > greatInc:
greatInc = last
greatIncDate = row[0]
if last < greatDec:
greatDec = last
greatDecDate = row[0]
# Calculate final changes
avgChange = int(total / count)
netChange = last - first
# Print results
# print(f"Financial Analysis")
# print(f"-----------------------")
# print(f"Total months: " + str(count))
# print(f"Net change: $" + str(netChange))
# print(f"Average change: $" + str(avgChange))
# print(f"Greatest increase in profits: " + greatIncDate + " ($" + str(greatInc) + ")")
# print(f"Greatest decrease in profits: " + greatDecDate + " ($" + str(greatDec) + ")")
lin1 = "Financial Analysis \n"
lin2 = "------------------------ \n"
lin3 = "Total months: " + str(count) + "\n"
lin4 = "Net change: $" + str(netChange) + "\n"
lin5 = "Average change: $" + str(avgChange) + "\n"
lin6 = "Greatest increase in profits: " + greatIncDate + " ($" + str(greatInc) + ") \n"
lin7 = "Greatest decrease in profits: " + greatDecDate + " ($" + str(greatDec) + ") \n"
L = [lin1,lin2,lin3,lin4,lin5,lin6,lin7]
fileWrite = open("BankResults.txt","w")
fileWrite.writelines(L)
print(lin1)
print(lin2)
print(lin3)
print(lin4)
print(lin5)
print(lin6)
print(lin7)
|
import numpy as np
"################ Prime Stuff ######################"
prime_list = [2, 3, 5]
"list of primes"
def prime_list_func(upper_limit):
"""
with sieve of atkin
:param upper_limit:
:return:
"""
start_limit = prime_list[-1] + 2
upper_limit = int(upper_limit) + 1
candidates = list(range(start_limit, upper_limit))
candidates_statuses = [True] * len(candidates)
for prime in prime_list:
to_remove = prime ** 2
if to_remove >= upper_limit:
break
while to_remove < upper_limit:
if to_remove >= start_limit:
candidates_statuses[to_remove - start_limit] = False
to_remove += prime
for cand, status in zip(candidates, candidates_statuses):
if status:
to_remove = cand ** 2
if to_remove >= upper_limit:
break
while to_remove < upper_limit:
candidates_statuses[to_remove - start_limit] = False
to_remove += cand
for cand, status in zip(candidates, candidates_statuses):
if status:
prime_list.append(cand)
def is_prime(x):
"""
get's slow for large numbers, because prime list is being updated
:param x:
:return:
"""
if x in prime_list:
return True
elif not prime_list[-1] > x // 2:
prime_list_func(x // 2 + 1)
if 0 in x % np.array(prime_list):
return False
else:
return True
def prime_factorization(number, as_dict=True):
"""
:param number:
:return:
"""
if prime_list[-1] < number // 2:
prime_list_func(number // 2)
x = number
prime_factors = {}
i = 2
while x >= i:
if is_prime(i):
while x % i == 0:
prime_factors[i] = prime_factors.get(i, 0) + 1
x //= i
if i == 2:
i += 1
else:
i += 2
if as_dict:
return prime_factors
else:
return prime_factor_dict_to_list(prime_factors)
def prime_factor_dict_to_list(prime_factor_dict):
prime_factors_list = []
for prime in prime_factor_dict.keys():
prime_factors_list.extend(prime_factor_dict[prime] * [prime])
return prime_factors_list
def prime_factors_product(prime_factors):
if type(prime_factors) is dict:
prod = 1
for key, val in prime_factors.items():
prod *= key ** val
return prod
elif type(prime_factors) is list:
return np.prod(np.array(prime_factors))
"################ Problem 1 ######################"
def mult_of_x_smaller_n(x, n):
return [i for i in range(x, n, x)]
"################ Problem 2 ######################"
def fibonacci(maximum):
pass
fib_list = [1, 2, 3]
next_num = fib_list[-1] + fib_list[-2]
while next_num < maximum:
fib_list.append(next_num)
next_num = fib_list[-1] + fib_list[-2]
return fib_list
def fibonacci2(no):
memo = {0: 0, 1: 1}
def fibm(n):
if not n in memo:
memo[n] = fibm(n - 1) + fibm(n - 2)
return memo[n]
return fibm(no)
"################ Problem 3 ######################"
def prime_list_func_old1(upper_limit):
prime_list = [2, 3, 5]
for i in np.arange(prime_list[-1] + 1, upper_limit + 1, dtype=int):
if 0 in i % np.array(prime_list):
continue
else:
prime_list.append(i)
def prime_list_func_old2(upper_limit):
prime_list = [2, 3, 5]
i = prime_list[-1] + 2
while i < upper_limit:
divider_found = False
for prime in prime_list[1:]:
if i % prime == 0:
divider_found = True
break
if not divider_found:
prime_list.append(i)
i += 2
def prime_factorization_old1(number):
"""
crashes for big numbers
"""
x = number
if not prime_list[-1] > x / 2:
prime_list_func(int(x / 2 + 1))
prime_factors = []
for i in prime_list:
while x % i == 0:
x = x / i
prime_factors.append(i)
return prime_factors
"################ Problem 4 ######################"
def is_palindrom(x):
x = str(x)
y = x[::-1]
return x == y
"################ Problem 5 ######################"
def find_generating_set_of_primes(group):
"""
gibt das Tupel an Primzahlen, mit welcher jedes Element von group gebildet werden kann
:param group: Satz an Zahlen
:return:
"""
gen_set = {}
group = np.array(group)
for i in group:
prime_factors = prime_factorization(i)
for pr_fct_prime, pr_fct_power in prime_factors.items():
if pr_fct_prime not in gen_set.keys():
gen_set[pr_fct_prime] = pr_fct_power
elif gen_set[pr_fct_prime] < pr_fct_power:
gen_set[pr_fct_prime] = pr_fct_power
return gen_set
"################ Problem 7 ######################"
def prime_list_func_by_no_of_primes(no, step=100):
upper_limit = step
while len(prime_list) < no:
prime_list_func(upper_limit)
upper_limit += step
"################ Problem 9 ######################"
def is_square(apositiveint):
x = apositiveint // 2
seen = {x}
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen:
return False
seen.add(x)
return True
"################ Problem 9 ######################"
def prime_list_func_step(maxi, step=100):
upper_limit = step
while prime_list[-1] < maxi:
prime_list_func(upper_limit)
upper_limit += step
"################ Problem 12 ######################"
def divisors(n):
"""
from: https://stackoverflow.com/questions/171765/what-is-the-best-way-to-get-all-the-divisors-of-a-number/37058745#37058745
:param n:
:return:
"""
if is_prime(n):
return [1, n]
factors = prime_factorization(n)
primes = list(factors.keys())
# generates factors from primes[k:] subset
def generate(k):
if k == len(primes):
yield 1
else:
rest = generate(k + 1)
prime = primes[k]
for factor in rest:
prime_to_i = 1
# prime_to_i iterates prime**i values, i being all possible exponents
for _ in range(factors[prime] + 1):
yield factor * prime_to_i
prime_to_i *= prime
return list(generate(0))
def divisors_gen(n):
"""
from: https://stackoverflow.com/questions/171765/what-is-the-best-way-to-get-all-the-divisors-of-a-number/37058745#37058745
:param n:
:return:
"""
factors = prime_factorization(n)
primes = list(factors.keys())
# generates factors from primes[k:] subset
def generate(k):
if k == len(primes):
yield 1
else:
rest = generate(k + 1)
prime = primes[k]
for factor in rest:
prime_to_i = 1
# prime_to_i iterates prime**i values, i being all possible exponents
for _ in range(factors[prime] + 1):
yield factor * prime_to_i
prime_to_i *= prime
yield from generate(0)
def divisors_old(n):
if is_prime(n):
return [1, n]
divis = [1]
for i in range(2, n + 1):
if n % i == 0:
divis.append(i)
return divis
def get_factors_no(n):
return sum(2 for i in range(1, int(np.sqrt(n) + 0.5) + 1) if not n % i)
def get_factors_no_numpy(num):
arr = num % np.arange(1, int(np.sqrt(num) + 0.5) + 1)
return arr[arr == 0].size
def triangle_numbers_generator():
i = 1
number = i
while True:
yield number
i += 1
number += i
def triangle_numbers(limit):
triang_nums = []
i = 1
number = i
while number < limit:
triang_nums.append(number)
i += 1
number += i
return triang_nums
def is_triangle_number(num):
from math import sqrt
root = sqrt(8 * num + 1)
if root % 1 != 0:
return False
elif (root + 1) / 2 % 1 != 0:
return False
else:
return True
def find_divisor_multiplicities(limit=500):
prod = 1
def generator(depth):
depth -= 1
if depth == 0:
i = 1
while prod < limit:
yield [i]
i += 1
else:
rest = generator(depth - 1)
i = 0
while True:
for x in rest:
yield [i] + x
i += 1
rest = generator(depth - 1)
d = 1
while True:
exp_base_range = range(2, 2 + d)
for exponent_list in generator(d):
prod_dict = dict(zip(exp_base_range, exponent_list))
prod = prime_factors_product(prod_dict)
if prod >= limit:
yield prod_dict
if exp_base_range[-1] ** exponent_list[-1]:
d += 1
break
"################ Problem 14 ######################"
def collatz_seq_length(n):
length = 1
while n != 1:
if n % 2:
n = 3 * n + 1
else:
n = n / 2
length += 1
return length
"################ Problem 15 ######################"
def factorial(n):
# oder einfach math.factorial
if n == 0:
return 1
else:
# np.prod(np.arange(2, n+1, dtype=np.uint64))
prod = 1
for i in range(2, n + 1):
prod *= i
return prod
"################ Problem 17 ######################"
def give_len_of_num_word(num):
# len of nums to 20
num_to_20 = ", one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, " \
"fourteen, fifteen, sixteen, seventeen, eighteen, nineteen"
num_to_20 = num_to_20.split(", ")
num_len_to_20 = list(map(len, num_to_20))
# print(num_len_to_20)
num_len_to_20_old = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
# print(num_len_to_20_old)
num_len_to_20 = num_len_to_20_old
# len of decimals
decimals_num = "zero, ten, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety"
decimals_num = decimals_num.split(", ")
# decimals_len = list(map(len, decimals_num))
decimals_len = [0, 3, 6, 6, 5, 5, 5, 7, 6, 6]
thous_len_of_num = 0
thous_digit = num // 1000
if thous_digit:
thous_len_of_num += num_len_to_20[thous_digit]
thous_len_of_num += 8 # len("thousand")
num = num % 1000
hun_len_of_num = 0
hun_digit = num // 100
if hun_digit:
hun_len_of_num += num_len_to_20[hun_digit]
hun_len_of_num += 7 # len("hundred")
num = num % 100
if num:
hun_len_of_num += 3 # len("and")
dec_len_of_num = 0
if num < 20:
dec_len_of_num += num_len_to_20[num]
else:
dec_digit = num // 10
dec_len_of_num += decimals_len[dec_digit]
dec_len_of_num += num_len_to_20[num % 10]
return dec_len_of_num + hun_len_of_num + thous_len_of_num
"################ Problem 18 ######################"
def binomial(x, y):
from math import factorial as fac
try:
return fac(x) // fac(y) // fac(x - y)
except ValueError:
return 0
def pascal(m):
return [[binomial(x, y) for y in range(x + 1)] for x in range(m+1)]
def flat_list(original_list):
return [item for l in original_list for item in l]
def product(iter_obj):
prod = 1
for i in iter_obj:
prod *= i
return prod
"################ Problem 21 ######################"
def check_amicable(num):
am_cand = sum(divisors(num)[:-1])
if sum(divisors(am_cand)[:-1]) == num:
return am_cand
else:
return False
|
list1 = {1:[[1,2,3,4],[100,100,100],[200,200,200]]}
# values = set(map(lambda x:x[1], list1))
newlist = [[y[1] for y in list1 if y[1]==x] for x in list1]
print newlist |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 23:02:51 2020
@author: Oussama
"""
#Question 7
#Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24
#Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) In case of input data being supplied to the question, it should be assumed to be a console input.
#Création d'une Fonction de Calcule avec des Valeur par Default
def calcule (D, C=50,H=30):
return int(((2*C*D)/H)**.5)
#Récupere la séquence des nombres avec input
#Utilisation de Map pour convertir "un par un" la sequence str en int et l'enregistrer dans une list
in_Liste = list(map(int,(input("\nEntrer une séquence de nombres 'séparer par une virgule: ").split(','))))
#Toujours avec map envoi la séquence in_Liste "un par un" vers la fonction Calcule
out_Liste = list(map(calcule, in_Liste))
#Affichage
print ('Séquence Entrer : \n', in_Liste , '\n Séquence de Sortie : \n', out_Liste )
|
"""
See https://algorist.com/problems/Set_Packing.html
The data are represented by a set of subsets S1,...,Sm of the universal set U={1,...,n}.
The problem is to find the largest number of mutually disjoint subsets from S?
Examples of Execution:
python3 SetPacking.py -data=Subsets_example.json
"""
from pycsp3 import *
subsets = data
vals = sorted({v for subset in subsets for v in subset})
m = len(subsets)
# x[i] is 1 iff the ith subset is selected
x = VarArray(size=m, dom={0, 1})
satisfy(
# avoiding intersection of subsets
Count(scp, value=1) <= 1 for scp in [[x[i] for i, subset in enumerate(subsets) if v in subset] for v in vals]
)
maximize(
# maximizing the number of selected subsets
Sum(x)
)
"""
1) we avoid using values instead of vals as name for the list of bid values
as it may enter in conflict with the function values() in a notebook
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.