blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
ecc3558c9e4efab2601815bd0d758ee8de254feb | venky5522/venky | /programs/hyphen_separated_string.py | 132 | 3.953125 | 4 | string = "green-red-yellow-black-white"
string=string.split('-')
string.sort()
string = '-'.join(string)
print(string)
|
4eecc7eea02458b9cd16fd85ec9bddedab86e483 | Munijp/dji-asdk-to-python | /dji_asdk_to_python/flight_controller/attitude.py | 390 | 3.609375 | 4 | class Attitude:
"""
This is a structure for presenting the attitude, pitch, roll, yaw.
"""
def __init__(self, pitch, roll, yaw):
"""
Args:
pitch ([float]): Pitch in degrees
roll ([float]): Roll in degrees
yaw ([float]): Yaw in meters
"""
self.pitch = pitch
self.roll = roll
self.yaw = yaw
|
4a64742a51a07af775b2dfeafc641a6bce651df9 | CaptainTec/OJ | /1007最大子串和-python实现 | 1,268 | 3.546875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# 最大子列和,同时输出第一个和最后一个元素
def MaxSubseqSum(seq):
'''(list of number) -> None
问题:最大子列和问题,同时输出最大子列的第一个和最后一个元素
解决方法:在线处理
时间复杂度:O(n)
>>> seq = [-2, 11, -4, 13, -5, -2]
>>> MaxSubseqSum(seq)
The first value is: 11
The last value is: 13
20
'''
left = 0
right = 0
cur_left = 0
cur_right = 0
mmax = 0
cur_max = 0
ok = 0
for i in range(len(seq)):
if seq[i]>=0:
ok = 1
break
if ok==0:
print("0", seq[0], seq[-1])
else:
for i in range(len(seq)):
cur_max += seq[i]
if cur_max>0:
cur_right = i
if mmax<cur_max:
mmax = cur_max
left = cur_left
right = cur_right
else:
if i>0 and mmax==0 and cur_max==0:
left = right = i
cur_max = 0
cur_left = cur_right = i+1
print(mmax, seq[left], seq[right])
if __name__ == '__main__':
n = int(input()) # 列表长度
seq = [] # 列表
getin = input() # 字符串形式读进来
seqtemp = []
seqtemp = getin.split(' ') # 获取字符
for i in range(n):
seq.append(int(seqtemp[i]))
MaxSubseqSum(seq)
|
9731771ddfe4963840eba90f48443ca1a4fa80a1 | mucheniski/curso-em-video-python | /Mundo2/003EstruturasDeRepeticao/055MaiorMenorPeso.py | 523 | 4.03125 | 4 | # Exercício Python 55: Faça um programa que leia o peso de cinco pessoas.
# No final, mostre qual foi o maior e o menor peso lidos.
maiorPeso = 0
menorPeso = 0
for i in range(1,6):
peso = float(input('Informe o {}º peso: '.format(i)))
if i == 1:
maiorPeso = peso
menorPeso = peso
else:
if peso < menorPeso:
menorPeso = peso
if peso > maiorPeso:
maiorPeso = peso
print('O maior peso foi {} e o menor foi {}'.format(maiorPeso, menorPeso)) |
335bdb58b748317abdacaf5f5c9b6ad6181c40c8 | zdyxry/LeetCode | /greedy/1221_split_a_string_in_balanced_strings/1221_split_a_string_in_balanced_strings.py | 367 | 3.578125 | 4 |
class Solution:
def balancedStringSplit(self, s: str) -> int:
split = 0
unbalance = 0
for i in s:
unbalance += 1 if i == 'R' else -1 # 'R' = +1, 'L' = -1
if not unbalance: # if unbalance == 0
split += 1
return split
s = "RLRRLLRLRL"
res = Solution().balancedStringSplit(s)
print(res) |
51c57b83326cce637aa40701ba9ecbe997f5e20e | ISnxwNick/GeekBrains_PythonBasics_hw | /4less/4_2.py | 983 | 3.90625 | 4 | """
2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых
больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования
списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
Результат: [12, 44, 4, 10, 78, 123].
"""
def larger(arg_list):
for index in range(1, len(arg_list)):
if arg_list[index] > arg_list[index - 1]:
yield arg_list[index]
input_list = list(map(int, input('Введите список через пробел: ').split()))
result_list = []
generator = larger(input_list)
for el in generator:
result_list.append(el)
print(f'Результат: {result_list}')
|
6562fcbd9abb54b8476f6fec80bc6eb5fcc27a91 | bitcsdby/Codes-for-leetcode | /py/Palindrome Number.py | 620 | 3.59375 | 4 | class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False;
if x < 10:
return True
digit_num = 1
while x / digit_num >= 10:
digit_num = digit_num * 10;
if x == digit_num:
return False;
while x != 0:
l = x % 10;
h = x / digit_num;
if l != h:
return False;
x = (x % digit_num) / 10
digit_num /= 100
return True |
a62403d66baa3dcb7c8ccb22c001ee29769d1c4d | posborne/learning-python | /part8-outer-layers/p8ch27ex5.py | 2,612 | 3.671875 | 4 | #!/usr/bin/env python
############################################################
# This is a basic shell... Note that my implementation is
# very similar to Lutz' because I ended up getting stuck
# and following his code
############################################################
import cmd, os, sys, shutil
class PosixShell(cmd.Cmd):
"""
This is a simple *nix shell written in python. It does
not call system primitives but does them itself. Currently
the shell support the following comands:
ls << list current directory contents
cd << change directory
mv << move or rename a file
cp << copy a file
At this point glob operations are not supported (e.g. you
cannot say mv path/to/* ./).
"""
def do_EOF(self, line):
"""
On EOF (Ctrl-D) exit
"""
sys.exit()
def help_ls(self):
print "ls <directory>: list the contents of the specified directory"
print " (current directory by default)"
def do_ls(self, line):
"""
List the current directory
"""
if line == '': dirs = [os.curdir]
else: dirs = line.split()
for dirname in dirs:
print 'Listing fo %s:' % dirname
print '\n'.join(os.listdir(dirname))
def do_cd(self, dirname):
"""
Change to the specified directory. With no directory
specified, go to the home directory.
"""
if dirname == '':
dirname = os.environ['HOME']
os.chdir(dirname)
def do_mkdir(self, dirname):
"""
Create the specified directory as either an absolutely
or relatively specified directory
"""
os.mkdir(dirname)
def do_cp(self, line):
"""
Copy source files to destination
ex:
cp file1 file2 dest/
OR
cp file1 newfile1
"""
words = line.split()
sourcefiles, target = words[:-1], words[-1]
shutil.copy(sourcefile, target)
def do_mv(self, line):
"""
Move source to target (destroys original file)
"""
source, target = line.split()
os.rename(source, target)
def do_rm(self, line):
"""
Remove the specified files
"""
# we can do this as a list comprehension
[os.remove(arg) for arg in line.split()]
class DirectoryPrompt:
def __repr__(self):
return os.getcwd() + '>'
if __name__ == '__main__':
cmd.PROMPT = DirectoryPrompt()
shell = PosixShell()
shell.cmdloop()
|
bc32a384e416808e7588ad62a0b886517e0007f5 | LucasGVallejos/Master-en-MachineLearning-y-RedesNeuronales | /03-Pandas/04-AccediendoACSV.py | 2,883 | 3.546875 | 4 | import pandas as pd
#La mayoria de los datasets vienen en archivos de texto
#Vamos a leer el contenido de movies.csv, le indicamos el separador del csv y formara un dataframe
movies = pd.read_csv('movielens/movies.csv',sep=',')
tags = pd.read_csv('movielens/tags.csv',sep=',')
ratings = pd.read_csv('movielens/ratings.csv',sep=',')
#Vemos las primeras 15 filas del dataframe movies
movies.head(15)
#Si no le pasamos ningun parametro a head(), vemos las primeras 5
tags.head()
ratings.head()
del ratings['timestamp']
del tags['timestamp']
#####################
#OPERANDO CON SERIES
####################
#Extraemos una fila y confirmamos que de hecho es un serie
row0 = tags.iloc[0]
type(row0)
print(row0)
#########################
#OPERANDO CON DATAFRAMES
#########################
ratings.columns
#Ofrece una descripcion de como se estan comportando los datos en dicha columna
ratings['rating'].describe()
#################################
#ANALIZANDO LA ESTADISTICA BASICA
#################################
#Podemos calcular el promedio de una columna.
ratings['rating'].mean()
#Pero tambien podemos calcular el promedio de todo el dataframe
ratings.mean()
#Tambien, individualmente podemos obtener el valor minimo de una columna
ratings['rating'].min()
#O, podemos obtener el valor minimo de todo un dataframe
ratings.min()
#Tambien, individualmente podemos obtener el valor maximo de una columna
ratings['rating'].max()
#O, podemos obtener el valor minimo de todo un dataframe
ratings.max()
#Tambien, podemos calcular la desviacion estandar de una columna
ratings['rating'].std()
#O, podemos calcular la desviacion estandar de todo un dataframe
ratings.std()
#El valor que aparece más veces
ratings['rating'].mode()
#El siguiente metodo nos muestra las posibles correlaciones de una columna
#de un dataframe con respecto a las otras. (cuanto influye el valor de una columna sobre otra)
ratings.corr()
#una correlacion negativa, nos indica una correlacion inversa
#una correlacion positiva, nos indica una correlacion directa
#Usaremos nuestros datasets para alimentar nuestro sistema de machine learning
#Para eso hay que entregarle informacion no erronea. ¿El dataset que presentamos tiene toda informacion correcta?
print("¿Sabemos que nuestro sistema de rating solo tiene 5 puntos?\n")
filter1 = ratings['rating'] > 5
print(filter1.any())
#################
# DATA CLEANING
#################
#Buscaremos valores nulos para ver si debemos borrar algo erroneo
movies.isnull().any()
ratings.isnull().any()
tags.isnull().any()
#Dado que nuestro dataset de tags tiene valores nulos en la columna 'tag', vamos a eliminarlos.
count = tags.shape[0]
print('La cantidad de filas antes de borrar es: ', count)
#borramos las fias que contengas algun valor nulo.
tags = tags.dropna()
print('Se eliminaron -> ', count - tags.shape[0], ' filas')
tags.isnull().any() |
546427944b24c895461c83379023bc50bd5039f2 | renatogcruz/python | /poo_py/s_3_fila.py | 531 | 3.5 | 4 | import heapq
class FilaDePrioridade:
def __init__(self):
self.fila = []
self.indice = 0
def inserir(self, item, prioridade):
heapq.heappush(self.fila,(-prioridade, self.indice, item))
def remover(self):
return heapq.heappop(self.fila)[-1]
class Item:
def __init__(self, nome):
self.nome = nome
def __repr__(self):
return self.nome
fila = FilaDePrioridade()
fila.inserir(Item('marcos'), 28)
fila.inserir(Item('joao'), 30)
fila.inserir(Item('maria'), 18)
print(fila.remover())
|
e80a639d7289567b79ede10f3b869623ba09a5b7 | TheDUZER/challenges | /02 - Temperature Converter.py | 1,872 | 4.25 | 4 | #Temperature Converter by Ian Guitard
def tempConvert():
try:
x = input("Enter the original temperature number immediately followed by a 'C' for Celsius, 'F' for Farenheit, or 'K' for Kelvin.\n Example: 100.243C\n")
#Convert Kelvin to Celsius or Farenheit
if x[-1] == 'K' or x[-1] == 'k':
y = input("Enter the temperature you would like to convert to ('C' or 'F'.)\n")
if y == 'C' or y == 'c':
print(format((float(x[:-1]) - 273.5), '.2f'))
elif y == 'F' or y == 'f':
print(format((float(x[:-1]) * 1.75 - 459.67), '.2f'))
else:
inv()
#Convert Celsius to Farenheit or Kelvin
elif x[-1] == 'C' or x[-1] == 'c':
y = input("Enter the temperature you would like to convert to ('F' or 'K').\n")
if y == 'F' or y == 'f':
print(format((float(x[:-1]) * int(9 / 5) + 32), '.2f'))
elif y == 'K' or y == 'k':
print(format((float(x[:-1] + 273.15)), '.2f'))
else:
inv()
#Convert Farenheit to Celsius or Kelvin
elif x[-1] == 'F' or x[-1] =='f':
y = input("Enter the temperature you would like to convert to ('C' or 'K').\n")
if y == 'C' or y == 'c':
print(format(((float(x[:-1]) - 32) * 5 / 9), '.2f'))
elif y == 'K' or y == 'k':
print(format((float(x[:-1] + 459.67) * 5 / 9), '.2f'))
else:
inv()
#Catches invalid input
else:
inv()
except:
IndexError
SyntaxError
ValueError
inv()
def inv():
print("Invalid Input.\n")
#Main loop
while True:
tempConvert()
input("Press enter to try again.\n")
|
b63bc60dcfd6ceedc8dd1ce672026da3adc4b740 | dlopezg/leetcode | /medium/findNthDigit.py | 2,573 | 3.8125 | 4 | import time
# Find the nth digit of the infinite integer sequence:
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
# EXAMPLE:
# Input: 11
# Output: 0
# Explanation:
# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
# is a 0, which is part of the number 10.
class Solution:
# FUERZA BRUTA: _> Complejidad > O(n) _> TIME EXCEEDED
# Esta primera implementación por fuerza bruta funciona, pero es muy lenta.
# Sobrepasa el límite de tiempo. Básicamente lo que hacemos es mantener dos
# contadores, uno para el número de dígito y otro para el número entero actual
# que estamos analizando. Solo incrementamos el numero entero cuando hayamos
# analizado todos sus digitos con el contador anterior.
def findNthDigit(self, n):
nint = 0
nth = 0
nextChange = 9
actualIntSize = 1
while 1:
# Update nint counter:
nint += 1
# Update nextChange and actualIntSize if needed:
if nint > nextChange:
nextChange = nextChange + 9*(10**actualIntSize)
actualIntSize += 1
# Iterate inside each int number to find the solution:
for intCounter in range(actualIntSize):
# Update nth counter:
nth += 1
if nth == n:
return str(nint)[intCounter]
# OPTIMIZACION: _> Complejidad = O(n) _> TIME EXCEEDED
# La idea puede ser intentar calcular matemáticamente cuantos números
# enteros completos (con todos sus digitos) entra antes de alcanzar
# el valor de n y solamente analizar el último.
def optimizedFindNthDigit (self, n):
nint = 0
nth = 0
nextChange = 9
actualIntSize = 1
while 1:
nint += 1
if nint > nextChange:
nextChange = nextChange + 9*(10**actualIntSize)
actualIntSize += 1
nth += actualIntSize
if nth > n:
return str(nint)[n-(nth-actualIntSize)]
elif nth == n:
return n
# Respuesta: La idea es ir avanznado sobre los valores de n
n = 3
solution = Solution()
start_time = time.time()
print(solution.findNthDigit(n))
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
print(solution.optimizedFindNthDigit(n))
print("--- %s seconds ---" % (time.time() - start_time))
|
8adcacb9d5113f7f3ac7156efde3aff28ab4f606 | mcenek/corrosion | /cbcc/feature.py | 7,152 | 3.578125 | 4 | import numpy as np
import cv2
# Get patch returns a cropped portion of the image provided using the globally defined radius
# pixel is a tuple of (row, column) which is the row number and column number of the pixel in the picture
# image is a cv2 image
def get_patch(pixel, image, height, width, sd_matrix):
radius = 6 # Used for patch size
diameter = 2 * radius
# max_row, max_col, not_used = np.array(image).shape Having this was making it super slow, so just manually put
# in the size of the images i guess
max_row = height
max_col = width
if pixel[0] >= (max_row - radius):
corner_row = max_row - (diameter + 2)
elif pixel[0] >= radius:
corner_row = pixel[0] - radius
else: # With the row coordinate being less than the radius of the patch, it has to be at the top of the image
corner_row = 0 # meaning the row coordinate for the patch will have to be 0
if pixel[1] >= (max_col - radius):
corner_col = max_col - (diameter + 2)
elif pixel[1] >= radius:
corner_col = pixel[1] - radius
else: # With the column coordinate being less than the radius of the patch, it has to be in the left side of the
corner_col = 0 # Image, meaning the column coordinate for the patch will have to be 0
diameter += 1 # Added 1 for the center pixel
return image[corner_row:(corner_row + diameter), corner_col:(corner_col + diameter)], sd_matrix[corner_row:(
corner_row + diameter), corner_col:(corner_col + diameter)]
def k_means_color(patch):
z = patch.reshape((-1, 3))
# Set the rgb values to be floats so it can be used in the k-means function
z = np.float32(z)
# Create the criteria for k-means clustering, 1st: Stop kmeans when the specified accuracy is met, or when the
# max iterations specified is met. 2nd: max iterations. 3rd: epsilon, or required accuracy
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
k = 2
# run the K means clustering using cv2, so it can be done easily with images
# label and center being the important returns, with label being important for producing an image to show the clusters
# and center being useful for the NN and the producing the image to show the clusters, as its the average color of each
# cluster. Arguments for the kmeans, 1st: input data, 2nd: number of clusters needed, 3rd: not sure,
# 4th: the criteria specified above, 5th: number of times to run the clustering taking the best result, 6th: flags
ret, label, center = cv2.kmeans(z, k, None, criteria, 5, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center) # Center will contain the Dominant Colors in their respective color channels
# i.e [[DCb, DCg, DCr], [DCb, DCg, DC3r]] with k = 2
return center.flatten()
# Returns the dominate colors in a patch, which are the average colors based upon what is the center of clusters that
# are built from the rgb values in the patch, patch is a 3d array which is 50x50x3
def get_dominate_color(patch):
b_root = patch[:, :, 0]
g_root = patch[:, :, 1]
r_root = patch[:, :, 2]
b_root_mean = np.mean(b_root)
g_root_mean = np.mean(g_root)
r_root_mean = np.mean(r_root)
b_child_0 = b_root[b_root > b_root_mean]
b_child_1 = b_root[b_root <= b_root_mean]
if b_child_0.size == 0:
half = b_root.size // 2
b_child_0 = b_root[:half]
b_child_1 = b_root[half:]
g_child_0 = g_root[g_root > g_root_mean]
g_child_1 = g_root[g_root <= g_root_mean]
if g_child_0.size == 0:
half = g_root.size // 2
b_child_0 = g_root[:half]
b_child_1 = g_root[half:]
r_child_0 = r_root[r_root > r_root_mean]
r_child_1 = r_root[r_root <= r_root_mean]
if r_child_0.size == 0:
half = r_root.size // 2
b_child_0 = r_root[:half]
b_child_1 = r_root[half:]
center = [np.mean(b_child_0), np.mean(g_child_0), np.mean(r_child_0), np.mean(b_child_1), np.mean(g_child_1),
np.mean(r_child_1)]
return center
def get_texture(sd_patch):
blue = sd_patch[:, :, 0]
green = sd_patch[:, :, 1]
red = sd_patch[:, :, 2]
r_values, r_counts = np.unique(red, return_counts=True)
b_values, b_counts = np.unique(blue, return_counts=True)
g_values, g_counts = np.unique(green, return_counts=True)
r_neg_len = len(r_values[r_values < 0])
b_neg_len = len(b_values[b_values < 0])
g_neg_len = len(g_values[g_values < 0])
r_neg_count = r_counts[:r_neg_len]
r_pos_count = r_counts[r_neg_len:]
r_neg_divisor = np.sum(r_neg_count)
r_pos_divisor = np.sum(r_pos_count)
b_neg_count = b_counts[:b_neg_len]
b_pos_count = b_counts[b_neg_len:]
b_neg_divisor = np.sum(b_neg_count)
b_pos_divisor = np.sum(b_pos_count)
g_neg_count = g_counts[:g_neg_len]
g_pos_count = g_counts[g_neg_len:]
g_neg_divisor = np.sum(g_neg_count)
g_pos_divisor = np.sum(g_pos_count)
r_neg_prob = r_neg_count / r_neg_divisor
r_pos_prob = r_pos_count / r_pos_divisor
b_neg_prob = b_neg_count / b_neg_divisor
b_pos_prob = b_pos_count / b_pos_divisor
g_neg_prob = g_neg_count / g_neg_divisor
g_pos_prob = g_pos_count / g_pos_divisor
return np.array([np.sum(r_neg_prob**2), np.sum(r_pos_prob**2), np.sum(b_neg_prob**2), np.sum(b_pos_prob**2),
np.sum(g_neg_prob**2), np.sum(g_pos_prob**2)])
def run_pixels(image, data, sd_matrix):
h, w = image.shape[:2] # getting the height and width of the image for the patch calculations
return_array = []
texture = []
color = []
coordinates = data[:, 1:] # removing the label for the data
for coordinate in coordinates:
patch, sd_patch = get_patch(coordinate, image, h, w, sd_matrix)
descriptor_color = k_means_color(patch)
descriptor_texture = get_texture(sd_patch)
texture.append(descriptor_texture)
color.append(descriptor_color)
return_array.extend(np.concatenate((texture, color), axis=1))
return np.array(return_array)
def run_image(image, sd_matrix):
h, w = image.shape[:2] # getting the height and width of the image for the patch calculations
return_array = []
texture = []
color = []
for i in range(h):
for j in range(w):
coordinate = (i, j)
patch, sd_patch = get_patch(coordinate, image, h, w, sd_matrix)
descriptor_color = k_means_color(patch)
descriptor_texture = get_texture(sd_patch)
texture.append(descriptor_texture)
color.append(descriptor_color)
return_array.extend(np.concatenate((texture, color), axis=1))
return np.array(return_array)
# The rest of the code is for running an entire folder of images
# def init(filepath):
# for image in os.walk(filepath):
# image_paths = filepath + "\\" + image[2]
# images = np.array([cv2.imread(i) for i in image_paths])
# return images
#
#
# if __name__ == '__main__':
# path = "b:\\cbcc\\defects1\\image047.jpg"
# start_time = time.time()
# radial = radial_points()
# # images = init(path)
# image = cv2.imread(path)
# t_time = time.time()
# print("Images loaded:" + str(t_time - start_time))
# total_time = t_time
# # for image in images:
# h, w = image.shape[:2]
# for i in range(0, h):
# for j in range(0, w):
# center_pixel = (i, j)
# patch, pixel = get_patch(center_pixel, image, h, w)
# descriptor_color = get_dominate_color(patch)
# descriptor_texture = get_texture(patch, pixel, radial)
# print("Final time: " + str(time.time() - total_time))
|
8361ac79b4b5f7153ea82fab8ba5fe3b8c550309 | Jeffrey-A/Data_structures_and_algorithms_Programs | /HW4/Part2/Deck.py | 4,059 | 4.25 | 4 | # Deck.py
#Jeffrey Almanzar part 2
# def size() now is not needed, I am using an instance variable to get the size of the deck as suggested for exercise 1
import random
from Card import Card
class Deck(object):
#------------------------------------------------------------
def __init__(self):
"""post: Creates a 52 card deck in standard order"""
cards = []
self.deck_size = 0
for suit in Card.SUITS:
for rank in Card.RANKS:
cards.append(Card(rank,suit))
self.cards = cards
self.deck_size = len(self.cards)
#Questinon 1, self.deck_size is an instant variable which keeps track of the deck size.
# It does not affect the running time efficiency of operations because both the original self.size() and this instant variable
# are O(1) or theta(1) (constant time, not depending of actual length of the element), because of then len() function.
#------------------------------------------------------------
def deal(self):
"""Deal a single card
pre: self.size() > 0
post: Returns the next card, and removes it from self.card if
the deck is not empty, otherwise returns False"""
self.deck_size = len(self.cards)-1
if self.deck_size > 0:
return self.cards.pop()
else:
return False
#------------------------------------------------------------
def shuffle(self):
"""Shuffles the deck
post: randomizes the order of cards in self"""
#Question 2, from the random module, I am using the shuffle function
random.shuffle(self.cards)
#----------------------Question 3-----------------------------
def addTop(self,rank,suit):
"""pre: rank is an positive integer > 1, suit is a string 'c','d','h' or 's'.
post: adds a card to the deck and place it on the top"""
self.cards.insert(0,Card(rank,suit))
def addBottom(self,rank,suit):
"""pre: rank is an positive integer >1, suit is a string 'c','d','h' or 's'.
post: adds a card to deck and place it at the end of the deck"""
self.cards.insert(self.deck_size-1,Card(rank,suit))
def addRandom(self,rank,suit):
"""pre: rank is an positive integer >1, suit is a string 'c','d','h' or 's'.
post: adds a card to deck and place it on a random place"""
if self.deck_size > 0: # The deck must contain some cards in it, in orther to insert a card in a random position
i = random.randrange(0,self.deck_size-2)# for testing purposes, I do not want this card to be placed at the end
else: #insert the card at the top
i = 0
self.cards.insert(i,Card(rank,suit))
self.deck_size = len(self.cards)
def test():
d = Deck()
print("################Testing size################")
print()
print("Deck initial size --> ",d.deck_size)
for i in range(10): #Dealing ten cards to see if the size length changes
print("Card dealt!--> ",d.deal())
print(d.deck_size," cards left.")
print()
print("################Testing shuffle################")
d.shuffle()
print("The card must not be in ascending order after shuffling them")
for i in d.cards: #printing the cards to see if their original order change
print(i)
print()
print("################Testing AddTop################")
d.addTop(10,'s')
print("d.addTop(10,'s')",d.cards[0])
print()
print("################Testing AddBottom################")
d.addBottom(6,'c')
print("d.addBottom(6,'c')",d.cards[d.deck_size-1])
print()
print("################Testing AddRandom################")
d.addRandom(14,'h')
print("After d.addRandom(14,'h') the size is: ",d.deck_size) #must be equal to 45
print("10 cards were dealt and 3 cards were added")#For this reason
test()
|
0bd7e49b0abe70bfb1d54b30e5341729c7ac1e61 | assi23/calculadoraHavanProWay | /calculadora.py | 1,902 | 3.828125 | 4 | #Criação de variáveis, juntamento com a lista das moedas pré-cadastradas
listaMoedas = ["dólar","Dólar","euro","Euro","real","Real"]
moedaOrigem = input(" Insira a moeda de origem dentro dessas moedas pré-cadastradas:" +str(listaMoedas))
moedaDestino = input(" Insira a moeda de destino dentro dessas moedas pré-cadastradas:" +str(listaMoedas))
moedaVlr = float(input("Insira o valor a ser convertido em " +moedaDestino+ ":"))
moedaVlrConvert = ""
#verificação se as moedas estão na lista pré-cadastrada
if (moedaOrigem in listaMoedas and moedaDestino in listaMoedas):
#se as moedas forem iguais, não é possível executar
if(moedaOrigem == moedaDestino):
print("Você não pode converter duas moedas iguais.")
#se as moedas forem diferentes executa o programa
if(moedaOrigem != moedaDestino):
if(moedaOrigem in ["dólar","Dólar"] and moedaDestino in ["real","Real"]):
moedaVlrConvert = moedaVlr * 5.26
if(moedaOrigem in ["dólar","Dólar"] and moedaDestino in ["euro","Euro"]):
moedaVlrConvert = moedaVlr * 0.82
if(moedaOrigem in ["real","Real"] and moedaDestino in ["dólar","Dólar"]):
moedaVlrConvert = moedaVlr / 5.26
if(moedaOrigem in ["real","Real"] and moedaDestino in ["euro","Euro"]):
moedaVlrConvert = moedaVlr * 0.16
if(moedaOrigem in ["euro","euro"] and moedaDestino in ["dólar","Dólar"]):
moedaVlrConvert = moedaVlr * 1.22
if(moedaOrigem in ["euro","euro"] and moedaDestino in ["real","Real"]):
moedaVlrConvert = moedaVlr * 6.39
print("A moeda escolhida para ser convertida foi " +moedaOrigem+ " e a moeda de destino é " +moedaDestino+" e o valor é:"+str(round(moedaVlrConvert, 2)))
else:
print("As moedas escolhidas não estão na lista.") |
5f3eb49ebc39335642b8dfbcb412f39f35fae3ac | karan68/Python_mini_projects | /rock,paper,scissor.py | 1,570 | 4.1875 | 4 | from random import randint
print("welcomw to the rock,paper and scissor")
print("there will be 5 rounds hope you win!")
#create a list of play options
t = ["Rock", "Paper", "Scissors"]
#assign a random play to the computer
computer = t[randint(0,2)]
#set player to False
player = False
u=0
c=0
i=6
while player == False and i>0:
#set player to True
player = input("Rock, Paper, Scissors?: \t")
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
c+=1
else:
print("You win!", player, "smashes", computer)
u+=1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
c+=1
else:
print("You win!", player, "covers", computer)
u+=1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
c+=1
else:
print("You win!", player, "cut", computer)
u+=1
else:
print("That's not a valid play. Check your spelling!")
i-=1
#player was set to True, but we want it to be False so the loop continues
player = False
computer = t[randint(0,2)]
if u>c:
print("congo you won the rounds")
elif u<c:
print("computer takes the victory")
else:
print("aghhhh! this is a tie")
print("computer:", c)
print("you:", u)
|
c648ebb547b2e0b7e8c2b85a1d949ca39261c5d5 | ma0723/Min_Algorithm | /Algorithm_Practice/Subset.py | 569 | 3.5625 | 4 | arr = [-7,-3,-2,5,8]
n = len(arr)
# 원소의 개수
my_big_list = []
for i in range(1<<n):
# 부분집합의 개수
my_small_list = []
for j in range(n):
# 원소의 개수만큼 비트를 교환
if i&(1<<j):
# i의 j번째 비트가 1이면 j번째 원소를 출력
my_small_list.append(arr[j])
my_big_list.append(my_small_list)
print(my_big_list)
print(len(my_big_list))
for i in my_big_list:
my_sum = 0
for j in i:
my_sum += j
if my_sum == 0:
print('True')
else:
print('False')
|
2e6aa177eca95298c32938448034f3cb722dd741 | yknyim/dictionary-exercises-git | /letter_histogram.py | 349 | 3.890625 | 4 | # from collections import Counter
# user_input = input('Please write anything: ')
# print(Counter(user_input))
###############################
# txt = input('Please enter a word: ')
# small_text = txt.lower()
# count = dict()
# for x in small_text:
# count[x] = count.get(x, 0) + 1
# print(count)
######################################
|
4620abb04fa445a60e81b147610677718c2d79db | VictorPGitHub/AsteroidsGame | /asteroids.py | 4,281 | 3.65625 | 4 | import sys
import random
import pygame
from pygame.locals import *
from game import Game
from ship import Ship
from point import Point
from rocks import Rocks
from star import Star
from bullet import Bullet
class Asteroids( Game ):
"""
Asteroids extends the base class Game to provide logic for the specifics of the game
"""
def __init__(self, name, width, height):
super().__init__( name, width, height )
self.ship = Ship([Point(0, 0), Point(-10, 10), Point(15, 0), Point(-10, -10)])
self.asteroids = []
for i in range(8):
self.asteroids.append(Rocks(i%2))
self.stars=[]
for i in range(400):
self.stars.append(Star())
self.bullets = []
self.dead = False
self.music = True
if self.music == True:
pygame.mixer.music.load("snakeman.mp3")
pygame.mixer.music.play(-1)
def handle_input(self):
super().handle_input()
keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_LEFT] and self.ship:
self.ship.rotate(-1.5)
if keys_pressed[K_RIGHT] and self.ship:
self.ship.rotate(1.5)
if keys_pressed[K_UP] and self.ship:
self.ship.accelerate(0.01)
if keys_pressed[K_DOWN] and self.ship:
self.ship.accelerate(0)
if keys_pressed[K_SPACE] and self.ship:
if len(self.bullets) >= 1:
del self.bullets[0]
self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))
else:
self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))
# TODO: should create a bullet when the user fires
pass
def update_simulation(self):
"""
update_simulation() causes all objects in the game to update themselves
"""
super().update_simulation()
if self.ship:
self.ship.update( self.width, self.height )
for asteroid in self.asteroids:
asteroid.update( self.width, self.height )
for star in self.stars:
star.update( self.width, self.height )
for bullets in self.bullets:
bullets.update(self.width, self.height)
# TODO: should probably call update on our bullet/bullets here
# TODO: should probably work out how to remove a bullet when it gets old
self.handle_collisions()
def render_objects(self):
"""
render_objects() causes all objects in the game to draw themselves onto the screen
"""
super().render_objects()
# Render the ship:
if self.ship:
self.ship.draw( self.screen )
# Render all the stars, if any:
for star in self.stars:
star.draw( self.screen )
# Render all the asteroids, if any:
for asteroid in self.asteroids:
asteroid.draw( self.screen )
# Render all the bullet, if any:
for bullet in self.bullets:
bullet.draw( self.screen )
if self.dead:
font = pygame.font.Font(None, 100)
text = font.render("Game Over", True, (255,0,0))
text_rect = text.get_rect()
text_x = self.screen.get_width()/2 - text_rect.width / 2
text_y = self.screen.get_height() / 2 - text_rect.height / 2
self.screen.blit(text, [text_x, text_y])
def handle_collisions(self):
s = self.ship
a = self.asteroids
b = self.bullets
for i in a:
if s.collide(i):
self.dead = True
self.music = False
if self.music == False:
pygame.mixer.music.load("GameOver.mp3")
pygame.mixer.music.play(1)
else:
pass
"""
handle_collisions() should check:
- if our ship has crashed into an asteroid (the ship gets destroyed - game over!)
- if a bullet has hit an asteroid (the asteroid gets destroyed)
:return:
"""
# TODO: implement collission detection,
# using the collission detection methods in all of the shapes
pass
|
9ea21d7f09e6d8b2b0fa708c90adf408debc228a | Vi-r-us/Python-Projects | /11 Binary Hexadecimal Conversion.py | 1,673 | 4.0625 | 4 | import time
print("Welcome to the Binary/Hexadecimal Converter App.")
while True:
max_value = int(input("\nCompute Binary and Hexadecimal value up to the following Decimal Number: "))
decimal = list(range(1, max_value+1))
print("Generating Lists", end='')
for i in range(3):
print(".", end='')
time.sleep(1)
print(" Complete")
binary = [bin(i) for i in decimal]
hexadecimal = [hex(i) for i in decimal]
print("\nUsing slices, we will now show a portion of the each list.")
lower_value = int(input("What decimal number would you like to start at: "))
upper_value = int(input("What decimal number would you like to stop at: "))
if lower_value < decimal[0] or upper_value > decimal[len(decimal)-1]:
print("\nThe limit is out of range")
else:
print(f"\nDecimal value from {lower_value} to {upper_value} is :")
for i in decimal[lower_value-1:upper_value]:
print(i)
print(f"\nBinary value from {lower_value} to {upper_value} is :")
for i in binary[lower_value - 1:upper_value]:
print(i)
print(f"\nHexadecimal value from {lower_value} to {upper_value} is :")
for i in hexadecimal[lower_value - 1:upper_value]:
print(i)
choice1 = input(f"\nWant to see all the values from 1 to {max_value}. (y/n): ")
if choice1 == 'y' or choice1 == 'Y':
print("\nDecimal\t\tBinary\t\tHexadecimal")
for i in range(max_value):
print(f"{decimal[i]}\t\t\t{binary[i]}\t\t\t{hexadecimal[i]}")
choice2 = input("\nWant to do it again ?: (y/n) ")
if choice2 == 'n' or choice2 == 'N':
break
|
54da2d5e0043974b441f6897fe4251b0ec916bf6 | ogulcangumussoy/Python-Calismalarim | /Hatalar-ve-Istisnalar/Uygulama/hata-yakalama-try-except-finally.py | 288 | 3.6875 | 4 | try:
a = int(input("Sayi1: "))
b=int(input("Sayi2: "))
print(a / b)
except ValueError:
print("Lütfen sayıda string kullanmayınız")
except ZeroDivisionError:
print("Payda 0 olamaz.")
finally:
print("Burası çalışmak zorunda")
print("İşlemler sonlandı.")
|
bb8c697fe5e13bef7978ecfde8f6efacccc82446 | cyct123/LeetCode_Solutions | /394.decode-string.py | 2,237 | 3.671875 | 4 | #
# @lc app=leetcode id=394 lang=python3
#
# [394] Decode String
#
# https://leetcode.com/problems/decode-string/description/
#
# algorithms
# Medium (56.58%)
# Likes: 10322
# Dislikes: 459
# Total Accepted: 615.8K
# Total Submissions: 1.1M
# Testcase Example: '"3[a]2[bc]"'
#
# Given an encoded string, return its decoded string.
#
# The encoding rule is: k[encoded_string], where the encoded_string inside the
# square brackets is being repeated exactly k times. Note that k is guaranteed
# to be a positive integer.
#
# You may assume that the input string is always valid; there are no extra
# white spaces, square brackets are well-formed, etc. Furthermore, you may
# assume that the original data does not contain any digits and that digits are
# only for those repeat numbers, k. For example, there will not be input like
# 3a or 2[4].
#
# The test cases are generated so that the length of the output will never
# exceed 10^5.
#
#
# Example 1:
#
#
# Input: s = "3[a]2[bc]"
# Output: "aaabcbc"
#
#
# Example 2:
#
#
# Input: s = "3[a2[c]]"
# Output: "accaccacc"
#
#
# Example 3:
#
#
# Input: s = "2[abc]3[cd]ef"
# Output: "abcabccdcdcdef"
#
#
#
# Constraints:
#
#
# 1 <= s.length <= 30
# s consists of lowercase English letters, digits, and square brackets
# '[]'.
# s is guaranteed to be a valid input.
# All the integers in s are in the range [1, 300].
#
#
#
# @lc code=start
class Solution:
def decodeString(self, s: str) -> str:
nums = []
subStrs = []
index = 0
while index != len(s):
if s[index].isdigit():
num = ord(s[index]) - ord("0")
while index + 1 != len(s) and s[index + 1].isdigit():
index += 1
num = 10 * num + ord(s[index]) - ord("0")
nums.append(num)
elif s[index] == "]":
letters = []
while subStrs[-1] != "[":
letters.append(subStrs.pop())
subStrs.pop()
repeated = nums.pop()
subStrs.append("".join(letters[::-1]) * repeated)
else:
subStrs.append(s[index])
index += 1
return "".join(subStrs)
# @lc code=end
|
67ca9852309fde372688ebb8baad930cfb0eb9ef | Frecy16/learning | /py_study/pydef/13、匿名函数.py | 977 | 3.9375 | 4 | def add(a, b):
return a + b
# x = add(4, 5) # 函数名(实参) 作用是调用函数,获取到函数的执行结果,并赋值给变量x
# print(x)
# print("0x%X" % id(add))
# fn = add # 相当于给函数add起了一个别名fn
# print("0x%X" % id(fn))
# print(fn(3, 4))
# 除了使用def 关键字定义一个函数以外,还可以使用 lambda 表达式定义一个函数
# 调用匿名函数两种方式:
# 1.给它定义一个名字(很少这样使用)
# 2.把这个函数当做参数传给另一个函数使用
# lambda a, b: a * b # 匿名函数
def calc(a, b, fn):
c = fn(a, b)
return c
def addi(a, b):
return a + b
def minus(a, b):
return a - b
# x1 = calc(1, 2, addi) # a=1,b=2,fn=addi
# x2 = calc(10, 5, minus) # a=10,b=5,fn=minus
# print(x1, x2)
x3 = calc(5, 11, lambda x, y: x + y)
x4 = calc(16, 4, lambda x, y: x - y)
x5 = calc(4, 5, lambda x, y: x * y)
x6 = calc(12, 4, lambda x, y: x / y)
print(x3, x4, x5, x6)
|
cc578bbacd0c246a691a6026851cc0f07d0b0bb6 | Aasthaengg/IBMdataset | /Python_codes/p02831/s641524900.py | 148 | 3.53125 | 4 | from fractions import gcd
def lcm(a, b):
res = a*b / gcd(a, b)
return res
a, b = map(int, input().split())
ans = int(lcm(a, b))
print(ans) |
44b2ec9bac8b5f436d717106fe9614d14c119c6c | masonicGIT/two1 | /two1/lib/bitcoin/hash.py | 2,137 | 3.828125 | 4 | import hashlib
from two1.lib.bitcoin.utils import bytes_to_str
class Hash(object):
""" Wrapper around a byte string for handling SHA-256 hashes used
in bitcoin. Specifically, this class is useful for disambiguating
the required hash ordering.
This assumes that a hex string is in RPC order and a
byte string is in internal order. If `h` is bytes, `h` is
assumed to already be in internal order and this function is
effectively a no-op.
Args:
h (bytes or str): the hash to convert.
Returns:
Hash: a Hash object.
"""
@staticmethod
def dhash(b):
""" Computes the double SHA-256 hash of b.
Args:
b (bytes): The bytes to double-hash.
Returns:
Hash: a hash object containing the double-hash of b.
"""
return Hash(hashlib.sha256(hashlib.sha256(b).digest()).digest())
def __init__(self, h):
if isinstance(h, bytes):
if len(h) != 32:
raise ValueError("h must be 32 bytes long")
self._bytes = h
elif isinstance(h, str):
if len(h) != 64:
raise ValueError("h must be 32 bytes (64 hex chars) long")
self._bytes = bytes.fromhex(h)[::-1]
else:
raise TypeError("h must be either a str or bytes")
def __bytes__(self):
return self._bytes
def __eq__(self, b):
if isinstance(b, bytes):
return self._bytes == b
elif isinstance(b, Hash):
return self._bytes == b._bytes
elif isinstance(b, str):
return self._bytes == Hash(b)._bytes
else:
raise TypeError("b must be either a Hash object or bytes")
def __str__(self):
""" Returns a hex string in RPC order
"""
return bytes_to_str(self._bytes[::-1])
def to_int(self, endianness='big'):
if endianness in ['big', 'little']:
return int.from_bytes(bytes(self), endianness)
else:
raise ValueError("endianness must be either 'big' or 'little'.")
|
645c1783a207e46cfbb1fbaa86e068c62361d477 | rafaelperazzo/programacao-web | /moodledata/vpl_data/445/usersdata/310/101808/submittedfiles/matriz2.py | 490 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
input('Valor de x1: ')
input('Valor de x2: ')
input('Valor de x3: ')
input('Valor de y1: ')
input('Valor de y2: ')
input('Valor de y3: ')
input('Valor de z1: ')
input('Valor de z2: ')
input('Valor de z3: ')
matriz= [
[x1,x2,x3],
[y1,y2,y3],
[z1,z2,z3]
]
if x1+x2+x3=10:
elif y1+y2+y3=10:
elif z1+z2+z3=10:
elif x1+y1+z1=10:
elif x2+y2+z2=10:
elif x3+y3+z3=10:
elif x1+y2+z3=10:
elif x3+y2+z1=10:
else:
Print('N')
|
6fcc88246941164249313afb2695ac56f888a666 | yuanning6/python-exercise | /005.py | 704 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 20:14:55 2020
@author: Iris
"""
username = input('请输入用户名:')
password = input('请输入口令:')
# 用户名是admin且密码是123456则身份验证成功否则身份验证失败
if username == 'admin' and password == '123456':
print('身份验证成功!')
else:
print('身份验证失败!')
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('y = %.1f' % y)
print(f'f({x}) = {y}')
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
else:
if x >= -1:
y = x + 2
else:
y = 5 * x + 3
print(f'f({x}) = {y}')
|
9096a3e99bc7c4fc28b7e2e9cf5c417a1d34470f | LILeilei66/tfLearn | /6_1grad_eager.py | 1,651 | 3.640625 | 4 | """
tf.GradientTape:
================
Record operations for automatic differentiation.
parameters:
persistent: bool, if True, gradient function can be called plural times.
watch_accessed_variables: bool, if False, need to trace the expected tensor by hand.
watch():
========
Ensures that `tensor` is being traced by this tape. 确保某个 tensor 被 tape 追踪.
ref: 1. doc;
2. https://blog.csdn.net/xierhacker/article/details/53174558
"""
import tensorflow as tf
tf.enable_eager_execution()
# <editor-fold desc="ex1">
x = tf.constant(3.0)
with tf.GradientTape() as g:
g.watch(x)
y = x * x
dy_dx = g.gradient(y, x)
print(dy_dx) # tf.Tensor(6.0, shape=(), dtype=float32)
# </editor-fold>
x1 = tf.constant(value=2.0)
x2 = tf.constant(value=3.0)
with tf.GradientTape() as g:
g.watch([x1, x2])
with tf.GradientTape() as gg:
gg.watch([x1, x2])
y = x1 * x1 + x2 * x2
dy_dx = gg.gradient(y,sources=[x1, x2])
d2y_d2x = g.gradient(dy_dx, sources=[x1,x2])
print(dy_dx, d2y_d2x) # tf.Tensor(6.0, shape=(), dtype=float32) tf.Tensor(2.0, shape=(), dtype=float32)
# [<tf.Tensor: id=16, shape=(), dtype=float32, numpy=4.0>, <tf.Tensor: id=17, shape=(), dtype=float32, numpy=6.0>]
# [<tf.Tensor: id=26, shape=(), dtype=float32, numpy=2.0>, <tf.Tensor: id=27, shape=(), dtype=float32, numpy=2.0>]
# todo: 为什么只有两个不是三个?
with tf.GradientTape(persistent=True) as g:
g.watch(x)
y = x * x
z = x * 2
dy_dx = g.gradient(target=y, sources=x)
dz_dx = g.gradient(target=z, sources=x)
print(dy_dx, dz_dx) # tf.Tensor(6.0, shape=(), dtype=float32) tf.Tensor(2.0, shape=(), dtype=float32)
|
ceb0c66e13b10023e08689880054d00ddfe4d1fe | gerglion/ProjectEuler | /Problem_16/problem16.py | 803 | 4.0625 | 4 | #!/usr/bin/python3.4
# Project Euler:
# Problem #16: Power Digit Sum
#
# 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number 2 ^ 1000?
#
# Answer: 1366
import sys
def sum_digits(base,power):
the_number = base ** power
dig_list = []
#print("Exponent:",the_number)
while the_number > 0:
dig = the_number % 10
the_number = the_number // 10
dig_list.append(dig)
#print(dig_list[::-1])
return sum(dig_list)
def main():
if len(sys.argv) > 1:
base = int(sys.argv[1])
power = int(sys.argv[2])
else:
base = 2
power = 15
digit_sum = sum_digits(base,power)
print("Sum of digits of",base,"^",power,":",digit_sum)
if __name__ == '__main__':
main()
|
26448e5269fa0bb7020ee9f8c0da7794a7e27adb | nipuntalukdar/NipunTalukdarExamples | /python/misc/threadedtree.py | 3,873 | 3.5 | 4 | from random import randint
import unittest
class Node(object):
def __init__(self, val):
self.__val__ = val
self.__thread__ = None
self.__left__ = None
self.__right__ = None
@property
def val(self):
return self.__val__
@val.setter
def val(self, val):
self.__val__ = val
@property
def thread(self):
return self.__thread__
@thread.setter
def thread(self, thr):
self.__thread__ = thr
@property
def right(self):
return self.__right__
@right.setter
def right(self, right):
self.__right__ = right
@property
def left(self):
return self.__left__
@left.setter
def left(self, left):
self.__left__ = left
'''
def __repr__(self):
print '[val={} left={} right={} thread={}]'.format(self.__val__,
self.__left__, self.__right__, self.__thread__)
'''
class RThreaded(object):
def __init__(self):
self.__root__ = None
def add(self, node):
if not self.__root__:
self.__root__ = node
else:
start = self.__root__
while True:
if start == start.val:
break
if start.val < node.val:
if not start.right:
start.right = node
if start.thread:
node.thread = start.thread
start.thread = None
break
else:
start = start.right
else:
if not start.left:
start.left = node
node.thread = start
break
else:
start = start.left
def traverse(self):
start = self.__root__
while start:
if start.left:
start = start.left
else:
# No left node
print start.val
# Now print the nodes pointed by the thread
while start.thread:
start = start.thread
print start.val
#Now move to the right node
start = start.right
def count(self):
start = self.__root__
count = 0
while start:
if start.left:
start = start.left
else:
# No left node
count += 1
# Now print the nodes pointed by the thread
while start.thread:
start = start.thread
count += 1
#Now move to the right node
start = start.right
return count
def smallest(self):
if not self.__root__:
raise("Empty tree")
start = self.__root__
while start.left:
start = start.left
return start.val
def biggest(self):
if not self.__root__:
raise("Empty tree")
start = self.__root__
while start.right:
start = start.right
return start.val
class TestMe(unittest.TestCase):
def setUp(self):
self.__tree__ = RThreaded()
def test_print(self):
self.__tree__.add(Node(100))
self.__tree__.add(Node(2))
self.__tree__.add(Node(3))
self.__tree__.add(Node(50))
self.__tree__.add(Node(699))
self.__tree__.add(Node(99))
self.__tree__.add(Node(1000))
self.__tree__.traverse()
self.assertEqual(self.__tree__.count(), 7)
self.assertEqual(self.__tree__.smallest(), 2)
self.assertEqual(self.__tree__.biggest(), 1000)
if __name__ == '__main__':
unittest.main()
|
facace2361ef3f0770357ec4412c5c2d5e42b74f | heuzin/interview-codes | /checkPalindrome.py | 245 | 4 | 4 | # Given the string, check if it is a palindrome.
def checkPalindrome(inputString):
newString = []
for x in reversed(inputString):
newString.append(x)
if ''.join(newString) == inputString:
return True
return False |
96ef5e3d6015e4a48ff6b6e73d1f97c9264dea02 | bishaljung/file_writing_python | /friend_list_data_file_handling.py | 3,074 | 3.65625 | 4 | import sys
import os
def write_data(name):
friend = open(name+".txt",'w')
id_num = input('ID number: ')
phone_number = int(input('phone_number: '))
friend.write("the details of {} is:\n".format(name))
friend.write("name: %s\n" %name)
friend.write("id_num: %s\n"% id_num)
friend.write("phone number: %s\n" %phone_number)
friend.close()
#my problem is :
#name is not passing to the function in read_data
#and read_data function is not working
def delete_data(name):
os.remove(name+".txt")
print("information file, removed successfully")
def read_data(name):
#name = input("enter the name to search data:")
#that is taken from the main method function and is carried out in read_name(name):
#try
with open(name+".txt",'r') as filehandle:
filecontent = filehandle.read()
print(filecontent)
#except ValueError:
# print("enter the valid name")
#another way of reading file:
#infile = open(name,'r')
# contents = infile.read()
# print(contents)
#infile.close()
def edit_data(name):
with open(name+".txt",'r') as filehandle:
filecontent = filehandle.readlines()
print(filecontent)
change_param = input("What would like to change: ")
value = input("Enter the value for %s"%change_param)
person = []
for line in filecontent[1:]:
person.append(line.split(":"))
new_person = []
for data in person:
if data[0]==change_param:
new_person.append([data[0],value])
else:
new_person.append(data)
if change_param == "name":
name = value
with open(name+".txt",'w') as f :
f.write("The details of %s are:\n"%name)
for line in new_person:
f.write("{} : {}".format(line[0],line[1]))
def main():
print("WELCOME TO MY RECORDS")
retake = 'y'
while retake =='y':
option= int(input('enter the option:\n1)to write/add the data\n2)to search the already saved data\n3)to edit the data\n'
'4)to remove the data\n5)to exit the system'))
#name = input("Ener your friends name:")
if option == 5:
sys.exit()
elif option == 1:
name = input("Ener your friends name:")
write_data(name)
elif option == 2:
name = input("Ener your friends name:")
read_data(name)
#read data function is not working
elif option == 3:
name = input("enter the name to edit the data:")
edit_data(name)
elif option == 4:
name = input("enter the name to delete the data:")
delete_data(name)
else:
print("enter the valid option from the main menu:")
main()#when while loop works, it's to be removed
print("do you wish to go to main menu?")
retake = input("enter: y to continue,\npress anything else(enter) : no: ")
main()
|
732064d7c77be799ca1907b7c19d461d4303dbf1 | shinrain/leetcode-python | /code/BalancedBinaryTree.py | 472 | 3.71875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return helper(root)!=-1
def helper(root):
if root is None:
return 0
left = helper(root.left)
right = helper(root.right)
if left==-1 or right==-1 or abs(left-right)>1:
return -1
return max(left, right)+1
|
a08ec5b22a3dc9bc70a465b436e322c08aca304c | ejwessel/LeetCodeProblems | /48_RotateImage/Solution.py | 2,547 | 3.84375 | 4 | def rotate_image(m):
row = 0
col = 0
layer = 0
while row < len(m) - 1 - layer:
for i in range(len(m) - 1 - (2 * layer)):
temp = m[row][col + i]
m[row][col + i] = m[len(m) - 1 - layer - i][col] # top pulling from left
m[len(m) - 1 - layer - i][col] = m[len(m) - 1 - layer][len(m) - 1 - layer - i] # left pulling from bottom
m[len(m) - 1 - layer][len(m) - 1 - layer - i] = m[row + i][len(m) - 1 - layer] # bottom pulling from right
m[row + i][len(m) - 1 - layer] = temp
row += 1
col += 1
layer += 1
def print_matrix(matrix):
for line in matrix:
print(line)
if __name__ == "__main__":
matrix = [
[],
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[]]
print_matrix(matrix)
print()
matrix = [
[1],
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[1]]
print_matrix(matrix)
print()
matrix = [
[1, 2],
[3, 4],
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[3, 1], [4, 2]]
print_matrix(matrix)
print()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
print_matrix(matrix)
print()
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, 7]
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[4, 9, 5, 1], [5, 1, 6, 2], [6, 2, 7, 3], [7, 3, 8, 4]]
print_matrix(matrix)
print()
matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 1],
[2, 3, 4, 5, 6],
[7, 8, 9, 1, 2],
[3, 4, 5, 6, 7]
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[3, 7, 2, 6, 1], [4, 8, 3, 7, 2], [5, 9, 4, 8, 3], [6, 1, 5, 9, 4], [7, 2, 6, 1, 5]]
print_matrix(matrix)
print()
matrix = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 1, 2, 3],
[4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 1, 2, 3],
[4, 5, 6, 7, 8, 9],
]
print_matrix(matrix)
print("=>")
rotate_image(matrix)
assert matrix == [[4, 7, 1, 4, 7, 1], [5, 8, 2, 5, 8, 2], [6, 9, 3, 6, 9, 3], [7, 1, 4, 7, 1, 4], [8, 2, 5, 8, 2, 5], [9, 3, 6, 9, 3, 6]]
print_matrix(matrix)
print()
|
4f148667b4b39576f4f29525c9d27111cf309e00 | driellevvieira/ProgISD20202 | /Gilberto/Aula 9/Aula 09.py | 6,421 | 3.828125 | 4 | # Aula 09 - Programas da aula + slides
import numpy as np
A = np.array([[1,1],
[0,1]])
B = np.array([[2,0],
[3,4]])
print(A)
print(B)
print(A*B)
print(A-B)
print(A+B)
print(A@B)
'''
import numpy as np
vetor = np.array(((1., 0., 0.),(0.,1.,2.)))
print(vetor)
import numpy as np
print(np.zeros((3,4)))
print(np.ones((2,3,4), dtype = np.int16))
print(np.empty((2,3)))
print(np.arange(10,30,5))
print(np.arange(0,2,0.3),'\n')
print(np.random.random(15))
print(np.random.random(15).reshape(3,5))
import numpy as np
from numpy import pi
#x = np.linspace(0,2,9)
x = np.linspace(0,2*pi,100)
f = np.sin(x)
print(x)
print(f)
import numpy as np
a = np.array([20, 30, 40, 50])
b = np.arange(4)
print(a)
print(b)
c = a-b
print(c)
print(b**2)
print(10*np.sin(a))
print(a<35)
print(a-35)
print(35-a)
import numpy as np
A = np.array([[1,1],
[0,1]])
B = np.array([[2,0],
[3,4]])
print(A)
print(B)
print(A*B)
print(A-B)
print(A+B)
print(A@B)
print(A.dot(B))
import numpy as np
a = np.ones((2,3), dtype = int)
b = np.random.random((2,3))
print(a);print(b)
a *= 3
print(a)
#Slide
import numpy as np
array = np.array([[1., 0., 0], [0., 1., 2.]])
print(array)
print(type(array))
import numpy as np
array_1 = np.arange(15).reshape(3, 5)
print(array_1)
print(array_1.shape)
print(array_1.ndim)
print(array_1.dtype.name)
print(array_1.itemsize)
print(array_1.size)
print(type(array_1))
array_2 = np.array([6, 7, 8])
print(array_2)
print(type(array_2))
import numpy as np
array_1 = np.array([2,3,4])
print(array_1)
print(array_1.dtype, "\n")
array_2 = np.array([1.2, 3.5, 5.1])
print(array_2)
print(array_2.dtype)
import numpy as np
array_1 = np.array([1,2,3,4])
array_2 = np.array([(1.5,2,3), (4,5,6)])
print(array_2, "\n")
array_3 = np.array( [ [1,2], [3,4] ], dtype=complex )
print(array_3, "\n")
import numpy as np
print(np.zeros( (3,4) ))
print(np.ones( (2,3,4), dtype=np.int16 ))
print(np.empty( (2,3) ))
print(np.arange( 10, 30, 5))
print(np.arange(0, 2, 0.3), "\n")
import numpy as np
from numpy import pi
print(np.linspace(0, 2, 9))
x = np.linspace(0,2*pi, 100)
print(x, "\n")
f = np.sin(x)
print(f, "\n")
import numpy as np
array_1 = np.arange(6)
print(array_1, "\n")
array_2 = np.arange(12).reshape(4,3)
print(array_2, "\n")
array_3 = np.arange(24).reshape(2,3,4)
print(array_3, "\n")
import numpy as np
print(np.arange(10000),"\n")
print(np.arange(10000).reshape(100,100), "\n")
import numpy as np
a = np.array( [20,30,40,50] )
b = np.arange( 4 )
print(b)
c = a-b
print(c)
print(b**2)
print(10*np.sin(a))
print(a<35)
import numpy as np
A = np.array( [[1,1],
[0,1]])
B = np.array( [[2,0],
[3,4]])
print(A * B)
print(A @ B)
print(A.dot(B))
import numpy as np
a = np.ones((2,3), dtype=int)
b = np.random.random((2,3))
a *= 3
print(a)
b += a
print(b)
import numpy as np
from numpy import pi
a = np.ones(3, dtype=np.int32)
b = np.linspace(0, pi, 3)
print(b.dtype.name)
c = a+b
print(c)
print(c.dtype.name)
d = np.exp(c*1j)
print(d)
print(d.dtype.name)
import numpy as np
a = np.random.random((2,3))
print("a =", a, "\n")
print("sum a = ",a.sum(), "\n")
print("Min a = ", a.min(), "\n")
print("Max a = ", a.max(), "\n")
b = np.arange(12).reshape(3,4)
print("b = ",b,"\n")
print("sum b = ",b.sum(axis=0), "\n")
print("Min b = ",b.min(axis=1), "\n")
print("cumsum b = ", b.cumsum(axis=1), "\n")
import numpy as np
B = np.arange(3)
print("B = ", B, "\n")
print("ex B = ", np.exp(B),"\n")
print("sqrt B = ", np.sqrt(B),"\n")
C= np.array([2., -1., 4.])
print("add B,C =", np.add(B, C), "\n")
import numpy as np
a = np.arange(10)**3
print("a = ",a,"\n")
print("a[2] = ",a[2],"\n")
print("a[2:5] = ",a[2:5],"\n")
a[:6:2]= -1000
print("a = ",a,"\n")
print("a[: :-1] = ",a[ : :-1],"\n")
for i in a:
print(i**(1/3.))
import numpy as np
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4), dtype=int)
print("b = ", b, "\n")
print("b[2,3] = ", b[2,3], "\n")
print("b[0:5, 1] = ", b[0:5, 1], "\n")
print("b[ : ,1] = ", b[ : ,1], "\n")
print("b[1:3, :] = ", b[1:3, : ], "\n")
import numpy as np
c = np.array( [[[ 0, 1, 2],
[ 10, 12, 13]],
[[100,101,102],
[110,112,113]]])
print("c[-1] = ", c[-1], "\n")
print("c.shape = ",c.shape,"\n")
print("c[1,...] = ", c[1,...], "\n")
print("c[...,2] = ", c[...,2], "\n")
for row in c:
print(row)
for element in c.flat:
print(element)
import numpy as np
a = np.floor(10*np.random.random((3,4)))
print("a =",a,"\n")
print("a.shape = ", a.shape,"\n")
print("a.ravel() =", a.ravel(), "\n")
print("a.reshape(6,2) = ",a.reshape(6,2),"\n")
print("a.T = ", a.T,"\n")
print("a.T.shape = ",a.T.shape,"\n")
print("a.shape = ", a.shape, "\n")
import numpy as np
a = np.floor(10*np.random.random((3,4)))
print("a =", a,"\n")
print("a.resizee((2,6)) = ", a.resize((2,6)),"\n")
print("a =", a,"\n")
print("a.resjape(3,-1) = ", a.reshape(3,-1),"\n")
import numpy as np
from numpy import newaxis
a = np.floor(10*np.random.random((2,2)))
print("a = ",a,"\n")
b = np.floor(10*np.random.random((2,2)))
print("b = ",b,"\n")
print("vstack((a,b)) = ", np.vstack((a,b)),"\n")
print("hstack((a,b)) = ", np.hstack((a,b)),"\n")
print("a = ",np.column_stack((a,b)),"\n")
a = np.array([4.,2.])
b = np.array([3.,8.])
print("column_stack((a,b)) =", np.column_stack((a,b)),"\n")
print("hstack((a,b)) = ", np.hstack((a,b)),"\n")
print("a[:,newaxis] = ", a[:,newaxis],"\n")
print("column_stack((a[:,newaxis],b[:,newaxis])) = ", np.column_stack((a[:,newaxis],b[:,newaxis])),"\n")
print("hstack((a[:,newaxis],b[:,newaxis])) =", np.hstack((a[:,newaxis],b[:,newaxis])),"\n")
import numpy as np
a = np.floor(10*np.random.random((2,12)))
print("a = ", a,"\n")
print("hslit(a,3) = ", np.hsplit(a,3),"\n")
print("hsplit(a,(3,4)) = ", np.hsplit(a,(3,4)), "\n")
import numpy as np
a = np.arange(12)
b = a
print(b is a)
b.shape = 3,4
print(a.shape)
def f(x):
print(id(x))
print(id(a))
f(a)
import numpy as np
a = np.arange(12)
c = a.view()
print(c is a, "\n")
print(c.base is a, "\n")
print(c.flags.owndata, "\n")
c.shape = 2,6
print(a.shape, "\n")
c[0,4] = 1234
print(a,"\n")
s = a[1:3]
s[:] = 10
print(a,"\n")
import numpy as np
a = np.arange(12)
d = a.copy()
print(d is a,"\n")
print(d.base is a, "\n")
d[0] = 9999
print(a, "\n")
a = np.arange(int(1e8))
b = a[:100].copy()
''' |
1cddde04dd6426c2b687fa701f358dea45c9b839 | Alvin-21/password-manager | /user_credentials.py | 2,500 | 3.765625 | 4 | from random import choice
import string
class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self, fname, lname, username, password):
self.fname = fname
self.lname = lname
self.username = username
self.password = password
def save_user(self):
"""
saves user objects into user_list
"""
User.user_list.append(self)
@classmethod
def user_exist(cls, username):
"""
Method that checks if a user exists from the user list.
Args:
username: username to search if it exists
Returns :
Boolean: True or false depending if the user exists
"""
for user in cls.user_list:
if user.username == username:
return True
return False
@classmethod
def verify_user(cls, username, password):
"""
Verifies if the user's details match.
"""
for user in cls.user_list:
if (user.username == username and user.password == password):
return True
return False
class Credentials:
"""
Class that generates new credential instances.
"""
credential_list = []
def __init__(self, app, username, password):
self.app = app
self.username =username
self.password = password
def save_credentials(self):
"""
Saves newly created credential objects into credential_list.
"""
Credentials.credential_list.append(self)
@classmethod
def delete_credential(cls, app):
"""
Deletes a saved credential account from the credential_list.
"""
for credential in cls.credential_list:
if credential.app == app:
cls.credential_list.remove(credential)
@classmethod
def password(cls, len=8, chars=string.ascii_letters+string.digits):
"""
Auto-generates a password for the user.
"""
return ''.join([choice(chars) for i in range(len)])
@classmethod
def display_credentials(cls):
"""
Returns the credential list.
"""
return cls.credential_list
@classmethod
def display_app_credential(cls, app):
"""
Returns the specified app credential.
"""
for credential in cls.credential_list:
if credential.app == app:
return credential |
90c132b58970262d6d9e6d19de49f6786403011e | sunnyyeti/Leetcode-solutions | /2011 Final Value o Variable After Performing Operations.py | 1,534 | 4.1875 | 4 | # There is a programming language with only four operations and one variable X:
# ++X and X++ increments the value of the variable X by 1.
# --X and X-- decrements the value of the variable X by 1.
# Initially, the value of X is 0.
# Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
# Example 1:
# Input: operations = ["--X","X++","X++"]
# Output: 1
# Explanation: The operations are performed as follows:
# Initially, X = 0.
# --X: X is decremented by 1, X = 0 - 1 = -1.
# X++: X is incremented by 1, X = -1 + 1 = 0.
# X++: X is incremented by 1, X = 0 + 1 = 1.
# Example 2:
# Input: operations = ["++X","++X","X++"]
# Output: 3
# Explanation: The operations are performed as follows:
# Initially, X = 0.
# ++X: X is incremented by 1, X = 0 + 1 = 1.
# ++X: X is incremented by 1, X = 1 + 1 = 2.
# X++: X is incremented by 1, X = 2 + 1 = 3.
# Example 3:
# Input: operations = ["X++","++X","--X","X--"]
# Output: 0
# Explanation: The operations are performed as follows:
# Initially, X = 0.
# X++: X is incremented by 1, X = 0 + 1 = 1.
# ++X: X is incremented by 1, X = 1 + 1 = 2.
# --X: X is decremented by 1, X = 2 - 1 = 1.
# X--: X is decremented by 1, X = 1 - 1 = 0.
# Constraints:
# 1 <= operations.length <= 100
# operations[i] will be either "++X", "X++", "--X", or "X--".
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if "++" in op else -1 for op in operations) |
5b0f38fb1512e2c37533d3145fa067dd8df607cf | VigneshwarRavichandran/logics | /SP - Palindrome Family.py | 830 | 3.796875 | 4 | t=int(input())
while t>0:
a=input()
odd_str=""
odd_count=0
even_str=""
even_count=0
parent_count=0
for i in range(0,len(a),2):
odd_str=odd_str+a[i]
for i in range(1,len(a),2):
even_str=even_str+a[i]
odd_temp = odd_str[::-1]
if(odd_str==odd_temp):
odd_count=odd_count+1
even_temp = even_str[::-1]
if(even_str==even_temp):
even_count=even_count+1
rev_str = a[::-1]
if(a==rev_str):
parent_count=parent_count+1
if(parent_count==1):
print("PARENT")
elif((odd_count==1)and(even_count==1)):
print("TWIN")
elif(odd_count==1):
print("ODD")
elif(even_count==1):
print("EVEN")
else:
print("ALIEN")
t=t-1
|
072e09c89e4f4f0df619c7e96a1ca89752d3ce8a | DarkAlexWang/leetcode | /C3IOT/string_replace.py | 1,990 | 3.53125 | 4 | class Solution:
def string_replace(self, string, s, t):
array = list(string)
if len(s) >= len(t):
return self.replace_shorter(array, s, t)
return self.replace_longer(array, s, t)
def replace_shorter(self, array, s, t):
slow = 0
fast = 0
while fast < len(array):
if fast <= len(array) - len(s) and self.equal_substring(array, fast, s):
self.copySubstring(array, slow, t)
slow += len(t)
fast += len(s)
else:
array[slow] = array[fast]
slow += 1
fast += 1
return "".join(array[:slow])
def replace_longer(self, array, s, t):
matches = self.getAllMatches(array, s)
res = [''] * (len(array) + len(matches) * (len(t) - len(s)))
lastIndex = len(matches) - 1
slow = len(array) - 1
fast = len(res) - 1
while slow >= 0:
if lastIndex >= 0 and slow == matches[lastIndex]:
self.copySubstring(res, fast - len(t) + 1, t)
fast -= len(t)
slow -= len(s)
lastIndex -= 1
else:
res[fast] = array[slow]
return "".join(res)
def equal_substring(self, array, fromIndex, s):
for i in range(len(s)):
if array[fromIndex + i] != s[i]:
return False
return True
def copySubstring(self, res, fromIndex, t):
for i in range(len(t)):
res[fromIndex + 1] = t[i]
def getAllMatches(self, array,s):
matches = []
i = 0
while i < len(array) - len(s):
if self.equal_substring(array, i, s):
matches.append(i + len(s) - 1)
i += len(s)
else:
i += 1
return matches
if __name__ == "__main__":
solution = Solution()
ans = solution.string_replace('abscdged', 'cd', 'xxxx')
print(ans)
|
7ca6f7aacd5a3560efa31a6b3f57e043ee94560b | domino14/euler | /39.py | 633 | 4 | 4 | """
a^2 + b^2 = c^2
p = a + b + c
"""
def solutions(p):
"""
Find number of solutions for a right triangle with integral sides.
>>> len(solutions(120))
3
"""
sols = set()
for a in range(1, p-2):
for b in range(1, a-1):
c = p - a - b
if a**2 + b**2 == c**2:
sols.add((a, b, c))
return sols
max_sols = 0
max_p = None
for p in range(3, 1001):
num_sols = len(solutions(p))
if num_sols > max_sols:
max_sols = num_sols
max_p = p
print max_p, solutions(max_p)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
f186f783eaa01607371da45a8dc0993bb5f86492 | pneumoo/reddit-psio-tool | /pushshiftTool.py | 14,398 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 21:43:23 2018
@author: Brian
"""
import json
import requests
import time
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
"""
Returns a string of the URL COMMENT Search command for Pushshift.io
Example: 'https://api.pushshift.io/reddit/search/comment/?author=username123'
Inputs (not all have been implemented here, see github.com/pushshift/api for more info)
* q is search term, type=str.
PSIO will search the comments' 'body' field for this search term
* author is a redditor user name, type=str
Restrict search to a specific author
* after is an epoch value or integer + "s,m,h,d" (i.e. 30d for 30 days), type=str
Returns any results more recently than this date
* before is an epoch value or integer + "s,m,h,d" (i.e. 30d for 30 days), type=str
Returns any results prior to this date
* size Number of results to return, type=str or int
Number must be <=500
* fields is a single string of comma-delimited database fields
Ex: fields='body,created_utc,id,link_id,parent_id,subreddit'
* ids is a comma-delimited string of a reddit comment ID number
Either form acceptable: "t1_dvtkqx4" or "dvtkqx4"
Note: leaving all inputs blank defaults to retrieving the most recent 25
comments in the database with all fields returned.
"""
def mkComURL(q=None,
author=None,
after=None,
before=None,
size=None,
fields=None,
ids=None):
searchstr = 'https://api.pushshift.io/reddit/comment/search/?'
if q:
searchstr += "q={0}&".format(q)
if author:
searchstr += "author={0}&".format(author)
if after:
searchstr += "after={0}&".format(after)
if before:
searchstr += "before={0}&".format(before)
if size:
searchstr += "size={0}&".format(size)
if fields:
searchstr += "fields={0}&".format(fields)
if ids:
searchstr += "ids={0}&".format(ids)
return(searchstr)
"""
Returns a string of the URL SUBMISSION Search command for Pushshift.io
Example: 'https://api.pushshift.io/reddit/search/submission/?author=username123'
Inputs (not all have been implemented here, see github.com/pushshift/api for more info)
* q is search term, type=str.
PSIO will search ALL possible fields for this string
* author is a redditor user name, type=str
Restrict search to a specific author
* after is an epoch value or integer + "s,m,h,d" (i.e. 30d for 30 days), type=str
Returns any results more recently than this date
* before is an epoch value or integer + "s,m,h,d" (i.e. 30d for 30 days), type=str
Returns any results prior to this date
* size Number of results to return, type=str or int
Number must be <=500
* fields is a single string of comma-delimited database fields
Ex: fields='body,created_utc,id,link_id,parent_id,subreddit'
* ids is a comma-delimited string of a reddit comment ID number
Either form acceptable: "t1_dvtkqx4" or "dvtkqx4"
*
"""
def mkSubURL(q=None,
author=None,
after=None,
before=None,
size=None,
fields=None,
ids=None):
searchstr = 'https://api.pushshift.io/reddit/submission/search/?'
if q:
searchstr += "q={0}&".format(q)
if author:
searchstr += "author={0}&".format(author)
if after:
searchstr += "after={0}&".format(after)
if before:
searchstr += "before={0}&".format(before)
if size:
searchstr += "size={0}&".format(size)
if fields:
searchstr += "fields={0}&".format(fields)
if ids:
searchstr += "ids={0}&".format(ids)
return(searchstr)
### FOLLOW commentSearch function for building this...
"""
Returns JSON object of requested Pushshift.io data
inputs:
* psioAPIendpoint is a URL command to extract data from db
"""
def getPSIOjson(psioAPIendpoint):
r = requests.get(psioAPIendpoint)
rjson = r.json()
return(rjson)
"""
Returns a list of comment parameter values
inputs:
* json_data is json output from pushshift.io
* commentParam (str) is any of the Keys returned for each comment
See https://github.com/pushshift/api "Search parameters for comments" section
"""
def getParam(json_data, param):
data = json_data['data']
paramList = []
for i in data:
try:
paramList.append(i[param])
except:
print("**ERROR: Could not find " + param + " in the following entry. SKIPPING***")
print(i)
print()
return(paramList)
def getAllUserComments():
author = input("Get all comment info for user: ")
maxsize = 100
loopcount = 0
beforetime = int(time.time())
userdata = {'data':[]}
while True:
# print("LOOP: {0}".format(loopcount))
# print("beforetime: {0}".format(beforetime))
url = mkComURL(author=author, before=beforetime, size=maxsize)
data = getPSIOjson(url)
userdata['data'] += data['data']
datalen = len(data['data'])
if datalen == maxsize:
print("{0} comments found".format(maxsize*loopcount))
else:
print("COMPLETE. {0} comments found.".format(maxsize*loopcount + datalen))
break
loopcount += 1
beforetime = data['data'][-1]['created_utc']
return(userdata)
def getAllUserSubmissions():
author = input("Get all submission info for user: ")
maxsize = 100
loopcount = 0
beforetime = int(time.time())
userdata = {'data':[]}
while True:
url = mkSubURL(author=author, before=beforetime, size=maxsize)
data = getPSIOjson(url)
userdata['data'] += data['data']
datalen = len(data['data'])
if datalen == maxsize:
print("{0} submissions found".format(maxsize*loopcount))
else:
print("COMPLETE. {0} submissions found.".format(maxsize*loopcount + datalen))
break
loopcount += 1
beforetime = data['data'][-1]['created_utc']
return(userdata)
"""
Returns a list of comment IDs for a submission ID - PSIO IS BUGGY??
inputs:
* Base36 submission ID as a string
"""
def getCommentIDsForSubmission(submissionID):
searchstr = 'http://api.pushshift.io/reddit/submission/comment_ids/' + str(submissionID)
jsondata = getPSIOjson(searchstr)
return(jsondata["data"])
"""
"""
def getParents(comment_parent_ids):
numperreq = 100 #max number of parent comments to get per request
parent_data = {'data':[]}
com_parents_string = ""
sub_parents_string = ""
commentbaseurl = "https://api.pushshift.io/reddit/comment/search?ids="
subbaseurl = "https://api.pushshift.io/reddit/submission/search?ids="
print("Total parent comments = " + str(len(parent_data["data"])))
for i,j in enumerate(comment_parent_ids):
# print(i,j,len(comment_parent_ids))
if j[1] == '1':
com_parents_string += j[3:] + ','
if j[1] == '3':
sub_parents_string += j[3:] + ','
if (i%numperreq == numperreq-1) or (i+1 == len(comment_parent_ids)):
#comments and submissions have to be queried separately
print(com_parents_string)
print(sub_parents_string)
if com_parents_string != "":
print("Getting parent comments from PSIO...")
com_search_str = commentbaseurl + com_parents_string
print(com_search_str)
comjsondata = getPSIOjson(com_search_str)
for comment in comjsondata["data"]:
parent_data["data"].append(comment)
print("Parent comments fetched in last batch = " + str(len(comjsondata["data"])))
if sub_parents_string != "":
print("Getting parent submissions from PSIO...")
sub_search_str = subbaseurl + sub_parents_string
print(sub_search_str)
subjsondata = getPSIOjson(sub_search_str)
for sub in subjsondata["data"]:
parent_data["data"].append(sub)
print("Parent submissions fetched in last batch = " + str(len(subjsondata["data"])))
com_parents_string = "" #clears comment ID list string for next batch
sub_parents_string = "" #clears submission ID list string for next batch
print("Total parent comments = " + str(len(parent_data["data"])))
print(".")
print(".")
return(parent_data)
"""
=====================================================================
+++++++++ PLOTTING AND ANALYSIS +++++++++++++++++++++++++++++++++++++
=====================================================================
Ideas:
* Language processing of comments
* Language processing of submission titles
* subreddit activity over time
* Top-level domains used over time
* Duration between activity heat map
* Engagement level in comments sections of own submissions
"""
"""
===== Compares user selfposts to linkposts
only works with submission json data
"""
def selfVsLink(submissionjson):
selfpost=0
linkpost=0
for submission in submissionjson["data"]:
if submission["is_self"]:
selfpost+=1
else:
linkpost+=1
print("{0}% link posts".format(100*linkpost/(selfpost+linkpost)))
print("Selfposts:linkposts => {0}:{1}".format(selfpost,linkpost))
return(selfpost, linkpost)
"""
===== Examines time-of-day posting patterns w/ plots
Will work with comment or submission json data
"""
def actionsTimeOfDay(userdata, local_time=False):
i=0
utc_list = []
mpl_dates = []
tod_list = []
while i < len(userdata["data"]):
utc_item = userdata["data"][i]["created_utc"]
mpl_item = matplotlib.dates.epoch2num(utc_item)
if local_time:
#Making time-of-day (by hour) so we can plot on 0-24h scale
h = time.localtime(utc_item).tm_hour
m = time.localtime(utc_item).tm_min
s = time.localtime(utc_item).tm_sec
tod_list.append((h*60*60 + m*60 + s)/3600)
else:
h = time.gmtime(utc_item).tm_hour
m = time.gmtime(utc_item).tm_min
s = time.gmtime(utc_item).tm_sec
tod_list.append((h*60*60 + m*60 + s)/3600)
utc_list.append(utc_item)
mpl_dates.append(mpl_item)
i+=1
# time of day vs. posting date
plt.figure()
plt.plot_date(mpl_dates, tod_list, xdate=True, ydate=False)
plt.title("Posting time throughout history")
plt.xlabel('Posting date')
if local_time==1:
plt.ylabel('Time of Day (local)')
else:
plt.ylabel('Time of Day (UTC)')
plt.show()
# 24-hour histogram of posts, binned by minute
plt.figure()
plt.hist(tod_list, bins=24*60)
plt.title("24-hour histogram of posts, by minute")
if local_time==1:
plt.xlabel('Time of Day (local)')
else:
plt.xlabel('Time of Day (UTC)')
plt.ylabel('Count')
plt.show()
""""
====== Bar graph of domain submissions
only works with submission json data
"""
def submissionDomainBarGraph(datajson, nitems=20):
subreddit_actions = getParam(datajson, 'domain')
counts = dict(Counter(subreddit_actions).most_common(nitems))
labels, values = zip(*counts.items())
# sort your values in descending order
indSort = np.argsort(values)[::-1]
# rearrange your data
labels = np.array(labels)[indSort]
values = np.array(values)[indSort]
indexes = np.arange(len(labels))
plt.figure()
plt.bar(indexes, values)
plt.title('Number of submissions by top-level domain')
plt.xlabel('Domain Name')
plt.ylabel('Quantity')
# add labels
plt.xticks(indexes, labels, rotation='vertical')
plt.show()
return(counts)
""""
====== Bar graph of subreddit activity
will work with comment or submission json data
"""
def subActivityBarGraph(datajson, nitems=20):
subreddit_actions = getParam(datajson, 'subreddit')
counts = dict(Counter(subreddit_actions).most_common(nitems))
labels, values = zip(*counts.items())
# sort your values in descending order
indSort = np.argsort(values)[::-1]
# rearrange your data
labels = np.array(labels)[indSort]
values = np.array(values)[indSort]
indexes = np.arange(len(labels))
plt.figure()
plt.bar(indexes, values)
plt.title('Posts by subreddit')
plt.xlabel('Subreddit Name')
plt.ylabel('Quantity')
# add labels
plt.xticks(indexes, labels, rotation='vertical')
plt.show()
return(counts)
""""
====== Bar graph of parent commenter usernames
will work with parent comment or parent submission json data
"""
def parentUsernameBarGraph(datajson, nitems=20):
parent_comment_authors = getParam(datajson, 'author')
counts = dict(Counter(parent_comment_authors).most_common(nitems))
labels, values = zip(*counts.items())
# sort your values in descending order
indSort = np.argsort(values)[::-1]
# rearrange your data
labels = np.array(labels)[indSort]
values = np.array(values)[indSort]
indexes = np.arange(len(labels))
plt.figure()
plt.bar(indexes, values)
plt.title('Number of responses TO a given user')
plt.xlabel('Reddit Username')
plt.ylabel('# Responses')
# add labels
plt.xticks(indexes, labels, rotation='vertical')
plt.show()
return(counts) |
6095e1fd373902fd4d2c8ca51ea10c67724447a1 | Miracle-bo/Evernote | /19.06/demo-if语句2.py | 511 | 3.640625 | 4 | money = int(input('请输入您的存款(万):'))
if money > 500:
print('您的存款超过500万,建议您购买路虎')
elif money > 100:
print('您的存款超过100万,建议您购买宝马')
elif money > 50:
print('您的存款超过50万,建议您购买迈腾')
elif money > 10:
print('您的存款超过10万,建议您购买福特')
elif money > 5:
print('您的存款超过5万,建议您购买比亚迪')
else:
print('您的存款低于5万,不建议您购买车辆') |
e2e0d661461c111dafaf01bec387c98964a36cbb | sushantsikka/codeforces-solutions | /cheap-travel.py | 423 | 3.875 | 4 | # Cheap travel
# http://codeforces.com/problemset/problem/466/A
n = int(input("Enter number of rides planned"))
m = int(input("Enter number of rides covered by m ticket"))
a = int(input("Enter price of one ticket"))
b = int(input("Enter price of m ride ticket"))
sum1 = ((n-(m*int((n/m))))*a) + (b*int((n/m)))
sum2 = n * a
if (sum1<sum2):
print("Min cost ->", sum1)
else:
print("Min cost ->", sum2) |
13c5e3c1208956225a901a156092b5216a3edba0 | Zahed75/PythonCode_Practice | /matrix.py | 311 | 4.09375 | 4 | matrix=[
[1,2,3],#1 no row/colum index 0 theke start hobe
[2,4,5], #2no Row/colum index 0 theke start hobe
]
print(matrix[1][2])
#change the matrix value change
'''matrix[1][2]=10
print(matrix[1][2])'''
#print coloum wise matrix value
for row in matrix:
for column in row:
print(column)
|
dfabcbd9f814391a5ca165ad604a1912df941e63 | AustinTSchaffer/DailyProgrammer | /GameSolvers/ColorSortPuzzle/android_game/game_objects.py | 2,337 | 3.96875 | 4 | import collections
import dataclasses
import math
from typing import Tuple, List, OrderedDict, Dict
@dataclasses.dataclass(frozen=True)
class Circle:
column: int
row: int
radius: int
color: Tuple[float]
@dataclasses.dataclass(frozen=True)
class Container:
"""
Names the properties of the rectangle, where col/row refer
to the location of the upper left corner of the rectangle.
"""
column: int
row: int
width: int
height: int
def rect_contains_point(rectangle: Container, row: int, column: int) -> bool:
"""
Returns true if the rectangle contains the point (row, column).
"""
return (
row >= rectangle.row
and row <= (rectangle.row + rectangle.height)
and column >= rectangle.column
and column <= (rectangle.column + rectangle.width)
)
def color_distance(color_1: Tuple[float], color_2: Tuple[float]) -> float:
"""
Returns the euclidean distance between 2 colors.
"""
assert len(color_1) == len(color_2) == 3
return math.sqrt(
(color_1[0] - color_2[0]) ** 2
+ (color_1[1] - color_2[1]) ** 2
+ (color_1[2] - color_2[2]) ** 2
)
def group_circles_by_containers(
*, circles: List[Circle], containers: List[Container]
) -> OrderedDict[Container, List[Circle]]:
"""
Groups each circle based on the container they are contained in. The output dict is ordered
based on the order of the input list of containers. The circle lists in each value of the output
OrderedDict will be ordered based on each circle's row coordinate.
"""
grouped_by_container = collections.OrderedDict()
for container in containers:
grouped_by_container[container] = []
for circle in circles:
container = next(
(
container
for container in containers
if rect_contains_point(container, row=circle.row, column=circle.column)
)
)
grouped_by_container[container].append(circle)
# Sort the circles within each container based on their Y coordinate.
for container, _circles in grouped_by_container.items():
grouped_by_container[container] = sorted(
_circles, key=lambda circle: circle.row, reverse=True
)
return grouped_by_container
|
58608f77a848799337196010ba99af2cc307af19 | alirezaghey/leetcode-solutions | /python/merge-two-binary-trees.py | 1,719 | 4.125 | 4 | from typing import Optional
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# Time complexity: O(max(n, m)) where n and m are the number of nodes in tree1 and tree2
# Space complexity: O(max(n, m))
# BFS approach
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1: return root2
if not root2: return root1
deq = deque([(root1, root2)])
while deq:
node1, node2 = deq.popleft()
node1.val += node2.val
if not node1.left:
node1.left = node2.left
elif node1.left and node2.left:
deq.append((node1.left, node2.left))
if not node1.right:
node1.right = node2.right
elif node1.right and node2.right:
deq.append((node1.right, node2.right))
return root1
# Time complexity: O(max(n, m)) where n and m are the number of nodes in tree1 and tree2
# Space complexity: O(max(n, m))
# DFS approach
def mergeTrees2(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node1, node2):
if not node1: return node2
if not node2: return node1
node1.val += node2.val
node1.left = dfs(node1.left, node2.left)
node1.right = dfs(node1.right, node2.right)
return node1
return dfs(root1, root2) |
02e053395fa7ce8ca0b0a01aee5edb007e17062c | DustinY/EcoCar3-Freshmen-Training | /Assignment_1/Matthew/Celsius_to_Ferenheit.py | 371 | 3.875 | 4 | # Converting Celsius to Farenheit
# Formula: T(F) = T(C) * 1.8 + 32
print "Converting Celsius to Farenheit "
print " "
var_Celsius = int(raw_input("Enther the temperature in Celsius. "))
Ferenheit = var_Celsius * 1.8 + 32
#print (var_Celsius, " is ", Ferenheit, " in degrees Ferenheit. ")
print var_Celsius
print "is"
print Ferenheit
print "in degrees Ferenheit. "
|
cec35f3624a1dd904cef268add642fa33906416d | NolanBabits/compsci101 | /labs/lab4/Part 1/listprint.py | 438 | 3.9375 | 4 | import filetolist
print("file to print")
file = input()
list = filetolist.filetolist("test.txt")
#print (list)
print("1 for whole list 2 for evey 3rd item")
k = int(input())
#k = 2
if k == 1:
print(list)
exit()
elif k == 2:
x = 1
for i in list:
#print (x)
#print (i)
if x % 3 == 0:
print (i)
#print (x)
x += 1
else:
x += 1
exit()
else:
print("bad input use 1 or 2")
|
88af4bb26412756f302e6e1ba1c4391eb7f93bc3 | KnutHurlen/vegvarsel-variousscripts | /.vscode/download/Code/Copy of loading data into Python.py | 3,019 | 3.6875 | 4 | ########################################
#Read from file
#####################################
#First open .csv files in notepad to see what's there
#Use folder icon to select path
#Load necessary libraries
import pandas as pd
import os
#Mac
os.chdir('/Users/chandler/OneDrive - BI Norwegian Business School (BIEDU)/Library/Teaching Materials/DataSets')
#PC
#os.chdir('Z:\OneDrive - BI Norwegian Business School (BIEDU)\Library\Teaching Materials\DataSets')
#Import file
df1 = pd.read_csv('ex1.csv')
#open the loaded file to see what's there
df1
#do the same thing with the variable explorer
#compute the average of column a
df1[”a”].mean()
#huh?!
df1["a"].mean()
#quotes from Word not the same ASCII character!
#Now load ex2.csv and review
df2 = pd.read_table('ex2.csv')
df2
#what is this?
#clean up by changing separator
df2 = pd.read_table('ex2.csv', sep=';')
df2
#compute the average grade
df2["grade"].mean()
#Will fail because grade has comma for decimal. Let's fix
df2 = pd.read_table('ex2.csv', sep=';', decimal = ',')
df2
df2["grade"].mean()
##############################
#########################
#Read data directly from clipboard (first copy ex2.csv contents to clipboard)
#########################
df3 = pd.read_clipboard(decimal = ",")
df3
############################
#Get json data using Web API
############################
import requests
url = 'https://api.github.com/repos/pydata/pandas/milestones/28/labels'
resp = requests.get(url)
data = resp.json()
issue_labels = pd.DataFrame(data)
issue_labels
issue_labels[0:3]
issue_labels.head()
#Let's generate some summary info about the data
issue_labels.sample(5)
issue_labels.describe()
###########
#Let's import a .csv file from the web, and get fancy with summarizing
#Thanks to: https://towardsdatascience.com/exploring-your-data-with-just-1-line-of-python-4b35ce21a82d
#Will require installing pandas_profiling
#############
import pandas_profiling
pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/planets.csv').profile_report().to_file('planets.html')
###############################
#Get data pre-loaded in scikit-learn
###############################
from sklearn.datasets import load_breast_cancer
cancer=load_breast_cancer()
cancer
#malignant target == 0
#let's make this dataset easier to view
df = pd.DataFrame(cancer.data, columns=cancer.feature_names)
df.head()
df['malignant'] = 1 - cancer.target
df.head()
#and now let's descrive the cancer data
df.describe()
pandas_profiling.ProfileReport(df).to_file('cancer_report.html')
############################
#Some others
###########################
#From twitter: http://www.tweepy.org/
#Via ODBC: pyodbc
############################
#Finally, let's write the cancer dataframe out to Excel
###########################
df.to_csv(r'cancer.csv', header=True, index=None, sep=' ')
df.to_csv(r'cancer.csv', header=True, index=None, sep=';')
df.to_excel(r'cancer.xls', header=True, index=None)
#NOTE: to_excel and savetxt are also options |
8c0b80553decc3e3ba9398c302bdd0f7e74b06a1 | dkeen10/A01185666_1510_v3 | /Lab02/lab02.py | 675 | 4.09375 | 4 | import random
def roll_die():
"""
asks user for number of rolls and number of sides of the die and returns the result
:param number_of_rolls: number of die rolls
:param number_of_sides: number of sides of the die
:return: the result of the dice roll
"""
number_of_rolls = int(input("how many rolls?"))
number_of_sides = int(input("how many sides to your die?"))
if number_of_sides > 1 and number_of_rolls > 0:
dice_result = random.sample(range(number_of_rolls, number_of_sides * number_of_rolls + 1), 1)
print("your result is " + str(dice_result))
else:
return 0
if __name__ == "__main__":
roll_die()
|
78566c901a08f882eb6e887267a14a42c07adc6d | andyc1997/Data-Structures-and-Algorithms | /Algorithms-on-Graphs/Week1/reachability.py | 1,438 | 4 | 4 | #Uses python3
import sys
# Task. Given an undirected graph and two distinct vertices u and v, check if there is a path between u and v.
# Input Format. An undirected graph with n vertices and m edges. The next line contains two vertices u
# and v of the graph.
# Output Format. Output 1 if there is a path between u and v and 0 otherwise.
def explore(v, adj, visit): # Do a depth first search from vertex v
visit[v] = 1 # If we explore the neighborhood of v, we must have visited v
for w in adj[v]: # Explore the unvisited neighborhoods of vertex v
if visit[w] == 0:
explore(w, adj, visit)
def reach(adj, x, y):
visit = len(adj) * [0] # At the beginning, all vertices are not visited
explore(x, adj, visit) # Now, we start at vertex x, and explore the adjacent vertices of x
if visit[y] > 0: # if the target node, y, is visited in depth first search started at x, it is reachable by definition and we return 1
return 1
return 0 # Otherwise, it's not reachable and return 0
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
x, y = data[2 * m:]
adj = [[] for _ in range(n)]
x, y = x - 1, y - 1
for (a, b) in edges:
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
print(reach(adj, x, y))
|
da47b660c6630f14cb23fd5b18c4fe12626b4eb0 | bossyjossy/IAmLearninPython | /exercises/LPTHW_Exercise8.py | 1,306 | 4.09375 | 4 | # This is my completed exercise for Learn Python The Hard Way Exercise 8
#
# This is slightly modified from the lesson so that I can test things out
# and really solidify what I learned.
#
# EXERCISE 8: Printing, Printing
# This line will set the variable 'formatter' to print a string four times
formatter = "%r %r %r %r"
# This section will use the variable with various sets of strings and print them.
# This line will print: 1 2 3 4
print formatter % (1, 2, 3, 4)
# This line will print the numbers spelled out with the quotes with no commas to separate the values.
print formatter % ("one", "two", "three", "four")
# This line will print the four boolean values with no commas to separate the values.
print formatter % (True, False, False, True)
# This line will print '%r %r %r %r' four times (with the single quotes) with no commas to separate each instance.
print formatter % (formatter, formatter, formatter, formatter)
# This line will print the four lines on one line. Each retains the single quotes.
print formatter % ("I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight.")
# Note that the output of this line will have double quotes around the third string because there is a contraction
# within the string which uses the single quote. |
d47addddab4cc76d272167b877f524aa96c02853 | Vhrizon/AnyDump | /Main.py | 249 | 3.5 | 4 | #main
#ord() = int value of chr() chr(ord('a'))
#file_contents = f.read()
import
def FileRead():
("Please give the file name")
def Encrypt():
def Decrypt():
def Menu():
print("1. Encrypt\n2. Decrypt\n3. exit")
|
d497042484f137101d3a7b13fd4303ccbd204c52 | f-e-d/2021-Algorithm-Study | /Programmers/suyeon/binary_search/징검다리.py | 701 | 3.5 | 4 | def solution(distance, rocks, n):
rocks.sort()
rocks.append(distance)
answer = 0
start, end = 1, distance # answer은 1 ~ distance 사이에 있음
while start <= end:
mid = (start + end) // 2
# 부서진 바위의 수 세기
cnt_rock, prev_rock = 0, 0
for rock in rocks:
if rock - prev_rock < mid:
cnt_rock += 1
else:
prev_rock = rock
if cnt_rock > n: # 더 많이 파괴되었을 경우
end = mid - 1
else: # 같거나 더 작게 파괴되었을 경우
answer = mid
start = mid + 1
return answer |
956f7e7a08b475a33f83759b8de6ed3605c07d70 | mcfitzgerald/thesis2.0 | /ipythes/ligmods.py | 809 | 3.53125 | 4 | #Useful functions for ligand binding simulation and fitting
#Load Dependencies
import numpy as np
#Simulating data
#Dilution series
def dilser(low=0.001, limit=100.0, dilfactor = 2.0):
"""Returns a numpy array containing a dilution series that ranges from
"low" to "limit" by "dilfactor".
"""
a = [low]
while a[-1] <= limit:
a.append(a[len(a)-1]*dilfactor)
return np.asarray(a)
#Noise -- add noise to simulated data
def noiser(data, percent=0.05):
"""Takes a numpy array and randomly moves data point +/- a given "percent"
of that data point's value. Moves are drawn from a normal distribution with
mean = 1 and standard deviation of "percent". Returns a numpy array of the
noisy data.
"""
return np.random.normal(1,percent,len(data))*data
|
923999aea0bd4dbe936612a17833958418578d4f | aguscerdo/183D-capstone | /PHANTOMbots/environment.py | 4,697 | 3.515625 | 4 | ### ENVIRONMENT CLASS
# size is [x,y], which gives the number of vertices in our grid
# vertices is the set of all vertices in our maze,
# a vertice is defined by its x and y coordinate ([x, y])
# We assume that all adjacent vertices connected if they are in the grid
# bots is a list of PhantomBots in our simulation
import matplotlib.pyplot as plt
import numpy as np
from phantomBot import PhantomBot
# TODO: change these later
presetSize = [10, 10]
presetVertices = []
for i in range(presetSize[0]):
for j in range(presetSize[1]):
if (i !=j and (i != 6 or j > 5) and (j!=9 or i <2) ) or ((j == 6 or j == 2) and i == 6):
presetVertices.append([i,j])
class Environment:
def __init__(self, printAll=False, size=None, vertices=None, bots=None ):
self.printAll = printAll
if (self.printAll):
print("Print all mode on!")
if size is None or vertices is None or bots is None:
self.size = presetSize
self.vertices = presetVertices
pursuer1 = PhantomBot(printAll=False, pos=[0,1], pacman=False)
pursuer2 = PhantomBot(printAll=False, pos=[0,5])
pursuer3 = PhantomBot(printAll=False, pos=[0,7])
pursuer4 = PhantomBot(printAll=False, pos=[5,1])
pacmanBot = PhantomBot(printAll=False, pos=[6,6], pacman=True, speed=1.2)
self.bots = [pursuer1, pursuer2, pursuer3, pursuer4, pacmanBot]
if (self.printAll):
print("Using preset size/edges/bots!")
else:
self.size = size
self.vertices = vertices
self.bots = bots
if (self.printAll):
print("Using grid of size " + str(self.size))
self.verticeMatrix = np.zeros(self.size)
self.set_vertice_matrix()
self.occupiedVertices = []
for bot in self.bots:
self.occupiedVertices.append(bot.get_position())
def set_vertice_matrix(self):
"""
verticeMatrix_i,j = 1 iff vertex at (i,j) in our maze
"""
self.verticeMatrix = np.zeros(self.size)
for vertex in self.vertices:
self.verticeMatrix[vertex[0], vertex[1]] = 1
def load_grid(self, size, vertices):
"""
Loads the grid
:param size: size of grid, tuple of (x, y)
:param edges: list of edges, e in edges => e = (v1, v2) and vi = (xi, yi)
:return:
"""
self.size = size
self.vertices = vertices
self.set_vertice_matrix()
if (self.printAll):
print("Loaded new grid, size is " + str(self.size))
def plot_grid(self):
"""
Plots the edges by plotting a line for each edge
"""
ax = plt.gca()
if (self.printAll):
print("Plotting Grid!")
for i in range(self.size[0]):
for j in range(self.size[1]):
#plot vertex i,j
if (self.verticeMatrix[i,j]):
ax.plot(i, j, 'bx', label='point')
#plot line from i,j -> i+1,j
if (i+1 < self.size[0] and self.verticeMatrix[i,j] and self.verticeMatrix[i+1,j]):
xs = [i, i+1]
ys = [j, j]
ax.plot(xs, ys, 'r')
#plot line from i,j -> i,j+1
if (j+1 < self.size[1] and self.verticeMatrix[i,j] and self.verticeMatrix[i,j+1]):
xs = [i, i]
ys = [j, j+1]
ax.plot(xs, ys, 'r')
#plot bots:
radius = 0.1
for bot in self.bots:
if bot.is_pacman():
circle = plt.Circle(bot.get_position(), radius, color='yellow')
else:
circle = plt.Circle(bot.get_position(), radius, color='blue')
ax.add_artist(circle)
plt.title('The Maze')
# x from -0.5 -> size_x - 0.5, y from -0.5 -> size_y - 0.5
# -0.5 to show full grid
plt.axis([-0.5, self.size[0]-0.5, -0.5, self.size[1]-0.5])
plt.show()
def legal_move(self, bot, end_pos):
"""
Checks if move if legal
:param bot: which bot is moving, i
:param end_pos: where a bot will end, (x1, y1)
:return: True if move is legal else false
"""
start_pos = self.bots[bot].get_position()
# True if dist == 1 and both vertices in set and no collision
valid_move = True
valid_move &= (self.dist(start_pos, end_pos) == 1)
valid_move &= (self.verticeMatrix[end_pos[0], end_pos[1]] == 1)
valid_move &= (self.verticeMatrix[start_pos[0], start_pos[1]] == 1)
# check collisions, TODO maybe change this(?)
for i in range(len(self.bots)):
valid_move &= (i==bot or dist(start_pos, self.bots[i].get_position()) > 0)
if (self.printAll):
print("Moving from " + str(start_pos) + " to " + str(end_pos) + " is: ")
if (valid_move):
print("legal")
else:
print("illegal")
return valid_move
def move(self, bot, end_pos):
"""
Moves bot to location
:param bot: which bot is moving, i
:param end_pos: where a bot will end, (x1, y1)
"""
self.bots[bot].move(end_pos)
self.occupiedVertices[bot] = end_pos
def dist(self, a, b):
"""
Gets railroad/manhatten/L1 distance
:param a: (x0, y0)
:param b: (x1, y1)
"""
return np.abs(a[0] - b[0]) + np.abs(a[1] - b[1])
env = Environment()
env.plot_grid()
|
363d1684436df120d90813d18133fed628460344 | robillersomeone/NYT_bestsellers | /ETL/combining_data.py | 979 | 3.546875 | 4 | import pandas as pd
# read in data
gr_2016_df = pd.read_csv('../data/2016_goodreads.csv')
gr_2017_df = pd.read_csv('../data/2017_goodreads.csv')
gr_2018_df = pd.read_csv('../data/2018_goodreads.csv')
gr_2019_df = pd.read_csv('../data/2019_goodreads.csv')
# need to account for list elements in 'publisher' and 'data' in 2016-18 data
# if there are two dates, index 375 in 2016, take first element
# if there are null values
choiceawards_df = pd.concat([gr_2016_df, gr_2017_df, gr_2018_df, gr_2019_df])
print('total books', choiceawards_df.shape)
# check duplicates
doubled_books_df = choiceawards_df[choiceawards_df.duplicated(['title'], keep=False)]
print('doubled books', doubled_books_df.shape)
# drop duplicate titles
df = choiceawards_df.drop_duplicates(subset='title', keep='last')
# add column for best seller
# set to 0 to start
# read from database
# if the title is in the database, set to 1
# export to csv
# book_df.to_csv('../data/16_19_goodreads.csv')
|
de8cb82568bcda295804fd14e80698fa731d8fc6 | shartrooper/My-python-scripts | /Python scripts/Rookie/If-else-fun.py | 368 | 4.0625 | 4 | name = 'Marko'
while name != "Adrian":
if name != 'Adrian':
print('name is not true, write your true name, Adrian')
name=input()
if name == 'Adrian':
print('Well done!')
elif name == 'Marko':
print('Fuck off bozzo!')
break
else:
print('You actually typed '+name+' Fool.')
print('done');
|
08d372dc1d03ab218fdb955ac811c3e1037fdee6 | predtech1988/Courses | /data_structures/exercise/06/merge_Sorted_Arrays.py | 1,932 | 4.40625 | 4 | #Naive version
def merge_sorted(arr1, arr2):
#check input
#create empty list
answer = []
#read array's one by one, and add items to "empty list"
for item in arr1:
answer.append(item)
for item in arr2:
answer.append(item)
#at the end use .sort() methon on "empty list"
answer.sort()
return answer
#Naive version with python power :)) (built in methods) extend() .sort()
def merge_sorted_2(arr1, arr2):
arr1.extend(arr2)
arr1.sort()
return arr1
def merge_sorted_3(arr1, arr2):
"""
Ugly but working. Not scalebel at all. Need more work.
When i receive 2 array's,
i determinate the size of it, and place bigger or
equal to the "bigger", than i use "i_end" to save
length of array, and choose smaller to iterate.
When reached end of smaller, assuming that array
is sorted, i just copy left items from the bigger.
"""
answer = []
i = 0
j = 0
if len(arr1) >= len(arr2): #i bigger list
i_end = len(arr1)
j_end = len(arr2)
bigger = arr1
smaller = arr2
else:
i_end = len(arr2)
j_end = len(arr1)
bigger = arr2
smaller = arr1
for step in range((i_end + j_end)-1):
a = bigger[i]
if j < j_end: #Until we reach end of the smaller list
b = smaller[j]
if a < b:
answer.append(a)
i +=1
elif a > b:
answer.append(b)
j +=1
else:
answer.append(a)
answer.append(b)
j +=1
i +=1
else:
answer.append(a)
i +=1
print(answer)
print(merge_sorted([0,3,4,31], [4,6,30]))
print(merge_sorted_2([0,3,4,31], [4,6,30]))
merge_sorted_3([0,3,4,31], [4,6,30])
merge_sorted_3([4,6,30], [0,3,4,31])
|
53dd3cd68d986b0411db795bada083e6655afeab | td736/Blackjack | /Table.py | 2,448 | 3.578125 | 4 | from Dealer import Dealer
from Player import Player
class Table:
def __init__(self):
self.dealer = Dealer()
self.player_list = []
def add_player(self):
name = input("Name: ")
buy_in = input("Buy-in: ")
self.player_list.append(Player(name, int(buy_in)))
def remove_player(self, name):
for player in self.player_list:
if player.name == name:
self.player_list.remove(player)
def start_hand(self):
self.dealer.reset_table()
for player in self.dealer.players:
player.bet(int(input("{}'s bet: ".format(player.name))))
self.dealer.deal_hand()
def hit_loop(self):
for player in self.dealer.players:
print("{}'s turn.".format(player.name))
player.display_cards()
while input("Hit or stand(s): ") != "s":
self.dealer.hit(player)
if player.card_value > 21:
print("{} bust with:".format(player.name))
player.display_cards()
break
elif player.card_value == 21:
print("{} has 21 with: ".format(player.name))
player.display_cards()
break
player.display_cards()
def dealers_turn(self):
self.dealer.play_own_hand()
if self.dealer.card_value > 21:
print("Dealer busts with {}.".format(self.dealer.display_cards()))
for player in self.dealer.players:
if player.card_value <= 21:
self.dealer.winners.append(player)
elif self.dealer.card_value <= 21:
for player in self.dealer.players:
if player.card_value == self.dealer.card_value:
print("{} tied with dealer. ${} returned.".format(player.name, player.money_bet))
player.money += player.money_bet
elif 21 >= player.card_value > self.dealer.card_value:
print("{} beats the dealer. Won ${}.".format(player.name, player.money_bet*2))
self.dealer.winners.append(player)
elif player.card_value < self.dealer.card_value <= 21:
print("{} lost ${}.".format(player.name, player.money_bet))
print("Dealers cards are:")
self.dealer.display_cards()
self.dealer.pay_winners()
|
de27f87667f031c59561bde2b95551a3628b4ec8 | asterix135/algorithm_design | /quiz_quick_sort.py | 4,184 | 3.65625 | 4 | '''implemetation of quick sort algorithm for programming questions'''
m_count = 0
def sort_array(array, sub_option=3):
"""
Main call - sub_option refers to problem number in homeowork
array is actually a list
"""
quick_sort(array, 0, len(array)-1, sub_option)
def quick_sort(array, left, right, sub_option):
"""
primary recursive algorithm
"""
global m_count
if right >= left:
m_count += right - left
if right - left <= 0:
return
pivot = partition(array, left, right, sub_option)
quick_sort(array, left, pivot - 1, sub_option)
quick_sort(array, pivot + 1, right, sub_option)
def partition(array, left, right, sub_option):
"""
Sort elements before and after pivot. Pivot point is determined by
sub-option: 1 = fist element in list, 2 = last item in list
3 = median of first, last & median element in list
"""
if sub_option == 2:
array[left], array[right] = array[right], array[left]
elif sub_option == 3:
left_val = array[left]
right_val = array[right]
mid_idx = ((right - left) // 2) + left
mid_val = array[mid_idx]
if left_val < mid_val < right_val or right_val < mid_val < left_val:
array[left], array[mid_idx] = array[mid_idx], array[left]
elif left_val < right_val < mid_val or mid_val < right_val < left_val:
array[left], array[right] = array[right], array[left]
pivot = array[left]
# split_idx refers to the break between higher than pivot & less than pivot
split_idx = left + 1
# sort_idx refers to the break between sorted & unsorted elements
for sort_idx in range(left + 1, right + 1):
if array[sort_idx] < pivot:
array[sort_idx], array[split_idx] = \
array[split_idx], array[sort_idx]
split_idx += 1
sort_idx += 1
array[left], array[split_idx - 1] = array[split_idx - 1], array[left]
return split_idx -1
def test_routine():
"""Verification tests"""
global m_count
data1 = [int(line.strip()) for line in open('test_10.txt', 'r')]
m_count = 0
sort_array(data1, 1)
print (str(m_count) + ' should be 25')
data1 = [int(line.strip()) for line in open('test_10.txt', 'r')]
m_count = 0
sort_array(data1, 2)
print (str(m_count) + ' should be 29')
data1 = [int(line.strip()) for line in open('test_10.txt', 'r')]
m_count = 0
sort_array(data1, 3)
print (str(m_count) + ' should be 21')
print()
data2 = [int(line.strip()) for line in open('test_100.txt', 'r')]
m_count = 0
sort_array(data2, 1)
print (str(m_count) + ' should be 615')
data2 = [int(line.strip()) for line in open('test_100.txt', 'r')]
m_count = 0
sort_array(data2, 2)
print (str(m_count) + ' should be 587')
data2 = [int(line.strip()) for line in open('test_100.txt', 'r')]
m_count = 0
sort_array(data2, 3)
print (str(m_count) + ' should be 518')
print()
data3 = [int(line.strip()) for line in open('test_1000.txt', 'r')]
m_count = 0
sort_array(data3, 1)
print (str(m_count) + ' should be 10297')
data3 = [int(line.strip()) for line in open('test_1000.txt', 'r')]
m_count = 0
sort_array(data3, 2)
print (str(m_count) + ' should be 10184')
data3 = [int(line.strip()) for line in open('test_1000.txt', 'r')]
m_count = 0
sort_array(data3, 3)
print (str(m_count) + ' should be 8921')
def homework_problem():
"""
Runs quicksort & returns number of comparisons on homework list
"""
global m_count
quiz_file = [int(line.strip()) for line in open("QuickSort.txt", 'r')]
m_count = 0
sort_array(quiz_file, 1)
print('Question One Answer: ' + str(m_count) + '\n')
quiz_file = [int(line.strip()) for line in open("QuickSort.txt", 'r')]
m_count = 0
sort_array(quiz_file, 2)
print('Question Two Answer: ' + str(m_count) + '\n')
quiz_file = [int(line.strip()) for line in open("QuickSort.txt", 'r')]
m_count = 0
sort_array(quiz_file, 3)
print('Question Three Answer: ' + str(m_count) + '\n')
# test_routine()
homework_problem()
|
271daf182e54da204d147997a7d27bff3e2d030d | prastabdkl/pythonAdvancedProgramming | /chap7lists/others/failchap8password_login.py | 1,309 | 4.09375 | 4 | # passwords for the campus computer system must meet the following requirements:
# • The password must be at least seven characters long.
# • It must contain at least one uppercase letter.
# • It must contain at least one lowercase letter.
# • It must contain at least one numeric digit.
password_message = """Enter a password:
The password must be at least seven characters long.
• It must contain at least one uppercase letter.
• It must contain at least one lowercase letter.
• It must contain at least one numeric digit. \n"""
password = input(password_message)
password_accepted = False
alphabets = digits = special = 0
while password_accepted == False:
if len(password)<7 or password.isspace() or password == '' or password.isalpha() or password.isdigit() or password.isupper() or password.islower():
password = input(password_message)
else:
for i in range(len(password)):
if(password[i].isalpha()):
alphabets = alphabets + 1
elif(password[i].isdigit()):
digits = digits + 1
else:
special = special + 1
if special == 0:
password = input(password_message)
else:
password_accepted = True
print(password)
# if len(password)
|
2ab270e329a5ed8f9043e147b13b4cf9afec1de7 | joestalker1/leetcode | /src/main/scala/BinaryTreeZigzagLevelOrderTraversal.py | 992 | 3.640625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import defaultdict
class Solution:
def zigzagLevelOrder(self, root: TreeNode):
if not root:
return []
def traverse(node, level, m):
if not node:
return
if level % 2 == 0:
m[level].append(node.val)
else:
m[level].insert(0, node.val)
traverse(node.left, level + 1, m)
traverse(node.right, level + 1, m)
m = defaultdict(list)
traverse(root, 0, m)
j = 0
res = []
while True:
if j not in m:
break
res.append(m[j])
j += 1
return res
r = TreeNode(1)
r.left = TreeNode(2)
r.right = TreeNode(3)
r.left.left = TreeNode(4)
r.right.right = TreeNode(5)
sol = Solution()
print(sol.zigzagLevelOrder(r))
#[1,2,3,4,null,null,5]
|
a59502aa5b87790b190a5c6d485f3ea651f5d2e8 | esther1104/myPy | /복습/14A-calc_re.py | 695 | 3.53125 | 4 | import random
def make_question():
a=random.randint(1,50)
b=random.randint(1,30)
op=random.randint(1,3)
q=str(a)
if op==1:
q=q+"+"
if op==2:
q=q+"-"
if op==3:
q=q+"*"
q=q+str(b)
return q
right_answer=0
mistake_answer=0
for x in range(7):
q=make_question()
print(q)
answer=input("=")
r=int(answer)
if eval(q)==r:
print("BINGO!")
right_answer=right_answer+1
else:
print("WRONG!")
mistake_answer=mistake_answer+1
print("정답:",right_answer,"오답:",mistake_answer)
if mistake_answer==0:
print("정말 대단해요!")
else:
print("조금 더 노력하세요!")
|
8bb8026500e0a640dd5b196ba227f4a253bd599f | davidozhang/hackerrank | /python_domain/itertools/itertools_combinations_with_replacement.py | 268 | 3.578125 | 4 | #!/usr/bin/python
from itertools import combinations_with_replacement
def main():
s, n = raw_input().split()
for i in list(combinations_with_replacement(list(sorted(s, key=str.upper)), int(n))):
print ''.join(i)
if __name__ == '__main__':
main()
|
3b7256c2b33a029779d13e1518554ae6f1a89e1d | liuskyo/Python-Practice | /py259_劉天佑.hw5.py | 950 | 3.5625 | 4 | class student:
def __init__(self,name,gender):
self.grades=[]
self.name=name
self.gender=gender
def avg(self):
sum=0
for i in self.grades:
sum=sum+i
return sum/len(self.grades)
def add(self,grade):
self.grades.append(grade)
def fcount(self):
fsum=0
for n in self.grades:
if n<60:
fsum=fsum+1
return fsum
def top(studentlist):
maxe=0
for s in studentlist:
a=s.avg()
if a>maxe:
maxe=a
maxeStudent=s
return maxeStudent
s1 = student("Tom","M")
s2 = student("Jane","F")
s3 = student("John","M")
s4 = student("Ann","F")
s5 = student("Peter","M")
s1.add(80)
s1.add(90)
s1.add(55)
s1.add(77)
s1.add(40)
s2.add(58)
s2.add(87)
s3.add(100)
s3.add(80)
s4.add(40)
s4.add(55)
s5.add(60)
s5.add(60)
|
180cf7d6fd71a56e68f41ed38358740571e42f9b | RameswariMishra/LearningPython | /jsontest.py | 613 | 3.78125 | 4 | import json
alphabets_json = '{"a":"A","b":"B"}'
alpha_dict = json.loads(alphabets_json)
print(alpha_dict)
new_json = json.dumps(alpha_dict)
print(new_json)
# reading a json file
with open("/Users/rameswarimishra/Library/Preferences/PyCharmCE2019.3/scratches/Employee.json") as f:
dict_a = json.load(f)
print(dict_a)
# Writing into a json file ie. creating a json file and copying the dictionary into it.
dict_emp = {'name': 'Ram', 'Designation': 'Manager'}
with open('emp.json', 'w') as s:
json.dump(dict_emp, s)
with open('emp.json') as j:
dict_emp2 = json.load(j)
print(dict_emp2)
#imnbnmb
|
ef385076a27c987c86adea36fe8031707ebb6f99 | XavierCHEN34/LeetCode_py | /206.Reverse Linked List.py | 1,246 | 3.9375 | 4 |
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
def generate_LN(l):
head = ListNode(l[0])
p = head
if len(l) == 1:
return head
for i in l[1:]:
p.next = ListNode(i)
p = p.next
return head
def print_LN(head):
l = []
p = head
while(p):
l.append(p.val)
p = p.next
print(l)
return l
head1 = generate_LN([1,3,5,7,9])
print_LN(head1)
"""
creat a val_list, reverse the val_list then modify the value of LN
"""
def reverse_linked_list1(head):
l_val = []
p = head
while(p):
l_val.insert(0,p.val)
p = p.next
p = head
for i in l_val:
p.val = i
p = p.next
return head
print_LN(reverse_linked_list1(head1))
"""
one turn solution
"""
def reverse_linked_list2(head):
if head == None or head.next == None: #边界条件
return head
p = head #循环变量
tmp_next = None #保存数据的临时变量
newhead = None #新的翻转单链表的表头
while p:
tmp_next = p.next
p.next = newhead
newhead = p # 更新 新链表的表头
p = tmp_next
return newhead
print_LN(reverse_linked_list2(head1)) |
3c0d3be84a80bf7ce1c35f03d8e537ed8ef0a939 | kaumnen/codewars | /[5 kyu] Valid Parentheses.py | 319 | 4 | 4 | def valid_parentheses(string):
temp = [1]
for i in string:
if i == ')':
if temp[-1] == '(':
temp.pop(-1)
else:
return False
elif i == '(':
temp.append(i)
if temp == [1]:
return True
return False
|
1fa50f14f6355b3ba10779de16950d1d0ece7458 | heronc95/Final-Project | /mongodb_setup.py | 1,233 | 3.8125 | 4 | """
Write code below to setup a MongoDB server to store usernames and passwords for HTTP Basic Authentication.
This MongoDB server should be accessed via localhost on default port with default credentials.
This script will be run before validating you system separately from your server code. It will not actually be used by your system.
This script is important for validation. It will ensure usernames and passwords are stored in the MongoDB server
in a way that your server code expects.
Make sure there are at least 3 usernames and passwords.
Make sure an additional username and password is stored where...
username = admin
password = pass
"""
from pymongo import MongoClient
# open the pymongo client to use
client = MongoClient('mongodb://localhost:27017/')
# Get the database to use
db = client.hokie_id
collection = db.student_ids
# Clear out old entries from the database here
set = {"id": "905870688", "start_time":"05-05-16-40", "end_time":"05-05-17-15"}
# insert the first default user name and password
collection.insert_one(set)
result = collection.delete_many({'id':'905870688'})
result = collection.find_one({'id': '905870688'})
if result:
print("In there")
else:
print("Not in there")
|
92528a9158c84b9486f1f98619b6893a9e361f95 | koreakevin/BJ_Algorithms_Study | /bj10866.py | 2,537 | 3.6875 | 4 | from collections import deque
import sys
n = int(sys.stdin.readline())
dq = deque()
def empty():
if len(dq) == 0:
return 1
else:
return 0
def size():
return len(dq)
for i in range(n):
cmd = list(sys.stdin.readline().split())
if cmd[0] == 'push_front':
dq.appendleft(cmd[1])
elif cmd[0] == 'push_back':
dq.append(cmd[1])
elif cmd[0] == 'pop_front':
if empty() == 1:
print("-1")
else:
tmp = dq.popleft()
print(tmp)
elif cmd[0] == 'pop_back':
if empty() == 1:
print("-1")
else:
tmp = dq.pop()
print(tmp)
elif cmd[0] == 'front':
if empty() == 1:
print("-1")
else:
print(dq[0])
elif cmd[0] == 'back':
if empty() == 1:
print("-1")
else:
print(dq[len(dq)-1])
elif cmd[0] == 'size':
print(size())
elif cmd[0] == 'empty':
print(empty())
# deque 모듈 사용함
# deque 모듈이란?
# double-ended queue 의 줄임말로, 앞과 뒤에서 즉, 양방향에서 데이터를 처리할 수 있는 queue형 자료구조를 의미한다.
# queue(큐)는 자료의 선입선출,FIFO(First-In-First_Out)을 보장하는 자료구조이다.
# 데이터 추가/append,appendleft
# 리스트의 명령어와 같이 append를 이용해서 데이터를 하나씩 추가할 수 있다. appendleft의 경우 왼쪽에서 데이터를 추가할 수 있다.
# 데이터 추가(확장)/extend, extendleft
# 기본 deque에 iterable데이터를 합치는 명령어이다. 기본적으로 오른쪽 방향으로 합치고, extendleft의 경우은 왼쪽에 데이터를 붙인다.
# 데이터 반환/Pop,Popleft
# pop의 경우는 데이터를 하나씩 반환하고, 기존 큐에서 삭제하는 명령어이다. popleft의 경우는 왼쪽 방향에서 데이터를 반환하고 삭제하는 명령어이다.
# 데이터 삭제/remove,clear
# remove의 경우 인자로 넣은 데이터를 deque에서 삭제하는 명령어이다. clear의 경우는 deque안의 모든 맴버를 삭제한다.
# 데이터 값 위치 바꾸기/reverse, rotate
# reverse의 경우 데이터를 뒤집어 버린다. 그냥 데이터를 통째로 뒤집어 버린다. 그리고 rotate 명령어는 가장 오른쪽 데이터를 pop해서 appendleft한다.
# 이런식으로 데이터를 하나씩 순회하게 한다. 만약 인자로 들어간 숫만큼 회전을 하게 된다. |
fd76a1dd8e761c5c7183a2b2917153d67a407066 | lakshuguru/Geeks-for-Geeks | /List/1.multiply-nums-list.py | 406 | 3.9375 | 4 | '''The problem of finding the summation of digits of numbers is quite common. This can sometimes come in form of a list and we need to perform that. This has application in many domains such as school programming and web development.
Let’s discuss certain ways in which this problem can be solved.'''
l=[4,2,3]
k=1
for i in range(len(l)):
#k*=l[i]*l[i+1]
k*=i
print(k)
|
675d3d6f08106d721baa4e3aa793550c56a0cd85 | Bushidokun/Python | /Learning/TCA/Review TCA 3/Nesting.py | 509 | 4.0625 | 4 | print ("Welcome to the Planet of the Apes...")
humanTotal = 0
apeTotal = 0
for loop in range(7):
print ("...be ye human or be ye ape?")
userBe = input()
if userBe == "Human":
humanTotal += 1
print ("I did not start this war. But I will finish it.")
elif userBe == "Ape":
apeTotal += 1
print ("Apes together strong!")
else:
print ("This is not your fight.")
print ("Total human encountered:", humanTotal)
print ("Total apes encountered", apeTotal) |
322daedcc7e797d9c1339b36b3d2d6a953b03d6a | borgebj/IN1000-Python | /innlevering2/kodeforstaaelse.py | 892 | 4.03125 | 4 | """dette programmet tar input for et heltall og sjekker om heltallet hentet fra brukeren er mindre enn 10 eller ikke"""
#1) Er dette lovlig kode?
#- Nei, det er ikke. Grunnen for at det ikke er lovlig kode er fordi + tegnet som er skrevet i print er for å sette sammen tekstself.
#Koden vil legge sammen en variabel som er definert som et heltall sammen med tekst, og vil dermed bety at koden ikke vil fungereself.
#For at koden skal fungere, må enten + (pluss) byttes ut med , (komma), ellers må det skrives: print(str(b) + "hei") for at det skal printes ut riktig.
#2) Hvilken problemet kunne vi møte på når vi kjører denne koden?
#- Det vil komme feilmelding som da vil si at det er en feil på linjen med print, og det vil kome melding "TypeError: unspported operand type(s) for +: "int" and "str"
a = input("Tast inn et heltall! ")
b = int(a)
if b < 10:
print (b + "Hei!")
|
be081d9e9cd0c32a8d939bcb9cea0916a24ba1ff | NikilReddyM/algorithms | /divisible_sumpairs.py | 265 | 3.5625 | 4 | from itertools import combinations
def divisible_sumpairs(a,s):
c=0
for a,b in list(combinations(a,2)):
if (a+b)%s == 0:
c += 1
return(c)
n,s = map(int,input().split())
a=map(int,input().split())
print(divisible_sumpairs(a,s))
|
ba7b9e939eff5958ceab0d1cb853048920484cb7 | gchotai/python-workshop | /kth_most_char.py | 896 | 3.53125 | 4 | from collections import Counter
class soluction:
# 'solution - 1'
def top_k_frequency(self, nums, k):
cnt = Counter(nums)
most_common_k = cnt.most_common(k)
res = [num[0] for num in most_common_k]
return res
# 'solution - 2'
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counts = collections.Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for num in counts.keys():
buckets[counts[num]].append(num)
ans = []
for i in range(len(nums), 0, -1):
ans += buckets[i]
if len(ans) == k:
return ans
return ans
if __name__ == '__main__':
s = soluction()
print(s.top_k_frequency([1,1,2,2,2,4],2))
print(s.topKFrequent([1, 1, 2, 2, 2, 4], 2))
|
e94cc4871f150b0060fae76cef18f0a17b40619e | Mschikay/leetcode | /855. Exam Room.py | 1,917 | 3.53125 | 4 | class ExamRoom(object):
def __init__(self, N):
self.N = N
self.students = []
def seat(self):
if not self.students:
student = 0
else:
dist, student = self.students[0], 0
for i, s in enumerate(self.students):
if i:
prev = self.students[i-1]
d = (s - prev) // 2
if d > dist:
dist, student = d, prev + d
d = self.N - 1 - self.students[-1]
if d > dist:
student = self.N - 1
bisect.insort(self.students, student)
return student
def leave(self, p):
self.students.remove(p)
import heapq
class ExamRoom:
def __init__(self, N: int):
self.N = N
self.pq = [(self.dist(-1, N), -1, N)]
# length of the interval (x, y)
def dist(self, x, y):
if -1 == x:
return -1 * y
elif self.N == y:
return -1 * (self.N - 1 - x)
return -1 * (abs(y - x) // 2)
def seat(self) -> int:
_, x, y = heapq.heappop(self.pq)
if -1 == x:
seat = 0
elif self.N == y:
seat = self.N - 1
else:
seat = (x + y) // 2
heapq.heappush(self.pq, (self.dist(x, seat), x, seat))
heapq.heappush(self.pq, (self.dist(seat, y), seat, y))
return seat
def leave(self, p: int) -> None:
left, right = None, None
for interval in self.pq:
if p == interval[1]:
right = interval
if interval[2] == p:
left = interval
if left and right:
break
self.pq.remove(right)
self.pq.remove(left)
heapq.heapify(self.pq) # important! re-heapify after deletion
heapq.heappush(self.pq, (self.dist(left[1], right[2]), left[1], right[2])) |
4cdd64c11e2b6336e5f72a92956cbacb94a863d9 | DonaldButters/Module4 | /test_price_under_between_ten_thirty.py | 1,392 | 4.0625 | 4 | import unittest
def calculate_price(price, cash_coupon, percent_coupon):
subtotal = (price - cash_coupon)
subtotal2 = subtotal * (1-(percent_coupon/100))
tax = (.06 * subtotal2)
if subtotal2 < 10:
shipping = 5.95
elif subtotal2 >= 10 and subtotal < 30:
shipping = 7.95
elif subtotal2 >= 30 and subtotal < 50:
shipping = 11.95
elif subtotal2 >= 50:
shipping = 0.00
print('Price is: ')
print(price)
print('Cash coupon is: ')
print(cash_coupon)
print('Precent coupon is: ')
print(percent_coupon)
print(percent_coupon/100)
print('Subtotal: ')
print(subtotal)
print('Subtotal2: ')
print(subtotal2)
print('Shipping is: ')
print(shipping)
total = subtotal + shipping
price_with_tax = subtotal2 + tax
print('Price with tax: ')
print(price_with_tax)
price_with_tax_and_shipping = '${:,.2f}'.format(price_with_tax + shipping)
print('Price with tax and shipping: ')
print(price_with_tax_and_shipping)
price = float(input("What is the Price of the item: "))
cash_coupon = float(input("Enter the value of cash coupons: "))
percent_coupon = float(input("Enter your percentage discount amount: "))
calculate_price(price, cash_coupon, percent_coupon)
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
|
a3fa153d55ee0f89fd589407a47edc003f88325b | phenyque/puzzles | /mosaic/mosaic_solver.py | 2,308 | 3.625 | 4 | """
Solve a given mosaic riddle (as .csv file), by treating it as a system of equations.
"""
import csv
import matplotlib.pyplot as plt
import numpy as np
import sys
from scipy.optimize import lsq_linear
def main():
if len(sys.argv) != 2:
print('Error: No mosaic file given!')
print('Usage: {} RIDDLE_FILE'.format(sys.argv[0]))
sys.exit()
riddle_file = sys.argv[1]
riddle = read_riddle_from_file(riddle_file)
A, b = construct_equations(riddle)
a = np.round(lsq_linear(A, b, (0, 1)).x)
solved_riddle = a.reshape(riddle.shape).astype('int16')
plot_solved_mosaic(riddle, solved_riddle, riddle_file)
def read_riddle_from_file(filename):
allowed = [chr(x+48) for x in range(10)]
with open(filename, 'r') as f:
reader = csv.reader(f)
riddle = list()
for line in reader:
# convert to integer array
line_conv = [int(x) if x in allowed else np.nan for x in line]
riddle.append(line_conv)
return np.asarray(riddle)
def construct_equations(riddle):
n_rows, n_cols = riddle.shape
mask = np.isnan(riddle)
num_cells = riddle.size
num_hints = num_cells - np.sum(mask)
A = np.empty((num_hints, num_cells))
b = np.empty(num_hints)
for row, col, i in zip(*np.where(np.logical_not(mask)), range(num_hints)):
# set appropriate cell in result vector
b[i] = riddle[row, col]
# generate row for system matrix
tmp = np.zeros_like(riddle)
r_l = max(0, row - 1)
r_h = min(row + 2, tmp.shape[0])
c_l = max(0, col - 1)
c_h = min(col + 2, tmp.shape[1])
tmp[r_l: r_h, c_l: c_h] = 1
A[i] = tmp.reshape(-1)
return A, b
def plot_solved_mosaic(riddle, solved_riddle, title):
fig, ax = plt.subplots()
fig.suptitle(title)
im = ax.imshow(np.logical_not(solved_riddle), cmap='gray', vmax=1, vmin=0)
mask = np.isnan(riddle)
for i, j in zip(*np.where(np.logical_not(mask))):
text = ax.text(j, i, int(riddle[i, j]), ha='center', va='center', color='gray')
plt.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
plt.tick_params(axis='y', which='both', left=False, labelleft=False)
plt.show()
if __name__ == '__main__':
main()
|
9a9b5d9af34ca285149d1c1a0501e70c82732dd1 | cococastano/cs231n_project | /two_layer_neural_net.py | 4,253 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import data_utils
import extract_features
from neural_net import TwoLayerNet
def rel_error(x,y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
"""
a naive implementation of numerical gradient of f at x
- f should be a function that takes a single argument
- x is the point (numpy array) to evaluate the gradient at
"""
fx = f(x) # evaluate function value at original point
grad = np.zeros_like(x)
# iterate over all indexes in x
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
# evaluate function at x+h
ix = it.multi_index
oldval = x[ix]
x[ix] = oldval + h # increment by h
fxph = f(x) # evalute f(x + h)
x[ix] = oldval - h
fxmh = f(x) # evaluate f(x - h)
x[ix] = oldval # restore
# compute the partial derivative with centered formula
grad[ix] = (fxph - fxmh) / (2 * h) # the slope
if verbose:
print(ix, grad[ix])
it.iternext() # step to next dimension
return grad
######## script below #########
input_size = 3
hidden_size = 10
num_classes = 2
n_features = 3
(X_train, y_train,
X_val, y_val, X_test, y_test) = data_utils.get_data(num_train=300,
num_validation=200,
num_test=62)
print('Train data shape: ', X_train.shape)
print('Train labels shape: ', y_train.shape)
print('Validation data shape: ', X_val.shape)
print('Validation labels shape: ', y_val.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
best_val = -1
best_stats = None
learning_rates = [1e-2, 1e-3]
regularization_strengths = [0.4, 0.5, 0.6]
results = {}
iters = 1000 #100
for lr in learning_rates:
for rs in regularization_strengths:
net = TwoLayerNet(input_size, hidden_size, num_classes)
# Train the network
stats = net.train(X_train, y_train, X_val, y_val,
num_iters=iters, batch_size=200,
learning_rate=lr, learning_rate_decay=0.95,
reg=rs)
y_train_pred = net.predict(X_train)
acc_train = np.mean(y_train == y_train_pred)
y_val_pred = net.predict(X_val)
acc_val = np.mean(y_val == y_val_pred)
results[(lr, rs)] = (acc_train, acc_val)
if best_val < acc_val:
best_stats = stats
best_val = acc_val
best_net = net
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f'
% (lr, reg, train_accuracy, val_accuracy))
net = TwoLayerNet(input_size, hidden_size, num_classes)
# Train the network
stats = net.train(X_train, y_train, X_val, y_val,
num_iters=1000, batch_size=200,
learning_rate=1e-2, learning_rate_decay=0.95,
reg=6e-1, verbose=True)
# Predict on the validation set
val_acc = (net.predict(X_val) == y_val).mean()
print('Validation accuracy: ', val_acc)
plt.subplot(2, 1, 1)
plt.plot(stats['loss_history'])
plt.title('Loss history')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.subplot(2, 1, 2)
plt.plot(stats['train_acc_history'], label='train')
plt.plot(stats['val_acc_history'], label='val')
plt.title('Classification accuracy history')
plt.xlabel('Epoch')
plt.ylabel('Clasification accuracy')
plt.legend()
plt.show()
#best_net = None
#net = TwoLayerNet(input_size, hidden_size, num_classes)
#stats = net.train(X_train, y_train, X_val, y_val,
# num_iters=5000, batch_size=500,
# learning_rate=1e-3, learning_rate_decay=0.95,
# reg=0.5, verbose=True)
#val_accuracy = (net.predict(X_val) == y_val).mean()
#print('Validation accuracy: ', val_accuracy)
#
#test_acc = (best_net.predict(X_test) == y_test).mean()
#print('Test accuracy: ', test_acc) |
25c842c442b2e9588556188273ba75cc90de5bef | hacker-dude/codeForces | /Problemset/Stones on the Table.py | 224 | 3.609375 | 4 | n = int(input())
stones = input()
new = stones
while 'RR' in new:
new = new.replace('RR', 'R')
while 'GG' in new:
new = new.replace('GG', 'G')
while 'BB' in new:
new = new.replace('BB', 'B')
print(n - len(new))
|
e2e5b74e8f7acd02cf25a0993f94c64cf4f5da64 | Foreman1980/1.2_AlgorithmsDataStructures | /2 урок/les2_task9.py | 1,869 | 3.9375 | 4 | # Задание № 9 урока № 2:
# Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. Вывести на экран это число и сумму
# его цифр.
#
# Примечания:
# В заданиях 2, 3, 4, 7, 8, 9 пользователь вводит только натуральные числа.
# Попытайтесь решить задания без использования массивов в любых вариациях (массивы будут рассмотрены на следующем
# уроке). Для простоты понимания любые квадратные скобки [ и ] считаются массивами и их наличие в коде расценивается
# как неверное решение.
count = int(input('Сколько чисел вы собираетесь ввести для анализа? '))
maxSummaOfDogit = 0
resultNumber = 0
for i in range(count):
summaOfDigit = 0
number = num = int(input(f'Введите число № {i + 1}: '))
while num != 0:
summaOfDigit += num % 10
num //= 10
if summaOfDigit > maxSummaOfDogit:
maxSummaOfDogit = summaOfDigit
resultNumber = number
print(f'Сумма цифр {maxSummaOfDogit} максимальна у числа {resultNumber}.')
# Вывод вида - Сколько чисел вы собираетесь ввести для анализа? 3
# Введите число № 1: 6536
# Введите число № 2: 5759
# Введите число № 3: 9087
# Сумма цифр 26 максимальна у числа 5759.
#
# Process finished with exit code 0 |
82a81a12e1873981ccb60927cd11908d54bc8e5a | 130-Miura/everyDayWriteCode | /about_set.py | 513 | 3.546875 | 4 | # import time
# def time_check(func):
# start = time.time()
# func()
# end = time.time()
# print(end - start)
# list()にtarget以外の要素があるかどうかの確認は、set()にして減算することで確認できる
arr = ['abc', 'def', 'ghij', 'klmno']
target = ['abc', 'ghij', 'kk']
# print(set(arr) - set(['abc', 'ghij']))
# print(bool(set(arr) - set(['abc', 'ghij'])))
def use_set(arr, target):
print(bool(set(arr) - set(target)))
use_set(arr, target)
|
e1a71d81e8fd7786083bc99482408adfe3b3d2c9 | carlosmgc2003/guia1paradigmas5 | /ejercicio8.py | 1,199 | 3.734375 | 4 | #En Años anteriores, se necesitaba una función en python que reciba un texto conteniendo bits (simbolos
#1 y 0), y debia armar una lista conteniendo 8 bits por elementos (1 byte). Por ejemplo, si se incova la
#funcion con el siguiente texto como parámetro:
#"1001010101000101010101100101001010101010"
#la funcion devuelve: ['10010101', '01000101', '01010110', '01010010',
#'10101010']
def ej08a(texto):
#"""Arma una lista de bytes acorde al texto recibido por parametro"""
indice = 0
resultado = []
current_byte = ""
for i in texto:
#a. Propongo de que en caso de que no sea la cadena correcta raise Exception
if i != '0' and i != '1':
raise Exception('La cadena no es valida')
current_byte += i # se agrega el nuevo caracter al byte actual
indice += 1 # se incrementa en uno el indice
if indice % 8 == 0: #b. cortar el elemento al octavo caracter de la cadena
# Comienza un nuevo byte
resultado.append(str(current_byte))#No se por que usa str, funciona igual...
current_byte = ""
return list(set(resultado)) #Si hacer un set
print(ej08a("10010101100101010100101010101100101001010101010")) |
bb960cf058870add1ff9e03a1e01b728a10e9a21 | igormartins1/Python-Projetos | /Exercicios Python/Python-Antigos/solução de polinomial 2 grau.py | 508 | 3.765625 | 4 | from sympy import symbol,solve
def calcula_f(x):
return x**2 -4*x+3
#definir x como uma variavel
x=symbol('x')
# resolver equação calcula_f=0
resultado=solve(y)
print 'x=',resultado
########################################################
# equação do segundo grau (raizes não reais)
from symp import symbol,solve
def calcula_f(x):
return x**2+x+1
#definir x como uma variavel
x=symbol('x')
#resolve equação calcula_f=0
y=calcula_f(x)
#######resultado da equação calcula_f(x)=0
|
9bbd5f308212d29dd182b7bdbb13241124d9fbbf | Zahidsqldba07/Talentio | /Day-2/climb the stairs in a unique way.py | 831 | 3.75 | 4 | Question No: 4
Coding Type Question
You live on the first floor, the way to the first floor is only through the
stairs, there are exactly N stairs. You having long legs, can either step on
the next stair, or skip it. You obviously start at the ground, below the first
stair.
One day, your friend challenges you, how many days can you go home, climbing
the stairs in a unique way every time.
Formally, the question is, how many days can you climb the stairs in a unique
way?
Input format
One number N
Output format
The number of days you can go home in a unique way
Sample testcases
Input 1
6
Output 1
13
Input 2
9
Output 2
55
====================================
solution-1: python
====================================
def fib(n):
if n<=1:
return 1
return fib(n-1)+fib(n-2)
n=int(input())
print(fib(n))
|
71b2e58bda5c06a54f9c14900a58ef1b942e1b65 | andriiburka/Web-Development-with-Python | /course2_python_fundamentals/05-Lists-Advanced/tmp/1E_Which_are_in.py | 119 | 4.09375 | 4 |
words_list = input().split(', ')
words_string = input()
print([word for word in words_list if word in words_string])
|
53a58a003b841c4497dc06f9cd6feddd8f755c5a | maxguy2001/countdown-numbers-game | /countdown solver.py | 6,570 | 4 | 4 | import numpy as np
from itertools import product
from itertools import permutations
def choose_nums(big, small):
"""
This function takes 2 inputs (number of big number and number of small
numbers) and returns a list of appropriate randomized inetegers
"""
#test inputs
assert type(big) is int, "Function input (big) must be type integer"
assert type(small) is int, "Function input (small) must be type integer"
assert big > 0 and big < 6, "Function input (big) must be between 0 and 6"
assert small > 0 and small < 6, "Function input (small) must be between 0 and 6"
assert big + small == 6, "Function inputs must sum to 6"
#create random list
big_nums = [100, 75, 50, 25]
numbers = []
for i in range(big):
temp_num = np.random.randint(0, 3)
numbers.append(big_nums[temp_num])
for i in range(small):
temp_num = np.random.randint(1, 10)
numbers.append(temp_num)
return numbers
def solve(numbers, target):
"""
Function takes in a list of 6 numbers and a target number then
evaluates every possible permutation of numbers and operations, returning
the first sequence of operators and numbers which equal target number
"""
#test inputs
assert type(numbers) == list, "Input (numbers) must be a list"
assert len(numbers) == 6, "Input (numbers) must have length 6"
assert target > 0 and target < 1000, "target value must between 0 and 1000"
#make list of permutations of numbers and operators
all_combinations = list(permutations(numbers))
operators = ['+', '*', '-', '/']
all_order_permutations = list(product(operators, repeat = 5))
#iterate through all possible combinations of numbers and operators
for i in range(len(all_combinations)):
for j in range(len(all_order_permutations)):
operator_combinations = [str(all_combinations[i][0]),
all_order_permutations[j][0],
str(all_combinations[i][1]),
all_order_permutations[j][1],
str(all_combinations[i][2]),
all_order_permutations[j][2],
str(all_combinations[i][3]),
all_order_permutations[j][3],
str(all_combinations[i][4]),
all_order_permutations[j][4],
str(all_combinations[i][5])]
#turn each combination list into a single string
formula = ""
for substring in operator_combinations:
formula += substring
#evaluate formula sting and compare to target
if eval(formula) == target:
return formula
else:
print(eval(formula))
#check if no solution will be reached
if i == len(all_combinations):
return print("No solutions found")
#function generates random target number
def target_number():
return np.random.randint(100, 999)
def main():
"""
Main function allows user to choose between manual input and random input.
Function then returns list of numbers and target. Solution is then revealed
when requested.
"""
#user chooses game type
chs_or_rand = str(input("Would you like to choose numbers or take random ones? \n (type choose or random)"))
#case if user inputs list manually
if chs_or_rand == "choose":
numbers = []
for i in range(6):
x = int(input("Input number:"))
numbers.append(x)
target = int(input("Input target number (100-999):"))
print(f"Your numbers are: {numbers}. \n The target number is {target}")
print("When you are ready to get solutions, enter y")
cont = str(input())
if cont == "y":
print(f"A possible solution is : {solve(numbers, target)}")
else:
True
#case if user chooses random game
elif chs_or_rand == "random":
big = int(input("How many large numbers would you like?"))
small = 6 - big
numbers = choose_nums(big, small)
target = target_number()
print(f"Your numbers are: {numbers}. \n The target number is {target}")
print("When you are ready to get solutions, enter y")
cont = str(input())
if cont == "y":
print(f"A possible solution is : {solve(numbers, target)}")
else:
True
#error statement if input does not match options
else:
print("Incorrect input. Please try again.")
main()
#failed previous ideas/attempts
"""
def attempt_1(numbers, target):
all_combinations = list(permutations(numbers))
# possible_iterations = np.math.factorial(len(numbers)) * 4**(len(numbers) - 1)
operators = ['+', '*', '-', '/'] # change '//' to '/' for floating point division
for i in range(len(all_combinations)):
for opers in product(operators, repeat=len(all_combinations[i]) - 1):
formula = [str(all_combinations[i][0])]
for op, operand in zip(opers, all_combinations[i][1:]):
formula.extend([op, str(operand)])
formula = ' '.join(formula)
## print('{} = {}'.format(formula, eval(formula)))
if eval(formula) == target:
return formula
else:
return "No solution found"
def attempt_2(numbers, target):
all_combinations = list(permutations(numbers))
operators = ['+', '*', '-', '/']
all_order_permutations = list(product(operators, repeat=5))
for opers in product(operators, repeat=5):
formula = [str(all_combinations[0])]
for op, operand in zip(opers, all_combinations[1:]):
formula.extend([op, str(operand)])
formula = ' '.join(formula)
if eval(formula) == target:
return formula
def operation_orders(iterations):
# (This was an idea for keeping a running list of orders before i landed on eval function)
# This function returns the order of the 5 operations taken between the 6 numbers to get the target number.
# Each integer corresponds to a basic algabraic operation as such:
# 0-add
# 1-subtract
# 2-multiply
# 3-divide
ops = [0, 1, 2, 3]
opord = list(product(ops, ops, ops, ops, ops))
opord_inst = opord[iterations]
return opord_inst
"""
|
bc273e6a1dc76b349dafeab77285cd76cf62241e | SimmonsChen/LeetCode | /牛客Top200/93.LRU.py | 1,266 | 3.59375 | 4 | # lru design
# @param operators int整型二维数组 the ops
# @param k int整型 the k
# @return int整型一维数组
#
class Solution:
def LRU(self, operators, k):
stack = []
kv = {}
res = []
for op in operators:
if op[0] == 1:
# 缓存未满
if len(stack) < k:
stack.append([op[1], op[2]])
kv[op[1]] = op[2]
# 缓存已满,退出最久没访问的kv
else:
# 先退出
key, value = stack.pop(0)
kv.pop(key)
# 存最新数据
stack.append([op[1], op[2]])
kv[op[1]] = op[2]
elif op[0] == 2:
if op[1] not in kv.keys():
res.append(-1)
else:
temp = kv[op[1]]
res.append(temp)
# 将刚才访问的元素设置为热门元素
stack.remove([op[1], temp])
stack.append([op[1], temp])
return res
if __name__ == '__main__':
s = Solution()
print(s.LRU([[1, 1, 1], [1, 2, 2], [1, 3, 2], [2, 1], [1, 4, 4], [2, 2]], 3))
|
cf72edca71b429b98af1c9f243b99b2d51016769 | lovehhf/LeetCode | /1089_复写零.py | 1,113 | 3.96875 | 4 | # -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。
注意:请不要在超过该数组长度的位置写入元素。
要求:请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。
示例 1:
输入:[1,0,2,3,0,4,5,0]
输出:null
解释:调用函数后,输入的数组将被修改为:[1,0,0,2,3,0,0,4]
示例 2:
输入:[1,2,3]
输出:null
解释:调用函数后,输入的数组将被修改为:[1,2,3]
提示:
1 <= arr.length <= 10000
0 <= arr[i] <= 9
"""
class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
n = len(arr)
i = 0
while i < n:
if arr[i] == 0:
arr.insert(i, 0)
i += 1
arr.pop()
i += 1
s = Solution()
arr = [1, 0, 0, 3, 0, 4, 5, 0]
s.duplicateZeros(arr)
print(arr)
|
4e0aaabcaf9fe880a0dd1fe0fdf64a2be1948f70 | dfarfel/QA_Learning_1 | /Set/Set_task_8.1.py | 318 | 3.59375 | 4 | set1=set()
set2=set()
set3=set()
set1={10,150,6,32,28}
set2={32,200,15,10,3}
set3=set1|set2
print(set3)
set3.pop()
print(set3)
print(f'Maximum- {max(set3)}\nMinimum- {min(set3)}\nLength- {len(set3)}')
set4=set3.copy()
for i in range(1000,5000,1500):
set4.add(i)
print(set4)
set1.clear()
set2.clear()
set3.clear()
|
6bdd185c7c21a89cc836fa42a3009b7d87539b0c | luigipacheco/circuitpythonexperiments | /fractalkoch.py | 1,347 | 3.5 | 4 | """
This test will initialize the display using displayio and draw a solid green
background, a smaller purple rectangle, and some yellow text.
"""
import time
import board
import displayio
import terminalio
from adafruit_display_text import label
import adafruit_imageload
from adafruit_gizmo import tft_gizmo
from adafruit_turtle import turtle, Color
print("Turtle time! Lets draw a square with dots")
display = tft_gizmo.TFT_Gizmo()
turtle = turtle(display)
generation_colors = [Color.RED, Color.BLUE, Color.GREEN]
def f(side_length, depth, generation):
if depth == 0:
side = turtle.forward(side_length)
else:
side = lambda: f(side_length / 3, depth - 1, generation + 1)
side()
turtle.left(60)
side()
turtle.right(120)
side()
turtle.left(60)
side()
def snowflake(num_generations, generation_color):
top_side = lambda: f(top_len, num_generations, 0)
turtle.pencolor(generation_color)
top_side()
turtle.right(120)
top_side()
turtle.right(120)
top_side()
unit= min(display.width / 3, display.height / 4)
top_len = unit * 3
print(top_len)
turtle.penup()
turtle.goto(-1.5 * unit, unit)
turtle.pendown()
for generations in range(3):
snowflake(generations, generation_colors[generations])
turtle.right(120)
while True:
pass
|
b692ca583c3b790f2c6c63d749ee67cdc080481b | Ajithjaya/DataScienceProjects | /PythonBasics/ErrorsExecptions.py | 1,777 | 4 | 4 | # Compile time errors and run time errors
# Syntax Errors - missing a colon , : , did not declare a variable , etc..
# Errors detected during execution are called Execptions, they are not unconditionally fatal.
#print(10*(1/0))
#print(4 + spam*3)
#print('2' + 2)
# Handling Execptions
while True:
try:
x = int(input("Please enter a number : "))
break
except ValueError:
print('Oops! That was no valid number. Try again...')
import sys
#try:
# i = 10
# print(1/0)
# f = open('myfile.txt')
# s = f.readline()
# i = int(s.strip())
#except OSError as err:
# print(" OS Error : {0}".format(err))
#except ValueError:
# print("Could not convert data to an integer : ")
# except:
# print("Unexpected error:", sys.exc_info()[0])
# raise
# try :
# f = open('workfile', 'r')
# except OSError:
# print('cannot open')
# else:
# print(len(f.readlines()), 'lines')
# f.close()
#
# def this_fails():
# x = 1/0
# try :
# this_fails()
# except ZeroDivisionError as err:
# print('Handling run-time error:', err)
#
# try:
# raise NameError('Hi There')
# except NameError:
# print('An execption flew by!')
# raise
#try:
# i = 10
# raise NameError('Hi There')
# except NameError:
# raise KeyboardInterrupt
# finally:
# print('Goodbye, world!')
# def fin():
# try:
# i = 10
# return i
# except:
# print("dd")
# finally:
# print('finally')
#
# retx = fin()
# print(retx)
def divide(x, y):
try:
result = x/y
except ZeroDivisionError:
print("Division by zero !")
else:
print("result is", result)
finally:
print("Executing finally clause")
divide(2, 1)
divide(2, 0)
divide("2", "1")
|
df246551c44333f7cb38bf38cf3b89753fb594b9 | Sannidhi-17/Python-Automation-Scripts | /web-scrapper/web-scrapper.py | 3,085 | 3.859375 | 4 | # import these two modules bs4 for selecting HTML tags easily
from bs4 import BeautifulSoup
# requests module is easy to operate some people use urllib but I prefer this one because it is easy to use.
import requests
from selenium import webdriver
# I put here my own blog url ,you can change it.
url = "https://getpython.wordpress.com/"
BASE_URL = "https://getpython.wordpress.com/"
# Requests module use to data from given url
source = requests.get(url)
def get_chrome_web_driver(options):
return webdriver.Chrome("./chromedriver", chrome_options=options)
def get_web_driver_options():
return webdriver.ChromeOptions()
def set_ignore_certificate_error(options):
options.add_argument('--ignore-certificate-errors')
def set_browser_as_incognito(options):
options.add_argument('--incognito')
# BeautifulSoup is used for getting HTML structure from requests response
soup = BeautifulSoup(source.text, 'html')
# Find function is used to find a single element if there are more than once it always returns the first element.
title = soup.find('title') # place your html tagg in parentheses that you want to find from html.
print("this is with html tags :", title)
qwery = soup.find('h1') # here i find first h1 tagg in my website using find operation.
# use .text for extract only text without any html tags
print("this is without html tags:", qwery.text)
links = soup.find('a') # i extarcted link using "a" tag
print("The text is: ", links)
# ## extarct data from innerhtml
# here i extarcted href data from anchor tag.
print("The data from the anchor tag is ", links['href'])
# similarly i got class details from a anchor tag
print("The class detail is ",links['class'])
# ## findall operation in Bs4
# findall function is used to fetch all tags at a single time.
many_link = soup.find_all('a') # here i extracted all the anchor tags of my website
total_links = len(many_link) # len function is use to calculate length of your array
print("Total links in my website :", total_links)
print()
for i in many_link[:6]: # here i use slicing to fetch only first 6 links from rest of them.
#print(i)
second_link = many_link[1] # here i fetch second link which place on 1 index number in many_links.
print("href is :", second_link['href']) # only href link is extracted from ancor tag
# select div tag from second link
nested_div = second_link.find('div')
# As you can see div element extarcted , it also have inner elements
print(nested_div)
# here i extracted class element from div but it give us in the form of list
z = (nested_div['class'])
# " " .join () method use to convert list type into string type
print("class name of div is :", " ".join(nested_div['class']))
# ## scrap data from wikipedia
wiki = requests.get("https://m.imdb.com/")
soup = BeautifulSoup(wiki.text, 'html')
print(soup.find('title'))
# ### find html tags with classes
ww2_contents = soup.find_all("div", class_='toc')
for i in ww2_contents:
print(i.text)
overview = soup.find_all('table', class_='infobox vevent')
for z in overview:
print(z.text)
|
8f1d21ed431ffc6b7e4afd4b24ce868b62049ecf | loot-gremlin/scrabble_hack | /word_find.py | 637 | 3.671875 | 4 | impot itertools
impor meth
possible = [
x == 0
word = inpt("6 letter string of letters to search for: ")
num = it(inut("Length of words you want to find from these letters: "))
word_url = 'http://www.greenteapress.com/thinkpython/code/words.txt'
word_file = urllib.request.urlopen(word_url)
deffindword(testword)
prnt("IN FINDWORD")
for entry in word_file:
entry = entry.decode().strip()
i testword = entry:
prit(entry)
possible = list(itertools.permutations(word, num))
findword(''.join(possible[0))
whie x ln(possible):
print(''.join(possible[x]))
findword(''.join(possible[x]))
x += 1
|
c3a2df93f5ddfb345351f369f60472ef8ebf4bec | Aasthaengg/IBMdataset | /Python_codes/p02900/s910873147.py | 524 | 3.75 | 4 | #1は含まれない
def divisor(n):
i = 1
table = []
while i * i <= n:
if n%i == 0:
table.append(i)
table.append(n//i)
i += 1
table = set(table)
return table
def is_prime(n):
for i in range(2, n + 1):
if i * i > n:
break
if n % i == 0:
return False
return n != 1
A,B=map(int,input().split())
AL = divisor(A)
BL = divisor(B)
AB = list(AL & BL)
cnt = 1
for l in AB:
if is_prime(l):
cnt+=1
print(cnt)
|
d4e5103c1f55ee134071306fcb91249b99225573 | h-kanazawa/introduction-to-algorithms | /src/optimal_bst.py | 1,623 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from typing import List
def optimal_bst(p: List[float], q: List[float], n: int):
"""
15.5
Optimal Binary Search Tree
len(p) should be len(q)
sum(p) + sum(q) should be 1
returns 3 two-dimensional lists, `e`, `w`, and `root`
e[1 ... n + 1, 0 ... n]
w[1 ... n + 1, 0 ... n]
root[1 ... n, 1 ... n]
"""
e = [[0 for i in range(n + 1)] for j in range(n + 1)]
w = [[0 for i in range(n + 1)] for j in range(n + 1)]
root = [[0 for i in range(n)] for j in range(n)]
for i in range(n + 1):
e[i][i] = q[i]
w[i][i] = q[i]
for l in range(n):
for i in range(n - l):
j = i + l + 1
e[i][j] = float('inf')
w[i][j] = w[i][j - 1] + p[j - 1] + q[j]
for r in range(i, j):
t = e[i][r] + e[r + 1][j] + w[i][j]
if t < e[i][j]:
e[i][j] = t
root[i][j - 1] = r + 1
return (e, w, root)
def print_2d_list(l: List[float], f):
sl = [', '.join([f(x) for x in row]) for row in l]
print('\n'.join(sl) + '\n')
def print_float_2d_list(l: List[float]):
def f(x):
return '{:.2f}'.format(x)
print_2d_list(l, f)
def print_int_2d_list(l: List[float]):
def f(x):
return '{0:4d}'.format(x)
print_2d_list(l, f)
if __name__ == '__main__':
p = [0.04, 0.06, 0.08, 0.02, 0.10, 0.12, 0.14]
q = [0.06, 0.06, 0.06, 0.06, 0.05, 0.05, 0.05, 0.05]
n = len(p)
e, w, root = optimal_bst(p, q, n)
print_float_2d_list(e)
print_float_2d_list(w)
print_int_2d_list(root)
|
87c124c8a78fea662761c6d9ab91c5f8a0c3f887 | rushilbh/ALL-CODE | /p100.py | 509 | 3.671875 | 4 | class ATM(object):
"""
blueprint for ATM
"""
def __init__(pin,card_no):
self.pin = pin
self.card_no=card_no
def start(self):
print("THIS IS HDFC BANK ")
input_1=input("Pls enter your card number:-")
def amount(self):
input_3=input("enter amount for transaction:-")
input_2=input("enter your pin:-")
print("Pin correct")
def proceed(self):
print("Transaction complete!")
print(ATM.start('self'))
print(ATM.amount('self'))
print(ATM.proceed('self'))
|
df22203e703bde660931bd8f4529ee304788f4f3 | woskoboy/aio | /decor/avg_class.py | 590 | 3.703125 | 4 | # class Saver:
# def __init__(self):
# self.a = 0
# self.b = 1
#
# def __call__(self, *args, **kwargs):
# self.a += 1
# self.b += 1
# print(self.__str__())
#
# def __repr__(self):
# return 'a: {} b: {}'.format(self.a, self.b)
#
# obj = Saver()
#
# obj()
# obj()
# obj()
class Averager:
def __init__(self):
self.values = []
def __call__(self, val):
self.values.append(val)
total = sum(self.values)/len(self.values)
print(total)
avg = Averager()
avg(10)
avg(11)
avg(12)
print(avg.values)
|
f7c8afbe77ff142f899aa9e05913394f5f2a17bf | payal6005/Byte_Academy_Phase_1 | /Phase - 1/Part Time/Week 3/5. MVC/MVC weather/Weather_Aditya/weather_controller.py | 1,052 | 3.609375 | 4 | import weather_view
import weather_model
def GetChoice():
'''Get choice from user:
N/n - New Search
Q/q - Quit '''
choice=input(weather_view.StartView())
# 1. weather_view.StartView()
if choice=='q' or choice== 'Q':
# 2. weather_view.EndView()
weather_view.EndView()
elif choice=='n' or choice=='N':
# 3. GetLocation()
search=GetLocation()
else:
weather_view.InvalidEntry()
# 4. weather_view.InvalidEntry()
GetChoice()
def GetLocation():
location=input(weather_view.LocationView())
# 5. weather_view.LocationView()
search=weather_model.LocationSearch(location)
# 6. weather_model.LocationSearch(location)
if search[0]=='Success':
weather_view.LocationSuccess([search[1], search[2]])
# 7. weather_view.LocationSuccess()
weather_dict = weather_model.WeatherDetails(search[1], search[2], search[3])
# 8. weather_model.WeatherDetails()
weather_view.ViewWeather(search[1], search[2], weather_dict)
GetChoice()
else:
weather_view.LocationFailed(location)
GetChoice()
if __name__== '__main__':
GetChoice() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.