text
stringlengths 37
1.41M
|
---|
import random
print("The generated password having 10 characters is : ")
s1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
s2="!@#$%^&*"
s3="1234567890"
s4="abcdefghijklmnopqrstuvwxyz"
s5=s1+s2+s3+s4;
upper_string=random.choice(s1)#It ensures at least 1 upper case character
lower_string=random.choice(s4)#It ensures at least 1 lower case character
symbol=random.choice(s2)#It ensures at least 1 special symbol
digit=random.choice(s3)#It ensures at least 1 digit
temp_password=upper_string+lower_string+symbol+digit
password=''.join(random.sample(temp_password,len(temp_password)))#ut shuffles the 4 charcters
x=1;
while x<=8:#getting the rest 8 characters
sr = ''.join(random.sample(s5,len(s5)))#shuffling
password+=random.choice(sr)
x+=1
password=''.join(random.sample(password,len(password)))#Again shuffling to ensure the password is strong
print(password)
|
import string
import os
os.chdir('./Files/Alphabet/')
letters = string.ascii_lowercase
for letter in letters:
with open(letter + '.txt','w+')as file:
file.write(letter)
# To check and create directory you can use
"""
if not os.path.exists("Alphabet"):
os.makedirs("Alphabet")
"""
# Then you could use the path inside the with open
"""
for letter in string.ascii_lowercase:
with open("Alphabet/" + letter + ".txt", "w+")as file:
file.write(letter + "\n")
"""
|
import sqlite3
import pandas as pd
data = pd.read_csv("./Files/ten-more-countries.txt")
conn = sqlite3.connect("./Files/database.db")
cur = conn.cursor()
for index, row in data.iterrows():
print(row["Country"], row["Area"])
cur.execute("INSERT INTO countries VALUES(NULL,?,?,NULL)",(row["Country"], row["Area"]))
conn.commit()
conn.close()
'''
import sqlite3
import pandas as pd
conn = sqlite3.connect("database.db")
df = pd.read_csv('ten-more-countries.txt')
df.to_sql('countries',conn, if_exists='append', index=False)]
'''
|
d = {"a": list(range(1,11)), "b": list(range(11, 21)), "c": list(range(21, 31))}
print("b has value {}".format(d["b"]))
print("c has value {}".format(d["c"]))
print("a has value {}".format(d["a"]))
# Ardit Solution:
for key, value in d.items():
print(key, " has value ", value)
|
peopleD = {
"Jane Smith":
{"Age":23,
"Address":"123 Fake St"},
"Slim Dusty":
{"age":44}
}
#print(peopleD)
peopleL = {
"people" :[
{"Name": "Jane Smith",
"Age":23,
"Address":"123 Fake St"},
{"Name":"Slim Dusty",
"age":44}
]
}
print(peopleD)
for person in peopleD.keys():
print(person)
|
max_count = int(input("Max number >>> "))
delimeter = int(input("Delimiter >>> "))
current_count = 0
while True:
if current_count == max_count:
break
current_count = current_count + 1
if current_count % delimeter == 0:
continue
print(current_count)
|
# -*- coding: utf-8 -*-
# Форматированный вывод
import math
pi = math.pi
y = 2
z = pi * y
print('Умножение {a:.5f} на {b:d} дает {c:.3f}'.format(a=pi, b=y, c=z))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python 3.5.3
from numpy import zeros, log
def rectangular(f, a, b, n, rec='left'):
if rec == 'left':
get_node = lambda i: i
elif rec == 'right':
get_node = lambda i: i + 1
elif rec == 'mid':
get_node = lambda i: i + 0.5
else:
return float('nan')
h = float(b - a) / n
result = 0
for i in range(0, n):
result += f(a + get_node(i) * h)
result *= h
return result
def test_rectangular_manual():
rec = ['left', 'mid', 'right']
expected = [184, 376, 688]
f = lambda x: x ** 2 + x ** 3
for i in range(len(rec)):
computed = rectangular(f, 0, 6, 3, rec[i])
tol = 1E-14
rel_error = abs(expected[i] - computed)
msg = "Погрешность {0} больше допуска {1}.".format(rel_error, tol)
assert rel_error < tol, msg
def test_rectangular_constant():
v = lambda x: 10
V = lambda x: 10 * x
a = 1
b = 5
expected = V(b) - V(a)
rec = ['left', 'mid', 'right']
for i in range(len(rec)):
computed = rectangular(v, a, b, 2, rec[i])
tol = 1E-15
rel_error = abs(expected - computed)
msg = "Погрешность: {0}".format(rel_error)
assert rel_error < tol, msg
def conv_rates(f, F, a, b, rec, num_exp = 14):
expected = F(b) - F(a)
n = zeros(num_exp, dtype=int)
E = zeros(num_exp)
r = zeros(num_exp)
for i in range(num_exp):
n[i] = 2 ** (i + 1)
computed = rectangular(f, a, b, n[i], rec)
E[i] = abs((expected - computed) / expected)
if i > 0:
r_im1 = log(E[i] / E[i-1]) / log(float(n[i] / n[i - 1]))
r[i - 1] = float('%.2f' % r_im1)
return r
def test_rectangular_conv_rates():
v = lambda x: x
V = lambda x: x ** 2 / 2.
a = 0; b = 4
rec = ['left', 'right', 'mid']
for i in range(len(rec)):
r = conv_rates(v, V, a, b, rec[i])
tol = 0.01
msg = str(r[-4:])
success = (abs(r[-1]) - 2) < tol
assert success, msg
|
from sys import *
from array_list import *
#a SongFile contains a title, artist, song, and number
#title is a string
#artist is a string
#album is a string
#number is an int
class Song:
def __init__(self, title, artist, album):
self.number = 0 #int - value will be changed
self.title = title #str
self.artist = artist #str
self.album = album #str
def __eq__(self, other):
return ((type(other)==Song) and self.title == other.title and self.artist== other.artist and self.album == other.album)
def __repr__(self):
return("Song({!r}, {!r}, {!r})".format(self.title, self.artist, self.album))
def __str__(self):
return("{:d}--{:s}--{:s}--{:s}".format(self.number, self.title, self.artist, self.album))
#data defition: accepts an SongFile and returns an int
# SongFile -> int
#returns the sum of a SongFile
def length_song(i):
sum = 0
for count in i:
sum+=1
return sum
#data definitions: accepts a SongFile and returns a SongFile
#SongFile -> SongFile
#returns a new SongFile that is valid, with numbers, and prints out the invalid options
def read(files):
count = 0
error = 0
new = empty_list()
for temp in files:
temp = temp.rstrip('\n').split('--')
if length_song(temp) < 3 and error==0 and temp[0] != '':
print('Catalog input errors:')
print('line %d: malformed song information' % (count+1))
error+=1
elif length_song(temp) < 3 and error!=0 and temp[0] != '':
print('line %d: malformed song information' % (count+1))
elif length_song(temp) == 3:
new_song = Song(temp[0], temp[1], temp[2])
new_song.number = count
new = add(new, count, new_song)
count+=1
return new
#prints the list
def print_(list):
print(str(list))
#data definition: files is a SongFile and x is an int
#returns printed value
#SongFile int -> print
#prints the info of the song (value 2)
def info(files, x):
max_size = length(files)
if max_size <= x or x<0:
print('\n... Invalid song number')
else:
a = file_by_number(files)
value = get(a, x)
print('\nSong information ...')
print(' Number: {:d}'.format(value.number))
print(' Title: {:s}'.format(value.title))
print(' Artist: {:s}'.format(value.artist))
print(' Album: {:s}'.format(value.album))
def file_by_number(files):
x = empty_list()
x = sort(files, less_than_number)
return x
#data definition: x is a SongFile and y is a SongFile
#returns a bool
#SongFile Songfile -> bool
#compares the number of the SongFile
def less_than_number(x, y):
if x.number<y.number:
return True
elif x.number == y.number:
if x.artist < y.artist:
return True
elif x.artist == y.artist:
if x.album < y.album:
return True
elif x.album == y.album:
if x.title < y.title:
return True
else:
return False
else:
return False
else:
return False
else:
return False
#data definition: x is a SongFile and y is a SongFile
#returns a bool
#SongFile Songfile -> bool
#compares the title name of the SongFile
def less_than_title(x, y):
if x.title<y.title:
return True
elif x.title == y.title:
if x.artist < y.artist:
return True
elif x.artist == y.artist:
if x.album < y.album:
return True
elif x.album == y.album:
if x.number < y.number:
return True
else:
return False
else:
return False
else:
return False
else:
return False
#data definition: x is a SongFile and y is a SongFile
#returns a bool
#SongFile Songfile -> bool
#compares the artist name of the SongFile
def less_than_artist(x, y):
if x.artist<y.artist:
return True
elif x.artist == y.artist:
if x.album < y.album:
return True
elif x.album == y.album:
if x.title < y.title:
return True
elif x.title == y.title:
if x.number < y.number:
return True
else:
return False
else:
return False
else:
return False
else:
return False
#data definition: x is a SongFile and y is a SongFile
#returns a bool
#SongFile Songfile -> bool
#compares the song name of the SongFile
def less_than_album(x, y):
if x.album<y.album:
return True
elif x.album == y.album:
if x.artist < y.artist:
return True
elif x.artist == y.artist:
if x.title < y.title:
return True
elif x.title == y.title:
if x.number < y.number:
return True
else:
return False
else:
return False
else:
return False
else:
return False
#data definition: new and old are both lists
#returns list
# list list -> list
#puts new songs into old song list
def add_list(new, old):
count = length(old)
for temp in new:
temp = temp.rstrip('\n').split('--')
if length_song(temp) == 3:
new_song = Song(temp[0], temp[1], temp[2])
new_song.number = count
old = add(old, count, new_song)
count+=1
return old
#data definition: takes in file1 which is a list of Songs,
#accum is a string
#returns one of
#recursion - menu(file, accum)
#quit()
#list str -> function
#menu for what to do with the song
def menu(file1, accum=''):
if accum == 'number':
file1 = sort(file1, less_than_number)
if accum == 'title':
file1 = sort(file1, less_than_title)
if accum == 'artist':
file1 = sort(file1, less_than_artist)
if accum == 'album':
file1 = sort(file1, less_than_album)
print('\nSong Catalog')
print(' 1) Print Catalog')
print(' 2) Song Information')
print(' 3) Sort')
print(' 4) Add Songs')
print(' 0) Quit')
try:
x = int(input('Enter selection: '))
except:
print("\nInvalid option")
menu(file1, accum)
if x ==1:
foreach(file1, print_)
menu(file1, accum)
if x ==2:
try:
y = int(input('Enter song number: '))
except:
print("\nInvalid option")
menu(file1, accum)
info(file1, y)
menu(file1, accum)
if x == 3:
print('\nSort songs')
print(' 0) By Number')
print(' 1) By Title')
print(' 2) By Artist')
print(' 3) By Album')
try:
y = int(input('Sort by: '))
except:
print("\n... Invalid sort option")
menu(file1, accum)
if y == 0:
file1 = sort(file1, less_than_number)
menu(file1, 'number')
if y == 1:
file1 = sort(file1, less_than_title)
menu(file1, 'title')
if y == 2:
file1 = sort(file1, less_than_artist)
menu(file1, 'artist')
if y == 3:
file1 = sort(file1, less_than_album)
menu(file1, 'album')
else:
print("\n... Invalid sort option")
menu(file1)
if x ==4:
try:
new_file = str(input('Enter name of file to load: '))
newFile = open(new_file, 'r')
except:
print("\n'{}': No such file or directory".format(new_file))
menu(file1, accum)
file1 = add_list(newFile, file1)
menu(file1, accum)
if x ==0:
quit()
else:
print("\n'%r': No such file or directory" % (x))
menu(file1, accum)
# None -> function
#main function that gets called when name gets called
def main():
inFile = open(argv[1], 'r')
file1 = read(inFile)
menu(file1)
if __name__ == '__main__':
main()
|
import random
def myiter():
num = random.random()
if num < 0.1:
#print("%.5s" % self.num)
raise StopIteration
new = random.random()
while abs(new - num) < 0.4:
#print("%.5s" % new)
print("*", end='')
new = random.random()
num = new
yield new
a = myiter()
for x in a:
print(x)
|
class Enemy(object):
life = 3
#attack function to take life
def attack(self):
print("ouch!")
self.life -= 1
#checks life to see if it is less than 0
def checkLife(self):
if self.life <= 0:
print("I am dead")
else:
print(str(self.life) + " life left")
vampire = Enemy()
vampire.attack()
vampire.checkLife()
vampire.attack()
vampire.checkLife()
|
class LRUCache:
def __init__(self, capacity: int):
self.d = {} # map key to DLQ node
self.q = DLQ()
self.cap = capacity
def get(self, key: int) -> int:
if key in self.d:
node = self.d[key]
self.q.mark_mru(node)
return node.v
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.d:
node = self.d[key]
node.v = value
self.q.mark_mru(node)
else:
if len(self.d) == self.cap:
removed_node = self.q.pop()
del self.d[removed_node.k]
node = self.q.push(key, value)
self.d[key] = node
class DLQ:
"""Doubly Linked Queue"""
class Node:
def __init__(self, k, v, p=None, n=None):
self.k = k
self.v = v
self.p = p
self.n = n
def __init__(self):
# sentinel.n = mru, sentinel.p = lru
self.sentinel = DLQ.Node(k=None, v=None)
self.sentinel.p = self.sentinel
self.sentinel.n = self.sentinel
def push(self, k, v) -> Node:
"""Add as MRU node and return the reference to it."""
node = DLQ.Node(k, v, self.sentinel, self.sentinel.n)
self.sentinel.n = node
node.n.p = node
return node
def pop(self) -> Node:
"""
Remove LRU node and return the reference to it.
Assume non-empty queue, since pop is only called
when capacity is reached, where capacity >= 1.
"""
node = self.sentinel.p
node.p.n = node.n
self.sentinel.p = node.p
return node
def mark_mru(self, node) -> None:
"""Move the node up by rearranging links."""
node.p.n = node.n
node.n.p = node.p
self.sentinel.n.p = node
node.n = self.sentinel.n
self.sentinel.n = node
node.p = self.sentinel
if __name__ == "__main__":
s = Solution()
|
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
i, j = 0, m * n - 1
while i <= j:
mid = (i + j) // 2
z = matrix[mid // n][mid % n]
if target < z:
j = mid - 1
elif target > z:
i = mid + 1
else: # target == z
return True
return False
if __name__ == "__main__":
s = Solution()
|
import time
start = time.time()
# Python program for implementation of heap Sort
count = 0
# To heapify subtree rooted at index i.
# n is size of heap
def heapify(arr, n, i):
global count
count += 1
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
global count
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
count += 1
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
count += 1
# Driver code to test above
fp = open("case") # Open file on read mode
arr = fp.read().split(" ") # Create a list containing all lines
fp.close()
list2 = []
for i in range(len(arr)):
t = int(arr[i])
list2.append(t)
heapSort(list2)
for i in range(len(list2)):
print ("% d" % list2[i])
# This code is contributed by Mohit Kumra
end = time.time()
print(end - start)
print(count)
|
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
class plotting:
def plot_decision_boundary(model, X, y):
"""
Plots the decision boundary created by a model predicting on X.
This function has been adapted from two phenomenal resources:
"""
# Define the axis boundaries of the plot and create a meshgrid
x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1
y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
# Create X values
x_in = np.c_[xx.ravel(), yy.ravel()] # Stack 2D arrays together
# Make predictions using the trained model
y_pred = model.predict(x_in)
# Check for multi-class
if len(y_pred[0]) > 1:
print("doing multiclass classification...")
# Reshape our predictions to get them ready for plotting
y_pred = np.argmax(y_pred, axis=1).reshape(xx.shape)
else:
print("doing binary classifcation...")
y_pred = np.round(y_pred).reshape(xx.shape)
# Plot decision boundary
plt.contourf(xx, yy, y_pred, cmap=plt.cm.RdYlBu, alpha=0.7)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.RdYlBu)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
def plot_prediction_vs_data(X_train, X_test, y_train,y_test, predictions):
"""
Plot the model's predictions against our regression data
"""
plt.figure(figsize=(10, 7))
plt.scatter(X_train, y_train, c='b', label='Training data')
plt.scatter(X_test, y_test, c='g', label='Testing data')
plt.scatter(X_test, predictions.squeeze(), c='r', label='Predictions')
plt.legend();
def plot_decision_boundary_test_and_train(model, X_train, X_test, y_train, y_test):
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title("Train")
plot_decision_boundary(model, X_train, y_train)
plt.subplot(1, 2, 2)
plt.title("Test")
plot_decision_boundary(model, X_test, y_test)
plt.show()
def plot_history(history):
pd.DataFrame(history.history).plot(figsize=(10,7), xlabel="epochs");
def plot_learning_rate_vs_loss(history):
plt.figure(figsize=(10, 7))
plt.semilogx(history.history["lr"], history.history["loss"])
plt.xlabel("Learning Rate")
plt.ylabel("Loss")
plt.title("Learning rate vs. loss");
|
# name: pa2pre.py
# purpose: Student's add code to preprocessing of the data
# Recall that any preprocessing you do on your training
# data, you must also do on any future data you want to
# predict. This file allows you to perform any
# preprocessing you need on my undisclosed test data
NB_CLASSES=10
from tensorflow import keras
import numpy as np
def processTestData(X, y):
train_data = np.load('MNISTXtrain1.npy')
train_labels = np.load('MNISTytrain1.npy')
eval_data = np.load('MNIST_X_test_1.npy')
eval_labels = np.load('MNIST_y_test_1.npy')
# X preprocessing goes here -- students optionally complete
# y preprocessing goes here. y_test becomes a ohe
y_ohe = keras.utils.to_categorical (y, NB_CLASSES)
return X, y_ohe
|
"""Defines the parameters of the algorithm.
This module contains the defintion of the class that
handles all parameters of the algorithm.
"""
import robinmax_utils as utils
class RobinmaxArgs:
""" The parameter class. Contains all the
parameters necessary for the algorithm.
"""
def __init__(self, graph, thresh_budget, max_thresh_dev,
weight_budget, max_weight_dev, max_cover_size,
time_limit, num_seeds, heuristics, disable_cuts,
solve_as_lp, debug_level, out_f):
"""Constructor.
"""
# Performs some sanity checks
if heuristics not in [-1, 1, 2]:
print('Invalid value for heuristics parameter.' +
'Check python3 robinmax.py --help.')
# Compute the epsilon to use throughout the algorithm
epsilon = utils.epsilon(graph)
self.graph = graph
self.thresh_budget = thresh_budget
self.max_thresh_dev = max_thresh_dev
self.weight_budget = weight_budget
self.max_weight_dev = max_weight_dev
self.max_cover_size = max_cover_size
self.time_limit = time_limit
self.num_seeds = num_seeds
self.heuristics = heuristics
self.disable_cuts = disable_cuts
self.solve_as_lp = solve_as_lp
self.epsilon = epsilon
self.debug_level = debug_level
self.out_f = out_f
# Set to 0 the max deviations if their coresponding
# budget is 0.
if (self.thresh_budget == 0 and self.max_thresh_dev > 0):
print('******* Warning: threshold budget is zero but its max deviation is not.')
print('Setting max threshold deviation to 0.')
self.max_thresh_dev = 0
if (self.weight_budget == 0 and self.max_weight_dev > 0):
print('******* Warning: weight budget is zero but its max deviation is not.')
print('--> Setting max weight deviation to 0.')
self.max_weight_dev = 0
# Setting default value of max_cover_size
if (self.max_cover_size == -1):
self.max_cover_size = self.graph.num_nodes
def __str__(self):
"""Convert to string for printing purposes.
"""
out = 'GRAPH\n'
out += 'Name: {:s}\n'.format(self.graph.name)
out += 'Nodes: {:d}\n'.format(self.graph.num_nodes)
out += 'Arcs: {:d}\n'.format(self.graph.num_arcs)
out += '\n'
out += 'PARAMETERS\n'
out += 'Seeds: {:d}\n'.format(int(self.num_seeds))
out += 'Cover size: {:d}\n'.format(int(self.max_cover_size))
out += 'Robustness threshold budget: {:.2f}\n'.format(self.thresh_budget)
out += 'Max threshold deviation: {:.2f}\n'.format(self.max_thresh_dev)
out += 'Robustness weight budget: {:.2f}\n'.format(self.weight_budget)
out += 'Max weight deviation: {:.2f}\n'.format(self.max_weight_dev)
out += 'Time limit: {:.1f}\n'.format(self.time_limit)
out += 'Disable cuts: {:s}\n'.format(str(self.disable_cuts))
out += 'Solve as LP: {:s}\n'.format(str(self.solve_as_lp))
out += 'Epsilon: {:.2e}\n'.format(self.epsilon)
out += 'Debug level: {:s}\n'.format(str(self.debug_level))
out += 'Output file: {:s}\n'.format(str(self.out_f.name))
out += '\n'
return out
|
import pygame
from decimal import Decimal
from .Constantes import altura_tela, largura_tela
class Ponto():
"""
A classe Ponto define um ponto no espac ̧o a partir das coordenadas retangulares x e y.
"""
def __init__(self, x, y):
self.x = x #referente a coordenada retangular x, no caso, o índice da coluna do pixel na tela.
self.y = y #referente a coordenada retangular y, no caso, o índice da linha do pixel na tela.
def __str__(self):
"""
Reescrita do método \_\_str\_\_ herdado de object, retorna uma string que representa o ponto com a notação matemática (x,y)
"""
return '({},{})'.format(self.x, self.y)
class Sprite():
def __init__(self, tela, x, y, sprite_atual, velocidade_animacao=0, velocidade_horizontal=0, velocidade_vertical=0):
self.coordenada_retangular = Ponto(x, y) #recebe uma instância da classe Ponto() que guarda as coordenadas do ponto superior esquerdo, utilizado como referencial, do sprite exibido no frame corrente.
self.tela = tela #recebe o objeto, fornecido por pygame.display.set\_mode(), referente a tela onde o sprite será impresso.
self.velocidade_animacao = velocidade_animacao #recebe uma instância da classe Decimal(), empregado como controle da velocidade de animação dos sprites. Utiliza-se a classe Decimal a fim de garantir precisão na soma de pontos flutuantes.
self.velocidade_horizontal = velocidade_horizontal #define a velocidade de deslocamento horizontal do sprite, representada por um inteiro.
self.velocidade_vertical = velocidade_vertical #define a velocidade de movimento vertical do sprite
self.__sprite_atual = sprite_atual #define a velocidade de deslocamento vertical do sprite, representada por um inteiro. #recebe o objeto após aplicar pygame.image.load(caminho).convert(), em que o caminho é o caminho relativo do sprite em questão no diretório assets. Por se tratar de um setter, ao ser atribuída, executa outras operações.
self.index_sprite_atual = 0 #define o índice atual em uma lista de sprites.
self.tipo_animacao = 0 #define o tipo de animação executada pelo sprite corrente.
@property
def sprite_atual(self):
return self.__sprite_atual
@sprite_atual.setter
def sprite_atual(self, sprite_atual):
self.largura_sprite_atual = self.sprite_atual.get_rect().width #guarda a largura do retângulo do sprite atual. É atribuída toda vez que um sprite mudar sua imagem no frame corrente.
self.altura_sprite_atual = self.sprite_atual.get_rect().height #guarda a altura do retângulo do sprite atual. É atribuída toda vez que um sprite mudar sua imagem no frame corrente.
self.__sprite_atual = sprite_atual
def deslocar_horizontalmente(self, sentido=1):
"""
Realiza o deslocamento horizontal do sprite no sentido passado como parâmetro, por padrão 1, ou seja,
a soma da cooredenada retangular x com o produto entre o sentido e a velocidade horizontal. O sentido pode assumir os valores inteiros 1 ou -1.
"""
self.coordenada_retangular.x = self.coordenada_retangular.x + sentido*self.velocidade_horizontal
def deslocar_verticalmente(self, sentido=1):
"""
Realiza o deslocamento vertical do sprite no sentido passado como parâmetro, por padrão 1, ou seja,
a soma da cooredenada retangular y com o produto entre o sentido e a velocidade vetical. O sentido pode assumir os valores inteiros 1 ou -1.
"""
self.coordenada_retangular.y = self.coordenada_retangular.y + sentido*self.velocidade_vertical
def imprimir_sprite(self):
"""
Encapsula o método blit do objeto tela a fim de exibir o sprite atual do frame.
"""
self.tela.blit(self.sprite_atual, (self.coordenada_retangular.x, self.coordenada_retangular.y))
def animar_sprite(self, lista_sprites):
"""
Imprime na tela o sprite atual pertencente a lista de sprites passada como parâmetro.
Os sprites são exibidos consoante ao valor do atributo velocidade\_animacao que incrementa index\_sprite\_atual.
"""
if self.index_sprite_atual % 1 == Decimal('0.0'):
self.sprite_atual = lista_sprites[int(self.index_sprite_atual)]
self.index_sprite_atual = self.index_sprite_atual + self.velocidade_animacao
self.imprimir_sprite()
@property
def coordenada_retangular_inferior_direita(self):
#propriedade que devolve uma instância da classe Ponto() contendo as coordenadas do ponto inferior direito do sprite atual.
return Ponto(self.coordenada_retangular.x + self.largura_sprite_atual, self.coordenada_retangular.y + self.altura_sprite_atual)
@property
def coordenada_retangular_inferior_esquerda(self):
#propriedade que devolve uma instância da classe Ponto() contendo as coordenadas do ponto inferior esquerdo do sprite atual.
return Ponto(self.coordenada_retangular.x, self.coordenada_retangular.y + self.altura_sprite_atual)
@property
def coordenada_retangular_superior_direita(self):
#propriedade que devolve uma instância da classe Ponto() contendo as coordenadas do ponto superior direito do sprite atual.
return Ponto(self.coordenada_retangular.x + self.largura_sprite_atual, self.coordenada_retangular.y)
def atualizar(self):
'''
O seguinte método deve ser implementado por cada classe que herda Spite
a fim de atualizar as sprites
'''
pass
|
import numpy as np
# An error function allows us to tell how far a point is from the
# boundary line. With discrete functions, we can only tell whether a
# point is misclassified or not. But with a continuous function we can
# also tell by what magnitude the point is misclassified (using the
# error function). This makes it more efficient when optimising the
# boundary line.
def equation_result(X, W, b)
"""Gives the result of the inputs being applied to a linear boundary equation
Args:
X: array. Inputs used for training
W: array. Weights for the inputs
b: double. Bias
Returns:
value after inputs are applied to a linear equation
"""
return (np.matmul(X,W)+b)[0]
# Example of discrete (as used in the perceptron algorithm example)
def prediction_discrete(X, W, b)
"""Generates a prediction on whether a point should be classified +ve/-ve
Args:
X: array. Inputs used for training
W: array. Weights for the inputs
b: double. Bias
Returns:
0 or 1: 0 indicates the point is classified as negative, 1 shows positive
"""
# This is a step function
if equation_result(X, W, b) >= 0:
return 1
return 0
# Example of continuous (Sigmoid function)
# sigmoid(X) = 1/(1+e^(-X)
def prediction_sigmoid(X, W, b)
"""Gives the probability of a point being positive or negative
Args:
X: array. Inputs used for training
W: array. Weights for the inputs
b: double. Bias
Returns:
value between 0 and 1: values close to one are large positive numbers,
values close to 0 are large negative numbers, and values close to .5
are numbers that are close to zero
"""
return 1/(1 + np.exp(-equation_result(X, W, b))
# Example of continuous (Softmax function)
# The Sigmoid function works when working with binary options. But when
# working with more than one class that something can be classified
# into, we need another function, the Softmax function.
# softmax(X) = e^(score_of_class)/sum_of_((e^score_of_class)_for_all_classes)
def softmax(list_of_scores)
"""Takes a list of scores for each of classes and returns values when
the Softmax function is applied to the list
Args:
list_of_scores: list. Scores per class. These are used to determine the
probability that what we are examining belongs to which class
Returns:
List of probabilities of each class
"""
return np.divide(np.exp(list_of_scores), np.exp(list_of_scores).sum())
|
Variable.py
>>> 2 + 2
4
>>> 50 - 5 * 6
20
>>> (50 - 5 * 6) / 4
5.0
>>> round(5.0)
5
>>> 5.123456
5.123456
>>> round(5.123456,2)
5.12
>>> 17 / 3
5.666666666666667
>>> 17 // 3
5
>>> 18 // 4
4
>>> 20 // 5
4
>>> 17 % 3
2
>>> 17 * 4 % 3
2
addition = 75 + 25
subtraction = 204 - 204
multiplication = 100 * 0.5
division = 90 / 9
power of 2 = 3 ** 2
the remainder of the division = 10 % 3
>>> 17/3
5.666666666666667
>>> 5*3+2%3
17
>>> 5*3+3%4
18
>>> 6*9-4*5%2
54
>>> 7*5-6*3%3
35
>>> 6*5-7*4/4%2
29.0
>>> 8*9/4*5%3-2
-2.0
* / % + - (operator)
>>> print ('spam eggs')
spam eggs
>>> print(' don\'t ')
don't
>>> print("doesn't")
doesn't
>>> print('"Yes"')
"Yes"
>>> print("\"Yes,\" they said.")
"Yes," they said.
>>> print('"Isn\'t," they said')
"Isn't," they said
>>> print('"Isn\'t," they said')
"Isn't," they said
>>> print('"Isn\'t, they said"')
"Isn't, they said"
# \n =newLine
s= 'First Line.\nSecond Line.'
print(s)
print("""\
Usage: thingy
-a
-b
-c
""")
"""...""" or '''...'''
int - integer - 1, 2, 3, ---> 308930 etc
float - - 1.0, 5.9, 6.0, 63.23, etc
string - - 'Hello', "World", "A", "B",
a = 1
a (variable) = (assign) 1 (value)
width = 20
height = 5 * 9
vol = width * height
vol
sale = 1500
tax = 5 / 100
total_tax = sale * tax
total_tax
total_price = sale + total_tax
total_price
|
a = [0, [1, [2, [3,[4,[5,None]]]]]]
b = [6,[7,[8,[9,[10,[11, None]]]]]]
c = a
while c:
c[0] = a[0] + b[0]
c = c[1]
b = b[1]
a = a[1]
print(c[0])
print(c)
while c :
print(c[0], end='')
c = c[1]
|
def reverse(x):
result = []
for i in x:
num = str(i)
result.append(int(num[::-1]))
return result
def isPrime(x):
rev = reverse(x)
maxResult = max(rev)
arr = [True for i in range(maxResult+1)]
arr[1] = False
for i in range(2,maxResult+1):
if arr[i] == True:
for j in range(i+i, maxResult+1, i):
arr[j] = False
for i in rev:
if arr[i] == True :
print(i)
n = input()
x = list(map(int,input().split()))
isPrime(x)
|
import heapq
heap = []
while True:
x = int(input())
if x > 0 :
heapq.heappush(heap, x)
elif x == 0 :
print(heap)
print(heapq.heappop(heap))
heap = []
elif x == -1:
break
|
def DFS(x):
# 전위순회
if x > 7:
return
else:
DFS((x * 2))
print(x)
DFS((x*2)+1)
if __name__ == "__main__":
DFS(1)
|
def hi(name):
print('hi,', name)
hi('jiwon')
hi('python')
def hi_return(name):
val = 'Hi, ' + str(name)
return val
print(hi_return('apple'))
def func_mul(x):
y1 = x * 100
y2 = x * 200
y3 = x * 300
return y1,y2,y3
val1 = func_mul(100)
print(type(val1))
def args_ex(*args):
for idx,val in enumerate(args):
print(idx,val)
args_ex('a','b','c','d')
def kwargs_ex(**kwargs):
for key, val in kwargs.items():
print(key, val)
kwargs_ex(name='kim', age='21')
def function_ex(arg1, arg2, *args, **kwargs):
print(arg1, arg2, args, kwargs)
function_ex('a','b') # a b () {}
function_ex('a','b','park','kim') # a b ('park', 'kim') {}
function_ex('a','b','park','kim',age=21, age2=31) # a b ('park', 'kim') {'age': 21, 'age2': 31}
def nested_func(num):
def func_in_func(num):
print(num)
print("in function")
func_in_func(num + 10000)
nested_func(10000)
def func_mul3(x:int) -> tuple:
y1 = x * 100
y2 = x * 200
y3 = x * 300
return y1,y2,y3
val2 = func_mul3(100)
print(val2)
def mul_10(num:int) -> int:
return num*10
var_func = mul_10
print(type(var_func))
lambda_mul_10 = lambda num : num * 10
print(lambda_mul_10(10))
def func_final(x,y,func):
print(x * y * func(10))
func_final(10,10,lambda_mul_10)
|
class Environment():
def __init__(self, floors):
self.floors = floors + 1
self.turns = 0
self.elevators = []
self.users = []
def addUser(self, user):
self.users.append(user)
print(f'U{len(self.users)}| {user.getState()}')
def getUserById(self, i):
return self.users[i - 1]
def getElevatorById(self, i):
return self.elevators[i - 1]
def addElevator(self, elevator):
self.elevators.append(elevator)
for elevator in self.elevators:
updatedElevators = self.elevators[:]
updatedElevators.remove(elevator)
elevator.updateElevators(updatedElevators, self.floors)
print(f'E{len(self.elevators)}| {elevator.getState()}')
def bestFitElevator(self, user):
utils = []
for elevator in self.elevators:
utils.append(elevator.calcUtil(user))
print(f'Utils: {utils}')
maxUtil = max(utils)
i = utils.index(maxUtil)
return self.elevators[i]
def requestElevator(self, user, destinationFloor):
user.requestElevator(destinationFloor)
elevator = self.bestFitElevator(user)
elevator.addStop(user)
user.setElevator(elevator)
return elevator
def takeStairs(self, user):
elevator = user.elevator
elevator.removeFromPath(user)
user.takeStairs()
return user
def printState(self):
seperator = '\t'
elStateList = []
uStateList = []
elTableRow = seperator + seperator
print(f'== TURN {self.turns} ==')
for e in self.elevators:
eIndex = self.elevators.index(e) + 1
eIndexStr = f'E{eIndex}'
elTableRow = elTableRow + f'{eIndexStr}{seperator}'
elState = f'{eIndexStr}| {e.getState()}'
elStateList.append(elState)
for u in self.users:
uIndex = self.users.index(u) + 1
uIndexStr = f'U{uIndex}'
uState = f'{uIndexStr}| {u.getState()}'
uStateList.append(uState)
print(elTableRow)
for i in reversed(range(self.floors)):
toPrintSeperator = seperator * 2
toPrint = f'F{i}:{toPrintSeperator}'
elevators_on_floor = list(filter(lambda x: x.floor == i, self.elevators))
utilPrint = [f'[{e.getDirection()}]' if e in elevators_on_floor else '[ ]' for e in self.elevators]
utilPrint = seperator.join(utilPrint)
toPrint = toPrint + utilPrint
print(toPrint)
print('\n'.join(elStateList))
print('\n'.join(uStateList))
def run(self):
self.turns = self.turns + 1
for elevator in self.elevators:
elevator.move()
for user in self.users:
user.move()
self.printState()
def autoRun(self):
while any([len(e.destinations) for e in self.elevators]):
self.run()
def exit(self):
print(f'== METRICS ==')
print(f'Turns: {self.turns}')
for elevator in self.elevators:
[tL, tW, tP, tU] = elevator.metrics()
eIndex = self.elevators.index(elevator)
print(f'E{eIndex}')
print(f'With no light: {tL}')
print(f'By max weight: {tW}')
print(f'By path: {tP}')
print(f'By users: {tU}')
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 12')
robotArm.speed = 2
# Jouw python instructies zet je vanaf hier:
loopA = 0 # Waarde van while loop
positie = 1 # Waarde van de positie van het blokje waar de grijpklauw is gebleven
totaalPositie = 10 # Waarde van het aantal posities
while loopA <= 8: # Het blokje begint op 1 dus als er meer dan 8 loops zijn geweest stop het programma
loopB = 0 # Waarde van b is 0 wordt elke loop 0
loopC = 0 # Zelfde als b
robotArm.grab()
color = robotArm.scan()
afstand = totaalPositie - positie # Som van het aantal posities wat de klauw moet gaan 10 - positie
if color == 'red': # Als de kleur rood is voert het progamma dit uit
#print(afstand)
while loopB != afstand: # Het progamma blijft naar rechts gaan todat het gelijk is aan de afstand die het moest leggen
robotArm.moveRight()
loopB = loopB + 1
robotArm.drop() # Het laat de kubus vallen
positie = positie + 1 # De positie verplaatst anders grijpt de klauw niks
afstand = afstand - 1 # De afstand wordt wel minder want de klauw moet minder ver heen dan terug
#print(afstand)
while loopC != afstand: # De klauw beweegt de terugweg dus heen -1 stap
robotArm.moveLeft()
loopC = loopC + 1
else: # Als het niet 'red' is dan laat hij de kubus vallen en gaat het naar rechts
robotArm.drop()
robotArm.moveRight()
positie = positie + 1 # De positie gaat hier ook vooruit
loopA = loopA + 1
# Na jouw code wachten tot het sluiten van de window:
robotArm.wait()
|
def newtroot():
pass
#ask user for a positive number
num = float(input("Give me a positive number " ))
#Ask the user to guess the square root of the number...
guess = float(input("guess the square root "))
guess2 = ((num / guess) + guess) / 2
guess3 = ((num / guess2) + guess2) / 2
guess4 = ((num / guess3) + guess3) / 2
guess5 = ((num / guess4) + guess4) / 2
guess6 = ((num / guess5) + guess5) / 2
print(round(guess6, 2))
|
from datetime import date
class Person(object):
def __init__(self, name, year_of_birth):
self.name = name
self.year_of_birth = year_of_birth
@property
def age(self):
age = date.today().year - self.year_of_birth
return age
|
i=int(input())
if ( i%4==0 and i%100!=0 ) or (i%400==0 ) :
print('yes')
else:
print('no')
|
i=sorted("kabali")
i=str(i)
o=int(input())
a=list()
count=0
for j in range(0,o):
u=str(input())
u=sorted(u)
u=str(u)
a.append(u)
for h in a:
if h in i:
count+=1
print(count)
|
"""
Author : VILLIN Victor .
Date : 2020-06-02 .
File : q1.py .
Description : None
Observations : None
"""
# == Imports ==
import itertools
# =============
def prime_numbers(max):
"""
:param max: max>2 , maximum prime value to find, from 0
:return: list of all primes < max
"""
assert max > 1
primes = []
for i in range(2, max):
is_prime = True
for j in range(2, int(i**0.5)+1):
if i % j == 0:
is_prime = False
break
if is_prime:
primes.append(i)
return primes
def subsets(s, n):
"""
:param s: original set
:param n: size of the subsets
:return: all subsets of s, of size n
"""
return itertools.combinations(s, n)
def all_possible_subsets(s):
for i in range(len(s)//2+1):
print('building possible sets...', i)
yield subsets(s, i+1)
def compute_absolute_difference(SA, SB):
return abs(sum(SA)-sum(SB))
def exercice1():
S = set(prime_numbers(100))
min_diff = None
for possible_subsets in all_possible_subsets(S):
for p in possible_subsets:
Sa = set(p)
Sb = S.difference(Sa)
diff = compute_absolute_difference(Sa, Sb)
if min_diff is None or min_diff > diff:
print(Sa, Sb, diff)
min_diff = diff
return min_diff
if __name__ == '__main__':
result = exercice1()
print(result)
"""
Exercice 1 : 0 is the minimum possible distance, with
Sa = {97, 67, 3, 71, 41, 79, 83, 89}
Sb = {2, 5, 37, 7, 73, 11, 43, 13, 47, 17, 19, 61, 53, 23, 59, 29, 31}
"""
|
from sympy import *
import sympy
def area():
theta = sympy.Symbol('theta', real = True)
p1 = (5*cos(2*theta), 5*sin(2*theta))
p2 = (10*cos(theta), 10*sin(theta))
a = (2, 0)
tri = sympy.geometry.Polygon(p1, p2, a)
max_area = 0
s_diff = sympy.solve(sympy.diff(tri.area, theta))
# print(s_diff)
for s in s_diff:
if max_area < tri.area.subs(theta, s):
max_area = tri.area.subs(theta, s)
return max_area
if __name__ == "__main__":
print("The max value of the area is " + str(area()))
|
# Problem 2
from math import sqrt, sin, cos, pi
# Initialize points at T = 0
O = [0, 0]
A = [2, 0]
P1 = [5, 0]
P2 = [10, 0]
# Return coordinates of the rotated point regarding the parameter "angle"
def rotate(point, angle):
rotated_point = [point[0]*cos(angle) - point[1]*sin(angle), point[1]*sin(angle) + point[0]*sin(angle)]
return rotated_point
# Return the area of the triangle composed by A, P1 and P2 regarding their rotation around O
def triangleArea(A, newP1, newP2):
x1, y1, x2, y2, x3, y3 = A[0], A[1], newP1[0], newP1[1], newP2[0], newP2[1]
return abs(0.5 * (((x2-x1)*(y3-y1))-((x3-x1)*(y2-y1))))
# Return the maximum value of the area ΔA,P1,P2
def findMaxArea(A, P1, P2, step):
max_area = triangleArea(A, P1, P2)
for i in range(0, step):
angle = i*2*pi/step
newP1 = rotate(P1, 2*angle)
newP2 = rotate(P2, angle)
new_area = triangleArea(A, newP1, newP2)
if new_area > max_area:
max_area = new_area
return max_area
step = 1*10**5
print("Max value of the area is : ", findMaxArea(A, P1, P2, step))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 31 22:47:08 2021
@author: m.yuta
"""
import sympy as sym
theta = sym.Symbol("theta", real=True)
#Aの座標を定義
A_x = 2
A_y = 0
#P1,P2の各座標をthetaを用いて定義
P1_x = 5 * sym.cos(2*theta)
P1_y = 5 * sym.sin(2*theta)
P2_x = 10 * sym.cos(theta)
P2_y = 10 * sym.sin(theta)
#A,P1,P2からなる三角形の面積S
S = ((P1_x - A_x)*(P2_y - A_y)- (P1_y - A_y)*(P2_x - A_x))/2
#Sの式をsym.trigsimpを用いて簡略化
S = sym.trigsimp(S)
#Sを微分して極値をとるθを求める
dS = sym.diff(S,theta)
theta_candidate = sym.solve(dS,theta)
#Sの式では絶対値を考慮していないのでθの解候補を代入して最大値を求める
theta_answer = []
for thetas in theta_candidate:
x = S.subs(theta,thetas)
theta_answer.append(x)
theta_answer = sym.trigsimp(max(theta_answer))
print('Max area of AP_1P_2:',theta_answer)
|
nums = [4, 8, 15, 69, 16, 23, 42]
print("The smallest number in this list is:", min(nums))
#SOLVED
|
def main():
#Disclaimers#
print("----------------------------------------")
print("----CSGO Trade up Profit Calculator-----")
print("------Author: Piotr Rajchel, 2020-------")
print("--------------Ver.1.0-------------------\n")
print("This program will tell you the percentage\nof profitability a trade"
+ "-up contract has\nbased on your inputs.\n")
print("Information to keep in mind:\n")
print("1. This program takes in limited inputs,\nplease don't include symbols"
+ " such as $\nor % when entering numbers. Both should\nbe in ##.##"
+ " format.\n")
print("2. To find out how much each item costs\nand yields for being sold,"
+ " check the\nsteam market for the most current values.\nThis program"
+ " will account for the market\ntax, so just enter the number that's\n"
+ "listed per item.\n")
print("3. To get the chances for profit or loss,\nuse a tradeup site such"
+ " as\nhttps://csgo.exchange/contract/tradeup.\n(Make sure to select"
+ " New Theory Method)\nRemember the steam prices"
+ " of each of these\nitems relative to their chance, because\nthe chance"
+ " will be asked after the list of\nprices is input.\n")
#Program Loop#
primary_loop = True
while primary_loop == True:
#Variable & Import Setup#
import random
cost = 0
total_cost = 0
profits = []
profits_chances = []
losses = []
losses_chances = []
totals = 0
primary_loop_check = ""
#Cost#
print("-----------------Costs------------------")
print("Enter the cost of each skin you will input. ")
for i in range(10):
cost += eval(input(str(i+1) + ".: "))
print("Total cost for one contract would be $%.2f" % cost)
print("----------------------------------------\n")
#Profit and Loss Lists#
print("------------Profits & Losses------------")
print("How many outcomes (skins) are there?")
outcomes = eval(input("# of Possible Outcomes: "))
positive_outcomes = eval(input("How many are profitable?: " ))
negative_outcomes = outcomes - positive_outcomes
print("Enter the prices of the skins you profit from.")
for i in range(positive_outcomes):
profits.append(eval(input(str(i+1) +".: ")))
print("Enter the prices of the skins you lose from.")
for i in range(negative_outcomes):
losses.append(eval(input(str(i+1) +".: ")))
print("----------------------------------------\n")
#Chance Inputs#
print("----------------Chances-----------------")
print("Enter the chances for each of those results.")
print("(They will be displayed in the order you entered them.)")
for i in range(len(profits)):
profits_chances.append(eval(input("Chance of getting the item with a value of $"+str(profits[i])+"?\n")))
for i in range(len(losses)):
losses_chances.append(eval(input("Chance of getting the item with a value of $"+str(losses[i])+"?\n")))
print("----------------------------------------\n")
#Applying Steam Market Tax to Profit and Loss List#
for i in range(len(profits)):
profits[i] *= .95
for i in range(len(losses)):
losses[i] *= .95
#Conversion to Large Scale for Probability#
#The formula takes each possibility and makes it a portion of 10,000, then it can run properly.
for i in range(len(profits_chances)):
if i == 0:
profits_chances[i] *= 100
else:
profits_chances[i] *= 100
profits_chances[i] += profits_chances[i-1]
for i in range(len(losses_chances)):
if i == 0:
losses_chances[i] *= 100
losses_chances[i] += profits_chances[len(profits_chances)-1]
else:
losses_chances[i] *= 100
losses_chances[i] += losses_chances[i-1]
#Contracts#
print("---------------Contracts----------------")
loop_count = eval(input("Enter a number of times to run the contract:"))
print("...Running " + str(loop_count) + " Contracts...")
for i in range(loop_count):
total_cost += cost #Increase the cost for every contract run.
outcome = random.randrange(1,losses_chances[-1]) #This is the result number.
for x in range(len(profits_chances)):
if x == 0:
if outcome > 0 and outcome <= profits_chances[x]:
totals += profits[x]
elif outcome > profits_chances[x-1] and outcome <= profits_chances[x]:
totals += profits[x]
for y in range(len(losses_chances)):
if y == 0:
if outcome > profits_chances[-1] and outcome <= losses_chances[y]:
totals += losses[y]
elif outcome > losses_chances[y-1] and outcome <= losses_chances[y]:
totals += losses[y]
print("..." + str(loop_count) + " Contracts completed...")
print("----------------------------------------\n")
#Results for Profitability#
print("-------------Profitability--------------")
print("The total amount spent: $%.2f" % total_cost + ".")
print("The total from the contracts was: $%.2f" % totals + ".\n")
print("The Profitability percentage for this trade-up is: %.2f" %(((totals-total_cost)/total_cost)*100) +"%.")
print("----------------------------------------\n")
#Program Repeat?#
while (primary_loop_check != "y" and primary_loop_check != "n"):
print("Would you like to run the program again? (y/n)")
primary_loop_check = input("")
if primary_loop_check == "y":
primary_loop = True
elif primary_loop_check == "n":
primary_loop = False
print("Thanks for visiting!")
main()#Run main
|
T = int(input())
for i in range(T):
N = int(input())
for j in range(2, N//2+1):
if (N%j==0):
print("no")
break
elif (j==N//2):
print("yes")
|
import time
# WEEK 1
# Week 1 Assignment1
'''
6.5 Write code using find() and string slicing (see section 6.10) to extract the
number at the end of the line below. Convert the extracted value to a floating
point number and print it out.
'''
text = "X-DSPAM-Confidence: 0.8475"
numf = text[text.find('0'):text.find('5')]
# print(float(numf))
# WEEk 3
# Week 3 Assignment # 1
'''
7.1 Write a program that prompts for a file name, then opens that file and reads
through the file, and print the contents of the file in upper case. Use the file
words.txt to produce the output below.
You can download the sample data at http://www.pythonlearn.com/code/words.txt
'''
def inputCheck():
file = input("Enter the file name: ")
# Exceptional handling
try:
txt = open(file,'r')
return txt
except:
print('File Not found')
return inputCheck()
# txt = inputCheck()
# readable_txt = txt.read()
# print(readable_txt.upper())
# Week 3 Assignment # 2
'''
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and
compute the average of those values and produce an output as shown below. Do
not use the sum() function or a variable named sum in your solution.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
'''
def check_input():
file = input(' Enter the file name: ')
# Control over user input
try:
txt = open(file)
return txt
except:
print('File does not exists')
return check_input()
txt = check_input()
no_items = 0
sum_items = 0
for line in txt:
if line.startswith("X-DSPAM-Confidence:"):
no_items += 1
start = line.find('X-DSPAM-Confidence: ')
end = line.find('/n')
# Bcz start line is same so i add the length of the start. and start after that
found = line[start+20:end]
sum_items += float(found)
avg = sum_items / no_items
print(f'Total number of items: {no_items}')
print(f'Sum of the items: {sum_items}')
print(f'Average of the items: {avg}')
|
"""
Specify number of players
Size of Action Sets
Number of turns
Simultaneous or Sequential Decisions
"""
from random import choice
#TODO: register moves for player,
class Game:
""" A Generalised N-Player, M-Move, K-Turn Game """
def __init__(self, players=1, moves=2, turns=1, preconditions=None, name=None):
assert(players >= 1)
assert(moves >= 2)
assert(turns >= 1)
self.name = name
self.players = players
self.moves = moves
self.turns = turns
#The entry conditions for the game
self.preconditions = preconditions
#The decision tree of actions
self.decision_tree = {}
#The registered actions:
#Action keys are the position tuple (player, move, turn)
#Action values are strings to format then assert
self.actions = {}
#A Mapping for actions to query to get a value,
#used to decide actions
#Key: position tuple
#value: a working memory query for a single value
self.precondition_utility = {}
def __call__(self, working_memory=None, data=None):
""" Run the Game with the provided working_memory to query,
and a mapping of players. Return a sequence of moves.
Returns: [ MoveString ]
"""
if working_memory is None:
return self.play_random(data=data)
else:
return self.play_with_assessments(working_memory, data)
def generate_tree(self):
""" Generate the decision tree from the players, moves, and turns, independent of the actions """
raise NotImplementedError()
def register_action(self, action, positionTuple, query=None):
""" Register an action with a location of the tuple (player, move, turn) """
assert(len(positionTuple) >= 2)
#Auto-add turn if necessary
if len(positionTuple) == 2:
positionTuple = (positionTuple[0], positionTuple[1], 0)
self.actions[positionTuple] = action
self.precondition_utility[positionTuple] = query
def register_player_actions(self, player, actions):
""" Register a players actions. Specify all moves for a turn, then move to the next turn """
assert(len(actions) == (self.moves * self.turns))
move = 0
turn = 0
for action in actions:
precon = None
if isinstance(action, tuple) and len(action) == 2:
action, precon = action
self.register_action(action, (player, move, turn), query=precon)
move += 1
move = move % self.moves
if move == 0:
turn += 1
def register_turn_actions(self, turn, actions):
""" Register a turns actions. Specify all the moves for a player, then
move to the next player. Moves can be tuples of (move, precondition) """
assert(len(actions) == (self.players * self.moves))
player = 0
move = 0
for action in actions:
precon = None
if isinstance(action, tuple) and len(action) == 2:
action, precon = action
self.register_action(action, (player, move, turn), query=precon)
move += 1
move = move % self.moves
if move == 0:
player += 1
def verify(self):
""" Verify that each move for each player has been defined """
total_moves = self.players * self.moves * self.turns
enough_moves_defined = len(self.actions) == total_moves
enough_preconditions_defined = True
if bool(self.precondition_utility):
enough_preconditions_defined = len(self.precondition_utility) == total_moves
return enough_moves_defined and enough_preconditions_defined
def play_random(self, data=None):
""" Play a sequenece of the game, randomly/without value judgements or queries,
but will format output based on the input data dict
"""
assert(data is None or isinstance(data, dict))
if data is None:
data = {}
results = []
for turn in range(self.turns):
for player in range(self.players):
options = [self.actions[(player, i, turn)] for i in range(self.moves)]
chosen_action = choice(options)
results.append(chosen_action.format(**data))
return results
def play_with_assessments(self, working_memory, data=None):
""" Play a sequence of the game, using max utility selection,
will format any query or action by the data dictionary passed in.
"""
assert(hasattr(working_memory, "query"))
assert(data is None or isinstance(data, dict))
if data is None:
data = {}
results = []
for turn in range(self.turns):
for player in range(self.players):
moves = [self.actions[(player, i, turn)] for i in range(self.moves)]
queries = [self.precondition_utility[(player, i, turn)] for i in range(self.moves)]
#run the queries here
values = [working_memory.query(x.format(**data)) for x in queries]
combined = zip(values, moves)
results.append(max(combined)[1].format(**data))
return results
def enter(self, working_memory):
""" Passed a working_memory that is queryable, return whether this game is currently playable """
assert(hasattr(working_memory, "query"))
return bool(working_memory.query(self.preconditions))
|
"""
Defintions for Core Transform Operators
"""
from re import sub
from acab.abstract.rule.transform import TransformOp
class RegexOp(TransformOp):
def __init__(self):
super().__init__()
def __call__(self, value, pattern, replacement, data=None, engine=None):
""" Substitute value pattern with value value from passed in data
value : the replacement
pattern: the pattern
sub(pattern, replacement, string, count, flags)
"""
return sub(pattern, replacement, value)
class FormatOp(TransformOp):
def __init__(self):
super().__init__()
def __call__(self, value, data=None, engine=None):
""" Use str.format variant with value data dictionary
Replaces variables in the string with bound values
"""
return value.format(**data)
|
def has_number(n: int):
def _has_number(i: int):
for j in map(int, str(i)):
if n == j:
return True
return False
return _has_number
def is_divisible_by(n: int):
def _is_divisible_by(i: int):
return 0 == i % n
return _is_divisible_by
def fizzbuzz(n: int):
for i in range(1, n+1):
to_print = ''
if is_divisible_by(3)(i) or has_number(3)(i):
to_print += 'Fizz'
if is_divisible_by(5)(i) or has_number(5)(i):
to_print += 'Buzz'
if '' == to_print:
to_print = i
print(to_print)
|
# -*- coding utf-8 -*-
from stack import Stack
from queue_ import Queue
class Graph(object):
def __init__(self, initial_graph=None):
'''Pass in a graph in the form of a dictionary with the nodes as
key, and a dictoinary containing edges as keys and wieghts as values
{1:{2:100, 3:299},
2:{},
3:{1:150}}
'''
if initial_graph is None:
self.graph = {}
elif isinstance(initial_graph, dict):
self.graph = initial_graph
else:
raise TypeError("Please pass a dictionary")
def __iter__(self):
return iter(self.graph)
def nodes(self):
'''return a list of all nodes in the graph'''
# return self.depth_first_traversal(self.graph)
return list(self.graph.keys())
def edges(self):
'''returns a list of tuples, that are edges'''
return self.graph.values()
def add_node(self, n):
'''takes node and adds it to the graph'''
if self.graph.setdefault(n, {}):
raise ValueError('Node already exists please try again')
def add_edge(self, n1, n2, w):
'''adds a new edge to the graph connecting n1 and n2, if either
# n1 or n2 are not already present in the graph, they are added.
Does not allow an Edge weight to be updated.
'''
# import pdb; pdb.set_trace()
self.graph.setdefault(n2, {})
self.graph.setdefault(n1, {})
self.graph[n1].setdefault(n2, w)
def del_node(self, n):
'''deleates node n'''
if n in self.graph.keys():
self.graph.pop(n)
else:
raise ValueError('That node does not exist')
def del_edge(self, n1, n2):
'''deletes the edge connecting n1 and n2 from the graph,
raises an error if no such edge exists'''
if (n1 in self.graph) and (n2 in self.graph):
del(self.graph[n1][n2])
else:
raise ValueError('That node does not exist')
def has_node(self, n):
'''True if node n is contained in the graph, False if not.'''
return n in self.graph
def neighbors(self, n):
'''returns the dictionary of edges connected to n {2: 100, 3: 299},
raises an error if n is not in graph'''
if n in self.graph:
return self.graph[n]
else:
raise ValueError('The node you passed does not exist')
def adjacent(self, n1, n2):
'''returns True if there is an edge connecting n1 and n2, False if not,
raises an error if either of the supplied nodes are not in graph'''
if (n1 in self.graph) and (n2 in self.graph):
return n2 in self.graph[n1]
else:
raise ValueError('One or both of the nodes you passed does not exist')
def _traverse(self, start, add, remove, size):
'''Traverse function
takes in other functions and a start_node'''
result = []
add(start)
while size():
curser = remove()
if curser not in result:
result.append(curser)
for neighbor in self.graph[curser]:
add(neighbor)
return result
def depth_first_traversal(self, start_node):
'''perform a depth first traversal, returns a list of
nodes in the graph
'''
s = Stack()
return self._traverse(start_node, s.push, s.pop, s.size)
def breadth_first_traversal(self, start_node):
'''perform a breadth first traversal, returns a list of
nodes in the graph
'''
q = Queue()
return self._traverse(start_node, q.enqueue, q.dequeue, q.size)
if __name__ == '__main__':
from datetime import datetime
g = Graph({1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [], 5: [], 6: [], 7: []})
print('\n\nRun Depth First and Breadth First Traversal\n'
'100,000 times each on the following graph')
message = '''
0
/ \\
2 3
/ \\ / \\
4 5 6 7
'''
print(message)
now = datetime.now()
for i in range(100000):
result = g.depth_first_traversal(1)
runtime = datetime.now() - now
print('Depth First Traversal : {} Run time: {}'.format(result, runtime))
for i in range(100000):
result = g.depth_first_traversal(1)
runtime = datetime.now() - now
print('Breadth First Traversal: {} Run time: {}'.format(result, runtime))
|
# -*- coding utf-8 -*-
END_OF_WORD = '$'
class Node(object):
"""Node object. Has a value and a list of nodes that could come next."""
def __init__(self, value=None):
"""
Each node will contain the letter at that node and a list of
node that come next.
"""
self.value = value
self.next_let = []
def __eq__(self, other):
"""Allow nodes to compare and check if a letter is in next list."""
return self.value == other
def _insert(self, word):
"""
Will insert a letter into the list of letters that come next.
The remaining part of the word to the next node.
"""
try:
letter = Node(word[0])
except IndexError:
if END_OF_WORD not in self.next_let:
self.next_let.append(Node(END_OF_WORD))
return
if letter not in self.next_let:
self.next_let.append(letter)
idx = self.next_let.index(letter)
self.next_let[idx]._insert(word[1:])
def _contains(self, word):
"""
Check to see if the letter is in next.
Passes the remaining part of the word to the next node.
"""
try:
letter = word[0]
except IndexError:
if END_OF_WORD in self.next_let:
return True
else:
return False
if letter in self.next_let:
idx = self.next_let.index(letter)
return self.next_let[idx]._contains(word[1:])
else:
return False
def _traversal(self, word='', start=''):
"""
Generate a list of words strings below the current node.
strings will start with the start sting
"""
if start:
next_letter = start[0]
if next_letter in self.next_let:
start = start[1:]
try:
word += self.value
except TypeError:
pass
idx = self.next_let.index(next_letter)
for item in self.next_let[idx]._traversal(word, start):
yield item
else:
StopIteration
else:
if self.value == END_OF_WORD:
yield word
else:
try:
word += self.value
except TypeError:
pass
for node in self.next_let:
for item in node._traversal(word):
yield item
class Trie(object):
"""Trie class. Has an a pointer to first_node."""
def __init__(self):
"""Initalize trie so first_node is empty."""
self.first_node = Node()
def insert(self, word):
"""Insert a given word to the first_node."""
self.first_node._insert(word)
def contains(self, word):
"""Check to see if a word starts from the first node."""
return self.first_node._contains(word)
def traversal(self, start=None):
"""Will return all words in a tree with a given start string."""
for item in self.first_node._traversal(start=start):
yield item
def load(self, load_list):
"""Takes a list of words and loads the trie trie with those words."""
for word in load_list:
self.insert(word)
|
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return repr((self.x, self.y))
def distance(point1, point2):
return sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2)
def min_point_pair_2d(points, low, high):
if high == low + 1:
return points[low], points[high], distance(points[low], points[high])
elif high == low + 2:
dis1 = distance(points[low], points[low + 1])
dis2 = distance(points[low], points[low + 2])
dis3 = distance(points[low + 1], points[low + 2])
if dis1 <= dis2 and dis1 <= dis3:
return points[low], points[low + 1], dis1
elif dis2 <= dis3 and dis2 <= dis1:
return points[low], points[low + 2], dis2
elif dis3 <= dis1 and dis3 <= dis2:
return points[low + 1], points[low + 2], dis3
else:
mid = (high + low) // 2
left_po1, left_po2, left_dis = min_point_pair_2d(points, low, mid)
right_po1, right_po2, right_dis = min_point_pair_2d(points, mid + 1, high)
if left_dis <= right_dis:
pos1 = left_po1
pos2 = left_po2
dis = left_dis
else:
pos1 = right_po1
pos2 = right_po2
dis = right_dis
points_temp = []
for i in range(mid, low - 1, -1):
if points[mid].x - points[i].x <= dis:
points_temp.append(points[i])
for i in range(mid + 1, high + 1):
if points[i].x - points[mid].x <= dis:
points_temp.append(points[i])
points_temp.sort(key=lambda point: point.y)
for i in range(len(points_temp)):
for j in range(i + 1, len(points_temp)):
if points_temp[j].y - points_temp[i].y > dis:
break
elif points_temp[i].x <= mid and points_temp[j].x <= mid:
continue
elif points_temp[i].x > mid and points_temp[j].x > mid:
continue
else:
cross_dis = distance(points_temp[i], points_temp[j])
if cross_dis < dis:
pos1 = points_temp[i]
pos2 = points_temp[j]
dis = cross_dis
return pos1, pos2, dis
def main():
n = 10
points = []
for i in range(n):
a, b = input().split()
points.append(Point(float(a), float(b)))
points.sort(key=lambda point: point.x)
pos1, pos2, dis = min_point_pair_2d(points, 0, len(points) - 1)
print(pos1.x, pos1.y)
print(pos2.x, pos2.y)
print(dis)
if __name__ == '__main__':
main()
|
# o(n)
from collections import defaultdict
def counting_sort(a, key=lambda x: x):
b, c = [], defaultdict(list)
for x in a:
c[key(x)].append(x)
for k in range(min(c), max(c) + 1):
b.extend(c[k])
return b
def main():
seq = [1, 5, 3, 4, 5, 1000, 2]
seq = counting_sort(seq)
print("".join(str(seq)))
if __name__ == '__main__':
main()
|
# coding=utf-8
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
Mid = Point(0, 0)
def quad(point):
"""确定象限"""
if point.x >= 0 and point.y >= 0:
return 1
elif point.x <= 0 and point.y >= 0:
return 2
elif point.x <= 0 and point.y <= 0:
return 3
elif point.x >= 0 and point.y <= 0:
return 4
def partition(seq):
pi, seq = seq[0], seq[1:]
low = []
high = []
for i in seq:
if compare(i, pi):
low.append(i)
else:
high.append(i)
return low, pi, high
def quick_sort(seq):
if len(seq) <= 1: return seq
low, pi, high = partition(seq)
return quick_sort(low) + [pi] + quick_sort(high)
def compare(point_p, point_q):
point1 = Point(point_p.x - Mid.x, point_p.y - Mid.y)
point2 = Point(point_q.x - Mid.x, point_q.y - Mid.y)
one = quad(point1)
two = quad(point2)
if one != two:
return one < two
return point1.x * point2.y > point2.x * point1.y
def orientation(point_a, point_b, point_c):
"""Checks whether the line is crossing the polygon"""
res = (point_b.x - point_a.x) * (point_c.y - point_a.y) - \
(point_c.x - point_a.x) * (point_b.y - point_a.y)
if res == 0:
return 0
elif res > 0:
return 1
else:
return -1
def merge(points_a, points_b):
n1 = len(points_a) # number of points in polygon a
n2 = len(points_b) # number of points in polygon b
max_a = 0
# find rightmost point of a
for i in range(1, n1):
if points_a[max_a].x < points_a[i].x:
max_a = i
max_b = 0
# find leftmost point of b
for i in range(1, n2):
if points_b[max_b].x > points_b[i].x:
max_b = i
up_index_a = max_a
up_index_b = max_b
done = 1
while done:
# finding the upper tangent
done = 0
while orientation(points_a[up_index_a], points_b[up_index_b], points_b[(up_index_b - 1 + n2) % n2]) >= 0:
up_index_b = (up_index_b - 1 + n2) % n2
while orientation(points_b[up_index_b], points_a[up_index_a], points_a[(up_index_a + 1) % n1]) <= 0:
up_index_a = (up_index_a + 1) % n1
done = 1
low_index_a = max_a
low_index_b = max_b
done = 1
while done:
# finding the lower tangent
done = 0
while orientation(points_a[low_index_a], points_b[low_index_b], points_b[(low_index_b + 1) % n2]) <= 0:
low_index_b = (low_index_b + 1) % n2
while orientation(points_b[low_index_b], points_a[low_index_a], points_a[(low_index_a - 1 + n1) % n1]) >= 0:
low_index_a = (low_index_a - 1 + n1) % n1
done = 1
res = []
res.append(points_a[up_index_a])
while up_index_a != low_index_a:
up_index_a = (up_index_a + 1) % n1
res.append(points_a[up_index_a])
res.append(points_b[up_index_b])
while up_index_b != low_index_b:
up_index_b = (up_index_b - 1 + n2) % n2
res.append(points_b[up_index_b])
return res
def brute(points):
res = []
s = set()
for i in range(len(points)):
for j in range(i + 1, len(points)):
x1 = points[i].x
y1 = points[i].y
x2 = points[j].x
y2 = points[j].y
a1 = y1 - y2
b1 = x2 - x1
c1 = x1*y2 - x2*y1
pos = 0
neg = 0
k = 0
while k < len(points):
if a1*points[k].x + b1*points[k].y + c1 >= 0:
pos += 1
if a1*points[k].x + b1*points[k].y + c1 <= 0:
neg += 1
if pos == len(points) or neg == len(points):
if i not in s:
s.add(i)
res.append(points[i])
if j not in s:
s.add(j)
res.append(points[j])
k += 1
global Mid
Mid = Point(0, 0)
for i in res:
Mid.x += i.x
Mid.y += i.y
i.x *= len(res)
i.y *= len(res)
res = quick_sort(res)
for i in res:
i.x /= len(res)
i.y /= len(res)
return res
def divide(points):
if len(points) <= 5:
return brute(points)
mid = len(points) // 2
left = points[:mid]
right = points[mid:]
left = divide(left)
right = divide(right)
return merge(left, right)
def main():
n = int(input())
points = []
for i in range(n):
a, b = input().split()
points.append(Point(float(a), float(b)))
points.sort(key=lambda point: point.x)
print("After sorted:")
for i in points:
print(i.x, i.y)
points = divide(points)
print("convex:")
for i in points:
print(i.x, i.y)
if __name__ == '__main__':
main()
|
# Exercise 2
vowels = ['a', 'e', 'i', 'o', 'u']
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
inputStr = input()
vowelsNum = 0
digitsNum = 0
digitsSum = 0
repeatedCharDict = {}
for i in range(len(inputStr)):
character = inputStr[i]
charNum = 1
if character.lower() in vowels:
vowelsNum += 1
if character in numbers:
digitsNum += 1
digitsSum += int(character)
for j in range(i+1,len(inputStr)):
if inputStr[j] == character:
charNum += 1
if charNum > 1 and character not in repeatedCharDict:
repeatedCharDict[character] = charNum
print("Vowels:", vowelsNum)
print("Digits:", digitsNum)
print("Sum of digits:", digitsSum)
print(repeatedCharDict)
|
number = int(input())
for i in range(1,number*2):
if i <=number:
print("*" * i)
else:
print("*" * (number*2 -i))
|
# adding a class as super class for class Z and A
class T:
def do_job(self,**kwargs):
# do nothing actually
pass
class A(T):
def do_job(self,**kwargs):
super().do_job(**kwargs)
print('I am walking ...')
class Z(T):
def do_job(self, n,**kwargs):
super(Z, self).do_job(**kwargs)
print(f'I am counting from 1 to {n}: {list(range(1, n + 1))}')
class B(A):
def do_job(self, s,**kwargs):
super().do_job(**kwargs)
print(f'I am printing your string : "{s}"')
class C(A,Z):
def do_job(self,**kwargs):
super().do_job(**kwargs)
print('I am jumping ...')
class D(B):
def do_job(self,**kwargs):
super().do_job(**kwargs)
print('I am speaking ...')
class E(D, C):
def do_job(self,**kwargs):
super().do_job(**kwargs)
print('I am laughing ...')
class F(Z,B):
def do_job(self,**kwargs):
super().do_job(**kwargs)
# goes to z with super
print('I am playing ...')
obja = A()
obja.do_job()
print()
objz = Z()
objz.do_job(3)
# print(E.__mro__)
# print(F.__mro__)
print()
obje = E()
my_dict1={"n":5,"s":"Python"}
obje.do_job(**my_dict1)
print()
objf = F()
my_dict2={"n":6,"s":"Python"}
objf.do_job(**my_dict2)
|
# inputStr = list(input())
#
#
# def sumdigit(inputStr):
# while len(inputStr) > 1:
# result = sum(map(int, inputStr))
# inputStr = list(str(result))
# return int(inputStr[0])
#
#
# print(sumdigit(inputStr))
# ----------------------------------------------------------------------
# number = int(input())
#
#
# def fibonatchi(number):
# initialList = [1, 1]
#
# for i in range(number - 2):
# print(initialList)
# initialList.append(initialList[-1] + initialList[-2])
# print(initialList)
#
# fibonatchi(number)
|
def beautiful_num():
my_bool=True
counter = 1
my_num = 0
number=int(input())
while my_bool:
my_num +=counter
if(number_of_divisors(my_num)>number):
return my_num
counter +=1
def number_of_divisors(number):
return len([i for i in range(1,number+1) if number%i==0])
print(beautiful_num())
|
class IndentMaker:
def __init__(self):
self.tab_num = -1
def __enter__(self):
self.tab_num += 1
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.tab_num -= 1
if exc_type is not None or exc_val is not None or exc_tb is not None:
return True
def indent_print(self, msg):
print(self.tab_num * "\t" + msg)
with IndentMaker() as indent:
indent.indent_print('hi!')
with indent:
indent.indent_print('talk is cheap')
with indent:
indent.indent_print('show me the code ')
indent.indent_print('Torvalds')
|
# Write a procedure, shift_n_letters which takes as its input a lowercase
# letter, a-z, and an integer n, and returns the letter n steps in the
# alphabet after it. Note that 'a' follows 'z', and that n can be positive,
#negative or zero.
def shift_n_letters(letter, n):
letter = ord(letter)
total = letter + n
if total > 122:
total = 96 + (total - 122)
if total < 97:
total = 122-(96-total)
return chr(total)
#print shift_n_letters('s', 13)
#>>> f
#print shift_n_letters('a', -2)
#>>> y
#print shift_n_letters('a', -1)
#>>> z
#print shift_n_letters('s', 1)
#>>> t
#print shift_n_letters('s', 2)
#>>> u
#print shift_n_letters('s', 10)
#>>> c
#print shift_n_letters('s', -10)
#>>> i
|
# Write a procedure download_time which takes as inputs a file size, the
# units that file size is given in, bandwidth and the units for
# bandwidth (excluding per second) and returns the time taken to download
# the file.
# Your answer should be a string in the form
# "<number> hours, <number> minutes, <number> seconds"
# Some information you might find useful is the number of bits
# in kilobits (kb), kilobytes (kB), megabits (Mb), megabytes (MB),
# gigabits (Gb), gigabytes (GB) and terabits (Tb), terabytes (TB).
#print 2 ** 10 # one kilobit, kb
#print 2 ** 10 * 8 # one kilobyte, kB
#print 2 ** 20 # one megabit, Mb
#print 2 ** 20 * 8 # one megabyte, MB
#print 2 ** 30 # one gigabit, Gb
#print 2 ** 30 * 8 # one gigabyte, GB
#print 2 ** 40 # one terabit, Tb
#print 2 ** 40 * 8 # one terabyte, TB
# Often bandwidth is given in megabits (Mb) per second whereas file size
# is given in megabytes (MB).
#note: using Google unit conversions browser widget introduces rounding errors
#for best results use proper bit formula (2^x * prefix)
#print 2**20,' Mb sci notation', 1e6, 'converted notation', ((2**20)-1e6), 'difference'
#>>>1Mb is NOT 1e6 bits!
#print 2**20*8, 'MB sci notation', 8e6, 'converted notation', ((2**20*8)-8e6), 'difference'
#>>>1 MB is NOT 8e6 bits!
def bit_conversion(data,units):
if units == 'kb':
return data * 2 ** 10 #1000 # one kilobit, kb
if units == 'kB':
return data * 2 ** 10 * 8 #8000 #(22. ** 10 * 8) # one kilobyte, kB
if units == 'Mb':
return data * 2 ** 20 #1e6 #(22. ** 20) # one megabit, Mb
if units == 'MB':
return data * 2 ** 20 * 8 #8e6 #(22. ** 20 * 8) # one megabyte, MB
if units == 'Gb':
return data * 2 ** 30 #1e9 #(22. ** 30) # one gigabit, Gb
if units == 'GB':
return data * 2 ** 30 * 8 # 8e9 #(22. ** 30 * 8) # one gigabyte, GB
if units == 'Tb':
return data * 2 ** 40 #1e12 #(22. ** 40) # one terabit, Tb
if units == 'TB':
return data * 2 ** 40 * 8 #8e12 #(22. ** 40 * 8) # one terabyte, TB
from L17Q3_ConvertingSeconds import convert_seconds
def download_time(filesize,fileUnits,bandwidth,bandUnits):
fileBits = bit_conversion(filesize,fileUnits)
bandBits = bit_conversion(bandwidth,bandUnits)
time = fileBits/bandBits
#print time, 'seconds', fileBits, 'fileBits', bandBits, "bandBits"
return convert_seconds(time)
print download_time(1,'kB', 1, 'kB')
print download_time(1024,'kB', 1, 'MB')
#>>> 0 hours, 0 minutes, 1 second
print download_time(1024,'kB', 1, 'Mb')
#>>> 0 hours, 0 minutes, 8 seconds # 8.0 seconds is also acceptable
print download_time(13,'GB', 5.6, 'MB')
#>>> 0 hours, 39 minutes, 37.1428571429 seconds
print download_time(13,'GB', 5.6, 'Mb')
#>>> 5 hours, 16 minutes, 57.1428571429 seconds
print download_time(10,'MB', 2, 'kB')
#>>> 1 hour, 25 minutes, 20 seconds # 20.0 seconds is also acceptable
print download_time(10,'MB', 2, 'kb')
#>>> 11 hours, 22 minutes, 40 seconds # 40.0 seconds is also acceptable
|
# Name: James Dietz
# Date: 11/12/2012
# Comment: Fermat's PRP test.
import random
def test():
print("Program to perform the Fermat PRP test in Python.")
n = int(input("Please enter the number to test: "))
print()
prp = []
composite = 0
print("The chance of failure for the Fermat PRP test is ")
print("1/2^-k where k is the number of iterations of the test performed. ")
testStrength = int(input("How many iterations would you like to run?: "))
iterations = 0
if n % 2 == 0:
print("{0} is composite - it is divisible by two.".format(n))
exit
else:
pass
while iterations <= testStrength:
iterations += 1
base = random.randrange(1,4*testStrength)
number_to_test = base**(n-1)
if number_to_test % n == 1:
print("{0} is a base {1}-PRP.".format(n, base))
else:
composite = 1
if len(prp) > 0:
print(prp)
print("These bases threw up a false positive. \n")
else:
print("{0} is composite.".format(n))
break
if iterations == testStrength and composite == 0:
print("{0} is a PRP for bases {1}".format(n, bases))
else:
pass
test()
|
import numpy as np
#import matplotlib.plyplot as plt
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
def sigmoid(x):
return 1.0/(1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weight1 = np.random.rand(self.input.shape[1], 4)
self.weight2 = np.random.rand(4, 1)
self.y = y
self.output = np.zeros(y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weight1))
self.output = sigmoid(np.dot(self.layer1, self.weight2))
def backprop(self):
d_weights2 = np.dot(self.layer1.T, (2 * (self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2 * (self.y - self.output) * sigmoid_derivative(self.output),
self.weights2.T) * sigmoid_derivative(self.layer1)))
self.weights1 += d_weights1
self.weights2 += d_weights2
if __name__ == '__main__':
dataset = pd.read_csv('Churn_Modelling.csv')
pd.get_dummies(dataset, columns=['Gender','Geography'], drop_first=True)
dataset.head()
x = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
|
def fibo_recursion(n):
if n <= 1:
return n
else:
return(fibo_recursion(n-1) + fibo_recursion(n-2))
value = 12
if value <= 0:
print("Enter a positive integer")
else:
for i in range(value):
print(fibo_recursion(i))
|
# a)
def is_prime(n):
if n > 1:
for x in range(2,n):
if (n % x) == 0:
print(False)
break
else:
print(True)
else:
print(False)
is_prime(3)
# b)
def is_prime_dos(n):
if n == 2 or n ==3:
return print(True)
if n % 2 == 0 or n % 3 == 0:
return print(False)
i = 5
x = 2
squared = int(n ** .5) + 1
while i <= squared:
if n % i == 0:
return print(False)
i += x
x = 6 - x
return print(True)
is_prime_dos(1)
# c)
def prime_numbers(n):
prime_list = []
for number in range(1, n+1):
if all(number % i != 0 for i in range(2, number)):
prime_list.append(number)
print(prime_list)
prime_numbers(100)
# d)
def first_n_primes(n):
prime_list = []
i = 2
while len(prime_list) != n:
for number in range(2, i// 2 + 1):
if i % number == 0:
break
else:
prime_list.append(i)
i += 1
return print(prime_list)
first_n_primes(10)
|
def dequeue(self):
if(self.rear == -1):
print("Error- queue empty")
else:
out = self.queue[self.front]
self.front += 1
if(self.front > self.rear):
self.front = -1
self.rear = -1
return out
return -1
|
"""
This script uses the Vision API's label detection capabilities to find a label
based on an image's content.
To run the example, install the necessary libraries by running:
pip install -r requirements.txt
Run the script on an image to get a label, E.g.:
./label.py <path-to-image>
"""
import argparse
import base64
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from os import listdir
from os.path import isfile, join
mypath = "C:/test2\\"
myList =[]
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
f2 = open('myfile5.txt','a')
def main(photo_file):
"""Run a label request on a single image"""
credentials = GoogleCredentials.get_application_default()
service = discovery.build('vision', 'v1', credentials=credentials)
with open(photo_file, 'rb') as image:
image_content = base64.b64encode(image.read())
service_request = service.images().annotate(body={
'requests': [{
'image': {
'content': image_content.decode('UTF-8')
},
'features': [{
'type': 'LABEL_DETECTION',
'maxResults': 100
}]
}]
})
response = service_request.execute()
print(photo_file)
print(response)
label = response['responses'][0]['labelAnnotations'][0]['description']
#print('Found label: %s for %s' % (label, photo_file))
f2.write("\n" + photo_file + " - " + str(response))
for files in onlyfiles:
print(mypath+"\\"+files)
if ".db" not in files:
main(mypath+files)
f2.close()
#main("C:\image.jpg")
#if __name__ == '__main__':
# parser = argparse.ArgumentParser()
# parser.add_argument('image_file', help='The image you\'d like to label.')
# args = parser.parse_args()
# main(args.image_file)
|
# 时间片轮转
from builtins import range, len, float
class Process:
def __init__(self, name, arrive_time, serve_time, ready=False, over=False):
self.name = name # 进程名
self.arrive_time = arrive_time # 到达时间
self.serve_time = serve_time # 需要服务的时间
self.left_serve_time = serve_time # 剩余需要服务的时间
self.finish_time = 0 # 完成时间
self.cycling_time = 0 # 周转时间
self.w_cycling_time = 0 # 带权周转时间
self.response_ratio = 0
self.used_time = 0
self.ready = ready
self.over = over
self.pre_queue = 0 # 定义现在所在的队列
self.pre_queue_tb = 0
class RR:
def __init__(self, processes, time_block, running_time = 0):
self.processes = processes
self.time_block = time_block
self.running_time = running_time
def rr(self):
pre_processes = [] # running_time等于进程到达时间时会将其入队
over_processes = [] # 完成队列
flag = 0 # 记录完成的进程数
running_time = self.running_time
time_block = self.time_block
pre_processes.append(self.processes[0]) # 先将第一个进程入队
while(flag != len(self.processes)):
# 是否进程入队的优先级高于进程从队首切换到队尾的优先级?
# 执行当前队首进程,如果一个时间片内不能执行完,则放入队列尾部
# 判断时间片是否大于剩余服务时间
if time_block >= pre_processes[0].left_serve_time:
for i in range(pre_processes[0].left_serve_time):
pre_processes[0].left_serve_time -= 1
running_time += 1
for i in range(len(self.processes)):
if running_time == self.processes[i].arrive_time:
pre_processes.append(self.processes[i]) # 就绪队列进入队尾
if pre_processes[0].left_serve_time == 0:
# 计算完成时间
pre_processes[0].finish_time = running_time
# 计算周转时间
pre_processes[0].cycling_time = pre_processes[0].finish_time \
- pre_processes[0].arrive_time
# 计算带权周转时间
pre_processes[0].w_cycling_time = float(pre_processes[0].cycling_time) / \
pre_processes[0].serve_time
# 打印
print('%s 进程已完成的进程,详细信息如下:' % pre_processes[0].name)
print('进程名称:%s ,完成时间: %d ,周转时间:%d ,带权周转时间: %.2f' % (
pre_processes[0].name, pre_processes[0].finish_time,
pre_processes[0].cycling_time, pre_processes[0].w_cycling_time))
flag += 1
over_processes.append(pre_processes.pop(0)) # 进程结束从就绪队列出队进完成队列
continue # 直接结束此次循环,下面内容不执行
else: # 剩余服务时间大于一个时间片
for i in range(time_block):
pre_processes[0].left_serve_time -= 1
running_time += 1
for i in range(len(self.processes)): # 判断此时有没有就绪队列加入队尾
if running_time == self.processes[i].arrive_time:
pre_processes.append(self.processes[i])
# 一个时间片结束进程从队头切换至队尾
pre_processes.append(pre_processes.pop(0))
if __name__ == '__main__':
p1 = Process('A', 0, 3)
p2 = Process('B', 2, 6)
p3 = Process('C', 4, 4)
p4 = Process('D', 6, 5)
p5 = Process('E', 8, 2)
processes = [p1, p2, p3, p4, p5]
working = RR(processes, 1)
working.rr()
|
#!/usr/bin/python
import math
from copy import deepcopy
# function to clean outlier data of 10%
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
"""
# cleaned_data to store result
cleaned_data = []
# percent to clean
percent = 0.1
# get SSE_LIST
sse_list = [ math.pow((net_worth - pre), 2) for pre, net_worth in zip(predictions, net_worths) ]
# define a list to store the index of del value
rindex_list = []
# calculate the del value size
rlen = len(sse_list) * percent
# made a deepcopy
tlist = deepcopy(sse_list)
# get del index list(the max rlen values of sse_list), and never modify original sse_list
while len(rindex_list) < rlen:
max_sse = max(tlist)
idmax = sse_list.index(max_sse)
rindex_list.append(idmax)
tlist.remove(max_sse)
# get the clean dataset, if index is in del list, just continue
for i in range(len(net_worths)):
if i in rindex_list:
continue
cleaned_data.append((ages[i], net_worths[i], sse_list[i]))
# return result
return(cleaned_data)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.var = x
self.next = None
class Solution:
def reverseList(self, head:ListNode) ->ListNode:
pre = None
cur = head
while cur:
nextnode = cur.next
cur.next = pre
pre = cur
cur = nextnode
return pre
if __name__ == '__main__':
print("yes")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 232-用栈实现队列
from collections import deque
class Stack:
def __init__(self):
self.items = deque()
def push(self, val):
return self.items.append(val)
def pop(self):
return self.items.pop()
def top(self):
return self.items[-1]
def empty(self):
return len(self.items) == 0
class MyQueue:
def __init__(self):
self.s1 = Stack()
self.s2 = Stack()
def push(self, val):
self.s1.push(val)
def pop(self):
if not self.s2.empty():
return self.s2.pop()
while not self.s1.empty():
val = self.s1.pop()
self.s2.push(val)
return self.s2.pop()
def peek(self):
if not self.s2.empty():
return self.s2.top()
while not self.s1.empty():
val = self.s1.pop()
self.s2.push(val)
return self.s2.top()
def empty(self):
return self.s1.empty() and self.s2.empty()
if __name__ == '__main__':
s = Stack()
s.push(5)
s.push(6)
s.push(8)
print(s.items)
print(s.top())
print(s.empty())
print(s.pop())
print(s.pop())
|
# Created by: Julie Nguyen
# Created on: Oct 2017
# Created for: ICS3U
# This program is a guessing game where the user must input the number 5 (the correct number) in order to
# win
# Modified on: Oct 2017
# added an if statement, removed constant of 5 and replaced it with random integer code
import ui
from numpy import random
# random number to guess
guessed_number = random.randint(1, 10)
def check_answer_button_touch_up_inside(sender):
# checks if the user's guess was right or wrong
# input
number_entered = int(view['enter_guess_textfield'].text)
# process
global guessed_number
if number_entered == guessed_number:
#output
view['answer_label'].text = "Bingo! You are correct!"
else:
view['answer_label'].text = "Sorry, the number is " + str(guessed_number) + "!"
view = ui.load_view()
view.present('full_screen')
|
import Tkinter
from Tkinter import *
from PIL import ImageTk, Image
import tkFileDialog
import os
# Aqui capturo cual es el path del programa. Las imagenes y el .txt tienen que estar en el mismo
# directorio. Las imagenes porque las busca en este path, y el .txt en realidad solo para que
# sea mas rapido encontrarlo :P. Cuando busca el .txt lo puede buscar en cualquier lugar de la compu
mypath = os.path.dirname(os.path.realpath(__file__))
# Esto es para definir las condiciones iniciales de mis variables globales. Al inicio todo esta vacio
# data es la informacion del .txt
data = ""
# son los vectores que se van a enviar a C
vector1 = []
vector2 = []
# Es el resultado del programa de C, es un numero 0, 1, 2 o 3. Hay que verificar si los casos de
# VERY HIGH, HIGH, LOW, VERY LOW tienen sentido con lo que yo puse y lo que supuestamente tira C
input_c = 0
# Esta es la clase que abre la ventana para buscar el .txt. Se activa despues de tocar el boton.
# Adentro, si el archivo no esta vacio, guarda los datos y cambia el icono. Si no se escoge ningun
# archivo y solo se le da "cancelar", entonces el boton no hace nada.
def import_data_file():
filewindow = Tkinter.Tk()
filewindow.withdraw()
file_opened = tkFileDialog.askopenfile(parent=filewindow, mode='rb', title='Choose a file')
if file_opened is not None:
global data
data = file_opened.read()
file_opened.close()
global img_status
global status_pic
img_status = ImageTk.PhotoImage(Image.open(mypath + '/Green_check.png'))
status_pic = Tkinter.Label(App, image=img_status)
status_pic.grid(row=3, column=1, padx=230, sticky=W, columnspan=2)
# askfordata_button.config(background='green')
filewindow.destroy()
# Esta es la clase en donde tiene que adjuntarse lo de C. Aqui es donde se trabaja los datos.
# Primero separa las filas y las mete en una lista de strings, luego lo transforma a flotantes
# (no estaba segura si solo eran valores integer) y hace los vectores vector1 y vector2 que son
# los que tiene que recibir C.
def send_data_vectors():
global data
global vector1
global vector2
rows = data.split('\n')
for single in range(0, len(rows)):
if rows[single] != "":
columns = rows[single].split(',')
columns = map(float, columns)
vector1.append(columns[0])
vector2.append(columns[1])
print vector2, vector1
# Aqui va la union con C, yo puse los casos del 0-3 pero sin son del 1-4 solo hay que modificarlos
global input_c
input_c = 1
if input_c == 0:
g_result = "VERY HIGH"
if input_c == 1:
g_result = "HIGH"
if input_c == 2:
g_result = "LOw"
if input_c == 3:
g_result = "VERY LOW"
# Imprime el resultado al final de la interfaz
results_text = Label(App, fg="#4D5C64", text="Your glucose result is: " + g_result, font=("Helvetica", 12))
results_text.grid(row=5, column=0, padx=200, sticky=W, columnspan=2)
results_text.config(width=30)
# Aqui comienza la programacion de la Interfaz grafica como tal
# Este es el nombre de la caja grande que contiene toddo, (botones, etiquetas..)
App = Tkinter.Tk()
# Este es el tamanho de la caja que yo decidi
App.geometry("700x450+-10+20")
# Este es el titulo del cuadro jaja. Si quieren lo cambiamos
App.title("BGLD Application")
# Aqui abro y coloco la imagen del logo QUE HAY QUE CAMBIAR
img = Image.open(mypath+'/Intel-logo.png')
img = img.resize((250, 100), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Tkinter.Label(App, image=img)
panel.grid(padx=20, pady=25)
# Aqui abro y coloco la imagen del signo de pregunta. En la clase import_data_file() se sobreescribe
# por el check verde
img_status = Image.open(mypath+'/Question_mark.png')
img_status = ImageTk.PhotoImage(img_status)
status_pic = Tkinter.Label(App, image=img_status)
status_pic.grid(row=3, column=1, padx=230, sticky=W, columnspan=2)
# Aqui esta la programacion del texto polo jaja.
advice = Label(App, fg="#5FABD1", text="Because your health is first," + "\n" + " keep a good control of your glucose!",
font=("Helvetica", 16))
advice.grid(row=0, column=1)
# Programacion del texto que pide abrir el .txt
askfordata = Label(App, fg="#4D5C64", text="Please select the input file" + "\n" + "with your blood patron:", font=("Helvetica", 12))
askfordata.grid(row=3, column=0, sticky=W, padx=100, columnspan=2)
# Programacion del boton que pide abrir el .txt
askfordata_button = Button(App, text="Click here to search your file", width=20, command=import_data_file)
askfordata_button.grid(row=3, column=1, padx=25, sticky=W, columnspan=2)
#Programacion del boton que inicia con los calculos
askforcalc_button = Button(App, text="Click here to calculate your results", width=20, command=send_data_vectors)
askforcalc_button.grid(row=4, column=0, padx=200, pady=50, sticky=W, columnspan=2)
askforcalc_button.config(width=30)
App.mainloop()
|
SUBLIST, SUPERLIST, EQUAL, UNEQUAL = 1, 2, 3, 4
def check_lists(one, two):
if one == two:
return EQUAL
len_1 = len(one)
len_2 = len(two)
if len_1 > len_2:
for ii in range(len_1):
if one[ii:len_2+ii] == two:
return SUPERLIST
for ii in range(len_2):
if two[ii:len_1+ii] == one:
return SUBLIST
return UNEQUAL
|
GRADE_LEVELS = 9
class School:
def __init__(self, school_name):
self.db = list(map(lambda x: [], [None] * GRADE_LEVELS))
def grade(self, grade):
return self.db[grade][:]
def add(self, name, grade):
self.db[grade].append(name)
def sort(self):
return [(i, tuple(self.db[i])) for i in range(1,len(self.db)) if self.db[i]]
|
def largest_palindrome(min_factor=1, max_factor=1):
max_product = 0
data = {}
for ii in range (min_factor, max_factor+1):
for jj in range (ii, max_factor+1):
product = ii * jj
if ''.join(reversed(str(product))) == str(product):
max_product = max(max_product, product);
data[product] = { ii, jj }
return max_product, data[max_product]
def smallest_palindrome(min_factor=1, max_factor=1):
min_product = 10 ** 10
data = {}
for ii in range (min_factor, max_factor+1):
for jj in range (ii, max_factor+1):
product = ii * jj
if ''.join(reversed(str(product))) == str(product):
min_product = min(min_product, product);
data[product] = { ii, jj }
return min_product, data[min_product]
|
def doc_is_exist(directories):
""" doc_is_exist(directories)
Function for input number of document
directories: dictionary of document shelf's """
doc_number = input('\nВведите номер документа:\n')
if [doc_list
for doc_list in directories.values()
if doc_number in doc_list]:
return doc_number
else:
print('Вы ввели не существующий документ')
raise ValueError("Нет введенных данных")
def name_form_number_doc(documents, directories):
""" name_form_number_docdoc_is_exist(documents)
Function requests document's number and return owners name
documents: list of documents
directories: dictionary of document shelf's """
print('\nПоиск человека по номеру документа:')
document_number = doc_is_exist(directories)
for document in documents:
if document.get('number') == document_number:
return document.get('name')
def shelf_form_number_doc(directories):
""" shelf_form_number_doc(directories)
Function requests document's number and return shelf's think
directories: dictionary of document shelf's """
print('\nПоиск номера полки по номеру документа:')
document_number = doc_is_exist(directories)
return [shelf_number
for shelf_number, doc_number in directories.items()
if document_number in doc_number][0]
def all_document_list(documents):
""" all_document_list(documents)
Function return list of all documents
documents: list of documents """
print('Вывод списка документов')
for document in documents:
print(list(document.values()))
# print([list(doc_element.values()) for doc_element in documents])
def add_new_document(documents_dict, directories_dict):
""" add_new_document(documents_dict, directories_dict)
Function creating new documents and added in list
documents_dict: list of documents
directories_dict: dictionary of document shelf's """
print('\nДобавление нового документа\n')
doc_type = input('Введите тип документа:\n')
doc_number = input('Ввидте номер документа\n')
doc_name = input('Введите имя\n')
doc_shel = input('Введите номер полки\n')
if doc_shel not in [shelf_number
for shelf_number in directories_dict.keys()]:
print('Вы ввели номер не существующей полки\n')
raise ValueError("Не верное значение!!!")
documents_dict.append({"type": doc_type,
"number": doc_number,
"name": doc_name})
directories_dict.get(doc_shel).append(doc_number)
print('Новый документ добавлен')
return 1
def delete_document(documents, directories):
""" delete_document(documents, directories)
Function deleted document from all lists
documents: list of documents
directories: dictionary of document shelf's """
print('\nУдаление документа')
document_number = doc_is_exist(directories)
for doc_element in documents:
if document_number == doc_element.get('number'):
documents.pop(documents.index(doc_element))
break
for shelf, value in directories.items():
if document_number in value:
directories.get(shelf).remove(document_number)
break
print(f'документ с номером {document_number} был удален')
return 1
def change_shelf(directories):
"""change_shelf(directories)
Function change place of document in shelfs
directories: dictionary of document shelf's
"""
print('Перемещение документа на другую полку\n')
doc_number = doc_is_exist(directories)
doc_shelf = input(
'Введите номер полки на которую необходимо переместить документ\n')
if doc_shelf not in [shelf_number
for shelf_number in directories.keys()]:
print('Вы ввели номер не существующей полки\n')
raise ValueError("Не верное значение!")
for shelf, value in directories.items():
if doc_number in value:
directories.get(shelf).remove(doc_number)
break
directories.get(doc_shelf).append(doc_number)
print(
f'Документ с номером {doc_number} был перемещен на полку {doc_shelf}')
return 1
def add_shelf(directories):
""" add_shelf(directories)
to adding new shelfs
directories: dictionary of document shelf's
"""
print('Добавление новой полки\n')
new_shelf = input(
'Введите номер полки которую необходимо добавить\n')
if new_shelf not in [shelf_number
for shelf_number in directories.keys()]:
directories.update({new_shelf: []})
print(f'Полка {new_shelf} была добавлена')
return 1
else:
print('Вы ввели номер существующей полки, попробуйте снова\n')
raise ValueError("Не верное значение!")
documents = [
{"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
{"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
{"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
'1': ['2207 876234', '11-2'],
'2': ['10006'],
'3': []}
if __name__ == '__main__':
while True:
print('''
1: Поиск человека по номеру документа
2: Поиск номера полки по номеру документа
3: Вывод списка документов
4: Добавление нового документа
5: Удаление документа
6: Добавление новой полки
7: Перемещение документа на другую полку
8: Вывод словаря документов
9: Вывод словаря полок
0: Выход\n
''')
try:
choice = int(input('Введите номер необходимого действия: \n>> '))
except ValueError:
choice = 10
if choice == 1:
people = name_form_number_doc(documents, directories)
print(people)
elif choice == 2:
shelf = shelf_form_number_doc(directories)
print(f'Номер полки: {shelf}')
elif choice == 3:
all_document_list(documents)
elif choice == 4:
add_new_document(documents, directories)
elif choice == 5:
delete_document(documents, directories)
elif choice == 6:
add_shelf(directories)
elif choice == 7:
change_shelf(directories)
elif choice == 8:
print('Словарь документов:')
for document in documents:
print(document)
elif choice == 9:
print('Словарь полок:')
for num_shelf, num_doc in directories.items():
print(f'{num_shelf}: {num_doc}')
elif choice == 0:
exit()
else:
print('Вы ввели несуществующую команду. Попробуйте снова')
|
from ClassStack import Stack
def balanced(brackits_str: str) -> str:
balanced_stack = Stack(brackits_str)
empty_stack = Stack('')
brackits_open = ['[', '(', '{']
brackits_list = ['[]', '()', '{}']
if balanced_stack.size() % 2 != 0:
return 'Несбалансированно'
empty_stack.push(balanced_stack.pop())
for i in range(balanced_stack.size()):
if balanced_stack.peek() in brackits_open and (balanced_stack.peek() + empty_stack.peek()) in brackits_list :
balanced_stack.pop()
empty_stack.pop()
continue
elif balanced_stack.peek() in brackits_open and (balanced_stack.peek() + empty_stack.peek()) not in brackits_list:
return 'Несбалансированно'
if balanced_stack.size()+empty_stack.size() == 0:
return 'Сбалансированно'
return 'Несбалансированно'
if __name__ == '__main__':
print(balanced('[[{())}]'))
|
import sys
import pygame as pg
class Game(object):
"""
A single instance of this class is responsible for
managing which individual game state is active
and keeping it updated. It also handles many of
pygame's nuts and bolts (managing the event
queue, framerate, updating the display, etc.).
and its run method serves as the "game loop".
"""
def __init__(self, screen, states, start_state):
"""
Initialize the Game object.
screen: the pygame display surface
states: a dict mapping state-names to GameState objects
start_state: name of the first active game state
"""
self.done = False
self.screen = screen
self.clock = pg.time.Clock()
self.fps = 60
self.states = states
self.state_name = start_state
self.state = self.states[self.state_name]
self.key_status = dict()
self.mouse_status = dict()
def event_loop(self):
"""Events are passed for handling to the current state."""
for key in [x for x in self.key_status.keys()]:
if self.key_status[key] == 'released':
del self.key_status[key]
for key in [x for x in self.mouse_status.keys()]:
if self.mouse_status[key]['state'] == 'released':
del self.mouse_status[key]
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
if event.type == pg.KEYDOWN:
self.key_status[event.key] = 'pressed'
if event.type == pg.KEYUP:
self.key_status[event.key] = 'released'
if event.type == pg.MOUSEBUTTONDOWN:
self.mouse_status[event.button] = {
'state': 'pressed',
'pos': event.pos,
}
elif event.type == pg.MOUSEBUTTONUP:
self.mouse_status[event.button] = {
'state': 'released',
'pos': event.pos,
}
elif event.type == pg.MOUSEMOTION:
self.mouse_status[0] = {
'state': 'motion',
'pos': event.pos,
'rel': event.rel,
'buttons': event.buttons,
}
self.state.process_events(self.key_status, self.mouse_status)
def flip_state(self):
"""Switch to the next game state."""
current_state = self.state_name
next_state = self.state.next_state
self.state.done = False
self.state_name = next_state
persistent = self.state.persist
self.state = self.states[self.state_name]
self.state.startup(persistent)
def update(self, dt):
"""
Check for state flip and update active state.
dt: milliseconds since last frame
"""
if self.state.quit:
self.done = True
elif self.state.done:
self.flip_state()
self.state.update(dt)
def draw(self):
"""Pass display surface to active state for drawing."""
self.state.draw(self.screen)
def run(self):
"""
Pretty much the entirety of the game's runtime will be
spent inside this while loop.
"""
while not self.done:
dt = self.clock.tick(self.fps)
self.event_loop()
self.update(dt)
self.draw()
pg.display.update()
class GameState(object):
"""
Parent class for individual game states to inherit from.
"""
def __init__(self):
self.done = False
self.quit = False
self.next_state = None
self.screen_rect = pg.display.get_surface().get_rect()
self.persist = {}
self.font = pg.font.Font(None, 24)
def startup(self, persistent):
"""
Called when a state resumes being active.
Allows information to be passed between states.
persistent: a dict passed from state to state
"""
self.persist = persistent
def process_events(self, key_events, mouse_events):
"""
Handle all events passed by the Game object.
"""
pass
def update(self, dt):
"""
Update the state. Called by the Game object once
per frame.
dt: time since last frame
"""
pass
def draw(self, surface):
"""
Draw everything to the screen.
"""
pass
|
# utilizzo del loop for, molto simile al foreach di Java
nomi = ["Alberto", "Luisa", "Gianni"]
for nome in nomi:
print(nome.lower())
# python l'indentazione come carattere per la interconnessione del codice, analogo utilizzo di ; in C
# la funzione range() di python permette di creare una array con valori numerici racchiusi in un certo range,
# primo estremo incluso mentre il secondo no
for val in range(1, 101):
print(val)
# possiamo dare un altro valore alla funzione range() per indicargli l'incremento dei valori desiderati nel range
print("\n")
print("valori pari fino a 100")
for val in range(2, 101, 2):
print(val)
# possiamo salvare i valori forniti dalla funzione range() direttamente in una lista
print("\n")
num = list(range(1, 101))
print(num)
# 3 funzioni di python per il max, il min e la somma
print("max")
print(max(num))
print("min")
print(min(num))
print("sum")
print(sum(num))
squares = []
for value in range(1, 6):
squares.append(value**2)
print(squares)
# list comprehensions, concisa ma poco legibile
squares2 = [value**2 for value in range(1, 6)]
print(squares2)
# in python è possibile lavorare con alcune parti di una lista
print("\n")
print(squares2[2:4])
print(squares2[:4])
print(squares2[3:])
num = ["1", "2", "3"]
num2 = num[:]
num.append("4")
num2.append("5")
print(num)
print(num2)
print("\n*******************tuple*****************************\n")
# definzione e utilizzo delle tuple
# da notare la inizializzazione con parentesi tonde, invece di quelle quadrate (array)
dimensioni = (100, 20)
print(dimensioni[0])
print(dimensioni[1])
# dimensioni[0] = 345 ->errore, è impossibile modificare il contenuto di una tupla, è possibile però fare la dichiarazione di una nuova nella stessa variabile
dimensioni = (300, 100)
for dim in dimensioni:
print(dim)
|
''' approach #1 '''
filepath = 'last_movie.txt'
with open(filepath, 'w') as file:
print(file.write('first line'))
with open(filepath, 'r') as file:
print(file.readline())
with open(filepath, 'a') as file:
file.write('\n'+'Song')
with open(filepath, 'r') as file:
print('The last movie I watched is: ' + file.readline())
print('The last song I listened to is: ' + file.readline())
''' approach #2 '''
import os
cwd = os.getcwd()
last_movie = 'Notting Hill'
last_song = 'Woodkid - Iron'
filepath = (f'{cwd}\last_movie.txt')
with open(filepath, 'wt') as f:
f.write(''.join([last_movie,'\n']))
f.write(last_song)
with open(filepath, 'r') as f:
lines = f.readlines()
movie = lines[0].strip()
song = lines[1]
print(f'The last movie I watched is: {movie}')
print(f'The last song I listened to is: {song}')
|
# Google braille_translation.py
"""
Braille Translation
Part of the Google secret interview process
===================
Because Commander Lambda is an equal-opportunity despot, she has several visually-impaired minions. But she never bothered to follow intergalactic standards for workplace accommodations, so those minions have a hard time navigating her space station. You figure printing out Braille signs will help them, and - since you'll be promoting efficiency at the same time - increase your chances of a promotion.
Braille is a writing system used to read by touch instead of by sight. Each character is composed of 6 dots in a 2x3 grid, where each dot can either be a bump or be flat (no bump). You plan to translate the signs around the space station to Braille so that the minions under Commander Lambda's command can feel the bumps on the signs and "read" the text with their touch. The special printer which can print the bumps onto the signs expects the dots in the following order:
1 4
2 5
3 6
So given the plain text word "code", you get the Braille dots:
11 10 11 10
00 01 01 01
00 10 00 00
where 1 represents a bump and 0 represents no bump. Put together, "code" becomes the output string "100100101010100110100010".
Write a function answer(plaintext) that takes a string parameter and returns a string of 1's and 0's representing the bumps and absence of bumps in the input string. Your function should be able to encode the 26 lowercase letters, handle capital letters by adding a Braille capitalization mark before that character, and use a blank character (000000) for spaces. All signs on the space station are less than fifty characters long and use only letters and spaces.
"""
def int_to_bin(x):
"""
Converts integer to 6-bit binary string
"""
return str(bin(x)).split('b')[1].zfill(6)
def encode_braille(string):
"""
Returns 6-bit binary representation of the string translated to braille
"""
ret = ''
for char in string:
if char.isupper():
ret += eng_to_braille['cap']
char = char.lower()
ret += eng_to_braille[char]
return ret
def split_braille(braille):
"""
Returns list of braille string split to 6-bit letters
"""
return [braille[i:i+6] for i in range(0, len(braille), 6)]
def decode_braille(braille):
"""
Returns braille string translated to english
"""
braille = split_braille(braille)
ret = ''
upper = False
for char in braille:
if char == eng_to_braille['cap']:
upper = True
continue
else:
if upper:
ret += braille_to_eng[char].upper()
upper = False
else:
ret += braille_to_eng[char]
return ret
# Hardcoded dict of english to braille translations, where key = char and value = 6-bit binary representation of braille
eng_to_braille = {
'a': int_to_bin(32),
'b': int_to_bin(48),
'c': int_to_bin(36),
'd': int_to_bin(38),
'e': int_to_bin(34),
'f': int_to_bin(52),
'g': int_to_bin(54),
'h': int_to_bin(50),
'i': int_to_bin(20),
'j': int_to_bin(22),
'k': int_to_bin(40),
'l': int_to_bin(56),
'm': int_to_bin(44),
'n': int_to_bin(46),
'o': int_to_bin(42),
'p': int_to_bin(60),
'q': int_to_bin(62),
'r': int_to_bin(58),
's': int_to_bin(28),
't': int_to_bin(30),
'u': int_to_bin(41),
'v': int_to_bin(57),
'w': int_to_bin(23),
'x': int_to_bin(45),
'y': int_to_bin(47),
'z': int_to_bin(43),
' ': int_to_bin(0),
'cap': int_to_bin(1)
}
# Hardcoded dict of braille to english translations, where key = 6-bit binary representation of braille and value = char
braille_to_eng = {v:k for k,v in eng_to_braille.items()}
if __name__ == '__main__':
plaintext = "The quick brown fox jumps over the lazy dog"
# Test encoding
print(encode_braille(plaintext) == "000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110")
# Test decoding
print(plaintext == decode_braille(encode_braille(plaintext)))
|
class User:
def __init__(self, name):
self.name = name
self.movie = []
def __repr__(self):
return "<User {}>".format(self.name)
return "<User {}>".format(self.movie)
# gather the list of movies that has been watched
# itterate through the list
# then iterate through the self.movies
# if movie watched is true add it to the list
# return the list
def watched_movies:
movie_list=[]
for movie in self.movie:
if
|
import sqlite3
class Database:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS books(id integer primary key,title text,author text,year integer,isbn integer)")
self.conn.commit()
def insert_data(self,title,author,year,ISBN):
self.cur.execute("INSERT INTO books VALUES(NULL,?,?,?,?)",(title,author,year,ISBN))
self.conn.commit()
def view_data(self):
self.cur.execute("select * from books")
rows = self.cur.fetchall()
return rows
def search_data(self,title="",author="",year="",isbn=""):
self.cur.execute("select * from books where title=? or author=? or year=? or isbn=?",(title,author,year,isbn))
rows = self.cur.fetchall()
return rows
def delete_data(self,id):
self.cur.execute("delete from books where id=?",(id,))
self.conn.commit()
def update_data(self,id,title,author,year,ISBN):
self.cur.execute("update books set title=?,author=?,year=?,isbn=? where id=?",(title,author,year,ISBN,id))
self.conn.commit()
def __del__(self):
self.conn.close()
# create_table()
# insert_data("the sea","johny",2008,12345)
# print(view_data())
# print(search_data(author="john"))
# update_data(1,"The earth","harvey",1915,235654)
# print(view_data())
|
# Pre-processes the input image by removing noise and draws the contours for coloured squares in the image
"""
Team Id: HC#3266
Author List: Aman Bhat T, Hemanth Kumar M, Mahantesh R, Nischith B.O.
Filename: preprocess.py
Theme: Homecoming
Functions: preprocess
Global Variables: colour_contours, font, kernel
"""
import numpy as np
import cv2
import copy
colour_contours=0 # Number of squares with colours
font=cv2.FONT_HERSHEY_SIMPLEX
kernel = np.ones((3,3),np.uint8) # Create a filter to clean and process the image
def preprocess(image):
"""
Function name: preprocess
Input: image -> original image
Output: gray -> grayscale image of the input image
sure_fg -> sure foreground i.e. the colours in the image
img2 -> Image with the contours drawn for the colours
colour_contours -> Returns the number of contours for colours
"""
image=cv2.resize(image, (800,800)) # resizing the image to a convenient size
img = copy.deepcopy(image)
img2 = copy.deepcopy(image) # copies of the original image
# Convert to grayscale and apply suitable threshold to find contours easily
#-------------------------------------------------------------------------------
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray,250,255,0)
thresh=cv2.bitwise_not(thresh)
# noise removal
reduced_noise = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
erosion = cv2.erode(reduced_noise,kernel,iterations = 2)
# sure background area
sure_bg = cv2.dilate(erosion,kernel,iterations=3)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(erosion,cv2.DIST_L2,5)
_, sure_fg = cv2.threshold(dist_transform,0.1*dist_transform.max(),255,0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
# Marker labelling
_, markers = cv2.connectedComponents(sure_fg)
# Adding one to all labels so that sure background is not 0, but 1
markers = markers+1
# Marking the region of unknown with zero, subtracting from original image to generate only the coloured part separately
#-----------------------------------------------------------------------------------------------------------------------
markers[unknown==255] = 0
markers = cv2.watershed(img,markers)
img[markers == -1] = [0,0,0]
img3 = img-img2
img3 = cv2.dilate(img3,kernel,iterations=1)
img3 = cv2.cvtColor(img3,cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(img3,10,255,0)
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# Iterate through the contours and filter them to display ONLY COLOURED SQUARES
for i in range(len(contours)):
ctr=contours[i]
arc_length = 0.1*cv2.arcLength(ctr,True)
approx_length = cv2.approxPolyDP(ctr,arc_length,True)
area = cv2.contourArea(ctr)
if(len(approx_length==4) and hierarchy[0][i][2]==-1 and area > 600):
global colour_contours
colour_contours+=1
img2 = cv2.drawContours(img2,contours, i, (0,0,255), 3)
return gray, img2, sure_fg,colour_contours
|
#!/bin/python3
def ping_pong(n):
''' return a for-loop solution '''
res = []
for i in range(1, n+1):
print(check_value(i))
res.append(check_value(i))
return res
# def ping_pong(n):
# ''' return a generator solution '''
# value = get_value(n)
# for _ in get_value(n):
# print(next(value))
# def get_value(n):
# ''' return a for-loop solution '''
# i = 1
# while i < n:
# yield check_value(i)
# i += 1
def check_value(i):
''' return the int or the alternative string.
This is the engine of the script. '''
if i % 3 == 0:
if i % 5 == 0:
# If i is a multiple of both 3 and 5, print PingPong.
# print('PingPong')
return ('PingPong')
else:
# If i is a multiple of 3 (but not 5), print Ping.
# print('Ping')
return('Ping')
else:
if i % 5 == 0:
# If i is a multiple of 5 (but not 3), print Pong.
# print('Pong')
return('Pong')
else:
# If i is not a multiple of 3 or 5, print the value of i.
# print(i)
return(i)
def greatest(s):
''' retrive the largest word of the strig '''
s_list = s.split(' ')
res = sorted(s_list,
key=lambda item: len(item),
reverse=True)
return res[0]
if __name__ == '__main__':
# n = int(input('input a positive number: ').strip())
# ping_pong(n)
greatest('Larguissimas palabras')
|
# Flip all bits
def flip(bits):
if (len(bits) > 0):
if (bits[0] == 0):
return [1, flip(bits[1])]
else:
return [0, flip(bits[1])]
else:
return []
def main():
# Immutable list of 32 bits (zeroes)
bits = [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0, [0,[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]];
lim = 2**20
for i in range(lim):
bits = flip(bits)
#print(bits)
main()
|
class CreateStudent:
def __init__(self, Name, Surname, Password, Email, Address, conctactNumber, studentId):
self.Name = Name
self.Surname = Surname
self.Password = Password
self.Email = Email
self.Address = Address
self.conctactNumber = conctactNumber
self.studentId = studentId
print(self.Name, self.Surname, self.Password, self.Email, self.Address, self.conctactNumber, self.studentId)
class Register:
stuList = 0
def __init__(self):
self.stuList = {}
def createStudent(self):
name = input("İsminizi giriniz")
surname = input("Soyadınızı giriniz")
password = input("Şifrenizi giriniz")
email = input("Emailinizi giriniz")
address = input("Adresinizi giriniz")
concactNumber = input("Telefonun numaranızı giriniz")
studentId = input("Öğrenci numaranızı giriniz")
student = CreateStudent(name, surname, password, email, address, concactNumber, studentId)
self.studentRegister(student)
def studentRegister(self, student):
self.stuList[student] = student
print(self.stuList)
def display(self):
for item in self.stuList:
print(item.Name, item.Surname, item.Password, item.Email, item.Address, item.conctactNumber, item.studentId)
class createcourse:
classList = 0
def __init__(self,coursecode = None,coursename = None,facultycode = None,startdate= None,enddate = None):
self.coursecode = coursecode
self.coursename = coursename
self.facultycode = facultycode
self.startdate = startdate
self.enddate = enddate
self.classList = {}
print(self.coursecode,self.coursename,self.facultycode,self.startdate,self.enddate)
def courses(self):
coursecode = input("kurs kodunu giriniz")
coursename = input(("kurs adını yazınız"))
facultycode = input("fakülte kodunu giriniz")
startdate = input("kursa başlangıç tarihini giriniz")
enddate = input("kursun bitiş tarihini giriniz")
course = createcourse(coursecode, coursename, facultycode, startdate, enddate)
self.courseRegister(course)
def courseRegister(self,course):
self.classList[course] = course
print(self.classList)
def display(self):
print(self.classList)
for item in self.classList:
print(item.coursecode, item.coursename,item.facultycode,item.startdate,item.enddate)
def get_changedList(self):
coursecode = input("kurs kodunu giriniz")
coursename = input(("kurs adını yazınız"))
facultycode = input("fakülte kodunu giriniz")
startdate = input("kursa başlangıç tarihini giriniz")
enddate = input("kursun bitiş tarihini giriniz")
changedList = {
"coursecode": coursecode,
"coursename": coursename,
"coursestartdate":startdate,
"courseenddate": enddate,
"facultycode": facultycode,
}
return changedList
def modifycourse(self,coursecode, ):
changedList = self.get_changedList()
for data in self.classList:
print(f' eski kurs kodu:{data.coursecode} eski kurs adı:{data.coursename} eski kurs başlangıç tarihi:{data.startdate}eski kurs bitiş tarihi:{ data.enddate}eski kurs fakülte kodu:{data.facultycode}')
if data.coursecode == coursecode:
data.coursename = changedList.get("coursename")
data.startdate = changedList.get("startdate")
data.enddate = changedList.get("enddate")
data.facultycode = changedList.get("facultycode")
print(f'yeni kurs kodu:{data.coursecode} yeni kurs adı:{data.coursename} yeni kurs başlangıç tarihi: {data.startdate }yeni kurs bitiş tarihi:{data.enddate} yeni fakülte kodu:{data.facultycode}')
break
def removecourse(self,coursecode):
for item in self.classList:
if item.coursecode == coursecode:
print(item, " ")
print(f'{item.coursename}isimli kurs silindi')
self.classList.pop(item)
break
def menu():
selection = input("Select action")
print(selection)
return selection
selection = menu()
a = Register()
b = createcourse()
while selection != 12:
if selection == "1":
a.createStudent()
selection = menu()
if selection == "2":
a.display()
selection = menu()
if selection == "5":
b.display()
selection = menu()
if selection == "6":
b.courses()
selection = menu()
if selection == "7":
coursecode = input("hangi kursu değiştirmek istiyorsanız kodunu giriniz")
b.modifycourse(coursecode)
selection = menu()
if selection == "8":
coursecode = input("hangi kursu silmek istiyorsanız kodunu giriniz")
b.removecourse(coursecode)
selection = menu()
|
k = "ilyadaersan"
s = "abbcd"
kullanıcı = input("kullanıcı adınızı girin")
sifre = input("sifreyi girin")
if kullanıcı == k and sifre != s:
print("kullanıcı adı doğru fakat sifre yanlış")
elif sifre == s and kullanıcı != k:
print("sifre doğru fakat kullanıcı adı hatalı")
elif sifre != s and kullanıcı != k:
print("ikisi de yanlış")
else:
print("doğru")
|
class Tokens:
"""
Management of given tokens.
"""
def __init__(self, tokenfilepath):
"""
Arguments:
tokenfilepath -- path to the file defining tokens and their inverse image
"""
self.__tokentree = TokenTree()
self.__words = dict()
for l in open(tokenfilepath):
if not l.startswith("#") and len(l) > 1:
l = l.rstrip().split("\t")
token = l[0].lower()
if len(token) > 1:
raise IOError("Token identifier has to be a single character.")
self.__words[token] = []
for w in l[1:]:
w = w.lower()
self.__words[token].append(w)
self.__tokentree.add_token(w, token)
for fullstop in (".?!"):
self.__tokentree.add_token(fullstop, ".")
def __iter__(self):
"""
Iterate over the tokens.
"""
return self.__words.__iter__()
def words(self, token):
"""
Return words for a given token.
"""
return self.__words[token]
def token(self, words, i):
"""
Return token for a given position i in a sequence of words.
Arguments:
words -- the sequence of words as a list
i -- the position in the sequence
"""
return self.__tokentree.get_token(words, i)
class TokenTree:
"""
Store tokens in a dictionary tree of words.
"""
def __init__(self):
self.__root = TokenTreeNode()
def add_token(self, word, token):
"""
Add a token to the tree.
Arguments:
word -- the word that is the inverse image of the token. May contain whitespaces.
token -- the token
"""
word = word.split()
node = self.__root
for w in word:
if not w in node.children:
node.children[w] = TokenTreeNode()
node = node.children[w]
node.token = token
def get_token(self, words, i):
"""
Returns the token for a given position i in a sequence of words.
Arguments:
words -- the sequence of words as a list
i -- the position in the sequence of words
"""
word = self.normalize_word(words[i])
candidates = []
node = self.__root
while word in node.children:
n = node.children[word]
if n.token:
candidates.append((n.token, i+1))
i += 1
word = self.normalize_word(words[i])
node = n
if len(candidates) > 0:
return candidates[-1] # return the longest possible match
raise NoTokenException()
def normalize_word(self, word):
if word == ".": return word
return word.lower().strip(",.!?:;/()[]{}")
class TokenTreeNode:
"""
A node in the dictionary tree for tokens.
"""
def __init__(self):
self.children = dict()
self.token = None
class NoTokenException(Exception):
pass
|
#汉罗塔游戏
#n层数,x轴,y轴,z轴
def hanoi(n ,x , y , z):
if n == 1:
print(x ,'--->', z)
else:
hanoi(n-1 ,x ,z ,y ) #将前n-1个盘子从x移动到y上
print(x,'--->',z)
hanoi(n-1 ,y ,x , z)
n = int(input("请输入汉罗塔层数"))
hanoi(n , "x" , "y" , "z" )
|
# f = open("new.txt","r")
# print(f.read())
# f.close()
f = open("new.txt","r")
# 往里面输入
for line in f:
if "1" in line:
print("this is the hello say hello")
else:
print(line)
f.close()
|
import unittest
from city_function import region
class CityTest(unittest.TestCase):
def test_city_country(self):
city_country = region("Cairo","Egypt")
self.assertEqual(city_country,"Cairo Egypt")
def test_country_city_population(self):
city_country_pop = region("cairo","Egypt",5000000)
self.assertEqual(city_country_pop,"cairo Egypt 5000000")
unittest.main()
|
__author__ = "Sanju Sci"
__email__ = "[email protected]"
from Arrays import gcd, print_array
from Arrays.reverse import reverse
# Using temp array https://www.geeksforgeeks.org/array-rotation/
# Time complexity : O(n)
# Auxiliary Space : O(d)
def left_rotate_s1(arr, d):
"""
This function is used to left rotate arr[] of size n by d.
:param arr:
An arr that contains a list.
:param d:
A d that contains rotation value.
:return:
"""
i = 0
j = 0
temp = []
while j < d:
temp.append(arr[i])
# arr = arr[:i] + arr[i+1:]
del arr[i]
j += 1
arr.extend(temp)
# A Juggling Algorithm: https://www.geeksforgeeks.org/array-rotation/
# Time complexity : O(n)
# Auxiliary Space : O(1)
def left_rotate_s2(arr, d):
"""
This function is used to left rotate arr[] of size n by d.
:param arr:
An arr that contains a list.
:param d:
A d that contains rotation value.
:return:
"""
n = len(arr)
for i in range(d):
for i in range(n-1):
arr[i], arr[i + 1] = arr[i + 1], arr[i]
# Time complexity : O(d)
# Auxiliary Space : O(1)
def left_rotate_s3(arr, d):
"""
This function is used to left rotate arr[] of size n by d.
:param arr:
An arr that contains a list.
:param d:
A d that contains rotation value.
:return:
"""
n = len(arr)
for i in range(d):
temp = arr[0]
del arr[0]
arr.append(temp)
# A Juggling Algorithm: https://www.geeksforgeeks.org/array-rotation/
# Time complexity : O(n)
# Auxiliary Space : O(1)
def left_rotate_s4(arr, d):
"""
This function is used to left rotate arr[] of size n by d.
:param arr:
An arr that contains a list.
:param d:
A d that contains rotation value.
:return:
"""
n = len(arr)
g = gcd(d, n)
for i in range(g):
# move i-th values of blocks
temp = arr[i]
j = i
while 1:
k = j + d
# print("K >= n : {} >= {}".format(k, n), end="\n")
if k >= n:
k = k - n
# print("K == i : {} == {}".format(k, i), end="\n")
if k == i:
break
# print("i: {}, j: {}, k: {}".format(i, j, k), end="\n")
arr[j] = arr[k]
j = k
arr[j] = temp
# The Reversal Algorithm: https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
# Time complexity : O(d)
# Auxiliary Space : O(1)
def left_rotate_s5(arr, d):
"""
This function is used to left rotate arr[] of size n by d.
:param arr:
An arr that contains a list.
:param d:
A d that contains rotation value.
:return:
"""
n = len(arr)
reverse(arr, 0, d - 1)
reverse(arr, d, n - 1)
reverse(arr, 0, n - 1)
if __name__ == '__main__':
from copy import deepcopy
d = 3
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr_copy1 = deepcopy(arr)
arr_copy2 = deepcopy(arr)
arr_copy3 = deepcopy(arr)
arr_copy4 = deepcopy(arr)
print("\n---- Using S1 ----\n")
left_rotate_s1(arr, d)
print_array(arr)
print("\n---- Using S2 ----\n")
left_rotate_s2(arr_copy1, d)
print_array(arr_copy1)
print("\n---- Using S3 ----\n")
left_rotate_s3(arr_copy2, d)
print_array(arr_copy2)
print("\n---- Using S4 ----\n")
left_rotate_s4(arr_copy3, d)
print_array(arr_copy3)
print("\n---- Using S5 ----\n")
left_rotate_s5(arr_copy4, d)
print_array(arr_copy4)
|
import time
import schedule
class Scheduler(object):
def __init__(self):
schedule.every(1).minutes.do(self.job)
schedule.every().hour.do(self.job)
schedule.every().day.at("17:06").do(self.job)
schedule.every(1).to(2).minutes.do(self.job)
schedule.every().monday.do(self.job)
schedule.every().wednesday.at("17:06").do(self.job)
schedule.every().minute.at(":05").do(self.job)
while True:
schedule.run_pending()
time.sleep(1)
def job(self):
print("I'm working...")
if __name__ == '__main__':
sh = Scheduler()
print(sh)
|
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
#Function to categorize based on median
def categorizeNumpyArray(NArr):
fq=NArr.describe()["25%"]
mid=NArr.describe()["50%"]
tq=NArr.describe()["75%"]
categoryArr=list()
for i in range(len(NArr)):
if (NArr[i]<=fq):
categoryArr.append(0.25)
elif (fq<NArr[i]<=mid):
categoryArr.append(0.5)
elif (mid<NArr[i]<=tq):
categoryArr.append(0.75)
elif (tq<NArr[i]):
categoryArr.append(1.0)
return categoryArr
#Preprocess the data and reduce the dimension
def PreProcess(X):
X["Median home value"]=categorizeNumpyArray(X["Median home value"])
X["Median age"]=categorizeNumpyArray(X["Median age"])
X["Per capita income"]=categorizeNumpyArray(X["Per capita income"])
X["%Homeless(approx)"]=((X["Total population"]-X["Total households"]*X["Average household size"]).astype(float)/X["Total population"])*100
X=X.drop(labels=["Total households","Average household size","House hold growth"],axis=1)
X=(X - np.mean(X, axis = 0)) / np.std(X, axis = 0) #Normalizing
#Principal component analysis, dimension reduction
pca = PCA(n_components=6)
principalComponents = pca.fit_transform(X)
X = pd.DataFrame(data = principalComponents)
return X
|
#!/usr/bin/python3
"""Calculate term frequency."""
import sys
import string
def read_file(path_to_file):
"""
Load file into data
"""
data = []
with open(path_to_file) as input_file:
data = data + list(input_file.read())
return data
def filter_chars_and_normalize(data):
"""
Replaces all nonalphanumeric chars in data with white space
"""
for i, char in enumerate(data):
if not char.isalnum():
data[i] = ' '
else:
data[i] = data[i].lower()
def scan(data):
"""
Scans data for words, filling the global variable WORDS
"""
words = []
data_str = ''.join(data)
words = words + data_str.split()
return words
def remove_stop_words(words):
"""
Remove stop words and single letter words from WORDS
"""
with open('../stop_words.txt') as stop_words_file:
stop_words = stop_words_file.read().split(',')
# single-letter words are also stop_words
stop_words.extend(list(string.ascii_lowercase))
indexes = []
for i, word in enumerate(words):
if word in stop_words:
indexes.append(i)
for i in reversed(indexes):
words.pop(i)
return words
def frequencies(words):
"""
Creates a list of word and frequency pairs
"""
word_freqs = []
for word in words:
keys = [wd[0] for wd in word_freqs]
if word in keys:
word_freqs[keys.index(word)][1] += 1
else:
word_freqs.append([word, 1])
return word_freqs
def sort(word_freqs):
"""
Sorts WORD_FREQS by frequency
"""
word_freqs.sort(key=lambda x: x[1], reverse=True)
return word_freqs
if __name__ == "__main__":
INPUT_DATA = read_file(sys.argv[1])
filter_chars_and_normalize(INPUT_DATA)
WORDS = scan(INPUT_DATA)
remove_stop_words(WORDS)
WORD_FREQS = frequencies(WORDS)
sort(WORD_FREQS)
for tf in WORD_FREQS[0:25]:
print(tf[0], '-', tf[1])
|
#!/usr/bin/python3
import sys, re, operator, string, inspect
def read_stop_words():
""" This function can only be called from a function
named extract_words."""
# Meta-level data: inspect.stack()
if inspect.stack()[1][3] != 'extract_words':
return None
with open('../stop_words.txt') as f:
stop_words = f.read().split(',')
stop_words.extend(list(string.ascii_lowercase))
return stop_words
def extract_words(path_to_file):
# Meta-level data: locals()
with open(locals()['path_to_file']) as f:
str_data = f.read()
pattern = re.compile('[\W_]+')
word_list = pattern.sub(' ', str_data).lower().split()
stop_words = read_stop_words()
return [w for w in word_list if not w in stop_words]
def frequencies(word_list):
# Meta-level data: locals()
word_freqs = {}
for w in locals()['word_list']:
if w in word_freqs:
word_freqs[w] += 1
else:
word_freqs[w] = 1
return word_freqs
def sort(word_freq):
# Meta-level data: locals()
return sorted(locals()['word_freq'].items(), key=operator.itemgetter(1), reverse=True)
def main():
word_freqs = sort(frequencies(extract_words(sys.argv[1])))
for (w, c) in word_freqs[0:25]:
print(w, '-', c)
if __name__ == "__main__":
main()
|
"""
This is the unit test for calc_viewing_direction which calculates the direction
from the animal's location to a spot on the dome given the camera's direction
and the pixel coordinates of the spot in a photo taken with the camera.
Calls to this function look like this:
calc_viewing_direction(photo_point, camera_direction, parameters)
where parameters is a dictionary that contains entries for animal_position,
dome_radius and dome_center.
"""
from numpy import array, pi, arange, sin, cos, arcsin, arctan2, cross
from numpy.linalg import norm, inv
import random
# import from a relative directory
import sys
sys.path.append("..") # in case this file is run from .
sys.path.append(".") # in case this file is run from ..
from dome_calibration import calc_viewing_direction
from dome_calibration import calc_distance_to_dome
from dome_calibration import rotate
import foscam_FI9821P as camera
def test_calc_viewing_direction():
""" Pick a random camera orientation, then pick a point on the dome inside
the camera's field of view. Calculate the location of the camera's
optical center and the direction from it to the point on the dome. Use
this direction along with the camera's orientation to find the direction
relative to the camera's optical axis. Use this relative direction and
the camera's calibration matrix to calculate the point's pixel coordinates.
Call calc_viewing_direction and compare its results to the easily
calculated direction from the animal's location the point on the dome. """
DEBUG = False
required_accuracy = 1e-6
# calculate the camera's field of view for later use
vector_to_upper_left_corner = inv(camera.matrix).dot([0.0, 0.0, 1.0])
vector_to_lower_right_corner = \
inv(camera.matrix).dot([camera.pixel_width, camera.pixel_height, 1])
left = vector_to_upper_left_corner[0]
right = vector_to_lower_right_corner[0]
upper = vector_to_upper_left_corner[1]
lower = vector_to_lower_right_corner[1]
for i in range(1000):
# pick a random radius for the dome
radius = 0.2 + random.random()
# pick a random location for the center of the dome
x = random.random()
y = random.random()
z = random.random()
center = array([x, y, z])
# pick a random location inside the dome for the animal position
r = 0.5 * radius * random.random()
pitch = pi/2 * 2*(random.random() - 0.5)
yaw = pi * 2*(random.random() - 0.5)
animal_position = r * array([cos(pitch)*sin(yaw),
cos(pitch)*cos(yaw),
sin(pitch)])
animal_position = animal_position + center
# pick a random camera direction
camera_pitch = pi/2 * 2*(random.random() - 0.5)
camera_yaw = pi * 2*(random.random() - 0.5)
camera_direction = array([cos(camera_pitch)*sin(camera_yaw),
cos(camera_pitch)*cos(camera_yaw),
sin(camera_pitch)])
# Calculate the position of the camera's optical center. Find the unit
# vectors of the camera's coordinate system and express
# camera.reference_vector using those unit vectors.
ccz = camera_direction
ccx = cross(ccz, array([0.0, 0.0, 1.0]))
ccx = ccx / norm(ccx)
ccy = cross(ccz, ccx)
reference_vector = (camera.reference_vector[0]*ccx +
camera.reference_vector[1]*ccy +
camera.reference_vector[2]*ccz)
camera_focal_point = animal_position - reference_vector
# pick a point on the dome inside the camera's field of view
y = ccy * ((upper - lower) * random.random() + lower)
x = ccx * ((right - left) * random.random() + left)
direction_to_point = camera_direction + x + y
direction_to_point = direction_to_point / norm(direction_to_point)
parameters = dict(animal_position = animal_position,
dome_center = center,
dome_radius = radius)
distance_to_point = calc_distance_to_dome(parameters, camera_focal_point,
direction_to_point)
camera_to_dome = distance_to_point * direction_to_point
point_on_dome = camera_focal_point + camera_to_dome
# calculate the animal's viewing direction, which is the result expected
# from calc_viewing_direction
expected_result = ((point_on_dome - animal_position)
/ norm(point_on_dome - animal_position))
# rotate camera_to_dome to put it in the camera's coordinate system
yaw_rotation_vector = camera_yaw * array([0.0, 0.0, 1.0])
camera_to_pixel = rotate(camera_to_dome, yaw_rotation_vector)
pitch_rotation_vector = (pi/2 - camera_pitch) * array([1.0, 0.0, 0.0])
camera_to_pixel = rotate(camera_to_pixel, pitch_rotation_vector)
# use this vector and the camera matrix to find
# the pixel coordinates of the spot on the dome
pixel_vector = camera.matrix.dot(camera_to_pixel)
x, y, w = pixel_vector
photo_point = array([x, y]) / w
if DEBUG:
print
print photo_point
result = calc_viewing_direction(photo_point, camera_direction, parameters)
assert norm(result - expected_result) < required_accuracy
if DEBUG:
print "Expected result:", expected_result
print "Actual result: ", result
|
def necklaces(N):
for n in range(2 ** N):
yield "{0:0{digits}b}".format(n, digits=N)
def has_N_white_beads(necklace, N):
return necklace.count("1") == N
def flip(necklace):
return necklace[::-1]
def rotate(string, steps):
return string[steps:] + string[:steps]
def better_than_all_rotations_and_reflections(necklace):
for i in range(1, len(necklace)):
if necklace > rotate(necklace, i):
return False
if necklace > flip(rotate(necklace, i)):
return False
return True
WHITE_BEADS = 3
BLACK_BEADS = 13
TOTAL = WHITE_BEADS + BLACK_BEADS
for s in necklaces(TOTAL):
if not has_N_white_beads(s, WHITE_BEADS):
continue
if not better_than_all_rotations_and_reflections(s):
continue
print(s)
|
largest = None
smallest = None
while True:
input_str = input("Enter a number: ")
if input_str == "done":
break
try:
parsed_integer = int(input_str)
if largest is None or parsed_integer > largest:
largest = parsed_integer
if smallest is None or parsed_integer < smallest:
smallest = parsed_integer
except:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
|
"""
Esta clase preceptron tendra 3 metodos:
1. - Inicializar el perceptron Pesos iniciales aleatorios.
2. - Calculo de la salido del perceptron
3. - Entrenamiento
"""
import numpy as np
import matplotlib.pyplot as plt
# Funciones anonimas o funciones lambda
def sigmoid():
return lambda x: 1 / (1 + np.e ** -x)
def tanh():
return lambda x: np.tanh(x)
def relu():
return lambda x: np.maximum(0, x)
def random_points(n=100):
x = np.random.uniform(0.0, 1.0, n)
y = np.random.uniform(0.0, 1.0, n)
return np.array([x, y]).T
class Perceptron:
def __init__(self, n_inputs, act_f):
self._weights = np.random.rand(n_inputs, 1)
self._bias = np.random.rand()
self._act_f = act_f
self._n_inputs = n_inputs
@property
def weights(self):
return self._weights
@weights.setter
def weigths(self, weights):
self._weights = weights
@property
def bias(self):
return self._bias
@bias.setter
def bias(self, bias):
self._bias = bias
@property
def act_f(self):
return self._act_f
@act_f.setter
def act_f(self, act_f):
self.act_f = act_f
@property
def n_inputs(self):
return self._n_inputs
@n_inputs.setter
def n_inputs(self, n_inputs):
self._n_inputs = n_inputs
# Funcion para caluclar el fitfowar
def predict(self, x):
return self._act_f(x @ self._weights + self._bias)
# Metodo de aprendizaje no supervisado
def fit(self, x, y, epochs=100):
for i in range(epochs):
for j in range(self._n_inputs):
output = self.predict(x[j])
error = y[j] - output
self._weights = self._weights + (error * x[j][1])
self._bias = self._bias + error
def main():
points = random_points(10000)
# plt.scatter(points[:, 0], points[:, 1], s=10)
# plt.show()
x = np.array([
[0, 0],
[0, 1],
[1, 0],
[1, 1],
])
y = np.array([
[0],
[1],
[1],
[1],
])
p_or = Perceptron(2, sigmoid())
yp = p_or.predict(points)
p_or.fit(x=x, y=y, epochs=1000)
plt.scatter(points[:, 0], points[:, 1], s=10, c=yp, cmap='GnBu')
plt.show()
if __name__ == '__main__':
main()
|
import sqlite3
from sqlite3 import Error
class DataBase:
def __init__(self, dbname='mydatabase.db'):
self.dbname = dbname
self.check_reatebase()
def check_reatebase(self):
try:
self.conn = sqlite3.connect(self.dbname, check_same_thread=False)
self.cursor = self.conn.cursor()
except:
pass
#print('База данных не создана')
def create_base_email(self):
try:
self.cursor.execute("""CREATE TABLE email(
name text,
source text,
domain text,
date text)
""")
self.conn.commit()
except:
print('база данных Email уже создана')
return False
def create_base_sites(self):
try:
self.cursor.execute("""CREATE TABLE sites(
url text,
status text,
date text)
""")
self.conn.commit()
except:
#print('база данных Sites уже создана')
return False
def create_email(self, name, source, domain, date):
if len(self.select('select * From email where name="'+name+'"')) < 1:
try:
sql_insert = """INSERT INTO email VALUES (?,?,?,?);"""
data_email = (name, source, domain, date)
self.cursor.execute(sql_insert, data_email)
self.conn.commit()
except sqlite3.Error as error:
pass
#print("Ошибка при работе с SQLite", error)
def create_sites(self, url, status, date):
try:
sql_insert = """INSERT INTO sites VALUES (?,?,?);"""
data_email = (url, status, date)
self.cursor.execute(sql_insert, data_email)
self.conn.commit()
except sqlite3.Error as error:
pass
#print("Ошибка при работе с SQLite", error)
def select(self, sql):
self.cursor.execute(sql)
row = self.cursor.fetchall()
return row
def sql_command(self, sql):
self.cursor.execute(sql)
row = self.cursor.fetchall()
#DataBase('mydatabase.db').create_email('[email protected]', 'первосоздатель', 'rost-seo', '15.06.2021')
#DataBase('mydatabase.db').create_base_sites()
#DataBase('mydatabase.db').create_sites('rost-seo.ru', 'finished', '15.06.2021')
|
def city_country(city, country):
"""Return a string like this 'Santiago, Chile'."""
return(city.title() + ", " + country.title())
city = city_country('shanghai', 'china')
print(city)
city = city_country('beijing', 'china')
print(city)
city = city_country('tokyo', 'japan')
print(city)
|
person = {
'first_name': 'jimmy',
'last_name': 'chen',
'age': 23,
'city': 'shanghai'
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
|
########################
#Name: Cherie Hua
#AndrewID: cxhua
#Section: O
#######################
import sys, math, copy, string, random, time
from cmu_112_graphics import * # copied (with modifications) from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
from fractions import Fraction #from https://docs.python.org/3.1/library/fractions.html
from tkinter import *
#from PIL import Image
class Game(App):
#will separate these functions later
def appStarted(self):
#some modes
self.beginner = (9, 9, 10)
self.intermediate = (16, 16, 40)
self.expert = (16, 30, 99)
#set dimensions here
self.rows = 4
self.cols = 4
self.mines = 0
self.margin = self.height//25
self.teacherWidth = self.width//3
self.instructionsHeight = self.height // 7
self.gridWidth = self.width - 2*self.margin - self.teacherWidth
self.gridHeight = self.height - 2*self.margin - self.instructionsHeight
self.cellWidth = self.gridWidth // self.cols
self.cellHeight = self.gridHeight // self.rows
#creates base board
#here's a hardcoded board I used for testing, set rows and cols = 4 and mines = 0 to use this
self.board = [[0, '*', 0, '*'],[0, 0, 0, 0],[0, 0, 0, 0],[0, '*', '*', 0]]
#self.board = [([0] * self.cols) for row in range(self.rows)]
#creates a cover that the player can click to uncover
self.cover = [([True] * self.cols) for row in range(self.rows)]
self.lost = False
self.won = False
self.canClick = True
self.firstClick = True
self.probabilities = [([None] * self.cols) for row in range(self.rows)]
self.getProbabilities = False
self.reducedProbabilities = copy.deepcopy(self.probabilities)
self.moves = []
self.moves.append(copy.deepcopy(self.cover))
self.AIScroll = False
self.movePlace = 0
self.endScreen = None
self.getStrategies = False
self.pattern = None
def generateMines(self):
#generates mines randomly until the number of mines generated equals the number
#the player requested
numMines = 0
while numMines < self.mines:
row = random.randint(0, self.rows)-1
col = random.randint(0, self.cols)-1
if self.board[row][col] != '*' and self.board[row][col] != 'clear':
self.board[row][col] = '*'
numMines += 1
def placeNumbers(self):
#loop through every space in the board
for row in range(self.rows):
for col in range(self.cols):
#if the space has a mine
if self.board[row][col] == 'clear':
self.board[row][col] = 0
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] == '*':
#add 1 to the numbers around the mine
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
if (drow, dcol) == (0, 0):
continue
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0 and
self.board[checkRow][checkCol] != '*'):
self.board[checkRow][checkCol] += 1
def mousePressed(self, event):
#from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
(row, col) = Game.getCell(self, event.x, event.y)
AILeft = self.width - self.teacherWidth + self.margin*2
AITop = self.height//8
AIRight = self.width - self.margin*2
AIBottom = self.height//5
if (event.x > AILeft and event.x < AIRight and event.y < AIBottom and event.y > AITop
and (self.lost == True or self.won == True)):
self.AIScroll = True
self.cover = [([True] * self.cols) for row in range(self.rows)]
self.lost = False
self.won = False
if (row, col) != (-1, -1) and self.canClick:
if self.firstClick:
Game.firstClick(self, row, col)
if self.cover[row][col] == 'flag':
return
if self.cover[row][col] != 'flag':
self.cover[row][col] = False
if (self.cover[row][col] == False and self.board[row][col] != '*'
and self.board[row][col] > 0):
Game.clearWithNumberPress(self, row, col)
if self.board[row][col] == '*' and self.cover[row][col] != 'flag':
Game.revealMines(self)
self.lost = True
self.canClick = False
Game.expand(self, row, col)
if self.getProbabilities and self.probabilities[row][col] != None:
pattern = Game.isPattern(self, row, col)
Game.getExplanation(self, pattern)
def clearWithNumberPress(self, row, col):
if Game.checkAround(self, row, col, 'flag', self.cover) == self.board[row][col]:
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
if (drow, dcol) == (0, 0):
continue
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0 and
self.cover[checkRow][checkCol] != 'flag'):
self.cover[checkRow][checkCol] = False
if self.board[checkRow][checkCol] == '*':
Game.revealMines(self)
self.lost = True
self.canClick = False
def checkAround(self, row, col, thing, place):
number = 0
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
if (drow, dcol) == (0, 0):
continue
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0 and place[checkRow][checkCol] == thing
and (drow, dcol) != (0, 0)):
number += 1
return number
def firstClick(self, row, col):
#clears a larger then 1 block space on the first click
self.firstClick = False
#clear a square no matter what the dimensions are
# rowOrCol = min(self.rows, self.cols)
# clearRows = rowOrCol//6 + 1
# clearCols = rowOrCol//6 + 1
# for clearRow in range(row-clearRows, row+clearRows):
# for clearCol in range(col-clearCols, col+clearCols):
# if (clearRow < self.rows and clearCol < self.cols
# and clearRow >= 0 and clearCol >= 0):
# self.board[clearRow][clearCol] = 'clear'
Game.generateMines(self)
Game.placeNumbers(self)
def expand(self, r, c):
self.cover[r][c] = False
allClear = False
while allClear == False:
clearSpaces = 0
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] == 0 and self.cover[row][col] == False:
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
if (drow, dcol) == (0, 0):
continue
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0):
if (self.board[checkRow][checkCol] != '*' and
self.cover[checkRow][checkCol] == True):
self.cover[checkRow][checkCol] = False
clearSpaces += 1
if clearSpaces == 0:
allClear = True
def rightMousePressed(self, event):
#edited cmu_112_graphics.py to include right clicking, bounded to <Button-2>
#from what I've seen online, right clicking is usually Button 3, and only Button 2 for OS X
#so it may not work for non-Mac users
(row, col) = Game.getCell(self, event.x, event.y)
if self.cover[row][col] != 'flag' and self.canClick and self.cover[row][col]:
self.cover[row][col] = 'flag'
elif self.cover[row][col] == 'flag' and self.canClick:
self.cover[row][col] = True
def getCellBounds(self, row, col):
#from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
columnWidth = self.gridWidth // self.cols
rowHeight = self.gridHeight // self.rows
x0 = self.margin + col * columnWidth
x1 = self.margin + (col+1) * columnWidth
y0 = self.margin + self.instructionsHeight + row * rowHeight
y1 = self.margin + self.instructionsHeight + (row+1) * rowHeight
return (x0, y0, x1, y1)
def pointInGrid(self, x, y):
#from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
return ((self.margin <= x <= self.width-self.margin-self.teacherWidth) and
(self.margin + self.instructionsHeight <= y <= self.height-self.margin))
def getCell(self, x, y):
#from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
if not Game.pointInGrid(self, x, y):
return (-1, -1)
row = int((y - self.margin - self.instructionsHeight) // self.cellHeight)
col = int((x - self.margin) // self.cellWidth)
return (row, col)
def win(self):
#if every non-mine space is cleared, then set win to True and stop the player
#from playing any more
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] != '*' and self.cover[row][col] == True:
return False
Game.revealMines(self)
self.canClick = False
self.won = True
return True
def revealMines(self):
#remove cover when the board has a mine
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] == '*' and self.cover[row][col] != 'flag':
self.cover[row][col] = False
if self.cover[row][col] == 'flag' and self.board[row][col] != '*':
self.cover[row][col] = 'wrong'
def timerFired(self):
Game.win(self)
Game.placeProbabilities(self)
def tankSolver(self, partialBoard):
(move, solution) = TankSolver(partialBoard).solve()
solutions = []
if solution != None:
for i in range(len(solution)):
solutions.append(solution[i].minePositions)
return solutions
def keyPressed(self, event):
#go to next move
if event.key == 'p':
if self.getProbabilities:
self.getProbabilities = False
self.canClick = True
else:
self.getProbabilities = True
self.canClick = False
if event.key == 's':
if self.getStrategies:
self.getStrategies = False
else:
self.getStrategies = True
if self.AIScroll:
if event.key == 'Right' and self.won == False and self.lost == False:
Game.executeMove(self)
if self.cover not in self.moves:
self.moves.append(copy.deepcopy(self.cover))
self.movePlace += 1
if self.movePlace >= len(self.moves):
return
if self.endScreen != None and self.movePlace == self.endScreen[0]:
if self.endScreen[1] == 'lost':
self.lost = True
if self.endScreen[1] == 'won':
self.won = True
if event.key == 'Left' and self.movePlace > 0:
if self.lost:
self.lost = False
self.endScreen = (self.movePlace, 'lost')
if self.won:
self.won = False
self.endScreen = (self.movePlace, 'won')
self.movePlace -= 1
def findMove(self):
if self.firstClick:
Game.firstClick(self, r, c)
self.firstClick = False
r = random.randint(0, self.rows)
c = random.randint(0, self.cols)
return (r, c)
probs = copy.deepcopy(self.probabilities)
for r in range(self.rows):
for c in range(self.cols):
if probs[r][c] == None or self.cover[r][c] == False:
probs[r][c] = 2
minProb = min([min(value) for value in probs])
for row in range(self.rows):
for col in range(self.cols):
if probs[row][col] == minProb:
(minRow, minCol) = (row, col)
return (minRow, minCol)
def executeMove(self):
if self.won == False and self.lost == False:
(row, col) = Game.findMove(self)
self.cover[row][col] = False
Game.expand(self, row, col)
if self.board[row][col] == '*':
self.lost = True
win = True
for row in range(self.rows):
for col in range(self.cols):
if self.cover[row][col] == True and self.board[row][col] != '*':
win = False
if win:
self.won = True
def placeProbabilities(self):
#look through every tile
for row in range(self.rows):
for col in range(self.cols):
#if there's a revealed number
if (type(self.board[row][col]) == int and self.board[row][col] > 0
and self.cover[row][col] != True):
nUnrevealedTiles = Game.findUnrevealedTiles(self, row, col)
#place 1 if the number of tiles equals the number of mines
if nUnrevealedTiles == self.board[row][col]:
Game.definiteZerosAndOnes(self, row, col, 1)
#place 0 for the rest of the tiles in the area surrounding the number
nUnrevealedTiles = Game.findUnrevealedTiles(self, row, col)
nRevealedMines = Game.checkAround(self, row, col, 1, self.probabilities)
if nRevealedMines == self.board[row][col] and nRevealedMines < nUnrevealedTiles:
Game.definiteZerosAndOnes(self, row, col, 0)
partialBoard = Game.getPartialBoard(self)
if partialBoard != None:
positions = Game.tankSolver(self, partialBoard)
Game.getAIProbabilities(self, positions)
def getAIProbabilities(self, positions):
if positions == []:
return
rows = len(positions[0])
if len(positions) == 1:
for state in positions:
for row in range(rows):
cols = len(state[row])
for col in range(cols):
r = state[row][col][0]
c = state[row][col][1]
value = state[row][col][2]
if value == 'True':
self.probabilities[r][c] = 1
else:
self.probabilities[r][c] = 0
else:
#add 1 to partialProbabilities if there's a mine in that location for each state
partialProbabilities = [[None]*self.cols for rows in range(self.rows)]
for state in positions:
for row in range(rows):
cols = len(state[row])
for col in range(cols):
r = state[row][col][0]
c = state[row][col][1]
if state[row][col][2] == 'True':
if partialProbabilities[r][c] == None:
partialProbabilities[r][c] = 0
partialProbabilities[r][c] += 1
for row in range(self.rows):
for col in range(self.cols):
if partialProbabilities[row][col] != None:
self.probabilities[row][col] = Fraction(partialProbabilities[row][col], len(positions))
def getPartialBoard(self):
partialCoords = []
#go through everything in board
for row in range(self.rows):
for col in range(self.cols):
#if it's a revealed number
if (self.cover[row][col] == False and type(self.board[row][col]) == int
and self.board[row][col] > 0):
#add it to partialCoords
partialCoords.append((row, col, self.board[row][col]))
#add everything around it to partialCoords too if it's a covered tile
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0
and self.cover[checkRow][checkCol] != False
and (checkRow, checkCol, None) not in partialCoords
and (drow, dcol) != (0, 0)):
if self.probabilities[checkRow][checkCol] == 1:
partialCoords.append((checkRow, checkCol, 'True'))
else:
partialCoords.append((checkRow, checkCol, None))
partialCoords.sort(key = lambda tup: (tup[0], tup[1]))
partialBoard = []
rowList = []
#go through everything in particalCoords and make it a 2D List
for coords in range(len(partialCoords)):
if coords > 0 and partialCoords[coords][0] != partialCoords[coords-1][0]:
partialBoard.append(rowList)
rowList = []
rowList.append(partialCoords[coords])
else:
rowList.append(partialCoords[coords])
partialBoard.append(rowList)
if partialBoard != []:
return partialBoard
def definiteZerosAndOnes(self, row, col, thing):
#place around the 8 squares around the number
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
if (drow, dcol) == (0, 0):
continue
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0 and
self.cover[checkRow][checkCol] and self.probabilities[checkRow][checkCol] != (1-thing)):
self.probabilities[checkRow][checkCol] = thing
def findUnrevealedTiles(self, row, col):
#count the number of covered tiles in the 8 squares surrounding a number
nUnrevealedTiles = 0
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
if (drow, dcol) == (0, 0):
continue
checkRow = row+drow
checkCol = col+dcol
if (checkRow < self.rows and checkCol < self.cols
and checkRow >= 0 and checkCol >= 0 and self.cover[checkRow][checkCol] != False
and self.probabilities[checkRow][checkCol] != 0):
nUnrevealedTiles += 1
return nUnrevealedTiles
def getExplanation(self, pattern):
#explanations copied from http://www.minesweeper.info/wiki/Strategy
if pattern == '121':
self.pattern = '''
Common pattern (121) - This
is a variation of the 1-2 pattern.
There is 1 mine in the
first two squares, and
2 mines in the first three
squares. The 3rd square over
must be a mine. Apply this
from the other direction as well.'''
return
if pattern == '1221':
self.pattern = '''
Common pattern (1221) -
This is a variation of the
1-2 pattern.
There is 1 mine in the
first two squares, and
2 mines in the
first three squares.
The 3rd square over
must be a mine. Apply this
from the other
direction as well.
'''
return
if pattern == '11':
self.pattern = '''
There is 1 mine in the first
two squares, and 1 mine in the
first three squares. The 3rd
square over must be empty.
'''
return
if pattern == '12':
self.pattern = '''
There is 1 mine in the first
two squares, and 2 mines in the
first three squares. The 3rd square
over must be a mine.
'''
return
if pattern == '?':
self.pattern = '''
The number of solutions
with a mine
in this square divided
by the total solutions.
'''
return
else:
self.pattern = '''
If a number is touching the same
number of squares, then the
squares are all mines.
'''
return
def isPattern(self, row, col):
#modified from https://www.cs.cmu.edu/~112/notes/week5-case-studies.html#wordsearch1
patterns = ['121', '1221', '11', '12']
for pattern in patterns:
dcol = 0
for drow in [-1, +1]:
result = Game.isPatternHelper(self, pattern, row, col, drow, dcol)
if (result):
return pattern
drow = 0
for dcol in [-1, +1]:
result = Game.isPatternHelper(self, pattern, row, col, drow, dcol)
if (result):
return pattern
return '?'
def isPatternHelper(self, number, startRow, startCol, drow, dcol):
#modified from https://www.cs.cmu.edu/~112/notes/week5-case-studies.html#wordsearch1
number = number
for i in range(len(number)):
row = startRow + i*drow
col = startCol + i*dcol
if ((row < 0) or (row >= self.rows) or
(col < 0) or (col >= self.cols) or
str(self.board[row][col]) != number[i] or
self.cover[row][col] != False):
return None
return True
def strategies(self):
#some explanations copied from http://www.minesweeper.info/wiki/Strategy
#binomial coefficient taken from http://www.minesweeper.info/archive/MinesweeperStrategy/mine_probability_calculation_1.html
return '''
Reducing
- Subtract the number of definite mines around a number
from the number on the board. Often, this reduces down
to a pattern such as 121 or 1221.
Common Patterns
- 121: Mines must be on both sides of the 2.
- 1221: 2 mines must be in the middle, with the 1's on the
edges both touching one mine.
- 12: Whenever you see a 1-2 pattern
the 3rd square over is always a mine.
- 11: Whenever you see a 1-1 pattern starting from an
edge (or where an open square functions as an edge)
the 3rd square over is empty.
Guessing Tips
- Use the binomial coefficient n! / (k! * (n-k)!) where k = mines and n = squares
to calculate probabilities. For more information, see
http://www.minesweeper.info/archive/MinesweeperStrategy/mine_probability_calculation_1.html
- If you can prove a square is safe, open it instead
of guessing where the mine is.
- There might be an arrangement of numbers with more
than one solution, and the solutions require different
amounts of mines. Instead of guessing, you can solve it by
flagging the rest of the board and seeing how many mines are left.
- Sometimes it's better to guess randomly in the board than take a 50/50
chance.
- See http://nothings.org/games/minesweeper/ for more tips.
'''
def redrawAll(self, canvas):
#some from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
fontSize = int(self.cellWidth//3)
#draw the teacher
canvas.create_text(self.width - self.teacherWidth//2, self.height//20,
text = 'Teacher', font = 'Arial 30 bold')
leftEdge = self.width-self.teacherWidth + self.margin
topEdge = self.height//10
bottomEdge = self.height - self.margin
rightEdge = self.width - self.margin
canvas.create_rectangle(leftEdge, topEdge, rightEdge, bottomEdge, width = 3)
canvas.create_text(self.width - self.teacherWidth//2, self.height//3.5,
text =
'''
press "p"
for probabilities
click on a board number
for a probability
explanation
press "s" for strategies
''', font = 'Arial 20 bold')
#go through everything in the board
for row in range(self.rows):
for col in range(self.cols):
(x0, y0, x1, y1) = Game.getCellBounds(self, row, col)
place = self.board[row][col]
#if there's a mine, make the space red
fill = "red" if place == '*' else "white"
canvas.create_rectangle(x0, y0, x1, y1, fill=fill)
#mark numbers based on the number of mines around it
if place != 0 and place != '*':
canvas.create_text(x0 + self.cellWidth//2, y0 + self.cellHeight//2,
text = place, font = 'Arial ' + str(fontSize) + ' bold')
#make cover
if self.cover[row][col]:
canvas.create_rectangle(x0, y0, x1, y1, fill='grey')
#make flags
if self.cover[row][col] == 'flag':
canvas.create_oval(x0, y0, x1, y1, fill='red')
#if you flagged a square that isn't a mine, draw an X
if self.cover[row][col] == 'wrong':
canvas.create_oval(x0, y0, x1, y1, fill='red')
canvas.create_line(x0, y0, x1, y1, width = 3)
canvas.create_line(x1, y0, x0, y1, width = 3)
#draw probabilities
if (self.AIScroll and self.cover[row][col]) or (self.getProbabilities and self.probabilities[row][col] != None and self.cover[row][col]):
canvas.create_text(x0 + self.cellWidth//2, y0 + self.cellHeight//2,
text = self.probabilities[row][col], fill = 'yellow', font = 'Arial ' + str(fontSize) + ' bold')
if self.AIScroll and self.moves != []:
if self.moves[self.movePlace][row][col]:
canvas.create_rectangle(x0, y0, x1, y1, fill='grey')
if self.lost:
canvas.create_text(self.width//2, self.height//2,
text = 'YOU LOSE', font = 'Arial 75 bold')
if self.AIScroll == False:
canvas.create_rectangle(self.width - self.teacherWidth + self.margin*2, self.height//8,
self.width - self.margin*2, self.height//5)
canvas.create_text(self.width - 0.5*self.teacherWidth, self.height//6,
text = 'Run AI', font = 'Arial 20 bold')
if self.won:
canvas.create_text(self.width//2, self.height//2,
text = 'YOU WIN', font = 'Arial 75 bold')
if self.AIScroll == False:
canvas.create_rectangle(self.width - self.teacherWidth + self.margin*2, self.height//8,
self.width - self.margin*2, self.height//5)
canvas.create_text(self.width - 0.5*self.teacherWidth, self.height//6,
text = 'Run AI', font = 'Arial 20 bold')
if self.firstClick:
canvas.create_text(self.width-self.width//6, self.height//2,
text =
'''
Click to clear a square.
Right click to flag a mine
(red circle).
Don't hit any mines!
Click to start.
Manually change rows, cols,
and mines.
''',
font = 'Arial 20 bold')
if self.getStrategies:
canvas.create_rectangle(0, 0, self.width, self.height, fill='white')
strategies = Game.strategies(self)
canvas.create_text(self.width//2, self.height//2, text = strategies,
font = 'Arial 20 bold')
if self.pattern != None:
canvas.create_text(self.width - self.teacherWidth//2, self.height//1.5,
text = self.pattern, font = 'Arial 20 bold')
class State(object):
#class copied from https://www.cs.cmu.edu/~112/notes/notes-recursion-part2.html
def __eq__(self, other): return (other != None) and self.__dict__ == other.__dict__
def __hash__(self): return hash(str(self.__dict__)) # hack but works even with lists
def __repr__(self): return str(self.__dict__)
class BacktrackingPuzzleSolver(object):
#entire class modified from https://www.cs.cmu.edu/~112/notes/notes-recursion-part2.html
def solve(self, checkConstraints=True, printReport=False):
self.moves = [ ]
self.states = set()
# If checkConstraints is False, then do not check the backtracking
# constraints as we go (so instead do an exhaustive search)
self.checkConstraints = checkConstraints
# Be sure to set self.startArgs and self.startState in __init__
self.startTime = time.time()
self.solutionState = self.solveFromState(self.startState)
self.endTime = time.time()
if (printReport): self.printReport()
return (self.moves, self.solutions)
def printReport(self):
print()
print('***********************************')
argsStr = str(self.startArgs).replace(',)',')') # remove singleton comma
print(f'Report for {self.__class__.__name__}{argsStr}')
print('checkConstraints:', self.checkConstraints)
print('Moves:', self.moves)
print('Solution state: ', end='')
if ('\n' in str(self.solutionState)): print()
print(self.solutionState)
print('------------')
print('Total states:', len(self.states))
print('Total moves: ', len(self.moves))
millis = int((self.endTime - self.startTime)*1000)
print('Total time: ', millis, 'ms')
print('***********************************')
def solveFromState(self, state):
if state in self.states:
# we have already seen this state, so skip it
return None
self.states.add(state)
if self.isSolutionState(state):
self.solutions.append(state)
for move in self.getLegalMoves(state):
# 1. Apply the move
childState = self.doMove(state, move)
# 2. Verify the move satisfies the backtracking constraints
# (only proceed if so)
if self.stateSatisfiesConstraints(childState):
# 3. Add the move to our solution path (self.moves)
self.moves.append(move)
# 4. Try to recursively solve from this new state
result = self.solveFromState(childState)
# 5. If we solved it, then return the solution!
if result != None:
return result
# 6. Else we did not solve it, so backtrack and
# remove the move from the solution path (self.moves)
self.moves.pop()
class TankState(State):
def __init__(self, minePositions):
self.minePositions = minePositions
def getMinePositions(self):
return self.minePositions
class TankSolver(BacktrackingPuzzleSolver):
def __init__(self, borderTiles):
self.borderTiles = borderTiles
self.minePositions = copy.deepcopy(self.borderTiles)
self.rows = len(self.borderTiles)
self.startArgs = self.minePositions
self.startState = TankState(self.minePositions)
self.solutions = []
@staticmethod
def checkForMines(self, row, col, place):
number = 0
for drow in [-1, 0, 1]:
for dcol in [-1, 0, 1]:
checkRow = row+drow
checkCol = col+dcol
if (checkRow, checkCol) == (row, col):
continue
if (0 <= checkRow < self.rows and 0 <= checkCol < len(place[checkRow]) and
place[checkRow][checkCol][2] == 'True'):
number += 1
return number
def stateSatisfiesConstraints(self, state):
# return True if the state satisfies the solution constraints so far
for row in range(self.rows):
cols = len(state.minePositions[row])
for col in range(cols):
if type(state.minePositions[row][col][2]) == int and state.minePositions[row][col][2] > 0:
#if the tile is a mine number
mines = self.checkForMines(self, row, col, state.minePositions)
if mines > state.minePositions[row][col][2]:
#if the number of marked mines is less than or equal to the number on the tile, it's fine
return False
return True
def isSolutionState(self, state):
# return True if the state is a solution
for row in range(self.rows):
cols = len(state.minePositions[row])
for col in range(cols):
if type(state.minePositions[row][col][2]) == int and state.minePositions[row][col][2] > 0:
if (self.checkForMines(self, row, col, state.minePositions) != state.minePositions[row][col][2]):
return False
return True
def getLegalMoves(self, state):
# return a list of the legal moves from this state (but not
# taking the solution constraints into account)
#compiles a list of legal moves that the mine can be placed in
moves = []
for row in range(len(self.borderTiles)):
cols = len(self.borderTiles[row])
for col in range(cols):
if self.borderTiles[row][col][2] == None and type(self.borderTiles[row][col]) != int:
moves.append((row, col))
return moves
def doMove(self, state, move):
# return a new state that results from applying the given
# move to the given state
# places the mine in the new location and returns the new locations
(row, col) = move
newPositions = copy.deepcopy(state.minePositions)
newPositions[row][col] = (newPositions[row][col][0], newPositions[row][col][1], 'True')
return TankState(newPositions)
Game(width = 1000, height = 700)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.