blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9d3cacac13b4a1e3e8b6c7d113c88e330dd2719e
ForgottenK/python_work
/fourth_chapter/pizza.py
675
4.40625
4
pizzas = ['pepperoni', 'hawaiian', 'cheese', 'seafood', 'meat', 'vegetable'] for pizza in pizzas: print('I like ' + pizza + ' pizza') print('I really love pizza!') print('The first three items in the list are:') for pizza in pizzas[:3]: print(pizza) print('The items from the middle of the list are:') for pizza in pizzas[2:5]: print(pizza) print('The last three items in the list are:') for pizza in pizzas[-3:]: print(pizza) friend_pizzas = pizzas[:] pizzas.append('beaf') friend_pizzas.append('korean pickles') print('\nMy favorite pizzas are:') for pizza in pizzas: print(pizza) print("\nMy friend's favorite pizzas are:") for pizza in friend_pizzas: print(pizza)
a6294fb0c2530e3b209226db852c53d2a2d7542e
brad-h/expy
/ExPy/ExPy/module36.py
2,003
4.34375
4
""" Computing Statistic """ from math import sqrt def mean(numbers): """Find the mean using an iterable of numbers Return None if the iterable is empty """ if not numbers: return None total = 0 count = 0 for number in numbers: total += number count += 1 return total / count def maximum(numbers): """Find the max using an iterable of numbers Return None if the iterable is empty """ if not numbers: return None max_number = numbers[0] for number in numbers: max_number = number if number > max_number else max_number return max_number def minimum(numbers): """Find the min using an iterable of numbers Return None if the iterable is empty """ if not numbers: return None min_number = numbers[0] for number in numbers: min_number = number if number < min_number else min_number return min_number def standard_deviation(numbers): """Find the std dev using an iterable of numbers Return None if the iterable is empty """ if not numbers: return None average = mean(numbers) squared_values = [(n - average) ** 2 for n in numbers] return sqrt(mean(squared_values)) def ex36(): """Prompt for numbers until the user types 'done' then print some statistics about those numbers """ numbers = [] while True: try: number = input('Enter a number: ') number = int(number) numbers.append(number) except ValueError: if number == 'done': break print('Enter a number or type "done"') print('Numbers: ' + ', '.join(map(str, numbers))) print('The average is {}.'.format(mean(numbers))) print('The minimum is {}'.format(minimum(numbers))) print('The maximium is {}.'.format(maximum(numbers))) print('The standard deviation is {}'.format(standard_deviation(numbers))) if __name__ == '__main__': ex36()
5e1d39dfa0d3d7ae0947aa0cc59eaa8a2126f32e
sendurr/spring-grading
/submission - Homework3/set2/DANIEL M HARPER_11090_assignsubmission_file_homework3/homework3/P5b.py
1,290
4.125
4
# Author: Daniel Harper # Assignment: Homework 3 - P5b.py # Original Date: 2/23/2016 # Last Updated: 2/23/2016 # Written using Python 3.4.3.7 # All rights reserved ##################################################################### # Importation Section################################################ #from math import * #import random #import sys import argparse # Body Section####################################################### #-------------------------------------------------------------------- # Consider the simplest program for evaluating the formula # y(t) = v0t-0.5gt^2 : # v0 = 3; g = 9.81; t = 0.6 # y = v0*t - 0.5*g*t**2 # print y # # write a program to work from the command line with the following # command: python p5b.py -v 5 -t 0.8 # which will assign 5 to v0 and 0.8 to t (use argparse module) parser = argparse.ArgumentParser() parser.add_argument('-g', action='store', dest='g',default=9.81, help='gravity value') parser.add_argument('-v', action='store', dest='v',default=0, help='initial velocity value') parser.add_argument('-t', action='store', dest='t',default=0, help='time value') parser.add_argument('--version', action='version', version='%(prog)s 1.0') args = parser.parse_args() g = 9.81 v = eval(args.v) t = eval(args.t) y = v*t - 0.5*g*t**2 print(y)
f2506872f005e8ce10c79c224b847a089d115c2e
tompsherman/cspt19long
/department.py
387
3.59375
4
class department: def __init__(self, name, products): self.name = name self.products = products def __str__(self): output = f"{self.name}\n" if len(self.products) > 0: for product in self.products: output += f"\t{product}\n" else: output += f"there are no products in here" return output
d6ed65465de73d51dde6d2fd1c72ca1e54c57cc1
Esaaj/Competitive_programming_codes
/CodeForces/CodeForces_Fake_News.py
327
3.828125
4
input_list=list(input()) flag=0 for a in input_list: if(a=='h' and flag==0): flag=1 elif(a=='e' and flag==1): flag=2 elif(a=='i' and flag==2): flag=3 elif(a=='d' and flag==3): flag=4 elif(a=='i' and flag==4): flag=5 if(flag==5): print("YES") else: print("NO")
4198fea560865e0c6776d1ee6414f7ccbae51587
margaretlclark3/Python
/infiniteloop_input_continue_break.py
451
4.21875
4
#create an infinite loop that takes input from user. If name is in ACCEPTED_NAMES, print name. Otherwise prompt to enter valid name. If user chooses to exit, print See Ya! ACCEPTED_NAMES = ['bob', 'larry', 'george', 'anna'] def check_name(): while True: name = input("Please enter a name or exit: ").lower() if name == 'exit': print('See Ya!') break if name not in ACCEPTED_NAMES: print('Enter valid name.') continue print(name)
0481eab7d22ffea1baa254407b02aba50b05eef8
cah835/Intro-to-Programming-1284
/Classwork Programs/cookierecipe.py
293
3.8125
4
c = float(input('How many cookies would you like to make? ')) s = c * .03215 b = c * .0208 f = c * .0573 sugar = ('Cups of sugar = ' + format(s, '.2f')) butter = ('Cups of butter = '+ format(b, '.2f')) flower = ('Cups of flower = ' + format(f, '.2f')) print(sugar) print(butter) print(flower)
ca59cd7d30b3c739229e4a61823f9e73d7e57def
Aliriss/PYTHON
/graphwins.py
1,248
4.25
4
from graphics import * def main(): # Introduction print('This program plots the growth of a 10-year investment.') #Get principal and interest rate principal = float(input('Enter the initial principal:')) apr = float(input ('Enter the annualized interest rate:')) #Craet a graphics window with labels on left edge win = GraphWin('Investment Growth Chart',320,240) win.setBackground('white') Text(Point(20,230),'0.0K').draw(win) Text(Point(20,180),'2.5K').draw(win) Text(Point(20,130),'5.0K').draw(win) Text(Point(20,80),'7.5K').draw(win) Text(Point(20,30),'10.0K').draw(win) #Draw bar for initial principal height = principal * 0.02 bar = Rectangle(Point(40,230),Point(65,230-height)) bar.setFill('green') bar.setWidth(2) bar.draw(win) #Draw bars for successive years for year in range(1,11): #Calculate value for the next year principal = principal*(1+apr) #Draw bar for this value x11=year*25+40 height=principal*0.02 bar = Rectangle(Point(x11,230),Point(x11+25,230-height)) bar.setFill('green') bar.setWidth(2) bar.draw(win) input('Press <Enter> to quit') win.close() main()
a6cc4805b7ed3a5ecfb45aea2c3bb2e6b09837bf
ichisadashioko/learning_repo
/opencv/02_core-operations/basic-operations/access_modify.py
685
3.734375
4
import cv2 import numpy as np img = cv2.imread('shiroha.png') px = img[100,100] print px # accessing only blue pixel blue = img[100,100,0] print blue # modify the pixel values img[0,0] = [0,0,0] ''' Warning: Numpy as a optimized library for fast array calculations. So simply accessing each and every pixel values and modifying it will be very slow and it is discouraged. ''' # better pixel accessing and editing method # accessing RED value red = img.item(10,10,2) print red # modifying RED value img.itemset((10,10,2),100) print img.item(10,10,2) img = cv2.resize(img,None,fx=3,fy=3,interpolation=cv2.INTER_CUBIC) cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows()
78bbd8f9efb7a6d9add6c5eae9119b8763a59050
junaid238/class_files
/python files/demo.py
311
4.09375
4
# a = 10 #class int # b = 3 #class float # print(a%b) # print(type(a)) # print(type(b)) # print(a+b) #120.5 # print(a-b) #79.5 # print(a*b )#2050.0 # print(a/b )#5.4 # print(a//b )#5.0 # print(a%b)# # print(a**b)# a power b x = 100 y = 200 z = 100 print(x>y) print(y>z) print(x==z) print(x!=y) # not equals
27e44c45c672fffde61592b95ba6b8272f44326e
sirakfilho/projetopython
/ProjetoAlinne.py
3,407
4.09375
4
def UsuarioComum(): e = 0 while e <= 0: print("entrou no academico: ") print(" \n\n------------------ Menu ---------------") print(" 1 - Cadastrar no Sistema ") print(" 2 - Logar no Sistema") print(" 3 - Confirmar ou Negar presença em uma reunião") print(" 4 - Visualizar as reuniões em que foi confirmada sua presença") print(" 5 - Visualizar atas de reuniões") print(" 6 - Criar uma reunião") print(" 7 - baixar atas de reuniões que perticipou") print(" 8 - Sair do programa\n") b = input("Digite o numero: ") if b == "1": print("entrou em cadastrar sistema") elif b == "2": print("entrou em logar no sistema") elif b == "3": print("confirmar ou cancelar presenca em uma reunião") elif b == "4": print("visualizar as reuniões que participou") elif b == "5": print("Visualizar atas de reuniões") elif b == "6": print("criar um reunião") elif b == "7": print("baixar atas de reuniões que participou") elif b == "8": break e = e - 1 def Coordenador(): e = 0 while e <= 0: print("entrou no adminitrativo: ") print(" \n\n------------------ Menu ---------------") print(" 1 - Logar no Sistema ") print(" 2 - Visualizar as reuniões em que foi confirmada sua presença ") print(" 3 - Confirmar ou Negar presença em uma reunião ") print(" 4 - Criar reuniões ") print(" 5 - Editar todas as atas ") print(" 6 - Realocar Reuniões de sala ") print(" 7 - Adicionar participantes na lista de reuniões ") print(" 8 - Sair do programa\n ") i = input("digite um número: ") if i == "1": print("logar no sistema") elif i == "2": print("Visualizar as reuniões em que foi confirmada sua presença") elif i == "3": print("confirmar ou cancelar presença em uma reunião") elif i == "4": print("criar reuniões") elif i == "5": print("editar todas as atas") elif i == "6": print("realocar reuniões de sala") elif i == "7": print("adicionar participantes na lista de reuniões") elif i == "8": break i = i - 1 def GestorRecurso(): g = 0 while g <= 0: print(" \n\n------------------ Menu ---------------") print(" 1 - Logar no Sistema ") print(" 2 - Confirmar local de reuniões ") print(" 3 - Cadastrar novos espaços de reunião ") print(" 4 - Sair do programa\n") g = input("digite um número") if g == "1": print("logar no sistema") elif g == "2": print("confirmar local de reuniões") elif g == "3": print("cadastras novos espaços de reuniões") elif g == "4": break g = g - 1 def main(): i = 0 while i <= 0: a = input('Digite os valores 1 ou 2 : ') if a == "1": UsuarioComum() elif a == "2": print("entrou no administrativo") elif a == "0": break else: print("Erro") i = i - 1 main()
61ff35e40920d5c82599ac1f27b207bb474f04c1
tuxi/video-hub
/extra_apps/DjangoUeditor/utils.py
3,751
3.6875
4
# coding: utf-8 # 文件大小类 class FileSize(): SIZE_UNIT = { "Byte": 1, "KB": 1024, "MB": 1048576, "GB": 1073741824, "TB": 1099511627776 } def __init__(self, size): self._size = FileSize.Format(size) @staticmethod def Format(size): import re size_Byte = 0 if isinstance(size, int): size_Byte = size elif isinstance(size, str): oSize = size.lstrip().upper().replace(" ", "") # 增加检查是否是全数字类型的字符串,添加默认的单位Byte if oSize.isdigit(): size_Byte = int(oSize) pattern = re.compile( r"(\d*\.?(?=\d)\d*)(byte|kb|mb|gb|tb)", re.I) match = pattern.match(oSize) if match: m_size, m_unit = match.groups() if m_size.find(".") == -1: m_size = int(m_size) else: m_size = float(m_size) size_Byte = m_size * FileSize.SIZE_UNIT[m_unit] return size_Byte # 返回字节为单位的值 @property def size(self): return self._size @size.setter def size(self, newsize): self._size = FileSize(newsize) # 返回带单位的自动值 @property def FriendValue(self): if self.size < FileSize.SIZE_UNIT["KB"]: unit = "Byte" elif self.size < FileSize.SIZE_UNIT["MB"]: unit = "KB" elif self.size < FileSize.SIZE_UNIT["GB"]: unit = "MB" elif self.size < FileSize.SIZE_UNIT["TB"]: unit = "GB" else: unit = "TB" print(unit) if (self.size % FileSize.SIZE_UNIT[unit]) == 0: return "%s%s" % ((self.size / FileSize.SIZE_UNIT[unit]), unit) else: return "%0.2f%s" % ( round(float(self.size) / float(FileSize.SIZE_UNIT[unit]), 2), unit) def __str__(self): return self.FriendValue # 相加 def __add__(self, other): if isinstance(other, FileSize): return FileSize(other.size + self.size) else: return FileSize(FileSize(other).size + self.size) def __sub__(self, other): if isinstance(other, FileSize): return FileSize(self.size - other.size) else: return FileSize(self.size - FileSize(other).size) def __gt__(self, other): if isinstance(other, FileSize): if self.size > other.size: return True else: return False else: if self.size > FileSize(other).size: return True else: return False def __lt__(self, other): if isinstance(other, FileSize): if other.size > self.size: return True else: return False else: if FileSize(other).size > self.size: return True else: return False def __ge__(self, other): if isinstance(other, FileSize): if self.size >= other.size: return True else: return False else: if self.size >= FileSize(other).size: return True else: return False def __le__(self, other): if isinstance(other, FileSize): if other.size >= self.size: return True else: return False else: if FileSize(other).size >= self.size: return True else: return False
a4d62113a606f1e6904c9e855cab440f40530622
Sri-Vadlamani/Problems-Vs-Algorithms
/Problem_6.py
669
4.09375
4
def get_min_max(ints): """Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if not ints: return max = ints[0] min = ints[0] for i in ints: if i > max: max = i if i < min: min = i return (min, max) ## Example Test Case of Ten Integers import random l = [int(i) for i in range(0, 10)] # a list containing 0 - 9 random.shuffle(l) print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail") #pass print ("Pass" if ((0, 0) == get_min_max([0])) else "Fail") #pass print ("Pass" if (None == get_min_max([])) else "Fail") #pass
400ad2904d759bc41a443aa811a87dd4c1a9cb5c
sunnysunny061/python-programs
/leap_year.py
310
3.984375
4
def leap_year(x): if (x%4==0): if(x%100==0): if(x%400==0): print('yes leap year') else: print('not a leap year') else: print('leap year') else: print('not a leap year') x=int(input()) leap_year(x)
edc06db14c7d42569a4446f679c840a488a8b52a
DanilWH/Python
/python_learning/chapter_09/m_homework_library_python.py
1,746
3.859375
4
from collections import OrderedDict golossariy = OrderedDict() golossariy['concatenation'] = 'line break' golossariy['variable'] = 'place of memory' golossariy['list'] = 'itemset' golossariy['if'] = 'condition' golossariy['tuples'] = 'an immutable list' golossariy['dictionary'] = 'the creation of real objects' golossariy['"keys()"'] = 'if you are only interested in the keys pars' golossariy['"value()"'] = 'if you are only interested in the values pars' golossariy['"items()"'] = 'display vocabularies in a list' golossariy['"sorted()"'] = 'sort lists, tuples, dictionaries, and more' for word, definition in golossariy.items(): print(word.title() + ":\n\t" + definition + ".") # Упражнение 9-13(переделанное 6-4). from random import randint class Die(): def __init__(self, sides=6): """Инициализирует атрибуты для сторон куба""" self.sides = sides def roll_die(self): """Выводит наугад любое число от 1 до сторон куба""" number = randint(1, self.sides) return number sides = Die() cube_6 = [] for roll in range(10): cube_6.append(sides.roll_die()) print("\n10 rolls:") print(cube_6) # cube_10 = Die(10) cube_witch_10 = [] for roll in range(10): cube_witch_10.append(cube_10.roll_die()) print("\n10 rolls:") print(cube_witch_10) # Моделирования 10-гранного куба с 10 бросками. cube_20 = Die(20) cube_witch_20 = [] for roll in range(10): cube_witch_20.append(cube_20.roll_die()) print("\n10 rolls:") print(cube_witch_20) # Моделирование 20-гранного куба с 10 бросками. # Упражнение 9-14.
917c34497b54c596c01e95468355290254e3956b
SaloniSaini02/Challenge
/challenge1/Flask-App.py
1,692
3.59375
4
#import packages from flask import Flask from flask import * import pandas as pd # Create Flask App app = Flask(__name__) # Create url routes @app.route("/Titanic") def function1(): """ Method reads the titanic dataset to a dataframe.The first half is stored in the first output(csv) file. The columns in the second half are reversed and stored in the second output file. Returns: Template to be displayed in user's browser. """ titanic_df = pd.read_csv('train.csv') first_df = titanic_df.iloc[:445,:] # Reverse the second half of the dataset second_df = titanic_df.iloc[445:,::-1] # Store the data in two files first_df.to_csv('titanic_output1.csv') second_df.to_csv('titanic_output2.csv') return render_template('view.html',tables=[first_df.head(15).to_html(classes='normal'), second_df.head(15).to_html(classes='reversed')], titles = ['na', 'Output1', 'Output2']) @app.route("/API/<string:apikey>") def function2(apikey): """ Method reads in data using an API call. The dataframe is stored in an excel file as output. Parameters: arg1(int): Takes the api key as an argument. Returns: Template to be displayed in user's browser. """ url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey='+apikey+'&datatype=csv' time_series_df = pd.read_csv(url) time_series_df.head() time_series_df.to_excel("output.xlsx") return render_template('view2.html',tables=[time_series_df.head(15).to_html(classes='time_series')], titles = ['na', 'Time_Series']) if __name__ == "__main__": app.run(debug=True)
953ed440d979b8d630b868bcbd004315bb14e26e
merrittd42/HackerRankCode
/PythonTut/Intro/ex6.py
65
3.609375
4
N = int(input()) x = 0 while(x<N): print(x*x) x = x + 1
8861eb718457af2881c8ca20632bfffcbf679512
jmast02/PythonCrashCourse
/restaurant.py
863
3.78125
4
class Restaurants(): def __init__(self, restaurant_name, cuisine_type): # initialize restaurant and cuisine attributes self.restaurant = restaurant_name self.cuisine = cuisine_type def describe_restaurant(self): print(f"{self.restaurant.title()} serves {self.cuisine.title()} food.") def open_restuarant(self): print(f"{self.restaurant.title()} is open!") #creating an instance my_restaurant my_restaurant = Restaurants('Tijuana taxi co.', 'mexican') my_restaurant.describe_restaurant() my_restaurant.open_restuarant() print('\n') #create a new instance for joes restaurant joes_restaurant = Restaurants('olive garden', 'italian') joes_restaurant.describe_restaurant() #one more instance for fun print('\n') steves_restaurant = Restaurants('Benihana', 'japanese') steves_restaurant.describe_restaurant()
dbf890ce9deadadc29112cd46e24c6bb54af0922
Venkataraman-Nagarajan/DAA-
/EX4/Inversions_v1.py
661
3.671875
4
def inversion_count(a): count=0 for i in range(len(a)-1): for j in range(i,len(a)): if(a[i]>a[j]): count+=1 return count print("Enter the array elements : ",end="") a=[int(x) for x in input().split()] print() print(a,end=" ") print(" :",end="") print(inversion_count(a)) """ venky@venky-Inspiron-5570:~/DAA/EX4$ python3 Inversions_v1.py Enter the array elements : 1 2 3 4 5 [1, 2, 3, 4, 5] :0 venky@venky-Inspiron-5570:~/DAA/EX4$ python3 Inversions_v1.py Enter the array elements : 5 4 3 2 1 [5, 4, 3, 2, 1] :10 venky@venky-Inspiron-5570:~/DAA/EX4$ python3 Inversions_v1.py Enter the array elements : 3 1 2 5 4 [3, 1, 2, 5, 4] :3 """
44213bafe081b69d879a3208cccc5278e291a650
LeqitSebi/sew4_sem1_python
/ue01_Bruch/Fraction.py
5,175
3.984375
4
# @author Sebastian Slanitsch, 4CN from functools import total_ordering @total_ordering class Fraction: """ >>> Fraction.gcd(17, 21) 1 >>> Fraction.gcd(21, 7) 7 >>> Fraction.gcd(-1, 1) 1 >>> f1 = Fraction(1, 2) >>> f1 # __repr__ Fraction(1, 2) >>> print(f1) # __str__ 1/2 >>> f2 = Fraction(1, 4) >>> print(f2) 1/4 >>> f1 + f2 Fraction(3, 4) >>> Fraction() Fraction(0, 1) >>> Fraction(1) Fraction(1, 1) >>> print(3 + 1 / (7 + Fraction(1, 15))) 3 15/106 >>> Fraction.from_float(0.125) Fraction(1, 8) >>> Fraction.from_float(0.1) Fraction(1, 10) >>> Fraction.from_float(0.333333333333) Fraction(1, 3) >>> Fraction(1, 2) > Fraction(1, 3) True >>> Fraction(1, 2) < 1 True """ def __init__(self, numerator: int = 0, denominator: int = 1): if denominator == 0: raise ArithmeticError("denominator may not be 0") neg = (numerator < 0 <= denominator) or (denominator < 0 <= numerator) self._numerator = int(abs(numerator) * (-1 if neg else 1)) self._denominator = int(abs(denominator)) self.cancel() @staticmethod def from_float(num: float): numerator = num denominator = 1 while abs(numerator % 1) > 2 ** -8: numerator *= 1.0625 denominator *= 1.0625 return Fraction(int(numerator), int(denominator)) @staticmethod def gcd(a: int, b: int): if a == 0: return abs(b) elif b == 0: return abs(a) while True: h = a % b a, b = b, h if b == 0: break return abs(a) @property def numerator(self): return self._numerator @property def denominator(self): return self._denominator def cancel(self): gcd = Fraction.gcd(self.numerator, self.denominator) self._numerator //= gcd self._denominator //= gcd def __str__(self): full = self.numerator // self.denominator if self.numerator % self.denominator == 0: return str(full) string = "" if full != 0: string = str(full) + " " return string + str(self.numerator % self.denominator) + "/" + str(self.denominator) def __repr__(self): return "Fraction(" + str(self.numerator) + ", " + str(self.denominator) + ")" def __add__(self, other): if isinstance(other, Fraction): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) elif isinstance(other, int): return Fraction(self.numerator + other * self.denominator, self.denominator) else: raise ValueError def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Fraction): return Fraction(self.numerator * other.denominator - other.numerator * self.denominator, self.denominator * other.denominator) elif isinstance(other, int): return Fraction(self.numerator - other * self.denominator, self.denominator) else: raise ValueError def __rsub__(self, other): return self - other def __truediv__(self, other): if isinstance(other, Fraction): return Fraction(self.numerator * other.denominator, self.denominator * other.numerator) elif isinstance(other, int): return Fraction(self.numerator, self.denominator * other) else: raise ValueError def __rtruediv__(self, other): return Fraction(other) / self def __mul__(self, other): if isinstance(other, Fraction): return Fraction(self.numerator * other.numerator, self.denominator * other.denominator) elif isinstance(other, int): return Fraction(self.numerator * other, self.denominator) else: raise ValueError def __rmul__(self, other): return self * other def __float__(self): return self.numerator / self.denominator def __int__(self): return self.numerator // self.denominator def __eq__(self, other): if isinstance(other, Fraction): return self.numerator == other.numerator and self.denominator == other.denominator elif isinstance(other, int): return self.denominator == 1 and self.numerator == other else: return False def __gt__(self, other): if isinstance(other, Fraction): return self.numerator * other.denominator > other.numerator * self.denominator elif isinstance(other, int): return self.numerator > other * self.denominator else: return False def __neg__(self): return Fraction(-self.numerator, self.denominator) def __abs__(self): return Fraction(abs(self.numerator), abs(self.denominator)) def __copy__(self): return Fraction(self.numerator, self.denominator)
a96d052bd515abb8cd270034147dab8246e349dd
DanGBat/mancDictionary
/mancDictionary.py
3,725
3.96875
4
dictionary = { "Ave it": "Exclamation", "Bobbins": "Nonsense", "Brew": "Tea", "Butty": "Sandwich", "Buzzin": "Excited / Extreme Happiness", "Cadge": "Freeload / Scrounge / Get Something Free", "Chuddy": "Chewing Gum", "Chuffed": "Happy", "Do One": "Go Away", "Duds": "Underwear / Boxers", "Easy": "Hello", "Fit": "Tasty / Attractive", "Gaggin": "Thirsty", "Give Over": "Stop It / Expression of Disbelief", "Keks": "Trousers", "Knackered": "Tired / Exhausted", "Legless": "Extremely Drunk", "Mardy": "Moody / Surly / Moaning", "Mingin": "Horrible / Revolting", "Mint": "Great, Fantastic", "Mooch": "Wander Around Aimlessly", "Nowt": "Nothing", "Our Kid": "Any Friend or Family Member", "Peg It": "To Run / Flee", "Proper": "Really / A Term of Exaggeration", "Rank": "Disgusting", "Scran": "Food", "Snide": "Tight / Not Generous", "Sorted": "Good / Excellent", "Sound": "Good / Fine", "Swear Down": "A Promise of The Truth", "Top One": "Excellent" } choice = None while choice != "0": print( """ Please choose from the following options 0 - Quit The Manc Dictionary 1 - List All Manc Words / Terms in Dictionary 2 - Look Up a Manc Word / Term 3 - Add a Manc Word / Term 4 - Redefine a Manc Word / Term 5 - Delete a Manc Term """ ) choice = input(""" Please enter your choice: """) if choice == "0": print(""" Thank you for using the Manc Dictionary. Good-bye! """) elif choice == "1": print(""" Here is a list of all the terms in the Manc Dictionary: """) for terms in sorted(dictionary): print(f"""\t{terms}""") elif choice == "2": word = input(""" Which Manc word would you like to look for?: """) if word in dictionary: definition = dictionary[word] print(f""" {word} means {definition} """) else: print(f""" Sorry, the word {word} is not in our dictionary """) elif choice == "3": word = input(""" Which word do you want to add to the Manc Dictionary?: """) if word not in dictionary: definition = input(""" What's the definition?: """) dictionary[word] = definition print(f""" OK, {word} has been added to the Manc Dictionary. """) else: print(""" That word already exists in our Manc Dictionary! """) elif choice == "4": word = input(""" What Manc term would you like to redefine?: """) if word in dictionary: definition = input(""" What's the new definition of our Manc word?: """) dictionary[word] = definition print(f""" OK, {word} has been redefined in the Manc Dictionary! """) else: print(""" That term doesn't exist in the Manc Dictioanry! Maybe You'd like to add it. """) elif choice == "5": word = input(""" Which word from the Manc Dictionary would you like to delete?: """) if word in dictionary: del dictionary[word] print(f""" Okay, {word} was deleted from the Manc Dictionary. """) else: print(f""" Sorry, {word} doesn't exist in the Manc Dictionary. """) else: print(f""" Sorry, but {choice} is not a valid choice. PLease check the options again. """)
f5a87ae84cf16df45248e511c0eaa2eb3d809cfe
fransHalason/IndonesiaAI
/Basic Python/Part 7 - Python Advanced Topics/tuples.py
252
3.71875
4
''' PYTHON: TUPLES A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. ''' # Create a Tuple thistuple = ("apple", "banana", "cherry") print(thistuple) # Access Tuple Items print(thistuple[1])
0963940e0e0e87b073b77af8124d055dbd3fb93e
Kevinliaoo/Sorting-Algorithms-Visualizer
/widgets/spinner.py
1,699
3.640625
4
from widgets.button import Button class Spinner (Button): def __init__ (self, x, y, width, height, color, text, *args): """ :param *args: list or tuple """ Button.__init__ (self, x, y, width, height, color, text) self.subButtons = [] self.showChilds = False pos = 0 for btn in args[0]: # Change the color of spinner's sub elements c = [] for i in color: c.append (i - int(i * 0.2)) sub = SubSpinner (x, y, width, height, tuple(c), btn, pos) self.subButtons.append (sub) pos += 1 # Override def onClick (self, x, y): """ This function shows the sub items of the spinner when is clicked. :param x: int :param y: int """ # Ckeck if clicked inside the spinner's area clickedInside = x > self.x and x < self.x + self.width and y > self.y and y < self.y + self.height # Check if clicked a sub item clickedChild = x > self.x and x < self.x + self.width and y > self.y + self.height and y < self.y + self.height + len(self.subButtons) * self.height if self.showChilds: if clickedChild: self.showChilds = False # Get the sub item cliked for i in self.subButtons: algo = i.onClick(x, y) if algo != None: self.text = algo else: self.showChilds = False else: if clickedInside: self.showChilds = True class SubSpinner (Button): def __init__ (self, spinX, spinY, width, height, color, text, position): """ :param position: int """ x = spinX y = spinY + height + height * position Button.__init__ (self, x, y, width, height, color, text, self._clickFunc) def _clickFunc (self): """ Function that is triggered when is clicked. """ return self.text
cd968c7839d5923588b9266b94f9f9c90fe14894
DanielZuerrer/AdventOfCode2018
/1_2/solution.py
457
3.75
4
with open('input.txt') as input: frequencyChanges = input.readlines() frequencyChanges = [int(change.strip()) for change in frequencyChanges] frequency = 0 knownFrequencies = {frequency} searching = True while searching: for frequencyChange in frequencyChanges: frequency += frequencyChange if frequency in knownFrequencies: searching = False break knownFrequencies.add(frequency) print(frequency)
79f92d0901770a3a7816d4db1284dd031163e2c3
KratiAnu/LinearRegression
/MultipleRegression.py
741
3.59375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score data = pd.read_csv("C:/Users/Anu/Desktop/Advertising.csv.txt") data.drop(['Unnamed : 0'], axis=1) plt.figure(figsize=(16,8)) plt.scatter( data['TV'], data['sales'], c = 'black' ) plt.xlabel("Money on TV ads ($)") plt.ylabel("Sales($)") plt.show() X = data.drop(['sales', 'Unnamed : 0'], axis=1) Y = data['sales'].values.reshape(-1,1) reg = LinearRegression() reg.fit(X,Y) print("The linear model is: Y = {:.5} + {:.5}*TV + {:.5}*radio + {:.5}*newspaper".format(reg.intercept_[0], reg.coef_[0][0], reg.coef_[0][1], reg.coef_[0][2]))
59633532405ba208fcc4d2392374351081095cbe
RomaTk/longNumber-operations
/longArithmetic/multiplication.py
3,775
4.375
4
from . import general from . import summary def multiplication(number1="0",number2="0"): """ This function multiplies numbers as float or int inputed as strings multiplication(number1="0",number2="0") arguments: "number1": type: string "number2": type: string """ result="0"; if (type(number1) is str)and(type(number2) is str): if (general.isNumber(number1))and(general.isNumber(number2)): result=multiplyStringsWithSymbol(number1,number2); else: raise Exception("Arguments should be like integers or floats in string"); else: raise Exception("Type of arguments should be str"); result=general.clearExtraZeros(result); return result def multiplyStringsWithSymbol(number1="0",number2="0"): """ This function multiply two numbers as int or float inputed as strings This function does not check are these strings represent integers or floats so you should check it before And this function does not check type of arguments multiplyStringsWithSymbol(number1="0",number2="0") arguments: "number1": type: str "number2": type: str """ symbol1,number1=general.getSymbolAndNumber(number1); symbol2,number2=general.getSymbolAndNumber(number2); if (symbol1==symbol2)or(number1=="0")or(number2=="0"): return multiplyStrings(number1,number2); else: return "-"+multiplyStrings(number1,number2); def multiplyStrings(number1="0",number2="0"): """ This function multiply two numbers as int or float inputed as strings without +/- in the beginning This function does not check are these strings represent integers or floats so you should check it before And this function does not check type of arguments multiplyStrings(number1="0",number2="0") arguments: "number1": type: str "number2": type: str """ def setPositionDot(numberStr=""): positionDot=len(numberStr); if "." in numberStr: positionDot=numberStr.index("."); return positionDot def deleteSymbolByPosition(st="",position=0): if (position>-1)and(position<len(st)): st=st[:position]+st[position+1:]; return st def getNumberOfSymbolsAfterDot(dotPosition=0,lenOfString=""): return lenOfString-dotPosition; def addSymbol(st,position,symbol): return st[:position+1]+symbol+st[position+1:] number1=general.clearExtraZeros(number1); number2=general.clearExtraZeros(number2); result='0'; positionDot1=setPositionDot(number1); positionDot2=setPositionDot(number2); number1=deleteSymbolByPosition(number1,positionDot1); number2=deleteSymbolByPosition(number2,positionDot2); for i in range(len(number2)-1,-1,-1): resultToSum=numeralWithNumber(number1,int(number2[i]))+'0'*(len(number2)-1-i); result=summary.sum(result,resultToSum); numbersAfterDot=getNumberOfSymbolsAfterDot(positionDot1,len(number1))+getNumberOfSymbolsAfterDot(positionDot2,len(number2)); result=(numbersAfterDot-len(result))*"0"+result result=addSymbol(result,len(result)-1-numbersAfterDot,"."); if result[0]==".": result="0"+result; if result[-1]==".": result=result+"0"; result=general.clearExtraZeros(result); return result def numeralWithNumber(number1="0",intNumber=0): """ This function multiplies a number as int inputed as strings and int This function does not check are these strings represent integers or floats so you should check it before And this function does not check type of arguments numeralWithNumber(number1="0",intNumber=0) arguments: "number1": type: string "intNumber": type: int """ addToNextLevel=0; result=''; for i in range(len(number1)-1,-1,-1): calculatedMult=int(number1[i])*intNumber+addToNextLevel; result=str(calculatedMult%10)+result; addToNextLevel=calculatedMult//10; if addToNextLevel!=0: result=str(addToNextLevel)+result; return result; if __name__=="__main__": print(multiplication("-154.6","-157.2"));
cc1eed0c2752e81a015a7ffb2e43bf309432fb99
AleByron/AleByron-The-Python-Workbook-second-edition
/Chap-2/ex42.py
545
3.953125
4
note = str(input('Insert a note:')) ch = note[0] n = note[1] n = int(n) if ch == 'C': f = 261.63 f = f/(2**(4-n)) elif ch == 'D': f = 293.66 f = f / (2 ** (4 - n)) elif ch == 'E': f = 329.63 f = f / (2 ** (4 - n)) elif ch == 'F': f = 349.23 f = f / (2 ** (4 - n)) elif ch == 'G': f = 392.00 f = f / (2 ** (4 - n)) elif ch == 'A': f = 440.00 f = f / (2 ** (4 - n)) elif ch == 'B': f = 493.88 f = f / (2 ** (4 - n)) else: print('This is not a note') print(f)
a4a021329d50a448b0d1aa0562bde2cade5b4d36
Keshav1506/competitive_programming
/Bit_Magic/019_EPI_Primitive_Multiply/Solution.py
5,472
3.75
4
# # Time : # Space : # # @tag : Bit Magic # @by : Shaikat Majumdar # @date: Aug 27, 2020 # ************************************************************************** # EPI ( Elements Of Programming Interviews - Adnan Aziz ) : Primitive Multiply # # Description: # # Write a program that multiplies two non-negative integers. The only operators you # are allowed to use are # • assignment, # • the bitwise operators », «, |, &, ^ and # • equality checks and Boolean combinations thereof. # # You may use loops and functions that you write yourself. These constraints imply, # for example, that you cannot use increment or decrement, or test if x < y. # # Hint: Add using bitwise operations; multiply using shift-and-add. # # ************************************************************************** # Source: https://github.com/adnanaziz/EPIJudge/blob/master/epi_judge_python/primitive_multiply.py (EPI - Primitive Multiply) # ************************************************************************** # from typing import List import unittest class Solution(object): # A brute-force approach would be to perform repeated addition, i.e., initial¬ # ize the result to 0 and then add x to it y times. For example, to form 5x3, we would # start with 0 and repeatedly add 5, i.e., form 0 + 5,5 + 5,10 + 5. The time complexity # is very high—as much as O(2^n), where n is the number of bits in the input, and it # still leaves open the problem of adding numbers without the presence of an add # instruction. # Solution: Grade-School Multiplication Algorithm. # # The algorithm taught in grade-school for decimal multiplication does not use # repeated addition—it uses shift and add to achieve a much better time complexity. # We can do the same with binary numbers—to multiply `x` and `y` we initialize the result # to 0 and iterate through the bits of `x`, adding `2^k * y` to the result if the k'th bit of `x` is 1. # # The value (2^k * y) can be computed by left-shifting `y` by `k`. Since we cannot use add # directly, we must implement it. We apply the grade-school algorithm for addition to # the binary case, i.e., compute the sum bit-by-bit, and "rippling" the carry along. # # As an example, we show how to multiply 13 = (1101)2 and 9 = (1001)2 using the # algorithm described above. In the first iteration, since the LSB of 13 is 1, we set the # result to (1001)2. The second bit of (1101)2 is 0, so we move on to the third bit. This # bit is 1,so we shift (1001)2 to the left by 2 to obtain (100100)2, which we add to (1001)2 # to get (101101)2. The fourth and final bit of (1101)2 is 1, so we shift (1001)2 to the left # by 3 to obtain (1001000)2, which we add to (101101)2 to get (1110101)2 = 117. # # Each addition is itself performed bit-by-bit. For example, when adding (101101)2 # and (1001000)2, the LSB of the result is 1 (since exactly one of the two LSBs of the # operands is 1). The next bit is 0 (since both the next bits of the operands are 0). The # next bit is 1 (since exactly one of the next bits of the operands is 1). The next bit is # 0 (since both the next bits of the operands are 1). We also "carry" a 1 to the next # position. The next bit is1(since the carry-in is1and both the next bits of the operands # are 0). The remaining bits are assigned similarly. # # Time Complexity: O(n^2) # n : the width of the operands. # # The time complexity of addition is O(n),where n is the width of the operands. Since # we do n additions to perform a single multiplication, the total time complexity is # O(n^2). # def multiply(self, x, y): def add(a, b): running_sum, carryin, k, temp_a, temp_b = 0, 0, 1, a, b while temp_a or temp_b: ak, bk = a & k, b & k carryout = (ak & bk) | (ak & carryin) | (bk & carryin) running_sum |= ak ^ bk ^ carryin carryin, k, temp_a, temp_b = ( carryout << 1, k << 1, temp_a >> 1, temp_b >> 1, ) return running_sum | carryin running_sum = 0 while x: # Examines each bit of x. if x & 1: running_sum = add(running_sum, y) x, y = x >> 1, y << 1 return running_sum def multiply_optimized(self, x: int, y: int) -> int: def add(a, b): return a if b == 0 else add(a ^ b, (a & b) << 1) running_sum = 0 while x: # Examines each bit of x. if x & 1: running_sum = add(running_sum, y) x, y = x >> 1, y << 1 return running_sum class Test(unittest.TestCase): def setUp(self) -> None: pass def tearDown(self) -> None: pass def test_primitive_multiply(self) -> None: sol = Solution() for x, y, solution in ( [0, 0, 0], [0, 1, 0], [0, 65533, 0], [1, 65533, 65533], [345, 1, 345], [345, 0, 0], [57536, 2187, 125831232], [4639, 45265, 209984335], ): self.assertEqual(solution, sol.multiply(x, y)) self.assertEqual(solution, sol.multiply_optimized(x, y)) # main if __name__ == "__main__": unittest.main()
ecbf7cdeca37a9fc800dbd674a92f5d9ae02ea95
lilyandcy/python3
/leetcode/mySqrt.py
406
3.515625
4
class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ if x == 0: return 0 l = 1 r = x while l <= x: num = (l + r) // 2 s = num **2 if s <= x < (num+1) **2: return num if s < x: l = num if s > x: r = num
3f33d2dd92ce920720df0d612454a94388867a0b
electricman991/cse210-student-hilo
/hilo/game/player.py
623
3.734375
4
class Player: """A code template for a person who guesses high or low. The responsibility of this class of objects is to say high or low, keep track of the values, the score, and determine whether or not it can throw again.""" def __init__(self): self.points = 300 def get_points(self, wasCorrect): if wasCorrect: self.points += 100 else: self.points -= 75 if self.points < 0: self.points = 0 return self.points def can_play(self): if self.points > 0: return True return False
1fc97f7b84a76f919529f389987e25f178c36bf2
muokicaleb/Hacker_rank_python
/itertools/itertools_product.py
767
4.28125
4
""" You are given a two lists A and B. Your task is to compute their cartesian product AXB. Example A = [1, 2] B = [3, 4] AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] Note: A and B are sorted lists, and the cartesian product's tuples should be output in sorted order. Input Format The first line contains the space separated elements of list A. The second line contains the space separated elements of list B. Both lists have no duplicate integer elements. Output Format Output the space separated tuples of the cartesian product. Sample Input 1 2 3 4 Sample Output (1, 3) (1, 4) (2, 3) (2, 4) """ from itertools import product A = input().split() B = input().split() A = list(map(int, A)) B = list(map(int, B)) for i in product(A, B): print (i, end=' ')
fa8d7b677b1de852a65321b2eb9bd67fc5166ef6
ilove52345234/while2
/while2.py
265
3.96875
4
x = 3 pwd = 'a123456' while x > 0: password = input('請輸入密碼: ') x = x - 1 if password == pwd: print('登入成功') break else: print('密碼錯誤') if x > 0: print('還有', x, '次機會') else: print('請聯絡客服人員!')
67e36de40909ec2527413d89351e933dbf524ab1
AbhayPotabatti/Industrial-training
/forloop.py
85
3.578125
4
list = [1,2,3,4,5,6,7,8,9,10] n = 5 for i in list: c = n*i print(c)
384025db1f834ec77b432433eb499510d2b1a3fa
Andi-FB/Investigando-Python
/08_Guessing game & 11_Functions.py
1,307
3.953125
4
import random random_number = random.randint(0, 10) def validate_in(): input_ok = False while not input_ok: user_in = input("Try a number from 0 to 10") if user_in.isnumeric(): return user_in def play(): number_of_tries = 0 while number_of_tries < 3: user_in = validate_in() if random_number == user_in: print('That´s correct you won!') return elif random_number < user_in: print('Lower!') number_of_tries += 1 elif user_in == -1: print('CHEAT ENABLED: THE NUMBER IS {}'.format(random_number)) elif abs(user_in - random_number) == 1: print('1 unit close!') number_of_tries += 1 else: print('Higher!') number_of_tries += 1 # This is not really recommended in python because of def keyword # def welcome: print("Welcome") # the name of the resulting function object is specifically 'welcome' instead of the generic '<lambda>' # But lambda functions are quite practical e.g. to define a sorting function welcome = lambda: print('Welcome!') welcome() wantsToPlayAgain = 'Y' while wantsToPlayAgain.upper() == 'Y': play() wantsToPlayAgain = input('Want to play again? Y/N') print('Game over :(')
16256b544712a0d31400deb614cc9d69bd0839fb
wotanCode/4GA-Learn-Python-Loops-and-lists-Interactively
/exercises/08.2-Divide_and_conquer/app.py
442
3.6875
4
list_of_numbers = [4, 80, 85, 59, 37,25, 5, 64, 66, 81,20, 64, 41, 22, 76,76, 55, 96, 2, 68] #Your code here: def merge_two_list(arreglo): odd = [] even = [] comb = [] for x in range(len(arreglo)): if arreglo[x]%2!=0: odd.append(arreglo[x]) elif arreglo[x]%2==0: even.append(arreglo[x]) comb.append(odd) comb.append(even) return comb print(merge_two_list(list_of_numbers))
e7086c914bb50eaa7e08f9c04952e16ccde7eb4b
robertcrowe-zz/OpenCV-Notes
/Shape_Detect/Contours/template_matching.py
2,328
3.578125
4
import cv2 import numpy as np import os.path """ cv2.matchShapes(contour template, contour, method, method parameter) Output – match value (lower values means a closer match) Contour Template – This is our reference contour that we’re trying to find in the new image Contour – The individual contour we are checking against Method – Type of contour matching (1, 2, 3) Method Parameter – leave alone as 0.0 (not fully utilized in python OpenCV) http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html """ # Load the shape template or reference image template = cv2.imread(os.path.dirname(__file__) + '/../../images/4star.jpg',0) cv2.imshow('Template', template) cv2.waitKey() # Load the target image with the shapes we're trying to match target = cv2.imread(os.path.dirname(__file__) + '/../../images/shapestomatch.jpg') target_gray = cv2.cvtColor(target,cv2.COLOR_BGR2GRAY) # Threshold both images first before using cv2.findContours ret, thresh1 = cv2.threshold(template, 127, 255, 0) ret, thresh2 = cv2.threshold(target_gray, 127, 255, 0) # Find contours in template # Python 3: _, contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # We need to sort the contours by area so that we can remove the largest # contour which is the image outline (frame) sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True) # We extract the second largest contour which will be our template contour template_contour = contours[1] # Extract contours from the target image # Python 3: _, contours, hierarchy = cv2.findContours(thresh2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) contours, hierarchy = cv2.findContours(thresh2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) best_match = (1.0, []) for c in contours: # Iterate through each contour in the target image and # use cv2.matchShapes to compare contour shapes # Lower values indicate a better match match = cv2.matchShapes(template_contour, c, 3, 0.0) print(match) if match <= best_match[0]: best_match = (match, c) cv2.drawContours(target, [best_match[1]], -1, (0,255,0), 3) cv2.imshow('Output', target) cv2.waitKey() cv2.destroyAllWindows()
496b942d9a1d3f9def09029cc5b42affd3f20482
atasky/Python-data-structures-and-algorithms
/pair_sum.py
611
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 26 20:24:37 2018 @author: Vaidehee """ # input # arr=[1,2,3,4] k=5 # output - # {(2,3),(1,4)} #input #arr = [1,2,3] k=3 #output - # {(1,2)} def pair_array(arr, k): if len(arr)<2: return seen=set() output=set() for num in arr: target = k-num if target not in seen: seen.add(num) else: output.add((min(target,num), max(target,num))) print('\n'.join(map(str, list(output)))) arr=[1,2,3,4] k=5 pair_array(arr, k)
3eeaf60faf654b987baa7c6e74c0d70d5338d9f4
here0009/LeetCode
/Python/MissingNumber.py
1,132
4
4
""" Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? """ class Solution: def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ max_num = 0 sum_num = 0 len_num = len(nums) for num in nums: sum_num += num max_num = max(num, max_num) # print(sum_num, max_num) if max_num < len_num: #max num is missing return max_num+1 else: #there is max num, calculate the sum based on max num, then substract the real sum return int((max_num)*(max_num+1)/2 - sum_num) s = Solution() nums = [3,0,1] print(s.missingNumber(nums)) nums = [9,6,4,2,3,5,7,0,1] print(s.missingNumber(nums)) nums = [1] print(s.missingNumber(nums)) nums = [0] print(s.missingNumber(nums)) nums = [0,1] print(s.missingNumber(nums))
500aecbb9e4f04ae672eb46407012b1e7cea4d1f
sumalemambo/IWI-131-Programacion-de-computadores-USM
/Certamen 1/2019/Problema 2.py
1,984
3.515625
4
################################################################ # Certamen 1 2019 Nombre: Ignacio Quintana ROL:201973610-8 # # Mail: ignacio.quintana@usm.cl # ################################################################ ################################################################## # Funcion: mejor # # Input: un numero entero de 4 digitos, con digitos del 1 al 7 # # Descripcion: obtiene la cancion con mejor calificacion # ################################################################## #Problema 2) a) def mejor(votos): D = votos % 10 votos = votos // 10 C = votos % 10 votos = votos // 10 B = votos % 10 votos = votos // 10 A = votos % 10 votos = votos // 10 if(A < 4 and B < 4 and C < 4 and D < 4): return '' elif(A > B and A > C and A > D): return 'A' elif(B > A and B > C and B > D): return 'B' elif(C > A and C > B and C > D): return 'C' else: return 'D' #Problema 2) b) ####################################################################### # Programa principal # # Descripcion: En cada iteracion pregunta un numero de 4 digitos # # correspondiente a los discos A,B,C y D ,y calcula cual es el mejor # # al final obtiene cual se repite como mejor # ####################################################################### A = B = C = D = 0 for i in range(0,1000): a = mejor(int(input("Voto? "))) if(a == 'A'): A += 1 elif(a == 'B'): B += 1 elif(a == 'C'): C += 1 elif(a == 'D'): D += 1 if(A > B and A > C and A > D): a = 'A' maximo = A elif(B > A and B > C and B > D): a = 'B' maximo = B elif(C > A and C > B and C > D): a = 'C' maximo = C else: a = 'D' maximo = D print("El ganador fue " + a + " con " + str(maximo) + " votos")
d1effd84ed1541efa677a1285c2c95dc479e37fb
bwasicki/Github-Stuff
/BenWikiSearch/new project.py
1,935
3.609375
4
import time import wikipedia import xlsxwriter from bs4 import BeautifulSoup excel = xlsxwriter.Workbook('doc1.xlsx') sheet = excel.add_worksheet() wikipage = wikipedia.WikipediaPage('British Empire') wikipages = list() titles = list() words = list() nums = list() def search(): page_title = '' while page_title != "!!!": page_title = input('Please Enter a valid Wikipedia Page. If done, Enter "!!!" ') if page_title != "!!!": try: wikipage = wikipedia.WikipediaPage(page_title) titles.append(page_title) except: print('Not a valid Page') titles.sort() for title in titles: wikipage = wikipedia.WikipediaPage(title) wikipages.append(wikipage) word = '' while word != "!!!": word = input('Please enter word to search. If done, Enter "!!!" ') if word != "!!!": words.append(word) time_s = time.time() words.sort() for wikipage in wikipages: for word in words: plainText = getPlainText(wikipage).get_text() num = plainText.lower().split().count(word.lower()) nums.append(num) writeToExcel() time_e=time.time() print('time elapsed: ', time_e-time_s) def writeToExcel(): print('writing to excel...') row=1 col=1 sheet.write(0, 0, 'page') sheet.write(0, 1, 'word') sheet.write(0, 2, 'count') for wikiIndex in range(0, len(wikipages)): sheet.write(wikiIndex*len(words)+1,0,wikipages[wikiIndex].title) for col in range(1, 2): for row in range(1, len(words)+1): sheet.write(wikiIndex*len(words)+row, col, words[row-1] ) sheet.write(wikiIndex*len(words)+row, col+1, nums[wikiIndex*len(words)+row-1]) excel.close() print('written.') def getPlainText(page): return BeautifulSoup(page.html(), 'html.parser')
691be557fb9427678ddb5c7260374032b78b7545
Programmer-Admin/binarysearch-editorials
/Trailing Zeros.py
1,559
4.21875
4
""" Trailing Zeros The key insight to the types of problem asking for the trailing number of zeroes is the following. The number of trailing zeroes is the number of times 10 can divide a number. The number of tens in a number can be found by doing its prime factorization: each ten is composed of prime factors 2 and 5, so the number of pairs of 2 and 5 in the prime factors of a number will give the number of trailing zeroes. Now, we must find the smallest value that can be divided by numbers [1,k], otherwise known as the least common multiple (lcm). Let's take an example (k=5): lcm(1,2,3,4,5) = lcm(1,lcm(2,lcm(3,lcm(4,5)))) lcm(4,5) =20 lcm(3,20)=60 lcm(2,60)=60 lcm(1,60)=60 A key insight here is that lcm(2,4) = 4, so we can ignore the 2 completely. The reason for this is that 4 is a multiple of 2. lcm(1,3,4,5)=1x3x4x5=60 (No number is a multiple of another). How does this help us counting the number of 10's? Well, if we can eliminate numbers for which one of their multiples is present in the series, it means if we have 5,10,15,20, we can eliminate 5,10,15 and just keep the largest number (20), and its prime factors are 2x2x5. In order to gain another 5, we must reach the next power of 5, 25: 25 = 5*5. => k=25 will have two trailing zeroes because we have two 5's. We can assume there will be enough 2's in the series because 2 is more frequent than 5, (2,4,6,8,...) vs (5,10,15,...) Hopefully this gives you the intuition (smiley face). """ from math import log class Solution: def solve(self, k): return int(log(k,5))
963ba197be2bd9fcaddab31f91dde54e985e6834
hellodk/dumpyard
/hacker_rank/sock_merchant/sock_merchant.py
446
3.5
4
#!/bin/python3 def sockMerchant(n, ar): di = {i: ar.count(i) for i in ar} count = 0 for elem in di.values(): count = count + int(elem // 2) return count if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # n = int(input()) n = 9 # ar = list(map(int, input().rstrip().split())) ar = [9, 10, 20, 20, 10, 10, 30, 50, 10, 20] result = sockMerchant(n, ar) print (result)
383d63a82de30f33eed7aa149c326f7419cdb312
GongFuXiong/leetcode
/topic12_backtrack/T131_partition/interview.py
1,343
3.515625
4
''' 131. 分割回文串 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 示例: 输入: "aab" 输出: [ ["aa","b"], ["a","a","b"] ] ''' # from T_HeapSort.Heap import MaxHeap,MinHeap class Solution: # 回溯法 def partition(self, s): s_len = len(s) res = [] if s_len == 0: return res def backtrack(s,start,s_len,path): if start == s_len: res.append(path[:]) return for i in range(start,s_len): # 如果 s[start:i] 不是回文,直接剪枝 if not self.checkPalindrome(s,start,i): continue path.append(s[start:i+1]) backtrack(s,i+1,s_len,path) path.pop() backtrack(s,0,s_len,[]) return res def checkPalindrome(self,s,l,r): while l < r: if s[l] != s[r]: return False l = l + 1 r = r - 1 return True if __name__ == "__main__": solution = Solution() while 1: str1 = input() if str1 != "": res = solution.partition(str1) print(res) else: break
e053922e4bcc83f7a9d227dfde9086b5b6448081
bishii/QA_Scripts
/IoT/RaspberryPi/messing_around/Chapter1_Frozen_Working/counting.py
2,021
3.578125
4
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) segments=(6,3,0,4,11,9,10,22) led=17 for segment in segments: print(segment) GPIO.setup(segment, GPIO.OUT) GPIO.output(segment, GPIO.LOW) GPIO.setup(led, GPIO.OUT) GPIO.output(led,GPIO.LOW) GPIO.setup(26, GPIO.OUT) GPIO.output(26,GPIO.LOW) GPIO.setup(19, GPIO.OUT) GPIO.output(19,GPIO.LOW) GPIO.setup(5, GPIO.OUT) GPIO.output(5,GPIO.LOW) GPIO.setup(13, GPIO.OUT) GPIO.output(13,GPIO.LOW) input("cleared...") GPIO.output(led,GPIO.HIGH) for segment in segments: print(segment) GPIO.output(segment, GPIO.HIGH) input("All turned on...") for segment in segments: print(segment) GPIO.output(segment, GPIO.LOW) givenAnswer=input("What number to display ??") def clearAllSegments(): for a in segmentOrder: GPIO.output(a,GPIO.LOW) def PrintNumber(DigitPos1to4, numberToPrint): # GPIO pin numbers for lookup (immutable) segmentOrder = (11,4,10,9,6,3,0) digitOrder = (19,26,13,5) num = {' ':(0,0,0,0,0,0,0), '0':(1,1,1,1,1,1,0), '1':(0,1,1,0,0,0,0), '2':(1,1,0,1,1,0,1), '3':(1,1,1,1,0,0,1), '4':(0,1,1,0,0,1,1), '5':(1,0,1,1,0,1,1), '6':(1,0,1,1,1,1,1), '7':(1,1,1,0,0,0,0), '8':(1,1,1,1,1,1,1), '9':(1,1,1,1,0,1,1)} #enumerate returns (indexPos, lookup's value) for a in enumerate(num[str(numberToPrint)]): if a[1] == 1: GPIO.output(segmentOrder[a[0]],GPIO.HIGH) else: GPIO.output(segmentOrder[a[0]],GPIO.LOW) GPIO.output(digitOrder[DigitPos1to4],GPIO.LOW) sleep(0.001) GPIO.output(digitOrder[DigitPos1to4],GPIO.HIGH) def PrintFourDigits(theNumber): #theNumber must be a 4 digit string. use ' ' for blank, 0 for zero digitOrder = (19,26,13,5) for digit in range(4): PrintNumber(digit,theNumber[digit]) GPIO.output(digitOrder[digit],GPIO.LOW) sleep(0.001) GPIO.output(digitOrder[digit],GPIO.HIGH) for x in range(1000): #for delay in range(5): PrintFourDigits(str(x).ljust(4,' ')) while True: for x in range(150): PrintFourDigits('1000') sleep(1) GPIO.cleanup()
6a22eb7599cabf17db774428cda83352f6b55cca
julie98/Python-Crash-Course
/chapter_5/user_name_check.py
356
3.84375
4
current_users = ['admin', 'Julie', 'Angela', 'Eric', 'Karolina'] new_users = ['Gisele', 'Angela', 'Eugenia', 'Kate', 'John', 'eric'] current_users_lower = [user.lower() for user in current_users] for new_user in new_users: if new_user.lower() in current_users_lower: print("This name has been taken!") else: print("This name is still available!")
98317742cf0a6bcee89b1367f3c9d0ca80ac5123
Kwasniok/ProjectEuler-Solver
/src/problem_012.py
1,690
3.90625
4
# coding=UTF_8 # # problem_012.py # ProjectEuler # # This file was created by Jens Kwasniok on 15.08.16. # Copyright (c) 2016 Jens Kwasniok. All rights reserved. # from problem_000 import * from ppe_math import number_of_divisors, list_of_divisors class Problem_012(Problem): def __init__(self): self.problem_nr = 12 self.input_format = (InputType.NUMBER_INT, 1, None) self.default_input = 500 self.description_str = '''The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over ''' + dye_input_var('five hundred') + " divisors?" def calculate(self, N): finnished = False i = 0 j = 0 res = 1 while not finnished: if number_of_divisors(j) > N: res = j finnished = True i += 1 j += i self.last_result = res def details(self): desc_str = "" desc_str += dye_input_var(self.last_result) + ' : ' divs = list_of_divisors(self.last_result) i = 0 while i < len(divs): desc_str += str(divs[i]) if i < len(divs) - 1: desc_str += ', ' i += 1 return desc_str register_problem(Problem_012())
2f8ea48be807266dc0d42e5d762c0e1da75eda43
Steuerwr/99-CapstoneProject-201930
/src/m1_laptop_code.py
3,605
3.96875
4
""" Capstone Project. Code to run on a LAPTOP (NOT the robot). Displays the Graphical User Interface (GUI) and communicates with the robot. Authors: Your professors (for the framework) and Will Steuerwald. Spring term, 2018-2019. """ # Done 1: Put your name in the above. import tkinter from tkinter import ttk import math import mqtt_remote_method_calls as mqtt import m2_laptop_code as m2 import m3_laptop_code as m3 def get_my_frame(root, window, mqtt_sender): # Construct your frame: frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge") frame_label = ttk.Label(frame, text="Will Steuerwald") frame_label.grid() # Done 2: Put your name in the above. # Add the rest of your GUI to your frame: # : Put your GUI onto your frame (using sub-frames if you wish). #forward_distance_button = ttk.Button(frame, text="Forward Distance") #forward_distance_button.grid() #forward_distance_button["command"] = lambda: MyLaptopDelegate.handle_forward_distance( # speed_entry, distance_entry, mqtt_sender) #distance_entry = ttk.Entry(frame) #distance_entry.insert(0, "100") #distance_entry.grid() #speed_button = ttk.Button(frame, text="Speed") #speed_button.grid() #speed_entry = ttk.Entry(frame) #speed_entry.insert(0, "100") #speed_entry.grid() direction_label = ttk.Label(frame, text="Choose a direction: ") direction_label.grid() forwards_button = ttk.Button(frame, text="Forwards") forwards_button.grid(row=2, column=0) backwards_button = ttk.Button(frame, text="Backwards") backwards_button.grid(row=2, column=1) speed_label = ttk.Label(frame, text='Enter speed') speed_label.grid() speed_entry = ttk.Entry(frame, width=8) speed_entry.grid() distance_label = ttk.Label(frame, text='Enter distance') distance_label.grid() distance_box = ttk.Entry(frame, width=8) distance_box.grid() function_label = ttk.Label(frame, text='Move until...') function_button = ttk.Button(frame, text='Move') frame_label.grid() function_label.grid() function_button.grid() forwards_button["command"] = lambda: MyLaptopDelegate.forward(speed_entry, distance_box, mqtt_sender) backwards_button["command"] = lambda: MyLaptopDelegate.backward(speed_entry, distance_box, mqtt_sender) function_button["command"] = lambda: MyLaptopDelegate.move_until(speed_entry, distance_box, mqtt_sender) # Return your frame: return frame class MyLaptopDelegate(object): """ Defines methods that are called by the MQTT listener when that listener gets a message (name of the method, plus its arguments) from the ROBOT via MQTT. """ def __init__(self, root): self.root = root # type: tkinter.Tk self.mqtt_sender = None # type: mqtt.MqttClient def set_mqtt_sender(self, mqtt_sender): self.mqtt_sender = mqtt_sender def forward(speed_entry, distance_box, mqtt_sender): speed = speed_entry.get() distance = distance_box.get() mqtt_sender.send_message("move_forward", [speed, distance]) def backward(speed_entry, distance_box, mqtt_sender): speed = speed_entry.get() distance = distance_box.get() mqtt_sender.send_message("move_backward", [speed, distance]) def move_until(speed_entry, distance_box, mqtt_sender): speed = speed_entry.get() distance = distance_box.get() mqtt_sender.send_message("move_until", [speed, distance]) # TODO: Add methods here as needed. # TODO: Add functions here as needed.
7a7f8681a4c7b2acd275a605657e6cd3ba42319a
gonjay/leetcode
/problems/reverse-integer/path-sum/Solution.py
1,065
3.71875
4
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: arr = [] hasPath = False # @param root, a tree node # @param sum, an integer # @return a boolean def hasPathSum(self, root, sum): self.sum = sum self.mapTree(root) return self.hasPath def mapTree(self, node): if node is None: return None self.arr.append(node.val) if node.left is not None: self.mapTree(node.left) if node.right is not None: self.mapTree(node.right) if node.left is None and node.right is None: pathsum = 0 for val in self.arr: pathsum = pathsum + val if pathsum == self.sum: self.hasPath = True self.arr.pop() su = Solution() n = TreeNode(0) root = n i = 1 while i < 10: n.left = TreeNode(i) n = n.left i += 1 next = root print su.hasPathSum(root, 0)
1a5d6a123c0740fb59ac1f89ac5db01104906908
girishgupta211/algorithms
/python/multi_processing.py
1,522
4
4
# importing the multiprocessing module import multiprocessing import os def cube(x): print("Worker process id for {0}: {1}".format(x, os.getpid())) return x ** 3 pool = multiprocessing.Pool(processes=4) # results = [pool.apply(cube, args=(x,)) for x in range(1, 7)] nums = [x for x in range(1, 7)] results = pool.map(cube, nums) print(results) print("---- pool is done ---") def square_list(mylist, q): """ function to square a given list """ # append squares of mylist to queue for num in mylist: q.put(num * num) def cube_list(mylist, q): """ function to square a given list """ # append squares of mylist to queue for num in mylist: q.put(num * num * num) def print_queue(q): """ function to print queue elements """ print("Queue elements:") while not q.empty(): print(q.get()) print("Queue is now empty!") if __name__ == "__main__": # input list input_list = [1, 2, 3, 4] # creating multiprocessing Queue q = multiprocessing.Queue() # creating new processes p1 = multiprocessing.Process(target=square_list, args=(input_list, q)) p2 = multiprocessing.Process(target=cube_list, args=(input_list, q)) p3 = multiprocessing.Process(target=print_queue, args=(q,)) # running process p1 to square list p1.start() p1.join() # running process p1 to square list p2.start() p2.join() # running process p2 to get queue elements p3.start() p3.join()
c3c68b21fb3c6bdec5d21c9284898b857972cf73
niteshsrivats/Labs
/5th Semester/Python/Sixth Lab/WordSplitter.py
760
3.703125
4
import math def clean(list): for i in range(len(list)): list[i] = list[i].replace(" ", "").replace("\n", "")[ : math.ceil(len(list[i]) / 2)] return list def merge(list1, list2): len1 = len(list1) len2 = len(list2) string = "" for i in range(len1): string += list1[i] if i < len2: string += list2[i] string += " " for i in range(len1, len2): string += list2[i] string += " " return string with open("SampleFile1.txt") as first: with open("SampleFile2.txt") as second: first_file_words = clean(first.read().split(" ")) second_file_words = clean(second.read().split(" ")) print(merge(first_file_words, second_file_words))
edd7f5d0ef81a36d480a103ab1ff0b6cf6bb784e
EPCJC-LP10/02
/Modulo9/projeto_new_/menu.py
1,311
3.828125
4
# -*- coding: utf-8 -*- def principal(): print print " +----------MENU--------+" print " | |" print " | 1. Gestão de Alunos |" print " | 2. Salas / Horários |" print " | 3. Registar Presença |" print " | 4. Ver todas as presenças |" print " +--------------------- +" print " | 0. Sair |" print " +----------------------+" op = raw_input("Opção: ") return op def alunos(): print print " *** Menu Alunos **** " print print "1. Inserir novo aluno" print "2. Listar todos alunos" print "3. Pesquisar aluno" print "4. Alterar dados de um aluno" print "5. Eliminar aluno" print "6. aluno com mais precensas" print print "0. Menu Anterior" op = raw_input("Opção: ") return op def salas(): print print " *** Menu Salas **** " print print "1. Inserir novo Sala/Hora" print "2. Listar todas as Prensenças" print "3. Pesquisar Presença" print "4. Alterar dados de uma Presença" print "5. Aluno com mais presenças" print "6. Eliminar Presença" print print "0. Menu Anterior" op = raw_input("Opção: ") return op if __name__ == "__main__": print "Este programa não deve ser executado diretamente"
eaa7385c8ddc75d4ef9cc684fb51cdcfcf58c1ea
victoruribehdz/programing-2
/Python/Exercise_26.py
3,694
4.375
4
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): ## ":" Missing #def print_first_word(words) """Prints the first word after popping it off.""" #word = words.poop(0) word = words.pop(0) # it is .pop print (word) def print_last_word(words): """Prints the last word after popping it off.""" #word = words.pop(-1 word = words.pop(-1) ## ")" Missing print (word) def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) print ("Let's practice everything.") print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.') poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print ("--------------") print (poem) print ("--------------") #five = 10 - 2 + 3 - 5 five = 10 - 2 + 3 - 6 ## I changed the 5 and I put 6 to give the result. print ("This should be five: %s" % five) def secret_formula(started): jelly_beans = started * 500 #jars = jelly_beans \ 1000 jars = jelly_beans / 1000 #The slash was wrong crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 #beans, jars, crates == secret_formula(start-point) beans, jars, crates = secret_formula(start_point) #The line would be down. print ("With a starting point of: %d" % start_point) #print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates) print ("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)) #It is not jeans, is beans. start_point = start_point / 10 print ("We can also do that this way:") #print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_pont print ("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)) #")" Missing #sentence = "All god\tthings come to those who weight." sentence = "All good things come to those who wait." #This slash should not be in the sentence. #Print the first and last word of the sentence #words = ex25.break_words(sentence) words = break_words(sentence) ##We don't need to import from exercise 25, we already have it in the functions. Break_words function. #sorted_words = ex25.sort_words(words) sorted_words = sort_words(words) ##We don't need to import from exercise 25, we already have it. Sort_words function print_first_word(words) print_last_word(words) #.print_first_word(sorted_words) print_first_word(sorted_words) ##This point should not be there print_last_word(sorted_words) #sorted_words = ex25.sort_sentence(sentence) sorted_words = sort_sentence(sentence) #We don't need to import from exercise 25, we already have it. Sorted_words function. #prin sorted_words print (sorted_words) #the word is 'print' and "()" Missing print_first_and_last(sentence) # print_first_a_last_sorted(senence) print_first_and_last_sorted(sentence) #the space is wrong, is 'and' no 'a', identification
9c971ee47bc7f4b1c10cb56e08a36ba48300371f
yiicao/final_project
/week 7/Authentication&CachingCodes/PersistCache.py
1,737
3.71875
4
import datetime import json CACHE_FILENAME = "cache.json" def open_cache(): ''' opens the cache file if it exists and loads the JSON into a dictionary, which it then returns. if the cache file doesn't exist, creates a new cache dictionary Parameters ---------- None Returns ------- The opened cache ''' try: cache_file = open(CACHE_FILENAME, 'r') cache_contents = cache_file.read() cache_dict = json.loads(cache_contents) cache_file.close() except: cache_dict = {} return cache_dict def save_cache(cache_dict): ''' saves the current state of the cache to disk Parameters ---------- cache_dict: dict The dictionary to save Returns ------- None ''' dumped_json_cache = json.dumps(cache_dict) fw = open(CACHE_FILENAME,"w") fw.write(dumped_json_cache) fw.close() def fib(n): fib_seq = [0, 1] for i in range(2, n): fib_seq.append(fib_seq[i - 2] + fib_seq[i - 1]) return fib_seq[-1] def fib_with_cache(n): n_key = str(n) if n_key in FIB_CACHE: return FIB_CACHE[n_key] else: FIB_CACHE[n_key] = fib(n) save_cache(FIB_CACHE) return FIB_CACHE[n_key] FIB_CACHE = open_cache() inp = input("What Fibonacci number would you like? ") t1 = datetime.datetime.now().timestamp() print(fib_with_cache(int(inp))) t2 = datetime.datetime.now().timestamp() inp = input("What Fibonacci number would you like? ") t3 = datetime.datetime.now().timestamp() print(fib_with_cache(int(inp))) t4 = datetime.datetime.now().timestamp() print("time without caching: ", (t2 - t1) * 1000, "ms") print("time with caching: ", (t4 - t3) * 1000, "ms")
12ec31232f018323b9777fb3148d06744e5546b2
identor/code
/python/point_circle.py
782
4.34375
4
import turtle import math cx, cy = eval(input("Enter the center of a circle x, y: ")) radius = eval(input("Enter the radius of the circle: ")) x, y = eval(input("Enter a point x, y: ")) distance = math.sqrt(((x - cx) ** 2) + ((y - cy) ** 2)) inside = radius >= distance # Draw the circle & the point turtle.hideturtle() turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.dot(5, "red") turtle.penup() turtle.goto(cx, cy - radius) turtle.pendown() turtle.circle(radius) # Write the remarks remarks = "The point is " + \ ("inside" if inside else "outside") + \ " the circle." turtle.penup() turtle.goto(cx, cy - radius - 20) turtle.write(remarks, align= "center",\ font= ("Arial", 12, "normal")) turtle.done()
78be22b581b4d7080b49749f7a6111f976ea6df8
fztest/Classified
/2.Binary_Search/2.14_459_Closest_Number_In_Sorted_Array.py
1,191
3.9375
4
""" Description __________ Given a target number and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to the given target. Return -1 if there is no element in the array. Example ________ Given [1, 2, 3] and target = 2, return 1. Given [1, 4, 6] and target = 3, return 1. Given [1, 4, 6] and target = 5, return 1 or 2. Given [1, 3, 3, 4] and target = 2, return 0 or 1 or 2. Approach ________ just a quick binary search Compleixty _________ Lg(N) """ class Solution: # @param {int[]} A an integer array sorted in ascending order # @param {int} target an integer # @return {int} an integer def closestNumber(self, A, target): # Write your code here if A is None or len(A) == 0: return -1 start, end = 0, len(A) - 1 while start + 1 < end: mid = start + (end - start) / 2 v = A[mid] if v == target: return mid elif v < target: start = mid else: end = mid if abs(A[start] - target) < abs(A[end] - target): return start else: return end
1d40bdf15538d428f94f2a1fe75924ce48b1774f
boknowswiki/mytraning
/lintcode/python/0486_merge_k_sorted_array.py
2,010
3.921875
4
#!/usr/bin/python -t # heap # 使用 Heapq 的方法 # 最快,因为不需要创建额外空间。 # 时间复杂度和其他的算法一致,都是 # O(NlogK) N 是所有元素个数 import heapq class Solution: """ @param arrays: k sorted integer arrays @return: a sorted array """ def mergekSortedArrays(self, arrays): # write your code here ret = [] heap = [] for index, array in enumerate(arrays): if len(array) == 0: continue heapq.heappush(heap, (array[0], index, 0)) while len(heap): val, x, y = heapq.heappop(heap) ret.append(val) if y + 1 < len(arrays[x]): heapq.heappush(heap, (arrays[x][y+1], x, y+1)) return ret # divid and conqur class Solution: """ @param arrays: k sorted integer arrays @return: a sorted array """ def mergekSortedArrays(self, arrays): # write your code here n = len(arrays) return self.helper(arrays, 0, n-1) def helper(self, arrays, start, end): if start >= end: return arrays[start] mid = (start + end) /2 left = self.helper(arrays, start, mid) right = self.helper(arrays, mid+1, end) return self.merge(left, right) def merge(self, l1, l2): ret = [] len_l1 = len(l1) index1 = 0 len_l2 = len(l2) index2 = 0 while index1 < len_l1 and index2 < len_l2: if l1[index1] < l2[index2]: ret.append(l1[index1]) index1 += 1 else: ret.append(l2[index2]) index2 += 1 if index1 < len_l1: ret.extend(l1[index1:]) if index2 < len_l2: ret.extend(l2[index2:]) return ret
5d93d1776d12f9f32f9184f595ff3ba192926fc7
jmast02/PY4E_exercises
/EX_8.5.py
767
4.28125
4
'''8.5 Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt''' fhand = open('mbox-short.txt') count = 0 for line in fhand: words = line.split() if len(words) == 0 or len(words) < 2 or words[0] != 'From' : continue print(words[1]) count = count + 1 print('There were %d lines in the file with From as the first word' % count)
54454034924ca8405acf7db2baa75ea50e382b32
PrestonFawcett/Snake_Game
/highscore.py
700
3.8125
4
#!/usr/bin/env python3 """ File keeps track of score board and saves to pickle file """ import pickle __author__ = 'Preston Fawcett' __email__ = 'ptfawcett@csu.fullerton.edu' __maintainer__ = 'PrestonFawcett' def write(score): """ Save top 5 scores to a list """ high_score = list() high_score = list(read()) high_score.append(score) high_score.sort(reverse=True) del high_score[5:] with open('game_data.pickle', 'wb') as fh: pickle.dump(high_score, fh, pickle.HIGHEST_PROTOCOL) def read(): """ Return saved scores """ with open('game_data.pickle', 'rb') as fh: high_score = pickle.load(fh) return high_score if __name__ == '__main__': write() read()
8e8cfda7d8249e5ec0c43978b0c6370ba6528489
navaniharsh31/blackjack-python
/blackjack.py
3,456
3.90625
4
#!/usr/bin/env python import random import sys print("--------------------") print(" BLACKJACK ") print("--------------------") print() while True: player_cards = [] dealer_cards = [] while len(dealer_cards) != 2: dealer_cards.append(random.randint(1, 10)) if len(dealer_cards) == 2: print("Dealer has X and", dealer_cards[1]) while len(player_cards) != 2: player_cards.append(random.randint(1, 10)) if len(player_cards) == 2: print("You have ", player_cards) if sum(player_cards) == 21: print("BLACKJACK") print("YOU WON") sys.exit() if sum(player_cards) == 11 and 1 in player_cards: index = player_cards.index(1) del player_cards[index] player_cards.append(11) print("YOU WON BLACKJACK") sys.exit() while sum(player_cards) <= 21: if sum(player_cards) > 21: print("YOU BUSTED") sys.exit() print("Do you want to") print("1. STAY") print("2. HIT") print() action = int(input("Enter your choice")) if action == 2: player_cards.append(random.randint(1, 10)) print() print("You have", player_cards, "Your sum is", sum(player_cards)) if sum(player_cards) == 21: print("----------") print("BLACKJACK") print("YOU WON") sys.exit() # print("Now your cards are", player_cards, "and sum is ", sum(player_cards)) elif action == 1: break if 1 in player_cards: print("Do you want to count 1 as 11") print("Y -Yes, N- No") c = (input()) if c == "y" or c == "Y": index = player_cards.index(1) del player_cards[index] player_cards.append(11) print("Now your cards are", player_cards, "and sum is ", sum(player_cards)) elif c == "N" or c == "n": if sum(player_cards) > 21: print("YOU BUSTED") sys.exit() # break if sum(player_cards) > 21: print("YOU BUSTED") sys.exit() print("Dealer has", dealer_cards, "sum is", sum(dealer_cards)) while sum(dealer_cards) <= 16: dealer_cards.append(random.randint(1, 10)) if sum(dealer_cards) <= 11 and 1 in dealer_cards: index = dealer_cards.index(1) del dealer_cards[index] dealer_cards.append(11) print() print("Now the dealer has", dealer_cards, "and sum is", sum(dealer_cards)) print() if sum(dealer_cards) > 21: print("----------") print("DEALER BUSTED") print("YOU WON") elif sum(dealer_cards) == 21: print("----------") print("Dealer BLACKJACK") print("You Lost") elif sum(dealer_cards) == sum(player_cards): print("----------") print("PUSH") elif sum(dealer_cards) > sum(player_cards): print("----------") print("Dealer WON") print("----------") elif sum(player_cards) > sum(dealer_cards): print("YOU WON") print("----------") print("Do you want to play again? Y/N") play = input() if play == "n" or play == "N": print("Goodbye") sys.exit()
7d0551d01440dc5cc351c2484936d09907197f45
moyalopez/Python3
/programa de notas.py
769
3.53125
4
#jairmoya opcion = int(input("1.promedio de 4 notas\n2.division\n3.Salir\nIngrese su opcion:.")) promedio = 0 while opcion != 3: if opcion == 1: for i in range (4): nota = int(input("ingrese primera nota")) promedio = promedio + nota div = int(promedio) / int(4) print ("el promedio es:. {}".format(div)) elif opcion == 2: num1 = float(input("Ingrese numero:.")) num2 = float(input("Ingrese numero:.")) if num2 != 0: total = num1 / num2 print("Total:.",total) else: print("error, valor incorrecto... intente de nuevo") opcion = int(input("1.promedio de 4 notas\n2.division\n3.Salir\nIngrese su opcion:."))
d94abaf1e4bd24c870ef428c3a906eab95c8b8d5
xuteng0220/python
/python_full_stack_s22/hw03.py
11,008
3.609375
4
### 1.将今天的课上代码敲一遍,然后整理笔记 # a = 156 # # 二进制数 # print(bin(a)) # print(int('10011100', 2)) # name = 'absdefghijklmnopqrstuvwxyz' # print(name[-2:]) # print(name[0:3:2]) # print(name[-2::-2]) # b = 'alex' # print(b.upper()) # print(b) # c = 'WUSIR' # c = c.lower() # print(c) # d = 'asdf' # print(d.startswith('a')) # print(d.endswith('d')) # e = 'asdfdafsafasa' # f = e.count('a') # print(f) # g = ' adsff ' # h = g.strip() # print(g) # print(h) # i = '今天是个好日子' # j = i.split('天') # print(j) # k = 'deabcfghijklmnopqrstuvwxyzde' # l = k.replace('de', 'xt') # l1 = k.replace('de', 'xt', 1) # print(l) # print(l1) # a1 = '2345' # a2 = a1.isdigit() # print(a2) # # b1 = '12' # b2 = b1.isdecimal() # print(b2) # # c1 = '231asd中文' # c2 = c1.isalnum() # # d1 = '中文' # d2 = d1.isalpha() # print(d2) # for i in 'asdf': # print(i) # # for i in range(0, 100): # print(i) # # e1 = 'sadfssagg' # print(len(e1)) # i = 0 # while i < len(e1): # i += 1 # print(i) # while input('请输入1或q, 1进入, q退出!>>>') != 'q': # content = input('请输入相加的数, 例如3+2, 按q退出>>>') # a = content.split('+') # print(int(a[0]) + int(a[1])) # else: # print('退出成功!') # goods = [{'name': '电脑', 'price': 1999}, # {'name': '鼠标', 'price': 10}, # {'name': '游艇', 'price': 20}, # {'name': '美女', 'price': 998} # ] # money, flag, sum_total, dic = 0, True, 0, {} # # # 进行充值 # while True: # money = input('请输入充值金额(Q/退出): ') # if money.strip().isdecimal(): # money = int(money) # print('充值成功,当前余额为%d' % money) # break # elif money.upper() == 'Q': # print('欢迎下次光临') # flag = False # break # else: # print('充值有误,请重新充值') # # # 开始购物 # my = {'money': money, 'shopping_car': [], 'flash': {}} # while flag: # print('-' * 20) # for i in range(0, len(goods)): # print(i + 1, goods[i]['name'], goods[i]['price']) # number = input('请选择需要购买的商品(Q/退出;N/结算): ') # if number.strip().isdecimal(): # number = int(number) # if 0 < number < len(goods) + 1: # print('添加购物车成功') # # 添加选择的1个商品到列表shopping_car # my['shopping_car'].append(goods[number - 1]['name'] + ':' + str(goods[number - 1]['price'])) # # 添加选择的1个商品到字典dic,记录商品name和price # dic[goods[number - 1]['name']] = goods[number - 1]['price'] # # 添加选择的1个商品的价格到总计sum_total # sum_total += goods[number - 1]['price'] # k, v = my['shopping_car'][-1].split(':') # # 把新添加到shopping_car的产品,加入到字典flash,记录商品name和数量,如果flash已有,数量+1,否则,数量=1 # if k in my['flash']: # my['flash'][k] = int(my['flash'][k]) + 1 # continue # my['flash'][goods[number - 1]['name']] = 1 # else: # print('序号输入有误,请重新输入') # elif number.strip().upper() == 'Q': # if money > sum_total: # for k, v in my['flash'].items(): # print(k, v, dic[k]) # print('此次消费%d元,账户余额为%d元' % (sum_total, money - sum_total)) # for i in range(0, len(my['shopping_car'])): # print((i + 1, my['shopping_car'][i])) # break # else: # print('账户余额不足') # print('欢迎下次光临') # break # elif number.strip().upper() == 'N': # while True: # if money > sum_total: # print('已购清单如下:') # for k, v in my['flash'].items(): # print(k, '数量:', v, '单价:', dic[k]) # change = input('是否结算?(Y/N)') # if change.strip().upper() == 'Y': # for k, v in my['flash'].items(): # # 打印名称、数量、价格 # print(k, v, dic[k]) # print('此次消费%d元,账户余额为%d元' % (sum_total, money - sum_total)) # for i in range(0, len(my['shopping_car'])): # # 按加入的顺序打印加入购物车中的goods # print(i + 1, my['shopping_car'][i]) # flag = False # break # elif change.strip().upper() == 'N': # break # else: # print('输入有误,默认返回商品界面') # else: # for i in range(0, len(my['shopping_car'])): # print(i + 1, my['shopping_car'][i]) # choice = input('钱不够,请输入需要删除的商品(Q/退出):') # if choice.strip().isdecimal(): # choice = int(choice) # if 0 < choice < len(my['shopping_car']) + 1: # # a是name+price的字符串 # a = my['shopping_car'].pop(choice - 1) # # 取name # for i in my['flash']: # if i in a: # my['flash'][i] = int(my['flash'][i]) - 1 # sum_total -= int(dic[i]) # dic1 = my['flash'].copy() # for i in dic1: # if my['flash'][i] == 0: # my['flash'].pop(i) # elif choice.strip().upper() == 'Q': # if money > sum_total: # print('此次消费%d元,账户余额%d元' % (sum_total, money - sum_total)) # else: # print('账户余额不足') # print('欢迎下次光临') # break # else: # print('输入有误,请重新输入') # else: # print('输入有误,请重新输入') # ### 2.name = "aleX leNb" # name = "aleX leNb" # print(name) # print(name.strip()) # print(name.startswith("al")) # print(name.endswith("Nb")) # print(name.replace('l','p')) # print(name.replace('l','p',1)) # print(name.split('l')) # print(name.split('l',1)) # print(name.upper()) # print(name.lower()) # print(name.count('l')) # print(name[0:4].count('l')) # print(name[1]) # print(name[0:3]) # print(name[-2:]) # ### 3.s = "123a4b5c" # s = "123a4b5c" # s1 = s[0:3] # s2 = s[3:6] # s3 = s[0::2] # s4 = s[1:6:2] # s5 = s[-1] # s6 = s[-3::-2] # print(s1) # print(s2) # print(s3) # print(s4) # print(s5) # print(s6) # ### 4.使用while和for循环分别打印字符串s="asdfer"中每个元素。 # s = "asdfer" # for i in s: # print(i) # i = 0 # while i < len(s): # print(s[i]) # i+=1 # ### 5.使用for循环对s="asdfer"进行循环,但是每次打印的内容都是"asdfer"~ # s = "asdfer" # for i in s: # print(s) # ### 6.使用for循环对s="abcdefg"进行循环,每次打印的内容是每个字符加上sb, 例如:asb, bsb,csb,...gsb。 # s = "abcdefg" # for i in s: # print(i+"sb") # ### 7.使用for循环对s="321"进行循环,打印的内容依次是:"倒计时3秒","倒计时2秒","倒计时1秒","出发!"。 # s = "321" # for i in s: # print("倒计时"+i+"秒") # # if i == "1": # # print("出发") # print("出发") # ### 8.实现一个整数加法计算器(两个数相加): # to_add = input('请输入两个数相加,比如1+2: ') # a, b = to_add.split('+') # print(int(a.strip()) + int(b.strip())) # # # user = input("请输入1或q,1进入,q退出!>>>") # # while user != 'q': # # content = input("请输入相加的数,例如3+2,按q退出>>>") # # a = content.split("+") # # print(int(a[0])+int(a[1])) # # else: # # print("退出成功!") # ### 9.实现一个整数加法计算器(多个数相加) # a = input('请输入1或q,1表示进入,q表示退出: ') # while a.upper() != 'Q': # to_add = input('请输入需要相加的数字,比如1 2 3 4 5: ') # if to_add.upper() == 'Q': # break # s = 0 # for i in to_add.split(): # s += int(i) # print(s) # else: # print('已退出') # ### 10.计算用户输入的内容中有几个整数(以个位数为单位) # a = input('请输入: ') # count = 0 # for i in a.split(): # if i.isdigit(): # count += 1 # print(count) # ### 11.计算 1 - 2 + 3 ... + 99 中除了88以外所有数的总和? # j, s = -1, 0 # for i in range(1, 100): # j *= -1 # if i != 88: # s = s + i * j # print(s) # # 12.选做题:写代码,完成下列需求: # 用户可持续输入(用while循环),用户使用的情况: # 输入A,则显示走大路回家,然后在让用户进一步选择: # 是选择公交车,还是步行? # 选择公交车,显示10分钟到家,并退出整个程序。 # 选择步行,显示20分钟到家,并退出整个程序。 # 输入B,则显示走小路回家,并退出整个程序。 # 输入C,则显示绕道回家,然后在让用户进一步选择: # 是选择游戏厅玩会,还是网吧? # 选择游戏厅,则显示 ‘一个半小时到家,爸爸在家,拿棍等你。’并让其重新输入A,B,C选项。 # 选择网吧,则显示‘两个小时到家,妈妈已做好了战斗准备。’并让其重新输入A,B,C选项。 while True: choice = input('请选择:') if choice == 'A': print('走大路回家') choice_a = input('公交车/步行:') if choice_a == '公交车': print('10分钟到家') break else: print('20分钟到家') break elif choice == 'B': print('走小路回家') break else: print('绕道回家') choice_c = input('游戏厅/网吧:') if choice_c == '游戏厅': print('一个半小时到家,爸爸在家,拿棍等你') else: print('两个小时到家,妈妈已经做好了战斗的准备') # # ### 13.回文 # # a = "十八到日本日到八十" # if a[::-1] == a: # print("是回文") # else: # print("不是回文")
111db966ce892f7711957ecba7e0c7c34c249708
Vivek-M416/Basics
/Array/array6.py
185
3.609375
4
# slicing from array import * x = array('i', [10, 20, 30, 40, 50, 60, 70]) y = x[1:4] print(y) y = x[:4] print(y) y = x[-4:] print(y) y = x[-4: -1] print(y) y = x[0:7:2] print(y)
7e60f4f89bac680fe3dbd98188ab869403d8feb9
dbms-ops/learn_python_3
/1_learn_python_3/3-数字日期和时间/12-基本的日期与时间转换.py
980
3.53125
4
#!/data1/Python-2.7.4/bin/python2.7 # -*-coding:utf-8-*- # time: 2020-04-04 16:44 # user: lixun # filename: 基本的日期与时间转换 # description: 执行简单的时间转换,天到秒,小时到分钟的转换 # from datetime import timedelta from datetime import datetime def detetime_change(): a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c = a + b print(c.days) print(c.seconds / 3600) print(c.total_seconds() / 3600) def datetime_express(): a = datetime(2012, 9, 23) print(a + timedelta(days=10)) b = datetime(2012, 12, 21) d = b - a print(d.days) now = datetime.today() print(now) print(now + timedelta(days=-1,minutes=10)) # datetime 是会自动处理闰年的 a = datetime(2020, 3, 1) b = datetime(2020, 4, 3) print(a -b) print((a-b).days) c = datetime(2020,7,6) print((b-a).days) def main(): datetime_express() if __name__ == "__main__": main()
05e6c34510a23ccd50bc3ffbc42eb964e4810179
athinaangelica/Python-Programming-Exercises
/StrukDis_TuTam_1.py
1,133
4.09375
4
def adjacency_matrix(nodes, vertices): adj_mtx = [] for a in nodes: #for every element in list nodes adj_row = [] #create empty list for b in nodes: #for every element in list nodes if (a,b) in vertices or (b,a) in vertices: #if (a,b) or (b,a) is in list vertices adj_row.append(1) #add 1 to empty list adj_row else: adj_row.append(0) #add 0 to empty list adj_row adj_mtx.append(adj_row) #add row to result matrix for row in adj_mtx: #print each row print (row) node = input("Input nodes (use ',' to separate values):\n") #ask input v = node.rstrip().split(",") #strip return character (\n and \r) from string, then split string into several parts. splits marked by ',' v = [x.strip(' ') for x in v] #remove extra spaces from each element in list v vertex = input("Input vertices (use ' ' (space) to separate values: (ex: 1,2 2,3 3,3)\n") vertex = vertex.rstrip().split(" ") e = [] for pair in vertex: vert_pair = tuple(pair.split(",")) #create tuple from every pair in list vertex, ex. turns string "1,2" into tuple ('1','2') e.append(vert_pair) adjacency_matrix(v, e)
af9e5910cbf58985eb3636120fd119ce6e507a09
pkdism/leetcode
/july-leetcoding-challenge/d11-subsets.py
510
3.515625
4
""" Given a set of distinct integers, nums, return all possible subsets (the power set). """ class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: n = len(nums) ps = [] for binary in range(2**n): temp = binary val = [] pos = n-1 while temp > 0: if temp%2 == 1: val.append(nums[pos]) pos -= 1 temp //= 2 ps.append(val) return ps
d11603c5cdb65edf10c54cdb5fdd1e0877d5debf
tooskaocr/ocr-evaluation
/SpaceAlignment/SpaceAligner.py
3,427
3.625
4
import re import argparse from enum import Enum class MatchCase(Enum): """ Indicates match cases for LCS algorithm. """ NONE = 0 TARGET = 1 RETRIEVED = 2 BOTH = 3 # current characters match SPACE = 4 def alignFiles(targetPath, retrievedPath, outputPath): """ Scans two input files line by line and aligns the spaces of the retrived file with the target file. Assumes files contain the same number of lines. Writes the result in the file at outputPath. """ target = open(targetPath, 'rb') retrieved = open(retrievedPath, 'rb') output = open(outputPath, 'wb') for targetLine in target: retrievedLine = retrieved.readline() targetLine = targetLine.decode('utf-8') retrievedLine = retrievedLine.decode('utf-8') aligned = LCSAlign(targetLine, retrievedLine) output.write(aligned.encode('utf-8')) output.flush() output.close() retrieved.close() target.close() def LCSAlign(target, retrieved): """Drops all spaces from retrieved string and tries to insert spaces so as to maximize LCS match between the two strings.""" retrieved = re.sub(r' ', '', retrieved) match = [[MatchCase.NONE for i in range(len(retrieved)+1)] for j in range(len(target)+1)] longest = [[0 for i in range(len(retrieved)+1)] for j in range(len(target)+1)] for i in range(len(target)): for j in range(len(retrieved)): if target[i] == retrieved[j]: longest[i+1][j+1] = longest[i][j] + 1 match[i+1][j+1] = MatchCase.BOTH elif target[i] == ' ': longest[i+1][j+1] = longest[i][j+1] + 1 match[i+1][j+1] = MatchCase.SPACE elif longest[i+1][j] >= longest[i][j+1]: longest[i+1][j+1] = longest[i+1][j] match[i+1][j+1] = MatchCase.TARGET else: longest[i+1][j+1] = longest[i][j+1] match[i+1][j+1] = MatchCase.RETRIEVED result = u'' targetInd = len(target) retrievedInd = len(retrieved) while retrievedInd > 0: matchType = match[targetInd][retrievedInd] if matchType == MatchCase.BOTH: result = target[targetInd-1] + result targetInd -= 1 retrievedInd -= 1 elif matchType == MatchCase.SPACE: result = u' ' + result targetInd -= 1 elif matchType == MatchCase.TARGET: result = retrieved[retrievedInd-1] + result retrievedInd -= 1 elif matchType == MatchCase.RETRIEVED: targetInd -= 1 return result def main(): parser = argparse.ArgumentParser(description='Aligns spaces of a retrieved file with those of a target file.') parser.add_argument('targetPath', type=str, help='path of the file containing target text') parser.add_argument('retrievedPath', type=str, help='path of the file containing retrieved text') parser.add_argument('outputPath', type=str, help='path of the output file') args = parser.parse_args() alignFiles(args.targetPath, args.retrievedPath, args.outputPath) def testMain(): for i in range(1, 6): target = 'tests/b{}_target.txt'.format(i) retrieved = 'tests/b{}_ocred.txt'.format(i) output = 'tests/b{}_result.txt'.format(i) alignFiles(target, retrieved, output) if __name__=='__main__': main()
5ba21575835c13f037861c23eb09bc95573161ea
ranfysvalle02/e2e-game-offers
/data_generators/initial/e2e_training_data_generator.py
4,401
3.796875
4
# importing the necessary libraries. Install sklearn, pandas and numpy first if you don't already have them from sklearn.datasets import make_classification import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler # In[ ]: ''' Creating the dataset - a dataframe as "X" with all the data. "y" is the outcome field as an array Argument explanations: n_samples - rows n_features - number of fields/columns in the dataset n_informative - the number of fields that have a predictive relatinship with the outcome n_redundant - the number of fields that have a high level of colinearity or interrelationship with each other n_classes - the number of possible outcomes, or unique values in "y" n_clusters_per_class - the number of cohorts, or groups, within each possible outcome - used for clustering in feature engineering flip_y - the amount of random noise inserted into the dataset - .1 means 10% of the data is random noise ''' X, y = make_classification(n_samples=10000000, n_features=15, n_informative=14, n_redundant=0, n_classes=5, n_clusters_per_class=4, flip_y=0.1) print(X.shape, y.shape) # In[ ]: # Bringing the outcome field "y" into the dataframe and printing the result df = pd.DataFrame(np.c_[X, y]) df # In[ ]: # creating a list of field names and then mapping them to the dataframe my_columns = ["characterId", "historicalSpend", "nextRankIsRedStar", "shardsToNextRank", "totalEquipShardsLast7D", "totalEquipsLast7D", "totalPlayTimeLast7D", "weekDayOfPurchase", "grade", "level", "gear_tier", "shards", "stars", "redstars", "abilities", "offerId"] df.columns = my_columns # In[ ]: # df.describe gives us some descriptive statistics of the dataframe now with the new fieldnames to review df.describe() # In[ ]: ''' Here is the structure of the data that will be generated in our app and sent to our model for inference { "offerId": {"$choose": {"from": [1,2,3,4,5]}}, "characterId": {"$integer":{"min":1, "max":16}}, "historicalSpend": {"$integer":{"min":0, "max":200000}}, "nextRankIsRedStar": "$bool", "shardsToNextRank": {"$integer":{"min":30, "max":50}}, "totalEquipShardsLast7D": {"$integer":{"min":50, "max":150}}, "totalEquipsLast7D": {"$integer":{"min":70, "max":150}}, "totalPlayTimeLast7D": {"$integer":{"min":1, "max":2000}}, "weekDayOfPurchase": {"$integer":{"min":1, "max":7}}, "grade": {"$choose":{"from": ["A","B","C","D"]}}, "level": {"$integer":{"min":1, "max":80}}, "gear_tier": {"$integer":{"min":1, "max":15}}, "shards": {"$integer":{"min":1, "max":810}}, "stars": {"$integer":{"min":1, "max":6}}, "redstars": {"$integer":{"min":1, "max":7}}, "abilities": {"$integer":{"min":0, "max":26}} } ''' # In[ ]: # creating a dictionary to catalog the range of values for each field - referring to the cell above thisdict = { "offerId": (1,5), "characterId": (1,16), "historicalSpend": (0,200000), "nextRankIsRedStar": (0,1), "shardsToNextRank": (30,50), "totalEquipShardsLast7D": (50,150), "totalEquipsLast7D": (70,150), "totalPlayTimeLast7D": (1,2000), "weekDayOfPurchase": (1,7), "grade": (1,4), "level": (1,80), "gear_tier": (1,15), "shards": (1,810), "stars": (1,6), "redstars": (1,7), "abilities": (0,26) } # In[ ]: # rescaling our data in every field from it's current range to the range assigned in our dictionary for eachitem in thisdict: scaler = MinMaxScaler(feature_range=thisdict[eachitem]) df[[eachitem]] = scaler.fit_transform(df[[eachitem]]) # In[ ]: # getting rid of the decimal values - rounding them to the nearest integer df = df.round(0) # In[ ]: # changing the datatypes of our fields from decimal to integer df = df.apply(pd.to_numeric, downcast='integer') # In[ ]: # printing the dataframe to make sure everything looks correct df # In[ ]: # CHANGE THE PATH AND CSV FILE NAME TO WHATEVER YOU WANT - below is just an example. # If you don't keep index=False you'll have an extra field in your csv for it df.to_csv('/Users/andrew.chaffin/Downloads/trainingData.csv', index=False)
438554eee5446338e28ca25fb14f17ff74556b88
najuzilu/ucsd_algorithms
/Algorithmic_Toolbox/week3/assignment/6_maximum_number_of_prizes/different_summands.py
462
3.5
4
# Uses python3 import sys import math def optimal_summands(n): summands = [] k = int(-1/2 + math.sqrt(1/4 + 2 * n)) if k == 1: summands.append(n) return summands for each in range(1, k): summands.append(each) last_item = n - sum(summands) summands.append(last_item) return summands if __name__ == '__main__': input = sys.stdin.read() n = int(input) summands = optimal_summands(n) print(len(summands)) for x in summands: print(x, end=' ')
edcab377fe47ccda40631e5c4a906446972c0ca3
nicowjy/practice
/Leetcode/101对称二叉树.py
753
4.15625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # 对称二叉树 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def helper(root1, root2): if not root1 and not root2: return True if (not root1 and root2) or (not root2 and root1): return False if root1.val != root2.val: return False return helper(root1.left, root2.right) and helper(root1.right, root2.left) return helper(root, root)
8f3edd19079d0850590a054361ac1a68ff058bd6
onewns/TIL
/algorithm/leetcode/LinkedList/0024_SwapNodesInPairs.py
1,369
3.578125
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: # my style (new ListNode) 24ms 14.2MB ans = h = ListNode()while head: if head.next: n1 = head.val head = head.next n2 = head.val head =head.next h.next = ListNode(n2) h = h.next h.next = ListNode(n1) h = h.next else: n1 = head.val head = head.next h.next = ListNode(n1) # return ans.next # swap value 32ms 14MB cur = head while cur and cur.next: cur.val, cur.next.val = cur.next.val, cur.val cur = cur.next.next # return head # use loop 24ms 14.2MB root = prev = ListNode(None) prev.next = head while head and head.next: b = head.next head.next = b.next b.next = head prev.next = b head = head.next prev = prev.next.next # return root.next # use recursion 32ms 14.1MB if head and head.next: p = head.next head.next = self.swapPairs(p.next) p.next = head return p # return head
417e153bb8a8453850d066442cde6788a2f1f7fa
constantlearning/uri-exercises-resolution
/01-INICIANTE/Python/1041.py
336
3.796875
4
# -*- coding:utf-8 -*- numbers = map(float, input().split(" ")) x,y = numbers if x == y == 0: print("Origem") elif x == 0: print("Eixo X") elif y == 0: print("Eixo Y") elif x > 0 and y > 0: print("Q1" ) elif x < 0 and y > 0: print("Q2") elif x < 0 and y < 0: print("Q3") elif x > 0 and y < 0: print("Q4")
5ba07b80011d04651b50ce1ef87d3157a4728636
KOOKDONGHUN/trading
/python/005study_class4.py
1,077
4.09375
4
class Myclass: def __init__(self): # 생성자 // 객체의 생성과 동시에 자동으로 호출되는 메서드이다 // initialize의 약어 (초기화하다) print('create object!!') inst1 = Myclass() # create object!! name = 'kookdonghun' email = 'dh3978@naver.com' addr = 'Ilsan' class BusinessCard: def __init__(self, name, email, addr): # self를 쓰는 이유 일단은 반드시 함수의 첫번째 파라미터는 self를 써야한다 책에서 일단은 외우란다. self.name = name self.email = email self.addr = addr def print_info(self): print('-'*33) print(f'Name : {self.name}') print(f'E-mail : {self.email}') print(f'Address : {self.addr}') print('-'*33) try : member1 = BusinessCard() # TypeError: __init__() missing 3 required positional arguments: 'name', 'email', and 'addr' except : print('TypeError: __init__() missing 3 required positional arguments: \'name\', \'email\', and \'addr\'') member1 = BusinessCard(name, email, addr) member1.print_info()
619dd7ccb2600d2ca70eb6853c567bc67760d623
joelper/MS-E346
/modules/Option.py
5,181
3.546875
4
from typing import NamedTuple, Union import numpy as np class Option(NamedTuple): call: bool # true if call option, false if put american: bool # true if american option, false if european S: float # underlying asset price K: float # strike price sigma: float # standard deviation of the return for the stock price tau: float # time to maturity (T-t), in years r: float # annual interest rate q: float #dividend yield def monte_carlo_stock(option: Option, m: int, n: int) -> np.ndarray: # takes in an option and creates m Monte-Carlo price path simulations of the underlying, for n time-steps # mu is the drift of the underlying # initialize the stock price matrix and set the first value to be the value of the underlying S = np.zeros((m, n + 1)) S[:, 0] = option.S # delta_t is the length of the time steps, i.e. the time to maturity divided by the umber of steps delta_t = option.tau / n # simulate a matrix of returns returns = np.random.normal((option.r - np.square(option.sigma) / 2.) * delta_t, option.sigma * np.sqrt(delta_t), size=(m, n)) for j in range(1, n + 1): # start at 1 since we have S_0, and then simulate n time-steps S[:, j] = np.multiply(S[:, j - 1], np.exp(returns[:, j - 1])) return S def payoff(s: Union[float, np.ndarray], option: Option) -> Union[float, np.ndarray]: # returns the payoff for an american option given price of underlying is s if option.call: return np.maximum(s - option.K, 0) return np.maximum(option.K - s, 0) def Binary_Tree(option: Option, steps: int) -> float: # function that recursively finds the price of an American option assert (steps >= 0) delta_t = option.tau / steps up = np.exp(option.sigma * np.sqrt(delta_t)) down = 1 / up # probability of upwards movement p = (np.exp((option.r - option.q) * delta_t) - down) / (up - down) # calculate the discount rate per time step gamma = np.exp(-option.r * delta_t) return binary_tree_helper(gamma, p, option.S, up, down, option, steps) def binary_tree_helper(gamma: float, p: float, s: float, up: float, down: float, option: Option, steps: int) -> float: # helper function to calculate the option price # feed in the price if steps <= 0: # we have reached the end if option.call: return np.maximum(s - option.K, 0) return np.maximum(option.K - s, 0) # recursively find the price of the next step price_up = binary_tree_helper(gamma, p, s * up, up, down, option, steps - 1) price_down = binary_tree_helper(gamma, p, s * down, up, down, option, steps - 1) if option.american: # check if option is american if option.call: # check if call option return np.maximum(gamma * (p * price_up + (1 - p) * price_down), s - option.K) return np.maximum(gamma * (p * price_up + (1 - p) * price_down), option.K - s) # if it reaches here it is a european option return gamma * (p * price_up + (1 - p) * price_down) def longstaff_schwartz(option: Option, m: int, n: int) -> float: # uses the longstaff-schwartz algorithm to return the value of an american option delta_t = option.tau / n disc = np.exp(-option.r * delta_t) # initialize the value function cf = np.zeros((m, 1)) # simulate the stock price SP = monte_carlo_stock(option, m, n) # set the initial value of the value function to the payoff at maturity cf = payoff(SP[:, -1], option) # recursively backtrack the value of the option for j in range(n - 1, 0, -1): cf = cf * disc # only add feature functions for paths that are in the money indices = np.array([i for i in range(m) if payoff(SP[i, j], option) > 0]).reshape(-1, 1) X = feature_func(SP[indices, j], option) Y = cf[indices].reshape(-1, 1) if np.size(X) > 0: # regress the non-linear features of stock price and strike price onto the value function estimate = X.dot(np.linalg.lstsq(X, Y, rcond=None)[0]) pay = payoff(SP[indices, j], option).reshape(-1, 1) # set the value function to be equal to payoff if the payoff is higher than the estimated future value # of holding onto the option, otherwise let it remain as the discounted value function cf[indices] = np.where(pay > estimate, pay, cf[indices]) # calculate the exercise vs continuation values exercise = payoff(option.S, option) cont = np.mean(cf * disc) return np.maximum(exercise, cont) def feature_func(s: Union[float, np.ndarray], option: Option) -> np.ndarray: # takes in price of underlying and an option and returns a feature function sp = np.divide(s, option.K).reshape(-1, 1) # uses the feature functions suggested by Longstaff-Schwartz phi_0 = np.ones((np.size(sp), 1)) phi_1 = np.exp(-sp / 2) phi_2 = np.multiply(np.exp(-sp / 2), 1 - sp) phi_3 = np.multiply(np.exp(-sp / 2), 1 - 2 * sp + np.square(sp) / 2) return np.concatenate((phi_0, phi_1, phi_2, phi_3), axis=1)
3a8734c244cf83dee4183302c266cc0d68840261
JAntonioMarin/restApisFlaskPython
/Section2/46.py
734
3.765625
4
def divide(dividend, divisor): if divisor == 0: raise ZeroDivisionError("Divisor cannot be 0.") return dividend / divisor def calculate(*values, operator): return operator(*values) result = calculate(20, 4, operator=divide) print(result) def search(sequence, expected, finder): for elem in sequence: if finder(elem) == expected: return elem raise RuntimeError(f"Could not fund an element with {expected}.") friends = [ {"name": "Rolf Smith", "age": 24}, {"name": "Adam Wool", "age": 30}, {"name": "Anne PunSmith", "age": 27}, ] def get_friend_name(friend): return friend["name"] try: print(search(friends, "Bob Smith", get_friend_name)) except RuntimeError as e: print(e)
407113cb641bdd06d33a7adf768ab2dfa3ffb91f
WeiKunChina/CodingInterviews-Practice
/python/12.exist.py
1,713
3.5
4
class Solution(object): # 定义上下左右四个行走方向 directs = [(0, 1), (0, -1), (1, 0), (-1, 0)] def exist(self, board, word): """ 题目可以模拟为 DFS 的过程,即从一个方向搜索到底,再回溯上一个节点,沿另一个方向继续搜索,递归进行。 在搜索过程中,若遇到该路径不可能与目标字符串匹配的情况,执行剪枝,立即返回。 时间复杂度:O(3^k IJ)。 一次搜索完全部矩阵的时间复杂度为 O(IJ) ,共需要 3^ 次搜索。 空间复杂度:搜索过程中的递归深度不超过 KK ,因此系统因函数调用累计使用的栈空间占用 O(K) :type board: List[List[str]] :type word: str :rtype: bool """ for i in range(len(board)): for j in range(len(board[0])): if self.dfs(board, word, i, j, 0): return True return False def dfs(self, board, word, i, j, k): """ :param board: List[List[str]] :param word: str :param i: index :param j: index :param k: index :return: bool """ if i >= len(board) or i < 0 or j >= len(board[0]) or j < 0 or board[i][j] != word[k]: return False if k == len(word) - 1: return True tmp = board[i][j] board[i][j] = '/' result = self.dfs(board, word, i + 1, j, k + 1) or \ self.dfs(board, word, i - 1, j, k + 1) or \ self.dfs(board, word, i, j + 1, k + 1) or \ self.dfs(board, word, i, j - 1, k + 1) board[i][j] = tmp return result
38779fecf3d154f544b4e8785217f50948b7ed3d
msaitejareddy/Python-programs
/sep13/list.py
175
3.671875
4
list1=[1,2,3,4,5] print(list1) list2=['a','bc','def'] print(list2) list3=['sai','[s,d,f,g]'] print(list3) print(len(list1)) print(list2[2]) print(list2[2:]) print(list3[1])
398192f38525ab79e98fc1918b0a6a36a88857a1
enderquestral/Reed-CSCI121
/distance.py
251
3.53125
4
locx = float(input("Location x-coordinate? ")) locy = float(input("Location y-coordinate? ")) classx = float(input("Classroom x-coordinate? ")) classy = float(input("Classroom y-coordinate? ")) print( (((classx-locx)**2) + (classy - locy)**2) **0.5 )
f47a52a2d5ea15bf236f85ccbbd532ef97a19a53
ReillyNelson/Python-Practice
/FizzBuzz_Test.py
247
3.890625
4
__author__ = 'Reilly' x=range(1,101) for number in x: if number%3==0 and number%5==0: print ("FizzBuzz") elif number%3==0: print("Fizz") elif number%5==0: print("Buzz") elif number: print (number)
e2493bdb93e8e3f8fef5cd91cfecd1f299cdf6f9
Johnqiu123/PythonHighSkill
/PythonSkill/ObjectIterative2.py
840
3.890625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 25 13:17:55 2017 @author: Administrator 问题:如何使用生成器函数构造可迭代对象? 将该类的__iter__方法实现生成器函数,每次yield返回一个值 """ class PrimeNumbers: def __init__(self, start, end): self.start = start self.end = end def isPrimeNum(self, k): """judge a num whether is prime""" if k < 2: return False for i in xrange(2, k): if k % i == 0: return False return True def __iter__(self): """use iter method""" for k in xrange(self.start, self.end + 1): if self.isPrimeNum(k): yield k if __name__ == '__main__': for i in PrimeNumbers(1, 100): print i
7f8e6b9b244ac7603036697b1ee96967c94e1ba4
adamslab-ub/SCoPP
/environments.py
29,890
3.671875
4
"""This code contains environment parameters to be loaded for use by the SCoPP algorithm. New classes should be created and stored here for any new environments that the user wishes to use the algorithm on. Simply copy and paste one of the environments below and alter the values to your liking. Each class follows the same format and require the following attributes: starting_position: list of lists - Starting position (in geographical coordinates) for the robots. If only one position is given, all robots start at that position) boundary_points: list of lists - Vertices of the polygon which defines the entire survey area (in geographical coordinates). The vertices must be in the order which they are connected; either clockwise or counterclockwise. geo_fencing_holes: list of lists of lists - Vertices of the polygon which defines each discontnuity in the survey area (in geographical coordinates). The vertices must be in the order which they are connected; either clockwise or counterclockwise. robot_FOV: int, float - Downward field of view of the robots in degrees robot_operating_height: int, float - Height at which the robots will be flying robot_velocity: int, float - Velocity of the robots save_path: string - Directory for output data to be sent **Optional: UAV: int - used to store and choose between multiple UAV parameters for a single environment """ class Debugger: """Robot parameter Class for debugging. This is a simple polygon with a low total area to reduce computation time substantially, to make debugging much faster """ def __init__(self): self.starting_position = [[40.68251, -73.91134]] self.boundary_points = [[40.68251, -73.91134], [40.68250, -73.90935], [40.68173, -73.90935], [40.68176, -73.91138]] self.geo_fencing_holes = None self.robot_FOV = 150 # degrees self.robot_operating_height = 2 # meters self.robot_velocity = 10 # meters per second self.save_path = "Debug/" class VeryLargeLafayetteFLood: def __init__(self, UAV): self.starting_position = [[30.31600, -91.89790], [30.27491, -91.89797], [30.33890, -92.07346]] * 10 self.boundary_points = [[30.27665, -91.94890], [30.35969, -91.94836], [30.37132, -91.99706], [30.35519, -92.00796], [30.31936, -92.00466], [30.25465, -91.99934]] self.geo_fencing_holes = [] self.save_path = "VeryLargeLafayetteFlood/" if UAV == 0: # Testing self.robot_FOV = 105 # degrees self.robot_operating_height = 20 # meters self.robot_velocity = 10 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 110 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second if UAV == 5: # DJI Matrice 300 RTK (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second class SmallLafayetteFLood: def __init__(self, UAV=0, mode=False): self.boundary_points = [[30.2472, -92.151], [30.247, -92.1426], [30.2464, -92.1427], [30.2418, -92.1472], [30.243, -92.1501], [30.245, -92.1516]] self.starting_position = [[30.2436, -92.145]] if mode: # Optimal Specs self.robot_FOV = 14 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second # Optimal Specs self.robot_FOV = 21 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second if mode[0] == "cont": self.geo_fencing_holes = [] if mode[1] == "nopath": self.save_path = "SmallLafayetteFlood/no_discontinuities/no_path_planning/" elif mode[1] == "path": self.save_path = "SmallLafayetteFlood/no_discontinuities/path_planning/" elif mode[1] == "conres": self.save_path = "SmallLafayetteFlood/no_discontinuities/conflict_resolution/" elif mode[1] == "noconres": self.save_path = "SmallLafayetteFlood/no_discontinuities/no_conflict_resolution/" else: self.save_path = "SmallLafayetteFlood/no_discontinuities/" elif mode[0] == "disc": self.geo_fencing_holes = [ [[30.2465, -92.1481], [30.2454, -92.1474], [30.2446, -92.1486], [30.2452, -92.1498], [30.2463, -92.1494]] ] if mode[1] == "nopath": self.save_path = "SmallLafayetteFlood/discontinuities/no_path_planning/" elif mode[1] == "path": self.save_path = "SmallLafayetteFlood/discontinuities/path_planning/" elif mode[1] == "conres": self.save_path = "SmallLafayetteFlood/discontinuities/conflict_resolution/" elif mode[1] == "noconres": self.save_path = "SmallLafayetteFlood/discontinuities/no_conflict_resolution/" else: self.save_path = "SmallLafayetteFlood/discontinuities/" else: self.geo_fencing_holes = [] self.save_path = "SmallLafayetteFlood/" if UAV == 0: # Map Comparison self.robot_FOV = 105 # degrees self.robot_operating_height = 12 # meters self.robot_velocity = 10 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 110 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second if UAV == 5: # DJI Matrice 300 RTK (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 40 # meters self.robot_velocity = 10 # meters per second if UAV == 6: # Optimal Specs self.robot_FOV = 14 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second if UAV == 7: # Testing self.robot_FOV = 25 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second class MediumLafayetteFLood: def __init__(self, UAV=0, mode=False): self.boundary_points = [[30.24610, -92.03380], [30.24430, -92.04200], [30.23530, -92.04290], [30.23480, -92.03470], [30.24290, -92.03210]] self.geo_fencing_holes = [] if mode: if mode == "dispatchers_T1": self.starting_position = [[30.24686, -92.03722] for i in range(50)] # North self.save_path = "MediumLafayetteFlood/Dispatchers_Tests/dispatchers_T1_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second elif mode == "dispatchers_T2": self.starting_position = [[30.24686, -92.03722] for i in range(25)] # North self.starting_position.extend([30.23410, -92.03780] for i in range(25)) # South self.save_path = "MediumLafayetteFlood/Dispatchers_Tests/dispatchers_T2_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second elif mode == "dispatchers_T3": self.starting_position = [[30.24686, -92.03722] for i in range(16)] # North self.starting_position.extend([30.23410, -92.03780] for i in range(16)) # South self.starting_position.extend([30.24104, -92.04399] for i in range(18)) # East self.save_path = "MediumLafayetteFlood/Dispatchers_Tests/dispatchers_T3_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second elif mode == "dispatchers_T4": self.starting_position = [[30.24686, -92.03722] for i in range(12)] # North self.starting_position.extend([30.23410, -92.03780] for i in range(12)) # South self.starting_position.extend([30.24104, -92.04399] for i in range(12)) # East self.starting_position.extend([30.24086, -92.03034] for i in range(14)) # West self.save_path = "MediumLafayetteFlood/Dispatchers_Tests/dispatchers_T4_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second else: self.starting_position = [[30.24686, -92.03722]] self.save_path = "MediumLafayetteFlood/" if UAV == 0: # Testing self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 110 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second if UAV == 5: # DJI Matrice 300 RTK (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 40 # meters self.robot_velocity = 10 # meters per second class LargeLafayetteFLood: def __init__(self, UAV=0, mode=False): self.boundary_points = [[30.27560, -92.12400], [30.28350, -92.11940], [30.28590, -92.12670], [30.28990, -92.12330], [30.29000, -92.13870], [30.28180, -92.14530], [30.27760, -92.13980], [30.27460, -92.13650], [30.27330, -92.13050]] self.geo_fencing_holes = [] if mode: if mode == "height_T25": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Height_Tests/height_T25_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 25 # meters self.robot_velocity = 10 # meters per second elif mode == "height_T50": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Height_Tests/height_T50_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 10 # meters per second elif mode == "height_T75": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Height_Tests/height_T75_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 75 # meters self.robot_velocity = 10 # meters per second elif mode == "height_T100": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Height_Tests/height_T100_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second elif mode == "velocity_T2": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Velocity_Tests/velocity_T2_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 2 # meters per second elif mode == "velocity_T4": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Velocity_Tests/velocity_T4_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second elif mode == "velocity_T6": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Velocity_Tests/velocity_T6_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 6 # meters per second elif mode == "velocity_T8": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Velocity_Tests/velocity_T8_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 8 # meters per second elif mode == "velocity_T10": self.starting_position = [[30.24686, -92.03722] for i in range(50)] self.save_path = "LargeLafayetteFLood/Velocity_Tests/velocity_T10_" # DJI Matrice 300 RTK specs (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 10 # meters per second else: self.starting_position = [[30.24686, -92.03722]] self.save_path = "LargeLafayetteFLood/" if UAV == 0: # Testing self.robot_FOV = 14 # degrees self.robot_operating_height = 50 # meters self.robot_velocity = 4 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 110 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second if UAV == 5: # DJI Matrice 300 RTK (max flight range: 15km) self.robot_FOV = 14 # degrees self.robot_operating_height = 100 # meters self.robot_velocity = 10 # meters per second # 34.66786, -77.24813 class Lejeune: def __init__(self, UAV): self.starting_position = [[34.66653, -77.24645]] self.boundary_points = [[34.66607, -77.24677], [34.66631, -77.24859], [34.66723, -77.24967], [34.66780, -77.24813], [34.66734, -77.24578]] self.geo_fencing_holes = [] self.save_path = "Lejeune/" if UAV == 0: # Testing self.robot_FOV = 105 # degrees self.robot_operating_height = 12 # meters self.robot_velocity = 10 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 100 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second class Benning: def __init__(self, UAV): self.starting_position = [[32.38856, -84.81078]] self.boundary_points = [[32.38886, -84.81030], [32.39025, -84.81050], [32.39163, -84.81087], [32.39158, -84.81236], [32.38991, -84.81217], [32.38838, -84.81141], [32.38811, -84.81050]] self.geo_fencing_holes = [ [[32.38991, -84.81119], [32.38970, -84.81137], [32.38949, -84.81113], [32.38976, -84.81097]], [[32.39132, -84.81172], [32.39105, -84.81164], [32.39114, -84.81123], [32.39142, -84.81134]] ] self.save_path = "Benning/" if UAV == 0: # Testing self.robot_FOV = 105 # degrees self.robot_operating_height = 12 # meters self.robot_velocity = 10 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 110 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second class HollandNewYorkAgriculture: def __init__(self, UAV): self.starting_position = [[42.73562, -78.56849]] self.boundary_points = [[42.74420, -78.56982], [42.74389, -78.56535], [42.74190, -78.56518], [42.74184, -78.56110], [42.74342, -78.56089], [42.74307, -78.55728], [42.73639, -78.55698], [42.73655, -78.55432], [42.73236, -78.55441], [42.73239, -78.55634], [42.72981, -78.55655], [42.72892, -78.55886], [42.72990, -78.56535], [42.72899, -78.56552], [42.72920, -78.57031]] self.geo_fencing_holes = [ [[42.73690, -78.56894], [42.73694, -78.56673], [42.73501, -78.56781], [42.73499, -78.56939]], [[42.73631, -78.56379], [42.73629, -78.56265], [42.73523, -78.56310], [42.73535, -78.56382]], [[42.73502, -78.56567], [42.73542, -78.56499], [42.73453, -78.56444], [42.73418, -78.56512]] ] self.save_path = "Holland_NY/" if UAV == 0: # Testing self.robot_FOV = 105 # degrees self.robot_operating_height = 12 # meters self.robot_velocity = 10 # meters per second if UAV == 1: # DJI Phantom 4 Pro (max flight range: 7km) self.robot_FOV = 75 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second if UAV == 2: # Autel Robotics Evo (max flight range: 7km) self.robot_FOV = 94 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 15 # meters per second if UAV == 3: # Parrot Anafi (max flight range: 4km) self.robot_FOV = 84 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 12 # meters per second if UAV == 4: # Yuneec Mantis Q (max flight range: 1.5km) self.robot_FOV = 110 # degrees self.robot_operating_height = 8 # meters self.robot_velocity = 8 # meters per second class Baseline_Envirnonment: def __init__(self, solver): self.starting_position = [[37.53607, 15.06927]] self.boundary_points = [[37.53685, 15.06921], [37.53682, 15.07013], [37.53599, 15.07011], [37.53601, 15.06954], [37.53615, 15.06926], [37.53616, 15.06905], [37.53667, 15.06905]] self.geo_fencing_holes = [ [[37.53629, 15.06946], [37.53629, 15.06953], [37.53611, 15.06953], [37.53611, 15.06946]], [[37.53665, 15.06926], [37.53665, 15.06932], [37.53656, 15.06937], [37.53656, 15.06926]], [[37.53683, 15.06952], [37.53674, 15.06969], [37.53665, 15.06968], [37.53665, 15.06957], [37.53656, 15.06957], [37.53656, 15.06950]], [[37.53674, 15.06976], [37.53674, 15.06984], [37.53674, 15.06990], [37.53665, 15.06993], [37.53656, 15.06988], [37.53656, 15.06983], [37.53656, 15.06975]] ] self.robot_FOV = 5 # degrees self.robot_operating_height = 40 # meters self.robot_velocity = 4 # meters per second if solver == "SCoPP": self.save_path = "Baseline_Environment/QLB_runs/" elif solver == "baseline": self.save_path = "Baseline_Environment/baseline_runs/" class BrooklynInitialTest: def __init__(self, solver): self.starting_position = [[40.68304, -73.94323]] self.boundary_points = [[40.69613, -73.92880], [40.68223, -73.92601], [40.68091, -73.93760], [40.68744, -73.93893], [40.68650, -73.94743], [40.69229, -73.94863], [40.69287, -73.94297]] self.geo_fencing_holes = [[[40.69333, -73.93468], [40.69297, -73.93284], [40.69200, -73.93155], [40.69069, -73.93245], [40.69011, -73.93400], [40.69040, -73.93567], [40.69138, -73.93692], [40.69271, -73.93614]]] self.robot_FOV = 105 # degrees self.robot_operating_height = 12 # meters self.robot_velocity = 10 # meters per second if solver == "SCoPP": self.save_path = "Brooklyn_Init_Test/QLB_runs/" elif solver == "baseline": self.save_path = "Brooklyn_Init_Test/baseline_runs/" class NevadaExploration: def __init__(self): self.starting_position = [[39.38447, -116.54262]] self.boundary_points = [[39.33668, -116.49525], [39.33560, -116.59151], [39.34833, -116.61177], [39.36558, -116.61658], [39.40987, -116.58018], [39.41915, -116.56026], [39.44910, -116.51458], [39.45069, -116.50085]] self.geo_fencing_holes = None self.robot_FOV = 50 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second self.save_path = "NevadaExploration/" class OntarioWaterRescue: def __init__(self): self.starting_position = [[44.26976, -76.24346]] self.boundary_points = [[44.26204, -76.27156], [44.23279, -76.24362], [44.23144, -76.20018], [44.26818, -76.18695], [44.27679, -76.22847]] self.robot_FOV = 50 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second self.save_path = "OntarioWaterRescue/" class SanAntonioFarming: def __init__(self): self.starting_position = [[29.61902, -98.54841]] self.boundary_points = [[29.62933, -98.55423], [29.62933, -98.55100], [29.62697, -98.55099], [29.62689, -98.54249], [29.61861, -98.54207], [29.61857, -98.55438]] self.robot_FOV = 50 # degrees self.robot_operating_height = 10 # meters self.robot_velocity = 10 # meters per second self.save_path = "SanAntonioFarming/"
cf0adeae78e423cad26d5ed0a24d6ac62e439ecf
boknowswiki/mytraning
/lc/python/2095_delete_the_middle_node_of_a_linked_list.py
708
3.6875
4
# linked list # time O(n) # space O(1) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: l = self.get_len(head) if l == 1: return None mid = l//2 cur = head while mid-1 > 0: cur = cur.next mid -= 1 cur.next = cur.next.next return head def get_len(self, node): cnt = 0 while node: cnt += 1 node = node.next return cnt
ee59e48191c2db6c26eda3f945a5416468a9d3b3
wegar-2/number_theory_python
/tools/chinese_remainder_theorem.py
1,774
3.796875
4
import euclid_algorithm as ea def crt_find_number_two_modules(n1, r1, n2, r2): """ Given two moduli n1, n2 that are relatively prime and given the remainders for these moduli, respectively, r1 and r2 this function finds a natural number in between 0 and (n1*n2 - 1) that is congruent to r1 modulo n1 and r2 modulo n2 :param n1: first modulus, int type :param r1: remainder modulo n1, int type :param n2: second modulus, int type :param r2: remainder modulo n2, int type :return: least positive integer that satisfies the condition """ # ---------- 1. input validation ---------- # 1.1. check if n1, r1, n2, r2 are integers if not isinstance(n1, int) or not isinstance(n2, int) or not isinstance(r1, int) or not isinstance(r2, int): raise Exception("One of the function parameters is not of integer type...") # 1.2. check if the values passed are in the allowed ranges: n1, n2 if n1 <= 1 or n2 <= 1: raise Exception("One of the function parameters n1, n2 is not at least 2!") # 1.3. check if the values passed are in the allowed ranges: r1, r2 if not (0 <= r1 < n1) or not (0 <= r2 < n2): raise Exception("One of the function parameters r1, r2 is out of the allowed ranges - cf. n1, n2 values!") # ---------- 2. find the number satisfying the required condition ---------- # 2.1. run the extended Euclid's algorithm if n1 <= n2: temp = n1 n1 = n2 n2 = temp x, y, d = ea.extended_euclid_algorithm(m=n1, n=n2) if d != 1: raise Exception("The parameters n1 and n2 are not coprime! ") # 2.2. calculate the value that satisfies the required condition using x, y directly and return n0 = r2*n1*x + r1*n2*y return n0 % (n1*n2)
efb48047a3f4cc3cd09606926750d5af94700a94
jaeehooon/baekjoon_python
/단계별로 풀어보기/9. 수학 2/[1978] 소수 찾기.py
469
3.625
4
import sys def find_decimal(num): cnt = 0 for i in range(1, num+1): if num % i == 0: cnt += 1 if cnt > 2: return False else: return True if __name__ == "__main__": num = int(sys.stdin.readline().rstrip("\n")) num_list = list(map(int, sys.stdin.readline().rstrip('\n').split())) cnt = 0 for i in num_list: if i != 1: if find_decimal(i): cnt += 1 print(cnt)
03f015eb17db832cb6be4b9ab4743f872c38f709
JakeRivett31/Year9DesignPythonJR
/Unit 1 Project/SleepCalc2.py
979
3.515625
4
from tkinter import * import tkinter as tk root = tk.Tk() root.title("Sleep Calculator") root.geometry("600x450") root.configure(bg="#001245") nameQuestion = tk.Label(root, text="What is your name?", font = ('Avenir',15), bg="#001245", fg="#0068f0").grid(row=0, padx=(80, 50)) e1 = Entry(root) e1.grid(row=0, column=1) def getName (): name = e1.get() print(name) button1 = tk.Button(text="Submit", command=getName) button1.grid(row=0,column=2) age = tk.Label(root, text="How old are you?", font = ('Avenir',15), bg="#001245", fg="#0068f0").grid(row=1, pady=10, padx=(80, 50)) agevariable = StringVar(root) agevariable.set("8") # default value ageDropdown = OptionMenu(root, agevariable, "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18") ageDropdown.grid(row=1, column=1) def getAge (): age = agevariable.get() print(age) button2 = tk.Button(text="Submit", command=getAge) button2.grid(row=1,column=2) root.mainloop()
9067bb04f141ad48133d8ff8cebc06274845b76d
byxm/learn-python
/function/basic-concept/f5.py
291
3.5
4
# 默认参数 def personInfo(name, age, sex, school, lessons = '数理化'): print(name + str(age) + sex + school + lessons) personInfo('席梦', 22, '男', '希望小学', '语数外') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') personInfo('simone', 17, '男', '希望小学')
9dafd57b71478ad0b546efb8cb3266ff7d279d27
farhanpro/Python_Workshop
/functions/Fahrenheit_converter.py
189
4.15625
4
def fahrenheit(fahrenheit = int(input("Enter the Temprature in Fahrenheit : "))): return print("The temprature when converted into Celsius will be :",(fahrenheit-32)*5/9) fahrenheit()
815b41ef0803117c0515ff0b7c080bed63dbd1eb
Aasthaengg/IBMdataset
/Python_codes/p02265/s861967074.py
416
3.53125
4
from collections import deque n = int(input()) output = deque() for i in range(n): li = input().split(' ') if(li[0] == 'insert'): output.appendleft(li[1]) elif(li[0] == 'deleteFirst'): output.popleft() elif(li[0] == 'deleteLast'): output.pop() elif(li[0] == 'delete'): try: output.remove(li[1]) except: pass print(' '.join(output))
7dbd3cf2752f03d1ca54e729fc3dd349ac3dc0b0
Par1Na/Interview-Question
/9.py
288
3.96875
4
# Interview-Question size = int(input("Enter the size of List: ")) List = [] for i in range(size): List.append(int(input("Enter the element " + str(i + 1) + " in the List: "))) k = int(input("Enter the value of K: ")) print(sorted(List)[k-1])
a89bf48b546c6bae69103e0c578c26aa5fbbacec
frclasso/turma1_Python3_2018
/cap09/exercicios/exercicio_9_31.py
353
3.640625
4
#!/usr/bin/env python3 """Criem um programa que corrija o da listagem 9.20 de forma a verificar se “z” existe e é um diretório. """ import os.path if os.path.isdir("z"): print("O diretório z existe.") elif os.path.isfile("z"): print ("z existe, mas é um arquivo e não um diretório.") else: print("O diretório z não existe.")
1b8447a944eb05e2c8dfc8c574bc60918c0a6214
HugoNgai/Leetcode
/Code/valid_palidrome.py
232
3.671875
4
#!/usr/bin/env python # encoding: utf-8 class Solution: def isPalindrome(self, s: str) -> bool: import re res = ''.join(re.findall(r'[a-zA-Z0-9]+', s)) res = res.lower() return res == res[::-1]
8d901e286cedf5bcf9257c8ad8ba3318dd55b63a
xM4Rz/Password-Cracker
/PassCrack.py
10,768
4.125
4
''' Project 9 CSE 231 -Prompts use to make a selection of given choices -if users chooses first selection, passwords are cracked from given text files by forming a hash and crossreferencing it with hashes create from common passwords -if the user chooses the second, common words within passwords are found by inputting common name, phrases, and words text files and cross referencing them with passwords from a given text file -if the third option is chosen, the user can input a password and get its entropy returned -the user can select to exit the program ''' from math import log2 from operator import itemgetter from hashlib import md5 from string import ascii_lowercase, ascii_uppercase, digits, punctuation def open_file(message): try: #try unless it gets error file = input(message) #get input name of file if file == "": #default if user hits enter f = open('pass.txt') else: f = open(file) #open file based on input #print() return f #return file pointer except IOError: #if an error happens (ioerror) print("File not found. Try again.") return open_file(message) #run function again with same message ''' takes message as input for prompt returns file pointer of inputted file name ''' pass def check_characters(password, characters): for ch in password: #for each character in password string if ch in characters: #if char is in other string return True return False ''' takes a password and strings of characters checks if the password has characters that match the ones given returns true or false ''' pass def password_entropy_calculator(password): #check if pass has uppercase letters uppercase = check_characters(password, ascii_uppercase) #check if pass has lowercase letters lowercase = check_characters(password, ascii_lowercase) #check if pass has numbers(digits) nums = check_characters(password, digits) #check if pass has special chars (punctuation) specials = check_characters(password, punctuation) n = 0 #declare n to 0 l = len(password) #get length of password if password == '': #return entropy of 0 if password is empty string return 0 #check different possibilities of password and get respective N value elif nums and not uppercase and not lowercase and not specials: n = 10 elif punctuation and not uppercase and not lowercase and not nums: n = 32 elif punctuation and not uppercase and not lowercase and nums: n = 42 elif lowercase and not uppercase and not specials and not nums: n = 26 elif uppercase and not lowercase and not specials and not nums: n = 26 elif uppercase and lowercase and not specials and not nums: n = 52 elif lowercase and not uppercase and not specials and nums: n = 36 elif uppercase and not lowercase and not specials and nums: n = 36 elif lowercase and not uppercase and specials and not nums: n = 58 elif uppercase and not lowercase and specials and not nums: n = 58 elif lowercase and not uppercase and specials and nums: n = 68 elif uppercase and not lowercase and specials and nums: n = 68 elif lowercase and uppercase and nums and not specials: n = 62 elif lowercase and uppercase and specials and not nums: n = 84 elif lowercase and uppercase and specials and nums: n = 94 #calculate entropy, round to 2nd decimal, and return as float return float(round(l*log2(n), 2)) ''' takes a password as input calculates entropy of password by checking characters within it and length return the calculated entropy rounded to the 2nd decimal as a float ''' pass def build_password_dictionary(fp): pass_dict = dict() #declare dictionary rank = 0 #declare rank to 0 for line in fp: #iterate for each line in text file password = line.strip() #strip extra md5_hash = md5(password.encode()).hexdigest() #get hash value entropy = password_entropy_calculator(password) #get entropy rank+=1 #increment rank #add tuple to dict with hash as key pass_dict[md5_hash] = (password, rank, entropy) return pass_dict #return dict ''' takes a file pointer as input iterates through each line in file and creates a hash from each word increments rank each time to rank hashes gets entropy from calling other function returns a dictionary with hash as the key, and a tuple of (password, rank, entropy) ''' pass def cracking(fp,hash_D): list_of_tups = [] #initalize list cracked_count = 0 #declare variables to 0 uncracked_count = 0 for line in fp: #iterate for each line in file line = line.split(':') #split the line at colons if line[0] in hash_D: #if the hash (line[0]) is in hash dictionary p_hash = str(line[0]) #set has as a string password = hash_D[p_hash] #get password from hash dict password = password[0] #specify password from tuple entropy = password_entropy_calculator(password) #get entropy list_of_tups.append((p_hash, password, entropy)) #append tuple cracked_count +=1 #iterate count of cracked hashes else: #if hash isnt cracked uncracked_count+=1 #iterate uncracked counts list_of_tups = sorted(list_of_tups, key=itemgetter(1)) #sort list by pass return (list_of_tups, cracked_count, uncracked_count) #return tuple ''' takes file pointer and hash dictionary as input creates a list of tuples of cracked hashes with their password and entropy returns sorted list by password name alphabetically, along with the amount of hashes cracked and uncracked, all within a tuple ''' pass def create_set(fp): word_set = set() #declare set for line in fp: #iterate for line in file if line.strip() not in word_set: #remove excess and check if in set word_set.add(line.strip()) #add to set else: continue return word_set #return set ''' takes file pointer as inpute creates a set from words in the file with no duplicates returns the set ''' pass def common_patterns(D,common,names,phrases): new_D = dict() #declare dictionary for key in D: #iterate for each key password = D[key] password = password[0].lower() #get password and set to lower s = set() #declare set s.clear() #empty set for word in common: #iterate for each word in file (line) if word.lower() in password: #check if word is in current password s.add(word.lower()) #add lowercase version of word to set for word in names: if word.lower() in password: s.add(word.lower()) for word in phrases: if word.lower() in password: s.add(word.lower()) s = list(s) #change set to a list s = sorted(s) #sort the list alphabetically new_D[password] = s #add to dictionary with password as key return new_D #return dictionary ''' takes dictionary with password data along with common words, names, and phrases txt file pointers iterates through each password from password dictionary and finds common words names and phrases that are in that password by iterating through the text files adds common words phrases and names to sorted list and appends to new dict returns new dict with password being the key ''' pass def main(): '''Put your docstring here''' BANNER = """ -Password Analysis- ____ , =, ( _________ | =' (VvvVvV--' |____( https://security.cse.msu.edu/ """ MENU = ''' [ 1 ] Crack MD5 password hashes [ 2 ] Locate common patterns [ 3 ] Calculate entropy of a password [ 4 ] Exit [ ? ] Enter choice: ''' print(BANNER) #display banner while True: #main loop i = int(input(MENU)) #take user input while i != 1 and i != 2 and i != 3 and i != 4: #misinput handle loop print('Error. Try again.') i = int(input(MENU)) if i == 1: #if input is 1 #get file pointers fp = open_file('Common passwords file [enter for default]: ') h = open_file('Hashes file: ') #get hash dictionary from fp hash_D = build_password_dictionary(fp) #get cracked data tuple cracked = cracking(h, hash_D) #get tuple list from cracked tuple tup_list = cracked[0] #display data print("\nCracked Passwords:") for tup in tup_list: print('[ + ] {:<12s} {:<34s} {:<14s} {:.2f}' .format('crack3d!', tup[0], tup[1], tup[2])) print('[ i ] stats: cracked {:,d}; uncracked {:,d}' .format(cracked[1], cracked[2])) if i == 2: #get file pointers fp = open_file('Common passwords file [enter for default]: ') ep = open_file('Common English Words file: ') np = open_file('First names file: ') pp = open_file('Phrases file: ') #get dictionary d = build_password_dictionary(fp) #get sets word_set = create_set(ep) name_set = create_set(np) phrase_set = create_set(pp) #create common word dict common_dict = common_patterns(d, word_set, name_set, phrase_set) #print phrases print("\n{:20s} {}".format('Password', 'Patterns')) #given code for printing for k,v in common_dict.items(): print("{:20s} [".format(k),end='')# print password print(', '.join(v),end=']\n') # print comma separated list if i == 3: inp = input('Enter the password: ') #take string input entropy = password_entropy_calculator(inp) #get entropy #print entropy print('The entropy of {} is {}'.format(inp, entropy)) if i == 4: break #exit ''' uses functions to create user input loop to crack passwords, get password entropy, and find common phrases in passwords ''' pass if __name__ == '__main__': main()
96885b22d768db26c3a1857f679fae17bb87d119
Chalmiller/competitive_programming
/python/algorithms/sliding_window/string_anagrams.py
364
3.65625
4
def find_string_anagrams(str, pattern): result_indexes = [] match = 0 win_length = len(pattern) counter_dict = {} for s in pattern: if s not in counter_dict: counter_dict[s] = 0 counter_dict[s] += 1 for win_start in range(len(str) - win_length + 1): sub_str = str[win_start : win_start + win_length] return result_indexes
439ea8babb5822ddc617f120129386bf05579e8e
Dzenis-Pepic/OOP-zadatak
/oop.py
1,873
4.4375
4
#1. Create a Vehicle class with max_speed and mileage instance attributes. class Vehicle: def __init__(self,max_speed,mileage): self.max_speed=max_speed self.mileage=mileage #2. Create a Vehicle class without any variables and methods. class Vehicle1: pass #3. Create a child class Bus that will inherit all of the # variables and methods of the Vehicle class and display class attributes. class Bus(Vehicle): def __init__(self,max_speed,mileage): super().__init__(max_speed,mileage) #4. Create a Bus class that inherits Vehicle class. # Vehicle class must have a seating_capacity method implemented. # Give the capacity argument of Bus.seating_capacity() a default value of 50. class Vehicle2: def __init__(self,max_speed,mileage,capacity): self.max_speed=max_speed self.mileage=mileage self.capacity=capacity def seating_capacity(self): return self.capacity class Bus2(Vehicle2): def __init__(self,max_speed,mileage,capacity=50): super().__init__(max_speed,mileage,capacity) #5. Define a class attribute color with a default value of white. # I.e. Every Vehicle should be white. class Vehicle3: def __init__(self,max_speed,mileage,color='white'): self.max_speed=max_speed self.mileage=mileage self.color=color #Create a Bus child class that inherits from the Vehicle class. #The default charge of any vehicle is seating capacity * 100. #If Vehicle is Bus instance, we need to add an extra 10% #on full fare as a maintenance charge. #So the total fare for Bus instance will become #the final amount = total fare + 10% of the total fare. #The Bus seating capacity is 50, so the final fare amount should be 5500. #Implement fare method on Vehicle class and do necessary #modifications on Bus class for the same method. class Bus3(Vehicle)
6333417e234d01bd560dce164281c6eddefece4b
aks789/python-code-basics-to-expert
/dictionary.py
545
3.65625
4
my_dict = {'a' : 'akriti', 'a' : 'akshay'}; print(my_dict); print(my_dict['a']); samp_dict = {'k1': 1 , 'k2': [0,1,2] , 'k3' : {'insideKey':100}} print(samp_dict['k3']['insideKey']) samp_dict['k4'] = 'New Val'; print(samp_dict.items()) print(samp_dict.values()) ## Tuples t=(1,2,3) my_list=[1,2,3] print(type(t)) ## Sets myset=set(); myset.add(1); myset.add(2); myset.add(1); print(myset) my_list=[1,1,2,2,3,3]; my_set=set(my_list) print(my_set); a = 1 > 2 print(a) print(type(a)) b = None my_set = set([1,1,2,3]) print(my_set)
0662429c7b9fc9bf46536fc8eb72e7bb885ce90a
simran135/CSSteminars
/CS2/Lesson1/quiz1.py
291
3.625
4
print("----------------") print("QUIZ TIME:\n") # Do the types match? Will these all compile? print(3 * 2) print(3 * "abc") print(3 + 2) print("abc" + "def") print(3 + "def") print("Precedence:") print(2+3*4) print(5+4%3) print(2**3*4) print() print("Associativity:") print(5-4-3)
13cebb4b4a6d5561617b2049d664d0916d5b441a
mango0713/Python
/20191210-숫자 맞추기.py
732
3.5625
4
import random def make_question() : a = random.randint(1, 20) b = random.randint(1, 20) op = random.randint(1, 3) q = str(a) if op == 1 : q = q + "+" if op == 2 : q = q + "-" if op == 3 : q = q + "*" q = q + str(b) return q sc1 = 0 sc2 = 0 for x in range (10) : q = make_question() print (q) r = int(input("=")) if eval(q) == r : print("정답") sc1 = sc1 + 1 else : print("틀였오.....") sc2 = sc2 + 1 print ("정답 : ", sc1, "오답 :", sc2)
195e0d2a73ad44dc4810f57a54461ff684d175b0
bhudnell/Past-Work
/Python/binaryClass/binaryClass.py
5,195
4.1875
4
""" Brendon Hudnell Section Leader: Will Zielinski 3/2/16 ISTA 350 Hw5 Contains the Binary class, which contains operator overload magic methods used to do basic binary integer arithmetic. """ class Binary: def __init__(self, bin_string=""): """ Takes a string of no more than 16 bits, converts it to a list, then pads the list to 16 elements by repeating the leftmost digit. bin_string: a string of up to 16 bits. (Only numbers 0 and 1) """ if len(bin_string) > 16: raise RuntimeError ("Binary: string longer than 16 bits") for char in bin_string: if char != '0' and char != '1': raise RuntimeError ("Binary: string contains values outside 0 and 1") self.num_list = list(bin_string) for i in range(len(self.num_list)): self.num_list[i] = int(self.num_list[i]) self.pad() def pad(self): """ Pads num_list by repeating the leftmost digit until it contains 16 elements. """ pad_num = self.num_list[0] if len(self.num_list) > 0 else 0 while len(self.num_list) < 16: self.num_list = [pad_num] + self.num_list def __repr__(self): """ Shows how the Binary class instance is represented when printed. """ string = "" for num in self.num_list: string += str(num) return string def __add__(self,other): """ Overloads the + operator to add two binary numbers together. other: the Binary instance to be added to self returns: the sum of the two Binary instances added together """ result = [] carry = 0 for i in range(15,-1,-1): bit_sum = self.num_list[i] + other.num_list[i] + carry result.insert(0, bit_sum%2) carry = int(bit_sum>1) if self.num_list[0] == other.num_list[0] != result[0]: raise RuntimeError ("Binary: overflow") string = "" for num in result: string += str(num) return Binary(string) def __neg__(self): """ Returns a new Binary instance equal to -self """ string = "" for i in range(len(self.num_list)): string += str((self.num_list[i] + 1)%2) return (Binary(string) + Binary("01")) def __sub__(self, other): """ Overloads the - operator to subtract one binary number from another. other: the Binary instance to be subtracted from self returns: the difference of the two Binary instances """ result = [] carry = 0 for i in range(15,-1,-1): bit_diff = (self.num_list[i] - other.num_list[i]) - carry result.insert(0, abs(bit_diff%2)) carry = int(bit_diff<0) if self.num_list[0] != other.num_list[0] and self.num_list[0] != result[0]: raise RuntimeError ("Binary: overflow") string = "" for num in result: string += str(num) return Binary(string) def __int__(self): """ Returns the decimal value of the Binary instance. """ sum = 0 bin_index = 0 if self.num_list[0] == 1: test = -(self + Binary("01")) for i in range(15,-1,-1): sum += test.num_list[bin_index]*2**i bin_index += 1 sum = -1 - sum else: test = self for i in range(15,-1,-1): sum += test.num_list[bin_index]*2**i bin_index += 1 return sum def __eq__(self, other): """ Overloads the == operator to determine if two Binary instances are equal. other: the Binary instance to be compared to self returns: True if self and other are equal, False otherwise """ for i in range(len(self.num_list)): if self.num_list[i] != other.num_list[i]: return False return True def __lt__(self, other): """ Overloads the < operator to determine if one Binary instance is less than the other. other: the Binary instance to be compared to self returns: True if self is less than other, False otherwise """ if self.num_list[0] == 1 and other.num_list[0] == 1: for i in range(16): if self.num_list[i] > other.num_list[i]: return False elif self.num_list[i] < other.num_list[i]: return True return False elif self.num_list[0] == 1 and other.num_list[0] == 0: return True elif self.num_list[0] == 0 and other.num_list[0] == 1: return False else: for i in range(16): if self.num_list[i] < other.num_list[i]: return True return False def __abs__(self): """ Returns a new Binary instance that is the absolute value of self """ if self.num_list[0] == 0: return Binary(repr(self)) return Binary(repr(-self))
2d8a4ec86718d281bc6e097164f7e744b29980d5
erin-biard/TP11
/Matrice.py
1,061
3.71875
4
class Matrice: def __init__(self,data=[]): self.__D = data def getD(self): return self.__D def __add__(self, m2): for i in range(0,4): newMat = self.__D[i] + m2.__D[i] print(newMat,end=' ') def __sub__(self, m2): for i in range(0,4): newMat = self.__D[i] - m2.__D[i] print(newMat,end=' ') def __mul__(self, m2): m = [] if len(self.__D[0]) != len(m2.__D): return False for i in range (len(self.__D)): ligne = [] for j in range(len(m2.__D[0])): #pour chaque colonne de m2 for k in range (len(self.__D[0])): element = self.__D[i][j] * m2.__D[i][j] element += self.__D[i][k] * m2.__D[k][i] ligne.append(element) m.append(ligne) return m if __name__== '__main__': data1 = [1,2,3,2] data2 = [1,0,2,1] m1 = Matrice(data1) m2 = Matrice(data2) m3 = m1 + m2 print(" ") m4 = m1 - m2 m5 = m1*m2
df672c118e479c3938746d6a9815e0f536b17709
Renittka/Web_2020
/week8/problems/informatics/while/B.py
287
3.921875
4
# Дано целое число, не меньшее 2. Выведите его наименьший натуральный делитель, отличный от 1. from math import pow a = int(input()) i = 2 while i < a+1: if a % i == 0: print(i) break i += 1
c1f462a7354819e316bce955ebca372a2e3f9fab
johnsjc/reverse-eng
/bomb/python/phase6.py
2,068
3.546875
4
#!/usr/bin/python # Reverse engineering phase 6 import sys class Node(object): def __init__(self, number, value, next_node): self.number = number self.value = value self.next_node = next_node nodes = [ Node(1, 0x0fd, None), Node(2, 0x2d5, None), Node(3, 0x12d, None), Node(4, 0x3e5, None), Node(5, 0x0d4, None), Node(6, 0x1b0, None) ] for i in range(1, 6): nodes[i - 1].next_node = nodes[i] def explode_bomb(): return False def phase_6(answer): # local_vars: # _n34 = pointer to node 1 in linked list # _n18 = pointer to num array # _n38 = index nums = [int(x) for x in answer.split()] # Check to see if the input is 6 unique numbers # in the range [1, 6] for i in range(6): if (nums[i] - 1) < 0 or (nums[i] - 1) > 5: explode_bomb() while (i + 1) <= 5: if nums[i] == nums[i + 1]: explode_bomb() i += 1 # local vars: # _n30 = ? # _n3c = sorted nodes # Order the nodes according to our input. # e.g. an input of 1 4 5 6 2 3 # results in [node1, node4, node5, node6, node2, node3] sorted_nodes = [] for i in range(6): node_pos = 1 while node_pos < nums[i]: node_pos += 1 # array is zero-indexed sorted_nodes.append(nodes[node_pos - 1]) # Link up the nodes in the sorted list for i in range(1, 6): sorted_nodes[i - 1].next_node = sorted_nodes[i] # final check - are the nodes in descending order? for i in range(5): if sorted_nodes[i].value < sorted_nodes[i + 1].value: return False return True def solve(): import itertools for poss in itertools.permutations([1, 2, 3, 4, 5, 6]): answer = " ".join([str(x) for x in poss]) if phase_6(answer): return answer if __name__ == "__main__": answer = solve() if answer: print("Bomb defused.\n") print("Answer: {}".format(answer))