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
e03ee23d27385f92bde5067aa3158823807ac747
ismael-lopezb/employee_class_project
/data_cleaning.py
2,303
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 22 23:20:36 2021 @author: ismaellopezbahena """ #import usefull libraries import pandas as pd import numpy as np #read csv file and get the info df = pd.read_csv('aug_train.csv') df.info() #let's replace the gender missing data with the mode gmode = df.gender.mode()[0] df['gender'].fillna(gmode, inplace=True) #fill missing data in enrolled university with the mode df['enrolled_university'].fillna(df.enrolled_university.mode()[0], inplace=True) #fill eduaction level missing values with the mode df['education_level'].fillna(df.education_level.mode()[0], inplace=True) #let's do the same with major discipline, experience, company size, company type, last new job for column in df.columns: df[column].fillna(df[column].mode()[0], inplace=True) #make sure we don't have more missing data df.info() #let's see relevent experience values df['relevent_experience'].value_counts() #we have two values so let's make 'yes'=relevent experience and 'no'= no relevet experince df['relevent_experience'] = df['relevent_experience'].apply(lambda x: 'Yes' if 'Has relevent experience' in x else 'No') #let's see the unique values of enrolled_university df['enrolled_university'].value_counts() #we have 3 categories so leave it like that. Education level and major values df['education_level'].value_counts() df['major_discipline'].value_counts() #we have 4 categories leave it as well with major discipline. We want experince to be int #remove the < and > from experince df['experience'] = df['experience'].apply(lambda x: x.replace('<', '')) df['experience'] = df['experience'].apply(lambda x: x.replace('>', '')) df['experience'] = df['experience'].astype(int) #lets put compani size in the same format n-m df['company_size'] = df['company_size'].apply(lambda x: x.replace('/', '-')) #we want last-new job be an int df['last_new_job']=df['last_new_job'].apply(lambda x: x.replace('+','')) df['last_new_job']=df['last_new_job'].apply(lambda x: x.replace('>','')) df['last_new_job']=df['last_new_job'].apply(lambda x: x.replace('never','0')) df['last_new_job'] = df['last_new_job'].astype(int) df.info() #we don't have missing values and we get numerical and categorical data. Save it df.to_csv('data_cleaned.csv', index=False)
34880def1217c10482dbbd3c637552fff0035ef3
mishra-ankit-dev/tkinter-chat-automation
/chatApp/gui_chat.py
1,659
3.625
4
# -*- coding:utf-8 -*- import sys import time import signal import socket import select import tkinter from tkinter import * from threading import Thread class client(): """ This class initializes client socket """ def __init__(self, server_ip = '0.0.0.0', server_port = 8081): if len(sys.argv) != 3: print("Correct usage: script, IP address, port number") self.server_ip = server_ip self.server_port = server_port else: self.server_ip = str(sys.argv[1]) self.server_port = int(sys.argv[2]) self.client_socket = socket.socket() self.client_socket.connect((self.server_ip, self.server_port)) self.client_name = input('Enter your NAME : ') #self.client_password = input('Enter your PASSWORD : ') #self.client_info = {} #self.client_info['client_name'] = self.client_name #self.client_info['client_password'] = self.client_password self.client_socket.sendall(self.client_name.encode()) def receive_data(self): """ Receives data continously """ print('Starting receive thread') while True: self.data = self.client_socket.recv(1000) print('server:', self.data) def send_data(self): """ This method sends the message to the server """ while True: self.send_message = input() self.client_socket.sendall(self.send_message.encode()) print('you :', self.send_message) s = client() t = Thread(target = s.receive_data) t.start() s.send_data()
52b60e4bba09587fefd57678440a8afe275b955c
chiachunho/NTNU_OOAD_Homework
/Homework1/Homework1-2/main.py
1,133
3.703125
4
from Triangle import Triangle from Square import Square from Circle import Circle from ShapeDatabse import ShapeDatabase # construct shapes shape1 = Triangle(0, 1, 6) shape2 = Square(2, 2, 4, side_length=2) shape3 = Circle(3, 3, 5, radius=3) shape4 = Circle(2, 3, 3, radius=4) shape5 = Square(1, 2, 1, side_length=5) shape6 = Triangle(3, 1, 2, side_length=6) # construct database db = ShapeDatabase() # append shapes to database db.append(shape1) db.append(shape2) db.append(shape3) db.append(shape4) db.append(shape5) db.append(shape6) # print amount to console print(f'Shape amount in database: {len(db)}') print('') # iterate the database to get shape and print its info out print('Print shape in database:') for shape in db: print(shape) # sort the database print('\nSort shapes in database by z-value.\n') db.sort() print('Print shape in database:') for shape in db: print(shape) # clear database print('\nClear database.\n') db.clear() print(f'Shape amount in database: {len(db)}') if len(db) == 0: print('Database is empty.') # print(db.__shape_list) # shape_list is private variable can't direct access
f0d679d573068b5fc1f2d66b2f0d2c17824c22ed
mdzierzecki/algorithms
/binarytree/Node.py
370
3.53125
4
class Node: def __init__(self, key=None): self.key = key self.left = None self.right = None def set_root(self, key): self.key = key def insert_left(self, new_node): self.left = new_node def insert_right(self, new_node): self.right = new_node def __str__(self): return "{}".format(self.key)
cc0c510075db7641bd5ae83e88c52b248473d999
nik-panekin/pyramid_puzzle
/button.py
1,238
4.09375
4
"""Module for implementation the Button class. """ import pygame from blinking_rect import BlinkingRect class Button(BlinkingRect): """The Button class implements visual rectangular element with a text inside. It can be used for GUI. Public attributes: caption: str (read only) - stores button caption as an identifier. """ def __init__(self, width: int, height: int, color: tuple, text: str, text_color: tuple, font: pygame.font.Font): """Input: width, height, color are the same as for RoundedRect constructor; text - string value for button caption; text_color - tuple(r: int, g: int, b: int) for button caption color representation; font - pygame.font.Font object for drawing text caption. """ super().__init__(width, height, color) self.caption = text self.text_surf = font.render(text, True, text_color) self.text_rect = self.text_surf.get_rect() def draw(self): """Draws the button. """ super().draw() ds = pygame.display.get_surface() self.text_rect.center = self.rect.center ds.blit(self.text_surf, self.text_rect)
1bb64c12a5738bc206746e547ed525089aaf0742
lux563624348/Python_Learn
/basic/OI.py
965
3.796875
4
######################################################################## #### Reading and Writing Files ###### Xiang Li Feb.18.2017 ######################################################################## ######################################################################## ##Module ######################################################################## # f = open(filename, mode) def f_read (filename): f = open (filename, 'r') read_data = float( f.read()) f.close() #print (read_data) return read_data #Mode: 'r' only be read, 't' text mode # 'w' for only writing '+' a disk file for updating (Reading and writing) # 'a' for appending 'U' universal newlines mode ??? # 'r+'reading and writing. # 'b' binary mode For example, 'w+b' # 2D data, t-x def f_write (filename,t,x): #print(len(t)) f = open (filename, 'w') for i in range (len(t)): f.write('%10.5f' % (t[i])) f.write('%10.5f' % (x[i])) f.close()
5ce316ef78144c1268521a913a494eead0b2baee
Yanhenning/python-exercises
/one/test_first_exercise.py
1,213
3.65625
4
from unittest import TestCase from one.first_exercise import return_duplicated_items class FirstExerciseTests(TestCase): def test_return_empty_list_given_an_empty_list(self): duplicated_items = return_duplicated_items([]) self.assertEqual([], duplicated_items) def test_return_empty_list_given_an_array_without_duplicated_items(self): duplicated_items = return_duplicated_items(list(range(20))) self.assertEqual([], duplicated_items) def test_should_return_the_duplicated_items(self): duplicated_items = return_duplicated_items([1, 2, 1, 2, 3, 4]) self.assertEqual([1, 2], duplicated_items) def test_return_duplicated_item_if_it_is_a_dict(self): a = {'a': 1} b = {'b': 2} duplicated_items = return_duplicated_items([a, b, a]) self.assertEqual([a], duplicated_items) def test_return_duplicated_item_if_it_is_a_object(self): class foo: def __init__(self): self.a = 1 self.b = 2 a = {'a': 1} b = {'b': 2} c = foo() duplicated_items = return_duplicated_items([a, b, a]) self.assertEqual([a], duplicated_items)
735e3a6325d2805d14e72615163138df6e79679f
Akawi85/Tiny-Python-Project
/03_picnic/picnic.py
1,477
4.09375
4
#!/usr/bin/env python3 """ Author : Me <ifeanyi.akawi85@gmail.com> Date : 31-10-2020 Purpose: A list of food for picnic! """ import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Picnic game', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('items', metavar='str', help='Item(s) to bring', nargs='+') parser.add_argument('-s', '--sorted', action='store_true', help='sort the items', default=False) return parser.parse_args() # -------------------------------------------------- def main(): """The main program goes here""" args = get_args() items_arg = args.items num_items = len(items_arg) items_arg.sort() if args.sorted else items_arg items_in_picnic = str() if num_items == 1: items_in_picnic = items_arg[0] elif num_items == 2: items_in_picnic = ' and '.join(items_arg) elif num_items > 2: items_arg[-1] = 'and ' + items_arg[-1] items_in_picnic = ', '.join(items_arg) print(f'You are bringing {items_in_picnic}.') # -------------------------------------------------- if __name__ == '__main__': main()
e650ddccebf0c6e1e97ee8c934e7c12948d299ab
BoHyeonPark/test1
/028.py
393
3.546875
4
#!/usr/bin/python3 seq1 = "ATGTTATAG" new_seq = "" seq_dic = {"A":"T","T":"A","C":"G","G":"C"} for i in seq1: new_seq += seq_dic[i] print(seq1) print(new_seq) new_seq1 = "" for i in seq1: if i == "A": new_seq1 += "T" elif i == "T": new_seq1 += "A" elif i == "C": new_seq1 += "G" elif i == "G": new_seq1 += "C" print(seq1) print(new_seq1)
c18490e52668ed9fc558ab7e4c1438dccd72427c
BoHyeonPark/test1
/029.py
207
3.53125
4
#!/usr/bin/python3 seq1 = "ATGTTATAG" print("C" in seq1) for s in seq1: b = (s == "C") #s == "C" -> False print(s,b) if b: break import re p = re.compile("C") m = p.match(seq1) print(m)
cf7706deabaa3e1f59c8bb31bf34980cee4ea881
BoHyeonPark/test1
/014.py
112
3.890625
4
#!/usr/bin/python3 a = input("Enter anything: ") if a.isalpha(): print("alphabet") else: print("digit")
cb8c1db76f1c7184635920f5811c56141929dbbf
BoHyeonPark/test1
/034.py
378
3.96875
4
#!/usr/bin/python3 l = [3,1,1,2,0,0,2,3,3] print(max(l)) print(min(l)) for i in range(0,len(l),1): if i == 0: #set max_val, min_val max_val = l[i] min_val = l[i] else: if max_val < l[i]: max_val = l[i] #max_val change if min_val > l[i]: min_val = l[i] #min_val change print("max:",max_val) print("min:",min_val)
c891cd0f585b21859cfde5ffc0ef3aa77dbf2401
BoHyeonPark/test1
/assignment1_3.py
111
3.515625
4
#!/usr/bin/python3 try: n = input("Enter number: ") print(10/n) except TypeError: print("no zero")
3cada4756c6fd7259becea52725a3b85a0d7c25d
maxalbert/micromagnetic-standard-problem-ferromagnetic-resonance_v3_rewrite
/src/postprocessing/util.py
1,478
3.96875
4
def get_conversion_factor(from_unit, to_unit): """ Return the conversion factor which converts a value given in unit `from_unit` to a value given in unit `to_unit`. Allowed values for `from_unit`, `to_unit` are 's' (= second), 'ns' (= nanosecond), 'Hz' (= Hertz) and 'GHz' (= GigaHertz). An error is raised if a different unit is given. Example: >>> get_conversion_factor('s', 'ns') 1e9 """ allowed_units = ['s', 'ns', 'Hz', 'GHz'] if not set([from_unit, to_unit]).issubset(allowed_units): raise ValueError("Invalid unit: '{}'. Must be one of " + ", ".join(allowed_units)) return {('s', 's'): 1.0, ('s', 'ns'): 1e9, ('ns', 's'): 1e-9, ('ns', 'ns'): 1.0, ('Hz', 'Hz'): 1.0, ('Hz', 'GHz'): 1e-9, ('GHz', 'Hz'): 1e9, ('GHz', 'GHz'): 1.0}[(from_unit, to_unit)] def get_index_of_m_avg_component(component): """ Internal helper function to return the column index for the x/y/z component of the average magnetisation. Note that indices start at 1, not zero, because the first column contains the timesteps. (TODO: This may be different for other data types, though!) """ try: idx = {'x': 1, 'y': 2, 'z': 3}[component] except KeyError: raise ValueError( "Argument 'component' must be one of 'x', 'y', 'z'. " "Got: '{}'".format(component)) return idx
34c657d098bd5e80640c4da17189022219528c7e
zhangchuan92910/cmpt419
/k_nearest_neighbor.py
2,899
3.609375
4
import numpy as np from math import log10, floor from collections import defaultdict import os from utils import * def round_to_1(x): return round(x, -int(floor(log10(abs(x))))) def compute_distances(X1, X2, name="dists"): """Compute the L2 distance between each point in X1 and each point in X2. It's possible to vectorize the computation entirely (i.e. not use any loop). Args: X1: numpy array of shape (M, D) normalized along axis=1 X2: numpy array of shape (N, D) normalized along axis=1 Returns: dists: numpy array of shape (M, N) containing the L2 distances. """ M = X1.shape[0] N = X2.shape[0] assert X1.shape[1] == X2.shape[1] dists = np.zeros((M, N)) print("Computing Distances") if os.path.isfile(name+".npy"): dists = np.load(name+".npy") else: benchmark = int(round_to_1(M)//10) for i in range(len(X1)): for j in range(len(X2)): dists[i,j] = np.linalg.norm(X1[i] - X2[j]) if i % benchmark == 0: print(str(i//benchmark)+"0% complete") np.save(name, dists) print("Distances Computed") return dists def predict_labels(dists, y_train, y_val, k=1): """Given a matrix of distances `dists` between test points and training points, predict a label for each test point based on the `k` nearest neighbors. Args: dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives the distance betwen the ith test point and the jth training point. Returns: y_pred: A numpy array of shape (num_test,) containing predicted labels for the test data, where y[i] is the predicted label for the test point X[i]. """ num_test, num_train = dists.shape y_pred = defaultdict(list) for i in range(num_test): closest_y = y_train[np.argpartition(dists[i], k-1)[:k]] occur = np.bincount(closest_y) top = sorted(enumerate(occur), key=lambda a: a[1], reverse=True) y_pred[y_val[i]].append([cat for cat, _ in top[:3]]) return y_pred def predict_labels_weighted(dists, y_train, y_val, k=1): num_test, num_train = dists.shape y_pred = defaultdict(list) idx_to_cat, _ = get_category_mappings() for i in range(num_test): indices = np.argpartition(dists[i], k-1)[:k] closest = sorted([(y_train[j], dists[i][j]) for j in indices], key=lambda a: a[1]) weights = np.linspace(1.0, 0.0, k) votes = defaultdict(float) for j in range(k): votes[closest[j][0]] += 1.0/np.sqrt(1.0*j+1.0) #1.0/closest[j][1] #1.0/np.sqrt(1.0*j+1.0) #weights[j] top = [(j, votes[j]) for j in sorted(votes, key=votes.get, reverse=True)] y_pred[idx_to_cat[y_val[i]]].append([idx_to_cat[cat] for cat, _ in top[:3]]) return y_pred
56df42f25fc0a3dddd57a8d70c63d7a3a4754900
devmadhuu/Python
/assignment_01/check_substr_in_str.py
308
4.34375
4
## Program to check if a Substring is Present in a Given String: main_str = input ('Enter main string to check substring :') sub_str = input ('Enter substring :') if main_str.index(sub_str) > 0: print('"{sub_str}" is present in main string - "{main_str}"'.format(sub_str = sub_str, main_str = main_str))
92d2b840f03db425aaaedf22ad57d0b291bb79e6
devmadhuu/Python
/assignment_01/odd_in_a_range.py
505
4.375
4
## Program to print Odd number within a given range. start = input ('Enter start number of range:') end = input ('Enter end number of range:') if start.isdigit() and end.isdigit(): start = int(start) end = int(end) if end > start: for num in range(start, end): if num % 2 != 0: print('Number {num} is odd'.format(num = num)) else: print('End number should be greater than start number !!!') else: print('Enter valid start and end range !!!')
020278f3785bb409de5cd0afd67c4ccaf295e011
devmadhuu/Python
/assignment_01/three_number_comparison.py
1,464
4.21875
4
## Program to do number comparison num1 = input('Enter first number :') if num1.isdigit() or (num1.count('-') == 1 and num1.index('-') == 0) or num1.count('.') == 1: num2 = input('Enter second number:') if num2.isdigit() or (num2.count('-') == 1 and num2.index('-') == 0) or num2.count('.') == 1: num3 = input('Enter third number:') if num3.isdigit() or (num3.count('-') == 1 and num3.index('-') == 0) or num3.count('.') == 1: if num1.count('.') == 1 or num2.count('.') == 1 or num3.count('.') == 1: operand1 = float(num1) operand2 = float(num2) operand3 = float(num3) else: operand1 = int(num1) operand2 = int(num2) operand3 = int(num3) if operand1 > operand2 and operand1 > operand3: print('{operand1} is greater than {operand2} and {operand3}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3)) elif operand2 > operand1 and operand2 > operand3: print('{operand2} is greater than {operand1} and {operand3}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3)) else: print('{operand3} is greater than {operand1} and {operand2}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3)) else: print('Enter valid numeric input') else: print('Enter valid numeric input')
bca391936ad2f918c4700dc581de7558dd081f41
devmadhuu/Python
/assignment_01/ljust_rjust_q18.py
409
3.6875
4
my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.' sub_str = 'Peck' index = 0 str_index = -1 replaced_str = '' while my_str[index:]: check_str = my_str[index:index + len(sub_str)] if check_str == sub_str: replaced_str = sub_str.rjust(index+1, '*') replaced_str+=sub_str.ljust(len(my_str) - (index + 1 + len(sub_str)), '*')[len(sub_str):] break index+=1 print(replaced_str)
66c8afbcdd793b3817993abfb904b4ec0111f666
devmadhuu/Python
/assignment_01/factorial.py
410
4.4375
4
## Python program to find the factorial of a number. userinput = input ('Enter number to find the factorial:') if userinput.isdigit() or userinput.find('-') >= 0: userinput = int(userinput) factorial = 1 for num in range (1, userinput + 1): factorial*=num print('Factorial of {a} is {factorial}'.format(a = userinput, factorial = factorial)) else: print('Enter valid numeric input')
83c5184a88d030bfd7d873e728653ac1f0248245
alee86/Informatorio
/Practic/Estructuras de control/Condicionales/desafio04.py
1,195
4.28125
4
''' Tenemos que decidir entre 2 recetas ecológicas. Los ingredientes para cada tipo de receta aparecen a continuación. Ingredientes comunes: Verduras y berenjena. Ingredientes Receta 1: Lentejas y apio. Ingredientes Receta 2: Morrón y Cebolla.. Escribir un programa que pregunte al usuario que tipo de receta desea, y en función de su respuesta le muestre un menú con los ingredientes disponibles para que elija. Solo se puede eligir 3 ingrediente (entre la receta elegida y los comunes.) y el tipo de receta. Al final se debe mostrar por pantalla la receta elegida y todos los ingredientes. ''' ingredientes_receta1 = "Lenjetas y Apio" ingredientes_receta2 = "Morrón y Cebolla" print (""" ******************************* Menu: Receta 1: Lentejas y Apio. Receta 2: Morrón y Cebolla. ******************************* """) receta = int(input("Indique si quiere la receta (1) o (2): ")) comun = int(input("Queres agregar Verduras (1) o Berenjenas (2)?")) if comun == 1: comun = "Verduras" else: comun = "Berenjenas" if receta == 1: receta = ingredientes_receta1 else: receta = ingredientes_receta2 print(f"Su plato tiene los siguientes ingredientes: {comun}, {receta}.")
e4fe2f3a2fcb0f61de0a04aa746de174b64c9256
alee86/Informatorio
/Practic/Estructuras de control/Complementarios/Complementarios4.py
325
3.90625
4
""" Realizar un programa que sea capaz de, habiéndose ingresado dos números m y n, determine si n es divisor de m. """ m = int(input("Ingrese el valor para el numerador ")) n = int(input("Ingrese el valor para el denominador ")) if m%n == 0: print(f"{n} es DIVISOR de {m}") else: print(f"{n} es NO es DIVISOR de {m}")
213dab8cccc5a3d763c4afd329e6a461bb920b01
alee86/Informatorio
/Practic/Estructuras de control/Repetitivas/desafio04.py
973
4.03125
4
''' DESAFÍO 4 Escriba un programa que permita imprimir un tablero Ecológico (verde y blanco) de acuerdo al tamaño indicado. Por ejemplo el gráfico a la izquierda es el resultado de un tamaño: 8x6 import os os.system('color') columna = int(input("ingrese columnas: ")) fila = int(input("ingrese filas: ")) for fila in range(fila): for i in range(columna): if i%2 != 0: print("I", end=" ") else: print("P", end=" ") print() ''' import os os.system('color') columna = int(input("Ingrese numero de columnas: ")) filas = int(input("Ingrese numero de filas : ")) for f in range(filas): if f%2 == 0: #Evaluo que las filas pares inicien con P for c in range(columna): if c%2 == 0: print("\033[1;32;40m[V]", end ="") else: print("\033[93m[B]",end ="") else: #Evaluo que las filas impares inicien con I for c in range(columna): if c%2 == 0: print("\033[1;37;44m[V]", end ="") else: print("\033[91m[B]",end ="") print()
55efa3a71c684d8f68040ef917434b00a2bb589d
alee86/Informatorio
/Practic/Estructuras de control/Condicionales/desafio01.py
793
4.09375
4
''' En nuestro rol de Devs (Programador o Programadora de Software), debemos elaborar un programa en Python que permita emitir un mensaje de acuerdo a lo que una persona ingresa como cantidad de años que viene usando insecticida en su plantación. Si hace 10 o más añoss, debemos emitir el mensaje "Por favor solicite revisión de suelos en su plantación". Si hace menos de 10 años, debemos emitir el mensaje "Intentaremos ayudarte con un nuevo sistema de control de plagas, y cuidaremos el suelo de tu plantación". ''' tiempo = float(input("Ingresa la cantidad de años:")) if tiempo >= 10: print("Por favor solicite revisión de suelos en su plantación") else: print("Intentaremos ayudarte con un nuevo sistema de control de plagas, y cuidaremos el suelo de tu plantación")
90965bb42e72a97fbea66ed53de0feff2eecc19c
alee86/Informatorio
/Practic/Listas/complementarios16.py
1,164
4.03125
4
''' f. Se tiene una lista con los datos de los clientes de una compañía de telefonía celular, los cuales pueden aparecer repetidos en la lista, si tienen registrado más de un número telefónico. La compañía para su próximo aniversario desea enviar un regalo a sus clientes, sin repetir regalos a un mismo cliente. En una lista se almacenan los regalos disponibles en orden. Se desea un programa que cree una nueva lista con los clientes, sin repetir y ordenada. que al final muestre el regalo que le corresponde a cada cliente. ''' lista = ['Ale', 'Edu', 'Ari', 'Car', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada', 'Mauri', 'Dami', 'Fer', 'Ari', 'Car', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada', 'Mauri', 'Ari', 'Car', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada', 'Mauri'] usuarios = [] delivery = [] regalos = ['birra', '$200', '4gb','abrazo', '$500', '2gb','Siga participando', '$200'] for i, element in enumerate(lista): if element not in usuarios: usuarios.append(element) usuarios.sort() for i in usuarios: aux = usuarios[usuarios.index(i)] , regalos[usuarios.index(i)] delivery.append(aux) print(delivery)
e23daf79dd41f1bce58bbaab7858941562be66ef
alee86/Informatorio
/Practic/Listas/complementarios12.py
437
3.9375
4
''' b. Leer una frase y luego invierta el orden de las palabras en la frase. Por Ejemplo: “una imagen vale por mil palabras” debe convertirse en “palabras mil por vale imagen una”. ''' frase = str(input('Ingrese una frase para verla invrertida: ')) lista = frase.split() #el metodo split toma un string y lo divide segun lo que pongas en () creando una lista lista.reverse() for i in lista: print(i, end=" ") #print(palabra)
77329d1eb28a5d3565a346a30047871d2306abc6
alee86/Informatorio
/Practic/Estructuras de control/Repetitivas/desafio01.py
1,484
4.21875
4
''' DESAFÍO 1 Nos han pedido desarrollar una aplicación móvil para reducir comportamientos inadecuados para el ambiente. a) Te toca escribir un programa que simule el proceso de Login. Para ello el programa debe preguntar al usuario la contraseña, y no le permita continuar hasta que la haya ingresado correctamente. b) Modificar el programa anterior para que solamente permita una cantidad fija de intentos. ''' enter_pass ="1" true_pass = "123" user_name = "" intento = 1 enter_user_name = input("Ingresa tu usuario: ") enter_pass = str(input("Ingresa tu pass: ")) if enter_pass == true_pass: print(""" ######################################### Pass correcto... Ingresando a tu cuenta #########################################""") else: print(f"El pass ingresado no es correcto. Tenes 2 intentos más") enter_pass = str(input("Ingresa tu pass: ")) if enter_pass == true_pass: print(""" ######################################### Pass correcto... Ingresando a tu cuenta #########################################""") else: print(f"El pass ingresado no es correcto. Tenes 1 intentos más") enter_pass = str(input("Ingresa tu pass: ")) if enter_pass == true_pass: print(""" ######################################### Pass correcto... Ingresando a tu cuenta #########################################""") else: print(""" ######################### No tenes mas intentos. Tu cuenta esa bloqueada. #########################""")
dd112a464e3c0ad07c28a31b94b693d533f758b3
alee86/Informatorio
/Practic/06distribucionEstudiantes.py
470
3.84375
4
name = "" while name != "quite": name = input("Ingresa tu nombre completo: ").upper() turn = input("ingresa si sos del TT (Turno Tarde) o del TN (Turno Noche): ").upper() letters = "ABCDEFGHIJKLMNÑOPQRSTUVWYZ" ft_letra = name[0] if (letters[0:13].find(ft_letra) >= 0 and turn == "TT") or (letters[13:25].find(ft_letra) >= 0 and turn == "TN"): print(f"El estudiante",name,"pertenece al grupo A") else : print(f"El estudiante",name,"pertenece al grupo B")
5112700bd8249864e978ed76dd52f85586fe848c
alee86/Informatorio
/Practic/Profe y compañeros/Desafio3.py
1,400
4.09375
4
'''Para el uso de fertilizantes es necesario medir cuánto abarca un determinado compuesto en el suelo el cual debe existir en una cantidad de al menos 10% por hectárea, y no debe existir vegetación del tipo MATORRAL. Escribir un programa que determine si es factible la utilización de fertilizantes.''' print("Iniciando programa para calculo de utilización de fertilizantes.") hectarea = bool(int(input("¿Usted ya midio el suelo?\n\t 1- Verdadero \n\t 0- Falso\n"))) if hectarea: compuesto = bool(int(input("¿El compuesto existe en al menos de 10% por hectarea?\n\t 1- Verdadero \n\t 0- Falso\n"))) vegetacion = bool(int(input("¿Existe vegetacion del tipo Matorral?\n\t 1- Verdadero \n\t 0- Falso\n "))) if compuesto and vegetacion: print("El uso de del fertilizante es factible.") elif compuesto and vegetacion: print("Debe exterminar la vegetacion del tipo Matorral para que el fertilizante sea factible. ") elif compuesto and vegetacion: print("Procure que almenos usar el fertilizante cubra un 10", "% " ,"de la hectarea para que sea factible usarlo. ") else: print("Procure que almenos usar el fertilizante cubra un 10", "% " ,"de la hectarea para que sea factible usarlo." ,"\n\t y ", "\n Debe exterminar la vegetacion del tipo Matorral para que el fertilizante sea factible. ") else: print("Mida el suelo primero y luego vuelva a iniciar el programa. ")
2649df22c828074a1eff5bcace5a2bf86dc5db98
alee86/Informatorio
/Practic/numerosPrimos.py
216
3.890625
4
num = int(input("Numero para evaluar: ")) contador = 0 for x in range(num): if num%(x+1) == 0: contador += 1 if contador > 2: print(f"El número {num} NO es primo") else: print(f"El número {num} SI es primo")
dd1eb3db497541007cb6abc22addb58838732c45
bp345sa/Fizz
/Ex 5.py
553
3.53125
4
name = 'Zed A. Shaw' age = 23 # not a lie height = 74 # inches h1 = height * 2.54 weight = 180 # lbs w1 = weight * 0.456 eyes = 'Blue' teeth = 'White' hair = 'Brown' print "Let's talk about %s." % name print "He's %f centimetres tall." % h1 print "He's %f kilograms heavy." % w1 print "Actually that's not too heavy." print "He's got %r eyes and %r" % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth # this line is tricky, try to get it exactly right print "If I add %d, %f, and %f I get %f." % (age, h1, w1, age + h1 + w1)
edff8364358f12b7248f2adb0d61cf18a97c349b
dds-utn/patrones-comunicacion
/corutinas/generator.py
165
3.6875
4
def productor(): n = 0 while True: yield n n += 1 def consumidor(productor): while True: println(productor.next()) consumidor(productor())
372fb0a40da5ea72d757f22ca8ed239abc52910d
CompAero/Genair
/geom/aircraft.py
2,040
3.78125
4
from part import Part __all__ = ['Aircraft'] class Aircraft(Part, dict): ''' An Aircraft is a customized Python dict that acts as root for all the Parts it is composed of. Intended usage -------------- >>> ac = Aircraft(fuselage=fus, wing=wi) >>> ac.items() {'wing': <geom.wing.Wing at <hex(id(wi))>, 'fuselage': <geom.fuselage.Fuselage at <hex(id(fus))>} >>> del ac['wing'] >>> ac['tail'] = tail ''' def __init__(self, *args, **kwargs): ''' Form an Aircraft from Part components. Parameters ---------- args, kwargs = the Parts to constitute the Aircraft with ''' dict.__init__(self, *args, **kwargs) if not all([isinstance(p, Part) for p in self.values()]): raise NonPartComponentDetected() def __repr__(self): ''' Override the object's internal representation. ''' return ('<{}.{} at {}>' .format(self.__module__, self.__class__.__name__, hex(id(self)))) def __setitem__(self, k, v): ''' Make sure v is a Part. ''' if not isinstance(v, Part): raise NonPartComponentDetected() super(Aircraft, self).__setitem__(k, v) def __delitem__(self, k): ''' Unglue the Part before deleting it. ''' self[k].unglue() super(Aircraft, self).__delitem__(k) def blowup(self): ''' Blow up the Aircraft's Parts in the current namespace. ''' IP = get_ipython() for k, v in self.items(): IP.user_ns[k] = v return self.items() def _glue(self): ''' See Part._glue. ''' return [o for P in self.values() for o in P._glue(self)] def _draw(self): ''' See Part._draw. ''' if hasattr(self, 'draw'): return self.draw return [P for P in self.values()] # EXCEPTIONS class AircraftException(Exception): pass class NonPartComponentDetected(AircraftException): pass
1ee513ff7f5aac3fd043c7a907f7339a2348224a
vinvaid1989/training
/datecheck.py
613
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 17 14:20:10 2018 @author: RPS """ import datetime print(datetime.datetime.now().hour) def cutoff(amount): currtime=datetime.datetime.now().hour; if(currtime > 17): print ("tomorrow") else: print ("ok") cutoff(56) # for (key,value) in datelist.items(): # print(("->").join(str(key)+str(value)) # print(key,"=",value) #holidaydates() #import holidays #from datetime import date #holidays(date.today().strftime("%d/%m/%Y")); #holidays('1/1/2018')
a877604bf5f4ed8a8ebb23c4a5e123113084a9cf
Tyshkevichvyacheslav/Lr3
/22.4.py
1,435
4.09375
4
print("Уравнения степени не выше второй — часть 2") def solve(*coefficients): if len(coefficients) == 3: d = coefficients[1] ** 2 - 4 * coefficients[0] * coefficients[2] if coefficients[0] == 0 and coefficients[1] == 0 and coefficients[2] == 0: x = ["all"] elif coefficients[0] == 0 and coefficients[1] == 0: x = '' elif coefficients[0] == 0: x = [-coefficients[2] / coefficients[1]] elif coefficients[1] == 0: x = [(coefficients[2] / coefficients[0]) ** 0.5] elif coefficients[2] == 0: x = [0, -coefficients[1] / coefficients[0]] else: if d == 0: x = [-coefficients[1] / (2 * coefficients[0])] elif d < 0: x = '' else: x = [float((-coefficients[1] + d ** 0.5) / (2 * coefficients[0])), float((-coefficients[1] - d ** 0.5) / (2 * coefficients[0]))] return x elif len(coefficients) == 2: return [-coefficients[1] / coefficients[0]] elif len(coefficients) == 1: if coefficients[0] == 0: return ["all"] else: return [] else: return ["all"] print(sorted(solve(1, 2, 1))) print("___________") print(sorted(solve(1, -3, 2))) input("Press any key to exit") exit(0)
5cb27604af3a7a610dd5c6f0c072d10254141496
Tyshkevichvyacheslav/Lr3
/23.1.py
282
3.625
4
print("Мимикрия") transformation = lambda x: x values = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] transformed_values = list(map(transformation, values)) if values == transformed_values: print('ok') else: print('fail') input("Press any key to exit") exit(0)
e2a854d1e492f741a8eb5746d76e51532edf5e68
Tyshkevichvyacheslav/Lr3
/21.4.py
332
4.09375
4
print("Фрактальный список – 2") def defractalize(fractal): return [x for x in fractal if x is not fractal] fractal = [2, 5] fractal.append(3) fractal.append(9) print(fractal) print("____________") fractal = [2, 5] fractal.append(3) print(fractal) input("Press any key to exit") exit(0)
bb02d54d7e24832e5fac78aed4fc6ae2ab765dc6
CognitiveNetworking/IOT-Malware
/ScoringAndPerformance/stats_calcutaion.py
7,994
3.5
4
''' Program name : stats_calculation.py Author : Manjunath R B This program Calcutes the statistics and generate statistical features. The program calculates statistics per class per feature basis. The program accepts three command line arguments 1. input file name 2. output file name 3. Quartile step value The stats are calculated with and without duplicates. ''' import pandas as pd import numpy as np import sys import matplotlib.pyplot as plt #filename ='C:\\Users\\manjuna\\Desktop\\netmate_files\\CTU-files_9\\csv_files\\42-1\\CTU-IoT-Malware-Capture-42-1.csv' in_filename = sys.argv[1] out_filename = sys.argv[2] perc_step = int(sys.argv[3]) # Reading data from CSV(ignore columns such as srcip,srcport,dstip,dtsport,proto) df = pd.read_csv(in_filename, index_col=0, usecols=lambda column: column not in ['srcip', 'srcport ', 'dstip ', 'dstport ', 'proto ']) newList = list(range(0, 100, perc_step)) perc = [i/100 for i in newList] print(perc) print("Printing the shape of the dataset\n") print(df.shape) print("Printing the index columns\n") print(df.columns) print("printing Classes from the CSV\n") print(df['local-label'].unique().tolist()) #separate out data based on per class basis dict_of_classes = dict(tuple(df.groupby("local-label"))) # for calculating statistics per class per feature with duplicates per column. per_class_data_with_dup=pd.DataFrame() for key,value in dict_of_classes.items(): per_class_stats_data_with_dup = pd.DataFrame(value) i = 0 while i < len(per_class_stats_data_with_dup.columns) -2: #get per column stats using iloc and store with column name as index per_class_data_with_dup[per_class_stats_data_with_dup.columns[i]]=per_class_stats_data_with_dup.iloc[:,i].describe(percentiles = perc) per_class_data_with_dup.loc['range',per_class_stats_data_with_dup.columns[i]] = per_class_data_with_dup.loc['max',per_class_stats_data_with_dup.columns[i]] - per_class_data_with_dup.loc['min',per_class_stats_data_with_dup.columns[i]] per_class_data_with_dup.loc['midrange',per_class_stats_data_with_dup.columns[i]] = (per_class_data_with_dup.loc['max',per_class_stats_data_with_dup.columns[i]] + per_class_data_with_dup.loc['min',per_class_stats_data_with_dup.columns[i]])/2 if per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]] != 0: per_class_data_with_dup.loc['coefVar',per_class_stats_data_with_dup.columns[i]] = per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]] / per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]] else: per_class_data_with_dup.loc['coefVar',per_class_stats_data_with_dup.columns[i]] = 0 per_class_data_with_dup.loc['count_of_min-(mean-sd)',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between(per_class_data_with_dup.loc['min',per_class_stats_data_with_dup.columns[i]], (per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]- per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]])).values) per_class_data_with_dup.loc['count_of_(mean-sd)-mean',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between((per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]- per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]]),per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]).values) per_class_data_with_dup.loc['count_of_mean-(mean+sd)',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between(per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]], (per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]] + per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]])).values) per_class_data_with_dup.loc['count_of_std-max',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between(per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]], per_class_data_with_dup.loc['max',per_class_stats_data_with_dup.columns[i]]).values) i = i +1 # add label column at the end per_class_data_with_dup['label'] = key per_class_data_with_dup.to_csv(out_filename, mode='a') # for calculating statistics per class per feature after removing duplicates per column. per_class_data_without_dup = pd.DataFrame() for key,value in dict_of_classes.items(): per_class_stats_data_without_dup = pd.DataFrame(value) i = 0 while i < len(per_class_stats_data_without_dup.columns) -2: #get per column stats using iloc and store with column name as index per_class_data_without_dup[per_class_stats_data_without_dup.columns[i]]=per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().describe(percentiles = perc) per_class_data_without_dup.loc['range',per_class_stats_data_without_dup.columns[i]] = per_class_data_without_dup.loc['max',per_class_stats_data_without_dup.columns[i]] - per_class_data_without_dup.loc['min',per_class_stats_data_without_dup.columns[i]] per_class_data_without_dup.loc['midrange',per_class_stats_data_without_dup.columns[i]] = (per_class_data_without_dup.loc['max',per_class_stats_data_without_dup.columns[i]] + per_class_data_without_dup.loc['min',per_class_stats_data_without_dup.columns[i]])/2 if per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]] != 0: per_class_data_without_dup.loc['coefVar',per_class_stats_data_without_dup.columns[i]] = per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]] / per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]] else: per_class_data_without_dup.loc['coefVar',per_class_stats_data_without_dup.columns[i]] = 0 per_class_data_without_dup.loc['count_of_min-(mean-sd)',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between(per_class_data_without_dup.loc['min',per_class_stats_data_without_dup.columns[i]], (per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]- per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]])).values) per_class_data_without_dup.loc['count_of_(mean-sd)-mean',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between((per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]- per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]]),per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]).values) per_class_data_without_dup.loc['count_of_mean-(mean+sd)',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between(per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]], (per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]] + per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]])).values) per_class_data_without_dup.loc['count_of_std-max',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between(per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]], per_class_data_without_dup.loc['max',per_class_stats_data_without_dup.columns[i]]).values) i = i +1 # add label column at the end per_class_data_without_dup['label'] = key per_class_data_without_dup.to_csv(out_filename, mode='a') print("DONE\n")
96ee7f84b68f60c999e8450ade3f30ad667b89e8
amark02/ICS4U-Classwork
/Classes/Encapsulation_1.py
665
3.84375
4
class Person: def __init__(self, name: str, age: int): self.set_name(name) self._age = age def get_age(self): #age = time_now - self.date_of_birth return self._age def set_age(self, value: int): self._age = value def get_name(self): return self._first_name + " " + self._last_name def set_name(self, value: str): first, last = value.split(" ") self._first_name = first self._last_name = last # /\ library author's code /\ # \/ OUR CODE \/ VOTING_AGE = 18 p = Person(name = "Jeff Foxworthy", age = 35) if p.get_age() >= VOTING_AGE: print(f"{p.get_name()} can vote")
6d030f79eb3df2a3572eaadb0757401d3a330326
amark02/ICS4U-Classwork
/Quiz2/evaluation.py
2,636
4.25
4
from typing import Dict, List def average(a: float, b: float, c:float) -> float: """Returns the average of 3 numbers. Args: a: A decimal number b: A decimal number c: A decimal number Returns: The average of the 3 numbers as a float """ return (a + b + c)/3 def count_length_of_wood(wood: List[int], wood_length: int) -> int: """Finds how many pieces of wood have a specific board length. Args: wood: A list of integers indicating length of a piece of wood wood_length: An integer that specifices what length of wood a person is looking for Returns: How many pieces of wood there are for a specific board length e.g., wood = [10, 5, 10] wood_length = 10 return 2 """ total = 0 for piece in wood: if piece == wood_length: total += 1 else: None return total def occurance_of_board_length(board_length: List[int]) -> Dict: """Returns a diciontary of the occurances of the length of a board. Args: board_length: A list of integers indicating the length of a piece of wood Returns: Dictionary with the key being the length, and the value being the number of times the length appeares in the list e.g., board_length = [10, 15, 20, 20, 10] return {10: 2, 15: 1, 20: 2} """ occurances = {} for wood_length in board_length: if wood_length in occurances.keys(): occurances[wood_length] += 1 else: occurances[wood_length] = 1 return occurances def get_board_length(board_length: Dict, wood_length: int) -> int: """Finds out how many pieces of wood have a specific board length. Args: board_length: A dictionary with the keys being the board length and the values being the number of boards with that specific length wood_length: An integer that specfies what length of wood a person is looking for Returns: How many pieces of wood there are for a specific board length """ #correct answer for key in board_length.keys(): if key == wood_length: return board_length[key] else: return 0 """ wrong answer: list_of_wood = [] for key in board_length.keys(): list_of_wood.append(key) total = 0 for piece in list_of_wood: if piece == wood_length: total += 1 else: None return total """
5b632636066e777092b375219a7a6cd571619157
amark02/ICS4U-Classwork
/Classes/01_store_data.py
271
4.1875
4
class Person: pass p = Person() p.name = "Jeff" p.eye_color = "Blue" p2 = Person() print(p) print(p.name) print(p.eye_color) """ print(p2.name) gives an error since the object has no attribute of name since you gave the other person an attribute on the fly """
4a1e0cd10aa31c063f1b38f2197e6c640ab0e1d9
robotBaby/linearAlgebrapython
/HW3.py
608
3.671875
4
from numpy import linalg as LA import numpy as np #Question 1 def get_determinant(m): return LA.det(m) ##### Examples #Eg: 1 #a = np.array([[4,3,2], [1,2,6], [5,8,1]]) #print get_determinant(a) #b = np.array([[1, 2], [1, 2]]) #print get_determinant(b)\ #Question 2 def find_area(three_points): m = np.array(three_points) return 0.5 * get_determinant(m) #### Examples #three_points = [[1,0,0], [1,3,0], [1,0,4]] #print find_area(three_points) #Question 3 a = np.array([[4,3,2], [1,2,6], [5,8,1]]) E = LA.eig(a) print "Eigenvalues are " , E[0] print "Corresponding eigenvectors are ", E[1]
012b65d8534f8d52d843fb52bed3e2827ff2d605
doranbae/shinko
/images/playShinko_vanilla.py
6,761
3.640625
4
# +--------------------------+ # | SHINKO | # | Play the mobile game | # +--------------------------+ import numpy as np # set random seed np.random.seed(84) # define variables matrix_min = 1 matrix_max = 5 matrix_width = 5 level_num = 2 shinko_goal = 5 handicap = 1 nox_pre_watch_size = 3 flat_matrix_length = matrix_width * level_num class Play: def __init__(self): """ :self.game_over : Boolean value to determine whether game is over or not :self.reward : Every time you successfully make an addition 5, you gain a reward :self.num_moves : Number of noxes you use to play the game. Given you beat the game, you want to use the smallest possible number of noxes :self.matrix : Initial set of boxes you need to play on :self.flat_matrix : Flattened form of the matrix :self.valid_actions: Simplifying feature not to allow the splitting of the matrix :self.init_nox_list: At the start of each game, you see next noxes up to 3 """ self.game_over = False self.reward = 0 self.num_moves = 0 self.matrix = np.random.randint( low = matrix_min, high = matrix_max, size = (level_num, matrix_width) ) self.flat_matrix = self.matrix.reshape( -1, flat_matrix_length ) self.valid_actions = np.arange( start = flat_matrix_length/2, stop = flat_matrix_length, step = 1, dtype = 'int') self.init_nox_list = np.random.randint( low = matrix_min, high = matrix_max-handicap, size = (nox_pre_watch_size) ) self.win_game = False def gen_nox(self): """ You will be abel to see future noxes up to 3. :return: new additional nox """ new_nox = np.random.randint( low = matrix_min, high = matrix_max-handicap, size = (1) ) return new_nox def find_best_action(self, nox): """ :return: updates self.valid_action_ranking, a list of actions in the order of most reward given """ valid_pairs = [] for valid_action in self.valid_actions: remainder = shinko_goal - self.flat_matrix[0][valid_action] - nox action_remainder_pair = ( valid_action, remainder ) valid_pairs.append(action_remainder_pair) sorted_valid_pairs = sorted(valid_pairs, key = lambda tup: tup[1], reverse = False) self.valid_action_ranking = [pos for (pos, remainder) in sorted_valid_pairs if remainder >= 0] def update_valid_actions(self, action): """ :return: Update self.valid_actions which keeps track of list of list of playable matrix indices """ curr_valid_actions = self.valid_actions # delete the index of the flat matrix which has a value of 5 # (--> not possible to play anymore) del_idx = np.where( curr_valid_actions == action )[0][0] updated_valid_actions = np.delete( curr_valid_actions, del_idx ) # add new index of the flat matrix which became available to play # (--> for example, when one of the box in matrix disappears, # the number underneath becomes playable) new_valid_action = action - matrix_width if new_valid_action >= 0: updated_valid_actions = np.append( updated_valid_actions, new_valid_action ) self.valid_actions = updated_valid_actions def update_matrix(self, nox): """ Updates the matrix based on nox and the best action Updates reward and num_moves Updates self.valid_actions (based on the current action) """ if len( self.valid_action_ranking ) == 0: print( '' ) print( '##################' ) print( ' GAME OVER' ) print( '##################' ) print( ' No more moves_____' ) print( self.flat_matrix.reshape(-1, matrix_width) ) print( ' nox: ', nox ) print( ' Total moves: ', self.num_moves ) self.game_over = True else: # best action is the first action from self.valid_action_ranking best_action = self.valid_action_ranking[0] print( 'Your action: ', best_action ) self.num_moves += 1 self.flat_matrix[ 0, best_action ] = self.flat_matrix[0][ best_action ] + nox if self.flat_matrix[ 0, best_action ] == 5: self.reward += 1 self.update_valid_actions( best_action ) def startGame(self): nox_list = [] nox_list.extend( self.init_nox_list ) print( 'Initializing the matrix________' ) print( self.flat_matrix.reshape(-1, matrix_width) ) print( '-------------------------------' ) while self.game_over == False: print( '( Num moves: {} ) Beat the game when next noxes are: {}'.format( self.num_moves, nox_list )) print( self.flat_matrix.reshape(-1, matrix_width) ) # rank the valid options by reward in self.valid_action_ranking nox = nox_list[0] self.find_best_action(nox) # the machine will always play the best move based on a simple arithmetic rule self.update_matrix(nox) # update nox_list nox_list.extend( list(self.gen_nox()) ) nox_list = nox_list[1: ] if np.all( self.flat_matrix == 5): print( '' ) print( '##################' ) print( ' YOU WIN' ) print( '##################' ) # print( 'Final score: ', self.reward * ( flat_matrix_length /self.num_moves) ) print( 'Total num of moves: ', self.num_moves ) self.game_over = True self.win_game = True print('~*~*~*~*~*~*~*~*~*~*~*~*~*~*') return self.win_game # if __name__ == "__main__": # print( 'Lets play Shinko!' ) # shinko = Play() # shinko.startGame() win_cnt = 0 win_idx = [] for x in range(300): np.random.seed(x) shinko = Play() win = shinko.startGame() if win == True: win_cnt += 1 win_idx.append(x) print( 'Testing done' ) print( 'Win count: {}'.format(win_cnt) )
72f64a3b98ee883737a0ea668eda1151365d72b6
MorHananovitz/CSCI-315-Artificial-Intelligence-through-Deep-Learning
/Assignment2/perceptron.py
1,034
3.515625
4
import numpy as np #Part 1 - Build Your Perceptron (Batch Learning) class Perceptron: def __init__(self,n, m): self.input = n self.output = m self.weight = np.random.random((n+1,m))-0.5 def __str__(self): return str( "This is a Perceptron with %d inputs and %d outputs" % (self.input, self.output)) def test(self, J): return(np.dot(np.transpose(np.append(J, [1])), self.weight) > 0) def train(self,I,T, t=1000): Itrain = np.hstack((I, np.split(np.ones(len(I)), len(I)))) for i in range(t): if i %100 == 0: print("Complete %d / %d Iterations" % (i, t)) dW = np.zeros((self.input + 1, self.output)) for row_I, row_T in zip(Itrain, T): O = np.dot(row_I, self.weight) > 0 D = row_T - O dW = dW + np.outer(row_I, D) self.weight = self.weight + dW / len(Itrain) print() print("Complete %d Iterations" % t)
e2fc0eb8047bbe73f5be60371a03ad388bc7f388
ClaeysKobe/Kobeehhh
/Thuis 3.py
520
3.609375
4
print("*** Welkom bij het kassasysteem ***") broeken = int(input("Hoeveel broeken werden er verkocht? ")) tshirts = int(input("Hoeveel T-shirts werden er verkocht? ")) vesten = int(input("Hoeveel vesten werden er verkocht? ")) prijs_broeken = broeken * 70.5 prijs_tshirts = tshirts * 20.89 prijs_vesten = vesten * 100.3 totaal = prijs_broeken + prijs_tshirts + prijs_vesten print(f"U Kocht: \n\tBroeken: {broeken} stuk(s) \n\tT-Shirts: {tshirts} stuk(s) \n\tVesten: {vesten} stuk(s) \nTotaal te betalen: {totaal: .2f}")
23ee2c8360e32e0334a31da848043cf6187cd636
cosinekitty/astronomy
/demo/python/gravity.py
1,137
4.125
4
#!/usr/bin/env python3 import sys from astronomy import ObserverGravity UsageText = r''' USAGE: gravity.py latitude height Calculates the gravitational acceleration experienced by an observer on the surface of the Earth at the specified latitude (degrees north of the equator) and height (meters above sea level). The output is the gravitational acceleration in m/s^2. ''' if __name__ == '__main__': if len(sys.argv) != 3: print(UsageText) sys.exit(1) latitude = float(sys.argv[1]) if latitude < -90.0 or latitude > +90.0: print("ERROR: Invalid latitude '{}'. Must be a number between -90 and +90.".format(sys.argv[1])) sys.exit(1) height = float(sys.argv[2]) MAX_HEIGHT_METERS = 100000.0 if height < 0.0 or height > MAX_HEIGHT_METERS: print("ERROR: Invalid height '{}'. Must be a number between 0 and {}.".format(sys.argv[1], MAX_HEIGHT_METERS)) sys.exit(1) gravity = ObserverGravity(latitude, height) print("latitude = {:8.4f}, height = {:6.0f}, gravity = {:8.6f}".format(latitude, height, gravity)) sys.exit(0)
6d0702099e71e5065cc3a1bdfeb152995fccdc81
loki2236/Python-Practice
/src/Ej2.py
439
3.71875
4
# # Dada una terna de números naturales que representan al día, al mes y al año de una determinada fecha # Informarla como un solo número natural de 8 dígitoscon la forma(AAAAMMDD). # dd = int(input("Ingrese el dia (2 digitos): ")) mm = int(input("Ingrese el mes (2 digitos): ")) yyyy = int(input("Ingrese el año (4 digitos): ")) intdate = (yyyy*10000) + (mm*100) + dd print("La fecha en formato entero es: ", intdate)
c5c9ed70accfeafc3d4ec07f8e9b9a556ec7143c
Dibyadarshidas/py4e
/open_files and big_count.py
449
3.671875
4
name = input("Enter file:") handle = open(name) counts = dict() bigcount = None bigword = None smallcount = None smallword = None for line in handle: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 #print(counts) for p,q in counts.items(): print(p,q) if bigcount is None or q > bigcount: bigword = p bigcount = q print("Highest Occurrence:",bigword,bigcount)
11575571fe85a08533ad8cfaffcdbd1c4936a8d8
Dibyadarshidas/py4e
/19.09.2020.py
640
3.640625
4
# Sort by values instead of key #c = {'a':10, 'b':1, 'c':22 } #tmp = [] #for k, v in c.items() : # tmp.append((v, k)) #print(tmp) #tmp = sorted(tmp, reverse=True) #print(tmp) # Long Method #fhand =open('words.txt') #counts = {} #for line in fhand: # words = line.split() # for word in words: # counts[word] = counts.get(word, 0) + 1 #lst = [] #for k,v in counts.items(): # newtup = (v, k) # lst.append(newtup) #lst = sorted(lst,reverse=True) #for v,k in lst[:10]: # print(k,v) # Shorter Version #c = {'a': 10 , 'b' : 1 , 'c': 22} #print(sorted([(v,k) for k,v in c.items()],reverse=True))
a7f2d4a9a20c2eb58a04861708ac895baa6156ee
abeltomvarghese/Data-Analysis
/Learning/DataFrames.py
724
3.765625
4
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use("fivethirtyeight") web_stats = {"Day":[1,2,3,4,5,6], "Visitors":[43,34,65,56,29,76], "Bounce Rate": [65,67,78,65,45,52]} #CONVERT TO DATAFRAME df = pd.DataFrame(web_stats) #PRINT THE FIRST FEW VALUES print(df.head()) #PRINT LAST FEW LINES print(df.tail()) #SPECIFY HOW MANY OF THE LAST ITEMS YOU WANT print(df.tail(2)) #SET INDEX FOR THE DATA USING A DATA COLUMN THAT CONNECTS ALL OTHER COLUMNS df.set_index("Day", inplace=True) #INPLACE HELPS US TO MODIFY THE DATAFRAME df[["Visitors", "Bounce Rate"]].plot() #YOU CAN PLOT THE ENTIRE DICTIONARY (VISITORS AND BOUNCE RATE) BY DOING df.plot() plt.show()
b8aa70ebee9c3db49bbc8905f88f0e604734894d
pureforwhite/ToyEncryptionAlgorithm
/main.py
1,729
4.09375
4
#PureForWhite create a string encryption program with Toy Encryption Algorithm #The source code will be in the link description below #Follow me on reddit, subscribe my youtube channel, like this video and share it thanks! #creating decryption function def decryption(s): s = list(s) for i in range(len(s)): if s[i] == "_": s[i] = " " first = s[:len(s)//2] second = s[len(s)//2:] second = second[::-1] result = [" "] * (len(s) + 1) for i in range(len(first)): result[i * 2] = first[i] for j in range(len(second)): result[j * 2 + 1] = second[j] print("".join(result)) #creating encryption function def encryption(s): s = list(s) first = [] second = [] for i in range(len(s)): if s[i] == " ": s[i] = "_" if i % 2 == 0: first.append(s[i]) else: second.append(s[i]) second = second[::-1] print("".join(first) + "".join(second)) #creating the main function def main(): themode = "off" while True: try: print("Current themode:", themode) if themode == "off": themode = input("themode(dec - decryption, enc - encryption)> ") else: s = input("String> ") if s == "#c": themode = "off" elif s == "#q": break elif themode == "dec": print(decryption(s)) elif themode == "enc": print(encryption(s)) print() if themode == "#q": break except: break if __name__ == "__main__": main()
de463c40b80011fd725e2675aa1ab0c4a16cf8c6
joshinihal/dsa
/recursion/basic_problems.py
1,146
3.828125
4
# Write a recursive function which takes an integer # and computes the cumulative sum of 0 to that integer def rec_sum(n): if n == 0: return 0 return n + rec_sum(n-1) rec_sum(10) #------------------------------------------------- # Given an integer, create a function which returns the sum of all the individual digits in that integer. def sum_func(n): if n<1: return 0 return n%10 + sum_func(int(n/10)) sum_func(6577) #-------------------------------------------------- # Create a function called word_split() which takes in a string phrase and a set list_of_words. # The function will then determine if it is possible to split the string in a way in which # words can be made from the list of words. # You can assume the phrase will only contain words found in the dictionary if it is completely splittable. def word_split(s,l,output = None): if output == None: output = [] for word in l: if s.startswith(word): output.append(word) return word_split(s[len(word):],l,output) return output word_split('themanran',['the','ran','man'])
e27d035e4e5e2cb1a95204bcdbccae9237d70eda
joshinihal/dsa
/trees/binary_heap_implementation.py
2,258
3.796875
4
# min heap implementation # https://en.wikipedia.org/wiki/Binary_heap # list has a '0' element at first index(0) i.e. [0,.....] class BinHeap(): def __init__(self): self.heapList = [0] self.currentSize = 0 def perUp(self, i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i = i // 2 # insert by appending at the end of the list def insert(self,k): self.heapList.append(k) self.currentSize = self.currentSize + 1 # since inserting at the end disturbs the heap property, # use percUp to push the newly added element upwards to satisy the heap property self.percUp(self.currentSize) # find the min child for an index , # if min child is smaller than the parent percdown the parent def percDown(self, i): while (i*2) <= self.currentSize: mc = self.minChild(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def minChild(self,i): if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapList[i*2] < self.heapList[i*2+1]: return i * 2 else: return i * 2 + 1 # delete by removing the root since in min heap root is the minimum. def delMin(): rootVal = self.heapList[1] # restore the size self.heapList[1] = self.heapList[self.currentSize] self.currentSize = self.currentSize - 1 self.heapList.pop() # since deleting disturbs the heap size, use percDown to put the min at root self.percDown(1) return rootVal def buildHeap(self,alist): i = len(alist) // 2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while (i > 0): self.percDown(i) i = i - 1
e79076cd45b6280c2046283d9a349620af0f8d70
joshinihal/dsa
/trees/tree_implementation_using_oop.py
1,428
4.21875
4
# Nodes and References Implementation of a Tree # defining a class: # python3 : class BinaryTree() # older than python 3: class BinaryTree(object) class BinaryTree(): def __init__(self,rootObj): # root value is also called key self.key = rootObj self.leftChild = None self.rightChild = None # add new as the left child of root, if a node already exists on left, push it down and make it child's child. def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t # add new as the right child of root, if a node already exists on right, push it down and make it child's child. def insertRight(self,newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getLeftChild(self): return self.leftChild def getRightChild(self): return self.rightChild def setRootValue(self,obj): self.key = obj def getRootValue(self): return self.key r = BinaryTree('a') r.getRootValue() r.insertLeft('b') r.getLeftChild().getRootValue()
4999709b618b6edca8a2e462c4575a56f81a580c
Amit998/python_software_design
/Intro/guess_game.py
1,036
3.78125
4
class GuessNumber: def __init__(self,number,min=0,max=100): self.number = number self.guesses=0 self.min=min self.max=max def get_guess(self): guess=input(f"Please guess a Number ({self.min} - {self.max}) : ") if (self.valid_number(guess)): return int(guess) else: print("please enter a valid number") return self.get_guess() def valid_number(self,str_number): try: number=int(str_number) except : return False return self.min <= number <= self.max def play(self): while True: self.guesses=self.guesses+1 guess=self.get_guess() if (guess < self.number): print("Your Guess Was Under") elif guess > self.number: print("your guess was over") else: break print(f"You guessed it in {self.guesses} guesses") game=GuessNumber(56,0,100) game.play()
2e41ccaf34b9b6d8083df766a3a578418bbf6db0
Khizanag/algorithms
/FooBar/Level 3/Bunny Prisoner Locating/Bunny Prisoner Locating.py
186
3.796875
4
def solution(x, y): H = x + y - 1 n = 1 # value when x = 1 temp = 0 # n increases by temp for i in range(H): n += temp temp += 1 print(n + x - 1) print(solution(3, 2))
6d67c92e324e39b17788d860548bfd23059ca5af
domzhaomathematics/Competitive-Coding-8
/minimum_window_substring.py
2,246
3.53125
4
#Time Complexity: O(s+t), traversal and building hashmaps #Space complexity: O(s+t),length of S and T ''' Evertime we encounter a letter that belongs to T, we append it to a queue and increment the hashmap with that key. We keep a hashmap to check how many times the letter appear in T. If we've found all the letter of T, we check the indices [slow,fast] and check if the length is better than our previous valid window. Then we pop from the queue to get the next position of slow, while decrementing the value that moved from in the hashmap. If the letter count goes below the number of that letter in T, we decrement found, since we need to find that letter again. When fast goes out, we're done. We return the string from the optimal window ''' class Solution: def minWindow(self, s: str, t: str) -> str: if len(t)>len(s): return '' if len(t)==1: for c in s: if c==t: return t return '' letters={c:0 for c in t} letters_freq={c:0 for c in t} for l in t: letters_freq[l]+=1 queue=collections.deque() slow=0 min_=float("inf") window=None while slow<len(s) and s[slow] not in letters: slow=slow+1 if slow==len(s): return '' fast=slow+1 found=1 letters[s[slow]]+=1 was_found=False while fast<len(s): if s[fast] in letters and not was_found: queue.append((fast,s[fast])) if letters[s[fast]]<letters_freq[s[fast]]: found+=1 letters[s[fast]]+=1 if found==len(t): if fast-slow<min_: window=[slow,fast] min_=fast-slow next_slow,next_slow_val=queue.popleft() letters[s[slow]]-=1 if letters[s[slow]]<letters_freq[s[slow]]: found-=1 slow=next_slow was_found=True continue else: was_found=False fast+=1 if not window: return '' return s[window[0]:window[1]+1]
20ac70eaf04d544691436bbd5c6c0f5323ba40f8
rizveeredwan/UID-Generation-Based-On-Polynomial-Hashing
/PhoneticMeasurePerformance/name_generator.py
1,631
3.65625
4
import csv """ ### SEGMENT 1: Name collection ### Taking input of all the names ###### names=[] with open('/home/student/Desktop/PhoneticAccuracyMeasure3/UID-Generation-Based-On-Polynomial-Hashing/TrainingData.csv') as csvFile: csvReader = csv.DictReader(csvFile) for row in csvReader: v=row['name'].split(' ') print(v) for n in v: if(n.strip().upper() not in names): names.append(n.strip().upper()) v=row['father_name'].split(' ') for n in v: if(n.strip().upper() not in names): names.append(n.strip().upper()) v=row['mother_name'].split(' ') for n in v: if(n.strip().upper() not in names): names.append(n.strip().upper()) print(len(names)) names = sorted(names) with open('nameFile.csv','w') as csvFile: csvWriter = csv.writer( csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csvWriter.writerow(['name']) for i in names: print(i) csvWriter.writerow([i]) """ ### SEGMENT 2: AFTER REMOVING UNNECESSARY SYMBOLS names=[] with open('nameFile.csv','r') as csvFile: csvReader=csv.DictReader(csvFile) for row in csvReader: n=row['name'].split(' ') for i in n: #WONT' TAKE NUMBER sp=i.strip() mainName="" for j in sp: if(ord(j)>=ord('A') and ord(j)<=ord('Z')): mainName=mainName+j if(len(mainName)>0 and (mainName not in names)): names.append(mainName) print(mainName) names=sorted(names) with open('nameFile.csv','w') as csvFile: csvWriter = csv.writer( csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csvWriter.writerow(['name']) for i in names: print(i) csvWriter.writerow([i]) print(len(names))
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7
AGriggs1/Labwork-Fall-2017
/hello.py
858
4.125
4
# Intro to Programming # Author: Anthony Griggs # Date: 9/1/17 ################################## # dprint # enables or disables debug printing # Simple function used by many, many programmers, I take no credit for it WHATSOEVER # to enable, simply set bDebugStatements to true! ##NOTE TO SELF: in Python, first letter to booleans are Capitalized bDebugStatements = True def dprint(message): if (bDebugStatements == True): print(message) #Simple function with no specific purpose def main(): iUsr = eval(input("Gimme a number! Not too little, not too big... ")) dprint("This message is for debugging purposes") for i in range(iUsr): #Hmmmm, ideally we don't want a space between (i + 1) and the "!" #GH! Why does Python automatically add spaces? print("Hello instructor", i + 1, "!") print("Good bye!") dprint("End") main()
dbf03069fac82c54e3a158dae1d62b0589440176
jphilippou27/kingmakers_capstone
/data/os2/load_cmte_advanced.py
1,002
3.640625
4
import csv, sqlite3, sys if __name__ == "__main__": conn = sqlite3.connect("os2.db") cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS cmte_advanced;") conn.commit() cur.execute("""CREATE TABLE cmte_advanced ( id TEXT(9), name TEXT(50), parent TEXT(50), cand_id TEXT(9), type TEXT(2), party TEXT(1), interest TEXT(5), sensitive TEXT(1) );""" ) conn.commit() with open("cmte_advanced.txt", errors="ignore") as input: counter = 0 reader = csv.reader(input, delimiter=",", quotechar="|") rows = [(row[1], row[2], row[4], row[7], row[6], row[8], row[9], row[11]) for row in reader] cur.executemany("""INSERT INTO cmte_advanced ( id, name, parent, cand_id, type, party, interest, sensitive ) VALUES (?, ?, ?, ?, ?, ?, ? ,?);""", rows ) conn.commit() conn.close()
4188c44dda65c2849f1ae89fd19eb46b7efffd14
dancing-elf/add2anki
/add2anki/add2anki.py
2,805
3.734375
4
"""Interactively translate and add words to csv file if needed""" import argparse import sys import tempfile import urllib import colorama import pygame import add2anki.cambridge as cambridge def add2anki(): """Translate and add words to csv file if needed""" parser = argparse.ArgumentParser() parser.add_argument('-from', dest='src_lang', help='Source language', required=True) parser.add_argument('-to', dest='dst_lang', help='Destination language', required=True) parser.add_argument('-out', dest='output', help='Destination csv file') args = parser.parse_args() colorama.init(autoreset=True) note = None _print_invitation() for line in sys.stdin: word = line.strip() if not word: pass elif word == 'h': _handle_help() elif word == 'q': sys.exit(0) elif word == 'a': _handle_add(note, args.output) elif word == 's': _handle_sound(note) else: note = _handle_word(word, args.src_lang, args.dst_lang) _print_invitation() def _print_invitation(): """Print invitation for user input""" print() print('Type command or word for translation. ' 'Type "h" for list of possible commands') print('>>> ', end='') def _handle_help(): """Display help""" print('h display this help') print('q exit from add2anki') print('a add note to csv file') print('s play sound for last word') def _handle_add(note, csv_file): """Add note to csv file""" if not note: _warn_none_note() return if not csv_file: print(colorama.Fore.YELLOW + 'csv file not selected') return with open(csv_file, 'a+') as output_file: print(note.word + "\t" + cambridge.to_html(note), file=output_file) def _handle_sound(note): """Play sound for note""" if not note: _warn_none_note() return with tempfile.NamedTemporaryFile() as temp: urllib.request.urlretrieve(note.pronunciation, temp.name) _play_audio(temp.name) def _handle_word(word, src_lang, dst_lang): """Translate word and print it to terminal""" note = None try: note = cambridge.translate(word, src_lang, dst_lang) cambridge.print_note(note) except: print(colorama.Fore.RED + 'Error while handle {}: '.format(word), sys.exc_info()) return note def _play_audio(path): """Play sound with pygame""" pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096) audio = pygame.mixer.Sound(path) audio.play() def _warn_none_note(): print('There is no successfully translated word')
29855d475c40a99d9c99896389b0129981d29131
ochuerta/bolt
/docs/_includes/lesson1-10/Boltdir/site-modules/exercise8/tasks/great_metadata.py
853
3.53125
4
#!/usr/bin/env python """ This script prints the values and types passed to it via standard in. It will return a JSON string with a parameters key containing objects that describe the parameters passed by the user. """ import json import sys def make_serializable(object): if sys.version_info[0] > 2: return object if isinstance(object, unicode): return object.encode('utf-8') else: return object data = json.load(sys.stdin) message = """ Congratulations on writing your metadata! Here are the keys and the values that you passed to this task. """ result = {'message': message, 'parameters': []} for key in data: k = make_serializable(key) v = make_serializable(data[key]) t = type(data[key]).__name__ param = {'key': k, 'value': v, 'type': t} result['parameters'].append(param) print(json.dumps(result))
243f97a94733bea6491fda338ab7831a6e773e4a
solonmoraes/CodigosPythonTurmaDSI
/Exercicio1/segunda atv.py
186
3.9375
4
print("===========Atividade=============") salaTotal = float(input("Informe o quanto recebeu:\n")) horasDia = int(input("Informe suas horas trabalhadas:\n")) print(salaTotal / horasDia)
38445453493bcae3afdfafc93fd6568027dca64d
solonmoraes/CodigosPythonTurmaDSI
/Listas.py
656
4.09375
4
pessoas = ["Fabio","Carlos","Regina","Vanuza"] print(type(pessoas)) print(pessoas) pessoas[1] = "Sergio" # adicionar elementoas pessoas.append("Sarah")# adiciona no final pessoas.insert(2,"Flavio")#adiciona em qualquer lugar for chave, valor in enumerate(pessoas): print(f"{chave:.<5}{valor}") #removendo elementos pessoas.pop()#remove o ultimo elemento pessoas.pop(1)#remove qualquer posiçao pessoas.remove("Flavio") print(pessoas) #copiando listas pessoasBkp = pessoas pessoasBkp.append("jeronimo") print("\n\n",pessoas) print(pessoasBkp,"\n\n") pessoas.clear()#limpa alista del(pessoas)#excluir a variavel ou lista print(pessoas,"\n\n")
079e2d347895e1d1cf900b4772a3ad5902f793d7
solonmoraes/CodigosPythonTurmaDSI
/banco de dados mongo/POO/aula3/conta.py
1,220
3.8125
4
class Conta: def __init__(self, numero, titular, saldo, limite=1000): self.__numero = numero self.__titular = titular self.__saldo = saldo self.__limite = limite def depositar(self, valor): if valor < 0: print("Voce nao pode depositar valor negativo") else: self.__saldo += valor def sacar(self, valor): if valor > self.__saldo: print(f"Voce nao pode sacar este valor, seu saldo e {self.__saldo}") else: self.__saldo -= valor def getSaldo(self): print(f"Seu saldo é {self.__saldo}") # Outra forma de criar getters e setters class Conta2: def __init__(self, numero, titular, saldo, limite=1000): self.__numero = numero self.__titular = titular self.__saldo = saldo self.__limite = limite # decorator # Exibir o saldo @property def saldo(self): return f"O seu saldo é R$ {self.saldo}" #Inserir valores no atributo @saldo.saldo(self, valor): if valor < 0: print ("Voce nao pode depositar valores negativos") else: self.__saldo += Valor: print("Valor depositado com sucesso")
f2794e3c31b085db9b10afa837d6026848ef1318
lucasferreira94/Python-projects
/jogo_da_velha.py
1,175
4.25
4
''' JOGO DA VELHA ''' # ABAIXO ESTAO AS POSIÇÕES DA CERQUILHA theBoard = {'top-L':'', 'top-M':'', 'top-R':'', 'mid-L':'','mid-M':'', 'mid-R':'', 'low-L':'', 'low-M':'', 'low-R':''} print ('Choose one Space per turn') print() print(' top-L'+' top-M'+ ' top-R') print() print(' mid-L'+' mid-M'+ ' mid-R') print() print(' low-L'+' low-M'+ ' low-R ') print() # FUNÇÃO PARA PRINTAR A CERQUILHA NA TELA def printBoard(board): print(board['top-L'] + '|' + board['top-M'] +'|' + board['top-R']) print('+-+-') print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R']) print('+-+-') print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R']) # O JOGO INICIA PELA VEZ DO 'X' turn = 'X' for i in range(9): printBoard(theBoard) print('Turn for ' + turn + '. Move on wich space? ') # INDICA A VEZ DO JOGADOR move = input() # O JOGADOR DEVERÁ COLOCAR A POSIÇÃO QUE QUER JOGAR theBoard[move] = turn # ASSOCIA A JOGADA AO JOGADOR print() # CONDICIONAL PARA REALIZAR A MUDANÇA DE JOGADOR if turn == 'X': turn = 'O' else: turn = 'X' printBoard(theBoard)
a9746ae70ae68aefacd3bb071fae46e949a7e29f
YangYishe/pythonStudy
/src/day8_15/day8_2.py
683
4.40625
4
""" 定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法。 """ class Point: def __init__(self, x, y): self._x = x self._y = y def move(self, x, y): self._x += x self._y += y def distance_between(self, other_point): return ((self._x - other_point._x) ** 2 + (self._y - other_point._y) ** 2) ** 0.5 def desc(self): return '{x:%f,y:%f}' % (self._x, self._y) def main(): p1 = Point(2, 4) p2 = Point(3, 8) p1.move(5, -10) print(p1.desc()) print(p2.desc()) print(f'distance:{p1.distance_between(p2)}') pass if __name__ == '__main__': main()
f12289953bccf14110d3d75acca9b35797bf9b30
YangYishe/pythonStudy
/src/day1_7/day4_3.py
481
3.984375
4
""" 打印如下所示的三角形图案。 """ for i1 in range(1, 6): for i2 in range(1, i1 + 1): print('*', end='') print('') for i1 in range(1, 6): for i2 in range(1, 6): if i2 + i1 <= 5: print(' ', end='') else: print('*', end='') print('') for i1 in range(1, 6): for i2 in range(1, i1 + 5): if i2 <= 5 - i1: print(' ', end='') else: print('*', end='') print('')
5c754378bc33111b88a28b80317c95ba075664a5
YangYishe/pythonStudy
/src/day1_7/day7_6.py
339
3.734375
4
""" 打印杨辉三角。 """ def yhsj(n): arr1=[1,1] for i in range(n-1): arr2=[1] for j in range(i): arr2.append(arr1[j]+arr1[j+1]) arr2.append(1) arr1=arr2 yield arr1 pass def main(): for i in yhsj(10): print(i) pass if __name__ == '__main__': main()
bd49df8de11f36cfc6b881024001c01f6c88348e
benb2611/AmericanAirlines-scraper
/american_airlines.py
16,446
3.828125
4
""" Contains AmericanAirlines class, where help methods and logic for scraping data from American Airlines web site are implemented. (all for educational purposes only!) Check '__init__()' docstring for required parameters. To start scraping - just create instance of AmericanAirlines and use 'run()' method. Example: scraper = AmericanAirlines('mia', 'sfo', '02/12/2018', '02/15/2018') scraper.run() **Note**: this class does little about input data validation, so use 'aa_manager.py' (or your own script) to perform data validation. """ import time import os import json from selenium import webdriver # from selenium.webdriver.chrome.options import Options from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.common.exceptions import NoSuchElementException, ElementNotInteractableException from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup class AmericanAirlines: def __init__(self, departure_airport, destination_airport, departure_date, return_date=None, sleeptime=3, trip_type="round trip", airline="AA", price="lowest", passengers=1, passengers_type=None, daytime="all day", file_path="", file_format="json"): """ :param departure_airport: code of airport from which you ant to depart (3 characters string) :param destination_airport: destination airport code (3 characters string) :param departure_date: date of departure - string with this format 'mm/dd/yyyy' (example: 02/10/2018) :param return_date: date of return - string 'mm/dd/yyyy' (example: 02/17/2018). Only needed, when trip_type="round trip" :param sleeptime: wait time to download starting page :param trip_type: type of the trip - "round trip" - trip to chosen destination and back - "one way" - trip to chosen destination :param airline: service provider - AA - Americans Airlines - ALL - all providers :param price: search by price, default value - "lowest"(doesnt have other options for now) :param passengers: number of passengers(for now supporting only one passenger) :param passengers_type: dictionary of passengers grouped by age corresponding to passengers total number; {1: "adult", 2: "child"} etc. (Not supported for now). :param daytime: return available flights only from chosen time interval(evening, morning). For now, class support only one interval - 'all day' :param file_path: full path to directory, where you want to save flights information(default location - - current directory) :param file_format: format in which data would be saved to a file. Chose from next option: -"json" """ # making Firefox work in headless mode firefox_options = Options() firefox_options.add_argument('-headless') # setting Firefox to use tor proxies # profile = webdriver.FirefoxProfile() # profile.set_preference('network.proxy.type', 1) # profile.set_preference('network.proxy.socks', '127.0.0.1') # profile.set_preference('network.proxy.socks_port', 9150) self.sleeptime = sleeptime self.trip_type = trip_type self.airline = airline self.price = price self.passengers = passengers self.passengers_type = passengers_type self.daytime = daytime self.departure = departure_airport self.destination = destination_airport self.departure_date = departure_date self.return_date = return_date self.file_path = file_path self.file_format = file_format self.driver = webdriver.Firefox(firefox_options=firefox_options) # site has bot protection and easy detect 'default cromedriver'so we using firefox for now # self.driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options) self.driver.get("https://www.aa.com/booking/find-flights") # opening site's search window time.sleep(self.sleeptime) def __del__(self): self.driver.close() def press_accept_cookies(self): """ Method for pressing 'accept button'. When we open site for the first time - they'll ask to accept cookies polices in separate pop-up window. """ try: self.driver.find_element_by_xpath('//div[@aria-describedby="cookieConsentDialog"]//button[@id="cookieConsentAccept"]').click() time.sleep(self.sleeptime) except NoSuchElementException as e: print(e.msg) def _validate_file_format(self): if self.file_format.lower() != "json": return False else: return True def _one_way_trip(self): if self.trip_type.lower() == ("one way" or "oneway"): return True else: return False def _round_trip(self): if self.trip_type.lower() == ("round trip" or "roundtrip"): return True else: return False def select_trip_type(self): """ Method for selecting trip type in search box. Can be "round trip" or "one way" trip """ if self._round_trip(): self.driver.find_element_by_xpath('//li[@aria-controls="roundtrip"]/a').click() time.sleep(0.5) if self._one_way_trip(): self.driver.find_element_by_xpath('//li[@aria-controls="oneway"]/a').click() time.sleep(0.5) def select_airline(self): """ Method for selecting airline provider from search form. Can be "aa" - which represent American Airlines or "all" - which represent all airlines """ if self.airline.lower() == "aa": self.driver.find_element_by_xpath('//select[@id="airline"]/option[@value="AA"]').click() time.sleep(0.5) if self.airline.lower() == "all": self.driver.find_element_by_xpath('//select[@id="airline"]/option[@value="ALL"]').click() time.sleep(0.5) def select_time_of_day(self, form): """ Method for selecting time interval("all day" for now) in which available flights will be returned""" form.find_element_by_xpath('.//option[@value="120001"]').click() @staticmethod def _clear_for_input(input_field, n): """ Method for clearing input field from default data "input_field" - selenium object located with webdriver.find method 'n' - number of characters to be deleted """ for i in range(0, n): input_field.send_keys(Keys.BACKSPACE) def fill_from_form(self): """ Here we filling form 'from' with appropriate airport code""" airport = self.driver.find_element_by_xpath('//input[@id="segments0.origin"]') # clearing form from default text self._clear_for_input(airport, 4) airport.send_keys(self.departure) def fill_destination_form(self): """ Here we filling destination form ith appropriate airport code""" airport = self.driver.find_element_by_xpath('//input[@id="segments0.destination"]') airport.send_keys(self.destination) def fill_date_form(self, selector, date): """ Here we filling departure date form with appropriate date""" self._clear_for_input(selector, 15) selector.send_keys(date) def click_search(self): """Pressing search form "search" button""" self.driver.find_element_by_xpath('//button[@id="flightSearchSubmitBtn"]').click() self._wait_to_load() def check_for_input_error(self): """ Here we checking if error box appeared and if so - terminated execution""" self.driver.refresh() try: self.driver.find_element_by_xpath('//div[@class="message-error margin-bottom"]') raise Exception("Search field was filled wrong") except NoSuchElementException: pass try: self.driver.find_element_by_xpath('//head/meta[@name="ROBOTS"]') # text = self.driver.find_element_by_xpath('//body//div[@class="outerContainer"]/p[1]').text # if text.strip() == "We're working on our site": raise Exception("Bot was detected!") except NoSuchElementException: pass def _wait_to_load(self): """ private method for waiting until 'loading' indicator gone""" time.sleep(0.5) # initializing timer for 10 sec (means: don't ait for page to load if its tale more than 10 sec) timer = time.time() + 10 while True: try: # this is loading indicator self.driver.find_element_by_xpath('//div[@class="aa-busy-module"]') if time.time() > timer: break time.sleep(0.5) except NoSuchElementException: break time.sleep(0.5) def fully_load_results(self): """ Here we trying to load results, hidden by 'show more' button/link """ # initial wait to load a result page time.sleep(self.sleeptime) while True: try: self.driver.find_element_by_xpath('//a[@class="showmorelink"]').click() time.sleep(0.2) except (NoSuchElementException, ElementNotInteractableException): break def click_on_round_trip(self): self.driver.find_element_by_xpath('//button[@data-triptype="roundTrip"]').click() self._wait_to_load() def parse_page(self): """Here we scraping flights information from 'search results' page""" flights_list = [] bs = BeautifulSoup(self.driver.page_source, "html.parser") # getting all flight available flights_block = bs.select("li.flight-search-results.js-moreflights") for flight in flights_block: # getting departure and arrival time departure_time = flight['data-departuretime'] arrival_time = flight['data-arrivaltime'] # getting information about amount of stops try: stops = flight.select_one("div.span3 div.flight-duration-stops a.text-underline").get_text() stops = stops.strip() temp = stops.split("\n") stops = temp[0] except AttributeError: stops = "Nonstop" # getting flight number and airplane model flight_numbers_models = [] flight_numbers = flight.select("span.flight-numbers") plane_model = flight.select("span.wrapText") for number, name in zip(flight_numbers, plane_model): temp = {"number": (number.get_text()).strip(), "airplane": (name.get_text()).strip(), } flight_numbers_models.append(temp) # getting lowest price lowest_price = flight['data-tripprice'] # for the case, when we need to book ticket directly at airport if lowest_price == "9999999999": lowest_price = "N/A" # dictionary with information about single flight flight_info = {"depart": departure_time, "arrive": arrival_time, "stops": stops, "price": lowest_price, "details": flight_numbers_models } flights_list.append(flight_info) # # print debugging info # print("Depart at: {} Arrive at: {}".format(departure_time, arrival_time)) # print("Stops: {}".format(stops)) # print("Lowest price: ${}".format(lowest_price)) # print("Flight details:") # for plane in flight_numbers_models: # print(plane) # print("-"*80) return flights_list @staticmethod def _generate_file_name(departure, destination, date, file_format): """ Private method for generating unique file names :param departure: - airport code from where we departure :param destination: - code of destination airport :param date: - date of departure :param file_format: - format of the file we will save or data to """ month, day, year = date.split("/") time_string = time.strftime("%H%M%S") return departure + "_" + destination + year + "-" + month + "-" + day + "-" + time_string + "." + file_format def save_to_json(self, filename, list_of_dict): """ Method to save scraped data to .json file :param filename: unique file name generated by ::method::**_generate_file_name** :param list_of_dict: scraped data, returned by ::method::**parse_page** """ name = os.path.join(self.file_path, filename) with open(name, 'w') as file: json.dump(list_of_dict, file, indent=2) # def _get_my_ip(self): # self.driver.get('https://checkmyip.com/') # my_ip = self.driver.find_element_by_xpath('//tr[1]/td[2]').text # print("My current ip was: {}".format(my_ip)) def run(self): """Here we executing scraping logic""" if not self._validate_file_format(): raise ValueError("Unsupported file format for saving data!") self.press_accept_cookies() self.select_trip_type() self.select_airline() # setting time interval and departure/arrival dates if self._round_trip(): # checking if we have return date filled: if self.return_date is None: raise ValueError("Return date must be filled!") # here we selecting 'time interval' form form1 = self.driver.find_element_by_xpath('//select[@id="segments0.travelTime"]') self.select_time_of_day(form1) depart_form = self.driver.find_element_by_xpath('//input[@id="segments0.travelDate"]') self.fill_date_form(depart_form, self.departure_date) time.sleep(0.5) form2 = self.driver.find_element_by_xpath('//select[@id="segments1.travelTime"]') return_form = self.driver.find_element_by_xpath('//input[@id="segments1.travelDate"]') self.fill_date_form(return_form, self.return_date) self.select_time_of_day(form2) time.sleep(0.5) elif self._one_way_trip(): # selecting 'time interval' form form = self.driver.find_element_by_xpath('//select[@id="segments0.travelTime"]') self.select_time_of_day(form) depart_form = self.driver.find_element_by_xpath('//input[@id="segments0.travelDate"]') self.fill_date_form(depart_form, self.departure_date) time.sleep(0.5) self.fill_from_form() self.fill_destination_form() # all search fields filled, and we beginning the search: self.click_search() self.check_for_input_error() self.fully_load_results() # scraping data from search results: if self._one_way_trip(): list_results = self.parse_page() file_name = self._generate_file_name(self.departure, self.destination, self.departure_date, self.file_format) self.save_to_json(file_name, list_results) # for round trip we need to scrap 2nd search page with returning flights if self._round_trip(): self.click_on_round_trip() self.fully_load_results() list_results2 = self.parse_page() file_name = self._generate_file_name(self.departure, self.destination, self.departure_date, self.file_format) self.save_to_json(file_name, list_results2) time.sleep(0.5) # self._get_my_ip() if __name__ == "__main__": browser = AmericanAirlines('mia', 'sfo', '02/12/2018', '02/15/2018') browser.run()
aab450116da1a0597767e1062274c9088cf8a9ef
damilarey98/user_validation
/user_validation.py
1,813
3.90625
4
import random value = "abcdefghijklmnopqrstuvwxyz1234567890" client_info = {} n = int(input("How many number of users?: ")) #since range begins from 1, when n=2, it request only one value for i in range(1, n): new_client = {} print("Enter first name of user", i, ":") fname = input() print("Enter last name of user", i, ":") lname = input() print("Enter email of user", i, ":") email = input() new_client["FirstName"] = fname new_client["LastName"] = lname new_client["Email"] = email #comb is the combination of strings to form password comb1 = fname[0:2] comb2 = lname[-2:] comb3 = random.sample(value, 5) comb3_str = ''.join([str(elem) for elem in comb3]) password = str(fname[0:2] + lname[-2:] + comb3_str) print("Your password is", password) new_client["Password"] = password #adds new clients to the main container which is printed out at the end of program. new_client_id = len(client_info) + 1 client_info[new_client_id] = new_client like = input("Do you like the password? [y/n]: ") if like == "y".lower(): print("Password is secure.") print("Details of user", i, ":" , new_client) elif like == "n".lower(): while True: new_password = input("Enter preffered password: ") new_client["Password"] = new_password if len(new_password) < 7: print("Your password is not strong. Try again") elif len(new_password) == 7: print("Still not strong enough, length should be more than 7.") else: print("Your new password", new_password) print("Details of user", i, ":", new_client) break; print("Clients added, client infos are now", client_info)
43d06f5cb81bd0e3c924b99164a4526758979052
SanamKhatri/school
/student_update.py
4,554
3.828125
4
import student_database from Student import Student def update_student(): roll_no = int(input("Enter the roll no:")) is_inserted = student_database.getStudentDetails(roll_no) if is_inserted: student_deatail = student_database.getStudentDetails(roll_no) print(student_deatail) print("The detail are") print("Name= " + student_deatail[1]) print("Address= " + student_deatail[2]) #print("Contact No= " + student_deatail[3]) update_menu = """ 1.Only Name 2.Only Address 3.Only Contact No 4.Name and Address 5.Name and Contact 6.Address and Contact 7.Name, Address and Contact""" print(update_menu) update_choice = int(input("Enter the update you want to do")) if update_choice == 1: update_name = input("Enter the name to update:") student_object = Student(name=update_name, address=None, contact_no=None) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") elif update_choice == 2: update_address = input("Enter the address to update:") student_object = Student(name=None, address=update_address, contact_no=None) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") elif update_choice == 3: update_contact_no = input("Enter the Contact No to update:") student_object = Student(name=None, address=None, contact_no=update_contact_no) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") elif update_choice == 4: update_name = input("Enter the name to update:") update_address = input("Enter the address to update:") student_object = Student(name=update_name, address=update_address, contact_no=None) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") elif update_choice == 5: update_name = input("Enter the name to update:") update_contact_no = input("Enter the contact no to update:") student_object = Student(name=update_name, address=None, contact_no=update_contact_no) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") elif update_choice == 6: update_address = input("Enter the address to update:") update_contact_no = input("Enter the contact no to update:") student_object = Student(name=None, address=update_address, contact_no=update_contact_no) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") elif update_choice == 7: update_name = input("Enter the name to update:") update_address = input("Enter the address to update:") update_contact_no = input("Entert the contact no to update") student_object = Student(name=update_name, address=update_address, contact_no=update_contact_no) student_object.setRollNo(student_deatail[0]) is_updated = student_database.update_by_name(student_object) if is_updated: print("The data is updated") else: print("The data is not updated") else: print("The data is not in database")
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7
SanamKhatri/school
/teacher_delete.py
1,234
4.1875
4
import teacher_database from Teacher import Teacher def delete_teacher(): delete_menu=""" 1.By Name 2.By Addeess 3.By Subject """ print(delete_menu) delete_choice=int(input("Enter the delete choice")) if delete_choice==1: delete_name=input("Enter the name of the teacher to delete") t=Teacher(name=delete_name) is_deleted=teacher_database.delete_by_name(t) if is_deleted: print("The data is deleted") else: print("There was error in the process") elif delete_choice==2: delete_address = input("Enter the address of the teacher to delete") t = Teacher(address=delete_address) is_deleted = teacher_database.delete_by_address(t) if is_deleted: print("The data is deleted") else: print("There was error in the process") elif delete_choice==3: delete_subject = input("Enter the subject of the teacher to delete") t = Teacher(subject=delete_subject) is_deleted = teacher_database.delete_by_subject(t) if is_deleted: print("The data is deleted") else: print("There was error in the process")
8103864502cd9649a73788870dabc9ac9cca1c6f
simhaonline/Database-Service-REST-API
/apps/app.py
4,488
3.53125
4
''' SAMPLE DATABASE AS A SERVICE API Register a user with username and password Login a user with username and password A user gets 10 coins by default when registration completed. Every time a user logs in 1 coin is used up. Once all coins are used up the registered user won't be able to log in. ''' from flask import Flask, jsonify, request, make_response from flask_restful import Api, Resource, reqparse from pymongo import MongoClient import bcrypt app = Flask(__name__) api = Api(app) db_client = MongoClient("mongodb://database:27017") database = db_client["Webapp"] users = database["Users"] class ParseData: parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True, help='The username field is required' ) parser.add_argument('password', type=str, required=True, help='The password field is required' ) def user_verification(username, password): if users.find_one({"Username":username}): hashed_password = users.find_one({ "Username":username })["Password"] if bcrypt.hashpw(password.encode('utf-8'), hashed_password) == hashed_password: return True else: return False else: return False def coins_counter(username): coins = users.find_one({ "Username":username })["Coins"] return coins class RegisterUser(Resource): def post(self): posted_data = ParseData.parser.parse_args() username = posted_data['username'] password = posted_data['password'] # Check whether a user with the username already exists if users.find_one({"Username":username}): message = username + " already exists" response = jsonify({"message": message}) resp = make_response(response) resp.headers["Content-Type"] = "application/json" resp.status_code = 422 return resp # Encode and encrypt the password hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) # Register the user with default coins users.insert_one({ "Username":username, "Password":hashed_password, "Coins":10 }) message = "User " + username + " successfully registered" response = jsonify({"message":message}) resp = make_response(response) resp.headers["Content-Type"] = "application/json" resp.status_code = 200 return resp class LoginUser(Resource): def post(self): posted_data = ParseData.parser.parse_args() username = posted_data["username"] password = posted_data["password"] # Verify the username and password verified = user_verification(username, password) if not verified: message = "Invalid username or password" response = jsonify({"message": message}) resp = make_response(response) resp.headers['Content-Type'] = 'application/json' resp.status_code = 422 return resp else: # Check the coins remaining coins_remaining = coins_counter(username) if coins_remaining <= 0: message = "User out of coins. Trial access expired" response = jsonify({"message":message}) resp = make_response(response) resp.headers["Content-Type"] = "application/json" resp.status_code = 402 return resp else: # Remove 1 coin for Logging In users.update({ "Username":username },{ "$set":{ "Coins":coins_remaining - 1 } }) message = "User Logged In" response = jsonify({ "message":message, "account_access_chance_remaining":coins_remaining - 1 }) resp = make_response(response) resp.headers['Content-Type'] = 'application/json' resp.status_code = 200 return resp api.add_resource(RegisterUser, '/register') api.add_resource(LoginUser, '/login') if __name__ == '__main__': app.run(host="0.0.0.0")
551d2c2c5d240929b8289bd9e86c95bd1c599114
DRogalsky/dataVisualizationPythonCC
/dice.py
317
3.625
4
from random import randint class Die: "a class to represent a single die" def __init__(self, num_sides=6): """assume 6 sides""" self.num_sides = num_sides def roll(self): """spit out a random number between 1 and the number of sides""" return randint(1, self.num_sides)
b86433902a7cf3e9dcba2d7f254c4318656ca7f7
heba-ali2030/number_guessing_game
/guess_game.py
2,509
4.1875
4
import random # check validity of user input # 1- check numbers def check_validity(user_guess): while user_guess.isdigit() == False: user_guess = input('please enter a valid number to continue: ') return (int(user_guess)) # 2- check string def check_name(name): while name.isalpha() == False: print('Ooh, Sorry is it your name?!') name = input('Please enter your name: ') return name # begin the game and ask the user to press yes to continue print(f'Are you ready to play this game : Type Yes button to begin: ') play = input(f' Type Yes or Y to continue and Type No or N to exit \n ').lower() if play == 'yes' or play == 'y': # get user name name = check_name(input('Enter your name: \n')) # get the number range from the user first = check_validity(input('enter the first number you want to play: \n first number: ')) last = check_validity(input('enter the last number of range you want to play: \n last number: ')) # tell the user that range print (f'Hello {name}, let\'s begin! the number lies between {first} and {last} \n You have 5 trials') number_to_be_guessed = random.randint(first, last) # print(number_to_be_guessed) # Number of times for the guess game to run run = 1 while run <= 5: run += 1 user_guess = check_validity(input('what is your guess: ')) # if user guess is in the range if user_guess in range(first, last): print('Great beginning, you are inside the right range') # 1- if the user guess is true if user_guess == number_to_be_guessed: print(f'Congratulation, you got it, the number is: {number_to_be_guessed}') break # 2- if the guess is high elif user_guess > number_to_be_guessed: print(f' Try Again! You guessed too high') # 3 - if the guess is small else: print(f'Try Again! You guessed too small') # # if the user guess is out of range else: print (f'You are out of the valid range, you should enter a number from {first} to {last} only!') # # when the number of play is over else: print(f'{name}, Sorry \n <<< Game is over, Good luck next time , the guessed number is {number_to_be_guessed} >>>') # # when user type no: else: print('Waiting to see you again, have a nice day')
f782209a4fb946cb6834f6c60cd33dd93d40b86e
josephevans24/SI106-Files
/ps6.py
13,035
4.09375
4
import test106 as test # this imports the module 106test.py, but lets you refer # to it by the nickname test #### 1. Write three function calls to the function ``give_greeting``: # * one that will return the string ``Hello, SI106!!!`` # * one that will return the string ``Hello, world!!!`` # * and one that will return the string ``Hey, everybody!`` # You may print the return values of those function calls, but you do not have to. def give_greeting(greet_word="Hello",name="SI106",num_exclam=3): final_string = greet_word + ", " + name + "!"*num_exclam return final_string #### DO NOT change the function definition above this line (OK to add comments) # Write your three function calls below print give_greeting() print give_greeting(name = 'world') print give_greeting(greet_word = 'Hey', name = 'everybody', num_exclam = 1) #### 2. Define a function called mult_both whose input is two integers, whose default parameter values are the integers 3 and 4, and whose return value is the two input integers multiplied together. def mult_both(x = 3, y = 4): return x*y print mult_both() print "\n---\n\n" print "Testing whether your function works as expected (calling the function mult_both)" test.testEqual(mult_both(), 12) test.testEqual(mult_both(5,10), 50) #### 3. Use a for loop to print the second element of each tuple in the list ``new_tuple_list``. new_tuple_list = [(1,2),(4, "umbrella"),("chair","hello"),("soda",56.2)] for (x, y) in new_tuple_list: print y #### 4. You can get data from Facebook that has nested structures which represent posts, or users, or various other types of things on Facebook. We won't put any of our actual Facebook group data on this textbook, because it's publicly available on the internet, but here's a structure that is almost exactly the same as the real thing, with fake data. # Notice that the stuff in the variable ``fb_data`` is basically a big nested dictionary, with dictionaries and lists, strings and integers, inside it as keys and values. (Later in the course we'll learn how to get this kind of thing directly FROM facebook, and then it will be a bit more complicated and have real information from our Facebook group.) # Follow the directions in the comments! # first, look through the data structure saved in the variable fb_data to get a sense for it. fb_data = { "data": [ { "id": "2253324325325123432madeup", "from": { "id": "23243152523425madeup", "name": "Jane Smith" }, "to": { "data": [ { "name": "Your Facebook Group", "id": "432542543635453245madeup" } ] }, "message": "This problem might use the accumulation pattern, like many problems do", "type": "status", "created_time": "2014-10-03T02:07:19+0000", "updated_time": "2014-10-03T02:07:19+0000" }, { "id": "2359739457974250975madeup", "from": { "id": "4363684063madeup", "name": "John Smythe" }, "to": { "data": [ { "name": "Your Facebook Group", "id": "432542543635453245madeup" } ] }, "message": "Here is a fun link about programming", "type": "status", "created_time": "2014-10-02T20:12:28+0000", "updated_time": "2014-10-02T20:12:28+0000" }] } # Here are some questions to help you. You don't need to # comment answers to these (we won't grade your answers) # but we suggest doing so! They # may help you think through this big nested data structure. for a in fb_data['data']: print a['from']['name'] for a in fb_data['data'][0]['to']['data']: print a['name'] print fb_data.keys() print [word['from']['name'] for word in fb_data['data']] print 'STOP' # What type is the structure saved in the variable fb_data? #This is a dictionary type with list rooted in it # What type does the expression fb_data["data"] evaluate to? # This evaluates to the list "data" the entire data set is rooted in this list # What about fb_data["data"][1]? # This evaluates to the second list that is nested in the entire dictionary. There are two data list within this and this directs you to the second # What about fb_data["data"][0]["from"]? #this evaluates to a dictionary # What about fb_data["data"][0]["id"]? #This evaluates to a string # Now write a line of code to assign the value of the first # message ("This problem might...") in the big fb_data data # structure to a variable called first_message. Do not hard code your answer! # (That is, write it in terms of fb_data, so that it would work # with any content stored in the variable fb_data that has # the same structure as that of the fb_data we gave you.) first_message = fb_data['data'][0]['message'] print first_message print "testing whether variable first_message was set correctly" test.testEqual(first_message,fb_data["data"][0]["message"]) #### 5. Here's a warm up exercise on defining and calling a function: # Define a function is_prefix that takes two strings and returns # True if the first one is a prefix of the second one, # False otherwise. def is_prefix(x, y): a = list(x) b = list(y) if y.find(x) == 0: return True else: return False # Here's a couple example function calls, printing the return value # to show you what it is. print is_prefix("He","Hello") # should print True print is_prefix("Hi","Hello") # should print False print 'testing whether "Big" is a prefix of "Bigger"' test.testEqual(is_prefix("Big", "Bigger"), True) print 'testing whether "Bigger" is a prefix of "Big"' test.testEqual(is_prefix("Bigger", "Big"), False) #### 6. Now, in the next few questions, you will ll build components and then a complete program that lets people play Hangman. Below is an image from the middle of a game... # Your first task is just to understand the logic of the program, by matching up elements of the flow chart above with elements of the code below. In later problems, you'll fill in a few details that aren't fully implemented here. For this question, write which lines of code go with which lines of the flow chart box, by answering the questions in comments at the bottom of this activecode box. # (Note: you may find it helpful to run this program in order to understand it. It will tell you feedback about your last guess, but won't tell you where the correct letters were or how much health you have. Those are the improvements you'll make in later problems.) def blanked(word, guesses): return "blanked word" def health_prompt(x, y): return "health prompt" def game_state_prompt(txt ="Nothing", h = 6, m_h = 6, word = "HELLO", guesses = ""): res = "\n" + txt + "\n" res = res + health_prompt(h, m_h) + "\n" if guesses != "": res = res + "Guesses so far: " + guesses.upper() + "\n" else: res = res + "No guesses so far" + "\n" res = res + "Word: " + blanked(word, guesses) + "\n" return(res) def main(): max_health = 3 health = max_health secret_word = raw_input("What's the word to guess? (Don't let the player see it!)") secret_word = secret_word.upper() # everything in all capitals to avoid confusion guesses_so_far = "" game_over = False feedback = "let's get started" # Now interactively ask the user to guess while not game_over: prompt = game_state_prompt(feedback, health, max_health, secret_word, guesses_so_far) next_guess = raw_input(prompt) next_guess = next_guess.upper() feedback = "" if len(next_guess) != 1: feedback = "I only understand single letter guesses. Please try again." elif next_guess in guesses_so_far: feedback = "You already guessed that" else: guesses_so_far = guesses_so_far + next_guess if next_guess in secret_word: if blanked(secret_word, guesses_so_far) == secret_word: feedback = "Congratulations" game_over = True else: feedback = "Yes, that letter is in the word" else: # next_guess is not in the word secret_word feedback = "Sorry, " + next_guess + " is not in the word." health = health - 1 if health <= 0: feedback = " Waah, waah, waah. Game over." game_over= True print(feedback) print("The word was..." + secret_word) # What line(s) of code do what's mentioned in box 1? # Line 21 # What line(s) of code do what's mentioned in box 2? # Line 29 # What line(s) of code do what's mentioned in box 3? # Lines 53 and 54 # What line(s) of code do what's mentioned in box 4? # Lines 31 and 32 # What line(s) of code do what's mentioned in box 5? # Line 34 # What line(s) of code do what's mentioned in box 6? # Line 36 # What line(s) of code do what's mentioned in box 7? # Line 39 # What line(s) of code do what's mentioned in box 8? # Line 40 # What line(s) of code do what's mentioned in box 9? # Lines 41-43 # What line(s) of code do what's mentioned in box 10? # Lines 46-48 # What line(s) of code do what's mentioned in box 11? # Lines 49-51 #### 7. The next task you have is to create a correct version of the blanked function: # define the function blanked(). # It takes a word and a string of letters that have been revealed. # It should return a string with the same number of characters as # the original word, but with the unrevealed characters replaced by _ def blanked(word, str): b = "" for a in word: if a in str: b = b + a else: b = b + '_' return b # a sample call to this function: print(blanked("hello", "elj")) #should output _ell_ print "testing blanking of hello when e,l, and j have been guessed" test.testEqual(blanked("hello", "elj"), "_ell_") print "testing blanking of hello when nothing has been guessed" test.testEqual(blanked("hello", ""), "_____") print "testing blanking of ground when r and n have been guessed" test.testEqual(blanked("ground", "rn"), "_r__n_") #### 8. Now you have to create a good version of the health_prompt() function. # define the function health_prompt(). The first parameter is the current # health and the second is the the maximum health you can have. It should return a string # with + signs for the current health, and - signs for the health that has been lost. def health_prompt(h, mh): b = mh - h c = h d = ('+'*c)+('-'*b) return d print(health_prompt(3, 7)) #this should produce the output #health: +++---- print(health_prompt(0, 4)) #this should produce the output #health: ---- print "testing health_prompt(3, 7)" test.testEqual(health_prompt(3,7), "+++----") print "testing health_prompt(0, 4)" test.testEqual(health_prompt(0, 4), "----") #### 9. Now you have a fully functioning hangman program! def blanked(word, str): b = "" for a in word: if a in str: b = b + a else: b = b + '_' return b def health_prompt(h, mh): b = mh - h c = h d = ('+'*c)+('-'*b) return d def game_state_prompt(txt ="Nothing", h = 6, m_h = 6, word = "HELLO", guesses = ""): res = "\n" + txt + "\n" res = res + health_prompt(h, m_h) + "\n" if guesses != "": res = res + "Guesses so far: " + guesses.upper() + "\n" else: res = res + "No guesses so far" + "\n" res = res + "Word: " + blanked(word, guesses) + "\n" return(res) def main(): max_health = 5 health = max_health secret_word = raw_input("What's the word to guess? (Don't let the player see it!)") secret_word = secret_word.upper() # everything in all capitals to avoid confusion guesses_so_far = "" game_over = False feedback = "let's get started" # Now interactively ask the user to guess while not game_over: prompt = game_state_prompt(feedback, health, max_health, secret_word, guesses_so_far) next_guess = raw_input(prompt) next_guess = next_guess.upper() feedback = "" if len(next_guess) != 1: feedback = "I only understand single letter guesses. Please try again." elif next_guess in guesses_so_far: feedback = "You already guessed that" else: guesses_so_far = guesses_so_far + next_guess if next_guess in secret_word: if blanked(secret_word, guesses_so_far) == secret_word: feedback = "Congratulations" game_over = True else: feedback = "Yes, that letter is in the word" else: # next_guess is not in the word secret_word feedback = "Sorry, " + next_guess + " is not in the word." health = health - 1 if health <= 0: feedback = " Waah, waah, waah. Game over." game_over= True print(feedback) print("The word was..." + secret_word) main()
020cea430b8939fef9b71ed4836c8bf85bf2211a
josephevans24/SI106-Files
/Final Project/finalproject.py
18,208
3.6875
4
import test106 as test import csv def collapse_whitespace(txt): # turn newlines and tabs into spaces and collapse multiple spaces to just one space res = "" prev = "" for c in txt: # if not second space in a row, use it if c == " " or prev == " ": res = res + c.replace(" ", "") else: res = res + c # current character will be prev on the next iteration return res class TextInformation: """A class used for helping the user discover simple information about large text files""" def __init__(self, txt_in): self.txt = txt_in def most_freqs_lets(self): if type(self.txt) == type(""): dictionary_wanted_output = {} split = collapse_whitespace(self.txt) for a in split: if a not in dictionary_wanted_output: dictionary_wanted_output[a] = 1 else: dictionary_wanted_output[a] += 1 keys = dictionary_wanted_output.keys() first = keys[0] for b in keys: if dictionary_wanted_output[b] > dictionary_wanted_output[first]: first = b print "%s occurs %d times" % (first, dictionary_wanted_output[first]) elif type(self.txt) == type([]): dictionary_wanted_output = {} for a in self.txt: for b in a: if b not in dictionary_wanted_output: dictionary_wanted_output[b] = 1 else: dictionary_wanted_output[b] += 1 keys = dictionary_wanted_output.keys() first = keys[0] for c in keys: if dictionary_wanted_output[c] > dictionary_wanted_output[first]: first = b print "%s occurs %d times" % (first, dictionary_wanted_output[first]) elif type(self.txt) == type({}): keys = self.txt.keys() first = keys[0] for b in keys: if self.txt[b] > self.txt[first]: first = b print "%s occurs %d times" % (first, self.txt[first]) def most_freqs_word(self): if type(self.txt) == type([]): dictionary_wanted_output = {} for a in self.txt: if a not in dictionary_wanted_output: dictionary_wanted_output[a] = 1 else: dictionary_wanted_output[a] += 1 keys = dictionary_wanted_output.keys() first = keys[0] for b in keys: if dictionary_wanted_output[b] > dictionary_wanted_output[first]: first = b print "%s occurs %d times" % (first, dictionary_wanted_output[first]) elif type(self.txt) == type(""): dictionary_wanted_output = {} split = self.txt.split() for a in split: if a not in dictionary_wanted_output: dictionary_wanted_output[a] = 1 else: dictionary_wanted_output[a] += 1 keys = dictionary_wanted_output.keys() first = keys[0] for b in keys: if dictionary_wanted_output[b] > dictionary_wanted_output[first]: first = b print "%s occurs %d times" % (first, dictionary_wanted_output[first]) elif type(self.txt) == type({}): keys = self.txt.keys() first = keys[0] for b in keys: if self.txt[b] > txt[first]: first = b print "%s occurs %s times" % (first, self.txt[first]) else: print "Can't get the most frequent word" def word_count(self, name): lower_case = self.txt.lower() txt = lower_case.replace("?", "").replace('"', "").replace(".", "").replace("!", "").replace(",", "") new_name = name.lower() count_it = txt.split() accum = len([word for word in count_it if word == new_name]) print "%s occurs %d times" % (name, accum) def top_five(self): dictionary_wanted_output = {} banana = self.txt.split() for a in banana: if a not in dictionary_wanted_output: dictionary_wanted_output[a] = 1 else: dictionary_wanted_output[a] += 1 going = sorted(dictionary_wanted_output.keys(), key = lambda x: dictionary_wanted_output[x], reverse = True) print "For this file the top five most used words are: %s" % (going[:5]) class ShannonGameGuesser: """A Shannon Game Guesser class that can tell you how predictive certain texts are based on another text file the user provides""" def __init__(self, txt_in, guesser_txt_in): self.txt = txt_in self.guesser_txt = guesser_txt_in self.big_dictionary = self.next_letter_frequencies() self.two_letter_big_dictionary = self.more_letter_frequencies() self.letters_sorted_by_frequency = "eothasinrdluymwfgcbpkvjqxz".upper() self.alphabet = self.setUpAlphabet() self.rls = [('.', ' '), (". ", self.letters_sorted_by_frequency), (' ', self.alphabet), (None, self.alphabet)] self.length_of_rules = 0 self.set_up_rules() self.set_up_rules_for_two_letters() def setUpAlphabet(self): """Creates an alphabet of every character in the training data to guess if none of the other rules appeal""" list_of_alphabet = [] for x in self.txt: if x not in list_of_alphabet: list_of_alphabet.append(x) return "".join(sorted(list_of_alphabet)) def next_letter_frequencies(self): """Creates a dictionary of letters and then the frequency of the next letter after""" r = {} #creating a blank dictionary for i in range(len(self.guesser_txt)-1): #iterating through positions in txt up to the last charcter if self.guesser_txt[i] not in r: # if the value of txt[i] not in r (i is an integer) r[self.guesser_txt[i]] = {} #make a new dictionary within the dictionary for that chracter next_letter_freqs = r[self.guesser_txt[i]] #assings the blank dictionary within the dictionary to next_letter_freqs next_letter = self.guesser_txt[i+1] #assings value next letter to be the position after the current character if next_letter not in next_letter_freqs: #if the next letter is not in the dictionary for that letter value... next_letter_freqs[next_letter] = 1 #assing it the value of 1 else: next_letter_freqs[next_letter] = next_letter_freqs[next_letter] + 1 #if the next letter is already in the dictionary of next letters after the current letter add one to that value return r def more_letter_frequencies(self): """Creates a dictionary of the past two letters in a text and frequency of the next letter after""" r = {} #creating a blank dictionary for i in range(len(self.guesser_txt)-1): #iterating through positions in txt up to the last charcter if self.guesser_txt[i-2: i] not in r: # if the value of txt[i] not in r (i is an integer) r[self.guesser_txt[i-2: i]] = {} #make a new dictionary within the dictionary for that chracter next_letter_freqs = r[self.guesser_txt[i-2: i]] #assings the blank dictionary within the dictionary to next_letter_freqs next_letter = self.guesser_txt[i+1] #assings value next letter to be the position after the current character if next_letter not in next_letter_freqs: #if the next letter is not in the dictionary for that letter value... next_letter_freqs[next_letter] = 1 #assing it the value of 1 else: next_letter_freqs[next_letter] = next_letter_freqs[next_letter] + 1 #if the next letter is already in the dictionary of next letters after the current letter add one to that value return r def set_up_rules(self): """Creates tuples to add to the rules and guess for the text were trying to predict""" for key in self.big_dictionary: string_to_append = "" values = self.big_dictionary[key] letter_list = sorted(values.keys(), key = lambda x: values[x], reverse = True) for letter in letter_list: string_to_append += letter tuple_to_insert = (key, string_to_append) self.rls.insert(1,tuple_to_insert) self.length_of_rules = len(self.rls) def set_up_rules_for_two_letters(self): """Creates rules based on what the past two letters are and what to guess next""" for next in self.two_letter_big_dictionary: add_on = "" more = self.two_letter_big_dictionary[next] almost = sorted(more.keys(), key = lambda x: more[x], reverse = True) closer = almost[:15] for lets in almost: add_on += lets tuple_to_insert = (next, add_on) self.rls.insert(self.length_of_rules, tuple_to_insert) def guesser(self, prev_txt): """Guesser function to be used in the performance function to create a string of guesses for the performance function to try""" all_guesses = "" for (suffix, guesses) in self.rls: try: if suffix == None or prev_txt[-len(suffix):] == suffix: all_guesses += guesses except: pass return all_guesses def performance(self): """Shannon Guesser function for how accurate our training data was""" tot = 0 #begins the accumulation for i in range(len(self.txt)-1): #iterate through the lenght of txt up to last character #print txt[:i+1] #print txt[:] to_try = self.guesser(self.txt[:i+1]) #using the guesser function to see if the previous letters used tell us what to guess based on the list rules guess_count = to_try.index(self.txt[i+1]) #Creates an integer for the index of the next letter of txt to iterate if a guess is possible by passing through the guesser function tot = tot + guess_count #Accumulates the total amount of guesses print "%d characters to guess\t%d guesses\t%.2f guesses per character, on average\n" % (len(self.txt) -1, tot, float(tot)/(len(self.txt) -1)) #prints how many characters to guess in the text, #the total amount of guesses needed to correctly predict the txt, and the average amount of guesses needed per charcter def most_freq_return(self): """Returns a numerical instead of a string value in a dictionary""" if type(self.txt) == type({}): keys = self.txt.keys() first = keys[0] for b in keys: if self.txt[b] > self.txt[first]: first = b return first def promptUser(): typeOfFile = "" firstTry = True firstChoicefirstTry = True first_choice = 0 while first_choice != 1 and first_choice != 2: if firstChoicefirstTry: firstChoicefirstTry = False else: print "You must enter a 1 or a 2" first_choice = int(raw_input("Press 1 and Enter if you would like to enter your own text. Press 2 if you would like to use text from a file.\n\n")) if first_choice == 2: while typeOfFile != "CSV" and typeOfFile != "TXT" and typeOfFile != "csv" and typeOfFile != "txt": if firstTry: firstTry = False else: print "You must enter CSV or TXT" typeOfFile = raw_input("Please type the file extension of the file you would like to use: CSV or TXT\n\n") nameOfTextFile = raw_input("Please give me the name of a file.\n\n") text_to_guess = "" if nameOfTextFile.find("csv") == -1 and nameOfTextFile.find("txt") == -1: if typeOfFile.lower() == "csv": opened = open(nameOfTextFile+".csv", "rU") text_to_guess = opened.read() elif typeOfFile.lower() == "txt": opened = open(nameOfTextFile+".txt", "r") text_to_guess = opened.read() else: opened = open(nameOfTextFile, "r") text_to_guess = opened.read() else: text_to_guess = raw_input("Please enter the text you want guessed.\n\n") return text_to_guess def RuleMaker(): filelib = "" firstTry = True firstChoicefirstTry = True first_choice = 0 while first_choice != 1 and first_choice != 2: if firstChoicefirstTry: firstChoicefirstTry = False else: print "You must enter a 1 or a 2" first_choice = int(raw_input(" Now well make the rules! Press 1 if you would like to use your own text or file. Press 2 if you would like to use a file from our library to make your predictive text\n\n")) if first_choice == 2: text_to_choose = raw_input("Enter (t) for a CSV of text messages\nEnter (totc) for a Tale of Two Cities\nEnter (w) for The Wizard of Oz\nEnter (b) to use a Biology Textbook\nEnter (4) for the novel I am Number Four\nEnter (g) for The Great Gatsby in Spanish\nEnter (p) for a Programming Textbook\n\n") text_to_choose =text_to_choose.lower() if text_to_choose == "t": message = open("SItextmessages.csv", "rU") rules = message.read() if text_to_choose == "totc": book = open("Tale of Two Cities.txt", "r") rules = book.read() if text_to_choose == "w": play = open("Wizard of Oz.txt", "r") rules = play.read() if text_to_choose == "b": textbook = open("Biology Textbook.txt", "r") rules = textbook.read() if text_to_choose == "4": novel = open("I am Number Four.txt", "r") rules = novel.read() if text_to_choose == "g": spanish = open("El Gran Gatsby.txt", "r") rules = spanish.read() if text_to_choose == "p": programming = open("Programming Textbook.txt", "r") rules = programming.read() if first_choice == 1: typeOfFile = "" secondTry = True secondChoicesecondTry = True second_choice = 0 while second_choice != 1 and second_choice != 2: if secondChoicesecondTry: secondChoicesecondTry = False else: print "You must enter a 1 or a 2" second_choice = int(raw_input("You've chosen to use your own text or file! Press 1 and Enter if you would like to make rules from your own text. Press 2 if you would like to use text from a file.\n\n")) if second_choice == 2: while typeOfFile != "CSV" and typeOfFile != "TXT" and typeOfFile != "csv" and typeOfFile != "txt": if secondTry: secondTry = False else: print "You must enter CSV or TXT" typeOfFile = raw_input("Please type the file extension of the file you would like to use: CSV or TXT (Make sure the file you choose is in the same directory)\n\n") nameOfTextFile = raw_input("Please give me the name of a file.\n\n") if nameOfTextFile.find("csv") == -1 and nameOfTextFile.find("txt") == -1: if typeOfFile.lower() == "csv": csv_file = open(nameOfTextFile+".csv", "rU") rules = csv_file.read() elif typeOfFile.lower() == "txt": txt_file = open(nameOfTextFile+".txt", "r") rules = txt_file.read() else: opened = open(nameOfTextFile, "r") rules = opened.read() else: rules = raw_input("Please enter the text you want to make your rules from.\n\n") return rules text = promptUser() rules_text = RuleMaker() print "\n\nInitializing the TextInformation class and the methods you can use it for" +'\n\n' First_Instance = TextInformation(text) First_Instance.top_five() First_Instance.most_freqs_word() First_Instance.most_freqs_lets() First_Instance.word_count('Ah') print "\n\nTime to see the accuracy of our Shannon Game Guesser" +'\n\n' gameInstance = ShannonGameGuesser(text, rules_text) gameInstance.performance() print "That's the end of my project, hope you enjoyed it! If you would like to see a variance in accuracy of the guesser, simply change the position of the two letter rules and the initial rules created. Oddly enough, the two letter guesser is not very accurate." Practice_Instance = TextInformation("This is a test string for my SI 106 final project. Let's see what TextInformation we can find out") Testing_Instance = ShannonGameGuesser("This is a test string for my SI 106 final project. Let's see what TextInformation we can find out", rules_text) test.testEqual(type(Practice_Instance.top_five()), type(Practice_Instance.word_count('Hey'))) test.testEqual(type(Testing_Instance.performance()), type(Practice_Instance.most_freqs_lets())) test.testEqual(type(Practice_Instance.most_freqs_word), type(Testing_Instance.performance))
a9a96b6bc344c5a44a45e61e4a947b1e37543e58
ricew4ng/Slim-Typer-v1.0
/code/class_thread_show_time_speed.py
1,721
3.609375
4
#coding:utf8 #显示用时以及计算打字速度的线程的类脚本 import threading import time # 创建此实例时,需要传入一个run_window(QtWidgets.QWidget对象) # running是启动和关闭thread的标志。设置为false,则关闭线程。 class thread_show_time_speed(threading.Thread): def __init__(self,run_window): super(thread_show_time_speed,self).__init__() self.run_window = run_window self.running = True self.waiting = False self.words = 0 #字数初始化 //用于计算打字速度 def run(self): time_start = time.time() self.repeat = True while self.running: if self.waiting == False: seconds = self.time_used(time_start,time.time()) if self.repeat: self.repeat = False else: if self.words > 0: self.words-=1 if seconds: self.run_window.type_speed_set.setText('%.2f0字/秒'%(self.words/seconds)) time.sleep(0.5) #在run_window界面的用时Label处 显示用时 #返回已花的时间(秒) int型 def time_used(self,time1,time2): time_used = time2 - time1 all_seconds = time_used hours_used = int(time_used // 3600 ) time_used = time_used % 3600 minutes_used = int(time_used // 60) seconds_used = int(time_used % 60) time_used = str(hours_used)+'时'+str(minutes_used)+'分'+str(seconds_used)+'秒' self.run_window.time_used_set.setText(time_used) return int(all_seconds) #用于计算英文打字速度 def add_number(self): self.words+=1 #用于计算汉字打字速度 def add_type_number(self,num): self.words+=num #用于终止线程运行及self.words初始化 def terminate(self): self.words = 0 self.running = False def wait(self): self.waiting = True
67df8cb2c8409510d9b0d1f0c859402db1993e93
aswarth123/DevoWorm
/parse-beautiful-stone-soup.py
298
3.515625
4
import lxml.etree as ET // uses lxml for parsing content = "data.xml" doc = ET.fromstring(content) data = doc.find('data of interest') //tag that defines source of data print(data.text) info = doc.find('information') //tag that defines metadata print(info.tail) outfile = "test.txt" FILE.close
3fa0e6d1bdde0a4086107ec9e84d37a3a1f78d73
ColgateLeoAscenzi/COMPUTERSCIENCE101
/HOMEWORK/hw2_volcano.py
1,104
4.03125
4
# ---------------------------------------------------------- # HW 2 PROGRAM 4 # ---------------------------------------------------------- # Name: Leo Ascenzi # Time Spent: 1 # ---------------------------------------------------------- # Write your program for the volcano pattern here import time #sets up loop for easy testing play = True while play: size = int(raw_input("Enter a size: ")) #cloud plumes for line in range(size): space1 = (size*4)-((line))+1 space2 = (size*3)-(line*2) print " "*space1+"("+" "*space2+")" #top of the mountain for line in range(1): space1 = ((size*3)-(line)+1) underscore = size print " "*space1+"("+"_"*underscore+")" for line in range((size*3)): space1 = ((size*3)-(line+1)+1) ayyy = 2+line*2+(size-1) print " "*space1+"/"+"A"*ayyy+"\\" #loops if Y, not if N resp = raw_input("Would you like to make another pyramid? (Y/N) ") if resp == "Y": play == True elif resp == "N": play == False print "Later!" time.sleep(2)
01a31344d5f0af270c71baa134890070081a1d5c
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/Lab01_challenge.py
898
4.28125
4
import time import random #Sets up the human like AI, and asks a random question every time AI = random.randint(1,3) if AI == 1: print "Please type a number with a decimal!" elif AI == 2: print "Give me a decimal number please!" elif AI == 3: print "Please enter a decimal number!" #defines the response and prompts the user to enter a number response = float(raw_input()) #defines the rounded response and does the math rounded_response = int(response)+1 #makes the computer seem more human a = "." print "Calculating" time.sleep(0.5) print(a) time.sleep(0.5) print(a) time.sleep(0.5) print(a) time.sleep(1) #prints the users number rounded up print "Response calculated!" time.sleep(1) print"The rounded up version of your number is: %s" % rounded_response #adds a delay at the end for the user to reflect upon their answer time.sleep(3)
bc9b0e89b907507970b187a44d0bfc3ecf2d4142
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/lab03_vowels.py
273
4.21875
4
#Leo Ascenzi #sets up empty string ohne_vowels = "" #gets response resp = str(raw_input("Enter a message: ")) #for loop to check if character is in a string for char in resp: if char not in "aeiouAEIOU": ohne_vowels += char print ohne_vowels
adb83bcac5c4340b2cf00a63bcb7fb2896981103
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/lab02_squares.py.py
701
3.75
4
#Leo Ascenzi import turtle import time times = int(raw_input("Please enter a number of squares you want for your spiral: ")) #ss stands for spiraly square ss = turtle.Turtle() L = 10 ss.pencolor("orchid") squares = times*4 count = 0 if 0<times<25: ss.speed("normal") for i in range(squares): ss.forward(L+count) ss.left(90) count = count + L elif 25<times<50: ss.speed(10) for i in range(squares): ss.forward(L+count) ss.left(90) count = count + L else: ss.speed("fastest") for i in range(squares): ss.forward(L+count) ss.left(90) count = count + L turtle.done() time.sleep(5)
676f4845dc145feee1be508213721e26f2e55b2a
ColgateLeoAscenzi/COMPUTERSCIENCE101
/HOMEWORK/hw3_leap.py
2,055
4.15625
4
# ---------------------------------------------------------- # -------- PROGRAM 3 --------- # ---------------------------------------------------------- # ---------------------------------------------------------- # Please answer these questions after having completed this # program # ---------------------------------------------------------- # Name: Leo Ascenzi # Hours spent on this program: 0.66 # Collaborators and sources: # (List any collaborators or sources here.) # ---------------------------------------------------------- def is_leap_year(y): if y%4 == 0: return True else: return False #Anything under 1582 is invalid invalidrange = range(1582) #defines start and endyears for future rearranging startyear = 0 endyear = 0 def main(): #gets inputs year1 = int(raw_input("Enter a year: ")) year2 = int(raw_input("Enter a second year: ")) #checks valid range if year1 in invalidrange or year2 in invalidrange: print "The range must start after or at 1582" #checks which year is bigger else: if year1>year2: startyear = year2 endyear = year1 elif year2>year1: startyear = year1 endyear = year2 else: startyear = year1 endyear = year2 #for all the years more than the start year in the endyear range, print leapyear or nah for years in range((endyear+1)): if years<startyear: pass else: if is_leap_year(years): print years, "is a leap year" else: print years, "is a normal year" # finally, call main. Which makes the code work main()
7004bc9b49acc1a75ac18e448c2256cbec808cf4
CodyPerdew/TireDegredation
/tirescript.py
1,350
4.15625
4
#This is a simple depreciation calculator for use in racing simulations #Users will note their tire % after 1 lap of testing, this lets us anticipate #how much any given tire will degrade in one lap. #From there the depreciation is calculated. sst=100 #Set tire life to 100% st=100 mt=100 ht=100 print("when entering degredation use X.XX format") #Have the user enter their degredation figures after a test lap for each type of tire. laps = int(input("How many laps to show?")) #how many laps in the race? ss = float(input("What is the degredation on SuperSoft tires?")) s = float(input("on Softs?")) m = float(input("on Medium?")) h = float(input("on Hards?")) laps += 1 print("Here's your expected tire life after each lap") lapcount = 1 while laps > 1: #multiply tire-left * degredation, subtract that amount from tire-left ssdeg = sst * ss sst = sst - ssdeg sdeg = st * s st = st - sdeg mdeg = mt * m mt = mt - mdeg hdeg = ht * h ht = ht - hdeg #print the expected tire life after X laps, ':<5' used for formatting print("AFTER LAP: {:<5} SST:{:<5} ST:{:<5} MT:{:<5} HT:{:<5}".format(lapcount, round(sst, 1), round(st, 1), round(mt, 1), round(ht, 1))) laps -= 1 lapcount += 1
a3f4a8d56272248fe4acdda876922deb6de03491
San4stim/Python_6_Homeworks
/lesson_9/lesson_9_1.py
659
3.546875
4
import math number_of_flat = int(input('Введите номер квартиры \n')) etazh = int(input('Введи количество этажей \n')) kol_vo_kvartir = int(input('Введи количество квартир на этаже \n')) kvartir_v_padike = etazh * kol_vo_kvartir if number_of_flat % kvartir_v_padike ==0: nomer_padika = number_of_flat // kvartir_v_padike else: nomer_padika = number_of_flat // kvartir_v_padike +1 etazh = ((number_of_flat - (nomer_padika - 1) * kvartir_v_padike) / kol_vo_kvartir) s = math.ceil(etazh) print('тебе нужен падик номер ', nomer_padika, 'и этаж номер ', s)
8204299aaf429a739a01539f53a94210c78006a9
AmitCharran/LearningPython
/first.py
7,651
4.125
4
print("This line will be printed") x = 1 if x == 1: print("x is 1") print("Goodbye, World") myInt = 7 print('int test', myInt) print('also use this ' + str(myInt)) myFloat = 7.0 print('float test ' + str(myFloat)) myString = 'string' myString2 = "string2" print("String test" + " " + myString + " " + myString2) one = 1 two = 2 three = one + two print(three) print('\nMultiple Variable Declaration - line 27') a, b = 2, 3 print(a + b) a, b = 2, 'three' # this will not work # print( a + " " + b) print(str(a) + " " + b) # List print('\n') print('List:') myList = [] myList.append(1) myList.append(2) myList.append(3) print(myList[0]), # prints 1 print(myList[1]), # prints 2 print(myList[2]), # prints 3 print('') # prints out 1,2,3 for x in myList: print(x), print("\nmyList only has 3 variables but if I try an access index outside it ex. myList[10]") print('\tDoes not work but does not give error and does not even print the print statement') # print('myList[10]:',myList[10]) # but nothing can execute after this # Arithmatic Operations print('\n\nArithmatic Operations line 57') print('squared = 7**2: so 7 squared') print(7 ** 2) print("cubed = 7**3: so 7 cubed") print(7 ** 3) print("\nmultiplication operation on string") string = "hello " print('string = "hello "\nstring * 10 = ' + str(string * 10)) print("\nOperations on List - line 67") even_numbers = [2, 4, 6, 8] odd_numbers = [1, 3, 5, 7] all_numbers = even_numbers + odd_numbers print("all_numbers= even_numbers + odd_numbers = " + str(all_numbers)) print("[1,2,3]*3 = " + str([1, 2, 3] * 3)) print("\n\nString Format") name = "John" print('name = "John"\n"Hello, %s!" % name') print("Hello, %s!" % name) name = "Jane" last = "Doe" age = 23 print('"hello %s %s you are %d years old" % (name,last,age)') print("hello %s %s you are %d years old" % (name, last, age)) # printing lists myList = [1, 2, 3] print('"A list: %s" % myList') print("A list: %s: " % myList) print('"%s" = String and list \n"%d" - Integers\n"%f" - Floating Point Number\n"%.<number of digits>"fixed digits' '\n"%x/%X" - Integers in Hex Representation (lowercase/uppercase)') # String Operations print("\n\nString Operations - line 93") print("name = " + name) print("len(name): " + str(len(name))) print("name.index('n'): " + str(name.index("n"))) print('name.count("a"): ' + str(name.count('a'))) print("name[1:3] :" + str(name[1:3])) # idk what this is # name[start:stop:step] print("name[1:2:3] :" + str(name[1:2:3])) print("name[::-1] :" + str(name[::-1])) print("Getting odd index from string") print("name[1::2] :" + str(name[1::2])) print('name.upper() :' + name.upper()) print('name.lower() :' + name.lower()) print("name.startswith('Ja') :" + str(name.startswith('Ja'))) print('name.endswith("nadshd") :' + str(name.endswith('nadshd'))) print("name.split('n')" + str(name.split('n'))) # Booleans print('\n\nBoolean') print("x = 2") x = 2 print("x == 2 : " + str(x == 2)) print("x == 3 : " + str(x == 3)) print("x < 3 : " + str(x < 3)) print("if 'in' operator - look at code line 120") if x in [1, 2, 3, 4]: print("x is in list") else: print("x is not in list") if x != 2: print("x is not 2") else: print("x is 2") print("There's also a not operator - line 131") print(not (x == 3)) # is myList is not empty if myList: print("yes") else: print("no") # Loops/for loops print("\n\nLoops/For Loops/While Loops - line 142") print("For Loops") primes = [2, 3, 5, 7, 11] for x in primes: print(x), print("") for i in range(5): print(primes[i]), print("\n\nWhile loop -- line 152") count = 0 while count < 5: print("primes[%d]" % count), print(primes[count]) count += 1 count = 0 print("count:"), while True: print(count), count += 1 if count > 5: break print('') for x in range(10): if x % 2 == 0: print(x), print('') for i in range(100, 200): if i % 10 == 0: print(i), print("\n\nFunctions -- line 180") def my_function(): print("this is my function") my_function() def function2(name, greeting): print("%s, %s\nHow are you?" % (name, greeting)) function2(name, "hello") def sum5(a2, b2): return a2 + b2 print(sum5(4, 5)) # Classes and Objects print('\n\nClasses and Objects -- line 203') class MyClass: variable = 'blah' def function(self): print("this is my function from inside class: " + self.variable) myObjectX = MyClass() print(myObjectX.variable) myObjecty = MyClass() myObjecty.variable = 'yackity' print(myObjectX.variable) print(myObjecty.variable) myObjectX.function() myObjecty.function() # Dictionaries # Dictionaries are similar to arrays but works with keys. It's like a SQL table print('\n\nDictionaries -- line 224') phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 print('phonebook = name: number = ' + str(phonebook)) # also can do this phonebook = { "John": 938477566, "Jack": 938377264, "Jill": 947662781 } print('\nCan also iterate through dictionaries -- line 238') for name, number in phonebook.items(): print("phone number of %s is %d" % (name, number)) # can also delete print("\ndel phonebook['John'] \\n print(phonebook)") del phonebook['John'] print(phonebook) print('or... phonebook.pop("John")') # Modules and Packages print('\n\nModeules and Packages -- line 250') print('Modules is python file with .py extension') print('This is something I should learn another day') # Numpy Arrays print('\n\nNumpy Arrays -- line 257') print("This gives users the opportunity to perform calculations on the entire array") height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85] weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45] # import numpy package as np import numpy as np # create 2 numpy arrays from height to weight np_height = np.array(height) np_weight = np.array(weight) print("type(np.height) = " + str(type(np_height))) # calulate bmi bmi = np_weight / (np_height ** 2) # for this arrays length must match print("bmi = np_weight / (np_height ** 2) = " + str(bmi)) print('\nNow lets do subsetting with numpy ') print('bmi[bmi > 24] = ' + str(bmi[bmi > 24])) print('\nConverting arrays of kg tp lbs using np -- line 278') weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45] np_weight_kg = np.array(weight_kg) np_weight_lbs = np_weight_kg * 2.2 print('Now we have the weights converted to kg to np using np\n' + str(np_weight_lbs)) # Pandas Basic DataFrame print('\n\nPandas Basic DataFrame -- line 285') print('\tPandas basic DataFrame is a high level manipulation tool developed by Wes McKinney.\n' '\tIt is built on Numpy package and its key data structure is called the DataFrame.\n' '\tDataFrame allows you to store tabular data in rows of observations and column variables.\n' '\tThere are several ways to create DataFrame.\n') countries = {"country":['Brazil', 'Russia', "India", 'China', "South Africa"], 'capital':["Brasilia", "Moscow", 'New Delhi', 'Beijing', "Pretoria"], "area":[8.516, 17.10, 3.286, 9.597, 1.221], "population":[200.4, 143.5, 1252, 1357, 52.98] } import pandas as pd brics = pd.DataFrame(countries) print(brics) brics.index = ("BR", "RU", 'IN', 'CH', "SA") print("\n\n") print(brics) # Reading form csv file and using panda to go through data print('\nUsing a .csv file to get data for pandas dataframe -- 305') cars = pd.read_csv('cars.csv') print(cars) print('\nCan also switch the first column like this') # doesn't reorder but shows this column first cars2 = pd.read_csv('cars.csv', index_col=3) print(cars2)
9919415bc66a1062c954f7cdde48df5901224a2a
Jason0409/cvxpy
/linear_programming.py
480
3.578125
4
import cvxpy as cvx # import numpy as np # Problem data. n = 4 A = [1, 2, 3, 4] m1 = [1, 1, 1, 1] m2 = [1, -1, 1, -1] # Construct the problem. x = cvx.Variable(n) objective = cvx.Minimize(A*x) constraints = [0 <= x, m1*x == 1, m2*x == 0] prob = cvx.Problem(objective, constraints) # The optimal objective value is returned by `prob.solve()`. result = prob.solve() # The optimal value for x is stored in `x.value`. print("x:", x.value) print("optimal objective value:", result)
d4345fbbeadafca2553d57b51b6b244bab0cdb31
devina-bhattacharyya/daily-coding-problem
/solutions/alternative_problem_077.py
1,055
3.84375
4
# Problem 77 # # This problem was asked by Snapchat. # # Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged. # # The input list is not necessarily ordered in any way. # # For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return [(1, 3), (4, 10), (20, 25)]. print("Merge Overlapping Intervals") def get_interval_start(e): return e[0] def merge_intervals(interval_list): interval_list.sort(key=get_interval_start) merged_intervals = [] merged_intervals.append(interval_list[0]) for idx, item in enumerate(interval_list[1:]): if merged_intervals[-1][1] < item[0]: merged_intervals.append(item) elif merged_intervals[-1][1] < item[1]: merged_intervals[-1][1] = item[1] return merged_intervals assert merge_intervals([[1, 3], [5, 8], [4, 10], [20, 25]]) == [ [1, 3], [4, 10], [20, 25]] assert merge_intervals([[1, 3], [5, 8], [4, 10], [20, 25], [6, 12]]) == [ [1, 3], [4, 12], [20, 25]]
e954a1ea02dbb3c0efc43db26b973f9a069ec92f
cursoweb/python-archivos
/Gonzalo Grassi/wordcount.py
4,069
4.28125
4
#!/usr/bin/python -tt # -*- coding: utf-8 -*- # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class La función main() de abajo ya está definida y completa. Llama a las funciones print_words() y print_top() que escribiste. 1. Para la bandera --count, implementar una función print_words(nombre_archivo) que cuenta qué tan frecuentemente cada palabra aparece en el texto e imprime: palabra1 cantidad1 palabra2 cantidad2 ... Imprimir la lista de arriba ordenadas por palabras (python ordenará para que la puntuación venga antes de las letras -- no se preocupen por eso). Guardar todas las palabras en minúsculas, así 'The' y 'the' cuentan como la misma palabra. 2. para la bandera --topcount, implementar una función print_top(nombre_archivo) que es similar a print_words() pero imprime sólo las 20 palabras más comunes ordenadas para que aparezca la palabra más común primero, luego la siguiente más común, y así. Utilizar str.split() (sin argumentos) para dividir todo por los espacios en blanco. Flujo de trabajo: no construyas todo el programa de una vez. Llega hasta un hito intermedio e imprime tu estructura de datos y luego sys.exit(0). Cuando eso funcione, intenta con el siguiente hito. Opcional: defina una función de ayuda para evitar duplicar código dentro de print_words() y print_top(). """ import sys # +++tu código aquí+++ # Define las funciones print_words(nombre_archivo) y print_top(nombre_archivo). # Puedes escribir una función de ayuda que lee un archivo y construye y retorna # un diccionario palabra/cantidad. # Luego print_words() y print_top() pueden llamar directamente a la función de ayuda. posicion = 2 #Posibles valores 0: clave 1: valor def print_words(nombre_archivo): diccionario = procesarTexto(nombre_archivo) #for clave in sorted(diccionario.keys()): # print clave, diccionario.get(clave) setPosicion("clave") for claveValor in sorted(diccionario.iteritems(), key = orden): print claveValor def orden(tuplaDicc): if posicion==1 or posicion==0: return tuplaDicc[posicion] def setPosicion(cadena): global posicion if cadena=="clave": posicion = 0 if cadena=="valor": posicion = 1 def print_top(nombre_archivo): diccionario = procesarTexto(nombre_archivo) contador = 1 setPosicion("valor") for claveValor in sorted(diccionario.iteritems(), key = orden, reverse=True): print claveValor contador = contador + 1; if contador == 20: break def procesarTexto (nombre_archivo): diccionario = {} contador = 1 palabra = "" f = open(nombre_archivo, 'rU') for linea in f: listaPalabra = linea.split() for palabraBruta in listaPalabra: for letra in palabraBruta: if letra.isalpha(): palabra = palabra + letra; else: break palabra = palabra.lower() if not diccionario.has_key(palabra) and len(palabra)!= 0: diccionario[palabra] = contador elif diccionario.has_key(palabra): diccionario[palabra] = diccionario.get(palabra) + 1 palabra = '' f.close() return diccionario ### # Se provee este código básico de parseado de argumentos de línea de comandos # que llama a las funciones print_words() y print_top() que debes definir. def main(): if len(sys.argv) != 3: print 'USAR: ./wordcount.py {--count | --topcount} archivo' sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print 'opcion desconocida: ' + option sys.exit(1) if __name__ == '__main__': main()
7bd3cd9699ae98046019347c12138fc1486788d9
k3llymariee/oo-melons
/melons.py
2,415
3.875
4
from random import randint from time import localtime """Classes for melon orders.""" class AbstractMelonOrder(): """An abstract base class that other Melon Order inherit from""" def __init__ (self, species, qty, country_code, order_type, tax): self.species = species self.qty = qty self.shipped = False self.order_type = order_type self.tax = tax self.country_code = country_code def get_base_price(self): random_price = randint(5, 9) base_price = random_price * 1.5 if self.species == 'Christmas' else random_price order_time = localtime() order_hour = order_time.tm_hour order_day = order_time.tm_wday # Rush hour is 8am to 11am, M-F if order_hour in range(8,12) and order_day in range(0,5): base_price += 4 return base_price def get_total(self): """Calculate price, including tax.""" base_price = self.get_base_price() total = (1 + self.tax) * self.qty * base_price if self.country_code != 'USA' and self.qty < 10: total += 3 return total def mark_shipped(self): """Record the fact than an order has been shipped.""" self.shipped = True def get_country_code(self): """Return the country code.""" return self.country_code class DomesticMelonOrder(AbstractMelonOrder): """A melon order within the USA.""" def __init__(self, species, qty): super().__init__(species, qty, country_code='USA', order_type='domestic', tax=0.08) class InternationalMelonOrder(AbstractMelonOrder): """An international (non-US) melon order.""" def __init__(self, species, qty, country_code): super().__init__(species, qty, country_code, order_type='international', tax=0.17) class GovernmentMelonOrder(AbstractMelonOrder): passed_inspection = False def __init__(self, species, qty): super().__init__(species, qty, country_code='USA', order_type='domestic', tax=0.00) def mark_inspection(self, passed): """Record the fact than an order has been inspected.""" self.passed_inspection = passed
e93589ee1564591a3baa32f82f8995038ce98b36
asynched/RSA-Implementation
/src/rsa/encrypt.py
1,308
4
4
import traceback def encrypt(message: str, key: list) -> str: """Encrypts a message using the public keys Args: message (str): Message to be encrypted key (list): Public key to encrypt the message with Raises: Exception: Raises an exception if the encryption process fails Returns: str: Encrypted version of the original string """ try: return "g".join([hex(pow(ord(letter), int(key[0]), int(key[1])))[2:] for letter in message]) except Exception as e: raise Exception(f"Error whilst trying to encrypt the message, error: {e}") def decrypt(message: str, key: list) -> str: """Decrypts a message using the private keys Args: message (str): Encrypted message to be decrypted key (list): Private key to decrypt the message Raises: Exception: Raises an excepton if the decryption process fails Returns: str: Decrypted version of the encrypted string """ try: arr: list = message.split("g") message: str = "".join([chr(pow(int(element, 16), int(key[0]), int(key[1]))) for element in arr]) return message except Exception as e: traceback.print_exc() raise Exception(f"Error whilst trying to encrypt the message, error: {e}")
f7df9b20ba1dcc224cb31aa03d6d3c8cb144834c
HolyPi/LeetCode
/Smallernumbers.py
1,108
3.78125
4
#Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. # 1. Restate the problem # Using an array of integers, remove the duplicates so they appear only once, and return the new length. # 2. Ask Clarifying Questions # Will there be negative numbers? Positives? Are they sorted? # 3. State Assumptions # I'll assume they are all positive unsorted numbers. # 4a. Brainstorm Solutions #Loop through numbers and set a count. Compare numbers with a nested loop and append the count to output to return the answer # 4c. Discuss Tradeoffs #It's would be n^2 because of the nested loop def smallerNumbersThanCurrent(nums): output = [] for i in range(len(nums)): count = 0 for m in range(len(nums)): if nums[m] < nums[i] and m!= i: count += 1 output.append(count) return output nums = [8, 4, 4, 6, 1] print(smallerNumbersThanCurrent(nums))
ca1f0e03618b285cebc24e19dd263f19f5def949
Elchin/PermaData
/replace_text.py
2,851
3.515625
4
""" String replace for column values. """ import csv import getopt import sys def replace_text(ggd361_csv, out_file, to_replace, with_replace): """ Replace text within field with new text. :param ggd361_csv: input CSV file :param out_file: output CSV file :param to_replace: substring within field to be replaced :param with_replace: substring to replace to_replace substring """ ofile = open(out_file, 'w') writer = csv.writer(ofile, delimiter=',', quoting=csv.QUOTE_NONE, lineterminator='\n') csv_data = [] field_names = None with open(ggd361_csv) as csv_values: reader = csv.reader(csv_values, delimiter=',', quoting=csv.QUOTE_NONE) for row in reader: field = row[0].replace('\'', '') new_field = field.replace(to_replace, with_replace) row[0] = '\'' + new_field + '\'' writer.writerow(row) ofile.close() def parse_arguments(argv): """ Parse the command line arguments and return them. """ ggd361_csv = None out_file = None to_replace = None with_replace = None try: opts, args = getopt.getopt(argv,"hi:o:t:w:",["ggd361_csv=","out_file=","to_replace=","with_replace="]) except getopt.GetoptError: print 'replace_text.py -i <GGD361 CSV file> -o <CSV output file> -t <text in field to replace> -w <replacement text>' sys.exit(2) found_in_file = False found_out_file = False found_to_replace = False found_with_replace = False for opt, arg in opts: if opt == '-h': print 'replace_text.py -i <GGD361 CSV file> -o <CSV output file> -t <text in field to replace> -w <replacement text>' sys.exit() elif opt in ("-i", "--ggd361_csv"): found_in_file = True ggd361_csv = arg elif opt in ("-o", "--out_file"): found_out_file = True out_file = arg elif opt in ("-t", "--to_replace"): found_to_replace = True to_replace = arg elif opt in ("-w", "--with_replace"): found_with_replace = True with_replace = arg if not found_in_file: print "Input file '-i' argument required." sys.exit(2) if not found_out_file: print "Output file '-o' argument required." sys.exit(2) if not found_to_replace: print "Text within field to replace '-t' argument required." sys.exit(2) if not found_with_replace: print "Replacement text '-w' argument required." sys.exit(2) return (ggd361_csv, out_file, to_replace, with_replace) if __name__ == '__main__': (ggd361_csv, output_csv, to_replace, with_replace) = parse_arguments(sys.argv[1:]) replace_text(ggd361_csv.strip(), output_csv.strip(), to_replace.strip(), with_replace.strip())
b38efc90e860c6f5366f603b6cbc85518a929ad2
Gujaratigirl/Python-Challenge
/PyBank/MainBank.py
3,285
3.84375
4
# module for PC/Mac file open import os # Module for reading cvs files import csv #start out empty list bank_date = [] bank_change = 0 bank_change_list1 = [] bank_change_list2 = [] bank_change_new=[] previous_bank_value=0 #loop thorough a list? HOw can I do this?? max_value=0 min_value=0 bankcsv = os.path.join('..', 'Resources', 'budget_data.csv') with open(bankcsv, 'r') as text: csvreader = csv.reader(text, delimiter=',') #moves to the first row with data header = next(csvreader) firstrow=next(csvreader) bankprofitloss=int(firstrow[1]) previous_bank_value=bankprofitloss for bank_value in csvreader: bank_date.append(bank_value[0]) bank_change_list1.append(int(bank_value[1])) bank_change_list2.append(int(bank_value[1])) netprofitloss=int(bankvalue[1])-previous_bank_value previous_bank_value=int(bankvalue[1]) #adding with += function for change price bank_change += int(bank_value[1]) # if bank_value[1]> max_value: #TypeError: '>' not supported between instances of 'str' and 'int' # max_value= bank_value[1] # if bank_value[1]< min_value # min_value= bank_value[1] bank_change_list2.pop(0) #print(bank_date) print(bank_change) #length of bank_date bank_date_length=len(bank_date) print(f"Total Months: {bank_date_length}") print(f"Total: ${bank_change}") def average(list): length=len(list) total =0.0 for number in list: total +=number return total /length print (bank_change_list1) print (bank_change_list2) print (bank_change_new) #didn't work-this isn't the average should be around 446309.047 print (average(bank_change_list1)) # Didn't work- I only want 2 decimal place HOW can I reduce it to only 2 print(float(average(bank_change_list1))) #print max and min of list --Doesn't work print(max(bank_change_list1)) print(min(bank_change_list1)) #loop thorough a list? HOw can I do this?? max_value=0 min_value=100000 for bank_value in csvreader: #ValueError: I/O operation on closed file. if bank_value[1]> max_value: max_value= bank_value[1] max_month=bank_value[0] if bank_value[1]< min_value: min_value= bank_value[1] min_month= bank_value[0] print(max_value) print(min_value) ######make new file and write into it what is calculated#### is this written correctly??? bank_output = os.path.join("..", "pybank", "bank_output.csv") with open(bank_output, 'w', newline='') as csvfile: #Initialize csv.writer print(f{Financial Analysis}) print("------------------------------------") print(f"Total Months: {bank_date_length}") print(f"Total: ${bank_change}") print(f"Average Change: ${average(bank_change_list1).3f}%" )# this is to drive number of decimil places ### None of this is working###### for find_max_row in csvreader: if max_value = max_value_row[1] print(f"Greatest Increase: {max_value_row[0]} (${max_value})" ) # Write the first row (column headers) #csvwriter.writerow(['First Name', 'Last Name', 'SSN']) # Write the second row #csvwriter.writerow(['Caleb', 'Frost', '505-80-2901']) #print(f"Expert status: {expert_status}")
f0afa65944197e58bad3e76686cef9c2813ab16d
chrismlee26/chatbot
/sample.py
2,521
4.34375
4
# This will give you access to the random module or library. # choice() will randomly return an element in a list. # Read more: https://pynative.com/python-random-choice/ from random import choice #combine functions and conditionals to get a response from the bot def get_mood_bot_response(user_response): #add some bot responses to this list bot_response_happy = ["omg! great!", "Keep smiling!", "I love to see you happy!"] bot_response_sad = ["im here for you", "sending good vibes", "Ok is fine"] if user_response == "happy": return choice(bot_response_happy) elif user_response == "sad": return choice(bot_response_sad) elif user_response == "ok": return choice(bot_response_sad) else: return "I hope your day gets better" print("Welcome to Mood Bot") print("Please enter how you are feeling") user_response = "" #TODO: we want to keep repeating until the user enters "done" what should we put here? while True: user_response = input("How are you feeling today?: ") # Quits program when user responds with 'done' if user_response == 'done': break bot_response = get_mood_bot_response(user_response) print(bot_response) # Create a function called get_bot_response(). This function must: # It should have 1 parameter called user_response, which is a string with the users input. # It should return a string with the chat bot’s response. # It should use at least 2 lists to store at least 3 unique responses to different user inputs. For example, if you were building a mood bot and the user entered “happy” for how they were feeling your happy response list could store something like “I’m glad to hear that!”, “Yay!”, “That is awesome!”. # Use conditionals to decide which of the response lists to select from. For example: if a user entered “sad”, my program would choose a reponse from the of sad response list. If a user entered “happy”, my program would choose a reponse from the of happy response list. # Use choice() to randomly select one of the three responses. (See example from class.) # Greet the user using print() statements and explain what the chat bot topic is and what kind of responses it expects. # Get user input using the input() function and pass that user input to the get_bot_response() function you will write # Print out the chat bot’s response that is returned from the get_bot_response() function # Use a while() loop to keep running your chat bot until the user enters "done".
30a7a05b2c37681fe0e1d187c98edf6a3c38da27
sseanik/Document-Reconstructor
/scanned/extractShreds.py
6,376
3.65625
4
import cv2 import numpy as np def viewImage(image): # Helper function to display an image in a small window cv2.namedWindow('Display', cv2.WINDOW_NORMAL) cv2.imshow('Display', image) cv2.waitKey(0) cv2.destroyAllWindows() # https://stackoverflow.com/questions/47899132/edge-detection-on-colored-background-using-opencv # Step 1: Convert the image from BGR (blue,green,red) into HSV (hue,saturation,value) # Step 2: We threshold the saturation channel (contains the colour background) # Step 3: Find the max size contour (i.e. ignore the small occurances of edge detection) def getContours(image, numShreds): # Convert to hsv-space, then split the channels hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) # Threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV) # Find all the external contours on the threshed S contours = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] contours = sorted(contours, key = cv2.contourArea, reverse=True) # Return all the shred contours (ignores the bigger rectangle and smaller particles) return contours[1:numShreds + 1] def getShredContour(shred): # Helper function used in case a shred needs to generate a new contour hsv = cv2.cvtColor(shred, cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV) contours = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] contours = sorted(contours, key = cv2.contourArea, reverse=True) return contours[0] # https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/ def order_points(pts): # First entry in the list is the top-left, second entry is the top-right, # third is the bottom-right, and the fourth is the bottom-left rect = np.zeros((4, 2), dtype = "float32") # The top-left point will have the smallest sum, whereas the bottom-right # point will have the largest sum s = pts.sum(axis = 1) # Point offset is to attempt to stretch content to edges rect[0] = pts[np.argmin(s)] + 5 rect[2] = pts[np.argmax(s)] # Compute the difference between the points, the top-right point will have # the smallest difference, the bottom-left will have the largest difference diff = np.diff(pts, axis = 1) # Point offset is to attempt to stretch content to edges rect[1] = pts[np.argmin(diff)] + 5 rect[3] = pts[np.argmax(diff)] # Return the reordered coordinates return rect # https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/ def four_point_transform(image, pts): # Set points to a specific order rect = order_points(pts) (tl, tr, br, bl) = rect # Compute width of the new image, which contains a maximum distance between # bottom-right and bottom-left x-coordiates or the top-right and top-left # x-coordinates widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) # Compute height of the new image, which contains a maximum distance between # the top-right and bottom-right y-coordinates or the top-left and # bottom-left y-coordinates heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) # With the dimensions of the new image, construct the set of destination # points to obtain a top down/unwarped view of the image specifying points # in the top-left, top-right, bottom-right, and bottom-left order # Width offset is to attempt to stretch content to edges dst = np.array([[0, 0], [maxWidth + 10, 0], [maxWidth + 10, maxHeight - 2], [0, maxHeight - 2]], dtype = "float32") # Compute the perspective transform matrix and then apply it M = cv2.getPerspectiveTransform(rect, dst) unwarped = cv2.warpPerspective(image, M, (maxWidth, maxHeight)) # Return the unwarped image return unwarped def getShreds(image, contours): shreds = [] # Iterater over each shred edge outline for i in contours: # Generate the points for each of the four corners of the contour rc = cv2.minAreaRect(i) box = cv2.boxPoints(rc) pts = np.float32([(box[1][0],box[1][1]),(box[2][0],box[2][1]), \ (box[0][0],box[0][1]),(box[3][0],box[3][1])]) crop = image.copy() # Perspective transform (straighen) the shred and crop it unwarped = four_point_transform(crop, pts) shreds.append(unwarped) return shreds if __name__ == '__main__': # Get the count for the amount of shreds on each scanned sheet print("How many shreds for the first image: ", end="") first = int(input()) print("How many shreds for the second image: ", end="") second = int(input()) # Set the path to the scanned sheets path1 = "../testImages/first.png" path2 = "../testImages/second.png" # Read both of the images image1 = cv2.imread(path1) image2 = cv2.imread(path2) # Using edge detection, generate the contours around each shred contours1 = getContours(image1, first) contours2 = getContours(image2, second) demo1 = image1.copy() cv2.drawContours(demo1, contours1, -1, (0, 255, 0), 10) cv2.imwrite(f"../testImages/demoContour1.png", demo1) demo2 = image2.copy() cv2.drawContours(demo2, contours2, -1, (0, 255, 0), 10) cv2.imwrite(f"../testImages/demoContour2.png", demo2) # Unwarp and separate each shred into its own image shreds1 = getShreds(image1, contours1) shreds2 = getShreds(image2, contours2) # Resize each shread to a uniform size and write each shred as a file uniformSize = (228, 6635) count = 0 for i in shreds1: resized = cv2.resize(i, uniformSize, interpolation = cv2.INTER_AREA) cv2.imwrite(f"../testImages/out/{count}.png", resized) count += 1 for j in shreds2: resized = cv2.resize(j, uniformSize, interpolation = cv2.INTER_AREA) cv2.imwrite(f"../testImages/out/{count}.png", resized) count += 1
c96676ff67e902f19f39c486d1c09344b5991116
inewhart/E01a-Control-Structues
/main10.py
2,305
4.09375
4
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') # prints Greetings colors = ['red','orange','yellow','green','blue','violet','purple'] # array of all colors play_again = '' #creates a new string variable best_count = sys.maxsize # the biggest number while (play_again != 'n' and play_again != 'no'): # creates a loop that will run aslong as play_again is not n or no match_color = random.choice(colors) # creates a variable that is set to a random color in the array of colors count = 0 # creates integer variable count color = '' # creates a string cariable color while (color != match_color): # creates a loop that runs as long as the input doesnt match the color saved in match_color color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line sets color equal to the input plus a new line and What is my favorite color? color = color.lower().strip() # makes the input lowercase and strips the extra spaces from the input count += 1 # increments count by 1 if (color == match_color): # checks if the input matches the randomized color print('Correct!')# if it doe match the code will output Correct and the loop will end else: # This will run if the input and random color do not match print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) # system will output this line and replace {guesses} with count print('\nYou guessed it in {0} tries!'.format(count)) # system will output this line when the loop ends if (count < best_count): # checks if the count of the most recent run of the loop is bigger than the best recorder number of tries print('This was your best guess so far!') # System will print this phrase if the last line is true best_count = count # sets best_counts value to that of count play_again = input("\nWould you like to play again? ").lower().strip()# takes an input that will rerun the loop as long as n or no are not inputted print('Thanks for playing!') # system will print thanks for playing
e361bf7eb084aa538eec3312b4a62cb77011ce72
rsakib15/Python-Study
/loop.py
64
3.546875
4
li = [1, 2, 3, 4, 5, 3] for i in range(len(li)): print(li[i])