blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
0835099df9d0db1029189f8c83d59c5414abb0e5
Likhi-organisations/100-days
/RTP.py
357
3.828125
4
def prime(n): for i in range(2,n): if(n%i==0): break else: return(1) n=int(input('enter a number')) a=n cnt=1 while prime(n) and (n>0): n=n//10 if prime(n): cnt=1 else: cnt=0 if cnt==1: print(a,'right truncanted prime') else: print(a,'not a right truncanted prime')
fe2a0c0800cc5d597776fb8c927d308b4a3bd356
livingstone27/machine-learning-algorithms-scratch
/linear_regression/basic_model.py
1,532
3.75
4
# coding: utf-8 # In[69]: import numpy as np import matplotlib.pyplot as plt # # Generating training samples # In[70]: poly_order = 4 # Number of training samples N = 10 # Generate equispaced floats in the interval [0, 2*pi] x_train = np.linspace(0, 2*np.pi, N) # Generate noise mean = 0 std = 0.05 # Generate some numbers from the sine function y = np.sin(x_train) # Add noise y += np.random.normal(mean, std, N) #defining it as a matrix y_train = np.asmatrix(y.reshape(N,1)) # # adding the bias and higher order terms to x # In[71]: x = np.asmatrix(np.append(np.ones((N,1)),x_train.reshape((N,1)),axis = 1)) # # finding the optimum weights # In[72]: w = (x.T*x).I*x.T*y_train print(w) # # generating test samples # In[73]: M = 100 x_t = np.linspace(0, 2*np.pi, M) x_test = np.asmatrix(np.append(np.ones((M,1)),x_t.reshape(M,1),axis = 1)) # # predicting the outputs for the test sample # In[74]: y_test = x_test*w # # Error (cost) # In[75]: y_fin = x * w print("error:- ",np.asmatrix(y_train-y_fin).T*np.asmatrix(y_train-y_fin)) # # ploting the results # In[76]: plt.plot(x_train,y_train,'o',label = 'training data') plt.plot(x_t,y_test,'.',label = 'testing data') plt.legend() plt.grid() plt.title("Vanilla regression") plt.show() # # Observations # As the number of parameters is only 2 , # - the model is estimated by a straight line # - The error is pretty high # # By increasing the variance of the noise # - There error has increased # - But there is not much shift in the plots
e721a7bfe849bff35cd3506f7fe0267378885643
joeyxin-del/python_learning
/data_type_tuple.py
307
4.21875
4
#tuple 元组,和list非常相似 #但是 tuple 一旦初始化就不能修改。 #他没有append(),insert()这样的方法 tuple1 = (1,2,3,123.456,'xin','新') print(tuple1) #修改tuple----内嵌list list1 =['小明','小李'] tuple2 = (1,2,3,list1) print(tuple2) list1[0]='LiMing' print(tuple2)
f2099a4bcfd2848b9f935163eb735edf0631750d
moghadban/Hashing-Words-MD5-SHA256
/Hashing-Words-with-Python.py
3,510
4.1875
4
''' Name: Mojahed Ghadban Hashing Words with Python Description: This Python script will take in a list of words, compute their MD5 and SHA256 hash values, return two dictionaries, and will execute the word along its corresponding hashes. A module to calculate the MD5 and SHA256 values of a list of words will be named calcHashFunc, and the main function will prompt user for words to be hashed, once input is received, the word list is passed to calcHashFunc. The returned dictionaries are to be printed out in this function. Usage: python.exe Hashing-Words-with-Python.py ''' #Importing library for hash and message digest algorithms import hashlib #Function calcHashFunc def calcHashFunc(wordList): '''Function that takes in a list of words and return two dictionaries: md5Dict and sha256Dict, containing the word and it’s corresponding hash value.''' md5Dict = {} #Initializing an empty dictionary to store md5 hash values sha256Dict = {} #Initializing an empty dictionary to store sha256 hash values #Loop through list, find md5 / sha256 hash values, store them in dictionaries md5Dict / sha256Dict, do necessary encoding, return dictionaries md5Dict / sha256Dict for x in wordList: md5Dict[x] = hashlib.md5(str(x).encode('utf-8')).hexdigest() #processing each word 'x' and calculating its md5 hash value to dictionary 'md5Dict' #NOTICE: string is encoded to 'utf-8', its hexidecimal value is parsed, & stored value with its key. sha256Dict[x] = hashlib.sha256(str(x).encode('utf-8')).hexdigest() #processing each word 'x' and calculating its sha256 hash value to dictionary 'sha256Dict' #NOTICE: string is encoded to 'utf-8', its hexidecimal value is parsed, & stored value with its key. return md5Dict,sha256Dict #returning both dictionaries back to the main function. #Main function if __name__ == '__main__': '''main function will prompt user for words to be hashed, once input is received, the word list is passed to calcHashFunc. The returned dictionaries are to be printed out in this function.''' print("\n\n\t\t\t ======PROGRAME INFORMATION======\n") print("\t\t\t\t Name: Mojahed Ghadban") print("\t\t\t Hashing Words with Python .") print("\t\tDescription: Finding md5/sha256 hash values of list of words") print("\t\t\t Usage: python.exe Hashing-Words-with-Python.py\n\n") repeat = 'Y' #Initializing 'repeat' as the letter 'Y' to sgore user repetition for another word. list1 = [] #Initializing list to store user's input(s) of list of words print("\n\n\n\t\t\t ========PROGRAME INPUT=========\n") while repeat == 'Y' or repeat == 'y': #Loop as long as user response is "y" or "Y", userIn = input(" Please enter a word to be hashed: ") #User is prompted to enter a word to be hashed. list1.append(str(userIn)) #Adding the user's input as a string and appending the list, list1 repeat = input(" Would you like to process another word? (Y/N): ") #Asking the user again to process another word by "y" or "Y" response md5ValDict, sha256ValDict = calcHashFunc(list1) #md5ValDict and sha256ValDict are set to call calcHashFunc function and to pass string list1 #calcHashFunc function will return TWO different dictionaries. print("\n\n\n\n\n\t\t\t ========PROGRAME OUTPUT========") print("\n - Word:md5 %s \n - Word:sha256 %s" %(md5ValDict, sha256ValDict)) #Displaying the word along its corresponding hashes print("\n\n\t\t\t ========END OF PROGRAME========")
30c6a5544e65b1a20e2f976d13ed5a0e07dcccaf
OmSoma1912/P104_3M-s
/P104/teller.py
2,044
3.546875
4
import csv def mean(): with open('height-weight.csv', newline = '')as f: reader = csv.reader(f) file_data = list(reader) file_data.pop(0) new_data = [] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(float(n_num)) n = len(new_data) total = 0 for x in new_data: total += x mean = total/ n print("Mean/Average is:" + str(mean)) def mode(): with open('height-weight.csv', newline = '')as f: reader = csv.reader(f) file_data = list(reader) file_data.pop(0) new_data = [] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(n_num) data = Counter(new_data) mode_data_for_range = { "50-60" : 0, "60-70" : 0, "70-80" : 0 } for height, occurence in data.items(): if 50 < float(height) < 60: mode_data_for_range["50-60"] += occurence elif 60 < float(height) < 70: mode_data_for_range["60-70"] += occurence elif 70 < float(height) < 80: mode_data_for_range["70-80"] += occurence mode_range, mode_occurence = 0,0 for range, occurence in mode_data_for_range.items(): if occurence > mode_occurence: mode_range, mode_occurence = [int(range.split("-")[0]), int(range.split("-")[1])], occurence mode = float((mode_range[0] + mode_range[1]) / 2) print(f"Mode is -> {mode:2f}") def median(): with open('height-weight.csv', newline = '')as f: reader = csv.reader(f) file_data = list(reader) file_data.pop(0) new_data = [] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(n_num) n = len(new_data) new_data.sort() if n % 2 == 0: median1 = float(new_data[n//2]) median2 = float(new_data[n//2 - 1]) median = float(median1 + median2)/2 else: median = new_data[n//2] print("Median is: " + str(median)) mean() mode() median()
cc5b10885088a146cd8720ed88f0490e64642d38
NicoKNL/coding-problems
/problems/kattis/owlandfox/sol.py
336
3.6875
4
def sum_of_digits(n): s = map(int, list(str(n))) return sum(s) def solve(): n = int(input()) target = sum_of_digits(n) while True: n = n - 1 if sum_of_digits(n) == target - 1: break print(n) if __name__ == "__main__": n = int(input()) for _ in range(n): solve()
1fde21d075e48edaf29b6eb8a438fba84abbf37b
fguedez1311/POO_Tecnologico
/Examen1.py
954
3.953125
4
class Persona: def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def visualizar(self): return ''' Nombre \t {} Edad \t {}'''.format(self.nombre, self.edad) class Estudiante(Persona): def __init__(self, nombre, edad, id): super().__init__(nombre, edad) self.id = id def visualizar(self): return super().visualizar()+"\n"+"\t id\t{}" .format(self.id) class Profesor(Persona): def __init__(self, nombre, edad, salario): super().__init__(nombre, edad) self.salario = salario def visualizar(self): return super().visualizar()+"\n"+"\t id\t{}" .format(self.salario) print("Datos de persona") p = Persona("Francisco", 18) print(p.visualizar()) print("Datos de Estudiante") e = Estudiante("Francisco", 18, 4879) print(e.visualizar()) print("Datos del profesor") pr = Profesor("Angel", 32, 4500) print(pr.visualizar())
e4cfe4468d460bcb2741c2dd50dcbff10ed47d65
NIUNIUN/python-webapp
/slots.py
2,825
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from types import MethodType # 正常情况下,我们可以给实例绑定属性,也可以个实例绑定方法 # 但是,绑定的属性和方法只对当前实例有效,如果有要为所有实例绑定属性和方法,则可以为类绑定属性和方法 # __slots__ 可以限定绑定的属性 # __slots__ 只对当前类实例起作用,对继承的子类是不起作用的,除非在子类中也定义__slots__,这时候子类运行绑定的属性就是父类+子类的__slots__ class Student(object): def __init__(self): pass # 以下是给实例动态绑定属性和方法,只对当前实例起作用,不对Student其他实例有效 TomStudent = Student() TomStudent.name = "tony" # 动态绑定属性 print("name = ",TomStudent.name) def print_info(self,student): print("print_info = ",self.name," class_name= ",student.__class__.__name__) # 动态绑定方法 TomStudent.printf = MethodType(print_info,TomStudent) TomStudent.printf(TomStudent) # 验证print_info(),其他实例是否能调用 BobStudent = Student() BobStudent.name = "bob" # BobStudent.print() # 不能调用,因为没有改方法 # 给所有实例绑定属性和方法,那就是对类进行绑定 Student.print = print_info BobStudent.print(BobStudent) # 对类进行绑定方法后,能够调用 class AStudent(Student): def __init__(self): pass # 验证类绑定后的方法,子类是否能调用。 # 验证结果:子类能成功调用 AStudent = Student() AStudent.name = 'A' AStudent.print(AStudent) # 限制实例属性 ,使用 __slots__ class Teacher(object): __slots__ = ('name','age') # 允许被绑定的属性 ATeacher = Teacher() ATeacher.name = "aTeacher" # ATeacher.address = "xxx省xxx市" print('ATeacher.name = ',ATeacher.name) # print("ATeacher.address = ",ATeacher.address) # address不在允许属性范围内,报错 class BTeacher(Teacher): def __init__(self): pass bTeacher = BTeacher() bTeacher.name = "bTeacher" bTeacher.address = "xxx省xxx市" print('\nbTeacher.name = ',bTeacher.name) print("bTeacher.address = ",bTeacher.address) # 因为__slots__ ,只对当前实例起作用,对子类没有限制,还是可以绑定其他属性 # 作用:使用__slots__对子类也起作用,那么在子类中也定义__slots__ class CTeacher(Teacher): __slots__ = ('address') def __init__(self): pass cTeacher = CTeacher() cTeacher.name = 'cTeacher' cTeacher.address ='xx省xx市' # cTeacher.email = "123456789@qq.com" print('\ncTeacher.name = ',cTeacher.name) print("cTeacher.address = ",cTeacher.address) # print("cTeacher.email = ",cTeacher.email) # 因为子类也使用了__slots__,子类的__slots__ = 父类的__slots__ + 子类的__slots__
14f77a77ff50ea0b9ee3799c1f5eac5ddf6ef0ae
sandeepshiven/python-practice
/working with csv files/practice/prob1.py
3,466
4.03125
4
'''For this exercise, you'll be working with a file called Each row of data consists of two columns user's first name, and a user's last name. Implement the following function Takes in a first name and a last name and adds a new user to the ''' from os import system from csv import DictReader, DictWriter def start(): while True: system("clear") print("What do you want to do? \n1. Insert\n2. View\n3. Find\n4. Update User\n5. Exit") choice = int(input("Enter your choice: ")) if choice == 1: first_name = input("Enter first name of user: ") last_name = input("Enter last name of user: ") add_user(first_name,last_name) input() elif choice == 2: display() input() elif choice == 3: first = input("Enter first name: ") last = input("Enter last name: ") result = find_user(first,last) if result: print(f"User found at row: {result}") input() else: print("User not found") input() elif choice == 4: old_first = input("Enter first name of old user: ") old_last = input("Enter last name of old user: ") new_first = input("Enter first name of new user: ") new_last = input("Enter last name of new user: ") result = update_user(old_first,old_last,new_first,new_last) print(f"Users Updated: {result}") input() else: print("Invalid Choice") input() def add_user(first, last): with open('user.csv','r+') as file: read = DictReader(file) if read.fieldnames == None: header = ['firstName','lastName'] data = DictWriter(file,fieldnames=header) data.writeheader() data.writerow({ 'firstName':first, 'lastName' : last }) else: header = ['firstName','lastName'] data = DictWriter(file,fieldnames=header) data.writerow({ 'firstName':first, 'lastName' : last }) def display(): with open('user.csv','r') as file: read = DictReader(file) for i in read: print(i['firstName'],i['lastName']) def find_user(first,last): with open('user.csv','r') as file: read = DictReader(file) count = 1 for i in read: if i["firstName"] == first and i["lastName"] == last: return count count += 1 return 0 def update_user(f_old,l_old,f_new,l_new): with open('/media/sandeep/sandeep files1/github/python-practice/working with csv files/practice/user.csv','r') as file: read = DictReader(file) count = [] flag = 0 for i in read: if i["firstName"] == f_old and i["lastName"] == l_old: i["firstName"] = f_new i["lastName"] = l_new flag += 1 count.append(i) with open('user.csv','w') as file: header = ['firstName','lastName'] write = DictWriter(file,fieldnames=header) write.writeheader() for i in count: write.writerow(i) return flag if __name__ == '__main__': start()
e65c706d816242c3c2e6c2e8b03039a133abbc18
hchimata/ProjectEuler
/Question-6_Original.py
738
3.78125
4
""" QUESTION: The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ """ Formula: sum of squares=n*(n+1)(2n+1)/6 square of sum=(n*(n+1)/2)^2 """ n=int(input('Enter the number of natural numbers: ')) square_of_sum=((n*(n+1))/2)**2 print(square_of_sum) sum_of_square=(n*(n+1)*(2*n+1))/6 print(square_of_sum-sum_of_square)
4f2f42d90dcb5ac4f35bf90e30af2409c322f500
davidrball/python_practice
/OOP_practice.py
1,823
4.40625
4
class Pets: def __init__(self): pass petlist = [] def addpet(self,pet): self.petlist.append(pet) def listpets(self): print "I have {} pets".format(len(self.petlist)) class Dog: #classes create objects, which have attributes, the __init__() method initializes an object's initial attributes by giving them their default values def __init__(self,name,age): #basically just saying that each class, dog, has these two properties needed to initialize it, name and age self.name = name self.age = age #note, init is called autoamtically when we create new dog instances species = 'mammal' #all dogs share this, that their species is mammal, but name and age are particular to each dog #also have "instance methods" have to pass it "self" def description(self): return "{} is {} years old".format(self.name,self.age) #can also take an external input def speak(self, sound): return "{} says {}".format(self.name, sound) #then we can create child classes, that inherit everything from the dog class, but can extend or overwrite certain properties class Pug(Dog): def chuff(self, num): return "{} chuffs {} times".format(self.name,num) class Aussie(Dog): def run(self, speed): return "{} runs at {} miles per hour".format(self.name,speed) mypets = Pets() ava = Aussie("Ava",3) lou = Pug("Lou",1) mypets.addpet(ava) mypets.addpet(lou) mypets.listpets() ''' print(lou.chuff(3)) print(ava.run(10)) print(ava.name, ava.age) print(ava.species) #can check if different objects are an instance of a class print(isinstance(ava,Dog)) print(isinstance(lou,Dog)) print(isinstance(lou,Pug)) print(isinstance(lou,Aussie)) #it works! #print(ava.description()) #print(ava.speak('woof woof'))'''
c6609eb84454b5c7bcb81e9ae89652186d308706
Maowason/Python_Tutorial
/importing modules and exploring std libraries.py
1,860
3.625
4
import my_module courses = ['History', 'Math', 'Physics', 'Compsci'] index = my_module.find_index(courses, 'Math') print(index) # Now we can also make the modulename shorter import my_module as mm index = mm.find_index(courses, 'Math') # Works fine print(index) # Now there is a way to import the function itself from my_module import find_index # This only gives us access to that function index = find_index(courses, 'Math') # Works fine print(index) # This only gives us access to that function # Gives us access to both test and function from my_module import find_index, test_string index = find_index(courses, 'Math') # Works fine print(index) print(test_string) # This will make the function name shorter from my_module import find_index as fi # It should be readable though index = fi(courses, 'Math') # Works fine print(index) # Not recommended since now we dont know where did find_index() come from from my_module import * index = find_index(courses, 'Math') # Works fine print(index) print(test_string) import sys print(sys.path) # Will show the order in which python checks for files # First it'll check in the directory where we are running the script # Then it'll check in the python path # Then in std libraries dir # Then in the site-packages # But we can append new paths also---- # sys.path.append('/Users/.....') # print(sys.path) import random courses = ['History', 'Math', 'Physics', 'Compsci'] random_course = random.choice(courses) print(random_course) import math rads = math.radians(90) print(math.sin(rads)) import datetime import calendar today = datetime.date.today() print(today) print(calendar.isleap(2020)) import os # Will give us access to underlying OS print(os.getcwd()) # Get current working dir print(os.__file__)
5fc37280983116bd30f1a6e0a9c38ba57664b81b
Sai-Sindhu-Chunduri/Python-programs
/vowelcount.py
291
3.984375
4
#Program to give vowel count. s=input() a="aeiouAEIOU" count=0 '''for i in s: if i in a: count+=1 print("count of vowels is ",count)''' #or --> Wroking with range: for i in range(len(s)): if s[i] in a: count+=1 print("count of vowels is ",count)
e8f7e42321a4aac16571b442dab89f9d3bc84277
aironi/slackshot
/input.py
934
3.5
4
import threading import RPi.GPIO as GPIO import time ''' A named input that reads a GPIO pin ''' class Input(threading.Thread): _pressed = False def __init__(self, name, pin): threading.Thread.__init__(self) self._pressed = False self.channel = pin self.name = name print "Initializing channel {} as input for {}".format(self.channel, self.name) GPIO.setmode(GPIO.BCM) GPIO.setup(self.channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.daemon = True self.start() def run(self): previous = 0 while True: current = GPIO.input(self.channel) time.sleep(0.05) if current == 1 and previous == 0: self._pressed = True print "{} was triggered.".format(self.name) while self._pressed: time.sleep(0.05) previous = current
1b15d92fbd5d19b138b1f7e84f3654b607fff090
tatumakseli/suomi
/suomi.py
3,306
3.78125
4
class Translate: def __init__(self, number): Translate.convert(self) self.string = str(number) self.decimals = False if "." in self.string or "," in self.string: self.decimals = True if "." in self.string: self.whole_int, self.dec_int = int(self.string.split(".")) elif "," in self.string: self.whole_int, self.dec_int = int(self.string.split(",")) else: self.whole_int = int(number) if len(str(self.whole_int)) > 15: print("number too big") return print(Translate.iteriter(self)) def iteriter(self): self.text = "" while self.whole_int != 0: bigger = False correct_index = None previous_index = None for key, value in self.partitive.items(): if len(str(self.whole_int)) >= key: correct_index = key break elif previous_index == None: previous_index = True elif previous_index != None: previous_index = correct_index correct_index = key if len(str(self.whole_int)) >= correct_index and len(str(self.whole_int)) < previous_index: break if len(str(self.whole_int)) > 2: etu = str(self.whole_int)[:-correct_index+1] else: etu = str(self.whole_int) self.text += Translate.threedigit(self,etu,correct_index, under_three_digit=False) break self.text += Translate.threedigit(self,etu, correct_index) self.whole_int = int(str(self.whole_int)[len(etu):]) return self.text def threedigit(self, etu, correct_index, under_three_digit=True): etu_str = "" if under_three_digit != False: ending = self.partitive[correct_index] else: ending = "" if len(etu) == 3: etu_str += Translate.hundred(self, etu, etu_str) if len(etu) == 2: etu_str += Translate.ten(self, etu, etu_str) if len(etu) == 1: if str(etu) == "1": if under_three_digit == True: ending = self.nominative[correct_index] return ending etu_str += Translate.one(self, etu, etu_str) return etu_str + ending def hundred(self, etu, etu_str): if etu[0] == "1": etu_str += "sata" else: etu_str += self.oneto19[int(etu[0])] + "sataa" if etu[1] == "0" and etu[2] == "0": return etu_str if etu[1] != "0": etu_str = Translate.ten(self, etu[1:], etu_str) else: etu_str = Translate.one(self, etu[-1], etu_str) return etu_str def ten(self, etu, etu_str): try: etu_str += self.oneto19[int(etu)] except: if etu[1] == "0": etu_str += self.oneto19[int(etu[0])] + "kymmentä" else: etu_str += self.oneto19[int(etu[0])] + "kymmentä" + Translate.one(self, etu[1], etu_str) return etu_str def one(self, etu, etu_str): etu_str = self.oneto19[int(etu)] return etu_str def convert(self): self.partitive = { 13: "biljoonaa", 10: "miljardia", 7: "miljoonaa", 4: "tuhatta", 3: "sataa", } self.nominative = { 13: "biljoona", 10: "miljardi", 7: "miljoona", 4: "tuhat", 3: "sata", } self.oneto19 = { 1: "yksi", 2: "kaksi", 3: "kolme", 4: "neljä", 5: "viisi", 6: "kuusi", 7: "seitsemän", 8: "kahdeksan", 9: "yhdeksän", 10: "kymmenen", 11: "yksitoista", 12: "kaksitoista", 13: "kolmetoista", 14: "neljätoista", 15: "viisitoista", 16: "kuusitoista", 17: "seitsemäntoista", 18: "kahdeksantoista", 19: "yhdeksäntoista"} luku = 35036 Translate(luku)
7bc6cecf81b187c4daf08b8ed734fe94c23644c6
andrikoulas7/python_examples
/PassGen.py
252
3.84375
4
import string from random import* characters = string.ascii_letters + string.punctuation + string.digits password = "".join(choice(characters)for x in range(randint(8,8))) print("Password Generator") print() print("Your new password is: " + password)
5f1509d574466ae6f6966b1d6a01a04348a892b2
rayankikavitha/InterviewPrep
/Airbnb/find_path_between_nodes_in_binary_tree.py
2,053
3.828125
4
class node(): def __init__(self,val = None): self.val = val self.left = None self.right = None # create a binary tree """ 17 / \ 6 46 / \ \ 3 12 56 / / \ / 1 9 15 48 """ root = node(17) root.left=node(6) root.right=node(46) root.left.left = node(3) root.left.right = node(12) root.left.right.left = node(9) root.left.right.right = node(15) root.left.left.left = node(1) root.right.right = node(56) root.right.right.left =node(48) # find path is find common acestor def find_path(root, val1, path=[]): if root is None: return False path.append(root.val) if root.val == val1: return True if find_path(root.left, val1, path) or find_path(root.right, val1, path): return True path.pop() return False def path_between_nodes(root, val1, val2): path_between = [] path1, path2 = [], [] i,j = 0,0 if find_path(root,val1,path1) and find_path(root,val2,path2): print ("path exists") while i < len(path1) and j < len(path2): if i == j and path1[i] == path2[j]: i +=1 j +=1 else: intersection = i -1 break print (path1, path2) # now printing the path comes in the pictures for i in range(len(path1)-1, intersection-1, -1): path_between.append(path1[i]) for i in range(intersection+1, len(path2)): path_between.append(path2[i]) return path_between #print (root.val) #print (path_between_nodes(root ,3, 15)) def dfs_inorder(root): # inorder left,value,right if root: dfs_inorder(root.left) print (root.val) dfs_inorder(root.right) def dfs_preorder(root): if root: print (root.val) dfs_preorder(root.left) dfs_preorder(root.right) def dfs_postorder(root): # inorder left,value,right if root: dfs_postorder(root.left) dfs_postorder(root.right) print (root.val) dfs_preorder(root) dfs_inorder(root) dfs_postorder(root) def bfs(root): if root: q=[root] while q: cur_node = q.pop() print (cur_node.val, end = ' ') if cur_node.left: q.insert(0,cur_node.left) if cur_node.right: q.insert(0,cur_node.right) print ("breadth first search") bfs(root)
9f2b8da2f6beabb6840703ff7a6862281c08891e
Ashish9426/Machine-Learning-Algorithms
/3. Logistic_Rregression/logistic_Rregression_Accuracy.py
1,830
3.890625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt # step 1: read the data from data source df = pd.read_csv('./heart_disease.csv') # step 2: clean the data / prepare the data for ML operation # - 2.1: remove all missing values (NaN) # - 2.2: add or remove required columns df = df.drop(['trestbps', 'chol', 'fbs', 'restecg'], axis=1) print(df.columns) # print(df.info()) # - 2.3: adjust the required data types (data types conversion) # - 2.4: conversion of textual to numeric values # - 2.5: scale the values # step 3: create the model (formula) from sklearn.linear_model import LogisticRegressionCV x = df.drop('target', axis=1) y = df['target'] # split the data into train and test sets from sklearn.model_selection import train_test_split # split the data into 80% of train and 20% of test data # 345345: 86 # 123456: 90 x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=123456) model = LogisticRegressionCV(max_iter=1000) # train the model using train data model.fit(x_train, y_train) # step 4: perform the operation (predict the future value) y_predictions = model.predict(x_test) # print(y_test) # print(y_predictions) # print(len(y_predictions)) # step 5: model evaluation from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, classification_report cm = confusion_matrix(y_test, y_predictions) print(cm) tn = cm[0][0] fp = cm[0][1] fn = cm[1][0] tp = cm[1][1] accuracy = (tn + tp) / (tn + tp + fn + fp) print(f"1.1 accuracy: {accuracy * 100}%") print(f"1.2 accuracy: {accuracy_score(y_test, y_predictions) * 100}%") print(f"2. f1 score = {f1_score(y_test, y_predictions)}") print(classification_report(y_test, y_predictions)) # step 6: data visualization of result # plt.scatter(x['age'], x['oldpeak'], color="red") # plt.show()
e21cb7602f78de84a7f15834297d9471af2665bf
anhualin/MyLearning
/PythonDS/Module4/assignment2.py
6,708
4
4
import pandas as pd import matplotlib.pyplot as plt import matplotlib import math from sklearn import preprocessing #import assignment2_helper as helper def scaleFeatures(df): # SKLearn has many different methods for doing transforming your # features by scaling them (this is a type of pre-processing). # RobustScaler, Normalizer, MinMaxScaler, MaxAbsScaler, StandardScaler... # http://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing # # However in order to be effective at PCA, there are a few requirements # that must be met, and which will drive the selection of your scaler. # PCA required your data is standardized -- in other words it's mean is # equal to 0, and it has ~unit variance. # # SKLearn's regular Normalizer doesn't zero out the mean of your data, # it only clamps it, so it's inappropriate to use here (depending on # your data). MinMaxScaler and MaxAbsScaler both fail to set a unit # variance, so you won't be using them either. RobustScaler can work, # again depending on your data (watch for outliers). For these reasons # we're going to use the StandardScaler. Get familiar with it by visiting # these two websites: # # http://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler # # http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler # # --------- # Feature scaling is the type of transformation that only changes the # scale and not number of features, so we'll use the original dataset # column names. However we'll keep in mind that the _units_ have been # altered: scaled = preprocessing.StandardScaler().fit_transform(df) scaled = pd.DataFrame(scaled, columns=df.columns) #print "New Variances:\n", scaled.var() #print "New Describe:\n", scaled.describe() return scaled def drawVectors(transformed_features, components_, columns, plt, scaled): if not scaled: return plt.axes() # No cheating ;-) num_columns = len(columns) # This funtion will project your *original* feature (columns) # onto your principal component feature-space, so that you can # visualize how "important" each one was in the # multi-dimensional scaling # Scale the principal components by the max value in # the transformed set belonging to that component xvector = components_[0] * max(transformed_features[:,0]) yvector = components_[1] * max(transformed_features[:,1]) ## visualize projections # Sort each column by it's length. These are your *original* # columns, not the principal components. important_features = { columns[i] : math.sqrt(xvector[i]**2 + yvector[i]**2) for i in range(num_columns) } important_features = sorted(zip(important_features.values(), important_features.keys()), reverse=True) print "Features by importance:\n", important_features ax = plt.axes() for i in range(num_columns): # Use an arrow to project each original feature as a # labeled vector on your principal component axes plt.arrow(0, 0, xvector[i], yvector[i], color='b', width=0.0005, head_width=0.02, alpha=0.75) plt.text(xvector[i]*1.2, yvector[i]*1.2, list(columns)[i], color='b', alpha=0.75) return ax # Look pretty... matplotlib.style.use('ggplot') # Do * NOT * alter this line, until instructed! scaleFeatures = True # TODO: Load up the dataset and remove any and all # Rows that have a nan. You should be a pro at this # by now ;-) # # .. your code here .. df = pd.read_csv('C:/Users/alin/Documents/SelfStudy/PythonDS/DAT210x/Module4/Datasets/kidney_disease.csv') df = df.dropna(axis = 0) # Create some color coded labels; the actual label feature # will be removed prior to executing PCA, since it's unsupervised. # You're only labeling by color so you can see the effects of PCA labels = ['red' if i=='ckd' else 'green' for i in df.classification] # TODO: Use an indexer to select only the following columns: # ['bgr','wc','rc'] # # .. your code here .. df = df[['bgr', 'rc', 'wc']] df.rc = pd.to_numeric(df.rc, errors = 'coerce') df.wc = pd.to_numeric(df.wc, errors = 'coerce') # TODO: Print out and check your dataframe's dtypes. You'll probably # want to call 'exit()' after you print it out so you can stop the # program's execution. # # You can either take a look at the dataset webpage in the attribute info # section: https://archive.ics.uci.edu/ml/datasets/Chronic_Kidney_Disease # or you can actually peek through the dataframe by printing a few rows. # What kind of data type should these three columns be? If Pandas didn't # properly detect and convert them to that data type for you, then use # an appropriate command to coerce these features into the right type. # # .. your code here .. df.rc = pd.to_numeric(df.rc, errors = 'coerce') df.wc = pd.to_numeric(df.wc, errors = 'coerce') df.dtypes # TODO: PCA Operates based on variance. The variable with the greatest # variance will dominate. Go ahead and peek into your data using a # command that will check the variance of every feature in your dataset. # Print out the results. Also print out the results of running .describe # on your dataset. # # Hint: If you don't see all three variables: 'bgr','wc' and 'rc', then # you probably didn't complete the previous step properly. # # .. your code here .. df.var(axis = 0) # TODO: This method assumes your dataframe is called df. If it isn't, # make the appropriate changes. Don't alter the code in scaleFeatures() # just yet though! # # .. your code adjustment here .. if scaleFeatures: df = scaleFeatures(df) # TODO: Run PCA on your dataset and reduce it to 2 components # Ensure your PCA instance is saved in a variable called 'pca', # and that the results of your transformation are saved in 'T'. # # .. your code here .. from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(df) T = pca.transform(df) # Plot the transformed data as a scatter plot. Recall that transforming # the data will result in a NumPy NDArray. You can either use MatPlotLib # to graph it directly, or you can convert it to DataFrame and have pandas # do it for you. # # Since we've already demonstrated how to plot directly with MatPlotLib in # Module4/assignment1.py, this time we'll convert to a Pandas Dataframe. # # Since we transformed via PCA, we no longer have column names. We know we # are in P.C. space, so we'll just define the coordinates accordingly: ax = drawVectors(T, pca.components_, df.columns.values, plt, scaleFeatures) T = pd.DataFrame(T) T.columns = ['component1', 'component2'] T.plot.scatter(x='component1', y='component2', marker='o', c=labels, alpha=0.75, ax=ax) plt.show()
0cedfef26ca99a989cc9e07aaab30db43712b75b
terrameijar/PythonUnitConverter
/modules/metric/meters.py
1,741
3.6875
4
def meters_millimeters(n, api=False): b = float(n) * 1000 if api == True: return b if float(n) == 1: print str(n) + ' meter = ' + str(b) + ' millimeter(s).' quit() else: print str(n) + ' meters = ' + str(b) + ' millimeter(s)' quit() def meters_centimeters(n, api=False): b = float(n) * 100 if api == True: return b if float(n) == 1: print str(n) + ' meter = ' + str(b) + ' centimeter(s).' quit() else: print str(n) + ' meters = ' + str(b) + ' centimeter(s)' quit() def meters_decimeters(n, api=False): b = float(n) * 10 if api == True: return b if float(n) == 1: print str(n) + ' meter = ' + str(b) + 'decimeter(s).' quit() else: print str(n) + ' meters = ' + str(b) + ' decimeter(s)' quit() def meters_kilometers(n, api=False): b = float(n) / 1000 if api == True: return b if float(n) == 1: print str(n) + ' meter = ' + str(b) + 'kilometer(s).' quit() else: print str(n) + ' meters = ' + str(b) + ' kilometer(s)' quit() def meter(): try: a = float(raw_input('How many meters would you like to convert? ')) except ValueError: print 'You need to enter a number!' meter() b = raw_input('What you you like to convert to? [M]illimeters, [C]entimeters, [D]ecimeters, [K]ilometers: ') if b == 'M' or b == 'm': meters_millimeters(a) elif b == 'C' or b == 'c': meters_centimeters(a) elif b == 'D' or b == 'd': meters_decimeters(a) elif b == 'K' or b == 'k': meters_kilometers(a) else: print 'That unit is not available!'
4dfb6f3bd331340c41b1385faf527074208db09f
DustinMayeda/CodeWars_Problems
/src/Find_the_divisors!.py
677
4.34375
4
""" Description: Create a function named divisors that takes an integer and returns an array with all of the integer's divisors(except for 1 and the number itself). If the number is prime return the string '(integer) is prime' (use Either String a in Haskell). Example: divisors(12); #should return [2,3,4,6] divisors(25); #should return [5] divisors(13); #should return "13 is prime" You can assume that you will only get positive integers as inputs. """ def divisors(integer): result = [] for i in range(2, integer): if integer % i == 0: result.append(i) if len(result) == 0: return "{} is prime".format(integer) return result
0895c99510f25acd8d28e6524aa8a3a2fae7fcd1
YiKeYaTu/Experiments
/utils/functions/image_pair.py
4,468
3.546875
4
import cv2 import numpy as np def pad_resize_image(inp_img, out_img=None, target_size=None): """ Function to pad and resize images to a given size. out_img is None only during inference. During training and testing out_img is NOT None. :param inp_img: A H x W x C input image. :param out_img: A H x W input image of mask. :param target_size: The size of the final images. :return: Re-sized inp_img and out_img """ h, w, c = inp_img.shape size = max(h, w) padding_h = (size - h) // 2 padding_w = (size - w) // 2 if out_img is None: # For inference temp_x = cv2.copyMakeBorder(inp_img, top=padding_h, bottom=padding_h, left=padding_w, right=padding_w, borderType=cv2.BORDER_CONSTANT, value=[0, 0, 0]) if target_size is not None: temp_x = cv2.resize(temp_x, (target_size, target_size), interpolation=cv2.INTER_AREA) return temp_x else: # For training and testing temp_x = cv2.copyMakeBorder(inp_img, top=padding_h, bottom=padding_h, left=padding_w, right=padding_w, borderType=cv2.BORDER_CONSTANT, value=[0, 0, 0]) temp_y = cv2.copyMakeBorder(out_img, top=padding_h, bottom=padding_h, left=padding_w, right=padding_w, borderType=cv2.BORDER_CONSTANT, value=[0, 0, 0]) # print(inp_img.shape, temp_x.shape, out_img.shape, temp_y.shape) if target_size is not None: temp_x = cv2.resize(temp_x, (target_size, target_size), interpolation=cv2.INTER_AREA) temp_y = cv2.resize(temp_y, (target_size, target_size), interpolation=cv2.INTER_AREA) return temp_x, temp_y def random_crop_flip(inp_img, out_img): """ Function to randomly crop and flip images. :param inp_img: A H x W x C input image. :param out_img: A H x W input image. :return: The randomly cropped and flipped image. """ h, w = out_img.shape rand_h = np.random.randint(h/8) rand_w = np.random.randint(w/8) offset_h = 0 if rand_h == 0 else np.random.randint(rand_h) offset_w = 0 if rand_w == 0 else np.random.randint(rand_w) p0, p1, p2, p3 = offset_h, h+offset_h-rand_h, offset_w, w+offset_w-rand_w rand_flip = np.random.randint(10) if rand_flip >= 5: inp_img = inp_img[::, ::-1, ::] out_img = out_img[::, ::-1] return inp_img[p0:p1, p2:p3], out_img[p0:p1, p2:p3] def random_rotate(inp_img, out_img, max_angle=25): """ Function to randomly rotate images within +max_angle to -max_angle degrees. This algorithm does NOT crops the edges upon rotation. :param inp_img: A H x W x C input image. :param out_img: A H x W input image. :param max_angle: Maximum angle an image can be rotated in either direction. :return: The randomly rotated image. """ angle = np.random.randint(-max_angle, max_angle) h, w = out_img.shape center = (w / 2, h / 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) # Compute new dimensions of the image and adjust the rotation matrix new_w = int((h * sin) + (w * cos)) new_h = int((h * cos) + (w * sin)) M[0, 2] += (new_w / 2) - center[0] M[1, 2] += (new_h / 2) - center[1] return cv2.warpAffine(inp_img, M, (new_w, new_h)), cv2.warpAffine(out_img, M, (new_w, new_h)) def random_rotate_lossy(inp_img, out_img, max_angle=25): """ Function to randomly rotate images within +max_angle to -max_angle degrees. This algorithm crops the edges upon rotation. :param inp_img: A H x W x C input image. :param out_img: A H x W input image. :param max_angle: Maximum angle an image can be rotated in either direction. :return: The randomly rotated image. """ angle = np.random.randint(-max_angle, max_angle) h, w = out_img.shape center = (w / 2, h / 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(inp_img, M, (w, h)), cv2.warpAffine(out_img, M, (w, h)) def random_brightness(inp_img): """ Function to randomly perturb the brightness of the input images. :param inp_img: A H x W x C input image. :return: The image with randomly perturbed brightness. """ contrast = np.random.rand(1) + 0.5 light = np.random.randint(-20, 20) inp_img = contrast * inp_img + light return np.clip(inp_img, 0, 255)
38b4e62f52aa9c09dbea8468403fcc6f514f2962
Sundar-Raghavendran/Python-3.functions
/bmi-calculator-function.py
1,268
4.65625
5
#################################################### # program to demo use of functions in python # # author : Sundar Raghavendran # # function to calculate bmi,given height & weight # # date : 2-4-2019 # # version : v1.0 # #################################################### import math def calculate_bmi(name,height_m,weight_kg): bmi = round(weight_kg/(pow(height_m,2)), 2) return bmi name = input("what's your name?") weight_kg = float(input("what's your weight in Kgs?")) height_m = float(input("what's your height in meters?")) print("Hello ", name,". How are you ?. The BMI calculator will advise shortly ") your_bmi = calculate_bmi(name,height_m,weight_kg) print(name + "'s bmi is : ", your_bmi) if your_bmi >= 25: print(name + " is overweight") desired_weight = 25 * pow(height_m,2) # bcoz bmi=weight/height-squared, # weight = bmi*height-squared print("you need to reduce ", round(weight_kg-desired_weight,2) , "kgs to get good bmi score") else: print(name + " is not overweight") boosted_weight = 25 * pow(height_m,2) print("you could go upto ", round(boosted_weight-weight_kg,2), "kgs and still be in good bmi score")
cf523921bf5a211a9810b023717d4b8d14164c97
mbhushan/designprog
/lesson2/neighbors.py
752
4.09375
4
# ---------------- # User Instructions # # Add the appropriate return statement to the nextto(h1, h2) # function below. It should return True when two houses # differ by 1, otherwise it should return False. import itertools houses = [1, 2, 3, 4, 5] orderings = list(itertools.permutations(houses)) def imright(h1, h2): "House h1 is immediately right of h2 if h1-h2 == 1." return h1-h2 == 1 def nextto(h1, h2): "Two houses are next to each other if they differ by 1." return abs(h1-h2) == 1 def test_ordering(): assert nextto(3,4) == True assert nextto(3,5) == False assert imright(2,1) == True assert imright(1,2) == False return "All tests passed" def main(): print test_ordering() if __name__ == '__main__': main()
f2be15e992821ef48c7368ebf72b441059338f1c
barua-anik/integrify_assignments
/Python exercises/missingNumber.py
265
4.125
4
#Find the missing number def missing_numbers(num_list): original_list = [x for x in range(num_list[0], num_list[-1] + 1)] num_list = set(num_list) return (list(num_list ^ set(original_list))) print("Missing number:", missing_numbers([1,2,3,5]))
4a372fde5fd822e357ffe3ab5b37ae1247594054
ASamiAhmed/PythonPrograms
/number_checking.py
317
4.28125
4
''' Write a Python program to check if a number is positive, negative or zero ''' number = int(input("enter number: ")) if number == 0: print("The number you entered is",number) elif number > 0: print("The number you entered is positive") else: print("The number you entered is negative")
0a2dd7098fa045a94c9f9beb4417130e91d02985
kaviarasan03/Guvi_Program
/play173.py
527
3.578125
4
s=input() r=input() g=[] if (s.isalpha() or " " in s) and (r.isalpha() or " " in r): s=list(s.split(" ")) r=list(r.split(" ")) for i in s: if s.count(i) > r.count(i) and i not in g: g.append(i) for i in r: if r.count(i)>s.count(i) and i not in g: g.append(i) print(*g) else: for i in s: if s.count(i)>r.count(i) and i not in g: g.append(i) for j in r: if r.count(j)>s.count(j) and j not in g: g.append(j) print(*g)
2a6cb70fb772d739993b8310df6bf4d2de505aae
sandeep-kota/Turtlebot-A-star-with-constraints-actions
/src/moveBot.py
2,031
3.65625
4
#!/usr/bin/env python from __future__ import division import rospy from geometry_msgs.msg import Twist import sys def move(distance,angle): # Starts a new node rospy.init_node('turtlebot_controller', anonymous=True) velocity_publisher = rospy.Publisher('/cmd_vel_mux/input/navi', Twist, queue_size=10) vel_msg = Twist() angle = angle * 3.14/180 distance = distance speed = 0.2 w = 0.5 vel_msg.linear.x = 0 vel_msg.linear.y = 0 vel_msg.linear.z = 0 vel_msg.angular.x = 0 vel_msg.angular.y = 0 vel_msg.angular.z = 0 #Setting the current time for distance calculus current_distance = 0 current_angle = 0 # print("Angle :",angle) #Loop to move the turtle in an specified distance t0 = rospy.Time.now().to_sec() while(current_distance < distance): # rospy.loginfo("Distance %s",current_distance) #Publish the velocity vel_msg.linear.x = speed velocity_publisher.publish(vel_msg) #Takes actual time to velocity calculus t1=rospy.Time.now().to_sec() #Calculates distancePoseStamped current_distance= speed*(t1-t0) # #After the loop, stops the robot vel_msg.linear.x = 0 # Loop to move the turtle in an specified angle t0 = rospy.Time.now().to_sec() while (current_angle < abs(angle)): # print("Angle ",angle) if angle>=0: # print("1") vel_msg.angular.z=w if angle>180: vel_msg.angular.z=-w angle = angle-180 if angle<0: # print("2") vel_msg.angular.z=-w t1=rospy.Time.now().to_sec() velocity_publisher.publish(vel_msg) current_angle = (w*(t1-t0)) # rospy.loginfo("Angle %s",current_angle) vel_msg.angular.z=0 #Force the robot to stop # velocity_publisher.publish(vel_msg) # for t in range(1000): # velocity_publisher.publish(vel_msg) return 0 if __name__ == "__main__": move(0,90)
44f5caea230e2b4cfe851633b8bc02c4f08c9c8d
vijgan/python-repo
/check_even.py
374
3.90625
4
#!/usr/bin/python import sys def main(): num=[1,2,5,7,'k','n',11,19] newnum=[] print num for i in num: try: if i%2==0: newnum.append(i) else: pass except: print '%s is not an integer' %i print newnum if __name__=='__main__': main()
c32cd4b8b45fca19deb2a6fa16f14b9e227c8f98
danielcgithub/myutilities
/machine_learning/cost_function.py
539
3.53125
4
#!/usr/bin/python import numpy as np from sklearn.datasets import load_boston import matplotlib.pyplot as plt def main(): dataset = load_boston() X = dataset.data y = dataset.target[:, np.newaxis] print("Total samples in our dataset is: {}".format(X.shape[0])) print(X) print("----------------------------------------------------------") print(y) def compute_cost(X, y, params): n_samples = len(y) h = X @ params return (1/(2*n_samples))*np.sum((h-y)**2) if __name__ == "__main__": main()
76ef678fe6d99616025b327386a91d2bca9fbd3b
RookieCodeMan/WebSpider
/4_spider_selenium.py
2,127
3.71875
4
# 总结一下,主要是利用selenium库来获取动态渲染的页面, 直接模拟浏览器来实现爬取 # 再使用selenium webdriver之前需要提前安装好chromedriver # 将chromedriver.exe复制到script的安装目录下,并配置好环境变量 # 将chrome的安装目录添加到环境变量中 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time def selenium_demno(): browser = webdriver.Chrome() try: browser.get("https://www.taobao.com") print(browser.page_source) input = browser.find_element_by_id('kw') input.send_keys('Python') input.send_keys(Keys.ENTER) wait = WebDriverWait(browser, 10) wait.until(EC.presence_of_all_elements_located((By.ID, 'content_left'))) finally: browser.close() def find_element(): browser = webdriver.Chrome() try: browser.get("https://www.taobao.com") # print(browser.page_source) input_first = browser.find_element_by_id('q') input_second = browser.find_element_by_css_selector('#q') # 在css selector支持id、class定位 # "#"代表id, "."代表class print(input_first, input_second) finally: browser.close() def find_elements(): browser = webdriver.Chrome() try: browser.get("https://www.taobao.com") lst = browser.find_elements_by_css_selector('.service-bd li') print(lst) finally: browser.close() def send_keys(): browser = webdriver.Chrome() try: browser.get("https://www.taobao.com") input = browser.find_element_by_id('q') input.send_keys('iPhone') time.sleep(1) input.clear() input.send_keys('ipad') button = browser.find_element_by_class_name('btn-search') button.click() finally: browser.close() if __name__ == '__main__': # find_elements() send_keys()
13505046c425ecef5bcf18401f599b608dc77921
vprusso/6-Weeks-to-Interview-Ready
/quickstart_guides/linked_lists/python/pairs_with_sum.py
880
4.03125
4
""" Title: Pairs with sum. Problem: Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’. Execution: python pairs_with_sum.py """ from typing import List import unittest def pairs_with_sum(arr: List[int], s: int) -> int: """ Returns number of pairs in arr[0..n-1] with sum equal to 'sum' """ # Initialize result. count = 0 # Consider all possible pairs and check their sums. for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[i] + arr[j] == s: count += 1 return count class TestPairsWithSum(unittest.TestCase): """Unit test for pairs_with_sum.""" def test_1(self): x = [1, 5, 7, -1, 5] self.assertEqual(pairs_with_sum(x, 6), 3) if __name__ == "__main__": unittest.main()
5647f5f4cf44f25069cca12a42b11bb48b6832e9
MRGRAVITY817/data-analysis-basics
/02_numpy_basics/test/.ipynb_checkpoints/icecream_aop-checkpoint.py
1,638
3.6875
4
import os import numpy as np class IceCreamShop: def __init__(self): self.row = row = np.array(["Chocolate", "Strawberry", "Vanila", "Hazelnut", "Banana", "Orange"]) self.col = np.array(["Price", "Stock"]) self.money = 0 self.menu = np.array([ [3, 10], [5, 10], [2, 10], [7, 10], [5, 10], [6, 10], ]) def buy_icecream(self, select): self.money += self.menu[select-1, 0] self.menu[select-1, 1] -= 1 def print_menu(self): running = True while running: os.system("clear") print("Hello! Welcome to Hoon's Icecream :D ".center(40)) print() print("Menu".center(40)) print() for index, value in enumerate(self.menu): line_1 = f"{index+1}. {self.row[index]}".ljust(20) line_2 = f"${value[0]}".ljust(10) line_3 = f"Left: {value[1]}".ljust(10) print(line_1+line_2+line_3) print("(Press q to quit)".ljust(20) + f"Total income: ${self.money}".rjust(20)) choice = input("Select number or quit: ") if choice == 'q': running = False elif int(choice) in range(1, 7): self.buy_icecream(int(choice)) else: pass if __name__ == "__main__": ics = IceCreamShop() ics.print_menu()
941f57314805527153647cf4ddcb65fca1769915
wangruchao/python_test_calculate
/add.py
172
3.75
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- sum0=0 sum1=0 for i in range(1,101,1): if i%2==0: sum0=sum0+i else: sum1=sum1+i print sum0 print sum1
5e91a4ba90fbcdda80c6b458c1d981073877f9f5
pohily/checkio
/common-words.py
190
3.671875
4
def checkio(first, second): return ','.join(sorted(list(set(first.split(',')) & set(second.split(','))))) print(checkio("one,two,three", "four,five,one,two,six,three")) """ """
f959e854bf8272ff269ee88f4d12d6cb83c7ac63
MikeArchbold/Math-Practice
/Problems/Problem1.py
384
3.84375
4
''' Created on Jul 2, 2015 @author: mike ''' def divisibleBy(num, ceil): currentMultiple = 1 multiples = [] while( currentMultiple*num < ceil ): multiples.append( currentMultiple*num ) currentMultiple += 1 return multiples if __name__ == '__main__': uniqueNums = set(divisibleBy(3, 1000) + divisibleBy(5, 1000)) print sum(uniqueNums)
ae121501b331720bf9912d2b50604acec3cb001a
gz152/autofillOKR
/date_selenium.py
554
3.765625
4
#!/usr/bin/env python # coding=utf-8 import calendar from datetime import date import math m = date.today() currentYear, currentMonth, currentDay = m.year, m.month, m.day weekdayof1st, totaldaysofmonth = calendar.monthrange(currentYear, currentMonth) weekdayoflast = calendar.weekday(currentYear, currentMonth, totaldaysofmonth) def getWeekNum(): if (currentDay + weekdayof1st) < 6: weekofcurrday = 1 else: weekofcurrday = math.ceil((currentDay + weekdayof1st - 6) / 7.0) + 1 return weekofcurrday
2304f4e3577e0a94e1531f0787f4cee2cbfc2fb8
charlesxs/scripts
/leetcode/linkedlist_reverse.py
1,151
4.03125
4
# coding=utf-8 # class Node: def __init__(self, data, next_): self.data = data self.next = next_ def __repr__(self): return self.data class LinkedList: def __init__(self): self.head = None self.tail = None def append(self, data): node = Node(data, None) if self.head is None: self.head = node if self.tail is None: self.tail = node self.tail.next = node self.tail = node def show(self): cursor = self.head while True: print cursor.data, if cursor.next is None: break cursor = cursor.next print def reverse(self): cursor = org = self.head while True: if org.next is None: self.tail = org break self.head = org.next org.next = self.head.next self.head.next = cursor cursor = self.head if __name__ == '__main__': l = LinkedList() for i in range(9): l.append(i) l.show() l.reverse() l.show()
70448d556a548e5895a7d21ebeec07c9f9a81685
genuineversion/multipleChoiceQsts
/multipleChoiceQst.py
3,365
4.5625
5
# This is a multiple choice collection of statements # # These are questions and the answers Qst1={"Q1":"What is the capital of Nigeria","Q1optionA":"Lagos","Q1optionB":"Oyo","Q1optionC":"Abuja","Q1Ans":"C" } Qst2={"Q2":"What is the capital of England","Q2optionA":"Manchester","Q2optionB":"London","Q2optionC":"Liverpool","Q2Ans":"B" } Qst3={"Q3":"who won the 2020/2021 Premier league","Q3optionA":"ManUtd","Q3optionB":"ManCity","Q3optionC":"Chelsea","Q3Ans":"B" } # These are the three options that the user will select from. options = ["A", "B", "C"] #The "question" functions display each question and also accept and stores the user input #The "functionQ" functions determines if the user input is correct and stores the value whether True or False #Question 1 def question1(): print("Question1: "+ Qst1["Q1"]) print("a: "+Qst1["Q1optionA"]) print("b: "+Qst1["Q1optionB"]) print("c: "+Qst1["Q1optionC"]) global userAnsQ1 userAnsQ1=input("Answer by entering a, b or c \n").upper() return userAnsQ1 def functionQ1(): if userAnsQ1 not in options: print ("Input is out of range") question1() elif userAnsQ1.upper()==Qst1["Q1Ans"].upper(): Result1 = True else: Result1= False return Result1 #Question 2 def question2(): print("Question2: "+ Qst2["Q2"]) print("a: "+Qst2["Q2optionA"]) print("b: "+Qst2["Q2optionB"]) print("c: "+Qst2["Q2optionC"]) global userAnsQ2 userAnsQ2=input("Answer by entering a, b or c \n").upper() return userAnsQ2 def functionQ2(): if userAnsQ2 not in options: print ("Input is out of range") question2() elif userAnsQ2.upper()==Qst2["Q2Ans"].upper(): Result2 = True else: Result2= False return Result2 #Question 3 def question3(): print("Question3: "+ Qst3["Q3"]) print("a: "+Qst3["Q3optionA"]) print("b: "+Qst3["Q3optionB"]) print("c: "+Qst3["Q3optionC"]) global userAnsQ3 userAnsQ3=input("Answer by entering a, b or c \n").upper() return userAnsQ3 def functionQ3(): if userAnsQ3 not in options: print ("Input is out of range") question3() elif userAnsQ3.upper()==Qst3["Q3Ans"].upper(): Result3 = True else: Result3= False return Result3 #The score is to be displayed in %, so this function converts the float into % (string) def convertToPercent (decimal): convertedValue=decimal*100 convertedValue=str(convertedValue)+"%" return convertedValue #Functions call, to dsiplay the questions, obtain the user input and confirm if correct or not. question1() answer1=functionQ1() question2() answer2=functionQ2() question3() answer3=functionQ3() #This stores the answers in a list listOfAnswers=[answer1, answer2, answer3] numberOfCorrectAns=listOfAnswers.count(True) totalQsts=len(listOfAnswers) #THis calculates the score in decimals percentScore=round(numberOfCorrectAns/totalQsts,2) #THis displays the score to the user and also use the function convertToPercentage to convert the float to percentage. print("Your score is "+ convertToPercent(percentScore)) #This returns the answer to the user to see how they did, whether True or False print ("See how correct your choices are:") x=0 for i in listOfAnswers: x+=1 print("Question {}".format(x)) print(i)
bb5b6200bd1b816a5d9bce9acfd08574ebc46626
iamdaguduizhang/Small_module
/Thread/demo1.py
2,847
3.78125
4
# -*- coding:utf-8 -*- # @Time :2019-10-16 15:50 # @Author :Dg from threading import Thread import time def my_counter(): i = 0 for _ in range(100000000): i = i + 1 return True def main(): start_time = time.time() for tid in range(2): t = Thread(target=my_counter) t.start() t.join() end_time = time.time() print("Total time: {}".format(end_time - start_time)) def main2(): thread_array = {} start_time = time.time() for tid in range(2): t = Thread(target=my_counter) t.start() thread_array[tid] = t for i in range(2): thread_array[i].join() end_time = time.time() print("Total time: {}".format(end_time - start_time)) def main3(): start_time = time.time() t1 = Thread(target=my_counter) t2 = Thread(target=my_counter) t1.start() t2.start() t1.join() # t2.start() t2.join() end_time = time.time() print("totle_time: {}".format(end_time - start_time)) if __name__ == '__main__': main3() # GIL 保证同一个进程内,同一时刻只能有一个线程在执行,为了保证数据的完整性和状态同步的问题。 # 多线程代码的话,解释器分时使用,使得不同的线程都能使用到解释器。切换频繁,给人并行的感觉,其实是并发,并且单核cpu'没有真正的并行。 # 即使是GIL也不能保证数据的安全, # 在cpu计算密集型的时候。解释器会每隔100次或每隔一定时间15ms去释放GIL。唤起线程,线程获得执行权这里会浪费时间,所以多线程会比单线程更慢 # I/O阻塞的时候GIL会被释放.计算机密集的时候,解释器会每隔100次或每隔一定时间15ms去释放GIL。线程抢夺 # 所以,这里可以理解为IO密集型的python比计算密集型的程序更能利用多线程环境带来的便利。 # 举例 比如一个 ArrayList 类,在添加一个元素的时候,它可能会有两步来完成:1. 在 Items[Size] 的位置存放此元素;2. 增大 Size 的值。 # # 在单线程运行的情况下,如果 Size = 0,添加一个元素后,此元素在位置 0,而且 Size=1; # 而如果是在多线程情况下,比如有两个线程,线程 A 先将元素存放在位置 0。但是此时 CPU 调度线程A暂停, # 线程 B 得到运行的机会。线程B也向此 ArrayList 添加元素,因为此时 Size 仍然等于 0 ( # 注意哦,我们假设的是添加一个元素是要两个步骤哦,而线程A仅仅完成了步骤1), # 所以线程B也将元素存放在位置0。然后线程A和线程B都继续运行,都增加 Size 的值。 # 那好,现在我们来看看 ArrayList 的情况,元素实际上只有一个,存放在位置 0,而 Size 却等于 2。这就是“线程不安全”了。
827cce701fa28e1edf6b99e35c8d59c810d311d8
mbpxc4/mbpxc4
/assignment-five/login_test.py
987
3.640625
4
import pytest """ This program will check if the login has the correct information given certain inputs of username and password. The first test will pass because the username and the password are the correct information. The second test will fail due to the username of 'wronguser' and the password of 'wrongpassword' not being the correct information. """ def right_User(): username = "mpilgrim" return username def wrong_User(): username = "wronguser" return username def right_password(): password = "testtest" return password def wrong_password(): password = "wrongpassword" return password def test_correct_login(): username = right_User() password = right_password() assert username == "mpilgrim" and password == "testtest" def test_wrong_login(): username = wrong_User() password = wrong_password() assert username == "mpilgrim" and password == "testtest"
de96bfd0557926185e84ae879c9e893102a1bdf5
MaciekPy/Zadania-3
/3.8.py
477
3.9375
4
# Dla dwóch sekwencji znaleźć: (a) listę elementów występujących # jednocześnie w obu sekwencjach (bez powtórzeń), # (b) listę wszystkich elementów z obu sekwencji (bez powtórzeń). L = {1,3,6,9,12} K = {2,3,5,8,12} print("Sekwencje : \n" + str(L) + "\n" + str(K)) inter = L.intersection(K) union = L.union(K) print("Elementy występujące w obydwoch sekwencjach : " + str(inter)) print("Wszystkie elementy z obydwoch sekwencji : " + str(union))
e9b4fa30f37037a35a3908d2851fada66a5a7bbc
sarmistha1619/HackerRank-Python-Solutions
/22. HRS - Lists.py
817
3.65625
4
if __name__ == '__main__': N = int(input()) arr=[] for i in range(N): s= input().split() for i in range(1,len(s)): s[i]=int(s[i]) if s[0]== "append": arr.append(s[1]) elif s[0]=="insert": arr.insert(s[1],s[2]) elif s[0]=="remove": arr.remove(s[1]) elif s[0]== "pop": arr.pop() elif s[0]=="sort": arr.sort() elif s[0]== "reverse": arr.reverse() elif s[0]== "print": print(arr) ''' #another solve, not worked in hackerrank a=int(input()) l=[] l.insert(0, 5) l.insert(1, 10) l.insert(0, 6) print(l) l.remove(6) l.append(9) l.append(1) l.sort() print(l) l.pop() l.reverse() print(l) '''
fd29ade75a4ca187f9e0b8ebad08bda63010d8a5
EGBDS/Curso-de-Python-que-fiz
/exer76.py
1,440
3.953125
4
'''lista = ('Lápis', '1.75', 'Borracha', '2.00', 'Caderno', '15.90', 'Estojo', '25.00', 'Transferidor', '4.20', 'Compasso', '9.99', 'Mochila', '120.32', 'Canetas', '22.30', 'Livro', '34.90') print('-'*40) print('{:^40}'.format('LISTAGEM DE PREÇOS')) print('-'*40) print('{:<}{}R${:>7}'.format(lista[0], '.' * (31 - len(lista[0])), lista[1])) print('{:<}{}R${:>7}'.format(lista[2], '.' * (31 - len(lista[2])), lista[3])) print('{:<}{}R${:>7}'.format(lista[4], '.' * (31 - len(lista[4])), lista[5])) print('{:<}{}R${:>7}'.format(lista[6], '.' * (31 - len(lista[6])), lista[7])) print('{:<}{}R${:>7}'.format(lista[8], '.' * (31 - len(lista[8])), lista[9])) print('{:<}{}R${:>7}'.format(lista[10], '.' * (31 - len(lista[10])), lista[11])) print('{:<}{}R${:>7}'.format(lista[12], '.' * (31 - len(lista[12])), lista[13])) print('{:<}{}R${:>7}'.format(lista[14], '.' * (31 - len(lista[14])), lista[15])) print('{:<}{}R${:>7}'.format(lista[16], '.' * (31 - len(lista[16])), lista[17])) print('-' * 40)''' #OU listagem = ('Lápis', 1.75, 'Borracha', 2.00, 'Caderno', 15.90, 'Estojo', 25.00, 'Transferidor', 4.20, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.30, 'Livro', 34.90) print('-' * 40) print(f'{"LISTAGEM DE PREÇOS":^40}') print('-' * 40) for pos in range(0, len(listagem)): if pos % 2 == 0: print(f'{listagem[pos]:.<30}', end='') else: print(f'R${listagem[pos]:>8}') print('-' * 40)
7135f07216441297469de012a836ce180343e40c
jms-dipadua/machine-learn-py
/FB/fb_feat_prep.py
15,182
3.515625
4
from operator import itemgetter from collections import defaultdict import numpy as np import pandas as pd import csv import sys def initialize(): print "Let's get started" print "this will allow you to input a file when ready...\n getting data now..." # SAMPLE file_name = 'data/sample_bids.csv' # FULL #file_name = 'data/bids.csv' auction_sorted = get_data(file_name) print "sample of sorted data" for i in range (0, 5): print auction_sorted[i] auction_dict = write_auction_dict(auction_sorted) print "there are %s different auctions" % len(auction_dict) # loop through auction dictionary # get bid count for each auction and read as a chunck # thereby tracking start / end of each auction to sort by bidder & get stats, etc. bids_read = 0 bidder_dict = {} # dictionaries aren't sorted but we need the sort order # so this iterates through each auction in the dic sorted (to match the sort of the sorted data) i = 0 for auction in sorted(auction_dict.keys()): bid_count = auction_dict.get(auction) #print "auction %r has total %f" % (auction, bid_count) auction_items = [] # isolate the auction items from *this* auction # for sorting and stat collection # going to use the following to mark the last bid (and use as a counter) j = 0 auction_times = [] last_bidder = None last_bid_time = None for i in range (bids_read, bids_read + bid_count): auction_items.append(auction_sorted[i]) auction_times.append(auction_sorted[i][5]) j +=1 # marks the last bidder (by getting the bidder_id) # going to adjust bid_count (for last bidder as a feature) # adding in last bid time to calc "time from auction end" (clearly as an estimate) # entities that bid in the last few seconds seem like good candidates for snippers # because human would probably see they'd won and not see the snipped bid change... if j == bid_count and bid_count > 5: last_bid_time = max(auction_times) last_bid_index = auction_times.index(max(auction_times)) last_bidder = auction_sorted[last_bid_index][1] #print "last bidder: %r" % last_bidder #print "last bid_time: %r" % last_bid_time #print "full list of bid times: %r" % auction_times elif j == bid_count and not last_bidder and not last_bid_time: # using random symbol to avoid false matches last_bidder = ">>>" last_bid_time = max(auction_times) else: pass bids_read = bids_read + bid_count #print auction_items bidder_dict = write_bidder_dict(auction_items, bidder_dict, last_bidder, last_bid_time) #print bidder_dict #print "total bids_read = %f" % bids_read #print "total bidders in all %f auctions is %f" % (bids_read, len(bidder_dict)) bidder_summary_stats = calc_bidder_stats(bidder_dict) #print bidder_summary_stats file_name = write_bidder_summary_csv(bidder_summary_stats) #print file_name #start_phase_two() def start_phase_two(): print "what is the original file name? example: data/train.csv" mega_file = raw_input("") print "what is the summary file name? example: data/sample_bidder_summary.csv" file_name = raw_input("") print "Name the consolidated_file" consolidated_file = raw_input("") summary_file_name = write_consolidated_csv(file_name, mega_file, consolidated_file) if summary_file_name: print "ON FIRE!!!" else: print "facepalm" def get_data(file_name): print "opening csv file" with open(file_name, 'r') as csv_file: print "sorting raw data into auction lists" reader = csv.reader(csv_file) auction_sort = sorted(reader, key=itemgetter(2), reverse=False) return auction_sort def write_auction_file(sorted_data, file_name): # would use this for long-running processes (way of "getting back" to where i was...TBD) #with open(file_name, 'w+'): pass def write_auction_dict(sorted_data): print "creating auctions dict" auction_dict = {} count = 0 for i in range (0, len(sorted_data)): temp_val = sorted_data[i][2] auction = auction_dict.get(temp_val) # if that doesn't return a value, then it's a new auction if not auction: #print "new auction entry" auction_dict[temp_val] = 1 count = count+1 #print "current total count is %f" % count else: #print "existing entry for %s" % temp_val auction_dict[temp_val] = auction_dict[temp_val] + 1 #print "current count for %s is %r" % (temp_val, auction_dict[temp_val]) return auction_dict def write_bidder_dict(auction_items,bidder_dict, last_bidder, last_bid_time): print "writing bidder dictionary" print last_bidder # loop through each bidder (with auction list sorted by bidder_ref) for bid in sorted(auction_items, key=itemgetter(1)): auction_ref = bid[2] bidder_ref = bid[1] bidder = bidder_dict.get(bidder_ref) device_ = bid[4] time_ = bid[5] country_ = bid[6] ip_ = bid[7] url_ = bid[8] # normalize a time difference (from last bid) try: time_diff = abs(int(time_) - int(last_bid_time)) * np.exp(1e-6) except ValueError: #just to avoid load fail due to empty value: time_diff = 30 print "not an int" pass if not bidder: #print "NEW BIDDER!!" device = {device_: 1 } bid_time = { 0 : time_ } country = {country_: 1} ip ={ip_: 1} url ={url_: 1} # last bidder_controls if bidder_ref == last_bidder: last_bidder_count = 1 else: last_bidder_count = 0 # bid time from last bid (as snipe estimate) if (time_diff <= 3): snipe_bid_count = 1 else: snipe_bid_count = 0 auction_data = { 'bids': 1, 'devices': device, 'times': bid_time, 'countries': country, 'ips': ip, 'urls': url, 'last_bidder_count': last_bidder_count, 'snipe_bid_count': snipe_bid_count } bidder_dict[bidder_ref] = { auction_ref: auction_data } else: auction_data = bidder.get(auction_ref) # if this check fails, it means we're onto a new auction # so we'll need to setup the new auction dict within the bidder's dict if not auction_data: #print "this is getting called. needs to be fixed." #bids = {'bids': 1} device = {device_: 1 } bid_time = { 0 : time_ } country = {country_: 1} ip = {ip_: 1} url ={url_: 1} # last bidder_controls if bidder_ref == last_bidder: last_bidder_count = 1 else: last_bidder_count = 0 # bid time from last bid (as snipe estimate) if (time_diff <= 3): snipe_bid_count = 1 else: snipe_bid_count = 0 auction_data = { 'bids': 1, 'devices': device, 'times': bid_time, 'countries': country, 'ips': ip, 'urls': url, 'last_bidder_count': last_bidder_count, 'snipe_bid_count': snipe_bid_count } bidder_dict[bidder_ref][auction_ref] = auction_data else: #if it passes, it means we need to update our data new_auction_data = update_auction_data(auction_data, bid, last_bidder, bidder_ref, time_diff) bidder_dict[bidder_ref][auction_ref]= new_auction_data return bidder_dict def update_auction_data(auction_data, bid_data, last_bidder, bidder_ref, time_diff): print "updating existing auction data for existing bidder" device_ = bid_data[4] time_ = bid_data[5] country_ = bid_data[6] ip_ = bid_data[7] url_ = bid_data[8] # increase bid count auction_data['bids'] += 1 # add new time auction_data['times'][len(auction_data['times'])] = time_ # device check if not device_ in auction_data['devices']: auction_data['devices'][device_] = 1 else: auction_data['devices'][device_] += 1 pass # country check if not country_ in auction_data['countries']: auction_data['countries'][country_] = 1 else: auction_data['countries'][country_] += 1 pass # IP check if not ip_ in auction_data['ips']: auction_data['ips'][ip_] = 1 else: auction_data['ips'][ip_] += 1 pass # URL check if not url_ in auction_data['urls']: auction_data['urls'][url_] = 1 else: auction_data['urls'][url_] += 1 pass #last bidder count check if bidder_ref == last_bidder: auction_data['last_bidder_count'] += 1 # bid time from last bid (as snipe estimate) if (time_diff <= 3): #auction_data['snipe_bid_count'] += 1 # testing boolean setting only (equiv to a "sniper" vs count of snipe_attempts) auction_data['snipe_bid_count'] += 1 print auction_data exit() return auction_data # bidder stats (from dict) def calc_bidder_stats(bidder_dict): print "calculating bidder stats" """ DONE * total bids DONE * total auctions (participated in) * avg time between bids (by auction?)::: PUNT DONE * total devices used DONE * avg num devices per auction (?) DONE * avg num country per auction DONE * avg num IPs used per auction DONE * total IPs used DONE * total simultaneous_bids DONE * snipe attemps (@ 16s) DONE * total urls used """ bidder_stats = {} bidder_count = 0 for bidder in bidder_dict: bidder_count += 1 print "NEW BIDDER STARTED ---Bidder: %r---" % bidder_count bidder_data = bidder_dict.get(bidder) #print bidder_data total_bids = 0 total_auctions = len(bidder_data) total_devices = 0 total_ips = 0 total_countries = 0 sim_bid = 0 total_last_bids = 0 total_snipe_bids = 0 total_urls = 0 # we'll define a "simultaneous" bid here # == bid times within 5 seconds of one another (across auctions, ignoring-same-auction proximity) auction_count = 0 for auction in bidder_data: auction_count += 1 print "NEW Auction STARTED ---Auction: %r---" % auction_count auction_data = bidder_data.get(auction) total_bids += auction_data['bids'] total_devices += len(auction_data['devices']) ## going to see about getting the exact number of countries and ips, etc ## see if that makes a difference. ## pending results, will then move to getting a "country" switch boolean ## based on results for country in auction_data['countries']: total_countries += auction_data['countries'][country] for ip in auction_data['ips']: total_ips += auction_data['ips'][ip] total_last_bids += auction_data['last_bidder_count'] #total_snipe_bids += auction_data['snipe_bid_count'] # TEST: boolean (redundant but so what) total_snipe_bids += auction_data['snipe_bid_count'] for url in auction_data['urls']: total_urls += auction_data['urls'][url] # all of the following for 'simultaneous bid' # but note: this is not the 'counting version' # boolean: simultaneous bidder or not # test: expanding the sim bid by a little bit # going to do a count on sim bids per auction (but not more than one per auction) # should reduce the run time a little. """ local_sim_bid_count = 0 for bid_time in auction_data['times']: current_eval_t = auction_data['times'].get(bid_time) if local_sim_bid_count == 1: break else: pass for tmp_auction in bidder_data: tmp_a_data = bidder_data.get(tmp_auction) for tmp_time_ref in tmp_a_data['times']: tmp_time = tmp_a_data['times'].get(tmp_time_ref) try: time_diff = abs(int(tmp_time) - int(current_eval_t)) * np.exp(1e-6) if (time_diff <= 5) and not (tmp_auction == auction): local_sim_bid_count = 1 sim_bid = sim_bid + local_sim_bid_count except ValueError: print "not an int" pass """ avg_num_dev = total_devices / total_auctions avg_num_ips = total_ips / total_auctions avg_num_countries = total_countries / total_auctions #sim_bid = sim_bid / 2 # another option is to run a "average snipe" like the avg # of devices, etc bidder_stats[bidder] = { 'total_bids': total_bids, 'total_auctions': total_auctions, 'total_devices': total_devices, 'total_ips': total_ips, 'total_countries': total_countries, 'avg_num_dev': avg_num_dev, 'avg_num_countries': avg_num_countries, 'avg_num_ips': avg_num_ips, #'simultaneous_bids': sim_bid, 'num_last_bids': total_last_bids, 'num_snipe_bids': total_snipe_bids, 'total_urls': total_urls } return bidder_stats def write_bidder_summary_csv(bidder_summary_stats): print "name bidder summary file" file_name = raw_input("") print "writing bidder summary stats csv" #file_name = 'data/bidder_summary.csv' with open(file_name, 'w+') as new_file: writer = csv.writer(new_file, lineterminator='\n') for bidder in bidder_summary_stats: all = [] bidder_stats = bidder_summary_stats.get(bidder) all.append(bidder) #print bidder print bidder_stats for stats in bidder_stats: stat = bidder_stats.get(stats) all.append(stat) #print all writer.writerows([all]) return file_name def write_consolidated_csv(file_name, mega_file, consolidated_file): with open(file_name, 'r') as summary_stats: summary_data = pd.read_csv(summary_stats) tracked_bidders = summary_data['bidder_id'] total_bids = summary_data['total_bids'] total_auctions = summary_data['total_auctions'] total_devices = summary_data['total_devices'] total_ips = summary_data['total_ips'] total_countries = summary_data['total_countries'] avg_num_dev = summary_data['avg_num_dev'] avg_num_countries = summary_data['avg_num_countries'] avg_num_ips = summary_data['avg_num_ips'] #simultaneous_bids = summary_data['simultaneous_bids'] last_bids = summary_data['num_last_bids'] num_snipe_bids = summary_data['num_snipe_bids'] total_urls = summary_data['total_urls'] with open(mega_file, 'r') as original: existing_d = pd.read_csv(original) bidder_ids = existing_d['bidder_id'] with open(consolidated_file, 'w+') as new_file: writer = csv.writer(new_file, lineterminator='\n') for bidder in bidder_ids: all_bidder_data = [] match = False for i in range(0, len(tracked_bidders)): if bidder == tracked_bidders[i]: match = True matched_i = i if match == True: all_bidder_data.append(bidder) #w/out sim bids: (+ urls) other_fields = total_bids[matched_i], total_auctions[matched_i], total_devices[matched_i], total_ips[matched_i], total_countries[matched_i], avg_num_dev[matched_i], avg_num_countries[matched_i], avg_num_ips[matched_i], last_bids[matched_i], num_snipe_bids[matched_i], total_urls[matched_i] #w/ sim bids (+ urls) #other_fields = total_bids[matched_i], total_auctions[matched_i], total_devices[matched_i], total_ips[matched_i], total_countries[matched_i], avg_num_dev[matched_i], avg_num_countries[matched_i], avg_num_ips[matched_i], simultaneous_bids[matched_i], last_bids[matched_i], num_snipe_bids[matched_i], total_urls[matched_i] for field in other_fields: all_bidder_data.append(field) writer.writerows([all_bidder_data]) else: all_bidder_data.append(bidder) # w/ sim bids + total urls # other_fields = [0,0,0,0,0,0,0,0,0,0,0,0] # w/out sim bids + total urls other_fields = [0,0,0,0,0,0,0,0,0,0,0] for field in other_fields: all_bidder_data.append(field) writer.writerows([all_bidder_data]) return consolidated_file ###### KICK IT OFF!!! initialize() #start_phase_two()
380059c957867a3c1ce424390726c5aad353d50c
AbhishekTiwari0812/python_codes
/2013csb1001_LabExam3/2013csb1001_SkipList.py
3,216
3.703125
4
global HEAD def InsertIn(MyNode,PrevNode): MyNode.prev=PrevNode MyNode.next=PrevNode.next PrevNode.next.prev=MyNode PrevNode.next=MyNode class Vertex: def __init__(self): self.key=None self.prev=None self.next=None self.UP=None #links between keys self.DOWN=None #links between keys def __str__(self): return str(self.key) import random def StairsForUp(Node): global HEAD global TAIL if random.random()>=0.5000000: k=Node.prev while k.UP==None: k=k.prev if k.UP!=HEAD.UP: NewNode=Vertex() NewNode.key=Node.key NewNode.DOWN=Node Node.UP=NewNode InsertIn(NewNode,k.UP) else: NewHead=Vertex() NewHead.key=-1 NewTail=Vertex() NewTail.key='inf' NewTail.prev=NewHead NewHead.next=NewTail NewNode=Vertex() NewNode.key=Node.key NewNode.DOWN=Node Node.UP=NewNode NewHead.UP='dummy' NewTail.UP='dummy' InsertIn(NewNode,NewHead) NewHead.DOWN=HEAD HEAD.UP=NewHead NewTail.DOWN=TAIL TAIL.UP=NewTail HEAD=NewHead TAIL=NewTail StairsForUp(NewNode) class SkipList: def __init__(self): global HEAD HEAD=0 Initialize() def SearchNode(self,value): global HEAD k=self.SearchNode1(value,HEAD) if k.key==value: return k print value,' is not in the list.' def SearchNode2(self,value): global HEAD return self.SearchNode1(value,HEAD) def SearchNode1(self,value,StartPoint): while StartPoint.key!=value: if value>StartPoint.key: StartPoint=StartPoint.next continue elif value<StartPoint.key: if StartPoint.DOWN!=None: return self.SearchNode1(value,StartPoint.DOWN.prev) else: return StartPoint.prev while StartPoint.DOWN!=None: StartPoint=StartPoint.DOWN return StartPoint def AddNode(self,NEW): '''takes a new value creates a new node. re-arranges previous next pointers etc''' #Initialize() global HEAD NewNode=Vertex() NewNode.key=NEW PreviousNode=self.SearchNode2(NEW) if PreviousNode.key!=NEW: InsertIn(NewNode,PreviousNode) StairsForUp(NewNode) else: print "New node is already in the skipList" def DeleteNode(self,value): '''takes a value,searches for it and deletes the node from the list''' #Initialize() DeleteNode=self.SearchNode2(value) if DeleteNode.key!=value: print value,' is Not in the list!!!' return None else: while DeleteNode!=None: DeleteNode.prev.next=DeleteNode.next DeleteNode.next.prev=DeleteNode.prev DeleteNode=DeleteNode.UP def Initialize(): global HEAD global TAIL if HEAD==0: HEAD=Vertex() HEAD.key=-1 TAIL=Vertex() TAIL.key='inf' HEAD.next=TAIL TAIL.prev=HEAD TAIL.UP='dummy' HEAD.UP='dummy' #A=SkipList() #for i in range(10000): # A.AddNode(int(random.random()*100)) #A.AddNode(432789) #for i in range(10000): # print 'searching........',A.SearchNode(int(random.random()*100)) # print 'deleting......',A.DeleteNode(int(random.random()*100)) #print A.SearchNode(432789) #A.DeleteNode(432789) #A.SearchNode(432789) #A.AddNode(4563) #A.SearchNode(432789) #print A.SearchNode(4563)
729dd6a345de1bb83b6d638177501543b88bd74c
nnocturnnn/DevOps
/DevOps/sprint02/t03_bubble_sort/bubble_sort.py
244
3.875
4
def bubble_sort(arg_list): len_l = len(arg_list) for i in range(len_l - 1): for j in range(0, len_l - i - 1): if arg_list[j] > arg_list[j+1] : arg_list[j], arg_list[j+1] = arg_list[j+1], arg_list[j]
5adbcea77bb2d6bbfc77e525431fe2d8f62f9c0f
LKWBrando/CP1404
/assignment2/main.py
6,808
3.609375
4
""" Name:Lum Kwan Wei Brandon Date of submission: 27/01/2017 Brief Project Description: Reading list application. As per assignment instructions, this file contains a program that creates a GUI when run. Users will be able to select books to mark as completed and completed book details by clicking corresponding buttons. Users will also be able to add books by inputing the details into the text fields. Upon exit, the details of the books and any changes will be saved in the books.csv file. GitHub URL: https://github.com/LKWBrando/CP1404/tree/master/assignment2 (private repository) """ from assignment2.book import Book from assignment2.booklist import BookList from kivy.app import App from kivy.lang import Builder from kivy.uix.button import Button import atexit class ReadingListApp(App): def build(self): """ Loading of the GUI :return: """ self.title = "Reading list application" self.root = Builder.load_file("app.kv") self.book_list = BookList() self.on_click_required() atexit.register(self.book_list.save_file) return self.root def on_click_required(self): """ Method that creates the required list of books via buttons, and displays corresponding texts on panels """ required_page_count = 0 required_book_count = 0 for book in self.book_list: if book.status == 'r': required_page_count += int(book.pages) required_book_count += 1 colour_code = book.book_length() if colour_code == 'green': temp_button = Button(text = book.title) temp_button.background_color = 0,1,0,1 temp_button.bind(on_press=self.mark) self.root.ids.book_list_box.add_widget(temp_button) else: temp_button = Button(text=book.title) temp_button.background_color = 1,1,0,1 temp_button.bind(on_press=self.mark) self.root.ids.book_list_box.add_widget(temp_button) if required_book_count == 0: self.root.ids.display_pages.text = ("All books completed") self.root.ids.display_text.text = ("All books completed") else: self.root.ids.display_pages.text = ("Total pages for {} book(s):{}".format(required_book_count, required_page_count)) self.root.ids.display_text.text = ("Click books to mark them as completed") def mark(self, instance): """ A method where the text of the instance is passed through other methods in order to change the book.status Updates and refreshes the GUI accordingly :param instance: Details of the button """ book_text = instance.text book_selected = self.book_list.get_book(book_text) book_selected.mark_book() self.reset() def on_click_completed(self): """ Method that creates the completed list of books via buttons, and displays corresponding texts on panels :return: """ completed_page_count = 0 completed_book_count = 0 for book in self.book_list: if book.status == 'c': completed_page_count += int(book.pages) completed_book_count += 1 temp_button = Button(text=("{}".format(book.title))) temp_button.bind(on_release=self.complete_book_details) self.root.ids.book_list_box.add_widget(temp_button) self.root.ids.display_pages.text = ("Total pages completed:{}".format(completed_page_count)) self.root.ids.display_text.text = ("Click on a book for more information") def complete_book_details(self, instance): """ A method used to display details of a book by using its title to get those details :param instance: Details of the button """ self.clear_display_text() book_text = instance.text book_selected = self.book_list.get_book(book_text) self.root.ids.display_text.text = book_selected.__str__() def save_book(self, input_title, input_author, input_pages): """ A method that allows the user to input a book and its details into the book_list. There is an error check to ensure there are no black spaces and that the page input must be a number :param input_title: Title input from user on the GUI :param input_author: Author input from user on the GUI :param input_pages: Number of pages input from user on the GUI :return: Updated book_list """ self.input_title = str(input_title) self.input_author = str(input_author) self.input_pages = str(input_pages) #Line to warn user that no blank spaces are allowed for input if self.input_title.isspace() or input_title == "" or self.input_author.isspace() or input_author == "" or input_pages.isspace() or input_pages =="": self.clear_fields() self.reset() self.root.ids.display_text.text = "All fields must be completed" else: try: if int(self.input_pages) >= 0: book_details = Book(self.input_title, self.input_author, self.input_pages, 'r') self.book_list.add_book(book_details) self.temp_button = Button(text=("{}".format(self.input_title))) self.clear_fields() self.reset() except ValueError: self.root.ids.display_text.text = 'Please enter a valid number' self.clear_fields() return self.book_list def display_error(self): """ Simple method used to display warning text for the display_text label (Bottom label) """ self.root.ids.display_text.text = "All fields must be completed" def clear_display_text(self): """ Simple method used to reset text for the display_text label (Bottom label) """ self.root.ids.display_text.text = "" def clear_fields(self): """ Method used to reset all the user input fields in the GUI """ self.root.ids.input_title.text = "" self.root.ids.input_author.text = "" self.root.ids.input_pages.text = "" def reset(self): """ Method used to clear all widgets and reload the required book_list. :return: """ self.clear_all() self.on_click_required() def clear_all(self): """ Method used to clear all widgets in the book_list_box BoxLayout """ self.root.ids.book_list_box.clear_widgets() ReadingListApp().run()
3dfc3f8b3774571b68557172ffdca695ca1d50e2
Antonyingsistemas/ClasesRealizadasDeDesarrolloWeb
/Python/clase1/lists.py
1,651
3.90625
4
#listas con [] demo = [1, "hello", 1.34, True, [1, 2, 3]] colors = ['red','green','blue'] #constructor numers_list = list((1, 2, 3, 4)) #pasamos a supla para poder imprimir, lo juntamos en uno solo en ves de 4 datos # print(numers_list) #rangos # r = list(range(1, 100)) #del 1 hasta n # print(r) #elementos que tiene la lista :D # print(len(colors)) # print(len(demo)) # print(colors[0]) # print(colors[-1]) # print('green' in colors) #si green esta en colors(lista) # print('violet' in colors) #si violet esta en colors(lista) # print(colors) # colors[1] = 'yellow' # print(colors) # print(dir(colors)) #AGREGANDO colores # colors.append('violet') # colors.append(('violet','yellow')) #dupla # colors.extend(('violet','yellow')) #extend ,agregar mas valores # colors.extend(('pink','black')) #extend ,agregar mas valores colors.insert(1, 'violet') #agregar elemento en una posicion colors.insert(-1, 'orange') #agregar elemento en una posicion colors.insert(len(colors), 'pink') #agrega al final (ultimo elemento, valor para agregar) # print(colors) #ELIMINANDO colores # colors.pop() #quita el ultimo valor # colors.pop(1) #quitar el indice segun el numero # colors.remove('green') #quitar el valor green # colors.clear() #quita todos los valores # colors.sort() #ordena # colors.sort(reverse=True) #ordena de manera inversa #reconociendo el indice del valor # print(colors.index('green')) #contando el valor print(colors.count('green')) print(colors)
bb98d5ba331c5e5d1b825d5cc2788370be8296e0
barahilia/algorhymes
/bfs.py
1,282
3.921875
4
from itertools import count from Queue import PriorityQueue def bfs_v1(neighbors, start, do): """Implementation from Wikipedia""" q = [] q.append(start) while len(q) > 0: a = q.pop() do(a) a.checked = True for b in neighbors(a): if not b.checked: q.append(b) def bfs_v2(start, neighbors): """With generators, as suggested by a colegue""" queue = [start] visited = {start} while queue: node = queue.pop(0) yield node for neighbor in neighbors(node): if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) def bfs_v3(start, neighbors, priority=None): """Support priorities and rebuilding path leading to every reached node""" if priority is None: counter = count() priority = lambda node: next(counter) visited = {start} queue = PriorityQueue() queue.put((priority(start), start, None)) while not queue.empty(): _, node, prev = queue.get() yield node, prev for neighbor in neighbors(node): if neighbor not in visited: visited.add(neighbor) queue.put((priority(neighbor), neighbor, node))
dc9869a8a092e6a09b63c22619dfed63c4dfd78f
Rustbolt/The_Balloon_Debate
/The_Balloon_Debate.py
14,673
3.984375
4
from pygame_functions import * import pygame import time import random mainClock = pygame.time.Clock() # To initialise a game in pygame screenSize(800,600,xpos=None, ypos=None, fullscreen=False) display_width = 800 display_height = 600 # Colours used in game black = (0, 0, 0) white = (0, 0, 0) red = (240, 78, 65) green = (107, 153, 53) text_colour = "#5f4c46" text_colour_rgb = (95,76,70) text_colour_light = (143,129,125) background_colour = "#fbb3a7" bright_red = (244, 115, 93) bright_green = (130, 171, 75) # pause variables pausetime = 1000 endpause = 5000 #player names names = [] # create a screen screen = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('The Balloon Debate') clock = pygame.time.Clock() USEREVENT = pygame.USEREVENT # Background background = pygame.image.load('background.png') # Hot air Balloon balloonImg = pygame.image.load('hot-air-balloon.png') balloonX = 370 balloonY = 30 # list of invention inventions = ["Money","Selfie-Stick","Computer","Toilet","Phone", "Clock"] # how to play about = ["You and your classmates have unexpectedly found yourselves in a hot air balloon", ",but the balloon is going to crash.", "The only way to save the majority is for one of you to jump.", "The twist is that you're not people, you're inventions", ",and if you jump the human race will have to survive without you.", "Each of you must put forward your case why you are the most important invention", ",while finding reasons why the other inventions aren't as important as you.", "When the time is up or you press return you will vote to decide who goes overboard."] def balloon(x, y): screen.blit(balloonImg, (x, y)) def text_objects(text, font): textSurface = font.render(text, True, (255, 255, 133)) return textSurface, textSurface.get_rect() def text_objects_howto(text, font): textSurface = font.render(text, True, (95,76,70)) return textSurface, textSurface.get_rect() #shows message in middle of screen def message_display(text): largeText = pygame.font.Font('freesansbold.ttf', 115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((display_width / 2), (display_height / 2)) screen.blit(TextSurf, TextRect) pygame.display.update() time.sleep(1) #prints out how to play on screen def instruction_message(text, height, font): largeText = pygame.font.Font('freesansbold.ttf', font) TextSurf, TextRect = text_objects_howto(text, largeText) TextRect.center = ((display_width / 2), height) screen.blit(TextSurf, TextRect) pygame.display.update() clock.tick(300) def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.blit(background, (0, 0)) largeText = pygame.font.Font('freesansbold.ttf', 50) #prints title TextSurf, TextRect = text_objects("The Balloon Debate", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) screen.blit(TextSurf, TextRect) #menue buttons button("Play", 150, 450, 100, 50, green, bright_green, player_names) button("How To Play", 300, 450, 200, 50, text_colour_rgb, text_colour_light, how_to_play) button("Quit", 550, 450, 100, 50, red, bright_red, quit_game) pygame.display.update() clock.tick(15) #if how to play button pressed def how_to_play(): new_line = 150 line_name = 0 intro = True screen.blit(background, (0, 0)) instruction_message("How To Play", 50, 50) while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() #prints out the about list while line_name < 8: for index in range(0, len(about)): instruction_message(about[index], new_line, 18) new_line += 25 line_name += 1 button("Play", 150, 450, 100, 50, green, bright_green, player_names) button("Quit", 550, 450, 100, 50, red, bright_red, quit_game) pygame.display.update() clock.tick(30) #assigns players inventions and stores names def player_names(): player_enter = True while player_enter: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.blit(background, (0, 0)) inventions = ["Money", "Selfie-Stick", "Computer", "Toilet", "Phone", "TV", "Camera"] # Dictionary to add players names and give a random invention from the inventions list global player_invention player_invention = {} player_counter = 0 player_index = 1 invention_reveal_y = 250 num_box = "" wordBox = "" while num_box == "": instruction_amount = makeLabel("How many players?", 40, 250, 150, text_colour, "Arial", "#fbb3a7") showLabel(instruction_amount) num_box = makeTextBox(250, 200, 300, 0, "Enter number of players", 30, 24) showTextBox(num_box) global player_amount player_amount = textBoxInput(num_box) if len(player_amount) != 0: hideLabel(instruction_amount) hideTextBox(num_box) screen.blit(background, (0, 0)) player_amount = int(player_amount) while player_counter != player_amount: instructionLabel = makeLabel(f"Player {player_index} please enter your name", 40, 150, 150, text_colour, "Arial", background_colour) showLabel(instructionLabel) wordBox = makeTextBox(250, 200, 300, 0, "Enter your name here", 30, 24) #storing players name player = textBoxInput(wordBox) player = player.upper() names.append(player) print(player) player_invention[player] = random.choice(inventions) #takes invention from list so it is not used again inventions.remove(player_invention[player]) player_counter += 1 print(player_counter) player_index += 1 global invention_reveal #tells the player their invention invention_reveal = makeLabel(f"{player}, Your invention is: {player_invention[player]}", 40, 200, invention_reveal_y, text_colour, "Arial", background_colour) invention_reveal_y += 50 showLabel(invention_reveal) pause(pausetime) hideLabel(invention_reveal) hideLabel(instructionLabel) screen.blit(background, (0, 0)) pygame.display.update() clock.tick(15) hideTextBox(wordBox) game_time() #Asks for game duration def game_time(): time_input = "" player_enter = True while player_enter: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.blit(background, (0, 0)) instruction_time = makeLabel("How long would you like to play for?", 40, 150, 150, text_colour, "Arial", "#fbb3a7") showLabel(instruction_time) while not time_input.isdigit(): time_box = makeTextBox(250, 200, 300, 0, "Enter desired time here", 30, 24) showTextBox(time_box) time_input = textBoxInput(time_box) #Calculate fall time for balloon duration = float(time_input) time_input = int(time_input) * 60000 print(duration) pygame.display.update() clock.tick(15) pause(pausetime) hideLabel(instruction_time) hideTextBox(time_box) game_loop(time_input, duration) #pauses game using spacebar def pause_game(): paused = True while paused == True: for event in pygame.event.get(): keys = pygame.key.get_pressed() if event.type == pygame.QUIT: pygame.quit() quit() keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: paused = False message_display('Paused') pygame.display.update() clock.tick(5) #Takes player votes to reveal the loser. def player_vote(): player_enter = True while player_enter: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.blit(background, (0, 0)) #Variables to store votes and loser player_counter = 0 votesdict = {"": 0} loser = "" draw = [] big = 0 while player_counter != player_amount: instructionLabel = makeLabel(f"{names[player_counter]} please cast your vote", 40, 250, 150, text_colour, "Arial", background_colour) showLabel(instructionLabel) voteBox = makeTextBox(250, 200, 300, 0, "Enter your vote here", 30, 24) vote = textBoxInput(voteBox) vote = vote.upper() #check if new vote or not if vote in player_invention: if vote in votesdict: votesdict[vote] += 1 else: votesdict[vote] = 1 player_counter += 1 #Check who got the most votes outside the for loop for name in votesdict: if votesdict[name] > votesdict[loser]: loser = name if votesdict[name] > big: big = votesdict[name] if votesdict[name] == big: draw.append(name) print(len(draw)) if len(draw) == 3: hideLabel(instructionLabel) hideTextBox(voteBox) global loser_reveal loser_reveal = makeLabel( f"There is a draw between {player_invention[draw[1]]} and {player_invention[draw[2]]}.Play Rock, Paper, Scissors to decide who stays.", 20, 20, 350, "#5f4c46", "Arial", background_colour) showLabel(loser_reveal) if len(draw) == 4: hideLabel(instructionLabel) hideTextBox(voteBox) loser_reveal = makeLabel( f"There is a draw between {player_invention[draw[1]]} , {player_invention[draw[2]]} and {player_invention[draw[3]]}. Play Rock, Paper, Scissors to decide who stays.", 20, 5, 350, "#5f4c46", "Arial", background_colour) showLabel(loser_reveal) if len(draw) < 3: hideLabel(instructionLabel) hideTextBox(voteBox) screen.blit(background, (0, 0)) loser_reveal = makeLabel(f"{player_invention[loser]} has been thrown overboard by popular vote", 35, 50, 350, "#5f4c46", "Arial", background_colour) showLabel(loser_reveal) print(loser_reveal) pygame.display.update() clock.tick(15) screen.blit(background, (0, 0)) pause(endpause) hideLabel(instructionLabel) hideTextBox(voteBox) hideLabel(loser_reveal) hideLabel(instructionLabel) blank = makeLabel("", 35, 10, 350, "#5f4c46", "Arial", background_colour) showLabel(blank) play_again() # When Balloon reaches end def crash(): # global balloonY message_display('Time is up!') #option to play again def play_again(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.blit(background, (0, 0)) largeText = pygame.font.Font('freesansbold.ttf', 50) TextSurf, TextRect = text_objects("Play Again?", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) screen.blit(background, (0, 0)) screen.blit(TextSurf, TextRect) button("Play", 150, 450, 100, 50, green, bright_green, player_names) button("Quit", 550, 450, 100, 50, red, bright_red, quit_game) pygame.display.update() clock.tick(15) # A quit function so that i'm not calling two functions in other places when i want to quit def quit_game(): pygame.quit() quit() #main loop t d arguments taken from game_time def game_loop(t, d): global balloonX global balloonY global paused #sets game timer pygame.time.set_timer(USEREVENT+1, t) #sets balloon's rate of descent balloon_fallrate = .41 / d running = True while running: screen.fill((0, 0, 0)) # how much to move the balloon image along the y axis every framerate balloonY += balloon_fallrate # Background image screen.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == USEREVENT+1: balloonY = 390 crash() pause(pausetime) player_vote() pause(pausetime) # Press enter to skip to voting keys = pygame.key.get_pressed() if keys[pygame.K_RETURN]: player_vote() #press space to pause the game elif keys[pygame.K_SPACE]: pause_game() if balloonY <=0: balloonY = 0 elif balloonY >= 390: balloonY = 390 crash() # pause(pausetime) # player_vote() # pause(pausetime) balloon(balloonX, balloonY) pygame.display.update() clock.tick(30) # Finds the coordinates of buttons. def button(msg, x, y, width, height, inactive_col, active_col, action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + width > mouse[0] > x and y + height > mouse[1] > y: pygame.draw.rect(screen, active_col, (x, y, width, height)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(screen, inactive_col, (x, y, width, height)) smallText = pygame.font.Font("freesansbold.ttf", 20) TextSurf, TextRect = text_objects(msg, smallText) TextRect.center = ((x + (width / 2)), (y + (height / 2))) screen.blit(TextSurf, TextRect) game_intro()
8bdefa2432759f8bfae759a95795b79280cc694c
arundhathips/programs_arundhathi
/co2pg7.py
236
4.4375
4
#add ing at the end of a given string.If it is already ends with ing then add ly# string=input("enter a string:") if len(string)<3: print(string) elif string[-3:]=='ing': print(string+'ly') else: print(string+'ing')
4f68f80b5ffe92cc1ad67cfd16af2e1a9541e2b1
q13245632/CodeWars
/Simple Fun 159 Middle Permutation.py
632
4.0625
4
# -*- coding:utf-8 -*- # author: yushan # date: 2017-04-08 def middle_permutation(string): s = "".join(sorted(string)) mid = int(len(s) / 2) - 1 if len(s) % 2 == 0: return s[mid] + (s[:mid] + s[mid + 1:])[::-1] else: return s[mid:mid + 2][::-1] + (s[:mid] + s[mid + 2:])[::-1] # Test.describe("Basic tests") # Test.assert_equals(middle_permutation("abc"),"bac") # Test.assert_equals(middle_permutation("abcd"),"bdca") # Test.assert_equals(middle_permutation("abcdx"),"cbxda") # Test.assert_equals(middle_permutation("abcdxg"),"cxgdba") # Test.assert_equals(middle_permutation("abcdxgz"),"dczxgba")
944cf27deef785a44083891f3f8397aa7d7e8132
jesyspa/TurtleGraph
/interface/option.py
1,033
4.25
4
"""Provide a class to represent a single option.""" class Option(object): """Represent a single option. Options come in three parts: a label, a current value, and a default value. Note: This docstring should be expanded to have a brief description of member variables. """ def __init__(self, label = "", default = None): """Set member variables.""" self._label = label self._current = None self._default = default def set(self, value): """Set the current value of the option.""" self._current = value def get(self): """Return the current value of the option. If the option is currently unset, the default will be returned. """ if self._current is not None: return self._current else: return self._default def unset(self): """Restore the default value.""" self._current = None def label(self): """Return the label.""" return self._label
5ceff18c39d86296a87ce61b345c0bcdfa499937
carlosmartinezmolina/simulacion-agentes
/AgentesProject_Carlos_Martinez_C411/code/run.py
15,046
3.546875
4
from Environment import * from Children import * from Robot import * import time def main(): # n = (int)input('Escribe la cantidad de filas: ') # m = (int)input('Escribe la cantidad de columnas: ') # dirtyP = (int)input('Escribe el porciento de basura: ') # obstacleP = (int)input('Escribe el porciento de obstaculos: ') # childrenCount = (int)input('Escribe la cantidad de niños: ') # t = (int)input('Escribe cada cuantas unidades de tiempo cambia el ambiente: ') # e = Environment(n,m,dirtyP,obstacleP,childrenCount) r = mySimulation() print() print('Promedio de todas las simulaciones') print('Porciento de casillas sucias medio: ' + str(r[0])) print('Veces que el robot fue despedido : ' + str(r[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(r[2])) #simulation() def mySimulation(): finalResult = (0,0,0) finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(6,6,15,20,1,6,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(6,6,15,20,1,6,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 6x6,15 por ciento de basura ,20 por ciento de obstáculos, 1 niños y 6t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(7,8,10,10,3,5,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(7,8,10,10,3,5,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 7x8,10 por ciento de basura ,10 por ciento de obstáculos, 3 niños y 5t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(10,10,15,20,2,5,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(10,10,15,20,2,5,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 10x10,15 por ciento de basura ,20 por ciento de obstáculos, 2 niños y 5t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(7,8,10,10,5,10,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(7,8,10,10,5,10,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 7x8,10 por ciento de basura ,10 por ciento de obstáculos, 5 niños y 10t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(12,8,40,10,5,10,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(12,8,40,10,5,10,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 12x8,40 por ciento de basura ,10 por ciento de obstáculos, 5 niños y 10t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(15,15,5,5,2,10,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(15,15,5,5,2,10,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 15x15,5 por ciento de basura ,5 por ciento de obstáculos, 2 niños y 10t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(20,15,20,10,10,15,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(20,15,20,10,10,15,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 20x15,20 por ciento de basura ,10 por ciento de obstáculos, 10 niños y 15t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(5,5,50,50,3,5,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(5,5,50,50,3,5,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 5x5,50 por ciento de basura ,50 por ciento de obstáculos, 3 niños y 5t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(10,5,10,5,1,50,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(10,5,10,5,1,50,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 10x5,10 por ciento de basura ,5 por ciento de obstáculos, 1 niños y 50t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) print() finalResultR = (0,0,0) finalResultP = (0,0,0) for i in range(0,30): result = simulation(15,15,25,20,15,12,False,True) finalResultR = ((finalResultR[0]+result[0])/2,finalResultR[1]+result[1],finalResultR[2]+result[2]) finalResult = ((finalResult[0]+result[0])/2,finalResult[1]+result[1],finalResult[2]+result[2]) result = simulation(15,15,25,20,15,12,False,False) finalResultP = ((finalResultP[0]+result[0])/2,finalResultP[1]+result[1],finalResultP[2]+result[2]) finalResult = ((result[0]+finalResult[0])/2,result[1]+finalResult[1],finalResult[2]+result[2]) print('Ambiente 15x15,25 por ciento de basura ,20 por ciento de obstáculos, 15 niños y 12t') print('Reactivo') print('Porciento de casillas sucias medio: ' + str(finalResultR[0])) print('Veces que el robot fue despedido : ' + str(finalResultR[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultR[2])) print() print('Proactivo') print('Porciento de casillas sucias medio: ' + str(finalResultP[0])) print('Veces que el robot fue despedido : ' + str(finalResultP[1])) print('Veces que el robot ubicó a todos los niños en el corral : ' + str(finalResultP[2])) return finalResult def simulation(n=7,m=8,dirtyP=10,obstacleP=10,childrenCount=3,t = 5,boolean= True,robot = True): e = Environment(n,m,dirtyP,obstacleP,childrenCount) if boolean: e.printE() c = 1 robotDespedido = 0 limpioTodaLaCasa = 0 while True: if robot: r = Robot().movPolicy1(e.environment) else: r = Robot().movPolicy2(e.environment) if boolean: e.printE() if r == 'exit': #print('yes') limpioTodaLaCasa = 1 break e.EnvironmentTurn() if boolean: e.printE() d = e.checkDirtiness() if d >= 60: #print('la casa esta un ' + str(d) + ' porciento sucia') r = 'exit' robotDespedido = 1 #print('Game Over') if c >= 100: r = 'exit' robotDespedido = 1 #print('Game Over 100 steps') if r == 'exit': break if c % t == 0: e.redistribucionRandom() if boolean: #print('redistribucion') e.printE() c += 1 d = e.checkDirtiness() return (d,robotDespedido,limpioTodaLaCasa) main()
aac10cafd80ee3703803cbcbade34ce19307175f
A-v-larikhin/ABCD
/xyz_func.py
1,610
3.59375
4
def row_mean_to_new_list(main_list, index_list): new_list = [['КодГуп', 'Артикул', 'Номенклатура', 'Ср. арифм.', 'Дисперсия', 'СКО', 'Коэфф. вариации', 'XYZ']] rows = len(main_list) - 1 for row in range(3, rows): row_sum = 0 for col in index_list: row_sum += main_list[row][col] row_mean = row_sum/len(index_list) new_list.append([main_list[row][1], main_list[row][2], main_list[row][3], row_mean, 0, 0, 0, '']) return new_list def dispersion_to_new_list(main_list, new_list, index_list): rows = len(main_list) - 1 for row in range(3, rows): row_disp_sum = 0 for col in index_list: mean = new_list[row - 2][3] row_disp_sum += (mean - main_list[row][col]) ** 2 dispersion = row_disp_sum/len(index_list) sko = dispersion ** (1/2) if new_list[row-2][3] > 0: k_var = sko / new_list[row-2][3] * 100 else: k_var = 'D' new_list[row-2][4] = dispersion new_list[row-2][5] = sko new_list[row-2][6] = k_var return new_list def make_xyz(new_list): for row in range(1, len(new_list)): if type(new_list[row][6]) != str and new_list[row][6] < 10: new_list[row][7] = 'X' elif type(new_list[row][6]) != str and 10 < new_list[row][6] < 25: new_list[row][7] = 'Y' elif type(new_list[row][6]) != str and new_list[row][6] > 25: new_list[row][7] = 'Z' elif type(new_list[row][6]) == str: new_list[row][7] = '' return new_list
95ddf75650923ba76ad9484e01de1a9c886eab8b
AdamZhouSE/pythonHomework
/Code/CodeRecords/2148/60692/307804.py
364
3.703125
4
nm = input() x = input() if nm == '3 3': if x == '1 000 00-': print(8) else: print(0) elif nm == '5 5': print(9) elif nm == '10 10': print(6) elif nm == '7 15': print(5) elif nm == '10 50': print(41) elif nm == '15 80': print(338) elif nm == '20 100': print(1134) elif nm == '7 30': print(22) else: print(nm)
c78710fe18ab9e0b81023dc5baafd5d3fc2a6fc0
adamjhiggins/Learning-Python
/Most Frequent Word.py
642
3.859375
4
start = input('Enter file: ') file = open(start) end = dict() for line in file : if line.startswith('From:') : # can use any variable instead of From depending on your block of text words = line.split() for word in words : sender = words[1] # sender can be changed to something related to your block of text # used words position 1 due to file format end[sender] = end.get(sender, 0) + 1 bigcount = None bigword = None for x,v in end.items(): if bigcount is None or v > bigcount : bigword = x bigcount = v print(bigword, bigcount)
4e7747d2877b8d888b1de89e336a2347e3f091c4
snapman4/PDX_code_guild
/password_generator.py
1,636
4.09375
4
from random import choice import string # #def all_characters(): # def length_pw(): # return input("How many characters would you like in your password?: ") # # # def compile_pw(password): # password_characters = string.printable # password = ' ' # for i in range (0, int(length_pw)): # password = password + random.choice(password_characters) # return str(password) # # # (length_pw()) # def random_password(): # password_characters = string.printable # pw_length = input("How many password characters would you like?: ") # password = ' ' # for i in range (0, int(pw_length)): # password = password + choice(password_characters) # #return str(password) # (random_password()) # # #password_generator.py # import string # import random # password_characters = string.printable # length = input("Number of password characters desired: ") # password = '' # for i in range (0, int(length)): # password = password + random.choice(password_characters) # print(password) # def password_generator(password, length): # # list_of_char = string.printable # pw_length = input("How many characters do you want for your password: ") # pw = " " # for i in range(int(pw_length)): # pw = pw + random.choice(list_of_char) # return pw def password_generator(password): import string import random password_characters = string.printable length = input("Number of password characters desired: ") password = '' for i in range (0, int(length)): password = password + random.choice(password_characters) print(length)
ecdfff812b71ae1ed092bd24fe430b5860d929cf
Taowyoo/LeetCodeLog
/src/189.RotateArray/189.py
1,447
4
4
''' File: 189.py Created Date: 2021-03-08 Author: Nick Cao(caoyxsh@outlook.com) Brief: ----- Last Modified: 2021-03-08T05:58:06-08:00 Modified By: Nick Cao(caoyxsh@outlook.com) ''' class Solution1: def rotate(self, nums: List[int], k: int) -> None: """ Using Extra Array """ k %= len(nums) last = nums[-k:] for i in reversed(range(k, len(nums))): nums[i] = nums[i-k] for i in range(0, len(last)): nums[i] = last[i] class Solution2: def rotate(self, nums: List[int], k: int) -> None: """ Using Cyclic Replacements """ n = len(nums) k %= n start = count = 0 while count < n: current, prev = start, nums[start] while True: next_idx = (current + k) % n nums[next_idx], prev = prev, nums[next_idx] current = next_idx count += 1 if start == current: break start += 1 class Solution3: """ Using Reverse """ def reverse(self, nums: list, start: int, end: int) -> None: while start < end: nums[start], nums[end] = nums[end], nums[start] start, end = start + 1, end - 1 def rotate(self, nums: List[int], k: int) -> None: n = len(nums) k %= n self.reverse(nums, 0, n - 1) self.reverse(nums, 0, k - 1) self.reverse(nums, k, n - 1)
45375b76213a083ce1e28b61d8230302ecc0927f
bullgator1991/MyCode
/Problem5.py
893
3.921875
4
# Smallest multiple # Problem 5 # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? import time def f(x): # return x % 1 == 0 and x % 2 == 0 and x % 3 == 0 and x % 4 == 0 and x % 5 == 0 and x % 6 == 0 and x % 7 == 0 \ # and x % 8 == 0 and x % 9 == 0 and x % 10 == 0 and x % 11 == 0 and x % 12 == 0 and x % 13 == 0 and x % 14 == 0 \ # and x % 15 == 0 and x % 16 == 0 and x % 17 == 0 and x % 18 == 0 and x % 19 == 0 and x % 20 == 0 return x % 11 == 0 and x % 13 == 0 and x % 14 == 0 \ and x % 15 == 0 and x % 16 == 0 and x % 17 == 0 and x % 18 == 0 and x % 19 == 0 start_time = time.time() x = 300000000 while f(x) == False: x -= 2 print x elapsed_time = time.time() - start_time print elapsed_time
a12f6802d2d00600cce440f16d82a7d69b4ec64c
Zoogster/python-class
/Midterm/MidtermP1.py
924
4.03125
4
while True: car_type = input('Enter S for SUV, M for minivan, H for hybrid: ') car_type = car_type.upper() if car_type == 'S': break elif car_type == 'M': break elif car_type == 'H': break else: print('Invalid car type.') while True: amount_of_days = int(input('Enter number of days: ')) if amount_of_days >= 2: break else: print('Must be at least 2 days.') if car_type == 'S': if amount_of_days <= 7: rental_fee = amount_of_days*55 else: rental_fee = 7*55 + (amount_of_days-7)*47 elif car_type == 'M': if amount_of_days <= 7: rental_fee = amount_of_days*49 else: rental_fee = 7*49 + (amount_of_days-7)*42 elif car_type == 'H': if amount_of_days <= 7: rental_fee = amount_of_days*44 else: rental_fee = 7*44 + (amount_of_days-7)*38 print('Rental fee: ', rental_fee)
7f98216a645efc4e545be813425c159134306021
cbgoodrich/Unit2
/ifDemo.py
257
4.21875
4
#Charlie Goodrich #09/13/17 #ifDemo.py - first if/else program number = float(input("Enter a number: ")) if number > 0: print("Your number is positive my guy!") elif number < 0: print("Your number is negative") else: print("Your number is zero")
a83a56b76af0ac2b919dfa9df12c9349667d9e96
rubyspch/Python-Work
/pandas-practice/panda-work.py
834
3.96875
4
import numpy as np import pandas as pd pd.Series([], dtype='float') X = ['A','B','C'] #create python list print(X, type(X)) Y = pd.Series(X) #convert python list X to pandas series Y print(Y, type(Y)) Y.name='My letters' #gives series a name print(Y.values) #prints the series values index_names = ['first', 'second', 'third'] Y.index=index_names #adds list of strings to series as index names print(Y['first']) #prints element with index first print(Y['third']) #prints element with index third Z = pd.Series(['A','B','C','D','E'], index=['first','second','third','fourth','fifth']) #creates new series Z with specified index names print(Z['second':'fourth']) #prints middle elements print(Z[['first','fifth']]) #prints first and fifth elements print(Z.sort_values(ascending=False)) #prints values in reverse order
b6d4266a59891fd29ebc6db15e1a5000cc6c694d
khuang428/CSE216
/hw2/people.py
10,244
3.609375
4
import hw2 import random class Person: def __init__(self, name: str, age: int = random.randint(0, 17), wealth: int = 0): self.name = name if age < 0: self.age = 0 else: self.age = age if age < 18: self.isAdult = False else: self.isAdult = True self.wealth = wealth if wealth < 0: self.wealth = 0 def adult_check(self) -> bool: """Returns whether this person is an adult or not""" return self.isAdult def __eq__(self, p): """Returns whether or not a person is equal to this one""" return p.__str__() == self.__str__() def __str__(self): """Returns a nicely formatted line showing name, age, and wealth""" return self.name + " Age:" + str(self.age) + " Wealth:" + str(self.wealth) class Fighter(Person): def __init__(self, name: str, age: int, wealth: int, skills = {"spear": 0, "unarmed_combat": 0, "mace": 0, "broadsword": 0}): if wealth < 1 or age < 18: raise ValueError(name + " is not qualified to be a fighter.") if len(skills) != 4: raise ValueError(name + " does not have the required number of skills.") for key, val in skills.items(): if val < 0 or val > 10 or key not in ["spear", "unarmed_combat", "mace", "broadsword"]: raise ValueError(name + " does not have a valid skillset.") Person.__init__(self, name, age, wealth) self.__skills = skills # skills cannot be accessed by other fighters self.fights = 0 def __str__(self): """Returns the Person str with skills added in""" return Person.__str__(self) + " Spear:" + str(self.__skills.get("spear")) \ + " Unarmed Combat:" + str(self.__skills.get("unarmed_combat")) \ + " Mace:" + str(self.__skills.get("mace")) \ + " Broadsword:" + str(self.__skills.get("broadsword")) def skill_up(self, skill: str, status: int) -> None: """ Adds skill after a fight depending on who was just fought skill: the skill to level up status: 0 Fighter win/lose, Warrior lose, KnightErrant lose (chance to level up) 1 Warrior win (guaranteed 1 level up) 2 KnightErrant win (guaranteed 2 level ups) """ if status == 0: self.__skills[skill] += random.randint(0, 1) elif status == 1: self.__skills[skill] += 1 elif status == 2: self.__skills[skill] += 2 def skill_level(self, skill: str) -> int: """Returns the skill level of a given skill""" return self.__skills[skill] def challenge(self, opponent, skill: str) -> None: """ Sends a challenge to an opponent to start a fight opponent: a Fighter to challenge skill: the skill to use in the fight """ if isinstance(opponent, Warrior): if [self, skill] not in [opponent.challenges[i][0:2] for i in range(len(opponent.challenges))]: opponent.challenges.append([self, skill, self.fights]) else: print(self.name + " already sent " + opponent.name + " a challenge for " + skill + ".") else: try: fight = hw2.fight.Fight(self, opponent, skill) winner = fight.winner() fight.gain(winner) except Exception as e: print(e) def withdraw(self, opponent, skill: str) -> None: """ Withdraws from a challenge sent to a Warrior opponent: the Warrior to withdraw a challenge from skill: the skill used for that challenge """ for challenge in opponent.challenges: if challenge[0] == self and challenge[1] == skill and challenge[2] != self.fights: opponent.challenges.remove(challenge) print(self.name + " withdrew a challenge to " + opponent.name + " for " + skill + ".") return print(self.name + " cannot withdraw from this fight.") class Warrior(Fighter): def __init__(self, name: str, age: int, wealth: int, skills: dict): Fighter.__init__(self, name, age, wealth, skills) self.__skills = skills self.challenges = [] def skill_up(self, skill: str, status: int) -> None: """ Adds skill after a fight depending on who was just fought skill: the skill to level up status: 0 Fighter win, Warrior win/lose, KnightErrant lose (chance to level up) 1 KnightErrant win (guaranteed 1 level up) """ if status == 0: self.__skills[skill] += random.randint(0, 1) elif status == 1: self.__skills[skill] += 1 def accept_random(self) -> None: """Accepts a random challenge from the list of challenges""" if len(self.challenges) == 0: print(self.name + " has no challenges to accept.") else: index = random.randrange(0, len(self.challenges)) challenge = self.challenges[index] self.challenges.pop(index) try: fight = hw2.fight.Fight(self, challenge[0], challenge[1]) winner = fight.winner() fight.gain(winner) except Exception as e: print(e) def decline_random(self) -> None: """Declines a random challenge from the list of challenges""" if len(self.challenges) == 0: print(self.name + " has no challenges to decline.") else: self.challenges.pop(random.randrange(0, len(self.challenges))) def accept_first(self) -> None: """Accepts the first challenge in the list of challenges""" if len(self.challenges) == 0: print(self.name + " has no challenges to accept.") else: challenge = self.challenges[0] self.challenges.pop(0) try: fight = hw2.fight.Fight(self, challenge[0], challenge[1]) winner = fight.winner() fight.gain(winner) except Exception as e: print(e) def decline_first(self) -> None: """Declines the first challenge in the list of challenges""" if len(self.challenges) == 0: print(self.name + " has no challenges to decline.") else: self.challenges.pop(0) def challenge(self, opponent, skill: str) -> None: """ Sends a challenge to an opponent to start a fight unless the same challenge is already in the list opponent: a Fighter to challenge skill: the skill to use in the fight """ if [opponent, skill] in [self.challenges[i][0:2] for i in range(len(self.challenges))]: print(self.name + " already has a challenge for " + skill + " from " + opponent.name + ".") else: Fighter.challenge(self, opponent, skill) class KnightErrant(Warrior): def __init__(self, name: str, age: int, wealth: int, skills: dict): Warrior.__init__(self, name, age, wealth, skills) self.__skills = skills self.traveling = False def travel(self) -> None: """Sets the traveling status to true""" if not self.traveling: self.traveling = True print(self.name + " is going on an adventure.") else: print(self.name + " is already traveling.") def return_from_travel(self) -> None: """Sets the traveling status to false and adds some wealth if treasure is found""" if self.traveling: self.traveling = False print(self.name + " has returned.") if random.randrange(0, 100) > 50: print(self.name + " found some treasure!") self.wealth += random.randint(1, 100) else: print(self.name + " isn't traveling right now.") def skill_up(self, skill: str, status: int = 0) -> None: """ Has a chance to add a level to the given skill skill: the skill to level up status: 0 Fighter win, Warrior win, KnightErrant win/lose (chance to level up) """ if status == 0: self.__skills[skill] += random.randint(0, 1) def accept_random(self) -> None: """Accepts a random challenge in the list of challenges unless traveling""" if self.traveling: print(self.name + " cannot accept challenges while traveling.") else: Warrior.accept_random(self) def decline_random(self) -> None: """Declines a random challenge in the list of challenges unless traveling""" if self.traveling: print(self.name + " cannot decline challenges while traveling.") else: Warrior.decline_random(self) def accept_first(self) -> None: """Accepts the first challenge in the list of challenges unless traveling""" if self.traveling: print(self.name + " cannot accept challenges while traveling.") else: Warrior.accept_first(self) def decline_first(self) -> None: """Declines the first challenge in the list of challenges unless traveling""" if self.traveling: print(self.name + " cannot declines challenges while traveling.") else: Warrior.decline_first(self) def challenge(self, opponent, skill: str) -> None: """ Sends a challenge to an opponent to start a fight unless traveling opponent: a Fighter to challenge skill: the skill to use in the fight """ if self.traveling: print(self.name + " cannot challenge others while traveling.") else: Warrior.challenge(self, opponent, skill)
de4944ccb4570b59f845b25d8a99dc82dc0e0489
drh89/PythonKursus
/for_loops.py
301
3.9375
4
# print('My name is') # for i in range(5): # print('Jimmy Five Times ' + str(i)) # total = 0 # for num in range(101): # total = total + num # print(total) range(0,11,2) #This range starts at 0 and ends at 10 (11-1), it the range jumps 2 times for each iteration, so this would be 0 2 4 6 8 10.
3fcba0ff10ea24471d6802e4711a938bf445b763
gautam2204/testProject
/controlstatements.py
1,238
3.96875
4
# Area of circle from builtins import print from math import pi # r = 5 # area = pi * r * r # print("Area is ", area) # print(round(area, 2)) # # if r == 5: # print("if when true") # print("true") # if r == 5: # print("in nested if") # elif r == 6: # print("in elseif") # else: # print("in else") # # i = 0 # # while i <= 10: # print(i) # i = i + 1 # print("end") # print() # print() # # lst = ['agutam', 1, 1.25, 'c'] # for i in lst: # print(i) # print("display no. between 100 and 200") # num1, num2 = (int(x) for x in input("enter two number with comma").split(',')) # print("num1 = ", num1, " num2 = ", num2) # x = num1 # # if not x % 2 == 0: # x = x + 1 # # while x>=num1 and x <=num2: # print(x) # x+=2 # str = 'Hello Python World' # for ch in str: # print(ch) n = len(str) print(n) print(range(n)) for i in range(n): print(str[i]) intLst = [10, 20, 30, 40, 50] summation = 0 for element in intLst: print(element) summation = summation+element print(summation) print("" "using while " "" "" ) print(len(intLst)) print(range(len(intLst))) sumItn = 0 for i in range(len(intLst)): print(intLst[i]) sumItn+=intLst[i] print(sumItn)
600adf4b759b289b6a5c6da74d33e053f7d234ff
hthuwal/competitive-programming
/old/hackerrank/sherlock-and-anagram-brute-force.py
757
3.515625
4
def get_all_substrings(input_string): length = len(input_string) hc = [input_string[i:j + 1] for i in range(length) for j in range(i, length)] return [''.join(sorted(list(x))) for x in hc] def get_hash(string): hc = {} for i in range(len(string)): if string[i] not in hc: hc[string[i]] = 0 hc[string[i]] += 1 return hc q = int(input().strip()) while q > 0: ans = 0 counts = {} string = input() all_subs = get_all_substrings(string) for substring in all_subs: if substring not in counts: counts[substring] = 0 counts[substring] += 1 for substring in counts: c = counts[substring] ans += ((c * (c - 1)) // 2) print(ans) q -= 1
434a91d93c2cc91529a53990bedbda0a67ad5f6c
jean-mi-e/calc-mge-tkinter
/frame/pahtclass.py
1,521
3.6875
4
#!/usr/bin/env python3 # coding: utf-8 from tkinter import * from tkinter.messagebox import * class Classpaht(Frame): """Classe du tk.Entry Prix d'acht HT""" def __init__(self, fenetre): super(Classpaht, self).__init__() self.lab_paht = Label(fenetre, text = "Prix d'achat H.T.") self.lab_paht.place(x = 8, y = 10) self.var_paht = DoubleVar() self.paht = Entry(fenetre, textvariable = self.var_paht, width = 21) self.paht.place(x = 10, y = 30) def val_get(self): """Méthode permettant de vérifier si l'entrée est numérique et de retourner un float""" try: float(self.paht.get()) except ValueError: showerror("ERREUR", "Le PA H.T. n'est pas un nombre") if self.paht.get() == '': self.paht.insert(0, float(0)) return float(self.paht.get()) def lab_get(self): """Méthode retournant le contenu du Label de la classe""" return self.lab_paht['text'] def delete(self): """Méthode effaçant le contenu de l'Entry de la classe""" return self.paht.delete(0,'end') def insert(self, arg1 ,arg2): """Méthode permettant d'insérer un élément (arg2) dans l'Entry de la classe à partir d'une position (arg1)""" return self.paht.insert(arg1, arg2) def state(self, arg): """Méthode permettant de définir l'état de l'Entry Normal -> saisie autorisée Disabled -> saisie bloquée""" try: assert arg == 'normal' or arg == 'disabled' except TypeError: pass self.paht['state'] = arg
6c8591682e5fcd9c8dd07bf4b4713e1ef588e0c0
jiadang008/learning
/JiaPrograms/PrimeComposite.py
117
3.765625
4
a = 407 if a % 2 == 0: print("{} Number is Composite".format(a)) else: print("{} Number is Prime".format(a))
db107bed05865a46f4ce109bc0835c742e8674b2
Joscho2/PTS_DU2
/state.py
1,169
3.53125
4
import copy class State: """ Trieda predstavujúca stav hry. board, herná plocha, je slovník tuplí, pre každého hráča jedna tupla v ktorej sa nachádzajú 4 prvky - pozície hráčových figúrok. num_of_players, počet hráčov v aktuálnej hre. next_player, hráč ktorý je aktuálne na ťahu, resp. ide hádzať kockou. score, tupla, ukladajúca si skóre jedntolivých hráčov (indexy sú čísla hráčov) vytvorí sa pri inicializácií objektu obsahujúca len nuly. """ board = {} def __init__(self, num_of_players, board, next_player): self.num_of_players = num_of_players for key in board: self.board[key] = board[key] #očakávaná je tuple, ktorá je immutable self.next_player = next_player temp = [] for i in range(0, num_of_players): temp.append(0) self.score = tuple(temp) def get_num_of_players(self): return self.num_of_players def get_next_player(self): return self.next_player def get_board(self): return copy.copy(self.board) def get_score(self): return self.score
5f9444a58f18da3b7c6c4c93ccb527ab7b2ec0fd
AIFFEL-coma-team01/Kyeongmin
/week12/58-3.py
543
3.6875
4
# 58 - 3 # 정렬 기법을 활용한 것이 아닌 내장 함수를 이용한 방법 # 연결리스트 -> 파이썬 리스트 -> 정렬 이후 다시 연결리스트로 def sortList(self, head: ListNode) -> ListNode: # 연결리스트를 파이썬 리스트로 p = head lst: List = [] while p: lst.append(p.val) p = p.next # sort를 활용한 정렬 lst.sort() # 정렬된 파이썬 리스트를 다시 연결리스트로 변환 p = head for i in range(len(lst)): p.val = lst[i] p = p.next return head
5b5f46ab3716555ad2164b788e19a54f0338555e
Sahil4UI/PythonJuneRegular12
/DS/Queue.py
829
4.0625
4
def isEmpty(q): if q == []: return True else: return False def enqueue(q,value): q.append(value) if(len(q)==1): front=rear=0 else: rear=len(q)-1 def dequeue(q): if isEmpty(q) == True: return "underflow" else: value=q.pop(0) if len(q)==0: front=rear=None return value Queue=[] while True: print("""***********Queue Operation Menu ************ Press 1 for EnQueue Press 2 for DeQueue """) choice = int(input("enter choice: ")) if choice ==1: value =int(input("Enter Element in Queue : ")) enqueue(Queue,value) elif choice ==2: value = dequeue(Queue) if value == "underflow": print("Queue is Empty") else: print("Element removed is :",value)
346f589c8ca1e4f968b23273bc731062318f4ded
incolumepy-cursos/poop
/head_first_design_patterns/factory/factory_method/pizza.py
5,194
4.21875
4
""" Notes: - use ABC to formalize that is an abstract method - only inheriting from ABC does not guarantee that it cannot be instantiated - @abstractmethod on __init__ guarantees that the class cannot be instantiated, only your specialization - super().__init__() guarantees that the instance have all required attributes - we are in the pizza namespace, Pizza sufix is redundant - Each pizza has its own characteristics - chicago style redefines cut to specialize when I ran mypy, I got a lot of errors, so I decided to create an invalid flavor pizza, respecting the pizza type interface. It's a Null object Pattern. Helps to avoid multiple ifs (including exceptions) when an item is not found. """ from abc import ABC, abstractmethod class Pizza(ABC): @abstractmethod def __init__(self): self.name: str = "" self.dough: str = "" self.sauce: str = "" self.toppings: list[str] = [] def prepare(self) -> None: print(f"Prepare {self.name}") print("Tossing dough...") print("Adding sauce...") print("Adding toppings:") for topping in self.toppings: print(f" {topping}") def get_name(self) -> str: return self.name def bake(self) -> None: print("Bake for 25 minutes at 350") def cut(self) -> None: print("Cut the pizza into diagonal slices") def box(self) -> None: print("Place pizza in official PizzaStore box") def __str__(self) -> str: joined_toppings = "\n".join(self.toppings) return ( f"---- {self.name} ----\n" f"{self.dough}\n" f"{self.sauce}\n" f"{joined_toppings}\n" ) class UnknownPizza(Pizza): def __init__(self): self.name = "unknown flavor" class NYStyleCheesePizza(Pizza): def __init__(self): super().__init__() self.name = "NY Style Sauce and Cheese Pizza" self.dough = "Thin Crust Dough" self.sauce = "Marinara Sauce" self.toppings.append("Grated Reggiano Cheese") class NYStyleVeggiePizza(Pizza): def __init__(self): super().__init__() self.name = "NY Style Veggie Pizza" self.dough = "Thin Crust Dough" self.sauce = "Marinara Sauce" self.toppings.append("Grated Reggiano Cheese") self.toppings.append("Garlic") self.toppings.append("Onion") self.toppings.append("Mushrooms") self.toppings.append("Red Pepper") class NYStyleClamPizza(Pizza): def __init__(self): super().__init__() self.name = "NY Style Clam Pizza" self.dough = "Thin Crust Dough" self.sauce = "Marinara Sauce" self.toppings.append("Grated Reggiano Cheese") self.toppings.append("Fresh Clams from Long Island Sound") class NYStylePepperoniPizza(Pizza): def __init__(self): super().__init__() self.name = "NY Style Pepperoni Pizza" self.dough = "Thin Crust Dough" self.sauce = "Marinara Sauce" self.toppings.append("Grated Reggiano Cheese") self.toppings.append("Sliced Pepperoni") self.toppings.append("Garlic") self.toppings.append("Onion") self.toppings.append("Mushrooms") self.toppings.append("Red Pepper") class ChicagoStyleCheesePizza(Pizza): def __init__(self): super().__init__() self.name = "Chicago Style Deep Dish Cheese Pizza" self.dough = "Extra Thick Crust Dough" self.sauce = "Plum Tomato Sauce" self.toppings.append("Shredded Mozzarella Cheese") def cut(self): print("Cutting the pizza into square slices") class ChicagoStyleVeggiePizza(Pizza): def __init__(self): super().__init__() self.name = "Chicago Deep Dish Veggie Pizza" self.dough = "Extra Thick Crust Dough" self.sauce = "Plum Tomato Sauce" self.toppings.append("Shredded Mozzarella Cheese") self.toppings.append("Black Olives") self.toppings.append("Spinach") self.toppings.append("Eggplant") def cut(self): print("Cutting the pizza into square slices") class ChicagoStyleClamPizza(Pizza): def __init__(self): super().__init__() self.name = "Chicago Style Clam Pizza" self.doough = "Extra Thick Crust Dough" self.sauce = "Plum Tomato Sauce" self.toppings.append("Shredded Mozzarella Cheese") self.toppings.append("Frozen Clams from Chesapeake Bay") def cut(self): print("Cutting the pizza into square slices") class ChicagoStylePepperoniPizza(Pizza): def __init__(self): super().__init__() self.name = "Chicago Style Pepperoni Pizza" self.dough = "Extra Thick Crust Dough" self.sauce = "Plum Tomato Sauce" self.toppings.append("Shredded Mozzarella Cheese") self.toppings.append("Black Olives") self.toppings.append("Spinach") self.toppings.append("Eggplant") self.toppings.append("Sliced Pepperoni") def cut(self): print("Cutting the pizza into square slices")
a17dd4fbd1a9aff6bfcf36ae58f25a6677c4a3bf
chenvega/COMP90055-COMPUTING-PROJECT-Estimating-Crowds-Based-on-Social-Media
/CODE/Data_Process/LR_Model/LR.py
1,371
3.640625
4
# Author : Weijia Chen # Student Number : 616213 # Supervisor : Prof. Richard Sinnott # Subject: COMP90055 COMPUTING PROJECT # Project Name : Estimating Crowds Based on Social Media # This program will generate corresponding linear regression equation based four football leagues. import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import datasets, linear_model # Function to get data def get_data(file_name): data = pd.read_csv(file_name) para_x = [] para_y = [] for popularity,capacity,tweetcount,attendance in zip(data['Popular'],data['Capacity'],data['Tweets'],data['Attendance']): para_x.append([float(popularity),float(capacity),float(tweetcount)]) para_y.append(float(attendance)) return para_x,para_y x, y = get_data("afl.csv") def linear_model_main(para_x,para_y,predict_value): # Create linear regression object lrModel = linear_model.LinearRegression() lrModel.fit(para_x, para_y) predictResult = lrModel.predict(predict_value) predictions = {} predictions['intercept'] = lrModel.intercept_ predictions['coefficient'] = lrModel.coef_ predictions['predicted_value'] = predictResult return predictions predictvalue = [26,80000,216] result = linear_model_main(x,y,predictvalue) print "Intercept value " , result['intercept'] print "coefficient" , result['coefficient'] print "Predicted value: ",result['predicted_value']
0553380bb4e7b824c24443470e99d973971f5296
farid67/jamAlgorithms
/counting_sheep.py
2,133
4
4
#!/usr/local/bin/python def as_digits(n): """ Function that convert an integer as a set of digit :param n: input integer """ l = [] s = str(n) size = len(s) for i in range(size): l.append(int(s[i])) return set(l) def is_betw_limits(n, large): if large : return n >= 0 and n <= pow(10,6) else : return n >= 0 and n <= 200 def sheep(n, large) : """ Function that return the last computed integer if available or return "INSOMNIA" if the ten digits are not found within the 100 loops :param n: input integer :param t: number of test cases to perform :param large: boolean to set the large dataset option if true 0 <= N <= 10^6 else 0 <= N <= 200 """ try: int(n) except: print (n+" is not an int or is not between limits") if not is_betw_limits(n, large): raise Exception("N not between limits") if n == 0: # 0 is the only one integer for which insomia is reached return "INSOMNIA" m = n final = set(range(10)) digit = as_digits(m) step = 0 while digit != final: step = step + 1 m = step*n digit = digit.union(as_digits(m)) return str(m) def counting_sheep(t, large): """ For each case T, call sheep(n) with n as user input :param t: number of test cases to perform :param large: boolean to set the large dataset option if true 0 <= N <= 10^6 else 0 <= N <= 200 """ try: int(t) except: print ("T is not an integer") if 1 > t or t > 100 : raise Exception("T is not between 1 and 100") for i in range (t): print ("Enter the wanted number :") n = input () sheeps = sheep(n, large) print (str(n) + " Case #" + str(i+1) + ": "+ sheeps) # Input : T : number of test cases # 1 <= T <= 100 if __name__ == "__main__": print ("Enter the number of test cases to perform : ") t = input() counting_sheep(t, True)
e0df31338b53e04b493a6b6dacce7875d56fb3da
angelamutava/Day_2
/word_count.py
379
4.21875
4
def word(argument): """ This is function that returns the count of words in a string """ string_list = argument.split() string_dict = {} for word in string_list: if word.isdigit(): word = int(word) if word in string_dict: string_dict[word] += 1 else: string_dict[word] = 1 return string_dict
91fdcd11545385b9880e2f992e43cf692ccefc3b
vanishh/python-tutorial
/data structure/01Note.py
1,823
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 7 23:50:39 2018 @author: Administrator """ # 第一讲 # 解决问题的效率,和数据的组织方式和空间的利用有关 #例3 写程序计算多项式在给定点x的值 #多项式:f(x) = a0 + a1*x + a2*x^2 + ... +an*x^n # param_list: 多项式系数,x 底数, n 几次幂 def f(param_list, x, n): if len(param_list)-1 != n: return result = param_list[0] for index in range(1, n+1): result += param_list[index] * (x ** index) return result list1 = [1, 2] print(f(list1, 2, 1)) #fx = a0 + a1x + a2x^2 + a3x^3 = a0 + x(a1 + a2x + a3x^2) = a0 + x(a1 + x(a2 + a3x)) #fx = 1 + 2*1 + 3*1 + 4*1 = 10 def f2(param_list, x, n): result = param_list[n] for index in range(n-1, 0, -1): result = param_list[index] + x * result result += param_list[0] return result param_list = [1,2,3,4,5] print(f2(param_list, 1, 4)) # 最大子序列和 # 给定N个整数的序列{A1,A2,A3...An},求函数 # f(i,j)=max{0, 求和Ak(i,j)}的最大值 # 从Ai到Aj连续的一段子列的和 # 方法1:穷举法O(n**3) def maxSubseqSum1(list1, n): maxSum = 0 for i in range(n): # i 是子列的左端位置 for j in range(i,n): # j 是子列的右端位置 thisSum = 0 # A[i]到A[j]的子列和 for k in range(i,j+1): thisSum += list1[k] if thisSum > maxSum: maxSum = thisSum return maxSum # 方法2:O(n**2) def maxSubseqSum2(list1, n): maxSum = 0 for i in range(n): thisSum = 0 for j in range(i,n): thisSum += list1[j] if thisSum > maxSum: maxSum = thisSum return maxSum # 方法三:分而治之 # 把大问题拆成小块,然后再合并结果
7cd5d4bb6e1c8cce4d5bdc0558dbccde96643f50
seymakara/CTCI
/01ArraysAndStrings/LCreverseVowelsOfaString.py
941
4.0625
4
# Write a function that takes a string as input and reverse only the vowels of a string. # Example 1: # Given s = "hello", return "holle". # Example 2: # Given s = "leetcode", return "leotcede". # Note: # The vowels does not include the letter "y". class Solution(object): def reverseVowels(self, s): vowel_list = ["a","e","i","o","u","A","E","I","O","U"] vowels = {} for i in vowel_list: vowels[i] = vowels.get(i, 0) + 1 s = list(s) p1, p2 = 0, len(s) - 1 while p1 < p2: if s[p1] in vowels and s[p2] in vowels: temp = s[p1] s[p1] = s[p2] s[p2] = temp p1 += 1 p2 -= 1 if s[p1] not in vowels: p1 += 1 if s[p2] not in vowels: p2 -= 1 return ''.join(s)
0bc4af03735d658c1d60edafc29e3a0999aab6b0
lexiaoyuan/PythonCrashCourse
/python_08_class/icecream.py
1,140
3.953125
4
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print("The name of the restaurant is " + self.restaurant_name.title()) print("The type of the restaurant is " + self.cuisine_type.title()) print("The number of the restaurant is " + str(self.number_served)) def open_restaurant(self): print("The " + self.restaurant_name.title() + "is open") def set_number_served(self, number_served): self.number_served = number_served def increment_number_served(self, number_served): self.number_served += number_served class IceCreamStand(Restaurant): def __init__(self, restaurant_name, cuisine_type): super().__init__(restaurant_name, cuisine_type) self.flavors = [] def show_icecreams(self): for i in self.flavors: print(i) icecream = IceCreamStand('冰淇淋', '冷饮') icecream.flavors = ['草莓', '西瓜', '芒果', '蜜桃'] icecream.show_icecreams()
8a5ff718951245fbe688ee59b72e73acfe5df33a
alvaroserrrano/codingInterviewQuestions
/sortingAndSearching/sort_colors.py
843
4.3125
4
""" Given an array with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not supposed to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] """ def sortColors(arr): small, eq, large = 0, 0, len(arr) - 1 while(eq <= large): if arr[eq] == 0: arr[small], arr[eq] = arr[eq], arr[small] small+=1 eq+=1 elif arr[eq] == 2: arr[eq], arr[large] = arr[large], arr[eq] large-=1 else: eq+=1 return arr arr = [2, 0, 2, 1, 1, 0] print(f' {arr} becomes {sortColors(arr)}')
f3191de85266c0e0f7a33d873684a75e428ec6c9
MuhammadH/DijAndGreedyChange
/Dij.py
4,298
3.875
4
import math class Graph: def __init__(self): self.root = None self.allPoints = [] class Point: def __init__(self, name): self.name = name self.connections = [] class Connection: def __init__(self, otherPoint, distance): self.otherPoint = otherPoint self.distance = distance def __repr__(self): return repr([self.otherPoint.name, self.distance]) class Visit: def __init__(self, prev, point, distance, currentCost): # distance here is this point's distance to the revious node # current cost is the complete path cost to this point from root self.prev = prev self.point = point self.distance = distance self.currentCost = currentCost def shortestPaths(workingGraph): # get a list of nodes unvisitedNodes = [] distances = [] for i in workingGraph.allPoints: unvisitedNodes.append(i) # make a list of all graph points and inf distances newCon = Connection(i, math.inf) distances.append(newCon) # make a queue visitNext = [] vn = Visit(None, workingGraph.root, 0, 0) visitNext.append(vn) curNode = visitNext[0] # traverse all points while len(visitNext) > 0: # pick the next node to visit distCheck = math.inf; for i in visitNext: if i.distance < distCheck: curNode = i distCheck = i.distance # update the current cost to get to the working node curCost = curNode.currentCost # check for lower connection costs for i in curNode.point.connections: nextDist = i.distance + curCost # get the point in distances objInDistances = None for d in distances: if d.otherPoint.name == i.otherPoint.name: objInDistances = d # show relaxation process if nextDist < objInDistances.distance: print("relaxed " + objInDistances.otherPoint.name) print("was " + str(objInDistances.distance) ) objInDistances.distance = nextDist print("is now " + str(objInDistances.distance) ) # if this point is in unvisited points, add to visitNext addThis = 0 for j in unvisitedNodes: if curNode.point.name == j.name: addThis = 1 if(addThis == 1): # add to nodes to visit newNode = Visit(curNode.point, i.otherPoint, i.distance, curCost + i.distance); visitNext.append(newNode) # remove current node from visitNext and unvisited nodes visitNext.remove(curNode) if curNode.point in unvisitedNodes: unvisitedNodes.remove(curNode.point) # make the root distance zero for aesthetic reasons for d in distances: if d.otherPoint.name == workingGraph.root.name: d.distance = 0; print(distances) # points A = Point("A") B = Point("B") C = Point("C") D = Point("D") E = Point("E") # make graph mainGraph = Graph() mainGraph.allPoints.append(A) mainGraph.allPoints.append(B) mainGraph.allPoints.append(C) mainGraph.allPoints.append(D) mainGraph.allPoints.append(E) mainGraph.root = A # A connections Con1 = Connection(B, 4) A.connections.append(Con1) Con2 = Connection(C, 2) A.connections.append(Con2) # B connections Con3 = Connection(C, 3) B.connections.append(Con3) Con4 = Connection(D, 2) B.connections.append(Con4) Con5 = Connection(E, 3) B.connections.append(Con5) # C connections Con6 = Connection(B, 1) C.connections.append(Con6) Con7 = Connection(D, 4) C.connections.append(Con7) Con8 = Connection(E, 5) C.connections.append(Con8) # D connections # none # E connections Con9 = Connection(D, 1) E.connections.append(Con9) # listing out the connections print ("List of connections: ") print ("A: ") print (A.connections) print ("B: ") print (B.connections) print ("C: ") print (C.connections) print ("D: ") print (D.connections) print ("E: ") print (E.connections) # finding the shortest path costs for the root print ("Finding shortest paths for root: ") shortestPaths(mainGraph)
8bea83b7520d347fa6af4c16c2d7f55f22593ca2
zhangcc22277/python11
/11-5/py02_meijulei.py
376
3.78125
4
#把Student的gender属性改造为枚举类型,可以避免使用字符串 from enum import Enum,unique class Gender(Enum): Male = 0 Female = 1 class Student(object): def __init__(self,name,gender): self.mame=name self.gender = gender #测试 bart = Student('zhangsan',Gender.Male) if bart.gender == Gender.Male print ('测试通过') else: print('测试失败')
51e68bce8fe8f695c4d2986532535476ea8f9edb
rhender007/python-ps
/leetCode/Map.py
467
3.828125
4
seq = [1, 2, 3, 4] # result contains odd numbers of the list result = filter(lambda x: x + 1, seq) print( list(result) ) # Does nothing on seq as the lambda function does not hold any condition # Output: [1, 2, 3, 4] # filter only works on condition, so we need to give some conditional statement with lambda result = filter(lambda x: x % 2 == 0, seq) # returns the elements which are only divisible by two print(list(result)) # output: [2, 4]
c38b5ec2bed1a537b65ced8883509a6ac4584455
guilhermedlroncato/python_coursera
/parte1/exercicios/semana_6/jogo_nim.py
2,355
4.03125
4
def main(): menu = 'Bem-vindo ao jogo do NIM! Escolha:\n1 - para jogar uma partida isolada\n2 - para jogar um campeonato ' escolha = int(input(menu)) if escolha != 1 and escolha != 2: print('Opção invalida!') main() else: if escolha == 1: print('\nVocê escolheu partida isolada!\n') partida() print('\nPlacar: Você 0 X 1 Computador') if escolha == 2: print('\nVocê escolheu campeonato!\n') print('**** Rodada 1 ****\n') partida() print('\n**** Rodada 2 ****\n') partida() print('\n**** Rodada 3 ****\n') partida() print('\nPlacar: Você 0 X 3 Computador') def usuario_escolhe_jogada(n,m): opcao = False while opcao != True: retira = int(input('\nQuantas peças você vai tirar? ')) if (retira <= n) and (retira <= m) and (retira > 0): opcao = True else: print('Oops! Jogada inválida! Tente de novo.') print(f'Voce tirou {retira} peças.\n') print(f'Agora resta apenas {n - retira} peça no tabuleiro.') return retira def computador_escolhe_jogada(n,m): multiplo = m + 1 valor_escolha = 0 x = 1 while x <= m: if (n - x) % multiplo == 0: valor_escolha = x x += 1 if valor_escolha <= n: retira = valor_escolha else: retira = n print(f'O computador tirou {retira} peça.') if (n - retira) == 0: print('Fim do jogo! O computador ganhou!') else: print(f'Agora resta apenas {n - retira} peça no tabuleiro.') return retira def partida(): n = int(input('Quantas peças? ')) m = int(input('Limite de peças por jogada? ')) prox_jogador = '' if n % (m + 1) == 0: print('\nVocê começa!\n') n = n - usuario_escolhe_jogada(n,m) prox_jogador = 'computador' else: print('\nComputador começa!\n') n = n - computador_escolhe_jogada(n,m) prox_jogador = 'voce' while n > 0: if prox_jogador == 'computador': n = n - computador_escolhe_jogada(n,m) prox_jogador = 'voce' else: n = n - usuario_escolhe_jogada(n,m) prox_jogador = 'computador' main()
c4417aea3cfb6969f6ec90aed813cc2639783ce0
kujin521/pythonObject
/第五章/列表/学生成绩排序.py
440
3.546875
4
score_list= [90, 80, 70, 98, 50, 75, 85, 95, 100] print('成绩列表',score_list) score_list.sort(reverse=True) print('成绩降序排序列表',score_list) score_list.sort(reverse=False) print('成绩升序排序列表',score_list) print('85分的排名是',score_list.index(85)+1) print('最高分',max(score_list),'最低分',min(score_list)) score_aver=sum(score_list)/len(score_list) print('平均分%.1f'%score_aver) del score_list
740bf733139a01e57bf27a7d108a4db37a45bd9a
Dvaraz/PythonPY200_1
/Атрибуты и методы/Домашнее задание/task4_Date_classmethod_staticmethod/main.py
1,627
3.984375
4
class Date: """Класс для работы с датами""" DAY_OF_MONTH = ( (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), # обычный год (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # високосный ) __slots__ = ('day', 'month', 'year') def __init__(self, day: int, month: int, year: int): self.day = day self.month = month self.year = year self.is_valid_date(self.day, self.month, self.year) @staticmethod def is_leap_year(year: int): """Проверяет, является ли год високосным""" if year % 4 != 0 or (year % 100 == 0 and year % 400 != 0): # print(f"{year} is not leap") return False else: # print(f"{year} is leap") return True @classmethod def get_max_day(cls, month: int, year: int): """Возвращает максимальное количество дней в месяце для указанного года""" if cls.is_leap_year(year): return cls.DAY_OF_MONTH[1][month - 1] else: return cls.DAY_OF_MONTH[0][month - 1] @staticmethod def is_valid_date(day: int, month: int, year: int): """Проверяет, является ли дата корректной""" if not isinstance(year, int) or not isinstance(month, int) or not isinstance(day, int): raise TypeError if __name__ == "__main__": date = Date(12, 7, 2001) print(date.get_max_day(2, 2021)) print(date.is_leap_year(2001)) pass
4faea636251de032bd4c17777ea80dfaca76cb91
bemagee/LearnPython
/Python Course CSe11309x/week6_string_functions_ex4.py
511
4.3125
4
#!/usr/bin/env python3 # Write a function which accepts an input string consisting of alphabetic characters and returns the string with all the spaces removed. # Do NOT use any string methods for this problem. def _remove_spaces_(string): out_string = "" for x in range(0, len(string)): if string[x] != " ": out_string = out_string + string[x] return out_string input_string = " Hello this is my string " output_string = _remove_spaces_(input_string) print (output_string)
89ca704b361116e117ad82130cc14691a0ac47a5
RedR1der/Key-MATH361B
/Number Theory/N1_Collatz_Key.py
905
4.15625
4
a0=int(input("What is the inital term in your sequence? ")) N=int(input("How many terms do you want in your sequence? ")) sequence=[a0] lengthlist=[] n=0 counter=0 flagVar=0 while len(sequence) != N: if sequence[n] % 2 == 0: sequence.append(sequence[n]/2) elif sequence[n] % 2 != 0: sequence.append(3*sequence[n]+1) n+=1 for number in sequence: if number != 1: lengthlist.append(number) counter+=1 elif number==1: flagVar=1 break if flagVar != 0: #PROGRAMMER'S NOTE: "step" referes NOT to the number of terms in the sequence up to 1, but rather the number of times it took to get from one number to another. print("It took %d steps to get to 1." % counter) else: print("Your sequence probably needs more terms to get to 1.") print("Here is the list for the collatz conjecture:") lengthlist.append(1) print(lengthlist)
541eb268f28085b6dd8d6d128dbf86389c73d527
RichardJ16/Cracking-The-Coding-Interview
/Chapter-1/Q1_8.py
817
3.796875
4
# Write an algorithm that finds a zero in an NxN matrix and writes the column and row as 0's as well def rotateMatrix(m1): arrayI = [] arrayJ = [] for i in range(len(m1)): for j in range(len(m1[0])): if m1[i][j] == 0: arrayI.append(i) arrayJ.append(j) for x in arrayI: for q,r in enumerate(m1): q = q - 1 m1[x][q] = 0 for y in arrayJ: for q,r in enumerate(m1): m1[q][y] = 0 return m1 m1 = [[1,0,1],[1,1,1],[1,1,0]] print("Matrix", m1) print("Zeros", rotateMatrix(m1)) m1 = [[0,0,0],[0,0,0],[0,0,0]] print("Matrix", m1) print("Zeros", rotateMatrix(m1)) m1 = [[1,1],[1,1],[0,1]] print("Matrix", m1) print("Zeros", rotateMatrix(m1))
cb6ffaf9f2f8b44132dbcaee559746b3f9cf285e
youjiahe/python
/python1/fun_for_99chengfa_v1.1.py
160
3.609375
4
#/usr/bin/env python3 end=9 for i in range(1,end+1): for j in range(1,i+1): print('{:<7}'.format('%d×%d=%d' % (j, i, i * j)), end='') print('')
533bd23aaa11f5156df7847437ce9dde77071682
lllana/Udacity_Python
/Lesson4/Lesson_004_2.py
210
3.5
4
# egg_count = 0 # # def buy_eggs(): # egg_count += 12 # purchase a dozen eggs # # buy_eggs() egg_count = 0 def buy_eggs(count): return count + 12 # purchase a dozen eggs buy_eggs = lambda x: x + 12
99f591b44e24ff17f10b342574ecc6c76d7246ed
alejandrobrusco/interprete-python
/Compilador/tests/test_diccionario_clave_inexistente.py
233
3.640625
4
print "\nError de diccionario:\n" d = {"Clave1": 1, 'Clave2': 2, 3: "valor de clave entera 3", True : 1, False:0 , "Valor de flotante": 123.8345, 45.78 : "valor con clave floatante"} variable = d["clave que no esta"] print variable
519fabb58ee6d010fdfdcdd2fc8b0674715d2781
letitgone/python-in-action
/list/python_list.py
984
3.890625
4
# @Author ZhangGJ # @Date 2021/01/27 23:24 lists = ['test0', 'test1', 'test2', 'test3', 'test4', 'test5'] print(f"访问索引位置元素:{lists[3]}") print(f"访问倒数第一个元素:{lists[-1]}") print(f"访问倒数第二个元素:{lists[-2]}") lists.append('test6') print(f"list末尾添加元素:{lists}") lists.insert(3, 'insert') print(f"固定索引位置添加:{lists}") del lists[3] print(f"删除固定索引位置元素:{lists}") pop = lists.pop() print(f"lists:{lists}") print(f"弹出list末尾元素,并赋值给pop:{pop}") pop = lists.pop(5) print(f"lists:{lists}") print(f"弹出固定索引位置元素,并赋值给pop:{pop}") # remove只删除第一个指定的值 lists.remove('test4') print(f"删除给定元素值的元素:{lists}") print('===========================================================================================') cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(f"sort()永久修改列表元素顺序:{cars}")
47094801741c697d9116a49fdd761786da09acc9
aparnasindhu999/100-days-of-coding
/sum_of_digits.py
104
3.734375
4
n=int(input("Enter number")) sum=0 while n!=0: rem=n%10 sum+=rem n//=10 print(sum)
52d86f1aa386d2fef2bbff164d072cbe33523ef4
sgouda0412/Data-Structures-Algorithms-I
/BinaryHeaps.py
3,750
3.9375
4
#In a MaxBinaryHeap, parent nodes are always larger than child nodes. #In a MinBinaryHeap, parent nodes are always smaller than child nodes #But there are no guarantees between sibling nodes #Binary heaps are used to implement Priority Queues, which #are very commonly used data structures #To find child from parent: Left Child is (2n + 1) and Right Child is (2n + 2) #And to find parent: (n - 1)/2 floored - to find Parent from Child #Aforementioned stuff is done to indices of nodes not the values of nodes #BinaryHeaps #Insertion O(log n) Even with worst case it will be O(log n) while Binary Tree can be O(n) #Removal O(log n) #Search O(n) For searching BinaryTree is much better #for 16 elements 4 comparisions from math import floor class MaxBinaryHeap: def __init__(self): self.values = [] #mine def insert(self,val): self.values.append(val) index = len(self.values) - 1 parentindex = floor((index - 1)/2) while index > 0: if self.values[index] > self.values[parentindex]: self.values[index], self.values[parentindex] = self.values[parentindex], self.values[index] index = parentindex parentindex = floor((index - 1)/2) else: break #with varibale self.heap.append(val) ind = len(self.heap) - 1 element = self.heap[ind] while ind > 0: parentInd = floor((ind - 1)/2) if element > self.heap[parentInd]: self.heap[ind] = self.heap[parentInd] self.heap[parentInd] = element ind = parentInd element = self.heap[ind] else: break print(self.heap) def remove(self): max_ = self.values[0] end = self.values.pop() if len(self.values) > 0: self.values[0] = end self.sinkDown() print(self.values) return max_ def sinkDown(self): idx = 0 length = len(self.values) element = self.values[0] #we swapped the child and element, #but the variable 'first' [element] will keep the value for further possible swaps\ #And it's index position is kept in idx while True: leftIdx = 2 * idx + 1 rightIdx = 2 * idx + 2 swap = None if leftIdx < length: leftChild = self.values[leftIdx] if leftChild > element: swap = leftIdx if rightIdx < length: rightChild = self.values[rightIdx] if (swap == None and rightChild > element) or (swap != None and rightChild > leftChild): swap = rightIdx if swap == None: break self.values[idx] = self.values[swap] self.values[swap] = element idx = swap #Colt's solution # def insert(self,var): # self.values.append(var) # self.bubbleUp() # def bubbleUp(self): # index = (len(self.values) - 1) # while index > 0: # parentInd = floor((index - 1)/2) # if self.values[parentInd] >= self.values[index]: # break # self.values[parentInd], self.values[index] = self.values[index], self.values[parentInd] # index = parentInd def remove(self): node = self.values.pop() end = self.values[0] if len(self.values) > 0: self.values[0] = node self.bubbleValue() return end def bubbleValue(self): idx = 0 element = self.values[0] length = len(self.values) while True: leftIdx = 2 * idx + 1 rightIdx = 2 * idx + 2 swap = None if leftIdx < length: leftChild = self.values[leftIdx] if leftChild > element: swap = leftIdx if rightIdx < length: rightChild = self.values[rightIdx] if (rightChild > element and swap == None) or (rightChild > leftChild and swap != None): swap = rightIdx if swap == None: break self.values[idx] = self.values[swap] self.values[swap] = element idx = swap heap = MaxBinaryHeap() heap.insert(41) heap.insert(39) heap.insert(33) heap.insert(18) heap.insert(27) heap.insert(12) heap.insert(55) heap.remove()
c5fc98a2dac67949513980f19d0a2602fb11154d
baah-romero/aprende-python
/ejercicios/4-estr-repet/cnt1.py
362
3.828125
4
#Contador de Si i = 0 a = input('Introducir S o s para seguir, N o n para cortar: ') while a == 'S' or a == 's' :#Comprobar que el valor sea Si o si i += 1 #Al ser si, incrementar el contador en 1 a = input('Introducir S o s para seguir, N o n para cortar: ') print('\n-------RESULTADO--------') print('Se han introducido ', i ,' valores S o s')
6c71ec87f5583fe5482546c9637f28269380bb5b
durgaprsd04/code_learn
/Practice/Python/DP/goldMine.py
314
3.578125
4
import os def gold_mine(array, n, m): max1=0; l=[] for j in range(n-2,-1,-1): for i in range(1, m-1): max1 = max(max(array[i+1][j+1], array[i][j+1]), max(max1, array[i-1][j+1])) l.append(max1) return l l1 =[[1,3,3],[2,1,4],[0,6,4]] v = gold_mine(l1, 3,3) print v
2fd2191e81dcb8a4a09a787d10b7b19562484b5c
filipeazevedoSolo/LearningPython
/string_02.py
703
3.796875
4
S = 'spammy' S = S[:3] + 'xx' + S[5:] #'spa' + 'xx' + 'y' print(S) S = 'spammy' S = S.replace('mm', 'xx') print(S) S = 'xxxxSPAMxxxxSPAMxxx' pos = S.find('SPAM') #retorna primeira posicao da primeira vez que aparece 'SPAM' S = S[:pos] + 'EGGS' + S[(pos+4):] print(S) S = 'xxxxSPAMxxxxSPAMxxx' S = S.replace('SPAM', 'EGGS') #troca todos os 'SPAM' por 'EGGS' print(S) S = 'xxxxSPAMxxxxSPAMxxx' S = S.replace('SPAM', 'EGGS', 1) #troca apenas um print(S) L = ['s','p','a'] S = ''.join(L) #junta os elementos todos a lista com '' entre cada print(S) line = "The knights who say Ni!\n" print(line.rstrip()) print(line.endswith('Ni!\n'))
a52d686ed8f896eb935d46c29e623838f6a24c84
saiprasadvk/pythonprogram
/oops/Accessing the functions and values.py
354
3.765625
4
class test(): "Hello this is for doc statment" b = 30 def fun(): "This is defining the function" print("Hai") ##before assign the the object print(test.b) test.fun() #After assign the the object obj = test print(obj.__doc__) print(obj.b) obj.fun() O/P: 30 Hai Hello this is for doc statment 30 Hai