blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
5df44fab429d251f964eb561f8a06f9a71a94a4a | pedrosimoes-programmer/exercicios-python | /exercicios-Python/ex020.py | 1,191 | 3.875 | 4 | #forma 1
#from random import shuffle
#a1 = input('Primeiro aluno: ')
#a2 = input('Segundo aluno: ')
#a3 = input('Terceiro aluno: ')
#a4 = input('Quarto aluno: ')
#lista = [a1, a2, a3, a4]
#random.shuffle(lista)
#print('A ordem de apresentação será: {}'.format(lista))
#forma 2 (A melhor forma)
from random import sample
a1 = input('Primeiro aluno: ')
a2 = input('Segundo aluno: ')
a3 = input('Terceiro aluno: ')
a4 = input('Quarto aluno: ')
lista = sample([a1, a2, a3, a4], k=4)
print('A ordem de apresentação será: {}'.format(lista))
#forma 3
#from random import choice
#a1 = input('Primeiro aluno: ')
#a2 = input('Segundo aluno: ')
#a3 = input('Terceiro aluno: ')
#a4 = input('Quarto aluno: ')
#lista = [a1, a2, a3, a4]
#primeiro = choice(lista)
#print('O primeiro aluno a apresentar será: {}'.format(primeiro))
#lista.remove(primeiro)
#segundo = choice(lista)
#print('O segundo aluno a apresentar será: {}'.format(segundo))
#lista.remove(segundo)
#terceiro = choice(lista)
#print('O terceiro aluno a apresentar será: {}'.format(terceiro))
#lista.remove(terceiro)
#quarto = choice(lista)
#print('O último aluno a apresentar será: {}'.format(quarto))
#lista.remove(quarto)
|
bb4a8f606ab02c1c198c339fadc59a2992c23da8 | sumanth82/py-practice | /python-workbook-practice/76-100/84-piglet.py | 554 | 3.71875 | 4 | # Use pyglet library to create a hello world application
# It should pop open a window which displays - Hello World;
# pyglet library is used for gaming apps/softwares
import pyglet
window = pyglet.window.Window()
label=pyglet.text.Label('Hello, World',
font_name='Times New Roman',
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center')
@window.event
def on_draw():
window.clear()
label.draw()
pyglet.app.run() |
6f064f3fe9a22ff6e5a0193f4ed4a6f280537b25 | AbhayKumarJain/Hackerrank-Codes | /30 Days of Code/D1-Data-Types.py | 2,530 | 4.0625 | 4 | '''
Objective
Today, we're discussing data types. Check out the Tutorial tab for learning materials and an instructional video!
Task
Complete the code in the editor below. The variables
, , and
are already declared and initialized for you. You must:
Declare
variables: one of type int, one of type double, and one of type String.
Read
lines of input from stdin (according to the sequence given in the Input Format section below) and initialize your
variables.
Use the
operator to perform the following operations:
Print the sum of
plus your int variable on a new line.
Print the sum of
plus your double variable to a scale of one decimal place on a new line.
Concatenate
with the string you read as input and print the result on a new line.
Note: If you are using a language that doesn't support using
for string concatenation (e.g.: C), you can just print one variable immediately following the other on the same line. The string provided in your editor must be printed first, immediately followed by the string you read as input.
Input Format
The first line contains an integer that you must sum with
.
The second line contains a double that you must sum with .
The third line contains a string that you must concatenate with
.
Output Format
Print the sum of both integers on the first line, the sum of both doubles (scaled to
decimal place) on the second line, and then the two concatenated strings on the third line.
Sample Input
12
4.0
is the best place to learn and practice coding!
Sample Output
16
8.0
HackerRank is the best place to learn and practice coding!
Explanation
When we sum the integers
and , we get the integer .
When we sum the floating-point numbers and , we get
.
When we concatenate HackerRank with is the best place to learn and practice coding!, we get HackerRank is the best place to learn and practice coding!.
You will not pass this challenge if you attempt to assign the Sample Case values to your variables instead of following the instructions above and reading input from stdin.
'''
i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
i2,d2,s2=0,0,''
# Read and save an integer, double, and String to your variables.
i2=int(input())
d2=float(input())
s2=input()
# Print the sum of both integer variables on a new line.
print(i+i2)
# Print the sum of the double variables on a new line.
print(d+d2)
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s+s2) |
3b260701f7b0f17fac57e74ebfdd1bf113f147ab | badbayesian/game_theory | /game_theory/model.py | 10,402 | 3.78125 | 4 | import copy
import itertools
import numpy as np
import pandas as pd
from game_theory.minimax import LinProg
class game():
"""Collection of methods to solve games in game theory.
Currently able to solve and find nash equilibriums for any two player game
with finite choices and deterministic strategies given player preferences
and actions sets (player payoffs)
Parameter:
----------
payoffs : list of list of each player's payoffs
payoff matrix inputed as a list of list of each players payoffs read
clockwise starting from the top-right sector (quadrant)
name : string
Name of game played
mixed : bool
If true, game is solved using mixed strategies
If false, game is solved with only deterministic strategies
Results:
--------
self.name : string
Name of the game played
self.players : int
Number of players in game (#TODO expand number of players)
self.dim : list of int
List of number of choices each player has in game
self.payoffs : matrix of tuples (#TODO expand number of players)
Stores payoffs as matrix of tuples as commonly stored in game theory
self.nash_location : list of tuples
Locations of all nash equilibriums in game
self.nash : tuple
Nash Equilibrium values #TODO multi nash and mixed nash
self.social_opt : tuple
Social optimal point which is defined as the sum with equal weights
"""
def __init__(self, payoffs, name='game', mixed=False):
"""Initialize and run game."""
self.name = name
self.players = 2
self.dim = [len(payoffs[0][0]), len(payoffs[0][1])]
self.payoffs = self.translate_payoffs(payoffs)
self.nash_location = self.find_nash(mixed)
self.social_optimal = self.find_social_opt()
try:
self.nash = self.payoffs[self.nash_location[0][0],
self.nash_location[0][1]]
except IndexError:
self.nash = None
except TypeError:
self.nash = "mixed"
def __repr__(self):
"""Print game with pandas, only 26 max choices for now."""
name = [[chr(i) for i in range(ord('A'), ord('Z') + 1)][0:self.dim[0]],
[chr(i) for i in range(ord('A'), ord('Z') + 1)][0:self.dim[1]]]
df = pd.DataFrame([self.payoffs[i] for i in range(0, self.dim[0])],
index=name[0], columns=name[1])
return(self.name + '\n\n' + str(df) + '\n\n' +
'Nash Equilibrum(s) at: ' + str(self.nash_location) + '\n\n' +
'Social Optimal of ' + str(self.social_optimal[0]) + ' at: ' +
str(self.social_optimal[1]))
def translate_payoffs(self, payoffs):
"""Manipulate payoffs arrays into matrix of tuples."""
payoff_matrix = np.zeros((self.dim[0], self.dim[1]), dtype='f,f')
for col in range(0, self.dim[0]):
for row in range(0, self.dim[1]):
payoff_matrix[col][row][0] = payoffs[0][col][row]
payoff_matrix[col][row][1] = payoffs[1][col][row]
return(payoff_matrix)
def find_nash(self, mixed):
"""Solve for the nash equilibrium coordinates.
Currently information is saved as a matrix of tuples. Unclear if that
will remain if multiagents are added.
#TODO multiagents
"""
if not mixed:
nash = np.zeros((self.dim[0], self.dim[1]), dtype='f,f')
player_1_choices = []
for row in range(0, self.dim[1]):
payoffs_per_column = [payoff[0] for payoff in
[column[row] for column in self.payoffs]]
player_1_choices.append(
np.argwhere(
payoffs_per_column == np.amax(payoffs_per_column)))
for row in range(0, self.dim[1]):
if len(player_1_choices[row].flatten()) == 1:
nash[player_1_choices[row].flatten()[0]][row][0] = 1
else:
for j in range(0, len(player_1_choices[row].flatten())):
nash[player_1_choices[row].flatten()[j]][row][0] = 1
player_2_choices = []
for col in range(0, self.dim[0]):
payoffs_per_row = [row[1] for row in self.payoffs[col]]
player_2_choices.append(
np.argwhere(payoffs_per_row == np.amax(payoffs_per_row)))
for col in range(0, self.dim[0]):
if len(player_2_choices[col].flatten()) == 1:
nash[col][player_2_choices[col].flatten()[0]][1] = 1
else:
for j in range(0, len(player_2_choices[col].flatten())):
nash[col][player_2_choices[col].flatten()[j]][1] = 1
coords = []
for col in range(0, self.dim[0]):
for row in range(0, self.dim[1]):
if nash[col][row][0] == 1 and nash[col][row][1] == 1:
coords.append([col, row])
return(coords)
else:
lp = LinProg()
sol = lp.ce(A=self.payoffs.flatten(), solver="glpk")
return(sol['x'])
def find_social_opt(self):
"""Find social optimal and its location."""
social_optimal = sum(self.payoffs[0][0])
social_optimal_loc = []
for col in range(0, self.dim[0]):
for row in range(0, self.dim[1]):
if social_optimal < sum(self.payoffs[col][row]):
social_optimal = sum(self.payoffs[col][row])
social_optimal_loc = [[col, row]]
elif social_optimal == sum(self.payoffs[col][row]):
social_optimal_loc.append([col, row])
return(social_optimal, social_optimal_loc)
class evolution():
"""Simulated iterative, non-memory games.
This method follows an evolutionary game theory flavor where each there are
different types of agents, each playing different games depending which
other agent they find. In each round, all agents are paired up with another
agent (same or different type) randomly. They play their game and are given
points accordingly. One can see how the scores evolve over time.
#TODO Population dynamics within game e.g. after a certain score the pop
either grows or diminishes.
Parameters:
-----------
games : dict
Dictionary of games with payoffs
player_pop : dict
Dictionary of agents and number of agents
number_of_games : int
Number of games
init_scores : #TODO
name : string
Name of enviroment of games
mixed : bool
If true, games are solved using mixed strategies
If false, games are solved with only deterministic strategies
Results:
--------
self.name : str
Name of enviroment
self.player_pop : dict
Dictionary of agents and number of agents
self.games :
self.number_of_games : int
self.mixed : bool
If true, games are solved using mixed strategies
If false, games are solved with only deterministic strategies
self.scores : array of dict
"""
def __init__(self, games, player_pop, number_of_games, init_scores=0,
name='env', mixed=False):
"""Initialize and run enviroment of games."""
self.name = name
self.player_pop = player_pop
self.games = games
self.number_of_games = number_of_games
self.mixed = mixed
self.scores = self.score_games()
def __repr__(self):
"""Print information of each different game."""
return(str([game(name='\n\n' + key, payoffs=values)
for (key, values) in self.games.items()]))
def score_games(self):
"""Run x games recording the score at after each game.
In this version, only two agents can meet each other to create a game.
As such, if there is an odd number of players, on player does not play
that round. The scores are saved as an array of dictonaries for easy
slicing.
Example:
[{'X': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Y': [0, 0, 0, 0, 0],
'Z': [0, 0, 0, 0, 0]},
{'X': [0, 0, 1, 0, 0, 0, 0, 0, 0, -2],
'Y': [-1, -1, -1, -2, 2],
'Z': [0, -1, 2, 2, 2]}]
"""
scores = [copy.deepcopy({key: [0] * values for (key, values)
in self.player_pop.items()})
for x in range(self.number_of_games)]
player_id = [item for sublist in [
[key + str(s) for s in list(range(0, values))] for
(key, values) in self.player_pop.items()] for item in sublist]
if len(player_id) % 2 != 0:
player_id = [None] + player_id
for i in range(1, self.number_of_games):
length = len(player_id)
index = np.random.choice(length, size=length, replace=False)
paired_list = list(zip([player_id[i] for i in index[::2]],
[player_id[i] for i in index[1::2]]))
for j in range(0, int(length / 2)):
if not all(paired_list[j]):
continue
players = [["".join(x) for _, x in
itertools.groupby(paired_list[j][0],
key=str.isdigit)],
["".join(x) for _, x in
itertools.groupby(paired_list[j][1],
key=str.isdigit)]]
try:
g = game(payoffs=self.games[str(players[0][0] +
" " + players[1][0])])
except KeyError:
g = game(payoffs=self.games[str(players[1][0] +
" " + players[0][0])])
scores[i][players[0][0]][int(players[0][1])] = (
scores[i - 1][players[0][0]][int(players[0][1])] +
g.nash[0])
scores[i][players[1][0]][int(players[1][1])] = (
scores[i - 1][players[1][0]][int(players[1][1])] +
g.nash[1])
return(scores)
|
968a885f41619acdb74cc8bb08f89a3e70d88f4f | bharat0071/Python_Assignments | /triangle_area.py | 270 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 16 20:21:08 2020
@author: MOHANA D
"""
#write a program to enter base and height of atraingle and find its area
h=float(input("enter height value:"))
b=float(input("enter base value:"))
a=(b*h)/2
print("area:",a) |
41f266997998141d1331f64b05a696b51138d366 | VinayakSingoriya/Data-Structures-Python | /Binary_Tree/14_Iterative Search In BST.py | 1,060 | 4.25 | 4 | # Implementation of Searching Operation in a BST in a Iterative Way.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printInorder(root):
if root is not None:
printInorder(root.left)
print(root.data, end=" ")
printInorder(root.right)
# A utility function to search a given key in BST
def search(root, key):
while(root != None):
if key == root.data:
return root
elif key < root.data:
root = root.left
else:
root = root.right
return None
root = Node(8)
root.left = Node(3)
root.right = Node(10)
root.left.left = Node(1)
root.left.right = Node(6)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
root.right.right = Node(14)
root.right.right.left = Node(13)
print("Inorder Traversal of Tree is:")
printInorder(root)
key = 13
isFound = search(root, key)
if isFound:
print(f"\n>> Element {key} Found\n")
else:
print(f"\n>> Element {key} Not Found\n")
|
e48cdd23e1c1ea5668e8fdb2fbd5415c5ed9f892 | mrgiser/helloworld-python | /oop/multipleInheritance.py | 686 | 4.09375 | 4 | class A:
def __init__(self,name):
self.name = name
print("class A init")
def hello(self, word):
print("class A helloA " + word)
class B:
def __init__(self,name2):
self.name2 = name2
print("class B init")
def hello2(self,word):
print("class B helloB " + word)
class C(A,B):
def __init__(self,name):
A.__init__(self,name)
B.__init__(self,name)
print('(C name: {})'.format(self.name))
print('(C name2: {})'.format(self.name2))
def hello(self,word):
A.hello(self,word)
def hello2(self,word):
B.hello2(self,word)
c = C("HF")
c.hello("word")
c.hello2("word2")
|
94c6de2b3be968e517c4baf85f937880fc28003b | snehamathur01/coding | /catc.py | 708 | 4.21875 | 4 | #!/usr/bin/python3
option='''
Press 1 to view file contents :
Press 2 to view multiple files contents :
Press 3 to show content preceding with line number :
Press 4 to create a file :
'''
print(option)
choice=int(input())
if choice == 1 :
print("enter file name")
f=input()
fi=open(f)
print(fi.read())
elif choice == 2 :
print("enter names of files")
files =input()
elif choice == 3:
name = input("Enter file name")
f = open(name)
text = f.readlines()
for i in range(1,len(text)+1):
print(i,text[i-1])
elif choice == 4:
name = input("enter file name to be created")
f=open(name,'w')
else :
print("invalid choice")
|
82cb46ddc3d1b1c3d94007134b7d2ae9e9153dca | artbohr/codewars-algorithms-in-python | /7-kyu/monty-hall-problem.py | 1,035 | 4.09375 | 4 | def monty_hall(c_door, p_guesses):
return int(round(sum([x/x for x in p_guesses if c_door!=x])/len(p_guesses)*100))
'''
The Monty Hall problem is a probability puzzle base on the
American TV show "Let's Make A Deal".
In this show, you would be presented with 3 doors:
One with a prize behind it, and two without (represented with goats).
After choosing a door, the host would open one of the other two doors
which didn't include a prize, and ask the participant if he or she
wanted to switch to the third door. Most wouldn't. One would think you
have a fifty-fifty chance of winning after having been shown a false door,
however the math proves that you significally increase your chances,
from 1/3 to 2/3 by switching.
In this program you are given an array of people who have all guessed on a
door from 1-3, as well as given the door which includes the price.
You need to make every person switch to the other door, and increase their
chances of winning. Return the win percentage (as a rounded int) of all participants.
'''
|
10a21c3b749e81497e9e6ea94546ca56e7e46126 | MichaelCurrin/machine-learning-server | /mlserver/lib/imageTransformer.py | 11,185 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""Image Transformer application file.
The purpose of the ImageTransformer is to transform (resize, crop, etc)
images so that images meet the requirements so that the images can be
sent to plugins, or returned.
We use float division from Python 3.x instead of floor division, so scaling
factor results are kept as floats and not rounded down to zero as an integer.
Usage for testing:
$ python -m lib.imageTransformer --help
"""
import os
import sys
from PIL import Image
class ImageTransformer(object):
"""Class for creating an image transformer instance, which is able contain
an image and manipulate it.
It is recommended to crop an image and the resize it (which also does some
cropping). Doing both together should give an identical image, but
doing resizing last ensures you always reach the target dimensions.
"""
def __init__(self):
"""Initialise an instance of the ImageTransformer class."""
self.image = None
def setImage(self, imageInput, mode='RGB', convert=True):
"""
Receive image then convert to Image object and store on instance.
When done working with an ImageTransformer instance, it is
recommended to use obj.image.close() to close the Image instance.
@param imageInput: Image input as path to local image file as a string.
Also accepts a readable file object in io.BytesIO format, but,
then it is recommended to close that file object or use a with
block so that it is removed from memory when no longer needed.
@param mode: Default 'RGB'. Image mode (string) to convert to,
provided that `convert` is True.
@param convert: Default True. Boolean flag to convert image
to required mode.
@return: None
"""
if isinstance(imageInput, str):
assert os.access(imageInput, os.R_OK), (
'Unable to read path to image: `{0}`.'.format(imageInput)
)
image = Image.open(imageInput)
self.image = image.convert(mode) if convert else image
def getImage(self):
"""Return the image stored on the instance.
It is recommended to close the image object after getting the image
from the Image Transformer.
@return: the image in the most recent state, either the original or
as modified.
"""
return self.image
def removeTransparency(self, bgColor=(255, 255, 255, 255)):
"""Remove transparent background from PNG images and converts to RGB
format.
@param bgColor: Background value to be used on replacing background
transparency of a PNG, as a tuple of 4 values from 0 to 255.
@return: None
"""
img = self.image
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and
'transparency' in img.info):
alpha = img.convert('RGBA').split()[-1]
bg = Image.new("RGBA", img.size, bgColor)
# Place original image on solid background.
bg.paste(img, mask=alpha)
img = bg.convert('RGB')
else:
img = img.convert('RGB')
# Overwrite image with the modified one with transparency removed.
self.image = img
def specialCrop(self, xCoord, yCoord, scaleFactorW, scaleFactorH,
minWidth=1, minHeight=1):
"""Crop an image around (X,Y) point coordinates to a fraction of the
actual image dimensions.
A co-ordinate point must be specified as a co-ordinate pair of values,
each on a percetnage scale exlcuding zero. i.e. from 1 to 100.
A crop factor must be supplied to indicate how much of the image
should be removed on cropping, where 0.9 would be 90% of the original
image.
@param xCoord: X co-ordinate of type int, or value which can be cast
to an int.
@param yCoord: Y co-ordinate of type int, or value which can be cast
to an int.
@param scaleFactorW: The target width crop factor, of type float.
@param scaleFactorH: The target height crop factor, of type float.
@param minWidth: Minimum image pixel width to crop to, to avoid getting
width of zero when cropping by a small percentage value on a
small image. Defaults to 1 if None.
@param minHeight: Minimum image pixel height to crop to. Defaults to
1 if None.
@return: None
"""
if minWidth is None or minHeight is None:
minWidth = minHeight = 1
xCoord = int(xCoord)
yCoord = int(yCoord)
assert 0 <= xCoord <= 100, (
'Expected the X co-ordinate {0} to be between 0 and 100.'
.format(xCoord)
)
assert 0 <= yCoord <= 100, (
'Expected the Y co-ordinate {0} to be between 0 and 100.'
.format(xCoord)
)
assert isinstance(scaleFactorW, float), (
'Expected scaleFactorW to be type `float`, but got type `{0}`.'
.format(type(scaleFactorW).__name__)
)
assert isinstance(scaleFactorH, float), (
'Expected scaleFactorH to be type `float`, but got type `{0}`.'
.format(type(scaleFactorH).__name__)
)
img = self.image
w = img.size[0]
h = img.size[1]
# Convert co-ordinates (percentage values) into pixel values.
xPx = int(xCoord / 100 * w)
yPx = int(yCoord / 100 * h)
targetW = max(int(scaleFactorW * w), minWidth)
targetH = max(int(scaleFactorH * h), minHeight)
# Get pixels for the corners of the cropped image box.
bStartX = xPx - (targetW / 2)
bEndX = xPx + (targetW / 2)
bStartY = yPx - (targetH / 2)
bEndY = yPx + (targetH / 2)
# Bring the target box corners back within the original image area if
# the mark was placed too close to the original image borders.
# Otherwise we end up with a part the original image surrounded
# by next to a black area.
if bStartX < 0:
bEndX = bEndX + abs(bStartX)
bStartX = 0
if bEndX > w:
bStartX = bStartX - abs(w - bEndX)
bEndX = w
if bStartY < 0:
bEndY = bEndY + abs(bStartY)
bStartY = 0
if bEndY > h:
bEndY = h
bStartY = bStartY - abs(h - bEndY)
self.image = img.crop((bStartX, bStartY, bEndX, bEndY))
def specialResize(self, targetWidth, targetHeight):
"""
Resize image without distorting it.
We calculate aspect ratio as width divided by height to do the
resizing. If the target width and height are supplied for a
rectangle or a square, either way we take off part of the image
to get to the target size, but without distorting the image.
i.e. resizing a landscape image to a square will remove the left
and right sides, instead of squashing all info in the original image
into a square. Note that the thinner the original image before
cropped to a square, the more info on the sides of the target
square which will be lost.
@param targetWidth: the width in pixels of the resized image, as
type int.
@param targetHeight: the height in pixels of the resized image, as
type int.
@return: None
"""
assert isinstance(targetWidth, int), (
'Expected targetWidth as type `int` but got type `{0}`.'
.format(type(targetWidth).__name__)
)
assert isinstance(targetHeight, int), (
'Expected targetHeight as type `int` but got type `{0}`.'
.format(type(targetHeight).__name__)
)
img = self.image
w = img.size[0]
h = img.size[1]
originalAspectRatio = w / h
targetAspectRatio = targetWidth / targetHeight
if targetAspectRatio != originalAspectRatio:
if targetAspectRatio > originalAspectRatio:
# Image is too tall so take some off the top and bottom.
scaleFactor = targetWidth / w
cropSizeWidth = w
cropSizeHeight = targetHeight / scaleFactor
topCutLine = (h - cropSizeHeight) / 2
sides = (0, topCutLine, cropSizeWidth,
topCutLine + cropSizeHeight)
else:
# Image is too wide so take some off the sides.
scaleFactor = targetHeight / h
cropSizeWidth = targetWidth / scaleFactor
cropSizeHeight = h
sideCutLine = (w - cropSizeWidth) / 2
sides = (sideCutLine, 0, sideCutLine + cropSizeWidth,
cropSizeHeight)
boxCorners = tuple(int(round(n)) for n in sides)
img = img.crop(boxCorners)
img = img.resize((targetWidth, targetHeight), Image.ANTIALIAS)
# Overwrite the image with the resized and possibly cropped version.
self.image = img
def test(args):
"""Test function for internal use when running script directly.
Does a test on an input image path to perform cropping and resizing on it.
Transparent backgrounds are removed for PNGs.
Saves the modified images to the same directory as the image path but
with a different filename.
"""
if not args or set(args) & set(('-h', '--help')):
print("Usage: python -m lib.imageTransformer [IMAGE_PATH] [-h|--help]")
print("IMAGE_PATH: path to file image to transform.")
else:
imgPath = args[0]
imgTr = ImageTransformer()
imgTr.setImage(imgPath)
# Remove background transparency.
if imgTr.getImage().format == 'PNG':
print("Remove transparency.")
imgTr.removeTransparency()
img = imgTr.getImage()
# Use original path but add in text before the extension.
newPath = "{0}_SOLID_BG.png".format(imgPath.rsplit('.', 1)[0])
print(" - writing out to: {0}".format(newPath))
img.save(newPath, format='png')
# Crop the image and write out.
print("Crop.")
# Place mark at centre of image.
x = 50
y = 50
# Crop to 40 % of original.
cropFactor = 0.4
imgTr.specialCrop(x, y, cropFactor, cropFactor)
img = imgTr.getImage()
newPath = "{0}_CROP.jpeg".format(imgPath.rsplit(".", 1)[0])
print(" - writing out to: {0}".format(newPath))
img.save(newPath, format='jpeg')
# Resize the cropped image and write out.
print("Resize.")
targetH = 299
targetW = 299
imgTr.specialResize(targetH, targetW)
img = imgTr.getImage()
newPath = "{0}_CROP_THEN_RESIZE.jpeg".format(imgPath.rsplit('.', 1)[0])
print(" - writing out to: {0}".format(newPath))
img.save(newPath, format='jpeg')
if __name__ == '__main__':
test(sys.argv[1:])
|
13064e0569f38840ac4c4f5b468619795104d71a | cs-richardson/fahrenheit-jelchakieh21 | /fahrenheit.py | 278 | 3.921875 | 4 | while True:
try:
celsiusInput = float(input ("Input Celsius: "))
fahrenheitOutput = 1.8*celsiusInput+32
print("Fahrenheit:" , fahrenheitOutput)
import sys
sys.exit()
except ValueError:
print("Fooey! That's not a number!")
|
c3c31e0d2abf127c8a47903fcdaba587db206680 | ag-python/pyzzle | /pyzzle/datafile.py | 3,762 | 4.125 | 4 | import sqlite3
import os
class Table(type):
"""A metaclass used to represent the tables of a database.
Intstances of a table class are stored in the rows attribute,
indexed by their primary key. For instance, Slide.rows['foobar']
accesses the instance 'foobar' from the Slide class,
which uses the Table metaclass.
Intstances can also be accessed like a dictionary (e.g. Slide['foobar']),
or like attributes (e.g. Slide.foobar) - this comes in handy when
scripting slides for a large scale video game.
"""
def __init__(cls, name, bases=(), attrs={}):
super(Table, cls).__init__(name, bases, attrs)
cls.rows={}
def __getattr__(cls, attr):
return cls.rows[attr]
def __getitem__(cls, key):
if not key: return None
if type(key) ==cls: return key
else: return cls.rows[key]
def __contains__(cls,item):
if type(item)==cls: return item in cls.rows.values()
else: return item in cls.rows.keys()
def __iter__(cls):
return cls.rows.itervalues()
class Row:
"""A generic row of a database.
This class is used in place of custom classes that
would just be used to store data without performing behavior.
A good example of this in practice are stages."""
@staticmethod
def _load(cells):
return Row(cells)
def __init__(self, cells):
self.cells=cells
def __getattr__(self, attr):
return self.cells[attr]
def __getitem__(self, key):
return self.cells[key]
def __setitem__(self, key, value):
self.cells[key]=value
def __contains__(self,item):
return item in self.cells
def __nonzero__(self):
return True
class DB:
"""Represents an SQLite database used to store data for Pyzzle games.
This class performs higher level functionality than classes within
the sqlite3 module. It also acts as an Adapter Class that may allow
other file formats to be implemented in the future."""
def __init__(self, file=':memory:'):
self._connection=sqlite3.connect(file)
self._connection.row_factory = sqlite3.Row
self._cursor = self._connection.cursor()
def load(self, TableClass, tablename=None, idcolumn='id'):
"""Loads all instances a Table class from rows in pyzzle.datafile.
@param TableClass: A class that uses the Table metaclass.
@param tablename: The name of the table in the database.
If not specified, the name of TableClass is used instead.
@param idcolumn: The name of the primary key column for the table.
"""
tablename = tablename if tablename else TableClass.__name__
query='select * from '+tablename
results=self._cursor.execute(query)
rows={}
for cells in results:
rows[cells[idcolumn]]=TableClass._load(cells)
return rows
def save(self, TableClass, tablename=None, idcolumn='id'):
"""Saves all members of a Table class to pyzzle.datafile."""
tablename = tablename if tablename else TableClass.__name__
self._cursor.execute('delete from '+tablename)
for row in TableClass:
cells=row._save()
query=' '.join(['insert into',tablename,'(',
', '.join(cells.keys()),
') values (',
', '.join(('?')*len(cells)),')'])
self._cursor.execute(query, cells.values())
self._connection.commit()
def close(self):
self._cursor.close()
self._connection.close() |
e6b478b0b54658996c0284ff8f9c289289239536 | adamandrz/Python-basics | /practice-python/eve-odd.py | 554 | 3.59375 | 4 |
number = int( input("Podaj liczbe (dzielna) :" ) )
check = int( input ("Podaj dzielną :"))
if number % 2 == 0:
if number == 4:
print ( "To jest liczba cztery, która jest liczbą parzystą! ")
else:
print ( str(number) + " jest liczba parzystą! ")
else:
print ( str(number) + " jest liczba nieparzystą! ")
res = number % check
if res == 0:
print (str(number) + " Dzieli się przez " + str(check) + " bez reszty.")
else:
print (str(number) + " Dzieli się przez " + str(check) + " z resztą " + str(res) + " .")
|
c523ab39acdb669a694049e67a8d54c2c628c994 | haivt28/advent-of-code | /2020/day10.py | 1,895 | 3.5625 | 4 | input = open('input/day10.txt').read()
# PART 1
adapters = list(map(int, input.split('\n')))
adapters = sorted(adapters)
init = 0
count1 = 0
count3 = 0
for adapt in adapters:
if adapt - init == 1:
count1 += 1
if adapt - init == 3:
count3 += 1
init = adapt
print(count1*(count3+1))
# PART 2
# Solution 1: Find set of pattern
# Split adapters into groups of consecutive ones,
# then calculate the possibility of each group and multiply them.
# For example:
# - Group of 3 consecutive adapters has 2 cases
# - Group of 4 consecutive adapters has 4 cases
# - Group of 5 consecutive adapters has 7 cases
adapters = [0] + adapters + [max(adapters) + 3]
count = 1
res = 1
for i in range(1, len(adapters)):
if adapters[i] == adapters[i - 1] + 1:
count += 1
else:
if count == 5:
res *= 7
elif count == 4:
res *= 4
elif count == 3:
res *= 2
count = 1
print(res)
# Solution 2: Dynamic Programming (Top Down)
traveled_cost = {}
def travel(adapter):
global traveled_cost
if adapter not in adapters:
return 0
if adapter not in traveled_cost:
traveled_cost[adapter] = travel(adapter - 1) + travel(adapter - 2) + travel(adapter - 3)
return traveled_cost[adapter]
travel(max(adapters))
print(res)
# Solution 3: Dynamic Programming (Bottom Up)
adapters = [100, 100] + adapters
cost = {100: 0, 0: 1}
for i in range(3, len(adapters)):
current_adapter = adapters[i]
current_cost = 0
if current_adapter - adapters[i-1] <= 3:
current_cost += cost[adapters[i-1]]
if current_adapter - adapters[i-2] <= 3:
current_cost += cost[adapters[i-2]]
if current_adapter - adapters[i-3] <= 3:
current_cost += cost[adapters[i-3]]
cost[current_adapter] = current_cost
print(cost[max(adapters)])
|
816f6572afa4cba53d4845153653e21574443061 | sangeethanandha/SANGEETHA | /b85.py | 153 | 3.953125 | 4 | str=input("enter the string")
lst=list(str)
even=""
odd=""
i=1
for j in lst:
if i%2==0:
even=even+j
else:
odd=odd+j
i=i+1
print(odd, even)
|
d80062915ffe2fe07946c031a6492506e053e86a | DenisIvanovo/test-task | /#1.py | 1,198 | 4.34375 | 4 | """
Дан массив чисел, состоящий из некоторого количества подряд идущих единиц,
за которыми следует какое-то количество подряд идущих нулей:
111111111111111111111111100000000.
Найти индекс первого нуля (то есть найти такое место, где заканчиваются единицы,
и начинаются нули)
"""
array = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# Вариант 1
def element_index(arr):
# Ищем индекс первого нуля.
return arr.index(0) # Возвращаем найденый индекс элемента.
# Вариант 2
def element_index2(arr):
# Ищем индекс первого нуля.
ind = 0 # Начальный индекс.
# В цикле перебираем все элементы и сверяем значение.
for i in arr:
if i == 0:
return ind
else:
ind += 1
print(element_index(array))
print(element_index2(array))
|
a1739de74fcf824ff8eea95a38b21e0cae8c76fb | E2057SalihPoyraz/Python-Daily_Challenges | /majority-element.py | 879 | 3.90625 | 4 | # QUESTION: Level of Interview Question = Easy
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
# Example 1:
# Input: [3,2,3]
# Output: 3
# Example 2:
# Input: [2,2,1,1,1,2,2]
# Output: 2
# çözüm:1
for i in Input:
if Input.count(i) > len(Input) / 2:
print(i)
break
# çözüm:2
class Solution:
def majorityElement(self, nums: List[int]) -> int:
x = set(nums)
for i in x:
if nums.count(i) > len(nums)/2:
return i
#çözüm:3
def majorityElement(nums):
return max(set(nums),key=nums.count)
# çözüm:4
def bul(arr):
for i in set(arr):
if arr.count(i) > len(arr)/2: return i
|
c5d160fa90534b6b83e6f4649417122dce98fa1d | Goku-kun/1000-ways-to-print-hello-world-in-python | /using-for.py | 96 | 4.15625 | 4 | #print "Hello, World!" using for loop
for letter in "Hello, World!":
print(letter, end="") |
cb2b22ff3ef934654983f20a2f789861fd69fdb6 | wslxko/LeetCode | /tencentSelect/number14.py | 839 | 4.125 | 4 | '''
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def majorityElement(self, nums):
newNums = list(set(nums))
a = None
for num in newNums:
if nums.count(num) > len(nums) / 2:
a = num
return a
if __name__ == "__main__":
a = Solution()
nums = [3,2,3]
print(a.majorityElement(nums))
|
6e9d02087889e7fdc6413d4a9091d8a7e4dcdee9 | zaleskasylwia/Resident | /community.py | 2,357 | 3.546875 | 4 | import csv
class Community:
def __init__(self, community_name, year_of_fundation, address):
if type(community_name) is str and type(year_of_fundation) is int and type(address) is str:
self.community_name=community_name
self.year_of_fundation=year_of_fundation
self.address=address
self.employees=[]
self.residents=[]
else:
raise TypeError
def add_employee(self, employee):
# czy tu mam dodawać przez klase Employee?
if employee not in self.employees:
self.employees.append(employee)
def add_resident(self, resident):
if resident not in self.residents:
self.residents.append(resident)
def save_community_to_file(self):
HEADERS = ['Community name', 'Year of fundation', 'address']
with open('{}.csv'.format(self.community_name), 'w', newline='') as csvfile:
community_writer = csv.writer(csvfile)
community_writer.writerow(HEADERS)
community_writer.writerow([self.community_name, self.year_of_fundation, self.address])
def read_community_from_file(self, csv_path):
community = []
with open(csv_path) as csvfile:
community_reader = csv.reader(csvfile)
next(community_reader) # skip heades
for data in community_reader:
community.append(data)
return community
def find_longest_working_employee(self):
if self.employeess == []:
raise IndexError
else:
longest_working_employee = self.employees[0]
for emply in self.employees:
if emply < longest_working_employee:
longest_working_employee = emply
return longest_working_employee
def calculate_total_community_area(self):
total_community_area = 0
for flat_area in self.resident:
total_community_area += flat_area
return total_community_area
def main():
com = Community("Nauczyciela", 2014, "Szkolan 41 Oświęcim")
com.save_community_to_file()
ab = Community("Na", 2014, "Kraków")
ab.save_community_to_file()
print(com.read_community_from_file("Nauczyciela.csv"))
print(ab.read_community_from_file("Na.csv"))
if __name__ == "__main__":
main()
|
d337e135daac60dbe0a182e168faeb53c93fa6e9 | Garvit-32/DL-from-scratch | /math.py | 4,712 | 3.640625 | 4 | import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from numpy import ndarray
from typing import List, Callable, Dict
def square(x):
return np.power(x, 2)
def relu(x):
return np.maximum(0, x)
def sigmoid(x):
return 1 / (1+np.exp(-x))
# 'A function to calculate deriv'
def deriv(func: Callable[[ndarray], ndarray], input_: ndarray, diff: float = 0.001) -> ndarray:
return (func(input_ + diff) - func(input_ - diff)) / (2 * diff)
# A Function takes in an ndarray as an argument and produces an ndarray
Array_Function = Callable[[ndarray], ndarray]
# A Chain is a list of function
Chain = List[Array_Function]
def chain_length_2(chain: Chain, x: ndarray) -> ndarray:
# 'Evaluate two function in a row in a chain'
assert len(chain) == 2
f1 = chain[0]
f2 = chain[1]
return f2(f1(x))
def chain_deriv_2(chain: Chain, input_range: ndarray) -> ndarray:
# Uses chain rule (f2(f1(x))' = f2'(f1(x)) * f1'(x)
assert len(chain) == 2
assert input_range.ndim == 1
f1 = chain[0]
f2 = chain[1]
# df1/dx
df1dx = deriv(f1, input_range)
# df2/dx
df2du = deriv(f2, f1(input_range))
return df1dx * df2du
def plot_chain(ax, chain: Chain, input_range: ndarray, length: int = 2) -> ndarray:
assert input_range.ndim == 1
if length == 2:
output_range = chain_length_2(chain, input_range)
elif length == 3:
output_range = chain_length_3(chain, input_range)
ax.plot(input_range, output_range)
def plot_chain_deriv(ax, chain: Chain, input_range: ndarray, length: int = 2) -> ndarray:
if length == 2:
output_range = chain_deriv_2(chain, input_range)
elif length == 3:
output_range = chain_deriv_3(chain, input_range)
ax.plot(input_range, output_range)
def chain_length_3(chain: Chain, x: ndarray) -> ndarray:
# Evaluates three functions in a row, in a "Chain".
assert len(chain) == 3
f1 = chain[0]
f2 = chain[1]
f3 = chain[2]
return f3(f2(f1(x)))
def chain_deriv_3(chain: Chain, input_range: ndarray) -> ndarray:
# Uses the chain rule to compute the derivative of three nested functions:
# (f3(f2(f1)))' = f3'(f2(f1(x))) * f2'(f1(x)) * f1'(x)
assert len(chain) == 3
f1 = chain[0]
f2 = chain[1]
f3 = chain[2]
# f1(x)
f1_of_x = f1(input_range)
# f2(f1(x))
f2_of_x = f2(f1_of_x)
# df3du
df3du = deriv(f3, f2_of_x)
# df2du
df2du = deriv(f2, f1_of_x)
# df1dx
df1dx = deriv(f1, input_range)
return df1dx * df2du * df3du
def multiple_inputs_add(x: ndarray, y: ndarray, sigma: Array_Function) -> float:
# forward pass
assert x.shape == y.shape
a = x + y
return sigma(a)
def multiple_inputs_add_backward(x: ndarray, y: ndarray, sigma: Array_Function) -> float:
# Computes the derivative of this simple function with respect to both inputs
a = x + y
dsda = deriv(sigma, a)
dadx, dady = 1, 1
return dsda * dadx, dsda * dady
def matmul_forward(X: ndarray, W: ndarray) -> ndarray:
# Computes the forward pass of a matrix multiplication
assert X.shape[1] == W.shape[0]
return np.dot(X, W)
def matmul_backward_first(X: ndarray, W: ndarray) -> ndarray:
# X =[x1,x2,x3,x4,x5]
# w= [w1
# w2
# w3]
# N = X.W = [x1 * w1 , x2 * w2 ,x3 * w3]
# And looking at this, we can see that if
# for example, x1 changes by ϵ units, then N will change by w1 × ϵ units
# dN/dX = [w1,w2,w3,w4,w5]
# dN/dX = transpose of W
dNdX = np.transpose(W, (1, 0))
return dNdX
def matrix_forward_extra(X: ndarray, W: ndarray, sigma: Array_Function) -> ndarray:
assert X.shape[1] == W.shape[0]
N = np.dot(X, W)
S = sigma(N)
return S
def matrix_function_backward_1(X: ndarray, W: ndarray, sigma: Array_Function) -> ndarray:
assert X.shape[1] == W.shape[0]
N = np.dot(X, W)
S = sigma(N)
dSdN = deriv(sigma, N)
dNdX = np.transpose(W, (1, 0))
return np.dot(dSdN, dNdX)
def matrix_function_forward_sum(X: ndarray, W: ndarray, sigma: Array_Function) -> float:
assert X.shape[1] == W.shape[0]
N = np.dot(X, W)
S = sigma(N)
L = np.sum(S)
return L
def matrix_function_backward_sum_1(X: ndarray, W: ndarray, sigma: Array_Function) -> ndarray:
# Compute derivative of matrix function with a sum with respect to the first matrix input
assert X.shape[1] == W.shape[0]
N = np.dot(X, W)
S = sigma(N)
L = np.sum(S)
dLdS = np.ones_like(S)
dSdN = deriv(sigma, N)
dLdN = dLdS * dSdN
dNdX = np.transpose(W, (1, 0))
dLdX = np.dot(dSdN, dNdX)
return dLdX
|
9b75139623ef1c7edf76b90f02c5d79f3bd40a32 | sumrdev/Code-Portfolio | /OBJECTORIENTED/Geometry2D/Circle.py | 220 | 3.921875 | 4 | class Circle:
def __init__(self, x, y ,r):
self.x = x
self.y = y
self.r = r
def printCircle(self):
print((self.x, self.y), "Radius: ", self.r)
c = Circle(20,10,3)
c.printCircle() |
0c7ebc72746934b5e74bbb42f4b11b049a4a806e | niurerav/Batch_rename | /batch_rename.py | 638 | 3.625 | 4 | """
This script removes a substring from a filename.
BackStory: I downloaded bunch of mp3 files from webmusic.in and
as expected all of them had "_(webmusic.in)" sub string attached to them.
And as such I put on my geeky hat and wrote this simple script to
remove the substring in the file.
"""
import os
for filename in os.listdir('.'):
if filename.startswith("(webmusic.in)_"):
os.rename(filename, filename[14:])
elif (filename.find("_(webmusic.in)")!= -1):
index = filename.find("_(webmusic.in)")
end_index = filename.find(".mp3")
new_filename = filename[:index] + filename[end_index:]
os.rename(filename, new_filename)
|
c6cf7198030e9c7e9f0e348000f5f88280996a4f | lamatehu/study-c-python | /python/chapter 5/exams/2.py | 481 | 3.546875 | 4 |
import turtle
def koch(size, n):
if n == 0:
turtle.fd(size)
else:
for anger in [0, 60, -120, 60]:
turtle.right(anger)
koch(size/3, n-1)
def main(level):
a= level
turtle.setup(600, 600)
turtle.penup()
turtle.goto(-200, 100)
turtle.pendown()
turtle.pensize(2)
koch(200, a)
turtle.done()
try:
level = eval(input("请输入科赫曲线的阶: "))
main(level)
except:
print("输入错误")
|
361f1a500b6738377eb779f0a9775127b5a334ec | saminathansami/alphabet | /leapyear.py | 184 | 3.578125 | 4 | ly=int(input(" "))
if ly%100==0:
if ly%400==0:
print ('yes')
else:
print ('no')
elif (ly%4==0):
print ('yes')
else:
print ('no')
|
73cedcd757c5f6d2bd710bd1d78a840d1734f3c5 | alexs95/ARC | /src/manual_solve.py | 25,154 | 3.5 | 4 | #!/usr/bin/python
"""NUI Galway CT5148 Programming and Tools for AI (James McDermott)
CT5148 Assignment 3: ARC
Student name(s): Alexey Shapovalov
Student ID(s): XXXXXXXX
GitHub: https://github.com/alexs95/ARC
Choice of Task
---------------------------------------------------------------
I looked through about 50 - 75 different tasks to decide which ones to implement.
What I found out is that tasks that I found the hardest to solve were ones I could not
figure out the pattern to the solution. However, once I figured out the pattern, I
almost always figured they would be fairly easy to implement.
As examples to this point, these were the tasks I found the hardest to solve:
6d0160f0 - this took one took the longest to figure out, was at it for at least 15 mins
44f52bb0 - still not sure if I what I think the answer to this is correct
68b16354 - convinced myself this one was a bug (looked purely random) before I finally figured it out
6d58a25d - not sure why it took so long but could not figure it out
99b1bc43 - I came up with very imaginative theories on what dictates
the amount of lines coming out of the triangle
Instead of choosing any of these, the criteria I judged the tasks "difficulty" was how hard
I thought it would be to solve them programmatically.
The main "feel" for this difficulty was when I had to take a minute to figure out what
it is I actually did to come up with a solution. Judging by this criteria, I would consider
much easier to implement. For example, 68b16354 would be to swap rows.
Code structure & GitHub
---------------------------------------------------------------
I did all my work on the assignment branch which I merged to master when I was complete.
The README contains contains comments about the purpose of this fork.
The code is laid out as follows:
At first there are three classes representing different levels of abstraction
about objects in the task. These provide an API for querying the input.
Then each solve_ function with functions that are used in the solutions below
each solve_ function.
Reflection
---------------------------------------------------------------
I would consider the main similarity between these (and all the other) tasks
pattern matching and interpretation of colors.
All of the challenges require you to figure out (the pattern) a set of transformations
to the input grid by interpreting what the colors mean.
You have a set of examples to figure out this pattern. In my solution the
three classes contain transformations (and also the function downscale if it was
implemented more generally), could potentially be used for more than one task.
The method get_adjacency_collections would be an example of pattern matching.
The actual solutions would in a way contain the interpretation of the colors.
Similarities:
Interpretation: All three solutions had a concept of a "background" on which
stuff was happening.
Pattern matching: All three required understanding of the idea of the significance of
cells of equal being color next to each other.
Transformation: 0e206a2e and required understanding geometrical transformation concepts
(but the transformations themselves were different).
Differences:
The most obvious difference is that the pattern to solve each task was different.
There was a concept of a path in b782dc8a.
Relationship to Chollet paper
---------------------------------------------------------------
Sadly as this was our second last assignment I was really stuck for time (could not start as soon
as I liked as I had to finish previous ones). I only had a chance to skim through the paper so
this section might be taken with a pinch of salt.. possibly a lot of salt.
I did want to give it a go. I will read it over Christmas properly for sure,
I found it very interesting!
My interpretation of the goal of ARC dataset is to provide a dataset that if solved would represent
a more general artificial intelligence. It explains how state of the art applications of machine
learning are usually very specific to one narrow task, e.g. playing Go or chess,
but are not generally intelligent. The ARC dataset sets out to contain general
tasks that would need to be a solved by an AI that is more generally intelligent.
The Chollet paper describes a set of priors that an entity can have to solve
these general tasks. I am thinking these would correspond to the similarities
in my solutions. For example the concept of rotating, moving, recognising squares
etc. This would loosely correspond to the three classes at the start of my solution.
The actual solve_ functions would correspond to the use of these priors to solve the
tasks, I guess this is what the AI would actually need to have understand.
"""
from itertools import combinations, product
from collections import defaultdict
from numpy import linalg
import numpy as np
import json
import os
import re
class ColouredPoint:
"""An abstraction of a point in the input array providing utility methods and
transformations on the point"""
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
def euclidean(self, other):
"""Euclidean distance between this and other"""
return linalg.norm([self.x - other.x, self.y - other.y])
def rotate(self, degrees):
"""Returns a new point by rotating this one about the origin (0, 0) by the given degrees"""
# Based on https://www.onlinemathlearning.com/transformation-review.html
if degrees == 90:
return ColouredPoint(x=-self.y, y=-self.x, color=self.color)
elif degrees == 180:
return ColouredPoint(x=-self.x, y=-self.y, color=self.color)
elif degrees == 270:
return ColouredPoint(x=self.y, y=-self.x, color=self.color)
else:
raise ValueError("Unsupported degrees: {}".format(degrees))
def reflect(self, axis):
"""Returns a new point by reflecting this one across the given axis"""
# Based on https://www.onlinemathlearning.com/transformation-review.html
if axis == "x":
return ColouredPoint(x=self.x, y=-self.y, color=self.color)
elif axis == "y":
return ColouredPoint(x=-self.x, y=self.y, color=self.color)
elif axis == "x=y":
return ColouredPoint(x=self.y, y=self.x, color=self.color)
else:
raise ValueError("Unsupported axis: {}".format(axis))
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.color == other.color
def __str__(self):
return "({}: ({}, {}))".format(self.color, self.x, self.y)
class Collection:
"""An abstraction representing a collection of points: provides information about the points
and methods (transformations) that operate the collection as a whole.
"""
def __init__(self, points):
points = list(points)
self.points = points
self.min_x = min(p.x for p in points)
self.min_y = min(p.y for p in points)
self.max_x = max(p.x for p in points)
self.max_y = max(p.y for p in points)
self.shape = (self.max_x - self.min_x + 1, self.max_y - self.min_y + 1)
self.colors = set([p.color for p in points])
def asnumpy(self, background=0):
arr = np.full(self.shape, background)
for p in self.points:
arr[p.x - self.min_x][p.y - self.min_y] = p.color
return arr
def fill(self, arr, color=None):
"""Fills arr (numpy array) with the points in this collection. If color is provided each point
will be filled with color rather than the color of the point
"""
for point in self.points:
arr[point.x][point.y] = color if color is not None else point.color
def translate(self, source, destination):
"""Translates each point in the collection defined by the translation
from source (point) to destination (point)
"""
# Based on https://www.onlinemathlearning.com/transformation-review.html
x_diff = destination.x - source.x
y_diff = destination.y - source.y
return Collection(
ColouredPoint(x=p.x+x_diff, y=p.y+y_diff, color=p.color) for p in self.points
)
def rotate(self, degrees):
return Collection(p.rotate(degrees) for p in self.points)
def reflect(self, axis):
return Collection(p.reflect(axis) for p in self.points)
def __str__(self):
return str(self.asnumpy())
def __eq__(self, other):
if len(other.points) == len(self.points):
sorted_points = sorted(other.points, key=lambda p: (p.x, p.y, p.color))
other_sorted_points = sorted(self.points, key=lambda p: (p.x, p.y, p.color))
return all(a == b for (a, b) in zip(sorted_points, other_sorted_points))
else:
return False
class Grid:
"""An abstraction representing a grid - provides information about arr and
contains methods that return Collections and ColouredPoints"""
def __init__(self, X):
self.arr = X
self.visited_mark = -1
def colors(self):
"""Returns a color frequency distribution as a dict"""
unique, counts = np.unique(self.arr, return_counts=True)
return {k: v for (k, v) in zip(unique, counts)}
def get_points_by_color(self, color=None):
"""Returns a Collection of all the points that have the same color"""
points = []
for x in range(self.arr.shape[0]):
for y in range(self.arr.shape[1]):
if self.arr[x][y] == color:
points.append(ColouredPoint(x, y, color))
return Collection(points)
def get_adjacency_collections(self, avoid_color, match_color=None):
"""Returns a list of Collection consisting of points that are not avoid_color and have
at least one other neighbouring point on either the x-axis or the y-axis
If match_color is set the points must be that color
"""
collections = []
visited = np.zeros(self.arr.shape)
for x in range(self.arr.shape[0]):
for y in range(self.arr.shape[1]):
collection = self._traverse(x, y, visited, avoid_color, match_color)
if collection is not None:
collections.append(Collection(collection))
return collections
def _traverse(self, x, y, visited, avoid_color, match_color):
stop_condition = (
x == -1 or x == self.arr.shape[0] or
y == -1 or y == self.arr.shape[1] or
self.arr[x][y] == avoid_color or
visited[x][y] == self.visited_mark or
(match_color is not None and self.arr[x][y] != match_color)
)
if not stop_condition:
visited[x][y] = self.visited_mark
point = ColouredPoint(x, y, self.arr[x][y])
points = [point]
for neighbour in ((x, y-1), (x, y+1), (x+1, y), (x-1, y)):
nx, ny = neighbour
new = self._traverse(nx, ny, visited, avoid_color, match_color)
if new is not None:
points += new
return points
return None
def solve_0e206a2e(X, background=0):
"""I would consider this one to be the hardest of all my choices. It was not super easy
to solve as a human (in comparison to others) but also the real difficulty was that
even after thinking about it for a while, I was not fully sure of the exact steps
I took in my head to solve it.
The steps in my head for solving it are:
1. Find the shape(s) and the "dots" that the shapes need to be placed on.
2. Figure out which shape belongs to which set of "dots".
3. Move the shape(s) into the correct position, judging it by the dots.
4. Remove the old position of the shape(s).
Algorithm:
1. The pattern here was that shapes would need to be connected by at least
one neighbour on the horizontal or vertical. The way I figured out the
reference "dots" was by creating sets of that that were closest together,
my metric for closest was summed distance.
2. I brute forced this, just tried every possible combination
of shape and set of "dots".
3. Move actually corresponded to transform.. you could also rotate, or flip
before moving. Also brute forced this step by trying all possibilities
of rotating and flipping until I found any match.
4. This was easily done by starting with a blank canvas for the solution.
Tasks solved: All
"""
# 4) The solution will be on a blank canvas
Y = np.full(X.shape, background)
# Extract what is needed from the input
X = Grid(X)
collections = X.get_adjacency_collections(background)
colors = X.colors()
# 1.a) Find the target collections, these need to be transformed to match the location
# of the corresponding reference points
targets = [s for s in collections if len(s.colors) >= len(colors) - 1]
# 1.b) Find the reference collections, the target collections
# will be transformed based on these points
references = find_references(s for s in collections if len(s.colors) < len(colors) - 1)
# 2) Brute force search on all (target, reference) possibilities
for target, reference in product(targets, references):
# 3) Try to find a transformation that places the target on reference
transformation = find_transformation(target, reference)
if transformation is not None:
# Draw the transformed collection in the correct location
# if a valid transformation is found
transformation.fill(Y)
return Y
def find_references(collections):
"""The reference points will be the set of points of unique colors that are nearest to each other.
I defined "nearest to each other" as the nearest summed euclidean distance between each point
collections - list of Collection - points to find references from (the collections
will be flattened)
"""
references = []
# Flatten collections to points
points = [p for s in collections for p in s.points]
# Greedily find the set of points that are unique in color and have minimum summed distance
while len(points) != 0:
support = find_best_reference_set(points)
if len(support) > 1:
references.append(Collection(support))
points = [p for p in points if p not in support]
return references
def find_best_reference_set(points):
"""Finds the best set of points that have a minimum summed distance between each point"""
# Group points by color
grouped = defaultdict(list)
for point in points:
grouped[point.color].append(point)
# Brute force search on all combinations of points with unique colors
possibilities = product(*[grouped[key] for key in grouped])
return min(possibilities, key=summed_distances)
def summed_distances(points):
return sum(a.euclidean(b) for a, b in combinations(points, 2))
def find_transformation(target, reference):
"""Finds a transformation of collection onto the points in the reference collection"""
# Brute force search on all possible transformations
for axis in (None, "x", "y", "x=y"):
curr = target
for degrees in (None, 90, 180, 270):
if axis is not None:
curr = curr.reflect(axis)
if degrees is not None:
curr = curr.rotate(degrees)
# Find the reference points in target by matching them with the colors in the
# reference collection
target_reference = Collection([p for p in curr.points if p.color in reference.colors])
# Apply the transformation of one point, to the rest of the points in the target collection
corresponding = next(p for p in reference.points if p.color == target_reference.points[0].color)
transformed = target_reference.translate(target_reference.points[0], corresponding)
# If the resulting collection is identical to the reference point collection it is a match
if transformed == reference:
return curr.translate(target_reference.points[0], corresponding)
return None
def solve_b782dc8a(X, wall=8):
"""This task is very simple to solve as a human but harder to solve programmatically.
The steps in my head for solving it are:
1. Identify the center point from which I would start the "painting".
2. Identify the second color in the every second one pattern judging it
by the neighbouring cells that were not the colour of the wall.
3. Paint the background until I could not paint anymore.
Algorithm:
1. The center point would be the only point with one color.
2. The pattern color would be the second least used color in the grid.
3. Painting is terminated when a wall is hit or the limits of the grid are reached.
Tasks solved: All
"""
# Solution will be on a canvas identical to the input
Y = X.copy()
# Extract what is needed from the input
X = Grid(X)
colors = X.colors()
# There will only be one center point, so only once cell will be colored
# with the center color. Ideally there should be more than one outward points, otherwise
# it is ambiguous which is the center. The code should work either way
# by picking one at random if this happens.
sorted_colors = sorted(colors.items(), key=lambda x: x[1])
center_color, out_color = [c for c, _ in sorted_colors[:2]]
center_point = X.get_points_by_color(center_color).points[0]
color_transitions = {center_color: out_color, out_color: center_color}
# Paint the pattern starting from the center point
visited = np.zeros(X.arr.shape)
paint(Y, (center_point.x, center_point.y), center_color, color_transitions, visited, wall)
return Y
def paint(X, point, color, color_transitions, visited, wall):
"""Recursively paints non-wall points starting from point by choosing the next color
using the color_transitions dict. Points that are already visited are not re-painted.
"""
visited_mark = -1
x, y = point
stop_condition = (
x == -1 or x == X.shape[0] or
y == -1 or y == X.shape[1] or
X[x][y] == wall or
visited[x][y] == visited_mark
)
if not stop_condition:
X[x][y] = color
visited[x][y] = visited_mark
for neighbour in ((x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)):
paint(X, neighbour, color_transitions[color], color_transitions, visited, wall)
def solve_5ad4f10b(X, background=0):
"""This task was not far off the difficulty of the first task done.
It was mentioned as one of the examples provided. As a human it is very simple
to solve but I struggled to come up with a pattern that was always true
when differentiate which color was which.
Note:
All of the examples have an output of shape (3, 3) but as a human I would know how
to solve the same problem with a (4, 4) or a (5, 5), etc. solution. I tried
to make the code generalize to this.
The steps in my head for solving it are:
1. Find the square of squares of equal size pattern.
2. Downscale the pattern so that each square is of size 1. Also change the color
to the other color that is not the background.
Algorithm:
This one did not transfer as smoothly to the same steps when its solved programmatically,
I will describe how the steps are achieved though:
1. This is handled by treating both colours as the color that contains the square of squares,
some condition would fail in the process and nothing would be returned when the
wrong color is attempted.
2. The size of each side would be the greatest common divisor of all the sides in the
square of squares. Downscaling is done pretty much exactly as you would think,
all squares are made a size of one.
Tasks solved: All
"""
# Extract what is needed from the input
X = Grid(X)
colors = X.colors()
del colors[background]
# Get the bounding boxes of each unique color
bounding_boxes = (Grid(X.get_points_by_color(c).asnumpy(background)) for c in colors.keys())
for box, color in zip(bounding_boxes, colors.keys()):
# Find adjacency collections for both the target color and the background
targets = box.get_adjacency_collections(background, color)
backgrounds = box.get_adjacency_collections(color, background)
# The length of the sides of the squares will be the greatest common divisor
# of all the sides in the square of squares
sides = [t.shape[0] for t in targets] + [t.shape[1] for t in targets] + [box.arr.shape[0]]
sides += [b.shape[0] for b in backgrounds] + [b.shape[1] for b in backgrounds]
side = np.gcd.reduce(sides)
# The fill color of the solution will be the only other color
# (and not the background color)
fill_color = next(c for c in colors.keys() if c != color)
Y = downscale(box.arr, side, fill_color, background)
if Y is not None:
return Y
def downscale(box, side, fill_color, background):
"""Downscales box by considering each box of length side as one pixel.
If a downscaled pixel contains more than on color this returns None"""
if side == 1:
return None
w, h = int(box.shape[0] / side), int(box.shape[1] / side)
Y = np.full((w, h), background)
for x in range(w):
for y in range(h):
square_color = get_square_color(box, x*side, y*side, side)
if square_color is not None:
if square_color != background:
Y[x][y] = fill_color
else:
return None
return Y
def get_square_color(box, x, y, side):
"""Gets the color of the square with its top left corner at (x, y) and with the sides being a length of side
Returns None if they are not all the same color or if side == 1"""
colors = set()
for i in range(side-1):
for j in range(side-1):
colors.add(box[x + i][y + j])
if len(colors) == 1:
return colors.pop()
else:
return None
def main():
# Find all the functions defined in this file whose names are
# like solve_abcd1234(), and run them.
# regex to match solve_* functions and extract task IDs
p = r"solve_([a-f0-9]{8})"
tasks_solvers = []
# globals() gives a dict containing all global names (variables
# and functions), as name: value pairs.
for name in globals():
m = re.match(p, name)
if m:
# if the name fits the pattern eg solve_abcd1234
ID = m.group(1) # just the task ID
solve_fn = globals()[name] # the fn itself
tasks_solvers.append((ID, solve_fn))
for ID, solve_fn in tasks_solvers:
# for each task, read the data and call test()
directory = os.path.join("..", "data", "training")
json_filename = os.path.join(directory, ID + ".json")
data = read_ARC_JSON(json_filename)
test(ID, solve_fn, data)
def read_ARC_JSON(filepath):
"""Given a filepath, read in the ARC task data which is in JSON
format. Extract the train/test input/output pairs of
grids. Convert each grid to np.array and return train_input,
train_output, test_input, test_output."""
# Open the JSON file and load it
data = json.load(open(filepath))
# Extract the train/test input/output grids. Each grid will be a
# list of lists of ints. We convert to Numpy.
train_input = [np.array(data['train'][i]['input']) for i in range(len(data['train']))]
train_output = [np.array(data['train'][i]['output']) for i in range(len(data['train']))]
test_input = [np.array(data['test'][i]['input']) for i in range(len(data['test']))]
test_output = [np.array(data['test'][i]['output']) for i in range(len(data['test']))]
return (train_input, train_output, test_input, test_output)
def test(taskID, solve, data):
"""Given a task ID, call the given solve() function on every
example in the task data."""
print(taskID)
train_input, train_output, test_input, test_output = data
print("Training grids")
for x, y in zip(train_input, train_output):
yhat = solve(x)
show_result(x, y, yhat)
print("Test grids")
for x, y in zip(test_input, test_output):
yhat = solve(x)
show_result(x, y, yhat)
def show_result(x, y, yhat):
print("Input")
print(x)
print("Correct output")
print(y)
print("Our output")
print(yhat)
print("Correct?")
# if yhat has the right shape, then (y == yhat) is a bool array
# and we test whether it is True everywhere. if yhat has the wrong
# shape, then y == yhat is just a single bool.
print(np.all(y == yhat))
if __name__ == "__main__":
main()
|
204d89e2cd7f6f6d8dd0dcf5fdd12e2e4bf52d06 | Ved005/project-euler-solutions | /code/the_incenter_of_a_triangle/sol_482.py | 638 | 3.5625 | 4 |
# -*- coding: utf-8 -*-
'''
File name: code\the_incenter_of_a_triangle\sol_482.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #482 :: The incenter of a triangle
#
# For more information see:
# https://projecteuler.net/problem=482
# Problem Statement
'''
ABC is an integer sided triangle with incenter I and perimeter p.
The segments IA, IB and IC have integral length as well.
Let L = p + |IA| + |IB| + |IC|.
Let S(P) = ∑L for all such triangles where p ≤ P. For example, S(103) = 3619.
Find S(107).
'''
# Solution
# Solution Approach
'''
'''
|
c03077f528f01261c65eb40ecf1a3b4553438b27 | Rachelspdo/Anagram-and-Substring | /solutions.py | 1,531 | 4.125 | 4 |
###### Question: Given two strings s and t, determine whether some anagram of t is a substring of s. For example: if s = "udacity" and t = "ad", then the function returns True. Your function definition should look like: question1(s, t) and return a boolean True or False. ######
import collections
def check_anagram(string1,string2):
length_string2 = len(string2);
count_string2 = {};
count_string1 = {};
all_comparedStr = [];
# construct a dictionary of each character and its occurance for shorter string
for i in string2:
letter_occurance_in_string2 = string2.count(i);
count_string2[i]=letter_occurance_in_string2
all_comparedStr = extract_Str(string1,length_string2)
# construct a dictionary of each character and its occurance for each set of the longer string, finally compare the 2 dictionary
for x in all_comparedStr:
count_string1 = collections.Counter(x)
# if the two dictionary matches then the shorter string is a anagram substring of the longer string
if count_string1 == count_string2:
return True
return False
# Chopped string at specific length into set
def extract_Str(string,length):
all_sets = [];
for i in range(len(string)):
set = string[i:i+length];
all_sets.append(set);
return all_sets
print "Expected: True"
print check_anagram("udacity","da")
print "Expected: True"
print check_anagram("banana","anb")
print "Expected: False"
print check_anagram("4732890793878894351", "13")
|
fcd2dc90a9f3c2a60dbcc99437e4ce66976a3611 | msamassa/git_lesson | /src/my_square.py | 236 | 3.984375 | 4 | def m_square(x):
""" take a value and returns the square value.
use operator *****
"""
return(x ** 2)
def my_square2(x):
""" uses the operator to calculate square
"""
return(x * x)
print(m_square(4))
print(my_square2(9))
|
9ebe6de372d7d35e0c9ea0adbae988c96e09a3e9 | csu100/LeetCode | /python/leetcoding/LeetCode_04.py | 884 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/12 21:32
# @Author : Zheng guoliang
# @Site :
# @File : LeetCode_04.py
# @Software: PyCharm
"""
1.需求功能:
https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
2.实现过程:
"""
class Solution:
def findMedianSortedArrays(self,nums1,nums2):
if len(nums1)==0:
return self.findMedian(nums2)
if len(nums2)==0:
return self.findMedian(nums1)
nums1.extend(nums2)
nums1.sort()
return self.findMedian(nums1)
def findMedian(self,nums):
if len(nums)&1==1:
return nums[len(nums)>>1]
else:
return (nums[len(nums)>>1]+nums[(len(nums)>>1)-1])/2.0
if __name__ == '__main__':
solution =Solution()
nums1=[1,2,4]
nums2=[1,3,5]
result = solution.findMedianSortedArrays(nums1,nums2)
|
a7bf957786d694360c04f2fbb0736f10820677ef | gwolf/sistop-2017-2 | /practicas/5/HernandezIvan/camino.py | 784 | 3.6875 | 4 | from os import walk
from colorama import init, Fore, Back, Style
init()
for (path, directorio, archivos) in walk("."):
#Lo primero es leer el path, ver donde se esta"""
print(Fore.RED + Style.BRIGHT + "PATH")
print(Style.RESET_ALL)
print (Fore.RED)
print path
print(Style.RESET_ALL)
"""Leer los directorios o directorio"""
print(Fore.GREEN + Style.BRIGHT + "directorio")
print(Style.RESET_ALL)
print (Fore.GREEN)
print directorio
print ("\n")
print(Style.RESET_ALL)
"""Ver los archivos dentro de los directorios"""
print(Fore.BLUE + Style.BRIGHT + "ARCHIVOS")
print(Style.RESET_ALL)
print(Fore.BLUE)
print archivos
print ("\n")
# Referencias http://www.alvarohurtado.es/leer-carpetas-y-archivos-con-python/ |
7b287e4588aa01ea40a2303adda6ff2160ed1cc8 | hanrick2000/LeetcodePy | /leetcode/dp/two_keys_board_solution1.py | 1,303 | 3.984375 | 4 | from collections import deque
import random
class Solution(object):
def minSteps(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 0
# org_n = n
prime_list = deque()
# iteratively divide by 2
while n % 2 == 0:
prime_list.append(2)
n = n / 2
# iteratively divide by prime (prime > 2)
for p in range(3, int(n ** 0.5) + 1, 2):
while n % p == 0:
prime_list.append(p)
n = n / p
# exit condition: n is divisible by all primes which is smaller than sqrt(n) + 1
# e.g. 18 = 2 x 2 x 3, among which 2 < sqrt(18) + 1 and 3 < sqrt(18) + 1
if n == 1: # or if p > n:
break
# exit condition: largest_divisible_prime > sqrt(n) + 1
# e.g. 820 = 2 x 2 x 5 x 41, among which 41 > sqrt(820) + 1
if n > 2:
prime_list.append(n)
# print "%d leftover_n: %d = products of %s" % (org_n, n, prime_list)
return sum(prime_list)
if __name__ == '__main__':
s = Solution()
for i in range(40):
ran = random.randint(50, 1001)
minStep = s.minSteps(ran)
# print "random_int: %d, min_steps: %d" % (ran, minStep)
|
dfc00f375172a34fa4bb5f22078e0cf696bdca3d | WAMaker/leetcode | /Algorithms/48-Rotate-Image.py | 595 | 3.546875 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n < 2:
return
lb, rb, tb, bb = 0, n - 1, 0, n - 1
while lb < rb:
for i in range(0, rb - lb):
matrix[tb + i][rb], matrix[bb][rb - i], matrix[bb - i][lb], matrix[tb][i + lb] = matrix[tb][i + lb], matrix[tb + i][rb], matrix[bb][rb - i], matrix[bb - i][lb]
lb += 1
rb -= 1
tb += 1
bb -= 1 |
f5d0499bf33d2aaa93fd537ddd7c1deb232849fc | Heckfy85/learnpython8 | /test_func.py | 252 | 3.765625 | 4 | def get_vat(price, vat_rate):
if price==int and vat_rate==int:
vat = price / 100 * vat_rate
price_no_vat = price - vat
print(price_no_vat)
else :
print('введите число')
price1 = 100
vat_rate1='5'
get_vat(price1,vat_rate1)
|
1462fdf5d6082945a8b4d3518bcc1eaa7a5cb179 | alvyxc/dailycode | /10_14_2019_MinNum.py | 930 | 3.65625 | 4 | #Given an array of integers, find the first missing positive integer in linear time and constant space.
#In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and
#negative numbers as well.
#For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
#You can modify the input array in-place.
import math
a = [10, 11, 8, -1, 11, 90, 1, 3]
i = 0
j = len(a) - 1
while i < j:
if a[i] < 1 or a[i] > len(a):
if a[j] < 1 or a[j] > len(a):
j = j - 1
else:
tmp = a[i]
a[i] = a[j]
a[j] = tmp
i = i + 1
j = j - 1
else:
i = i + 1
k = 0
while k < i:
index = abs(a[k]) - 1
a[index] = -1 * abs(a[index])
k = k + 1
print(a)
k = 0
min_value = i
while k < i:
if a[k] > 0:
min_value = k
k = k + 1
print (min_value + 1) |
4f8f0f7cf9f526d500f4d238dde254b662e243e1 | jhandrad/agenda-tefonica | /classes.py | 4,749 | 3.5625 | 4 | # imports da lib padrão
from typing import Type
from functools import total_ordering
import os
# imports de terceiros
# imports de módulos próprios
import funcoes_bd
'''
Arquivo que contem as classes responsáveis pelo funcionamento
da agenda. Poderiamos dizer que é o back-end.
'''
class ListaUnica(): # classe legada da versão sem BD
def __init__(self, tipo_elemento: Type) -> None:
self.tipo_dos_elementos = tipo_elemento
self.lista = []
def __iter__(self):
return iter(self.lista)
def __len__(self) -> int:
return len(self.lista)
def __getitem__(self, indice: int):
return self.lista[indice]
def adiciona_elemento(self, elemento) -> bool:
if (self.verifica_tipo(elemento) and not
self.pesquisa_elemento(elemento)):
self.lista.append(elemento)
return True
return False
def remove_elemento(self, elemento) -> bool:
if len(self.lista) > 0 and self.pesquisa_elemento(elemento):
self.lista.remove(elemento)
return True
return False
def verifica_tipo(self, elemento) -> bool:
return type(elemento) == self.tipo_dos_elementos
def pesquisa_elemento(self, elemento) -> bool:
return elemento in self.lista
class ListaDeContatos(ListaUnica): # classe legada da versão sem BD
def __init__(self) -> None:
super().__init__(Contato)
@total_ordering
class Contato():
def __init__(self, values: dict) -> None:
self.nome = values["-NOME-"]
self.celular = values["-CELULAR-"]
self.fixo = values["-FIXO-"]
self.fax = values["-FAX-"]
def __str__(self) -> str:
contato = (
"Nome: {0}\nCelular: {1}\nFixo: {2}\nFax:{3}".format(
self.nome,
self.celular,
self.fixo,
self.fax))
return contato
def __eq__(self, o: object) -> bool:
return self.__chave == o.__chave
def __lt__(self, o: object) -> bool:
return self.nome < o.nome
@property
def nome(self) -> str:
return self.__nome
@property
def chave(self) -> str:
return self.__chave
@nome.setter
def nome(self, valor: str) -> None:
if valor == None or not valor.strip():
raise ValueError("Nome não pode ser nulo nem em branco")
self.__nome = valor
self.__chave = Contato.cria_chave(valor)
@staticmethod
def cria_chave(cls: str) -> str:
return cls.strip().lower()
def edita_contato(self, values: dict) -> None:
self.nome = values["-NOME-"]
self.celular = values["-CELULAR-"]
self.fixo = values["-FIXO-"]
self.fax = values["-FAX-"]
def retorna_dados(self) -> dict:
resultado = {"-CHAVE-": self.__chave,
"-NOME-": self.__nome,
"-CELULAR-": self.celular,
"-FIXO-": self.fixo,
"-FAX-": self.fax}
return resultado
class Agenda():
def __init__(self) -> None:
novo = not os.path.isfile("agenda.db")
if novo:
funcoes_bd.cria_tabela_bd()
def adiciona_contato(self, values: dict) -> bool:
dados_contato = self.cria_contato_retorna_dados(values)
return funcoes_bd.adiciona_bd(dados_contato)
def remove_contato(self, nome: str) -> bool:
chave = self.cria_chave(nome)
return funcoes_bd.remove_bd(chave)
def exibe_contato(self, nome: str) -> Contato:
chave = self.cria_chave(nome)
dados_bd = funcoes_bd.retorna_contato_bd(chave)
values = {"-NOME-": dados_bd[0],
"-CELULAR-": dados_bd[1],
"-FIXO-": dados_bd[2],
"-FAX-": dados_bd[3]}
contato = Contato(values)
return contato
def edita_contato(self, nome: str, values: dict) -> None:
dados_contato = self.cria_contato_retorna_dados(values)
chave = self.cria_chave(nome)
funcoes_bd.edita_contato_bd(chave, dados_contato)
def retorna_dados(self, nome: str) -> any:
chave = self.cria_chave(nome)
dados_bd = funcoes_bd.retorna_contato_bd(chave)
return dados_bd
def retorna_nomes(self) -> list:
return funcoes_bd.retorna_nomes_bd()
def cria_chave(self, nome: str) -> str:
return nome.lower().strip()
def cria_contato_retorna_dados(self, values: dict) -> dict:
contato = Contato(values)
return contato.retorna_dados()
|
bcbe8170a2a831e9c9d7da1b5a82fe36473bb543 | euzin4/gex003_algprog | /material/respostas_exercicios/lista4/exe3.py | 148 | 3.953125 | 4 | N = int(input("Informe um número: "))
if N <= 10:
print("F1")
elif N > 10 and N <= 100:
print("F2")
else: #caso seja maior que 100
print("F3")
|
4279b85f04ee9dcd7916bab733d800297096b452 | escm1990/PhythonProjects | /Otros/POO/Ejercicios POO/03_Ejercicio.py | 847 | 3.96875 | 4 | # Crear una clase Fabrica que tenga los atributos de Llantas, Color y Precio;
# luego crear dos clases mas que hereden de Fabrica, las cuales son Moto y Carro.
# Crear metodos que muestren la cantidad de llantas, color y precio de ambos transportes.
# Por ultimo, crear objetos para cada clase y mostrar por pantalla los atributos de cada uno
class Fabrica():
def __init__(self,pLlantas,pColor,pPrecio):
self.llantas = pLlantas
self.color = pColor
self.precio = pPrecio
def __str__(self):
return "El objeto creado es {} - {} - {}".format(self.llantas,self.color,self.precio)
###################
class Moto(Fabrica):
pass
###################
class Carro(Fabrica):
pass
###################
moto = Moto(2,"Rojo",1000)
print(str(moto))
carro = Carro(4,"Negro",6000)
print(str(carro)) |
4a4c68ae28971ac23e94b948356ee611f42159a2 | aveetron/Algooo | /Sort/selection-sort.py | 772 | 3.875 | 4 | class SelectionSort(object):
def __init__(self,number_list):
self.number_list = number_list
def sort_list(self):
for i in range(len(self.number_list)):
min_index = i
for j in range(i, len(self.number_list)):
if self.number_list[j] < self.number_list[min_index]:
min_index = j
temp = self.number_list[i]
self.number_list[i] = self.number_list[min_index]
self.number_list[min_index] = temp
return self.number_list
sel = SelectionSort([7,3,5,10,2])
print(sel.sort_list())
'''
Executing output step by step ->
[2, 3, 5, 10, 7]
[2, 3, 5, 10, 7]
[2, 3, 5, 10, 7]
[2, 3, 5, 7, 10]
[2, 3, 5, 7, 10]
''' |
dea1489c3567ec2bc982143ac1cc57361274917f | vaibz96/Special-Topics-in-Software-Engineering-Course-work | /Homework 5/Homework05-Vaibhav.py | 3,318 | 4.1875 | 4 | """
@author: Vaibhav Vishnu Shanbhag
@homework: HW 05
@date: 02/24/2019
@time: 05:08:11 PM
This code Implements a class for string methods and the automated testing
"""
import unittest
"""Part 1"""
def reverse(str):
string = ''
index_val = len(str)
"""
While loop will start with the length of the string and decrement the index
and return the value at that index
"""
while index_val:
index_val -= 1
string += str[index_val]
return string
"""Part 2"""
def rev_enumerate(str):
string=''
index_val = len(str)
"""
While loop will start with the length of the string and decrement the index
and return the value at that index
"""
while index_val:
index_val -= 1
string += str[index_val]
count = len(string)
"""
the count will store the length of the string
and the while iterate through each string returning the count in reverse order as an offset in reverse order
"""
while count:
for i in string:
"""the default index of any element in a string is 0 I have yielded count-1 """
yield count-1, i
count -= 1
"""Part 3"""
def find_second(s1, s2):
"""
here this function returns the substring s1 in s2 string s2.find(s1) will return the index of the string s1
and s2.find(s1)+1 will give index from its second occurrence note:index==offset
at second index
"""
return s2.find(s1, s2.find(s1)+1)
"""Part 4"""
def get_lines():
"""
the f variable will open the text file using
open function and f.close() will close the same text file
"""
f = open('test.txt', 'r')
new_line = ''
for line in f:
line = line.rstrip("\r\n")
if line.endswith('\\'):
new_line += line.rstrip('\\')
continue
new_line += line
find_hash = new_line.find('#')
if find_hash == 0:
new_line = ''
if find_hash >= 1:
new_line = new_line[:find_hash]
yield new_line
new_line = ''
if find_hash == -1:
yield new_line
new_line = ''
f.close()
class Reverse_Test(unittest.TestCase):
def test_reverse(self):
self.assertEqual(reverse('hi my bro'), 'orb ym ih')
self.assertFalse(reverse('hi my name') == 'ieurfygvcj')
self.assertEqual(reverse('8976'), '6798')
self.assertFalse(reverse('my name')== 'myname')
class Reverse_Enumerate_Test(unittest.TestCase):
def test_rev_enumerate(self):
self.assertEqual(list(rev_enumerate("hi bro!")),[(6, '!'), (5, 'o'), (4, 'r'), (3, 'b'),\
(2, ' '), (1, 'i'), (0, 'h')])
class Test_Second_Occurance(unittest.TestCase):
def test_find_second(self):
self.assertEqual(find_second('iss', 'Mississippi'), 4)
self.assertEqual(find_second('abba', 'abbabba'), 3)
self.assertEqual(find_second('x', 'abbabba'), -1)
class GetLinesTest(unittest.TestCase):
def test_get_lines(self):
expect = ['<line0>', '<line1>', '<line2>', '<line3.1 line3.2 line3.3>', '<line4.1 line4.2>', '<line5>', '<line6>']
result = list(get_lines())
self.assertEqual(result, expect)
if __name__=='__main__':
unittest.main(exit=False, verbosity=2)
|
7c412dcfce2d1237887521546c43e32078cabe8d | Pavche/python_scripts | /remove_duplicates.py | 305 | 4.03125 | 4 | def remove_duplicates(list_of_items):
new_list = []
for item in list_of_items:
for elem in new_list:
# is this item present in new_list
if elem == item:
break
else:
new_list.append(item)
result = new_list
return result
print remove_duplicates(['a','b','c','a','b','c']) |
9db8a4fcf1ab8b9a74a692c295c3398e23bd8d4f | BarnetteME1/textminer | /textminer/validator.py | 1,918 | 3.71875 | 4 | def binary_numbers(string):
if re.search(r"[2-9]", string):
return False
return True
def binary_even(string):
if re.search(r"0$", string):
return True
return False
def hexadecimal(string):
if re.search(r"[A-F]\d", string):
return True
return False
def word(string):
if re.findall(r"(\w+[^\d])", string):
if re.findall(r"[!*]", string):
return False
return True
return False
def words(string):
if re.findall(r"(\w+[^\d\S])", string):
return True
return False
def phone_numbers(string):
if re.findall(r"(\(?[\d]{3}\)?).?([\d]{3}.?[\d]{4})", string):
return True
return False
def money(string):
if string.count(','):
if not re.findall(r",\d{3}", string):
return False
string = re.findall(r"([^\,])", string)
string = ''.join(string)
cash_money = {}
if string.count('.'):
if not re.findall(r"\.\d{1,2}$", string):
return False
if string.count('$') > 1:
return False
if re.findall(r"([^\d])", string):
return False
cash = re.findall(r"(\S)(\d+.?(?:\d+))", string)
if len(cash[0]) < 2:
return False
return True
def zipcode(inputs):
zip_code = {}
full_zip = re.findall(r"(\d+)(-?\d{4})?", inputs)
if full_zip == []:
return False
zips, plus4 = full_zip[0]
if len(zips) != 5:
return False
zip_code["zip"] = zips
if plus4 == '' and len(plus4) != 4:
return False
return True
def date(string):
tests = [r"(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<year>\d{4}|\d{2})",
r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{2})"]
for test in tests:
match = re.match(test, string)
if match:
return True
## HARD MODE BEGINS
def hard_date(string):
def email(string):
def address(string):
|
a1854e8a9459161e890498275ea9a964db1f8d40 | LukazDane/CS-2-Tweet-Generator | /sample.py | 1,345 | 4 | 4 | import random
import sys
# words = sys.argv[1:]
words = ["one", "fish", "two", "fish", "red", "fish", "blue", "fish"]
histogram = {'cats': 3, 'dogs': 4, 'rabbits': 2, 'turtles': 1}
hg = {'cats': 3, 'dogs': 4, 'rabbits': 2, 'turtles': 1}
def sample(histogram):
tokens = sum([count for word, count in histogram.items()])
dart = random.randint(1, tokens)
fence = 0
for word, count in histogram.items():
fence += count
if fence >= dart:
return word
print(sample(histogram))
"""
import random
from random import randint
text = 'one fish two fish red fish blue fish'
word_counts = {'one': 1, 'fish': 4, 'two': 1,
'red': 1, 'blue': 1}
def sample_by_frequency(histogram):
new_ls = []
# TODO: select a word based on frequency
#how can we sample words using observed frequencies?
#call randint to give us a random index to help us select a word
for k in word_counts:
new_ls.append(random.choice([k for k in word_counts for x in range(word_counts[k])]))
return new_ls
print(sample_by_frequency(word_counts))
#for key in word_counts
#append random choice
# k for each key(5) for x in ramge of word_counts*value of K
#start = 0
#for word in count of histogram.items():
#end = start +
# if
# return word
# else
"""
|
feababa0ba2e52b185b9f252d57b9a2eff73f147 | IgorJordany/Compiladores-1-20172 | /Implementações/AnalisadorLexico_v2.py | 1,808 | 3.84375 | 4 | def pReservada (token):
reservadas = ['var', 'integer', 'real', 'if', 'then']
if token in reservadas:
return True
return False
def operador (token):
operadores = [':=','+']
if token in operadores:
return True
return False
def delimitador (token):
delimitadores = [':',',',';']
if token in delimitadores:
return True
return False
def verificabuf(buf):
if buf!="":
return True
return False
arq = open('codigo.txt','r') # Abre o arquivo
texto = arq.read() # Leitura do arquivo
buf = ""
linhatok = 1
for caracter in texto:
if caracter == "\n":
if verificabuf(buf):
if pReservada(buf):
print("palavra reservada ", buf, " linha ", linhatok)
buf=""
elif operador(buf):
print("operador ",buf," linha ", linhatok)
buf=""
else:
print("talvez ID")
buf=""
linhatok=linhatok+1
elif caracter ==" ":
if verificabuf(buf):
if pReservada(buf):
print("palavra reservada ", buf, " linha ", linhatok)
buf=""
elif operador(buf):
print("operador ",buf," linha ", linhatok)
buf=""
else:
print("talvez ID")
buf=""
elif delimitador(caracter):
if verificabuf(buf):
if pReservada(buf):
print("palavra reservada ", buf, " linha ", linhatok)
buf=""
elif operador(buf):
print("operador ",buf," linha ", linhatok)
buf=""
else:
print("talvez ID")
buf=""
else:
print("demilitador ",caracter," linha ", linhatok)
elif operador(caracter):
if verificabuf(buf):
if pReservada(buf):
print("palavra reservada ", buf, " linha ", linhatok)
buf=""
elif operador(buf):
print("operador ",buf," linha ", linhatok)
buf=""
else:
print("talvez ID")
buf=""
else:
print("operador ",caracter," linha ", linhatok)
else:
buf=buf+caracter
arq.close() # Fecha o arquivo codigo.txts |
1d36a0cec63d0a13f7db4f4d58c5f561160611cc | mrozsypal81/323-Compilers-Assignment-3 | /compiler/syntax_analyzer/syntax_analyzer.py | 2,676 | 3.515625 | 4 | class Syntax_analyzer (object):
def __init__(self, *arg):
self.lexemes = arg
# print('arg = ', arg)
# statemenize method - create statement list from lexemes
def syntaxA(self):
lexemes = list(self.lexemes[0])
begin = 0
tablestart = 5000
resultlist = []
print('len(lexemes) = ', len(lexemes))
while begin < len(lexemes) and begin >= 0:
isCheck, result, newBegin,newtablestart = checkAllRules(lexemes, begin,tablestart)
print('Returned from CheckAllRules')
resultlist.append(result)
print('isCheck = ', isCheck)
for i in result:
print(i)
begin = newBegin
tablestart = newtablestart
print('\n\n')
print('Done with all Lexemes')
return resultlist
# ==============================================
# End class here
# ==============================================
def checkAllRules(arg, begin,tablestart):
count = begin
tablecount = tablestart
availableLen = len(arg) - begin
print('availableLen = ', availableLen)
#This returns the next semicolon position so that you can tell where to end
#print("Begin value")
print(begin)
semicolkey,semicolval,semicolpos = getSpecificKV(arg,";",begin)
templist = arg[begin:semicolpos+1]
print("++++++++++++++++++++templist++++++++++++++++")
print(templist)
print("++++++++++++++++++++++++++++++++++++++++++++")
#testkey,testval,testpos = getSpecificKVreverse(arg,"+",semicolpos)
#print("isDeclarative Check in CheckAllRules")
if len(templist) == 3:
#print("Going into isDeclarative CheckAllRules")
isDeclare, resultDeclare = isDeclarative (templist)
#print("Return from isDeclarative in CheckAllRules")
if isDeclare:
count = begin + 3
return isDeclare, resultDeclare, count
eqkey,eqval,eqpos = getSpecificKV(templist,"=",0)
#print("isAssign Check in CheckAllRules")
if eqval == "=":
#print("Going into isAssign in CheckAllRules")
isAss, resultAssign, AddCount = isAssign (templist)
#print("Return from isAssign in CheckAllRules")
if isAss:
count += AddCount
return isAss, resultAssign, count
#print("Going into isExpress in CheckAllRules")
isExp, resultExpress, AddCount,newpos = isExpress(templist,0)
#print("Return from isExpress in CheckAllRules")
if isExp:
count += AddCount
return isExp,resultExpress,count
#print('End of CheckAllRules')
return False,[],-1
|
0d8fe7b7aba67a18a81993c8ca3b67dde007d636 | AMALj248/sentdex_cnn | /sentdex_pt_3.py | 740 | 3.59375 | 4 | import numpy as np
import pandas as pd
import cv2
img = cv2.imread('images/omega.jpg' , cv2.IMREAD_COLOR)
#Drawing a black line
cv2.line(img , (0 ,0 ) , (150 , 150) , (0,0,0))
#Drawing a Rectangle
cv2.rectangle(img , (15,15) , (200 , 150) ,(0,255,0) , 5)
#Drawing a Circle , -1 fills the circle with color
cv2.circle(img , (100,63) ,55 , (0,0,255) ,-1)
#Drawing Polygons
pts = np.array(([10,5] , [70,20] , [20,30] , [50,10]) , np.int32)
#True is to make a closed curve
cv2.polylines(img ,[pts] , True , (0,255,3))
#To write a text
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img , 'OpenCV' , (0,130) , font , 1 , (200 ,255 , 255) , 2 , cv2.LINE_AA)
cv2.imshow('image' , img)
cv2.waitKey(0)
cv2.destroyAllWindows() |
256b6631e6b2e8fc72e3874dd67774bc3db796dc | Schimith98/Exercicios_em_Python | /ex043.py | 763 | 4.0625 | 4 | #Exercício Python 043: Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:
#- IMC abaixo de 18,5: Abaixo do Peso
#- Entre 18,5 e 25: Peso Ideal
#- 25 até 30: Sobrepeso
#- 30 até 40: Obesidade
#- Acima de 40: Obesidade Mórbida
peso = float(input('Qual seu peso? (kg) '))
altura = float(input('Qual sua altura? (m) '))
imc = float(peso/(altura * altura))
print('Seu IMC é {:.2f} e vc está '.format(imc), end="")
if imc < 18.5:
print('abaixo do peso')
elif imc <= 25:
print(' com o peso ideal')
elif imc <= 30:
print('com sobrepeso')
elif imc <= 40:
print('com obesidade')
else:
print('com obesidade mórbida') |
bb2dc40fe7545feedda25114e32e118b623debcf | naturalis/biovel-nbc | /script/ParseTsvFile.py | 2,111 | 3.546875 | 4 | import sys,os
sys.stdout.write('Insert the input file location\n') # Metadata TSV file location. the first column is often TaxonID
Input=raw_input()
sys.stdout.write('Insert a list of column names seperated by semicolon\n') # list of headers names that you wish to extract and put them in csv file (e.g. 'GeographicalOrigin;Pathogenic_Potential;Biomass;host;phenology' OR 'Biomass')
Cols=raw_input()
def dict2TSV(D_TaxRequestedValues):
'''A dictionary having as keys TaxonIDs and as values
a list of the values of the requested columns'''
L=[]
for TaxID in D_TaxRequestedValues:
S_KeyValue=TaxID+','+','.join(D_TaxRequestedValues[TaxID])
L.append(S_KeyValue)
return L
def getColsOfInterest(f_in, colNames):
'''f_in is an input tsv file with headers
colNames should be a semicolon separated string of headerNames.
This function outputs a file compatible with ITOL display tools for single
and multiple value bar charts, where the first line starts with the word 'LABELS'
and the rest of the file is a comma-separated values.'''
ColOfInterest={}
f=open(f_in, 'r')
Headers=[]
Headers_temp=f.readline().split('\t')
for i in Headers_temp:
Headers.append(i.strip())
TaxID=Headers[0]
requestedCols=[]
for headerName in colNames.split(';'):
requestedCols.append(Headers.index(headerName))
requestedCols.sort()
#print requestedCols
tempDict_Allfile={}
for line in f:
l=line.split('\t')
tempDict_Allfile[l[0]]=l
#print tempDict_Allfile
for Taxon in tempDict_Allfile:
AllCols=tempDict_Allfile[Taxon]
for j in requestedCols:
AllCols[j]=AllCols[j].strip()
if ',' in AllCols[j]:
AllCols[j]=AllCols[j].replace(',',';')
sys.stdout.write('the comma has been replaced by ; in ' + AllCols[j]+ '\n')
ColOfInterest.setdefault(Taxon,[]).append(AllCols[j])
else:
ColOfInterest.setdefault(Taxon,[]).append(AllCols[j])
f.close()
f_out=open(f_in + '_ColsOfInterest.csv','w')
f_out.write('LABELS,'+ ','.join(colNames.split(';')) + '\n')
Cols2Write=dict2TSV(ColOfInterest)
f_out.write('\n'.join(Cols2Write)+ '\n')
f_out.close()
getColsOfInterest(Input, Cols)
|
be187ae27095d30747e723bf48400c71ef54d3a6 | robojukie/coursera_p4e | /ds9_4.py | 1,041 | 3.78125 | 4 | # 9.4 Write a program to read through the mbox-short.txt and figure out who has
# the sent the greatest number of mail messages. The program looks for 'From '
# lines and takes the second word of those lines as the person who sent the
# mail. The program creates a Python dictionary that maps the sender's mail
# address to a count of the number of times they appear in the file. After the
# dictionary is produced, the program reads through the dictionary using a
# maximum loop to find the most prolific committer.
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = {}
for line in handle :
if line.startswith('From ') :
line = line.strip()
sender_info = line.split()
sender = sender_info[1]
counts[sender] = counts.get(sender,0)+1
max_count = None
max_sender = None
for sender, count in counts.items() :
if max_count is None or count > max_count :
max_count = count
max_sender = sender
print max_sender, max_count
|
bbc00934e9b5900886f979c0a40ee1c21d1243f4 | samkitsheth95/InterviewPrep | /com/Leetcode/824.GoatLatin.py | 729 | 3.609375 | 4 | class Solution:
def toGoatLatin(self, S: str) -> str:
vowel = set('aeiouAEIOU')
def latin(w, i):
if w[0] not in vowel:
w = w[1:] + w[0]
return w + 'ma' + 'a' * (i + 1)
return ' '.join(latin(w, i) for i, w in enumerate(S.split()))
def toGoatLatinNaive(self, S: str) -> str:
words, ans, i = S.split(), [], 1
for word in words:
if word[0] in "aeiouAEIOU":
word += "ma"
else:
word = word[1:] + word[0] + "ma"
word += ("a" * i)
ans.append(word)
i += 1
return " ".join(ans)
sol = Solution()
print(sol.toGoatLatinNaive("I speak Goat Latin"))
|
1a126e881c5a7c359d68fcac83058d6c02abfa11 | csills/DIGITAL-CRAFTS | /week1/day3/loops/triangleII.py | 125 | 3.828125 | 4 | rows = int(raw_input("What is the height of the triangle? "))
for i in range(rows):
print ' '*(rows-i-1) + '*'*(2*i+1)
|
cb61e42e0a5f549f0019a43538f55ea30c6168a9 | CirXe0N/AdventOfCode | /2019/03/puzzle_01.py | 1,115 | 3.71875 | 4 | def load_input() -> list:
wire_paths = []
with open('input.txt') as f:
for line in f.readlines():
wire_path = []
for wire in line.split(','):
wire_path.append({
'direction': wire[0],
'steps': int(wire[1:])
})
wire_paths.append(wire_path)
return wire_paths
def move(commands: list) -> list:
positions = []
x, y = 0, 0
for command in commands:
direction = command['direction']
steps = command['steps']
for n in range(1, steps + 1):
if direction == 'R':
x += 1
if direction == 'L':
x -= 1
if direction == 'U':
y += 1
if direction == 'D':
y -= 1
positions.append((x, y))
return positions
wire_paths = load_input()
p1 = move(wire_paths[0])
p2 = move(wire_paths[1])
intersections = set(p1).intersection(set(p2))
answer = min([abs(pos[0]) + abs(pos[1]) for pos in intersections])
print(f'The answer is {answer}')
|
3b662ae9a6ed17f4cf659c32f855282fd9c34f74 | Blackshirt99/1902 | /1902/_python_/base/for.py | 173 | 3.578125 | 4 | li = list()
li.append(200)
li.append(100)
li.append(300)
print(li)
print('*'*50)
s = {400, 500, 600, 200}
for i in li:
print(i)
print('*'*50)
for i in s:
print(i)
|
82d9e57233b9cce0c833b42274c321a55e4fe7af | ydj515/record-study | /Web_Crawling_Python3/BeautifulSoup4/13_naver_menu.py | 894 | 3.578125 | 4 | import urllib.request
import bs4
def main():
url = "https://www.naver.com"
html = urllib.request.urlopen(url)
# url에 해당하는 html이 bsObj에 들어감
bsObj = bs4.BeautifulSoup(html, "html.parser")
# <ul class="an_l">의 ul 태그만 뽑는다
ul = bsObj.find("ul",{"class":"an_l"})
# 위의 찾은 ul 태그에서 li태그를 다 찾아 list 형태로 반환
# [<li></li>, <li></li>, <li></li> ...]
lis = ul.findAll("li")
print(lis)
# 리스트 이므로 길이 출력 가능
print(len(lis))
for li in lis:
print(li) # 하나씩 꺼내서 출력 하므로 [] 대괄호가 찍히지 않음 cf) 19라인
a_tag = li.find("a")
span = a_tag.find("span",{"class":"an_txt"})
# .text를 붙히면 안의 값만 나옴
print(span.text)
if __name__ == "__main__":
main() |
b2ddbbefe481b383cea0c37a1b7db9115d55aedd | KiranSpace/pythonScriptsTutorial | /Naveen/for.py | 578 | 3.6875 | 4 | #! /usr/bin/python
lst=[0,'one',2,"three"]
lst1=lst
print(id(lst1))
lst1=list(lst)
print(id(lst1))
scores={"kohli":100,"Shewag":55,"Ghambir":85}
newScores=scores
newScores['dravid']=200
print (id(scores))
print (id(newScores))
x=10
y=x
print (id(x))
print (id(y))
x=100
print("y :",y)
print("x :",x)
print (id(x))
print (id(y))
for element in scores.keys():
print(element, "Scored ", scores[element])
for num in range (-1,-11,-1):
print(num)
for num in range (0,20,2):
# if(num%2) == 0:
print(num)
|
30a37bc812e420d55d9530bfd4b2c4b3fa2fdff5 | Vinez1/TugasUas | /input-nilai.py | 1,160 | 3.75 | 4 | data = []
data = {}
print("PROGRAM MENAMPILKAN DAFTAR NILAI MAHASISWA")
while True:
print("")
c =input("(L)lihat, (T)ambah, (U)bah, (H)apus, (K)eluar : ")
if c.lower() == 't':
print("=======Tambah Data=======")
nama = input("Nama : ")
nim = input("Nim : ")
tugas = int(input("Masukan Nilai Tugas : "))
uts = int(input("Masukan Nilai UTS : "))
uas = int(input("Masukan Nilai UAS : "))
akhir = (0.30 * tugas) + (0.35 * uts) + (0.35 * uas)
data[nama] = nim, tugas, uts, uas, akhir
elif c.lower() == 'u':
print('=======Ubah Data Mahasiswa=======')
nama = input('Nama : ')
if nama in data.keys():
nim = input('Nim : ')
tugas = int(input("Masukan Nilai Tugas : "))
uts = int(input("Masukan Nilai UTS : "))
uas = int(input("Masukan Nilai UAS : "))
akhir = (0.30 * tugas) + (0.35 * uts) + (0.35 * uas)
data[nama] = nim, tugas, uts, uas, akhir
else:
print("Data Nilai Tidak Ada".format(nama))
|
01681d3cab571283947064c7c6b2d8675db86338 | Artimbocca/python | /demos/08-exceptions/06_tryfinally.py | 484 | 3.546875 | 4 | import traceback
def ExceptionDoNotCatch():
try:
print ("In ExceptionDoNotCatch")
i = 10
j = 0
z = i/j
print (z)
finally:
print ("Finally executed in ExceptionDoNotCatch")
print ("Will never reach this point")
print ("\nCalling ExceptionDoNotCatch")
try:
ExceptionDoNotCatch()
except Exception as e:
print ("Caught exception from ExceptionDoNotCatch in main program.")
print (e.args)
traceback.print_exc() |
39bf54d87234eb3e93c57f5a7d1ec6c0421c1eb8 | jrotithor/summer-projects | /matrix_multiplier.py | 1,266 | 4 | 4 | import sys
def matrix_multiplier(list_1, list_2,cols,rows,cols2,rows2):
sum = 0;
final_list = [[0 for i in range(rows)]for j in range(cols2)];
for i in range(rows):
for j in range(cols2):
for k in range(cols):
sum += list_1[i][k] * list_2[k][j];
#sum += 5;
print(sum);
k = 0;
final_list[j][i] = sum;
sum = 0;
j = 0;
return final_list;
cols = int(input("How many columns do you want in your first matrix?"));
rows = int(input("How many rows do you want in your first matrix?"));
cols2 = int(input("How many columns do you want in your second matrix?"));
rows2 = int(input("How many rows do you want in your second matrix?"));
list1 = [[0 for i in range(cols)] for j in range(rows)]
list2 = [[0 for i in range(cols2)] for j in range(rows2)]
if(cols != rows2):
print("matrices cannot be muliplied");
sys.exit();
print(list1);
print(list2);
#for(i in range(x*y)):
for i in range(rows):
for j in range(cols):
print(i);
list1[i][j] = int(input("Enter a number here"));
for i in range(rows2):
for j in range (cols2):
print(cols2);
print(rows2);
list2[i][j] = int(input("Enter a number here:"));
else:
print(matrix_multiplier(list1, list2, cols,rows,cols2,rows2));
|
8dfeacef6b844931cfbb3a4a2eebacf891856dbf | peltierchip/the_python_workbook_exercises | /chapter_3/exercise_71.py | 349 | 3.984375 | 4 | #Display 15 approximations of pi greek
#Store the number of approximations as a constant
LIMIT=15
app=3.0
#Display the approximations of pi greek up to the limit
for i in range(LIMIT):
#Compute the approximations
app=app+4*((-1)**i/((2*i+2)*(2*i+3)*(2*i+4)))
#Display the result
print("Approximation %2d of pi greek: %f"%(i+1,app))
|
ed3390a3240ace528d23cd5fe3c6d03ad102c044 | guozhaoxin/leetcode | /num001_100/num091_100/num096.py | 1,060 | 4.09375 | 4 | #encoding:utf8
__author__ = 'gold'
'''
Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
treeCount = [1 for i in range(n + 1)]
treeCount[2] = 2
nums = [i + 1 for i in range(n)]
for i in range(3,n + 1):
count = 0
for j in range(0,i):
count += treeCount[j] * treeCount[i - j - 1]
treeCount[i] = count
return treeCount[n]
if __name__ == '__main__':
print(Solution().numTrees(5)) |
5024a61791bcb8cddcafbfa5416f7668921cc553 | Psylekin/Advent_of_code | /advent_of_code/2/project/calc.py | 1,137 | 3.828125 | 4 |
def find_unique_characters(word):
return list(set(word))
inputList = [line.rstrip('\n') for line in open('input.txt')]
endresult = 0
def find_double_and_tribble_chars(inputList):
counter2 = 0
counter3 = 0
# Iteriere durch die Liste
for entrie in inputList:
# Finde einzigartige Buchstaben
uniqueList = find_unique_characters(entrie)
# Mach eine Liste, wie häufig die einzelnen Buchstaben in einem Wort sind.
charfrequencys = list()
for uniqueChar in uniqueList:
charfrequency = entrie.count(uniqueChar)
charfrequencys.append(charfrequency)
# Wenn du einen 2 findest --> Adde es zum Counter
if 2 in charfrequencys:
counter2 += 1
# Wenn du einee 3 findest --> Add es zum Counter
if 3 in charfrequencys:
counter3 += 1
return (counter2, counter3)
# Multipliziere counter 2 und 3
counter2, counter3 = find_double_and_tribble_chars(inputList)
endresult = counter2*counter3
print("Ergebnis: {}\n1: {}\n2: {}"
.format(endresult, counter2, counter3)) |
70f759af5dae88243501465b95af9ce92500f8fe | Lucas0liveira/Aulas-Inteligencia-Artificial | /Trabalho I - Algoritmos de Busca/MissionariosLargura.py | 3,079 | 3.71875 | 4 | def filhosToString(s):
return ' '.join([str(v) for v in s])
def objetivo(s):
goal = False
if (s[0] == 0) and (s[1] == 0) and (s[2] == 0):
goal = True
return goal
def validar(s):
# mais canibais que missionarios em qualquer lado do rio
if(s[0] > 0 and s[0] < s[1]) or (s[0] < 3 and s[0] > s[1]):
return False
return True
def geraFilhos(s):
listaDeFilhos = []
if(s[2] == 0): # partindo do lado direito do rio
if(s[0] < 3) and (s[1] < 3): # atravessar um de cada
estado = [s[0]+1, s[1]+1, 1]
if validar(estado):
listaDeFilhos.append(estado)
if (s[1] < 2): # atravessar dois canibais
estado = [s[0], s[1]+2, 1]
if validar(estado):
listaDeFilhos.append(estado)
if (s[0] < 2): # atravessar dois missionários
estado = [s[0]+2, s[1], 1]
if validar(estado):
listaDeFilhos.append(estado)
if (s[1] < 3): # atravessar um canibal
estado = [s[0], s[1]+1, 1]
if validar(estado):
listaDeFilhos.append(estado)
if (s[0] < 3): # atravessar um missionário
estado = [s[0]+1, s[1], 1]
if validar(estado):
listaDeFilhos.append(estado)
else: # partindo do lado esquerdo do rio
if(s[0] >= 1) and (s[1] >= 1): # atravessar um de cada
estado = [s[0]-1, s[1]-1, 0]
if validar(estado):
listaDeFilhos.append(estado)
if (s[1] >= 2): # atravessar dois canibais
estado = [s[0], s[1]-2, 0]
if validar(estado):
listaDeFilhos.append(estado)
if (s[0] >= 2): # atravessar dois missionários
estado = [s[0]-2, s[1], 0]
if validar(estado):
listaDeFilhos.append(estado)
if (s[1] >= 1): # atravessar um canibal
estado = [s[0], s[1]-1, 0]
if validar(estado):
listaDeFilhos.append(estado)
if (s[0] >= 1): # atravessar um missionário
estado = [s[0]-1, s[1], 0]
if validar(estado):
listaDeFilhos.append(estado)
return listaDeFilhos
def busca(inicio):
candidatos = [inicio]
pais = dict()
visitados = [inicio]
while len(candidatos) > 0:
pai = candidatos[0]
print("Lista de candidatos: ", candidatos)
del candidatos[0]
print("Visitado: ", pai)
if objetivo(pai):
res = []
node = pai
while node != inicio:
res.append(node)
node = pais[filhosToString(node)]
res.reverse()
print("Solucao encontrada: ", res)
for son in geraFilhos(pai):
if son not in visitados:
print("Enfileirado: ", son, pai)
visitados.append(son)
pais[filhosToString(son)] = pai
candidatos.append(son)
if __name__ == '__main__':
busca([3, 3, 1])
|
5126bebb8e60744a49ea5c3e1586101594a85b88 | sf-yaya/testPro | /task_two/game_g/game.py | 1,067 | 4.21875 | 4 | """
一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
定义一个fight方法:
final_hp = hp-enemy_power
enemy_final_hp = enemy_hp - power
两个hp进行对比,血量剩余多的人获胜
"""
# 定义一个游戏类
class Game:
# 初始化变量
def __init__(self, hp, power):
self.hp = hp
self.power = power
# 定义一个fight方法,传入对手的攻击力enemy_power、对手的血量enemy_hp两个参数
def fight(self, enemy_power, enemy_hp):
# 对2个hp进行计算
# 我的最终血量
final_hp = self.hp - enemy_power
# 对手的最终血量
enemy_final_hp = enemy_hp - self.power
# 两个hp进行对比,血量剩余多的人获胜
if final_hp > enemy_final_hp:
print("我赢了")
elif final_hp == enemy_final_hp:
print("平局")
else:
print("对手赢了")
# 实例化类
gm = Game(1000, 200)
gm.fight(800, 300)
|
1729fff9f46556b1efd2fb430bb4de34708f9bb0 | Ahmed--Mohsen/leetcode | /house_robber 2.py | 1,683 | 3.640625 | 4 | """
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def rob(self, nums):
n = len(nums)
# base cases
if n == 0: return 0
if n == 1: return nums[0]
# we have 2 options (1) rob house 0 (2) rob house n-1
# (1) solve for interval [0, n-2] (leave house n-1)
rob_first = self.rob_helper(nums, 0, n-2)
# (2) solve for interval [1, n-1] (leave house 0)
rob_last = self.rob_helper(nums, 1, n-1)
# answer is the max of the 2 options
return max(rob_first, rob_last)
# @param {integer[]} nums
# @param {integer} start
# @param {integer} end
# @return {integer}
def rob_helper(self, nums, start, end):
n = end - start + 1
# base cases ... n < 2
if n == 1: return nums[start]
if n == 2: return max(nums[start], nums[start+1])
# general case when n > 2
# dp[i] = max(dp[i-1], dp[i-2] + nums[i])
#dp = [0] * n
dp = [0] * n
dp[0] = nums[start]
dp[1] = max(nums[start], nums[start+1])
for i in range(2, n):
dp[i] = max(dp[i-1], dp[i-2] + nums[start+i])
return dp[n-1]
s = Solution()
print s.rob([1,16,5,20])
|
667e0adb73594c4cbb3056e27bfd16fcd198daac | huwenbo920529/otherLibraryStudy | /pandasStudy/test3.py | 1,838 | 3.6875 | 4 | # -*- coding:utf-8 -*-
# Pandas面板(Panel)
# 面板(Panel)是3D容器的数据。面板数据一词来源于计量经济学,部分源于名称:Pandas - pan(el)-da(ta)-s。
# 3轴(axis)这个名称旨在给出描述涉及面板数据的操作的一些语义。它们是 -
# items - axis 0,每个项目对应于内部包含的数据帧(DataFrame)。
# major_axis - axis 1,它是每个数据帧(DataFrame)的索引(行)。
# minor_axis - axis 2,它是每个数据帧(DataFrame)的列。
# pandas.Panel()
# 可以使用以下构造函数创建面板 -
# pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)
# Python
# 构造函数的参数如下 -
# 参数 描述
# data 数据采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个数据帧(DataFrame)
# items axis=0
# major_axis axis=1
# minor_axis axis=2
# dtype 每列的数据类型
# copy 复制数据,默认 - false
# 创建面板
# 可以使用多种方式创建面板 -
# 从ndarrays创建
# 从DataFrames的dict创建
import pandas as pd
import numpy as np
# 1.创建一个空面板
p1 = pd.Panel()
print(p1)
# 2.从3Dndarray创建
data = np.random.rand(2, 4, 5)
p2 = pd.Panel(data)
print(p2)
# 3.从DataFrame对象的dict创建面板
data = {'Item1': pd.DataFrame(np.random.randn(4, 3)),
'Item2': pd.DataFrame(np.random.randn(4, 2))}
p3 = pd.Panel(data)
print(p3)
# 4.从面板中选择数据
# 要从面板中选择数据,可以使用以下方式 -
# Items
# Major_axis
# Minor_axis
data = {'Item1': pd.DataFrame(np.array([i for i in range(12)]).reshape(4, 3)),
'Item2': pd.DataFrame(np.array([i for i in range(8)]).reshape(4, 2))}
p = pd.Panel(data)
print(p['Item1'])
print(p['Item2'])
print(p.major_xs(0)) # 每个Item的第1行
print(p.minor_xs(0)) # 每个Item的第1列
|
57c109f9b68c71f6fcaab1f52bafe7c48f828cec | mmenghnani/CS_learn | /Pattern Searching/anagram_substring_search.py | 846 | 3.640625 | 4 | def compare(count_pat, count_txt):
for i in range(256):
if count_pat[i] != count_txt[i]:
return False
return True
def search(pat, txt):
m = len(pat)
n = len(txt)
count_pat = [0]*256
count_txt = [0]*256
for i in range(m):
count_pat[ord(pat[i])] += 1
count_txt[ord(txt[i])] += 1
for i in range(m,n):
if compare(count_pat, count_txt):
print "found at ",(i-m)
#adding the current character to current window
count_txt[ord(txt[i])] += 1
#and removing the first of previous window
count_txt[ord(txt[i-m])] -= 1
#to check for last window in text
if compare(count_pat, count_txt):
print "found at ", (n-m)
txt = "BACDGABCDA"
pat = "ABCD"
search(pat, txt)
'''
time complexity O(n)
''' |
e648a29b5bff7a52d18bb4e1c90d8f9490d4c5b1 | ErinSmith17/100-days-of-code | /Days 67-69.py | 949 | 4.0625 | 4 | #Copy and Paste with Pyperclip
import pyperclip
AFFILIATE_CODE = '&tag=pyb0f-20'
url = pyperclip.paste()
if 'amazon' not in url:
print('Sorry, invalid link.')
else:
new_link = url + AFFILIATE_CODE
pyperclip.copy(new_link)
print('Affiliate Link generated and copied to clipboard')
#text replacer
def paste_from_clipboard():
text = pyperclip.paste()
return text
def copy_to_clipboard(new_text):
pyperclip.copy(new_text)
print("The new string is now copied to the clipboard. Hit CTRL V to paste.")
def replace_text(old_text):
target = input('What would you like to replace? ')
replacement = input('And what would you like to replace it with? ')
new_text = old_text.replace(target, replacement)
return new_text
if __name__ == "__main__":
old_text = paste_from_clipboard()
new_text = replace_text(old_text)
copy_to_clipboard(new_text)
input() |
703d3c255ce43567959c142c55a05ac4da359187 | jachang820/r-vs-python | /python/scatterplot.py | 838 | 3.75 | 4 | import matplotlib.pyplot as plt
# Interpolate more points to make it easier to visualize
# model prediction. This is especially necessary for CART
# algorithms to properly show the nodes.
def smooth_regression_line(X_test, model):
X_grid = np.arange(min(X_test), max(X_test), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
y_pred = model.predict(X_grid)
return X_grid, y_pred
# Scatter plot dataset with regression line
def scatterplot(X_train, X_test, y_train, y_test, y_pred, model, is_smooth):
if is_smooth == True:
X_test, y_pred = smooth_regression_line(X_test, model)
plt.scatter(X_train[:, 0], y_train, color='red')
plt.scatter(X_test[:, 0], y_test, color='pink')
plt.plot(X_test[:, 0], y_pred, color='blue')
plt.title('Prediction')
plt.xlabel('Independent variable')
plt.ylabel('Dependent variable')
plt.show()
|
ddbfef958a943647f7ae3c0b90f4a41ab2ced36c | gavrie/pycourse | /examples/memoize1.py | 511 | 3.515625 | 4 | ##########
def make_cached(func):
cache = {}
def cached_func(*args):
key = args
if key not in cache:
cache[key] = func(*args)
return cache[key]
return cached_func
##########
@make_cached
def calc(a, b):
# ....
result = 42 + a + b
print "calc({}, {}) => {}".format(a, b, result)
return result
# calc = make_cached(calc)
##########
def main():
calc(3, 4)
# ...
calc(5, 6)
calc(3, 4)
if __name__ == '__main__':
main()
|
211ccad6ad35466e6200649295cc8147c31be34c | deblina23/CodeChef | /Beginner/enormousInputTest.py | 618 | 3.8125 | 4 | #!/usr/bin/env python3
def readInput():
n,k = map(int,(input().split()))
listData = []
for number in range(0,n):
listData.append(int(input()))
return(k,listData)
def resultCalculation(data):
result = 0
k,listData = tuple(value for value in data)
if(k<=pow(10,7)):
for number in listData:
if((number<=(pow(10,9))) and ((number%k)==0)):
result =result+1
return(result)
def printResult(result):
print(result)
if __name__ == "__main__":
readData = readInput()
result = resultCalculation(readData)
printResult(result)
|
05443f3fb5b14fe9d97ef81eed5fdf934e4603c9 | DKCisco/Starting_Out_W_Python | /4_8.py | 169 | 4.03125 | 4 | # Rewrite the code so it calls the range function instead
# of using the list.
# Print a message five times
for x in range(1,5, +1):
print('I love to program') |
be5bfd864077b303279777f1cba595cebe5809f1 | blackozone/pynet-ons-feb19 | /day1/lists_ex1lee.py | 218 | 3.859375 | 4 | my_list = ["non", "naan", "nyan", "nine", "nein"]
print(my_list)
my_list.append("gucci")
my_list.append("prada")
print(my_list.pop(0))
print("Length of list: {}".format(len(my_list)))
my_list.sort()
print(my_list)
|
331f599b854d006ece817977c34b029a27087850 | pilgeun/Python2-Day-5-HW-Exercise-Song | /test_cities.py | 743 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import unittest
from city_functions import city_info
class CityTestCase(unittest.TestCase) :
"""Test for 'city_functions.py'"""
def test_city_country(self) :
"""Testing city = 'Anchorage', country = 'United States'"""
result = city_info('Anchorage','United States') #
self.assertEqual(result, 'Anchorage, United States - population 288,000')
def test_city_country_population(self) :
"""Testing city = 'Anchorage', country = 'United States, population = 288000"""
result = city_info('Anchorage','United States', 288000)
self.assertEqual(result, 'Anchorage, United States - population 288,000')
unittest.main()
|
941c04b580379d99c81ffff80762a4bb95d522a7 | DontTouchMyMind/education | /MFTU/lesson 3/practice/task_I.py | 835 | 4.125 | 4 | # Последовательность состоит из натуральных чисел и завершается числом 0.
# Определите значение наибольшего элемента последовательности.
#
# Числа, следующие за нулем, считывать не нужно.
#
# Формат входных данных
# Вводится последовательность целых чисел,
# оканчивающаяся числом 0 (само число 0 в последовательность не входит).
#
# Формат выходных данных
# Выведите ответ на задачу (одно число).
my_list = []
number = 1
while number != 0:
number = int(input())
my_list.append(number)
print(max(my_list))
|
0d65a4819226e7cd6491872a34d26323b20d9df8 | SRK-wakasugi/Dx- | /Python課題1/Q4.py | 314 | 3.96875 | 4 | import math
#ユーザー入力用
print("任意の自然数を入力してください")
num_a = float(input("a= "))
num_b = float(input("b= "))
#割り算(小数点以下切り捨て)
print(math.floor(num_a / num_b))
#割り算(小数点込み)
print(num_a / num_b)
input("処理終了")
|
c76d134c63ccd54934f8ca54422b5ff52b49aae6 | praveenv253/idsa | /endsem/find-the-count.py | 803 | 3.859375 | 4 | #!/usr/bin/env python
def main():
import sys
from bisect import bisect_left
# http://docs.python.org/2/library/bisect.html#searching-sorted-lists
def contains(a, x):
"""Locate the leftmost value exactly equal to x"""
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
count = 0
a = []
for line in sys.stdin.readlines():
line = line.replace('\n', '')
a.append(int(line))
a.sort()
l = len(a)
for i in xrange(l-1):
j = i + 1
while j < l:
index = contains(a, a[i] * a[j])
if index != -1 and index != i and index != j:
count += 1
j += 1
print count
if __name__ == '__main__':
main()
|
6d6dda6f91c46252b85a653d55e3859aebef082b | TJJTJJTJJ/leetcode | /31.next-permutation.py | 1,466 | 3.8125 | 4 | #
# @lc app=leetcode id=31 lang=python3
#
# [31] Next Permutation
#
# https://leetcode.com/problems/next-permutation/description/
#
# algorithms
# Medium (30.07%)
# Total Accepted: 217.9K
# Total Submissions: 724.3K
# Testcase Example: '[1,2,3]'
#
# Implement next permutation, which rearranges numbers into the
# lexicographically next greater permutation of numbers.
#
# If such arrangement is not possible, it must rearrange it as the lowest
# possible order (ie, sorted in ascending order).
#
# The replacement must be in-place and use only constant extra memory.
#
# Here are some examples. Inputs are in the left-hand column and its
# corresponding outputs are in the right-hand column.
#
# 1,2,3 → 1,3,2
# 3,2,1 → 1,2,3
# 1,1,5 → 1,5,1
#
#
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums)==0:
return
len_nums = len(nums)
j = len_nums-1
while j>0 and nums[j]<=nums[j-1]:
j-=1
if j==0:
self.swap(nums, 0, len_nums-1)
else:
k = len_nums-1
while nums[k]<=nums[j-1]:
k-=1
nums[j-1], nums[k] = nums[k], nums[j-1]
self.swap(nums, j, len_nums-1)
def swap(self, nums, i, j):
while i<j:
nums[i], nums[j]=nums[j], nums[i]
i+=1
j-=1
|
c5909f23f28f343ae0f4f4c51e856ff2bf7b0325 | sberk11/Python-Projects | /Python_Gui_Programming.py | 5,324 | 3.5 | 4 | from tkinter import *
from tkinter import messagebox
#PENCERE OLUŞTURMA
pencere = Tk() # Pencere Objesi
pencere.title("Program")
pencere.geometry("650x650")
#KULLANMAK İSTEDİĞİNİZ KISIMLARIN TIRNAKLARINI KALDIRIN.
"""
# alt ve üst frameler oluşturup ilerde bu bölgelere bi şeyler koyacağız.
#"INVISIBLE CONTAINERS" deniliyor bu frame'lere. Bu terim mantığını anlamamı sağlıyor.
üstframe = Frame(pencere)
üstframe.pack()
altframe = Frame(pencere)
altframe.pack(side=BOTTOM)
#LABEL OLUŞTURMA
metin = Label(pencere, text="Metin 1", bg="red",fg="white")
metin.pack() #pack yerine place kullanılırsa yerini de belirleriz.
#metin.pack() #pack kullanıldığında bulduğu ilk boşluğa nesnemizi yerleştirir.
metin2 = Label(pencere, text="Metin 2", bg="blue",fg="white")
metin2.pack(fill=X)
metin3 = Label(pencere, text="Metin 3", bg="black",fg="green")
metin3.pack(fill=Y, side=LEFT)
"""
"""
#ENTRY (GİRİŞ) OLUŞTURMA
isim = Label(pencere, text="İsim:")
isimgiris = Entry(pencere)
sifre = Label(pencere, text="Şifre Giriniz:")
sifregir = Entry(pencere)
#grid parametresi ile ızgara mantığı gibi yerleştirme yapılabilir. satır ve sütunlar oluşturur.
isim.grid(row=0, sticky="w") # sticky yazıyı yaslama yönünü belirtir.( 4 yön: n,s,w,e)
sifre.grid(row=1, sticky="w")
isimgiris.grid(row=0,column=1)
sifregir.grid(row=1, column=1)
#dikkat et pack kullanamıyoruz grid yaptığımız zaman. yeri belirtmeliyiz her şey için.
c = Checkbutton(pencere, text="Keep me Logged In")
c.grid(columnspan=2)
"""
"""
#BUTON OLUŞTURMA
buton1 = Button(altframe, text = "Buton", fg="green", bg="black",COMMAND=None)
buton1.pack()
"""
"""
#FONKSİYONLARI KULLANMA!!!
def yazdir(event):
print("Fonksiyon Çalıştı...")
buton1 = Button(pencere, text="Çalıştır-1", command=yazdir)
buton1.pack()
#buton1.bind("<Button-1>", yazdir)
# <Button-1> mouse da sol tık demek bu. Ayrıca bind kullanırken komutu sadece buraya yaz.
#Çoklu görev atama. bir tuşa birden fazla fonksiyon.
def sag(Event):
print("sağ")
def sol(Event):
print("sol")
def middle(Event):
print("orta")
#bu sefer içine tıkladığımızda yazdıracağımız bir frame olsun.
frame1 = Frame(pencere, width=150, height=200)
frame1.bind("<Button-1>", sol) #BUTON AYARLANIRSA SADECE BUTONA TIKLANDIĞINDA ÇALIŞIR...
frame1.bind("<Button-2>", middle) # BUTON AYARLANMAZSA PROGRAM AÇILDIĞINDA ÇALIŞIR.
frame1.bind("<Button-3>", sag) #BUTONA FONKSİYON ATANACAKSA CLICK YAPISI KULLANILMALI Kİ HEMEN ÇALIŞMASIN.
frame1.pack()
buton2 = Button(pencere, text="Çalıştır-2")
"""
"""
#CLASS YAPISI İLE ÇALIŞMA!!!
#ilk başta bir pencere ve butonlar self olarak çalıştırılacak ve gerisi sınıfın fonksiyonlarıyla yapılacak.
class Butonlar:
def __init__(self, master): #master dediğimizşey aslında pencere objesi. ismini öyle koyduk sadece.
frame1 = Frame(master)
frame1.pack()
self.yazdirmabutonu = Button(frame1, text="Mesajı Yazdır")
self.yazdirmabutonu.bind("<Button-1>", self.yazdir)
self.yazdirmabutonu.pack(side=LEFT)
self.cikisbuton = Button(frame1, text="ÇIKIŞ", command=frame1.quit)
self.cikisbuton.pack(side= BOTTOM)
def yazdir(self, Event):
print("Yazı Yazdırıldı...")
uyari = messagebox.showwarning("Uyarı!", "Konsola Bak!!!")
Butonlar(pencere)
"""
"""
#PROGRAMDA ÜST MENÜ ÇUBUĞU VE STATUS BAR OLUŞTURMA
def calis():
print("Tamam, yapmadık be!")
menu = Menu(pencere)
pencere.config(menu=menu)
#şimdi bu menunun içine bi şyler koyalım
altmenu = Menu(menu)
#üstte görünen menüler oluşturalım.
menu.add_cascade(label="File", menu=altmenu)
#üstteki menülerin içine alt açılır menüler koyalım.
altmenu.add_command(label="New", command=calis)
altmenu.add_command(label="Save", command=calis)
#ayrıcı çizgi ekleyelim.
altmenu.add_separator()
altmenu.add_command(label="Exit", command=quit)
#ikinci bir menü objesi daha ekleyelim
menu2 = Menu(menu)
menu.add_cascade(label="Edit", menu=menu2)
menu2.add_command(label="Ekle", command=calis)
#ŞİMDİ SIRA STATUS BAR OLUŞTURMADA(DURUM ÇUBUĞU)
status = Label(pencere, text="Yükleme Başarılı...", bd=1, relief=SUNKEN, anchor="w")
status.pack(side=BOTTOM, fill=X)
"""
"""
#MESSAGEBOX OLUŞTURMA
# from tkinter import messagebox #bu modülü import etmek zorundayız.
import sys
messagebox.showinfo(title="Bilgi", message="Hoşgeldiniz...") #bilgi penceresi
#çıkış sorusu
answer = messagebox.askokcancel(title="Çıkış", message="Emin misiniz?")
if answer == TRUE:
print("Çıkış Yapıldı...")
sys.exit()
"""
"""
#ŞEKİL VE GRAFİK ALANLARI
#grafik, şekil, metin koymak için bi canvas objesi oluşturalım.
canvas = Canvas(pencere, width=200, height=300)
canvas.pack()
yesilkure = canvas.create_oval(0,0,50,50, fill="green")
kırmızıcizgi = canvas.create_line(60,50,40,80, fill="red")
mavikare = canvas.create_rectangle(100,150,200,250, fill="blue")
#silmek istediğimiz obje olursa
#canvas.delete(kırmızıcizgi) #hepsini silmek için delete(ALL) diyebiliriz.
"""
#RESİM VE İKONLAR
foto = PhotoImage(file="ai.png")
label1 = Label(pencere, image=foto)
label1.pack(fill=BOTH)
mainloop() #PENCEREYİ SÜREKLİ EKRANDA TUTMAK İÇİN BİR LOOP OLUŞTURDUK.
|
e6f52e70fd77e5a176aef7d4781f28109eab4d28 | AlexanderBrandborg/DesignPatterns4Python | /Construction/singleton.py | 917 | 4 | 4 | # The classic singleton pattern. Now in Python!
# It's a bit wacky since we cannot protect the constructor
# Instead of accessing the singleton through a static method,
# we access it through dummy instances that are wrapped around it.
# (Usually I'd just implement singletonish behavior through a cached module,
# but hey this gives us the possibility of doing some inheritance)
class Singleton(object):
class __Singleton(object):
path = "/some/nice/place/on/the/drive/"
_instance = None
def __init__(self):
if not self._instance:
self._instance = self.__Singleton()
def __getattr__(self, name):
return getattr(self._instance, name)
# Notice that they are different objects,
# but the getattr implementation allows us to access the internal singletons attributes
s = Singleton()
print(s)
print(s.path)
t = Singleton()
print(t)
print(t.path)
|
a37715580315d38ce33bcd9182c9525daa8e5200 | wibowodiditri/Tugas-1 | /Soal - [3].py | 412 | 3.734375 | 4 | Teori = 70
Praktek = 70
nilai1 = int (input ("Masukkan Nilai Teori : "))
nilai2 = int (input("Masukkan Nilai Praktek : "))
if nilai1 & nilai2 >= 70:
print ("Selamat anda lulus!")
elif nilai2 < 70 & nilai1 >= 70:
print ("Anda harus mengulang ujian praktek")
elif nilai1 < 70 & nilai2 >= 70:
print ("Anda harus mengulang ujian teori")
else:
print ("Anda harus mengulang ujian teori dan praktek")
|
ffb775b61d8e6268d65137edf12950d26b360431 | LigianeBasques/aluraparte1 | /advinhacao.py | 601 | 3.953125 | 4 | print("*************************************")
print("Bem vindo ao jogo de advinhação!")
print("**************************************")
numero_secreto = 42
chute_str = input("Digite seu número: ")
print("Você", "digitou", chute_str)
chute = int(chute_str)
acertou = chute == numero_secreto
maior = chute>numero_secreto
menor = chute<numero_secreto
if(acertou):
print("Você acertou")
else:
if(maior):
print("Você errou, o seu chute foi maior que o número secreto")
elif(menor):
print("Você errou, o seu chute foi menor que o número secreto")
print("Game OVER")
|
ed21bced915dc8378907e5031fd5df8f845bb833 | Jashwanth-k/Data-Structures-and-Algorithms | /4.Linked Lists/MergeSort in Linked Lists .py | 2,071 | 3.859375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
def printLL(head):
while head is not None:
print(str(head.data)+'->',end='')
head = head.next
print('None')
return
def takeInput():
inputList = [int(ele) for ele in input().split()]
head = tail = None
for currdata in inputList:
if currdata == -1:
break
newNode = Node(currdata)
if head == None:
head = newNode
tail = newNode
else:
tail.next = newNode
tail = tail.next
return head
head = takeInput()
def merge(head1,head2):
#this function same as merging function which merges two sorted LL
fh = ft = None
if head1.data < head2.data:
fh = ft = head1
head1 = head1.next
else:
#head2.data <= head1.data
fh = ft = head2
head2 = head2.next
while head1 != None and head2 != None:
if head1.data < head2.data:
ft.next = head1
ft = ft.next
head1 = head1.next
else:
#head2.data <= head1.data
ft.next = head2
ft = ft.next
head2 = head2.next
if head1 is not None:
ft.next = head1
else:
#head2 is not None
ft.next = head2
return fh
def MergeSort_LL(head):
#base case if head.next is None returns head i.e last element of LL
#if head == None is special case for input given as null
if head == None or head.next == None:
return head
#finds mid value
slow = head
fast = head
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
mid = slow
#splits the LL into two parts using mid
head2 = mid.next
mid.next = None
head1 = head
head1 = MergeSort_LL(head1)
head2 = MergeSort_LL(head2)
fh = merge(head1,head2)
return fh
head = MergeSort_LL(head)
printLL(head) |
b6035c5d8ea752af0333cf02867065f630ffd397 | DasHache/Learnbybook | /bamboo/bamboo.py | 2,977 | 3.9375 | 4 | # To run this file
# python3 ./bamboo.py "1 2 10 3"
# ...
# Answer = 4
def splitter(a, m):
'''
Input:
a = list of integers, example: [1, 2, 3, 4]
m = element to split the list, example: 3
Output:
list of lists of integers, example: [ [1, 2], [4] ]
'''
# make list of strings from list of int
list_of_str = [str(i) for i in a]
# make string "1 2 3 4" from list ["1","2","3","4"]
s = ' '.join(list_of_str)
# if m = 3, make ["1 2 ", " 4"] from "1 2 3 4"
list_of_str = s.split(str(m))
# make [ ["1", "2"], ["4"] ] from ["1 2 ", " 4"]
list_of_lists_of_str = [a_string.split() for a_string in list_of_str]
# make [ [1, 2], [4] ] from [ ["1", "2"], ["4"] ]
list_of_lists_of_int = [ [int(si) for si in s] for s in list_of_lists_of_str]
return list_of_lists_of_int
def sword_stroke(a):
'''
Input:
a = list of integers
Output:
sum_len = number of sword strokes required
'''
print("Input list: ", str(a))
# CHECK: 'a' must be a list
if not isinstance(a, list): raise TypeError
if len(a) == 0:
return 0 # Empty list => zero stroke
# CHECK: 'a' must be a list of integers
if not isinstance(a[0], int): raise TypeError
if len(a) == 1:
return 1 # Single element => 1 stroke
# find the maximum element and split the array
m = max(a)
list_of_lists = splitter(a, m)
sum_len = 1
# summ up (recursively) for all the splits
for an_list in list_of_lists:
list_len = sword_stroke(an_list)
sum_len = sum_len + list_len
print("<== ", str(sum_len))
return sum_len
# Entry point
from sys import argv
str_of_int = argv[1] # second command line argument: string of integers
list_of_int = [int(s) for s in str_of_int.split()] # make it a list of integers
answer = sword_stroke(list_of_int)
print("Answer =", answer)
# Examples of "splitter" function calls:
# >>> splitter([4,4,4,3], 4)
# [[], [], [], ['3']]
# >>> splitter([4,4,4,3,4], 4)
# [[], [], [], ['3'], []]
# >>> splitter([4,4,4,3,2,1,3,4], 4)
# [[], [], [], ['3', '2', '1', '3'], []]
# >>> splitter([4,5,4,4,3,2,1,3,4], 4)
# [[], ['5'], [], ['3', '2', '1', '3'], []]
# function: sword_stroke
# input: list of numbers
# logic:
# - find the max element(s)
# - split the list into several lists (without the max element)
# - call sword_stroke on all the list and summ up the return values
# return = possible cases:
# - case1: len 0: []
# : then return 0
# - case2: all are equal: [4,4,4]
# : then return 1
# - case3: not all are equal: [4,4,4,3] or [4,4,3,4] or [4,1,2,1,3]
# : then split by the max number and call sword_stroke again on each part:
# : examples:
# [4,4,4,3] => [], [], [], [3] => 0 + 0 + 0 + 1
# [4,4,3,4] => [], [], [3], [] => 0 + 0 + 1 + 0
# [4,1,2,1,4,3] => [], [1,2,1], [3] => 0 + x + 1, where x = sword_stroke([1,2,1])
|
41a15c892132b5d558a3ed2430bb7b38d15d9acd | Zadrayca/Kourse | /lect10.1.py | 499 | 3.671875 | 4 | # Декораторы
#
# def decorator(funk):
# # преобразуем функцию в новую
#
# return new_funk
def decorator(funk):
def new_funk():
print('Запуск new_funk')
return funk() + 1
return new_funk
@decorator # Декорирование функции
def some_funk():
print('Запуск some_funk')
return max([1, 2, 3, 54, 56])
new_some_funk = decorator(some_funk) # запуск декоратора
print(new_some_funk()) |
4299cf6ae5a94e29f022391bfbe8b308c4ca91c3 | fan-weiwei/algo-prep | /xin-era/codility/maximal_slice/max_slice_sum.py | 1,307 | 3.71875 | 4 | """
given an array A consisting of N integers, returns the maximum sum of any slice of A
N is an integer within the range [1..1,000,000];
each element of array A is an integer within the range [−1,000,000..1,000,000];
the result will be an integer within the range [−2,147,483,648..2,147,483,647].
"""
def solution(arr):
if not arr: raise ValueError()
working_sum = arr[0]
result = arr[0]
for x in arr[1:]:
working_sum = max(x, working_sum + x)
if working_sum > result:
result = working_sum
return result
import unittest
class SliceTests(unittest.TestCase):
def testExample(self):
arr = [3, 2, -6, 4, 0]
self.assertEqual(solution(arr), 5)
def testSimple(self):
arr = [3, 2, 5]
self.assertEqual(solution(arr), 10)
def testNegative(self):
arr = [-3, -2, -5]
self.assertEqual(solution(arr), -2)
def testComplex(self):
arr = [3, 2, -6, 4, 0, 10, -2, 4, -6, -2, 2]
self.assertEqual(solution(arr), 16)
def testOnes(self):
arr = [1, 1, 1, 1, 1]
self.assertEqual(solution(arr), 5)
def testEmpty(self):
arr = []
self.assertRaises(ValueError, solution, arr)
if __name__ == '__main__':
unittest.main()
print('here')
|
4aa2308cc19e8637e6f055ab4b2279deb2c86f58 | PeterSchell11/Python---Beginnings | /Bool_IfElse.py | 275 | 3.796875 | 4 |
#boolean
food = 'rice'
if food == 'rice':
print('ummm, my favorite!')
print(100 * (food + '! '))
#if else
x = 4
if x == 5 :
print('x is equal to 5')
print('canhave multiple lines here with same indentation')
else :
print('x is not equal to 5')
|
ced9cbb4cf8048edc70b5f98d8308025669061ac | afridhasuhaina/pythonprogramming | /alphabetornot.py | 101 | 3.859375 | 4 | ch=input()
if(ch >='a'):
print("Alphabet")
elif(ch >='A'):
print("Alphabet")
else:
print("No")
|
1117ff1264d3380b1a70e7a81ddf66d5fa62f848 | reema-eilouti/python-problems | /CA11/problem10.py | 4,039 | 4.25 | 4 | # Define a class for the linked list
from node import Node
# Class for a simple Linked List
class LinkedList:
def __init__(self, data):
self.start_node = Node(data)
def traverse_list(self):
pointer_node = self.start_node
while pointer_node is not None:
print(pointer_node.data)
pointer_node = pointer_node.next
def insert_at_start(self, data):
new_node = Node(data)
pointer_node = new_node
pointer_node.next = self.start_node
self.start_node = new_node
def insert_at_end(self, data):
new_node = Node(data)
pointer_node = self.start_node
while pointer_node.next is not None:
pointer_node = pointer_node.next
pointer_node.next = new_node
def insert_after(self, x, data):
new_node = Node(data)
pointer_node = self.start_node
for point in range(x):
pointer_node = pointer_node.next
new_node.next = pointer_node.next
pointer_node.next = new_node
def insert_before_item(self, x, data):
new_node = Node(data)
pointer_node = self.start_node
while pointer_node.next.data != x:
pointer_node = pointer_node.next
else:
new_node.next = pointer_node.next
pointer_node.next = new_node
def insert_at_index (self, index, data):
new_node = Node(data)
pointer_node = self.start_node
for point in range(index-1):
pointer_node = pointer_node.next
new_node.next = pointer_node.next
pointer_node.next = new_node
def get_count(self):
counter = 0
pointer_node = self.start_node
while pointer_node is not None:
pointer_node = pointer_node.next
counter += 1
print(counter)
def search_item(self, x):
pointer_node = self.start_node
while pointer_node.data != x :
if pointer_node.next == None:
break
pointer_node = pointer_node.next
if pointer_node.next == None:
print("the item you are looking for does not exist")
else:
print(f"the item you are looking for exists ")
def make_new_list(self):
node_bravo = Node(2)
node_charlie = Node(3)
node_delta = Node(4)
node_echo = Node(5)
node_fox = Node(6)
node_alpha.start_node.next = node_bravo
node_bravo.next = node_charlie
node_charlie.next = node_delta
node_delta.next = node_echo
node_echo.next = node_fox
def delete_at_start(self):
pointer_node = self.start_node
self.start_node = pointer_node.next
def delete_at_end(self):
pointer_node = self.start_node
while pointer_node.next.next != None:
pointer_node = pointer_node.next
pointer_node.next = None
def reverse_linkedlist(self):
my_list = []
pointer_node = self.start_node
while pointer_node is not None:
my_list.append(pointer_node.data)
pointer_node = pointer_node.next
my_list.reverse()
print(my_list)
# Our linked list like this now
# (40)->(10)->(5)->(3)->(15)->(20)-> None
# node_1 = LinkedList(40)
# node_2 = Node(10)
# node_3 = Node(5)
# node_4 = Node(3)
# node_5 = Node(15)
# node_6 = Node(20)
# node_1.start_node.next = node_2
# node_2.next = node_3
# node_3.next = node_4
# node_4.next = node_5
# node_5.next = node_6
# node_1.insert_at_start(12)
# node_1.insert_at_end(88)
# node_1.insert_after
# node_1.insert_before_item(15,55)
# node_1.insert_at_index(2,66)
# node_1.get_count()
# node_1.traverse_list()
# node_1.search_item(40)
node_alpha = LinkedList(1)
node_alpha.make_new_list()
# node_alpha.delete_at_start()
# node_alpha.delete_at_end()
node_alpha.reverse_linkedlist()
# node_alpha.traverse_list() |
07363491eb30a5e49e5298ea9a979a18873f5f0c | xiaoliangL-12/driving | /driving.py | 357 | 4.03125 | 4 | country = input('请问你是哪国人: ')
age = input('请输入你年龄: ')
age = int(age)
if country == '中国人':
if age >= 18:
print('你可以开车')
else:
print('你不能开车')
elif country == '美国人':
if age >= 16:
print('你可以开车')
else:
print('你不能开车')
else:
print('你只能输入中国人或者美国人') |
6fc98a5e4bab4129f4e92c60fc7389bb980699e6 | devanshu464/devanshu | /Answer1(armstrong number).py | 361 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 19:09:19 2020
@author: HP
"""
num = int(input ("Enter an armstrong number\t"))
tempv = num
sum = 0
while tempv > 0:
digit = tempv % 10
sum = sum + digit**3
tempv = tempv // 10
#print(sum)
if sum == num:
print("Armstrong number")
else:
print("not an armstrong number") |
5da83da18aeff4df9b7dd7bf45073a9a275f455f | ckloppers/PythonTraining | /exercises/day1/wordsNum.py | 118 | 3.6875 | 4 |
sentence = raw_input("Sentence: ")
sentenceList = sentence.split(' ')
print 'Number of words: ', len(sentenceList) |
ebe40f17b7e85ff3c75d907998b9b4443bbecc65 | marcuswyh/deep-learning-tensorflow | /Part A/Question1_3.py | 8,039 | 3.5625 | 4 | import tensorflow as tf
from keras.utils import np_utils
import matplotlib.pyplot as plt
import numpy as np
CPU, GPU = '/CPU:0', '/GPU:0'
DEVICE = GPU
def loadData():
fashion_mnist = tf.keras.datasets.fashion_mnist
# load the training and test data
(tr_x, tr_y), (te_x, te_y) = fashion_mnist.load_data()
# reshape the feature data
tr_x = tr_x.reshape(tr_x.shape[0], 784)
te_x = te_x.reshape(te_x.shape[0], 784)
# noramlise feature data
tr_x = tr_x / 255.0
te_x = te_x / 255.0
print( "Shape of training features ", tr_x.shape)
print( "Shape of test features ", te_x.shape)
# one hot encode the training labels and get the transpose
tr_y = np_utils.to_categorical(tr_y,10)
print ("Shape of training labels ", tr_y.shape)
# one hot encode the test labels and get the transpose
te_y = np_utils.to_categorical(te_y,10)
print ("Shape of testing labels ", te_y.shape)
return tr_x, tr_y, te_x, te_y
def forward_pass(x, weights1, bias1, weights2, bias2, weights3, bias3):
# first layer (ReLu) with 300 neurons
A1 = tf.matmul(x, weights1) + bias1
H1 = tf.maximum(A1, 0)
# second layer (ReLu) with 100 neurons
A2 = tf.matmul(H1, weights2) + bias2
H2 = tf.maximum(A2, 0)
# second layer (softmax)
A3 = tf.matmul(H2, weights3) + bias3
t = tf.math.exp(A3)
sumOfT = tf.reduce_sum(t, axis=1)
sumOfT = tf.reshape(sumOfT, (H2.shape[0], 1))
H3 = t / sumOfT
return H3
def cross_entropy(y, pred, reg_rate, REG, weights1, weights2, weights3):
entropy = -tf.reduce_sum(y * tf.math.log(pred + 1e-9), axis=1)
loss = tf.reduce_mean(entropy)
# regularization
if REG == "L1":
# L1 REGULARISATION
l1 = reg_rate * (tf.reduce_sum(tf.math.abs(weights1)) + tf.reduce_sum(tf.math.abs(weights2)) + tf.reduce_sum(tf.math.abs(weights3)))
loss = loss + l1
elif REG == "L2":
# L2 REGULARISATION
l2 = reg_rate * (tf.reduce_sum(weights1 ** 2) + tf.reduce_sum(weights2 ** 2) + tf.reduce_sum(weights3 ** 2))
loss = loss + l2
return loss
def calculate_accuracy(x, y, weights1, bias1, weights2, bias2, weights3, bias3):
pred = forward_pass(x, weights1, bias1, weights2, bias2, weights3, bias3)
predictions_correct = tf.cast(tf.equal(tf.math.argmax(pred, axis=1), tf.math.argmax(y, axis=1)), tf.float32)
accuracy = tf.reduce_mean(predictions_correct)
return accuracy
def main():
with tf.device(DEVICE):
learning_rate = 0.01
iterations = 500
reg_rate = 0.0001
REG_TYPE = ["L1", "L2"]
TRAIN, TRAIN_LABEL, TEST, TEST_LABEL = loadData()
TRAIN = tf.cast(TRAIN, tf.float32)
TEST = tf.cast(TEST, tf.float32)
TRAIN_LABEL = tf.cast(TRAIN_LABEL, tf.float32)
TEST_LABEL = tf.cast(TEST_LABEL, tf.float32)
adam_optimizer = tf.keras.optimizers.Adam(learning_rate)
weights1, weights2, weights3 = tf.Variable(tf.random.normal([784, 300], mean=0.0, stddev=0.05, seed=0)), tf.Variable(tf.random.normal([300, 100], mean=0.0, stddev=0.05, seed=0)), tf.Variable(tf.random.normal([100, 10], mean=0.0, stddev=0.05, seed=0))
bias1, bias2, bias3 = tf.Variable(tf.zeros([300])), tf.Variable(tf.zeros([100])), tf.Variable(tf.zeros([10]))
accuracy_arr, val_acc_arr, loss_arr, val_loss_arr = [], [], [], []
for i in range(iterations):
with tf.GradientTape() as tape:
pred = forward_pass(TRAIN, weights1, bias1, weights2, bias2, weights3, bias3)
current_loss = cross_entropy(TRAIN_LABEL, pred, reg_rate, REG_TYPE[0], weights1, weights2, weights3)
val_pred = forward_pass(TEST, weights1, bias1, weights2, bias2, weights3, bias3)
val_loss = cross_entropy(TEST_LABEL, val_pred, reg_rate, REG_TYPE[0], weights1, weights2, weights3)
gradients = tape.gradient(current_loss, [weights1, bias1, weights2, bias2, weights3, bias3])
accuracy = calculate_accuracy(TRAIN, TRAIN_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)
val_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)
accuracy_arr.append(accuracy)
loss_arr.append(current_loss)
val_acc_arr.append(val_accuracy)
val_loss_arr.append(val_loss)
print ("Iteration", i, ": Loss = ", current_loss.numpy(), " Acc:", accuracy.numpy(), " Val loss = ", val_loss.numpy(), " Val Acc = ", val_accuracy.numpy())
adam_optimizer.apply_gradients(zip(gradients, [weights1, bias1, weights2, bias2, weights3, bias3]))
test_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)
print ("\nTest accuracy: ", test_accuracy.numpy(), "\n")
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, iterations), accuracy_arr, label="train_accuracy")
plt.plot(np.arange(0, iterations), loss_arr, label="train_loss")
plt.plot(np.arange(0, iterations), val_acc_arr, label="val_accuracy")
plt.plot(np.arange(0, iterations), val_loss_arr, label="val_loss")
plt.title("Training loss and accuracy (L1 Regularisation)")
plt.xlabel("Epoch#")
plt.ylabel("Loss/Accuracy")
plt.legend(['train_acc','train_loss', 'val_acc', 'val_loss'], loc="best")
plt.show()
adam_optimizer = tf.keras.optimizers.Adam(learning_rate)
weights1, weights2, weights3 = tf.Variable(tf.random.normal([784, 300], mean=0.0, stddev=0.05, seed=0)), tf.Variable(tf.random.normal([300, 100], mean=0.0, stddev=0.05)), tf.Variable(tf.random.normal([100, 10], mean=0.0, stddev=0.05))
bias1, bias2, bias3 = tf.Variable(tf.zeros([300])), tf.Variable(tf.zeros([100])), tf.Variable(tf.zeros([10]))
accuracy_arr2, loss_arr2, val_acc_arr2, val_loss_arr2 = [], [], [], []
for i in range(iterations):
with tf.GradientTape() as tape:
pred = forward_pass(TRAIN, weights1, bias1, weights2, bias2, weights3, bias3)
current_loss = cross_entropy(TRAIN_LABEL, pred, reg_rate, REG_TYPE[1], weights1, weights2, weights3)
val_pred = forward_pass(TEST, weights1, bias1, weights2, bias2, weights3, bias3)
val_loss = cross_entropy(TEST_LABEL, val_pred, reg_rate, REG_TYPE[1], weights1, weights2, weights3)
gradients = tape.gradient(current_loss, [weights1, bias1, weights2, bias2, weights3, bias3])
accuracy = calculate_accuracy(TRAIN, TRAIN_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)
val_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)
accuracy_arr2.append(accuracy)
loss_arr2.append(current_loss)
val_acc_arr2.append(val_accuracy)
val_loss_arr2.append(val_loss)
print ("Iteration", i, ": Loss = ", current_loss.numpy(), " Acc:", accuracy.numpy(), " Val loss = ", val_loss.numpy(), " Val Acc = ", val_accuracy.numpy())
adam_optimizer.apply_gradients(zip(gradients, [weights1, bias1, weights2, bias2, weights3, bias3]))
test_accuracy = calculate_accuracy(TEST, TEST_LABEL, weights1, bias1, weights2, bias2, weights3, bias3)
print ("\nTest accuracy: ", test_accuracy.numpy())
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, iterations), accuracy_arr2, label="train_accuracy")
plt.plot(np.arange(0, iterations), loss_arr2, label="train_loss")
plt.plot(np.arange(0, iterations), val_acc_arr2, label="val_accuracy")
plt.plot(np.arange(0, iterations), val_loss_arr2, label="val_loss")
plt.title("Training loss and accuracy (L2 Regularisation)")
plt.xlabel("Epoch#")
plt.ylabel("Loss/Accuracy")
plt.legend(['train_acc','train_loss', 'val_acc', 'val_loss'], loc="best")
plt.show()
main() |
4be4ff2e3d2d32e11e6849076f9ffe07623a2871 | jose-brenis-lanegra/Verificadores-en-Python | /conversion-cadena.py | 651 | 4.09375 | 4 | #convertir la cadena 3.87 a cadena
x="3.87"
a=str(x)
print(a)
#convertir el flotante 34.78 a cadena
x=34.78
a=str(x)
print(a)
#convertir el entero 324 a cadena
x=324
a=str(x)
print(a)
#convertir el booleano 476>=587 a cadena
x=476>=587
a=str(x)
print(a)
#convertir el booleano 64<67 a cadena
x=64<67
a=str(x)
print(a)
#convertir el entero -745 a cadena
x=-745
a=str(x)
print(a)
#convertir el flotante 0.56 a cadena
x=0.56
a=str(x)
print(a)
#convertir la cadena cinco a cadena
x="cinco"
a=str(x)
print(a)
#convertir la cadena 3276!=3276 a cadena
x="3276!=3276"
a=str(x)
print(a)
#convertir el flotante 64.78 a cadena
x=64.78
a=str(x)
print(a)
|
bd36a8a99fd2d3eae86da3fa0b115bd553f9a618 | eidanjacob/advent-of-code | /2020/6.py | 476 | 3.53125 | 4 | s = 0
with open("./input.txt") as f:
group = set()
first = True
for line in f:
if line != "\n" and line != "":
if first:
first = False
[group.add(c) for c in line if c != "\n"]
else:
newgroup = set([c for c in group if c in line])
group = newgroup
else:
first = True
s += len(group)
group = set()
print(s + len(group))
|
1b01641db2b2553e3d92c21271a7f5d0afe10b12 | All3yp/Daily-Coding-Problem-Solutions | /Solutions/137.py | 1,258 | 3.921875 | 4 | """
Problem:
Implement a bit array.
A bit array is a space efficient array that holds a value of 1 or 0 at each index.
init(size): initialize the array with size
set(i, val): updates index at i with val where val is either 1 or 0.
get(i): gets the value at index i.
"""
class Bit_Array:
def __init__(self, length: int) -> None:
self.length = length
self.indices = set()
def set(self, pos: int, val: int) -> None:
if pos >= self.length:
raise IndexError("Index is out of range")
if val == 0:
if pos in self.indices:
self.indices.remove(pos)
else:
self.indices.add(pos)
def get(self, pos: int) -> int:
if pos >= self.length:
raise IndexError("Index is out of range")
if pos in self.indices:
return 1
return 0
def __repr__(self) -> str:
res = []
for pos in range(self.length):
if pos in self.indices:
res.append(1)
else:
res.append(0)
return str(res)
if __name__ == "__main__":
arr = Bit_Array(8)
print(arr)
arr.set(5, 1)
arr.set(1, 1)
print(arr)
print(arr.get(1))
print(arr.get(4))
|
2a19f35e570f3436b15cc980ece15fc8564d6aa2 | jamesmcglone/dsp | /python/q8_parsing.py | 748 | 4.34375 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import csv
# open football.csv
with open('football.csv', "rb") as football:
new_diff = 100
new_team = ""
football.readline()
for row in csv.reader(football):
diff = abs(int(row[5]) - int(row[6]))
team = row[0]
if diff < new_diff:
new_diff = diff
new_team = team
print new_team
|
8cdc8f042c9ce47806a1a993a88e943e791a3a75 | github-ygy/python_leisure | /py4/UseDeco.py | 956 | 3.640625 | 4 | #!/usr/bin/env python
# author:ygy
import time
#使用高阶函数与嵌套函数实现装饰者模式
# def calTime(func):
# def decoFunc():
# startTime = time.time()
# func()
# endTime = time.time()
# print(" func takes time = %s" %(endTime - startTime))
# return decoFunc
#
# def test():
# time.sleep(3)
# print(" test is end ")
#
# test = calTime(test) #传递函数地址
# test()
##python 实现装饰者模式
def calTime(extra):
print(extra)
def outerFunc(func):
def decoFunc(*args,**kwargs):
startTime = time.time()
res = func(*args,**kwargs)
endTime = time.time()
print(" func takes time = %s" %(endTime - startTime))
return res
return decoFunc
return outerFunc
@calTime(extra = "test")
def test(msg):
time.sleep(3)
print(" test is end " + msg)
test(msg="this is extra param ")
|
4cf8edb7c85a44b6ac8332ad283362f0a91fb3b1 | Ablyamitov/Programming | /Practice/19/python/19.py | 1,708 | 3.875 | 4 | #алгоритм такой же, как и в с++, но не понимаю, почему не работает(согласен, код ужасный)???
import random
f = 0
a = 1
check = True
n = int(input())
allpassword = []
password = str(input())
notall=""
size_password = len(password)
notpassword =[size_password]
for i in range (size_password):
notpassword.append(0)
alll = ""
for i in range (1,size_password+1):
a*=i
for i in range (size_password):
for j in range (n):
notall += password[i]
notpassword[i] = notall
notall =""
allpassword =[a]
if(size_password<n):
for j in range (a):
check = True
for i in range (n):
x = random.randint(0,size_password-1)
alll += password[x]
allpassword.append(alll)
alll = ""
if (j>0):
for i in range (j):
if (allpassword[i]==allpassword[j]):
check = False
allpassword[j] =""
break
else:
continue
for h in range (size_password):
if (allpassword[j]==notpassword[h]):
check = False
allpassword[j]=""
break
else:
continue
if(check):
print(allpassword[j])
else:
j=j-1
continue
else:
for j in range (a):
check = True
for i in range (n):
x = random.randint(0,size_password-1)
alll+=password[x]
allpassword[j]=alll
for h in range(j):
if (allpassword[j]==notpassword[h]):
check =False
allpassword[j] =""
alll=""
break
else:
continue
if (check == False):
break
if (check == True):
for t in range (j):
if (allpassword[t]==allpassword[j]):
check = False
allpassword[j]=""
alll = ""
break
if (check == True):
print(allpassword[j]," ", end="")
alll = ""
else:
j-=1
continue
|
d1e5ab7bd3bd4df79f2d18969088f40eb357f019 | LiLi-scripts/Python_Basic | /Homework3/op_repeat.py | 562 | 3.890625 | 4 | n = input ("Enter a 5-digit number: ")
while True:
try:
k = int (n)
except ValueError:
print ("Input Number: ", n, " - is not a digit")
break
if 9999 < k <= 99999:
# 99999
k1 = k // 10000 * 10000 # 90000
k2 = k // 1000 * 1000 - k1 # 9000
k3 = k // 100 * 100 - k1 - k2 # 900
k4 = k // 10 * 10 - k1 - k2 -k3 # 90
k5 = k - k1 - k2 - k3 - k4 # 9
print (k1 + k3 + k5)
break
else:
print ("Number is not 5-digit")
break
|
a74dcbf05bd74239bad76737ff0c635b3325dbd7 | MatthewJHolden/Connect4 | /ConnectAI2.py | 15,084 | 3.734375 | 4 | import numpy as np
import random
import pygame
import sys
import math
# https://en.wikipedia.org/wiki/Minimax#Pseudocode
# https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning
#
BLUE = (0,0,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
ROW_COUNT = 6
COLUMN_COUNT = 7
PLAYER = 0
AI = 1
PLAYER_PIECE = 1
AI_PIECE = 2
WINDOWLENGTH = 4
EMPTY = 0
def create_board():
board = np.zeros((ROW_COUNT,COLUMN_COUNT))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_location(board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
# check all horizontal locations for win
for c in range(COLUMN_COUNT-3): #COLUMN_COUNT-3 because working from left to right if there is no piece
# at position COLUMN_COUNT-3 then not possible to have winning move -> same logic for rest
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check for vertical locations for win
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check for positively sloped diagonals
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check for negatively sloped diagonals
for c in range(COLUMN_COUNT-3):
for r in range(3,ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
def evaluate_window(window, piece):
score = 0
opp_piece = PLAYER_PIECE
if piece == PLAYER_PIECE:
opp_piece = AI_PIECE
if window.count(piece) == 4:
score += 4
elif window.count(piece) == 3 and window.count(EMPTY) == 1:
score += 5
elif window.count(piece) == 2 and window.count(EMPTY) == 2:
score += 2
if window.count(opp_piece) == 3 and window.count(EMPTY) == 1:
score -= 4
return score
def score_position(board, piece):
score = 0
# Score Centre
centre_array = [int(i) for i in list(board[:, COLUMN_COUNT//2])]
centre_count = centre_array.count(piece)
score += centre_count * 3
# Score Horizontal
for r in range(ROW_COUNT):
row_array = [int(i) for i in list(board[r,:])]
for c in range(COLUMN_COUNT-3):
window = row_array[c:c+WINDOWLENGTH]
score += evaluate_window(window, piece)
# Score Vertical
for c in range(COLUMN_COUNT):
col_array = [int(i) for i in list(board[:,c])]
for r in range(ROW_COUNT-3):
window = col_array[r:WINDOWLENGTH]
score += evaluate_window(window, piece)
# Score positive sloped diagonal
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT-3):
window = [board[r+i][c+i] for i in range(WINDOWLENGTH)]
score += evaluate_window(window, piece)
# Score negative sloped diagonal
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT-3):
window = [board[r+3-i][c+i] for i in range(WINDOWLENGTH)]
score += evaluate_window(window, piece)
return score
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locations(board)) == 0
def minimax(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, AI_PIECE):
return (None, 10000000)
elif winning_move(board, PLAYER_PIECE):
return (None, -10000000)
else: # Game is over, no more valid moves
return (None, 0)
else: #Depth is zero
return (None, score_position(board, AI_PIECE))
if maximizingPlayer:
value = -math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = get_next_open_row(board,col)
b_copy = board.copy()
drop_piece(b_copy, row, col, AI_PIECE)
new_score = minimax(b_copy, depth-1, alpha, beta, False)[1]
if new_score > value:
value = new_score
column = col
alpha = max(alpha, value)
if alpha >= beta:
break
return column, value
else: #minimising player
value = math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = get_next_open_row(board, col)
b_copy = board.copy()
drop_piece(b_copy, row, col, PLAYER_PIECE)
new_score = minimax(b_copy, depth-1, alpha, beta, True)[1]
if new_score < value:
value = new_score
column = col
beta = min(beta, value)
if alpha >= beta:
break
return column, value
def get_valid_locations(board):
valid_locations = []
for col in range(COLUMN_COUNT):
if is_valid_location(board,col):
valid_locations.append(col)
return valid_locations
def pick_best_move(board,piece):
valid_locations = get_valid_locations(board)
best_score = -1000
best_col = random.choice(valid_locations)
for col in valid_locations:
row = get_next_open_row(board, col)
temp_board = board.copy()
drop_piece(temp_board, row, col, piece)
score = score_position(temp_board, piece)
if score > best_score:
best_score = score
best_col = col
return best_col
class button():
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw(self, win, outline=None):
# Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 60)
text = font.render(self.text, 1, (0, 0, 0))
win.blit(text, (
self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))
def isOver(self, pos):
# Pos is the mouse position or a tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
def draw_board(board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
if board[r][c] == PLAYER_PIECE:
pygame.draw.circle(screen, RED, (int(c * SQUARESIZE + SQUARESIZE / 2), height - int(r * SQUARESIZE + SQUARESIZE / 2)), RADIUS)
elif board[r][c] == AI_PIECE:
pygame.draw.circle(screen, YELLOW,(int(c * SQUARESIZE + SQUARESIZE / 2), height - int(r * SQUARESIZE + SQUARESIZE / 2)),RADIUS)
pygame.display.update()
def text_objects(msg):
font = pygame.font.Font(pygame.font.get_default_font(), 36)
textSurface = font.render(msg, True, YELLOW)
# pygame.display.update(textSurface)
return textSurface, textSurface.get_rect()
def draw_main_screen(difficulty):
# pygame.draw.rect(screen, BLUE, (SQUARESIZE, SQUARESIZE, SQUARESIZE, SQUARESIZE))
startbutton.draw(screen,(0,0,0))
level1button.draw(screen,(0,0,0))
level2button.draw(screen, (0, 0, 0))
level3button.draw(screen, (0, 0, 0))
level4button.draw(screen, (0, 0, 0))
level5button.draw(screen, (0, 0, 0))
# label = mainfont.render("Select Difficulty Level", 1, YELLOW)
# screen.blit(label, (125, 350))
# color = (0, 255, 0)
msg = f'Select Difficulty Level:'
textSurf, textRect = text_objects(msg)
textRect.center = (width/2), STARTHEIGHT + 275
screen.blit(textSurf,textRect)
msg2 = f'Difficulty Level: {difficulty}'
textSurf, textRect = text_objects(msg2)
textRect.center = (width/2), STARTHEIGHT + 175
screen.blit(textSurf,textRect)
pygame.display.update()
board = create_board()
print_board(board)
game_over = False
pygame.init()
SQUARESIZE = 100
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width,height)
RADIUS = int(SQUARESIZE/2 - 5)
STARTHEIGHT = 100
screen = pygame.display.set_mode(size)
startbutton = button((0, 255, 0), 225, STARTHEIGHT, 250, 100, 'Start Game')
difficultyY = STARTHEIGHT + 325
difficulty = 3
level1button = button((0, 255, 0), 25, difficultyY, 100, 100, '1')
level2button = button((0, 255, 0), (550/4+25), difficultyY, 100, 100, '2')
level3button = button((0, 255, 0), (550/4*2+25), difficultyY, 100, 100, '3')
level4button = button((0, 255, 0), (550/4*3+25), difficultyY, 100, 100, '4')
level5button = button((0, 255, 0), 575, difficultyY, 100, 100, '5')
myfont = pygame.font.SysFont("monospace", 75)
mainfont = pygame.font.SysFont("monospace", 25)
# Main Screen Loop
home = True
turn = random.randint(PLAYER,AI)
while not game_over:
while home:
pygame.display.update()
draw_main_screen(difficulty)
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if startbutton.isOver(pos):
home = False
if level1button.isOver(pos):
screen.fill((0,0,0))
difficulty = 1
draw_main_screen(difficulty)
if level2button.isOver(pos):
screen.fill((0, 0, 0))
difficulty = 2
draw_main_screen(difficulty)
if level3button.isOver(pos):
screen.fill((0, 0, 0))
difficulty = 3
draw_main_screen(difficulty)
if level4button.isOver(pos):
screen.fill((0, 0, 0))
difficulty = 4
draw_main_screen(difficulty)
if level5button.isOver(pos):
screen.fill((0, 0, 0))
difficulty = 5
draw_main_screen(difficulty)
if event.type == pygame.MOUSEMOTION:
if startbutton.isOver(pos):
startbutton.color = (255, 0, 0)
else:
startbutton.color = (0, 255, 0)
if level1button.isOver(pos):
level1button.color = (255, 0, 0)
else:
level1button.color = (0, 255, 0)
if level2button.isOver(pos):
level2button.color = (255, 0, 0)
else:
level2button.color = (0, 255, 0)
if level3button.isOver(pos):
level3button.color = (255, 0, 0)
else:
level3button.color = (0, 255, 0)
if level4button.isOver(pos):
level4button.color = (255, 0, 0)
else:
level4button.color = (0, 255, 0)
if level5button.isOver(pos):
level5button.color = (255, 0, 0)
else:
level5button.color = (0, 255, 0)
draw_board(board)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0,0,width,SQUARESIZE))
posx = event.pos[0]
if turn == PLAYER:
pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS)
# else:
# pygame.draw.circle(screen, YELLOW, (posx, int(SQUARESIZE / 2)), RADIUS)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
# print(event.pos)
# Ask for Player 1 Input
if turn == PLAYER:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, PLAYER_PIECE)
pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
if winning_move(board, PLAYER_PIECE):
pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
label = myfont.render("Player 1 Wins!!", 1, RED)
screen.blit(label, (40,10))
game_over = True
turn += 1
turn = turn % 2
# print_board(board)
draw_board(board)
# Ask for AI Input
if turn == AI and not game_over:
# col = random.randint(0, COLUMN_COUNT-1)#
# col = pick_best_move(board, AI_PIECE)
col,mimimax_score = minimax(board,difficulty, -math.inf, math.inf, True)
if is_valid_location(board, col):
pygame.time.wait(500)
row = get_next_open_row(board, col)
drop_piece(board, row, col, AI_PIECE)
if winning_move(board, AI_PIECE):
pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
label = myfont.render("Player 2 Wins!!", 1, YELLOW)
screen.blit(label, (40,10))
game_over = True
print_board(board)
draw_board(board)
turn += 1
turn = turn % 2
while game_over:
msg = f'Press X to Exit'
font = pygame.font.Font(pygame.font.get_default_font(), 36)
textSurf = font.render(msg, True, (255,255,255))
textRect = textSurf.get_rect()
textSurf, textRect = text_objects(msg)
textRect.center = (width / 2), 95
screen.blit(textSurf, textRect)
pygame.display.update()
game_over = True
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
sys.exit()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.