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
0423a1f2927e6d4ea4a16578801e4f237d0cda6d
20040116/Learning-experience-of-python
/Day02(2021.07.07)_Class.py
2,588
4.40625
4
###类的基础学习 ###书上的例子 ###属性:类中的形参和实参 方法:类中的具体函数 ###将一个类作为另一个类的属性 class Wheel(): def __init__(self, maker, size): self.maker = maker self.size = size def wheel_description(self): print("This wheel is " + str(self.size) + " maked by " + self.maker) class Car(): '''模拟汽车的简单尝试''' def __init__(self, make, model, year, maker, size): self.make = make self.model = model self.year = year self.maker = maker self.size = size self.odometer_reading = 0 self.gas_tank = 50 self.wheel = Wheel(self.maker, self.size) ###将Wheel类作为Car类的一个属性 def get_descriptive(self): long_name = self.make + ' ' + self.model + ' ' + str(self.year) return long_name.title() '''修改属性的值''' def update_odometer(self, mileage): self.odometer_reading = mileage print('当前里程数为' + str(self.odometer_reading)) def increment_odometer(self, miles): self.odometer_reading += miles ###mileage和miles为外部形参 print('当前里程数为' + str(self.odometer_reading)) def fill_gas_tank(self): print("This car's gas tank is " + str(self.gas_tank)) ###类的继承 ###子类继承父类的所有属性和方法,同时可以定义自己的属性和方法 ###父类必须包含在当前文件中,且位于子类的前面 class ElectricCar(Car): '''对Car类的继承''' def __init__(self, make, model, year, maker, size): ###初始化父类的属性 super().__init__(make, model, year, maker, size) ###super()是一个特殊函数,帮助父类和子类关联起来 self.battery_size = 100 '''给子类定义属性和方法''' def describe_battery(self): print('Battery size is ' + str(self.battery_size)) '''重写父类的方法''' def fill_gas_tank(self): print("This car has no gas tank") ###改写父类中的函数,调用时忽略父类的同名函数 my_car = Car('audi', 'a4', 2021, "maker1", 20) print(my_car.get_descriptive()) my_car.update_odometer(1000) my_car.increment_odometer(100) my_car.fill_gas_tank() my_car.wheel.wheel_description() my_byd_car = ElectricCar('BYD', "秦", 2021, "maker2", 30) print(my_byd_car.get_descriptive()) my_byd_car.describe_battery() my_byd_car.fill_gas_tank() my_byd_car.wheel.wheel_description()
5424c43a517edba09323db69e71cb470a8f0e555
Lokhead/Python_les_4
/dz4_6.py
201
3.515625
4
from itertools import count, cycle for el in count(10): if el > 20: break else: print(el) n = 0 for el in cycle('Hello'): if n > 9: break print(el) n += 1
98245ddd60d27d0651d060d0e2658dcac9e803db
ellispax/Binus_Workspace
/Assignment_07_10_19/family_feud.py
2,381
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 03:36:08 2019 @author: Ellis_Pax """ question = { '1':"What is your favourite snack?", '2':"What is your favourite 2019 movie?", '3':"What is your fvourite holiday resort?", '4':"Who do you consider the best actor?" } answer = { '1': ['chocolate', 'nuts', 'cream', 'chips'], '2': ['avengers', 'frozen', 'joker' ,'rundown'], '3': ['victoria', 'amsterdam', 'islands', 'beach'], '4': ['rambo', 'dwayne', 'smith', 'chan'] } def create_feud(question): ply1 = 0 ply2 = 0 while len(question) > 0: print(" ".join(question.keys())) x = input("Choose your question: ") if x not in question: print(f"Choice invalid! ") continue print(question[x]) print(answer[x]) answerA = input("Player 1 Please Enter your answer -->").lower() answerB = input("Player 2 Please Enter your answer -->").lower() if answerA != answerB: #for i in answer[x]: if (answerA == answer[x][0]): ply1 = ply1 + 50 elif (answerA == answer[x][1]): ply1 = ply1 + 40 elif (answerA == answer[x][2]): ply1 = ply1 + 30 elif (answerA == answer[x][3]): ply1 = ply1 + 20 if (answerB == answer[x][0]): ply2 = ply2 + 50 elif (answerB == answer[x][1]): ply2 = ply2 + 40 elif (answerB == answer[x][2]): ply2 = ply2 + 30 elif (answerB == answer[x][3]): ply2 = ply2 + 20 else: ("Invalid Input") else: print("Player 1 and player 2 cannot choose the same answer! ") del question[x] print("Player 1 has ", ply1, "Points") print("Player 2 has ", ply2, "Ponits") create_feud(question)
470d90a27f626ad900f689843c07d003e0852ca3
ausmarton/simple-notes
/notes_test.py
987
4.0625
4
""" Test cases """ # !coding: utf-8 from unittest import TestCase from Calculator import add from Calculator import multiply from notes import get def add_note(strings,string): strings.append(string) return strings class NotesTestCase(TestCase): """ Notes Test""" def test_get_note_from_list(self): """ get note from list """ notes = ["a" , "b" , "c"] id = 1 expected_output = "b" self.assertEqual(expected_output, get(notes,id)) def test_get_first_note_from_list(self): """ get first note from list """ notes = ["a", "b", "c"] id = 0 expected_output = "a" self.assertEqual(expected_output,get(notes,id)) def test_add_note_to_list(self): """ add note to list """ initial_notes = ["a" , "b" , "c"] notes = add_note(initial_notes,"d") id = 3 expected_output = "d" self.assertEqual(expected_output, get(notes,id))
4df55036ec4dd5ee2a2bf6b4594a5ef63a3b9292
allenjstewart/SU_Programming_19
/Individual Folders/helliwed/factor3.py
1,152
4
4
# My second attempt at a factoring program now in Python 3 #seems to work, except some numbers are presented with a decimal... num = int(input("Enter an integer greater than 1. ")) factorlist = [] print() while (num > 1): i=2 while (i <= num**(.5)): #only need to check up to if num%i != 0: #and including the square root i = i+1 else: factorlist = factorlist + [i] num = int(num/i) i = 2 factorlist = factorlist + [num] num = 1 #print "Factors are %s." %(factorlist) #how many of which primes? primelist = [] #some empty lists explist = [] for factor in factorlist: #list of distinct primes if factor not in primelist: primelist.append(factor) for prime in primelist: #count how many of each prime there are explist.append(factorlist.count(prime)) #print "Primes are %s,\nExponents for those primes are %s" %(primelist, explist) #now to rebuild the number productstring = '' for prime in primelist: num = num*(prime**explist[primelist.index(prime)]) productstring = productstring + '(' + str(prime) + \ '^' + str(explist[primelist.index(prime)]) + ')' print ("%s = %s \n" %(num, productstring)) exit()
8c8ec1b011a85861ad88cd5b003a69e0c54139bb
Kami32l/pong-game
/screen.py
869
3.65625
4
from turtle import Screen, Turtle class ScreenGenerator: def __init__(self): self.generate_screen() self.generate_line() def generate_screen(self): screen = Screen() screen.setup(width=1000, height=600) screen.bgcolor("black") screen.title("My Pong Game") screen.tracer(0) def generate_line(self): mid_line = Turtle() mid_line.hideturtle() mid_line.pencolor("white") mid_line.penup() mid_line.goto(0, 280) mid_line.setheading(-90) mid_line.width(5) i = 0 is_penup = True while i < 38: i += 1 if is_penup: is_penup = False mid_line.pendown() else: is_penup = True mid_line.penup() mid_line.forward(15)
8a66ddada41f0d9c67dc46330e93771c0186a6d5
shishir2812/HockeyFantasyOptimizer
/Baseline.py
2,037
3.5
4
import pandas as pd df=pd.read_csv("DataTable.csv") pos_dict={"C":[],"W":[],"D":[],"G":[]} for index, item in df.iterrows(): # item=dict(item) # print(type(item)) # print( item["DKPos"]) if item["DKPos"] in pos_dict: pos_dict[item["DKPos"]].append({"DKSalary":item["DKSalary"],"FDFP":item["FDFP"],"PlayerID":item["PlayerID"]}) # print(pos_dict["G"]) #According to FDFP descending order, then according to DKSalary ascending order for pos,item in pos_dict.items(): pos_dict[pos]=sorted(item, key=lambda x: (x["FDFP"],-float(x["DKSalary"])), reverse=True) # print(pos_dict["G"]) budget=50000 #2G 3C 3W 2D num_dict={"G":2,"C":3,"W":3,"D":2} i=0 def get_player(i): while True: cost=0 result_dict={"G":[],"C":[],"W":[],"D":[]} for pos in ["G","C","W","D"]: item=pos_dict[pos] #The greedy method is mainly used here, based on the sorted "G", "C", "W", "D". To be done. Because it is found that the salary of G C is relatively large, we give priority to them, and WD will directly take the largest salary. If not, then take the salary with the smaller G C if pos=="G": item=item[i:] if pos=="C": item=item[i:] # print(item[0]) for value in item: if len(result_dict[pos])<num_dict[pos] and cost<=budget: result_dict[pos].append(value) cost+=value["DKSalary"] if len(result_dict["D"])==num_dict["D"] and len(result_dict["G"])==num_dict["G"] \ and len(result_dict["W"])==num_dict["W"] and len(result_dict["C"])==num_dict["C"] :return result_dict,cost if len(result_dict["D"])==num_dict["D"] and len(result_dict["G"])==num_dict["G"] \ and len(result_dict["W"])==num_dict["W"] and len(result_dict["C"])==num_dict["C"] :return result_dict,cost # print(result_dict) i+=1 print(i) result_dict,cost=get_player(i) print(result_dict) print(cost)
7f1751848f21d7a90c259c773c324b39bcd370b3
AlexSR2590/curso-python
/07-ejercicios/ejercicio2.py
175
3.6875
4
""" Crear un script que muestre los numero pares del 1 al 120 """ for i in range(1,121): if i % 2 == 0 : print(f"Número par: {i}") else: print(f"Número impar: {i}")
f0fb1d24bbeffbc40fbfed97db945a69ffd9a6a1
AlexSR2590/curso-python
/07-ejercicios/ejercicio1.py
433
4.3125
4
""" Ejercicio 1 -Crear dos variables "pais" y "continente" -Mostrar el valor por pantalla (imprimir) -imprimir el tipo de dato de las dos variables """ pais = input("Introduce un país: ") continente = input("Introduce un continente: ") print("Pais: ", pais) print("Tipo de dato de la variable pais: ") print(type(pais)) print("Continente: ",continente) print("Tipo de dato de la variable continente: ") print(type(continente))
1a9900260ede8d1f9fa50622b31f2244ff70d858
AlexSR2590/curso-python
/11-ejercicios/ejercicio1.py
1,774
4.28125
4
""" Hcaer un programa que tenga una lista de 8 numeros enteros y hacer lo siguiente: - Recorrer la lista y mostrarla - Ordenar la lista y mostrarla - Mostrar su longitud - Bucar algun elemento que el usuario pida por teclado """ numeros = [1, 9, 4, 2, 30, 7, 28, 18] #Recorrer la lista y mostrarla (función) print("Recorrer la lista y mostrarla") def recorrerLista(lista): resultado = "" for numero in lista: resultado += "\n" + str(numero) return resultado print(recorrerLista(numeros)) print("------------------------\n") #Ordernar la lista y mostrarla (función) print("Ordenar lista") def ordernarLista(lista): lista.sort() return lista print(ordernarLista(numeros)) print("------------------------\n") #Mostrar longitud de la lista print("Mostar longitud de la lita") print(len(numeros)) print("------------------------\n") #Buscar algún elemento que pida el usuario print("Buscar elemento en la lista\n") encontrado = False def buscarElemento(lista, encontrar): if encontrar in lista: return True else: return False while encontrado == False: encontrar = int(input("¿Qué número quieres buscar?: ")) encontrado = buscarElemento(numeros, encontrar) if encontrado == False: print("Número no encontrado en la lista\n") else: print("Número encontrado en la lista en el índice: ") print(numeros.index(encontrar)) """ print("Buscar elemento en la lista") busqueda = int(input("Introduce un número: ")) comprobar = isinstance(busqueda, int) while not comprobar or busqueda <= 0: busqueda = int(input("introduce un númro: ")) else: print(f"Has introducido el {busqueda}") print(f"#### Buscar en la lista el número {busqueda} #####") search = numeros.index(busqueda) print(f"El número buscado existe en el indice: {search}") """
f8de2e157b5a6a3360dbfc695f71220e4080c1de
AlexSR2590/curso-python
/07-ejercicios/ejercicio7.py
531
4.03125
4
""" Hacer un programa que nos muestre todos los números impares entre dos numero que de el usuario """ numero1 = int(input("Dame el primer número: ")) numero2 = int(input("Dame el segundo número: ")) if numero1 < numero2 and numero1 >=0 and numero2 >=0: # mostrar numeros impares entre los numero dados for i in range(numero1, numero2 + 1): residuo = i % 2 if residuo != 0: print(f"Número impar: {i}") else: print(f"Número par: {i}") else: print("Error!!, El primer número debe ser menor al segundo número")
08af65139899c28b6e118af7f9c15ecfda947611
AlexSR2590/curso-python
/03-operadores/aritmeticos.py
446
4.125
4
#Operadores aritmeticos numero1 =77 numero2 = 44 #Operador asignación = resta = numero1 - numero2 multiplicacion = numero1 * numero2 division = numero1 / numero2 resto = numero1 % numero2 print("***********Calculadora*************") print(f"La resta es: {resta}" ) print(f"La suma es: {numero1 + numero2} ") print("La multiplicacion es: ", multiplicacion) print("La divison es: ", division) print("El resto de numero1 / numero2 es: ", resto)
f7b0abb69961b66369b6039acb9d614aba30a4b5
AlexSR2590/curso-python
/07-ejercicios/ejercicio3.py
444
4
4
""" Escribir un programa los cuadrados de los 60 primeros numero naturales, usar bucle while y for """ print("*****Bucle While*****") i = 0 while i <= 60: print(f"EL cuadrado de {i} es: {i * i}") i += 1 else: print("Programa terminado con bucle while!!") print("______________________________") print("*****Bucle For*****") for j in range(61): print(f"EL cuadrado de {j} es: {j * j}") else: print("Programa terminado con bucle For!!")
e04f6d80c5333bb085fe5d5c15c217338ba94e6f
cbelden/markovchain
/markovchain/tests/markov_chain_test.py
3,795
3.5
4
import unittest from markovchain import MarkovChain class TestMarkovChain(unittest.TestCase): """Tests the public methods for the MarkovChain class.""" def setUp(self): self._corpus = "This is a, sample' corpus.\n How neat is that.\n" self._expected_chain = {'this': {'is': 1}, 'is': {'a': 1, 'that': 1}, 'a': {'sample': 1}, 'sample': {'corpus': 1}, 'corpus': {'.': 1}, '.': {'how': 1}, 'how': {'neat': 1}, 'neat': {'is': 1}, 'that': {'.': 1}} def tearDown(self): pass # ~~~~~~~~~~~ CONSTRUCTOR TESTS ~~~~~~~~~~~~~~~ def test_constructor_valid_input(self): """Tests the MarkovChain constructor.""" chain = MarkovChain(self._corpus) # Assert underlying Markov Chain is as expected self.assertEqual(chain._markov_chain, self._expected_chain) def test_constructor_no_input(self): """Tests the MarkovChain constructor with null input.""" self.assertRaises(TypeError, MarkovChain.__init__, '') # ~~~~~~~~~~~ GENERATE PHRASE TESTS ~~~~~~~~~~~~~~~ def test_generate_phrase_no_params(self): """Tests the MarkovChain.generate_phrase method with no input arguments.""" chain = MarkovChain(self._corpus) phrase = chain.generate_phrase() # Assert non-None self.assertNotEqual(phrase, '') def test_generate_phrase_min_words(self): """Tests the MarkovChain.generate_phrase method with min_words arg specified.""" _min_words = 20 chain = MarkovChain(self._corpus) # Generate 10 phrases; test each one for i in range(10): phrase = chain.generate_phrase(min_words=_min_words) self.assertTrue(len(phrase.split(' ')) >= _min_words) def test_generate_phrase_invalid_min_words(self): """Tests the MarkovChain.generate_phrase method with invalid min_words arg specified.""" chain = MarkovChain(self._corpus) self.assertRaises(ValueError, chain.generate_phrase, -1) def test_generate_phrase_max_size(self): """Tests the MarkovChain.generate_phrase method with max_size arg specified.""" _max_size = 140 chain = MarkovChain(self._corpus) # Generate 10 phrases; make sure all under max size. for i in range(10): phrase = chain.generate_phrase(max_size=_max_size) self.assertTrue(len(phrase) <= _max_size) def test_generate_phrase_invalid_max_size(self): """Tests the MarkovChain.generate_phrase method with invalid max_size arg specified.""" chain = MarkovChain(self._corpus) self.assertRaises(ValueError, chain.generate_phrase, -1) def test_generate_phrase_both_valid_params(self): """Tests the MarkovChain.generate_phrase method with min_words and max_size args specified.""" _max_size = 140 _min_words = 5 chain = MarkovChain(self._corpus) for i in range(10): phrase = chain.generate_phrase(max_size=_max_size, min_words=_min_words) valid = len(phrase.split(' ')) >= _min_words and len(phrase) < 140 self.assertTrue(valid) def test_generate_phrase_invalid_parameters(self): """Tests the MarkovChain.generate_phrase with conflicting parameters.""" _max_size = 5 _min_words = 10 chain = MarkovChain(self._corpus) self.assertRaises(ValueError, chain.generate_phrase, max_size=_max_size, min_words=_min_words) if __name__ == '__main__': # Run Tests unittest.main()
38cf064d18af9ebb2a2586ae187b3226835cd946
savadev/30-Days-of-Leetcode
/twoUnique.py
254
3.703125
4
def two_unique(num): arr = [] for i in range(len(num)): temp = num[i] num.pop(i) if temp not in num: arr.append(temp) num.append(temp) return arr print(two_unique([5, 5, 2, 4, 4, 4, 9, 9, 9, 1]))
f02f75dfc5af0a67166c15428440de8245474710
jaredfreytapingo/calculator_obj
/utils.py
756
3.734375
4
import inspect from types import * def symbolChecker(symbol_input): if not stringChecker(symbol_input): print 'The Symbol {} must be a string'.format(symbol_input) return False elif symbol_input.isdigit(): print "The Symbol you typed {} must not be a digit".format(symbol_input) return False else: return True def stringChecker(input): if isinstance(input, str): return True else: return False def expressionChecker(expression): """ Input: expression input Output: True or False depending on the expression """ if not inspect.isfunction(expression): print 'The Input expression is not a function' return False else: return True
6f72c6c369a23e1a3410271a2ef85d7b35597651
khiljaekang/git-study
/keras/pratice_split.py
1,523
3.6875
4
#1. 데이터 import numpy as np x = np.array(range(1, 101)) y = np.array(range(101, 201)) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split( x, y, shuffle = False, train_size =0.7 ) print(x_train) print(x_test) from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(100, input_dim= 1 )) model.add(Dense(60)) model.add(Dense(80)) model.add(Dense(80)) model.add(Dense(110)) model.add(Dense(10)) model.add(Dense(110)) model.add(Dense(10)) model.add(Dense(105)) model.add(Dense(10)) model.add(Dense(140)) model.add(Dense(40)) model.add(Dense(40)) model.add(Dense(40)) model.add(Dense(40)) model.add(Dense(40)) model.add(Dense(40)) model.add(Dense(40)) model.add(Dense(1)) model.compile(loss='mse', optimizer='adam', metrics=['mse']) model.fit(x_train, y_train, epochs=100, batch_size=1, validation_split=4/7) loss, mse = model.evaluate(x_test ,y_test, batch_size=1) print("loss :", loss) print("mse :", mse) # y_pred = model.predict(x_pred) # print("y_predict :", y_pred) y_predict = model.predict(x_test) print(y_predict) #RMSE 구하기 from sklearn.metrics import mean_squared_error def RMSE(y_test, y_predict): return np.sqrt(mean_squared_error(y_test, y_predict)) print("RMSE : ", RMSE(y_test, y_predict)) #R2 구하기 from sklearn.metrics import r2_score r2 = r2_score(y_test, y_predict) print("R2 :", r2)
d58fb5dc170496f46cdd9268795e4d40cbc44844
khiljaekang/git-study
/keras/keras59_cifal10_imshow.py
560
3.765625
4
# cifar10 색상이 들어가 있다. from keras.datasets import cifar10 from keras.utils.np_utils import to_categorical from keras.models import Sequential, Model from keras.layers import Dense, LSTM, Conv2D from keras.layers import Flatten, MaxPooling2D, Dropout import matplotlib.pyplot as plt #1. data (x_train, y_train),(x_test, y_test) = cifar10.load_data() print(x_train[0]) print('y_train[0] :',y_train[0]) print(x_train.shape) print(x_test.shape) print(y_train.shape) print(y_test.shape) plt.imshow(x_train[3]) plt.show()
9e51ffbb2aeb0846e753a7749ffdf0176880cd85
khiljaekang/git-study
/keras/practice_keras04.py
776
3.546875
4
import numpy as np from keras.models import Sequential from keras.layers import Dense x = np.array([1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010]) y = np.array([2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010]) model = Sequential() model.add(Dense(2, input_dim=1)) model.add(Dense(400)) model.add(Dense(600)) model.add(Dense(800)) model.add(Dense(1000)) model.add(Dense(800)) model.add(Dense(600)) model.add(Dense(400)) model.add(Dense(200)) model.add(Dense(100)) model.add(Dense(1)) model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) model.fit(x, y, epochs=500, batch_size=1) loss,acc =model.evaluate(x, y, batch_size=1) print("acc:", acc) print("loss:", loss) #데이터가 많지 않기 때문에 accuracy가 0일수도 있는건가?
69b104c84a60cdaf332de46fcbbaee440427b060
khiljaekang/git-study
/keras/keras04_acc_test.py
889
3.546875
4
#1.데이터 import numpy as np x = np.array([1,2,3,4,5,6,7,8,9,10]) y = np.array([1,2,3,4,5,6,7,8,9,10]) x_pred = np.array([11,12,13]) #2.모델구성 from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(5, input_dim= 1)) model.add(Dense(3)) # model.add(Dense(1000000)) # model.add(Dense(1000000)) # model.add(Dense(1000000)) # model.add(Dense(1000000)) # model.add(Dense(1000000)) model.add(Dense(500)) model.add(Dense(500)) model.add(Dense(500)) model.add(Dense(500)) model.add(Dense(500)) model.add(Dense(1)) #3.훈련 model.compile(loss='mse', optimizer='adam', metrics=['acc']) model.fit(x, y, epochs=30, batch_size=1) #4.평가, 예측 loss, acc = model.evaluate(x ,y, batch_size=1) print("loss :", loss) print("acc :", acc) y_pred = model.predict(x_pred) print("y_predict :", y_pred)
2f446566d8589aa4141ad746d8a04e836093c969
dancojocaru2000/TruthTableLCS
/main.py
1,044
3.8125
4
#!/usr/bin/env python3 from logical_prop import LogicProposition, gen_table, get_max_width, print_table from sys import stdout, stdin p = None if stdout.isatty() and stdin.isatty(): print(" ! is the symbol for not\n","| is the symbol for or\n","& is the symbol for and\n","> is the symbol for implies\n","= is the symbol for if and only if\n","Any upper case letter is an atomic proposition") p = input(" Please input a string of symbols:\n") else: p = input() prop = LogicProposition(p) def should_print_color(): # Print color only if the output is a terminal # If the output is a file, print normally if not stdout.isatty(): return False import os # Some users prefer to disable colors in output of programs # Those users generally set the NO_COLOR environment variable # to any value. The program should respect that choice. # See: https://no-color.org/ if os.getenv("NO_COLOR") is not None: return False return True table = gen_table(prop) print_table(table, get_max_width(table), print_color=should_print_color())
9ea156cae87f883f1f3a9e7efa7593a26eeb2e1e
OnlineReview/FlockIdentification
/src/GridFormation/Point.py
723
3.734375
4
from math import sqrt, degrees,atan class Point(object): ''' classdocs ''' def __init__(self, x,y): ''' Constructor ''' self.id=0 self.x=x+0.0 self.y=y+0.0 self.isOnVertex=False def getAngle(self,vertex): angle= degrees(atan((vertex.y-self.y)/(vertex.x-self.x))) return angle def getDist(self,vertex): return sqrt((self.x-vertex.x)**2+(self.y-vertex.y)**2) def __hash__(self): stmt=str(self.x)+" "+str(self.y) return hash(stmt) def __eq__(self, other): cond = self.x==other.x and self.y==other.y return cond
54b1926cfdea43184ac12a7762faa6bc7cadef20
sharvaniadiga/squirrel-game
/src/game/TreeNode.py
412
3.703125
4
''' Created on Feb 5, 2016 @author: sharvani ''' import SquarePosition class TreeNode(object): def setPosition(self, x, y): self.position = SquarePosition.SquarePosition() self.position.setPosition(x, y) def getPosition(self): return self.position def setValue(self, value): self.value = value def getValue(self): return self.value
b6faa8956a6bb83be2729eda9dec08a31a81cae0
enderweb/smallStuff
/minutesToSeconds/minutesToSeconds.py
148
3.984375
4
print "How many minutes would you like to convert into seconds?" def convert(minutes): print minutes * 60 userChoice = input() convert(userChoice)
01f42ded2480038227e1d492193c9a1dbb3395bf
Chih-YunW/Leap-Year
/leapYear_y.py
410
4.1875
4
while True: try: year = int(input("Enter a year: ")) except ValueError: print("Input is invalid. Please enter an integer input(year)") continue break if (year%4) != 0: print(str(year) + " is not a leap year.") else: if(year%100) != 0: print(str(year) + " is a leap year.") else: if(year%400) == 0: print(str(year) + " is a leap year.") else: print(str(year) + " is not a leap year.")
999579d8777c53f7ab91ebdcc13b5c76689f7411
ayushmohanty24/python
/asign7.2.py
682
4.1875
4
""" Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values """ fname = input("Enter file name: ") try: fh = open(fname) except: print("File doesn't exist") quit() total=0 count=0 for line in fh: if line.startswith("X-DSPAM-Confidence:"): count=count+1 finding=line.find(':') number=line[finding+1:].strip() num=float(number) total=total+num average=total/count print("Average spam confidence:",average)
8e4a66d317f3be15980c606a8f45281ac6b5dea3
eswaribala/pythontraining
/tupledemo.py
206
3.53125
4
''' Created on 02-Jun-2016 @author: BALASUBRAMANIAM ''' data=(5,"Coimbatore",78.5,True) print(data) #data.append(67) print(data[1:]) listdata=list(data) listdata.append(56) print(listdata)
6bc7c7dbb046089646a85d79b22b59593efbe190
eswaribala/pythontraining
/tupleex.py
383
3.765625
4
''' Created on 03-Nov-2016 @author: BALASUBRAMANIAM ''' data=(4,'keeranatham',True) #print(data) #data.append(4359) nestedTuple=(('Ashok',567569756),('Aruna',356995345 ),('Karthik',46704765467)) for tuple in nestedTuple: for data in tuple: print(data,"\t", end='') print() hrData=list(nestedTuple) print(hrData)
ad8c141cf0078dd636bff155cbfcf777d8c952ef
eswaribala/pythontraining
/Coercing.py
318
3.578125
4
''' Created on 01-Jun-2016 @author: BALASUBRAMANIAM ''' from _decimal import Decimal import fractions n = 15 print(bin(n)) print(oct(n)) print(hex(n)) print(float(n)) binarydata=bin(n) print(int(binarydata,2)) print(int(hex(n),16)) import fractions x = fractions.Fraction(1, 3) print(x)
8ea8ce121ad1266f432af418e833a47e02d71732
Abdelrahman-Mohamed-1/Epsilon-Data-Science-Assignments
/Assignment 3/MyAssignment/mypackage/Transformers/stringTransformer.py
85
3.59375
4
def reverse(s): s=s[::-1] print(s) def cee(n): n=n.capitalize() print(n)
2dd7e5f50727ef2fd7531715d87d974d2c5ed588
dephiros/random_python_script
/unique_char_in_string.py
1,782
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest def is_string_unique_char_array(s): """ only support ASCII, use extra array of 128 chars for this version""" char_counts = [0] * 128 if s is None: return False for i in s: i_ord = ord(i) if i_ord > 127: raise ValueError("char %s out of range" % i) char_counts[i_ord] += 1 if char_counts[i_ord] > 1: return False return True def is_string_unique_char(s): """ check if string contains only unique char, does not use any extra data structure but O(n^2) """ if s is None: return False for i, j in enumerate(s): if ord(j) > 127: raise ValueError("char %s out of range" % j) for k in xrange(i, len(s) - 1): if k + 1 < len(s) and s[k + 1] == j: return False return True class TestUniqueStringArray(unittest.TestCase): def testNoneValue(self): self.assertFalse(is_string_unique_char_array(None)) self.assertFalse(is_string_unique_char(None)) def testEmptyString(self): self.assertTrue(is_string_unique_char_array('')) self.assertTrue(is_string_unique_char('')) def testRepeatingChar(self): self.assertFalse(is_string_unique_char_array('aabcdef')) self.assertFalse(is_string_unique_char('aabcdef')) def testRepeatingCharEnd(self): self.assertFalse(is_string_unique_char_array("abcdefga")) self.assertFalse(is_string_unique_char("abcdefga")) def testUniqueCharString(self): self.assertTrue(is_string_unique_char_array("abcde12345")) self.assertTrue(is_string_unique_char("abcde12345")) def testStringNotASCII(self): with self.assertRaises(ValueError): is_string_unique_char_array('カタカナ') is_string_unique_char('カタカナ') if __name__ == '__main__': unittest.main()
f6de4676af1625e12369026507cfcf70c927e6a0
czchapma/college-diversity-data
/validateFiles.py
546
3.625
4
#Run python validateFiles.py before checking in! def validate(filename): f = open(filename, 'r') header_cols = f.readline().count(",") data = f.readlines() count = 2 error = False for line in data: if line.count(",") != header_cols: error = True print "Error in " + filename + " at line " + str(count) + " expected " + str(header_cols) + " columns" count += 1 if not error: print filename + " is all set for checking in!" validate("gender.csv") validate("race.csv")
51b86194f9598763abd275668fd4554fcd174daf
vasilisal/cs102
/homework2/sudoku.py
6,721
3.921875
4
def read_sudoku(filename: str) -> List[List[str]]: """ Прочитать Судоку из указанного файла """ with open(filename) as f: content = f.read() digits = [c for c in content if c in '123456789.'] grid = group(digits, 9) return grid def display(grid: List[List[str]]) -> None: """Вывод Судоку """ width = 2 line = '+'.join(['-' * (width * 3)] * 3) for row in range(9): print(''.join(grid[row][col].center(width) + ('|' if str(col) in '25' else '') for col in range(9))) if str(row) in '25': print(line) print() def group(values: List[str], n: int) -> List[List[str]]: """ Сгруппировать значения values в список, состоящий из списков по n элементов >>> group([1,2,3,4], 2) [[1, 2], [3, 4]] >>> group([1,2,3,4,5,6,7,8,9], 3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] """ return [row[i:i+n] for i in range(0,len(row), n)] def get_row(grid: List[List[str]], pos: Tuple[int, int]) -> List[str]: """ Возвращает все значения для номера строки, указанной в pos >>> get_row([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0)) ['1', '2', '.'] >>> get_row([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (1, 0)) ['4', '.', '6'] >>> get_row([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (2, 0)) ['.', '8', '9'] """ return grid[pos[0]] def get_col(grid: List[List[str]], pos: Tuple[int, int]) -> List[str]: """ Возвращает все значения для номера столбца, указанного в pos >>> get_col([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0)) ['1', '4', '7'] >>> get_col([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (0, 1)) ['2', '.', '8'] >>> get_col([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (0, 2)) ['3', '6', '9'] """ return [grid[i][pos[1]] for i in range(len(grid))] def get_block(grid: List[List[str]], pos: Tuple[int, int]) -> List[str]: """ Возвращает все значения из квадрата, в который попадает позиция pos >>> grid = read_sudoku('puzzle1.txt') >>> get_block(grid, (0, 1)) ['5', '3', '.', '6', '.', '.', '.', '9', '8'] >>> get_block(grid, (4, 7)) ['.', '.', '3', '.', '.', '1', '.', '.', '6'] >>> get_block(grid, (8, 8)) ['2', '8', '.', '.', '.', '5', '.', '7', '9'] """ lc = (pos[0]//3 *3, pos[1]//3*3) #левый верхний угол return [grid[i][j] for i in range(lc[0],lc[0]+3) for j in range(lc[1],lc[1]+3)] def find_empty_positions(grid: List[List[str]]) -> Optional[Tuple[int, int]]: """ Найти первую свободную позицию в пазле >>> find_empty_positions([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']]) (0, 2) >>> find_empty_positions([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']]) (1, 1) >>> find_empty_positions([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']]) (2, 0) """ L = len(grid) for i in range(L): for j in range(L): if grid[i][j] == '.': return (i, j) return (-1, -1) def find_possible_values(grid: List[List[str]], pos: Tuple[int, int]) -> Set[str]: """ Вернуть множество всех возможных значения для указанной позиции >>> grid = read_sudoku('puzzles/puzzle1.txt') >>> values = find_possible_values(grid, (0,2)) >>> set(values) == {'1', '2', '4'} True >>> values = find_possible_values(grid, (4,7)) >>> set(values) == {'2', '5', '9'} True """ s = set(map(str, range(1,10))) return (s - set(get_col(grid,pos) + get_row(grid, pos) + get_block(grid,pos))) def solve(grid: List[List[str]]) -> Optional[List[List[str]]]: """ Решение пазла, заданного в grid Как решать Судоку? 1. Найти свободную позицию 2. Найти все возможные значения, которые могут находиться на этой позиции 3. Для каждого возможного значения: 3.1. Поместить это значение на эту позицию 3.2. Продолжить решать оставшуюся часть пазла >>> grid = read_sudoku('puzzle1.txt') >>> solve(grid) [['5', '3', '4', '6', '7', '8', '9', '1', '2'], ['6', '7', '2', '1', '9', '5', '3', '4', '8'], ['1', '9', '8', '3', '4', '2', '5', '6', '7'], ['8', '5', '9', '7', '6', '1', '4', '2', '3'], ['4', '2', '6', '8', '5', '3', '7', '9', '1'], ['7', '1', '3', '9', '2', '4', '8', '5', '6'], ['9', '6', '1', '5', '3', '7', '2', '8', '4'], ['2', '8', '7', '4', '1', '9', '6', '3', '5'], ['3', '4', '5', '2', '8', '6', '1', '7', '9']] """ i, j = find_empty_positions(grid) if i == -1: return grid pv = find_possible_values(grid, (i, j)) #possible values for v in pv: grid[i][j] = v solution = solve(grid) if solution is not None: return solution grid[i][j] = '.' def check_solution(solution: List[List[str]]) -> bool: """ Если решение solution верно, то вернуть True, в противном случае False """ return all(not find_possible_values(solution, (i, j)) for i in range(9) for j in range(9)) import random from typing import Tuple, List, Set, Optional def generate_sudoku(N: int) -> List[List[str]]: """ Генерация судоку заполненного на N элементов >>> grid = generate_sudoku(40) >>> sum(1 for row in grid for e in row if e == '.') 41 >>> solution = solve(grid) >>> check_solution(solution) True >>> grid = generate_sudoku(1000) >>> sum(1 for row in grid for e in row if e == '.') 0 >>> solution = solve(grid) >>> check_solution(solution) True >>> grid = generate_sudoku(0) >>> sum(1 for row in grid for e in row if e == '.') 81 >>> solution = solve(grid) >>> check_solution(solution) True """ def generate_sudoku(N): s = set(map(str, range(1,10))) field = [['.']*9] for i in range(9)] if N <= 0: return field #возвращаем пустое поле field[0] = random.sample(s, 9) solve(field) if N>81: return field else: spaces = random.sample(range(81), 81 - N) for sp in spaces: field[sp // 9][sp % 9] = '.' return field
7f50b347102b88416d153a8cd199f0e523e7d8c7
Aang1993/python_mathesis_course
/code/week3/13_scope/_13_test_allign.py
655
3.640625
4
# mathesis.cup.gr # Ν. Αβούρης: Εισαγωγή στην Python # Μάθημα 13: Εμβέλεια μεταβλητών # Άσκηση 13_test_allign st = 'Αιγαίο, με βελτίωση του' def allign_text(line, width): sp = ' ' extra_spaces = width- len(line) print(line, extra_spaces) if sp in line: while extra_spaces > 0 : line = line.replace(sp, sp+' ', extra_spaces) print(line) extra_spaces = width- len(line) sp += ' ' return line else: return line print(st) print(allign_text(st, 30))
da4e49fa3fb25559bc845d28b7fd75d5196cc7b5
Aang1993/python_mathesis_course
/code/week2/09_while/9_0.py
392
3.71875
4
# mathesis.cup.gr # N. Αβούρης: Εισαγωγή στην Python # Μάθημα 9. Δομή while # βρες τους 10 μικρότερους πρώτους αριθμούς primes = [] num = 2 while len(primes) < 10 : x = num // 2 while x > 1 : if num % x == 0: break x -= 1 else: primes.append(num) num += 1 print(primes)
9a7c385c6a60b598e819543b2b1a6bd00c25a901
Aang1993/python_mathesis_course
/code/week6/19_re/_19_1.py
772
3.59375
4
# mathesis.cup.gr # Ν. Αβούρης: Εισαγωγή στην Python # Μάθημα 19: Regular Expressions # Άσκηση 19_1 import re tonoi = ('αά', 'εέ', 'ηή', 'ιί', 'οό', 'ύυ', 'ωώ') tw = 'trivizas_works.txt' try: with open(tw, 'r', encoding = 'utf-8') as f: works = f.read() for line in works.split('\n'): print(line) except IOError as e: print(e) while True: phrase = input('Δώσε λέξη-κλειδί:') if phrase == '': break n_phrase = '' for c in phrase: char = c for t in tonoi: if c in t: char = '['+t+']' n_phrase += char print(n_phrase) pattern = '.*'+n_phrase+'.*' w =re.findall(pattern, works, re.I) for work in w: print(work)
587182397e95f57d30df6dde183cae386c74f717
Aang1993/python_mathesis_course
/code/week3/12_functions/12_4.py
601
3.640625
4
# mathesis.cup.gr # N. Αβούρης: Εισαγωγή στην Python # Μάθημα 12. Functions '''12.4 Να κατασκευάσετε συνάρτηση που παίρνει στην είσοδο μια λίστα και επιστρέφει τη λίστα με μοναδικά στοιχεία. ''' def list_set(li): # επιστρέφει τη λίστα χωρίς διπλά στοιχεία if not type(li) is list : return [] li_new = [] for i in li: if i not in li_new : li_new.append(i) return li_new print(list_set([1,2,3,4,2,3,4,2,3,4]))
8d2fc43a94c2e5fe4e52e41d18543d10bd9052d1
Aang1993/python_mathesis_course
/code/week6/19_re/_19_3.py
965
3.609375
4
# mathesis.cup.gr # Ν. Αβούρης: Εισαγωγή στην Python # Μάθημα 19: Regular Expressions # Άσκηση 19_3 import re with open('vouna.txt', 'r', encoding = 'utf-8') as f: text = f.read() for line in text.split("\n"): #print(line.rstrip()) line = line.split("\t") oros =line[0] height = int(line[1]) perioxh = line[2] perioxh = re.sub(r'\([^)]*\)', '', perioxh).split(",") #print(oros, height, perioxh) print("Το όρος {}, ύψους {}, βρίσκεται".format(oros, height), end = "") kai = "" for i in perioxh: area = i.strip() if area[-1] == "ς" : area = area[:-1] if perioxh.index(i)> 0 : kai = "και" if area[0].upper() in "ΑΕΗΙΟΥΩΆΈΉΊΌΎΏ": n = "ν" else : n = "" print("{} στη{} {} ".format(kai, n, area), end="") print()
9950df95b026a80b9f184b534400a1b2d1d7d763
Aang1993/python_mathesis_course
/code/week4/14_modules/_14_3.py
607
3.765625
4
# mathesis.cup.gr # Ν. Αβούρης: Εισαγωγή στην Python # Μάθημα 14: Βιβλιοθήκες # Άσκηση 14_3 import math def ypot(a,b) : ''' INPUT : a, b οι κάθετες πλευρές ενός ορθογωνίου τριγώνου OUTPUT: η υποτείνουσα, ή False αν κάποιο από τα a,b δεν είναι αριθμός ''' if ((type(a) is int or type(a) is float) and (type(b) is int or type(b) is float) ) : c = math.sqrt(math.pow(a,2) + math.pow(b,2)) return c else: return False print(ypot(3,4))
755377403ca0f4ac0380deb69f2c3607bf20206b
Arnkrishn/ProjectEuler
/Problem15/problem15.py
427
3.9375
4
def factorial(num): if num < 0: print "Please provide positive input" elif num in (0, 1): return 1 else: return num * factorial(num - 1) def lattice_path_count(num): if num < 0: print "Please provide positive input" elif num == 1: return 1 else: return factorial(2 * num) / (factorial(2 * num - num) * factorial(num)) #Test print lattice_path_count(20)
90ed430e058508cf21e8e49fcc18738154cb79df
Arnkrishn/ProjectEuler
/Problem3/problem3.py
781
4.03125
4
import math def is_prime(num): if num <= 1: print "Please enter a number greater than 1" elif num in (2, 3): return True else: for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def largest_prime_factor(num): if num <= 1: print "Please enter a number greater than 1" elif num in (2, 3): return num else: num_sqrt = int(math.sqrt(num)) for i in range(2, num_sqrt + 1): if i == num_sqrt: return num if num % i == 0: return max(i, largest_prime_factor(num / i)) #Test print largest_prime_factor(3) print largest_prime_factor(13195) print largest_prime_factor(600851475143)
d2bd67c580f11a4e07be0778095eebd806c926e0
sergii-yatsuk/projecteuler
/problem0014.py
891
3.875
4
#The following iterative sequence is defined for the set of positive integers: #n n/2 (n is even) #n 3n + 1 (n is odd) #Using the rule above and starting with 13, we generate the following sequence: #13 40 20 10 5 16 8 4 2 1 #It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. #Which starting number, under one million, produces the longest chain? #NOTE: Once the chain starts the terms are allowed to go above one million. def seqCount(n): le = 1 while (n>1): if (n&1): n = 3*n+1 else: n = n//2 le += 1 return le maxN = 1 maxL = 1 m = 1000000 for i in range (1, m): le = seqCount(i) if (maxL < le): maxL = le maxN = i print(maxN)
adfa2df9495c4631f0d660714a2d130bfedd9072
jni/interactive-prog-python
/guess-the-number.py
2,010
4.15625
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random def initialize_game(): global secret_number, rangemax, guesses_remaining, guesses_label rangemax = 100 guesses_remaining = 7 new_game() # helper function to start and restart the game def new_game(): global secret_number, rangemax, guesses_remaining, guesses_label secret_number = random.randrange(rangemax) if rangemax == 100: guesses_remaining = 7 else: guesses_remaining = 10 # define event handlers for control panel def range100(): global rangemax rangemax = 100 new_game() print 'The secret number is now in [0, 100).' def range1000(): global rangemax rangemax = 1000 new_game() print 'The secret number is now in [0, 1000).' def input_guess(guess): global secret_number, guesses_remaining, guesses_label guess = int(guess) print 'Your guess was %i' % guess guesses_remaining -= 1 guesses_label.set_text('Guesses remaining: %i' % guesses_remaining) if guess < secret_number: print '... and it was too low.' elif guess > secret_number: print '... and it was too high.' else: print '... and BOOM. You got it.' new_game() if guesses_remaining == 0: print 'You ran out of guesses! Starting a new game.' print '(The secret number was %i.)' % secret_number new_game() # create frame initialize_game() frame = simplegui.create_frame('Guess the number', 200, 200) # register event handlers for control elements and start frame frame.add_input('Enter guess:', input_guess, 50) frame.add_button('New game in [0, 100)', range100, 100) frame.add_button('New game in [0, 1000)', range1000, 100) guesses_label = frame.add_label('Guesses remaining: %i' % guesses_remaining) # call new_game new_game() frame.start()
f3e112fc6cda9426823e439c95c79fed1b07b12e
alanveloso/ppgcc-ufpa-ics-2021
/extended_euclidean_algorithm.py
941
3.703125
4
''' Extended Euclidean Algorithm ---------------------------- This algorithm determined the greatest common divisor (GCD) of two integers (​numbers). Also, It returns two integers such that GCD(a, b) = xa + by. @author: @alanveloso ''' def gcd(a, b): ''' Run extended euclidean algorithm. Parameters ---------- a : int b : int Returns ------- int the greatest common divisor int x in GCD(a, b) = xa + by int y in GCD(a, b) = xa + by ''' if (b <= 0) or (a <=0): raise ValueError("Expected values greater than zero!") if (a < b): raise ValueError("The second value must be greater or equal than the first!") x = 1 y = 0 g = a r = 0 s = 1 t = b while (t > 0): q = g//t u = x - q*r v = y - q*s w = g - q*t x, y, g = r, s, t r, s, t = u, v, w return g, x, y
45c49bf02c95b6762003d8019e9f687a5f5c0c76
esteev/Eko
/utils/myThread.py
677
3.5
4
import threading import time class myThread(threading.Thread): exitFlag=0 threadId = name = counter = None def __init__(self, threadId, name, counter): threading.Thread.__init__(self) self.threadId = threadId self.name = name self.counter = counter def run(self): print "Starting " + self.name self.print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(self, threadName, counter, delay): while counter: if self.exitFlag: threadName.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1
e5738c78692248985beba2738ce237546d429779
kuseinova/task4
/task4.py
606
3.53125
4
# import math # import os # import random # import re # import sys # Complete the twoStrings function below. # def twoStrings(s1, s2): # flag=False # for c in s1: # if c in s2: # flag=True # break # if flag: # return ('YES') # else: # return ('NO') # if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # q = int(input()) # for q_itr in range(q): # s1 = input() # s2 = input() # result = twoStrings(s1, s2) # fptr.write(result + '\n') # fptr.close()
29488acb724a4418b491dd098c58c0eab4de0839
raghav1674/graph-Algos-In-Python
/Recursion/01/NthFibonacci.py
488
3.8125
4
def nthFibonacii(n): if n == 1: return 0 if n == 1 or n == 2: return 1 return nthFibonacii(n-1) + nthFibonacii(n-2) dp = {} def memFibonacci(n): if n == 1 or n == 2: return n-1 if n not in dp: dp[n] = memFibonacci(n-1) + memFibonacci(n-2) return dp[n] def top_down_fib(n): if n == 1 or n == 2: return n-1 a = 0 b = 1 for n in range(2, n): a, b = b, a+b return b print(top_down_fib(8))
5fd5b964582057ac930249378e9b944ac1b31bc0
raghav1674/graph-Algos-In-Python
/Recursion/05/StairCaseTraversal.py
393
4.15625
4
def max_ways_to_reach_staircase_end(staircase_height, max_step, current_step=1): if staircase_height == 0 or current_step == 0: return 1 elif staircase_height >= current_step: return max_ways_to_reach_staircase_end( staircase_height-current_step, max_step, current_step-1) + staircase_height//current_step print(max_ways_to_reach_staircase_end(10, 2))
17807197961c90ef347ae2d10fb881f8dd2b70af
CGVanWyk/CS50
/Pset 6/Sentimental-mario-less/mario.py
478
4.03125
4
from cs50 import get_int def main(): hashCount = 2 while True: height = get_int("Height: ") if height >= 0 and height <= 23: break spaceCount = height - 1 for i in range(height): for j in reversed(range(spaceCount)): print(" ", end="") for j in reversed(range(hashCount)): print("#", end="") print() spaceCount -= 1 hashCount += 1 if __name__ == "__main__": main()
a25bca880b3d7f34c2bd11a1a615f7897c66c484
keegan8912/tweet_prediction
/remove_extra_lines.py
738
3.734375
4
import re text_1 = "This is some text, that can be used. I am not sure! How many characters? This is an extra line " text_2 = "What the hell ?" text_3 = "whoopwhoop." text_4 = "This is crazyyyyy " text_5 = "This is some kind of a test. Yeaah." def remove_extra_lines(text): list_of_suffix = [".", ",", "!", "?"] idx = [] for suffix in list_of_suffix: idx.append(text.rfind(suffix)) for suffix in list_of_suffix: if text.endswith(suffix, 0, len(text)): #save index, take the largest index here return text # elif text.rfind(suffix) != -1: else: return text[0:max(idx)+1] if __name__ == "__main__": text = remove_extra_lines(text_1) print(text)
c4f19c2737304045a2b67a296862818258db96a8
deovaliandro/uri
/1020.py
285
3.53125
4
# 1020 - Age in Days day, month, year = 0, 0, 0 myday = int(input()) year = myday/365 myday = myday % 365 month = myday/30 myday = myday % 30 day = myday if month >= 12: aa = month/12 year+=aa month %= 12 print("%d ano(s)\n%d mes(es)\n%d dia(s)\n" % (year, month, day))
9b35d89bb63cda01e8f774ea545cfe4370fec989
deovaliandro/uri
/1041.py
344
3.90625
4
# 1041 - Coordinates of a Point x = float(input()) y = float(input()) if x == 0 and y == 0 : print("Origem\n") elif x > 0 and y > 0: print("Q1") elif x < 0 and y > 0: print("Q2") elif x < 0 and y < 0: print("Q3") elif x > 0 and y < 0: print("Q4") elif x == 0: print("Eixo X") elif y == 0: print("Eixo Y") print("")
2b412f66b6e1b94d2e92fcbe2be0ac240890ee20
EdsonLMarques/URI
/resolvidos/1051.py
536
3.84375
4
salario = float(input()) imposto_1 = 0 imposto_2 = 0 imposto_3 = 0 if salario <= 2000: print("Isento") else: if 4500 < salario: imposto_3 = (salario - 4500) * 0.28 salario = salario - (salario - 4500) if 3000 < salario: imposto_2 = (salario - 3000) * 0.18 salario = salario - (salario - 3000) if 2000 < salario: imposto_1 = (salario - 2000)*0.08 salario = salario - (salario - 2000) imposto = imposto_1 + imposto_2 + imposto_3 print("R$ {:.2f}".format(imposto))
5d3e6144ee08719ed3faee2879a041081ac282ac
EdsonLMarques/URI
/main.py
2,203
3.53125
4
N, M, P = map(int, input().split()) palavras = [] for i in range(0, N): palavras.append(input()) linha = [] matriz = [] for i in range(0, M): linhas = input() for char in linhas: linha.append(char) matriz.append(linha[:]) linha.clear() PRINCIPAL = [] ACIMA = [] ABAIXO = [] DIAGONAL = [] COLUNA = 0 LINHA = 0 tem_palavra = False for palavra in palavras: palavra.capitalize() # diagonal principal______________________________________________________ for i in range(0, M): PRINCIPAL.append(matriz[i][i]) diagonal_direta = ''.join(PRINCIPAL) diagonal_direta = diagonal_direta.capitalize() diagonal_reversa = diagonal_direta[::-1] if palavra in diagonal_direta or palavra in diagonal_reversa: print("1 Palavra \"{}\" na diagonal principal".format(palavra)) tem_palavra = True PRINCIPAL.clear() # acima______________________________________________________ for i in range(1, M): LINHA = 0 for COLUNA in range(i, M): ACIMA.append(matriz[LINHA][COLUNA]) LINHA += 1 diagonal_direta = ''.join(ACIMA) diagonal_direta = diagonal_direta.capitalize() diagonal_reversa = diagonal_direta[::-1] if palavra in diagonal_direta or palavra in diagonal_reversa: print("2 Palavra \"{}\" acima da diagonal principal".format(palavra)) tem_palavra = True break ACIMA.clear() # abaixo______________________________________________________ for i in range(1, M): COLUNA = 0 for LINHA in range(i, P): ABAIXO.append(matriz[LINHA][COLUNA]) COLUNA += 1 diagonal_direta = ''.join(ABAIXO) diagonal_direta = diagonal_direta.capitalize() diagonal_reversa = diagonal_direta[::-1] if palavra in diagonal_direta or palavra in diagonal_reversa: print("3 Palavra \"{}\" abaixo da diagonal principal".format(palavra)) tem_palavra = True break ABAIXO.clear() if tem_palavra: tem_palavra = False else: tem_palavra = False print("4 Palavra \"{}\" inexistente".format(palavra))
fff6349aa9a27b61921f6408fa06bcd1aec159d8
EdsonLMarques/URI
/resolvidos/1071.py
122
3.53125
4
x = int(input()) y = int(input()) soma = 0 for n in range(y+1, x): if n % 2 != 0: soma = soma + n print(soma)
a4a7c7db2d8fbfb5649f831e832190e719c499c6
phos-tou-kosmou/python_portfolio
/euler_project/multiples_of_three_and_five.py
1,459
4.34375
4
def what_are_n(): storage = [] container = 0 while container != -1: container = int(input("Enter a number in which you would like to find multiples of: ")) if container == -1: break if type(container) is int and container not in storage: storage.append(container) elif container in storage: print("You have already entered this number, please enter all positive unique integer values") else: print("You must enter a valid integer that is postive") return storage def __main__(): # what_are_n() will return an array of integers main_storage = what_are_n() # next we will take a user input for what number they would # like to find the summation of all multiples from storage n = int(input("What number would you like to find the multiples of? : ")) final_arr = [] '''This will loop through n and enter a second for loop that will check the mod of each element in final_arr. We are able to break once finding an element because duplicates would skew the outcome. Once one number mods n, then any other mod that equals 0 is arbitrary to that i''' for i in range(0,n): for j, fac in enumerate(main_storage): if i % fac == 0: final_arr.append(i) break final = sum(final_arr) print(final) if __name__ == "__main__": pass __main__()
eec09d1b8c6506de84400410771fcdeb6fe73f73
StephenTanksley/hackerrank-grind-list
/problem-solving/extra_long_factorials.py
950
4.5625
5
""" The factorial of the integer n, written n!, is defined as: n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1 Calculate and print the factorial of a given integer. Complete the extraLongFactorials function in the editor below. It should print the result and return. extraLongFactorials has the following parameter(s): n: an integer """ #!/bin/python3 import math import os import random import re import sys # Complete the extraLongFactorials function below. # Memoization here isn't strictly necessary, but I wanted to practice writing out a memoization feature. def memo(f): table = {} def helper(x): if x not in table: table[x] = f(x) return table[x] return helper @memo def extraLongFactorials(n): product = 1 for i in range(1, n+1): product *= i print(product) if __name__ == '__main__': n = int(input()) extraLongFactorials(n)
706fe7a6d67d4df85a66c25d952ef7cc2d6ba6d3
jamiepg1/GameDevelopment
/examples/python/basics/fibonacci.py
277
4.1875
4
def fibonacci (n): """ Returns the Fibonacci number for given integer n """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-2) + fibonacci(n-1) n = 25 for i in range(n): result = fibonacci(i) print "The fibonacci number for ", i, " is ", result
cd59185b740c3ef165e6163c22bddd1dfa34623a
TheGrumpyCAT/Algorithms
/Divide and Conquer/BinarySearch/program_recursive.py
448
3.84375
4
def binary_search(arr, search_el): if len(arr) > 0: mid = len(arr) // 2 mid_el = arr[mid] if mid_el == search_el: return mid elif search_el > mid_el: return binary_search(arr[:mid], search_el) elif search_el < mid_el: return binary_search(arr[mid + 1:], search_el) else: return -1 arr = [5, 4, 3, 2, 1] search_el = 5 print(binary_search(arr, search_el))
34c6867e4dc393cdcf455a09701e906b48cf5f5e
solitary-s/python-learn
/list/tuple.py
329
4.15625
4
# 元组 不可以修改 类似字符串 tuple1 = tuple(range(1, 10)) print(tuple1) # ,逗号才是元组的标识 temp1 = (1) print(type(temp1)) # <class 'int'> temp2 = (1,) print(type(temp2)) # <class 'tuple'> # 元组的更新和删除,通过切片拼接 temp = (1, 2, 4) temp = temp[:2] + (3,) + temp[2:] print(temp)
cf8e0b2ce24068f60f4c4cb056e2baa57cae3f8f
solitary-s/python-learn
/dict/dict.py
479
4.125
4
# 字典 dict1 = {'1': 'a', '2': 'b', '3': 'c'} print(dict1) print(dict1['2']) # 空字典 empty = {} print(type(empty)) # 创建 dict((('F', 70), ('i', 105))) dict(one=1, two=2, three=3) # 内置方法 # 用来创建并返回一个新的字典 dict2 = {} dict2 = dict2.fromkeys((1, 2, 3), ('one', 'two', 'three')) print(dict2) # keys(), values() 和 items() dict3 = {} dict3 = dict3.fromkeys(range(10), 'good') print(dict3.keys()) print(dict3.values()) print(dict3.items())
1a24f59123824b0a90d3149ea8ccfdd8cc1a224e
solitary-s/python-learn
/class/salary.py
1,451
3.8125
4
from abc import ABCMeta, abstractmethod class Employee(object, metaclass=ABCMeta): def __init__(self, name): self._name = name @property def name(self): return self._name @abstractmethod def get_salary(self): pass class Manager(Employee): def get_salary(self): return 15000.0 class Programmer(Employee): def __init__(self, name, work_hours=0): super().__init__(name) self._work_hours=work_hours @property def work_hours(self): return self._work_hours @work_hours.setter def work_hours(self, work_hours): self._work_hours = work_hours def get_salary(self): return self._work_hours * 150.0 class Saleman(Employee): def __init__(self, name, sales=0): super().__init__(name) self._sales = sales @property def sales(self): return self._sales @sales.setter def sales(self, sales): self._sales = sales def get_salary(self): return 1200 + self._sales * 0.05 def main(): emps = [Manager('tong1'), Programmer('aloneness1'), Saleman('salitary1'), Manager('tong2'), Programmer('aloneness2')] for emp in emps: if isinstance(emp, Programmer): emp.work_hours = int(input('请输入%s本月的工作时间' % emp.name)) elif isinstance(emp, Saleman): emp.sales = int(input('请输入%s本月的销售额' % emp.name)) print('%s本月的工资为%s' %(emp.name, emp.get_salary())) if __name__ == '__main__': main()
1a106be5577902e27ef98f60a6e94a374cdcb55d
josineidess/Daily-Coding-Problem
/Problem1.py
294
3.609375
4
qa = int(input("Quantidade de elementos: ")) k = int(input("valor da soma: ")) lista = [] for r in range(qa): a = int(input("elemento:")) lista.append(a) i = len(lista) - 1 for e in lista: if(lista[i] + e == k): print("sim") break else: print("nao") break i-=1
121f9c3fdbe5cdfa6d7a39b8617b5b29bd5a9abc
jsbaidwan/PythonTutorial
/ConditionalStatement.py
617
4.09375
4
# If condition age = 22 if age >= 18: print("Adult") elif age >= 13: print("Teenager") else: print("Child") print("done") # Statement block if age > 1: pass # for empty block use pass else: pass # Not Operators name = "baidwan" if not name: print("Not a name") # And Operators age = 22 if age >= 18 and age < 60: print("Eligible") # Chain comparison if 18 <= age < 60: print("eligible") if age >= 18: message = "Eligible" else: message = "Not Eligible" # Ternary Operators for above Statement message = "Eligible " if age >= 18 else "Not Eligible" print(message)
dea21a1897bc30bb33b9f170bae9c281f36b4ff7
gereniz/PG1926Repo
/SifiriTasi.py
293
3.8125
4
liste = [] yeniliste = [] for i in range(0,7): sayi = int(input("Sayı giriniz : ")) liste.append(sayi) for i in range(0,len(liste)): if liste[i] == 0 : yeniliste.append(liste[i]) for i in range (0,len(liste)) : if liste[i] != 0 : yeniliste.append(liste[i]) print(yeniliste)
624f3f7ae285e9a6cfbe1b3a3941c9140833d8d8
michael1016/The-chat-room
/re/regex.py
420
3.53125
4
import re s = 'Alex:1994,Sunny:1993' pattern = r"(\w+):(\d+)" # 通过re模块调用findall l = re.findall(pattern, s) print(l) # 使用compile对象调用 regex = re.compile(pattern) l = regex.findall(s) print(l) # 按照匹配内容切割字符串 re.split(r':|,', s) print(l) # 替换匹配到的内容 s = re.subn(r'\s+','#','This is a test',2) print(s) s = re.sub(r'\s+','#','This is a test',2) print(s)
585bd470c5450d29aab458c79ec8b0c3468fe6aa
Bristy1411/Python-Codes
/First work.py
469
3.578125
4
import matplotlib.pyplot as plt m = 50 g = 9.81 c = 10 V_current = 0 T_current = 0 T_list = list() V_list = list() for i in range(1,10): T_new = i T_list.append(T_new) print(T_new) V_new = V_current + (g-(c*V_current/m))*(T_new - T_current) V_list.append(V_new) print(V_new) T_current = T_new V_current = V_new plt.xlim(0,10) plt.ylim(0,50) plt.plot(T_list , V_list ,"g") plt.plot(T_list,V_list,"ro") plt.xlabel("Time") plt.ylabel("Velocity") plt.show()
06cd3f9c93f63aca5e7ca2ee4f282b25d4985ff0
Arpita-Mahapatra/Python_class
/PROJECT1.py
4,245
4.34375
4
#Ds/Dt Calculator #Algebra Functions Functions={1:"Numbers",2:"List",3:"Sets",4:"Strings",5:"Tuples",6:"Dictionaries"} for values,keys in Functions.items(): print(values,keys) #to print all the keys with their values. Func_input=int(input("Enter the function to be performed from above options:")) def Number_Operations(): Number_ops={1:"Add",2:"Subtract",3:"Multiply",4:"Divide",5:"Floor Division",6:"Power",7:"Mod",8:"Square",9:"Square root",10:"Cube",11:"Cube root",12:"Prime",13:"Armstrong",14:"Fibonacci",15:"Factorial",16:"Odd/ Even"} for values,keys in Number_ops.items(): print(values,keys) Num_Func=int(input("Enter the Algebra function to be performed from above options:")) x, y = map(int, input("Enter two numbers seperated by ',':").split(",")) #print(x,y) import math if Num_Func==1: #if user chose 1 then we need to perform addition sum1=x+y print("The sum of numbers is:", sum1) elif Num_Func==2: sub=x-y print("The difference between the number is:",sub) elif Num_Func==3: prod=x*y print("The product of the numbers is:",prod) elif Num_Func==4: div=x/y print("The division value of the numbers is:",div) elif Num_Func==5: print("The floor division value is:", math.floor(x//y)) elif Num_Func==6: print("The power value is:", math.pow(x,y)) elif Num_Func==7: print("The Mod of numbers is:", math.fmod(x,y)) elif Num_Func==8: print("The square of x is:",(x**2)) elif Num_Func==9: print("The square root of x is:", math.sqrt(x)) elif Num_Func==10: print("The cube of x is:",(x**3)) elif Num_Func==11: print("The cube root of x is:",(x**(1/3))) elif Num_Func==12: for val in range(x, y+1): if val > 1: for n in range(2, val//2 + 2): if (val % n) == 0: break else: if n == val//2 + 1: print("The Prime numbers between x and y are:", val) elif Num_Func==13: for num in range(x,y+1): # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num) elif Num_Func==14: def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print("The fibonacci of x is:",Fibonacci(x)) print("The fibonacci of y is:",Fibonacci(y)) elif Num_Func==15: print("The factorial of x is:",math.factorial(x)) print("The factorial of y is:",math.factorial(y)) elif Num_Func==16: if (x%2)==0: print("Number given is an even number") else: print("Number given is an odd number") if Func_input==1: Number_Operations() def List_Operations(): List_ops={1:"Create List",2:"Length of List",3:"Min",4:"Max",5:"Add",6:"Insert",7:"Sort",8:"Remove",9:"Pop",10:"Concate",11:"Slicing/indexing",12:"Replace",13:"Duplicates"} for values,keys in List_ops.items(): print(values,keys) if Func_input==2: List_Operations()
cfa8ff6a920cfbf24b950c8f47e8e109b52d2fde
Arpita-Mahapatra/Python_class
/List_task.py
1,074
4.15625
4
'''a=[2,5,4,8,9,3] #reversing list a.reverse() print(a)''' #[3, 9, 8, 4, 5, 2] '''a=[1,3,5,7,9] #deleting element from list del a[1] print(a)''' #[1, 5, 7, 9] '''a=[6,0,4,1] #clearing all elements from list a.clear() print(a)''' #o/p : [] '''n = [1, 2, 3, 4, 5] #mean l = len(n) nsum = sum(n) mean = nsum / l print("mean is",mean)''' #o/p: mean is 3.0 '''n=[6,9,4,3,1] #median n.sort() l=int(len(n)/2) median=n[l] print(median)''' #O/P : 4 '''n=[2,6,4,9,3] #avg of first, middle,last elements l=int(len(n)/2) avg= (n[0]+n[l]+n[-1])/3 print(avg)''' #O/P : 3.0 '''a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]] print(a[5][2][2][3:])''' #print "come" '''a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]] print(a[5][2][2])''' #o/p: Welcome '''a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]] print(a[5][2][1][1:4])''' #o/p:yth a=[[1,2,3],4,5,6,[8,9],[[44,55,66],[66,77],["Hello","Python","Welcome"]]] print(a[5][2][1:]) #o/p:['Python', 'Welcome']
4435a66bd1a8ac1ea63bff7d57e218a6d1b27f6c
andcsantos/mlexercises
/multiplelinearregression.py
1,808
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 22 13:32:37 2018 @author: lasiand """ import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values ##dummy variables #independentes from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() X[:, 3] = labelencoder_X.fit_transform(X[:, 3]) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() #dependentes #labelencoder_y = LabelEncoder() #y = labelencoder_y.fit_transform(y) #avoiding the dummy variable track X = X[:, 1:] #removendo primeira coluna modelo = #dummys - 1 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) from sklearn.linear_model import LinearRegression regressor = LinearRegression() ##cria um objeto de regressao regressor.fit(X_train, y_train) #predicting y_pred = regressor.predict(X_test) #otimizando com Backward Elimination import statsmodels.formula.api as sm X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1) X_opt = X[:, [0, 1, 2, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 1, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 3, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 3]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary()
ac2b45ef810b82758d5ee147ee31f897566ad230
shellyb19-meet/meet2017y1lab4
/caugh_speeding.py
357
4.03125
4
speed = 61 is_birthday = False if not is_birthday: if speed < 31: print("no ticket") elif speed > 30 and speed < 51: print("small ticket") else: print("big ticket") else: if speed < 36: print("no ticket") elif speed > 35 and speed < 56: print("small ticket") else: print("big ticket")
557724847397c80b198f7e6afebbfedc503f96b1
taingocbui/Coursera
/AlgorithmicToolbox/week3/Python/moneychange.py
250
3.53125
4
# Uses python3 import sys def get_change(m): answer = m//10 answer = answer + (m%10)//5 answer = answer + (m%10)%5 return answer if __name__ == '__main__': m = int(sys.stdin.read()) #m = int(input()) print(get_change(m))
5cf0f38f2c0e5eb93d51a45537867604104435e5
taingocbui/Coursera
/AlgorithmicToolbox/week5/change.py
763
3.53125
4
import sys def DPchange(money, coins): MinNumCoins = [0] * (money+1) for m in range(1, money+1): MinNumCoins[m] = sys.maxsize for coin in coins: if m >= coin: change = MinNumCoins[m-coin] + 1 if change < MinNumCoins[m]: MinNumCoins[m] = change return MinNumCoins[money] def RecursiveMinNumCoins(m, coins): if m == 0: return 0 minNum = sys.maxsize for coin in coins: if m >= coin: change = RecursiveMinNumCoins(m-coin, coins) if change+1 < minNum: minNum = change+1 return minNum if __name__ == "__main__": m = int(sys.stdin.read()) coins = [1,3,4] print(DPchange(m, coins))
e1fa97c33df716401b0873340666f7b1fda19020
ygohil2350/infytq-Python_Fandamentals-
/validate_credit_card_number.py
866
3.625
4
#lex_auth_01269445968039936095 def validate_credit_card_number(card_number): #start writing your code here card=str(card_number) l=[] if len(card)==16: for i in card[-2::-2]: n=int(i)*2 if n>9: n1=n%10+n//10 l.append(n1) else: l.append(n) return (sum(l)+sum(list(map(int,card[-1::-2]))))%10==0 else: return False card_number= 5239512608615007 result=validate_credit_card_number(card_number) if(result): print("credit card number is valid") else: print("credit card number is invalid") card_number= 1456734512345698 #4539869650133101 #1456734512345698 # #5239512608615007 result=validate_credit_card_number(card_number) if(result): print("credit card number is valid") else: print("credit card number is invalid")
bbf1edc06f3ea8e92fa9b2916bae24933eeef938
ygohil2350/infytq-Python_Fandamentals-
/sms_encoding.py
851
3.703125
4
#lex_auth_01269444961482342489 def sms_encoding(data): #start writing your code here vowel = "aeiouAEIOU" list1 = data.split() list2 = [] for i in list1: length=len(i) if length == 1: list2.append(i) list2.append(" ")#to add spaces between the words else: count=0 for a in i: if a in vowel: count+=1 if count==length: #to check if all the letters are vowels list2.append(i) list2.append(" ") for a in i: if a not in vowel: list2.append(a) list2.append(" ") list2.pop() #to remove the extra space at the end of the whole sentence q="".join(list2) return q data="I love Python" print(sms_encoding(data))
ed6993edb8dda10d5bd7d30188773f6269c208b3
smsali97/bioinformatics-work
/pollutantmean.py
1,572
3.5
4
''' Created on Apr 17, 2018 @author: Sualeh Ali ''' import csv def main(): directory = "F:/Drive/Books/Bioinformatics/assignments" pollutant = "sulfate" id = range(1,11) pollutantmean(directory, pollutant, id) """ Calculates the mean of a pollutant (sulfate or nitrate) across a specified list of monitors. The function ‘pollutantmean’ takes three arguments: ‘directory’, ‘pollutant’, and ‘id’. Given a vector monitor ID numbers, ‘pollutantmean’ reads that monitor’s particulate matter data from the directory specified in the ‘directory’ argument and returns the mean of the pollutant across all of the monitors, ignoring any missing values coded as NA """ def pollutantmean(directory, pollutant, id=range(1,333)): # counter ctr = 0 # cumulative c_sum c_sum = 0 for i in id: # Each csv files with open(directory + "/{0:03}.csv".format(i), newline='') as csvfile: reader = csv.reader(csvfile, delimiter='\n') next(reader) for row in reader: items = row[0].split(",") # if not empty if pollutant == 'sulfate' and not items[1] == 'NA': c_sum += float(items[1]) ctr += 1 elif pollutant == 'nitrate'and not items[2] == 'NA': c_sum += float(items[2]) ctr += 1 print("{:.3f}".format(c_sum/ctr)) if __name__ == '__main__': main()
7b72f3093deaf07fe7dc3694f0c6462db14b72ab
Abstrys/abstrys-toolkit
/scripts/srep
1,759
3.65625
4
#!/usr/bin/env python import sys import glob import re file_list = None search_term = None replace_term = None # takes 3 args (see usage string for details). if len(sys.argv) < 4: print(""" Usage: srep <searchterm> <replaceterm> <filespec> ... Notes: * All arguments are required. * searchterm and/or replaceterm can be regular expressions. * filespec can be a file name or glob. Multiple filespecs can be specified. """) sys.exit(1) # the first two user arguments are the search and replace terms. (search_term, replace_term) = sys.argv[1:3] # this will alwasy return a list file_list = sys.argv[3:] # process all arguments to see if they're fileglobs (the user can type multiple # fileglobs, such as: *.txt *.md. expanded_list = [] for filespec in file_list: expanded_list += glob.glob(filespec) print("This will replace all instances of '%s' with '%s' in %d files.\n" % ( search_term, replace_term, len(expanded_list))) confirm = input("Continue? (y/n): ") confirm = confirm.lower() if confirm != 'y': print("\nAborted operation.") print("Whew. That was close!\n") sys.exit() print("") for filename in expanded_list: # read in the file contents sys.stdout.write(" %s" % filename) in_file = open(filename) contents = in_file.read() in_file.close() # fuzzle 'em. (contents, times) = re.subn(search_term, replace_term, contents, 0, re.MULTILINE|re.UNICODE) if times > 0: end = 's' if times > 1 else '' print(" - %d replacement%s made." % (times, end)) # write out the results. out_file = open(filename, "w+") out_file.write(contents) out_file.close() else: print("") print("\nfinished!\n") sys.exit(0)
c1dfa57cd7bbe5492f8617a867d280e5e7cd91fc
C0nn0rNash/Neural-Network-classifier-and-optimization
/application L-layered.py
1,630
3.875
4
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009 np.random.seed(1) costs = [] # keep track of cost # Parameters initialization. (≈ 1 line of code) ### START CODE HERE ### parameters = initialize_parameters_deep(layers_dims) ### END CODE HERE ### # Loop (gradient descent) for i in range(0, num_iterations): # Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID. ### START CODE HERE ### (≈ 1 line of code) AL, caches = L_model_forward(X, parameters) ### END CODE HERE ### # Compute cost. ### START CODE HERE ### (≈ 1 line of code) cost = compute_cost(AL, Y) ### END CODE HERE ### # Backward propagation. ### START CODE HERE ### (≈ 1 line of code) grads = L_model_backward(AL, Y, caches) ### END CODE HERE ### # Update parameters. ### START CODE HERE ### (≈ 1 line of code) parameters = update_parameters(parameters, grads, learning_rate) ### END CODE HERE ### # Print the cost every 100 training example if print_cost and i % 100 == 0: print ("Cost after iteration %i: %f" %(i, cost)) if print_cost and i % 100 == 0: costs.append(cost) # plot the cost plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(learning_rate)) plt.show() return parameters
3e2b74991e778c965022834d02d2662a369c1666
subhaminion/Pylearn
/matchparenthesis.py
290
3.828125
4
def matched(str): count = 0 for i in str: print i if i == "(": count += 1 elif i == ")": count -= 1 if count < 0 or count == 0: print 'all matched' else: print 'Something fishy' string = '(abc)' matched(string)
96e43fad4ca2c0ed89fdce56ede8d6e9f260a062
subhaminion/Pylearn
/recur.py
217
3.84375
4
# def calc_factorial(x): # if x == 1: # return 1 # else: # return (x * calc_factorial(x-1)) # print(calc_factorial(4)) def fac(x): if x==1: return 1 else: return (x * fac(x-1)) num = 4 print (fac(num))
1fb9c5027803f73d2c15dac285bd1a9064a0f386
subhaminion/Pylearn
/regextut.py
118
3.671875
4
import re pattern = re.compile(r"\w+") string = "regex is awesome" result = pattern.match(string) print result.group()
00ace827d268e376f6344ddc8fe79857a661fd0f
subhaminion/Pylearn
/second.py
388
3.71875
4
__author__ = 'subham' me = 'Subham' print('Hello subham') #this is a comment line # Another Comment line just to @#$@#% str = 'the price of a good laptop is ' price = 30000 # print 'Hello ' + str + price #throwing an error in first attempt price2 = 40000 print '{0} is thirty thousand. And {1} is fourty'.format(price, price2) print me + ' love way more than ' + str(price2) + 'Money'
44462bf98aa69155790a70f2a9ae5cf71607e393
KingOfRaccoon/python
/main.py
484
3.515625
4
def countOnNumber(data=[], number=0): summary = 0 counter = 0 for i in data: if summary + i <= number: counter += 1 summary += i return summary, counter with open("27888.txt") as file: data = file.read().split() for i in range(len(data)): data[i] = int(data[i]) size = data.pop(0) quantity = data.pop(0) data.sort() print(countOnNumber(data, size)) print(data[600]) print(size) print(data)
0f09dd205b9184aa5faab057156b8f0242d17878
MOHAMMADHOSSEIN-JAFARI/Mini-Project-Gussing-the-numeber
/gussing.py
429
3.53125
4
import random f= 1 g= 99 a = random.randint(f,g) print(a) b= input("please inter: ") while b != 'd': if b == 'k': g= a-1 a = random.randint(f,a-1) print(a) b= input("please inter: ") continue elif b == 'b': f= a+1 a= random.randint(f,g) print(a) b= input("please inter: ") continue print('it is corret')
197a59eb37208a39290d4f5ef87ae6c1989d1bd0
iiison/python_experiments
/dictionary.py
757
3.71875
4
def v(): print('Yep, this shit works.') dic = { 'a' : 'val', 'test' : v, 23 : '23 as strting', 'b' : 'some value here too' } print(dic.get('a')) result = dic.get('b', 'Not available!') print(result) print ('---------------------------------------') # Iteration using for loop: for key in dic : print('{} <===> {}'.format(key, dic.get(key))) print ('---------------------------------------') all_keys = list(dic.keys()) length = len(all_keys) i = 0 while ( i < length ) : print('{} <===> {}'.format(i, all_keys[i])) i += 1 print ('---------------------------------------') for i in range(0, length) : print('{} --- {}'.format(i, all_keys[i])) print ('---------------------------------------') pritn(dic['vs'])
d94010fb59fae9ea75e2a20ab7b02e20dab5f625
iiison/python_experiments
/helloWorld.py
2,097
3.9375
4
from math import pi # import math.pi as pie # import math import input_method string_var = "20" print("Yo YO! " + string_var) print(type(string_var)) # string_var = str(90) string_var = 90 print type(string_var) # print "Say man! this is the number value " + str(string_var) str_ = "honey singh mera bhai hai!" # print str_[3:10] another = 232 formatted = 'some shit {}, and then some more {}'.format(string_var, str_) # observe that %s converts digit to string, basically, str() fxn formattedOld = "some shit %s, and then some more %s" % (string_var, another) print formatted print formattedOld # In operator: print "H" in str_ print "Q" not in str_ triple = """BC Gazab LE BC or Gazab \t(tab) or je to BC matlab next he level""" print triple # String methods print str_.capitalize() print str_ print str_.count('h', 5, len(str_)) print str_.endswith('h', 5, len(str_)) print str_.startswith('h') # Slice the string and then check if string starts with 'h' print str_.startswith('h', 5, len(str_)) print str_.find('h', 3, 20) print "AGB32".isalnum() # NO SPACES print " AGB32".isalnum() # NO SPACES print "AGB32".isalpha() # NO SPACES print " AGB32".isalpha() # NO SPACES print "AGB".isalpha() # NO SPACES # Lists ls = [3, 2, 'yep!'] print ls print len(ls) ls[1] = 'yeah!' # ls[3] = 32 # throws error out of range print ls print ls[1:35] for i in ls: print i # MIND THE INDENTATION if 3 in ls: print "Found 3 in list" copy_ls = ls # List methods ls.append('okay.') print ls ls.insert(2, 'custom') print ls ls.extend([1, 2, 3]) print ls ls.append([1, 2, 3]) print ls ls.extend([1, 2, 3]) ls.remove(1) print ls ls.pop(ls.index('custom')) print ls print "OMG, list are saved as references!" print copy_ls # Tuples tup = (1, 2, 3) tup2 = (3, 2, 1) print tup list_to_tuple = tuple(ls) print ls # ls is still a list print list_to_tuple print tup + tup2 # Dictionaly - Objects dic = { "val" : 1, "val2" : 23 } print dic dic = { "val" : 1, "val2" : 23 # "val" : 11, = Syntax Error } # print dic print pi print(input_method.name_teller())
aad85067c090c60b6095d335c6b9a0863dd76311
dpolevodin/Euler-s-project
/task#4.py
820
4.15625
4
#A palindromic number reads the same both ways. #The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. num_list = [] result = [] # Create a list with elements multiplied by each other for i in range(100,1000): for j in range(100,1000): num_list.append(i * j) word_list_str = map(str, num_list) # Find palindrom in list and add it in new list for element in word_list_str: element_reverse = ''.join(reversed(element)) if element == element_reverse: result.append(element_reverse) # Sort list to find max value in palindromic numbers fin_result = list(map(int, result)) fin_result.sort() # Print max palindromic number print('Max palindrom is: ', fin_result[-1])
70f2ebd8a2757660de025817d99eb4e1a6ec6555
aswathysoman97/LuminarPython
/pythondjangojuneclass/lamda/employee.py
1,180
3.8125
4
class Employee(): def __init__(self,id,name,desgn,salary,exp): self.id=id self.name=name self.desgn=desgn self.sal=salary self.exp=exp def printval(self): print("\n id:",self.id,"\n","name:",self.name,"\n","desgn:",self.desgn,"\n","salary:",self.sal,"\n","exp:",self.exp) f=open("emp") emp=[] for data in f: val=data.rstrip("\n").split(",") id=val[0] name=val[1] desgn=val[2] salary=int(val[3]) exp=int(val[4]) ob=Employee(id,name,desgn,salary,exp) ob.printval() emp.append(ob) uprcs=list(map(lambda Employee:Employee.name.upper(),emp)) print("\n") print("<uppercase>") print(uprcs) salary=list(filter(lambda Employee:Employee.sal>15000,emp)) print("\n<salary>15000>") for i in salary: print(i.name) salgrowth=list(filter(lambda Employee:Employee.exp>=2,emp)) print("\n<increment of 5000 for all employee who have exp>=2>") for j in salgrowth: print("name= ",j.name,"salary= ",j.sal) sal=j.sal+5000 print("new salary= ",sal) print("\n") print("<designation=developer>") dsg=list(filter(lambda Employee:Employee.desgn=="developer",emp)) for k in dsg: print (k.name)
3d82537c0f7694667d9df5dd6f63e969872543b1
aswathysoman97/LuminarPython
/pythondjangojuneclass/lamda/patternmtchng.py
362
3.546875
4
import re # x='[a-z][369][a-z]*' # vname=input("variable name= ") # match=re.fullmatch(x,vname) # if(match!=None): # print("valid") # else: # print("invalid") # validate vehicle registration number x='[klKL]\d{2}[a-zA-Z]{2}\d{4}' vname=input("variable name= ") match=re.fullmatch(x,vname) if(match!=None): print("valid") else: print("invalid")
7d3fa79cb95f79e6a8795d1a5415b9d3bc504b04
aswathysoman97/LuminarPython
/pythondjangojuneclass/dob.py
124
3.65625
4
dob=input("birth year dd-mm-yy: ") byr=dob.split("-") today=int(input("recent year:")) age=(today-int (byr[2])) print(age)
dab6c268e95af478d5c41c58002fb1bed956392f
aswathysoman97/LuminarPython
/pythondjangojuneclass/exception/handling.py
330
3.75
4
n1=int(input("n1=")) n2=int(input("n2=")) try: res=n1/n2 print(res) # except: # print("<zero division error>") except Exception as f: print(f.args) n2 = int(input("another n2=")) res = n1 / n2 print(res) finally: print("exception is abnormal situation") print("program terminate the execution")
3abffd00b7b8830997dd40cedb7c204385c00c1c
aswathysoman97/LuminarPython
/pythondjangojuneclass/class/student.py
812
3.671875
4
class Student: def __init__(self,rollno,name,course,tmark): self.rollno=rollno self.name=name self.course=course self.tmark=tmark def printval(self): print("rollno:",self.rollno,"\n","name:",self.name,"\n","course:",self.course,"\n","total mark:",self.tmark) f=open("studdata") student=[] for data in f: val=data.rstrip("\n").split(",") rollno=val[0] name=val[1] course=val[2] tmark=int(val[3]) ob=Student(rollno,name,course,tmark) ob.printval() student.append(ob) print("\n") for stud in student: print(stud.name.upper()) # print(name.upper()) print("\n") fw=open("winner.txt","w") for stud in student: if(stud.tmark>460): fw.write(stud.name+"\t"+stud.course+"\n") # print(stud.name,":",stud.tmark)
b2a12ab4f0f3701606abc2447f61ec8488e9d327
Mewwaa/Basics-of-Python
/Game_Mewwaa/important_Mewwaa.py
3,269
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Ewa Zalewska # Concept: Simple terminal game # Github: https://github.com/Mewwaa import random class Spell: def __init__(self, name, cost, dmg, magic_type): self.name = name self.cost = cost self.dmg = dmg self.magic_type = magic_type def generate_damage(self): min_wartosc = self.dmg - 15 max_martosc = self.dmg + 15 return random.randrange(min_wartosc,max_martosc) class Item: def __init__(self, name, itemType, description, prop): self.name = name self.itemType = itemType self.description = description self.prop = prop class specialItem: def __init__(self, name, specialItemType, description, prop): self.name = name self.specialItemType = specialItemType self.description = description self.prop = prop class Person: def __init__(self, name, hp, mp, dmg, magic, items, specialItems): self.name = name self.hp = hp self.mp = mp self.dmg = dmg self.magic = magic self.items = items self.maxhp = hp self.maxmp = mp self.actions = ["Attack", "Magic", "Items", "Special Items", "Give up"] self.specialItems = specialItems def generate_damage(self): min_wartosc = self.dmg - 15 max_martosc = self.dmg + 15 return random.randrange(min_wartosc,max_martosc) def generate_spell_damage(self, i): min_wartosc = self.magic[i]["dmg"] - 5 max_martosc = self.magic[i]["dmg"] + 5 return random.randrange(min_wartosc,max_martosc) def take_damage(self, dmg_loss): if (self.hp - dmg_loss < 0): self.hp = 0 else: self.hp -= dmg_loss def get_hp(self): return self.hp def get_mp(self): return self.mp def reduce_mp(self, mp_loss): self.mp -= mp_loss def choose_action(self): i=1 for action in self.actions: print(i, action) i+=1 def heal(self, increased_hp): if(self.hp+increased_hp > self.maxhp): self.hp = self.maxhp else: self.hp += increased_hp def choose_magic(self): i=1 print("Magic") for magicItem in self.magic: print(i, "Name:", magicItem.name, "-- cost: ", magicItem.cost, "--dmg: ", magicItem.dmg, "--type:", magicItem.magic_type) i+=1 def choose_target(self, enemies): i=1 for enemy in enemies: print(str(i) + ":", enemy.name, "hp:", enemy.hp) i+=1 choice = int(input("Choose target:")) - 1 return choice def choose_item(self): i=1 print("Items") for item in self.items: print(i, item["item"].name,"(description:", str(item["item"].description) + ", quantity: ", str(item["quantity"]), ")") i+=1 def choose_specialItem(self): i=1 print("Special items") for specialItem in self.specialItems: print(i, specialItem["item"].name,"(description:", str(specialItem["item"].description) + ", quantity: ", str(specialItem["quantity"]), ")") i+=1
526a90a5eaa144a562bc22133f96e563e753cf64
AvadhootRaikar/PracticePythonPrograms
/count vowels.py
300
4
4
# Code to count the No. of vowels in a Text file file = open("textfile.txt","r") line =file.read() c=0 for i in line: word=i.split(" ") if i=="A" or i=="a" or i=="E" or i=="e" or i=="I" or i=="i"or i=="O"or i=="o"or i=="U"or i=="u": c+=1 print ("count of vowels is ",c) file.close()
f7569057859b1753d6f47293519212bb18f347af
AvadhootRaikar/PracticePythonPrograms
/Simple ATM system.py
4,039
4.03125
4
print('Welcome to Dharavi Bank ATM') restart=('Y') chances = 3 balance = 100.00 while chances >= 0: pin = int(input('Please Enter You 4 Digit Pin: ')) if pin == (1234): print('You entered you pin Correctly\n') while restart not in ('n','NO','no','N'): print('Please Press 1 For Your Balance\n') print('Please Press 2 To Make a Withdrawl\n') print('Please Press 3 To Pay in\n') print('Please Press 4 To Transfer Money\n') print('Please Press 5 To Return Card\n') option = int(input('What Would you like to choose?')) #To check the balance if option == 1: print('Your Balance is Rs.',balance,'\n') restart = input('Would You you like to go back (y / yes or n/ no)? ') if restart in ('n','NO','no','N'): print('Thank You') break #To withdraw money elif option == 2: option2 = ('y') withdrawl = float(input('How Much Would you like to withdraw? ')) if withdrawl % 10 == 0 and withdrawl <= balance: balance = balance - withdrawl print ('\nYour Balance is now Rs.',balance) restart = input('Would You you like to go back (y / yes or n/ no)? ') if restart in ('n','NO','no','N'): print('Thank You') break elif withdrawl %10 != 0: print('Invalid Amount, Please Re-try\n') restart = ('y') elif withdrawl == 1: withdrawl = float(input('Please Enter Desired amount:')) else: print("you don't have sufficient balance") #To pay in or add money to your account elif option == 3: Pay_in = float(input('How Much Would You Like To Pay In? ')) if Pay_in %10 ==0: balance = balance + Pay_in print ('\nYour Balance is now Rs.',balance) else : print("please pay in a valid amount") restart = input('Would You you like to go back (y / yes or n/ no) ? ') if restart in ('n','NO','no','N'): print('Thank You') break #To transfer money elif option == 4: trans =input("please enter account number(14-digits) or mobile number (10 - digits):") transfer = int(input("please enter the amount you wanted to transfer")) if transfer % 10 == 0 and transfer <= balance: balance = balance - transfer print("money transfered to",transfer) print ('\nYour Balance is now Rs.',balance) restart = input('Would You you like to go back (y / yes or n/ no)? ') if restart in ('n','NO','no','N'): print('Thank You') break elif transfer %10 != 0: print('Invalid Amount, Please Re-try\n') restart = ('y') elif transfer == 1: transfer= float(input('Please Enter Desired amount:')) else: print("you don't have sufficient balance") #To return your card elif option == 5: print('Please wait whilst your card is Returned...\n') print('Thank you for your service') break else: print('Please Enter a correct number. \n') restart = ('y') elif pin != ('1234'): print('Incorrect Password') chances = chances - 1 if chances == 0: print('\nNo more tries') break
8b89f2d6afb68ebffa4453f3fddb46c5de544aae
cty123/Leetcode
/1. Two Sum.py
463
3.5
4
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i_index, i_val in enumerate(nums): for j_index, j_val in enumerate(nums): if i_index != j_index: if i_val + j_val == target: return i_index, j_index s = Solution() i, j = s.twoSum([3, 2, 4], 6) print('[%d,%d]' % (i, j))
036285387d4b42972cdb6d57dab29d4f485da633
cty123/Leetcode
/19.py
746
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: window = [] temp = head # Preload window for i in range(n+1): if temp is None: return head.next window.append(temp) temp = temp.next while temp is not None: window.pop(0) window.append(temp) temp = temp.next node = window[0] if node.next is None: return None node.next = node.next.next return head
41b6ee22ddfb9f6ad0d6dc18d0ec4e5bf1e0bb43
anagharumade/Back-to-Basics
/BinarySearch.py
827
4.125
4
def BinarySearch(arr, search): high = len(arr) low = 0 index = ((high - low)//2) for i in range(len(arr)): if search > arr[index]: low = index index = index + ((high - low)//2) if i == (len(arr)-1): print("Number is not present in the input array.") else: pass elif search < arr[index]: high = index index = (high - low)//2 if i == (len(arr)-1): print("Number is not present in the input array.") else: pass else: if arr[index] == search: print("Number found at position: ", index) break if __name__ == "__main__": arr = [1,2,3,4,5,6,7,8,9,12] BinarySearch(arr, 7)
90dd382141f1aa05d85f5f3831beadb31f2497bd
cheetah100/ecosim
/ecosim.py
5,273
3.6875
4
import model import random import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np def get_best_price(industry, min_price): chosen_company = None best_price = 1000000 industry_companies = industries[industry] for company in industry_companies: if company.price < best_price and company.price > min_price and company.stock > 0: chosen_company = company best_price = company.price return chosen_company def buy(person, company): if person.alive: price = company.price * person.consumption company.demand = company.demand + person.consumption if person.balance > price and company.stock >= person.consumption: person.balance = person.balance - price company.balance = company.balance + price company.stock = company.stock - person.consumption if person.pain > -20: person.pain = person.pain - 1 else : person.pain = person.pain + 1 def find_employee(max_salary): for person in people: if person.employer == None and person.salary < max_salary and person.alive : return person return None def scale(l, max_value): list_max = 0 for v in l: if v > list_max: list_max = v divisor = list_max / max_value r = [] for v in l: r.append(int(v / divisor)) return r # SET UP COMPANIES companies = [] industries = {'food':[],'housing':[],'power':[],'transport':[]} company_wealth = [] company_demand = [] company_production = [] company_costs = [] company_revenue = [] company_stock = [] for industry in industries: for x in range(1,4): company = model.Company() company.industry = industry company.balance = 1000000 company.stock = 1000 company.price = 10 + random.randint(1,10) company.max_salary = 40 + random.randint(1,40) companies.append(company) industries[industry].append(company) # SET UP PEOPLE people = [] people_wealth = [] people_alive = [] for x in range(1,100): person = model.Person() person.balance = 1000 person.consumption = 1 person.productivity = 1 + random.randint(1,3) person.salary = 10 + random.randint(1,90) person.min_price = 10 + random.randint(1,10) people.append(person) # ITERATE EACH WEEK FOR A YEAR for week in range(1,500): print('Week', week) # ITERATE PEOPLE - PURCHASE GOOD / SERVICES w = 0 a = 0 for person in people: if person.alive: w = w + person.balance a = a + 1 for industry in industries: company = get_best_price(industry, person.min_price) if company != None: buy(person, company) else : person.pain = person.pain + 1 # Too Much Adversity and they Die if person.pain > 20: person.alive = False people_wealth.append(w) people_alive.append(a) # ITERATE COMPANIES - PRODUCE GOODS / PAY STAFF d = 0 p = 0 s = 0 for company in companies: print('Company ', company.balance) d = d + company.demand s = s + company.stock # Produce New Goods / Services, Pay Living Staff company.production = 0 company.cost = 0 for employee in company.employees: if employee.alive: company.production = company.production + employee.productivity company.cost = company.cost + employee.salary employee.balance = employee.balance + employee.salary company.balance = company.balance - company.cost company.stock = company.stock + company.production p = p + company.production # New Employment (does production meet demand?) print( 'Demand', company.demand, 'Production', company.production) x = company.production - company.demand if x < 0: employee = find_employee(company.max_salary) if employee != None: employee.employer = company company.employees.append(employee) print('New Hire', employee.salary) else: print('No Hire Found', company.max_salary, x) company.max_salary = company.max_salary + 5 else: if len( company.employees ) > 0: employee = company.employees[0] employee.employer = None company.employees = company.employees[1:] print('Employee Fired', employee.salary) if company.demand == 0 and company.price > 5: company.price = company.price - 1 print("No Demand, reducing price",company.price) if company.cost > 0: unit_cost = company.production / company.cost if company.price < unit_cost: company.price = int(unit_cost) + 1 print("Not covering costs, increasing price", company.price) # Reset Demand company.demand = 0 company_demand.append(d) company_production.append(p) company_stock.append(s) print('Final Results - People') for person in people: print(person.productivity, person.min_price, person.balance, person.pain) print('Final Results - Companies') for company in companies: print(company.price, company.balance, company.stock, company.demand) # Plot Results # xref = range(0,len(people_alive)*20,20) xref = range(0,len(people_alive),1) y_pos = np.arange(len(people_alive)) plt.plot(xref, scale(people_wealth,100), label='Wealth' ) plt.plot(xref, scale(people_alive,100), label='Population' ) plt.plot(xref, scale(company_demand,100), label='Demand' ) plt.plot(xref, scale(company_production,100), label='Production' ) plt.plot(xref, scale(company_stock,100), label='Stock' ) # plt.xticks(xref, y_pos) # plt.ylabel('Dollars') plt.xlabel('Week') plt.title('Economic Simulation Results') plt.show()
cf1f0d657e3e744eb6a3793c020a553a0faed8cf
mootfowl/dp_pdxcodeguild
/python assignments/lab16_Pick6_v2.py
2,899
3.875
4
''' LAB16v2: Another approach to the Pick 6 problem that utilizes a function that calls another function. Also, instead of comparing if each of the ticket numbers is in the list of winning numbers, regardless of position, this new version requires ticket and winning numbers match the same index. This mirrors the actual way in which the lottery works. ''' import random def pick_six(): six_random = [] for i in range(6): six_random.append(random.randint(0, 99)) return(six_random) def are_you_feeling_lucky(attempts): matching_numbers = [] expenses = 0 winnings = 0 for tickets in range(attempts): ticket_numbers = pick_six() print(f"NEXT TICKET {ticket_numbers}.") # Compares the ticket numbers at each index (0-5) with the corresponding winning numbers. # If they match, they are added to the matching numbers list. # if ticket_numbers[0] == winning_numbers[0]: # matching_numbers.append(ticket_numbers[0]) # # if ticket_numbers[1] == winning_numbers[1]: # matching_numbers.append(ticket_numbers[1]) # # if ticket_numbers[2] == winning_numbers[2]: # matching_numbers.append(ticket_numbers[2]) # # if ticket_numbers[3] == winning_numbers[3]: # matching_numbers.append(ticket_numbers[3]) # # if ticket_numbers[4] == winning_numbers[4]: # matching_numbers.append(ticket_numbers[4]) # # if ticket_numbers[5] == winning_numbers[5]: # matching_numbers.append(ticket_numbers[5]) for i in range(6): if ticket_numbers[i] == winning_numbers[i]: matching_numbers.append(ticket_numbers[i]) print(f"You matched {matching_numbers}.") # Determines the amount won for this ticket, if anything. if len(matching_numbers) == 1: winnings += 4 elif len(matching_numbers) == 2: winnings += 7 elif len(matching_numbers) == 3: winnings += 100 elif len(matching_numbers) == 4: winnings += 50000 elif len(matching_numbers) == 5: winnings += 1000000 elif len(matching_numbers) == 6: winnings += 25000000 expenses += 2 # Adds 2 dollars to the expenses total per ticket print(f"You've spent ${expenses} on tickets.") print(f"Your earnings so far are ${winnings}.") print(f"Your return on investment (ROI) is", (winnings - expenses) / expenses) matching_numbers = [] # Empties the list for the next ticket i_am_feeling_lucky = int(input("Are you feeling lucky!? \nHow many tickets would you like to buy? ")) number_of_attempts = i_am_feeling_lucky winning_numbers = pick_six() print(f"The winning numbers are {winning_numbers}.") are_you_feeling_lucky(number_of_attempts)