blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
02bb684370a2ee69f635f4108fb731a8338d081a | photonPrograms/TicTacToe | /play1p.py | 5,132 | 4.21875 | 4 | from random import choice as chrand
def disp_board(board, nrow = 3, ncol = 3):
"""display the current status of the board"""
print(" ", end = "")
for j in range(ncol):
print(f"{j + 1}", end = " ")
print()
for j in range(ncol + 1):
print("--", end = "")
print("-")
for i in range(nrow):
print("|", end = " ")
for j in range(ncol):
print(f"{board[i][j]}", end = " ")
print(f"| {i + 1}")
for j in range(ncol + 1):
print("--", end = "")
print("-")
def play1p(nrow = 3, ncol = 3, consec = 3):
"""
to let two players play a game of tictactoe
with a 3 x 3 game board with 3 consecutive symbols to be joined
return the name of the winner
"""
# a list of 2 dictionaries to hold the players
p = [{}, {}]
print("Player 1, what is your name?")
p[0]["name"] = input()
print("Player 2 is the computer - 'Lord of Probability'.")
p[1]["name"] = "Lord of Probability"
# allocation of symbols to the players
print("Tossing a coin to decide who chooses the symbol...")
k = chrand([0, 1])
print(f"{p[k]['name']} chooses the symbol. So what do you choose - X or O?")
if k == 0:
while True:
sym = input()
if sym.upper() == "X" or sym.upper() == "O":
break
print("Invalid choice. Enter X or O.")
else:
sym = chrand(["X", "O"])
print(f"I choose {sym}")
p[k]["sym"] = sym
k = 0 if k else 1
p[k]["sym"] = "X" if sym.upper() == "O" else "O"
# board is 2D array to hold the current status of the playing board
board = []
for i in range(nrow):
board.append([])
for j in range(ncol):
board[i].append(".")
# deciding who plays first
print("Tossing a coin to decide who takes the first turn...")
k = chrand([0,1])
# playing until we run out of the board or someone wins
turn = 1 # the turn number
while turn <= ncol * nrow:
print(f"Board at turn {turn}:\n")
disp_board(board, nrow, ncol)
print(f"{p[k]['name']} plays the turn {turn}.")
while True:
if k == 0:
coord = input().split("-")
r, c = int(coord[0]), int(coord[1])
else:
r = chrand(range(nrow)) + 1
c = chrand(range(ncol)) + 1
if (r >= 1 and r <= nrow) and (c >= 1 and c <= ncol):
if board[r - 1][c - 1] == ".":
board[r - 1][c - 1] = p[k]["sym"]
break
else:
if k == 0:
print("Occupied. Enter vacant coordinates.")
else:
if k == 0:
print("Out of bounds. Enter valid coordinates.")
# checking along for victory along rows
for i in range(nrow):
for j in range(ncol - consec + 1):
sym = board[i][j]
if sym == ".":
continue
l = 0
while l < consec :
if board[i][j + l] != sym:
break
l += 1
if l == consec:
winner = p[k]["name"] if sym == p[k]["sym"] else p[0 if k else 1]["name"]
return winner
# checking for victory along columns
for j in range(ncol):
for i in range(nrow - consec + 1):
sym = board[i][j]
if sym == ".":
continue
l = 0
while l < consec:
if board[i + l][j] != sym:
break
l += 1
if l == consec:
winner = p[k]["name"] if sym == p[k]["sym"] else p[0 if k else 1]["name"]
return winner
# checking for victory along diagonals
for i in range(nrow - consec + 1):
# checking for victory along \ diagonals
for j in range(ncol - consec + 1):
sym = board[i][j]
if sym == ".":
continue
l = 0
while l < consec:
if board[i + l][j + l] != sym:
break
l += 1
if l == consec:
winner = p[k]["name"] if sym == p[k]["sym"] else p[0 if k else 1]["name"]
return winner
# checking for victory along / diagonals
for j in reversed(range(consec - 1, ncol)):
sym = board[i][j]
if sym == ".":
continue
l = 0
while l < consec:
if board[i + l][j - l] != sym:
break
l += 1
if l == consec:
winner = p[k]["name"] if sym == p[k]["sym"] else p[0 if k else 1]["name"]
return winner
k = 0 if k else 1
turn += 1
return "Draw: Both"
|
7062768b022d7d32868aa727e824a369a2c5847a | thesourabh/python-practice | /ProjectEuler/145-unfinished.py | 316 | 3.671875 | 4 | def rev(n):
r = 0
if (n % 10 == 0):
return 2000000000
while(n > 0):
r = r * 10 + (n % 10)
n /= 10
return r
def reversible(n):
while (n > 0):
if (n % 10 % 2 == 0):
return False
n /= 10
return True
count = 0
for i in xrange(1, 500000):
n = i + rev(i)
if (reversible(n)):
count += 1
print count |
929b6dc095ea73c5111092c914de94c37573dec8 | soneo1127/pysc2-examples | /mineral/tsp2.py | 8,684 | 4.03125 | 4 | import math
import random
def distL2(x1,y1, x2,y2):
"""Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
xdiff = x2 - x1
ydiff = y2 - y1
return int(math.sqrt(xdiff*xdiff + ydiff*ydiff) + .5)
def distL1(x1,y1, x2,y2):
"""Compute the L1-norm (Manhattan) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
return int(abs(x2-x1) + abs(y2-y1)+.5)
def mk_matrix(coord, dist):
"""Compute a distance matrix for a set of points.
Uses function 'dist' to calculate distance between
any two points. Parameters:
-coord -- list of tuples with coordinates of all points, [(x1,y1),...,(xn,yn)]
-dist -- distance function
"""
n = len(coord)
D = {} # dictionary to hold n times n matrix
for i in range(n-1):
for j in range(i+1,n):
(x1,y1) = coord[i]
(x2,y2) = coord[j]
D[i,j] = dist(x1,y1, x2,y2)
D[j,i] = D[i,j]
return n,D
def read_tsplib(filename):
"basic function for reading a TSP problem on the TSPLIB format"
"NOTE: only works for 2D euclidean or manhattan distances"
f = open(filename, 'r')
line = f.readline()
while line.find("EDGE_WEIGHT_TYPE") == -1:
line = f.readline()
if line.find("EUC_2D") != -1:
dist = distL2
elif line.find("MAN_2D") != -1:
dist = distL1
else:
print("cannot deal with non-euclidean or non-manhattan distances")
raise Exception
while line.find("NODE_COORD_SECTION") == -1:
line = f.readline()
xy_positions = []
while 1:
line = f.readline()
if line.find("EOF") != -1: break
(i,x,y) = line.split()
x = float(x)
y = float(y)
xy_positions.append((x,y))
n,D = mk_matrix(xy_positions, dist)
return n, xy_positions, D
def mk_closest(D, n):
"""Compute a sorted list of the distances for each of the nodes.
For each node, the entry is in the form [(d1,i1), (d2,i2), ...]
where each tuple is a pair (distance,node).
"""
C = []
for i in range(n):
dlist = [(D[i,j], j) for j in range(n) if j != i]
dlist.sort()
C.append(dlist)
return C
def length(tour, D):
"""Calculate the length of a tour according to distance matrix 'D'."""
z = D[tour[-1], tour[0]] # edge from last to first city of the tour
for i in range(1,len(tour)):
z += D[tour[i], tour[i-1]] # add length of edge from city i-1 to i
return z
def randtour(n):
"""Construct a random tour of size 'n'."""
sol = list(range(n)) # set solution equal to [0,1,...,n-1]
random.shuffle(sol) # place it in a random order
return sol
def nearest(last, unvisited, D):
"""Return the index of the node which is closest to 'last'."""
near = unvisited[0]
min_dist = D[last, near]
for i in unvisited[1:]:
if D[last,i] < min_dist:
near = i
min_dist = D[last, near]
return near
def nearest_neighbor(n, i, D):
"""Return tour starting from city 'i', using the Nearest Neighbor.
Uses the Nearest Neighbor heuristic to construct a solution:
- start visiting city i
- while there are unvisited cities, follow to the closest one
- return to city i
"""
unvisited = list(range(n))
unvisited.remove(i)
last = i
tour = [i]
while unvisited != []:
next = nearest(last, unvisited, D)
tour.append(next)
unvisited.remove(next)
last = next
return tour
def exchange_cost(tour, i, j, D):
"""Calculate the cost of exchanging two arcs in a tour.
Determine the variation in the tour length if
arcs (i,i+1) and (j,j+1) are removed,
and replaced by (i,j) and (i+1,j+1)
(note the exception for the last arc).
Parameters:
-t -- a tour
-i -- position of the first arc
-j>i -- position of the second arc
"""
n = len(tour)
a,b = tour[i],tour[(i+1)%n]
c,d = tour[j],tour[(j+1)%n]
return (D[a,c] + D[b,d]) - (D[a,b] + D[c,d])
def exchange(tour, tinv, i, j):
"""Exchange arcs (i,i+1) and (j,j+1) with (i,j) and (i+1,j+1).
For the given tour 't', remove the arcs (i,i+1) and (j,j+1) and
insert (i,j) and (i+1,j+1).
This is done by inverting the sublist of cities between i and j.
"""
n = len(tour)
if i>j:
i,j = j,i
assert i>=0 and i<j-1 and j<n
path = tour[i+1:j+1]
path.reverse()
tour[i+1:j+1] = path
for k in range(i+1,j+1):
tinv[tour[k]] = k
def improve(tour, z, D, C):
"""Try to improve tour 't' by exchanging arcs; return improved tour length.
If possible, make a series of local improvements on the solution 'tour',
using a breadth first strategy, until reaching a local optimum.
"""
n = len(tour)
tinv = [0 for i in tour]
for k in range(n):
tinv[tour[k]] = k # position of each city in 't'
for i in range(n):
a,b = tour[i],tour[(i+1)%n]
dist_ab = D[a,b]
improved = False
for dist_ac,c in C[a]:
if dist_ac >= dist_ab:
break
j = tinv[c]
d = tour[(j+1)%n]
dist_cd = D[c,d]
dist_bd = D[b,d]
delta = (dist_ac + dist_bd) - (dist_ab + dist_cd)
if delta < 0: # exchange decreases length
exchange(tour, tinv, i, j);
z += delta
improved = True
break
if improved:
continue
for dist_bd,d in C[b]:
if dist_bd >= dist_ab:
break
j = tinv[d]-1
if j==-1:
j=n-1
c = tour[j]
dist_cd = D[c,d]
dist_ac = D[a,c]
delta = (dist_ac + dist_bd) - (dist_ab + dist_cd)
if delta < 0: # exchange decreases length
exchange(tour, tinv, i, j);
z += delta
break
return z
def localsearch(tour, z, D, C=None):
"""Obtain a local optimum starting from solution t; return solution length.
Parameters:
tour -- initial tour
z -- length of the initial tour
D -- distance matrix
"""
n = len(tour)
if C == None:
C = mk_closest(D, n) # create a sorted list of distances to each node
while 1:
newz = improve(tour, z, D, C)
if newz < z:
z = newz
else:
break
return z
def multistart_localsearch(k, n, D, report=None):
"""Do k iterations of local search, starting from random solutions.
Parameters:
-k -- number of iterations
-D -- distance matrix
-report -- if not None, call it to print verbose output
Returns best solution and its cost.
"""
C = mk_closest(D, n) # create a sorted list of distances to each node
bestt=None
bestz=None
for i in range(0,k):
tour = randtour(n)
z = length(tour, D)
z = localsearch(tour, z, D, C)
if bestz == None or z < bestz:
bestz = z
bestt = list(tour)
if report:
report(z, tour)
return bestt, bestz
if __name__ == "__main__":
"""Local search for the Travelling Saleman Problem: sample usage."""
#
# test the functions:
#
# random.seed(1) # uncomment for having always the same behavior
import sys
if len(sys.argv) == 1:
# create a graph with several cities' coordinates
coord = [(4,0),(5,6),(8,3),(4,4),(4,1),(4,10),(4,7),(6,8),(8,1)]
n, D = mk_matrix(coord, distL2) # create the distance matrix
instance = "toy problem"
else:
instance = sys.argv[1]
n, coord, D = read_tsplib(instance) # create the distance matrix
# n, coord, D = read_tsplib('INSTANCES/TSP/eil51.tsp') # create the distance matrix
# function for printing best found solution when it is found
from time import clock
init = clock()
def report_sol(obj, s=""):
print("cpu:%g\tobj:%g\ttour:%s" % \
(clock(), obj, s))
print("*** travelling salesman problem ***")
# random construction
print("random construction + local search:")
tour = randtour(n) # create a random tour
z = length(tour, D) # calculate its length
print("random:", tour, z, ' --> ',)
z = localsearch(tour, z, D) # local search starting from the random tour
print(tour, z)
# greedy construction
print("greedy construction with nearest neighbor + local search:")
for i in range(n):
tour = nearest_neighbor(n, i, D) # create a greedy tour, visiting city 'i' first
z = length(tour, D)
print("nneigh:", tour, z, ' --> ',)
z = localsearch(tour, z, D)
print(tour, z)
# multi-start local search
print("random start local search:")
niter = 100
tour,z = multistart_localsearch(niter, n, D, report_sol)
assert z == length(tour, D)
print("best found solution (%d iterations): z = %g" % (niter, z))
print(tour) |
a370331a756b5790e1dd67fba818520922da08b9 | niraj-r/RCXD | /rpLidar_python/Thread_Tests/threadtest2.py | 1,556 | 3.578125 | 4 | """
This comes from a tutorial found here:
https://www.youtube.com/watch?v=i1SW4q9yUEs
I want to create a queue so that LIDAR data can be captured
independently from any drawing. I'm worried the drawing
will slow down the reading and data points will be dropped
I initially thought to use RabbitMQ or ZeroMQ but this seemed
like I was thinking in the wrong direction. I think threads
are the way to go. If we decide to process offline from the
bot itself then I will switch back to the Queue
"""
import threading, time, random
try:
import Queue
except:
import queue as Queue
class Producer:
def __init__(self):
self.food = ["ham", "soup", "salad"]
self.nextTime = 0
def run(self):
global q
while (time.clock() < 10):
if(self.nextTime < time.clock()):
f = self.food[random.randrange(len(self.food))]
q.put(f)
print("Adding " + f)
self.nextTime += random.random()
class Consumer:
def __init__(self):
self.nextTime = 0
def run(self):
global q
while (time.clock() < 10):
if (self.nextTime < time.clock() and not q.empty()):
f = q.get()
print("Removing " + f)
self.nextTime += random.random() * 2
if __name__ == '__main__':
q = Queue.Queue(10)
p = Producer()
c = Consumer()
pt = threading.Thread(target=p.run, args=())
ct = threading.Thread(target=c.run, args=())
pt.start()
ct.start()
|
91ab6e03396f616b0bfd69b3e33f3ae99daf7c72 | wdampier2000/pyton-curso | /09-Listas/main.py | 1,291 | 4.0625 | 4 | """
Colecciones o conjuntos de datos/valores bajo un unico nombre
Para acceder a esos datos usamos indice numerico
"""
Lista1=["Victor", "Jose", "Raul"]
print (Lista1)
#otra forma
cantantes= list(("Luis Miguel", "Riqui Martin", "Julio Iglesias"))
print (cantantes)
#otra
year = list(range(2020,2025))
print (year)
#otra
variada=["Casa", 2019, 23.8, True, "Victor"]
print (variada)
print("\n")
#Indices
print(cantantes[2])
print("\n")
print(cantantes[0:3])
print("\n")
print(cantantes[1:])
cantantes[2]="Sabrina"
print("\n")
print(cantantes[2])
print("\n")
print(cantantes[0:])
#Agregar elementos
cantantes.append("BBKING")
print(cantantes[0:])
#mostrar listado de cantantes y ubicacion en la lista
print("\n")
for cantante in cantantes:
print (f"{cantantes.index(cantante)} {cantante}")
"""
#Agregar cantantes a la lista
nuevoCantante=""
while nuevoCantante != "fin":
nuevoCantante=input(f"Nuevo cantante: ")
cantantes.append(nuevoCantante)
print(cantantes[0:])
"""
#listas multidimensionales
contactos=[
[
'Victor',
'rmi.com.ar'
],
[
'Jose',
'Nubemotic.com.ar'
],
[
'Roberto',
'google.com.ar'
]
]
print("\n")
print(contactos)
print(contactos[1][1])
print(contactos[1][0])
print(contactos[0][1])
print("\n")
|
efe5f2e1cdd39d4bf49420e20b1b2f1822e8284c | szhao13/interview_prep | /girl_scouts.py | 763 | 3.890625 | 4 |
def merge_lists(array_0, array_1):
curr_id_0 = 0
curr_id_1 = 0
merged_array = []
len_0 = len(array_0)
len_1 = len(array_1)
total = len_0 + len_1
for index in range(total):
if curr_id_0 < len_0:
if curr_id_1 == len_1 or array_0[curr_id_0] <= array_1[curr_id_1]:
merged_array.append(array_0[curr_id_0])
curr_id_0 += 1
continue
# print "curr_id_0 is %d" %curr_id_0
if curr_id_1 < len_1:
if curr_id_0 == len_0 or array_1[curr_id_1] <= array_0[curr_id_0]:
merged_array.append(array_1[curr_id_1])
curr_id_1 += 1
# print merged_array
return merged_array
my_list = [3, 4, 6, 10, 11, 15]
alices_list = [1, 5, 8, 12, 14, 19]
# Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]
print merge_lists(my_list, alices_list) |
af9629037f201e6484c0825da4cc56c2d3fe5616 | Omkarj21/Data-Structures_Collections_Collectors | /number.py | 1,452 | 3.859375 | 4 | # Important Packages = math, binary, decimal, fraction
# -------------------------------------
# Numerical literals :
# integer, float, complex
# -------------------------------------
# Output: <class 'int'>
print(type(2))
# Output: <class 'float'>
print(type(2.0))
# Output: (15+2j)
a = 9 + 2j
print(a + 6)
# Output: True
print(isinstance(a, complex))
# -------------------------------------
# Output: 59
print(0b111011)
# Output: 173 (171 + 2)
print(0xAB + 0b10)
# Output: 250
print(0xFA)
# Output: 9
print(0o11)
# -------------------------------------
# fractions Module
from fractions import Fraction as f
# Output: 3/2
print(f(1.5))
# Output: 5
print(f(5))
# Output: 1/3
print(f(1,3))
# Output: 2/3
print(f(1,3) + f(1,3))
# Output: 6/5
print(1 / f(5,6))
# Output: False
print(f(-3,10) > 0)
# Output: True
print(f(-3,10) < 0)
# -----------------------------------------------------------------------------------------------
# math module
import math
# Output: 3.141592653589793
print(math.pi)
# Output: -1.0
print(math.cos(math.pi))
# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))
# Output: 1.1752011936438014
print(math.sinh(1))
# Output: 720
print(math.factorial(6))
# -------------------------------------
# decimal module
from decimal import Decimal as D
# Output: Decimal('3.3')
print(D('1.1') + D('2.2'))
# Output: Decimal('3.000')
print(D('1.2') * D('2.50'))
# ------------------------------------- |
6e84588e49e3cd9b087691296b572d11df4f3441 | NapsterInBlue/image_to_sprite | /spritify.py | 1,976 | 3.578125 | 4 | import cv2
import numpy as np
def mask_iterator(skip_n=20, take_n=10):
"""
Determines the filtering pattern of the image.
Infinately loops per skip_n, take_n, and generates
a 0/1 value, used to build a mask over an image
Parameters
----------
skip_n: int
How many sequential pixels are skipped
take_n: int
How many sequential pixels are taken
"""
while True:
for _ in range(skip_n):
yield 0
for _ in range(take_n):
yield 1
def generate_mask_array(arr_size, mask_iter):
"""
Iterate through the length of one dimension, per
the definition of mask_iter
Parameters
----------
arr_size: int
Length of whatever dimension you want to make a
mask for
mask_iter: infinite iterable of ints
Defined using `mask_iterator()`
"""
mask = []
for _, mask_val in zip(range(arr_size), mask_iter):
mask.append(mask_val)
return np.array(mask)
def im_to_sprite(im_fpath, skip_n=20, take_n=10, auto_size=False):
"""
Parameters
----------
skip_n: int
How many sequential pixels are skipped
take_n: int
How many sequential pixels are taken
"""
raw = cv2.imread(im_fpath)
raw = cv2.cvtColor(raw, cv2.COLOR_BGR2RGB)
raw_h, raw_w, _ = raw.shape
if auto_size:
max_dim = max(raw.shape[:2])
take_n = max_dim // 30
skip_n = take_n * 2
mask_iter_row = mask_iterator(skip_n, take_n)
mask_iter_col = mask_iterator(skip_n, take_n)
row_mask = generate_mask_array(raw_h, mask_iter_row)
col_mask = generate_mask_array(raw_w, mask_iter_col)
row_repeated = np.repeat(row_mask, repeats=raw_w).reshape(raw_h, raw_w)
col_repeated = np.repeat(col_mask, repeats=raw_h).reshape(raw_w, raw_h).T
final_mask = row_repeated & col_repeated
cols_activated = final_mask.sum(axis=1).max()
rows_activated = final_mask.sum(axis=0).max()
masked_raw = raw[final_mask.astype(bool)]
sprite = masked_raw.reshape(rows_activated, cols_activated, 3)
return sprite
|
9e358d7d1e2276e3ab12ab814aefb533d075c1ea | nucktwillieren/big_data_course | /20210303/ex5.py | 553 | 3.65625 | 4 |
def a_1():
n = int(input("Enter a integer number: "))
s = 0
for i in range(n):
three = i * 3
five = i * 5
if three > n: break
if i % 5 != 0: s += three
if five < n: s += five
print(s)
def a_2():
n = int(input("Enter a integer number: "))
threes = sum([i for i in range(0,n,3)])
fives = sum([i for i in range(0,n,5)])
overlapped = sum([i for i in range(0,n,15)])
print(threes + fives - overlapped)
if __name__ == "__main__":
a_1()
a_2() |
aee89a2e08d4d93ac06072f4af5488e7b4bbef0a | azrodriquez/MyPythonCourse | /CH04/num_list.py | 384 | 3.828125 | 4 | some_nums = [2,6,4,2,22,54,12,8,-1]
print(len(some_nums))
print("The sum of the list is: ", sum(some_nums))
print(some_nums[2])
hightest_num = some_nums[0]
for x in some_nums:
if x > hightest_num:
hightest_num = x
print("the highest number is: ", hightest_num)
for x in range(len(some_nums)-1):
print(x)
if (x%2==0):
some_nums[x] = 11
print(some_nums) |
bb5d16d4fe0e84e70729519c94574a6984afc475 | tainenko/Leetcode2019 | /leetcode/editor/en/[489]Robot Room Cleaner.py | 4,218 | 3.578125 | 4 | # You are controlling a robot that is located somewhere in a room. The room is
# modeled as an m x n binary grid where 0 represents a wall and 1 represents an
# empty slot.
#
# The robot starts at an unknown location in the room that is guaranteed to be
# empty, and you do not have access to the grid, but you can move the robot using
# the given API Robot.
#
# You are tasked to use the robot to clean the entire room (i.e., clean every
# empty cell in the room). The robot with the four given APIs can move forward,
# turn left, or turn right. Each turn is 90 degrees.
#
# When the robot tries to move into a wall cell, its bumper sensor detects the
# obstacle, and it stays on the current cell.
#
# Design an algorithm to clean the entire room using the following APIs:
#
#
# interface Robot {
# // returns true if next cell is open and robot moves into the cell.
# // returns false if next cell is obstacle and robot stays on the current
# cell.
# boolean move();
#
# // Robot will stay on the same cell after calling turnLeft/turnRight.
# // Each turn will be 90 degrees.
# void turnLeft();
# void turnRight();
#
# // Clean the current cell.
# void clean();
# }
#
#
# Note that the initial direction of the robot will be facing up. You can
# assume all four edges of the grid are all surrounded by a wall.
#
#
#
# Custom testing:
#
# The input is only given to initialize the room and the robot's position
# internally. You must solve this problem "blindfolded". In other words, you must
# control the robot using only the four mentioned APIs without knowing the room layout
# and the initial robot's position.
#
#
# Example 1:
#
#
# Input: room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,
# 0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
# Output: Robot cleaned all rooms.
# Explanation: All grids in the room are marked by either 0 or 1.
# 0 means the cell is blocked, while 1 means the cell is accessible.
# The robot initially starts at the position of row=1, col=3.
# From the top left corner, its position is one row below and three columns
# right.
#
#
# Example 2:
#
#
# Input: room = [[1]], row = 0, col = 0
# Output: Robot cleaned all rooms.
#
#
#
# Constraints:
#
#
# m == room.length
# n == room[i].length
# 1 <= m <= 100
# 1 <= n <= 200
# room[i][j] is either 0 or 1.
# 0 <= row < m
# 0 <= col < n
# room[row][col] == 1
# All the empty cells can be visited from the starting position.
#
#
# Related Topics Backtracking Interactive 👍 2594 👎 159
# leetcode submit region begin(Prohibit modification and deletion)
# """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
# class Robot:
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and robot stays in the current cell.
# :rtype bool
# """
#
# def turnLeft(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def turnRight(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def clean(self):
# """
# Clean the current cell.
# :rtype void
# """
class Solution:
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
visited = {(0, 0)}
def dfs(x, y, dx, dy):
robot.clean()
visited.add((x, y))
for _ in range(4):
if (x + dx, y + dy) not in visited and robot.move():
dfs(x + dx, y + dy, dx, dy)
robot.turnLeft()
dx, dy = -dy, dx
robot.turnLeft()
robot.turnLeft()
robot.move()
robot.turnLeft()
robot.turnLeft()
dfs(0, 0, 0, 1)
# leetcode submit region end(Prohibit modification and deletion)
|
59000cac11b0c80dceb43e6b817270d491b53f4e | machillef/Mastermind-Clone | /modules.py | 6,130 | 3.796875 | 4 | # -*- coding: utf-8 -* -
import pygame, sys, textrect
import os
from os.path import dirname, realpath, abspath
from pygame.locals import *
from pygame.sprite import *
pygame.init()
#constants, like screen size, and some colors
#screen
WIDTH = 800
HEIGHT = 600
display = pygame.display.set_mode((WIDTH,HEIGHT))
#colors
BLACK = (0,0,0)
lBLACK = (51,51,51)
#update global function
def update():
pygame.display.update()
#button super class.
class Button(pygame.Rect):
font = pygame.font.SysFont("monospace", 36)
def __init__(self, buttonText, heightOffset, buttonX, buttonY, buttonWidth, buttonHeight):
#we create the rectangle, and we center it accordingly to our WIDTH, HEIGHT, and offset.
Rect.__init__(self, buttonX, buttonY, buttonWidth, buttonHeight)
self.center = (WIDTH/2 , HEIGHT/2-heightOffset)
self.color = (255,255,0)
self.text = buttonText
def drawButton(self, color = (255,255,0)):
#the label is a surface object. via get_rect() we get its rectangle, so we can center the text.
label = self.font.render(self.text, 1, color)
buttonRect = label.get_rect()
#after we get the rectangle of the text, we use the coordinates of self, i.e our rect.
buttonRect.center = (self.centerx , self.centery)
pygame.draw.rect(display, BLACK, self )
display.blit(label, buttonRect)
def hover(self, color = (255,255,0) ):
if self.collidepoint(pygame.mouse.get_pos()):
self.drawButton((224,224,224))
return True
else:
self.drawButton(color)
return False
def clicked(self):
isClicked = pygame.mouse.get_pressed() #returns a tuple with the 3 elements.
if self.hover():
if isClicked[0] == 1: #we check if the left mouse click was pressed
return True
return False
class StartButton(Button):
def __init__(self, *args):
Button.__init__(self, *args)
def clicked(self):
isClicked = pygame.mouse.get_pressed() #returns a tuple with the 3 elements.
if self.hover():
if isClicked[0] == 1: #we check if the left mouse click was pressed
return True
class InstructionsButton(Button):
def __init__(self, *args):
super().__init__(*args)
class ExitButton(Button):
def __init__(self, *args):
super().__init__(*args)
def clicked(self):
isClicked = pygame.mouse.get_pressed() #returns a tuple with the 3 elements.
if self.hover():
if isClicked[0] == 1: #we check if the left mouse click was pressed
pygame.quit()
sys.exit()
class BackButton(Button):
def __init__(self, *args):
super().__init__(*args)
self.topleft = (WIDTH-self.width, HEIGHT-self.height) #align it to the bottom corner of the screen
def deleteButton(self):
display.fill(lBLACK, self)
class AboutButton(Button):
def __init__(self, *args):
super().__init__(*args)
self.topleft = (WIDTH-self.width, HEIGHT-self.height) #align it to the bottom corner of the screen
class CheckButton(Button):
def __init__(self, *args):
super().__init__(*args)
self.topleft = (WIDTH-self.width, HEIGHT-self.height) #align it to the bottom corner of the screen
def drawButton(self, color = (51,255,102)):
#the label is a surface object. via get_rect() we get its rectangle, so we can center the text.
label = self.font.render(self.text, 1, color)
buttonRect = label.get_rect()
#after we get the rectangle of the text, we use the coordinates of self, i.e our rect.
buttonRect.center = (self.centerx , self.centery)
pygame.draw.rect(display, BLACK, self )
display.blit(label, buttonRect)
def hover(self ):
if self.collidepoint(pygame.mouse.get_pos()):
self.drawButton((224,224,224))
return True
else:
self.drawButton((51,255,102))
return False
def clicked(self):
isClicked = pygame.mouse.get_pressed() #returns a tuple with the 3 elements.
if self.hover():
if isClicked[0] == 1: #we check if the left mouse click was pressed
return True
return False
#Peg super class
class Peg(Sprite):
def __init__(self, spriteX, spriteY, width=62, height=60):
Sprite.__init__(self)
self.rect = pygame.Rect(spriteX, spriteY, width, height)
def hover(self):
if self.rect.collidepoint(pygame.mouse.get_pos()):
return True
return False
def clicked(self):
clicks = pygame.mouse.get_pressed()
if self.rect.collidepoint(pygame.mouse.get_pos()):
if clicks[0] == 1:
#print("clicked")
return self
return None
def draw(self):
pass
#red peg
class RedPeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","redPeg.png"))
self.string = "red"
#orange peg
class OrangePeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","orangePeg.png"))
self.string = "orange"
#yellow peg
class YellowPeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","yellowPeg.png"))
self.string = "yellow"
#green peg
class GreenPeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","greenPeg.png"))
self.string = "green"
#blue peg
class BluePeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","bluePeg.png"))
self.string = "blue"
#purple peg
class PurplePeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","purplePeg.png"))
self.string = "purple"
#black peg
class BlackPeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","blackPeg.png"))
def draw(self, x, y): #draw the peg into the x,y cords
self.rect.x = x
self.rect.x = y
display.blit(self.image, (x,y))
#white peg
class WhitePeg(Peg):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.image.load(os.path.join("Recources","whitePeg.png"))
def draw(self, x, y): #draw the peg into the x,y cords
self.x = x
self.y = y
display.blit(self.image, (x,y))
|
9771797706bb2f19b0a4907c37bf94f312cb9ad9 | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | /students/AndrewMiotke/lesson02/assignment/src/charges_calc.py | 3,103 | 3.578125 | 4 | '''
Returns total price paid for individual rentals
'''
import argparse
import json
import datetime
import math
import logging
def parse_cmd_arguments():
""" Command line arguements to start the program """
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-i', '--input', help='input JSON file', required=True)
parser.add_argument('-o', '--output', help='ouput JSON file', required=True)
parser.add_argument('-d', '--debug', help='debug error messages', required=False)
return parser.parse_args()
def load_rentals_file(filename):
""" Load the source.json file """
with open(filename) as file:
try:
parsed_json = file.read()
parsed_json = parsed_json.replace(',,', ',')
data = json.loads(parsed_json)
except ValueError:
logging.error(ValueError)
exit(0)
return data
def calculate_additional_fields(data):
""" Calculates any other fields for json """
for value in data.values():
try:
rental_start = datetime.datetime.strptime(value["rental_start"], "%m/%d/%y")
except ValueError:
# add logging
logging.error(ValueError)
rental_end = datetime.datetime.strptime(value["rental_end"], "%m/%d/%y")
value["total_days"] = (rental_end - rental_start).days
value["total_price"] = value["total_days"] * value["price_per_day"]
value["unit_cost"] = value["total_price"] / value["units_rented"]
value["sqrt_total_price"] = math.sqrt(value["total_price"])
except ValueError:
logging.error(ValueError)
raise
return data
def save_to_json(filename, data):
""" Saves the filename with new data to json """
with open(filename, 'w') as file:
json.dump(data, file)
def debug_levels(level=0):
LOG_FILE = datetime.datetime.now().strftime("%Y-%m-%d")+'.log'
logger = logging.getLogger()
logger.setLevel(logging.NOTSET)
LOG_FORMAT = "%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s"
FORMATTER = logging.Formatter(LOG_FORMAT)
FILE_HANDLER = logging.FileHandler(LOG_FILE)
FILE_HANDLER.setFormatter(FORMATTER)
STREAM_HANDLER = logging.StreamHandler(LOG_FILE)
STREAM_HANDLER.setFormatter(FORMATTER)
if level == "3":
FILE_HANDLER.setLevel(logging.WARNING)
STREAM_HANDLER.setLevel(logging.DEBUG)
elif level == "2":
FILE_HANDLER.setLevel(logging.WARNING)
STREAM_HANDLER.setLevel(logging.WARNING)
elif level == "1":
FILE_HANDLER.setLevel(logging.ERROR)
STREAM_HANDLER.setLevel(logging.ERROR)
else:
FILE_HANDLER.setLevel(logging.NOTSET)
STREAM_HANDLER.setLevel(logging.NOTSET)
logger.addHandler(FILE_HANDLER)
logger.addHandler(STREAM_HANDLER)
if __name__ == "__main__":
args = parse_cmd_arguments()
debug_levels(args.debug)
data = load_rentals_file(args.input)
data = calculate_additional_fields(data)
save_to_json(args.output, data)
|
e5af6c784289ec95cc90a298574e6871a7692402 | matheus-nbx52/Python | /matriz.py | 548 | 3.8125 | 4 | from random import randint
print(randint(1, 9))
coluna = []
matriz = []
linhas = int(input('Informe a quantidade de linhas: '))
colunas = int(input('Informe a quantidade de colunas: '))
i = 0
while i <= colunas:
numero = randint(1, 9)
coluna.append(numero)
i += 1
if i == colunas:
matriz.append(coluna)
coluna = []
i = 0
if len(matriz) == linhas:
break
i = 0
print(f'impressão da matriz {linhas}x{colunas}:')
while i < linhas:
print(matriz[i])
i += 1 |
db207090f5c4ab6d4de2a18fd9b31f8346b54537 | pluzun/supinfo_1ads_labs_2018 | /3.1.2.py | 246 | 3.75 | 4 | def syracuse(a, n):
if n == 0:
return a
print(int(a))
if a % 2 == 0:
return syracuse(a/2, n-1)
else:
return syracuse(a*3+1, n-1)
a = int(input("a : "))
n = int(input("n : "))
print(int(syracuse(a, n-1)))
|
6debe26429e591d54910e5126c590b02d07e9c9b | beloplv/practicasUnoDosTres | /p2e1.py | 366 | 3.515625 | 4 | tam = ['im1 4,14', 'im2 33,15', 'im3 6,34', 'im4 410,134']
lista1=[]
lista2=[]
num = int(input('ingrese un numero '))
for i in tam:
im,space,tupla = i.partition(' ')
aux = (int(tupla.split(',')[0]), int(tupla.split(',')[1]))
if num >= aux[0]:
lista1.extend([im,tupla])
else:
lista2.extend([im,tupla])
print(lista1)
print(lista2)
|
1bcf87651c1eded053d78631a5a174d507839689 | elainekamlley/python_scripts | /while_loop/chips_eating.py | 612 | 4.1875 | 4 | #chips_eating.py
#Section 1: Set out current values
chips_in_bag = 30
print "There are "+ str(chips_in_bag)+ " chips in the bag."
#Section 2: Inside a while loop, ask the user how many chips they want to eat until the bag is gone.
#Ask the user how many chips they want to eat a time, until the bag is gone. When the
#bag is empty, print "The bag is empty!"
while chips_in_bag > 0:
chips_ate = input("How many chips do you want to eat?: ")
chips_in_bag = chips_in_bag - chips_ate
print "\n (Munching Sounds) \n"
print "There are "+ str(chips_in_bag)+ " chips in the bag."
print "The bag is empty. sad." |
e098b4f8579fbf197ea0e04e37fc773f17247fb7 | garcheuy/python-challenge | /PyBank/main.py | 3,237 | 3.75 | 4 | import os
import csv
file_list = []
x = 0
for file in os.listdir("raw_data"):
if file.endswith(".csv"):
file_list.insert(x, os.path.join(file))
x += x
file_list.sort()
for file_name in file_list:
print("[" + str(file_list.index(file_name)) + "] " + file_name)
# ask user as to which of the two files to open for analysis
selection = int(input("Which file do you want to open? "))
csvpath = ('raw_data/' + file_list[selection])
# for verifications
# with open(csvpath, newline = "") as csvfile:
# csvreader = csv.reader(csvfile, delimiter = ",")
# for row in csvreader:
# print(row)
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
next(csvreader) # skip header row
total_month = sum(1 for row in csvreader)
total_revenue = 0
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
for row in csvreader:
monthly_revenue = row[1]
try:
monthly_revenue = int(monthly_revenue)
except ValueError:
monthly_revenue = 0
total_revenue = total_revenue + monthly_revenue
average_revenue_change = total_revenue / total_month
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
next(csvreader) # skip header row
max_increase = max(int(column[1].replace(',', '')) for column in csvreader)
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
for index, row in enumerate(csvreader):
if row[1] == str(max_increase):
max_increase_month = row[0]
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
next(csvreader) # skip header row
max_decrease = min(int(column[1].replace(',', '')) for column in csvreader)
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
for index, row in enumerate(csvreader):
if row[1] == str(max_decrease):
max_decrease_month = row[0]
print()
print("Financial Analysis")
print()
print("--------------------------")
print()
print("Total Months: " + str(total_month))
print()
print("Total Revenue: $" + str(total_revenue))
print()
print("Average Revenue Change: $" + str(int(average_revenue_change)))
print()
print("Greatest Increase in Revenue: " + max_increase_month + " ($" + str(max_increase) + ")")
print()
print("Greatest Decrease in Revenue: " + max_decrease_month + " ($" + str(max_decrease) + ")")
print()
# export to text file
file = open("report.txt", "w")
file.write("Financial Analysis\n")
file.write("\n")
file.write("--------------------------\n")
file.write("\n")
file.write("Total Months: " + str(total_month) + "\n")
file.write("\n")
file.write("Total Revenue: $" + str(total_revenue) + "\n")
file.write("\n")
file.write("Average Revenue Change: $" + str(int(average_revenue_change)) + "\n")
file.write("\n")
file.write("Greatest Increase in Revenue: " + max_increase_month + " ($" + str(max_increase) + ")\n")
file.write("\n")
file.write("Greatest Decrease in Revenue: " + max_decrease_month + " ($" + str(max_decrease) + ")\n")
file.close() |
0fdc8b41c64aa6773979362f6ba06ade122592b0 | aakash2602/InterviewBit | /xor_trie/xor_key_trie.py | 5,347 | 3.65625 | 4 | import collections
# import time
class Node:
def __init__(self):
self.left_child = None # corresponds to bit 0
self.right_child = None # corresponds to bit 1
self.terminus = False
self.bit_index = {}
self.word = ""
def add(self, child_node, bit, bit_index):
if bit == '0':
self.left_child = child_node
self.left_child.bit_index[bit_index] = 1
elif bit == '1':
self.right_child = child_node
self.right_child.bit_index[bit_index] = 1
def update_terminus(self, status):
self.terminus = status
def print_node(self):
print(self.bit_index)
print(self.terminus)
print(self.left_child)
print(self.right_child)
print(self.word)
class Trie:
def __init__(self):
self.head = Node()
# print (self.head.bit_index)
# print ("head created")
def insert(self, num, index):
word = '{0:016b}'.format(num)
root = self.head
for i in range(len(word)):
# print (root.bit_index)
# print (i)
if self.has_node(root, word[i]):
root = root.left_child if word[i] == '0' else root.right_child
root.bit_index[index] = 1
else:
child_node = Node()
root.add(child_node, word[i], index)
# root.print_node()
root = root.left_child if word[i] == '0' else root.right_child
# root.print_node()
if i == len(word) - 1:
# print (" inside terminus array")
root.update_terminus(True)
root.word = word
# root.print_node()
def has_node(self, node, bit):
if node == None:
return False
if bit == '0':
return True if node.left_child != None else False
elif bit == '1':
return True if node.right_child != None else False
def print_graph(self):
root = self.head
queue = collections.deque()
queue.append(root)
while len(queue) > 0:
node = queue.popleft()
print(node.bit_index)
if node.terminus == True:
print("word is: " + node.word)
if node.left_child != None:
queue.append(node.left_child)
if node.right_child != None:
queue.append(node.right_child)
def find_max_xor_old(self, num):
word = '{0:016b}'.format(num)
root = self.head
optimal_num = -1
for i in range(len(word)):
if word[i] == '0':
root = root.right_child if root.right_child != None else root.left_child
elif word[i] == '1':
root = root.left_child if root.left_child != None else root.right_child
if root.terminus == True:
optimal_num = int(root.word, 2)
break
return optimal_num
def find_max_xor(self, num, start, end):
word = '{0:016b}'.format(num)
root = self.head
optimal_num = -1
for i in range(len(word)):
# print (i)
if word[i] == '0':
if root.right_child != None:
mode = 0
for k in range(start, end):
if k in root.right_child.bit_index:
root = root.right_child
mode = 1
break
if mode == 0:
root = root.left_child
else:
root = root.left_child
# root = root.right_child if root.right_child != None else root.left_child
elif word[i] == '1':
if root.left_child != None:
mode = 0
for k in range(start, end):
if k in root.left_child.bit_index:
root = root.left_child
mode = 1
break
if mode == 0:
root = root.right_child
else:
root = root.right_child
# root = root.left_child if root.left_child != None else root.right_child
if root.terminus == True:
optimal_num = int(root.word, 2)
break
return optimal_num
# millis=int(round(time.time()*1000))
t = int(input().strip())
for test_cases in range(t):
n, m = input().strip().split(" ")
n, m = [int(n), int(m)]
nums = input().strip().split(" ")
nums = [int(num) for num in nums]
t = Trie()
# insert_arr = list(set(nums[x - 1:y]))
for j in range(len(nums)):
t.insert(nums[j], j)
# t.print_graph()
for i in range(m):
a, x, y = input().strip().split()
a, x, y = [int(a), int(x), int(y)]
max_num = t.find_max_xor(a, x-1, y)
# print (max_num)
# t = Trie()
# nums_new = nums[x-1:y]
# for j in range(len(nums_new)):
# t.insert(nums[j], j)
# max_num = t.find_max_xor_old(a)
print(a ^ max_num)
# millis1=int(round(time.time()*1000))
# print("timetakenforinternalparse:"+str(millis1-millis)+"ms") |
d66a3b94b3997bb33fec801ea1b0d88aa7fa6e8d | vondirath/functions | /quicksort.py | 584 | 4.125 | 4 | def quicksort(thisarray):
"""
A python Quicksort with recursion
"""
less = []
equal = []
greater = []
if len(thisarray) > 1:
pivot = thisarray[0]
for item in thisarray:
if item < pivot:
less.append(item)
if item == pivot:
equal.append(item)
if item > pivot:
greater.append(item)
return quicksort(less) + equal + quicksort(greater)
else:
return thisarray
thisarray = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(thisarray)
|
9e055c47be1762ca5fff0313b91996cd827dd5cd | Renmy/MyRepo | /fileSearcher/dbConnection.py | 828 | 4 | 4 | import sqlite3
class db_Connection:
def __init__(self, dbname):
"""Initialize db class variables"""
self.connection = sqlite3.connect(dbname)
self.cur = self.connection.cursor()
def close(self):
"""close sqlite3 connection"""
self.connection.close()
def execute(self, sql):
"""execute a row of data to current cursor"""
self.cur.execute(sql)
def executemany(self, sql, values):
"""execute a row of data to current cursor"""
self.cur.execute(sql, values)
def create_table(self):
"""create a database table if it does not exist already"""
self.cur.execute('''CREATE TABLE IF NOT EXISTS ARCHIVOS''')
def commit(self):
"""commit changes to database"""
self.connection.commit() |
c14e9d328f0ce405b0ad69fa35af5cd2f2fa7fa8 | apisqa/Group_2 | /Lessons/July_15/test.py | 316 | 4.03125 | 4 | """Word-revert the string"""
s = raw_input('\nEnter the string to revert:\n')
temp = ''
result = ''
for i in range(1, len(s) + 1):
temp2 = s[len(s) - i]
if temp2 != ' ':
temp = temp2 + temp
else:
result += temp + ' '
temp = ''
result += temp
print('Final string is:\n%s' % result) |
15c0a536f5bc62c937da2b8a94a28840c789edce | taisei-d/python-training | /break文.py | 254 | 3.921875 | 4 | kens = ["Tottori","Shimane","END","Hiroshima","Okayama","Yamaguchi"]
for ken in kens:
if ken == "END":
print("Break LOOP")
break
print(ken)
else:
print("End LOOP")
for ken in kens:
print(ken)
else:
print("End LOOP")
|
24c55abf940d267c3b93e82663a1165bf75e11ca | Ferveloper/python-exercises | /KC_EJ05.py | 187 | 3.875 | 4 | #-*- coding: utf-8 -*-
month1 = raw_input('Mes 1: ')
year1 = raw_input('Año 1: ')
month2 = raw_input('Mes 2: ')
year2 = raw_input('Año 2: ')
print(month1 == month2 and year1 == year2) |
06638c3a7b3ca9a4ba510bd9b4aba68144e830f9 | Spuntininki/Aulas-Python-Guanabara | /ex0062.py | 799 | 3.640625 | 4 | #Progressão aritimetica 2.0
n1 = int(input('Digite o primeiro termo da progressão: '))
raz = int(input('Digite a razão da PA: '))
soma = n1 + raz
print('{}'.format(n1), end=' ')
c = 1
d = 10
decision = ''
while c != d:
print('{}'.format(soma), end=' ')
soma = soma + raz
c += 1
if c == d:
print('')
n1 = int(input('Insira quantos termos gostaria de ver a mais: '))
d = d + n1
print('Obrigado pela preferencia!')
'''if c == d:
print(' ')
decision = str(input('Deseja continuar? Y/N ')).upper()
if decision == 'Y':
n1 = int(input('Digite Quantos termos gostaria de ver a mais: '))
d = d + n1
if n1 == 0:
c = d
elif decision == 'N':
print('Obrigado pela preferencia.')
else:
print('\033[1;31mOpção invalida, o programa irá se encerrar.\033[m')''' |
bb699b9c8bd49ad7d5eea9a78c2c3509e6c2c05a | SergeiEroshkin/python_basics | /functions/sort_list.py | 542 | 3.84375 | 4 | def find_smallest(lst):
# Store smallest value
smallest = lst[0]
# Store smallest index
smallest_idx = 0
for index in range(1, len(lst)):
if lst[index] < smallest:
smallest = lst[index]
smallest_idx = index
return smallest_idx
def get_sorted(lst):
sorted_list = []
for item in range(len(lst)):
smallest = find_smallest(lst)
sorted_list.append(lst.pop(smallest))
return sorted_list
a = [9, 90, 100, 1, 3, 2, 7]
print find_smallest(a)
print get_sorted(a)
|
72109201a44c51b1ca168d5ea0da97fcf3143c06 | StellaNguyen68/Fundamental-in-Python | /Python basic.py | 1,258 | 3.71875 | 4 | a=29.11
print(a)
print(type(a))
#take decimal from libraby
from decimal import*
getcontext().prec=3 #take max 30 number behind ,
print(Decimal(10)/Decimal(3))
print(type(Decimal(10)/Decimal(3)))
#Fraction
from fractions import*
frac=Fraction(6,9)
print(frac)
print(type(frac))
print(frac+2/3)
#Complex
c=complex(2,5)
print(c.real)
print(c.imag)
print(10/3)
print(10//3)
print(10%3) #10/3 = 3*3+"1"
print(10**3) #10^3
#String
a = '''stella'''
print(a)
b=a.capitalize() #capitalize the first letter of string
b=a.upper() #capitalize all letters of string
b=a.lower()
b=a.swapcase() #switch from capitalizing to
b=a.title()
b=a.center(5)
print(b)
print(a+"\n"+b)
c=a*5
print(c)
strA = "Nguyen"
strB="Stella"
strC = strB in strA # check if strB is included in strA => FALSE
print(strC)
#refer an object in string
print(strA[-1]) #refer 3rd element in strA, string index should not be out of range,
print(strA[len(strA)-1]) # refer the last element in strA
print(strA[1:len(strA)])
print(strA[1:None])
print(strA[None:None])
print(strA[None:None:2])
strD= strA[None:1] + "0" +strA[2:None]
print(strD)
from time import sleep
your_name = "Stella"
greeting="Hello! My name is "
for c in greeting+your_name:
print(c,end="",flush=True)
sleep(0.05)
print() |
52ec24bac243e57b2f24d55dac6d40e6f158c5e8 | Armando8766/Modified-8Puzzle-AI | /8Puzzle.py | 11,667 | 4.0625 | 4 | import time as t
print('Hey buddy! Hope you are having a great time! Are you in the mood to play some 8-Puzzle? :)\nYes??!\nWonderful!\nLets go then!\n')
print('Choose one of the following options for the difficulty level of the puzzle:')
print('1) EASY Mode\n2) MEDIUM Mode\n3) HARD Mode')
option = input()
if option == '1':
print('Really?! Easy?! Don`t you like a little bit of challenge?? Okay then!' )
s = [1,3,4,8,6,2,7,0,5]
elif option == '2':
print('Not too hard and not too easy? It seems you had a really long day :D Okay, go ahead!')
s = [2,8,1,0,4,3,7,6,5]
elif option == '3':
print('Now we`re talking! Your computer is going to be crushed by this puzzle!')
s = [5,6,7,4,0,8,3,2,1]
print('\nNow choose one of the following methods to solve the puzzle:')
print('1) Breadth First Search\n2) Depth First Search\n3) Greedy Best First Search\n4) Uniform Cost Search\n5) Iterative Deepening Search\n6) A* Search')
option = input()
if option == '1':
search_algorithm = 'bfs'
iterative_deep = False
h_function = 'default'
elif option == '2':
search_algorithm = 'dfs'
iterative_deep = False
h_function = 'default'
elif option == '3':
search_algorithm = 'gbfs'
iterative_deep = False
h_function = 'default'
elif option == '4':
search_algorithm = 'ucs'
iterative_deep = False
h_function = 'default'
elif option == '5':
search_algorithm = 'ids'
iterative_deep = True
h_function = 'default'
elif option == '6':
search_algorithm = 'astar'
iterative_deep = False
print('Cool! Which heuristics do you want to use for A*?')
print('\n1) Number of Misplaced Tiles\n2) Manhattan Distance\n3) Euclidean Distance')
answer = input()
if answer == '1':
h_function = 'misplacedTiles'
elif answer == '2':
h_function = 'Manhattan'
elif answer == '3':
h_function = 'Euclidean'
else:
print('Wrong number! Press 1, 2 or 3...')
else:
print('Wroooooong! Wake up! The available options are 1, 2, 3, 4, 5, and 6...')
goal = [1,2,3,8,0,4,7,6,5]
class Thing:
def HeuristicCost(state, goal, function):
heuristic_cost = 0
# the number of puzzle pieces out of place
if function == 'misplacedTiles':
for i in zip(state, goal):
if i[0] != i[1]:
heuristic_cost += 1
else:
continue
# manhattan distance of the puzzle pieces to their goal state
elif function == 'Manhattan':
for i in goal:
heuristic_cost += abs(goal.index(i) - state.index(i))
# euclidean distance of the puzzle pieces to their goal state
elif function == 'Euclidean':
for i in goal:
heuristic_cost += (goal.index(i) - state.index(i))**2
elif function == 'default':
heuristic_cost = 0
return heuristic_cost
def __init__(self, key, state, parent, g_n, depth, h_function, goal, move):
self.key = key
self.state = state
self.parent = parent
self.g_n = g_n
self.depth = depth
self.h_function = h_function
self.goal = goal
self.move = move
self.h_n = Thing.HeuristicCost(self.state , self.goal , self.h_function)
self.total_cost = self.g_n + self.h_n
self.get_moves()
def get_moves(self):
self.moves = []
# possible moves
if self.state.index(0) == 0 : self.moves.extend(('left','up'))
elif self.state.index(0) == 1: self.moves.extend(('left','right','up'))
elif self.state.index(0) == 2: self.moves.extend(('right','up'))
elif self.state.index(0) == 3: self.moves.extend(('up','down', 'left'))
elif self.state.index(0) == 4: self.moves.extend(('up','down','left','right',))
elif self.state.index(0) == 5: self.moves.extend(('right','up', 'down'))
elif self.state.index(0) == 6: self.moves.extend(('down','left'))
elif self.state.index(0) == 7: self.moves.extend(('left','right', 'down'))
else: self.moves.extend(('right','down'))
def move_piece(self, move):
new_node = self.state[:]
zero_idx = new_node.index(0)
if move == 'left': rep_idx = zero_idx + 1
elif move == 'right': rep_idx = zero_idx - 1
elif move == 'up': rep_idx = zero_idx + 3
else: rep_idx = zero_idx - 3
# rep_val also represents the cost since it's the value of the piece being moved
rep_val = self.state[rep_idx]
new_node[zero_idx] = rep_val
new_node[rep_idx] = 0
return new_node , rep_val
class queue:
def __init__(self, search_algorithm, goal_state):
self.search_algorithm = search_algorithm
self.queue = []
def return_node(self):
if self.search_algorithm == 'bfs': return self.queue[0] # FIFO
elif self.search_algorithm == 'dfs': return self.queue[-1] # LIFO
elif self.search_algorithm == 'ucs': return sorted(self.queue, key=lambda x: x.g_n)[0] # return node with the lowest cost, g(n)
elif self.search_algorithm == 'astar': return sorted(self.queue, key=lambda x: x.total_cost)[0] # return node with the lowest total cost
elif self.search_algorithm == 'gbfs': return sorted(self.queue, key=lambda x: x.h_n)[0] # return node with the lowest heuristic cost, h(n)
elif self.search_algorithm == 'ids': return sorted(self.queue, key=lambda x: x.depth)[0]
class PuzzleSolver:
def __init__(self, node_init, goal_state, search_algorithm, iterative_deep):
self.goal_state = node_init.goal
self.current_node = node_init
self.root = node_init
self.search_algorithm = search_algorithm
self.heuristic_function = node_init.h_function
self.iterative_deep = iterative_deep
self.key = 0
self.move_counter = 0
self.tree = {}
self.queue = queue(self.search_algorithm, self.goal_state)
self.queue.queue.append(self.root)
self.visited_states = []
self.depth_counter = 0
self.limit = 0
self.tree[0] = self.root
self.solver()
def solver(self):
start_time = t.time()
self.current_node = self.queue.return_node()
while self.queue:
# used to find the maximum length of the queue at the end
que_len = []
que_len.append(len(self.queue.queue))
# check for goal convergence
if self.current_node.state != self.goal_state:
if self.iterative_deep:
if self.depth_counter > self.limit:
self.limit += 1
self.key = 0
self.move_counter = 0
self.tree = {}
self.queue = queue(self.search_algorithm, self.goal_state)
self.queue.queue.append(self.root)
self.visited_states = []
self.depth_counter = 0
self.current_node = self.root
else: pass
else: pass
# repeated state checking
if self.current_node.state not in self.visited_states:
self.visited_states.append(self.current_node.state[:])
self.move_counter+=1
# for the current node, begin looping through possible nodes so we can make new nodes in the tree, we use the
# move piece method to iteratively return new states and the cost of the move
for move in self.current_node.moves:
self.key += 1
new_state , g_n = self.current_node.move_piece(move)
g_n += self.current_node.g_n
new_node = Thing(key=self.key,state=new_state,parent=self.current_node.key,g_n = g_n,depth=self.depth_counter+1,\
h_function=self.heuristic_function,goal=self.goal_state,move=move)
self.tree[self.key] = new_node
# for searches that sort on cost, we have to search the queue to see if the states exists in the queue, if so
# we have to check and see if the cost of these existing nodes is more, if it isn't we leave the node in the queue
if self.search_algorithm in ['ucs', 'astar', 'gbfs']:
c = 0
if self.search_algorithm == 'ucs': sort = 'g_n'
elif self.search_algorithm == 'astar': sort = 'total_cost'
else: sort = 'h_n'
for i in self.queue.queue:
if i.state == new_node.state:
if getattr(i,sort) > getattr(new_node,sort):
del self.queue.queue[c]
else: c+=1
else: c += 1
else: pass
self.queue.queue.append(new_node)
self.depth_counter+=1
self.current_node = self.queue.return_node()
else:
if self.search_algorithm == 'dfs': idx = -1
else: idx = 0
# if we need to sort the queue we do, so we delete the proper node from the queue///// in the case of uniform cost,
# we sort by cost, best first we sort by heuristic cost and A* we sort by total cost
if self.search_algorithm == 'ucs': self.queue.queue = sorted(self.queue.queue, key=lambda x: x.g_n)
elif self.search_algorithm == 'gbfs': self.queue.queue = sorted(self.queue.queue, key=lambda x: x.h_n)
elif self.search_algorithm == 'astar': self.queue.queue = sorted(self.queue.queue, key=lambda x: x.total_cost)
else: pass
# we now delete an item from the queue based on the index defined above
del self.queue.queue[idx]
self.current_node = self.queue.return_node()
else:
# the puzzle has been solved so we can break the while loop
break
end_time = t.time()
for i,j in self.tree.items():
if j.state == self.goal_state:
out = i
break
else: continue
# this will loop through the tree and find the path until we reach the root node
# items are added in reverse order so we can print the path
path = [out]
while out != 0:
path.insert(0, self.tree[out].parent)
out = path[0]
for i in path:
print ('Move:', self.tree[i].move, '\n', 'Heuristic Cost:', self.tree[i].h_n, '\n', 'Total Cost:',self.tree[i].g_n,\
'\n', self.tree[i].state[0:3], '\n', self.tree[i].state[3:6], '\n', self.tree[ i].state[6:], '\n')
print ('Total Moves: ', len(path) - 1) # don't include the initial state as a move
print ('Output:', '\n', 'Maximum Queue Length:', max(que_len), '\n', 'Nodes Popped:', self.move_counter, '\n',\
'Time:', end_time - start_time)
Output = Thing(key=0,state=s,parent=0,g_n=0,depth=0,h_function=h_function,goal=goal,move='Initial State')
Run = PuzzleSolver(Output,goal_state=goal,search_algorithm=search_algorithm,iterative_deep=False)
|
0a737180df692377b18f863998d8e963841dc742 | innovatorved/python-recall | /py29 - decorators.py | 371 | 3.65625 | 4 | # Decorators
# """
def fun1(fun):
def fun2():
print("I am")
fun()
print("Ved Prakash Gupta")
def fun5():
fun()
return fun2
def fun3():
print("Good Boy")
# fun3()
fun3 = fun1(fun3)
fun3()
# """
# easiest way to do this @fun1 before fun3 function
@fun1
def fun4():
print("Good Boy fun4")
fun4()
|
b61fafebdfb93c0bc605f42409b43a18263749a1 | flo62134/hyperskill_python_tic_tac_toe | /Problems/A list of words/task.py | 356 | 4 | 4 | # work with the preset variable `words`
def start_with_letter(word: str, letter: str):
first_letter = word[0]
starts_with_letter = first_letter.upper() == letter.upper()
if starts_with_letter:
return True
else:
return False
starting_with_a = [word for word in words if start_with_letter(word, 'A')]
print(starting_with_a)
|
414651c1f32098240ffe3a7fb5bee038b5b9ea38 | shcherbinaap/new_rep_for_hw | /Lesson_3/task 1.py | 826 | 4 | 4 | #1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
from sys import exit
def inp_num(a):
while True:
num = input(f"Введите число {a} или 'q' для выхода: ")
if num.lower() == "q": exit()
try:
return float(num)
except ValueError:
print("Введено не число!")
def my_fun(num_1, num_2):
try:
return num_1 / num_2
except ZeroDivisionError:
print("Деление на 0!!!")
exit()
print(my_fun(inp_num(1), inp_num(2)))
|
ce027990e71a057b28a02f3dde1f0ddae260705c | mocmeo/algorithms | /Q2.py | 141 | 3.828125 | 4 | def sumOfThree(num):
if (num - 3) % 3 != 0:
return []
x = (num - 3) / 3
return [x, x+1,x+2]
print(sumOfThree(33))
print(sumOfThree(0)) |
9d30dada7480e710f0b76cfb69b438de55afb790 | LarisaOvchinnikova/Python | /Loops/loop.py | 1,829 | 3.734375 | 4 | # ----------------------------for ------------------------
colors = ["red", "green", "blue"]
for elem in colors:
print(elem)
elem = elem.capitalize()
print(f"I like {elem}")
for i in range(len(colors)):
print(i)
print(colors[i])
if i == 1:
colors[i] = "white"
# ----------------------
nums = [10, 20, 5]
sum = 0
for el in nums:
sum += el
print(sum)
# ----------------------
# 1, 2, 3, 4...
# x = list(range(10))
for num in range(10):
print(num)
# ===================
for num in range(5, 20, 2):
print(num)
# ============
sum = 0
for i in range(15):
if i % 3 == 0:
print(i)
sum += i
print(sum)
# -----------------
sum = 0
nums = [6, 4, 3, 0 -1, -5, -10]
for i in nums:
if i > 0:
sum += i
else:
break
print(sum)
for i in range(20, 10, -2):
print(i)
print('---------------------')
# ---------------------------------------while----------
i = 0
while i < 5:
print(i)
i += 1
# ---------------
i = 0
while True:
print("Hello")
i += 1
if i > 5:
break
# ----------------
# while True:
# name = input("What is your name?")
# print("Hello " + name)
# if name == "q":
# break
# ----------------
#while True:
# degrees = input("enter degrees in F")
# if not degrees.isdigit():
# break
# else:
# c = (int(degrees) - 32) * 5 / 9
# print(c)
# ------------------
n = 2
power = 0
value = n
while value < 1000:
power += 1
value *= n
print(power, value)
# ------------------
n = 50
nums = [10, 4, 23, 6, 18, 27, 47]
# n1 + n2 === n? first pair those sum = 50
for el in nums:
if (n - el) in nums:
print(el, n - el)
break
# -----------------continue---------------------------
for i in range(10):
if i % 2 != 0:
continue
print(i)
|
8f3a90b39415f6288fc5c94a3a444690d8eefcb5 | ajaypraj/gittest | /operator_loading.py | 314 | 3.734375 | 4 | class Book:
def __init__(self,pages):
self.pages=pages
def __str__(self):
return str(self.pages)
def __add__(self,other):
total=self.pages+other.pages
b=Book(total)
return b
b1=Book(100)
b2=Book(200)
b3=Book(200)
print(b1+b2)
print(b2+b3)
print(b1+b2+b3) |
6260d81976829427907cce2c0f81f3ef5fb27dbe | gsudarshan1990/PythonSampleProjects | /Python/InputWithCommandLineArguments.py | 481 | 3.734375 | 4 | from sys import argv
script, user_name=argv
prompt='>'
print('The name of the this file is {} and your name is {}'.format(script,user_name))
print ('Answer the following question')
print('Do you like me {}'.format(user_name))
like=input(prompt)
print('where do you live {}'.format(user_name))
live=input(prompt)
print('what kind of computer you have?')
computer=input(prompt)
print('So you {} {}, you live at {}, and you have {} computer'.format(like,user_name,live,computer))
|
d42faed66c7045fdbb749092ebf3459b6bc21476 | lukeaparker/super-hero-team-dueler- | /superhero.py | 7,455 | 3.703125 | 4 | import random
import superhero
class Ability:
def __init__(self, name, attack_strength):
self.name = name
self.max_damage = attack_strength
def attack(self):
''' Return a value between 0 and the
value set by self.max_damage.'''
return random.randint(0, self.max_damage)
class Armor:
def __init__(self, name, max_block):
self.name = name
self.max_block = max_block
def block(self):
''' Return a value between 0 and the
value set by self.max_damage.'''
return random.randint(0, self.max_block)
class Hero():
def __init__(self, name, starting_health=100):
self.name = name
self.starting_health = starting_health
self.current_health = starting_health
self.abilities = list()
self.armors = list()
self.deaths = 0
self.kills = 0
def add_ability(self, ability):
self.abilities.append(ability)
def add_weapons(self, weapon):
self.abilities.append(weapon)
def attack(self):
'''Calculate the total damage from all ability attacks.
return: total:Int
'''
damage_val = 0
for ability in self.abilities:
attack = ability.attack() + damage_val
damage_val = attack
return damage_val
def add_armor(self, armor):
'''Add armor to self.armors
Armor: Armor Object
'''
self.armors.append(armor)
def defend(self):
defense_val = 0
for armor in self.armors:
blocked = armor.block() + defense_val
defense_val = blocked
return defense_val
def take_damage(self, damage):
defend = self.defend()
if damage - defend > 0:
dmg_amount = damage - defend
else:
dmg_amount = 0
self.current_health = self.current_health - dmg_amount
return self.current_health
def is_alive(self):
if self.current_health <= 0:
return False
else:
return True
def add_kills(self):
self.kills += 1
def add_deaths(self):
self.deaths += 1
def fight(self, opponent):
self_alive = True
opp_alive = True
draw = False
while self_alive == True and opp_alive == True:
self_alive = self.is_alive()
opp_alive = opponent.is_alive()
if self.abilities == [] and opponent.abilities == []:
print(f"You have run out of abilities")
return draw == True
opponent.take_damage(self.attack())
opp_alive = opponent.is_alive()
self.take_damage(opponent.attack())
self_alive = self.is_alive()
if self_alive == True and opp_alive == False:
print(self.name, "has won")
self.add_kills()
opponent.add_deaths()
elif self_alive == False and opp_alive == True:
print(opponent.name, "has won")
opponent.add_kills()
self.add_deaths()
elif self_alive == False and opp_alive == False:
print("Both dead")
class Weapon(Ability):
def attack(self):
return random.randint(self.max_damage//2, self.max_damage)
class Team():
def __init__(self, name):
self.name = name
self.heros = []
def remove_hero(self, name):
if name in self.heros:
return self.heros.remove(name)
else:
return 0
def view_all_heros(self):
for hero in self.heros:
print(hero.name)
def add_hero(self, hero):
self.hero = hero
self.heros.append(hero)
def attack(self, other_team):
self.self_hero = random.choice(self.heros)
self.opp_hero = random.choice(other_team.heros)
Hero.fight(self.self_hero, self.opp_hero)
def revive_heroes(self, health=100):
current_health = health
def stats(self):
for hero in self.heros:
print(f"Kills: {hero.kills} Deaths: {hero.deaths} k / d : {hero.kills} / {hero.deaths}")
class Arena:
def __init__(self):
self.team_one = []
self.team_two = []
def create_ability(self):
'''Prompt for Ability information.
return Ability with values from user Input
'''
ability = Ability(input("Name ability? "), int(input("Strength value?")))
return ability
def create_weapon(self):
weapon = Weapon(input("Name weapon? "), int(input("Strength value?")))
return weapon
def create_armor(self):
armor = Armor(input("Name armor? "), int(input("Strength value?")))
return armor
def create_hero(self):
hero = Hero(input("Name Hero? "))
number = int(input("How many abilities?"))
for i in range(number):
ability = self.create_ability()
hero.add_ability(ability)
number = int(input("How many weapons?"))
for i in range(number):
weapon = self.create_weapon()
hero.add_ability(weapon)
number = int(input("How much armor?"))
for i in range(number):
armor = self.create_armor()
hero.add_armor(armor)
return hero
def build_team_one(self):
self.team_one = Team(input("Team name?"))
number = int(input("How many heros do you want?"))
for i in range(number):
hero = self.create_hero()
self.team_one.add_hero(hero)
return self.team_one
def build_team_two(self):
self.team_two = Team(input("Team name?"))
number = int(input("How many heros do you want?"))
for i in range(number):
hero = self.create_hero()
self.team_two.add_hero(hero)
return self.team_two
def team_battle(self):
self.team_one = self.build_team_one()
self.team_two = self.build_team_two()
return self.team_one.attack(self.team_two)
def show_stats(self):
print(f"{self.team_one.name} stats: ")
self.team_one.stats()
print(f"{self.team_two.name} stats: ")
self.team_two.stats()
if __name__ == "__main__":
# If you run this file from the terminal
# this block is executed.
# hero1 = Hero("Wonder Woman")
# hero2 = Hero("Dumbledore")
# ability1 = Ability("Super Speed", 3)
# ability2 = Ability("Super Eyes", 1)
# ability3 = Ability("Wizard Wand", 8000)
# ability4 = Ability("Wizard Beard", 2000)
# hero1.add_ability(ability1)
# hero1.add_ability(ability2)
# hero2.add_ability(ability3)
# hero2.add_ability(ability4)
# hero1.fight(hero2)
''' game test '''
# arena = Arena()
# arena.build_team_one()
# arena.build_team_two()
# arena.team_battle()
# arena.show_stats()
game_is_running = True
# Instantiate Game Arena
arena = Arena()
#Build Teams
# arena.build_team_one()
# arena.build_team_two()
while game_is_running:
arena.team_battle()
arena.show_stats()
play_again = input("Play Again? Y or N: ")
#Check for Player Input
if play_again.lower() == "n":
game_is_running = False
else:
#Revive heroes to play again
arena.team_one.revive_heroes()
arena.team_two.revive_heroes()
|
7c4682edd9aebb582e2df1bfd9ab1ccaeedeff0d | Sivasankar-tech/Codewars-1 | /Solutions/6kyu/6kyu_transform_to_prime.py | 222 | 3.921875 | 4 | def minimum_number(numbers,add=0):
return add if isprime(sum(numbers)+add) else minimum_number(numbers,add+1)
def isprime(n):
return False if n<2 else True if n==2 else all(n%i!=0 for i in range(2,int(n**0.5)+1))
|
72ff1ad04f3106bd18598cd349085a884ed9beff | nathanstouffer/adv-alg | /project/implementation/code/vector2.py | 932 | 4.15625 | 4 | # a basic vector in \R^2
import math
class Vector2:
# CONSTRUCTOR ------------------------------------------------------------------
def __init__(self, x, y):
self.x = x
self.y = y
# PUBLIC METHODS ---------------------------------------------------------------
def normalize(self):
return self.scale(1/self.mag())
def mag(self):
dist = self.x*self.x + self.y*self.y
return math.sqrt(dist)
def scale(self, scalar):
return Vector2(scalar*self.x, scalar*self.y)
# other must be of type Vector2
def __add__(self, other):
return Vector2(self.x+other.x, self.y+other.y)
# other must be of type Vector2
def __sub__(self, other):
return Vector2(self.x-other.x, self.y-other.y)
def __str__(self):
return str(self.x) + ", " + str(self.y)
# PRIVATE METHODS --------------------------------------------------------------
|
f9e89fc5952c61e6ae2d3a9024d9956011f12fdb | Aasthaengg/IBMdataset | /Python_codes/p02899/s521305336.py | 267 | 3.5 | 4 | def main():
n = int(input())
a = [int(_) for _ in input().split()]
order = [0 for i in range(n)]
for i in range(n):
order[a[i] - 1] = i + 1
# order.append(a.index(i+1) + 1)
print(*order)
if __name__ == '__main__':
main()
|
f1c64982db09686238b4508bf903ea4fe3ce3efc | xiegd/sy | /zuoye/118010100411/4.2.py | 365 | 3.8125 | 4 | str = input('请输入一串字符:')
e = num = space = other = 0
for char in str:
if 'a' < char < 'z' or 'A' < char < 'Z':
e += 1
elif '0' < char < '9':
num += 1
elif char == ' ':
space += 1
else:
other += 1
print('英文字符数{},数字数{},空格数{},其他字符数{}'.format(e,num,space,other))
|
7eefacc4a87a608503971d30d8dd7d0ab96163c0 | tzablock/PythonLearn | /src/spark/python/collection/dictionary.py | 178 | 4.25 | 4 | dict = {"a":1,"b":2,"c":3}
# getting element by key
print(dict["a"])
# inserting element with key
dict["d"] = 4
print(dict)
# delete some element by key
del dict["b"]
print(dict) |
3d80e544c4855753da721a8c4522aa69371059d7 | AmitHasanShuvo/Programming | /kangaroo.py | 177 | 3.5625 | 4 | def kangaroo(x1, v1, x2, v2):
return 'YES' if (v1 > v2) and (x2 - x1) % (v2 - v1) == 0 else 'NO'
x1, v1, x2, v2 = map(int, input().split())
print(kangaroo(x1, v1, x2, v2)) |
4340221792b1a1fb1e6b6617089eed8ce4e58cb1 | philiphoang/Python-Machine-Learning | /Exercise2/main.py | 1,726 | 3.828125 | 4 | import numpy as np
#plot data
import matplotlib.pyplot as plt
from gradientrunner import gradient_descent_runner
from gradientearlystop import gradient_descent_runner_early_stop
from normaleq import normalEquation
from sklearn.linear_model import LinearRegression
#Exercise 1.1
np.random.seed(2)
#generate 100 x values from 0 to 2 randomly, then sort them in ascending order
X = 2 * np.random.rand(100, 1)
X.sort(axis = 0)
#generate y values and add noise to it
y = 4 + 3 * X + np.random.rand(100, 1)
#matplotlib inline
plt.scatter(X, y)
points = np.column_stack((X, y))
num_iterations = 100
learning_rate = 0.47
initial_w0 = 0 #initial y-intercept guess
initial_w1 = 0 #initial slope guess
threshold = 0.1
[w0, w1, mse] = gradient_descent_runner(points, initial_w0, initial_w1, learning_rate, num_iterations)
#------------
#Exercise 1.2
#[w0, w1, mse] = gradient_descent_runner_early_stop(points, initial_w0, initial_w1, learning_rate, num_iterations, threshold)
#------------
#Exercise 1.3
normalEquation(X,y)
#make a lin_reg object from the LinearRegressionclass
lin_reg = LinearRegression()
#use the fit method of LinearRegression class to fit a straight line through the data
lin_reg.fit(X, y)
print('y-intercept w0:', lin_reg.intercept_)
print('slope w1', lin_reg.coef_)
#plot the original data points as a scatter plot
plt.scatter(X, y, label='original data')
#plot the line that fits these points. Use the values of m and b as provided by the fit method
y_ = lin_reg.coef_*X + lin_reg.intercept_
#you can also get y_ by using the predict method.
#y_ = lin_reg.predict(X)
plt.plot(X, y_, color='r', label='predicted fit')
plt.xlabel('x'); plt.ylabel('y')
plt.legend(loc='best')
plt.show()
#-------------
|
22db866fc5203585c92ef60c02cdcbf9421c923e | BenDataAnalyst/Practice-Coding-Questions | /leetcode/123-Hard-Best-Time-To-Buy-And-Sell-Stock-III/answer.py | 2,346 | 3.8125 | 4 | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Brute Force O(n^2) Solution
#-------------------------------------------------------------------------------
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# Really brute force n^2
pairs = []
profit = 0
# Find every valid transaction
for i in range(len(prices)):
for j in range(i+1, len(prices)):
if prices[j] - prices[i] > 0:
pairs.append((i, j, prices[j] - prices[i]))
print(pairs)
for i in range(len(pairs)):
# Get profit from first transction
first = pairs[i][2]
profit = max(profit, first)
for j in range(i+1, len(pairs)):
# If valid second transaction
if pairs[j][0] >= pairs[i][1]:
profit = max(profit, first + pairs[j][2])
return profit
#-------------------------------------------------------------------------------
# O(3n) Solution
#-------------------------------------------------------------------------------
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)<=1: return 0
profit = 0
left = [0]*len(prices)
curr = prices[0]
# Find max gain from left to right
for i in range(1, len(prices)):
curr= min(curr, prices[i])
left[i] = max(prices[i]-curr, left[i-1])
# Find max gain from right to left
right = [0]*len(prices)
curr = prices[-1]
for i in range(len(prices)-2, -1, -1):
curr = max(curr, prices[i])
right[i] = max(curr-prices[i], right[i+1])
# By finding the profit left/right we can determine
# them to be pairs of transactions. Together they
# represent the max profit of selling and buying on
# that day
for l, r in zip(left, right):
profit = max(profit, l + r)
return profit
#-------------------------------------------------------------------------------
# Testing
|
fed10e92e2106b583fbd0b7d128d0c89fe90289d | kaisjessa/Project-Euler | /pe066.py | 980 | 3.53125 | 4 | from math import sqrt, ceil, floor
#x**2 - D * y**2 = 1
#x**2 = 1 + D * y**2
#for D <- 2 to 1000 (no perfect squares), find integer values for x,y s.t. x in minimized
#https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Algorithm
def determine_period(n):
period = 0
m = 0
d = 1
a_0 = int(sqrt(n))
a = int(sqrt(n))
arr = []
arr.append(a)
while a != 2*a_0:
m = d*a - m
d = (n-m**2)/d
a = int((a_0 + m)/d)
arr.append(a)
period += 1
if(period % 2 == 0):
return arr[0:period]
return arr[0:period] + arr[1:period]
squares = [n**2 for n in range(int(sqrt(1000))+1)]
def continued_fraction(arr):
num = 1
arr2 = arr[::-1]
dem = arr2[0]
for i in arr2[1:]:
#add previous element to fraction
num += dem*i
#take reciprocal
temp = num
num = dem
dem = temp
return dem
max_x = 0
max_D = 0
for D in range(2, 1001):
if(D not in squares):
x = continued_fraction(determine_period(D))
if(x > max_x):
max_x = x
max_D = D
print(max_D)
|
e34c28723e2e6b989c558e467a890c1b7858dc15 | AyelaChughtai/CS88 | /Labs/lab03.py | 2,631 | 4.09375 | 4 | # Question 1-3
def second_max(lst):
"""
Return the second highest number in a list of positive integers.
>>> second_max([3, 2, 1, 0])
2
>>> second_max([2, 3, 3, 4, 5, 6, 7, 2, 3])
6
>>> second_max([1, 5, 5, 5, 1])
5
>>> second_max([5, 6, 6, 7, 1])
6
>>> second_max([5, 6, 7, 7, 1])
7
"""
max_value = max(lst)
lst.remove(max_value)
return (max(lst))
from math import sqrt
def is_square(n):
return float(sqrt(n)) == int(sqrt(n))
def squares(seq):
"""Returns a new list containing elements of the original list that are
perfect squares.
>>> seq = [49, 8, 2, 1, 102]
>>> squares(seq)
[49, 1]
>>> seq = [500, 30]
>>> squares(seq)
[]
"""
return [x for x in seq if is_square(x)==True]
#from math import range
def pairs(n):
"""Returns a new list containing two element lists from values 1 to n
>>> pairs(1)
[[1, 1]]
>>> x = pairs(2)
>>> x
[[1, 1], [2, 2]]
>>> pairs(5)
[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
>>> pairs(-1)
[]
"""
return [[x, x] for x in range(n+1) if x>0]
# Question 4
def where_above(lst, limit):
"""
where_above behaves like table.where(column, are.above(limit)).
The analogy is completed if you think of a column of a table as a list and return the filtered column instead of the entire table.
>>> where_above([1, 2, 3], 2)
[3]
>>> where_above(range(13), 10)
[11, 12]
>>> where_above(range(123), 120)
[121, 122]
"""
return [x for x in lst if x>limit]
# Question 5
def minmax(s):
"""Return the minimum and maximum elements of a non-empty list. Hint: start
with defining two variables at the beginning. Do not use the built in
max or min functions
>>> minmax([1, 2, -3])
[-3, 2]
>>> x = minmax([2])
>>> x
[2, 2]
>>> minmax([4, 5, 4, 5, 1, 9, 0, 7])
[0, 9]
>>> minmax([100, -10, 1, 0, 10, -100])
[-100, 100]
"""
if len(s) >=1:
min = s[0]
max = s[0]
else:
min = None
max = None
for x in s :
if x > min:
min = x
if x < max :
max = x
return [max,min]
# Question 6
from math import log
def closest_power_2(x):
""" Returns the closest power of 2 that is less than x
>>> closest_power_2(6)
4
>>> closest_power_2(32)
16
>>> closest_power_2(87)
64
>>> closest_power_2(4095)
2048
>>> closest_power_2(524290)
524288
"""
Max_power = int((log(x-0.1,2)))
return 2**Max_power
|
d9027cec689a6f58fcaccba0a7006c47f2dd5ad8 | Shiv2195/Algorithm_Toolbox | /week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 260 | 3.9375 | 4 | # Uses python3
def fibonacci_series(n):
fibo_list = []
fibo_list.append(0)
fibo_list.append(1)
for i in range(2,n+1):
fibo_list.append(fibo_list[i-1] + fibo_list[i-2])
return fibo_list[n]
n = int(input())
print(fibonacci_series(n))
|
7cc6851f07e89518d8f993a3efc8be7298e55e74 | bobbyhalljr/Hash-Tables | /src/hashes/hashes.py | 267 | 3.546875 | 4 | import hashlib
# bits string
key = b"str"
# another way for bit
my_string = 'This is a normal string'.encode()
# for i in range(10):
# hashed = hashlib.sha256(key).hexdigest()
# print(hashed)
for i in range(10):
hashed = hash(key)
print(hashed % 8) |
39d3ea9678ec2c96d61b441d959934f81f0819ef | zhaochuanshen/leetcode | /Search_for_a_Range.py | 1,658 | 3.9375 | 4 | '''
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
'''
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, A, target):
s = 0
end = len(A)-1
#left = self.searchRangeleft(A, target, s, end)
left = -1
while (s <= end):
mid = (s + end)/2
if A[mid] < target:
s = mid +1
if A[mid] > target:
end = mid - 1
if A[mid] == target:
if mid == 0:
left = 0
break
if A[mid-1] != target:
left = mid
break
else:
end = mid - 1
if left == -1:
return [-1, -1]
right = -1
s, end = 0, len(A)-1
while (s <= end):
mid = (s + end)/2
if A[mid] > target:
end = mid - 1
if A[mid] < target:
s = mid + 1
if A[mid] == target:
if mid == len(A)-1:
right = mid
break
if A[mid + 1] != target:
right = mid
break
else:
s = mid + 1
return [left, right]
|
8044f340304f9c434c272e3823f5951f2b3a1dab | Joecth/leetcode_3rd_vscode | /49.group-anagrams.py | 4,631 | 3.6875 | 4 | #
# @lc app=leetcode id=49 lang=python3
#
# [49] Group Anagrams
#
# https://leetcode.com/problems/group-anagrams/description/
#
# algorithms
# Medium (53.31%)
# Likes: 2809
# Dislikes: 157
# Total Accepted: 537.4K
# Total Submissions: 997.8K
# Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
#
# Given an array of strings, group anagrams together.
#
# Example:
#
#
# Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
# Output:
# [
# ["ate","eat","tea"],
# ["nat","tan"],
# ["bat"]
# ]
#
# Note:
#
#
# All inputs will be in lowercase.
# The order of your output does not matter.
#
#
#
# @lc code=start
from collections import defaultdict
class Solution:
# def __init__(self):
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# write your code here
# return self.helper(strs)
return self.helper_better(strs)
def helper_better(self, strs):
d = {}
for s in strs:
tmp_s = ''.join(sorted(s))
if tmp_s not in d:
d[tmp_s] = [s]
else:
d[tmp_s] += [s]
return [val for val in d.values()]
def helper(self, strs):
# map_s = {}
# map_s for strs[0]
# map_s_cand = []
# str2anagrams = {}
# for s in str[1] ==> str[-1]:
# for cand in map_s_cand
# if not is_anagram(cand, s):
# update map_s_cand
# else
# update str2anagrams
# res = []
# for key in str2anagrams:
# append valu into res
# return res
map_s = {} # represents strs[0]
cur_str = strs[0]
for i in range(len(cur_str)):
map_s[cur_str[i]] = map_s.get(cur_str[i], 0) + 1
# map_s_candidates = []
# map_s_candidates.append(map_s)
map_s_candidates = {cur_str: map_s}
str2anagrams = {cur_str: [cur_str]}
for i in range(1, len(strs)):
cur_str = strs[i]
# for key in map_s_candidates.keys():
# map_tmp = {}
group_key = None
for key in map_s_candidates.keys():
# print("cand: ", map_s_candidates[key], "; cur_str: ", cur_str)
if self.is_anagram(map_s_candidates[key].copy(), cur_str):
str2anagrams[key] += [cur_str]
group_key = key
break
if group_key == None:
map_tmp = {}
for i in range(len(cur_str)):
map_tmp[cur_str[i]] = map_tmp.get(cur_str[i], 0) + 1
map_s_candidates[cur_str] = map_tmp
str2anagrams[cur_str] = [cur_str]
# print("map_s_candidates: \n", map_s_candidates)
# print("str2anagrams: \n", str2anagrams)
res = []
for key in str2anagrams.keys():
res.append(str2anagrams[key])
return res
def is_anagram(self, map_s, t):
for i in range(len(t)):
if t[i] not in map_s:
return False
map_s[t[i]] -= 1
if map_s[t[i]] == 0:
del map_s[t[i]]
for val in map_s.values():
if val != 0:
return False
return True
def old(self, strs):
res = []
d = defaultdict(list)
for i in range(len(strs)):
item = ''.join(sorted(strs[i]))
# print(item)
d[item].append(strs[i]) # {aet: [eat, ]}
# print(d)
return [l for l in d.values()]
def groupAnagrams_old(self, strs: List[str]) -> List[List[str]]:
d = {}
# build a one-hot mapping
for s in strs:
onehot = self.chars2onehot(s)
# if onehot not in d: # unhashable type: 'list' CAUTIOUS! should turn into tuple for hashable
if tuple(onehot) not in d:
d[tuple(onehot)] = [s] # [100101] ==> eat
else:
d[tuple(onehot)].append(s)
# d[onehot] = d.get(onehot, 0) + 1
# {[1 0 0 0 0 1 0 0 1 0 ]}
ret = []
for key in d.keys():
ret.append(d[key])
return ret
def chars2onehot(self, s):
onehot = [0] * 26
for c in s:
onehot[ord(c)-97] += 1 # 97 is ord('a') CAUTIOUS!!
return onehot
# @lc code=end
|
a44c34e52b52a2423dab7317cf1256d0835083d9 | himadrinayak/Color-Game | /scap.py | 1,612 | 3.671875 | 4 | import tkinter
import random
import tkinter.messagebox
colours = ['Red', 'Brown', 'Pink', 'Blue', 'Green', 'Purple', 'Violet', 'Yellow', 'Black', 'Orange']
score =0
timeleft = 30
def startGame(Event):
if timeleft== 30:
countdown()
elif timeleft ==0:
endgame()
nextcolor()
def endgame():
global score
tkinter.messagebox.showinfo("GAME OVER", " SCORE :"+ str(score))
def nextcolor():
global score
global timeleft
if timeleft >0:
e.focus_set()
if e.get().lower() == colours[1].lower():
score = score+1
e.delete(0, tkinter.END)
random.shuffle(colours)
label.config(fg=str(colours[1]), text=str(colours[0]))
scorelabel.config(text= " Score : "+ str(score))
def countdown():
global timeleft
if timeleft > 0:
timeleft = timeleft - 1
timelabel.config(text = "Time Left:"+ str(timeleft) )
timelabel.after(1000, countdown)
root = tkinter.Tk()
root.title("COLOR GAME")
root.geometry("800x200")
instruction = tkinter.Label(root, text ="Enter the name of the colour and not the text!!", font = ('Helvetica', 20))
instruction.pack()
scorelabel = tkinter.Label(root, text ="Press enter to start", font = ('Helvetica', 20))
scorelabel.pack()
timelabel = tkinter.Label(root, text = "Time Left:"+ str(timeleft), font = ('Helvetica', 20))
timelabel.pack()
label = tkinter.Label(root, font = ('Helvetica', 20))
label.pack()
e = tkinter.Entry(root)
root.bind('<Return>', startGame)
e.pack()
e.focus_set()
root.mainloop() |
f82aa1fb7bec005ecc49715f38239aa050def162 | AChen24562/Python-QCC | /Exam2/Q9.py | 632 | 4.1875 | 4 | '''Given:
items = ['notebooks', 'pens', 'pencils', 'usb']
quantities = [10, 24, 16, 12]
1) Create a dictionary, supplies by using the two given lists above.
2) Use a loop to print all keys and values in the dictionary supplies.
3) Print the dictionary supplies.
Example Output
10 - NOTEBOOKS, 24 - PENS, 16 - PENCILS, 12 - USB,
{'notebooks': 10, 'pens': 24, 'pencils': 16, 'usb': 12}'''
items = ['notebooks', 'pens', 'pencils', 'usb']
quantities = [10, 24, 16, 12]
supplies = dict(zip(items, quantities))
for items, quantities in supplies.items():
print(f"{quantities} - {items.upper()}", end=", ")
print()
print(supplies)
|
4d08331903105c326c53618de2d3871ff055fb4b | vi31/APS-2020 | /CodeLib/104-CountingSort.py | 461 | 3.625 | 4 | def CountingSort(lst):
left=min(lst)
right=max(lst)
Range=right-left+1
count=[0 for x in range(Range)]
sortedArray=lst[:]
for i in range(0,len(lst)):
count[lst[i]-left]+=1
for i in range(1,Range):
count[i]+=count[i-1]
for i in range(0,len(lst)):
count[lst[i]-left]-=1
sortedArray[count[lst[i]-left]]=lst[i]
print("Sorted array:",sortedArray)
if __name__=='__main__':
l=list(map(int,input('Enter array elements ').split(' ')))
CountingSort(l)
|
15fd52b4a919488d2da49da080f18930524b96aa | danisbagus/data-visualization-python | /from_json.py | 388 | 3.515625 | 4 | import matplotlib.pylab as plt
import json
year = []
population = []
with open('population.json') as json_file:
data = json.load(json_file)
for value in data:
year.append(value['year'])
population.append(value['population'])
plt.plot(year,population)
plt.title('data population')
plt.xlabel('years')
plt.ylabel('population')
plt.legend(['Population'])
plt.show() |
79bcfa61cf6bc85ebe2a1f717e638f37a5b8f791 | MustafaMuhammad2000/Neural_Net | /Test.py | 839 | 3.6875 | 4 | import NeuralNet as MN
import numpy as np
# Using the neural network!
test_neural_network = MN.neural_network([2, 3, 3, 1], 0.2)
# Testing a simple XOR bitwise function
input_arr = [[0, 0], [0, 1], [1, 0], [1, 1]]
target_arr = [[0], [1], [1], [0]]
print("Pre-training results")
print(test_neural_network.test(input_arr[0]))
print(test_neural_network.test(input_arr[1]))
print(test_neural_network.test(input_arr[2]))
print(test_neural_network.test(input_arr[3]))
for i in range(100000):
rand = np.random.randint(0, 4)
test_neural_network.train(input_arr[rand], target_arr[rand])
print("Training complete, now time for post-training results")
print(test_neural_network.test(input_arr[0]))
print(test_neural_network.test(input_arr[1]))
print(test_neural_network.test(input_arr[2]))
print(test_neural_network.test(input_arr[3])) |
da9bbb610f3966c5f3fa2d63f5b583ceb1a67015 | srinidhi136/python-app | /Volume of cone.py | 261 | 4.5 | 4 | ##this program is to calculate the Volume of the cone
Radius_of_the_cone = 7.5
height_of_the_cone = 21.5
pi = 3.14
volume_of_the_cone =(pi*Radius_of_the_cone*Radius_of_the_cone*height_of_the_cone)/(1/3)
print("The volume of the cone", volume_of_the_cone)
|
700dd85b92006177b860cda5d027e4a19c08ded5 | shachafk/FeedbackVertexSet | /graphs/multi_graph.py | 515 | 3.890625 | 4 | import networkx as nx
from utils.functions import show_graph
from utils.reductions import run_reductions
mg = nx.MultiGraph()
mg.add_node(1)
mg.add_node(2)
mg.add_node(3)
mg.add_edge(1, 2)
mg.add_edge(1, 3)
mg.add_edge(2, 3)
mg.add_edge(1, 2)
# mg.add_edge(1, 1)
k = 3
# show_graph(mg, "before")
print("number of nodes before " + str(len(mg.nodes)))
print("k before " + str(k))
k, x = run_reductions(mg, k)
print("number of nodes after " + str(len(mg.nodes)))
print("k after " + str(k))
# show_graph(mg, "after")
|
f573fde72ed101360a2a41cf648cedcd8f2268c3 | floo1/Richtungshoeren_mit_Python | /combinig_arrays.py | 850 | 3.890625 | 4 | # Arrays zusammenführen
# hier mal ein Beispiel wie man Arrays zu einem Array zusammenfassen kann:
import numpy as np
# erzeuge zwei zeilenvektoren mit jew. 2 spalten
a = np.zeros([2,2])
b = np.array([[5,6],[7,8]])
# ranheangen der zwei vektoren als zeilenvektor in einem array
p=np.vstack([a,b])
# weiter Array erzeugen und anhaengen (schleife ware natürlich eleganter...):
b2 = np.array([[1,1],[1,1]])
p=np.vstack([p,b2])
b3 = np.array([[2,2],[2,2]])
p3=np.vstack([p,b3])
print('zusammengefuegt zu einem Array unterinander: ', p3)
# zwei arrays in einen array als zeilenvektor
z1 = np.append(a,b) # heangt die arrays aneinander
print('aneinander geheangtes Array: ', z1)
z2 = np.append(a,b, axis=1) # axis=1 gibt die info: bitte nebeneinander heangen
print('zusammengefuegt zu einem Array als Zeielnvektor, also nebeneinander: ')
print(z2) |
47d932de814350ae2947cde5d0aff6e5299a5470 | riturajsingh2015/Algorithms-and-Datastructures-with-Python | /matrix_ele_sum.py | 352 | 3.640625 | 4 | def matrixElementsSum(matrix):
total=sum(matrix[0])
for i in range(1,len(matrix)): # row index
for j in range(len(matrix[i])): # col index
if matrix[i-1][j] !=0:
total+=matrix[i][j]
return total
matrix=[[0,1,1,2],
[0,5,0,0],
[2,0,3,3]]
print(matrixElementsSum(matrix))
|
5861087fd3a093f080c343137f300c2975a407f6 | fnpy/fn.py | /fn/immutable/finger.py | 7,130 | 4.125 | 4 | """Finger tree implementation and application examples.
A finger tree is a purely functional data structure used in
efficiently implementing other functional data structures. A
finger tree gives amortized constant time access to the "fingers"
(leaves) of the tree, where data is stored, and the internal
nodes are labeled in some way as to provide the functionality of
the particular data structure being implemented.
More information on Wikipedia: http://goo.gl/ppH2nE
"Finger trees: a simple general-purpose data structure": http://goo.gl/jX4DeL
"""
from collections import namedtuple
from fn.uniform import reduce
# data Node a = Node2 a a | Node3 a a a
# data Digit a = One a | Two a a | Three a a a | Four a a a a
# data FingerTree a = Empty
# | Single a
# | Deep (Digit a) (FingerTree (Node a)) (Digit a)
One = namedtuple("One", "a")
Two = namedtuple("Two", "a,b")
Three = namedtuple("Three", "a,b,c")
Four = namedtuple("Four", "a,b,c,d")
class Node2(namedtuple("Node2", "a,b")):
def __iter__(self):
yield self.a
yield self.b
class Node3(namedtuple("Node3", "a,b,c")):
def __iter__(self):
yield self.a
yield self.b
yield self.c
class FingerTree(object):
class Empty(object):
__slots__ = ("measure",)
def __init__(self, measure):
object.__setattr__(self, "measure", measure)
def __setattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be changed".format("Empty"))
def __delattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be deleted".format("Empty"))
def is_empty(self):
return True
def head(self):
return None
def last(self):
return None
def tail(self):
return self
def butlast(self):
return self
def push_front(self, v):
return FingerTree.Single(self.measure, v)
def push_back(self, v):
return FingerTree.Single(self.measure, v)
def __iter__(self):
return iter([])
class Single(object):
__slots__ = ("measure", "elem",)
def __init__(self, measure, elem):
object.__setattr__(self, "measure", measure)
object.__setattr__(self, "elem", elem)
def __setattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be changed".format("Single"))
def __delattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be deleted".format("Single"))
def is_empty(self):
return False
def head(self):
return self.elem
def last(self):
return self.elem
def tail(self):
return FingerTree.Empty(self.measure)
def butlast(self):
return FingerTree.Empty(self.measure)
def push_front(self, v):
return FingerTree.Deep(
self.measure, [v], FingerTree.Empty(self.measure), [self.elem]
)
def push_back(self, v):
return FingerTree.Deep(
self.measure, [self.elem], FingerTree.Empty(self.measure), [v]
)
def __iter__(self):
return iter([self.elem])
class Deep(object):
__slots__ = ("measure", "left", "middle", "right",)
def __init__(self, measure, left, middle, right):
object.__setattr__(self, "measure", measure)
object.__setattr__(self, "left", left)
object.__setattr__(self, "middle", middle)
object.__setattr__(self, "right", right)
def __setattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be changed".format("Deep"))
def __delattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be deleted".format("Deep"))
def is_empty(self):
return False
def head(self):
return self.left[0]
def last(self):
return self.right[-1]
def tail(self):
if len(self.left) == 1:
if self.middle.is_empty():
return FingerTree.from_iterable(
self.measure, list(self.right)
)
return FingerTree.Deep(
self.measure,
[self.middle.head()],
self.middle.tail(),
self.right
)
return FingerTree.Deep(
self.measure, self.left[1:], self.middle, self.right
)
def butlast(self):
if len(self.rigth) == 1:
if self.middle.is_empty():
return FingerTree.from_iterable(
self.measure, list(self.left)
)
return FingerTree.Deep(
self.measure,
self.left,
self.middle.butlast(),
[self.middle.last()])
return FingerTree.Deep(
self.measure, self.left, self.middle, self.right[:-1]
)
def push_front(self, v):
if len(self.left) == 4:
return FingerTree.Deep(
self.measure,
[v, self.left[0]],
self.middle.push_front(Node3(*self.left[1:])),
self.right
)
return FingerTree.Deep(
self.measure, [v] + self.left, self.middle, self.right
)
def push_back(self, v):
if len(self.right) == 4:
return FingerTree.Deep(
self.measure,
self.left,
self.middle.push_back(Node3(*self.right[:3])),
[self.right[-1], v])
return FingerTree.Deep(
self.measure, self.left, self.middle, self.right + [v]
)
def __iter__(self):
for l in self.left:
yield l
for m in self.middle:
for mi in m:
yield mi
for r in self.right:
yield r
@staticmethod
def from_iterable(measure, it):
tree = FingerTree.Empty(measure)
return reduce(lambda acc, curr: acc.push_front(curr), it, tree)
def __new__(_cls, measure):
return FingerTree.Empty(measure)
#####################################################
# Possible applications of finger tree in practice
#####################################################
class Deque(object):
def __new__(_cls):
return FingerTree.Empty(lambda x: x)
@staticmethod
def from_iterable(it):
return FingerTree.from_iterable(lambda x: x, it)
|
24b81468ea0defee70e319dab673cc74369dfa0c | brentoncollins/wateringsys | /livelevel.py | 631 | 3.6875 | 4 | #!/usr/bin/python3
#!/
# This is a python script reading the live level in the water tank.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO.OUT) # set pin 22 gpio to an output
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Pulldown the input resistor on pin 23
GPIO.output(22, 1) # voltage output voltage for level sensor to 1
while True:
if GPIO.input(23) == 0:
print ("The Water Level Is Low")
time.sleep (2)
if GPIO.input(23)== 1:
print ("Water Level Ok")
time.sleep (2)
|
c272b6a2f57292851b097536be1810e3515ba77b | Sanjay-2001/Assignment | /Day1_assignment.py | 315 | 4 | 4 | #Question no. 1
a="hello"
b="hello"
print(a is b)
c=89.3
d=78.4
print(c is d)
#Question no. 2
print(1>3>4)
#Question no. 3
str='100'
print("int('100') with base 2 = ", int(str,2))
s=str
print("value of str function = ",s)
float_string=float("-12")
print("value of float function = ",float_string) |
dc66a0705b1585b986dbd5a984b818efec84effc | rahilanjum/PIAIC | /Assignment 2.py | 2,560 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Step 1. Import the necessary libraries
# In[1]:
import pandas as pd
# In[ ]:
# # Step 2. Import the dataset Euro_2012_stats_TEAM
# # Step 3. Assign it to a variable called euro12.
# In[140]:
euro12 = pd.read_csv("Euro_2012_stats_TEAM.csv", skipfooter=4, engine='python')
print("data-frame shape: ", euro12.shape)
print("---------------------")
print("Columns: ", euro12.columns.values)
# # Step 4. Select only the Goal column.
# In[141]:
print(euro12["Goals"])
print("---------------------")
print(euro12.Goals)
# # Step 5. How many team participated in the Euro2012?
# In[148]:
print(len(euro12["Team"]))
print("------------------")
print(euro12["Team"])
# # Step 6. What is the number of columns in the dataset?
# In[79]:
len(euro12.columns)
# # Step 7. View only the columns Team, Yellow Cards and Red Cards and assign them to a dataframe called discipline
# In[143]:
discipline = pd.DataFrame(euro12[["Team", "Yellow Cards", "Red Cards"]])
print(discipline)
# # Step 8. Sort the teams by Red Cards, then to Yellow Cards
# In[144]:
discipline.sort_values(['Red Cards', 'Yellow Cards'], ascending=False)
# # Step 9. Calculate the mean Yellow Cards given per Team
# In[81]:
discipline["Yellow Cards"].mean()
# # Step 10. Filter teams that scored more than 6 goals
# In[77]:
euro12[euro12.Goals > 6]
# # Step 11. Select the teams that start with G
# In[87]:
euro12[euro12.Team.str[0] == 'G']
# # Step 12. Select the first 7 columns
# In[145]:
euro12.iloc[:, 0:7]
# # Step 13. Select all columns except the last 3.
# In[146]:
euro12.iloc[:, 0:32]
# # Step 14. Present only the Shooting Accuracy from England, Italy and Russia
# In[147]:
euro12.iloc[[3,7,12], [0,4]]
# # Step 15. Use apply method on Goal Column to make a new column called Performance, using following conditions
# 1 - If Goals are less than or equal to 2, peformance is Below Avg
# 2 - If Goals are more than 2 and less than or equal to 5, peformance is Average
# 3 - If Goals are more than 5 and less than or equal to 10, peformance is Above Average
# 4 - If Goals are more than 10 then peformance is Excellent
# In[159]:
def condition(Goals):
if Goals > 10:
return "Excellent"
elif Goals > 5:
return "Above Average"
elif Goals > 2:
return "Average"
else:
return "Below Average"
euro12['Performance'] = euro12.Goals.apply(condition)
euro12[["Team", "Goals", "Performance"]]
# In[ ]:
# In[ ]:
# In[ ]:
|
3b809a638726ffec612b160b6fa8087d18bc8608 | Tom-van-Grinsven/Sudoku-Solver | /src/solver.py | 2,768 | 3.65625 | 4 | import urllib.request, json
def get_board():
with urllib.request.urlopen("https://sugoku.herokuapp.com/board?difficulty=easy") as url:
data = json.loads(url.read().decode())
return data["board"]
board = get_board()
# board = [
# [0,0,3,7,0,0,0,6,0],
# [0,0,0,5,6,0,0,4,0],
# [0,6,2,0,0,0,7,0,8],
# [0,9,7,3,8,0,6,0,0],
# [0,8,0,6,0,0,0,9,0],
# [0,0,5,4,0,7,0,0,0],
# [1,0,0,0,0,0,2,0,0],
# [8,0,0,0,0,0,0,3,9],
# [0,5,6,0,3,0,0,0,0]
# ]
def print_board(board):
# traverse the rows
for row in range(len(board)):
if row % 3 == 0 and row != 0:
print("- - - - - - - - - - - - - ")
# traverse the columns within the row
for column in range(len(board[0])):
if column % 3 == 0 and column != 0:
print(" | ", end="")
if column == 8:
print(board[row][column])
else:
print(str(board[row][column]) + " ", end="")
def find_next_empty_place(board):
for row in range(len(board)):
for column in range(len(board[0])):
if board[row][column] == 0:
return row, column
return None
def is_valid(board, number, position):
# traverse the row
for i in range(len(board[0])):
# if two of the same numbers are in the row (without checking the current inserted number), the board is not valid
if board[position[0]][i] == number and position[1] != i:
return False
# traverse the column
for i in range(len(board)):
# if two of the same numbers are in the column (without checking the current inserted number), the board is not valid
if board[i][position[1]] == number and position[0] != i:
return False
# traverse the boxes
box_x = position[1] // 3
box_y = position[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == number and (i,j) != position:
return False
return True
def solve_sudoku(board):
# if we hit the end of the board, the solution is found
found = find_next_empty_place(board)
if not found:
return True
else:
row, column = found
for i in range(1, 10):
if is_valid(board, i, (row, column)):
board[row][column] = i
if solve_sudoku(board):
return True
board[row][column] = 0
return False
def print_process():
print("Board before solving: ")
print("\n")
print_board(board)
print("\n")
print("Solving")
print("\n")
solve_sudoku(board)
print("Board after solving: ")
print("\n")
print_board(board)
print_process() |
756c79ed1fc6fa02c4383a2656cae004827a20da | fanwangwang/fww_study | /doc/_book/py_example/femknowledge/usefor.py | 201 | 4 | 4 | # 使用`for`循环
# 给定一个函数 $f(x) = x*x + x + 1$ ,求从0到n的值以及他们的和
def f(x):
f = x*x + x + 1
return f
s = 0
for i in range(5):
s += f(i)
print(f(i),s)
|
c7e3a6d361c1bb5453f60f37b47dda1d772be648 | Rebecca-Simms/10-Days-of-Statistics | /2-Quartiles_Interquartile_Range_SD.py | 2,450 | 4.5625 | 5 | """ The quartiles of an ordered data set are the three points that split the data set into four equal groups. The three quartiles are defined as follows:
- Q1: The first quartile is the middle number between the smallest number in a data set and its median.
- Q2: The second quartile is the median (50% percentile) of the data set.
- Q3: The third quartile is the middle number between a data set's median and its largest number.
"""
""" We will split the data into two halves, lower half and upper half:
- If there are an odd number of data points in the original ordered data set, do not include the median (the central value in the ordered list) in either half.
- If there are an even number of data points in the original ordered data set, split this data set exactly in half.
"""
""" The value of the first quartile is the median of the lower half and the value of the third quartile is the median of the upper half.
"""
from statistics import median
def quartiles(numbers):
numbers.sort()
no_numbers = len(numbers)
if no_numbers % 2 != 0:
first_half = numbers[:len(numbers)//2]
second_half = numbers[len(numbers)//2 + 1:]
q1 = median(first_half)
q3 = median(second_half)
q2 = median(numbers)
elif no_numbers % 2 == 0:
first_half = numbers[:len(numbers)//2]
second_half = numbers[len(numbers)//2:]
q1 = median(first_half)
q3 = median(second_half)
q2 = median(numbers)
return q1, q2, q3
numbers = [6, 7, 15, 36, 39, 40, 41, 42, 43, 47, 49]
print(quartiles(numbers)) # (15,40,43)
""" The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q1 - Q3).
"""
""" The expected value of a discrete random variable, X, is more or less another way of referring to the mean. The variance is the average magnitude of fluctuations of X from its expected value.
Given a data set, X, of size n, the variance can be calculated using
"""
'$\sigma^{2} = \frac{\sum^{n}_{i=1} (x_{i}-\mu)^{2}}{n}$'
""" The standard deviation quantifies the amount of variation in a set of data values and is given by the square root of the variance.
"""
def stand_dev(numbers):
mean = sum(numbers) / len(numbers)
variance = sum([((x - mean) ** 2) for x in X]) / len(numbers)
standard_deviation = variance ** 0.5
return round(standard_deviation, 1)
X = [10,40,30,50,20]
print(stand_dev(X)) # 14.1
|
9628be44e10ce921120a17a6ad3f2053eba649a3 | vizeit/Leetcode | /MergeKSortedLists.py | 1,269 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeKLists(lists) -> ListNode:
if not len(lists): return None
elif len(lists) == 1: return lists[0]
d = {}
front = None
while len(lists):
i = 0
while i < len(lists):
if lists[i]:
n = ListNode(lists[i].val)
if lists[i].val not in d:
d[lists[i].val] = [n, n]
else:
d[lists[i].val][1].next = n
d[lists[i].val][1] = n
lists[i] = lists[i].next
if lists[i] is None:
del lists[i]
i -= 1
i += 1
for j in sorted(d.keys(),reverse=True):
if front is None:
front = d[j][0]
else:
d[j][1].next = front
front = d[j][0]
return front
if __name__ == "__main__":
#mergeKLists([None, None, None])
l1 = ListNode(2, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
l3 = ListNode(7, ListNode(8, ListNode(9)))
out = mergeKLists([l1, l2, l3])
while out:
print(out.val)
out = out.next |
c2c9342fc0c49f979b2ef3ce910a6cabaed1af80 | neerajp99/intro_to_cs_CS-101 | /cs1101/Neeraj_Pandey_cs1101_practice4/q11.py | 836 | 4.125 | 4 | """
Concatenate two different lists in the following way:
List1 = ["bingo ", "bango"]
List2 = ["bongo ", "dry”]
[“bingle bongo”, “bingo dry”, “bango bongo”, “bango dry”]
Solution: Using list comprehensions, makes work simpler
"""
if __name__ == "__main__":
list1 = list()
list2 = list()
n1 = int(input("Enter the length of list 1: "))
for i in range(n1):
x = input(f"Enter the first list value { i + 1 }: ")
list1.append(x)
n2 = int(input("Enter the length of list 1: "))
for i in range(n2):
x = input(f"Enter the first list value { i + 1 }: ")
list2.append(x)
# list1 = ["bingo ", "bango "]
# list2 = ["bongo ", "dry "]
combined_list = [x + " " + y for x in list1 for y in map(str, list2)]
print(combined_list)
|
19449a8c3d7391986351f441cf5c2b743a3dbcb2 | tx991020/MyLeetcode | /腾讯/回溯算法/022括号生成.py | 2,960 | 3.78125 | 4 | '''
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
'''
'''
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
self.res = []
self.singleStr('', 0, 0, n)
return self.res
def singleStr(self, s, left, right, n):
if left == n and right == n:
self.res.append(s)
if left < n:
self.singleStr(s + '(',left + 1, right, n)
if right < left:
self.singleStr(s + ')',left, right + 1, n)
非常牛逼的讲解,需要这样的人来给我们讲算法
####以Generate Parentheses为例,backtrack的题到底该怎么去思考?
所谓Backtracking都是这样的思路:在当前局面下,你有若干种选择。那么尝试每一种选择。如果已经发现某种选择肯定不行(因为违反了某些限定条件),就返回;如果某种选择试到最后发现是正确解,就将其加入解集
所以你思考递归题时,只要明确三点就行:选择 (Options),限制 (Restraints),结束条件 (Termination)。即“ORT原则”(这个是我自己编的)
对于这道题,在任何时刻,你都有两种选择:
加左括号。
加右括号。
同时有以下限制:
如果左括号已经用完了,则不能再加左括号了。
如果已经出现的右括号和左括号一样多,则不能再加右括号了。因为那样的话新加入的右括号一定无法匹配。
结束条件是: 左右括号都已经用完。
结束后的正确性: 左右括号用完以后,一定是正确解。因为1. 左右括号一样多,2. 每个右括号都一定有与之配对的左括号。因此一旦结束就可以加入解集(有时也可能出现结束以后不一定是正确解的情况,这时要多一步判断)。
递归函数传入参数: 限制和结束条件中有“用完”和“一样多”字样,因此你需要知道左右括号的数目。 当然你还需要知道当前局面sublist和解集res。
因此,把上面的思路拼起来就是代码:
if (左右括号都已用完) {
加入解集,返回
}
//否则开始试各种选择
if (还有左括号可以用) {
加一个左括号,继续递归
}
if (右括号小于左括号) {
加一个右括号,继续递归
}
你帖的那段代码逻辑中加了一条限制:“3. 是否还有右括号剩余。如有才加右括号”。这是合理的。不过对于这道题,如果满足限制1、2时,3一定自动满足,所以可以不判断3。
这题其实是最好的backtracking初学练习之一,因为ORT三者都非常简单明显。你不妨按上述思路再梳理一遍,还有问题的话再说。
以上文字来自 1point3arces的牛人解答
''' |
caacbe649b7d147338a246d9276480152c704980 | danielcanuto/python_revisao | /fucoes/unpacking.py | 543 | 3.71875 | 4 | #!/usr/bin/python3
def soma_2(a, b):
return a + b
def soma_3(a, b, c):
return a + b + c
def soma_n(*args):
soma = 0
for n in args:
soma += n
return soma
if __name__ == "__main__":
print(soma_2( 20, 30))
print(soma_3(10, 20, 30))
# packing
print(soma_n(10, 20, 30, 22))
print(soma_n(10, 20))
print(soma_n(10))
print(soma_n(10, 1, 3, 5, 5, 6))
# unpacking
tupla_nums = (1, 2, 3)
print(soma_n(*tupla_nums))
lista_nums = (1, 2, 4, 8, 16)
print(soma_n(*lista_nums)) |
f54278a00f8a7ede8600c1e14fbcacc8dd8499ad | CarolineSantosAlves/Exercicios-Python | /Exercícios/ex105AnilisandoGerandoDicionarios.py | 1,075 | 3.703125 | 4 | def notas(* nota, sit=False):
"""
->Função para analisar notas e situções de vários alunos.
:param nota: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a situação da turma
"""
avaliacao = dict()
cont = maior = menor = soma = 0
avaliacao['total'] = len(nota)
for n in nota:
if cont == 0:
maior = n
menor = n
elif n > maior:
maior = n
elif n < menor:
menor = n
cont += 1
soma += n
avaliacao['maior'] = maior
avaliacao['menor'] = menor
avaliacao['media'] = soma / len(nota)
if sit:
if avaliacao['media'] >= 7:
avaliacao['situação'] = 'BOA'
elif 5 <= avaliacao['media'] < 7:
avaliacao['situação'] = 'RAZOÁVEL'
else:
avaliacao['situação'] = 'RUIM'
return avaliacao
#programa principal
resp = notas(2.5, 5.5, 4, 6.5)
print(resp) |
0bea1f33b56ed7cdcfb4daf08848043b362c439c | dbwilson35/TicTacToe | /TicTacToe.py | 4,599 | 3.515625 | 4 | class ttc_board:
def __init__(self):
self.board = {1: '_',2: '_',3: '_',
4: '_',5: '_',6: '_',
7: '_',8: '_',9: '_'}
def display(self):
print(self.board[1] + '|' + self.board[2] + '|' + self.board[3])
print(self.board[4] + '|' + self.board[5] + '|' + self.board[6])
print(self.board[7] + '|' + self.board[8] + '|' + self.board[9])
def check_win(self):
win = [ # List of win variations
# row variations
self.board[1] == self.board[2] == self.board[3] != '_',
self.board[4] == self.board[5] == self.board[6] != '_',
self.board[7] == self.board[8] == self.board[9] != '_',
# column variations
self.board[1] == self.board[4] == self.board[7] != '_',
self.board[2] == self.board[5] == self.board[8] != '_',
self.board[3] == self.board[6] == self.board[9] != '_',
# diagonal variations
self.board[1] == self.board[5] == self.board[9] != '_',
self.board[3] == self.board[5] == self.board[7] != '_'
]
return win.count(True) > 0
def check_tie(self):
list_of_values = [value for value in self.board.values()]
return list_of_values.count('_') == 0 and self.check_win() != True # return True if there are no blank spaces and no winner
def new_game(self):
global game_running
new_game = input('Would you like to play again? (Y/N)')
if new_game == 'Y':
self.__init__()
if new_game != 'Y': # If anything other than Y, update game_running to False so the game stops
game_running = False
#next player
def next_player(current_player):
if current_player == 1:
return 2
if current_player == 2:
return 1
#Let's play the game!
def play_game():
global game_running
game_running = True
current_player = 1 #set player 1 as the current_player
plank = ttc_board() #variable named plank because naming it board might get confusing and a blank is another word for a board right??
while game_running:
plank.display()
turn = input('Hello Player ' + str(current_player) + '. Please choose a spot that has not been chosen! (1-9)') #request current player pick a square
if int(turn) not in range(1,10): #if number is not between 1 and 9 then have player re-enter number
print('That number is invalid. Please select a number 1 through 9')
continue
if plank.board[int(turn)] != '_': #if space has already been chosen have player choose new number
print('That spot has already been chosen. Please select a different one.')
continue
if plank.board[int(turn)] == '_': # if space has not been chosen then
if current_player == 1:
plank.board[int(turn)] = 'X' # X for Player 1
if current_player == 2:
plank.board[int(turn)] = 'O' # O for Player 2
if plank.check_win():
print('Congratulations Player ' + str(current_player) + '! You are the winner!') # Congratulate winning player
plank.display() # Display board
plank.new_game() # Ask to play again?
continue
if plank.check_tie():
print('Tie Game!') #Oops Tie Game
plank.display() #Display board
plank.new_game() #Ask to play again?
continue
current_player = next_player(current_player) #Change Player to next player (1 -> 2, 2 -> 1)
continue
play_game()
|
1b9f3d7efbce8a408868f4b3e0f1915321815e9b | kk31398/guvi-project | /Given a string S-check if it is a palindrome.Print yes or no.py | 68 | 3.828125 | 4 | value=str(input())
a=value[::-1]
print("yes" if a==value else "no")
|
4e21a9e050ed9f8ab9372970a2c7fd6df271e556 | FerdinandAlick/Python-Assignment | /Python Assignmet1/Question4.py | 282 | 4.53125 | 5 | #Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
celsius=float(input("Enter the temperature in degree celsius:"))
fahrenheit = (celsius * 1.8) + 32
print("Fahrenheit=",fahrenheit) |
52ea80abad4906c7c587989e62d50e28415c768d | czs108/LeetCode-Solutions | /Medium/371. Sum of Two Integers/solution (1).py | 510 | 3.578125 | 4 | # 371. Sum of Two Integers
class Solution:
def getSum(self, a: int, b: int) -> int:
x, y = abs(a), abs(b)
if x < y:
return self.getSum(b, a)
sign = 1 if a > 0 else -1
if a * b >= 0:
# Sum of two positive integers x + y.
while y:
x, y = x ^ y, (x & y) << 1
else:
# Difference of two positive integers x - y.
while y:
x, y = x ^ y, ((~x) & y) << 1
return x * sign |
c274ee8fefa3f228aaf3fd4a070b463776e82fb8 | MatheusFilipe21/exercicios-python-3 | /exercicio24.py | 104 | 3.765625 | 4 | cidade = str(input('Em que cidade que você nasceu: ')).strip()
print(cidade[0:5].upper() == 'SANTO')
|
9b7ca16e1d86edccd175ca2b0ea93bf94d3be9d2 | ankitaroyyy/JISAssasins | /Tenth.py | 279 | 3.890625 | 4 | X = input("Enter your string")
l=len(X)
print("The length is", l)
Y = "Ankita"
Z= X+Y
print("After concatenation", Z)
print(''.join(reversed(X)))
old="I like Python"
new=old.replace("like","love")
print(new)
if X == Y:
print("Equal")
else:
print("Not Equal") |
891bd5a620a45683f40ab4b8428e6fb0b119eca6 | Uma98/Python | /Day3/namesList.py | 128 | 3.609375 | 4 | list = ["john", "jake", "jack", "george", "jenny", "jason"]
for i in list:
if len(i) < 5 and "e" in i:
print(i) |
1754a73482f44b96680cc7a81660fb4add73ac53 | bogeoung/AIffel-X-SSAC | /Leetcode/week 03/344. Reverse String.py | 1,073 | 3.609375 | 4 | class Solution:
def reverseString(self, s) -> None:
# 반복할 횟수를 정하기 위해 전체길이의 2를 나눈 몫을 구함
time = len(s)/2
# 바꿀 문자열의 위치를 지정할 변수 count 선언
count = 0
while time >= 1 :
time -= 1 # 무한루프를 막기 위해 time 감소
temp = s[count] # temp라는 임시 변수에 s[count]값을 저장 후, 값을 교환함
s[count] = s[-(count+1)] # 파이썬에서는 s[count], s[-(count+1)] = s[-(count+1), s[count]로 사용 가능하다고 함.]
s[-(count+1)] = temp
count += 1
''' Another Answer 1
def reverseString(self, s:List[str]) -> None:
left, right = 0, len(s) -1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
'''
''' Another Answer 2
def reverseString(self, s:List[str]) -> None:
s.reverse() # 파이썬 리스트의 메소드 reverse()를 이용
''' |
1235ad04057f91b827c57836083a2c87c5797a28 | rodrigojgrande/python-mundo | /desafios/desafio-097.py | 468 | 4 | 4 | #Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável.
# Ex: escreva(‘Olá, Mundo!’) Saída:
#~~~~~~~~~
#Olá, Mundo!
#~~~~~~~~~
def escreve(frase):
tamanho = (len(frase) + 4)
print('~' * tamanho)
print(f'{frase:^{tamanho}}')
print('~' * tamanho)
mensagem = str(input('Digite uma mensagem: '))
escreve(mensagem) |
75ab92954f109e3e28ea7d05970859a3811ddde2 | gene63/BaekJoonStep | /step1/9.py | 121 | 3.6875 | 4 | a, b = input().split()
a = int(a)
b = int(b)
print(str(a+b)+'\n'+str(a-b)+'\n'+str(a*b)+'\n'+str(int(a/b))+'\n'+str(a%b)) |
e5dffe9f0e4e37ba2bcf0fe78987183ecf1f2905 | lizwikhanyile/challenge2 | /dna_complementary.py | 862 | 4 | 4 |
### START FUNCTION
def dna_complementary(dna):
# define how key and values will be maped
maping = {'ins':'0'}
# A dictinary of links
dict_links = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
#We assume other letters or characters may exist
# other than 'ATGC' and we map them to single letters
for k,v in maping.items():
dna = dna.replace(k,v)
# store as a list
dna_letters = list(dna)
#reversing the list
dna_letters= reversed([dict_links.get(letter,letter) for letter in dna_letters])
dna_letters = ''.join(dna_letters)
for k,v in maping.items():
dna_letters = dna_letters.replace(v,k)
# returning the reversed string
return dna_letters[::-1]
### END FUNCTION
dna = "ATCTTATAATTACCGAGTCGATCGG"
print("Reverse Complement:")
print(dna_complementary(dna)) |
bd2f459186e85151205aece274f97169b5ce3615 | AndrejLiptak/schoolwork | /Python/class5.py | 1,822 | 3.671875 | 4 | def find_max(lst):
maximum = lst[0]
for value in lst:
if maximum < value:
maximum = value
print(maximum)
def find_min(lst):
minimum = lst[0]
for value in lst:
if minimum > value:
minimum = value
print(minimum)
def list_sum(lst):
total = 0
for value in lst:
total += value
print(total)
def nonzero_product(numbers):
product = 1
for value in numbers:
if value != 0:
product *= value
print(product)
def double_all(numbers):
for pos in range(len(numbers)):
numbers[pos] *= 2
print(numbers)
def create_double(numbers):
result = map(lambda x: x * 2, numbers)
print(list(result))
def linear_search(value, lst):
for val in lst:
if val == value:
return True
return False
def flatten(lists):
my_list = []
for lst in lists:
for value in lst:
my_list.append(value)
print(my_list)
def reverse_extended(string, ch, value):
return (ch * value).join(string[::-1])
def value(word):
word = word.upper()
values = []
for char in word:
values.append(ord(char) - ord('A') + 1)
return sum(values)
def ceasar(word, move):
word = word.upper()
cypher = ""
for char in word:
cypher += chr((((ord(char) + move) - ord('A')) % 26) + ord('A'))
return cypher
find_max([1, 2, 3, 4, 2, 3, 18, 1])
find_min([6, 7, 3, 2, ])
list_sum([2, 3, 1, 5])
nonzero_product([1, -2, 3, 0, 5])
create_double([1, 2, 3])
double_all([1, 2, 3])
print(linear_search(2, [1, 3, 2, 4]))
flatten([[1, 2, 3], [5, 1, 2], [4, 1]])
print(reverse_extended("hello", '#', 2))
print(value("hello"))
print(ceasar("Python", 2))
|
1e1208a3ce1c967cc98c9f3485242cf798c1cdca | techkids-c4e/c4e5 | /Vũ Đình Hưng/Lesson 4/Bài 1 phần 5.py | 294 | 4.1875 | 4 | from turtle import *
speed(0)
def draw_square(x, y):
color(y)
for a in range (4):
forward(x)
left(90)
square_length = float(input('What is the length of the square?: '))
square_color = input('What is the color of the square?: ')
draw_square(square_length, square_color)
|
42b5a11339851544418f71b3cd7e1ceb8ab46966 | dlcios/coding-py | /basic/def.py | 594 | 3.65625 | 4 | #coding: utf-8
# to16mod = hex
# n1 = to16mod(25)
# print(n1)
# #定义函数
# def mabs(num):
# if num > 0:
# return num
# else:
# return -num
# a = -15
# b = 15
# print(mabs(a), mabs(b))
# def power(x):
# return x * x
# print(power(a))
# def powern(x,y = 2):
# s = 1
# while y > 0:
# s = s * x
# y -= 1
# return s
# print(powern(2,1))
def add_append(l=None):
if l == None:
l = []
l.append('hello')
return l
print(add_append([1,2]))
print(add_append([3,4]))
print(add_append())
print(add_append())
|
ab457e196aca3eae49300e84606518350dea7120 | adailsom/arquiv | /loop.py | 119 | 3.96875 | 4 | a = 2
while a > 0:
print(a)
a -= 1
print('fim do while')
for x in range(-10):
if x % 2 == 0:
print(x) |
da3cde5fe0ebccf7df02602392fd1d0a5c17d6b8 | damoyaweb/Python | /CursoInical/tablasMultiplicarConFor.py | 161 | 3.734375 | 4 | table = int(input('Que tabla quieres ver: '))
mumeros = range(0,112)
for num in mumeros:
result = table * num
print(f'{table} X {num} = {result}')
|
3cf05f83acb236b10a0666298d39b1a940f139f6 | GauravRoy48/XGBoost | /xgboost_GR.py | 1,981 | 3.515625 | 4 | #####################################################################################
# Creator : Gaurav Roy
# Date : 22 May 2019
# Description : The code applies XGBoost on the Artificial Neural Network algorithm
# for the given dataset Churn_Modelling.csv.
#####################################################################################
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import Dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:,3:13].values
Y = dataset.iloc[:,13].values
# Categorical variables present as there are strings in X
# Encoding X categorical data + HotEncoding
# Encoding for the Gender Column
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
X[:,2] = le.fit_transform(X[:,2])
# Encoding for the Geography Column
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([('encoder', OneHotEncoder(), [1])], remainder='passthrough')
X = np.array(ct.fit_transform(X), dtype=np.float)
# Avoiding Dummy Variable Trap
X = X[:,1:]
# Splitting to Training and Test Set
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state= 0)
# Fitting XGBoost to the training set
from xgboost import XGBClassifier
classifier = XGBClassifier()
classifier.fit(X_train, Y_train)
# Making Predictions and Evaluating Model
# Predicting the Test Set Results
Y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test, Y_pred)
# Applying k-Fold Cross Validation where k=10
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator=classifier, X=X_train, y=Y_train, cv=10)
avg_accuracies = accuracies.mean()
std_accuracies = accuracies.std() |
4a4f79db929eb24d9a211fca329a9f6ce2478678 | VassarIgniteCS/intro_to_python | /lecture_3/activities/solutions/list_shuffle.py | 1,555 | 4.34375 | 4 | '''
==========================================================
LIST SHUFFLE
----------------------------------------------------------
Say we have two lists:
[1, 2, 3, 4, 5] and
['a', 'b', 'c', 'd', 'e']
If we interleaved them together they would look like:
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e']
Let's write a function that takes two lists of the same
length and shuffles them together!
=========================================================
'''
#takes in two equally length list and returns both list shuffled together
def list_shuffle(list1, list2):
shuffle = []
#for i from 0 to length of list1 - 1
for i in range(len(list1)):
#append an element from list1 and an element from list2
shuffle.append(list1[i])
shuffle.append(list2[i])
return shuffle
def list_shuffle2(list1, list2):
if len(list1) < len(list2):
#if the length of the first list is less than the second
#shuffle up to list1 then append the rest of list2
shuffle = list_shuffle(list1, list2[:len(list1)]) + list2[len(list1):]
elif len(list2) < len(list1):
#if the length of the first list is less than the second
#shuffle up to list2 then append the rest list1
shuffle = list_shuffle(list1[:len(list2)], list2) + list1[len(list2):]
else:
#else, just do the regular list_shuffle
shuffle = list_shuffle(list1, list2)
return shuffle
a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
print(list_shuffle(a, b))
a = [1, 2, 3, 4, 5, 6]
b = ['a', 'b', 'c']
print(list_shuffle2(a, b))
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd', 'e']
print(list_shuffle2(a, b)) |
700772fc7146da538c39c6db77a6b028967e6ea2 | lleonie/hackinscience | /exercises/025/solution.py | 193 | 3.78125 | 4 | import datetime
from datetime import time
date = datetime.date.today()
now = datetime.datetime.now().time()
heure = now.replace(microsecond=0)
print("Today is %s and it is %s" % (date, heure))
|
b596b0843e57375625daeacd6c857013644c75a9 | hariss0411/Python-Codes | /linked_list.py | 2,147 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linked_list:
def __init__(self):
self.start=None
def insert_start(self,new_node):
if self.start==None:
self.start=new_node
else:
(new_node.next,self.start)=(self.start,new_node)
#temp=self.start
#self.start=new_node
#new_node.next=temp
def insert_end(self,new_node):
if self.start==None:
self.start=new_node
else:
temp=self.start
while temp.next!=None:
temp=temp.next
temp.next=new_node
def insert_after(self,new_node):
if self.start==None:
print("List Empty")
else:
af_data=int(input("Enter Data after you have to insert:- "))
temp=self.start
while temp!=None and af_data!=temp.data:
temp=temp.next
if temp==None:
print(af_data,"Not Found")
else:
new_node.next=temp.next
temp.next=new_node
def display(self):
temp=self.start
if temp==None:
print("Empty")
return
while temp!=None:
print(temp.data)
temp=temp.next
link_list=Linked_list()
ch=1
while ch:
ch=int(input("0 for exit\t1 for Display\t2 for insert End\t3 for insert Start\t4 for insert After:= "))
switch={0:'break',
1:'link_list.display()',
2:'link_list.insert_end(Node(int(input("Enter Data:= "))))',
3:'link_list.insert_start(Node(int(input("Enter Data:= "))))',
4:'link_list.insert_after(Node(int(input("Enter Data:= "))))'}
eval(switch[ch])
'''if ch==1:
link_list.display()
elif ch==2:
link_list.insert_end(Node(int(input("Enter Data:= "))))
elif ch==3:
link_list.insert_start(Node(int(input("Enter Data:= "))))
elif ch==4:
link_list.insert_after(Node(int(input("Enter Data:= "))))'''
|
6b3a525a2356e997a8bdffbd4f52b89ce8804e28 | virakobrynchuk/Olimpiada | /6.2015.py | 138 | 3.609375 | 4 | from fractions import gcd
a, b = [int(i) for i in input().split()]
def lcm(a, b):
return abs(a*b) // gcd(a, b)
print(lcm(a, b))
|
02175cdb6fd8f861b2f8ff7561977c9f862244d0 | mwnickerson/python-crash-course | /chapter_9/dice.py | 895 | 4.3125 | 4 | # Dice
# Chapter 9 exercise 13
# Create a die with imported random module
from random import randint as r
class Die:
def __init__(self, sides=6):
"""initialize default dice side value"""
self.sides = sides
def roll_dice(self):
"""generate a number between 1 and number of sides"""
rolled_value = r(1, self.sides)
print(f"You rolled a {rolled_value}!")
# Rolling a six sided die 10 times
print("Rolling a Six-Sided Die!")
six_die = Die()
x = 0;
while (x < 10):
six_die.roll_dice()
x += 1
# Rolling a ten-sided die 10 times
print("\nRolling a Ten-Sided Die!")
ten_die = Die(10)
x = 0;
while (x < 10):
ten_die.roll_dice()
x += 1
# Rolling a 20 sided dice ten times
print("\nRolling a Twenty-Sided Die!")
twenty_die = Die(20)
x = 0;
while (x < 10):
twenty_die.roll_dice()
x += 1
print("finished rolling the dice!")
|
65a7a896c236f76859beccb888b869d2b100510e | SubuNayak/Python-Basic-Programs | /maxlist.py | 240 | 4.3125 | 4 | #Python program to find largest number in a list
def maxlist(arr):
return max(arr)
n = int(input("Enter the size of the array: "))
arr = []
arr = list(map(int,input('Enter the elements: ').strip().split()))[:n]
print(maxlist(arr)) |
dea1a298c4470fafb9ea4548bc432c24a3cdf522 | slawektestowy/bootcamping | /struktury_danych/petla_for.py | 638 | 3.703125 | 4 |
# ZADANIE: WYPISZ ILE JEST DANYCH ELEMNTOW (UJEMNYCH I DODATNICH0
# lista = [1,2,-3,4,5,6,-7,8,9]
#
# ile_d=0
# ile_u=0
#
# for i in lista:
# if i >0: # widze liczbe dodatnia
# ile_d +=1 # zwiekszam licznik dodatnich ile jest elementów
#
# for i in lista:
# if i <0: # widze liczbe ujemnych
# ile_u +=1 # zwiekszam licznik dodatnich
#
# print(f'Na liscie jest {ile_d} liczb dodatnich')
# print(f'Na liscie jest {ile_u} liczb ujemnych')
# minusy =lista.count(1)
# print(minusy)
ile_podz =0
for i in range(101):
if i % 3 == 0 or i % 5 ==0:
#ile_podz += 1
print(i)
ile_podz += 1
print(ile_podz) |
9d7b1c79a99c650cad7e2a7a727ea1dcbf119c0c | jishnujagadeeshpi/OS-Lab | /First Come First Serve Scheduling.py | 6,758 | 3.640625 | 4 |
'''
Write a program to implement FCFS scheduling with arrival time.
'''
from prettytable import PrettyTable
time = 0
processes = []
ID = 0
table = PrettyTable()
table.field_names = ["Process" , "Arrival Time" , "Burst Time" , "Completion Time" , "Turn-around Time" , "Waiting Time" ]
class Process:
def __init__(self,id,arrival,burst):
self.id = id
self.ArrivalTime = arrival
self.BurstTime = burst
self.CompletionTime = int()
self.TurnAroundTime = int()
self.WaitingTime = int()
def SetCompletionTime(self,time):
self.CompletionTime = time
def SetTurnAroundTime(self):
self.TurnAroundTime = self.CompletionTime - self.ArrivalTime
def SetWaitingTime(self):
self.WaitingTime = self.TurnAroundTime - self.BurstTime
def createProcess():
global ID,processes
ID += 1
id =ID
print(f'Process {ID}')
arrival = int(input(f'Enter the arrival time of the process {ID} :- '))
burst = int(input(f'Enter the burst time of the process {ID} :- '))
print()
p = Process(id,arrival,burst)
processes.append(p)
def sortProcesses():
global processes
processes.sort(key=(lambda x : x.ArrivalTime))
def print_table():
global processes,table
avgWaitingTime = sum(process.WaitingTime for process in processes) / len(processes)
avgTurnAroundTime = sum(process.TurnAroundTime for process in processes) / len(processes)
for process in processes:
table.add_row([
process.id,
process.ArrivalTime,
process.BurstTime,
process.CompletionTime,
process.TurnAroundTime,
process.WaitingTime,
])
print(table)
print("Average waiting time: " + str(format(avgWaitingTime, '.5f')))
print("Average turn-around time: " + str(format(avgTurnAroundTime, '.5f')))
def sortProcessesOnId():
global processes
processes.sort(key=lambda x: x.id)
def executeProcesses():
global processes, time
for process in processes:
if time < process.ArrivalTime:
time = process.ArrivalTime
time += process.BurstTime
process.SetCompletionTime(time)
process.SetTurnAroundTime()
process.SetWaitingTime()
def main():
print("\n Jishnu Jagadeesh P I \n")
N = int(input("Enter the number of processes: "))
print()
for i in range(N):
createProcess()
sortProcesses()
executeProcesses()
sortProcessesOnId()
print_table()
main()
'''
Sample 1:
Enter the number of processes: 3
Process 1
Enter the arrival time of the process 1 :- 0
Enter the burst time of the process 1 :- 5
Process 2
Enter the arrival time of the process 2 :- 3
Enter the burst time of the process 2 :- 9
Process 3
Enter the arrival time of the process 3 :- 6
Enter the burst time of the process 3 :- 6
+---------+--------------+------------+-----------------+------------------+--------------+
| Process | Arrival Time | Burst Time | Completion Time | Turn-around Time | Waiting Time |
+---------+--------------+------------+-----------------+------------------+--------------+
| 1 | 0 | 5 | 5 | 5 | 0 |
| 2 | 3 | 9 | 14 | 11 | 2 |
| 3 | 6 | 6 | 20 | 14 | 8 |
+---------+--------------+------------+-----------------+------------------+--------------+
Average waiting time: 3.33333
Average turn-around time: 10.00000
Sample 2:
Enter the number of processes: 4
Process 1
Enter the arrival time of the process 1 :- 0
Enter the burst time of the process 1 :- 2
Process 2
Enter the arrival time of the process 2 :- 1
Enter the burst time of the process 2 :- 2
Process 3
Enter the arrival time of the process 3 :- 5
Enter the burst time of the process 3 :- 3
Process 4
Enter the arrival time of the process 4 :- 6
Enter the burst time of the process 4 :- 4
+---------+--------------+------------+-----------------+------------------+--------------+
| Process | Arrival Time | Burst Time | Completion Time | Turn-around Time | Waiting Time |
+---------+--------------+------------+-----------------+------------------+--------------+
| 1 | 0 | 2 | 2 | 2 | 0 |
| 2 | 1 | 2 | 4 | 3 | 1 |
| 3 | 5 | 3 | 8 | 3 | 0 |
| 4 | 6 | 4 | 12 | 6 | 2 |
+---------+--------------+------------+-----------------+------------------+--------------+
Average waiting time: 0.75000
Average turn-around time: 3.50000
Sample 3:
Enter the number of processes: 5
Process 1
Enter the arrival time of the process 1 :- 2
Enter the burst time of the process 1 :- 2
Process 2
Enter the arrival time of the process 2 :- 0
Enter the burst time of the process 2 :- 1
Process 3
Enter the arrival time of the process 3 :- 2
Enter the burst time of the process 3 :- 3
Process 4
Enter the arrival time of the process 4 :- 3
Enter the burst time of the process 4 :- 5
Process 5
Enter the arrival time of the process 5 :- 4
Enter the burst time of the process 5 :- 4
+---------+--------------+------------+-----------------+------------------+--------------+
| Process | Arrival Time | Burst Time | Completion Time | Turn-around Time | Waiting Time |
+---------+--------------+------------+-----------------+------------------+--------------+
| 1 | 2 | 2 | 4 | 2 | 0 |
| 2 | 0 | 1 | 1 | 1 | 0 |
| 3 | 2 | 3 | 7 | 5 | 2 |
| 4 | 3 | 5 | 12 | 9 | 4 |
| 5 | 4 | 4 | 16 | 12 | 8 |
+---------+--------------+------------+-----------------+------------------+--------------+
Average waiting time: 2.80000
Average turn-around time: 5.80000
''' |
f959daa8292a10e590a46e4bec3eaed205d7cb98 | Usefulmaths/Linear-Regression | /ridge_regression.py | 1,633 | 3.53125 | 4 | import numpy as np
from linear_regression import LinearRegression
class RidgeRegression(LinearRegression):
def __init__(self, lambd):
super().__init__()
self.lambd = lambd
def fit(self, X, y, bias=True):
'''
Finds the parameters that minimises the
MSE + L2 norm of the data points to a straight line.
Arguments:
X: the features of the data points
y: the labels of the data points
bias: specify whether a bias should be used or not
Returns:
theta: the found parameters
'''
if bias:
bias = np.ones((X.shape[0], 1))
X = np.hstack([X, bias])
XT = X.T
XTX = np.dot(XT, X)
regularisation_term = self.lambd * np.identity(XTX.shape[0])
inverse_XTX = np.linalg.inv(XTX + regularisation_term)
inverse_XTX_XT = np.dot(inverse_XTX, XT)
theta = np.dot(inverse_XTX_XT, y)
self.theta = theta
return theta
def loss(self, y, y_hat):
'''
Calculates the L2 regularised loss between the predicted
labels and the true labels.
Arguments:
y: the true labels
y_hat: the predicted labels
Returns:
loss: the loss between the real and predicted labels
'''
number_of_points = y.shape[0]
residual = np.linalg.norm(y - y_hat)
regularisation_term = self.lambd * np.dot(self.theta.T, self.theta)[0, 0]
loss = 1. / number_of_points * residual + regularisation_term
return loss
|
37cc436e5a879d95ed038b63471fdb1600cfccee | ericohenrique/Udacity-DataScienceI | /Semana2/Semana2-Lesson2-25.py | 540 | 3.859375 | 4 | # Define a procedure, measure_udacity,
# that takes as its input a list of strings,
# and returns a number that is a count
# of the number of elements in the input
# list that start with the uppercase
# letter 'U'.
def measure_udacity(list):
count = 0
i=0
while i < len(list):
if list[i].find('U') == 0:
count = count + 1
i = i +1
else:
i = i +1
return count
print measure_udacity(['Dave','Sebastian','Katy'])
#>>> 0
print measure_udacity(['Umika','Umberto'])
#>>> 2
|
4d1c34ae5819b78b1115dd9ab988d72ba6c94c0f | sakshi303/CS50_web_programming | /lecture_python/functions.py | 93 | 3.8125 | 4 | def cube(n):
return n*n*n
for n in range(6):
print(f"the cube of {n} is {cube(n)}")
|
e1cd49e61627c3e3e73ff6d8a4b50dac2b2f625a | suryaraj93/LuminarPython | /FlowControls/Decisionmaking/Modulus.py | 117 | 4.0625 | 4 | num1=int(input("Enter number 1: "))
num2=int(input("Enter number 2: "))
modulus=(num1%num2)
print("result: ",modulus) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.