blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2ee2bb41ea1d31f6a7f55c30e38d1355afc8f8ae
tranvanquan1999/k-thu-t-l-p-tr-nh
/th24.py
235
3.578125
4
# viết chương trình nhập số tự nhiên n>0, in ra màn hình các số tự nhiên giảm dần ừ n đến 0 mỗi kí tự in trên một hàng n=int(input("nhap so tu nhien n>0:")) while n>=0: print(n); n=n-1;
dcde41bc5a615f0e5d5325c0d4a203bbd727de5f
Enigmamemory/submissions
/7/intro-proj1/Steven-Richard/BESTPOKEDEX.py
2,899
3.546875
4
def pokedexreader(): ''' reads the source code of a bulbapedia to extract data ''' sourcecodedata=open("Pokedex").readlines() codedata=[] pokemondata=[] pokedexnumber=0 pokedexname="" onedigitcase="" for x in sourcecodedata: if '<span class="plainlinks"><a href="/wiki/' in x: pokedexnumber=x.find("title") + 7 pokemondata += [x[pokedexnumber:pokedexnumber+3]] pokedexname=x.find("_") pokemondata += [x[45:pokedexname]] if '<td style="background:#' in x: onedigitcase= x[-4:-1].split() if onedigitcase[0]==">": pokemondata += x[-3:-1].split() else: pokemondata += x[-4:-1].split() if "</td></tr>" in x: codedata.append(pokemondata) pokemondata=[] return codedata pokedexreader=pokedexreader() #[[#,Name,HP,ATK,DEF,SP.ATK,SP.DEF,SPE],[ def pokedexmod(): ''' Includes the BST and the AVG stats ''' pokedexmod=[] for x in pokedexreader: sum=[int(x[2])\ +int(x[3])\ +int(x[4])\ +int(x[5])\ +int(x[6])\ +int(x[7])] pokedexmod.append(x+sum+[sum[0]/6]) return pokedexmod pokedexmod=pokedexmod() #[[#,Name,HP,ATK,DEF,SP.ATK,SP.DEF,SPE,BST,AVG],[ def pokemovesdictionary(): ''' Creates a dictionary of viable moves for the pokemon ''' d={} datas=open("Viable Moves").readlines() data=[] do=False i=0 for x in datas: data.append(x.strip().split()) for y in pokedexmod: while do == False and i<len(data): if [y[1].lower()+":", '{']==data[i]: finder = i do == True elif len(data[i]) > 2: if [y[1].lower()+":",'{'] == [data[i][0]+" "+data[i][1],'{']: finder = i do == True i+=1 do = False d[y[1]]= data[finder+1][1][2:].split('":1,"') d[y[1]][-1]=d[y[1]][-1][:-5] d[y[1]]=" ".join(d[y[1]]).upper() finder = 0 i=0 return d movesdictionary=pokemovesdictionary() countingmoves=movesdictionary.values() def countmoves(): result=[] result2=[] for x in countingmoves: result.append(x.split(" ")) for x in result: result2 += x d={} for x in result2: if x not in d: d[x]=1 else: d[x]+=1 return result2 countmoves=countmoves() def abilitycheck(): data=open("Abilities").readlines() result=[] bigresult=[] tinyresult="" for x in data: result.append(x[3:].strip().split("/t")) for x in result: while "\t" not in x: x=x.replace("\t",",",3)
0601ecfe7c3c14feefb74c06374483d34302343d
Temitope-A/movietopics
/reviewmovies.py
1,061
3.53125
4
def review(movie): from names import keys, current_dir import os title = movie.title year = str(movie.year) print('M > Insert an integer between -3 (value totally on the left)' 'and 3 (value totally on the right)') att = {} for key in keys: flag = 0 while flag == 0: att['key'] = input('M < {}: '.format(key)) try: value = int(att['key']) except: print('M > Invalid input, insert an integer') else: if abs(value) <= 3: flag = 1 else: print('M > Value out of range, input must be in [-3,3]') f = open(current_dir + '/Reviews/' + title + '(' + year + ').txt', 'w') for key in keys: f.write(key + ' ' + att['key'] + '\n') f.close() movie.att = att movie.reviewed = 1 movie.sync = 0 path = current_dir + '/.Sync/' + title + '(' + year + ').txt' if os.path.exists(path) is True: os.unlink(path) return()
e7ce5c6822b45d062cc40acae49968e31c710e72
summercake/Python_Jose
/12.For.py
643
3.90625
4
# # for item in object: # statements to do stuff # l = [1, 2, 3, 4, 5] for v in l: print(v) for num in l: if num % 2 == 0: print(num) else: print('{x} is a odd number'.format(x=num)) print('%s is a odd number' % num) list_num = 0 for num in l: list_num += num print(list_num) s = 'this is a string!' for l in s: print(l) tup = (1, 2, 3, 4, 5) for t in tup: print(t) l = [(2, 4), (6, 8), (10, 12)] for tup in l: print(tup) for (t1, t2) in l: print(t1) d = {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4} for item in d: print(item) for (k, v) in d.items(): print(k) print(v)
e443d0fe759f3929b7859def9d0db338f13021d1
schlumpyj/Smart-Thermostat
/components/servoControl.py
1,044
3.546875
4
import RPi.GPIO as GPIO from time import sleep class ServoControl(object): SERVO_UP_PIN = 3 SERVO_DOWN_PIN = 5 def __init__(self): GPIO.setmode(GPIO.BOARD) self.servoUp = self.addServo(self.SERVO_UP_PIN) self.servoDown = self.addServo(self.SERVO_DOWN_PIN) def addServo(self, pin): print pin print type(pin) GPIO.setup(pin, GPIO.OUT) servo = GPIO.PWM(pin, 50) servo.start(0) return servo def changeUpDown(self, upDown): if upDown == 'up': self.setAngle(90, self.SERVO_UP_PIN, self.servoUp) self.setAngle(0, self.SERVO_UP_PIN, self.servoUp) elif upDown == 'down': self.setAngle(90, self.SERVO_DOWN_PIN, self.servoDown) self.setAngle(0, self.SERVO_DOWN_PIN, self.servoDown) def setAngle(self, angle, pin, servo): duty = angle/18 + 2 GPIO.output(pin, True) servo.ChangeDutyCycle(duty) sleep(2) GPIO.output(pin, False) servo.ChangeDutyCycle(0)
67448215952d812af27886e23f0131fc486cb28a
yyotova/DungeonsAndPythons
/source_package/main_classes/potion.py
283
3.65625
4
class Potion: def __init__(self, potion, points): self.potion = potion self.points = points def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return f'Hero has {self.points} points {self.potion} potion'
6870deebd6b1a8b49758791ed692a4ccbeea31a1
gabreuvcr/curso-em-video
/mundo3/ex079.py
478
4
4
## EX079 ## numeros = [] while True: num = int(input('Digite um valor: ')) if num in numeros: print('Valor duplicado! Não irei adicionar.') else: numeros.append(num) print('Valor adicionado com sucesso.') while True: r = str(input('Quer continuar [S/N]? ')).strip().upper()[0] if r == 'S' or 'N': break print('') if r == 'N': break numeros.sort() print(f'Você digitou os valores {numeros}')
ddf04f0bcc05cdae71f6ec0ae04a9808ebf8d728
bhanuprakashbalusu/Python-Fundamentals
/Dates&Times.py
5,565
4.6875
5
# In python we have date, time, datetime, timezone and timedelta. Let's explore all these. # Main module to work with dates in python is datetime module import datetime import pytz # before working with dates and times it is important to understand difference between naive and aware dates # and times # naive dates and times don't have information to determine things like timezones or daylight savings times # to avoid confusion and be aware of that information we use aware dates and times # Let's first explore about naive dates and times: # for a normal date we use date() constructor and it works with year, month, day d = datetime.date(2020, 7, 29) # here be sure to pass regular integers as days and months with no leading 0 print(d) # d = datetime.date(2020, 07, 29) # print(d) # this will give a syntax error since we added leading 0 to month as 07 # to get today's local date we use date.today() method tday = datetime.date.today() print(tday) # prints current local date # to get more information about our dates we can used year, month and day attributes print(tday.year) print(tday.month) print(tday.day) # to get the day of the week we can use weekday() or isoweekday() methods print(tday.weekday()) # for weekday() monday is 0 to sunday which is 6 print(tday.isoweekday()) # for isoweekday() monday is 1 to sunday which is 7 # Now let's look at timedelta. Timedelta is simply the difference between two dates or times. And they are # extremely useful when we do operations on our dates and times # we use timedelta() method by passing the duration of difference between the dates or times as argument # if we add or subtract a timedelta from a date we get another date tdelta = datetime.timedelta(days=7) print(tday + tdelta) # prints what the date will be after 7 days from now print(tday - tdelta) # prints what the date was before 7 days from now # if we instead add or subtract a date from another date we get timedelta as the result bday = datetime.date(2020, 9, 30) till_bday = bday - tday print(till_bday.days) # prints number of days until birthday from today print(till_bday.total_seconds()) # prints total number of seconds until birthday from today # now let's look at times. In times we work with hours, minutes, seconds and micro seconds. t = datetime.time(9, 30, 45, 100000) # here we are specifying new local time in hrs, mins, secs & milli-secs print(t) print(t.hour) print(t.minute) print(t.second) print(t.microsecond) # Generally we would be needing both date and time simultaneously, for thais we use datetime.datetime module dt = datetime.datetime(2020, 7, 30, 17, 41, 30, 100000) print(dt) # prints both date ant time print(dt.date()) # prints only date print(dt.time()) # prints only time print(dt.hour) # prints hour # we can also add and subtract timedelta duration tdelta_1 = datetime.timedelta(days=7) print(dt + tdelta_1) # prints the date adding one week # we can also add hours or minutes or seconds with this datetime.datetime module tdelta_2 = datetime.timedelta(hours=12) print(dt + tdelta_2) # prints the date adding 12 hours # Let's see some of the alternative constructors that come with datetime dt_today = datetime.datetime.today() # .today() returns the current today's local time with timezone equals none dt_now = datetime.datetime.now() # .now() gives us the option of passing the timezone. If it is left empty then # timezone will be equal to none dt_utcnow = datetime.datetime.utcnow() # .utcnow gives the current utc time but tzinfo is still set to none print(dt_today) print(dt_now) print(dt_utcnow) # Now let's look into time zone aware dates and times. This is done using third party package called pytz. # We can install pytz using pip and type the command in the terminal as -> pip install pytz dt_tz = datetime.datetime(2020, 7, 30, 18, 18, 45, tzinfo=pytz.UTC) # by using tzinfo=pytz.UTC we are # making it timezone aware print(dt_tz) # prints date and time with extra 00:00 dt_now_tz = datetime.datetime.now(tz=pytz.UTC) print(dt_now_tz) # prints current date and time with timezone aware dt_utcnow_tz = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC) print(dt_utcnow_tz) # prints current utc date and time with timezone aware # let's convert it to a different timezone # to see the list of all timezones available wa can use pytz.all_timezones for tz in pytz.all_timezones: print(tz) dt_asia = dt_now_tz.astimezone(pytz.timezone('Asia/Calcutta')) print(dt_asia) # Making naive datetime timezone aware by running timezone localized function dt_now_ldn = datetime.datetime.now() ldn_tz = pytz.timezone('Europe/London') dt_now_ldn = ldn_tz.localize(dt_now_ldn) dt_usa = dt_now_ldn.astimezone(pytz.timezone('America/Montreal')) print(dt_usa) # Best way to pass these dates and time for internal use is by using isoformat() method print(dt_now.isoformat()) # To print these dates and times in a specific format we can look at the format codes in the # python documentation for any type of display format # for this we use strftime() method and pass in format code # if we want to display as July 30, 2020 we can use %B %d, %Y format code in strftime() method print(dt_now.strftime('%B %d, %Y')) # prints -> July 30, 2020 # to convert a string to datetime we use strptime() method and pass string and what date format that string is in dt_str = 'July 30, 2020' d_t = datetime.datetime.strptime(dt_str, '%B %d, %Y') print(d_t)
2eca5e85729872669ca4133b4d01125dd11c5c61
Wenjie-Xu/Pandas-Learn
/21.transpose.py
259
3.609375
4
import pandas as pd pd.options.display.max_columns = 999 # 设置展现的最大列数 students = pd.read_excel('/Users/Apple/Desktop/pandas/transpose.xlsx', index_col='name') table = students.transpose() # 旋转数据后生成新的DataFrame print(table)
6e2ce815bfc96bd7b33ca07a0eff0c20de4a6d1a
kumbharswativ/Core2Web
/Python/DailyFlash/14mar2020/MySolutions/program4.py
431
3.546875
4
''' write a program to print the following pattern 0 2 3 4 2 4 6 8 10 0 3 6 9 12 15 18 ''' for i in range(4): a=0 b=1 for j in range(7): if(i+j<=2 or j-i>=4): print(" ",end=" ") else: if(i==0): print("0",end=" ") elif(i==1): print(b+1,end=" ") elif(i==2): print(b*2,end=" ") elif(i==3): print(a*3,end=" ") a+=1 b+=1 print(" ")
ae1a0a6cbb2b0d2c800568d3aa2929f0d39b1644
AmirYousofAbdi/ml_projects
/LinearR_attempt_1.py
1,459
3.640625
4
########## ########## Notice that this code will return the average of accuracy of n times prediction and it would predict the last column! ########## from sklearn import linear_model import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.preprocessing import LabelEncoder as le def csv2d(file = 'iris_flower_data.csv'): my_file = open(file, 'r') column_number = len(my_file.readline().split(',')) classes = [str(each_column) for each_column in range(column_number)] column_number -= 1 dataset = pd.read_csv(file ,names = classes) encoder = le() dataset[str(column_number)] = encoder.fit_transform(dataset[str(column_number)]) global x,y x , y = dataset.drop(str(column_number),axis = 1) , dataset[str(column_number)] def pred(): csv2d() x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.20) linear = linear_model.LinearRegression() linear.fit(x_train,y_train) y_predict = list(linear.predict(x_test)) y_test = list(y_test) y_predict = list(map(round,y_predict)) y_predict = list(map(int,y_predict)) return accuracy_score(y_test,y_predict) number_pred = int(input("How many times you wanna predict? ")) avg_pred_acc = 0 for i in range(number_pred): avg_pred_acc += pred() print(f"The average of accuracies are:{avg_pred_acc/number_pred}")
2048b396655f1f3e17cea71dd7290043295e0180
tsmcalister/vsimcon
/vsimcon/controllers/fixed_controller.py
737
3.53125
4
from .abstract_controller import AbstractController from typing import Callable class FixedController(AbstractController): def __init__(self, phi_t: Callable[[float], float]): self.t = 0 self.phi_t = phi_t @property def output(self) -> float: return self.phi_t(self.t) def update(self, dt: float): self.t += dt def reset(self): self.t = 0 @classmethod def constant_controller(cls, output: float = 1) -> 'FixedController': """ Initialises a constant controller that doesn't change its output :param output: the constant output of the controller :return: a FixedController instance """ return cls(lambda x: output)
cdf94c6238c9f18e1aad3a98d133f0bbd343622b
Ekeopara-Praise/python-challenge-solutions
/Ekeopara_Praise/Phase 2/TUPLE/Day 52 Tasks/Task8.py
320
4.625
5
'''8. Write a Python program to create the colon of a tuple.''' from copy import deepcopy #create a tuple tuplex = ("HELLO", 5, [], True) print(tuplex) #make a copy of a tuple using deepcopy() function tuplex_colon = deepcopy(tuplex) tuplex_colon[2].append(50) print(tuplex_colon) print(tuplex) #Reference: w3resource
6d3a3deebf96a02caeaebd90731769df810cd1a8
will-ing/data-structure-and-algorithms
/dsa-python/challenges/tree_intersection/tree_intersection.py
317
3.640625
4
def intersection(tree, tree_two): while tree.root: value = tree.root.val duplicates(value, tree_two) def duplicates(val, tree): tree_list = [] while tree.root: if val == tree.root.val: tree_list.append(val) else: tree.root = tree.root.right_child
ec91b7f68906ca189ae77c79efc3487f54e1b2ee
wtomalves/exerciciopython
/ex033maior.py
545
4.25
4
um = int(input('Digite o primeiro número:')) dois = int(input('Digite o segundo número:')) tres = int(input('Digite o terceiro numeros:')) if um > dois > tres: print('Maior número é {}'.format(um)) if tres > dois > um: print('Maior número é {}'.format(tres)) if dois > tres > um: print('Maior número é {}'.format(dois)) if um < dois < tres: print('Menor número é {}'.format(um)) if tres < dois < um: print('Menor número é {}'.format(tres)) if dois < tres < um: print('Menor número é {}'.format(dois))
30eaab740d16cd0559a92e62ef67b4792dad2203
IonutPopovici1992/Python
/LearnPython/basic_calculator.py
135
3.921875
4
number1 = input("Enter a number: ") number2 = input("Enter another number: ") result = float(number1) + float(number2) print(result)
83d8cf95d0379f2c86bdbe93fbe3c6002904d41d
janraj00/AlgoStart
/zes2/prime.py
292
3.546875
4
def prime_test(n): if n % 2 == 0: return False if n % 3 == 0: return False i = 1 while 6 * i - 1 <= n ** 0.5: if n % (6 * i - 1) == 0: return False if n % (6 * i + 1) == 0: return False i += 1 return True
a09c67a1c2a8936080a3dc0435770951e44053ff
justingolden21/synthetic-poe
/synthesizer.py
3,071
4.0625
4
import random # input_text: the text used to generate our synthetic text # size: number of characters we look back # num_chars: the approx size of our output str def synthesize(input_text, size, num_chars): # create char dict char_dict = {} # for every char except the last (size) chars for i in range(len(input_text)-size): # our substring is (size) chars after index i sub_str = input_text[i:i+size] # make obj if doesnt exist if not sub_str in char_dict: char_dict[sub_str] = {} # if we havent seen this combo before, init to 1, else incremement # number of times we've seen these size characters # correspond to the next character after them if not input_text[i+size] in char_dict[sub_str]: char_dict[sub_str][input_text[i+size]] = 1 else: char_dict[sub_str][input_text[i+size]] += 1 # ---------------- # generate ouput # our output str generated_sentence = "" # star us off at a random point in the input, to (size) chars # after that point (so we have context to begin our loop) rand_idx = random.randint(0, len(input_text)-size) generated_sentence += input_text[rand_idx:rand_idx+size] # for every char we want to make for i in range(num_chars-size): # the next char is a weighted random char from our helper function next_char = get_next_char(char_dict, generated_sentence[-size:]) # if we have no data, pick random char if next_char == -1: next_char = random.choice(input_text) # change this? generated_sentence += next_char # ---------------- # almost done, now fix the start and end # for end, we repeat above loop until an end of sentence character is found # keep adding chars like we did before until the last one is an end of sentence char while not isSentenceEnd(generated_sentence[-1]): next_char = get_next_char(char_dict, generated_sentence[-size:]) if next_char == -1: next_char = random.choice(input_text) generated_sentence += next_char # delete chars from beginning until the first char is the char after an end of sentence char while not isSentenceEnd(generated_sentence[0]): generated_sentence = generated_sentence[1:] generated_sentence = generated_sentence[1:] return generated_sentence # ---------------- # helper functions # given an input str of size (size), get a weighted random character # given all combos of characters we've seen after that str def get_next_char(char_dict, input_str): if input_str not in char_dict: return -1 # if we don't have data for that char, handle in loop rand_max = 0 # number of all total times that sequence occured for key in char_dict[input_str]: rand_max += char_dict[input_str][key] # choose a random one of those sequences rand_choice = random.randint(0, rand_max) for key in char_dict[input_str]: rand_choice -= char_dict[input_str][key] # and choose the character at that index if rand_choice <= 0: return key # returns true if given char is an end of sentence char def isSentenceEnd(test_char): return test_char in ". ! ? \n".split(" ")
7bf6a0ca936db2fc9ba8f8eec1389968398134f1
aminbouraiss/flask-dashboard
/filterArray.py
7,599
3.640625
4
import numpy as np import re import csv import json import datetime as dt from collections import namedtuple def csvToTuple(filePath): """Convert a csv file to a list of tuples""" with open(filePath, 'rb') as f: reader = csv.reader(f) converted = [tuple(row) for row in reader] return converted def findType(value): """Find the dtype corresponding to of a value. Args: value (string): The string for which the dtype will be evaluated. Returns: string: The dtype to use. """ if type(value) == str: dateRegex = '([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))' dateVal = re.match(dateRegex, value) floatVal = re.match('^\d+\.\d*$', value) intVal = re.match('^\d+$', value) if dateVal: valueType = 'M8[D]' elif floatVal: valueType = 'f8' elif intVal: valueType = 'int' else: valueType = 'O' return valueType def replaceNulls(valueTuple, numericList): """Replace null values by zeros in a list. Args: valueTuple (tuple): A tuple containing the list of values and indexes. numericList (list): list of numeric columns. Returns: list: The return value """ for idx, val in enumerate(valueTuple): isNumeric = idx in numericList if len(val) == 0 and isNumeric: yield 0 else: yield val def getNumindexes(typeList): """Find the indexes of the numeric columns. Args: typeList (list): A list of numpy dTypes converted to strings. Returns: generator: the returned generator. """ """Find the indexes of the numeric columns""" for index, curList in enumerate(typeList): if re.match("f8|int", curList[1]): yield index def roundSum(col): """Calculate the sum for a column round it to two precision points Args: col (numpy Array): The values to sum. Returns: float: The rounded sum. """ colSum = sum(col) return round(colSum, 2) def toTimezone(dateObject): """Convert a datetime object to iso 8601 format. Args: dateObject: A datetime object. Returns: string: The oconverted value. """ return dt.datetime.strftime(dateObject, '%Y-%m-%dT%H:%M:%S.%SZ') def toTuples(array, cols): """Create name,column pairs for a dict. Args: array (numpy Array) : The Array to convert. cols (list): The array's column names. Returns: tuple: Name of the column and its values (numpy Array). """ for name in cols: col = array[name] kind = col.dtype.kind if kind == "M": yield (name, [toTimezone(x) for x in col.tolist()]) else: yield (name, col.tolist()) def sliceTime(array, start, end, col='Date'): """Slices a numpy Array based on specified dates. Args: array (numpy Array) : The Array to slice. start (datetime object) : The start date for the slicing end (datetime object) : The end date for the slicing col (string) : The column on which the slicing will be applied Returns: Numpy Array: The sliced array. """ targetCol = array[col].tolist() matchValues = [idx if (val >= start) & (val <= end) else False for idx, val in enumerate(targetCol)] mask = list(filter(lambda x: x, matchValues)) return array[mask] def arrayToDict(arr, arr_columns, start_Date, end_Date): """Generate two dicts for the periods before the provided timespan and and the current period. Args: arr (Numpy Array): The original Array. startDate (string): The start date of the current period. endDate (string): The end date of the current period. Returns: namedtuple: The filtered Arrays """ startDate = dt.datetime.strptime(start_Date, '%Y-%m-%d') endDate = dt.datetime.strptime(end_Date, '%Y-%m-%d') delta = endDate - startDate previous_period_start = startDate - delta previous_period_array = sliceTime(arr, previous_period_start, startDate) current_period_array = sliceTime(arr, startDate, endDate) previous_dict = dict(list(toTuples(previous_period_array, arr_columns))) current_dict = dict(list(toTuples(current_period_array, arr_columns))) returnTuple = namedtuple( 'filteredData', ['current_period', 'previous_period']) return returnTuple(current_dict, previous_dict) def getPeriodSdum(valuesDict, metricList): """Calculate the sum for each column in a value dict. Args: valuesDict (dict): The dict for which the sums will be calculated. metricList (list): The list of metrics. Returns: dict: the sum for each metric. """ sumDict = dict((name, roundSum(valuesDict[name])) for name in metricList) return sumDict def makeJson(arr): returnVal = json.dumps(arr, encoding='utf-8') return returnVal def generateValues(csvFilePath): dataList = csvToTuple(csvFilePath) # split the columns and the data columns = dataList[0] dataraw = dataList[1:] testRow = dataList[1] # Find the dtype of each column dtypes = [(col, findType(val)) for col, val in zip(columns, testRow)] # Generate a list containing the indexes of numeric columns floatList = list(getNumindexes(dtypes)) # Remove the nulls from the data noNans = [tuple(replaceNulls(i, floatList)) for i in dataraw] # Create the final array data_Array = np.array(noNans, dtype=dtypes) returnTuple = namedtuple( 'rawData', ['data', 'dtypes', 'floatList', 'columns']) return returnTuple(data_Array, dtypes, floatList, columns) def dictList(value_dict, rowsCol='Date'): """Converts a dict to a list of dict, one dict for each row. Args: value_dict (dict): The dict to convert. rowsCol (string): The key that will be used to count the number of rows. Returns: list: The dict converted to a list of dicts. """ columns = value_dict.keys() rowCount = range(len(value_dict[rowsCol])) converted = [dict((col, value_dict[col][x]) for col in columns) for x in rowCount] return converted def exportToJson(rawData, period_start, period_end,): # Convert the numpy Array and its values to a dict data_tuple = arrayToDict( rawData.data, rawData.columns, period_start, period_end) # Calculate the sums for the current and the previous period metric_indexes = np.array(rawData.dtypes) metrics = [row[0] for row in metric_indexes[rawData.floatList]] current_period = data_tuple.current_period previous_period = data_tuple.previous_period # Get the filtered data for the current and the previous period currentSumDict = getPeriodSdum(current_period, metrics) previousSumDict = getPeriodSdum(previous_period, metrics) # Calculate the sums for the current and the previous period # prepare the value to export them as a json file returnStr = makeJson({'data': dictList(current_period), 'currentSum': currentSumDict, 'beforeSum': previousSumDict, 'beforeData': dictList(previous_period)}) return returnStr
a4ed9504c9668389f7796103efbe408d1a61942e
AnnHalii/Python_Hillel
/lk_11_hw/2_task.py
443
3.984375
4
class Person: def __init__(self, age, name): self.age = age self.name = name self.__friends = [] def know(self, other): self.__friends.append(other) def is_known(self, other): return other in self.__friends person1 = Person(18, 'Oleg') person2 = Person(24, 'Dima') person3 = Person(25, 'Vitalik') person1.know(person2) print(person1.is_known(person2)) print(person1.is_known(person3))
3ae945229acf77acec03941cf128e213e574a546
ashish-5209/TreeDataStructure
/sumTree.py
713
3.875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def s1(root): if root is None: return 0 return s1(root.left) + root.data + s1(root.right) def subTree(root): ls = 0 rs = 0 if root is None or (root.left is None and root.right is None): return True ls = s1(root.left) rs = s1(root.right) if ((root.data == ls+rs) and subTree(root.left) and subTree(root.right)): return True return False root = Node(26) root.left = Node(10) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(6) root.right.right = Node(3) print(subTree(root))
f72fab6f02e1add20c4e595f7b433afc988fbee4
danmackinlay/ipypublish
/nbconvert/latex_hide_input_output.py
1,984
3.578125
4
def remove_dollars(input, **kwargs): """remove dollars from start/end of file""" while input.startswith('$'): input = input[1:] while input.endswith('$'): input = input[0:-1] return input def first_para(input, **kwargs): r"""get only ttext before a \n (i.e. the fist paragraph)""" return input.split('\n')[0] import re from collections import OrderedDict def write_roman(num): roman = OrderedDict() roman[1000] = "M" roman[900] = "CM" roman[500] = "D" roman[400] = "CD" roman[100] = "C" roman[90] = "XC" roman[50] = "L" roman[40] = "XL" roman[10] = "X" roman[9] = "IX" roman[5] = "V" roman[4] = "IV" roman[1] = "I" def roman_num(num): for r in roman.keys(): x, y = divmod(num, r) yield roman[r] * x num -= (r * x) if num > 0: roman_num(num) else: break return "".join([a for a in roman_num(num)]) def repl(match): return write_roman(int(match.group(0))) def create_key(input, **kwargs): """create sanitized key string which only contains lowercase letters, (semi)colons as c, underscores as u and numbers as roman numerals in this way the keys with different input should mainly be unique >>> sanitize_key('fig:A_10name56') 'figcauxnamelvi' """ input = re.compile(r"\d+").sub(repl, input) input = input.replace(':','c') input = input.replace(';','c') input = input.replace('_','u') return re.sub('[^a-zA-Z]+', '', str(input)).lower() c = get_config() c.NbConvertApp.export_format = 'latex' c.TemplateExporter.filters = c.Exporter.filters = {'remove_dollars': remove_dollars, 'first_para': first_para, 'create_key': create_key} c.Exporter.template_file = 'latex_hide_input_output.tplx'
e5e5d7397c8026abbf017a33cbf0eb3311f54600
zhou-dong/python-study
/list-example.py
1,327
4.25
4
nums = [1, 3, 2, 15, 10] print "len:", len(nums) print "sum:", sum(nums) print "min:", min(nums) print "max:", max(nums) for num in nums: print num, print print "range:", range(len(nums)) # nums.sort() print nums for x in range(len(nums)): print "index:", x, "; num:", nums[x] print dir(nums) print nums[-1] # this is amazing, the position of 10 in the list print nums.index(10) nums.append(4) print nums print nums.pop(1) print nums print nums.pop() print nums print nums.count(2) nums.append(2) print nums.count(2) # I really like python now! list method: # 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' # get index and value of list in same time choices = ['pizza', 'pasta', 'salad', 'nachos'] print 'Your choices are:' for index, item in enumerate(choices): print index+1, item ''' It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy. zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list. zip can handle three or more lists as well! ''' list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] for a, b in zip(list_a, list_b): # Add your code here! print max(a,b) ''' while and for loop can use with else '''
e82e9733a01b86a2d7f1b31025dfacf0386ba72d
soomark/Level_0_Chanllenges
/Task_0.1.py
183
3.828125
4
#Demonstrate the order of the program #Output of x and y equals 0 and 1 x = 0 y = 1 print(x) print(y) #Output of x and y equals 3 and 4 x += 3 y += x print(x) print(y)
2e431cc4fa09c6d2eb339c4cfa0990eaf22f0647
pavonvazquez/Proyecto
/pit.py
107
3.96875
4
n = int(input("Ingresa el numero: ")) print("El valor del numero es: %d"%n) for i in range(n): print(i)
0016569aae8e3e1e60a417967232dd8a6b2f1217
ssarrayya/python-deitel-exercises
/com/exercises/chapter_four/rounding_numbers.py
450
3.890625
4
# 4.8 (Rounding Numbers) Investigate built-in function round at # https://docs.python.org/3/library/functions.html#round # then use it to round the float value 13.56449 to the nearest integer, # tenths, hundredths and thousandths positions. # to the nearest integer print(round(13.56449)) # to the nearest tenth print(round(13.56449, 1)) # to the nearest hundredth print(round(13.56449, 2)) # to the nearest thousandth print(round(13.56449, 3))
1357b9bab710207b0d3348a2ea0253e97a62482d
sumitkr4/DataStr
/Recursion/reverseString.py
282
4.03125
4
def reverse(string): # # 1st Approach # if len(string) == 0: # return # temp = string[0] # reverse(string[1:]) # print(temp,end="") if len(string)<=1: return string return reverse(string[1:]) + string[0] print(reverse('I m a fan of fan'))
944a60554bdab4d520e43c12a28f5387ce36b759
abhisheknm99/APS-2020
/39-Uppercase_to_lowercase.py
212
4.21875
4
#Converts the given string to lowercase #Method1 def upper_lower(s): res=[] for i in s: i=chr(ord(i)|32) res.append(i) return "".join(res) s="ABcDE" r=upper_lower(s) print(r) #Method 2 print(s.lower())
c67c71afe937e33419b115d1573cb32036c23376
GustavoMarzullo/Livro-Guttag
/Integrais/Integral_MC.py
995
3.796875
4
#integral por monte carlo #\int_{a}^{b}=(valor_médio)*(b-a) import random import scipy.stats as stats import numpy as np def ts(alpha,gl): '''Retorna o valor de t-student para tal alpha e tal gis graus de liberdade.''' return stats.t.ppf(1-(alpha/2), gl) def siginificativos(n): '''Retorna o número de algarismos siginificativos de um número.''' return abs(int(np.floor(np.log10(abs(n))))) def integral(f,a,b,n=1000,x=100): '''Retorna a integral com x séries de n pontos de a até b de uma função f definida anteriormente. Retorna também o intervalo de confiança(IC).''' valores_medios=[] for i in range(x): valor=0.0 for i in range(n): valor+=f(random.uniform(a,b)) valores_medios.append(valor/n*(b-a)) IC=ts(0.05,x-1)*(stats.tstd(valores_medios)/(x**0.5)) valor_medio=stats.tmean(valores_medios) casas=siginificativos(IC) return round(valor_medio,casas),round(IC,casas)
7242fb6a269570f2e6b55f4132eca4bcfd5001f3
ikeshou/Kyoupuro_library_python
/src/mypkg/basic_data_structures/priority_queue.py
2,686
4.25
4
""" 一番ベーシックな min priority queue, max priority queue の実装 - リスト上で min heap を構築するためのモジュール heapq は存在するが priority queue はサポートされていないので自前で用意する必要がある。 <メソッド早見表> empty(): O(1) PQueue が空か判定 add_task(task, priority): O(lgn) task を priority の優先度で PQueue に追加 pop_task(): O(lgn) 優先度が (最小: min-pqueue / 最大: max-pqueue) の task オブジェクトを取り出し、(task, priority) を返す """ import itertools from heapq import heappush, heappop from heapq import _heappop_max, _siftdown_max def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1) from typing import Any, Union Num = Union[int, float] class PQueueMin: """ min priority queue Attributes: self.pq (list): (priority, count, task) というタプルのエントリからなるヒープ。 self.counter (iter): ユニークな番号。上記エントリを比較する際、task までに必ず順序関係が決定するようにするためのもの。(task に順序関係がないことがある) """ def __init__(self): self.pq = [] self.counter = itertools.count() def empty(self) -> bool: return len(self.pq) == 0 def add_task(self, task: Any, priority: Num) -> None: count = next(self.counter) entry = (priority, count, task) heappush(self.pq, entry) def pop_task(self) -> Any: if self.empty(): raise KeyError(f"PQueueMin.pop_task(): pqueue is empty.") priority, _, task = heappop(self.pq) return (task, priority) class PQueueMax: """ max priority queue Attributes: self.pq (list): (-priority, count, task) というタプルのエントリからなるヒープ。 self.counter (iter): ユニークな番号。上記エントリを比較する際、task までに必ず順序関係が決定するようにするためのもの。(task に順序関係がないことがある) """ def __init__(self): self.pq = [] self.counter = itertools.count() def empty(self) -> bool: return len(self.pq) == 0 def add_task(self, task: Any, priority: Num) -> None: count = next(self.counter) entry = (priority, count, task) _heappush_max(self.pq, entry) def pop_task(self) -> Any: if self.empty(): raise KeyError(f"PQueueMax.pop_task(): pqueue is empty.") priority, _, task = _heappop_max(self.pq) return (task, priority)
d8dee13bb040d6dab1c1d2fa3a9a7c4197821634
ivceh/Advent-of-Code-2019
/Intcode_computer.py
4,021
3.546875
4
from collections import deque def instruction_modes(instruction): opcode = instruction % 100 instruction //= 100 mode1 = instruction % 10 instruction //= 10 return (opcode, mode1, instruction % 10, instruction // 10) class program: def __init__(self, A, in_func = None, out_func = None): if isinstance(A, list): self.A = dict(enumerate(A)) elif isinstance(A, dict): self.A = A.copy() else: raise TypeError("A must be list or dict!") self.pc = self.relative_base = 0 self.in_func = in_func self.out_func = out_func self.get_opcode_modes() def get_opcode_modes(self): self.opcode, self.mode1, self.mode2, self.mode3 = instruction_modes(self.A[self.pc]) def value_at_address(self, pc): if pc in self.A: return self.A[pc] else: return 0 def value(self, mode, pc): if mode == 0: return self.value_at_address(self.value_at_address(pc)) elif mode == 1: return self.value_at_address(pc) elif mode == 2: return self.value_at_address(self.value_at_address(pc) + self.relative_base) else: raise ValueError("Invalid mode {}!".format(mode)) def set_value(self, mode, pc, value): if mode == 0: self.A[self.value_at_address(pc)] = value elif mode == 2: self.A[self.value_at_address(pc) + self.relative_base] = value else: raise ValueError("Invalid mode {}!".format(mode)) def step(self): if self.opcode == 1: self.set_value(self.mode3, self.pc + 3, self.value(self.mode1, self.pc + 1) + self.value(self.mode2, self.pc + 2)) self.pc += 4 elif self.opcode == 2: self.set_value(self.mode3, self.pc + 3, self.value(self.mode1, self.pc + 1) * self.value(self.mode2, self.pc + 2)) self.pc += 4 elif self.opcode == 3: self.set_value(self.mode1, self.pc + 1, self.in_func()) self.pc += 2 elif self.opcode == 4: self.out_func(self.value(self.mode1, self.pc + 1)) self.pc += 2 elif self.opcode == 5: if self.value(self.mode1, self.pc + 1) == 0: self.pc += 3 else: self.pc = self.value(self.mode2, self.pc + 2) elif self.opcode == 6: if self.value(self.mode1, self.pc + 1) == 0: self.pc = self.value(self.mode2, self.pc + 2) else: self.pc += 3 elif self.opcode == 7: if self.value(self.mode1, self.pc + 1) < self.value(self.mode2, self.pc + 2): self.set_value(self.mode3, self.pc + 3, 1) else: self.set_value(self.mode3, self.pc + 3, 0) self.pc += 4 elif self.opcode == 8: if self.value(self.mode1, self.pc + 1) == self.value(self.mode2, self.pc + 2): self.set_value(self.mode3, self.pc + 3, 1) else: self.set_value(self.mode3, self.pc + 3, 0) self.pc += 4 elif self.opcode == 9: self.relative_base += self.value(self.mode1, self.pc + 1) self.pc += 2 else: raise ValueError("Invalid opcode {}!".format(self.opcode)) self.get_opcode_modes() def finished(self): return self.opcode == 99 def exec(self): while not self.finished(): self.step() def exec_until_input(self): while not self.finished() and self.opcode != 3: self.step() inputQ = deque() def input_from_queue(Q = inputQ): def in_func(): return Q.popleft() return in_func def output_to_queue(Q = inputQ): def out_func(x): Q.append(x) return out_func
662f493c535fb4797ef8a5a7782b0dce9960582a
Afrooz-mohamadipour/python-ex
/046.py
181
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: num = 0 while num<5: num = int(input("Please enter a number =>")) print("The last number you enterd was ",num) # In[ ]:
4ce9c91e5a4bec7a74a21727f5b9fe862570ac11
catonis/Numerical-Methods
/sequences.py
1,498
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 23 04:40:31 2019 @author: Chris Mitchell """ import requests import re def get_oeis_ref(sequence_ref): """This function accepts a sequence identification number as a string for the OEIS and pulls the sequence, name, and comment from the database in the JSON format. The function returns a list of integers containing the reference data.""" #Sequence IDs are in the form of A123456 #Use regular expressions to enforce proper format p = re.compile('^A\d{6}$') if p.findall(sequence_ref) == []: raise TypeError('Invalid sequence format.') #Set the appropriate url to query url = 'https://oeis.org/search?q=id:' + sequence_ref + '&fmt=json' #Make the request for the data req = requests.get(url) #Read the request as a JSON and unnest oeis_json = req.json() oeis_json = oeis_json['results'][0] #Break the 'data' field down into a list of numbers and return return [int(seq_val) for seq_val in oeis_json['data'].split(',')] def collatzSequence(start): """Returns the Collatz sequence for the starting number as a list of integers.""" evenFunc = lambda x : x // 2 oddFunc = lambda x : (3 * x) + 1 colList = [start] while start != 1: if start % 2 == 0: start = evenFunc(start) else: start = oddFunc(start) colList.append(start) return colList
58a61eef7b111b286f767432dd5ef8efb33908a5
pombredanne/n-tuple-plagiarism-detector
/ntuple.py
6,193
4.34375
4
import re def read_string_to_word_list(line): """Takes in a string of text and returns a list of the words in the text.""" regex = r"[a-zA-Z]+" words_in_text = [] # Finds all the words in the text matches = re.findall(regex, line) # Iterate through all the words in the line and add them to the list for word in matches: # We want the list of words to be case-sensitive words_in_text.append(word.lower()) return words_in_text class NTupleAlgorithm: """ A class representing an N-tuple comparison algorithm.""" def __init__(self, n): """ NTupleAlgorithm constructor """ self.n = n def compare(self, input1, input2): """ Takes in two lists of items. Returns a number between `0` and `1` \ representing the confidence that the two lists are similar. Assumes that \ the two lists contain the same number of items.""" # Get the N-size tuples for the two input lists. input1_n_tuples = NTupleInput(input1, self.n) input2_n_tuples = NTupleInput(input2, self.n) num_matches = 0 # Iterate through the N-size tuples for the first input. If the tuple matches one in # the second input, take note by incrementing our counter of the number of matches. for tuple in input1_n_tuples: if input2_n_tuples.match(tuple): num_matches += 1 # Return the percentage of matching tuples to total tuples in the first input list. return float(num_matches)/float(len(input1_n_tuples)) class NTupleInput: """A helper class for NTupleAlgorithm which breaks down lists of items \ into tuples of size N.""" def __init__(self, input_list, n): """NTupleInput constructor. Expects a list of inputs in `input_list` and a N size for the tuples in `n`.""" # Create a HashMap to store the N-size tuples self.tuple_map = {} curr_window = [] # Iterate through the list of items using a moving window of size N for item in input_list: # Add a new item to the window curr_window.append(item) # If the window is of size N, we can add it to our HashMap. if len(curr_window) == n: self.tuple_map[tuple(curr_window)] = 1 # Popping off the first element ensures that the window doesn't get too large. curr_window.pop(0) def __iter__(self): """The Iterator operator for the NTupleInput class.""" # We want to iterate over the list of tuples, which is stored in the metadata of the HashMap. # While this could be stored in a second list, using the pre-existing metadata from the HashMap # saves on memory usage. return iter(self.tuple_map.keys()) def __len__(self): """The Length opereator for the NTupleInput class.""" # Returns the number of objects in the HashMap. return len(self.tuple_map) def match(self, tuple): """Checks if the input tuple matches any in the object.""" # To do this, we just check if the tuple exists in the HashMap return tuple in self.tuple_map class GeneralWordListGenerator: """A helper class which generates generalized lists of words using a provided list of synonyms""" def __init__(self, synonyms_list): """GeneralWordListGenerator constructor Takes in a list where each item is a tuple containing words that are synonyms of each other.""" self.synonyms_dict = self.generate_synonym_to_tuple_dict(synonyms_list) @staticmethod def read_file_to_tuple_list(file): """Reads in a file and outputs a list, where each item in the list is a \ tuple of the words in a line in the file.""" tuple_list = [] # Read in the first line of the file curr_line = file.readline() while curr_line != "": # Break up the text of a line by word words_in_line = read_string_to_word_list(curr_line) # Append the tuple of words to the list of tuples tuple_list.append(tuple(words_in_line)) # Read in the next line curr_line = file.readline() return tuple_list @staticmethod def generate_synonym_to_tuple_dict(synonym_list): """Takes in a list where each element is a tuple of words that are synonyms of \ each other. Returns a dictionary matching each word to its corresponding tuple \ of synonyms.""" synonym_to_tuple_dict = {} # Iterate through the list of tuples for synonym_tuple in synonym_list: # Iterate through the tuple and add each word to the dictionary for word in synonym_tuple: # The word should be the key and the synonym tuple should be the value. We want # it such that if we indexed the dictionary for two different words which are # synonyms of each other, they will return the same value. synonym_to_tuple_dict[word] = synonym_tuple return synonym_to_tuple_dict def generate_word_list(self, string): """Takes in a string representing an input text. Returns a list representing a \ generalized version of the text, where words with synonyms are represented \ as the tuple of all the synonyms and words without synonyms are represented as \ strings of just the word. """ # Read in the string and get the list of the words in the string words_in_line = read_string_to_word_list(string) general_word_list = [] # Iterate through the words in the list for word in words_in_line: # If the word has synonyms from the list of synonyms provided in the constructor method, # append the generalized tuple of the synonyms of the word. Otherwise, append the word # itself. if word in self.synonyms_dict: general_word_list.append(self.synonyms_dict[word]) else: general_word_list.append(word) return general_word_list
687131e9e083cf4c2a6a9ce8fa60536539f2f3c2
nkrishnappa/100DaysOfCode
/Python/Day-#24/1_types_of_paths.py
492
3.890625
4
""" 1. Absolute File path - /root/filename.extension 2. Relative File path - filename.extension or ./filename.extension # How to goto the parent folder - ../ """ # Using Absolute file path with open(r"C:\Users\nkrishnappa\Desktop\100DaysOfCode\Python\Day-#24\FindMeDude\my_file.txt") as file: print(file.read()) # relative file path with open(r"./FindMeDude/my_file.txt") as file: print(file.read()) with open(r"../Day-#24/FindMeDude/my_file.txt") as file: print(file.read())
f344c246dde041f0f7e94ae02eb03e2ea6fdefa6
nischalshrestha/automatic_wat_discovery
/Notebooks/py/shanxingg/titanic-ml-from-disaster/titanic-ml-from-disaster.py
2,833
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[265]: # import packages import numpy as np import pandas as pd from sklearn import preprocessing from sklearn import tree from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt # In[266]: # Import data train = pd.read_csv("../input/train.csv", index_col='PassengerId') test = pd.read_csv("../input/test.csv", index_col='PassengerId') test_survived = pd.read_csv("../input/gender_submission.csv", index_col='PassengerId') # In[267]: # EDA - average value of attributes based on different Pclass-Sex combination train.groupby(['Pclass','Sex']).mean() # In[268]: # EDA - average value of attributes based on different age range age_range = pd.cut(train.Age, np.arange(0,90,10)) train.groupby(age_range).mean() # In[269]: # EDA - volume of test and train data print(f"Train Dataset:\n{train.count()}\n") print(f"Test Dataset:\n{test.count()}") # Train dataset has missing data on "Age", "Cabin", "Embarked" # # Test dataset has missing data on "Age", "Fare", "Cabin" # # Conclusion: # # * drop "Cabin" (too little data, not a good category variable) # # * drop "Ticket" (not a category variable) # # * drop "Name" (not a category variable) # # * impute missing value for "Age", "Embarked", "Fare" # In[270]: # handle missing values of Age train.Age.hist() plt.show() # The distribution of Age is not normal. Therefore, impute missing values with median age # In[271]: # handle missing values of Embarked train.Embarked.hist() plt.show() # Impute missing values with "S" (mode), because: # # * only very few missing data # * S is the majority # In[272]: # handle missing values of Fare train.Fare.hist() plt.show() # The distribution of Fare is not normal. Therefore, impute missing values with median Fare # In[273]: # Combine train x and test x train_x = train.drop(['Survived'],axis=1) test_x = test.copy() attr = pd.concat([train_x, test_x]) # Preparing data for machine learning algorithm attr = attr.drop(['Name','Cabin','Ticket'],axis=1) attr.Age = attr.Age.fillna(attr.Age.median(skipna=True)) attr.Fare = attr.Fare.fillna(attr.Fare.median(skipna=True)) attr.Embarked = attr.Embarked.fillna(attr.Embarked.mode()[0]) le = preprocessing.LabelEncoder() attr.Sex = le.fit_transform(attr.Sex) attr.Embarked = le.fit_transform(attr.Embarked) # split train x and test x train_x = attr[:len(train_x)].copy() test_x = attr[-len(test_x):].copy() # extract train y and test y train_y = train['Survived'] test_y = test_survived.copy() # In[274]: # Decision Tree Model model = tree.DecisionTreeClassifier() model.fit(train_x, train_y) pred_y = pd.DataFrame(model.predict(test_x), index=test_y.index, columns=['Survived']) accuracy_score(test_y, pred_y) # In[275]: # Export prediction pred_y.to_csv('prediction.csv')
ccfd4d30c34ac74cdc34a217a7faeaad9dc06994
flafick/project
/Arkanoid.py
7,611
3.546875
4
import pygame import random class Ball(pygame.sprite.Sprite): def __init__(self, paddle): pygame.sprite.Sprite.__init__(self) self.paddle = paddle self.size = 17 self.end_game_flag = False self.image = pygame.Surface((self.size, self.size)) pygame.draw.circle(self.image, GREEN, (self.size//2 , self.size//2), self.size // 2) #self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.center = (WIDTH // 2, HEIGHT // 2) self.rect.center = (random.randint(int(0.2*WIDTH), int(0.8*WIDTH)), random.randint(HEIGHT//2, int(HEIGHT*0.8))) self.step = 5 self.x_direction = 'right' self.y_direction = 'top' self.message = '' def update(self): if self.rect.y + self.size >= HEIGHT: self.message = "Game Over" self.end_game_flag = True if self.rect.colliderect(paddle.rect): self.y_direction = 'top' # if self.rect.y + self.size >= self.paddle.rect.y: # if self.rect.x < self.paddle.rect.x +self.paddle.rect.w and self.rect.x + self.size > self.paddle.rect.x: if self.rect.x + self.size >= WIDTH: self.x_direction = 'left' elif self.rect.x <= 0: self.x_direction = 'right' if self.x_direction == 'right': self.rect.x = self.rect.x + self.step elif self.x_direction == 'left': self.rect.x = self.rect.x - self.step if self.rect.y <= 0: self.y_direction = 'down' if self.y_direction == 'down': self.rect.y = self.rect.y + self.step elif self.y_direction == 'top': self.rect.y = self.rect.y - self.step def change_y_direction(self): if self.y_direction == 'down': self.y_direction = 'top' else: self.y_direction = 'down' def change_x_direction(self): if self.x_direction == 'right': self.x_direction = 'left' else: self.x_direction = 'right' def win(self): self.message = "!!!! YOU WIN !!!!" self.end_game_flag = True class Paddle(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.h = 20 self.w = 100 self.image = pygame.Surface((self.w, self.h)) self.image.fill((255,0,0)) self.rect = self.image.get_rect() self.rect.x = WIDTH // 2 self.rect.y = HEIGHT - self.h self.step = 15 self.x_direction = 'right' def update(self): step = self.step if self.rect.x + self.w >= WIDTH and self.x_direction == 'right': step = 0 elif self.rect.x <= 0 and self.x_direction == 'left': step = 0 if self.x_direction == 'right': self.rect.x = self.rect.x + step elif self.x_direction == 'left': self.rect.x = self.rect.x - step self.x_direction = '' class Block(pygame.sprite.Sprite): def __init__(self, x, y, size): pygame.sprite.Sprite.__init__(self) self.size = size self.image = pygame.Surface((self.size, self.size)) self.image.fill((127,0,127)) self.rect = self.image.get_rect() self.rect.center = (x + size // 2, y + size // 2) self.mortal = False def update(self): self.mortal = True def get_score_text(score): return "Score: " +str(score) def drawTextInCenter(screen, text, COLOR = (255,255,255), font_size = 24): font = pygame.font.SysFont(None, font_size) textSurface = font.render(text, True, COLOR) x = int(screen.get_width()*0.5 - textSurface.get_width()*0.5) y = int(screen.get_height()*0.5 - textSurface.get_height()*0.5) return textSurface, (x,y) WIDTH = 1500 HEIGHT= 800 BASE_FPS = 60 BLACK=(0,0,0) GREEN = (0,255,0) SCORE_COLOR= (255,255,0) ## GET FROM https://www.pygame.org/wiki/SettingWindowPosition x = 100 y = 50 import os os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y) pygame.init() pygame.mixer.init() pygame.font.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("MEGA ARCANOID by Dan 'helper' Kuznetsov") clock = pygame.time.Clock() game_quit = False while not game_quit: all_sprites = pygame.sprite.Group() blocks_sprites = pygame.sprite.Group() paddle = Paddle() all_sprites.add(paddle) ball = Ball(paddle) all_sprites.add(ball) block_size = 21 block_start_y = block_size*6 block_end_y = block_size*6+(block_size+1)*5 for block_y in range(block_start_y, block_end_y, block_size+1): empty_blocks = random.randint(0, 10) block_start_x = empty_blocks * (block_size+1) block_end_x = WIDTH - empty_blocks * (block_size+1) for block_x in range(block_start_x, block_end_x, block_size+1): blockN = Block(block_x, block_y, block_size) blocks_sprites.add(blockN) screen.fill(BLACK) game_score = 0 font = pygame.font.SysFont(None, 24) FPS = BASE_FPS screen.blit(font.render(get_score_text(game_score), True, SCORE_COLOR),(0,0)) while not ball.end_game_flag: clock.tick(FPS) for event in pygame.event.get(): # проверить закрытие окна if event.type == pygame.QUIT: game_quit = True break keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: game_quit = True break if keys[pygame.K_LEFT]: paddle.x_direction = 'left' if keys[pygame.K_RIGHT]: paddle.x_direction = 'right' #UPDATE ALL SPRITES POSITIONS all_sprites.update() blocks_sprites.update() blocks_hit_list = pygame.sprite.spritecollide(ball, blocks_sprites, True) game_score = game_score + len(blocks_hit_list) if len(blocks_hit_list) > 0: block_hitted = blocks_hit_list[0] dx = abs(block_hitted.rect.centerx - ball.rect.centerx) dy = abs(block_hitted.rect.centery - ball.rect.centery) if dx < dy: ball.change_y_direction() elif dy < dx: ball.change_x_direction() elif dy == dx: ball.change_x_direction() ball.change_y_direction() #DRAW ALL SPRITES screen.fill(BLACK) screen.blit(font.render(get_score_text(game_score), True, SCORE_COLOR),(0,0)) all_sprites.draw(screen) blocks_sprites.draw(screen) #SHOW ALL UPDATES pygame.display.flip() if game_score > 0 and game_score % 5 == 0: FPS = BASE_FPS + (game_score // 5) * 6 print(FPS) if len(blocks_sprites.sprites()) == 0: ball.win() break textImg, textCoordinate = drawTextInCenter(screen, ball.message, (255,127,255), 50) screen.blit(textImg,textCoordinate) screen.blit(font.render("Press N for new game", True, (255,0,255)),(WIDTH // 2 - 60,0)) pygame.display.flip() while True: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: game_quit = True break keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: game_quit = True break if keys[pygame.K_n]: game_quit = False break pygame.quit()
a79cbf35bcccc5ad1c9e8be2c9c65918ee592039
DeanHe/Practice
/LeetCodePython/MaximumNumberOfVisiblePoints.py
2,843
3.875
4
""" You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view. There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see. Example 1: Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1] Output: 3 Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight. Example 2: Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1] Output: 4 Explanation: All points can be made visible in your field of view, including the one at your location. Example 3: Input: points = [[1,0],[2,1]], angle = 13, location = [1,1] Output: 1 Explanation: You can only see one of the two points, as shown above. Constraints: 1 <= points.length <= 105 points[i].length == 2 location.length == 2 0 <= angle < 360 0 <= posx, posy, xi, yi <= 100 hint: 1 Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. 2 We can use two pointers to keep track of visible points for each start point 3 For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting. """ import math from typing import List class MaximumNumberOfVisiblePoints: def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int: lx, ly = location degrees, dup = [], 0 for x, y in points: if x == lx and y == ly: dup += 1 else: degrees.append(math.atan2(ly - y, lx - x)) degrees.sort() degrees += [d + 2.0 * math.pi for d in degrees] angle = math.pi * angle / 180 s = res = 0 for e in range(len(degrees)): while degrees[e] - degrees[s] > angle: s += 1 res = max(res, e - s + 1) return res + dup
f9b91d7ecd3c963d83a15d143c74de08aa6b5985
malavikasekhar/Malavika
/arm.py
139
3.8125
4
y=int(input()) sum=0 temp=y while temp>0: digit=temp%10 sum += digit**3 temp//=10 if y==sum: print("yes") else: print("no")
fd9f267999c35582f19e7f662e4ac74f6fc86446
hearsid/hackerrank
/__python/py-basic-data-types/nested-list.py
561
3.546875
4
names = [] scores = [] if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input()) names.append(name) scores.append(score) scores = list(scores) originalScores = scores[:] scores = set(scores) scores = sorted(scores) secondMinScore = scores[1] indexes = [index for index, i in enumerate(originalScores) if i == secondMinScore] winners = [] for x in range(len(indexes)): winners.append(names[indexes[x]]) winners = sorted(winners) for i in range(len(winners)): print(winners[i])
a0bb8e3054f7dfbfa4eaae8f6ef700e2d0110224
mlbudda/Checkio
/elementary/max_digit.py
288
3.96875
4
# Max Digit def max_digit(number): """ Returns which digit in this number is the biggest """ return int(max(str(number))) # Running some tests.. print(max_digit(0) == 0) print(max_digit(52) == 5) print(max_digit(634) == 6) print(max_digit(1) == 1) print(max_digit(10000) == 1)
7e8c6d54ed6f6ecd0ed2a9f49af77a711039d15e
harismuzaffer/python_core
/magic_square.py
1,702
3.828125
4
from numpy import * n= int (input("Enter a positive odd integer")) while n%2==0 or n < 1: n = int (input("Enter a positive odd integer")) a= zeros((n, n), dtype= int) # print(a) m= int (n/2) row= 0 col= m a[row, col]= 1 count= 2 while count<= n*n: if (row-1 >= 0) and (col+1<= n-1) and (a[row-1, col+1]!= 0): #if existing element row+= 1 a[row, col]= count elif (row-1 >= 0) and (col+1<= n-1) and (a[row-1, col+1]== 0): # fill diagonally while row-1 >= 0 and col+1<= n-1 and a[row-1, col+1]== 0: col += 1 row -= 1 a[row, col]= count count+= 1 count-=1 elif (row-1< 0) and (col+1> n-1): #if both row and col out of range row+= 1 a[row, col]= count else: if (row-1< 0) or (col+1 > n-1): #if row or col out of range but not both if row== 0: col+= 1 if row== 0: row= n-1 else: row= 0 elif (col== 0) or (col== n-1): row-= 1 if col== 0: col=n-1 else: col= 0 a[row, col]= count count+= 1 print(a) # checking if valid magic square def check(a): colsum= sum(a, axis=0) rowsum = sum(a, axis=1) diogsum1= 0 diogsum2= 0 for i in range(n): diogsum1 += a[n- i -1, i] diogsum2 += a[i, n - i - 1] colset= set(colsum) rowset= set(rowsum) if (size(colset) == size(rowset) == 1) and diogsum1 == diogsum2 == list(colset): print("correct") check(a)
b5b68903dbe45ce962930adea6d4ae47522d7348
Raihan-Sharif/CorePythonPractice
/listMethod.py
1,210
4.125
4
list1 = [1,2,3] list2 = ['One','Two'] print('list1:',list1) print('list2: ',list2) print('\n') list12 = list1 + list2 print('list1 + list2 :',list12) list2x3 = list2 * 3 print('list2 * 3 ; ',list2x3) hasThree = 'Three' in list2 print('"Three" in list2? : ',hasThree) years = [1990,1991,1992,1993,1993,1993,1994] print('Years : ',years) print('\n -Reverse the list') # Reverse the list years.reverse() print('Years (After Reverse): ',years) aTuple = (2001,2002,2003) print('\n - Extend:',aTuple) years.extend(aTuple) print('Years (After Extend) : ',years) print('\n -Append 3000') years.append(3000) print('Years (After append) : ',years) print('\n - Remove 1993') years.remove(1993) print('Years (After Remove): ',years) print('\n -Years.pop()') # Remove last element of list lastElement = years.pop() print('last element : ',lastElement) print('\n') # Count print("Years.count(1993): ",years.count(1993)) # sort b = [6,3,8,2,7,3,9] b.sort() print(b) # List of Integers b = [6,3,8,2,7,3,9] b.sort(reverse=True) print(b) # list of String d = ['aaa','bb','c'] d.sort(key=len) print(d) d.sort(key=len,reverse=True) print(d) f = ['A','a','B','b','C','c'] f.sort(key=str.lower,reverse=False) print(f)
8db8a0435adaaa04915add6e8171919cab1eb048
rpparada/udemy_complete-python-bootcamp
/Ejercicios Antiguos/Jugador.py
2,505
3.5625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Dec 17 22:53:03 2017 @author: Rodrigo Parada """ from Persona import Persona class Jugador(Persona): def __init__(self, nombre, monto_inicial): Persona.__init__(self, nombre) self.monto_inicial = monto_inicial self.monto_restante = monto_inicial # Estado 0 = inactivo, 1 = en juego (apuesta inicial hecha), 2 = gano, 3 = empato, 4 = perdio, 5 = plantarce self.estado_jugador = 0 self.lista_cartas_juego = [] self.apuesta_actual = 0 def dame_monto_inicial(self): return self.monto_inicial def dame_monto_restante(self): return self.monto_restante def dame_apuesta_inicial(self): return self.apuesta_inicial def dame_estado_jugador(self): return self.estado_jugador def dame_lista_cartas_juego(self): return self.lista_cartas_juego def dame_apuesta_actual(self): return self.apuesta_actual def definir_estado_jugador(self, nuevo_estado): # Estado 0 = inactivo, 1 = en juego (apuesta inicial hecha), 2 = gano, 3 = empato, 4 = perdio, 5 = plantarce if nuevo_estado == 0 or 1 or 2 or 3 or 4 or 5: self.estado_jugador = nuevo_estado else: print 'Estado desconosido, jugador %s mantendra su estado actual' %self.nombre def definir_apuesta_actual(self, monto): self.apuesta_actual = monto self.monto_restante -= monto def perdir_carta(self, carta): if carta != None: self.lista_cartas_juego.append(carta) def dame_suma_cartas(self): total = 0 for carta in self.lista_cartas_juego: total += carta[0][1] return total def plantarce(self): # Estado 0 = inactivo, 1 = en juego (apuesta inicial hecha), 2 = gano, 3 = empato, 4 = perdio, 5 = plantarce if self.estado_jugador == 1: self.estado_jugador = 5 elif self.estado_jugador == 2: print 'No puedes plantarte, ya ganaste' elif self.estado_jugador == 3: print 'No puedes plantarte, empataste' elif self.estado_jugador == 4: print 'No puedes plantarte, ya perdiste' elif self.estado_jugador == 5: print 'No puedes plantarte, ya lo hiciste' def doblar_apuesta(self): pass def separar_cartas(self): pass
03e4efc02def809edd9cfcaf2d41740f130f7b9b
MHibbard77/lab6
/delete_account.py
1,813
3.578125
4
import unittest class deleteTests(unittest.TestCase): def setup(self): self.ui.command("create_user Admin AdminPassword") self.ui.command("create_user Supervisor SupervisorPassword") self.ui.commant("create_user TA TAPassword") self.ui.command("create_user Instructor InstructorPassword") """ When the delete command is entered, it takes one argument: - Username If the user has permission to delete and the username matches the database entry the user delete is successful: - "User deleted successfully" If the user does not have permission, failure: - "You do not have permission to delete users" If the username does not match or is omitted, failure: - "Error deleting account" """ def test_delete_fromAdmin(self): self.ui.command("login Admin AdminPassword") self.assertEqual(self.ui.command("delete TA"), "User deleted successfully") def test_delete_fromSupervisor(self): self.ui.command("login Supervisor SupervisorPassword") self.assertEqual(self.ui.command("delete TA"), "User deleted successfully") def test_delete_fromInstructor(self): self.ui.command("login Instructor InstructorPassword") self.assertEqual(self.ui.command("delete TA"), "You do not have permission to delete users") def test_delete_fromTA(self): self.ui.command("login TA TAPassword") self.assertEqual(self.ui.command("delete TA"), "You do not have permission to delete users") def test_delete_no_args(self): self.assertEqual(self.ui.command("delete"), "Error deleting account") def test_delete_wrongUsername(self): self.assertEqual(self.ui.command("delete TA1"), "Error deleting account") def
e0b911c04c186edd4085ab1cad69b23749bd839b
zhaoyb950810/python_learn_private
/day02/varDesc.py
1,214
4.03125
4
""" 使用变量保存数据病进行算术运算 a = 321 b = 123 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print(a ** b) """ """ 使用input()函数获取键盘输入 使用int()进行类型转换 用占位符格式化输出的字符串 a = int(input('a = ')) b = int(input('b = ')) print('%d + %d = %d' % (a, b, a + b)) print('%d - %d = %d' % (a, b, a - b)) print('%d * %d = %d' % (a, b, a * b)) print('%d / %d = %f' % (a, b, a / b)) print('%d // %d = %d' % (a, b, a // b)) print('%d %% %d = %d' % (a, b, a % b)) print('%d ** %d = %d' % (a, b, a ** b) """ """ 使用type()检查变量的类型 a = 100 b = 12.345 c = 1 + 5j d = 'hello, world' e = True print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) """ """ 运算符的使用 """ a = 5 b = 10 c = 3 d = 4 e = 5 a += b a -= c a *= d a /= e print("a = ", a) flag1 = 3 > 2 flag2 = 2 < 1 flag3 = flag1 and flag2 flag4 = flag1 or flag2 flag5 = not flag1 print("flag1 = ", flag1) print("flag2 = ", flag2) print("flag3 = ", flag3) print("flag4 = ", flag4) print("flag5 = ", flag5) print(flag1 is True) print(flag2 is not False)
90f20012d0d4e0ba295bb8c0b160d6e87ad0c838
wiichog/Simulation
/Homework/MiniProyecto1/Shierpinski.py
1,516
3.859375
4
# -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ import matplotlib.pyplot as plt import random class Point:#Creamos una clase que maneje el punto def __init__(self,x,y):#le mandamos los parametros x y y self.x = x#damos valor al parametro self.y = y#damos valor al parametro def f1(p): return Point(p.x/2, p.y/2)#primer funciones def f2(p): return Point(p.x/2 + 0.5, p.y/2)#segunda funcion def f3(p): return Point(p.x/2 + 0.25, p.y/2 + 0.5)#tercera funcion p = Point#creamos un objeto p.x=random.random()#damos valores al objeto para su parametro x p.y= random.random()#damos valores al objeto para su parametro y numbers = []#creamos un array para guardar resultados numbers.append(p)#guardamos en la primera posicion del array el objeto p for i in range(100000): rand = random.randint(1,3)#creamos un random entre 1 y 3 if rand ==1:#si da 1 evaluamos la primera funcion numbers.append(f1(numbers[i-1]))#guardamos el evaluo en el array elif rand == 2:#si da 2 evaluaos la segunda funcion numbers.append(f2(numbers[i-1]))#guardamos el evaluo en el array elif rand == 3:#si da 3 evaluamos la tercera funcion numbers.append(f3(numbers[i-1]))#guardamos el evaluo en el array xlist = [points.x for points in numbers]#sacamos las x de los objetos en el vector ylist = [points.y for points in numbers]#sacamos las y de los objetos en ele vector plt.plot(xlist, ylist, ".", ms=0.1)#ploteamos x,y, con un . y ms de 0.1
8fc7deeeb5aadc33f39e4077e51fb230f129e467
XeroHero/Python
/src/program3.py
103
3.765625
4
def adder(x, y): print (x + y) x = input("enter a number") y=input("Enter a number.") adder(x, y)
35d4569c10fe3a1f996068e7ebbc40008cd7b3b6
shanirajkali/coding
/list/arry/matrix.py
944
4.28125
4
num = input("Enter the size of matrix : ") mat=[] mat1=[] mul=[] i=0 j=0 k=0 add=0 while(add<num): mat.append([]) mat1.append([]) mul.append([]) add+=1 for i in range(0,num,1): print "Enter elements Matrix:1 Row : "+`i+1` for j in range(0,num,1): mat[i].append(input("enter th element : ")) for i in range(0,num,1): print "Enter elements Matrix : 2 of row : "+`i+1` for j in range(0,num,1): mat1[i].append(input("enter th element : ")) print "Ist Matrix" for i in range(0,num,1): print "Row : "+`i+1`+"" +`mat[i]` print "IInd Matrix" for i in range(0,num,1): print "Row : "+`i+1`+"" +`mat1[i]` add=0 for i in range(0,num,1): for j in range(0,num,1): for k in range(0,num,1): add+=mat[i][k]*mat1[k][j] mul[i].append(add) add=0 print "Multiplication Matrix" for i in range(0,num,1): print "Row : "+`i+1`+"" +`mul[i]`
3b08171268dc4e81317f9d8ad7c4961fe9070f82
kamojiro/Project-Euler
/027.py
734
3.765625
4
#import sys #input = sys.stdin.readline def is_prime(x): x = abs(x) y = x if x == 0 or x == 1: return False for i in range(2, int(x**(1/2))+1): while x%i == 0: x //= i if y > x: return False else: return True def consective_primes(a,b): for i in range(1000): if is_prime(i**2 + a*i + b): continue return i+1 def main(): ans = 0 l = 0 # for i in range(10): # print(i, is_prime(i)) for a in range(-999, 1000): for b in range(-1000, 1001): t = consective_primes(a,b) if l < t: l = t ans = a*b print(ans) if __name__ == '__main__': main()
b5a644355f16947758e6ff43dae0951e0cd3b9c2
RZachLamberty/google_code_jam
/2020/r1b/prob2.py
3,967
3.5625
4
# run with interactive runner and testing tool via # > python interactive_runner.py python testing_tool.py 0 -- python prob2.py import math import sys CENTER = 'CENTER' HIT = 'HIT' MISS = 'MISS' WRONG = 'WRONG' def throw_dart(i, j): print('{} {}'.format(i, j)) sys.stdout.flush() return input() def main(): T, A, B = [int(_) for _ in input().split(' ')] N = 10 ** 9 for test_idx in range(1, T + 1): # find a corner grid_size = math.ceil(2 * N / A) response = None for i in range(grid_size + 1): x = min(-N + i * A, N) for j in range(grid_size + 1): y = min(-N + j * A, N) if abs(x) == abs(y) == N: continue response = throw_dart(x, y) if response in [CENTER, HIT]: break if response in [CENTER, HIT]: break if response is None: raise ValueError('had a response of None') elif response == CENTER: # one of the corners was the center, not bad continue else: know_center = False # we know a point; binary search to find the elements along the x # and y directions that are the edges of the circle # + y if throw_dart(x, N) == HIT: y_plus = N else: lft, rgt = y, N while rgt - lft > 1: mp = (lft + rgt) // 2 resp_mp = throw_dart(x, mp) if resp_mp == CENTER: know_center = True break elif resp_mp == HIT: lft = mp else: rgt = mp if know_center: continue y_plus = lft # - y if throw_dart(x, -N) == HIT: y_minus = -N else: lft, rgt = -N, y while rgt - lft > 1: mp = (lft + rgt) // 2 resp_mp = throw_dart(x, mp) if resp_mp == CENTER: know_center = True break elif resp_mp == HIT: rgt = mp else: lft = mp if know_center: continue y_minus = rgt # + x if throw_dart(N, y) == HIT: x_plus = N else: lft, rgt = x, N while rgt - lft > 1: mp = (lft + rgt) // 2 resp_mp = throw_dart(mp, y) if resp_mp == CENTER: know_center = True break elif resp_mp == HIT: lft = mp else: rgt = mp if know_center: continue x_plus = lft # - x if throw_dart(-N, y) == HIT: x_minus = -N else: lft, rgt = -N, x while rgt - lft > 1: mp = (lft + rgt) // 2 resp_mp = throw_dart(mp, y) if resp_mp == CENTER: know_center = True break elif resp_mp == HIT: rgt = mp else: lft = mp if know_center: continue x_minus = rgt x_mid = (x_plus + x_minus) // 2 y_mid = (y_plus + y_minus) // 2 resp_mid = throw_dart(x_mid, y_mid) if resp_mid != CENTER: raise ValueError("fuck") if __name__ == '__main__': main()
50956f529320e551f07a71600677d930f51f66ab
rickyjreyes/Python_Tutorial
/1HelloWorld.py
575
4.03125
4
# HelloWorld.py # # First Program! # This prints hello world print("Hello World!") # More Practice: Make 5 of your own prints print("My name is Ricky!!!!") print("My favorite color is blue!!!!") print("Video games are cool!!!!") print("I love to code!!!!") print("This is Python :)") # This is a comment # Make your own comments """I am a comment with multiple lines """ # blah blah blah # The computer doesn't read this # Practice Input user = input("Enter input: ") print("Output: ", user) # Manipulate Inp ") print(int(user*10))
ef747ada6e37e32f8f40add6a7af83982b0754e5
Leotiv-Vibs/GeekBrains
/lesson_7/task_2.py
1,023
4.09375
4
# Отсортируйте по возрастанию методом # слияния одномерный вещественный массив, # заданный случайными числами на промежутке [0; 50). # Выведите на экран исходный и отсортированный массивы. import random array = [random.randint(-100, 100) for i in range(200)] print('Изначальный массив: ', array) def merge(left, right): result_ = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result_.append(left[i]) i += 1 else: result_.append(right[j]) j += 1 result_ += left[i:] + right[j:] return result_ def merge_sort(array): if len(array) <= 1: return array else: left = array[:len(array) // 2] right = array[len(array) // 2:] return merge(merge_sort(left), merge_sort(right)) print(merge_sort(array))
e38084a2d730cc69d69858f6044d8f5a65625c51
prubach/Python_Winter_2020_2
/bank.py
3,308
4.09375
4
class Customer: last_id = 0 def __init__(self, first_name, last_name, email): self.first_name = first_name self.last_name = last_name self.email = email Customer.last_id += 1 self.customer_id = Customer.last_id def __repr__(self): return self.__class__.__name__ + "(" + str(self.customer_id) + "): " + self.first_name + " " + self.last_name + " (" + self.email + ")" class Account: last_id = 0 def __init__(self, customer): self.customer = customer self._balance = 0 self.interest_rate = 0.05 Account.last_id += 1 self.account_id = Account.last_id def deposit(self, amount): #TODO - add validation to prevent misuse if amount < 0: raise NegativeAmountException('Negative amount: {0} amount {1}'.format(self.account_id, amount)) else: self._balance += amount print("Deposited: " + str(amount) + ". The new balance is: " + str(self._balance)) def charge(self, amount): #TODO - add validation to prevent misuse if amount < 0: raise NegativeAmountException('Negative amount: {0} amount {1}'.format(self.account_id, amount)) if self._balance >= amount: self._balance -= amount print("Charged: " + str(amount) + ". The new balance is: " + str(self._balance)) else: raise NotEnoughMoneyException('Not enough... ' + str(amount)) #print("Sorry, you do not have that much money on your account to withdraw: " + str(amount)) def calc_interest(self): #TODO - add implementation based on self.interest_rate pass def get_balance(self): print("The balance is: " + self._balance) return self._balance def __repr__(self): return "{0} ({1}): {2} belonging to: {3} {4} ".format(self.__class__.__name__, self.account_id, self._balance, self.customer.first_name, self.customer.last_name) #return self.__class__.__name__ + "(" + + ")" + " belonging to: " + self.customer.first_name + " " + self.customer.last_name + " (" + self.customer.email + ")" class Bank: def __init__(self): self.customers = [] self.accounts = [] def create_customer(self, first_name, last_name, email): c = Customer(first_name, last_name, email) self.customers.append(c) return c def create_account(self, customer): a = Account(customer) self.accounts.append(a) return a def transfer(self, acc_from, acc_to, amount): # TODO - implement it (input parameters are account ids) acc_from.charge(amount) acc_to.deposit(amount) def __repr__(self): return 'Bank(cust: {0}, acc: {1})'.format(self.customers, self.accounts) class BankException(Exception): pass class NotEnoughMoneyException(BankException): pass class NegativeAmountException(BankException): pass try: bank = Bank() c1 = bank.create_customer("Jan", "Kowalski", "j.kowalski@gmail.com") print(c1) a1 = bank.create_account(c1) a2 = bank.create_account(c1) print(a1) a1.deposit(200) a2.deposit(100) print(bank) bank.transfer(a1, a2, 250) print(bank) except BankException as be: print(str(be))
c0ce1f60be2d343535802f8243709471287cbaf9
fsym-fs/Python_AID
/month01/day13_oop/test/test01_extend.py
2,564
4.0625
4
""" 一家公司有如下几种岗位: 程序员:底薪+项目分红 测试员:底薪+bug*5 ..... 创建员工管理器 记录所有员工 提供计算总工资的功能 叙述: 三大特征: 封装:根据需求划分为员工管理器,程序员测试类 继承:创建员工类,隔离员工管理器和具体员工的变化 多态:员工管理器调用父类(员工)--->具体员工重写员工类的计算薪资方法--->添加具体员工对象方法 调父 重写 创建子对象 总结: 步骤:面对变化点,需要使用3步进行处理 价值(作用):程序灵活(扩展性强 = 开闭原则) 六大原则: 开闭原则:增加员工种类,员工管理器代码不变 单一职责:员工管理器:统一管理所有员工 程序员:为了定义该员工的薪资算法 测试员:为了定义该员工的薪资算法 依赖倒置:员工管理器调用员工类,不调用具体员工类 组合复用:优先选择组合:员工管理器通过组合关系,使用具体员工的薪资算法 里氏替换:向员工管理器添加的是员工类的子类对象--->子类重写员工类,先调用员工类的计算薪资方法,返回底薪,在添加自己的其他工资 迪米特:每个具体员工类之间低耦合,员工管理器和具体员之间低耦合 """ class Staff_manager: result = 0 def __init__(self): self.list_manager = [] def record(self, staff): wage = staff.wage() self.list_manager.append({staff.name: wage}) Staff_manager.result += wage print(self.list_manager, Staff_manager.result) class Staff: def __init__(self, base_salary, name): self.base_salary = base_salary self.name = name def wage(self): return self.base_salary class Programmer(Staff): def __init__(self, base_salary, share_out_bonus, name): super().__init__(base_salary, name) self.share_out_bonus = share_out_bonus def wage(self): return super().wage() + self.share_out_bonus class Tester(Staff): def __init__(self, base_salary, bug_number, name): super().__init__(base_salary, name) self.bug_number = bug_number def wage(self): return super().wage() + 5 * self.bug_number a = Staff_manager() p = Programmer(100, 1000, "hh") t = Tester(50, 10, "gg") a.record(p) a.record(t)
2b2f27da7b2b65967765bdc9e071c968da0ec1ca
ParijatDhar97/Data-Structures-Python
/Doubly Linked Lists/InsertionFront.py
1,974
4.6875
5
#Insert a node at the front of the List #Class for making nodes class Node: def __init__(self, data= None, next= None, prev= None): self.next= next self.prev= prev self.data= data #Class for making a Doubly Linked List class DoublyLinkedList: def __init__(self, head= None): self.head= head #Function to print the List in forward direction def printForward(self): if (self.head==None): print ("The List is empty!") return temp= self.head while(temp): print (temp.data, end='\t') temp= temp.next print ('') #Function to print the List in backward direction def printBackward(self): if (self.head==None): print ("The List is empty!") return temp= self.head while(temp.next!=None): temp= temp.next while(temp): print (temp.data, end='\t') temp= temp.prev print ('') #Function to insert a node at the front of the List #This function takes 1 parameter- data of the new node to be added def insertFront(self, data): #Store the original head node temp= self.head #Assign the new head node with given data self.head= Node(data) #Set the next pointer of new head to old head self.head.next= temp #Set previous pointer of new head to None self.head.prev= None #Set previous pointer of old head to new head temp.prev= self.head if __name__=='__main__': dllist= DoublyLinkedList() dllist.head= Node(2) second= Node(4) third= Node(6) fourth= Node(8) fifth= Node(10) #Setting the next pointers dllist.head.next= second second.next= third third.next= fourth fourth.next= fifth fifth.next= None #Setting the previous pointers dllist.head.prev= None second.prev= dllist.head third.prev= second fourth.prev= third fifth.prev= fourth print ("Original list") dllist.printForward() print ("Adding a node at the front with data 0") dllist.insertFront(0) dllist.printForward() print ("Printing the list in backward direction") dllist.printBackward()
0b649fc363adb0d813aa1745e69e7f09cf389437
JulyKikuAkita/PythonPrac
/cs15211/PathSumII.py
5,669
4.09375
4
__source__ = 'https://leetcode.com/problems/path-sum-ii/' # https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum-ii.py # Time: O(n) # Space: O(h), h is height of binary tree # DFS # # Description: Leetcode # 113. Path Sum II # # Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. # # For example: # Given the below binary tree and sum = 22, # 5 # / \ # 4 8 # / / \ # 11 13 4 # / \ / \ # 7 2 5 1 # return # [ # [5,4,11,2], # [5,8,4,5] # ] # # # Companies # Bloomberg # Related Topics # Tree Depth-first Search # Similar Questions # Path Sum Binary Tree Paths Path Sum III # import unittest # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a list of lists of integers def pathSum(self, root, sum): return self.pathSumRecu([], [], root, sum) def pathSumRecu(self, result, cur, root, sum): if root is None: return result if root.left is None and root.right is None and root.val == sum: result.append(cur + [root.val]) return result cur.append(root.val) self.pathSumRecu(result, cur, root.left, sum - root.val) self.pathSumRecu(result, cur, root.right, sum - root.val) cur.pop() return result class Solution2: # @param root, a tree node # @param sum, an integer # @return a list of lists of integers def pathSum(self, root, sum): result = [] self.pathSumRecu(result, [], root, sum) return result def pathSumRecu(self, result, cur, root, sum): if root is None: return result # if fo return, it means return null, bad behavior if root.left is None and root.right is None and root.val == sum: result.append(cur + [root.val]) return result self.pathSumRecu(result, cur + [root.val], root.left, sum - root.val) self.pathSumRecu(result, cur + [root.val], root.right, sum - root.val) return result class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) print Solution().pathSum(root, 22) print Solution2().pathSum(root, 77) if __name__ == '__main__': unittest.main() Java = ''' # Thought: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ # DFS # 2ms 61.15% class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } pathSum(root, sum, result, new ArrayList<>()); return result; } private void pathSum(TreeNode root, int sum, List<List<Integer>> result, List<Integer> list) { sum -= root.val; list.add(root.val); if (root.left == null && root.right == null) { if (sum == 0) { result.add(new ArrayList<>(list)); } } else { if (root.left != null) { pathSum(root.left, sum, result, list); } if (root.right != null) { pathSum(root.right, sum, result, list); } } list.remove(list.size() - 1); } } # 2ms 61.15% class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); dfs(root, sum, res, path); return res; } public void dfs(TreeNode root, int sum, List<List<Integer>> res, List<Integer> path){ if(root==null) return; path.add(root.val); if(root.left==null && root.right==null ){ if(root.val==sum) res.add(new ArrayList<Integer>(path)); return; } if(root.left!=null) { dfs(root.left,sum-root.val,res,path); path.remove(path.size()-1); } if(root.right!=null) { dfs(root.right,sum-root.val,res,path); path.remove(path.size()-1); } } } # BFS # 6ms 9.98% class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); Stack<TreeNode> stack = new Stack<TreeNode>(); int SUM = 0; TreeNode cur = root; TreeNode pre = null; while(cur!=null || !stack.isEmpty()){ while(cur!=null){ stack.push(cur); path.add(cur.val); SUM+=cur.val; cur=cur.left; } cur = stack.peek(); if(cur.right!=null && cur.right!=pre){ cur = cur.right; continue; } if(cur.left==null && cur.right==null && SUM==sum) res.add(new ArrayList<Integer>(path)); pre = cur; stack.pop(); path.remove(path.size()-1); SUM-=cur.val; cur = null; } return res; } } '''
78e92173a248f88ca7faef1135c8722f86247ba0
matttilton/coursework
/AdvDataStructures/intlistdelete.py
231
3.578125
4
# matthew tilton # not sure how to do this recursively this is as good as i can get in the 3 minutes that i had import intlist def delete(x, y): if x.first() == y: return x.rest() else: return delete(x.rest(), y)
30c615afe0c298ff40c453a3cea37d4c69f15c71
subha996/Wine-Quality-is-BAD
/src/get_data.py
1,017
3.890625
4
# read the parameter # process it # reyturn the dataframe. import os import yaml import pandas as pd import argparse # creating read param.yaml file def read_params(config_path): """This functon will read the yaml file and will return a dictionary.""" with open(config_path, 'r') as ymlfile: config = yaml.safe_load(ymlfile) # reading the yaml file as dictionary return config # creating function to get the data def get_data(config_path): # reading the data config = read_params(config_path) # print(config) data_path = config["data_source"]["s3_source"] # geeting data path from config file # print(data_path) df = pd.read_csv(data_path, sep=",", encoding="utf-8") # print(df.head()) return df # extra comment to make a example changes if __name__ == '__main__': args = argparse.ArgumentParser() args.add_argument("--config", default="params.yaml") parsed_args = args.parse_args() data = get_data(config_path=parsed_args.config)
edc2e940fde5a5363b1085c21669b4426eeb202c
smiley16479/AI_bootcamp
/week_0/Day02/ex03/csvreader.py
2,368
3.53125
4
import csv #Pas fini les check et les exceptions sont incompletes class CsvReader(object): def __init__(self, filename=None, sep=',', header=False, skip_top=0, skip_bottom=0): if filename == None: raise ValueError('filename not provided') return None self.filename = filename self.sep = sep self.header = header self.skip_top = skip_top self.skip_bottom = skip_bottom def __enter__(self): self.file_obj = open(self.filename, 'r') return self def __exit__(self, type, value, traceback): print("Exception has been handled") self.file_obj.close() return True def getdata(self): """ Retrieves the data/records from skip_top to skip bottom.Returns:nested list (list(list, list, ...)) representing the data.""" print(self.getdata.__name__) num_lines = sum(1 for line in self.file_obj) # count file lines print("num_lines :", num_lines) self.file_obj.seek(0) csvreader = csv.reader(self.file_obj, delimiter=self.sep) # header = next(csvreader) # print("header(getdata) :",header) rows = [] i = 0 last_column_nb = 0 try: for row in csvreader: if i >= self.skip_top and i < (num_lines - self.skip_bottom): rows.append(row) if last_column_nb != 0: print(row) for content in row: if content == '': print("bac") raise ValueError('corrupted csv file') if last_column_nb != len(row): print("bac") raise ValueError('corrupted csv file') else: last_column_nb = len(row) else: last_column_nb = len(row) i += 1 except ValueError as e: print(e) quit() print("row hors boucle :", row) print(rows) def getheader(self): """ Retrieves the header from csv file.Returns:list: representing the data (when self.header is True).None: (when self.header is False).""" if self.header:# and csv.Sniffer().has_header(self.filename.read(1024)): self.file_obj.seek(0) header = self.file_obj.readline() print("header(getheader) :", header) return header # from csvreader import CsvReader if __name__ == "__main__": with CsvReader('../resources/bad.csv', skip_top=5, skip_bottom=1) as file: data = file.getdata() header = file.getheader() # from csvreader import CsvReader # if __name__ == "__main__": # with CsvReader('../resources/bad.csv') as file: # if file == None: # print("File is corrupted")
ae1bb5f589622d728c4704420825085bbdc25870
vanya2143/ITEA-tasks
/hw-4/task_1.py
3,155
4.09375
4
""" К реализованному классу Matrix в Домашнем задании 3 добавить следующее: 1. __add__ принимающий второй экземпляр класса Matrix и возвращающий сумму матриц, если передалась на вход матрица другого размера - поднимать исключение MatrixSizeError (по желанию реализовать так, чтобы текст ошибки содержал размерность 1 и 2 матриц - пример: "Matrixes have different sizes - Matrix(x1, y1) and Matrix(x2, y2)") 2. __mul__ принимающий число типа int или float и возвращающий матрицу, умноженную на скаляр 3. __str__ переводящий матрицу в строку. Столбцы разделены между собой табуляцией, а строки — переносами строк (символ новой строки). При этом после каждой строки не должно быть символа табуляции и в конце не должно быть переноса строки. """ class MatrixSizeError(Exception): pass class Matrix: def __init__(self, some_list): self.data_list = some_list.copy() def __add__(self, other): if self.size() != other.size(): raise MatrixSizeError( f'Matrixes have different sizes - Matrix{self.size()} and Matrix{other.size()}' ) return [ [self.data_list[row][col] + other.data_list[row][col] for col in range(self.size()[1])] for row in range(self.size()[0]) ] def __mul__(self, other): return [[item * other for item in row] for row in self.data_list] def __str__(self): return ''.join('%s\n' % '\t'.join(map(str, x)) for x in self.data_list).rstrip('\n') def size(self): row = len(self.data_list) col = len(self.data_list[0]) return row, col def transpose(self): t_matrix = [ [item[i] for item in self.data_list] for i in range(self.size()[1]) ] self.data_list = t_matrix return self.data_list @classmethod def create_transposed(cls, int_list): obj = cls(int_list) obj.transpose() return obj if __name__ == '__main__': list_1 = [[1, 2, 9], [3, 4, 0], [5, 6, 4]] list_2 = [[2, 3, 0], [1, 2, 3], [5, 6, 4]] list_3 = [[2, 3], [1, 2], [5, 6]] t1 = Matrix(list_1) t1.transpose() t2 = Matrix.create_transposed(list_2) t3 = Matrix(list_3) print("t1: ", t1.data_list) print("t2: ", t2.data_list) print("t3: ", t3.data_list) # __add__ print("\nt1.__add__(t2) : ", t1 + t2) try: print("\nПробую: t1 + t3") print(t1 + t3) except MatrixSizeError: print('Тут было вызвано исключение MatrixSizeError') # __mul__ print("\nt2.__mul__(3): \n", t2 * 3) # __str__ print('\nt1.__str__') print(t1)
736b7fe16db2111f8bf80a450972f04417292c78
misan128/machine_learning
/100pagesbook/test_scikit.py
463
3.765625
4
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from import_file import * def train(x, y): from sklearn.linear_model import LinearRegression model = LinearRegression().fit(x,y) return model X, Y = getdata_x_y("Advertising.csv") print np.reshape(X, (-1, 1)) print np.reshape(Y, (-1, 1)) model = train(np.reshape(X, (-1, 1)), np.reshape(Y, (-1, 1))) x_new = np.reshape([23.0], (-1, 1)) y_new = model.predict(x_new) print y_new
c3f9cbd07cf815ef9ddf431895461f5211bf18ee
depsir/university
/softcomputing/main.py
1,282
3.609375
4
#!/usr/bin/python import csv import geometric_transformation START_POSITION_FILE = "data/start_position" CAMERAS_DATA_FILE = "data/camera_rotations" def main(): point = geometric_transformation.geometric_transformation(3,5,7) with open(CAMERAS_DATA_FILE, 'rb') as csvfile: data = csv.reader(csvfile, skipinitialspace=True) for row in data: # skip row with comments or empty if len(row) == 0: continue if row[0][0] == '#': continue # transform text to integers row = map(lambda x: float(x), row) point.rotate_X_axis(row[0]) # rotate of value point.rotate_X_axis(row[1]) # rotate as the error value print point.actual_position point.rotate_Y_axis(row[2]) # rotate on Y as value point.rotate_Y_axis(row[3]) # rotate as the error value print point.actual_position point.rotate_Z_axis(row[4]) # rotate on Y as value point.rotate_Z_axis(row[5]) # rotate as the error value print point.actual_position point.traslate(row[6]+row[7], row[8]+row[9], row[10]+row[11]) print point.actual_position print "-----------------------" __init__ = main()
0f199da2d995d37b6ae6a499d4ffcb61a99712af
amourbrus/spiders_crawder
/concurrent/A_thread_share_source.py
1,170
3.84375
4
# 问题导入:共享资源导致资源竞争问题 import threading import time g_num = 0 def foo1(n, mutex): # mutex.acquire() global g_num for i in range(n): # time.sleep(0.001) g_num += 1 # mutex.release() print('foo1 ----->',g_num) def foo2(n, mutex): global g_num # mutex.acquire() for i in range(n): # time.sleep(0.001) g_num += 1 # mutex.release() print('foo2---->', g_num) def main(): # 创建锁,默认是打开的 mutex = threading.Lock() t1 = threading.Thread(target=foo1, args=(1000000, mutex)) t2 = threading.Thread(target=foo2, args=(1000000, mutex)) t1.start() t2.start() time.sleep(10) # 保证子线程执行完 # t1.join() # t2.join() print('finally num --->', g_num) if __name__ == '__main__': main() # 都在循环外面加锁,都不解锁,就会导致最后的结果阻塞(无finally),两个都是100000 # 在外部加锁,再解锁,就 # 不加锁,两者数据都是错的(一错都错,全局变量) -- foo1 1279745 foo2 1393459 finally_num 1393459
54adbc9f3e16d44527b459656d29718ceec5769f
mcatcruz/school_schedule
/school_schedule/student.py
406
3.578125
4
class Student(): def __init__(self, name, grade, classes): self.name = name self.grade = grade self.classes = classes def add_class(self, class_name): self.classes.append(class_name) def get_num_classes(self): return len(self.classes) def summary(self): return f"{self.name} is a {self.grade} enrolled in {self.get_num_classes()} classes"
df92c863b89e5790fac23983924c0fe23a2760de
GabrielSant0204/Python
/IMC.py
820
3.9375
4
print('================================') print(' CALCULE SEU IMC ') print('================================') nome = input('Qual é seu nome?').capitalize() altura = float(input('qual é sua altura?')) peso = int(input('qual é seu peso?')) imc = peso / (altura * altura) print('o IMC de {} é {}'.format(nome, imc)) if imc <= 18.5: print('você está abaixo do peso. Alimente-se melhor!') elif imc >= 18.6 and imc <= 24.9: print('Peso Ideal, PARABÉNS!!!') elif imc >= 25.0 and imc <=29.9: print('levemente acima do peso') elif imc >= 30.0 and imc <=34.9: print('obesidade grau I, CUIDADO!!!') elif imc >= 35.0 and imc <=39.9: print('obesidade grau II,ISSO É SEVERO!!!') elif imc >= 40: print('obesidade grau III, ISSO JÁ É MÓRBIDO!!!')
300fd0954738d2e3019772afed0cefc0774dfced
amit-mittal/Programming-Questions-Practice
/py/euler7.py
240
3.84375
4
import array import math n=3 counter=1 def isprime(n): f=0 for i in range(int(math.sqrt(n)),2,-1): if n%i==0: f=1 return 0 if f==0: #print n return 1 while counter<10001: if (isprime(n)): counter+=1 print n n+=2
a5d22871d82c3e3ce63db7e2e1fe52ebb1a84945
BanarasiVaibhav/LearningPython
/RE.py
479
3.796875
4
import re #import regular expression module https://docs.python.org/3/library/re.html message='''Hello my name is vaibhav i am vaibhav my real name is also vaibhav my friende call me vaibhav''' print(re.finditer(r'vaibhav',message)) # finditer print(re.search(r'vaibhav',message)) #searches all over string print(re.match(r'vaibhav',message)) #matches pattern only at begining print(re.findall(r'vaibhav',message)) # find all returns list
21a882cd0b64abaa0f017620fea827a958e65b2e
mgh3326/programmers_algorithm
/KAKAO BLIND RECRUITMENT/2017/1차/셔틀버스/다시풀기.py
1,362
3.546875
4
import heapq def solution(n, t, m, timetable): answer = '' time_list = [] for timetable_value in timetable: hour, minute = map(int, timetable_value.split(":")) minute += hour * 60 heapq.heappush(time_list, minute) start_minute = 9 * 60 for bus_start_time_index in range(n): current_minute = start_minute + bus_start_time_index * t temp_list = [] for bus_count_index in range(m): if len(time_list) == 0: break heappop = heapq.heappop(time_list) if heappop > current_minute: heapq.heappush(time_list, heappop) break else: temp_list.append(heappop) if len(temp_list) < m: answer_minute = current_minute else: answer_minute = temp_list[-1] - 1 answer_hour = str(answer_minute // 60) answer_minute = str(answer_minute % 60) if len(answer_hour) == 1: answer_hour = '0' + answer_hour if len(answer_minute) == 1: answer_minute = '0' + answer_minute answer = answer_hour + ":" + answer_minute return answer print( solution( 1, 1, 1, ["09:10"] ) ) print( solution( 1, 1, 5, ["08:00", "08:01", "08:02", "08:03"] ) ) print( solution( 2, 10, 2, ["09:10", "09:09", "08:00"] ) )
5a7811108cbf4d942390c2fff5101fa4f62d075c
Cammr94/Spring2019_Python1_Data119
/Week4/reading_in_class_assignment_1a.py
879
4.3125
4
# -*- coding: utf-8 -*- """ Cameron Reading Data 119 2/27/2019 In-Class Assignment We are figuring out if a year is a leap year or not and output how many days are in February """ #Asking User for a year, and assigning it to a variable entered_year = int(input("Please enter a year to find out how many days February has: ")) #Running modular division (specifically to see if it is a 0) and assigning the result to a variable divide_by_4 = entered_year % 4 divide_by_100 = entered_year % 100 divide_by_400 = entered_year % 400 #Checking the results of the modular division, and determining output phrase if divide_by_4 == 0 and divide_by_100 == 0 and divide_by_400 ==0: print("February has 29 Days in", entered_year) elif divide_by_4 == 0 and divide_by_100 != 0: print("February has 29 Days in", entered_year) else: print("February has 28 Days in", entered_year)
58c1d9670f410755863f9df44ed441767d493d97
PVyukov/python_lessons
/Lesson1/dz1_4.py
261
3.78125
4
#!/usr/bin/python3 var_number = int(input('Введите целое положительное число: ')) var_max = 0 while var_number>1: var_let=var_number %10 var_number //= 10 if var_let > var_max: var_max = var_let print(var_max)
7c493dab63c5dd0817c03dc2876534ebdaf47cb7
milanshah/Python_assignements
/python_hw/ex3-1.py
178
3.75
4
def donuts(count): if count < 10: return count else: return 'manay' print(donuts(5)) print(donuts(23)) """ return 'no of donuts ' + str(count) """
8beb4ed0f4ca5d113ff6f165fc642464a1aa6f40
defgsus/cthulhu2d
/src/util/timer.py
1,048
3.734375
4
import time class Timer: def __init__(self, count=None): self.count = count self.start_time = None self.end_time = None self.length = None @property def rate(self): if not self.count or self.length is None: return None return self.count / self.length def __enter__(self): self.start_time = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.end_time = time.time() self.length = self.end_time - self.start_time def print(self, desc=None, file=None): if desc: text = f"{desc} " else: text = "" if self.count: text += f"x{self.count} " text += f"took {self._round(self.length)} seconds" rate = self.rate if rate: text += f" = {self._round(rate)} per second" print(text, file=file) @staticmethod def _round(x): if abs(x) < 1: return round(x, 5) return round(x, 2)
90091e7c97234061dd319e92fd7f5d7544d7fa18
iffy/eliot
/eliot/_py3json.py
746
3.96875
4
""" Python 3 JSON encoding/decoding, emulating Python 2's json module. Python 3 json module doesn't support decoding bytes or encoding. Rather than adding isinstance checks in main code path which would slow down Python 2, instead we write our encoder that can support those. """ import json as pyjson class JSONEncoder(pyjson.JSONEncoder): """ JSON encoder that supports L{bytes}. """ def default(self, o): if isinstance(o, bytes): return o.decode("utf-8") return pyjson.JSONEncoder.default(self, o) _encoder = JSONEncoder() def loads(s): if isinstance(s, bytes): s = s.decode("utf-8") return pyjson.loads(s) def dumps(obj): return _encoder.encode(obj).encode("utf-8")
9555951dbcbfc8520338292bd29a188953e8326a
nicolageorge/play
/expanded_form.py
354
3.671875
4
def expanded_form(num): # num = float(num) str = "{}".format(num % 10) num = num / 10 cnt = 10 while num / 10 > 0: str = "{} + {}".format(num % 10 * cnt, str) num = num / 10 cnt = cnt * 10 str = "{} + {}".format(num % 10 * cnt, str) return str print expanded_form(56849848694165161561561651651657695)
29d018d1e0686735d33c696903798cb4eb5d99fb
PMiskew/Year9Design_MISP
/Hello.py
411
4.15625
4
import math #Information about program print("This program calculates the volume of") print("a cylinder given radius and height") #Input r = int(input("What is the radius: ")) h = int(input("What is the height: ")) #Process v = math.pi*r*r*h v = round(v,3) #Output print("The volume of a cylinder with") print("r = ",r," units") print("h = ",h," units") print("is ",v," units cubed") print("PROGRAM DONE")
c5dc77d32af67bd6d9ab32a6dd413dfd03e463fb
EricLiu750501/stanCode-projects
/stanCode projects/boggle/anagram.py
3,573
4.09375
4
""" File: anagram.py Name: Eric Liu ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 19 If you correctly implement this program, you should see the number of anagrams for each word listed below: * arm -> 3 anagrams * contains -> 5 anagrams * stop -> 6 anagrams * tesla -> 10 anagrams * spear -> 12 anagrams """ # Constants FILE = 'dictionary.txt' # This is the filename of an English dictionary EXIT = '-1' # Controls when to stop the loop dictionary_words = set() # set, It has all the words in dictionary.txt permutation_words = set() # set, It has all the words that you input and be permuted def main(): print(f'Welcome to stanCode \"Anagram Generator\" (or {EXIT} to quit) ') while True: print('-----------------------') word = input('Find anagram for: ').lower() # can input uppers too. read_dictionary(word) if word == EXIT: break find_anagrams(word) # take the intersection with words in dict and words we permute print_words = sorted(dictionary_words.intersection(permutation_words)) if len(print_words) == 0: print('No anagrams!') else: for w in print_words: print(f'\"{w}\"', end=', ') print(f'{len(print_words)} anagram(s) in total') def read_dictionary(w): print('Searching...') # avoid that users think the computer is crash with open('dictionary.txt', 'r') as f: global dictionary_words dictionary_words = set() l = [] for ele in w: # if ele not in l: l.append(ele) for word in f: l2 = [] word = word.strip('\n') for e in word: # if e not in l2: l2.append(e) if sorted(l) == sorted(l2): dictionary_words.add(word) ########################### # can do the assignment by only this ########################### def find_anagrams(s): """ :param s: str, the word you input :return: None """ global permutation_words lst = [] # new word that permuted from letter_list letter_list = [] # stop ---> ['s', 't', 'o', 'p'] permutation_words.clear() # clear permutation words from previous run for letter in s: letter_list.append(letter) find_anagrams_helper(letter_list, lst) def find_anagrams_helper(letters, lst): # Base case if len(lst) == len(letters): if sorted(letters) == sorted(lst): # True--> means the the numbers of each litters in a word is the same w = '' # str will be add from element in lst for i in range(len(lst)): w += lst[i] if w not in permutation_words: permutation_words.add(w) else: # Recursion if has_prefix(lst, letters): for ele in letters: # choose lst.append(ele) # explore find_anagrams_helper(letters, lst) # un-choose lst.pop() def has_prefix(lst, letters): s = '' if len(lst) < len(letters) / 2 + 1: for ltr in lst: s += ltr for ele in dictionary_words: if ele.startswith(s): return True return False if __name__ == '__main__': main()
4976bc621fb5644c098540dceef938726c6750cb
JamesGilsenan/Python-3
/Linked Lists/Singly_Linked_List.py
3,488
3.953125
4
class Node: def __init__(self, data, position=0): self.data = data self.next = None self.position = position def __repr__(self): return str(self.data) class LinkedList: def __init__(self): self.head = None def __str__(self): current_node = self.head string = "[" if self.head is None: return "Linked List is empty" while current_node is not None: string += str(current_node.data) if current_node.next is not None: string += ", " current_node = current_node.next string += "]" return string def get(self, index): if index > self.size() - 1: raise IndexError("List index is out of range") current = self.head count = 0 found = False while current is not None and not found: if count == index: found = True else: current = current.next count += 1 return current.data def add_at_head(self, new_node): if self.head is None: self.head = new_node else: next_node = self.head self.head = new_node self.head.next = next_node def add_at_tail(self, new_node): last_node = self.head if self.head is None: self.head = new_node return while True: if last_node.next == None: break last_node = last_node.next last_node.next = new_node def add_at_index(self, index, new_node): temp = Node(new_node) current = self.head previous = None count = 0 found = False if index > self.size(): print("Cannot insert item. Index out of range") while current is not None and not found: if count == index: found = True else: previous = current current = current.next count += 1 if previous is None: temp.next = self.head self.head = temp else: temp.next = current previous.next = temp def delete_at_index(self, index): if index > self.size() - 1: raise IndexError("List index out of range") current = self.head previous = None count = 0 found = False while current is not None and not found: if count == index: found = True else: previous = current current = current.next count += 1 if previous is None: self.head = current.next else: previous.next = current.next def size(self): count = 0 last_node = self.head while True: if last_node.next == None: return count + 1 last_node = last_node.next count += 1 """ first_node = Node("John") second_node = Node("Ben") third_node = Node("Paddy") fourth_node = Node("Lad") linked_list = LinkedList() linked_list.add_at_head(first_node) linked_list.add_at_head(second_node) linked_list.add_at_tail(third_node) #print(linked_list) #linked_list.add_at_index(3, fourth_node) #linked_list.delete_at_index(3) print(linked_list.get(2)) print(linked_list) print(linked_list.size()) """
c09a861b648713f8339942dab836d7f005b47304
VPanjeta/Wikipedia-Game
/src/get_links.py
501
3.640625
4
import urllib.request main = 'http://en.wikipedia.org/wiki/Main_Page' #Main page url def get_links(source_url, regex): page = urllib.request.urlopen(source_url) page_html = str(page.read()) links = set() for link in regex.findall(page_html): links.add("http://en.wikipedia.org" + link.split("\"")[1]) #Remove entries to the main page links.discard(main) return links #returns a set of all links from a page except the link to the main page
c3cae8dc33c6b0e13dbf2f51f524c9e38991493c
dennisasilva/PythonCourse
/Exercicios/11-20/ex011.py
495
4
4
# Desafio 11 # Faça um programa que leia a largura e altura de uma parede em metros, calcule a sua area e a quantidade de tinta # necessária para pintá-la, sabendo que cada litro de tinta pinta uma area de 2m. alt = int(input('Digite a altura da parede em metros: ')) larg = int(input('Digite a largura da parede em metros: ')) area = alt * larg tinta = area / 2 print('A quantidade de metros que você vai pintar é {} metros sendo necessário {:.1f} litros de tinta'.format(area,tinta))
98975cd3e6bbe9433dd4b5ea838c2974f48e6706
RobertHan96/English_Coding_Test
/HackerRank_staircase.py
328
3.875
4
sharp = 1 def staircase(n): global sharp for i in range(n): for j in range(n+1): if j == n: print(end='\n') sharp += 1 elif j < n and j + sharp < n: print(' ', end='') else: print('#', end='') staircase(100)
ca39f812bd8271617cbd4ca3629ada41d2569c3d
blueclowd/leetCode
/python/0187-Repeated_dna_sequences.py
623
3.640625
4
''' Description: All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. ''' class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: table = defaultdict(int) for i in range(len(s) - 9): sub_s = s[i:i + 10] table[sub_s] += 1 return [sub_s for sub_s, frequency in table.items() if frequency > 1]
84b090f3def06b79df70873c40e9fb0d44f59a6a
jhoancardona07/code_challenges
/validateBalancedParenthesis/JLH.py
752
3.96875
4
class Solution: def isValid(self, string): stack=[] for character in string: if(character == "(" or character=="[" or character=="{"): stack.append(character) if(character == ")"): if(not(stack.pop()=="(")): stack.append("(") if(character == "]"): if(not(stack.pop()=="[")): stack.append("[") if(character == "}"): if(not(stack.pop()=="{")): stack.append("{") if(len(stack)==0): return True else: return False #TEST ZONE s="((()))" print(s, Solution().isValid(s)) s="[()]{}" print(s, Solution().isValid(s)) s="({[)]" print(s, Solution().isValid(s)) s="" print(s, Solution().isValid(s))
f19e08ccb6ba18c76d2409be174217cbcc2575be
jancyrusm/programming-logic-and-design
/L/10.py
999
4.3125
4
# Jan Cyrus M. Villar # BS CoE 1-6 ''' Write a program that accepts three numbers and prints "All numbers are equal" if all three numbers are equal, "All numbers are different" if all three numbers are different. If only one is different, print that number. Input first number: 256 Input second number: 352 Input third number: 256 352 is different ''' print() panguna = int(input("Please input the 1st number: ")) pangalawa = int(input("Please input the 2nd number: ")) pangaltlo = int(input("Please input the 3rd number: ")) if panguna == pangalawa == pangaltlo: print("All numbers are equal.") print() elif panguna != pangalawa != pangaltlo: print("All numbers are different.") print() elif panguna == pangalawa != pangaltlo: print(pangaltlo, "is different.") print() elif pangaltlo == pangalawa != panguna: print(panguna, "is different.") print() elif panguna == pangaltlo != pangalawa: print(pangalawa, "is different.") print()
e31d97afebcc6af002d4f40cf6b2d51dcb22fb9d
nabilnabs1080/FIJ_Robotique
/00_algorithmique/01_python/Conditions.py
289
3.8125
4
# if > si # elif > sinon si # else > sinon age = 15 if age < 10 : print("trop jeune") elif age < 20: print("ok") elif age >= 20: print("trop vieux") else: print("egale a 20") mots= "bonjour" if "o" in mots: print("in est dedans") else : print("pas dedans")
19c5316488b97967c3d1eed77654ecd33522cd7a
Brenda-M/Password-Locker
/main.py
5,997
4.21875
4
#!/usr/bin/env python from user_credentials import User, Credentials import pyperclip import string import random def create_user(username, password): ''' Creates a new user account ''' new_user = User(username, password) return new_user def save_user(user): ''' Saves a user account ''' user.save_user() def verify_user(user_name, password): ''' Ensures that a user has created an account before the can log in ''' finding_user = User.find_user(user_name, password) return finding_user def create_credential(user_name, account_name, password): ''' Creates a new credential ''' new_credential = Credentials(user_name, account_name, password) return new_credential def save_credentials(credential): ''' Saves a user's credentials ''' Credentials.save_credentials(credential) def del_credential(credential): ''' Deletes a credential from the account ''' Credentials.delete_credential(credential) def display_credential(): ''' Displays the saved credentials ''' return Credentials.display_credentials() def find_account (account_name): ''' Finds a saved credential by it account name ''' return Credentials.find_by_account_name(account_name) def copy_credential(account_name): ''' Copies a credentials password to the clipboard ''' return Credentials.copy_credentials(account_name) def generate_password(length): ''' Generates a random password for the user ''' letters = string.ascii_letters + string.digits return ''.join((random.choice(letters)) for i in range(length)) def main(): print('') print("Hello There! Welcome to the password vault") while True: print('-' * 70) print("Use these short codes to navigate through the vault: \n ca - To create an account \n li - To log In \n ex - To Exit") short_code = input("Enter code here: ").lower() print('') print('-' * 70) if short_code == 'ca': print("To create a new account: ") user_name = input ("Enter a username: ") password = input ("Create a password: ") save_user(create_user(user_name, password)) print('') print('-' * 70) print(f"Thank you for joining us {user_name}") print(f"The password to your account is {password}. \nYou can log in to your account below") elif short_code == 'li': print("Great to see you again.\nEnter your username and password below in order to log in") print('') user_name = input("Username: ").lower() password = str(input("Password: ")) user_exists = verify_user(user_name, password) if user_exists == user_name: print('-' * 70) print(f"Welcome {user_name}, \nChoose one of the options below to proceed") print('') while True: print("cc - To add a credential \ndc - To display credentials \ndel - To delete a credential \nc - To copy a password \nex - To exit") short_code = input ("Enter code: ").lower() print('-' * 70) if short_code == "cc": print("Enter your credentials below") account_name = input("Name of site: ").lower() user_name = input ("Username: ").lower() while True: print("Enter: \n op to create your own custom password, \n gp to generate one \n ex to exit") password_choice = input().lower() if password_choice == "op": password = input("Enter a password: ") break elif password_choice == "gp": password = generate_password(8) break elif password_choice == "ex": break else: print('-' * 70) print("The code you have entered does not exist. Please try again") print('-' * 70) save_credentials(create_credential(user_name, account_name, password)) print('') print('-'* 70) print(f"Your credentials have been saved succesfully. \nAccount Name: {account_name} \nUserName: {user_name}. \nPassword: {password}") print('') print('-'* 70) elif short_code == 'del': print('-' * 70) delete_account = input("Enter the name of the account whose credentials you would like to delete, e.g Twiter: ").lower() del_credential(find_account(delete_account)) print('') print('Credentials deleted succesfully') print('-' * 70) elif short_code == 'dc': if display_credential(): print('=' * 70) print("Here is a list of all your credentials") print('') for user in display_credential(): print(f'Account Name: {user.account_name} UserName: {user.user_name} Password: {user.password}') print('') print('=' * 70) else: print('-' * 70) print("There are no saved credentials") print('-' * 70) elif short_code == "c": choose_site = input("Enter the name of the site whose password you would like to copy: ").lower() copy_credential(choose_site) print('') print("Password copied succesfully") print('=' * 70) elif short_code == "ex": print("You have been logged out. Goodbye!!") break else: print('-' * 70) print("Please check your short code and try again") print('-' * 70) else: print('') print("Invalid login credentials. Check your username and password and then try again") elif short_code == "ex": print("We are sorry to see you leave. Goodbye!!") break else: print('-' * 70) print("Please check your short code and try again") print('-' * 70) if __name__ == '__main__': main()
7a8d3a175c8a0681558a01198c23eeb5c5d9cfdc
sng0616/practice
/digressions/book_search/ISBN_search.py
1,328
3.609375
4
import requests from keys import google as GBooks_Key pros_ISBN = raw_input("Please enter an ISBN. ") # A function that takes an ISBN and finds the corresponding book if the ISBN is in use def find_book_isbn(pros_ISBN): GBooks_API = "https://www.googleapis.com/books/v1/volumes?q=isbn:" fields = "items/volumeInfo(title, authors, pageCount, categories, publisher), items/searchInfo(textSnippet)" GBooks_URL = GBooks_API + pros_ISBN + "&key=" + GBooks_Key + "&fields=" + fields GBooks_JSON = requests.get(GBooks_URL).json()['items'][0] title, authors, page_count, genre, summary = GBooks_JSON['volumeInfo']['title'], ', '.join(GBooks_JSON['volumeInfo']['authors']), GBooks_JSON['volumeInfo']['pageCount'], ', '.join(GBooks_JSON['volumeInfo']['categories']), GBooks_JSON['searchInfo']['textSnippet'] return title, authors, page_count, genre, summary # A function that encodes unicode objects and replaces poorly encoded characters to quotes def encode_str(json_output): return [x.encode('ascii','ignore').replace('&quot;','"').replace('&#39;','\'') if isinstance(x, unicode) else x for x in json_output] try: print encode_str(find_book_isbn(pros_ISBN)) except KeyError: print "This book is no additional data available through Google Books." except UnboundLocalError: print "Publisher information is unavailable."
215d981de996d7a3221de0d765dd4581a8bb4bba
balajisuresh1359/Sorting-Algorithm
/mergeSort.py
585
3.96875
4
def merge(arr,leftArray,rightArray): i=j=k=0 while i < len(leftArray) and j < len(rightArray): if leftArray[i] < rightArray[j]: arr[k]=leftArray[i] i+=1 else: arr[k]=rightArray[j] j+=1 k+=1 while i<len(leftArray): arr[k]=leftArray[i] i+=1 k+=1 while j<len(rightArray): arr[k]=rightArray[j] j+=1 k+=1 return arr def mergeSort(arr): if len(arr) == 1: return arr mid = len(arr)//2 return merge(arr,mergeSort(arr[:mid]),mergeSort(arr[mid:])) if __name__=="__main__": arr = [] for i in range(10,0,-1): arr.append(i) mergeSort(arr) print(arr)
24edb9f9fc4bb5846bd04c6f995b8cdd750faed0
mychristopher/test
/Selenium练习/webdriver_api/2_browser_back.py
583
3.75
4
""" * back() 后退 * forward() 前进 * refresh() 刷新 """ from selenium import webdriver driver = webdriver.Chrome() # 访问百度首页 first_url = 'http://www.baidu.com' print("now access %s" %(first_url)) driver.get(first_url) # 访问新闻页面 second_url = 'http://news.baidu.com' print("now access %s" %(second_url)) driver.get(second_url) # 返回(后退)到百度首页 print("back to %s " %(first_url)) driver.back() # 前进到新闻页 print("forward to %s" %(second_url)) driver.forward() driver.refresh() # 刷新当前页面 driver.quit()
ea11639f8bc09d8bfee35cc526987780bc20422d
Svensson17/python-project-lvl1
/brain_games/games/brain_progression.py
513
3.578125
4
import random RULE = "What number is missing in the progression?" def get_question_and_answer(): result = [] score = random.randint(1, 15) score2 = random.randint(1, 5) score1 = score + (score2 * 9) for num in range(score, score1, score2): result.append(str(num)) right_answer = random.choice(result) for index, value in enumerate(result): if right_answer == value: result[index] = ".." question = " ".join(result) return question, right_answer
a7ea3f851eb47b27aa2bb53268596fbad6a0e1d4
AJPassDe/pandas
/05-data-types-and-missing-values.py
2,665
3.53125
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 19 11:37:09 2020 Info from: https://www.kaggle.com/residentmario/data-types-and-missing-values @author: AJ """ import pandas as pd reviews = pd.read_csv("input/wine-reviews/winemag-data-130k-v2.csv", index_col=0) # ============================================================================= # Data types # ============================================================================= # grab type of specific column reviews.price.dtype # returns dtype of every column reviews.dtypes # convert column poiints from int64 to float 64 reviews.points.astype('float64') # index has its own datatype reviews.index.dtype # ============================================================================= # Missing Data # ============================================================================= # entries missing values are given value NaN = "Not a Number". NaN are always float64 dtype. # to select Nan data use pd.isnull() or pd.notnull otherwise. countryNull = reviews[pd.isnull(reviews.country)] # replacing missing values is common operation. Handy method: fillna(). Replace each "NaN" with "Unknown". reviews.region_2.fillna("Unknown") # Backfill strategy: fill each missing value with the first non-null value that appears sometime # after the given record in the database # we may have a non-null value that we would like to replace. For example, suppose that since this # dataset was published, reviewer Kerin O'Keefe has changed her Twitter handle from # @kerinokeefe to @kerino. One way to reflect this in the dataset is using the replace() method: reviews.taster_twitter_handle.replace("@kerinokeefe", "@kerino") # The replace() method is worth mentioning here because it's handy for replacing missing data which is given # some kind of sentinel value in the dataset: things like "Unknown", "Undisclosed", "Invalid", and so on. # 2. Create a Series from entries in the points column, but convert the entries to strings. # Hint: strings are str in native Python. point_strings = reviews.points.astype('str') # 3. Sometimes the price column is null. How many reviews in the dataset are missing a price? missing_price_reviews = reviews[reviews.price.isnull()] n_missing_prices = len(missing_price_reviews) # 4. What are the most common wine-producing regions? Create a Series counting the number of times each value # occurs in the region_1 field. This field is often missing data, so replace missing values with Unknown. # Sort in descending order. Your output should look something like this: reviews_per_region = reviews.region_1.fillna("Unknown").value_counts().sort_values(ascending=False)
8bd1d69756c4352f9e2be105c5bbd4c9c9922b9e
Roberto09/Tutorials-Python
/Proyectos Personales/Numeros Primos/1o.py
358
3.890625
4
"""numeros primos""" print ("Elige el entre que numeros quieres encontrar los numeros primos") ninicial= input("Numero inicial: ") nfinal= input("Numero final: ") def alg(p): z=True for n in range(2,(p/2)+1): y=float(p)%float(n) if y != 0: continue else: z=False break return z for x in range(ninicial,nfinal): if alg(x): print(x)
936663177a9d736ed36f4ee59ba0e1e6395039c8
SurajB/Practice
/area.py
1,064
4.3125
4
#This program calculates the area of a circle or a triangle from math import * import time from datetime import datetime now=datetime.now() print "The calculator is starting up" print "%s-%s-%s %02d:%02d:%02d" % (now.year, now.month, now.day, now.hour, now.minute, now.second) time.sleep(2) option=raw_input("What is the area you want to find? C for Circle, T for Triangle \n").upper() if(option=="C"): rad=float(raw_input("Enter the radius of the circle: ")) unit=raw_input("What is the unit measure: ") area_circle=pi*rad*rad print "The pie is baking..." time.sleep(2) print "The area of the circle is "+ str(round(area_circle,2)) + " " + str(unit) elif option=="T": ht=float(raw_input("Enter the height of the triangle: ")) base=float(raw_input("Enter the base of the triangle: ")) unit=raw_input("What is the unit measure: ") area_tri=(base*ht)/2 print "Uni Bi Tri..." time.sleep(2) print "The area of traingle is "+ str(round(area_tri,2)) + " " + str(unit) else: print "Please enter a valid value" exit()
4809c12f23d4b01436c829eff24ead928e6d89fa
MaoningGuan/Python-100-Days
/Day01-15/06_exercise_2.py
1,813
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 1、求最大公约数 2、求最小公倍数的函数 3、判断一个数是不是回文数的函数。 4、判断一个数是不是素数 5、求一个数的反向排列:1234 ——> 4321 """ def gcd(x, y): """ 求x和y的最大公约数 :param x: :param y: :return: x和y的最大公约数 """ (x, y) = (y, x) if x > y else (x, y) for factor in range(x, 0, -1): if x % factor == 0 and y % factor == 0: return factor def lcm(x, y): """ 求x和y的最小公倍数 :param x: :param y: :return: x和y的最小公倍数 """ return x * y // gcd(x, y) def is_palindrome(num): """ 判断一个数是不是回文数 回文数n:将n的各位数字反向排列所得自然数n1与n相等 :param num: :return: True or False """ temp = num total = 0 while temp > 0: total = total * 10 + temp % 10 temp //= 10 return total == num def is_prime(num): """ 判断一个数是不是素数 :param num: :return: """ # 因为num的因子存在具有对称性,所以只需要判断前半部分int(num ** 0.5) + 1即可。 for factor in range(2, int(num ** 0.5) + 1): if num % factor == 0: return False return True if num != 1 else False def reversed_num(num): """ 求一个数的反向排列:1234 ——> 4321 :param num: :return: """ if num < 0: raise TypeError('输入的数必须为正数!') return int(str(a)[::-1]) if __name__ == '__main__': num = int(input('请输入正整数:')) if is_palindrome(num) and is_prime(num): print('%d是回文素数。' % num) else: print('%d不是回文素数。' % num)
9024fbdfb1e7e7ce19b619bd24f50155148ec57c
Rpratik13/Algorithm_Implementations
/probing.py
427
3.609375
4
c1 = 0 c2 = 1 m = 7 def hashing(key): return key % m def probing(array: list) -> list: result = [None] * m for elem in array: hsh = hashing(elem) i = 1 while result[hsh] != None: hsh = (hashing(elem) + c1 * i + c2 * (i ** 2)) % m i += 1 result[hsh] = elem return result if __name__ == '__main__': array = [1, 8, 15] hashed = probing(array) for i, j in enumerate(hashed): print("{}: {}".format(i, j))
e56e018b5847dddd79506fe30ea4b530d06b0ee7
novmar/python_learn
/pets_learn/1..7-animals.py
2,549
4.09375
4
### 1. Make a list of pets. You will need it in later exercises. Known pets are: 'dog', 'cat', 'rabbit', 'snake' pets = [ 'dog', 'cat', 'rabbit', 'snake',] ### 2. Write a functon that returns the name of pets (list given as the argument) that are shorter than 5 leters. def fiveless (mypets): pets5 = [] for pet in mypets: if len(pet)<5 : pets5.append(pet) return(pets5) ### 3. Write a functon that returns the names of pets (list given as the argument) that begin with 'd'. def dstarted (mypets): dstart = [] for pet in mypets: if pet[0] == "d": dstart.append(pet) return dstart ### 4. Write a functon that gets a word and detects if it's in the pet list. “Detects” means that the functon returns True or False. def ispet(tryit): if tryit in pets: return True else: return False ### 5. Write a functon that gets two lists of animal names and returns three lists: ### (a) the animals that are on both lists (common ones), ### (b) animals which are only in the frst list, ### (c) animals that are only in the second list ### Write the test to verify that it works properly. def comparelists(one,two): both = [] # Prepare "both" o = list(set(one)) # clear duplications t = list(set(two)) # clear duplications print(one,o,"\n",two,t,"\n") for i in one: if i in t: both.append(i) t.remove(i) o.remove(i) return o,t,both ### 6. Write a program that sorts the list of pets by alphabet. def normalsort(list): return sorted(list) ### 7. Write a functon that sorts the animals alphabetcally, but ignores the frst leter ### Returns: ['rabbit', 'cat', 'snake', 'dog'] def weirdsort(list): prelist={} key=[] ws=[] for i in list: prelist[i[1:]]= i key.append(i[1:]) for i in sorted(prelist): ws.append(prelist[i]) return ws ### Results ### 1. #print(pets) ### 2. #print(fiveless(pets)) ### 3. #print(dstarted(pets)) ### 4. #print(ispet("dog")) #print(ispet("cat")) #print(ispet("morce")) ### 5. f=["ahoj","aneta","nema","nohy","aneta"] s=["zdar","aneta","nova","nema","zadny","ruce"] #print ("vysledky:",comparelists(f,s)) f=["ahoj","aneta","nema","nohy"] s=["zdar","aneta","nova","nema","zadny","ruce"] #print ("vysledky:",comparelists(f,s),"\n\n") f=["oba1","oba2","oba3","prvni1","prvni1"] s=["druha12","oba1","oba2","oba3","druha1"] #print ("vysledky:",comparelists(f,s)) ### 6. #print (normalsort(pets)) ### 7. #print(weirdsort(pets))
7e195192c2a79a3d6200806acf69ee534ab7faae
JoeKabongo/Sorting-Project
/Python/insertion.py
467
4.1875
4
def insertion(array): # Move elements of arr[0..i-1], that are # greater than element, to one position ahead # of their current position length = len(array) for i in range(1, length): element = array[i] sorted = i-1 while sorted >= 0 and array[sorted] > element: array[sorted+1] = array[sorted] sorted -=1 array[sorted+1] = element print(array) m = [1, 12, 3, 10, 78, -9] insertion(m)
09ea228d95f9d692d659dac1c9a2b797bcfbd480
Jeanzw/LeetCode_Practice
/Python/Easy/575 Distribute Candies(set+数学思维).py
1,439
3.75
4
# 这一道题目的思路其实很简单: # 题目的意思其实就是,糖果分一半,那么妹妹最多可以得到多少种类的糖果呢? # 由于哥哥和妹妹是一人一半,所以妹妹最多也就分到一半的糖果,就算这些糖果都不是一个种类的,也就只能分到一半数量糖果种类的糖果 # 所以这就说明,总数/2 这是一个分界点,也是我们讨论的依据 class Solution: def distributeCandies(self, candies: List[int]) -> int: kind = set(candies) print(kind) if len(kind) >= len(candies)/2: #如果糖果种类大于总糖果数的一半的话,那么其实无论妹妹怎么拿,最多也只能得到总糖果数一半数量的种类 return int(len(candies)/2) else: #如果糖果种类小于总糖果数的一半的话,那么妹妹最多也就是把所有种类的糖果全部拿完 return len(kind) #另一种思路: #我们假设说这里有n种不同的糖果len(set(candies)),然后妹妹也只能拿走其中的一半而已len(candies) / 2 #我们打个比方,如果这里有5种不同的糖果,如果妹妹要拿走4个,那么4种糖果都可以不同 #但是如果这个时候,妹妹其实要拿走的糖果数量是7个呢?那么必定是有重复的,但是糖果种类最多也只能是5种 print(min(len(candies) / 2, len(set(candies))))
64ab864cd0b4ed96e0a0e1d8d5953d638765e028
Youlow/py101
/ex1/models.py
941
3.609375
4
# -*- coding: utf-8 -*- class Field(object): def __init__(self, rank=3): self.empty = " " self.rank = rank self.field = [[self.empty, ] * rank for i in range(rank)] def set_value(self, x, y, sign): self.field[x][y] = sign.sym def get_rank(self): return self.rank def clear(self): self.field = [[self.empty, ] * self.rank for i in range(self.rank)] class Player(object): def __init__(self): self.name = "PC" self.sign = Sign(True) def set_name(self, name): self.name = name def set_sign(self, first_turn): self.sign = Sign(first_turn) class Sign(object): def __init__(self, first_turn): if first_turn: self.sym = "X" else: self.sym = "O" self.is_x = first_turn def __str__(self): return self.sym if __name__ == "__main__": print("It's a model module")
d3151a45eb5a025a9970afd1aad30208b8a5c316
KaylaBaum/astr-119-hw-1
/python_arrays.py
498
4.15625
4
x = [0.0, 3.0, 5.0, 2.5, 3.7] #define an array print(type(x)) #remove the third element x.pop(2) print(x) #remove the element equal to 2.5 x.remove(2.5) print(x) #add an element at the end x.append(1.2) print(x) #get a copy y = x.copy() print(y) #how many elements are 0.0 print(y.count(0.0)) #print the index with value 3.7 print(y.index(3.7)) #sort the list y.sort() print(y) #reverse sort y.reverse() print(y) #remove all elements y.clear() print(y)