blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0966afba7b408899717116feb36d960434974d7b | CODEREASYPYTHON/Calculator | /easy_calculator.py | 661 | 4.21875 | 4 | while True:
number_one = input("Enter the first number:")
query = input("Which arithmetic operation should be carried out? (+,-,/.,*):")
number_two = input("Enter the second number:")
Equal_1 = float(number_one)
Equal_2 = float(number_two)
if query == "+":
print("Your result",Equal_1+Equal_2)
if query == "-":
print("Your result",Equal_1-Equal_2)
if query == "*":
print("Your result",Equal_1*Equal_2)
if query == "**":
print("Your result",Equal_1**Equal_2)
if query == "/":
print("Your result",Equal_1/Equal_2)
if query == "//":
print("Your result",Equal_1//Equal_2) |
b91f74e2774e901539f90ce7315542323e36c696 | MomsFriendlyRobotCompany/mjolnir | /ex8029/software/camera-imu/tools/hertz.py | 901 | 3.71875 | 4 | import time
class Hertz:
__slots__ = ["rollover", "format", "start", "count"]
def __init__(self, format, rollover):
"""
format: string format to use when printing
rollover: when to print string
"""
self.rollover = rollover
self.format = format
self.reset()
def increment(self):
"""
Update count and if count == rollover, then print
hertz using the format. Also at rollover, it resets
"""
self.count += 1
if (self.count % self.rollover) == 0:
now = time.monotonic()
hz = self.count/(now - self.start)
self.count = 0
self.start = now
print(self.format.format(hz))
def reset(self):
"""
Resets count to 0 and start to current time
"""
self.start = time.monotonic()
self.count = 0
|
366919c9cc78b5fbbb4b9320d61594b36b3c2e09 | MomsFriendlyRobotCompany/mjolnir | /ex8029/software/camera-imu/old/python/filters.py | 890 | 3.515625 | 4 |
from collections import deque
from collections import namedtuple
class AverageFilter(deque):
def __init__(self, maxlen=5):
super().__init__(maxlen=maxlen)
for i in range(maxlen):
# self.__setitem__(i, 0.0)
self.append(np.zeros(3))
def avg(self):
avg = 0
num = self.__len__()
# print(num)
for i in range(num):
# print(self.__getitem__(i), end=" ")
avg += self.__getitem__(i)
return avg/num
def normalize3(x, y, z):
"""Return a unit vector"""
norm = sqrt(x * x + y * y + z * z)
# already a unit vector
if norm == 1.0:
return (x, y, z)
inorm = 1.0/norm
if inorm > 1e-6:
x *= inorm
y *= inorm
z *= inorm
else:
raise ZeroDivisionError(f'norm({x:.4f}, {y:.4f}, {z:.4f},) = {inorm:.6f}')
return (x, y, z,)
|
8fc1f9ae760502e3dff87c84369319a8264ce645 | panluo/learn | /test/python/threading/prodcons.py | 1,360 | 3.5 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from random import randint
from time import sleep,ctime
from Queue import Queue
import threading
class Mythread(threading.Thread):
def __init__(self,func,args,name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
def getResult(self):
return self.res
def run(self):
print 'starting',self.name,'at:',ctime()
self.res = apply(self.func,self.args)
print self.name,'finished at:',ctime()
def writeQ(queue):
print 'producing object for Q...',queue.put('xxx',1)
print 'size now',queue.qsize()
def readQ(queue):
val = queue.get(1)
print 'consumed object from Q... size now',queue.qsize()
def writer(queue,loops):
for i in range(loops):
writeQ(queue)
sleep(randint(1,3))
def reader(queue,loops):
for i in range(loops):
readQ(queue)
sleep(randint(2,5))
funcs = [writer, reader]
nfuncs = range(len(funcs))
def main():
nloops = randint(2,5)
q = Queue(32)
threads = []
for i in nfuncs:
t = Mythread(funcs[i],(q,nloops),funcs[i].__name__)
threads.append(t)
for i in nfuncs:
threads[i].start()
for i in nfuncs:
threads[i].join()
print 'all DONE'
if __name__ == '__main__':
main()
|
13ebec916c6fc5bdefc1fad2756229ecd99c034d | panluo/learn | /test/python/string/reverse.py | 2,095 | 3.71875 | 4 | '''
created on 2014-10-20
@author : luopan
'''
class MyString():
def reverse(self, some_seq):
"""
input : Sequence
output : Sequence:
reversed version
"""
return some_seq[::-1]
def count_vowels(self, string):
"""
@param string : String
@return : Integer :
No. of vowels or 0
"""
vowel = "aeiou"
count = {char:0 for char in vowels}
for char in string:
if char in vowels:
count[char]+=1
return count
def is_palindrome(self,some_seq):
"""
@param some_seq: sequence of anything
@return: Boolean:
palindrome check of sequence passed
"""
return some_seq == self.reverse(some_seq)
def count_words(self,string=None,file=None):
"""
@param string : A string
@param file : A file to be read
"""
word_count = 0
if string:
word_count = len(string.split())
if file:
with open(file) as f:
word_count = len(f.read().split())
return word_count
def piglatin(self, string):
"""
Pig Latin – Pig Latin is a game of alterations played on the English language game.
To create the Pig Latin form of an English word the initial consonant sound is
transposed to the end of the word and an ay is affixed
(Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules.
"""
words = []
vowels = 'aeiou'
for word in string.split():
if len(word) > 2 and word[0] not in vowels:
words.append(word[1:]+'-'+word[0]+'ay')
else:
words.append(word+'-ay')
return ' '.join(words)
if __name__ == '__main__':
x = MyString()
string = "a barbie vanquished the knights of the round table by hitting them in the face"
print(x.piglatin(string))
|
ec002bc040269247d5414ab19f16f4c96ee57b6d | dalton-omens/hackjam-fa-2016 | /make_preferences.py | 1,020 | 3.90625 | 4 | def make_preferences(genre_list, num_users):
def prompt():
print('\nWhat are you interested in? Here are your options: If you\'re done, type \"Done\".\n')
lst = ''
for i in range(len(genre_list) - 2):
lst = lst + genre_list[i] + ', '
lst = lst[:-2] + '\n'
return input(lst).strip()
preferences = []
for user in range(int(num_users)):
print('\nUser ' + str(user + 1) + ':')
user_preferences = []
done = False
while not done:
new_preference = prompt()
if new_preference in genre_list and new_preference not in genre_list[:-3:-1] and new_preference not in user_preferences:
user_preferences += [new_preference]
elif new_preference == 'Done' or new_preference == "done":
done = True
else:
print('\nPlease type a valid new word in the list.')
preferences += [user_preferences]
return preferences
|
53683a4d01754dbc4cfa211524ed4c3f86259b03 | cocococosti/Tarea2IngSoftware | /classPension.py | 3,088 | 3.5625 | 4 | '''
Creado el 10 oct. 2018
@author: Constanza Abarca 13-10000
@author: Pedro Maldona 13-10790
'''
import datetime
from _datetime import date
class Pension():
def calcularSemanas(self, dia, mes, anio):
# Obtener fecha hoy
hoy = datetime.date.today()
fechaTrabajo = datetime.date(anio, mes, dia)
dias = (hoy-fechaTrabajo).days
semanas = dias/7
# Redondear semanas
return round(semanas)
def esPensionado (self, genero, dia, mes, anio, edad, cond):
if (isinstance(dia, float) or isinstance(mes, float) or isinstance(anio, float) or isinstance(edad, float)):
raise ValueError("Error. No pueden ser numeros decimales")
if (dia <= 0 or mes <= 0 or anio <= 0 or edad <= 0):
raise ValueError("Error. No pueden ser numeros negativos o cero")
if (dia > 31 or mes > 12 or anio > 2018):
raise ValueError("Error. Valores invalidos para una fecha.")
if (genero != "M" and genero != "F"):
raise ValueError("Error. El genero solo puede ser M o F.")
if ((datetime.date.today()-datetime.date(anio, mes, dia)).days<0):
raise Exception("Error. La fecha no puede ser futura.")
mayorEdad = datetime.date.today().year - edad + 18
if (anio < mayorEdad):
raise Exception("Error. La fecha inicio de trabajo debe ser posterior a haber cumplido 18 años.")
semanas = self.calcularSemanas(dia, mes, anio)
if (cond == True):
if (semanas >= 48 and semanas < 96):
edad = edad + 1
elif (semanas >= 95 and semanas < 144):
edad = edad + 2
elif (semanas >= 144 and semanas < 192):
edad = edad + 3
elif (semanas >= 192 and semanas < 240):
edad = edad + 5
elif (semanas >= 240):
edad = edad + 5
else:
pass
if (genero == "M"):
if (edad < 60):
return False
elif (genero == "F"):
if (edad < 55):
return False
if (semanas > 750):
return True
else:
return False
if __name__ == '__main__':
pension = Pension()
edad = int(input("Introduzca edad "))
dia = int(input("Introudzca dia de incio de trabajo "))
mes = int(input("Introudzca mes de incio de trabajo "))
anio = int(input("Introudzca anio de incio de trabajo "))
genero = input("Introudzca genero (F/M) ")
cond = input("¿Trabajo en condiciones insalubres?(y/n) ")
if (cond == "y"):
insa = True
else:
insa = False
try:
jubilado = pension.esPensionado(genero, dia, mes, anio, edad, insa)
if (jubilado):
print("La persona cumple los requisitos para recibir una pension.")
else:
print("La persona no cumple los requisitos para recibir una pension.")
except:
print("Valores invalidos. Intente de nuevo.")
|
6d668b5191a2af61832ea30fddd53dfc650f684c | pengshancai/math-lego | /lego_basic.py | 3,633 | 3.5 | 4 | # Author: Pengshan Cai
# Email: pengshancai@umass.edu
from utils import *
delta_min = 1e-17
# the derivative is a constant
def const_bender(args):
num_steps = args['num_steps']
cur_angle = args['angle']
bend_rate = args['bend_rate']
for i in range(num_steps):
yield cur_angle, bend_rate
cur_angle -= bend_rate
# the derivative is in accordance with a linear function
# smoothly adjust the derivative, keeping the function differentiable (thus smooth)
def linear_bender(args):
num_steps = args['num_steps']
cur_angle = args['angle']
bend_rate_ss = (args['target_bend_rate'] - args['init_bend_rate'])/num_steps
bend_rate = args['init_bend_rate']
for i in range(num_steps):
cur_angle -= bend_rate
bend_rate += bend_rate_ss
yield cur_angle, bend_rate
# the derivative is in accordance with a sin function
# d_bend_rate_angle_ss: step size of the bend rate angle, increase this parameter would cause a more curly bend
# amplitude: the maximum bend rate derivative, increase this parameter would also cause a more curly bend
def sin_bender(args):
# parameters
num_steps = args['num_steps']
cur_angle = args['angle']
init_bend_rate = args['init_bend_rate']
bend_rate = init_bend_rate
amplitude = args['amplitude']
bend_rate_angle = args['bend_rate_angle']
bend_rate_angle_ss = args['bend_rate_angle_ss']
for i in range(num_steps):
d_bend_rate = amplitude * np.sin(angle2radian(bend_rate_angle))
cur_angle -= bend_rate
bend_rate = init_bend_rate + d_bend_rate
bend_rate_angle += bend_rate_angle_ss
yield cur_angle, bend_rate
# slowly decrease to zero
def exp_bender(args):
pass
# the derivative is in accordance with a inverse function
def inverse_bender():
pass
# Make sure all necessary parameters are contained in args
# if not, use the default setting
def sanity_check(args):
assert 'x' in args
assert 'angle' in args
if 'color' not in args:
args['color'] = (1.0, 1.0, 1.0, 1.0)
if 'num_steps' not in args:
args['num_steps'] = 180
print('number of step not specified')
if 'step_size' not in args:
args['step_size'] = 0.01
print('step size not specified')
if 'line_width' not in args:
args['line_width'] = 1.0
print('line width not specified')
if 'delta' not in args:
args['delta'] = 0.09
def paint(args, bender):
x = args['x']
palette = get_color(args['color'], args['num_steps'])
line_width_iter = get_line_width(args['line_width'], args['num_steps'])
for angle, bend_rate in bender:
y = get_next_point(x, angle, args['step_size'])
color = next(palette)
line_width = next(line_width_iter)
animate(x, y, color, line_width)
x = y
plt.draw()
plt.pause(delta_min)
time.sleep(args['delta'])
return x, angle, bend_rate
def paint_const(args):
# sanity check
sanity_check(args)
assert 'bend_rate' in args
# initialization
bender = const_bender(args)
# paint
return paint(args, bender)
def paint_linear(args):
# sanity check
sanity_check(args)
assert 'init_bend_rate' in args
assert 'target_bend_rate' in args
# initialization
bender = linear_bender(args)
# paint
return paint(args, bender)
def paint_sin(args):
# sanity check
sanity_check(args)
assert 'init_bend_rate' in args
assert 'amplitude' in args
assert 'bend_rate_angle_ss' in args
# initialization
bender = sin_bender(args)
# paint
return paint(args, bender)
|
9f343926f97ffa60ce5f1ea46e48b94cb8ff78b1 | siddhartht16/IR-web-crawler-python | /utils.py | 5,532 | 4 | 4 | import os
from urlparse import urlparse
def is_string_valid(p_string):
"""
Method to validate whether the input string is a valid string or not
:param p_string: Input string which needs to be validated
:return: true if string is valid else false
"""
if p_string == '':
return False
elif p_string is None:
return False
elif p_string.strip() == '':
return False
else:
return True
def create_directory(p_Directory):
"""
Method to create directory for each site for storing files
:param p_Directory: Directory path which needs to be created
:return: nothing
"""
if not os.path.exists(p_Directory):
print('creating directory: ' + p_Directory)
os.makedirs(p_Directory)
def create_file(p_filename, p_filepath):
"""
Method to create a file with the given name
:param p_filename: Filename with which the file is to be created
:param p_filepath: Path at which the file is to be created
:return: nothing
"""
if is_string_valid(p_filepath):
p_filename += p_filepath
if not os.path.isfile(p_filename):
write_to_file(p_filename, '')
def write_to_file(p_filepath, p_data):
"""
Method to write input data to file
:param p_filepath: Path at which the file is to be created
:param p_data: Data which needs to be written to the file
:return: nothing
"""
with open(p_filepath, 'w') as lfile:
lfile.write(p_data)
def append_to_file(p_FilePath, p_Data):
"""
Method to append data to file
:param p_FilePath: File's complete path at which the file is there in which the data needs to be appended
:param p_Data: Data to be appended to the file
:return: Nothing
"""
with open(p_FilePath, 'a') as LFile:
LFile.write(p_Data + '\n')
def delete_contents_of_file(p_FilePath):
"""
Method to delete contents of a file
:param p_FilePath: File whose contents need to be deleted
:return: Nothing
"""
open(p_FilePath, 'w').close()
def convert_data_from_file_to_collection(p_FileName):
"""
Method to get data from a file into a set
:param p_FileName: Location of the file to read the contents from
:return: Set containing the entries in the file
"""
result = []
# open the file in read mode
with open(p_FileName, 'rt') as lfile:
# iterate over each line in the file and add it to the set
for line in lfile:
# replace the newline character in line
result.append(line.replace('\n', ''))
# return the set after adding all the links from the file
return result
def convert_data_from_collection_to_file(p_filename, p_data):
"""
Method to convert data from a set to file
:param p_filename: File in which the data from the set needs to be written
:param p_data: Dataset from which the data needs to be written to a file
:return: Nothing
"""
# open the file in write mode
with open(p_filename, "w") as lfile:
# iterate over each item in set and add it to file
for litem in p_data:
litem = litem.encode('utf-8')
lfile.write(str(litem) + "\n")
def get_domain_name_from_url(p_Url):
"""
Method to return domain name from url
:param p_Url: Url from which the domain name is to be retrieved
:return: Domain name from the url
"""
try:
lresult = urlparse(p_Url).netloc
except:
lresult = ''
try:
lresult = lresult.split('.')
lresult = lresult[-2] + '.' + lresult[-1]
except:
lresult = ''
print lresult
return lresult
def can_add_link(p_linkhref):
"""
Method to check whether a link can be crawled by the crawler or not
:param p_linkhref: href url from an anchor tag
:return: True if the link can be crawled else False
"""
if not is_string_valid(p_linkhref):
return False
# get the lowercase for href
llinkhref = p_linkhref.lower()
if ":" in llinkhref:
return False
if "#" in llinkhref:
return False
if "/wiki/" not in llinkhref:
return False
if (".jpeg" in llinkhref)or (".jpg" in llinkhref) or (".png" in llinkhref) \
or (".gif" in llinkhref) or (".svg" in llinkhref):
return False
#if "main_page" in llinkhref:
# return False
if "wikimediafoundation.org" in llinkhref:
return False
return True
def get_complete_url(p_domain, p_url):
"""
Method to return the complete url with domain name
:param p_domain: Domain name to be added to url
:param p_url: Url
:return: Url with domain name if it is not already there, else the same url
"""
lresult = p_url
if p_domain not in p_url:
lresult = p_domain + p_url
return lresult
def contains_keyword(p_keyword, p_anchortag):
"""
Method used to check whether the keyword occurs in the anchor tag text or href
:param p_keyword: Keyword to be searched for
:param p_anchortag: Anchor tag in which the keyword is to be searched
:return: Nothing
"""
if not is_string_valid(p_keyword):
return False
llinkhref = p_anchortag.get("href")
llinkstring = p_anchortag.string
p_keyword = p_keyword.lower()
if ( is_string_valid(llinkhref) and p_keyword not in llinkhref.lower() ) and \
(is_string_valid(llinkstring) and p_keyword not in llinkstring.lower()):
return False
return True |
e7a9d09ad3b6b59dba8fbc816f32d48659a1908a | emiliocarcanobringas/15.-Imprimir_texto_mas_valor_concatenandolos_python | /15.-Imprimir_texto_mas_valor_concatenandolos_python.py | 473 | 3.953125 | 4 | # Este programa muestra como concatenar una texto con un valor
print("Este programa muestra como concatenar una texto con un valor")
print("Para hacerlo cerramos comillas, separamos con una coma y colocamos la variable")
print("Antes de cerrar el paréntesis")
numero1 = 34.12
print("El valor del numero es: ", numero1)
print("La variable es del tipo: ")
print(type(numero1))
print("Este programa fue escrito por Emilio Carcaño Bringas")
# Este programa fue escrito por Emilio Carcaño Bringas |
9b206c69562b967ae955947990826b5861a68255 | franwatafaka/funciones_python | /ejemplos_clase/ejemplo_5.py | 2,452 | 4.4375 | 4 | # Funciones [Python]
# Ejemplos de clase
# Autor: Inove Coding School
# Version: 2.0
# Ejemplos de parámetros ocultos en funciones conocidas
def cantidad_letras(lista_palabras):
for palabra in lista_palabras:
cantidad_letras = len(palabra)
print('Cantidad de letras de {}: {}'.format(palabra, cantidad_letras))
def ordenar_palabras(lista_palabras, operador):
''' Ordenar palabras alfabeticamente
o por cantidad de letras de mayor a menor
'''
if operador == 1:
lista_palabras.sort(reverse=True)
elif operador == 2:
lista_palabras.sort(reverse=True, key=len)
# lista_palabras.sort(reverse=True, key=cantidad_letras)
else:
print('Operador ingresado', operador, 'incorrecto, ingrese 1 o 2')
print(lista_palabras)
def max_max(lista_palabras):
# Ejemplo de diferentes formas de utilizar max
# Buscamos la palabra alfabéticamente mayor
max_alfabeticamente = max(lista_palabras)
print('La palabra alfabéticamente más grande:', max_alfabeticamente)
# Buscamos la palabra con mayor cantidad de letras
# Para eso cambiamos el criterio de búsqueda "key"
# por búsqueda por cantidad de letras "len"
max_tamaño = max(lista_palabras, key=len)
print('La palabra más larga:', max_tamaño)
# Con count podemos contar cuantas veces
# aparece "te" en la lista de palabras
cantidad_max = lista_palabras.count('te')
print('La palabra "te" aparece {} veces'.format(cantidad_max))
# Buscamos la palabra que más se repite en la lista
# cambiando el criterio de búsqueda "key" por el función
# count que se aprovechó antes.
max_repeticiones = max(lista_palabras, key=lista_palabras.count)
print('La palabra con más repetición en la lista es "{}"'.format(max_repeticiones))
if __name__ == '__main__':
print("Bienvenidos a otra clase de Inove con Python")
lista_palabras = ['vida', 'te', 'inove', 'dia', 'te']
# Cuantas letras tiene cada palabra en la lista?
cantidad_letras(lista_palabras)
# Ordenar las palabras de mayor a menor por orden alfabético
ordenar_palabras(lista_palabras, 1)
# Ordenar las palabras de mayor a menor por cnatidad de letras
ordenar_palabras(lista_palabras, 2)
# Ingresar mal el operador
ordenar_palabras(lista_palabras, 56)
# Parámetros ocultos por defecto de la función max
max_max(lista_palabras)
|
2e71cea6007aedd41d0d4f297853f02b4ec28e48 | Shane-kolkoto/Unit_testing | /Unit_testing.py | 414 | 3.8125 | 4 | import unittest
from main import max_number
from main import descending_sort
class TestMaxNumbers(unittest.TestCase):
def test_max_numbers(self):
assert max_number([3, 5, 6, 9, 12, 78]) == 78, "The max number in [[3, 5, 6, 9, 12, 78]"
def test_descending_order_sorter(self):
assert descending_sort([10, 6, 5, 18]) == [18, 10, 6, 5], "The order in [10, 6, 5, 18] should be [18, 10, 6, 5]"
|
7a0e305ffc206484470efa1ea05cb3339810dbaf | markwilliams0/MWMass | /python_expts/eapprox.py | 416 | 3.859375 | 4 | def fact(x):
if x==0:
return 1
else:
return float(x*fact(x-1))
n=int(input('Enter a positive integer: '))
if n%100==11 or n%100==12 or n%100==13:
str='th'
elif n%10==1:
str='st'
elif n%10==2:
str='nd'
elif n%10==3:
str='rd'
else:
str='th'
est=0
for i in range(n+1):
est=est+(1/(fact(i)))
print 'The value of e, to a {}{} order approximation, is {}'.format(n,str,est) |
2d2b5427fcfc7e0fa204f6f03fdbba46018869a8 | MuslumErfidan/Binary_Tree | /BFS.py | 3,957 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.parent = None # yeni
self.data = data
def insert(self, data):
if self.data: # karılaştırma yaparak ekle
if data < self.data: # küçükse sola
if self.left is None: # sol boşsa sola ekle
self.left = Node(data)
self.left.parent = self # yeni
else:
self.left.insert(data) # sol boş değilse sol alt-ağaca ekle
elif data > self.data: # büyükse sağa
if self.right is None: # sağ boşsa sağa ekle
self.right = Node(data)
self.right.parent = self # yeni
else: # sağ boş değilse sağ alt-ağaca ekle
self.right.insert(data)
else:
self.data = data # ağacın ilk düşümü
# Ağacı yazdır
def PrintTree(self):
visited = [] #ziyaret edilen düğümleri tutacak bir dizi oluşturduk
if self:
visited.append(self) #diziyi ilk düğümle birlikte arttırdık
print(self.data, end='-') #ilk düğümün içeriğini yazdık
current = self #current adlı değişkene self i atadık ve replikasyon yapmış olduk
while current :
if current.left: #self in soldaki ilk düğümü iken:
print(current.left.data, end='-') #self in soldaki ilk düğümünün datasını yazdık
visited.append(current.left) #visited adlı dizimize soldaki ilk düğümü geçirdik
if current.right: #self in sağdaki ilk düğümü iken:
print(current.right.data, end='-') #self in sağdaki ilk düğümünün datasını yazdık
visited.append(current.right) #visited adlı dizimize soldaki ilk düğümü geçirdik
visited.pop(0) #.pop(0) ile visited adlı dizinin ilk elemanını patlattık(döngünün her seferinde kök düğümü yazmaması için)
if not visited: #tüm düğümler ziyaret edildiyse aşağıdaki break ile döngüyü kırdık
break
current = visited[0] #listenin ilk elemanı kök düğümden sonraki ilk düğüm oldu
def sizeTree(self):
if self.left and self.right:
return 1 + self.left.sizeTree() + self.right.sizeTree()
elif self.left:
return 1 + self.left.sizeTree()
elif self.right:
return 1 + self.right.sizeTree()
else:
return 1
def breadth(self):
if self.left and self.right:
l = self.left.breadh()
r = self.right.breadth()
return 1 + max(l,r)
elif self.left:
return 1 + self.left.breadth()
elif self.right:
return 1 + self.right.breadth()
else:
return 1
# Use the insert method to add nodes
root = Node(25)
root.insert(12)
root.insert(10)
root.insert(22)
root.insert(5)
root.insert(36)
root.insert(30)
root.insert(40)
root.insert(28)
root.insert(38)
root.insert(48)
root.PrintTree()
"""
# 25,36,20,10,5,22,40,48,38,30,22,12,28
root = Node(25)
root.insert(36)
root.insert(20)
root.insert(10)
root.insert(5)
root.insert(22)
root.insert(40)
root.insert(48)
root.insert(38)
root.insert(30)
root.insert(12)
root.insert(28)
print(root.sizeTree(),root.depth())
"""
|
cf717c597321786c758d22056fd1c90eb8d4b175 | lima-oscar/GTx-CS1301xIV-Computing-in-Python-IV-Objects-Algorithms | /Chapter 5.1_Objects/Burrito5.py | 1,764 | 4.46875 | 4 | #In this exercise, you won't edit any of your code from the
#Burrito class. Instead, you're just going to write a
#function to use instances of the Burrito class. You don't
#actually have to copy/paste your previous code here if you
#don't want to, although you'll need to if you want to write
#some test code at the bottom.
#
#Write a function called total_cost. total_cost should take
#as input a list of instances of Burrito, and return the
#total cost of all those burritos together as a float.
#
#Hint: Don't reinvent the wheel. Use the work that you've
#already done. The function can be written in only five
#lines, including the function declaration.
#
#Hint 2: The exercise here is to write a function, not a
#method. That means this function should *not* be part of
#the Burrito class.
#If you'd like to use the test code, paste your previous
#code here.
#Write your new function here.
def total_cost(burrito_list):
total_cost = 0
for burrito_n in burrito_list:
total_cost += burrito_n.get_cost()
return total_cost
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs. Note that these lines
#will ONLY work if you copy/paste your Burrito, Meat,
#Beans, and Rice classes in.
#
#If your function works correctly, this will originally
#print: 28.0
#burrito_1 = Burrito("tofu", True, "white", "black")
#burrito_2 = Burrito("steak", True, "white", "pinto", extra_meat = True)
#burrito_3 = Burrito("pork", True, "brown", "black", guacamole = True)
#burrito_4 = Burrito("chicken", True, "brown", "pinto", extra_meat = True, guacamole = True)
#burrito_list = [burrito_1, burrito_2, burrito_3, burrito_4]
#print(total_cost(burrito_list)) |
c1140b6e9f15fd3f62915a7434688354cb0fbb91 | kpwhri/pyscriven | /src/pyscriven/utils.py | 373 | 3.6875 | 4 | import random
import string
def make_safe_title(s):
from string import ascii_lowercase
return ''.join(x if x in ascii_lowercase + '_-0123456789' else
'-' if x == ' ' else '' for x in s.lower())
def generate_random_string(size=8, charset=string.ascii_uppercase + string.digits):
return ''.join(random.choice(charset) for _ in range(size))
|
0cb569bae9d8335f3ca86f036d2cafd3ba7c6ebf | rsd16/Solo-Pong | /Solo Pong.py | 2,123 | 3.578125 | 4 | import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('pong')
rect_x = 400
rect_y = 580
rect_change_x = 0
rect_change_y = 0
ball_x = 50
ball_y = 50
ball_change_x = 5
ball_change_y = 5
score = 0
def drawrect(screen,x,y):
if x <= 0:
x = 0
if x >= 699:
x = 699
pygame.draw.rect(screen,RED,[x, y, 100, 20])
done = False
clock=pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
rect_change_x = -6
elif event.key == pygame.K_RIGHT:
rect_change_x = 6
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
rect_change_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
rect_change_y = 0
screen.fill(BLACK)
rect_x += rect_change_x
rect_y += rect_change_y
ball_x += ball_change_x
ball_y += ball_change_y
if ball_x < 0:
ball_x = 0
ball_change_x = ball_change_x * -1
elif ball_x > 785:
ball_x = 785
ball_change_x = ball_change_x * -1
elif ball_y < 0:
ball_y = 0
ball_change_y = ball_change_y * -1
elif ball_x > rect_x and ball_x < rect_x + 100 and ball_y == 565:
ball_change_y = ball_change_y * -1
score = score + 1
elif ball_y > 600:
ball_change_y = ball_change_y * -1
score = 0
pygame.draw.rect(screen,WHITE,[ball_x, ball_y, 15, 15])
drawrect(screen,rect_x,rect_y)
font= pygame.font.SysFont('Calibri', 15, False, False)
text = font.render('Score = ' + str(score), True, WHITE)
screen.blit(text,[600,100])
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
f954e13fd82932e87e2e482007e828b3effaaf68 | douglasmg7/data_science | /matplotlib/exercise_2.py | 244 | 3.609375 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 100)
y = x*2
z = x**2
plt.subplot(1, 2, 1)
plt.plot(x, y, 'b', lw=4)
plt.subplot(1, 2, 2,)
plt.plot(x, z, 'r', lw=3, ls='--')
plt.show()
plt.show()
|
5ab600b4f8b67082d934ec0e244fb6f7570be53d | douglasmg7/data_science | /matplotlib/matplotlib_limits.py | 384 | 3.5625 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
# Plot x, y using function
x = np.linspace(0, 5, 11)
y = x ** 2
# Classes mode instead function mode
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, .8, .8]) # 0 - 1 (0 to 100% of window) x, y, width, height
ax.plot(x, y, color='purple', lw=2, ls='--')
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
plt.show()
|
fcda1b2cdb587bd28dfe91766a2a9d2662a74bbe | annp89/Weekly-Noodler | /folding_subsequence.py | 1,407 | 3.5625 | 4 | input_sequence = [1, 2, 2, 5, 3, 4]
output_sequence = []
sequence_length = len(input_sequence) - 1
check = False
for count, item in enumerate(input_sequence):
if count == 0:
output_sequence.append(item)
elif not check:
if input_sequence[count] < output_sequence[-1]:
if count != sequence_length and input_sequence[count+1] <= input_sequence[count]:
continue
check = 'CHECK_GREATER'
output_sequence.append(item)
elif input_sequence[count] > output_sequence[-1]:
if count != sequence_length and input_sequence[count+1] >= input_sequence[count]:
continue
check = 'CHECK_LESSER'
output_sequence.append(item)
else:
continue
else:
if check == 'CHECK_GREATER' and input_sequence[count] > output_sequence[-1]:
if count != sequence_length and input_sequence[count+1] >= input_sequence[count]:
continue
check = 'CHECK_LESSER'
output_sequence.append(item)
elif check == 'CHECK_LESSER' and input_sequence[count] < output_sequence[-1]:
if count != sequence_length and input_sequence[count+1] <= input_sequence[count]:
continue
check = 'CHECK_GREATER'
output_sequence.append(item)
else:
continue
print output_sequence
|
449dfbec39900b6e6118ef3fe5cdf7c19f8e8031 | panhboth111/AI-CODES | /matplotlib/02.py | 286 | 4.09375 | 4 | #Question: Write a Python program to draw a line using given axis values with suitable label in the x axis , y axis and a title.
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,1]
plt.plot(x, y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Sample graph!')
plt.show()
|
09c67cc5a452e5af7021221d589c49e17f37d7b6 | panhboth111/AI-CODES | /pandas/4.py | 394 | 4.34375 | 4 | #Question: Write a Pandas program to compare the elements of the two Pandas Series.
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)
# |
2bf7cbe5bcecf17ebaf46be2f5420ebbde0163b0 | panhboth111/AI-CODES | /pandas/16.py | 530 | 4.28125 | 4 | """Question: Write a Pandas program to get the items of a given series not present in another given series.
Sample Output:
Original Series:
sr1:
0 1
1 2
2 3
3 4
4 5
dtype: int64
sr2:
0 2
1 4
2 6
3 8
4 10
dtype: int64
Items of sr1 not present in sr2:
0 1
2 3
4 5
dtype: int64 """
import pandas as pd
sr1 = pd.Series([1, 7, 3, 4, 5])
sr2 = pd.Series([2, 4, 6, 8, 10])
print("Original Series:")
print("sr1:")
print(sr1)
print("sr2:")
print(sr2)
print("\nItems of sr1 not present in sr2:")
result = sr1[~sr1.isin(sr2)]
print(result) |
290a5ce82e4fbface4e8ad3c975daee5a324c15a | panhboth111/AI-CODES | /numpy/15.py | 344 | 4.03125 | 4 | <<<<<<< HEAD
#Question: Write a NumPy program to create an array of all the even integers from 30 to 70.
import numpy as np
array = np.arange(30,70,2)
print(array)
=======
#Question: Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21.
import numpy as np
m= np.arange(10,22).reshape((3, 4))
print(m)
#
>>>>>>> borey
|
48e57fc36b12184ca0475da829b1f5f626a2afcf | Claudiu1995/CN_3 | /equal_matrix.py | 947 | 3.875 | 4 | from math import *
epsilon = pow(10, -8)
def equals(matrix_A: tuple, matrix_B: tuple) -> bool:
diagonal_of_A = matrix_A[0]
vector_of_A = matrix_A[1]
diagonal_of_B = matrix_B[0]
vector_of_B = matrix_B[1]
if abs(len(diagonal_of_A) - len(diagonal_of_B)) >= epsilon:
print("diag dim", len(diagonal_of_A), len(diagonal_of_B))
return False
for i in range(0, len(diagonal_of_A)):
if abs(diagonal_of_A[i] - diagonal_of_B[i]) >= epsilon:
print("diag", diagonal_of_A[i], diagonal_of_B[i])
return False
if abs(len(vector_of_A) - len(vector_of_B)) >= epsilon:
print("vect dim", len(vector_of_A), len(vector_of_B))
return False
for i in range(0, len(vector_of_A)):
val_A = vector_of_A[i][0]
val_B = vector_of_B[i][0]
if abs(val_A - val_B) >= epsilon:
print("val", val_A, val_B)
return False
return True
|
379df23246686c37bc64e45d81a402e234379029 | Mr-Perfection/python-postgresql | /practice/python/division.py | 482 | 3.75 | 4 | def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Divisor cannot be 0")
return dividend/divisor
try:
# average = divide(20, 0)
average = divide(20, 1)
except ZeroDivisionError as e:
print(e)
print('error')
else:
print('success')
print(average)
finally:
print('finally!')
class NoNegativeValuesError(ValueError):
pass
test_value = -199
if test_value < 0:
raise NoNegativeValuesError("no negative ")
|
95de3442c81369f3de708734c3742f6ab4b8ffdf | manishjain79/regular_expression | /17_regex_sub.py | 2,243 | 3.953125 | 4 | import re
# re.sub
# re.sub finds pattern in through out the file/multiline string and substitute it with desired string.
string = '''Manish works with IBM Singapore Pte. Ltd. and Kiran works with Wipro International.'''
result = re.sub('(Manish|Kiran)', r'\1 Jain', string)
print(result)
# output is: Manish Jain works with IBM Singapore Pte. Ltd. and Kiran Jain works with Wipro International.
# Look at the desired string pattern, I started it with r'' as raw string. It did not work without r in front.
string = '&1234 ^Manish'
result = re.sub("(\W)(?P<number>\d+) (\W)(?P<word>\w+)", r"\g<word> \g<number>", string)
print(result)
# output is: Manish 1234
# Few examples.
# input = 'abcdefghijkl'
# result = re.sub('abc', '', input) # Delete pattern abc
# result = re.sub('abc', 'def', input) # Replace pattern abc -> def
# result = re.sub(r'\s+', ' ', input) # Eliminate duplicate whitespaces
# result = re.sub('abc(def)ghi', r'\1', input) # Replace a string with a part of itself
# Note: Take care to always prefix patterns containing \ escapes with raw strings (by adding an r in front of the
# string). Otherwise the \ is used as an escape sequence and the regex won't work.
#
#
# Lamdda Expressions
square = lambda x: x**2
print(square) # <function <lambda> at 0x000001E158B4AA60>
print(square(3))
# output is: 9
# lambda functions return a function of x the value of the expression written at the right side after :
x = lambda x: x
print(x(3))
# output is: 3
string = 'Devang has 3 cats'
result = re.sub('(\d+)', lambda x: (x.group(0)), string)
print(result)
# output is: 3 which was return value of f(x).
string = 'Devang has 3 cats'
result = re.sub('(\d+)', lambda x: str(square(int(x.group(0)))), string)
print(result)
# output is:
# Devang has 9 cats
# step-1: lambda x: x.group(0) x is the match object.
# step-2: turn the result into int, because we are running lambda expression on an integer.
# step-3: use square function
# step-4: turn back to string because in re.sub we are dealing with string here.
#
# Another example:
string = 'eat sleep laugh study'
result = re.sub('\w+', lambda x: x.group(0) + 'ing', string)
print(result)
# output is: eating sleeping laughing studying
|
337f69b86893036694a6603630f86ea38c39c587 | manishjain79/regular_expression | /05_regex_CharacterSet_1.py | 2,365 | 3.890625 | 4 | import re
# We will move from bigger character set metacharacter to more granular one.
#
# [.] = [a-z][A-Z][0-9] & any other symbol - [*%$#):;], except \n.
# [\w] = [a-z][A-Z][0-9][_]
# [\W] = opposite of \w. Represents anything other than: [a-z][A-Z][0-9][_]
# So, we can say
# [.] & \n == [\w] & [\W]
#
#
# '.' Matches any character except '\n'. Let's see this.
match_object = re.search('.', 'abcd')
print(match_object)
# output is: <re.Match object; span=(0, 1), match='a'>
match_object = re.search('.', '\nbcd')
print(match_object)
# output is: None. Because, it could not hit newline character.
match_object = re.search('.', '^bcd')
print(match_object)
# output is: <re.Match object; span=(0, 1), match='^'>
match_object = re.search('.', '*bcd')
print(match_object)
# output is: <re.Match object; span=(0, 1), match='*'>
match_object = re.search('.', ' bcd')
print(match_object)
# output is: <re.Match object; span=(0, 1), match=' '>. It matched space.
# [.] = [a-zA-Z0-9] & any other symbol, except \n.
# with match() and search() the output remains same.
# But if I use, findall(), it will find all instances of 'any-character'
match_object = re.findall('.', ' bcd')
print(match_object)
# output is: [' ', 'b', 'c', 'd']
# '\w' Matches alphanumeric characters only and underscore. It doesn't match any other character.
# ['\w'] = [a-zA-Z0-9_]
match_object = re.match('\w', 'abcd')
print(match_object)
# output is: <re.Match object; span=(0, 1), match='a'>
match_object = re.match('\w', '\nbcd')
# print(match_object)
# output is: None. Because, it could not hit newline character. But if I would apply search() method instead
# it would have skipped all miss (in this case \n) and would have had a hit on b.
# with search() output is: <re.Match object; span=(1, 2), match='b'>
match_object = re.match('\w', '^bcd')
print(match_object)
# output is: None
match_object = re.match('\w', '*bcd')
# print(match_object)
# output is: None
# match_object = re.match('\w', ' bcd')
# print(match_object)
# output is: None
match_object = re.findall('\w', 'ab cd&87*sda%3#23')
# print(match_object)
# output is: ['a', 'b', 'c', 'd', '8', '7', 's', 'd', 'a', '3', '2', '3']
match_object = re.findall('\w\w', 'ab cd&87*sda%3#23')
# print(match_object)
# output is: ['ab', 'cd', '87', 'sd', '23']
print(match_object)
# output is: ['b ', 'd&', '7*', 'a%', '3#']
|
e133ba7d9f305a476985d6d2659aefb7b91ddb51 | MariinoS/projectEuler | /problem1.py | 571 | 4.125 | 4 | # Project Euler: Problem 1 Source Code. By MariinoS. 5th Feb 2016.
"""
# task: If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# My Solution:
"""
list = range(1000)
def sum_of_multiples(input):
total = 0
for i in input:
if i % 3 == 0 or i % 5 == 0:
total = total + i
return total
print sum_of_multiples(list)
"""
# The script finishes in O.O37s.
# The answer = 233168
"""
|
02bc2eb8476f2dc28cf62865c08741b2087e8c94 | oliverralbertini/euler | /003/solution.py | 560 | 3.953125 | 4 | """Problem 3: Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"""
import sys
import math as m
sys.path.append('../modules')
from isprime import is_prime
from prime_factorization import prime_factorization
"""find out the largest prime factor of big_int"""
big_int = 600851475143
#big_int = 13195
def main():
"""in case big_int is prime"""
if is_prime(big_int) == True:
return big_int
return prime_factorization(big_int)
primes = main()
print primes[-1]
|
e308b5863276672ef888b77fb5bfcf8760c7dc42 | enzorossetto/uri-online-judge-problems | /python/1044.py | 181 | 3.828125 | 4 | num= input().split()
num[0]= int(num[0])
num[1]= int(num[1])
num.sort()
if((num[0] > 0) and (num[1]%num[0] == 0)):
print("Sao Multiplos")
else:
print("Nao sao Multiplos") |
5f92038718ec03fd850a2e02b4a925965c453e2b | enzorossetto/uri-online-judge-problems | /python/1064.py | 303 | 3.6875 | 4 | numeros = [float(input()) for i in range(6)]
somaPositivos = 0
quantiaPositivos = 0
for i in range (6):
if(numeros[i] > 0):
somaPositivos = somaPositivos + numeros[i]
quantiaPositivos += 1
print(quantiaPositivos, "valores positivos")
print("%.1f" %(somaPositivos/quantiaPositivos)) |
e7a2979469aadfd3022bc1c34ece80e951281a14 | enzorossetto/uri-online-judge-problems | /python/1065.py | 151 | 3.671875 | 4 | numeros = [int(input()) for i in range(5)]
pares = 0
for i in range(5):
if(numeros[i] % 2 == 0):
pares += 1
print(pares, "valores pares") |
5a16637a3b4e7687b6e270ebd40821c32dbb0672 | taimurshaikh/Record | /record.py | 1,992 | 3.59375 | 4 | import datetime
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
class Record:
def __init__(self, forename, surname, dob, gender, isCSStudent):
self.__forename = forename
self.__surname = surname
self.__dob = dob
self.__gender = gender
self.__CS_student = isCSStudent
self.time_of_creation = datetime.datetime.now()
def Invalid(self):
print("Invalid Data Type")
def getFName(self):
return self.__forename
def setFName(self, value):
if type(value) == str:
self.forename = value
return
self.Invalid()
def getLName(self):
return self.__surname
def setLName(self, value):
if type(value) == str:
self.__surname = value
return
self.Invalid()
def getDOB(self):
return self.__dob
def getAge(self):
age = datetime.date.today().year - int(self.__dob[6:])
return age
def setAge(self, value):
if type(value) == int:
self.__age = value
return
self.Invalid()
def getGender(self):
return self.__gender
def setGender(self, value):
if value.lower() == "m" or value.lower() == "f" or value.lower() == "male" or value.lower() == "female":
self.__gender = value.title()
return
self.Invalid()
def getCSStudent(self):
return self.__CS_student
def setCSStudent(self, value):
if type(value) == bool:
self.__CS_student = value
return
self.Invalid()
def created(self):
return self.time_of_creation
def day_born(self):
unit_date = int(self.__dob[:2]) if self.__dob[0] != "0" else int(self.__dob[1])
date = datetime.datetime(int(self.__dob[6:]), int(self.__dob[3:5]), unit_date)
return days[date.weekday()]
me = Record("Taimur", "Shaikh", "16/01/2004", "M", True)
|
fc613bf47803961e25733eb9eb3a4f4fb25a82cc | datascience-bitacademy/python-basics | /03/03.object_id.py | 1,031 | 3.65625 | 4 | # id 함수 : 실제 객체의 주소를 반환
i1 = 10
i2 = 20
print(hex(id(i1)), hex(id(i2)))
i1 = 1234567890
i2 = 1234567890
print(hex(id(i1)), hex(id(i2)))
i1 = 11
i2 = 10 + 1
print(hex(id(i1)), hex(id(i2)))
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(hex(id(l1)), hex(id(l2)))
s1 = 'hello'
s2 = 'hello'
print(hex(id(s1)), hex(id(s2)))
# is (동일 레퍼런스 비교)
# 가변 객체는 is(동일성)와 ==(동질성)는 다른 결과다. (list, set, dict)
# 불변 객체는 is(동일성)와 ==(동질성)는 같은 결과다. (나머지)
print(i1 is i2)
print(l1 is l2)
print(s1 is s2)
# ?
t1 = (1, 2, 3)
t2 = (1, 2, 3)
print(t1 is t2)
# 형변환 함수는 불변 객체라고 하더라도 새로운 객체를 만든다. (바로 대입하는 = 와는 다르게 작동한다)
r = range(1, 4)
t3 = tuple(r)
print(t1 == t3)
print(t1 is t3)
# slicing 경우에도 불변 객체라고 하더라도 새로운 객체를 만든다. (바로 대입하는 = 와는 다르게 작동한다)
t4 = (0, 1, 2, 3)[1:]
print(t1 is t4)
|
af88a413fbbf74c6d68c4b3fd75577f2dc8bfebb | datascience-bitacademy/python-basics | /04/03.while.py | 486 | 3.515625 | 4 | # 1 ~ 10 합을 구하기
s, count = 0, 1
while count < 11:
s += count
count += 1
print(s)
# break
i = 0
while i < 10:
if i > 5:
break
print(i, end=' ')
i += 1
print("\n-------------------------------")
# continue
i = 0
while i < 10:
if i <= 5:
i += 1
continue
print(i, end=' ')
i += 1
print('\n-------------------------------')
# 무한루프
i = 0
while True:
print(i, end=' ')
if i > 5:
break
i += 1
|
dcb967c309149c9c849e515a8c05e3d4c8db2bbb | datascience-bitacademy/python-basics | /02/14.unpacking.py | 433 | 3.765625 | 4 | # packing은 tuple로만 가능하다.
t = 10, 20, 30, 'python'
print(t, type(t))
# unpacking
a, b, c, d = t
print(a, b, c, d)
# 오류: 패킹되어 있는 객체가 더 많은 경우
# x, y, z = t
# 오류: 패킹되어 있는 객체가 더 적은 경우
# l, m, n, o, p = t
# unpacking 확장
t2 = (1, 2, 3, 4, 5)
a, *b = t2
print(a, b)
*a, b = t2
print(a, b)
a, b, *c = t2
print(a, b, c)
a, *b, c = t2
print(a, b, c)
|
4ede0c5bea3a9e14b82675234a3f43f5512d4a8f | datascience-bitacademy/python-basics | /03/04.object_copy.py | 766 | 4.28125 | 4 | # 레퍼런스 복사
import copy
a = 1
b = a
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = x
print(x)
print(y)
print(x is y)
# 얕은(swallow) 복사
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = copy.copy(x)
print(x)
print(y)
print(x is y)
print(x[0] is y[0])
# 깊은(deep) 복사
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = copy.deepcopy(x)
print(x)
print(y)
print(x is y)
print(x[0] is y[0])
# 깊은복사가 복합객체만을 생성하기 때문에
# 복합객체가 한개만 있는 경우에는
# 얕은복사와 깊은복사는 별 차이가 없다.
a = ['hello', 'world']
b = copy.copy(a)
print(a)
print(b)
print(a is b)
print(a[0] is b[0])
a = ['hello', 'world']
b = copy.deepcopy(a)
print(a)
print(b)
print(a is b)
print(a[0] is b[0]) |
0a97cf80ae62f3d30f7f1cf607e965d04f9c868d | datascience-bitacademy/python-basics | /02/18.zip.py | 457 | 3.859375 | 4 | # zip() 사용 예
# 여러 순차형을 하나로 묶어준다
seq1 = ['foo', 'bar', 'baz']
seq2 = ['one', 'two', 'three', 'four']
z = zip(seq1, seq2)
print(z, type(z))
for t in z:
print(t)
# zip 객체는 한번 순회하면 내용이 비어버린다
# 제네레이터이므로 실제 내부 데이터는 담고 있지 않다
z = zip(seq1, seq2)
for index, t in enumerate(z):
print(index, t)
z = zip(seq1, seq2)
for a, b in z:
print(a, b)
|
bb673dbbd1f50eec1d07a418d6fe01920e216747 | datascience-bitacademy/python-basics | /02/19.comprehension.py | 1,481 | 3.703125 | 4 | numbers = [1, 2, 3, 4, 5, 6, 7, 8]
results = []
# 리스트 컴프리헨션
# [ 값 연산식 for 객체 in 순차형 if 조건 ]
# numbers 순차형의 모든 내부 요소를 제곱
for n in numbers:
result = n * n
results.append(result)
print(results)
results = [num*num for num in numbers]
print(results)
# 문자열 리스트에서 길이가 2이하인 문자열만 새로운 리스트에 담기
strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
results = []
for s in strings:
if len(s) <= 2:
results.append(s)
print(results)
results = [s for s in strings if len(s) <= 2]
print(results)
# 1~100 사이의 수 중에 짝수 리스트 만들기
results = [n for n in range(1, 101) if n % 2 == 0]
print(results)
# 문자열 리스트에서 각각의 문자열의 길이를 담은 리스트 만들기
results = [len(s) for s in strings]
print(results)
# 369게임: 1~100 사이에 3, 6, 9가 있는 수 리스트 만들기
# [3, 6, 9, 13, 16, 19, 23, 26, 29, 30, 31, 33, 36, ...... ]
results = [number for number in range(1, 101)
if str(number).count('3') > 0 or
str(number).count('6') > 0 or
str(number).count('9') > 0]
print(results)
# set comprehension
# Syntax : { 값 연산식 for 객체 in 순차형 if 조건 }
s = {s for s in strings if len(s) <= 2}
print(s)
# dict comprehension
# Syntax : { 키연산식: 값연산삭 for 객체 in 순차형 if 조건 }
d = {s: len(s) for s in strings}
print(d)
|
6a5fe6de000f85d985129f3df785a73f97f41de3 | NenadPantelic/Hackerearth-DSA-practise-track | /Data structures/Queues/micro_and_queue.py | 636 | 3.609375 | 4 | from collections import deque
class QueueWrapper:
def __init__(self):
self._queue = deque()
self._size = 0
def enqueue(self, elem):
self._queue.append(elem)
self._size += 1
print(self._size)
def dequeue(self):
x = -1
if self._size != 0:
x = self._queue.popleft()
self._size -= 1
print(x, end=" ")
print(self._size)
n = int(input())
q = QueueWrapper()
for i in range(n):
line = input().split(' ')
if line[0] == 'E':
q.enqueue(line[1])
else:
q.dequeue()
'''
5
E 2
D
D
E 3
D
'''
|
bb0d351a166c1cfd118979578e03067c82a1ab52 | reidtc82/8puzzle | /ForHumanstoPlay.py | 3,686 | 4.03125 | 4 | import sys
if sys.version_info[0] == 3:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
else:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
# This is not really part of the assignment
# I meant to incorporate the search algorithms to let the computer solve the problem
# At least it helped me visualize the problem
# repeat - this part does not support the search algorithms, but if youre bored play away
from PuzzleBoard import PuzzleBoard
from State import State
import numpy as np
class Main:
# just a main class
def __init__(self, master):
# constructor
self.canvas_width = 300
self.canvas_height = 300
self.rectangles = [0] *8
self.texts = [0] *8
self.board = PuzzleBoard()
# setting up the tkinter GUI
self.master = master
master.title("8 Puzzle")
master.geometry('640x480')
self.label = Label(master, text="This is 8 Puzzle")
self.label.pack()
self.score = Label(master, text=self.board.getScore())
self.score.pack()
self.canvasSpace = Canvas(master, width=self.canvas_width, height=self.canvas_height)
self.canvasSpace.pack()
self.canvasSpace.create_rectangle(0, 0, 300, 300, fill="#696969")
self.drawBoard(self.canvasSpace)
self.resetPuzzle_button = Button(master, text="Reset Puzzle", command=self.newPuzzle)
self.resetPuzzle_button.pack()
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.pack()
self.up_button = Button(master, text="Up", command=self.moveUp)
self.up_button.pack()
self.down_button = Button(master, text="Down", command=self.moveDown)
self.down_button.pack()
self.left_button = Button(master, text="Left", command=self.moveLeft)
self.left_button.pack()
self.right_button = Button(master, text="Right", command=self.moveRight)
self.right_button.pack()
# processing button clicks
def moveRight(self):
self.board.moveRight()
self.score.config(text=self.board.getScore())
self.drawBoard(self.canvasSpace)
def moveLeft(self):
self.board.moveLeft()
self.score.config(text=self.board.getScore())
self.drawBoard(self.canvasSpace)
def moveDown(self):
self.board.moveDown()
self.score.config(text=self.board.getScore())
self.drawBoard(self.canvasSpace)
def moveUp(self):
self.board.moveUp()
self.score.config(text=self.board.getScore())
self.drawBoard(self.canvasSpace)
def newPuzzle(self):
print('hello')
self.board.resetPuzzle()
self.board.resetScore()
self.score.config(text=self.board.getScore())
self.drawBoard(self.canvasSpace)
# drawing the board after every click
def drawBoard(self, canvas):
for rec in self.rectangles:
canvas.delete(rec)
for txt in self.texts:
canvas.delete(txt)
currentState = self.board.getState()
for i in range(3):
for j in range(3):
if currentState[i][j] != 0:
origin_X = 100*i
origin_Y = 100*j
final_X = origin_X+100
final_Y = origin_Y+100
self.rectangles.append(canvas.create_rectangle(origin_X, origin_Y, final_X, final_Y, fill="#DCDCDC"))
self.texts.append(canvas.create_text(origin_X+50,origin_Y+50,text=currentState[i][j]))
root = Tk()
mainPanel = Main(root)
root.mainloop()
|
8faa3c41a488d834d973c24546eab34f8c8f90f0 | Ayaan-Imran/Checklist | /checklist.py | 1,408 | 4.09375 | 4 | import sqlite3
# Create database and table
connection = sqlite3.connect("lists.db")
c = connection.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS list (
task text
)
""")
connection.commit()
# Takes mode
mode = input("Do you want to make a new task (1) or finish a task (2) or view your tasks (3): ")
if mode == "1":
mode = input("Enter the task: ")
c.execute("INSERT INTO list VALUES ('{}')".format(mode))
connection.commit()
c.execute("SELECT rowid, * FROM list WHERE task='{}'".format(mode))
lst = c.fetchall()
connection.commit()
print("Task is added. The number for your task is: {}.\nNote: The number value has changed for each task".format(lst[0][0]))
elif mode == "2":
mode = input("Please choose a way to delete. Through number(1) or through the task(2): ")
if mode == "1":
mode = input("Enter the number of the task: ")
c.execute("DELETE FROM list WHERE rowid={}".format(int(mode)))
connection.commit()
print("Phew! The task is over!")
else:
mode = input("Enter the task: ")
c.execute("DELETE FROM list WHERE task='{}'".format(mode))
connection.commit()
print("Phew! The task is over!")
else:
c.execute("SELECT rowid, * FROM list")
lst = c.fetchall()
connection.commit()
for i in lst:
print("Number: {} Task: {}".format(i[0], i[1]))
connection.close() |
529908b3397f08c8a5a6b1ba864c6bf1cef22add | VedranSagodic/SmartninjaHomework | /python1/Loops/main.py | 421 | 3.78125 | 4 | #x = 5
#y = 2
#print(x + y)
#print("Hello World")
#userName = input("Your name")
#print("Hello" + userName)
#favColor = input("Your favorite color")
#print("Favorite color" + favColor)
broj_a = int(input("Unesi prvi broj:"))
broj_b = int(input("Unesi drugi broj:"))
rezultat= broj_a + broj_b
print(rezultat)
if rezultat > 10:
print("Rezultat je veci od 10")
else:
print("Rezultat je jednak ili manji od 10") |
787a20a9bb460a92944f38bfd011fc79eb726176 | VedranSagodic/SmartninjaHomework | /python1/lists.py | 322 | 3.78125 | 4 | #liste
lista_brojeva = [1, 99, 24, 46, 5]
print(lista_brojeva[3])
print()
lista_brojeva.reverse()
print(lista_brojeva)
print()
lista_brojeva.append(100)
print(lista_brojeva)
print()
lista_brojeva.sort()
print(lista_brojeva)
print()
auti = ["tesla", "audi", "bmw"]
print(auti)
for item in auti:
print(item)
|
327accad9ef09bbcfa6c58d16cd49572d3982c02 | rsdavies/advent-of-code | /day_3/day_3.py | 2,498 | 4.03125 | 4 | from typing import List
from utils.read_input import read_wires
def get_positions(wire):
"""
Gives the x, y position of a wire after each instruction
:param wire: the wire instructions
:return: x, y. Assuming wire starts at 0, 0
"""
x = 0
y = 0
positions = [(0, 0)]
for instruction in wire:
direction = instruction[0]
dist = int(instruction[1:])
if direction == "R":
for pos in range(1, dist+1):
positions.append((x + pos, y))
x += dist
elif direction == "L":
for pos in range(1, dist+1):
positions.append((x - pos, y))
x -= dist
elif direction == "U":
for pos in range(1, dist + 1):
positions.append((x, y + pos))
y += dist
elif direction == "D":
for pos in range(1, dist + 1):
positions.append((x, y - pos))
y -= dist
else:
raise ValueError("Direction not recognised")
return positions
def manhattan_distance(x: int, y: int) -> int:
return abs(x) + abs(y)
def distance(wires) -> int:
"""
Takes the wires and finds the manhattan distance of the closest intersection to (0,0)
:param wires: a list of lists of wires
:return: the Manhattan distance to the central port of the closest cross
"""
wire_0_pos = get_positions(wires[0])
wire_1_pos = get_positions(wires[1])
# find intersections
intersections = list(set(wire_0_pos).intersection(set(wire_1_pos)))
# ignore the 0,0 intersect
intersections.remove((0, 0))
m_distances = [manhattan_distance(x, y) for x, y in intersections]
return min(m_distances)
def steps(wires) -> int:
"""
Takes the wires and finds the mimimum number of steps between the origin and an intersection
:param wires: a list of lists of wires
:return: the minimum number of steps to a cross
"""
wire_0_pos = get_positions(wires[0])
wire_1_pos = get_positions(wires[1])
# find intersections
intersections = list(set(wire_0_pos).intersection(set(wire_1_pos)))
intersections.remove((0, 0))
steps = [wire_0_pos.index(intersection) + wire_1_pos.index(intersection) for intersection in intersections]
return min(steps)
if __name__ == "__main__":
wires = read_wires("/Users/rhiannonsteele/PycharmProjects/advent-of-code/day_3/input.txt")
print(distance(wires))
print(steps(wires))
|
299ddbbc61487dd6c38e0a1c4cba8061fc683695 | rsdavies/advent-of-code | /day_2/day_2.py | 2,149 | 3.984375 | 4 | class Computer:
def __init__(self, program):
self.program = program
self._instruction_pointer = 0
def add(self):
parameter_1 = self.program[self._instruction_pointer + 1]
parameter_2 = self.program[self._instruction_pointer + 2]
parameter_3 = self.program[self._instruction_pointer + 3]
self.program[parameter_3] = self.program[parameter_1] + self.program[parameter_2]
self._instruction_pointer += 4
def multiply(self):
parameter_1 = self.program[self._instruction_pointer + 1]
parameter_2 = self.program[self._instruction_pointer + 2]
parameter_3 = self.program[self._instruction_pointer + 3]
self.program[parameter_3] = self.program[parameter_1] * self.program[parameter_2]
self._instruction_pointer += 4
def run(self):
"""
Runs the program
updates program
"""
opcode = self.program[self._instruction_pointer]
while opcode != 99:
if opcode == 1:
self.add()
opcode = self.program[self._instruction_pointer]
elif opcode == 2:
self.multiply()
opcode = self.program[self._instruction_pointer]
@staticmethod
def load(file_path: str):
"""
loads an intcode program
:param file_path: The full path to the input file containing the program
:return: the program to work on as a list of ints
"""
f = open(file_path, 'r')
raw = f.read()
program = raw.split(',')
program = [int(item) for item in program]
return Computer(program)
if __name__ == "__main__":
for noun in range(0, 100):
for verb in range(0, 100):
c = Computer.load("/Users/rhiannonsteele/PycharmProjects/advent-of-code/day_2/input.txt")
c.program[1] = noun
c.program[2] = verb
c.run()
if c.program[0] == 19690720:
print("noun = {}, verb = {}".format(noun, verb))
print("100 * noun + verb = {}".format(100 * noun + verb))
break
|
9816db2f8a4bc992ca21113834898bcd879136a8 | Irlyue/DL-AI | /Concepts/receptive-field/calc_receptive_field.py | 2,731 | 3.765625 | 4 | """
Please refer to blog
https://medium.com/mlreview/a-guide-to-receptive-field-arithmetic-for-convolutional-neural-networks-e0f514068807
for detailed information.
"""
import math
from collections import namedtuple
class Kernel(namedtuple('Kernel', 'k s p name')):
def __repr__(self):
return '{}(kernel size={:<2}, stride={}, padding={}, name={})'.format(self.__class__.__name__, *self)
class LayerInfo(namedtuple('LayerInfo', 'n j r start')):
"""
Information about the output of one layer, including the spatial dimension `n`, jump `j`, receptive field `r` and
the starting position of the upper left feature `start`. The "jump" is actually the stride distance in the input
image and it's usually the power of 2, say 2, 4, 8, etc.
Supposed the output tensor of this layer is X with shape(batch_size, height, width, n_channels), then the upper
left feature or the first feature as mentioned in the blog is X[:, 0, 0, :]. The starting position of one specific
feature value is the center location of the receptive field.
The starting position may or may not move, depending on the padding strategy and the kernel size. Take VGG for
example, the starting position moves due to the pooling layers and fc layers. Yet in ResNet, the starting
position remains unchanged.
"""
def __repr__(self):
return '{}(size={:<3}, jump={:<3}, receptive field={:<3}, start={:<5})'.format(self.__class__.__name__, *self)
class Layer:
def __init__(self, info=None, kernel=None):
self.info = info
self.kernel = kernel
def __repr__(self):
return '{} {}'.format(self.info, 'Input layer' if self.kernel is None else self.kernel)
class Net:
def __init__(self, kernels, name='Net'):
self.name = name
self.kernels = kernels
self.layers = []
def display_network(self, input_layer=None):
input_layer = input_layer or Layer(info=LayerInfo(224, 1, 1, 0.5))
layers = [input_layer]
for kernel in self.kernels:
layer_info = Net.out_from_in(kernel, layers[-1].info)
layers.append(Layer(layer_info, kernel))
self.layers = layers
print(self)
def __len__(self):
return len(self.layers)
def __repr__(self):
fmt = '{}\n' * len(self)
return '{}{}{}\n'.format('*'*10, self.name, '*'*10) + fmt.format(*self.layers)
@staticmethod
def out_from_in(kernel, layer):
n = math.floor((layer.n + 2*kernel.p - kernel.k) / kernel.s) + 1
j = layer.j * kernel.s
r = layer.r + (kernel.k - 1) * layer.j
start = layer.start + ((kernel.k - 1)/2 - kernel.p) * layer.j
return LayerInfo(n, j, r, start)
|
2bc939ea849abf9eae5df3bcb2c582774fe368dd | suazz/TEXT-ADVENTURE | /first_Text_Adventure.py | 7,426 | 3.875 | 4 | from sys import exit
print("""
===========Text Adventure ============
| |
| .---------. |
| |.-------.| |
| ||>run# || |
| || || |
| |"-------'| |
| .-^---------^-. |
| | ---~ ----~| |
| "-------------' |
| * Written in : Python 3 |
| * Purpose: I'm bored |
| * Shouts out to: Yo mama! |
| -henry s.|
======================================
""")
def room_1():
print("There's a giant bear here eating a cheese cake.")
print(f"What do you do {ask_user}?")
print("")
print("1. Take the cake")
print("2. Scream at the bear")
print("3. Fall to the floor and play dead")
print("4. Grab your crotch and say \"Hey Bear mothafucka!\" ")
print("5. Run!!!!")
bear = input("> ")
if bear == "1":
print(f"The bear eats {ask_user}'s face off. Good job!")
print(" XX DEAD XX ")
elif bear == "2":
print(f"The bear eats {ask_user}'s legs off. Good job!")
print(" XX DEAD XX ")
elif bear == "3":
print(f"Bear says: \"Oldest trick in the book dumbass\" and crushes {ask_user}'s' skull")
print(" XX DEAD XX ")
elif bear == "4":
print("Bear says: \"Oh very mature asshole!.\" Then he rips both arms off")
print(" XX DEAD XX ")
elif bear == "5":
print(f"Good thing I though of running before that bear could mame me")
print("""
YOU WIN!!
THANK YOU FOR PLAYING THIS
CRAPY GAME
[copyright © 2020]
""")
restart_game()
def room_2():
print("Ben Stiller is standing in a dojo"
"\nhe looks like he wants to rumble")
print("")
print("Ben Stiller: \"Como esta bitches?\"")
print("")
print(f"What do you do {ask_user}?")
print("")
print("1. Sweep the legs!")
print("2. Ask him: \"Do you have any idea who I am?\"")
print("3. Kick him on the nuts!")
print("4. Get close to him and say \"Hey what's that?\" then punch him on the face")
print("5. Shake his hand")
response = input("> ")
if response == "1" or response == "3":
print(f"Ben Stiller dodges {ask_user}'s move, then stabs {ask_user} in the heart with a spear")
print("Bad choice!")
elif response == "2":
print(f"(Ben Stiller says \"The guy I'm about to punch in the face\" [POOW!!]")
elif response == "4":
print(f"Ben Stiller does not fall for it and does a Round House kick on {ask_user} then says \"Do you how hard\
\nit is to be really really good looking?\"")
elif response == "5":
print(f"Ben Stiller does not fall for it and kicks {ask_user} in the nuts then says \"Valla con Dios!\" ")
restart_game()
def room_3():
print("OLD Thai lady is standing in a room very angry!")
print("Make her smile!")
print("")
print(f"1.{ask_user} says: \"DOHMAH!\" ")
print(f"2.{ask_user} says: \"What up shorty?\" ")
print(f"3.{ask_user} says: \"want to PHO..K\" ")
print(f"4.{ask_user} says: \"You give special massages?\"")
print(f"5.{ask_user} says: \"Me so horny!\"")
response = input("> ")
if response == "1" or response == "3":
print("Fuck you Bloody bastard!")
print(f"{ask_user} you lose!")
elif response == "2" or response == "4":
print("She flicks you off")
print(f"{ask_user} you lose!")
else:
print("I so horny too, let's go big boy!")
print("""
THE END!!
THANK YOU FOR PLAYING THIS
CRAPY GAME
[copyright © 2020]
""")
restart_game()
def room_4():
print(f"{ask_user} enters a room with \"Toby\", \"Bin Laden\", \"Hitler\" ")
print("")
print(f"On {ask_user}'s' left there is a night stand with a gun on it")
print(f"{ask_user} takes the gun but there is only one bullet")
print("")
print(f"What do you do {ask_user}?")
print("1. Kill Toby")
print("2. Kill Bind Laden")
print("3. Kill Hitler")
print("4. Lign them up and shoot them throught the throat")
print("5. Curve the bullet to kill them all in one shot")
kill = input("> ")
if kill == "1":
print(f"{ask_user} misses and just graze Tobys ear")
print(" XX DAMM! XX ")
elif kill == "2":
print(f"{ask_user} killed Bin Laden but he goes to heaven and receives 32 virgin")
print(" XX THAT BLOWS! XX ")
elif kill == "3":
print(f"{ask_user} kills Hitler, after Doc. Brown shows up in a Delorian and says \"You are not Marty!\"")
print(" XX YOU LOSE? XX ")
elif kill == "4":
print("The bullet is a dud, and they all woop yo' ass!")
print(" XX FUDGE! XX ")
elif kill == "5":
print(f"{ask_user} put tomuch curve and you shoot yourself in the nuts")
print("""
THE END!!
THANK YOU FOR PLAYING THIS
CRAPY GAME
[copyright © 2020]
""")
restart_game()
def room_5():
print(f"{ask_user} bumps into some jerk and the jerk punches {ask_user}\
\nin the face and knocks out a tooth. The police arrest you\
\nand not the jerk.")
print(f"A year later {ask_user} is working at a burger shop.")
print("")
print(f"The same cop that arrested you orders a burger")
print(f"What do you do {ask_user}?")
print("")
print("1. Spit on the burger")
print("2. Say: \"Do you remember me Asshole!\"")
print("3. Quit the job")
print("4. Jump over the counter and kick his ass!")
print("5. Just make him his food")
call_to_action = input("> ")
if call_to_action == "1":
print(f"As your are spitting on the burger, your manager is standing\
\nbehind you[puzzled]")
print(" XX YOUR FIRED! XX ")
elif call_to_action == "2":
print(f"The cop has no clue who you are")
print("He orders a liter of Cola with his burger.")
print(" XX DEAD XX ")
elif call_to_action == "3":
print(f"You yell \"I quit!\", as you leave, a drunk\
\ncustomer comes in, bumps into you, punches you in the face.\
\nthe cop arrest both of you. ")
print(" XX THIS SUCKED! XX ")
elif call_to_action == "4":
print("The cops reflexes are good. He takes out his baton\
\nwacks you in the head.")
print(" XX YOU WAKE UP IN JAIL XX ")
elif call_to_action == "5":
print(f"The cop has a pickle allergy and he forgot to order\
\nhis burger without them. The cop dies!")
print("""
YOU WIN!!
THANK YOU FOR PLAYING THIS
CRAPY GAME
[copyright © 2020]
""")
restart_game()
# Store the username
user_name = []
user_name.append(input)
ask_user = input("Hello!, what is your name?> ")
#This is where the game start/restarts
def game_running():
print("__________________________________________________")
print(f"{ask_user} is in a room facing five doors")
print("")
print("Do you go through door [#1] - [#2] - [#3] - [#4] ?")
# print("Or")
print(" [#5] ")
print("__________________________________________________")
door = input("> ")
# These are all the rooms
if door == "1":
room_1()
elif door == "2":
room_2()
elif door == "3":
room_3()
elif door == "4":
room_4()
elif door == "5":
room_5()
elif door == "6":
room_6()
elif door == "7":
room_7()
elif door == "8":
room_8()
# This func. is called to restart the game
def restart_game():
print("Play again? y or n")
replay = input("> ")
print("")
if replay == "y":
game_running()
elif replay == "n":
exit(0)
game_running()
|
23e559cc1bd3a9f8000581702e68755464369780 | gyuree-kim/algorithm | /dfs_and_bfs/dfs/dfs_template.py | 612 | 3.59375 | 4 | graph = []
graph.append(list(map(int, input())))
# 1차원 그래프
def dfs(graph, v, visited):
visited[v] = True
print(v, end=' ')
for i in graph[v]:
if not visited[i]:
dfs(graph, i, visited)
# 2차원 그래프
def dfs(x,y):
# out of the map size
if x < 0 or y < 0 or x >= n or y >= n:
return False
# haven't visited
if graph[x][y] == 0 :
graph[x][y] = 1 #check visited
# reculsive calls for up, down, left, and right
dfs(x-1, y)
dfs(x, y-1)
dfs(x+1, y)
dfs(x, y+1)
return True
return False |
72d0213b6cb5186226e0c748ac86dd4e124a200d | sonjoonho/InterviewPrep | /algorithms_ii.py | 12,496 | 3.78125 | 4 | import pytest
from typing import List
from queue import Queue
"""
Contains Python implementations of most algorithms encountered in the 2nd year
Algorithms II course at Imperial College London.
"""
"""
DYNAMIC PROGRAMMING
"""
"""
Quicksort
"""
def super_speedy_sort(arr, p, r):
# p is the beginning of the array, r is the end
if p < r:
q = partition(arr, p, r)
# At this point, arr has been partitioned around the pivot
super_speedy_sort(arr, p, q-1)
super_speedy_sort(arr, q+1, r)
def partition(arr, p, r):
# Select arr[r] as the pivot element
x = arr[r]
i = p - 1
# Region p to i is the region less than the pivot
# Region i to j is the regin greater than the pivot
for j in range(p, r):
if arr[j] <= x:
i = i+1
swap(arr, i, j)
swap(arr, i+1, r)
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
"""
Maximum Subarray Sum
"""
def max_subarray_dp(arr):
max_so_far = -1000
max_ending_here = 0
for i in range(len(arr)):
max_ending_here += arr[i]
if max_so_far < max_ending_here:
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
"""
Rod cutting
"""
def cutting_a_rod(rods: List[int]) -> int:
# A rod of length 0 is worth nothing.
rods[0] = 0
# Let T[i] be the maximum value obtained from a rod of length i.
T = [0 for i in range(len(rods)+1)]
# Either T[i] = max(rods[i], T[i-1] + rods[1], T[i-2] + rods[2]...)
for i in range(1, len(T)):
T[i] = max([rods[j] + T[i-j] for j in range(i)])
return T[-1]
"""
0/1 Knapsack problem
"""
def zero_one_knapsack_problem(values, weights, W):
assert(len(values) == len(weights))
# For each item, either it is included in the maximum subset or it is not.
# Therefore, there are two cases:
# 1. Maximum value obtained by n-1 items and W weight (excl. n).
# 2. Value of nth item + maximum value obtained by n-1 items and W minus
# the weight of the nth item (incl. n).
# D[i][j] = max value using i items in volume j.
D = [[0 for i in range(W+1)] for j in range(len(values)+1)]
for i in range(len(values)+1):
for j in range(W+1):
if i == 0 or j == 0:
D[i][j] = 0
elif weights[i-1] > j:
D[i][j] = D[i-1][j]
else:
D[i][j] = max(D[i-1][j], values[i-1] + D[i-1][j - weights[i-1]])
return D[len(values)][W]
"""
Longest Common Subsequence
Calculates the longest common subsequence between two strings.
"""
def longest_common_subsequence(A, B):
m = len(A)
n = len(B)
D = [[0 for i in range(n+1)] for j in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
D[i][j] = 0
elif A[i-1] == B[j-1]:
D[i][j] = D[i-1][j-1] + 1
elif D[i-1][j] >= D[i][j-1]:
D[i][j] = D[i-1][j]
else:
D[i][j] = D[i][j-1]
print(print_lcs(D, A, B))
return D[m][n]
"""
Prints the longest common subsequence using the DP table calculated above.
dab lol
"""
def print_lcs(D, A, B):
m = len(A)
n = len(B)
index = D[m][n]
result = [' ' for i in range(index)]
i = m
j = n
while i > 0 and j > 0:
# If current character in X and Y are same, then
# current character is part of LCS
if A[i-1] == B[j-1]:
result[index-1] = A[i-1]
i-=1
j-=1
index-=1
# If not same, then find the larger of two and
# go in the direction of larger value
elif D[i-1][j] > D[i][j-1]:
i-=1
else:
j-=1
return "".join(result)
"""
Longest Common Subsequence of three strings
Simple extension of LCS.
"""
def longest_common_subsequence_of_three_strings(A, B, C):
a = len(A)
b = len(B)
c = len(C)
D = [[[0 for k in range(c+1)] for j in range(b+1)] for i in range(a+1)]
for i in range(a+1):
for j in range(b+1):
for k in range(c+1):
if i == 0 or j == 0 or j == 0:
D[i][j][k] = 0
elif A[i-1] == B[j-1] == C[k-1]:
D[i][j][k] = D[i-1][j-1][k-1] + 1
else:
D[i][j][k] = max(D[i-1][j][k],
D[i][j-1][k],
D[i][j][k-1])
return D[a][b][c]
def longest_common_palindromic_subsequence(s):
s_r = s[::-1]
return longest_common_subsequence(s, s_r)
"""
Longest snake
Longest path in a grid (similar to max_apples which
appeared in a past paper.
"""
def longest_snake(grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
T = [[0 for i in range(n)] for j in range(m)]
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if i == m-1 and j == n-1:
T[m-1][n-1] = grid[m-1][n-1]
elif i == m-1:
T[i][j] = grid[i][j] + T[i][j+1]
elif j == n-1:
T[i][j] = grid[i][j] + T[i+1][j]
else:
T[i][j] = grid[i][j] + max(T[i+1][j], T[i][j+1])
return max(map(max, T))
"""
Is Subset Sum
Simple recursive implementation.
"""
def is_subset_sum_rec(numbers: List[int], m: int):
if m == 0:
return True
if m < 0:
return False
if len(numbers) == 0:
return False
return is_subset_sum_rec(numbers[1 :], m) or is_subset_sum_rec(numbers[ 1:], m-numbers[0])
"""
Is Subset Sum
Bottom-up dynamic programming solution.
"""
def is_subset_sum_dp(numbers, m):
n = len(numbers)
dp = [[False for i in range(m+1)] for i in range(n+1)]
for i in range(n+1):
for j in range(m+1):
if j == 0:
dp[i][j] = True
elif i == 0:
dp[i][j] = False
elif j < numbers[i-1]:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j] or dp[i-1][j-numbers[i-1]]
return dp[n][m]
"""
GREEDY ALGORITHMS
"""
"""
Fractional Knapsack Problem
"""
def fractional_knapsack_problem(values: List[int], weights: List[int], W: int) -> int:
# Calculate the value per unit weight.
value_per_weight = [v / w for (v, w) in zip(values, weights)][::-1]
# Sort and reindex values and weights (I think you can just state this as
# an assumption in the exam.
values = [v for _, v in sorted(zip(value_per_weight, values), key = lambda pair: pair[0])]
weights = [w for _, w in sorted(zip(value_per_weight, weights), key = lambda pair: pair[0])]
remaining_weight = W
max_val = 0
i = 0
while remaining_weight >= 0 and i < len(value_per_weight):
# Determine how much we should take.
t = min(1, remaining_weight / weights[i])
max_val += t * values[i]
remaining_weight -= t * weights[i]
i += 1
return max_val
"""
GRAPH ALGORTIHMS
"""
"""
Notes on graph represenations
You can have an adjacency list or an adjacency matrix
Adjacency lists are generally better because you can easily iterate through all the neighours
With adjacency matrices, you need to iterate through all the nodes to find a node's neighbours
"""
class Graph:
def __init__(self, nodes=[]):
self.nodes = nodes
class GraphNode:
def __init__(self, value, adjacent=[], visited=False):
self.value = value
self.adjacent = adjancent
self.visited = visited
"""
Depth First Search
Recursive implementation is generally easiest, but can be implemented
iteratively using a stack.
"""
def recursive_dfs(root):
if root is None:
return
print(root.value)
root.visited = True
for n in root.adjacent:
if not n.visited:
recursive_dfs(n)
"""
Breadth First Search
Uses a queue.
"""
def iterative_bfs(root):
queue = Queue()
root.visited = True
while not queue.empty():
r = queue.get()
r.visited = True
print(r.value)
for n in r.adjacent:
if not n.visited:
queue.put(n)
#def bellman_ford():
"""
Get Closest Number
Uses binary search for O(n log n) runtime.
"""
def closest_number(arr: List[int], n: int) -> int:
low = 0
high = len(arr)
if n <= arr[0]:
return arr[0]
elif n >= arr[-1]:
return arr[-1]
while low < high:
mid = (low + high) // 2
if arr[mid] == n:
return n
elif n < arr[mid]:
# Search left
if mid > 0 and n > arr[mid-1]:
return get_closest(arr[mid-1], arr[mid], n)
high = mid
else:
if mid < n-1 and n < arr[mid+1]:
return get_closest(arr[mid+1], arr[mid], n)
low = mid+1
return arr[mid]
def get_closest(a, b, n):
return a if abs(n - a) < abs(n-b) else b
"""
DIVIDE AND CONQUER
"""
"""
Maximum Sum Subarray
1. Divide the array into two halves
2. Return max of
a. Maximum subarray of left half
b. Maximum subarray of right half
c. Maximum subarray of mid
"""
def max_subarray_dc(arr, low, high):
# Base case
if (low == high):
return arr[low]
mid = (low + high) // 2
# Max of three cases
return max(max_subarray_dc(arr, low, mid),
max_subarray_dc(arr, mid+1 ,high),
max_crossing_sum(arr, low, mid, high))
def max_crossing_sum(arr, low, mid, high):
total = 0
left_total = -10000
for i in range(mid, low-1, -1):
total += arr[i]
if total > left_total:
left_total = total
total = 0
right_total = -10000
for i in range(mid+1, high+1):
total += arr[i]
if total > right_total:
right_total = total
return left_total + right_total
class TestAlgorithmsII:
def test_rod_cutting_1(self):
rods = {1: 1, 2: 5, 3: 8, 4: 9, 5: 10, 6: 17, 7: 17, 8: 20}
assert cutting_a_rod(rods) == 22
def test_rod_cutting_2(self):
rods = {1: 3, 2: 5, 3: 8, 4: 9, 5: 10, 6: 17, 7: 17, 8: 20}
assert cutting_a_rod(rods) == 24
def test_01_knapsack(self):
values = [60, 100, 120]
weights = [10, 20, 30]
W = 50
assert zero_one_knapsack_problem(values, weights, W) == 220
def test_longest_common_subsequence_1(self):
A = "ABCDGH"
B = "AEDFHR"
assert longest_common_subsequence(A, B) == 3
def test_longest_common_subsequence_2(self):
A = "AGGTAB"
B = "GXTXAYB"
assert longest_common_subsequence(A, B) == 4
def test_longest_common_subsequence_of_three_strings_1(self):
A = "geeks"
B = "geeksfor"
C = "geeksforgeeks"
# bless geeks for geeks
assert longest_common_subsequence_of_three_strings(A, B, C)
def test_longest_common_subsequence_of_three_strings_1(self):
A = "abcd1e2"
B = "bc12ea"
C = "bd1ea"
# bless geeks for geeks
assert longest_common_subsequence_of_three_strings(A, B, C)
def test_longest_palindromic_subsequence(self):
s = "CHARACTER"
assert longest_common_palindromic_subsequence(s)
def test_is_subset_sum_1(self):
assert is_subset_sum_dp([1, 2, 3], 5) == True
def test_is_subset_sum_2(self):
assert is_subset_sum_dp([1, 2, 3], 6) == True
def test_is_subset_sum_3(self):
assert is_subset_sum_dp([1, 2, 3], 7) == False
def test_is_subset_sum_4(self):
assert is_subset_sum_dp([1, 2, 3], 9) == False
def test_fractional_knapsack_problem(self):
values = [60, 100, 120]
weights = [10, 20, 30]
W = 50
assert fractional_knapsack_problem(values, weights, W) == 240
def test_closest_number_1(self):
arr = [1, 2, 4, 5, 6, 6, 8, 9]
assert closest_number(arr, 11) == 9
def test_closest_number_2(self):
arr = [2, 5, 6, 7, 8, 8, 9]
assert closest_number(arr, 4) == 5
def test_maximum_subarray_dc(self):
arr = [-2, -5, 6, -2, -3, 1, 5, -6]
assert max_subarray_dc(arr, 0, len(arr)-1) == 7
def test_maximum_subarray_dp(self):
arr = [-2, -5, 6, -2, -3, 1, 5, -6]
assert max_subarray_dp(arr) == 7
|
1890b26e7af1a71f45fc5cd6e56759d295b34c8d | sonjoonho/InterviewPrep | /stacksandqueues.py | 2,445 | 4.0625 | 4 | class Stack:
def __init__(self, stack=[]):
self.stack = stack
def pop(self):
# Get last element
#val = self.stack[-1]
# Remove last element
#self.stack = stack[:-1]
# Python lists have a pop method, but that's probably not what you're looking for
return stack.pop()
def push(self, val):
self.stack.append(val)
def peek(self):
return self.stack[-1]
def isempty(self):
return self.stack.isempty()
# Also can be implemented using a singly linked list!!
# So can queues. Heaps can be used to implement a PRORITY queue
# Stacks and queues are pretty much the same thing, just add and remove at different ends
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack():
def __init__(self):
self.top = None
def pop(self):
if self.top is None:
raise Exception("Stack is empty")
item = self.top.value
self.top = self.top.next
return item
def push(self, value):
node = Node(value)
node.next = self.top
self.top = node
def peek(self):
return self.top
def isempty(self):
return self.top is None
class Queue():
def __init__(self):
self.first = None
self.last = None
def add(self, value):
node = Node(value)
if self.last is not None:
self.last.next = node
self.last = node
if self.first is None:
self.first = self.last
def remove(self):
if self.first is None:
raise Exception("Queue is empty")
item = self.first.value
self.first = self.first.next
return item
def peek(self):
if self.first is None:
raise Exception("Queue is empty")
return self.first.value
def isempty(self):
return self.first is None
if __name__ == "__main__":
stack = Stack()
stack.push(5)
stack.push(3)
stack.push(8)
stack.push(0)
v = stack.pop()
print(v)
v = stack.pop()
print(v)
v = stack.pop()
print(v)
v = stack.pop()
print(v)
queue = Queue()
queue.add(5)
queue.add(3)
queue.add(8)
queue.add(0)
v = queue.remove()
print(v)
v = queue.remove()
print(v)
v = queue.remove()
print(v)
v = queue.remove()
print(v)
|
38f472d2526c729eebc6e8cf927421db57a66c3f | onkarbk/OOPS | /Assignments/Trello/Python/Card.py | 2,709 | 3.640625 | 4 | import json
class Card:
def __init__(self, id, name):
"""
Creates a `Card` instance
Parameters:
id(str): Card ID
name(str): Card name
"""
self.id = id
self.name = name
self.description =""
self.assignedTo = ""
self.isAssigned = False
self.user = None
def updateDescription(self, descr):
"""
Updates the `self.description` attribute.
Parameters:
descr(str): New description of the card.
Returns:
None
"""
self.description = descr
def updateName(self, name):
"""
Updates the `self.name` attribute.
Parameters:
name(str): New name of the card.
Returns:
None
"""
self.name = name
def assign(self,id, user):
"""
Assigns a user to the card. lso adds the crdId to the `User.cards` attribute.
Parameters:
id(str): User ID
user(User): `User` instance of the user assigned to the card.
Returns:
None
"""
if self.isAssigned:
self.unassign()
self.isAssigned = True
self.assignedTo = id
self.user = user
self.user.cards.append(self.id)
def unassign(self):
"""
If any user is assigned to the card, unassigns the user.
Also removes the cardId from the `User.cards` attribute.
Parameters:
None
Returns:
None
"""
if self.isAssigned:
self.isAssigned = False
self.assignedTo = ""
self.user.cards.remove(self.id)
self.user = None
else:
print('Card '+self.id+' is already unassigned.')
def getJsonObject(self):
"""
Retrieves a Dictionary object of `Card` instance which can be converted to JSON.
Parameters:
None
Returns:
jsonObject (dict): `dict` object of the `Card` instance.
"""
jsonObject = {
'id': self.id,
'isAssigned': self.isAssigned,
'name': self.name,
'description': self.description,
'assignedTo': self.assignedTo,
}
return jsonObject
def jsonify(self):
"""
Retrieves JSON string of the `Card` instance.
Parameters:
None
Returns:
jsonString (str): JSON string of `Card` instance.
"""
jsonObject = self.getJsonObject()
return json.dumps(jsonObject) |
4ee0bc9c49c58f4d225c2d5a4eedc3c2e124ead3 | linkenghong/Backtesting | /Backtesting/portfolio_handler/position.py | 2,431 | 3.65625 | 4 | import csv
class Position(object):
def __init__(
self, action, symbol, init_quantity,
init_price, init_commission,
cur_price
):
"""
Set up the initial "account" of the Position.
Then calculate the initial values and finally update the
market value of the transaction.
"""
self.action = action
self.symbol = symbol
self.quantity = init_quantity
self.unavailable_quantity = init_quantity
self.available_quantity = 0
self.init_price = init_price
self.price = round(init_price, 2)
self.init_commission = init_commission
self.total_commission = init_commission
self.avg_price = 0
if self.action == "BUY":
self.avg_price = round((self.init_price * self.quantity + self.init_commission) / self.quantity , 2)
self.update_market_value(cur_price)
def update_market_value(self, price):
"""
Update market values with the latest price.
"""
self.market_value = round(self.quantity * price, 2)
def update_position(self):
"""
At A share, trading rule is T+1, when it is a new day, the
available position should be update.
"""
self.available_quantity += self.unavailable_quantity
self.unavailable_quantity = 0
def transact_shares(self, action, quantity, price, commission):
"""
Calculates the adjustments to the Position that occur
once new shares are bought and sold.
"""
self.price = round(price, 2)
self.total_commission += commission
direction = 1 if action == "BUY" else -1
self.unavailable_quantity += quantity
lastest_quantity = self.quantity + direction * quantity
if lastest_quantity > 0:
self.avg_price = round((
self.quantity * self.avg_price + commission
+ direction * quantity * price
) / lastest_quantity , 2)
self.quantity = lastest_quantity
def record_position(self, fname, timestamp):
with open(fname, 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([
timestamp, self.symbol, self.quantity,
self.price, self.avg_price, self.market_value,
self.total_commission
])
|
38597fbfee7395d38bb8f1a97b8184ec8ceff5ab | mboker/Cardinal_Katas | /kata_two.py | 1,572 | 3.578125 | 4 | import pandas as pd
import numpy as np
if __name__ == '__main__':
# First, read football.dat into a pandas dataframe
# using any contiguous block of whitespace as the delimiter between columns.
# Upon observing the data, I see that there is a column of hyphens between the 'for' and 'against'
# columns, and this column has no header.
# To account for this, I set header=0 to discard the top row from the file,
# thus allowing me to use my own set of column headers.
# I specify the headers in the 'names' parameter.
table = pd.read_table('football.dat', delim_whitespace=True, header=0, \
names=['number', 'name', 'p', 'w', 'l', 'd', 'for', 'dash', 'against', 'pts'])
# convert the 'for' and 'against' series into numpy float arrays
pts_agnst, pts_for = np.float_(table['against']), np.float_(table['for'])
# create a numpy float array that contains the absolute values of the differences between 'against' and 'for'
spread = abs(pts_agnst-pts_for)
# Now, get the array index of the smallest spread value that is not == nan
# Ignoring nan is necessary to account for the row of hyphens. Another option would have been to
# skip this row in pd.read_table, but the approach I have used is more general.
# numpy.nanargmin does exactly this, finding the index of a float array for the minimum value in
# that array which is not nan
answer_idx = np.nanargmin(spread)
# Print the value in the name column for the row with the smallest spread
print(table['name'][answer_idx]) |
cd1c5a3524e3511df63ca649fb0a99242a290c24 | nirorman/DeepLearningAcademy | /kMeans/k_means.py | 3,201 | 3.578125 | 4 | from random import uniform
import math
from matplotlib import pyplot as plt
class KMeans(object):
def __init__(self, k, data):
self.k = k
self.data = data
self.clusters = self.get_clusters()
self.data = data
def get_clusters(self):
if type(self.data[0]) is float:
return [uniform(min(self.data), max(self.data)) for i in range(self.k)]
elif type(self.data[0]) is (float, float):
return zip([uniform(min(self.data), max(self.data)) for i in range(self.k)], [uniform(min(self.data), max(self.data)) for i in range(self.k)])
def _cluster_number_to_list_of_points(self):
cluster_number_to_list_of_points = {}
for i in range(self.k):
cluster_number_to_list_of_points[i] = []
for d in self.data:
min_distance = self.distance(d, self.clusters[0])
best_cluster_index = 0
for i in range(len(self.clusters)):
dist = self.distance(d, self.clusters[i])
if dist < min_distance:
min_distance = dist
best_cluster_index = i
cluster_number_to_list_of_points[best_cluster_index].append(d)
return cluster_number_to_list_of_points
@staticmethod
def distance(a, b):
if type(a) is float and type(b) is float:
return abs(a - b)
elif type(a) is (float, float) and type(b) is (float, float):
return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
else:
print("ERROR")
return None
def _calculate_cluster_location(self, cluster_number_to_list_of_points):
clusters_locations = []
for key, value in cluster_number_to_list_of_points.items():
clusters_locations.append(sum(value)/len(value))
return clusters_locations
def get_new_clusters_location(self):
cluster_number_to_list_of_points = self._cluster_number_to_list_of_points()
self._visualize(cluster_number_to_list_of_points)
return self._calculate_cluster_location(cluster_number_to_list_of_points)
@staticmethod
def _is_converged(new_cluster_locations, old_cluster_locations):
return new_cluster_locations == old_cluster_locations
def cluster(self):
number_of_iterations = 0
while True:
number_of_iterations += 1
new_cluster_locations = self.get_new_clusters_location()
if self._is_converged(new_cluster_locations, self.clusters):
break
self.clusters = new_cluster_locations
print(number_of_iterations)
return self.clusters
def _visualize(self, cluster_number_to_list_of_points):
#points = [(x, y) for x in cluster_number_to_list_of_points.keys() for y in cluster_number_to_list_of_points.values()]
points = []
for x in cluster_number_to_list_of_points.keys():
for y in cluster_number_to_list_of_points[x]:
points.append((x,y))
x_values = [point[0] for point in points]
y_values = [point[1] for point in points]
p = plt.plot(x_values, y_values,'.')
plt.show()
|
ff0ea44b2231c4dc567931ad1d3c514f8be198b2 | kc97ble/testfmt5 | /testfmt/filelist.py | 7,416 | 3.640625 | 4 | #!/usr/bin/env python3
""" filelist.py
BaseFileList
FileList
ZipFileList
Usage:
file_list = FileList/ZipFileList(...)
print file_list.files
file_list.files = ...
success = file_list.move_files_indirectly(src, dst, real=..., quiet=...)
"""
import os
import sys
import zipfile
import datetime
import misc
from zipfile import ZipFile
class BaseFileList(object):
"""
Moves files.
Properties:
files (list)
Methods:
__init__(self, files)
__repr__(self):
really_renames(self, src, dst)
move_file(self, src, dst, real=False, quiet=False)
move_files_best_effort(self, src, dst, **kwargs)
move_files_directly(self, src, dst, **kwargs)
move_files_indirectly(self, src, dst, **kwargs)
"""
#TODO: Handle natural sorting order
def __init__(self, files):
self.files = list(files)
def __repr__(self):
return 'filelist.BaseFileList({})'.format(self.files)
def really_renames(self, src, dst):
""" (self, str, str) -> bool """
raise NotImplementedError
def move_file(self, src, dst, real=False, quiet=False):
""" (self, str, str, ...) -> bool
Moves a file.
Changes:
self.files
really_renames will be called if self.real == True
Returns:
True if success,
False otherwise.
"""
if src == dst:
return src in self.files
if (src not in self.files) or (dst in self.files):
return False
if not quiet:
print("Moving '{}' -> '{}'".format(src, dst))
self.files[self.files.index(src)] = dst
return self.really_renames(src, dst) if real else True
def move_files_best_effort(self, src, dst, **kwargs):
""" (list, list) -> int
Moves files, stop at the first failure.
Returns:
Number of successful moves
"""
assert len(src) == len(dst)
n = len(src)
for i in range(n):
if not self.move_file(src[i], dst[i], **kwargs):
return i
return n
def move_files_directly(self, src, dst, **kwargs):
""" (self, list, list) -> bool
Moves files. If success, returns True.
Otherwise, recovers the original state and return False.
Exceptions will be raised if recovering is failed.
Returns:
True if success,
False otherwise.
"""
assert len(src) == len(dst)
n = len(src)
success = self.move_files_best_effort(src, dst, **kwargs)
if success == n:
return True
else:
src2 = list(reversed(dst[:success]))
dst2 = list(reversed(src[:success]))
recovered = self.move_files_best_effort(src2, dst2, **kwargs)
if recovered == success:
return False
else:
raise RuntimeError("Failed to recover")
def move_files_indirectly(self, src, dst, **kwargs):
""" (self, list, list, ...) -> bool
Same as move_file_directly, except that this method
uses an intermediate list of file names to move files.
Returns:
True if success,
False otherwise.
"""
n = misc.ensure_equal_len(src, dst)
pre = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
sep = '--------'
mid = list(range(n))
for i in range(n):
t0 = src[i].replace('/', '----').replace('\\', '------')
t1 = dst[i].replace('/', '----').replace('\\', '------')
mid[i] = pre+sep+t0+sep+t1+sep+str(i).zfill(8)+'.testdata'
return self.move_files_directly(src+mid, mid+dst, **kwargs)
class FileList(BaseFileList):
"""
Moves files in the working directory.
"""
@classmethod
def from_working_directory(cls, **kwargs):
return cls(misc.get_file_list_recursively(**kwargs))
def really_renames(self, src, dst):
""" (self, str, str) -> bool """
try:
os.renames(src, dst)
except OSError as e:
print(e.errno, file=sys.stderr)
print(e, file=sys.stderr)
return False
return True
class ZipFileList(BaseFileList):
"""
Moves files in a ZIP file.
"""
def __init__(self, zip_path):
self.src_path = zip_path
files = ZipFile(self.src_path, 'r').namelist()
super(ZipFileList, self).__init__(files)
def really_renames(self, src, dst):
if src == dst:
return True
if (dst in self.old_name) or (src not in self.old_name):
return False
self.old_name[dst] = self.old_name.pop(src)
return True
def apply_changes(self, quiet=False):
src_path = self.src_path
dst_path = src_path + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
try:
with ZipFile(src_path, 'r') as src, ZipFile(dst_path, 'w', zipfile.ZIP_DEFLATED) as dst:
assert src.testzip() == None
for name in self.old_name:
if not quiet:
print("Writing data of '{}'".format(name))
data = src.read(self.old_name[name])
info = src.getinfo(self.old_name[name])
info.filename = name
dst.writestr(info, data)
assert ZipFile(dst_path, 'r').testzip() == None
os.rename(src_path, dst_path + '.backup')
os.rename(dst_path, src_path)
os.remove(dst_path + '.backup')
finally:
if os.path.isfile(dst_path):
os.remove(dst_path)
if not os.path.isfile(src_path) and os.path.isfile(dst_path + '.backup'):
os.rename(dst_path + '.backup', src_path)
def move_files_directly(self, src, dst, **kwargs):
self.old_name = {x: x for x in self.files}
super(ZipFileList, self).move_files_directly(src, dst, **kwargs)
if kwargs.get('real', False):
self.apply_changes()
del self.old_name
return True
if __name__ == '__main__':
print(BaseFileList(['a', 'b', 'c']))
assert BaseFileList(['a', 'b', 'c']).move_file('a', 'a', quiet=True) == True
assert BaseFileList(['a', 'b', 'c']).move_file('a', 'b', quiet=True) == False
assert BaseFileList(['a', 'b', 'c']).move_file('a', 'c', quiet=True) == False
assert BaseFileList(['a', 'b', 'c']).move_file('a', 'd', quiet=True) == True
assert BaseFileList(['a', 'b', 'c']).move_files_best_effort(['a', 'b'], ['d', 'e'], quiet=True) == 2
assert BaseFileList(['a', 'b', 'c']).move_files_best_effort(['a', 'b'], ['d', 'd'], quiet=True) == 1
assert BaseFileList(['a', 'b', 'c']).move_files_directly(['a', 'b'], ['d', 'e'], quiet=True) == True
assert BaseFileList(['a', 'b', 'c']).move_files_directly(['a', 'b'], ['d', 'd'], quiet=True) == False
assert BaseFileList(['a', 'b', 'c']).move_files_directly(['a', 'b', 'c'], ['c', 'd', 'e'], quiet=True) == False
assert BaseFileList(['a', 'b', 'c']).move_files_indirectly(['a', 'b', 'c'], ['c', 'd', 'e'], quiet=True) == True
|
a51fca588c89afc244eab2b1fa734935933b1672 | maddiemooney/adventofcode2020 | /3.py | 422 | 3.65625 | 4 | def day3(lines, x, y):
count = 0
row = 0
col = 0
while row < len(lines):
if(lines[row][col] == '#'):
count += 1
row += x
col = (col + y) % len(lines[0])
return(count)
file3 = open('input3.txt', 'r')
lines = [line.strip() for line in file3.readlines()]
print(day3(lines, 1, 3))
a = day3(lines, 1, 1)
b = day3(lines, 1, 3)
c = day3(lines, 1, 5)
d = day3(lines, 1, 7)
e = day3(lines, 2, 1)
print(a*b*c*d*e)
|
74d1e8ed8267e8af09cb20e8f9b4f75ae01b97eb | Phantom1721/python | /ip-py/main.py | 310 | 3.5625 | 4 | print("Welcome guys, today i will show you how you can get your ip with python")
# first we will import request library
import requests
# this will send a get request to the website and the website will return the ip
r = requests.get("https://httpbin.org/ip")
print(r.text)
# now lets test it |
385051c244641e98896c18a8fd8211f86a50143a | Puneethgr/MachineLearningLabVTU | /01 (Find S algorithm)/1.py | 655 | 3.703125 | 4 | # Program 1 (Find S):
import pandas as pd
data = pd.read_csv("EnjoySport.csv", header = None)
print(data)
numberAttributes = len(data.columns)-1
hypothesis = ['0' for _ in range(numberAttributes)]
print("hypothesis 0 : ", hypothesis)
for index, row in data.iterrows():
if row[len(row)-1] == "Yes":
for colIndex in range(len(row)-1):
if hypothesis[colIndex] == '0':
hypothesis[colIndex] = row[colIndex]
elif hypothesis[colIndex] != row[colIndex]:
hypothesis[colIndex] = '?'
print("hypothesis {} : {}".format(index+1, hypothesis))
print("Final hypothesis: ", hypothesis) |
717975751852860d17fb06e6f8e0b15afaaf20c9 | jose137sp/lab3-py | /problema1.py | 667 | 3.953125 | 4 | print()
lista=[]
for i in range(20):
lista.append(int(input("Introduzca un numero: ")))
print("\n Lista impresa: ")
print(lista)
print("\n Lista ordenada: ")
ordenada=sorted(lista)
print(ordenada)
print("\nLongitud: ")
print(len(lista))
print("\n--------------------------------------------------------------")
n=1
while n==1:
x=int(input("Introduzca un numero para buscarlo dentro de la lista: "))
if x in lista:
print("Encontrado")
else:
print("Este numero no se encuentra en su lista...")
n=int(input("\nSi desea buscar otro numero en esta lista introduzca el numero (1): "))
print("\nPrograma finalizado...\n") |
000ca6ba92ba3927f35b2bf77eff25f74d60e862 | tasneem786/DNA-string-Complement_and_GC_content | /Problem7.py | 179 | 3.59375 | 4 | s = input("Enter ")
c = s[::-1]
print (c)
complementary =""
com_rule={"T":"A", "A":"T","G":"C","C":"G"}
for i in c :
complementary+= com_rule[i]
print (complementary)
|
eee5b0b3595809d6df59ab3cdd9733465b3dd466 | MasKong/Algorithms | /Merge k Sorted Lists_v2.py | 1,726 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists): #naive version
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
i = 0
n = len(lists)
while i < n:
if lists[i] is None:
del lists[i]
n = len(lists)
else:
i += 1
cur_l = sorted(lists, key=lambda i:i.val)
if len(lists) == 0:
return None
head = cur_l[0]
p = head
if cur_l[0].next is not None:
cur_l[0] = cur_l[0].next
else:
del cur_l[0]
self.sort_l(cur_l)
while cur_l:
p.next = cur_l[0]
p = p.next
if cur_l[0].next is None:
del cur_l[0]
else:
cur_l[0] = cur_l[0].next
self.sort_l(cur_l)
return head
def sort_l(self, cur_l):
'''cur_l is a list and the first node is with the minimum value'''
cur = 0
for i in range(1, len(cur_l)):
if cur_l[cur].val > cur_l[i].val:
# if i==1:
# break
# else:
cur_l[cur], cur_l[i] = cur_l[i], cur_l[cur]
cur = i
# cur = cur_l[i]
# cur_l[0], cur_l[len(cur_l)-1] = cur_l[len(cur_l)-1], cur_l[0]
# from utils import make_linked_list, print_linked_list, ListNode
# s = Solution()
# l = [1,4,5]
# l1 = [1,3,4]
# l2 = [2,6]
# input_l = list(map(make_linked_list,[l,l1,l2]))
# h = s.mergeKLists(input_l)
# print_linked_list(h)
|
175a33228e101c2b2b9b232a938eaa078a9cdccd | MasKong/Algorithms | /aigeng.py | 999 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sort(self, head): #naive version
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if head is None:
return None
cur = head
count = 0
while cur is not None:
if cur.val % 2 != count % 2:
idiot = cur.next
while idiot is not None and idiot.val % 2 != count % 2:
idiot = idiot.next
if idiot is None:
return None
else:
cur.val, idiot.val = idiot.val, cur.val
count += 1
cur = cur.next
# if cur.val % 2 == count % 2:
from utils import make_linked_list, print_linked_list, ListNode
s = Solution()
l = [2,1,3,5,6,4,7]
input_l = make_linked_list(l)
h = s.sort(input_l)
print_linked_list(h)
|
0794f310ba90efe98b8bf0eeeeb4a5ce0ad74660 | MasKong/Algorithms | /Palindromic Substrings.py | 707 | 3.515625 | 4 | class Solution:
def countSubstrings(self, s: str) -> int:
res = []
for i in range(0, len(s)):
for j in range(i+1,len(s)+1):
if self.is_palindromic(s[i:j]):
res.append(s[i:j])
return len(res)
def is_palindromic(self, s: str):
if s == s[::-1]:
return True
return False
# if len(s) == 0:
# return True
# for i in range(int(len(s)/2)):
# if s[i] != s[len(s)-1-i]:
# return False
# return True
s = Solution()
res = s.countSubstrings("aba")
print(res)
res = s.countSubstrings("abc")
print(res)
res = s.countSubstrings("aaa")
print(res)
|
329516d87315f02847f4842b34420df44b0b2fbe | MasKong/Algorithms | /用两个栈实现队列.py | 562 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.l = []
self.l1 = []
def push(self, node):
# write code here
# if self.l:
# self.l1.append(self.l.pop())
self.l.append(node)
def pop(self):
# return xx
if not self.l:
return None
while len(self.l) > 1:
self.l1.append(self.l.pop())
elem = self.l.pop()
# self.l, self.l1 = self.l1, self.l
while self.l1:
self.l.append(self.l1.pop())
return elem
|
4f863139c0e3767ce9aff281aa639a2730b2538a | MasKong/Algorithms | /Add Two Numbers.py | 757 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
if l1 is None and l2 is None:
return None
elif l1 is None:
return list(self.traverse(l2))
elif l2 is None:
return list(self.traverse(l1))
return list(map(lambda i:int(i), list(str(int(self.traverse(l1)) + int(self.traverse(l2)))[::-1])))
def traverse(self, l1):
res = ''
cur = l1
while cur is not None:
res += str(cur.val)
cur = cur.next
return res[::-1]
s = Solution()
# res = s.addTwoNumbers((2 -> 4 -> 3) + (5 -> 6 -> 4))
# print(res) |
16407eb4a356857abddcf2af40d351eb284b26f1 | MasKong/Algorithms | /Binary Tree Right Side View.py | 869 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
'''BFS'''
if not root:
return []
l = [root]
result = []
# node = root
while l:
intermediate = []
record = len(l)
for i in range(record):
node = l[i]
intermediate.append(node.val)
if node.left:
l.append(node.left)
if node.right:
l.append(node.right)
result.append(intermediate[-1])
l = l[record:]
return result |
bb7964b4c045e07e7302a9ab908a02b86e28627b | iijii-0c/hangman | /Game_Petr.py | 6,828 | 3.671875 | 4 | import random
words=["лошадка","тумбочка","переводчик","компьютер",
"клавиатура","переплет","сиденье","наклейка",
"холодильник","зеркало"]
for i in range(2):
i=len(words)
nomber_word=random.randint(0,i)
def hangman(word): # Задаем функцию от параметра "word"
wrong=0 #Создаем переменную содержащую количество неправильных ответов("0")
stages=["",
"_________",
"| |",
"| |",
"| ^",
"| ( 0 )",
"| |",
"| /|\ ",
"| / | \ ",
"| / | \ ",
"| |",
"| / \ ",
"| / \ ",
"| / \ ",
"|",
"|",
"|________________"
] #Создаем построчный рисунок для построчного вывода при неправильных
#предположениях
rletters=list(word) #Создаем список состоящий из букв заданного слова
board=["_"]*len(word) # Создаем переменную(список),которая выводит подсказку,
#показывающую уже угаданные буквы. В самом
#начале будет показываться "_" столько раз, сколько
#букв в загаданном слове
win=False #Создаем переменную, сигнализирующую о проигрыше
# НАДО ДОБАВИТЬ ЛОГИКУ СРАБАТЫВАНИЯ
print("""\n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n
Добро пожаловать на казнь!""") # Выводим приветствие
while wrong < len(stages)-1: #Проверяем сколько неправильных значений
#введено(так чтобы количество неправильных
#ответов было меньше строк в рисунке)
print("\n") #Переходим на новую строчку(?)
msg="Введите букву:" #Запрвшиваем букву
char=input(msg) #Вводим переменную, и присваиваем ей содержание ответа
if char in rletters: #Проверяем есть ли данный ответ в загаданном слове
cind=rletters.index(char) #Вводим переменную, и присваиваем ей
#номер, соответствующий положению
#введенного ответа в загадонном
#слове
board[cind]=char #В списке "board" элемент с порядковым номером
#угаданной буквы заменяется значением
#(соответствующей угаданной буквой)
rletters[cind]='$' #выводит символ '$' если введенная буква
#повторяется в загаданном слове?????
else:
wrong+=1 #если введенной буквы нет в загаданном слове, то
#увеличиваем переменную "wrong" на 1
print(board)
print((" ".join(board))) #Выводит содержание словаря "board" и добавляет
#пробелы между элементами словаря
e=wrong+1 #Создается переменная для вывода части рисунка при неправильном
#ответе. Ее значение равно ????
print("\n".join(stages[0:e]))#Выводит рисунок (количество строк в пере-
#менной "stages" равное количеству непра-
#вильных ответов
if "_" not in board: #проверяем остались ли неотгаданные буквы в
#словаре "board"
print("Вы выиграли! Было загадано слово: ")#если нет неотгаданных
#букв, то выводится сооб-
#щение о выигрыше
print(" ".join(board))#выводится загаданное слово
win=True #Присваиваем переменной "win" значение "True" дя сигналао
#выигрыше
break #прерываем цикл проверки выигрыша
if not win: #если переменная "win" "False"(ложь), товыполнить следующее:
print("\n".join(stages[0:wrong]))# вывести рисунок(количество строк в
#словаре "stages", соостветсвующее
#количеству неправильных ответов,
#равному переменной "wrong" и добавить
#пренос строки после каждого элемента
#словаря "stages"
print("Вы проиграли! Было загадано слово:{}.".format(word)) #Выводит сообще-
#ние о выигрыше и добавляет к сообщению загаданное
#слово
hangman(words[nomber_word]) #вызывается функция с параметром "word"
new_word=input("Введите слово для пополнения списка словаря:")
words.append(new_word)
|
14779d4fa7f2085220f8f41e784ff8fa7d701a17 | StRobertCHS-ICS4U1a-201819/rams-rewards-final-project-power-rangers | /Student.py | 1,210 | 3.5625 | 4 | class Student(object):
def __init__(self, first_name, last_name, student_id, grade):
self.__first_name = first_name
self.__last_name = last_name
self.__student_id = student_id
self.__grade = grade
self.__points = 0
self.__history = []
self.__selected = False
def get_name(self):
if self.__first_name == "":
return self.__last_name
elif self.__last_name == "":
return self.__first_name
return self.__last_name + ", " + self.__first_name
def get_id(self):
return self.__student_id
def get_grade(self):
return self.__grade
def get_points(self):
return self.__points
def set_points(self, points):
self.__points = points
def select(self, select):
self.__selected = select
def isSelected(self):
return self.__selected
def log_event(self, activity):
self.__history.append(activity)
def get_history(self):
string = ""
for i in range(len(self.__history)-1, -1, -1):
string += str(i+1) + ". "
string += self.__history[i]
string += '\n'
return string |
5fe9ed06ba223240c33031393d01250ff0ccac3c | Marcus-Mosley/ICS3U-Unit4-07-Python | /numbers.py | 603 | 4.09375 | 4 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on October 2020
# This program states all integers from 1000 to 2000
def main():
# This function states all integers from 1000 to 2000
# Input
counter = 0
# Process & Output
print("Here are all integers 1000 to 2000:")
print("")
for counter in range(1000, 2001):
if counter % 5 == 0:
if counter == 2000:
print("2000")
else:
print(counter, counter + 1, counter + 2, counter + 3,
counter + 4)
if __name__ == "__main__":
main()
|
f33f356480974c2cb73e997ff780bf8344dbc468 | ani30697/HELLO-PSS | /pract4.py | 161 | 3.859375 | 4 | num=int(input("enter a number of your choice:"))
x= list(range(2,50))
for y in x:
if num%y==0:
print(y)
else:
print("no number available")
|
45be402fa399778a342a55e19e35d9a26ca41fef | MaciejLaczynski/WizualizacjaDanych | /Cw5/Zadanie2-20.04.2020.py | 765 | 3.703125 | 4 | class Ksztalty:
def __init__(self, x, y):
self.x=x
self.y=y
self.opis = "Klasa Kształtów"
def pole(self):
return self.x * self.y
def obwod(self):
return 2 * self.x + 2 * self.y
def wpisz_opis(self, text):
self.opis = text
def skalowanie(self, czynnik):
self.x = self.x * czynnik
self.x = self.y * czynnik
class Kwadrat(Ksztalty):
def __init__(self, x):
self.x =x
self.y=x
def __add__(self,pom):
return self.x + pom.x
figura = Kwadrat(69)
print('Pierwsza figura:', figura.x,'x', figura.y)
figura2 = Kwadrat(420)
print('Druga figura:', figura2.x,'x', figura2.y)
figura3 = Kwadrat(figura + figura2)
print('Trzecia figura:', figura3.x,'x', figura3.y) |
6767f4dee61a6bae62c4c3ac6a7eec227fb198a3 | tryap1/Sudoku-Backtracking | /sudoku.py | 2,525 | 3.8125 | 4 | #Define a SOLVABLE sudoku board
board = [
[0,0,0,0,0,0,0,0,0],
[0,1,5,3,0,9,7,8,0],
[0,4,0,2,0,1,0,6,0],
[0,6,4,7,0,8,1,2,0],
[0,0,0,0,0,0,0,0,0],
[0,3,7,5,0,6,8,4,0],
[0,8,0,4,0,5,0,9,0],
[0,7,9,8,0,2,4,3,0],
[0,0,0,0,0,0,0,0,0]
]
#Sudoku solving function
def sudoku_solve(board):
#reached the end when you can no longer find blanks
if not find_blanks(board):
return True
else:
blank = find_blanks(board)
for i in range(1,10):
#insert potential answer into blank and check if answer is possible
if check_valid(board,i,blank) == True:
#if true insert answer into board
board[blank[0]][blank[1]] = i
#recursively call function to check answer in board
if sudoku_solve(board) == True:
return True
#if cannot solve: wrong answer, go back and reset last blank
else:
board[blank[0]][blank[1]] = 0 #reset the last blank ie backtrack
return False
#function to check validity of input, test is an insertable integer to test, blank is a tupple of pos
def check_valid(board,test,blank):
#check column
for i in range(len(board[0])):
if board[i][blank[1]] == test and blank[0] != i:
return False
#check column
for j in range(len(board)):
if board[blank[0]][j] == test and blank[1] != j:
return False
#check quardrant
quad_col = blank[1]//3
quad_row = blank[0]//3
for i in range(quad_row*3, quad_row*3+3):
for j in range(quad_col*3, quad_col*3+3):
if board[i][j] == test and (i,j) != blank:
return False
return True
#this function takes in a board and returns coordinates of first available blank
def find_blanks(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i,j)
return None
def print_board(board):
for i in range(len(board)):
if i % 3 ==0 and i !=0:
print("____________________")
for j in range(len(board[0])):
if j % 3 ==0 and j !=0:
print("|", end = '')
if j==8:
print(board[i][j])
else:
print(str(board[i][j])+' ', end='')
print_board(board)
print("__________________________")
sudoku_solve(board)
print_board(board) |
5eeffaa304c531ef1b7af40394f4e8c953e1d51c | SeYearSt/Analysis-algorithm | /lab6.py | 393 | 3.890625 | 4 | import random
def insertion_sort(A):
for j in range(1,len(A)):
temp = A[j]
i = j - 1
while (i>= 0 and A[i] > temp):
A[i+1] = A[i]
A[i] = temp
i=i - 1
def main():
size = int(input("Etner size of list: "))
A = [int(random.random()*10) for i in range(size)]
print("A =",A)
insertion_sort(A)
print("A =",A)
|
53e4f07e95344f78079d61bc7ad668ae242f0cce | theomartinsantoso/Kumpulan-Program-Python | /ContohException.py | 189 | 3.53125 | 4 | try:
x = 'Gunadarma'
input1 = input ("Masukan inputan 1 : ")
print x [input1]
except IndexError:
print 'Index tidak ada'
except NameError:
print 'Tidak boleh karakter'
|
b920948b31d211e1aa995b7609141ab11ce46d70 | theomartinsantoso/Kumpulan-Program-Python | /Ujian.py | 3,134 | 3.921875 | 4 | def menu():
print '''
============== MENU =============
1. PROGRAM KALKULATOR
2. PROGRAM LUAS SEGITIGA
3. PROGRAM LUAS PERSEGI
4. PROGRAM GAJI
5. PROGRAM SUHU
6. PROGRAM GANJIL
7. PROGRAM GENAP
8. PROGRAM RANGE
9. PROGRAM KOPI
10. EXIT
================================== '''
pil = input ("Masukkan Pilihan Anda: ")
if pil == 1:
kalkulator()
menu()
elif pil == 2:
segitiga()
menu()
elif pil == 3:
persegi()
menu()
elif pil == 4:
gaji()
menu()
elif pil == 5:
suhu()
menu()
elif pil == 6:
ganjil()
menu()
elif pil == 7:
genap()
menu()
elif pil == 8:
jarak()
menu()
elif pil == 9:
kopi()
menu()
elif pil == 10:
exit()
else:
print "Pilihan Anda Tidak Tersedia"
menu()
def kalkulator():
print "======= PROGRAM KALKULATOR ======="
a = input ("Masukkan Angka 1 : ")
b = input ("Masukkan Angka 2 : ")
print a,'+' ,b, '=',a+b
print a,'-' ,b, '=',a-b
print a,'*' ,b, '=',a*b
print a,'/' ,b, '=',a/b
def segitiga():
print "======= PROGRAM SEGITIGA ======="
a = input ("Masukkan Angka 1: ")
b = input ("Masukkan Angka 2: ")
l = (a*b)/2
print "Luas Segitiga Adalah " ,l
def persegi():
print "======== PROGRAM PERSEGI ========"
s = input ("Masukkan Sisi : ")
l = s*s
print "Luas Persegi Adalah " ,l
def ganjil():
i = 0
for i in range (1,20,i+2):
print i
def genap():
i = 0
for i in range (0,20,i+2):
print i
def jarak():
a = input ("Masukkan Angka : ")
for i in range (0,a) :
print i
def gaji():
print "======= PROGRAM GAJI ======="
a = raw_input ("Nama : ")
b = input ("Jumlah Anak : ")
c = input ("Gaji : ")
t = (b*c*0.1)
g = (c+t)
print ' '
print "Nama : " ,a
print "Jumlah Anak : " ,b
print "Gaji : " ,c
print "Tunjangan : " ,t
print "Gaji Total : " ,g
def suhu():
print "========== PROGRAM SUHU ==========="
c = float (input ("Masukkan Celcius : "))
f = float (input ("Masukkan Fahrenheit : "))
r = float (input ("Masukkan Reamur : "))
k = float (input ("Masukkan Kelvin : "))
print "Hasil Celcius ke Fahrenheit adalah " ,5/9*(f-32)
print "Hasil Celcius ke Kelvin adalah " ,k-273
print "Hasil Celcius ke Reamur adalah " ,(5/4)*r
def kopi():
kopi = ["Torabika Susu","ABC Susu","Good Day","Top Coffe"]
print '''
========= PROGRAM KOPI =======
1. Torabika Susu
2. ABC Susu
3. Good Day
4. Top Coffe
5. Exit
============================== '''
pil = input ("Masukkan Pilihan Anda : ")
if pil == 1:
print kopi[0], "Siap diantar"
elif pil == 2:
print kopi[1], "Siap diantar"
elif pil == 3:
print kopi[2], "Siap diantar"
elif pil == 4:
print kopi[3], "Siap diantar"
elif pil == 5:
exit()
else:
print "Tidak Ada Yang Anda Pilih"
menu()
|
f4d9d333ada3342e7ec6a9cac6d653491e01b0d5 | awahl1/Insight_Project | /Grammar/Baseclasses.py | 1,139 | 3.546875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 13:38:41 2017
@author: alexanderwahl
"""
import random
class Template(object):
def __init__(self):
self.sequence = []
def generate(self):
self.lexicalized_sequence = []
for element in self.sequence:
if issubclass(type(element), Lexicalizer):
self.lexicalized_sequence.extend(element.lexicalize())
elif issubclass(type(element), Expander):
self.lexicalized_sequence.extend(element.expand())
return self.lexicalized_sequence
class Lexicalizer(object):
def __init__(self):
self.all_words = []
def lexicalize(self):
if self.all_words:
return random.sample(self.all_words,1)
else:
return []
class Expander(object):
def __init__(self):
self.all_templates = []
def expand(self):
self.curr_template = random.sample(self.all_templates,1)[0]
return self.curr_template.generate() |
07d8483c17ec09a9731afbf8f50aeead4e6fdc2a | scottgreenup/lum | /main.py | 2,969 | 3.90625 | 4 | #!/usr/bin/env python
"""
Example:
$ ./main.py --choices 10 --list host1 host2 host3 host4 host5 --number 4
['host1', 'host2', 'host3', 'host4']
['host1', 'host2', 'host3', 'host5']
['host1', 'host2', 'host4', 'host5']
['host1', 'host3', 'host4', 'host5']
['host2', 'host3', 'host4', 'host5']
"""
import argparse
import textwrap
parser = argparse.ArgumentParser(
prog="main.py",
description=textwrap.dedent("""\
Produce the top N combinations, sorted by LUM. Normally combinations
would come out as 1234, 1235, 1236, ... however this program wants to
minimise the maximum. Therefore the program produces 1234, 1235, 1245,
1345, 2345, and 1236... Take two adjacent combinations, find the unique
maximum you'll see it is strictly increasing for the wholeset.
"""))
parser.add_argument(
'-c', '--choices',
dest='choices',
type=int,
required=True)
parser.add_argument(
'-n', '--number',
dest='number',
type=int,
required=True)
parser.add_argument(
'-l', '--list',
nargs='+',
dest='list',
required=True)
def generator(ordered, n, choices):
"""Generates the next LUM combination starting with ordered[:n]
ordered - Ascending list of elements
n - The number of elements per combination
choices - The number of choies
run_time = O(choices)
"""
if len(ordered) == n:
yield ordered
return
if len(ordered) < n:
print(
"Can't create combinations of length {} with only {} elements"
.format(n, len(ordered)))
return
y = n
pool = []
results = []
curr = ordered[:n]
counted = 0
while True:
yield list(curr)
counted += 1
if counted >= choices:
return
if not pool or (max(pool) < min(curr)):
if y >= len(ordered):
return
pool.append(ordered[y])
y += 1
# TODO replace pool with ordered set or something
pool = sorted(pool)
index = None
index_smallest = 0
while index is None:
smallest = pool[index_smallest]
for i in range(len(curr)-1, -1, -1):
if curr[i] < smallest:
index = i
break
if index is None:
index_smallest += 1
do_swap(curr, index, pool, index_smallest)
pool = sorted(pool)
for i in range(0, index):
if pool[0] < curr[i]:
do_swap(curr, i, pool, 0)
pool = sorted(pool)
def do_swap(curr, curr_index, pool, pool_index):
a = pool[pool_index]
pool.remove(pool[pool_index])
pool.append(curr[curr_index])
curr[curr_index] = a
if __name__ == '__main__':
args = parser.parse_args()
for result in generator(args.list, args.number, args.choices):
print(result)
|
316843da752d708f6bf325a8e0bf20fac3569caa | ccheng3/Rosalind_Problems | /Python_Village/INI5.py | 780 | 4 | 4 | # Problem Description and Solution Design Notes
#
# Given a file containing at most 1000 lines,
# return a file containing all of the even-numbered lines from the
# original file. (The lines in the file are assumed to be 1-based numbered)
# Solution Design
#
# First, read the file and store each line as an element in a list.
# Even-numbered lines in the original file will then become odd-numbered indices
# in the list.
# Then, write the odd-numbered index elements of the list over to the output file.
filename = 'rosalind_ini5.txt'
with open(filename) as fileobject:
line_list = fileobject.readlines()
with open('INI5_outputfile.txt','w') as outputfile:
for line in line_list:
if (line_list.index(line) % 2 == 1):
outputfile.write(line) |
adc886d69bc57e080f0a5937233cc4d9285f950f | SilverXuz/TextBasedPythonGame | /Game.py | 4,449 | 3.765625 | 4 | import random as r
hp = 0
coins = 0
damage = 0
def printParameters():
print("У тебя {0} жизней, {1} урона и {2} монет.".format(hp, damage, coins))
def printHp():
print("У тебя", hp, "жизней.")
def printCoins():
print("У тебя", coins, "монет.")
def printDamage():
print("У тебя", damage, "урона.")
def meetShop():
global hp
global damage
global coins
def buy(cost):
global coins
if coins >= cost:
coins -= cost
printCoins()
return True
print("У тебя маловато монет!")
return False
weaponLvl = r.randint(1, 3)
weaponDmg = r.randint(1, 5) * weaponLvl
weapons = ["AK-47", "Iron Sword", "Showel", "Flower", "Bow", "Fish"]
weaponRarities = ["Spoiled", "Rare", "Legendary"]
weaponRarity = weaponRarities[weaponLvl - 1]
weaponCost = r.randint(3, 10) * weaponLvl
weapon = r.choice(weapons)
oneHpCost = 5
threeHpCost = 12
print("На пути тебе встретился торговец!")
printParameters()
while input("Что ты будешь делать (зайти/уйти): ").lower() == "зайти":
print("1) Одна единица здоровья -", oneHpCost, "монет;")
print("2) Три единицы здоровья -", threeHpCost, "монет;")
print("3) {0} {1} - {2} монет".format(weaponRarity, weapon, weaponCost))
choice = input("Что хочешь приобрести: ")
if choice == "1":
if buy(oneHpCost):
hp += 1
printHp()
elif choice == "2":
if buy(threeHpCost):
hp += 3
printHp()
elif choice == "3":
if buy(weaponCost):
damage = weaponDmg
printDamage()
else:
print("Я такое не продаю.")
def meetMonster():
global hp
global coins
monsterLvl = r.randint(1, 3)
monsterHp = monsterLvl
monsterDmg = monsterLvl * 2 - 1
monsters = ["Grock", "Clop", "Cholop", "Madrock", "Lilbitch"]
monster = r.choice(monsters)
print("Ты набрел на монстра - {0}, у него {1} уровень, {2} жизней и {3} урона.".format(monster, monsterLvl, monsterHp, monsterDmg))
printParameters()
while monsterHp > 0:
choice = input("Что будешь делать (атака/бег): ").lower()
if choice == "атака":
monsterHp -= damage
print("Ты атаковал монстра и у него осталось", monsterHp, "жизней.")
elif choice == "бег":
chance = r.randint(0, monsterLvl)
if chance == 0:
print("Тебе удалось сбежать с поля боя!")
break
else:
print("Монстр оказался чересчур сильным и догнал тебя...")
else:
continue
if monsterHp > 0:
hp -= monsterDmg
print("Монстр атаковал и у тебя осталось", hp, "жизней.")
if hp <= 0:
break
else:
loot = r.randint(0, 2) + monsterLvl
coins += loot
print("Тебе удалось одолеть монстра, за что ты получил", loot, "монет.")
printCoins()
def initGame(initHp, initCoins, initDamage):
global hp
global coins
global damage
hp = initHp
coins = initCoins
damage = initDamage
print("Ты отправился в странствие навстречу приключениям и опасностям. Удачного путешествия!")
printParameters()
def gameLoop():
situation = r.randint(0, 10)
if situation == 0:
meetShop()
elif situation == 1:
meetMonster()
else:
input("Блуждаем...")
initGame(3, 5, 1)
while True:
gameLoop()
if hp <= 0:
if input("Хочешь начать сначала (да/нет): ").lower() == "да":
initGame(3, 5, 1)
else:
break
|
968b815966af601f07946e4fc0cdc7d7f107fd01 | komararyna/HW3 | /task3.py | 130 | 4.09375 | 4 | a=int(input('insert your number:'))
if a == 0:
print('your number is zero')
else:
print('your number isn`t equal to zero') |
2834050573db40f828573a3a5e88137c4851382e | P-RASHMI/Python-programs | /Functional pgms/QuadraticRoots.py | 979 | 4.3125 | 4 | '''
@Author: Rashmi
@Date: 2021-09-17 19:10:01
@Last Modified by: Rashmi
@Last Modified time: 2021-09-17 19:36:03
@Title : A program that takes a,d,c from quadratic equation and print the roots”
'''
import math
def deriveroots(a,b,c):
"""to calculate roots of quadratic equation
parameter : a,b,c
return value : roots"""
#To find determinent
detrimt = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(detrimt))
if detrimt > 0:
print("real and different")
root1 = (-b + sqrt_val)/(2*a)
root2 = (-b - sqrt_val)/(2*a)
print("roots are: ", root1 , root2 )
elif detrimt == 0:
print("roots are real and same")
print("root is", -b /(2*a))
else:
print("roots are complex")
a = int(input("enter the x* x coefficient"))
b = int(input("enter the x coefficient"))
c = int(input("enter the constant"))
if (a == 0):
print("give the corect quadratic equation")
else:
deriveroots(a,b,c)
|
a40e98c3231f4f3a16e86dfe2eeb9951ae29b05d | P-RASHMI/Python-programs | /oops_sample/Innerclass.py | 764 | 4.5 | 4 | '''
@Author: Rashmi
@Date: 2021-09-20 17:10
@Last Modified by: Rashmi
@Last Modified time: 2021-09-20 17:17
@Title : sample program to perform Concept of inner class and calling inner class values,inner class
'''
class Student:
def __init__(self,name,rollno):
self.name = name
self.rollno = rollno
self.lap = self.Laptop()
def show(self):
print(self.name,self.rollno)
class Laptop:
def __init__(self):
self.brand = 'Dell'
self.cpu = 'i5'
self.ram = 8
print(self.brand,self.cpu,self.ram)
s1 = Student('Rashmi',1)
s2 = Student('Ravali',2)
s1.show()
s1.lap.brand
#other way
lap1 = s1.lap
lap2 = s2.lap
#calling inner class
lap1 = Student.Laptop()
|
2af7aa31f51f43d8d4cdaaaf245833f3c215e9cf | P-RASHMI/Python-programs | /Logicalprogram/gambler.py | 1,715 | 4.3125 | 4 | '''
@Author: Rashmi
@Date: 2021-09-18 23:10
@Last Modified by: Rashmi
@Last Modified time: 2021-09-19 2:17
@Title : Simulates a gambler who start with $stake and place fair $1 bets until
he/she goes broke (i.e. has no money) or reach $goal. Keeps track of the number of
times he/she wins and the number of bets he/she makes.
'''
import random
def gambler(stake,goal,number):
"""Description :to calculate wins, loss and percentage of wins,loss
parameter : stake,goal,number(amount he had,win amount,bets)
printing value : wins loss percentages and wins"""
win_count = 0
loss_count = 0
counter = 0
while (stake > 0 and stake < goal and counter < number):
try:
counter+=1
randum_generated = random.randint(0,1) #if suppose randint(0,1,78) given three parameters generating type error exception
if (randum_generated == 1):
win_count = win_count + 1
stake = stake + 1
else:
loss_count = loss_count + 1
stake = stake - 1
except TypeError as e:
print("error found ", e ) #to find type of exception type(e).__name__
percent_win = (win_count/number)*100
percent_loss = 100-percent_win
print("Number of wins",win_count)
print("win percentage :",percent_win)
print("loss percentage :",percent_loss )
print("Number of times betting done",counter)
if __name__ == '__main__':
stake = int(input("Enter the stake amount :"))
goal = int(input("Enter how much money want to win"))
number = int(input("Enter number of times he want to get involved in betting"))
gambler(stake,goal,number) |
290e75703b068540669951c640dda07edf175a69 | Firtoshkr/Years_of_Experience-VS-Salary | /Years_of_Experience VS Salary.py | 1,575 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
# In[33]:
data = pd.read_csv("C:\\Users\\firto\\jupyter\\salary.csv")
# In[34]:
X = np.array(data['YearsExperience'])
y = np.array(data['Salary'])
# In[35]:
plt.scatter(X,y)
# In[36]:
u = np.mean(X)
std = np.std(X)
X = (X-u)/std
# In[37]:
print(X.shape,y.shape)
x = X.reshape((30,1))
y = y.reshape((30,1))
print(x.shape,y.shape)
# In[79]:
def hypothesis(x,theta):
y_ = theta[1]*x + theta[0]
return y_
def error(x,y,theta):
m,n = x.shape
y_ = hypothesis(x,theta)
err = np.sum((y_-y)**2)
return err/m
def gradient(x,y,theta):
m,n = x.shape
y_ = hypothesis(x,theta)
grad = np.zeros((2,))
grad[0] = np.sum(y_-y)
grad[1] = np.dot(x.T,y_-y)
return grad/m
def gradientDescent(x,y,learning_rate = 0.1,epoch = 300):
m,n = x.shape
grad = np.zeros((2,))
theta = np.zeros((2,))
err = []
for i in range(epoch):
er = error(x,y,theta)
err.append(er)
grad = gradient(x,y,theta)
theta = theta - learning_rate * grad
return err, theta
# In[80]:
err , theta = gradientDescent(x,y)
err
# In[81]:
ypred = theta[1]*x + theta[0]
plt.scatter(x,y,c='green')
plt.plot(x,ypred,c='red')
# In[82]:
def r2score():
Ypred = hypothesis(x,theta)
num = np.sum((y-Ypred)**2)
denom = np.sum((y-y.mean())**2)
score = (1-num/denom)
return score*100
# In[83]:
r2score()
# In[ ]:
|
6e5145040d2cc26b349ed29cfcf259e6bdbfcd3c | kslee9572/stock-prediction | /plot.py | 351 | 3.53125 | 4 | # returns a heat map as a result
import matplotlib.pyplot as plt
import numpy as np
def plot(x_max, y_max, data):
x = np.arange(10, x_max + 1, 10)
y = np.arange(10, y_max + 1, 10)
plot = plt.contourf(x, y, data, cmap=plt.cm.coolwarm)
plt.title("Accuracy")
plt.ylabel("Forecast Days")
plt.xlabel("Timesteps")
plt.show() |
11e3ef41dd81b901834dbd29be56f9657ddbc38e | NJIT-CS490-SP21/project2-sjr52 | /tests/unmocked/unit_tests.py | 5,571 | 4.15625 | 4 | '''
The file is used to do unmocked testing
'''
import unittest
KEY_INPUT = "input"
KEY_EXPECTED = "expected"
KEY_EXPECTED1 = "name_expected"
KEY_EXPECTED2 = "score_expected"
class SplitTestCase(unittest.TestCase):
'''This class is used to extend the unittest.TestCase and performs splitting of the string'''
def setUp(self):
self.success_test_params_one = [{
KEY_INPUT:
"Sunny Abhi",
KEY_EXPECTED: ["Sunny", "Abhi"],
}]
self.success_test_params_two = [{
KEY_INPUT:
"Sunny Abhi SR",
KEY_EXPECTED: ["Sunny", "Abhi", "SR"],
}]
self.success_test_params_three = [{
KEY_INPUT:
"Sunny Abhi SR AR",
KEY_EXPECTED: ["Sunny", "Abhi", "SR", 'AR'],
}]
def test_split_success(self):
'''This function is used to split string and replicates the way it was done in app.py'''
for test in self.success_test_params_one:
actual_result = test[KEY_INPUT].split()
print(actual_result)
expected_result = test[KEY_EXPECTED]
print(expected_result)
self.assertEqual(actual_result[1], expected_result[1])
self.assertEqual(len(actual_result[1]), len(expected_result[1]))
for test in self.success_test_params_two:
actual_result = test[KEY_INPUT].split()
print(actual_result)
expected_result = test[KEY_EXPECTED]
print(expected_result)
self.assertEqual(actual_result[2], expected_result[2])
self.assertEqual(len(actual_result[2]), len(expected_result[2]))
for test in self.success_test_params_three:
actual_result = test[KEY_INPUT].split()
print(actual_result)
expected_result = test[KEY_EXPECTED]
print(expected_result)
self.assertEqual(actual_result[3], expected_result[3])
self.assertEqual(len(actual_result[3]), len(expected_result[3]))
class ScoreCheck(unittest.TestCase):
'''Class extend unittest.TestCase and check if username and score are synchronously stored'''
def setUp(self):
self.success_test_params_user_score_one = [{
KEY_INPUT: {
"Sunny": 101
},
KEY_EXPECTED1: ["Sunny"],
KEY_EXPECTED2: [101],
}]
self.success_test_params_user_score_two = [{
KEY_INPUT: {
"Sunny": 101,
"Abhi": 102
},
KEY_EXPECTED1: ["Sunny", "Abhi"],
KEY_EXPECTED2: [101, 102],
}]
self.success_test_params_user_score_three = [{
KEY_INPUT: {
"Sunny": 101,
"Abhi": 102,
"SR": 99
},
KEY_EXPECTED1: ["Sunny", "Abhi", "SR"],
KEY_EXPECTED2: [101, 102, 99],
}]
self.success_test_params_user_score_four = [{
KEY_INPUT: {
"Sunny": 101,
"Abhi": 102,
"SR": 99,
"AR": 98
},
KEY_EXPECTED1: ["Sunny", "Abhi", "SR", "AR"],
KEY_EXPECTED2: [101, 102, 99, 98],
}]
def test_scores(self):
'''This function checks if the result obtained matches the format shown above'''
for test in self.success_test_params_user_score_one:
actual_result = test[KEY_INPUT]
print(actual_result)
expected_result1 = test[KEY_EXPECTED1]
print(expected_result1)
expected_result2 = test[KEY_EXPECTED2]
print(expected_result2)
self.assertEqual(
list(actual_result.keys())[0], expected_result1[0])
self.assertEqual(actual_result[list(actual_result.keys())[0]],
expected_result2[0])
for test in self.success_test_params_user_score_two:
actual_result = test[KEY_INPUT]
print(actual_result)
expected_result1 = test[KEY_EXPECTED1]
print(expected_result1)
expected_result2 = test[KEY_EXPECTED2]
print(expected_result2)
self.assertEqual(
list(actual_result.keys())[1], expected_result1[1])
self.assertEqual(actual_result[list(actual_result.keys())[1]],
expected_result2[1])
for test in self.success_test_params_user_score_three:
actual_result = test[KEY_INPUT]
print(actual_result)
expected_result1 = test[KEY_EXPECTED1]
print(expected_result1)
expected_result2 = test[KEY_EXPECTED2]
print(expected_result2)
self.assertEqual(
list(actual_result.keys())[2], expected_result1[2])
self.assertEqual(actual_result[list(actual_result.keys())[2]],
expected_result2[2])
for test in self.success_test_params_user_score_four:
actual_result = test[KEY_INPUT]
print(actual_result)
expected_result1 = test[KEY_EXPECTED1]
print(expected_result1)
expected_result2 = test[KEY_EXPECTED2]
print(expected_result2)
self.assertEqual(
list(actual_result.keys())[3], expected_result1[3])
self.assertEqual(actual_result[list(actual_result.keys())[3]],
expected_result2[3])
if __name__ == '__main__':
unittest.main()
|
5313c423050296073aa06aa8cb09a47079920edf | sandhyakopparla/task1exam | /evenodd.py | 237 | 3.984375 | 4 | n1=int(input("enter the num"))
even=[]
odd=[]
def check(n1):
if n1%2==0:
even.append(n1)
else:
odd.append(n1)
check(n1)
if(len(even)>0 and len(odd)<=0):
print(even,"even no")
else:
print(odd,"odd no")
|
416cb191e71588c9e419a7e9b562328c2c925291 | AndresSanchezSanchez/master-ai | /cursoPython/numpy_example.py | 575 | 3.546875 | 4 | # %%
import numpy as np
import time
# %% Clock list vs numpy array
rango = 10000000
list1 = range(rango)
list2 = range(rango)
array1 = np.array(range(rango))
array2 = np.array(range(rango))
start1 = time.time()
result = [x - y for x, y in zip(list1, list2)]
end1 = time.time()
start2 = time.time()
result = array1 - array2
end2 = time.time()
print('List:', end1 - start1)
print('Numpy arrays:', end2 - start2)
# %%
lista = [[1, 2, 3, 4, 5, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 7, 8, 9, 10]]
a = np.array(lista, dtype='float32')
print(a)
|
f304620cb4866239d45abd9e74933815c0d7c5c8 | faseehahmed26/Python-Practice | /currentbill.py | 486 | 4.03125 | 4 | n=int(input("Enter units of Electricity:"))
if n<=50:
cost=n*0.5
#price=(cost+(cost/5))
#print("Cost=",price)
elif(50<n<=150):
cost=(50*0.5)+(n-50)*1.25
#print("Cost=",price)
elif(150<n<=250):
cost=(50*0.5)+(n-50)*1.25+(n-100)*1.75
#price=(cost+(cost/5))
#print("Cost=",price)
elif(n>250):
cost=(50*0.5)+((n-50)*1.25)+((n-100)*1.75)+((n-250)*2.5)
price=(cost+(cost/5))
print("Cost without surplus:",cost)
print("Cost=",price)
|
f48eebdf0a8d5f6dbd4ac0edcf8a4c981cd4fc53 | faseehahmed26/Python-Practice | /repetitionword.py | 72 | 3.75 | 4 | n=str(input("enter word:\n"))
for i in range(200):
print(n,end=" ")
|
e463a3faa5fb416d6e72537ed60a44c07c9932ea | faseehahmed26/Python-Practice | /dictionary.py | 528 | 3.984375 | 4 | """
Write a Python code to store the name and age of the employee of an organisation
in the dictionary from user, where name is "Key" and age is the "value".
Find the number of employees whose age is greater than 25 and display them.
"""
n=int(input("Enter number of persons:"))
l1={}
count=0
for i in range(n):
name=input("enter name:")
age=int(input("enter age:"))
l1[name]=age
print("Employees age greater than 25")
for k,v in l1.items():
if v>25:
count+=1
print(k,v)
print("count =",count)
|
fdfcbcbed691b3d63e86da9952e16e754382cfb4 | faseehahmed26/Python-Practice | /listcommon.py | 143 | 3.828125 | 4 | a=[1,1,2,3,5,8,13,21,34,55,89]
b=[1,2,3,4,5,6,7,8,9,10,11,12,13]
l1=[]
for z in a:
if z in b:
l1.append(z)
print("new list is",l1)
|
ced83d41eba97d0378ac0632fdac951aa786f707 | faseehahmed26/Python-Practice | /sumofdigits.py | 119 | 3.953125 | 4 | n=int(input("Enter number to add sum of digits:\n"))
sum=0
while(n>0):
a=n%10
n=n//10
sum=sum+a
print(sum)
|
c3c0421e340c3bd8f196752426f1bcaa8ef3eb72 | faseehahmed26/Python-Practice | /nptelml0.py | 480 | 3.53125 | 4 | def compute_j(w1,w2):
j= w1**2 +w2**2 +4*w1-6*w2-7
return j
def compute_gradient_w1(w1,w2):
return(2*w1+4)
def compute_gradient_w2(w1,w2):
return(2*w2-6)
w1 = 5
w2 = 5
Alpha = 0.3
for i in range(1000):
j = compute_j(w1,w2)
print("iteration ",i+1)
print('w1=',w1)
print('w2=',w2)
print('j=',j)
oldw1=w1
w1=w1-Alpha*compute_gradient_w1(w1,w2)
w2=w2-Alpha*compute_gradient_w2(oldw1,w2)
|
23bcf2c9399717fb3e0d89281eeba04312162395 | faseehahmed26/Python-Practice | /oop.py | 628 | 4 | 4 | class MyClass:
'''This is my DocString
Example of Class Variable a,Instance variable a
Instantiation,Call Function using object of class
Display'''
a=10 #Class Variable
def __init__(self): #Class Constructor
self.a=100 #Instance Variable
print("Instance variable a=",self.a)
def func(self):#Method in a class
print("Hello")
#Display Class variable
print("Using class name class variable a=",MyClass.a)
Mc1=MyClass() #instantiation
#get address of func() method
print(MyClass.func)
Mc1.func() #Function call using class object Mc1
print(MyClass.__doc__) #Prints the docstring
print(Mc1.a)
|
63b92439468f887c773942dbf97a10f21732ca14 | faseehahmed26/Python-Practice | /loopsintro.py | 207 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 7 09:16:23 2019
@author: abhishekbodapati
"""
count=0
while(count<5):
print('The count is:',count)
count+=1
print("Good Bye!") |
fd95b563863d2ed4ca81a7716abf830dc4aca51c | faseehahmed26/Python-Practice | /factors.py | 115 | 4.0625 | 4 | n=int(input("Enter any number to find factors:"))
for x in range(1,n+1):
if (n%x==0):
print(x,end=" ")
|
829a4118953274b9d8c4f1d3f2fb082d82c49d45 | faseehahmed26/Python-Practice | /armstrongnum.py | 178 | 3.796875 | 4 | a=int(input("Enter number:\n"))
sum=0
x=a
while(a>0):
d=a%10
sum=sum+d*d*d
a=a//10
if (sum==x):
print("Armstrong number")
else:
print("Not Armstrong number")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.