blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cbb2fde8488094dc64bec7d85d9d7190fd40ade8 | Haroldov/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/100-print_tebahpla.py | 128 | 3.6875 | 4 | #!/usr/bin/python3
for i in range(25, -1, -1):
if (i % 2 == 0):
i -= 32
print("{}".format(chr(i + 97)), end="")
|
55226d9380b4ba5cd0443751989462c98b7746ab | amirsaleem1990/python-practice-and-assignments | /area calculator.py | 937 | 4.09375 | 4 | # area calculator
a = True
while a:
print('\n***************************\nWelcome to Area Calculator\n***************************')
b = input('\nwhich shape you want to calulate? \n[sq]:\t for square\n[rec]:\t for rectriangle\n[cir]:\t for circle\n')
if b == 'sq':
d = int(input('\nEnter one side length: '))
print('\nyour square has area of '+str(d * d)+' '+ c+'s')
elif b == 'rec':
e = input('\nEnter lenght and hight seperated by space eg: 22 77 ')
g = e[:e.find(' ')]; h = e[e.find(' ') +1 :]
print('\nyour rectriange has area of '+str(int(g)*int(h)))
#elif b == 'cir':
#f = input('\nEnter daya meter for your sircle: ')
#pppppppppppppppppppppppppppppppppppppppppppppp
#print('sorry.. yet not circle ready')
else: continue
i = input('\nAre you want to calculate once more? \n[y/n] ')
if i == 'y': a = True
else: a = False
|
06c68836ebe35c6d909bbebd97c41887fb8d950e | CraneJen/Python-Learning | /Sort/InsertSort.py | 385 | 3.90625 | 4 | def insertsort(seq):
n = len(seq)
count = 0
for i in range(1, n):
key = seq[i]
j = i - 1
while j >= 0 and key < seq[j]:
seq[j + 1] = seq[j]
j -= 1
count += 1
seq[j + 1] = key
print(count)
return seq
if __name__ == '__main__':
seq = [9, 8, 7, 6, 5, 4, 3, 2, 1]
print(insertsort(seq))
|
4ffdd4f05f9fb9b7d9b0bd018b7a96cd99a73474 | PatrikoPy/MIW | /wprowadzenie02/cw5.py | 997 | 3.90625 | 4 | __all__ = ['Calculator']
class Calculator:
def add(self, *args):
current = 0
try:
for num in args:
current += float(num)
return current
except:
print("error")
def difference(self, a=0, b=0):
try:
return float(a) - float(b)
except:
print("error")
def multiply(self, *args):
current = 1
try:
for num in args:
current *= float(num)
return current
except:
print("error")
def divide(self, a=1, b=1):
try:
return float(a) / float(b)
except(ZeroDivisionError):
print("nie dziel przez zero...")
return 0
except:
print("error")
if __name__ == "__main__":
calc = Calculator()
print(calc.divide(8, 0))
print(calc.add(5, 7, 6, 9, 8, 5, 4, 7))
print(calc.multiply(8, 3, 6))
print(calc.difference(8, 9))
|
bd7dae154e92bb54eabec1528b9042bda5260241 | vijaykanth1729/python_material | /decorators/generators/gen.py | 264 | 3.921875 | 4 | def my_gen():
n=1
print("This is printed first:")
yield n
n+=1
print("This is printed second")
yield n
n+=1
print("This is printed third: ")
yield n
it = my_gen()
print(next(it))
print(next(it))
print(next(it))
print(next(it))
|
40086ce76a749680f8a203ea6bac439cca0c0fbf | Voolodimer/DevOps3_python | /hw5.py | 855 | 3.796875 | 4 | #!/usr/bin/python3
# 1. После запуска предлагает пользователю ввести неотрицательные целые числа,
# разделенные через пробел и ожидает ввода от пользователя.
# 2. Находит наименьшее положительное число, не входящее в данный пользователем
# список чисел и печатает его.
def hw5():
print('Введите список чисел: ')
input_list = sorted((int(x) for x in input().split()))
i = 0
# print(input_list)
min_num = input_list[0]
if min_num > 1:
return min_num - 1
while i <= len(input_list):
if min_num not in input_list:
return min_num
i += 1
min_num += 1
print(hw5())
|
20ce0ba6316450e7aee1e4a972f9e37787b4c5f7 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/1373.py | 1,241 | 3.5 | 4 | # -*- coding: utf-8 -*-
import sys
import os
import math
#input_text_path = __file__.replace('.py', '.txt')
#fd = os.open(input_text_path, os.O_RDONLY)
#os.dup2(fd, sys.stdin.fileno())
def flip(A, start_i, K):
for i in range(start_i, start_i + K):
if A[i] == '+':
A[i] = '-'
else:
A[i] = '+'
def solve(cakes, K):
flip_num = 0
# 左から+にしていく
index = 0
while True:
#print(cakes)
if cakes[index] == '+':
index += 1
else:
# ひっくり返す
flip(cakes, index, K)
flip_num += 1
index += 1
# 終端
if index > len(cakes) - K:
break
if cakes.count('+') == len(cakes):
return True, flip_num
else:
return False, None
f = open('submit.txt', 'w')
N = int(input())
for i in range(N):
lst = input().split()
cakes_str = lst[0]
cakes = list(cakes_str)
K = int(lst[1])
#print('Input', cakes_str, K)
solvable, num = solve(cakes, K)
if solvable:
s = 'Case #{}: {}\n'.format(i + 1, num)
f.write(s)
else:
s = 'Case #{}: {}\n'.format(i + 1, 'IMPOSSIBLE')
f.write(s)
f.close() |
ac0c3b1deb09163b99b68c7d57940fcd93feac29 | Biorrith/Software-Teknologi | /Older versions/Python server/client.py | 1,002 | 3.828125 | 4 | # Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 25
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server
print (s.recv(1024))
send_bytes = 'I see this as an absoloute success!\r\n'
send_bytes = send_bytes.encode()
s.sendall(send_bytes)
"""
print (s.recv(1024))
send_bytes = 'mail This is a test\r\n'
send_bytes = send_bytes.encode()
s.sendall(send_bytes)
print (s.recv(1024))
send_bytes = 'rcpt Daniel\r\n'
send_bytes = send_bytes.encode()
s.sendall(send_bytes)
# print (s.recv(1024))
# send_bytes = 'data idk what to type here \r\n'
# send_bytes = send_bytes.encode()
# s.sendall(send_bytes)
print (s.recv(1024))
send_bytes = 'quit\r\n'
send_bytes = send_bytes.encode()
s.sendall(send_bytes)
print (s.recv(1024))
"""
# close the connection
s.close()
#TODO: Make an actual client, man... |
de1aafdb2d37bff0630db9e539bcf80508756640 | raulmercadox/curso_python | /longestRun.py | 1,081 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 12:57:23 2019
@author: ezmerra
"""
def longestRun(L):
ancho = len(L)
if ancho == 0 or ancho == 1:
return ancho
anterior = None
contador = 0
maximo_ancho = 0
for i in L:
if anterior == None:
anterior = i
contador += 1
else:
if i >= anterior:
contador += 1
else:
if contador > maximo_ancho:
maximo_ancho = contador
contador = 1
anterior = i
if contador > maximo_ancho:
maximo_ancho = contador
return maximo_ancho
"""
assert longestRun([])==0
assert longestRun([2])==1
assert longestRun([1,2])==2
assert longestRun([2,1])==1
assert longestRun([1,2,1,2])==2
assert longestRun([1,2,3,1,2])==3
assert longestRun([1,2,2,3,1,2])==4
assert longestRun([1,2,1,2,2,3])==4
assert longestRun([1,2,1,2,2,3,6,7])==6
assert longestRun([1,2,1,2,2,3,1,7,8,8,9])==5
assert longestRun([1,2,1,2,2,3,5,1,7,8,8,9])==5
"""
|
635e7fb013185aa53b44b6e8d16d63b91b97e858 | jogubaba/PythonScripts | /22sed.py | 594 | 3.6875 | 4 | file = open('/home/jogubaba/Downloads/My List', 'r')
f_contents = file.readlines()
sn = open('/home/jogubaba/Downloads/servervmname', 'r')
contents = sn.readlines()
for f_contents in contents:
print(contents)
else:
print("Not in List")
#another
keywords = input("Please Enter keywords path as c:/example/ \n :")
keys = open((keywords), "r").readlines()
keys = keys.split(',') # separates key strings
with open("/home/jogubaba/Downloads/file2.txt") as f:
for line in f:
for key in keys:
if key.strip() in line:
print(line)
# another
|
8aa6c344747ebffdde38cdfe610a30d0075cc0d7 | TareqHasa/python_stack | /_python/python_fundamentals/functions_basic_II.py | 825 | 3.8125 | 4 | def count_down (num):
x=list()
for i in range(num,-1,-1):
x.append(i)
return x
print(count_down(5)) # 1
def print_and_return (arr):
print (arr[0])
return arr[1]
print_and_return([1,2])
def first_plus_length(arr):
return arr[0]+len(arr)
print (first_plus_length([1,2,3,4,5]))
def values_greater_than_second (arr):
print(len(arr))
count=0
newarr=list()
if len(arr)<2:
return False
for i in range (0,len(arr)-1,1):
if arr[i]>arr[i+1]:
count+=1
newarr.append(arr[i])
print(count)
return newarr
print(values_greater_than_second([5,2,3,2,1,4]))
def length_and_value(size,value):
x=[]
for i in range (0,size):
x.append(value)
return x
print(length_and_value(4,7))
print(length_and_value(6,2)) |
35891cca608d2ad6cd6da859fdc245163c20cfc9 | StraMil/Sorting-Algorithm-Visualization | /visualization.py | 5,267 | 3.65625 | 4 | import pygame
import sys
import random
import time
WIDTH = 1280
HEIGHT = 400
BLACK = pygame.Color(0, 0, 0)
num_bars = 20
bar_witdh = 800/num_bars
space = 400/num_bars
sorting = False
array = []
bars = []
cycles = 0
BLUE = (0, 0, 255)
# Initialize the pygame
pygame.init()
font = pygame.font.SysFont("Arial", 30)
clock = pygame.time.Clock()
# Create the screen
SCREEN = pygame.display.set_mode((WIDTH,HEIGHT))
# Set Background color
SCREEN.fill((255,255,255))
pygame.display.update()
def bubbleSort(bars):
sorting = False
cycles = 0
for i in range(len(bars)-1):
for j in range(0, len(bars)-1-i):
if bars[j] < bars[j + 1]:
bars[j], bars[j + 1] = bars[j + 1], bars[j]
#print(bars)
SCREEN.fill((255,255,255))
for k in range(len(bars)):
x = (k * bar_witdh) + (k * space) + (WIDTH - (num_bars * bar_witdh + num_bars * space))/2
if bars[k] is bars[j]:
red = 255
green = 130
blue = 80
last = k
else:
red = 0
blue = bars[k] * (-1)
green = 255 - blue
pygame.draw.rect(SCREEN, ((red, green, blue)), (x, 365, bar_witdh, bars[k]), 0, 6)
buttonSort("Sort", 105 + 30, 30, 75, 50, (230, 230, 230), (200, 200, 200))
buttonNewArray("New", 30, 30, 75, 50, (230, 230, 230), (200, 200, 200))
resetArray("Reset", 210 + 30, 30, 75, 50, (230, 230, 230), (200, 200, 200))
showNumOfCycles(cycles)
pygame.display.update()
#time.sleep(1)
cycles = cycles + 1
red = 0
blue = bars[last] * (-1)
green = 255 - blue
x = (last * bar_witdh) + (last * space) + (WIDTH - (num_bars * bar_witdh + num_bars * space))/2
pygame.draw.rect(SCREEN, ((red, green, blue)), (x, 365, bar_witdh, bars[last]), 0, 6)
pygame.display.update()
#print(last)
def getHeight(num_bars):
if num_bars <= 10:
return 25
if num_bars <= 25:
return 10
if num_bars <= 50:
return 5
if num_bars <= 100:
return 2.5
if num_bars <= 200:
return 1.25
else:
return 1
def buttonSort(msg, x, y, w, h, ic, ac):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
global sorting
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(SCREEN, ac, (x,y,w,h), 0)
if click[0] == 1:
sorting = True
else:
pygame.draw.rect(SCREEN, ic, (x, y, w, h), 0)
text = font.render(msg, True, (0, 0, 0))
SCREEN.blit(text, (x + 10, y + 10))
def buttonNewArray(msg, x, y, w, h, ic, ac):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(SCREEN, ac, (x,y,w,h), 0)
if click[0] == 1:
cycles = 0
SCREEN.fill((255,255,255))
bars.clear()
array.clear()
mulitplayer = getHeight(num_bars)
#print(mulitplayer)
for i in range(num_bars):
height = random.randint(-num_bars*mulitplayer, -1)
array.append(height)
#print(height)
x = (i * bar_witdh) + (i * space) + (WIDTH - (num_bars * bar_witdh + num_bars * space))/2
drawBar(x,height)
print("New", bars)
else:
pygame.draw.rect(SCREEN, ic, (x, y, w, h), 0)
text = font.render(msg, True, (0, 0, 0))
SCREEN.blit(text, (x + 10, y + 10))
def resetArray(msg, x, y, w, h, ic, ac):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
bars = []
sorting = False
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(SCREEN, ac, (x,y,w,h), 0)
bars = []
sorting = False
if click[0] == 1:
SCREEN.fill((255,255,255))
for i in range(num_bars):
x = (i * bar_witdh) + (i * space) + (WIDTH - (num_bars * bar_witdh + num_bars * space))/2
drawBar(x,array[i])
print("Reset", bars)
else:
pygame.draw.rect(SCREEN, ic, (x, y, w, h), 0)
text = font.render(msg, True, (0, 0, 0))
SCREEN.blit(text, (x + 10, y + 10))
def showNumOfCycles(cicles):
cicle = font.render("Cycles: " + str(cicles), True, (0,0,0))
SCREEN.blit(cicle, (1100, 30))
def drawBar(x,height):
blue = height * (-1)
green = 255-blue
pygame.draw.rect(SCREEN, (0,green,blue), (x, 365, bar_witdh, height), 0, 6)
if not sorting:
bars.append(height)
# Loop
while True:
buttonSort("Sort", 105 + 30, 30, 75, 50, (230, 230, 230), (200, 200, 200))
buttonNewArray("New", 30, 30, 75, 50, (230, 230, 230), (200, 200, 200))
resetArray("Reset", 210 + 30, 30, 75, 50, (230, 230, 230), (200, 200, 200))
pygame.display.update()
if sorting:
bubbleSort(bars)
sorting = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
|
ae123cd90ab8496f41452da98a30a0d935870ba9 | jgartsu12/my_python_learning | /python_data_structures/lists/sorted_fn.py | 490 | 4.1875 | 4 | # Guide to the sorted Function in Python
# using sorted() method
#sorted() allows u to store that new value in a new variable that stores that list and keeps original list stored
sale_prices = [
100,
83,
220,
40,
100,
400,
10,
1,
3
]
sorted_list = sorted(sale_prices, reverse=True) # sorted(argument_list, reverse order)
print(sorted_list) # prints [400, 220, 100, 100, 83, 40, 10, 3, 1] # can set sorted() with reverse in descending integer order
|
90fc5450b0c74dd0e006aad3dedb900e396a2ee6 | ivo-bass/SoftUni-Solutions | /programming_fundamentals/mid_exam_preparation/3_last_stop.py | 1,424 | 3.71875 | 4 | class Gallery:
def __init__(self, seq):
self.sequence = seq
def change(self, old, new):
if old in self.sequence:
index = self.sequence.index(old)
self.sequence[index] = new
def hide(self, num):
if num in self.sequence:
self.sequence.remove(num)
def switch(self, num1, num2):
if num1 in self.sequence and num2 in self.sequence:
index1, index2 = self.sequence.index(num1), self.sequence.index(num2)
self.sequence[index1], self.sequence[index2] = self.sequence[index2], self.sequence[index1]
def insert_p(self, index, num):
if index in range(len(self.sequence)):
self.sequence.insert(index + 1, num)
def reverse(self):
self.sequence = self.sequence[::-1]
def print_gallery(self):
print(" ".join(self.sequence))
def main():
gallery = Gallery(input().split())
data = input()
while not data == "END":
command = data.split()
action = command[0]
if action == "Change":
current_num, changed_num = command[1], command[2]
gallery.change(current_num, changed_num)
elif action == "Hide":
num = command[1]
gallery.hide(num)
elif action == "Switch":
num1, num2 = command[1], command[2]
gallery.switch(num1, num2)
elif action == "Insert":
index, num = command[1], command[2]
index = int(index)
gallery.insert_p(index, num)
elif action == "Reverse":
gallery.reverse()
data = input()
gallery.print_gallery()
if __name__ == '__main__':
main()
|
b2423910fd63360cbebbbbe88fa157a3567f2c16 | HIT-GH/EPN-CEC-Python | /Lab01-v03-20210625.py | 1,308 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 00:04:03 2021
@author: HendersonIturralde
Crear un código en el editor que asigna un valor flotante, lo coloca en
una variable llamada "x", e imprime el valor de la variable llamada "y".
Su tarea es completar el código para evaluar la siguiente expresión:
3x3 - 2x2 + 3x - 1
El resultado debe ser asignado a "y".
Datos de Muestra:
x = 0
x = 1
x = -1
Salida Esperada:
y = -1.0
y = 3.0
y = -9.0
"""
print("\n"*1, "EPN-CEC - Python Essentials")
print(" Laboratorio 01-v03")
print(" Evaluar Expresión", "\n"*1)
w = [0, 1, -1]
print(":"*15, "Opt 1",":"*15)
print(":"*4, "y = 3*x*3 - 2*x*2 + 3*x - 1",":"*4,"\n")
for n in w:
x = float(n)
print(f" x = {x}")
print(f" x Type = {type(x)}")
if x!=1:
y = float(3*x*3 - 2*x*2 + 3*x - 1)
print(f" y = {y}", "\n"*1)
else:
n = 3
y = float(n)
print(f" y = {y}", "\n"*1)
print(":"*15, "Opt 2",":"*15)
print(":"*3, "y = 3*x**3 - 2*x**2 + 3*x - 1",":"*3,"\n")
for n in w:
x = float(n)
print(f" x = {x}")
print(f" x Type = {type(x)}")
y = float(3*x**3 - 2*x**2 + 3*x - 1)
print(f" y = {y}", "\n"*1)
|
c632c57f8fe4fcd0502bd65119b6150c88550a74 | ScarletMcLearn/student_data_facebook | /collocation.py | 1,155 | 3.8125 | 4 | import nltk
from nltk.collocations import *
#count single word frequency
f = open('aamir.txt')
raw = f.read()
tokens = nltk.word_tokenize(raw)
#Create your bigrams
#bgs = nltk.bigrams(tokens)
#compute frequency distribution for all the words in the text
fdist = nltk.FreqDist(tokens)
for k,v in fdist.items():
if v>=3:
print(k,v)
print('\n')
#bigram and trigram count
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()
# change this to read in your data
finder = BigramCollocationFinder.from_words(
nltk.corpus.genesis.words('aamir.txt'))
finder1 = TrigramCollocationFinder.from_words(nltk.corpus.genesis.words('aamir.txt'))
# only bigrams that appear 3+ times
finder.apply_freq_filter(2)
finder1.apply_freq_filter(1)
# return the 10 n-grams with the highest PMI
token = finder.nbest(bigram_measures.pmi, 10)
token1 = finder1.nbest(trigram_measures.pmi, 10)
#print(finder.ngram_fd.viewitems())
for item in token:
print(item)
#print(token.count(item))
#for k,v in finder.ngram_fd.items():
#print(k,v)
print('\n')
for item in token1:
print(item)
#print(token2) |
eb977e6ec1c57016fd533839d883bb50bd624c34 | WeslySantos07/QUEST-ES-OBI | /areadacircuferencia.py | 79 | 4 | 4 | r = float(input())
pi = 3.1416
res = (r**2)*pi
print("{:.2f}".format(res))
|
3a60dfbf0c81af500067303ca10e4306eb7d1556 | LiamTyler/AStarTesting | /src/AStar.py | 3,592 | 3.703125 | 4 | import math
class Cell:
def __init__(self, r = 0, c = 0):
self.f = 0
self.g = 0
self.h = 0
self.row = r
self.col = c
self.parent = None
def __eq__(self, other):
return self.row == other.row and self.col == other.col
def __str__(self):
return "Cell: f = " + str(self.f) + ", r = " + \
str(self.row) + ", c = " + str(self.col)
def __repr__(self):
return self.__str__()
# Manhattan heuristic
def heuristic(start, goal):
return abs(goal.row - start.row) + abs(goal.col - start.col)
# Shitty linear search to fin the lowest F cost cell
def getLowestCost(olist):
lowestIndex = 0
for i in range(1, len(olist)):
if olist[i].f < olist[lowestIndex].f:
lowestIndex = i
return lowestIndex
def isValidAndNotAWall(node, grid):
w = len(grid[0])
h = len(grid)
if 0 <= node.col and node.col < w:
if 0 <= node.row and node.row < h:
if grid[node.row][node.col] != 'W':
return True
return False
def getNeighbors(node, grid):
r = node.row
c = node.col
potential = [Cell(r-1,c),Cell(r+1,c),Cell(r,c-1),Cell(r,c+1)]
neighbors = [cell for cell in potential if isValidAndNotAWall(cell, grid)]
for n in neighbors:
n.g = node.g + .5*grid[node.row][node.col] + .5*grid[n.row][n.col]
n.parent = node
return neighbors
def construct_path(node):
path = [node]
while node.parent:
node = node.parent
path = [node] + path
return path
def print_path(path):
for x in path:
print(x.row, " ", x.col)
def AStar(start, goal, grid):
open_list = [start]
closed_list = []
start.g = 0
start.f = start.g + heuristic(start, goal)
while open_list != []:
index = getLowestCost(open_list)
current = open_list[index]
if current == goal:
return current
open_list = open_list[:index] + open_list[index+1:]
closed_list.append(current)
neighbors = getNeighbors(current, grid)
#print("neighbors: ", neighbors)
#input()
for neighbor in neighbors:
if neighbor not in closed_list:
neighbor.f = neighbor.g + heuristic(neighbor, goal)
if neighbor not in open_list:
open_list.append(neighbor)
else:
open_neighbor = open_list[open_list.index(neighbor)]
if neighbor.g < open_neighbor.g:
open_neighbor.g = neighbor.g
open_neighbor.parent = neighbor.parent
return None
def gridVal(char):
if char == 'S':
return 'S'
elif char == 'F':
return 'F'
elif char == 'W':
return 'W'
else:
return int(char)
fname = "../maps/map2.txt"
w = 0
h = 0
grid = None
start = None
finish = None
with open(fname) as fp:
w, h = [int(x) for x in next(fp).strip().split()]
grid = [[gridVal(x) for x in line.strip()] for line in fp]
for r in range(h):
for c in range(w):
if grid[r][c] == 'S':
start = Cell(r, c)
grid[r][c] = 1
elif grid[r][c] == 'F':
finish = Cell(r, c)
grid[r][c] = 1
for r in range(h):
for c in range(w):
print(grid[r][c], end=' ')
print()
ret = AStar(start, finish, grid)
if ret:
print("path found")
path = construct_path(ret)
print_path(path)
else:
print("no possible path")
|
547380b3a0fdf94205010cbd5325c091db82e0e6 | Vampirskiy/helloworld | /venv/Scripts/Урок3/step2_input.py | 1,215 | 3.703125 | 4 | import random
number = random.randint(1, 100)
#print(number)
user_number = None
levels = {1 : 10, 2 : 5, 3 : 3}
level = int(input('Введите уровень сложности от 1 до 3'))
count = 0
max_count = levels[level]
user_count = int(input('Введите количество пользователей'))
users = []
for i in range(user_count):
user_name = input(f'Введите имя пользователя {i+1}')
users.append(user_name)
is_vinner = False
vinner_name = None
while not is_vinner:
count += 1
if count > max_count:
print('Вы дибилы!')
break
print(f'Попытка номер {count}')
for user in users:
print(f'Ход пользователя {user}: ')
user_number = int(input('Введите число от 1 до 100'))
if user_number == number:
is_vinner = True
vinner_name = user
break
elif number < user_number:
print('Введенное число больше загаданного')
else:
print('Введенное число меньше загаданного')
else:
print(f'Победитель {vinner_name}') |
70a9a1f6d75cbf949fccb3054ba5a912b58fcd33 | juriansluiman/AdventOfCode2019 | /3.py | 1,760 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
### Advent of Code 2019, Day 3
f = open('3.txt', 'r')
c = f.readlines()
wire1 = c[0].rstrip('\n').split(',')
wire2 = c[1].split(',')
def createPath(wire):
path = []
pos = (0,0)
for i in wire:
direction = i[0]
steps = int(i[1:])
if direction == 'U':
for j in range(steps):
pos = (pos[0], pos[1]+1)
path.append(pos)
elif direction == 'D':
for j in range(steps):
pos = (pos[0], pos[1]-1)
path.append(pos)
elif direction == 'L':
for j in range(steps):
pos = (pos[0]-1, pos[1])
path.append(pos)
elif direction == 'R':
for j in range(steps):
pos = (pos[0]+1, pos[1])
path.append(pos)
return path
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
def getClosestCross(crosses):
minDist = 0
minCross = 0
for cross in crosses:
dist = abs(cross[0]) + abs(cross[1])
if minDist == 0 or dist < minDist:
minDist = dist
minCross = cross
return (minDist, minCross)
path1 = createPath(wire1)
path2 = createPath(wire2)
crosses = intersection(path1, path2)
minimal = getClosestCross(crosses)
print('Part 1', minimal[0])
# 352
def findPathLengths(crosses, path1, path2):
minimum = 0
for cross in crosses:
steps1 = path1.index(cross) + 1
steps2 = path2.index(cross) + 1
steps = steps1 + steps2
if minimum == 0 or steps < minimum:
minimum = steps
return minimum
minimum = findPathLengths(crosses, path1, path2)
print('Part 2', minimum)
# 43848 |
033f42f6352769d21c80e20d5f9bbd6f7557b146 | SensenLiu123/Lintcode | /223.py | 1,313 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: A ListNode.
@return: A boolean.
"""
def isPalindrome(self, head):
if head is None:
return True
mid = self.find_middle(head)
# middle 重新指针到链表尾巴,逆链表!
mid.next = self.reverse(mid.next)
node1, node2 = head, mid.next
while node2:
if node1.val != node2.val:
return False
node1 = node1.next
node2 = node2.next
return True
def find_middle(self, head):
slow, fast = head, head.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
def reverse(self, head):
prev = None
node = head
while node:
future = node.next
node.next = prev
prev = node
node = future
return prev
|
e33dfb6488fbd637355a5308b2ed2c04bb280329 | mattryanharris/CIS7---Discrete-Structures | /Assignments/Due 09-25-2017/Assignment 8 Answers.py | 1,071 | 4.03125 | 4 | import math
def squareChecker(number):
status = False
simplifiedN = math.sqrt(number)
if (number % simplifiedN) == 0 :
return True
else:
return False
def guessGame(number):
test = 0
for x in xrange(1, number + 1):
if squareChecker(x) == True:
test = test + 1
return test
def guessPrompt(number):
while True:
attempt = raw_input("\nHow many prime numbers are between 1 and " + str(number) + ": ")
try:
if attempt == 'q':
print("\nProgram Ended\n")
exit()
number = int(attempt)
return number
break
except ValueError:
print("\nThat's not a valid option! Enter a number!\n")
def main():
number = input("\nEnter a number: ")
result = guessGame(number)
userPrompt = guessPrompt(number)
if(userPrompt > result):
print("\nYou chose a number too high!\n")
elif(userPrompt < result):
print("\nYou chose a number too low!\n")
elif(userPrompt == result):
print("\nCongrats! You chose the right number!\n")
print("There are " + str(result) + " prime numbers in between 1 and " + str(number) + "\n")
main()
|
a696d12cb940545d3348ed2bd9ac74cc7006776d | sunfinite/siri | /getwords.py | 3,221 | 3.578125 | 4 | #!/usr/bin/python
#Filename:check.py
from BeautifulSoup import BeautifulSoup
import codecs
from strip import gettext
import HTMLParser
import os
import pickle
#Function for cases where the punctuations and the words are not separated by spaces.
def checkpunct(string):
if(len(string)!=0):
j=-1#for punctuations at the end of the word...eg:what????
temp=string[j]
while(not(repr(temp)>="u'\u0c82'" and repr(temp)<="u'\u0cef'")):
j-=1
if(j==-(len(string)+1)):
return
temp=string[j]
j+=1#slicing does not include the last character
k=0
temp=string[k]
while(not(repr(temp)>="u'\u0c82'" and repr(temp)<="u'\u0cef'") ): #for punctuations at the beginning ....kindalikethis
k+=1
temp=string[k]
if(j==0):
string=string[k:]#Slicing out the punctuation marks
else:
string=string[k:j]
j=0
temp=string[j]#But,punctuations can be in the middle without spaces,can't they?
while(repr(temp)>="u'\u0c82'" and repr(temp)<="u'\u0cef'"):
j+=1#Keep going till you find the first punctuation
if(j==len(string)):
break
temp=string[j]
str1=string[:j] #Slice till the first punctuation
wordfrequency(str1) #Put the first slice in the dictionary
str2=string[(j+1):]#The second slice may still contain punctuations Eg:F.R.I.E.N.D.S.
checkpunct(str2)#Recursively call for the second slice
#Function to build dictionary
def wordfrequency(temp):
if not wordlist.has_key(temp):#Simple dictionary operations
wordlist[temp]=1
else:
wordlist[temp]+=1
wordlist={}
wordcount=0
flag=False
proceed=False
urltable=[]
wordtable=[]
freqtable=[]
path='dataset/'
#fout1=codecs.open("urltable","w","UTF-8")
#fout2=codecs.open("wordtable","w","UTF-8")
#fout3=codecs.open("freqtable","w","UTF-8")
fout1=file("urltable","w")
fout2=file("wordtable","w")
fout3=file("freqtable","w")
sites=os.listdir(path)
for site in sites:
sitepath=os.path.join(path,site)
urls=os.listdir(sitepath)
for url in urls:
if url not in urltable:
urltable.append(url)
urlpath=os.path.join(sitepath,url)
soup=BeautifulSoup(file(urlpath))
string=gettext(soup)
h=HTMLParser.HTMLParser()
string=h.unescape(string)#Convert all HTML entities to Unicode.
words=string.split()
for word in words:
for char in word:
if(repr(char)>="u'\u0cac'" and repr(char)<="u'\u0cef'"):
proceed=True
if proceed==True:
proceed=False
if(not word.isalnum() and len(word)>1):
for char in word:
if((not(repr(char)>="u'\u0c82'" and repr(char)<="u'\u0cef'")) and (not char.isalnum())):
flag=True
if flag==True:
checkpunct(word)
flag=False
else:
wordfrequency(word)
else:
wordfrequency(word)
for word,frequency in wordlist.items():
if word not in wordtable:
print word
wordtable.append(word)
temp=[]
temp.append(wordtable.index(word))
temp.append(urltable.index(url))
temp.append(frequency)
freqtable.append(temp)
|
0f1ef240e3e58a530379029e4adfb6ec977bc594 | Luis-Otavio-Araujo/Curso-de-Python | /PhythonExercicios/ex031.py | 269 | 3.828125 | 4 | distancia = float(input('São quantos Km de viagem? :'))
if distancia <= 200:
distancia = distancia * 0.50
print('Você deverá pagar R${:.2f}'.format(distancia))
else:
distancia = distancia * 0.45
print('Você deverá pagar R${:.2f}'.format(distancia)) |
f45f52a39101e0446c0f32f8bc8ea9aac33efd47 | nagkom/MathWithPython | /chapter3_statistics/readingdata/reading_csv_corr_scatter.py | 1,767 | 3.546875 | 4 | # data based on:
# https://www.google.com/trends/correlate/search?e=summer&e=swimming+lessons&t=weekly&p=us
import matplotlib.pyplot as plt
import csv
def read_csv(filename):
with open(filename) as f:
reader =csv.reader(f)
next(reader)
summer = []
highest_correlated = []
for row in reader:
summer.append(float(row[1]))
highest_correlated.append(float(row[2]))
return summer, highest_correlated
def find_corr_x_y(x, y):
n = len(x)
# Find the sum of the products
prod = []
for xi, yi in zip(x, y):
prod.append(xi * yi)
sum_prod_x_y = sum(prod)
sum_x = sum(x)
sum_y = sum(y)
squared_sum_x = sum_x ** 2
squared_sum_y = sum_y ** 2
x_square = []
for xi in x:
x_square.append(xi ** 2)
# Find the sum
x_square_sum = sum(x_square)
y_square = []
for yi in y:
y_square.append(yi ** 2)
# Find the sum
y_square_sum = sum(y_square)
# Use formula to calculate correlation
numerator = n * sum_prod_x_y - sum_x * sum_y
denominator_term1 = n * x_square_sum - squared_sum_x
denominator_term2 = n * y_square_sum - squared_sum_y
denominator = (denominator_term1 * denominator_term2) ** 0.5
correlation = numerator / denominator
return correlation
def scatter_plot(x,y):
plt.scatter(x,y)
plt.xlabel('summer')
plt.ylabel('swimming lessons')
plt.show()
if __name__ == '__main__':
summer, highest_correlated = read_csv('correlate-summer.csv')
corr = find_corr_x_y(summer, highest_correlated)
print('Highest correlation: {0}' .format(corr))
scatter_plot(summer, highest_correlated)
|
dbb1d47756bdd222cb8a056b0125c623bf0a545e | JMosqueraM/algoritmos_y_programacion | /taller_estructuras_de_control_selectivas/ejercicio_6.py | 1,167 | 3.859375 | 4 | # Segun el numero de 4 digitos (entero y positivo) conformado por A, B, C, y D (de la forma ABCD).
# Redondee el numero a la centecima mas cercana
A = int(input("digite el valor A: "))
B = int(input("digite el valor B: "))
C = int(input("digite el valor C: "))
D = int(input("digite el valor D: "))
# Redondear el valor de la variable de la unidad
if D > 5:
C += 1
# Redondear el valor de la variable de decima
if C > 5:
B += 1
# Redondear el valor de la variable de centecima
if B > 5:
A += 1
# Convertir los digitos de las variables en cadenas para crear el numero
A = str(A)
B = str(B)
C = str(C)
D = str(D)
# Creacion del numero sumando los caracteres de las variables A, B, C, y D
num = A + B + C + D
# Redondeo final al numero si en el proceso anterior de redondeo el numero terminaba constando de mas de 4 digitos
if len(num) > 4:
B = str(int(B) * 0)
C = str(int(C) * 0)
D = str(int(D) * 0)
num = A + B + C + D
# Redondeo final al numero si en el proceso anterior de rendonde el numero terminaba constando mas de 3 digitos
elif len(num) > 3:
C = str(int(C) * 0)
D = str(int(D) * 0)
num = A + B + C + D
print(num)
|
d643ebc986e97e453175ef14130356bc994f2003 | CatharticPotatoz/python-projects | /mudd/functions/testpg3.py | 1,639 | 3.609375 | 4 |
last_in = ""
health = 20
fortitude = 5
intellect = 7
agillity = 7
charisma = 7
armor = 5
##########################################################################################
grassy_noll = ("your surouded by thickets of grass that stretch out as far as you can see in any direction. out in the distance you can see a house in the opposite direction you see a single tree. the rest of the field seems eirily empty.")
###################################################################################################
def look_room():
global last_in
if last_in == "look" or last_in == "look around":
print(room)
def stndrdprmt():
global last_in
last_in = input("what would you like to do?")
inventory = ["pocketlint", " a pocket", "nothing"]
def check_constant():
if last_in == "stats":
print(health + "" + fortitude + "" + intellect + "" + agillity + "" + charisma + "" + armor)
elif last_in == "inventory":
print(inventory)
def chk_last_in():
return last_in == "stats" or last_in == "inventory"
#def Master_temp():
while True:
stndrdprmt()
if chk_last_in():
check_constant()
#else
room = grassy_noll
while True:
stndrdprmt()
if chk_last_in():
check_constant()
else:
print("you " + last_in + ". after " +last_in + "ing for hours you grow weary and decide to take a nap.")
break
print("you wake up from your nap feeling rejuvinated + 1 to health and + 1 to intellect")
#health + 1 = health
#intellect + 1 = intellect
Master_temp()
|
4fd9d34c89cbbae4c5ee25fa0d9262644246805e | Sevendeadlys/leetcode | /321/maxNumber.py | 2,322 | 4.1875 | 4 | '''
To create the max number from num1 and nums2 with k elements,
we assume the final result combined by i numbers (denotes as left)
from num1 and j numbers (denotes as right) from nums2, where i+j==k.
Obviously, left and right must be the maximum possible number in num1 and num2 respectively.
i.e. num1 = [6,5,7,1] and i == 2, then left must be [7,1].
The final result is the maximum possible merge of all left and right.
So there're 3 steps:
iterate i from 0 to k.
find max number from num1, num2 by select i , k-i numbers, denotes as left, right
find max merge of left, right
function maxSingleNumber select i elements from num1 that is maximum.
The idea find the max number one by one. i.e. assume nums [6,5,7,1,4,2], selects = 3.
1st digit: find max digit in [6,5,7,1], the last two digits [4, 2] can not be selected at this moment.
2nd digits: find max digit in [1,4], since we have already selects 7, we should consider elements after it,
also, we should leave one element out. 3rd digits: only one left [2], we select it. and function output [7,4,2]
function mergeMax find the maximum combination of left, and right.
'''
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
n,m = len(nums1),len(nums2)
ans = []
for i in range(k+1):
j = k - i
if i > n or j > m: continue
str1 = self.maxSingleStr(nums1,i)
str2 = self.maxSingleStr(nums2,j)
ans = max(ans,self.mergeStr(str1,str2))
return ans
@staticmethod
def mergeStr(nums1,nums2):
ret = []
while nums1 or nums2:
if nums1 > nums2:
ret.append(nums1[0])
nums1 = nums1[1:]
else:
ret.append(nums2[0])
nums2 = nums2[1:]
return ret
@staticmethod
def maxSingleStr(nums,part):
n = len(nums)
ret = [-1]
if part > n: return nums
while part > 0:
start = ret[-1] + 1
end = n - part + 1
ret.append(max(range(start,end),key=nums.__getitem__))
part -= 1
ret = [nums[i] for i in ret[1:]]
return ret
|
a8e70ab881a45bbae1462cd26a0611bb6ceb2a26 | AndyTian-Devops/PythonSample | /FunctionAndParameter.py | 1,290 | 4 | 4 | # Chapter Six: Function and parameter
##def lookup(data,lable,name):
## return data[lable].get(name)
##
##def store(data, full_name):
## names = full_name.split()
## if len(names) == 2: names.insert(1,'')
## labels = 'first', 'middle', 'last'
##for label, name in zip(labels, names):
## people = lookup(data, label,name)
## if people:
## people.append(full_name)
## else:
## data[label][name] = [full_name]
def story(**kwds):
return 'Once upon a time, there was a %(job)s called %(name)s' % kwds
def power(x,y,*others):
if others:
print ('Received redundant parameters:',others)
return pow(x,y)
def interval(start, stop=None,step=1):
'Imitates range() for step > 0'
if stop is None:
start, stop = 0, start
result = []
i = start
while i < stop:
result.append(i)
i += step
return result
print (story(job='king', name = 'Gumby'))
print (story(name='Sir Robin', job='brave knight'))
params = {'job':'lanange', 'name':'Python'}
print (story(**params))
del params['job']
print (story(job='stroke of genius', **params))
print (power(2,3))
print (power(3,2))
print (power(y=3,x=2))
powerparams = (5,)*2
print (power(*powerparams))
print(power(3,3,'Hello, World!'))
print(interval(10))
|
28d96881b4accbce52f985ecb61a59b043cd656a | ebegeti/LeetCode-problems | /question1_7.py | 812 | 3.875 | 4 | #Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
from chapter1_arrays_strings import AssortedMethods
def setZeros(matrix):
rows=[0 for i in range(0,len(matrix))]
cols=[0 for i in range(0,len(matrix[0]))]
for row in range(0,len(matrix)):
for col in range(0,len(matrix[0])):
if matrix[row][col]==0:
rows[row]=1
cols[col]=1
for row in range(0,len(matrix)):
for col in range(0,len(matrix[0])):
if (rows[row]==1 or cols[col]==1):
matrix[row][col]=0
return matrix
# driver code
if __name__ == "__main__":
matrix=AssortedMethods.AssortedMethods()
matrix=matrix.setRandomMatrix(10,4,5)
print(matrix,'\n\n')
print(setZeros(matrix))
|
582b8217362a026537300c472b6d451f6cc586a5 | JiazaiWu/ForPython | /hello/object.py | 1,120 | 3.5625 | 4 | # hello.py
# -*- coding: utf-8 -*-
import types
#stduent is extended from object
class student(object):
def __init__(self, name, score):
#__member can not be seen out of class
self.__name = name
self.score = score
def print_stu_score(self):
print '%s get %s' %(self.__name, self.score)
bart = student('jiazai', 90)
bart.print_stu_score()
#print bart.__name <---build break
print bart.score
class Animal(object):
def run(self):
print 'An animal is running!'
class Cat(Animal):
pass
class Dog(Animal):
def run(self):
print 'A dog is running!'
cat = Cat()
cat.run()
dog = Dog()
dog.run()
print isinstance(cat, Cat)
def run_twice(animal):
animal.run()
animal.run()
run_twice(dog)
print type(123) == types.IntType
print type(dog) == Dog
#'type()' is strict type check
print type(dog) == Animal#this is false!!
#use isinstance to check extend relation ship
print isinstance(dog, Animal)#this is true!!
print hasattr(dog, 'y')
setattr(dog, 'y', 19)
print hasattr(dog, 'y')
print 'dog y attr is', dog.y
#yes!!!
print hasattr(dog, 'run')
print hasattr(dog.run, '__call__')
print callable(dog.run) |
4c7a3c5a134547e26998ad588eebf6d2470fa6ba | krytech/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | 448 | 3.78125 | 4 | #!/usr/bin/python3
"""
A suqare class which inherits properties from the subclass
rectangle and the parent class BaseGeometry
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
""" New square class that inherits properties from Rectangle """
def __init__(self, size):
""" initializes size """
self.integer_validator("size", size)
super().__init__(size, size)
self.__size = size
|
fdca639463e3d522bac478521cd633cb3a57dc28 | Kalo7o/VUTP-Python | /exercise_02/08.Positive_negative_zero.py | 177 | 4.21875 | 4 | n = int(input('Enter a number: '))
if n > 0:
print('The number is positive.')
if n < 0:
print('The number is negative.')
if n == 0:
print('The number is zero.')
|
138fffc8f6ac1f065a1799f45bb8bfbeed9b9ade | knightrohit/monthly_challenges | /leetcode_aug_2020/12_pascal_triangle.py | 602 | 3.71875 | 4 | """
Time/Space Complexity = O(K**2)
"""
# Dynamic Programming
# Bottom Up Approach
from functools import lru_cache
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
out = [1]
if rowIndex == 0:
return out
@lru_cache(None)
def search(row, col):
if row == col or col == 0:
return 1
return search(row - 1, col - 1) + search(row - 1, col)
for i in range(1, rowIndex):
out.append(search(rowIndex, i))
out.append(1)
return out |
df3f06459e1043e8cc5510005c20f4dd7cb3f799 | sharondevs/DL | /Image_Denoising/image_denoising.py | 4,134 | 3.625 | 4 | ## Denoising gray scale images using Auto Encoders
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as snb
""" The label translation is as follows:
0 - T-Shirt
1 - Trouser
2 - Pullover
3 - Dress
4 - Coat
5 - Sandal
6 - Shirt
7 - Sneaker
8 - bag
9 - Ankle boot
"""
## We load the dataset for the images to be obtained in grey scale
(X_train,y_train), (X_test,y_test) = tf.keras.datasets.fashion_mnist.load_data()
# For sanity checking the image obtained,we plot the image
plt.imshow(X_train[0], cmap='gray')
## Now to perform the visualization
i = random.randint(1,60000) # Produces a random number between 1 and 60000
plt.imshow(X_train[i], cmap = 'gray')
label = y_train[i]
# To do mroe visualization, we need to view the images in a grid of 15x15
W_grid = 10
L_grid = 10
fig , axes = plt.subplots(L_grid, W_grid, figsize = (17,17)) # This gives the subplot for the images
axes = axes.ravel() # This expands the 15x15 into 225 element list
n_training = len(X_train)
for i in np.arange(0, W_grid*L_grid):
index = np.random.randint(0, n_training) # We initialize random interger for indexign out of the training set
axes[i].imshow(X_train[index]) # the axes array of objects of the subplot class can be instantitated with the images
axes[i].set_title(y_train[index],fontsize = 8) # We set the title for the figures of the subplot on each figure
axes[i].axis('off')
## Data Preprocessing
# We need to normaliza the data
X_train = X_train/255 # Due to the grey scale images
X_test = X_test/255
# Now, to add the noise
noise_factor = 0.3
noise_dataset = []
for img in X_train:
noisy_image = img + noise_factor * np.random.randn(*img.shape)
noisy_image = np.clip(noisy_image, 0,1)
noise_dataset.append(noisy_image)
noise_dataset = np.array(noise_dataset)
# So to test the image obtained
plt.imshow(noise_dataset[22],cmap = 'gray')
# Now to add the noise to the testing data
noise_factor = 0.1
noise_test_dataset = []
for img in X_test:
noisy_image = img + noise_factor * np.random.randn(*img.shape)
noisy_image = np.clip(noisy_image, 0,1)
noise_test_dataset.append(noisy_image)
noise_test_dataset = np.array(noise_test_dataset)
## Building the Autoencoder
autoencoder = tf.keras.Sequential()
# Encoder
autoencoder.add(tf.keras.layers.Conv2D(filters = 16, kernel_size=3,strides = 2,padding = 'same', input_shape=(28,28,1) ))
autoencoder.add(tf.keras.layers.Conv2D(filters = 8, kernel_size=3,strides = 2,padding = 'same'))
autoencoder.add(tf.keras.layers.Conv2D(filters = 8, kernel_size=3,strides = 1,padding = 'same'))
# Decoder
autoencoder.add(tf.keras.layers.Conv2DTranspose(filters = 16, kernel_size=3,strides = 2,padding = 'same'))
autoencoder.add(tf.keras.layers.Conv2DTranspose(filters = 1, kernel_size=3,strides = 2,padding = 'same', activation = 'sigmoid'))
autoencoder.compile(loss='binary_crossentropy', optimizer = tf.keras.optimizers.Adam(lr=0.001))
autoencoder.summary()
## Now to fit the data for training the model
# I have trained the data for an epoch of 10
autoencoder.fit(noise_dataset.reshape(-1,28,28,1),
X_train.reshape(-1,28,28,1),
epochs = 100,
batch_size = 200,
validation_data = (noise_test_dataset.reshape(-1,28,28,1), X_test.reshape(-1,28,28,1)) )
## Evaluating the model
evaluation = autoencoder.evaluate(noise_test_dataset.reshape(-1,28,28,1),X_test.reshape(-1,28,28,1))
print('Test Accuracy : {:.3f}'.format(evaluation))
## Prediction of images to generate clear images
predicted = autoencoder.predict(noise_test_dataset[:10].reshape(-1,28,28,1))
## Visualization of the Generated predicted images
fig , axes = plt.subplots(2,10,sharex=True,sharey=True,figsize=(20,4))
for images,row in zip([noise_test_dataset[:10],predicted],axes):
for img,ax in zip(images,row):
ax.imshow(img.reshape((28,28)),cmap = 'Greys_r')
ax.get_xaxis().set_visible(False)
ax.get_xaxis().set_visible(False)
|
d58851b7f1a1a6c06f1af44c87dbc419171dbb5e | l33tdaima/l33tdaima | /p328m/odd_even_list.py | 1,071 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from typing import Optional
from local_packages.list import ListNode
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# produce two sub lists and concatnate them
if not head:
return None
pod, pev, evhead = head, head.next, head.next
while pod.next and pev.next:
pod.next = pev.next
pev.next = pod.next.next
pod, pev = pod.next, pev.next
pod.next = evhead
return head
# TESTS
for array, expected in [
([], []),
([1], [1]),
([1, 2], [1, 2]),
([1, 2, 3, 4, 5], [1, 3, 5, 2, 4]),
([1, 2, 3, 4, 5, 6], [1, 3, 5, 2, 4, 6]),
([2, 1, 3, 5, 6, 4, 7], [2, 3, 6, 7, 1, 5, 4]),
]:
sol = Solution()
actual = ListNode.to_array(sol.oddEvenList(ListNode.from_array(array)))
print("Odd even linked list of", array, "->", actual)
assert actual == expected
|
64cabb119e5afe63c6be42a59f8a3d547fb9ad4d | Nimisha-V-Arun/Interview-Prep | /Arrays/Python/countLetter.py | 500 | 4.0625 | 4 | def countLetter(string):
count = list()
cnt = 1
for x in range(len(string)):
# if you reach the last char of the string or if the adj char are different
if(x+1 == len(string) or string[x] != string[x+1]):
count.append(string[x])
count.append(str(cnt))
cnt = 1
elif string[x] == string[x+1]:
# if adj char are the same
cnt += 1
print("".join(string),"".join(count))
countLetter(list("aaabccb")) |
98f7f140cfdba8c10d8e34913afae995568c5a93 | DominikaJastrzebska/Kurs_Python | /05_christmas_tree/zad_calendar.py | 1,038 | 4.21875 | 4 | '''
https://stackoverflow.com/questions/33624221/make-a-yearly-calendar-without-importing-a-calendar
'''
data = [
('January', range(31)),
('February', range(28)),
('March', range(31)),
('April', range(30)),
('May', range(31)),
('June', range(30)),
('July', range(31)),
('August', range(31)),
('September', range(30)),
('October', range(31)),
('November', range(30)),
('December', range(31)),
]
# for i in range(len(data)):
# print(data[i][0])
# days = []
# for x in range(7):
# for j in data[i][1]:
# print(j, end=' ')
def make_simple_calendar():
for month, days in data:
print(month)
start_day = 0
for day in days:
if day <= 9:
print('0'+str(day), end=' ')
else:
print('{0:<3}'.format(day), end='')
start_day += 1
if start_day == 7:
print()
start_day = 0
print()
print()
make_simple_calendar()
|
c30b610ab597f90c3a6de88cf42b62eeab13ecb5 | helixstring/introduction-helixstring | /Xiaoyu-excercise-4.py | 292 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 17:25:12 2017
@author: xchen
"""
#Calculate all coordinates of the line x=y with x < 100.
#Note: This is the sequence (0, 0), (1, 1), ... (99, 99)
coord={0:0}
for i in range(101):
coord.update ({i:i})
print coord.items()
|
711973b736b80f666eac3a4f09ecba217182a7b6 | pingguosanjiantao/Elements-of-Programming-Interviews | /11-Heaps/11.1-Merge sorted files.py | 1,325 | 3.546875 | 4 | class MinHeap:
def __init__(self):
self.data = []
def add(self, x):
k = len(self.data)
if k == 0:
self.data += [x]
else:
self.data += [float("inf")]
while k > 0:
idx = (k - 1) >> 1
parent = self.data[idx]
if parent <= x:
break
self.data[k] = parent # parent down
k = idx
self.data[k] = x
def poll(self):
if len(self.data) == 0:
return None
if len(self.data) == 1:
return self.data.pop()
ret = self.data[0]
x = self.data.pop()
size = len(self.data)
k, half = 0, size >> 1
while k < half:
leftId = (k << 1) + 1
rightId = leftId + 1
idx = rightId if rightId < size and self.data[rightId] < self.data[leftId] else leftId
child = self.data[idx]
if x <= child:
break
self.data[k] = child
k = idx
self.data[k] = x
return ret
def isEmpty(self):
return len(self.data) == 0
heap = MinHeap()
heap.add(5)
heap.add(3)
heap.add(1)
heap.add(2)
print heap.poll()
print heap.poll()
print heap.poll()
print heap.poll()
print heap.poll()
|
f1f311c1fec85e050ac513bb9e3222cd6672ac90 | techknowledgist/techknowledgist | /ontology/maturity/count_terms.py | 1,000 | 3.796875 | 4 | """
Takes a couple of usage files and creates a file with terms that occur 25 times or more.
Usage:
python count_terms.py data/usage-*.txt
Output is written to terms-0025.txt.
"""
import sys, codecs
TERMS = {}
def collect_term_counts(fnames):
for fname in fnames:
print fname,
fh = codecs.open(fname, encoding='utf8')
for line in fh:
if line.startswith('#'):
continue
fields = line.split("\t")
term = fields[-1].strip()
freq = int(fields[2])
TERMS[term] = TERMS.get(term, 0) + freq
print len(TERMS)
def print_terms(frequency):
fname = "terms-%04d.txt" % frequency
fh = codecs.open(fname, 'w', encoding='utf8')
for term in TERMS:
freq = TERMS[term]
if freq >= frequency:
fh.write("%d\t%s\n" % (freq, term))
if __name__ == '__main__':
fnames = sys.argv[1:]
collect_term_counts(fnames)
print_terms(25)
|
5c011ea768ef962d012890b791e71e6840aeffad | dParikesit/TubesDaspro | /login.py | 832 | 3.921875 | 4 | from hash import hash
def login(users):
username = input('Masukan username: ')
password = hash(input('Masukan password: '))
id = -1
role = ''
name = ''
for user in users:
if user[1]==username:
id = user[0]
name = user[2]
if user[4]==password:
role = user[5]
while id == -1:
print('User tidak ditemukan')
username = input('Masukan username: ')
password = hash(input('Masukan password: '))
for user in users:
if user[1]==username:
id = user[0]
name = user[2]
if user[4]==password:
role = user[5]
while role =='':
print('Password salah')
password = hash(input('Masukan password: '))
for user in users:
if user[1]==username:
if user[4]==password:
role = user[5]
return id, role, name
|
8462a4ff0552a1a366040ad72a6204bac2ccacb6 | mahendraprateik/DataStructures | /problem6_union_intersection.py | 4,447 | 4.15625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList(object):
def __init__(self):
self.head = None
def __str__(self):
if self.head is None:
return
node = self.head
out = ""
while node:
out += str(node.value) + " ---> "
node = node.next
return out
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
def size(self):
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def union(llist_1, llist_2):
# Your Solution Here
"""
Function to find union of 2 linked lists
Parameters:
llist_1 (LinkedList Object): first linked list
llist_2 (LinkedList Object): second linked list
Returns:
Union-ed linked list of all elements
"""
if not llist_1.head and not llist_2.head:
print("Cannot find union of 2 empty linkedlists") # Empty linkedlist case
return
if llist_1.head is None:
return llist_2
elif llist_2.head is None:
return llist_1
union_set = set()
llist1_node = llist_1.head
while llist1_node:
union_set.add(llist1_node.value)
llist1_node = llist1_node.next
llist2_node = llist_2.head
while llist2_node:
union_set.add(llist2_node.value)
llist2_node = llist2_node.next
llist_union = LinkedList()
for ele in union_set:
llist_union.append(ele)
return str(llist_union)
pass
def intersection(llist_1, llist_2):
# Your Solution Here
"""
Function to find intersection of 2 linked lists
Parameters:
llist_1 (LinkedList Object): first linked list
llist_2 (LinkedList Object): second linked list
Returns:
Intersection-ed linked list of all elements
"""
if llist_1.head is None and llist_2.head is None:
print("Cannot find intersection of 2 empty linkedlists")
return
if llist_1.head is None or llist_2.head is None:
return
set1 = set()
llist1_node = llist_1.head
while llist1_node:
set1.add(llist1_node.value)
llist1_node = llist1_node.next
set2 = set()
llist2_node = llist_2.head
while llist2_node:
set2.add(llist2_node.value)
llist2_node = llist2_node.next
intersection_set = set1.intersection(set2)
if len(intersection_set) == 0:
return None
llist_intersection = LinkedList()
for ele in intersection_set:
llist_intersection.append(ele)
return llist_intersection
pass
# Test cases - Regular
linked_list_1 = LinkedList()
linked_list_2 = LinkedList()
element_1 = [3,2,4,35,6,65,6,4,3,21]
element_2 = [6,32,4,9,6,1,11,21,1]
for i in element_1:
linked_list_1.append(i)
for i in element_2:
linked_list_2.append(i)
print("Union\n",union(linked_list_1, linked_list_2))
print("Intersection\n",intersection(linked_list_1, linked_list_2))
"""
Union
32 ---> 65 ---> 2 ---> 35 ---> 3 ---> 4 ---> 6 ---> 1 ---> 9 ---> 11 ---> 21 --->
Intersection
4 ---> 21 ---> 6 --->
"""
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_3 = []
element_4 = [1]
for i in element_3:
linked_list_3.append(i)
for i in element_4:
linked_list_4.append(i)
print("Union\n",union(linked_list_3, linked_list_4))
print("Intersection\n",intersection(linked_list_3, linked_list_4))
"""
Union
1 --->
Intersection
None
"""
linked_list_5 = LinkedList()
linked_list_6 = LinkedList()
element_5 = [1]
element_6 = [1]
for i in element_5:
linked_list_5.append(i)
for i in element_6:
linked_list_6.append(i)
print("Union\n",union(linked_list_5, linked_list_6))
print("Intersection\n",intersection(linked_list_5, linked_list_6))
"""
Union
1 --->
Intersection
1 --->
"""
# Test case - Edge
# Empty linked lists
linked_list_7 = LinkedList()
linked_list_8 = LinkedList()
print("Union\n",union(linked_list_7, linked_list_8)) # Empty linked list warning
print("Intersection\n",intersection(linked_list_7, linked_list_8)) # Empty linked list warning
|
cae50539c58a816ed7a7249d09474a40b38a5cf4 | bitcs231n/nasty | /数据挖掘/作业1/dissimilarity.py | 1,627 | 3.578125 | 4 | from homework1.pre_processing import data_array
import numpy as np
from math import sqrt
import pickle
def num_similarity(array, a, b):
a1 = list(array[a, [4, 5, 6, 16, 19, 20, 22]])
a2 = list(array[b, [4, 5, 6, 16, 19, 20, 22]])
i = len(a1) - 1
while i >= 0:
if a1[i] == '?' or a2[i] == '?':
a1.pop(i)
a2.pop(i)
else:
a1[i] = float(a1[i])
a2[i] = float(a2[i])
i -= 1
result = sqrt(sum(np.square(np.array(a1)-np.array(a2))))
return result
def nom_similarity(array, a, b):
a1 = list(array[a, [i-1 for i in range(1, 29) if i not in [4, 5, 6, 16, 19, 20, 22]]])
a2 = list(array[b, [i-1 for i in range(1, 29) if i not in [4, 5, 6, 16, 19, 20, 22]]])
i = len(a1) - 1
m = 0
while i >= 0:
if a1[i] == '?' or a2[i] == '?':
a1.pop(i)
a2.pop(i)
elif a1[i] == a2[i]:
m += 1
i -= 1
l = len(a1)
return (l-m)/l
def sim_matrix():
num_array = np.zeros([368,368])
nom_array = np.zeros([368,368])
for i in range(368):
for j in range(368):
if i != j:
num_array[i][j] = num_similarity(data_array, i, j)
nom_array[i][j] = nom_similarity(data_array, i, j)
num_array = (num_array - np.ones([368, 368])*num_array.min())/num_array.max()
sim_array = (num_array + nom_array)/2
return sim_array
if __name__ == '__main__':
sim_array = sim_matrix()
with open('sim_array.pkl', 'wb') as f:
pickle.dump(sim_array, f)
|
8c09b2821d45bf59a78d6d37d882a50d878abed0 | gavrilmihai/python_challenges | /python_challenge4_sol4.py | 164 | 3.796875 | 4 |
import random
num_list = range(1, random.randint(10,500))
odd, even = [x for x in num_list if x%2], [x for x in num_list if not x%2]
print(f'{odd} \n\n {even}')
|
d2721e95ec6243fd486de610460b8ff01d00fd69 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2397/60791/306420.py | 170 | 3.796875 | 4 | n = int(input())
if n == 7 or n == 12:
print(15)
pass
elif n == 17:
print(32)
pass
elif n == 3:
print(17)
pass
else:
print('n')
print(n) |
8357073d255501e80709983f17046fdd5720112a | pi-2021-2-db6/lecture-code | /aula22-24-listas-ii/percursos.py | 782 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Demonstra as diferentes tecnicas classicas para percorrer
(visitar todos os elementos) de uma matriz.
@author: Prof. Diogo SM
"""
import matrizes
def percorre_por_linhas(m: [[]]):
for i in range(len(m)):
for j in range(len(m[i])):
print(f"m[{i}][{j}] =", m[i][j])
def percorre_por_colunas(m: [[]]):
if len(m) > 0:
for j in range(len(m[0])):
for i in range(len(m)):
print(f"m[{i}][{j}] =", m[i][j])
def testes():
v = matrizes.cria_matriz_int_aleatorio(3, 4)
print(v)
percorre_por_linhas(v)
percorre_por_linhas([])
print()
percorre_por_colunas(v)
percorre_por_colunas([])
if __name__ == "__main__":
testes() |
7b1bcfa1fa069bf14d3c86a1e973b1a07ea70b23 | bigpussy/pythontestarea | /mapandreduce.py | 1,067 | 4 | 4 | # -*- coding: utf-8 -*-
print u"map函数"
def f(x):
return x * x
print map(f , [1, 2, 3, 4, 5, 6, 7, 8, 9])
print map(f , range(10))
print u"reduce函数"
def add(x , y):
return x + y
print reduce(add , [1 , 2 , 3 , 4 , 5, 6])
def fn(x , y):
return x * 10 + y
print reduce(fn , [1, 3, 5, 7, 9])
def char2num(s):
return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[s]
print map(char2num, '13579')
print reduce(fn , map(char2num, '13579'))
print u"整理为一个str2int函数"
def str2int(s):
def fn(x , y):
return x * 10 + y
def char2num(s):
return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[s]
return reduce(fn , map(char2num, '13579'))
print str2int('13579')
print u"lambda 函数"
g = lambda x:x * 2
print g(3)
def str2int(s):
return reduce(lambda x, y : x * 10 + y, map(char2num, s))
print str2int("13579")
print u"练习1"
def cap(s):
return s.capitalize()
print map(cap, ['adam', 'LISA', 'barT'])
print u"练习2"
def mutl(x , y):
return x * y
print reduce(mutl , range(1 , 10))
|
fe7fff4cdda7d57431a313f6a2531cec04239ee4 | ARBUCHELI/LIST-COMPREHENSIONS | /list_comprehensions.py | 379 | 4.03125 | 4 | scores = {
"Rick Sanchez": 70, #dictionary
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
#Creation of the list that retrieves the names of the people with score >= 65
passed = [name for name, score in scores.items() if score >=65]
# write your list comprehension here
print(passed)
|
e331ab1255f19afffb314b9380485a266bae557f | rodrigocruz13/holbertonschool-machine_learning | /supervised_learning/0x00-binary_classification/9-neural_network.py | 2,996 | 4.03125 | 4 | #!/usr/bin/env python3
"""
Class NeuralNetwork
"""
import numpy as np
class NeuralNetwork:
""" Class """
def __init__(self, nx, nodes):
"""
Initialize NeuralNetwork
Args:
- nx: is the number of input features to the neuron
- Nodes: is the number of nodes found in the hidden layer
Public attributes:
- W1: The weights vector for the hidden layer. Upon instantiation,
it should be initialized using a random normal distribution.
- b1: b1: The bias for the hidden layer. Upon instantiation,
it should be initialized with 0’s.
- A1: The activated output for the hidden layer. Upon instantiation,
it should be initialized to 0.
- W2: The weights vector for the neuron.
It is initialized with a random normal distribution.
- b2: The bias for the neuron. Upon instantiation.
It is initialized to 0.
- A2: The activated output of the neuron (prediction).
It is initialized to 0.
"""
if not isinstance(nx, int):
raise TypeError("nx must be an integer")
if nx < 1:
raise ValueError("nx must be a positive integer")
if not isinstance(nodes, int):
raise TypeError("nodes must be an integer")
if nodes < 1:
raise ValueError("nodes must be a positive integer")
self.__W1 = np.random.randn(nodes, nx)
# Draw random samples from a normal dist.
self.__b1 = np.zeros((nodes, 1))
self.__A1 = 0
self.__W2 = np.random.randn(1, nodes)
# Draw random samples from a normal dist.
self.__b2 = 0
self.__A2 = 0
@property
def W1(self):
"""
getter method
Args:
- self
Return:
- __W1: The value of the proate attribute __W1.
"""
return self.__W1
@property
def A1(self):
"""
getter method
Args:
- self
Return:
- __A1: The value of the proate attribute __A1.
"""
return self.__A1
@property
def b1(self):
"""
getter method
Args:
- self
Return:
- __b1: The value of the proate attribute __b1.
"""
return self.__b1
@property
def W2(self):
"""
getter method
Args:
- self
Return:
- __W2: The value of the proate attribute __W2.
"""
return self.__W2
@property
def A2(self):
"""
getter method
Args:
- self
Return:
- __A2: The value of the proate attribute __A2.
"""
return self.__A2
@property
def b2(self):
"""
getter method
Args:
- self
Return:
- __b2: The value of the proate attribute __b2.
"""
return self.__b2
|
db65068c3bc649aad7b5f9a12a1ba856f4c82482 | Daviderose/Whiteboard-excercises | /Fibonacci/Fibonacci.py | 289 | 3.84375 | 4 |
def fib(n):
if n == 1 or n == 2:
return 1
fib_array = [None] * (n + 1)
fib_array[1] = 1
fib_array[2] = 1
for i in range(3,n + 1):
fib_array[i] = fib_array[i - 1] + fib_array[i - 2]
return fib_array[n]
if __name__ == '__main__':
print(fib(100)) |
c5346058b3ec8ce30caa7b8eec1a63be34fafc00 | gabriellaec/desoft-analise-exercicios | /backup/user_294/ch16_2020_04_12_21_31_06_341008.py | 136 | 3.703125 | 4 | programa = float(input('qual o valor da sua conta ? '))
final = programa*1.1
print ('Valor da conta com 10%: R$ {0:.2f}' .format(final)) |
1a90cc52744885e50a5ee9481f2fc1471e62b7d3 | vikasnarwaria/CtCI_PYTHON_SOLUTIONS | /SORTING_AND_SEARCHING/basics.py | 10,560 | 4.5625 | 5 | from random import randint
'''
This script illustrates the implementation of the following sorting algorithms.
1. merge_sort.
2. Quick_sort.
3. Heap_sort.
4. Bubble/Insertion sort.
5. Selection sort.
'''
def merge_sort(arr):
'''
Merge Sort is a very basic and efficient Sorting algorithm which takes O(NlogN) run time.
Algorithm:
We will sort the array by dividing it into 2 halves and sort each half individually and later merge the sorted halves.
To do this, we need to use a helper array.
merge_sort_util function:
1. define a merge_sort_util function that will take array, helper, low and high.
2. Base condition for this function will be when low <= high.
3. mid = (low + high) // 2, call same function for left half (low is low and high is mid) and right half (low is mid + 1
and high is high).
4. Once both the calls are done, we should have both the halves sorted.
5. In the end, call merge function with inputs as arr, helper, low, mid and high as inputs.
merge function:
1. merge function will sort the input array with the help of helper array. It will merge the 2 halves of the array (defined
by low, mid and high values) which are already sorted.
1. copy everything from arr into helper array.
2. We will maintain 3 pointers: left, right and current starting from low, mid + 1 and low respectively.
3. run a loop till left <= mid and right <= high and inside the loop check if helper[left] < helper[right],
based on the comparison, set arr[current] and increase all 3 pointers accordingly.
4. After the loop, if left array has anything left then we need to copy those elements from helper and set them into array.
5. After the loop, if right array has anything left then no need to do anything as they will already be in sorted order.
'''
def merge_sort_util(arr, helper, low, high):
if low >= high:
return
mid = (low + high) // 2
merge_sort_util(arr, helper, low, mid)
merge_sort_util(arr, helper, mid + 1, high)
merge(arr, helper, low, mid, high)
def merge(arr, helper, low, mid, high):
helper = list(arr)
left = low
right = mid + 1
current = low
while left <= mid and right <= high:
if helper[left] <= helper[right]:
arr[current] = helper[left]
left += 1
else:
arr[current] = helper[right]
right += 1
current += 1
remaining = mid - left
for r in range(remaining + 1):
arr[current + r] = helper[left + r]
if arr is None or len(arr) == 0:
return
helper = []
merge_sort_util(arr, helper, 0, len(arr) - 1)
return arr
# One more implementation of quick sort by using a slighty different approach in Partition()
# def partition(array, begin, end):
# pivot = begin
# for i in range(begin+1, end+1):
# if array[i] <= array[begin]:
# pivot += 1
# array[i], array[pivot] = array[pivot], array[i]
# array[pivot], array[begin] = array[begin], array[pivot]
# return pivot
# def quicksort(array):
# def quicksort_util(array, low, high):
# if low >= high: return
# pivot = partition(array, low, high)
# quicksort_util(array, low, pivot-1)
# quicksort_util(array, pivot+1, high)
# quicksort_util(array, 0, len(array)-1)
def quick_sort(arr):
'''
Quick Sort is another efficient sorting algorithm which sorts an array in O(NlogN) time.
Algorithm:
Quick sort is done by selecting a random point in an array and then swapping the elements from left and right half
so that all left elements will be smaller than Pivot and all right elements will be larger than pivot.
We can implement the above logic by creating 3 util functions.
1. swap_elements function: this will just take 2 indexes and swap their values in given array.
2. partition function: this will take array, low and high as inputs.
First, we will select a pivot value by selecting a random point in the array.
We will run a loop till low <= high.
First, we will adjust the low pointer till we find a point that is larger than pivot point by increasing it with 1.
Then, we will adjust the high pointer till we find a point that is smaller than pivot point by decreasing it with 1.
if low <= high then we will swap the low and high elements. Increment low by 1 and Decrement high by 1.
Repeat the loop.
In the end return low.
So, if we have got low as 0, high as 4 and pivot has been selected as mid point (that is 2) then partition will return 3
as a result.
3. quick_sort_util function: This function will also take array, low and high as inputs. This will be the starting point of
the algorithm and will be called recursively.
First, we will get an index point by calling partition function in the array.
If low < index - 1 then call quick_sort_util for low to index - 1.
If index < high then call quick_sort_util for index to high.
In example take in point 2, we got index value as 3.
So, next it will apply quick_sort on 0 to 2 and 3 to 4. Once these 2 parts are sorted, whole array will be sorted
completely.
'''
def partition(arr, low, high):
pivot = arr[randint(low, high)]
while low <= high:
while arr[low] < pivot:
low += 1
while arr[high] > pivot:
high -= 1
if low <= high:
arr[low], arr[high] = arr[high], arr[low]
low += 1
high -= 1
return low
def quick_sort_util(arr, low, high):
if low >= high: return
index = partition(arr, low, high)
quick_sort_util(arr, low, index - 1)
quick_sort_util(arr, index, high)
if arr is None or len(arr) == 0:
return
quick_sort_util(arr, 0, len(arr) - 1)
return arr
def heap_sort(arr):
'''
Heap sort is one more sorting algorithm that can complete the sorting in O(NlogN) time.
Algorithm:
1. Make a max binary heap with the given array.
2. Swap the root of binary heap with its last element. Now, last element of the array is its max element.
3. Reduce the size of the heap by 1.
4. If size of heap is more then 1 then Heapify the root again to make it a max binary heap. Else return as our
array has been sorted.
5. Repeat from step number 2 till size of the heap becomes 1.
Algorithm to Implement min/max Binary Heap:
1. Since in a binary heap, half of the elements are at the bottom level so we will only apply heapify in top half
array elements.
2. We will start with last element in 2nd last level and keep applying heapify to create a min/max binary heap.
3. Heapify algorithm is nothing but its a recursive algorithm to apply sink method.
4. Suppose, we called sink on node 3 of the heap/array. First, we will find its child node (2*i + 1 and 2*i + 2).
If both child nodes are outside the size then return. Else, select the minimum of the child node to implement a
min binary heap. Swap this child node value with root node and apply sink on child node.
'''
def create_max_binary_heap(arr):
size = len(arr)
half_value = (size - 1) // 2
for r in reversed(range(half_value + 1)):
heapify(arr, r, size - 1)
def heapify(arr, index, max_index):
left_child = 2*index + 1
right_child = 2*index + 2
if left_child > max_index:
return
if right_child <= max_index and arr[right_child] > arr[left_child]:
child = right_child
else:
child = left_child
if arr[child] > arr[index]:
temp = arr[child]
arr[child] = arr[index]
arr[index] = temp
heapify(arr, child, max_index)
if arr is None or len(arr) == 0:
return
create_max_binary_heap(arr)
size = len(arr)
while size > 1:
temp = arr[0]
arr[0] = arr[size - 1]
arr[size - 1] = temp
size -= 1
heapify(arr, 0, size - 1)
return arr
def bubble_sort(arr):
'''
Run Time of bubble_sort is O(N^2).
It is also called as Insertion Sort.
Algorithm:
Run an outer loop for the whole length of the array.
Run an inner loop also for the whole length of the array.
Compare the current index with previous index and swap them if they are not in correct order.
'''
if arr is None or len(arr) == 0:
return
for i in range(1, len(arr)):
for j in range(1, len(arr)):
if arr[j] < arr[j - 1]:
temp = arr[j]
arr[j] = arr[j-1]
arr[j-1] = temp
return arr
def selection_sort(arr):
'''
Selection sort is also known as child's algorithm.
We find the minimum of the array and put it in the beginning of the array.
Algorithm:
Run a loop for whole array length.
Start an inner loop which will start from outer loop variable and goes till end of the array.
start min as outer loop index.
Keep comparing min with inner loop index. If inner loop index is less than min then swap inner loop index and min.
In the end of the outer loop, whole array will be sorted.
'''
if arr is None or len(arr) == 0:
return
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
min = arr[i]
if arr[j] < min:
temp = min
min = arr[j]
arr[j] = temp
arr[i] = min
return arr
if __name__ == "__main__":
print("####### Merge Sort #######")
print(merge_sort([6,5,4,1,2,3,0]))
print("\n####### Quick Sort #######")
# print(quick_sort([6,5,4,1,2,3,0]))
print(quick_sort([10,9,8,7,6,5,4,1,2,3,4,5,6,5,3]))
print("\n####### Heap Sort #######")
print(quick_sort([6,5,4,1,2,3,0]))
print("\n####### Bubble/Insertion Sort #######")
print(bubble_sort([6,5,4,1,2,3,0]))
print("\n####### Selection Sort #######")
print(selection_sort([6,5,4,1,2,3,0]))
|
a982243fa67db7b92d6f233ec019f37ceb7383e6 | opussf/Masyu | /test/TestSolveMasyu.py | 21,301 | 3.515625 | 4 | import unittest
from MasyuBoard import *
from SolveMasyu import *
class TestSolveMasyu( unittest.TestCase ):
Masyu = SolveMasyu( MasyuBoard.MasyuBoard(), True )
def setUp( self ):
""" setUp """
self.Masyu.board.loadFromFile( "puzzles/puzzle_0.txt" )
def test_Masyu_hasBoard( self ):
self.assertTrue( self.Masyu.board )
def test_Masyu_dot_empty( self ):
self.assertFalse( self.Masyu.dot( 0, 0 ) )
def test_Masyu_dot_black( self ):
self.assertTrue( self.Masyu.dot( 2, 0 ) )
def test_Masyu_dot_white( self ):
self.assertTrue( self.Masyu.dot( 1, 0 ) )
def test_Masyu_blackDot_vertical_01( self ):
""" finds a vertical component """
self.Masyu.dotBlack( 0, 2 )
self.assertEquals( self.Masyu.board.getValue( 0, 0 )[1],
( self.Masyu.board.NORTH | self.Masyu.board.WEST ) << 4 | self.Masyu.board.SOUTH )
def test_Masyu_blackDot_horizontal_01( self ):
""" find a horizontal component """
self.Masyu.dotBlack( 0, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( self.Masyu.board.SOUTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.WEST )
def test_Masyu_blackDot_vertical_02( self ):
self.Masyu.dotBlack( 2, 0 )
self.assertEquals( self.Masyu.board.getValue( 0, 0 )[1],
( self.Masyu.board.NORTH | self.Masyu.board.WEST ) << 4 | self.Masyu.board.EAST )
def test_Masyu_blackDot_horizontal_02( self ):
self.Masyu.dotBlack( 0, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( self.Masyu.board.SOUTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.WEST )
def test_Masyu_blackDot_single_exit_East( self ):
""" draws the one line it can guess at """
self.Masyu.board.loadFromFile( "puzzles/puzzle_5x5_single_black.txt" )
self.Masyu.dotBlack( 1, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST )
def test_Masyu_blackDot_single_noExit_West( self ):
""" marks a noExit on the short side """
self.Masyu.board.loadFromFile( "puzzles/puzzle_5x5_single_black.txt" )
self.Masyu.dotBlack( 1, 2 )
self.assertEquals( self.Masyu.board.getValue( 1, 2 )[1],
( self.Masyu.board.WEST << 4 ) | self.Masyu.board.EAST )
def test_Masyu_blackDot_single_exit_West( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n...b.\n.....\n....." )
self.Masyu.dotBlack( 3, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST )
def test_Masyu_blackDot_single_noExit_East( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n...b.\n.....\n....." )
self.Masyu.dotBlack( 3, 2 )
self.assertEquals( self.Masyu.board.getValue( 3, 2 )[1],
( self.Masyu.board.EAST << 4 | self.Masyu.board.WEST ) )
def test_Masyu_blackDot_single_exit_South( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n..b..\n.....\n.....\n....." )
self.Masyu.dotBlack( 2, 1 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( self.Masyu.board.EAST | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.SOUTH )
def test_Masyu_blackDot_single_noExit_North( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n..b..\n.....\n.....\n....." )
self.Masyu.dotBlack( 2, 1 )
self.assertEquals( self.Masyu.board.getValue( 2, 1 )[1],
( self.Masyu.board.NORTH << 4 | self.Masyu.board.SOUTH ) )
def test_Masyu_blackDot_single_exit_North( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n.....\n..b..\n....." )
self.Masyu.dotBlack( 2, 3 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( self.Masyu.board.EAST | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.SOUTH )
def test_Masyu_blackDot_single_noExit_South( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n.....\n..b..\n....." )
self.Masyu.dotBlack( 2, 3 )
self.assertEquals( self.Masyu.board.getValue( 2, 3 )[1],
( self.Masyu.board.SOUTH << 4 | self.Masyu.board.NORTH ) )
def test_Masyu_blackDot_nested( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n...b.\n..b..\n.....\n....." )
self.Masyu.dotBlack( 3, 1 )
self.Masyu.dotBlack( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 0, 2 )[1],
( self.Masyu.board.WEST << 4 | self.Masyu.board.EAST ) )
def test_Masyu_blackDot_falseOnSolved( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_00.txt" )
self.Masyu.dotBlack( 2, 0 )
self.assertFalse( self.Masyu.dotBlack( 2, 0 ) )
def test_Masyu_blackDot_falseOnUnableToSolve( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_5x5_single_black.txt" )
self.Masyu.dotBlack( 1, 2 )
self.assertFalse( self.Masyu.dotBlack( 1, 2 ) )
def test_Masyu_blackDot_sideBySide( self ):
self.Masyu.board.initBoard( 6, 6, "..bb..\n......\n......\n......\n......\n......" )
self.Masyu.dotBlack( 2, 0 )
self.Masyu.dotBlack( 3, 0 )
self.assertEquals( self.Masyu.board.getValue( 1, 0 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.WEST | self.Masyu.board.EAST ) )
def test_Masyu_whiteDot_onTheEdge_North( self ):
self.Masyu.dotWhite( 1, 0 )
self.assertEquals( self.Masyu.board.getValue( 1, 0 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.WEST | self.Masyu.board.EAST ) )
def test_Masyu_whiteDot_hasEntryLine( self ):
self.Masyu.board.initBoard( 4, 3, "....\n.ww.\n...." )
self.Masyu.board.setExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.dotWhite( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.WEST | self.Masyu.board.EAST ) )
def test_Masyu_whiteDot_boarderedOnTwoSidesByWhiteDots( self ):
""" a white dot in the middle of 2 others cannot go through them.
( only 2 white dots can be on a straight line )
"""
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n.www.\n.....\n....." )
self.Masyu.dotWhite( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.EAST | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) )
def test_Masyu_empty_returns_false( self ):
self.assertFalse( self.Masyu.dot( 1, 1 ) )
def test_Masyu_empty_lineOnly_setsNoExits( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.board.setExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST ) )
def test_Masyu_empty_lineOnly_returns_True( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.board.setExit( 1, 1, self.Masyu.board.WEST )
self.assertTrue( self.Masyu.dot( 1, 1 ) )
def test_Masyu_empty_lineAndNoExits_returnsFalse( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.board.setExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.NORTH )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.SOUTH )
self.assertFalse( self.Masyu.dot( 1, 1 ) )
def test_Masyu_empty_singleEntry_singleExit_EastToWest( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.NORTH )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.SOUTH )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST ) )
def test_Masyu_empty_singleEntry_singleExit_WestToEast( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.NORTH )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.SOUTH )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST ) )
def test_Masyu_empty_singleEntry_singleExit_NorthToEast( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.NORTH )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.SOUTH )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.WEST | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.NORTH ) )
def test_Masyu_empty_singleEntry_singleExit_EastToSouth( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.NORTH )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.WEST | self.Masyu.board.NORTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.SOUTH ) )
def test_Masyu_empty_singleEntry_singleExit_SouthToWest( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.NORTH )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.SOUTH | self.Masyu.board.WEST ) )
def test_Masyu_empty_singleEntry_singleExit_WestToNorth( self ):
self.Masyu.board.setExit( 1, 1, self.Masyu.board.WEST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.EAST )
self.Masyu.board.setNoExit( 1, 1, self.Masyu.board.SOUTH )
self.Masyu.dot( 1, 1 )
self.assertEquals( self.Masyu.board.getValue( 1, 1 )[1],
( ( self.Masyu.board.EAST | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.WEST ) )
def test_Masyu_empty_threeNoExits_setFourthNoExit( self ):
""" normally corners, could be elsewhere though """
self.Masyu.board.setNoExit( 2, 2, self.Masyu.board.WEST )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( 15 << 4 ) ) )
def test_Masyu_blackDot_ignoreDirectionWhereThereIsASingleExitAt90DegreesInTheNextCoordinate( self ):
""" since the black dot has to go a distance of 2, a location with a single exit at 90 degrees would
need to exclude that direction.
invalid board... """
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..b..\n..www\n....." )
self.Masyu.dot( 2, 2 )
self.Masyu.dot( 3, 3 )
self.Masyu.dot( 4, 3 )
self.Masyu.dot( 2, 3 )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.SOUTH | self.Masyu.board.WEST ) )
def test_Masyu_whiteDot_followLine_terminateShortestEnd_01( self ):
""" a white dot 'must turn in the previous and/or next cell in its path.'
-w- has not enough info
-w-.- has enough to make x-w-.-
-w-w- would work the same, each dot would terminate the short end x-w-w-x
-w-.-.-.-.-.-w- is no different.
|-w-| would set the exits anyway
"""
self.Masyu.board.initBoard( 6, 2, "..ww..\n......" )
self.Masyu.dot( 2, 0 ) # draws the first one.
self.Masyu.dot( 3, 0 ) # draws the 2nd one.
self.Masyu.dot( 2, 0 ) # this time it should find the noExit
self.assertEquals( self.Masyu.board.getValue( 1, 0 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.WEST ) << 4 | self.Masyu.board.EAST ) )
def test_Masyu_whiteDot_followLine_terminateShortestEnd_02( self ):
self.Masyu.board.initBoard( 7, 2, "..w.w..\n......." )
self.Masyu.dot( 2, 0 ) # draws the first one.
self.Masyu.dot( 4, 0 ) # draws the 2nd one.
self.Masyu.dot( 2, 0 )
self.assertEquals( self.Masyu.board.getValue( 1, 0 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.WEST ) << 4 | self.Masyu.board.EAST ) )
self.Masyu.dot( 4, 0 )
self.assertEquals( self.Masyu.board.getValue( 5, 0 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.WEST ) )
def test_Masyu_followLine_01( self ):
self.Masyu.board.initBoard( 4, 5, "....\n....\n....\n....\n...." )
self.Masyu.board.setExit( 0, 0, self.Masyu.board.EAST )
self.Masyu.board.setExit( 0, 0, self.Masyu.board.SOUTH )
self.Masyu.board.setExit( 1, 0, self.Masyu.board.SOUTH )
result = self.Masyu.followLine( 0, 1 )
self.assertEquals( result, ( 1, 1 ) )
def test_Masyu_line_cannotCreateSmallLoop( self ):
self.Masyu.board.initBoard( 4, 5, "....\n.www\n....\n....\n...." )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.getValue( 0, 3 )[1],
( ( self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH ) )
def test_Masyu_blackDot_preconnected_lines_setsNoExits_01( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..b..\n.....\n....." )
self.Masyu.board.setExit( 2, 2, self.Masyu.board.NORTH )
self.Masyu.board.setExit( 2, 2, self.Masyu.board.EAST )
result = self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.SOUTH | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.EAST ) )
def test_Masyu_blackDot_preconnected_lines_setsNoExits_02( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..b..\n.....\n....." )
self.Masyu.board.setExit( 2, 2, self.Masyu.board.SOUTH )
self.Masyu.board.setExit( 2, 2, self.Masyu.board.WEST )
result = self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.SOUTH | self.Masyu.board.WEST ) )
def test_Masyu_blackDot_preconnected_lines_setsNoExits_03( self ):
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..b..\n.....\n....." )
self.Masyu.board.setExit( 2, 2, self.Masyu.board.SOUTH )
self.Masyu.board.setExit( 2, 2, self.Masyu.board.WEST )
self.Masyu.board.setNoExit( 2, 2, self.Masyu.board.NORTH )
result = self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.EAST ) << 4 | self.Masyu.board.SOUTH | self.Masyu.board.WEST ) )
def test_Masyu_whiteDot_TwoInLineWithLineinline_lineInWest( self ):
""" -.ww Testing the left white dot will result in it having a vertical line.
"""
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..ww.\n.....\n....." )
self.Masyu.board.setExit( 1, 2, self.Masyu.board.WEST )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.EAST | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) )
def test_Masyu_whiteDot_TwoInLineWithLineinline_lineInEast( self ):
""" .ww.- Testing the left white dot will result in it having a vertical line.
"""
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n.ww..\n.....\n....." )
self.Masyu.board.setExit( 3, 2, self.Masyu.board.EAST )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.EAST | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) )
def test_Masyu_whiteDot_TwoInLineWithLineinline_lineInNorth( self ):
""" see other tests for this for example """
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..w..\n..w..\n....." )
self.Masyu.board.setExit( 2, 1, self.Masyu.board.NORTH )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST ) )
def test_Masyu_whiteDot_TwoInLineWithLineinline_lineInSouth( self ):
""" see other tests for this for example """
self.Masyu.board.initBoard( 5, 5, ".....\n..w..\n..w..\n.....\n....." )
self.Masyu.board.setExit( 2, 3, self.Masyu.board.SOUTH )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST ) )
def test_Masyu_whiteDot_inTheMiddleOfTwoIncomingLines_EastWest( self ):
""" -. w .- should result in a vertical line
-- the white dot needs to turn 90 degrees either before or after. """
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..w..\n.....\n....." )
self.Masyu.board.setExit( 1, 2, self.Masyu.board.WEST )
self.Masyu.board.setExit( 3, 2, self.Masyu.board.EAST )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.EAST | self.Masyu.board.WEST ) << 4 | self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) )
def test_Masyu_whiteDot_inTheMiddleOfTwoIncomingLines_NorthSouth( self ):
""" -. w .- """
self.Masyu.board.initBoard( 5, 5, ".....\n.....\n..w..\n.....\n....." )
self.Masyu.board.setExit( 2, 1, self.Masyu.board.NORTH )
self.Masyu.board.setExit( 2, 3, self.Masyu.board.SOUTH )
self.Masyu.dot( 2, 2 )
self.assertEquals( self.Masyu.board.getValue( 2, 2 )[1],
( ( self.Masyu.board.NORTH | self.Masyu.board.SOUTH ) << 4 | self.Masyu.board.EAST | self.Masyu.board.WEST ) )
# try some real boards, keep track of how far they can be solved
def test_Masyu_SolveBoard_00( self ):
self.Masyu.board.initBoard( 3, 3, ".w.\nw..\n..." )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 55.56 )
def test_Masyu_SolveBoard_6x6_easy_example( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_example.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_1( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-1.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_2( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-2.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_3( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-3.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_4( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-4.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_5( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-5.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def notest_Masyu_SolveBoard_6x6_easy_1_1_6( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-6.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_7( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-7.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_8( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-8.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_6x6_easy_1_1_22( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_6x6_easy_1-1-22.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 100.0 )
def test_Masyu_SolveBoard_10x12_hard( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_10x12_hard.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 59.17 )
def test_Masyu_SolveBoard_13x15_medium_1_1_1( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_13x15_medium_1-1-1.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 86.67 )
def test_Masyu_SolveBoard_13x15_hard_1_1_6( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_13x15_hard_1-1-6.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 77.44 )
def test_Masyu_SolveBoard_13x15_hard_1_1_7( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_13x15_hard_1-1-7.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 51.79 )
def test_Masyu_SolveBoard_13x15_hard_1_3_7( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_13x15_hard_1-3-7.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 59.49 )
def test_Masyu_SolveBoard_15x10_hard_1_1_6( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_15x10_hard_1-1-6.txt" )
#self.Masyu.board.setNoExit( 2, 1, self.Masyu.board.EAST )
#self.Masyu.board.setNoExit( 10, 2, self.Masyu.board.NORTH )
#self.Masyu.board.setNoExit( 5, 4, self.Masyu.board.NORTH )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 69.33 )
def test_Masyu_SolveBoard_puzzle_17x17_01( self ):
self.Masyu.board.loadFromFile( "puzzles/puzzle_17x17_01.txt" )
self.Masyu.solveBoard()
self.assertEquals( self.Masyu.board.solvedPercent(), 26.99 )
def suite():
suite = unittest.TestSuite()
suite.addTests( unittest.makeSuite( TestSolveMasyu ) )
return suite
if __name__=="__main__":
unittest.main()
|
4a9a487bbf4fb4bf2f8501dc9dd19dd5a9c9aa00 | sealire/algorithm-py | /sort/shell_sort.py | 905 | 3.796875 | 4 | # -*-coding:utf-8 -*-
def shellSort(input_list):
'''
函数说明:希尔排序(升序)
Parameters:
input_list - 待排序列表
Returns:
sorted_list - 升序排序好的列表
'''
length = len(input_list)
if length <= 1:
return input_list
sorted_list = input_list
gap = length // 2
while gap > 0:
for i in range(gap, length):
j = i - gap
temp = sorted_list[i]
while j >= 0 and temp < sorted_list[j]:
sorted_list[j + gap] = sorted_list[j]
j -= gap
sorted_list[j + gap] = temp
gap //= 2
return sorted_list
if __name__ == '__main__':
input_list = [50, 123, 543, 187, 49, 30, 0, 2, 11, 100]
print('排序前:', input_list)
sorted_list = shellSort(input_list)
print('排序后:', sorted_list)
|
7e7aca4f2c7fa28fa2e1522c7d89e94915d44b0d | noelz8/trabajos-intro | /clase 8 alv.py | 2,442 | 3.8125 | 4 | #lista verificacion positivo
def listap(lista):
if isinstance (lista, list) and lista != []:
return listap_aux(lista)
else: return "Error"
def listap_aux(lista):
if lista ==[]:
return True
elif (lista[0] < 0):
return False
else: return listap_aux(lista[1:])
######Lista y un numero, elimine ese numero de la lista.
def funcion(lista, num):
if isinstance(lista, list):
return funcion_aux(lista, num)
elif isinstance (n, list):
return funcion_aux(lista, num)
else: return "Error"
def funcion_aux(lista, num):
if lista==[]:
return []
elif lista[0]==n:
return funcion_aux(1[1:],n);
else:
return lista[0]+funcion(lista[1:], num)
#Respuest profe
def eliminar (lista, elemento):
if ((isinstance (lista, list) and lista != [] and isinstance (elemento, int)) and elemento >=0):
return eliminar_aux(lista, elemento)
else: return " Revise parametros"
def eliminar_aux(lista, elemento):
if lista == []:
return []
elif lista [0] == elemento:
return eliminar_aux(lista[1:], elemento)
else: return [lista[0]] + eliminar_aux(lista[1:], elemento)
################################################################
#Determinar el minimo de una lista
def lista_minimo(lista):
if isinstance (lista, list):
return lista_minimo_aux(lista)
else: return "Error no hay minimo"
def lista_minimo_aux(lista):
if lista ==[]:
return 0
elif lista[0]== lista[0:]:
return min
else: return [lista[0]] - lista_minimo_aux(lista[0:])
### respuesta profe########################################
def minux(lista):####analizar########!!!!!!
if isinstance (lista, list):
return minimum(lista)
else: return "Error"
def minimum(lista):
if lista [1:]== []: # rojo
return lista[0]
elif lista [0] <= lista [1]: #verde
return minimum([lista[0]] + lista[2:])
else: return minimum (lista[1:])
##########################################################
#sacar el valor mayor
def mayor(lista):
if isinstance (lista, list):
return maximum(lista)
else: return "Error"
def maximum(lista):
if lista[1:]== []:
return lista [0]
elif lista[0]>= lista[1]:
return maximum([lista[0]]+ lista[2:])
else: return maximum(lista[1:])
|
e61abe676bc8d0c2d2271c959b2e09e348d29318 | Vampiro20111/prueba2 | /listas.py | 3,999 | 4.28125 | 4 | #LISTAS: conjunto de elementos preferiblemente del mismo
#tipo. Los elementos se encuentran ordenados por indice.
#es una estructura de datos.
#sintaxis
#se define el identificador, seguido del operador de
#asignacion =, y entre corchetes [] se ponen los elementos
#separados por ,
#arreglo que contiene numeros
numeros = [13, 14, 15, 200.5, -100]
#arreglo(lista) vacia
lista_vacia = []
print("----lectura----")
#lectura de elementos
#se usa el identificador seguido de corchetes que contienen el
#indice del elemento que se quiere leer
print("elemento de indice 3: ", numeros[3])
print("----asignacion-sobreescritura----")
#para asignar o sobreescribir elementos se usa
#el operador de asignacion =
#aca sobreescribimos el elemento de indice 4
#y le asignamos un nuevo valor 10000
numeros[4] = 10000
print("verificamos si el elemento cambio: ", numeros[4])
print("-------Borrado--------")
print("Arreglo antes del borrado: ", numeros)
#para eliminar usamos el metodo pop evaluandolo en el indice
#del elemnto que queremos eliminar
#aca eliminamos el elemento 10000 cuyo indice es 4
numeros.pop(4)
print("Arreglo despues del borrado: ", numeros)
#aca eliminamos el elemento 14 cuyo indice es 1
numeros.pop(1)
print("Arreglo despues del segundo borrado: ", numeros)
print("-------agregacion de elementos--------")
#para agregar se usa el metodo append evaluado en el nuevo
#elemento que queremos agregar
#aca agragamos el elemento 25
print("Arreglo antes de agregar un elemento: ", numeros)
numeros.append(25)
print("Arreglo despues de agregar un elemento: ", numeros)
#que pasa cuando tratamos de acceder a un indice que no existe?
#aca tratamos de acceder al indice 20 de la lista numeros
#numeros[20]
print("---copia de arreglos-----")
#copia de arreglos. Para realizar una copia de arreglos independiente
#debemos usar el metodo copy.
#copia no independiente
edades = [10, 15, 90, 20]
edades_copia = edades
print("contenido antes de modificar edades", edades_copia)
edades.pop(2)
print("contenido despues de modificar edades", edades_copia)
#copia independiente usamos copy()
edades_2 = [100, 12, 19, 5]
edades_copia_2 = edades_2.copy()
print("contenido antes de modificar edades_2", edades_copia_2)
edades_2.pop(2)
print("contenido despues de modificar edades", edades_copia_2)
print("-------operador len--------")
#operador len: nos sirve para saber al ongitud de p.e.
#arreglos, cadenas...
#operador len aplicado a una cadena, devuelve la longitud
#de la cadena, es decir, el numero de caracteres de la cadena
#sintaxis: se una len evaluado en el elemento del cual queremos
#saber su longitud
cadena = "abc zx"
print("longitud de la cadena: ", len(cadena))
#len aplicado a LISTAS
#devuelve el numero de elementos de la lista
lista_len = [True, "ADSI RAPPI", 10.6, 100]
print("longitud de la LISTA: ", len(lista_len))
print("-----1 for aplicado a un arreglo------")
#imprimir cuatro nombres de personas que esten previamente
#guardadas
#SIN ARREGLOS
#aca tenemos una colecccion de nombres de
nombre1 = "Maria"
nombre2 = "Pedro"
nombre3 = "Raul"
nombre4 = "Luisa"
print(nombre1, nombre2, nombre3, nombre4)
#las colecciones las trabajamos con estructuras de datos
#CON ARREGLOS
arreglo_nombres = ["Maria", "Pedro", "Raul", "Luisa"]
#iteracion sobre el arreglo
for nombre in arreglo_nombres:
print("nombres: ", nombre)
#iteracion con range, usando len
#nos permite trabajar con el indice
#si eliminamos un elemento el for no tira
#errores, igual si agregamos elementos
#EL LIMITE SUPERIOS EN LOS CICLOS CUANDO RECORREMOS
#ARREGLOS LO DEBEMOS TRABAJAR SUJETO A LA LONGITUD
#DEL ARREGLOS
arreglo_nombres.pop(2)
for i in range(0, len(arreglo_nombres)):
print("elemento: ", arreglo_nombres[i])
print("----AUMENTAR ELEMENTOS DE UN ARREGLO CON for-----")
#aumentar los elementos del siguiente arreglo en 1
#use for
arreglo_aumento = [5, 6, 7, 8]
for i in range(len(arreglo_aumento)):
arreglo_aumento[i] = arreglo_aumento[i] + 1
print("arreglo despues de aumento: ", arreglo_aumento)
|
693b5293405e04d0c0f567e5c355b335d6270e90 | mfranklin128/interview-prep | /linked_lists/node.py | 537 | 3.875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def append(head, data):
if not head:
return Node(data)
curr = head
while curr.next:
curr = curr.next
new_node = Node(data)
curr.next = new_node
return head
def make_test_list(l):
head = None
for element in l:
head = append(head, element)
return head
def print_list(head):
curr = head
while curr:
print(curr.data, end=' ')
curr = curr.next
print() |
ca23c39962c81dc6020fb57e4d4f70c54bf33ed1 | balassit/improved-potato | /microsoft/Largest-Integer.py | 333 | 4.1875 | 4 | def largestInt(arr):
"""
Time Complexity - O(n)
Space Complexity - O(n)
"""
found = set()
res = 0
for num in arr:
# if found opposite
if -1 * num in found:
res = max(abs(num), res)
else:
found.add(num)
return res
print(largestInt([3, 2, -2, 5, -3]))
|
5a84db125f0597b6769b03199bbe72b1bc09a5c5 | luojianbiao/Python-100 | /Days/Day04/Circulate.py | 986 | 3.515625 | 4 | #!/usr/bin/python
#coding:utf-8#
"""
@author: Luo-Jianbiao
@contact: 1037487025@qq.com
@software: PyCharm
@file: Circulate.py
@time: 2020/5/25 15:18
"""
# 求1-100之间的偶数和
sum = 0
# 如果for循环中没有这样的{}块,我们如何知道for循环中的哪个代码块--那就是靠缩进来判别
for x in range(2,101,2):
sum += x
print(sum)
index = 0
for x in range(1,101,1):
if x % 2 == 0:
index += x
print(index)
"""While循环的使用"""
# 使用while循环实现猜字游戏
import random
answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
number = int(input('请输入:'))
if number < answer :
print('大一点')
elif number > answer :
print('小一点')
else :
print('恭喜你猜对了')
break
print('你总共猜了%d'%counter)
if counter > 7 :
print('智商明显不足')
# 打印九九乘法口诀
for i in range(1,10) :
for j in range(1,i+1) :
print('%d * %d = %d'%(i , j, i * j),end='\t')
print()
|
218e5f7a4e3f2bf5fccc4b7ed60480ef633e01b7 | ravi4all/PythonReg2_30_2020 | /AdvPythonReg/01-OOPS/Descriptors.py | 535 | 3.71875 | 4 | # class Emp:
#
# def __init__(self):
# self.__name = ""
#
# def __get__(self, instance, owner):
# name = self.__name
# print("Name is",name)
# return name
#
# def __set__(self, instance, value):
# self.__name = value
# print("Setter called for",self.__name)
class Emp:
@property
def name(self):
print("Getter Called")
return self.__name
@name.setter
def name(self,value):
print("Setter Called")
obj = Emp() |
aac4843151cc3376977bcac4f3501d76eb29104a | ignaciomgy/python | /Tests/test.py | 1,330 | 3.90625 | 4 | # \n Salto de linea
# \t TAb
# Con strings myString[inicio:fin:paso].
myString = "hola como estas, que tal estuvo el asado"
#print(myString[::-1])
#en valores negativos el indice lo toma desde el final hacia el inicio
#print("tinker"[1:4])
#result = 100 / 88
#print("El resultado es {r:1.3f}".format(r=result))
#otra forma
#print(f"El resultado es {result:1.3f}")
#ordenamiento de listas SORT
una_lista = ["a", "b", "e", "x", "c"]
una_lista.sort()
#print(una_lista)
#para diccionarios
d = {"naranjas":100, "pomelos":300, "sandia":900}
print(d.keys())
print(d.values())
print(d.items())
#tuplas
print("------------- tuplas --------------------")
t = ('a', 'a', 'b')
print(t.count('a'))
print(t.index('a'))
print(set([1,1,2,3]))
numeros = [(1,2,3)]
winner_combinations = [(1,2,3), (4,5,6), (7,8,9), (1,4,7), (2,5,8), (3,6,9), (1,5,9), (3,5,7)]
result = all(elem in winner_combinations for elem in numeros)
print(result)
print('---------------------\n')
# List of string
list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
# List of string
list2 = ['there' , 'hello', 'Hi']
'''
check if list1 contains all elements in list2
'''
result = all(elem in list1 for elem in list2)
if result:
print("Yes, list1 contains all elements in list2")
else :
print("No, list1 does not contains all elements in list2") |
6edd8da05ba792262433ecf6a57941f787c64514 | UCSB-dataScience-ProjectGroup/movie_rating_prediction | /src/dataCall_example.py | 211 | 3.5625 | 4 | import json
from dataCall import dataCall as DC
movie = "0"
while movie != "":
print(" ")
movie = input("Enter a movie name! \n")
print(" ")
if movie != "":
print(DC.findMovie(movie))
|
c670b1bd1ba089fa44383028f80f23b133b2e749 | kajott/adventofcode | /2020/18/aoc2020_18_part2_nogolf.py | 1,943 | 3.671875 | 4 | #!/usr/bin/env python3
import re
V = 0
def my_eval(expr):
tokens = re.findall(r'\d+|[+*()]', expr)
if V >= 2:
print("expr:", repr(expr))
print("tokens:", ' '.join(tokens))
# phase 1: use Shunting Yard Algorithm to convert infix into RPN
ops = []
rpn = []
for token in tokens:
if V >= 2:
print(rpn, ops, token)
if token == "(":
ops.append(token)
elif token == ")":
while ops[-1] != "(":
rpn.append(ops.pop())
if ops[-1] == "(":
ops.pop()
elif token in "+*":
while ops and (ops[-1] != "(") and ((ops[-1] == "+") and (token == "*")):
rpn.append(ops.pop())
ops.append(token)
else:
rpn.append(int(token))
if V >= 2:
print(rpn, ops, "END")
while ops:
rpn.append(ops.pop())
if V >= 2:
print("final RPN:", rpn)
# phase 2: evaluate RPN
stack = []
for token in rpn:
if V >= 2:
print(stack, token)
if token == '+':
n = stack.pop()
stack[-1] += n
elif token == '*':
n = stack.pop()
stack[-1] *= n
else:
stack.append(token)
if V >= 2:
print(stack, "END")
assert len(stack) == 1
if V >= 2:
print()
elif V >= 1:
print(expr.strip(), "=", stack[-1])
return stack.pop()
if __name__ == "__main__":
assert my_eval("1 + 2 * 3 + 4 * 5 + 6") == 231
assert my_eval("1 + (2 * 3) + (4 * (5 + 6))") == 51
assert my_eval("2 * 3 + (4 * 5)") == 46
assert my_eval("5 + (8 * 3 + 9 + 3 * 4 * 3)") == 1445
assert my_eval("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))") == 669060
assert my_eval("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2") == 23340
s = 0
for line in open("input.txt"):
s += my_eval(line)
print(s)
|
e4086b5ea10abba405eb65e8ecd312f7fab30746 | cocka/py4e | /2_python_data_structures/3week/7.2.alt.py | 752 | 3.765625 | 4 | filename = input("Enter the file name: ")
count = 0
dspam = 0
sumdspam = 0
try:
if filename == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
else:
file = open(filename)
except:
print("File cannot be opened:", filename)
for line in file:
if line.startswith('X-DSPAM-Confidence:'):
line = line.rstrip()
linepos = line.find(':')
dspam = line[linepos+1:]
dspam = float(dspam)
count = count + 1
sumdspam = dspam + sumdspam
print("Average spam confidence:", format(sumdspam/count, '.12f'))
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
print(line)
print("Done")
|
dfc0437afbe93a5649b2ba1ae2bf9da7ba49f80d | infinite-Joy/programming-languages | /python-projects/algo_and_ds/best_time_to_buy_and_sell_stocks_kadanes_leetcode121.py | 1,386 | 3.765625 | 4 | """
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
another way of doing this is using the kadanes algorithm
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
7 1 5 3 6 4
_
min val = 1
max diff = 0
1, 4
1, 2
1, 5
1, 3
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
7, 0
6, 0
4, 0
looks like we can use the kadanes algo
if kadanes work then we will be able to do this in O(n)
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1: return 0
minval = prices[0]
maxdiff = 0
for p in prices[1:]:
# we have found the min val and we will update it
minval = min(minval, p)
# now we update the max diff seen so far
maxdiff = max(maxdiff, p - minval)
return maxdiff
prices = [7,1,5,3,6,4]
s = Solution()
print(s.maxProfit(prices))
prices = [7,6,4,3,1]
s = Solution()
print(s.maxProfit(prices))
|
f84b2afc6c35b0a0bf3a5a8568e686db7475bc80 | tanvirraihan142/CtCi-in-python | /Chap 1/1.2.2 Check Permutation.py | 379 | 3.59375 | 4 | def permutation(str1, str2):
if len(str1) != len(str2):
return False
letters = [0 for i in range(128)]
str1_array = list(str1)
for i in str1_array:
letters[ord(i)] += 1
for i in range(len(str2)):
c = str2[i]
letters[ord(c)] -= 1
for i in letters:
if i!=0:
return False
return True
|
4000b94cb2f8ace418792e7de40789092aa9cb72 | devs-nest/python-primer | /Day4/dictionaries.py | 516 | 4.0625 | 4 | my_dict = {"A": "Apple",
"B": "Boy",
"E": "No, not an elephant.",
"C": "Cat",
"D": "Devsnest!!"}
# my_dict["F"] = "Fox"
# my_dict["C"] = "Cow"
# print(my_dict)
# del my_dict["C"]
# my_dict.clear()
# print(my_dict)
# print(my_dict["G"])
# print(my_dict.get("G"))
# print(my_dict)
while True:
dict_key = input("Please enter something: ")
if dict_key == "quit":
break
description = my_dict.get(dict_key, f"we don't have a {dict_key}")
print(description)
|
b3cfe1ba6b28715f0f2bccff2599412d406fd342 | n001ce/python-control-flow-lab | /exercise-5.py | 670 | 4.40625 | 4 | # exercise-05 Fibonacci sequence for first 50 terms
# Write the code that:
# 1. Calculates and prints the first 50 terms of the fibonacci sequence.
# 2. Print each term and number as follows:
# term: 0 / number: 0
# term: 1 / number: 1
# term: 2 / number: 1
# term: 3 / number: 2
# term: 4 / number: 3
# term: 5 / number: 5
# etc.
# Hint: The next number is found by adding the two numbers before it
# Program to display the Fibonacci sequence up to n-th term
n1, n2 = 0, 1
count = 0
print("Fibonacci sequence:")
while count < 50:
print(f"term: {count} / number: {n1}")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1 |
5cfa9a263c7c9ddd18c8ff561be9e9b07801aada | advinstai/python | /solucoes/Duan-Python/Lista1-Python/problem12.py | 180 | 3.828125 | 4 | def count_digits(num):
if(type(num)!=type(1)):
print("Seu input nao eh inteiro")
else:
i=0
while num>=1:
num = num/10
i+=1
return print(i)
count_digits(123456789)
|
7e1d87b492ac42b4d383309e87a644758224f3d2 | lauren-lopez/learning_python | /translate_mRNA.py | 5,330 | 3.515625 | 4 | #!/usr/bin/env python3
import gzip
import sys
import biotools as bt
import argparse
# Use argparse
# Write a program that translates an mRNA
# Assume the protein encoded is the longest ORF
def longest_orf(seq):
# find all ATGs (start codon)
assert len(seq) > 0
atgs = []
for i in range(len(seq) -2):
if seq[i:i+3] == 'ATG': atgs.append(i) # position number of each START codon
# for each ATG, find nearest in-frame STOP
# check if longest
max_len = 0
max_seq = None
for atg in atgs:
stop = None
for i in range(atg, len(seq)-2, 3):
codon = seq[i:i+3]
if codon == 'TAA' or codon == 'TAG' or codon == 'TGA':
stop = i # position number of the first STOP codon after each START
break # Only need to find the first, not all
if stop != None:
cds_len = stop - atg +3 # cds = coding region *Make sure ends with a STOP CODON!*
if cds_len > max_len: # checks if sequence is longest
max_len = cds_len
max_seq = seq[atg:atg+cds_len] # max_seq is the seq with the longest orf length
# translate longest ORF into protein
if max_seq == None: return None
return translate(max_seq)
def translate(seq):
assert(len(seq) % 3 == 0) # ensures the seq len is divisible by 3, i.e. full codons
pro = []
for i in range(0, len(seq), 3):
codon = seq[i:i+3]
if codon == 'AAA': pro.append('K')
elif codon == 'AAC': pro.append('N')
elif codon == 'AAG': pro.append('K')
elif codon == 'AAT': pro.append('N')
elif codon == 'ACA': pro.append('T')
elif codon == 'ACC': pro.append('T')
elif codon == 'ACG': pro.append('T')
elif codon == 'ACT': pro.append('T')
elif codon == 'AGA': pro.append('R')
elif codon == 'AGC': pro.append('S')
elif codon == 'AGG': pro.append('R')
elif codon == 'AGT': pro.append('S')
elif codon == 'ATA': pro.append('I')
elif codon == 'ATC': pro.append('I')
elif codon == 'ATG': pro.append('M')
elif codon == 'ATT': pro.append('I')
elif codon == 'CAA': pro.append('Q')
elif codon == 'CAC': pro.append('H')
elif codon == 'CAG': pro.append('Q')
elif codon == 'CAT': pro.append('H')
elif codon == 'CCA': pro.append('P')
elif codon == 'CCC': pro.append('P')
elif codon == 'CCG': pro.append('P')
elif codon == 'CCT': pro.append('P')
elif codon == 'CGA': pro.append('R')
elif codon == 'CGC': pro.append('R')
elif codon == 'CGG': pro.append('R')
elif codon == 'CGT': pro.append('R')
elif codon == 'CTA': pro.append('L')
elif codon == 'CTC': pro.append('L')
elif codon == 'CTG': pro.append('L')
elif codon == 'CTT': pro.append('L')
elif codon == 'GAA': pro.append('E')
elif codon == 'GAC': pro.append('D')
elif codon == 'GAG': pro.append('E')
elif codon == 'GAT': pro.append('D')
elif codon == 'GCA': pro.append('A')
elif codon == 'GCC': pro.append('A')
elif codon == 'GCG': pro.append('A')
elif codon == 'GCT': pro.append('A')
elif codon == 'GGA': pro.append('G')
elif codon == 'GGC': pro.append('G')
elif codon == 'GGT': pro.append('G')
elif codon == 'GGG': pro.append('G')
elif codon == 'GTA': pro.append('V')
elif codon == 'GTC': pro.append('V')
elif codon == 'GTG': pro.append('V')
elif codon == 'GTT': pro.append('V')
elif codon == 'TAA': pro.append('*')
elif codon == 'TAC': pro.append('Y')
elif codon == 'TAG': pro.append('*')
elif codon == 'TAT': pro.append('Y')
elif codon == 'TCA': pro.append('S')
elif codon == 'TCC': pro.append('S')
elif codon == 'TCT': pro.append('S')
elif codon == 'TCT': pro.append('S')
elif codon == 'TGA': pro.append('*')
elif codon == 'TGC': pro.append('C')
elif codon == 'TGG': pro.append('W')
elif codon == 'TGT': pro.append('C')
elif codon == 'TTA': pro.append('L')
elif codon == 'TTC': pro.append('F')
elif codon == 'TTG': pro.append('L')
elif codon == 'TTT': pro.append('F')
else: pro.append('X')
return ''.join(pro)
for name, seq in bt.read_fasta('mRNA.fa.gz'):
pro = longest_orf(seq)
if pro != None:
print(f'>{name}')
print(pro)
"""
python3 translate_mRNA.py --file ../Lesson05/transcripts.fasta.gz
>CBG00001.1
MTFCENKNLPKPPSDRCQVVVISILSMILDFYLKYNPDKHWAHLFYGASPILEILVIFGMLANSVYGNKLAMFACVLDLVSGVFCLLTLPVISVAENATGVRLHLPYISTFHSQFSFQVSTPVDLFYVATFLGFVSTILILLFLILDALKFMKLRKLRNEDLEKEKKMNPIEKV*
>CBG00006.1
MNGVEKVNKYFDIKDKRDFLYHFGFGVDTLDIKAVFGDTKFVCTGGSPGRFKLYAEWFAKETSIPCSENLSRSDRFVIYKTGPVCWINHGMGTPSLSIMLVESFKLMHHAGVKNPTFIRLGTSGGVGVPPGTVVVSTGAMNAELGDTYVQVIAGKRIERPTQLDATLREALCAVGKEKNIPVETGKTMCADDFYEGQMRLDGYFCDYEEEDKYAFLRKLNSLGVRNIEMESTCFASFTCRAGFPSAIVCVTLLNRMDGDQVQIDKEKYIEYEERPFRLVTAYIRQQTGV*
etc.
"""
|
9358046f93085f1ade11be0be05d4d0f484d5e05 | jackpan123/Python-Crash-Course-exercise | /chapter06/practice/survey.py | 372 | 3.953125 | 4 | favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
survey = ['jen', 'sarah', 'edward', 'phil', 'jack', 'pan']
for name in survey:
if name in favorite_languages.keys():
print(name.title() + ", thank you for survey!")
else:
print(name.title() + ", woulid you like to accept my survey?")
|
c854c78004956b54de558c2b18575e315a51d827 | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom06/sort/bubble_sort3.py | 405 | 4.1875 | 4 | #!/usr/bin/python3
"""
Sorting algorithm Bubble sort
"""
def bubble_sort(seq):
"""
Sorts a list with integer values with the bubble sort algorithm. O(n*n)
"""
for _ in range(len(seq)):
for j in range(len(seq) - 1):
if seq[j] > seq[j+1]:
(seq[j], seq[j+1]) = (seq[j+1], seq[j])
return seq
my_list = [7, 2, 11, 4, 1, 8]
print(bubble_sort(my_list))
|
003c936cadc313650befc2c69d4dc1b65f072fb0 | diorge-zz/usage-of-set-expansion-for-structured-data | /artificialdatasets.py | 3,917 | 3.796875 | 4 | import os
import numpy as np
import pandas as pd
from sklearn.preprocessing import Binarizer
def bernoulli_generation(instances, dimensions, n_classes=2,
density=0.05, density_sd=0.02, target=None):
"""Creates a binary DataFrame using independent Bernoulli distribution.
Each class uses its own distribution for each attribute.
Uses a normal distribution to find the distribution for each value `p`.
:param dimensions: int - number of features
:param instances: int - number of instances
:param n_classes: int - number of classes
:param density: float - approximate ratio of 1s in the data
:param density_sd: float - standard deviation of the density
:returns: a pandas DataFrame with `dimensions` numbered columns,
and a target column
"""
if target is None:
target = np.random.choice(n_classes, size=instances, replace=True)
random_matrix = np.random.rand(instances, dimensions)
df = pd.DataFrame(random_matrix).assign(target=target)
for cls in range(n_classes):
for dim in range(dimensions):
density = np.random.rand() * density_sd + density
threshold = 1.0 - density
binner = Binarizer(threshold)
df.loc[df.target == cls, dim] = binner.transform(
df.loc[df.target == cls, dim].values.reshape(-1, 1)
).reshape(-1, 1)[0]
return df
def binomial_generation(instances, dimensions, n_classes=2,
p_mean=0.2, p_sd=0.05,
n_min=5, n_max=20, target=None):
"""Creates an integer DataFrame using a binomial distribution.
Each class has its own distribution for each feature.
Uses a normal distribution to find the values of `p`,
and a uniform distribution for the values of `n`.
"""
if target is None:
target = np.random.choice(n_classes, size=instances, replace=True)
random_matrix = np.zeros((instances, dimensions))
df = pd.DataFrame(random_matrix).assign(target=target)
for cls in range(n_classes):
for dim in range(dimensions):
p = np.random.randn() * p_sd + p_mean
n = np.random.randint(n_min, n_max + 1)
size = df.loc[df.target == cls, dim].shape
df.loc[df.target == cls, dim] = np.random.binomial(n, p, size)
return df
def sparse_binomial_generation(instances, dimensions, n_classes=2,
density=0.05, density_sd=0.02,
p_mean=0.2, p_sd=0.05,
n_min=5, n_max=20):
base = bernoulli_generation(instances, dimensions, n_classes,
density, density_sd)
weights = binomial_generation(instances, dimensions, n_classes,
p_mean, p_sd, n_min, n_max,
target=base.target)
base_matrix = base.drop('target', axis=1).as_matrix()
weights_matrix = weights.drop('target', axis=1).as_matrix()
final_matrix = base_matrix * weights_matrix
return pd.DataFrame(final_matrix).assign(target=base.target)
def main():
np.random.seed(42)
bernoulli_generation(10000, 200, 50, density=0.3).to_csv(os.path.join('data', 'densebinary.csv'))
bernoulli_generation(10000, 200, 50, density=0.05).to_csv(os.path.join('data', 'sparsebinary.csv'))
sparse_binomial_generation(10000, 200, 30, density=0.3, p_mean=0.4).to_csv(os.path.join('data', 'denseinteger.csv'))
sparse_binomial_generation(10000, 200, 30, density=0.05, p_mean=0.5).to_csv(os.path.join('data', 'sparseinteger.csv'))
bernoulli_generation(100000, 300, 200, density=0.05).to_csv(os.path.join('data', 'hugebinary.csv'))
sparse_binomial_generation(100000, 300, 100, density=0.05, p_mean=0.5).to_csv(os.path.join('data', 'hugeinteger.csv'))
if __name__ == '__main__':
main()
|
ee759aa710eeba647a8a87b1efea71b699737ccf | Styfjion/code | /24.两两交换链表中的节点.py | 1,189 | 3.75 | 4 | #
# @lc app=leetcode.cn id=24 lang=python3
#
# [24] 两两交换链表中的节点
#
# https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
#
# algorithms
# Medium (61.08%)
# Likes: 301
# Dislikes: 0
# Total Accepted: 44.8K
# Total Submissions: 71.6K
# Testcase Example: '[1,2,3,4]'
#
# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
#
# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
#
#
#
# 示例:
#
# 给定 1->2->3->4, 你应该返回 2->1->4->3.
#
#
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
dummy = ListNode(-1)
preNode = dummy
node = head
while node and node.next:
temp = node.next
preNode.next = temp
node.next = temp.next
temp.next = node
preNode = node
node = node.next
return dummy.next
# @lc code=end
|
9396619942f4bf94c9dace6468bf9c2bf50a602e | ChrisKenyon/Practice | /fill_graph.py | 1,467 | 3.703125 | 4 | heights = [2,0,1,0,3,2,1,0,2,3]
#heights = [0,1,0,2,1,0,1,3,2,1,2,1]
#heights = [3,0,0,2,0,0,1,0]
'''
start = 0
start_idx = 0
potential = 0
total_fill = 0
occupied = 0
highest_close = 0
highest_close_idx = 0
i = 0
import pdb
while i < len(heights):
curr = heights[i]
pdb.set_trace()
if curr > start:
total_fill += potential
potential = 0
start = curr
start_idx = i
occupied = 0
elif curr == start:
total_fill += potential
potential = 0
occupied = 0
elif curr < start:
# THIS IS ALL WRONG
pot_rem = (start - curr) * (i - start_idx - 1)
pot_mid_fill = potential - pot_rem - occupied
if pot_mid_fill > 0:
total_fill += pot_mid_fill
potential -= pot_mid_fill
occupied+= pot_mid_fill
potential += start-curr
occupied += curr
i+=1
print total_fill
'''
import pdb
left = [0]*len(heights)
right = [0]*len(heights)
left[0] = heights[0]
right[-1] = heights[-1]
fill = 0
# make a left array showing the highest to the left
for i in range(1,len(heights)):
left[i] = max(left[i-1], heights[i])
# make a right array showing the highest to the right
for i in range(len(heights)-2,-1,-1):
right[i] = max(right[i+1],heights[i])
# find the max you can fill in each spot, the min highest
# to both the left and right
for i in range(len(heights)):
fill += min(left[i],right[i]) - heights[i]
print fill
|
aed79bdf1d8c99af6c1d0098c632b56d65a6f96d | uditiarora/CG-Lab | /lab6/n3.py | 2,598 | 3.84375 | 4 | #perspective projection
from graphics import *
import math
def translate():
for i in range(n):
vertex1[i][0]=vertex1[i][0]+tx
vertex1[i][1]=vertex1[i][1]+ty
vertex1[i][2]=vertex1[i][2]+tz
vertex2[i][0]=vertex2[i][0]+tx
vertex2[i][1]=vertex2[i][1]+ty
vertex2[i][2]=vertex2[i][2]+tz
def line(x0,y0,z0,x1,y1,z1,color):
ax=x0-(z0*0.3)
ay=y0-(z0*0.3)
bx=x1-(z1*0.3)
by=y1-(z1*0.3)
line=Line(Point(ax,ay),Point(bx,by));
line.setFill(color)
line.setWidth(3)
line.draw(win_obj)
def draw3d(clr):
for i in range(n):
x0=vertex1[i][0]
y0=vertex1[i][1]
z0=vertex1[i][2]
x1=vertex2[i][0]
y1=vertex2[i][1]
z1=vertex2[i][2]
line(x0,y0,z0,x1,y1,z1,clr)
def projection():
for i in range(n):
x0=vertex1[i][0]
y0=vertex1[i][1]
z0=vertex1[i][2]
x1=vertex2[i][0]
y1=vertex2[i][1]
z1=vertex2[i][2]
x0=(x0*(a*n1+d)+y0*a*n2+z0*a*n3-a*(d1+d))/(x0*n1+y0*n2+z0*n3-d1)
y0=(y0*(b*n2+d)+x0*b*n1+z0*b*n3-b*(d1+d))/(x0*n1+y0*n2+z0*n3-d1)
z0=(z0*(c*n3+d)+y0*c*n2+x0*c*n1-c*(d1+d))/(x0*n1+y0*n2+z0*n3-d1)
x1=(x1*(a*n1+d)+y1*a*n2+z1*a*n3-a*(d1+d))/(x1*n1+y1*n2+z1*n3-d1)
y1=(y1*(b*n2+d)+x1*b*n1+z1*b*n3-b*(d1+d))/(x1*n1+y1*n2+z1*n3-d1)
z1=(z1*(c*n3+d)+y1*c*n2+x1*c*n1-c*(d1+d))/(x1*n1+y1*n2+z1*n3-d1)
vertex1[i]=[x0,y0,z0]
vertex2[i]=[x1,y1,z1]
win_obj=GraphWin("Orthogonal Projection",900,900)
win_obj.setCoords(-300,-300,600,600)
x_axis=Line(Point(-300,0),Point(600,0))
y_axis=Line(Point(0,-300),Point(0,600))
z_axis=Line(Point(300,300),Point(-300,-300))
x_axis.setOutline("Black")
y_axis.setOutline("Black")
z_axis.setOutline("Black")
x_axis.setArrow('both')
y_axis.setArrow('both')
z_axis.setArrow('both')
x_axis.draw(win_obj)
y_axis.draw(win_obj)
z_axis.draw(win_obj)
info_x=Text(Point(580,-10),"x")
info_x.draw(win_obj)
info_y=Text(Point(-10,580),"y")
info_y.draw(win_obj)
info_ny=Text(Point(-280,-280),"z")
info_ny.draw(win_obj)
color1="blue"
color2="red"
vertex1=[]
vertex2=[]
n=int(input())
for i in range(n):
pointstr=input().split(' ')
points=[int(i) for i in pointstr]
x=points[0]
y=points[1]
z=points[2]
vertex1.append([x,y,z])
x=points[3]
y=points[4]
z=points[5]
vertex2.append([x,y,z])
tx=int(input("x translate : "))
ty=int(input("y translate : "))
tz=int(input("z translate : "))
translate()
print("Enter vector normal :")
n1=int(input())
n2=int(input())
n3=int(input())
a=int(input())
b=int(input())
c=int(input())
print("Enter reference point :")
R0=input().split()
d0=int(R0[0])*n1+int(R0[1])*n2+int(R0[2])*n3
d1=a*n1+b*n2+c*n3
d=d0-d1
draw3d(color1)
projection()
draw3d(color2)
win_obj.getMouse()
win_obj.close() |
66070cb5b210c9b4bc4ec4958db6b17339843581 | vnbl/Sorter_UWC | /sorter_UWC.py | 1,771 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import random
lst_1 = [number for number in range(1,91)]
lst_3 = [number for number in range(1,91)]
lst_2 = [number for number in range(1,91)]
rev_lst = np.zeros([9,30],dtype=int)
random.shuffle(lst_1)
random.shuffle(lst_2)
random.shuffle(lst_3)
for i in range(30):
for u in range(3):
rev_lst[u,i] = lst_1[i]
rev_lst[1,i] = lst_2[i]
rev_lst[2,i] = lst_3[i]
j = i+30
rev_lst[u+3,i] = lst_1[j]
rev_lst[4,i] = lst_2[j]
rev_lst[5,i] = lst_3[j]
k = j+30
rev_lst[u+6,i] = lst_1[k]
rev_lst[7,i] = lst_2[k]
rev_lst[8,i] = lst_3[k]
print(rev_lst)
num_col = 30*9
print(num_col)
def bubbleSort(arr):
n = 30
for l in range(9):
for i in range(29):
for j in range(0, 30-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[l,j] > arr[l,j+1]:
arr[l,j], arr[l,j+1] = arr[l,j+1], arr[l,j]
bubbleSort(rev_lst)
print(rev_lst)
b = 0
for k in range(1,91):
bandera = 0
for i in range(9):
for j in range(30):
if rev_lst[i,j] == k:
bandera = bandera + 1
if bandera > 3:
print("ALERTA")
b = b+1
print(b)
dicts = {}
for i in range(9):
dicts[i] = rev_lst[i,:]
import xlsxwriter
workbook = xlsxwriter.Workbook('arrays.xlsx')
worksheet = workbook.add_worksheet()
row = 0
for col, data in enumerate(rev_lst):
worksheet.write_column(row, col, data)
workbook.close()
|
687e1e26b4da1a331e72c980b09a4a064b81d25f | ashish8796/Codewars | /python-kata/squares_sequence.py | 454 | 4.21875 | 4 | '''
Complete the function that returns an array of length n, starting with the given number
x and the squares of the previous number. If n is negative or zero, return an empty array/list.
'''
x , n = 2, 5
def squares(x, n):
res = []
if n<=0:
return []
else:
for i in range(n):
if i == 0:
res.append(x)
else:
res.append(res[-1]**2)
return res
print(squares(x, n)) |
a3abc7c72e2f895adc25fb3164fe0c63d7b1ba41 | James4Deutschland/Vault7Data | /Logger.py | 737 | 3.6875 | 4 | from datetime import datetime
import time
###
# Kyle Beck, 2017-02-12
# This is a logger module that provides an interface for writing strings to a
# log queue that will be dumped to a file if the program ends execution.
###
log = []
outputDir = 'output/'
# Appends a message to the log. Automatically includes timestamp.
def write(msg):
curTime = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
log.append('[' + curTime + ']:' + msg)
# Dumps the log to a txt document. Document will be timestamped.
def dump():
fileName = ('Log_' + str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) +
'.txt')
with open(outputDir + fileName, 'w', encoding='utf-8') as f:
for l in log:
f.write(l + '\n')
|
2f04d981ded532d2792750a82183f9f1154394c3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/189/usersdata/264/65174/submittedfiles/al2.py | 196 | 4.125 | 4 | # -*- coding: utf-8 -*-
#ENTRADA: NÚMERO QUALQUER:x
x= float(input('digite um número real x:')
#PROCESSAMENTO: u:PARTE INTEIRA, j: PARTE FRACIONÁRIA
u= (X/1)
j= (x%1)
#Saída:
print(u)
print(j) |
295154400b1e8ef8a830aab5d94ac622e5a34665 | sonmaz/gesture-recognition | /sortIncreasing.py | 511 | 3.78125 | 4 | def findSmallest(arr):
list=[]
min = -1
index= -1
for i in range(8):
min = -1
index= -1
for num in range(len(arr)):
if(num not in list):
if(min < 0):
min = arr[num]
index = num
else:
if min > arr[num]:
min = arr[num]
index = num
list.append(index)
return list
def findthresh(arr,threshold):
list=[]
min = -1
index= -1
for num in arr:
if float(num[1]) < float(threshold):
#print arr[num]
list.append(num[0])
return list |
b7f9bf9426b4a3a2ef7223ccf1ee96d60e854c26 | nathanramnath21/project-106 | /project106/cups-of-coffee-and-less-sleep.py | 208 | 3.53125 | 4 | import plotly.express as px
import csv
with open('cups of coffee vs hours of sleep.csv', newline='') as f:
df=csv.DictReader(f)
fig=px.scatter(df, x="sleep in hours", y="Coffee in ml")
fig.show() |
457f47e234ecddc651f27adc051777010279fb25 | josecaro02/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 456 | 3.875 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
p_number = -((number * -1) % 10) if number < 0 else number % 10
if p_number == 0:
print("Last digit of {:d} is {:d} and is 0".format(number, p_number))
elif p_number < 6:
print("Last digit of {:d} is {:d} and is less than 6 and not 0"
.format(number, p_number))
else:
print("Last digit of {:d} is {:d} and is greater than 5"
.format(number, p_number))
|
91959deddeeadc330b2d2e910db6196792d35dd9 | choigabin/PythonProgramming | /IX.Project/TICTACTOE_play.py | 3,356 | 3.59375 | 4 | import tkinter
from tkinter import messagebox
from TICTACTOE import TictactoeGameEngine
class Tictactoe:
def __init__(self):
self.game_engine = TictactoeGameEngine()
def play(self):
#show board
print(self.game_engine)
while True:
#무한반복
#row, col 입력받자
row = int(input('row: '))
col = int(input('col: '))
#말을 놓자
self.game_engine.set(row,col)
#show board
# print(self.game_engine)
#만약에 승자가 있으면, 무승부이면 끝
winner = self.game_engine.check_winner
if winner == 'O' or winner == 'X' or winner == 'd':
break
#결과 출력하자
if winner =='O':
print("O승리")
elif winner == 'X':
print("X승리")
elif winner == 'd':
print("무승부")
class TictactoeGUI:
def __init__(self):
self.game_engine = TictactoeGameEngine()
CANVAS_SIZE =300
self.TITLE_SIZE = CANVAS_SIZE/3
self.root = tkinter.Tk()
self.root.geometry(str(CANVAS_SIZE)+'x'+str(CANVAS_SIZE))
self.root.title('틱 택 토')
self.root.resizable(width=False, height=False)
self.canvas = tkinter.Canvas(self.root, bg='white', width=CANVAS_SIZE, height=CANVAS_SIZE)
self.canvas.pack()
self.images = {}
self.images['O'] = tkinter.PhotoImage(file='O.gif')
self.images['X'] = tkinter.PhotoImage(file='X.gif')
self.canvas.bind('<Button-1>', self.click_handler)
def click_handler(self, event):
x = event.x
y = event.y
col = x//100+1
row = y//100+1
self.game_engine.set(row, col)
# print(self.game_engine)
self.draw_board()
if self.game_engine.check_winner == 'O':
messagebox.showinfo('Game Over','O 이김')
self.root.quit()
elif self.game_engine.check_winner == 'X':
messagebox.showinfo('Game Over','X 이김')
self.root.quit()
elif self.game_engine.check_winner == 'd':
messagebox.showinfo('Game Over','무승부')
self.root.quit()
def draw_board(self):
x=0
y=0
for i,v in enumerate(self.game_engine.board):#->얘를 바탕으로 그림을 그린당!
if v =='X':
self.canvas.create_image(x, y, anchor='nw', image=self.images['X'])
elif v =='O':
self.canvas.create_image(x, y, anchor='nw', image=self.images['O'])
# elif v !='.':
# self.canvas.create_image(x, y, anchor='nw', image=self.images[v])
x += self.TITLE_SIZE
if i%3==2:
x=0
y +=self.TITLE_SIZE
def play(self):
# self.canvas.create_image(0,100, anchor='nw', image=self.images['O'])
# self.canvas.create_image(200, 100, anchor='nw', image=self.images['O'])
# self.canvas.create_image(100, 200, anchor='nw', image=self.images['O'])
# self.canvas.create_image(200, 0, anchor='nw', image=self.images['X'])
# self.canvas.create_image(0,0, anchor='nw', image=self.images['X'])
self.root.mainloop()
if __name__=='__main__':
ttt = TictactoeGUI()
ttt.play() |
0754788645c086f4440803685433196ea9ee22f7 | jtraver/dev | /python3/sudoku/simple1.py | 4,182 | 3.625 | 4 | #!/usr/bin/env python3
#!/usr/bin/python
r0 = [ 5, 0, 9, 8, 1, 2, 7, 0, 0 ]
r1 = [ 0, 0, 0, 9, 0, 6, 2, 5, 1 ]
r2 = [ 0, 0, 2, 0, 3, 0, 0, 6, 0 ]
r3 = [ 0, 0, 0, 0, 0, 5, 0, 7, 0 ]
r4 = [ 8, 7, 6, 0, 2, 0, 5, 4, 9 ]
r5 = [ 0, 4, 0, 7, 0, 0, 0, 0, 0 ]
r6 = [ 0, 5, 0, 0, 9, 0, 8, 0, 0 ]
r7 = [ 7, 9, 8, 1, 0, 4, 0, 0, 0 ]
r8 = [ 0, 0, 1, 2, 7, 8, 4, 0, 5 ]
g0 = [ r0, r1, r2, r3, r4, r5, r6, r7, r8 ]
def print_grid(grid):
for x in range(9):
line = ''
for y in range(9):
line += ' %d' % grid[x][y]
print("%s" % line)
def check_grid_solved(grid):
for x in range(9):
row = {}
col = {}
for y in range(9):
rcell = grid[x][y]
if rcell in row:
return False
row[rcell] = 1
ccell = grid[y][x]
if ccell in col:
return False
col[ccell] = 1
for x in range(1, 10):
if x in row:
pass
else:
return False
if x in col:
pass
else:
return False
for x1 in range(0, 9, 3):
for y1 in range(0, 9, 3):
# print "%d %d" % (x1, y1)
sgrid = {}
for x2 in range(3):
line = ''
for y2 in range(3):
cell = grid[x1 + x2][y1 + y2]
line += " %d" % cell
if cell in sgrid:
return False
sgrid[cell] = 1
# print line
# print "subgrid is ok"
for x in range(1, 10):
if x in sgrid:
pass
else:
return False
return True
def check_grid_consistent(grid):
for x in range(9):
row = {}
col = {}
for y in range(9):
rcell = grid[x][y]
if rcell != 0 and rcell in row:
return False
row[rcell] = 1
ccell = grid[y][x]
if ccell != 0 and ccell in col:
return False
col[ccell] = 1
for x1 in range(0, 9, 3):
for y1 in range(0, 9, 3):
# print "%d %d" % (x1, y1)
sgrid = {}
for x2 in range(3):
line = ''
for y2 in range(3):
cell = grid[x1 + x2][y1 + y2]
line += " %d" % cell
if cell != 0 and cell in sgrid:
return False
sgrid[cell] = 1
# print line
# print "subgrid is ok"
return True
def check_available(grid, x, y):
# print
# print "checking %d %d" % (x, y)
used = {}
for y1 in range(9):
cell = grid[x][y1]
used[cell] = 1
# print " found %d at %d %d" % (cell, x, y1)
for x1 in range(9):
cell = grid[x1][y]
used[cell] = 1
# print " found %d at %d %d" % (cell, x1, y)
x1 = x - (x % 3)
y1 = y - (y % 3)
# print "checking %d %d in grid at %d %d" % (x, y, x1, y1)
for x2 in range(x1, x1 + 3):
for y2 in range(y1, y1 + 3):
cell = grid[x2][y2]
used[cell] = 1
# print " found %d at %d %d" % (cell, x2, y2)
# print " used = %s" % str(used)
available = []
for a1 in range(1, 10):
if a1 in used:
# print " %d is used" % a1
pass
else:
available.append(a1)
# print "%s, %s available: %s" % (str(x), str(y), str(available))
return available
def solve_grid(grid):
for x in range(9):
for y in range(9):
cell = grid[x][y]
# check_available(grid, x, y)
if cell == 0:
a1 = check_available(grid, x, y)
if len(a1) == 1:
c = a1[0]
grid[x][y] = c
print("found %d for %d %d" % (c, x, y))
if check_grid_solved(grid):
return
print_grid(g0)
solve_grid(grid)
def main():
print_grid(g0)
solve_grid(g0)
print_grid(g0)
main()
|
1ec42fccb532e1e8ac52dd0eead4eff69e3d037c | aplcido/Machine-Learning | /Machine-Learning/testing_numpy_speed.py | 1,218 | 3.75 | 4 | """Testing NumPy speed."""
import numpy as np
from time import time
def how_long(func, *args):
"""Execute functions with given arguments, and measure time execution"""
t0 = time()
result = func(*args) #all arguments are passed in as -is
t1 = time()
return result, t1-t0
def manual_mean(arr):
"""Compute mean (average) of all elements in the given 2D array"""
sum = 0
for i in range(0,arr.shape[0]):
for j in range(0,arr.shape[1]):
sum = sum + arr[i][j]
return sum / arr.size
def numpy_mean(arr):
"""compute mean (average) using numpy"""
return arr.mean()
def test_run():
"""Function called by test_run"""
nd1 = np.random.random((1000,10000)) #very large array
#time the two functions, retrieving results and execution times
res_manual, t_manual = how_long(manual_mean, nd1)
res_numpy, t_numpy = how_long(numpy_mean,nd1)
#make sure both give us the same result )upto some precision
assert(abs(res_manual-res_numpy)) <=10e-6, "Results aren't equal!"
#compute speedup
speedup = t_manual / t_numpy
print ("NumPy mean is", speedup, "times faster than manual loops.")
if __name__ == "__main__":
test_run()
|
0480356cb0265460e433ada645e41a6b8bd31535 | fabiangothman/Python | /fundamentals/2_datatype.py | 1,003 | 3.5625 | 4 | #Datatypes
print(type("Hello world")) #str
print(type(100)) #int
print(type(100.5)) #float
print(type(False)) #bool
print(type([1, 2, 3])) #list
print(type(["Hello", "Bye", "Again"])) #list
print(type([10, "Hello", True, 11.5])) #list
print(type(None)) #NoneType
#Inmutables data types (doesn't change)
print(type((10, 30, 55))) #tuple
#Sets list without index
print(type({"Pedro", "Paco", "Luis"})) #str
#Dictionaries
print(type({ #dict
'name': 'Ryan',
'age': 15,
'alias': 'Ry',
'family': {
'mom': 'Grey',
'dad': 'Joseph',
'grandparents':[
{
'type': 'grandmom',
'name':'Norah'
},
{
'type': 'grandmom',
'name':'Philliphs'
}
]
}
}))
#Operators
print("hola_"+"como_"+"estas.") |
212a11aa354cafc7c542d4f5aab9665de315d803 | msw1535540/MachineLearning | /MachineLearning/Leetcode/020.valid-parentheses/Valid_Parentheses.py | 957 | 3.75 | 4 | #-*- coding:utf-8 _*-
"""
@author:charlesXu
@file: Valid_Parentheses.py
@desc:
@time: 2018/02/04
"""
'''
思路:
栈最典型的应用就是验证配对情况,作为有效的括号,有一个右括号就必定有一个左括号在前面,
所以我们可以将左括号都push进栈中,遇到右括号的时候再pop来消掉。
这里不用担心连续不同种类左括号的问题,因为有效的括号对最终还是会有紧邻的括号对。如栈中是({[,来一个]变成({,再来一个},变成(。
'''
'''
了解堆栈的性质
'''
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
d = ['()', '[]', '{}']
for i in range(0, len(s)):
stack.append(s[i])
if len(stack) >2 and stack[-2] + stack[-1] in d:
stack.pop()
stack.pop()
return len(stack) == 0 |
c5414e4f1d1a7162c5ad876dfe9542d603aef8be | tylerphillips55/pyp-w1-gw-language-detector | /language_detector/main.py | 1,848 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
from .languages import LANGUAGES
import string
import re
def detect_language(text, languages):
text = re.compile('[%s]' % re.escape(string.punctuation)).sub('',text) #remove punctuation in string
text = text.lower()
ls = text.split() #returns list of words in text
word_counts = {} #dict will hold {word:frequency in text}
total = {} #dict will hold {language:total common words that appear}
for word in ls: #iterate over words from text
word_counts[word] = word_counts.get(word,0) + 1 #return current count of word if exists or 0 if it has not beed added yet, then increment by 1
for d in languages: #iterate over dictionaries
count = 0 #count tallies total number of common word occurences for langauge
for key,value in word_counts.items(): #iterate over word:frequency pairs in dict of words in text
if key in d["common_words"]: #if word is a common word,
count += value # increment count by word frequency in text and
total[d["name"]] = count # add or update {language:total commmon words}
return max(total, key=total.get) #return language with greatest common word total
|
60fdaa9752810c79c493d9835a6948ab2501f1d9 | RuchiraPatil/Python-3.x | /reverse.py | 84 | 3.609375 | 4 | s = input('Text : ')
for i in range(len(s)-1, -1, -1):
print(s[i], end="")
|
192f81f687b2f02046436fc88cfc24247dcd0ec2 | minhnguyen2610/C4T-BO4 | /Session6/input_number.py | 186 | 3.90625 | 4 | while True:
n = input("Nhap so vao day: ")
print(n)
if n.isdigit():
print("This shitz is el numero")
break
else:
print("This shitz ain't numero")
|
4e0a77eab4b83e2a4854e68fc14fa123bd990ddd | lpuls/CodeExercise | /leetcode/107.二叉树的层次遍历-ii.py | 1,218 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=107 lang=python3
#
# [107] 二叉树的层次遍历 II
#
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
def levelOrderBottom(self, root):
open = list()
close = list()
open.append((root, 0))
while len(open) > 0:
temp = open[0]
temp_node = temp[0]
temp_depth = temp[1]
del open[0]
if None is not temp_node:
if temp_depth >= len(close):
close.insert(0, list())
# python中,a[x] = a[-(len(a) + x)]
close[-(temp_depth + 1)].append(temp_node.val)
open.append((temp_node.left, temp_depth + 1))
open.append((temp_node.right, temp_depth + 1))
return close
# s = Solution()
# r = TreeNode(3)
# r.left = TreeNode(9)
# r.right = TreeNode(20)
# r.left.left = None
# r.left.right = None
# r.right.left = TreeNode(15)
# r.right.right = TreeNode(7)
# print(s.levelOrderBottom(r))
|
f5f71dfb5334932c9424a1fccb1376cb4a442a44 | YutoTakaki0626/My-Python-REVIEW | /basic/is.py | 370 | 3.96875 | 4 | # is演算子:同じオブジェクトかどうかを判定する
a = 1
b = 1
c = 3
d = a
e = 2 - 1
print(id(1))
print(id(a))
print(id(b))
print(a is b)
print(a is not c)
hello = 'hello'
hello2 = 'h' + 'e' + 'l' + 'l' + 'o'
print(hello is hello2)
hello = 'konnichiwa'
print(hello is hello2)
# Noneかどうかの判定によく使う
nothing = None
print(id(nothing)) |
e59a1f49d2cfb1afc7176509c2e2182e0b75aae8 | ljmerza/algorithms | /python-algorithms/insertion.py | 952 | 4.5 | 4 | # insertion sort
def insertion(arr):
'''
for each item in an array, you look at the current item then the item behind it
if the current item is smaller than the one behind it then switch. go to previous item.
you are taking the current item and pushing it back each time the item before it is smaller
until this is not true (inner loop). then you go to the next unsorted item (outer loop) and
keep pushing that back to the sorted position.
'''
arr = arr[:] # copy array
arr_len = len(arr) # get array length
for i in range(1, arr_len): # from 1 to length-1
j=i # start inner loop at currently unsorted index
while j>0 and (arr[j] < arr[j-1]): # if the array is smaller than the one before it then switch
arr[j], arr[j-1] = arr[j-1], arr[j] # switch here
j=j-1 # go previous index
return arr
arr = [5,8,3,1,9,7,4,2,6]
print('unsorted array is {}'.format(arr))
print('insertion sorted array is {}'.format( insertion(arr) ))
|
5ddd9f7cca5a5890a4c64b8b6b2aa87635353f94 | callmekeyz/Digital-Crafts-Classes | /Programming101/user-input.py | 197 | 4.03125 | 4 | #print('hi')
name = input("Name Please:")
subject = input ("Favorite subject\n")
age = input("How old are you?\n")
if age >= 21:
print("Grab a Beer?")
print (f "You said your name is {name}") |
e7498cc2d4bb05ed99f49618b0a40ba266cf935a | C-SON-TC1028-001-2113/parcial-practico-2-marianadiazl | /assignments/17NCuadradoMayor/src/exercise.py | 211 | 4 | 4 |
def main():
numero = int(input("Escribe un numero : "))
#escribe tu código abajo de esta línea
r = 1
while numero<=r**2:
r = r + 1
print(r)
if __name__=='__main__':
main()
|
1286812346feeb6a75e2ff7ecd5f265c851690af | tomduhourq/p4e-coursera | /src/DictPractice/examples.py | 807 | 3.578125 | 4 | __author__ = 'tomasduhourq'
import string
from src.FilePractice.file_helper import choose_file
# Sorting the keys of a dict
counts = {'chuck': 1, 'annie': 42, 'jan': 100}
# Create a list of the keys in the dict
def sort_keys(d):
keys = d.keys()
keys.sort()
for key in keys:
print key, d[key]
sort_keys(counts)
# Using string.translate to get rid of punctuation characters
counts = dict()
for line in open('../ListPractice/romeo.txt'):
line = line.translate(None, string.punctuation).lower()
for word in line.split():
counts[word] = counts.get(word, 0) + 1
# Integrating everything
counts = dict()
for line in choose_file():
for word in line.translate(None, string.punctuation).lower().split():
counts[word] = counts.get(word, 0) + 1
sort_keys(counts)
|
6b588787e8b3404ba2f9e17c5f52710fa930b1f8 | GalyaBorislavova/SoftUni_Python_Advanced_May_2021 | /Exams/Python Advanced Exam - 27 June 2020/01. Bombs.py | 1,601 | 3.609375 | 4 | from collections import deque
def print_data(created_bombs, bomb_effects, bomb_casings):
if bomb_effects:
print(f"Bomb Effects: {', '.join([str(el) for el in bomb_effects])}")
else:
print(f"Bomb Effects: empty")
if bomb_casings:
print(f"Bomb Casings: {', '.join([str(el) for el in bomb_casings])}")
else:
print(f"Bomb Casings: empty")
for bomb_type, count in sorted((created_bombs.items()), key=lambda x: x[0]):
print(f"{bomb_type} Bombs: {count}")
exit(0)
effects = deque([int(el) for el in input().split(", ")])
casings = [int(el) for el in input().split(", ")]
bombs = {
"Datura": 0,
"Cherry": 0,
"Smoke Decoy": 0
}
success = False
while effects and casings:
current_effect = effects.popleft()
current_casing = casings.pop()
current_sum = current_effect + current_casing
if current_sum == 40:
bombs["Datura"] += 1
elif current_sum == 60:
bombs["Cherry"] += 1
elif current_sum == 120:
bombs["Smoke Decoy"] += 1
else:
current_casing -= 5
if current_casing >= 0:
casings.append(current_casing)
effects.appendleft(current_effect)
for value in bombs.values():
if not value >= 3:
success = False
break
success = True
if success:
print("Bene! You have successfully filled the bomb pouch!")
print_data(bombs, effects, casings)
break
if not success:
print("You don't have enough materials to fill the bomb pouch.")
print_data(bombs, effects, casings)
|
22d7f83f4ddf6c201090294d7cbbc54bd1392be7 | jchenpanyu/Python_test | /Python Machine Learning/[Ch6_P170-172]Pipelines.py | 3,079 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 06 13:43:40 2017
"Python Machine Learning"
Chapter 6
Page: 170-172
working with the Breast Cancer Wisconsin dataset, which contains 569 samples of malignant and benign tumor cells.
The first two columns in the dataset store the unique ID numbers of the samples and the corresponding
diagnosis (M=malignant, B=benign), respectively. The columns 3-32 contain 30 real-value features
that have been computed from digitized images of the cell nuclei, which can be used to build a model
to predict whether a tumor is benign or malignant.
@author: vincchen
"""
"""
reading in the dataset directly from the UCI website using pandas:
"""
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data', header=None)
"""
assign the 30 features to a NumPy array X. Using LabelEncoder, we transform the class labels from
their original string representation (M and B) into integers:
"""
from sklearn.preprocessing import LabelEncoder
X = df.loc[:, 2:].values
y = df.loc[:, 1].values
le = LabelEncoder()
y = le.fit_transform(y)
"""
After encoding the class labels (diagnosis) in an array y, the malignant tumors are now represented as class 1,
and the benign tumors are represented as class 0, respectively, which we can illustrate by calling
the transform method of LabelEncoder on two dummy class labels:
"""
le.transform(['M', 'B'])
"""
divide the dataset into a separate training dataset (80 percent of the data) and a
separate test dataset (20 percent of the data):
"""
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1)
"""
standardize the columns in the Breast Cancer Wisconsin dataset before we can feed them to a linear classifier
&
compress our data from the initial 30 dimensions onto a lower two-dimensional subspace via principal component analysis (PCA)
we can chain the StandardScaler, PCA, and LogisticRegression objects in a pipeline:
"""
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
pipe_lr = Pipeline([('scl', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', LogisticRegression(random_state=1))])
pipe_lr.fit(X_train, y_train)
print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))
"""
In the preceding code example, we built a pipeline that consisted of two intermediate steps, a StandardScaler and a PCA transformer, and a logistic regression classifier as a final estimator. When we executed the fit method on the pipeline pipe_lr, the StandardScaler performed fit and transform on the training data, and the transformed training data was then passed onto the next object in the pipeline, the PCA. Similar to the previous step, PCA also executed fit and transform on the scaled input data and passed it to the final element of the pipeline, the estimator.
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.