blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d61f11456525b2d90b1a56e69ba87fd1c51965fb
patelrohan750/python_practicals
/Practicals/practical1_A.py
191
4.1875
4
#A.Develop a Python Program to Add Two Numbers. num1=int(input("Enter First Number: ")) num2=int(input("Enter Second Number: ")) print("The Addition of two Numbers is: ",num1+num2)
0759aee7ac2793f2d3d9fd0b67ded89f90ba49bf
javadeveloperethan/ddd
/aboutMe.py
263
3.765625
4
o = input("자신의 나이를 입력하세요 :") h = input("자신의 키를 입력하세요 :") w = input("자신의 몸무게를 입력하세요 :") print("제 나이는" + o + "이고," + "제 키는" + h + "이며," + "제 몸무게는" + w + "입니다")
a13984fa71b097435f1c0e795d046ba94879572f
JancisWang/leetcode_python
/67.二进制求和.py
943
3.75
4
''' 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-binary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def addBinary(self, a: str, b: str) -> str: if len(a) > len(b): b = '0' * (len(a)-len(b)) + b elif len(a) < len(b): a = "0" * (len(b)-len(a)) + a summ = 0 result = "" for i in range(len(a)-1, -1, -1): result = str((int(a[i]) + int(b[i]) + summ) % 2) + result summ = (int(a[i]) + int(b[i]) + summ) // 2 if summ > 0: result = "1" + result return result
f34ee47b0993ddc755461e315345130929e08a2c
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex104.py
319
3.984375
4
def leia_inteiro(_texto): while True: numero = str(input(_texto)) if numero.isnumeric(): return numero else: print('Erro! Digite um número inteiro válido!') numero = leia_inteiro('Digite um número: ') print('Você acabou de digitar o número {}.'.format(numero))
919709209c6e243d30ff490decdbb715c585af15
Mirror-Shard/L3
/1 user.py
207
3.984375
4
name = str(input("Enter your name: ")) age = str(input("How old are you live? ")) adress = str(input("Where are you live? ")) print("This is " + name) print("It is " + age) print("(S)he live in " + adress)
03542820f283738423c28b2cf71e243c7458692d
shashank31mar/DSAlgo
/rotate_array.py
939
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 20 07:48:53 2018 @author: shashankgupta """ def swap(arr,ai,bi,d): for i in range(d): arr[ai+i],arr[bi+i] = arr[bi+i],arr[ai+i] def rotate_array(arr,d,n): ''' divide array in two parts A[1...D-1] and B[D....high] if A < B divide B such that Bl is of same size as A and swap them So... ABlBr -> BrBlA else AlArB -> BArAl after doing this recur of remaining peices of A or B by changing the d ''' if d == 0 or d == n: return if n-d == d: return swap(arr,0,n-d,d) #A is bigger if d > n-d: swap(arr,0,d,n-d) rotate_array(arr[n-d:],d-(n-d),d) elif d < n-d: swap(arr,0,d,n-d) rotate_array(arr,d,n-d) def main(): arr= [1,2,3,4,5] rotate_array(arr,4,len(arr)) print("rotated arrary is:{}".format(arr)) if __name__ == "__main__": main()
52cbc851e57d9e0ca4237340a23f4250d3ae910b
vakaru2013/lwater
/water_model/fv2.py
14,269
3.703125
4
""" Feature vector model No.2 short target: calculate the rate of stock return, if it is good, I am a genius. a list, each item in it is a dict, its key is a feature vector, while its value is all lineidx whose fv equal to the key. then, a function, print info into a file like this: fv: [......] date: date1, date2, ... ------- then repeat to print info of another fv ------- then, a function, given a date info, return a list of date info whose fv equal to the given date. the feature vector: 1234567890 -- the latter 5 are used for outcome/label ^ ^ -- ^ ^ -- trend combination ^^^ ^^ -- mean variation """ from format import format class CSV: def __init__(self, fp, itemsperday=10): """given file path of the csv, this csv file containing history informaiton of a stock, each line contains multiple days' info. """ self.inited = False with open(fp) as f: l = f.readline() items = l.split(', ') # each line contains multiple day's info. self.daysperline = len(items) / itemsperday self.fp = fp self.itemsperday = itemsperday # each item in it is a list, the list contains all items of a line self.lineitems = [] with open(fp) as f: for l in f: self.lineitems.append(l.split(', ')) # each item in it is a feature vector of a line self.fvs = [] for i in range(len(self.lineitems)): self.fvs.append(self.fv(line=i)) self.inited = True def vol(self, lineidx, dayidx): """return volume value of in the line by index and the day by index -- start from 0. because each line contains multiple day's info. """ return float(self.lineitems[lineidx][8 + self.itemsperday * dayidx]) def ratiorank(self, ratio): """given a ratio, return a rank value. the rank value is from 0~6, the higher value means the ratio is larger. """ rank = { 0.5: 0, 0.75: 1, 0.85: 2, 1.1: 3, 1.25: 4, 1.7: 5 } for key, val in rank.iteritems(): if ratio < key: return val return 6 def f1(self, **kwargs): """return the first feature of a date in the csv file, either date=2015-06-25, or line=0. the return value is a ratio rank value. """ if 'line' in kwargs: lineidx = kwargs['line'] elif 'date' in kwargs: lineidx = self.linebydate(kwargs['date']) if self.inited is True: return self.fvs[lineidx][0] mean1 = (self.vol(lineidx, 0) + self.vol(lineidx, 1) + self.vol(lineidx, 2)) / 3 mean2 = (self.vol(lineidx, 3) + self.vol(lineidx, 4)) / 2 ratio = mean2 / mean1 return self.ratiorank(ratio) def f23(self, **kwargs): """return the 2nd and 3rd features of a date in the csv file, either date=2015-06-25 or line=0. the return value is a list containing two rank values. """ if 'line' in kwargs: lineidx = kwargs['line'] elif 'date' in kwargs: lineidx = self.linebydate(kwargs['date']) if self.inited is True: return self.fvs[lineidx][1:] vol3 = self.vol(lineidx, 2) vol4 = self.vol(lineidx, 3) vol5 = self.vol(lineidx, 4) rt54 = vol5 / vol4 rt43 = vol4 / vol3 return [self.ratiorank(rt43), self.ratiorank(rt54)] def fv(self, **kwargs): """return a feature vector of a date in the csv file, either date=2015-06-25 -- calculate and reuturn that day's feature vector, or line=0 -- calculate and return the feature vector of that line. """ if 'line' in kwargs: lineidx = kwargs['line'] elif 'date' in kwargs: lineidx = self.linebydate(kwargs['date']) return [self.f1(line=lineidx)] + self.f23(line=lineidx) def linebydate(self, date): """given a date, return line idx of that date, although every line contains multiple days' info, here the date is the major day. date format: 2015-06-25 """ assert date >= self.majordate(0) and \ date <= self.majordate(len(self.lineitems) - 1), \ 'date %s is out of scope of the csv %s, (%s, %s)' % \ (date, self.fp, self.majordate(0), self.majordate(len(self.lineitems) - 1)) for i in range(len(self.lineitems)): if date == self.majordate(i): return i raise Exception('can\'t find lineidx in csv for: ' + date) def date(self, lineidx, dayidx): """given lineidx and dayidx, return the date, both indexes start from 0. date formate is: 2015-06-25 """ return self.lineitems[lineidx][self.itemsperday * dayidx] def majordate(self, lineidx): """given a lineidx, return its major date, major date is something like the current day, as one line contains multiple days' info, but there is something like current day. """ return self.date(lineidx, 4) def closeprice(self, **kwargs): """given a date, return its closing price, e.g. date='2015-06-25' or, given the lineidx and the dayidx e.g. lineidx=0 dayidx=4 """ if 'date' in kwargs: lineidx = self.linebydate(kwargs['date']) dayidx = 4 return float(self.lineitems[lineidx][self.itemsperday * dayidx + 2]) def predict(self, date): """ given a date, return prediction -- price will up, down or unchanged. the date's format: 2015-06-25 """ fv = self.fv(date=date) f1 = fv[0] f2 = fv[1] f3 = fv[2] if f2 >= 5 or f3 >= 5 or f1 >= 5: return 'up' elif f2 <= 1 or f3 <= 1 or f1 <= 1: return 'down' else: return 'flat' def predictbyline(self, lineidx): """ given lineidx, return prediction """ return self.predict(self.majordate(lineidx)) class ROR: """ calculate the rate of stock return, if it is good, I am a genius. given a begin date, an end date (however, no deal will be made in the end day -- neither buy nor sell), and given the initial state -- hold cash or hold stock, if it is holding stock, then the closing price of that begining day is used as reference, from a relative long run, whether using closing price or opening price will generally lead no big difference, for convenience, the closing price of the begining date is used. assuming the initial cash is 100 unit (if holding cash), or initial stock is 100 shares (if holding stock). implementation: 1, calculate the initial money, 100 unit(if holding cash) or closing price* 100 shares(if holding stock). 2, every time when an event happened, update and remember the new state -- holding cash or holding stock shares. And: 1, if it is a selling event, then calculate and remember the money: using selling price * stock shares number 2, otherwise, calculate and remember the shares of stock, using cash/buying price 3, at the end, calculate (if need) and return the final money: using shares of stock* closing price of that day (if holding stock). """ def __init__(self, bgdate, enddate, initcash, csv, bonusshares): """given a begin date, an end date, and the initial state -- hold cash or hold stock: True or False. and given a csvobj, which represents history info of stock. and given a BonusShares object, containing bonus share issuing info. bgdate and enddate's format: 2015-06-25 """ self.bonusshares = bonusshares self.bgdate = bgdate self.enddate = enddate # initial state whether is holding cash self.initcash = initcash self.csv = csv self.initmoney = 100 if initcash is True else \ 100 * csv.closeprice(date=bgdate) # latest state whether is holding cash self.bcash = initcash # latest cash, valid only when state is holding cash, # otherwise, ignore it self.cash = 100.0 # latest shares, valid only when state is holding share, # otherwise, ignore it self.shares = 100.0 # key is date, value is 'buy', 'sell' or 'stay' self.decisions = {} def ror(self, bbuyandhold=False): """return rate of return. 1, iterate from the bgdate to enddate, using lineidx in the csv file, get prediction, and get decision, 2, given decision of a day, know the action: convert cash to stock, or convert stock to cash, or stay unchanged, calculate and remember the latest state, number of shares and cash unit. 3, after the last day is processed, we get the final state. 4, then, convert to money, and compare to the initial money, and get the rate of return. there is a special parameter, bbuyandhold, when it is True then no sell. this can be used for compareing purpose. """ for i in range(self.csv.linebydate(self.bgdate), self.csv.linebydate(self.enddate)): mjdate = self.csv.majordate(i) self.handle_bonusshare(mjdate) if bbuyandhold is False: pred = self.csv.predictbyline(i) dec = self.decision(self.bcash, pred) dp = self.csv.closeprice(date=mjdate) self.deal(dec, dp, mjdate) return self.money(self.enddate) / self.initmoney def handle_bonusshare(self, date): """given date, check if there is any bonus shares, if yes, then handle it: if current state is holding stock shares, then modify the shares accroding to the bonus share issuing info. if current state is holding cash, then do nothing. """ bonus = self.bonusshares.check(date) if bonus is not None: if self.bcash is False: old = self.shares self.shares = self.shares / bonus[0] * bonus[1] print 'shares holded was %0.2f, now becomes %0.2f, %s...' % \ (old, self.shares, date) def decision(self, bcash, pred): """ given current state -- holding cash or holding stock, and given prediction -- price will up, down or unchanged, return decision -- buy, sell or stay unchanged. """ if bcash is True: if pred == 'up': return 'buy' else: return 'stay' else: if pred == 'down': return 'sell' else: return 'stay' def deal(self, dec, dp, date): """ given decision, given the deal price, and date, update the latest status -- holding cash or stock, and update the money -- cash unit or stock shares. this function will also store all decision info in this instance. """ if dec == 'stay': pass elif dec == 'buy': assert self.bcash is True, 'can\'t buy when holding stock shares.' self.shares = self.cash / dp self.bcash = False print 'buying, %s, %0.2f' % (date, dp) elif dec == 'sell': assert self.bcash is False, 'can\' sell when holding cash.' self.cash = self.shares * dp self.bcash = True print 'selling, %s, %0.2f' % (date, dp) else: raise Exception('invalid deal decision.') def money(self, date=None): """return money number, date may be needed as input, because if it is holding shares, need date to calculate the latest price. """ if self.bcash is True: return self.cash assert date is not None, 'must specify date in order to calculate \ money when holding stock shares.' return self.shares * self.csv.closeprice(date=date) def prepare_history(incsv, outcsv, daysperline): """given a input csv filename, which is a raw history csv file, each line contains only one day's info, and given daysperline, then this function generates a new csv file, each line contains multiple days info, finally this function returns a CSV object based on that new csv file. """ format(incsv, outcsv, daysperline) return CSV(outcsv) class BonusShare: """this class contains information about the bonus share issue info. """ def __init__(self, bonus_file): """given a bonusshare file, which is a csv file. """ # this is a dictionary, the key is date, e.g. '2015-06-25', # the value is a list, e.g. [10, 20], means issuing 10 new shares for # every 10 old shares. self.bonusinfo = {} with open(bonus_file) as f: for l in f: l = l.rstrip('\n') items = l.split(', ') self.bonusinfo[items[0]] = [float(i) for i in items[-2:]] def check(self, date): """given date, return None or a list, e.g. [10, 20], means issuing 10 new shares for every 10 old shares. """ return self.bonusinfo.get(date, None) def print_ror(bonusinfo, csv, bgdate, enddate): """ this is an entry function. """ ror = ROR(bgdate, enddate, True, csv, bonusinfo) print 'rate of return: %0.2f, ending date: %s, ending close price: %0.2f' \ % (ror.ror(), enddate, csv.closeprice(date=enddate)) ror = ROR(bgdate, enddate, False, csv, bonusinfo) print 'rate of return if buy and hold: %0.2f' % ror.ror(True) print 'begin date: %s' % bgdate
ea9b3121115d5cebf26f298c127c56236607606a
thohidu/google-algorithms
/lesson_5/binary_tree_quiz.py
2,713
4.375
4
"""Your goal is to create your own binary tree. You'll need to implement two methods : search(), which searches for the presence of a node in the tree and print_tree(), which prints out the values of tree nodes in a pre-order traversal. You should attempt to use the helper methods provided to create recursive solutions to these functions. """ class Node(): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(): def __init__(self, root): self.root = Node(root) def search(self, find_val): """Return True if the value is in the tree, return False otherwise.""" boolean = self.preorder_search(self.root, find_val) return boolean def print_tree(self): """Print out all tree nodes as they are visited in a pre-order traversal.""" traversal = "" traversal = self.preorder_print(self.root, traversal) return "-".join(traversal) def preorder_search(self, start, find_val): """Helper method - use this to create a recursive search solution.""" if start.value == find_val: return True if start.left: pre_boolean = self.preorder_search(start.left, find_val) if pre_boolean: return pre_boolean if start.right: pre_boolean = self.preorder_search(start.right, find_val) if pre_boolean: return pre_boolean return False def preorder_print(self, start, traversal): """Use this to create a recursive print solution.""" traversal = traversal + str(start.value) if start.left: traversal = self.preorder_print(start.left, traversal) if start.right: traversal = self.preorder_print(start.right, traversal) return traversal if __name__ == "__main__": # Set up tree tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) # Test search # Should be True print(tree.search(4)) # Should be False print(tree.search(6)) # Test print_tree # Should be 1-2-4-5-3 print(tree.print_tree()) # Set up 2nd tree tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) # Test search # Should be True print(tree.search(4)) # Should be True print(tree.search(6)) # Test print_tree # Should be 1-2-4-5-3-6-7 print(tree.print_tree())
8935ff518a052b3d170f811f66cb7bec5a8170fa
keriber596/Piter_and_Starck
/starter_obj.py
1,140
3.65625
4
import pygame import classes import random #sprite_hero = classes.Sprites_hero() "_____________________________________________" width_window = 1000 height_window = 500 background = classes.Background(width_window, height_window, 0, 0) #все фоны "_____________________________________________" bullets = [] enemys = [] "_____________________________________________" width_h = 50 height_h = 50 speed = 10 is_jump = False xy = [1, height_window - int(height_h + 110)] #320 hero = classes.Hero(xy, width_h, height_h, speed) "_____________________________________________" def enemy_add(width_en): width_enemy = 60 height_enemy = 70 xy = [random.randint(1, width_en), 410 - height_enemy] speed = 5 enemys.append(classes.Enemy(xy, width_enemy, height_enemy, speed)) "_____________________________________________" def attack_ball(): # выстрел speed_ball = 20 x_ball = hero.xy[0] + hero.width//2 y_ball = hero.xy[1] + hero.height//2 bullets.append(classes.Attack([x_ball, y_ball], hero.width//5, speed_ball, hero.front)) return True "_____________________________________________"
09af33962d2c43d81cf5ced1d35760456c2b35e6
Yelchuri555/PythonPrograms
/StringProgram/UpperLowerCases.py
136
3.765625
4
userinp = raw_input("Enter a String :") upperCount = 0 lowerCount = 0 for i in userinp: if(i.isupper()): upperCount += 1
269d988c5629524a852c89c8d94f0aed7dd6914a
marceloccs/phytonAulas
/my_first_project/media.py
709
3.5625
4
#media, mediana, moda def media (lista): media = sum(lista)/float(len(lista)) return media def mediana (lista): list.sort(lista) if(len(lista)%2==0): return (lista[int(len(lista)/2)]+lista[int((len(lista)/2)+1)])/2 else: return lista[int((len(lista)+1)/2)] def moda (lista): list.sort(lista) mapa = {} for valor in lista: if(valor not in mapa): mapa[valor] = 1 else: mapa[valor] +=1 maior_lista = max(mapa.values()) if(maior_lista>1): for i in mapa: if mapa[i] == maior_lista: moda = i break return moda else: return "Não tem moda"
05da4dd28a64b06ea3c827850c6c8c9816972561
AshTiwari/Standard-DSA-Topics-with-Python
/Matrix/Search_Element_in_a_Sorted_Matrix.py
581
4.09375
4
# Search an element in a matrix which is sorted by rows. from binarySearch import lessThanEqualBinarySearch def binarySearch(matrix, m, n, element): i = j = 0 row_begs = [matrix[i][0] for i in range(m)] row_no = lessThanEqualBinarySearch(row_begs, element) if row_no != -1: for i in range(0,n): if matrix[row_no][i] == element: return (row_no, i) return (-1,-1) if __name__ == "__main__": matrix = [[i + j*5 for i in range(1, 6)] for j in range(5)] m = n = 5 for element in range(27): print(binarySearch(matrix, m, n, element))
f3fe2d5990ab69a0bc4548d15f66676ecef0a339
Abhay-official/Summer-Training
/Day06/Day6D.py
163
3.765625
4
x=[2,3,4,5] y=[-1,2,-2,1] z=[10,20,15,30,25,67] print("x:",x) print("y:",y) print("z:",z) res=[] for i,j,k in zip(x,y,z): res.append(i+j+k) print("res:",res)
70ffc495e659c54d8f43109b8310b3686c05171e
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter10/0004_validate_us_social_security_number.py
436
3.96875
4
""" Program 10.3 Validate U.S.-based Social Security Number """ import re def main(): pattern = re.compile(r"\b\d{3}-?\d{2}-?\d{4}\b") match_object = pattern.search("Social Security Number" "For James is 916-30-2017") if match_object: print(f"Extracted Social Security Number is {match_object.group()}") else: print("No Match") if __name__ == "__main__": main()
243c5ce189d452fe3e82b7ba77b9f1a719cc79ec
buraaksenturk/GlobalAIHubPythonHomework
/1_day/1_homework.py
666
4.15625
4
# Getting data from the user nameandsurname = str(input('What is your name and surname :')) age = int(input('How old are you :')) height = float(input('What is your height :')) study = bool(input('Are you study (True/False) :')) letter = list(input('What are your favorite letters :')) # Printing data types print(f''' Name and Surname Type : {type(nameandsurname)} Age Type : {type(age)} Height Type : {type(height)} Study Type : {type(study)} Letters Type : {type(letter)} ''') # Printing values ​​entered on inputs print(f''' Name and Surname : {nameandsurname} Age : {age} Height : {height} Study : {study} Letters : {letter} ''')
40ff6a91f38bea6d97fc1ed955c5308849dbfd9f
DmitryZiganurov/hse
/Test_I-3.py
1,800
3.78125
4
import matplotlib.pyplot as plt import numpy as np from collections import namedtuple #Графики левой и правой части уравнения и производной разности этих функций x = np.arange(0.6,0.7,0.001) plt.grid() plt.plot(x,np.cos(x)) plt.plot(x,np.sqrt(x)) #Корень уравнения приблизительно 0.642 #plt.plot(x,-np.sin(x)-1/(2*np.sqrt(x))) #Производная функции result = namedtuple('result',['x', 'niter','error']) def f(x): return np.cos(x)-np.sqrt(x) def newton_iteration(f, x0, alpha, eps=1e-5, maxiter=10000): x_prev=x0 x_curr=x_prev-alpha*f(x_prev) niter=0 while(abs(x_prev-x_curr)>eps and niter<maxiter): x_prev=x_curr x_curr=x_prev-alpha*f(x_prev) niter+=1 error=False if(niter==maxiter): error=True return result(x_curr,niter,error) res=newton_iteration(f,0.9,-0.8) print("Корень: ",res.x) print("Количество итераций: ",res.niter) print("Ошибка: ",res.error) #Зависимость количества интераций от альфа: #-1.0 7 #-0.9 5 #-0.8 3 #-0.7 6 #-0.6 8 #-0.5 11 #-0.4 14 #-0.3 20 #-0.2 32 #Минимум итераций достигается при альфа примерно равное -0.8. Из графика производной функции можно видеть, #что она ограничена: ее значение принадлежить промежутку от -1.21 до -1.24 в окрестности корня. Вычисляя альфа-оптимальное, #можно убедиться в том, что ее значение также примерно -0.8.
3e0ee3cc9b14a4c1c4138fa5b180dd7aad2202b5
missuzundiz/GlobalAIHubPythonCourse
/Homeworks/HW1.py
306
3.78125
4
liste=["elma","armut","kalem","kitap"] liste1=liste[0:2] liste2=liste[2:5] print(liste2+liste1) sayi=int(input("Tek basamaklı bir tamsayı giriniz:")) try: if sayi>=0: print("Çift Sayılar:") for i in range (sayi): if i%2==0: print(i) except: print("Sayı Giriniz:")
fe41ef7e6948c8d6528ea2ba0350a32047020169
meghasundriyal/Python-Tutorials
/strings.py
598
4.25
4
#performing different string operations a = "Sample! String " #single line string b = '''This is an example of multiline string ''' #double quotes can also be used print(a) print(b) #strings are treated as array of byte characters in python print("a[1] : " ,a[1]) print("a[2:7] : ",a[2:7]) #METHODS ON STRINGS print("strip : ", a.strip()) print("length of a : ",len(a)) print("uppercase : ",a.upper()) print("lowercase : ",a.lower()) print("split : ",a.split("!")) print("Hello, world") print("Helllo","world") print("Hello"+"world") print(a.find("t"))
5157e700f99bc0f49e35b4fc11f43e2c41f5ed88
chrisidakwo/Intro-to-Python
/Week 2 - Control Statements & Iterations/DaysInAMonth.py
1,037
4.4375
4
"""Display the number of days for a given month in a given year. RULE: Should be displayed as such: 'March 2005 has 31 days' """ import datetime def isleapyear(year): """ Returns True if the argument year is a leap year, else returns False""" leap_status = ((year % 100 != 0) if (year % 4 == 0) else (year % 400 == 0)) return leap_status # Set global variables DAYS_IN_A_MONTH = 31 MONTH_NAMES = "January", "February", "March", "April", "May", "June", "July", "August", "September", \ "October", "November" "December" # Get user input MONTH = int(input("Enter a month: ")) YEAR = int(input("Enter a year: ")) # Set for months with 30 days LIMITED_MONTHS = 9, 4, 6, 11 # A Tuple if MONTH in LIMITED_MONTHS: DAYS_IN_A_MONTH = 30 # Set for February # Take into account Leap years if MONTH == 2 and not isleapyear(YEAR): DAYS_IN_A_MONTH = 28 elif MONTH == 2 and isleapyear(YEAR): DAYS_IN_A_MONTH = 29 print("{0} {1} has {3} days".format(MONTH_NAMES[MONTH - 1], YEAR, DAYS_IN_A_MONTH))
ba97f6bc69874d143605a6109a204f13ae450796
sudarshannkarki/sda-project
/Ecommerce-site1/check.py
56
3.703125
4
# Display Hello! 3 times p = 3 q = 'Hello! ' print(q*p)
b774b3ed48516875dcf9bb4e57dcd5c3ca143461
shenbeixinqu/leetcode
/2-哈希表/350-两个数组的交集ii(easy).py
1,332
3.875
4
# 给定两个数组,编写一个函数来计算它们的交集。 # # # 示例 1: # # 输入:nums1 = [1,2,2,1], nums2 = [2,2] # 输出:[2,2] # # 示例 2: # # 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] # 输出:[4,9] # # 说明: # # 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。 # 我们可以不考虑输出结果的顺序。 # # 进阶: # # 如果给定的数组已经排好序呢?你将如何优化你的算法? # 如果 nums1 的大小比 nums2 小很多,哪种方法更优? # 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办? # # Related Topics 排序 哈希表 双指针 二分查找 class Solution: def intersect(self, nums1, nums2): if not nums1 and not nums2: return [] hashmap1 = dict.fromkeys(nums1, 0) hashmap2 = dict.fromkeys(nums2, 0) for num in nums1: hashmap1[num] += 1 for num in nums2: if hashmap1.get(num) and hashmap1[num] >0: hashmap2[num] += 1 hashmap1[num] -= 1 res = [] for k, v in hashmap2.items(): for _ in range(v): res.append(k) return res
9378196a1a5edd07762d73c4f160b28d16242d82
max64q/Python_Practice
/Question 9.py
436
4.125
4
#Question 9 #Write a program that accepts sequence of lines as input and prints the lines #after making all characters in the sentence capitalized. #Suppose the following input is supplied to the program: #Hello world #Practice makes perfect #Then, the output should be: #HELLO WORLD #PRACTICE MAKES PERFECT lines = input("Enter Lines seperated by '.': ") lines = lines.upper() lines = lines.split(".") print(lines)
6711056af34bdb97ffda829077a430a6f7060ec2
CleverInsight/predicteasy
/predicteasy/core/nlp/spelling.py
1,074
3.578125
4
import io import pandas as pd from textblob import TextBlob class SpellCheck: def __init__(self, text, multiple=False, column=""): self.data = text self.multiple = multiple self.column = column def spell_apply(self, data): """ spell_apply takes incorrect text and correct the spell and returns it :param data: The data :type data: { type_description } :returns: { description_of_the_return_value } :rtype: { return_type_description } """ return str(TextBlob(data).correct()) def correct(self): """ Correct method helps us to loop throught the given dataframe and correct the grammer :returns: { description_of_the_return_value } :rtype: { return_type_description } """ if self.multiple: data = pd.read_csv(io.StringIO(self.data), lineterminator='\n') data.rename(columns=lambda x: x.strip(), inplace=True) data[self.column.strip()].apply(self.spell_apply).apply(pd.Series) return dict(data=data.to_json(orient='records'), summary=[]) else: return self.spell_apply(self.data)
2ab54f3b2b187c48cd164cafe50674d7aa8c93f4
valentinegarikayi/Getting-Started-
/OddorEven2.py
274
4.1875
4
#!/usr/bin/env python num = int(input('Give me the number to check: ')) check =int(input('Give me the number to divide: ')) if num % check ==0: print ('{} divides evenly into,{}'.format(check, num)) else: print ('{} doesnt divide evenly into,{}'.format(check, num))
75d80349388342e0bdd045c7f03e06e41f399e9f
peoolivro/codigos
/Cap2_Exercicios/PEOO_Cap2_ExercicioProposto07.py
537
3.921875
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 02 # Questão.: Exercício Proposto 7 # Autor...: Fábio Procópio # Data....: 18/02/2019 sal_base = 1500 comissao = 200 corretor = input("Digite o nome do corretor: ") qtd_vendas = int(input("Informe a quantidade de imóveis vendidos: ")) tot_vendas = float(input("Informe o valor total das vendas do corretor (R$): ")) sal_final = sal_base + comissao * qtd_vendas + tot_vendas * 0.05 print(f"Salário final de {corretor} é R$ {sal_final:.2f}")
600a67ec6403f2d942e835a8ca4eded853d3e229
cpeixin/leetcode-bbbbrent
/binary_search/search-in-rotated-sorted-array.py
1,337
3.78125
4
# coding: utf-8 # Author:Brent # Date :2020/7/6 1:06 PM # Tool :PyCharm # Describe :假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # # 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # # 你可以假设数组中不存在重复的元素。 # # 你的算法时间复杂度必须是 O(log n) 级别。 # # 示例 1: # # 输入: nums = [4,5,6,7,0,1,2], target = 0 # 输出: 4 # 示例 2: # # 输入: nums = [4,5,6,7,0,1,2], target = 3 # 输出: -1 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array class Solution(object): def search(self, nums, target): if not nums: return -1 left, right = 0, len(nums)-1 while left <= right: mid = left + (right - left) // 2 if nums[mid] == target: return mid # 左边有序 if nums[left] <= nums[mid]: if nums[left] <= target <= nums[mid]: right = mid -1 else: left = mid + 1 # 右边有序 else: if nums[mid] < target <= nums[right]: left = mid + 1 else:right = mid - 1 return -1
1f8d4fb268cf11f32bb6795c7dc3d62fe231c031
antonioramos1/dataquest-data-analyst
/1-1-python-programming-beginner/challenge_--files,-loops,-and-conditional-logic-157.py
1,053
3.90625
4
## 3. Read the File Into a String ## filenames = open('dq_unisex_names.csv', 'r') names = filenames.read() ## 4. Convert the String to a List ## f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split('\n') first_five = names_list[:5] print(first_five) ## 5. Convert the List of Strings to a List of Lists ## f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split('\n') nested_list = [] for valuelist in names_list: comma_list = valuelist.split(',') nested_list.append(comma_list) print(nested_list) ## 6. Convert Numerical Values ## print(nested_list[0:5]) numerical_list = [] for lst in nested_list: index0 = lst[0] index1 = float(lst[1]) numerical_list.append([index0,index1]) print(numerical_list[:5]) ## 7. Filter the List ## # The last value is ~100 people # numerical_list[len(numerical_list)-1] thousand_or_greater = [] for value in numerical_list: if value[1] > 1000: thousand_or_greater.append(value[0]) thousand_or_greater
056d758613051ac32c759837751124ff2e8fbc5e
SabiqulHassan13/try-web-scrapping-with-python
/web_scrapping_intellipaat/web_scrp.py
954
3.640625
4
# web scrapping intellipaat # import the libraries to query a website import requests from bs4 import BeautifulSoup import pandas as pd # specify the url web_link = "https://en.wikipedia.org/wiki/List_of_Asian_countries_by_area" link = requests.get(web_link) #print(link) soup = BeautifulSoup(link.content, 'html.parser') #print(soup.prettify()) print(soup.title) print(soup.title.string) """ all_links = soup.find_all('a') for link in all_links: print(link.get('href')) all_tables = soup.find_all('table') for table in all_tables: print(table) """ desired_table = soup.find('table', class_='wikitable sortable') #print(desired_table.prettify()) desired_table_links = desired_table.findAll('a') #print(desired_table_links) country_names = [] for link in desired_table_links: country_names.append(link.get('title')) print(country_names) # store data into pandas dataframe df = pd.DataFrame() df['Country'] = country_names print(df)
0dfb2ae2e43541d65aa0647f7ab59538cc5c4d33
mexicoraver83/cursopythonkmmx
/while_loop.py
122
3.90625
4
#! /usr/bin/python # -*- encoding: utf-8 -*- year = 2001 while year <= 2012: print "The year is: ", str(year) year += 1
d697da3cb1e867d846d338e404ee3bbcea870a70
yangyu2010/leetcode
/二叉树/236二叉树的最近公共祖先.py
1,516
3.5
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Yu Yang from TreeNode import TreeNode from TreeNode import preOrderTraverse from TreeNode import inOrderTraverse from TreeNode import postOrderTraverse class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': dic = {root: None} def bfs(node): if node: if node.left: dic[node.left] = node if node.right: dic[node.right] = node bfs(node.left) bfs(node.right) bfs(root) l1, l2 = p, q while(l1 != l2): l1 = dic.get(l1) if l1 else q l2 = dic.get(l2) if l2 else p # print(l1, l2) if l1: print('1-', l1.val) if l2: print('2-', l2.val) print('------') return l1 node1 = TreeNode(6) node2 = TreeNode(2) node3 = TreeNode(8) node4 = TreeNode(0) node5 = TreeNode(4) node6 = TreeNode(7) node7 = TreeNode(9) node8 = TreeNode(3) node9 = TreeNode(5) node1.left = node2 node1.right = node3 node2.left = node4 node2.right = node5 node3.left = node6 node3.right = node7 node5.left = node8 node5.right = node9 # print('----1----') # preOrderTraverse(node1) # print('----2----') # inOrderTraverse(node1) # print('----3----') # postOrderTraverse(node1) # print('---------') print(Solution().lowestCommonAncestor(node1, node4, node9).val)
e90a8f9476a4ee22ee9dfef2a3378f7856eaf2d2
Aasthaengg/IBMdataset
/Python_codes/p02880/s554734044.py
186
3.671875
4
N = int(input()) product = [] for i in range(1,10): for j in range(1,10): product.append(i * j) if N in product: result = 'Yes' else: result = 'No' print(result)
0e10c4407534e8943e57ba05a44fa6bc0df6e7dc
NataliiaBidak/py-training-hw
/Homework6/Task6.py
1,438
3.796875
4
""" Provided a text file with information about artists and songs: Joy Division - Love Will Tear Us Apart Joy Division - New Dawn Fades Pixies - Where Is My Mind Pixies - Hey Genesis - Mama """ from collections import defaultdict class Artist: def __init__(self, artist_name, songs): self.artist_name = artist_name self._songs = songs @property def songs(self): return self._songs class MusicFile: def __init__(self, file_name): self.music_dict = self.read_file(file_name) def read_file(self, file_name): music_dict = defaultdict(list) with open(file_name) as musicfile: for line in musicfile.readlines(): artist, song = line.split('-') artist = artist.strip() song = song.strip() # if artist in music_dict.keys(): # songs_list = list() # songs_list.append(music_dict.get(artist)) # songs_list.append(song) # music_dict.update({artist: songs_list}) # else: # music_dict[artist] = song music_dict[artist].append(song) return music_dict def artist(self, name): artist = Artist(name, self.music_dict.get(name)) return artist music = MusicFile('music.txt') print(music.artist('Joy Division').songs) # a = Artist("blalalalal", )
404a13fb0defb805471a150d9c6cc0ed2e311c10
ghostlyman/python_demos
/syntax/function/imooc_mh_20180126/demo_04.py
630
3.828125
4
# -*- coding:utf-8 -*- def my_sum(*args): return sum(args) def my_average(*args): return sum(args) / len(args) def dec(func): def in_dec(*args): # 参数预处理 print('in dec args =', args) if len(args) == 0: return 0 for val in args: if not isinstance(val, int): return 0 # 函数的原本逻辑 return func(*args) return in_dec my_sum = dec(my_sum) my_average = dec(my_average) print(my_sum(1, 2, 3, 4, 5)) print(my_sum(1, 2, 3, 4, 5, '6')) print(my_average(1, 2, 3, 4, 5)) print(my_average(1, 2, 3, 4, 5, '6'))
5d9f2bd7d72dbc86307858e565ad994e65a29fd0
PaulineRoca/AIP2016
/Info-2/GUI/converter.py
1,291
3.84375
4
# /usr/bin/env python # Time-stamp: <2016-09-18 08:34:47 cp983411> # code adapted from http://www.tkdocs.com/tutorial/firstexample.html # import Tkinter import ttk def calculate(*args): try: value = float(feet.get()) meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0) except ValueError: pass root = Tkinter.Tk() root.title("Feet to Meters") mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S')) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) feet = Tkinter.StringVar() meters = Tkinter.StringVar() feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet) feet_entry.grid(column=2, row=1, sticky=('W', 'E')) ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=('W', 'E')) ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky='W') ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky='W') ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky='E') ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky='W') for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) feet_entry.focus() root.bind('<Return>', calculate) root.mainloop()
1b083db112cfc38a12c3de2aa3da72af47a5d79a
leonardolginfo/ExerciciosDEVPROPythonBrasil
/venv/EstruturaSequencial/exercicio11-int-float-calculos.py
652
4.34375
4
''' Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: o produto do dobro do primeiro com metade do segundo . a soma do triplo do primeiro com o terceiro. o terceiro elevado ao cubo. ''' num_1 = int(input('Digite o primeiro número: ')) num_2 = int(input('Digite o segundo número: ')) num_3 = float(input('Digite o terceiro número: ')) calculo_1 = (num_1**2) * (num_2/2) print(f'O produto do dobro de {num_1} com metade de {num_2} é {calculo_1}') calculo_2 = (num_1*3) + num_3 print(f'A soma do triplo de {num_1} com {num_3} é {calculo_2}') calculo_3 = (num_3**3) print(f'O triplo de {num_3} é {calculo_3}')
125a682465cf5e7ce32e6d7ede5e5228edeeb50d
LeeJaeng/study
/python/basic/4_calupper.py
410
3.59375
4
def cal_upper(price): increment = price * 0.3 upper_price = price + increment return upper_price def cal_upper_lower(price): offset = price * 0.3 upper_price = price + offset; lower_price = price - offset; return upper_price, lower_price def main(): print(cal_upper(50000)) result = cal_upper_lower(24240) print(type(result)) if __name__ == '__main__': main()
2e87553b4b62596be4807ea68bdf86a6a4309b3c
padamowiczUWM/wd
/cw4.py
7,587
3.640625
4
# Zad. 1 # Wygeneruj liczby podzielne przez 4 i zapisz je do pliku. lista = [i for i in range(4, 100, 4)] with open("dane.txt", "w") as file: file.writelines(str(l) + '\n' for l in lista) # Zad. 2 # Odczytaj plik z poprzedniego zadania i wyświetl jego zawartość w konsoli. with open("dane.txt", "r") as file: print(file.read()) # Zad. 3 # Wykorzystując komendę with zapisz kilka linijek tekstu do pliku a następnie wyświetl je na ekranie. with open('linijki.txt', "w+") as file: file.write("""Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.""") with open("linijki.txt", "r") as file: print(file.read()) # Zad. 4 # # Stwórz klasę NaZakupy, która będzie przechowywać atrybuty: # # nazwa_produktu, ilosc, jednostka_miary, cena_jed oraz metody: # konstruktor – który nadaje wartości # wyświetl_produkt() – drukuje informacje o produkcie na ekranie # ile_produktu() – informacje ile danego produktu ma być czyli ilosc + jednostka_miary np. 1 szt., 3 kg itd. # ile_kosztuje() – oblicza ile kosztuje dana ilość produktu np. 3 kg ziemniaków a cena_jed wynosi 2 zł/kg wówczas funkcja powinna zwrócić wartość 3*2 class NaZakupy: nazwa_produktu = None ilosc = None jednostka_miary = None cena_jed = None def __init__(self, nazwa_produktu, ilosc, jednostka_miary, cena_jed): self.nazwa_produktu = nazwa_produktu self.ilosc = ilosc self.jednostka_miary = jednostka_miary self.cena_jed = cena_jed def wyswietl_produkt(self): print("""Nazwa produktu: {} Ilość: {} Jednostka miary: {} Cena: {}""".format(self.nazwa_produktu, self.ilosc, self.jednostka_miary, self.cena_jed)) def ile_produktu(self): return "{} {}".format(self.ilosc, self.jednostka_miary) def ile_kosztuje(self): return float(self.ilosc) * float(self.cena_jed) produkt = NaZakupy(nazwa_produktu="Ziemniaki", ilosc=3, jednostka_miary="kg", cena_jed=10) produkt.wyswietl_produkt() print(produkt.ile_produktu()) print(produkt.ile_kosztuje()) # Zad. 5 # # Utwórz klasę, która definiuje ciągi arytmetyczne. Wartości powinny być przechowywane jako atrybut. Klasa powinna mieć metody: # # wyświetl_dane – drukuje elementy na ekran # pobierz_elementy– pobiera konkretne wartości ciągu od użytkownika # pobierz_parametry – pobiera pierwsza wartość i różnicę od użytkownika oraz ilość elementów ciągu do wygenerowania. # policz_sume – liczy sume elementow # policz_elementy – liczy elementy jeśli pierwsza wartość i różnica jest podana # Stwórz instancję klasy i sprawdź działanie wszystkich metod. class Ciag: ciagi = [] a1 = None n = None r = None def wyswietl_dane(self): for ciag in self.ciagi: print(ciag, end="\t") print('') def pobierz_elementy(self): ciag = int(input("Podaj liczbe: ")) self.ciagi.append(ciag) def pobierz_parametry(self): self.a1 = int(input("Podaj a1: ")) self.n = int(input("Podaj n: ")) self.r = int(input("Podaj r: ")) def policz_sume(self): return sum(self.ciagi) def policz_elementy(self): if self.a1 is not None and self.r is not None: return len(self.ciagi) ciag = Ciag() ciag.pobierz_elementy() ciag.pobierz_parametry() print(ciag.policz_sume()) print(ciag.policz_elementy()) ciag.wyswietl_dane() # Zad. 6 # # Utwórz klasę Slowa, która będzie zarządzać różnymi grami słownymi. Klasa powinna przechowywać przynajmniej dwa słowa i metody: # # sprawdz_czy_palindrom – metoda sprawdza czy dany wyraz jest palindromem (czytany od początku czy wspak jest taki sam np. kajak) # sprawdz_czy_metagramy – metoda sprawdza czy wyrazy różnią się jedną litera a poza tym są takie same np. mata, tata # sprawdz_czy_anagramy – metoda sprawdza czy wyrazy maja ten sam zestaw liter. Np. mata i tama # wyświetl_wyrazy – wyświetla podane wyrazy # Stwórz instancję klasy i sprawdź działanie wszystkich metod. class Slowa: first_word = None second_word = None def __init__(self, first_word, second_word): self.first_word = first_word self.second_word = second_word def sprawdz_czy_palindrom(self): i = 0 j = len(self.second_word) - 1 while i < j: if self.first_word[i] != self.second_word[j]: return False i += 1 j -= 1 return True def sprawdz_czy_metagramy(self): min_length = min(len(self.first_word), len(self.second_word)) max_length = max(len(self.first_word), len(self.second_word)) difference_count = 0 for i in range(min_length): if self.first_word[i] != self.second_word[i]: difference_count += 1 difference_count += max_length - min_length if difference_count == 1: return True return False def sprawdz_czy_anagramy(self): first_list = list(self.first_word) second_list = list(self.second_word) print(first_list) if sorted(first_list) == sorted(second_list): return True return False def wyswietl_wyrazy(self): print("{}, {}".format(self.first_word, self.second_word)) slowa = Slowa(first_word="mata", second_word="atma") print(slowa.sprawdz_czy_anagramy()) print(slowa.sprawdz_czy_metagramy()) print(slowa.sprawdz_czy_palindrom()) # Zad. 7 # # Stwórz klasę Robot, która będzie sterować ruchami robota. Klasa powinna przechowywać współrzędne x, y, krok (stała wartość kroku dla robota), # i powinna mieć następujące metody: # # konstruktor – który nadaje wartość dla x, y i krok # idz_w_gore(ile_krokow) – metoda która przesuwa robota o ile_krokow*krok w odpowiednim kierunku i ustawia nowe wartości współrzędnych x i y # idz_w_dol(ile_krokow) – metoda która przesuwa robota o ile_krokow*krok w odpowiednim kierunku i ustawia nowe wartości współrzędnych x i y # idz_w_lewo(ile_krokow) – metoda która przesuwa robota o ile_krokow*krok w odpowiednim kierunku i ustawia nowe wartości współrzędnych x i y # idz_w_prawo(ile_krokow) – metoda która przesuwa robota o ile_krokow*krok w odpowiednim kierunku i ustawia nowe wartości współrzędnych x i y # pokaz_gdzie_jestes() – metoda, która wyświetla aktualne współrzędne robota class Robot: x = None y = None krok = None def __init__(self, x, y, krok=1): self.x = x self.y = y self.krok = krok def idz_w_gore(self, ile_krokow): self.y += ile_krokow * self.krok def idz_w_dol(self, ile_krokow): self.y -= ile_krokow * self.krok def idz_w_lewo(self, ile_krokow): self.x -= ile_krokow * self.krok def idz_w_prawo(self, ile_krokow): self.x += ile_krokow * self.krok def pokaz_gdzie_jestes(self): print("x: {}, y: {}".format(self.x, self.y)) def __del__(self): print('--niszczenie--') robot = Robot(x=5, y=5) robot.idz_w_gore(ile_krokow=1) robot.idz_w_dol(ile_krokow=2) robot.idz_w_lewo(ile_krokow=3) robot.idz_w_prawo(ile_krokow=4) robot.pokaz_gdzie_jestes() # Zad. 8 # # Do klasy z wybranego poprzedniego zadania dołącz funkcję niszczenia obiektu.
d985f7cfe12bca34653390725e6123f16b604fdd
ishakapoor4218/sample_python
/first.py
271
4.34375
4
print('Isha Kapoor') #this command is used to print anything print('Welcome to Python') print('Happy Sunday') num1 = 10 num2 = 20 num3 = (num1+num2)/2 total = 0 print(num3) total = 0 for x in range(1,6): print(x) t1 = total + x total = t1 avg = total/x print(avg)
d76c871a2ba6d481938abbc1078d7d3bf02a9347
whikwon/python-patterns
/behavioral/visitor.py
869
3.953125
4
from abc import ABC, abstractmethod class Salesman(ABC): pass class Door2DoorSalesman(Salesman): def visit_premium_customer(self): print("Hello sir, we have prepared a new product for you.") def visit_normal_customer(self): print("Hi, new product has been released. Would you take a look?") class Customer(ABC): @abstractmethod def accept(self, visitor): pass class PremiumCustomer(Customer): def accept(self, visitor): visitor.visit_premium_customer() class NormalCustomer(Customer): def accept(self, visitor): visitor.visit_normal_customer() def main(): premium_customer = PremiumCustomer() normal_customer = NormalCustomer() salesman = Door2DoorSalesman() normal_customer.accept(salesman) premium_customer.accept(salesman) if __name__ == "__main__": main()
12338665dd5035e8afca2befb6ec3f0aef151304
jemtca/CodingBat
/Python/Warmup-1/not_string.py
342
4.40625
4
# this function return a new string where "not" is added to the front # if the string already begin with "not", the function return the string unchanged def not_string(str): s = "" if not str.startswith("not"): s = "not " + str else: s = str return s print(not_string("candy")) print(not_string("x")) print(not_string("not bad"))
7385f3f9411492534b27caee2e54e699315fa10a
Wang-Yann/LeetCodeMe
/python/_1001_1500/1497_check-if-array-pairs-are-divisible-by-k.py
2,543
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Rock Wayne # @Created : 2020-07-10 18:59:15 # @Last Modified : 2020-07-10 18:59:15 # @Mail : lostlorder@gmail.com # @Version : alpha-1.0 """ # 给你一个整数数组 arr 和一个整数 k ,其中数组长度是偶数,值为 n 。 # # 现在需要把数组恰好分成 n / 2 对,以使每对数字的和都能够被 k 整除。 # # 如果存在这样的分法,请返回 True ;否则,返回 False 。 # # # # 示例 1: # # 输入:arr = [1,2,3,4,5,10,6,7,8,9], k = 5 # 输出:true # 解释:划分后的数字对为 (1,9),(2,8),(3,7),(4,6) 以及 (5,10) 。 # # # 示例 2: # # 输入:arr = [1,2,3,4,5,6], k = 7 # 输出:true # 解释:划分后的数字对为 (1,6),(2,5) 以及 (3,4) 。 # # # 示例 3: # # 输入:arr = [1,2,3,4,5,6], k = 10 # 输出:false # 解释:无法在将数组中的数字分为三对的同时满足每对数字和能够被 10 整除的条件。 # # # 示例 4: # # 输入:arr = [-10,10], k = 2 # 输出:true # # # 示例 5: # # 输入:arr = [-1,1,-2,2,-3,3,-4,4], k = 3 # 输出:true # # # # # 提示: # # # arr.length == n # 1 <= n <= 10^5 # n 为偶数 # -10^9 <= arr[i] <= 10^9 # 1 <= k <= 10^5 # # Related Topics 贪心算法 数组 数学 # 👍 15 👎 0 """ import collections from typing import List import pytest # leetcode submit region begin(Prohibit modification and deletion) class Solution: def canArrange(self, arr: List[int], k: int) -> bool: """AC""" counter = collections.Counter() for v in arr: counter[v % k] += 1 # print(counter, "\n") for i in range(k // 2 + 1): if i == 0: if counter[i] % 2 == 1: return False else: j = k - i if counter[i] != counter[j]: return False return True # leetcode submit region end(Prohibit modification and deletion) @pytest.mark.parametrize("kw,expected", [ [dict(arr=[1, 2, 3, 4, 5, 10, 6, 7, 8, 9], k=5), True], [dict(arr=[1, 2, 3, 4, 5, 6], k=7), True], [dict(arr=[1, 2, 3, 4, 5, 6], k=10), False], [dict(arr=[-10, 10], k=2), True], [dict(arr=[-1, 1, -2, 2, -3, 3, -4, 4], k=3), True], ]) def test_solutions(kw, expected): assert Solution().canArrange(**kw) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
16c04687853a3ec86a89668d60947f87dd4bdb67
arrtych/python-algorithms
/s03.py
327
3.6875
4
# -*- coding: utf-8 -*- s = input("Введите строку: ") search = input("Введите искомый символ: ") count = 0 id = 1; while id != -1: id = s.find(search) if id >= 0: count += 1 s = s[id+1:] print ("символ(ы): " + search + " найден " + str(count) + " раз(а)")
b227d42585250ee3d85a9d415309f9b96e22c0bc
curiousTauseef/codility-python
/Lesson 03 - Time Complexity/PermMissingElem_2.py
279
3.578125
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 N = len(A)+1 missing = N for i in range(1, N): missing ^= A[i-1] missing ^= i return missing
a48092ca076b971fd209205613b3d258cefa22e5
LubbyAnneLiu/python_code
/python_NQueen4algorithm.py
1,205
3.734375
4
''' 201721198590 信息科学学院 刘璐 python 回溯法 爬楼梯问题 某楼梯有n层台阶,每步只能走1级台阶,或2级台阶。从下向上爬楼梯,有多少种爬法? ''' n = 6 # 楼梯阶数 x = [] # 一个解(长度不固定,1-2数组,表示该步走的台阶数) X = [] # 一组解 # 冲突检测 def conflict(k): global n, x, X # 部分解步的步数之和超过总台阶数 if sum(x[:k + 1]) > n: return True return False # 无冲突 # 回溯法(递归版本) def climb_stairs(k): # 走第k步 global n, x, X if sum(x) == n: # 已走的所有步数之和等于楼梯总台阶数 print(x) # X.append(x[:]) # 保存(一个解) else: for i in [1, 2]: # 第k步这个元素的状态空间为[1,2] x.append(i) if not conflict(k): # 剪枝 climb_stairs(k + 1) x.pop() # 回溯 # 测试 climb_stairs(0) # 走第0步 ''' 其中一个解: [1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 2] [1, 1, 1, 2, 1] [1, 1, 2, 1, 1] [1, 1, 2, 2] [1, 2, 1, 1, 1] [1, 2, 1, 2] [1, 2, 2, 1] [2, 1, 1, 1, 1] [2, 1, 1, 2] [2, 1, 2, 1] [2, 2, 1, 1] [2, 2, 2] '''
c9d9619629abb0fa21f842b22b428da09ae8bbed
GlobalCreativeCommunityFounder/InfiniteList
/InfiniteList/InfiniteList.py
8,460
4.15625
4
""" This file contains code for the data type "InfiniteList". Author: GlobalCreativeCommunityFounder """ # Importing necessary libraries import copy # import sys from mpmath import * mp.pretty = True # Creating InfiniteList class class InfiniteList: """ This class contains attributes of an infinite list. """ def __init__(self, elements=None): # type: (list) -> None self.list_count: int = 0 # initial value self.MAX_SUBLIST_SIZE: int = 50 # a reasonable number of elements allowed per # sublist to ensure that the data type runs fast and is good for storing many elements if elements is None: elements = [] # Transferring all elements from 'elements' list to this infinite list. num_lists: int = 1 + (len(elements) // self.MAX_SUBLIST_SIZE) # The number of sub lists required for i in range(num_lists): self.__add_sublist() curr_list: list = elements[0:self.MAX_SUBLIST_SIZE] if len(elements) >= self.MAX_SUBLIST_SIZE \ else elements self.__setattr__("list" + str(i + 1), curr_list) def copy(self): # type: () -> InfiniteList return copy.deepcopy(self) def count(self, elem): # type: (object) -> int result: int = 0 for i in range(self.__len__()): if self.__getitem__(i) == elem: result += 1 return result def index(self, elem): # type: (object) -> int for i in range(self.__len__()): if self.__getitem__(i) == elem: return i return -1 def reverse(self): # type: () -> None reversed_infinite_list: InfiniteList = InfiniteList() # initial value saved_list_count: int = self.list_count # saving the initial value of 'self.list_count' for i in range(self.list_count, 0, -1): curr_list: list = self.__getattribute__("list" + str(i)) curr_list.reverse() reversed_infinite_list.extend(curr_list) self.clear() for i in range(saved_list_count): self.__add_sublist() self.__setattr__("list" + str(i + 1), reversed_infinite_list.__getattribute__("list" + str(i + 1))) def sort(self): # type: () -> None for i in range(self.__len__()): minimum_index: int = i for j in range(i + 1, self.__len__()): if self.__getitem__(minimum_index) > self.__getitem__(j): minimum_index = j temp1 = self.__getitem__(i) temp2 = self.__getitem__(minimum_index) self.__setitem__(minimum_index, temp1) self.__setitem__(i, temp2) def min(self): # type: () -> object return min(min(self.__getattribute__("list" + str(i))) for i in range(1, self.list_count + 1)) def max(self): # type: () -> object return max(max(self.__getattribute__("list" + str(i))) for i in range(1, self.list_count + 1)) def sum(self): # type: () -> mpf return mpf(sum(sum(self.__getattribute__("list" + str(i))) for i in range(1, self.list_count + 1))) def extend(self, a_list): # type: (list) -> None for elem in a_list: self.append(elem) def insert(self, pos, elem): # type: (int, object) -> None if pos < 0 or pos >= self.__len__(): raise Exception("InfiniteList index out of range!") else: last_list: list = self.__getattribute__("list" + str(self.list_count)) last_elem: object = last_list[len(last_list) - 1] if len(last_list) == self.MAX_SUBLIST_SIZE: self.__add_sublist() for index in range(self.__len__() - 1, pos, -1): self.__setitem__(index, self.__getitem__(index - 1)) self.__setitem__(pos, elem) self.append(last_elem) def append(self, elem): # type: (object) -> None last_list: list = self.__getattribute__("list" + str(self.list_count)) if len(last_list) < self.MAX_SUBLIST_SIZE: last_list.append(elem) else: self.__add_sublist() last_list = self.__getattribute__("list" + str(self.list_count)) last_list.append(elem) def delete(self, index): # type: (int) -> None if index < 0 or index >= self.__len__(): raise Exception("InfiniteList index out of range!") for curr_index in range(index, self.__len__() - 1): self.__setitem__(curr_index, self.__getitem__(curr_index + 1)) last_list: list = self.__getattribute__("list" + str(self.list_count)) last_list.remove(last_list[len(last_list) - 1]) if self.list_count > 1: before_last_list: list = self.__getattribute__("list" + str(self.list_count - 1)) # Remove the last list if it is empty and the previous list is not full if len(last_list) == 0 and len(before_last_list) < self.MAX_SUBLIST_SIZE: self.__remove_sublist() else: if len(last_list) == 0: self.__remove_sublist() def remove(self, elem): # type: (object) -> bool elem_index: int = -1 # initial value for index in range(self.__len__()): if self.__getitem__(index) == elem: elem_index = index break if elem_index == -1: return False for index in range(elem_index, self.__len__() - 1): self.__setitem__(index, self.__getitem__(index + 1)) last_list: list = self.__getattribute__("list" + str(self.list_count)) last_list.remove(last_list[len(last_list) - 1]) if self.list_count > 1: before_last_list: list = self.__getattribute__("list" + str(self.list_count - 1)) # Remove the last list if it is empty and the previous list is not full if len(last_list) == 0 and len(before_last_list) < self.MAX_SUBLIST_SIZE: self.__remove_sublist() else: if len(last_list) == 0: self.__remove_sublist() return True def clear(self): # type: () -> None for i in range(1, self.list_count + 1): self.__setattr__("list" + str(i), []) for i in range(self.list_count): self.__remove_sublist() def __len__(self): # type: () -> InfiniteList if self.list_count == 0: return 0 last_list: list = self.__getattribute__("list" + str(self.list_count)) return self.MAX_SUBLIST_SIZE * (self.list_count - 1) + len(last_list) def __getitem__(self, index): # type: (int) -> object if index < 0 or index >= self.__len__(): raise Exception("InfiniteList index out of range!") else: list_number: int = 1 + (index // self.MAX_SUBLIST_SIZE) list_index: int = index % self.MAX_SUBLIST_SIZE curr_list: list = self.__getattribute__("list" + str(list_number)) return curr_list[list_index] def __setitem__(self, index, value): # type: (int, object) -> None if index < 0 or index >= self.__len__(): raise Exception("InfiniteList index out of range!") else: list_number: int = 1 + (index // self.MAX_SUBLIST_SIZE) list_index: int = index % self.MAX_SUBLIST_SIZE curr_list: list = self.__getattribute__("list" + str(list_number)) curr_list[list_index] = value def __add_sublist(self): # type: () -> None self.__setattr__("list" + str(self.list_count + 1), []) self.list_count += 1 def __remove_sublist(self): # type: () -> None self.__delattr__("list" + str(self.list_count)) self.list_count -= 1 def __str__(self): # type: () -> str if self.__len__() == 0: return "[]" res: str = "[" # initial value for i in range(1, self.list_count + 1): curr_list = self.__getattribute__("list" + str(i)) for j in range(len(curr_list)): if i == self.list_count and j == len(curr_list) - 1: res += str(curr_list[j]) + "]" else: res += str(curr_list[j]) + ", " return res
071e3f75d0441c0786e4ed071eed6de167f39476
abingham/project_euler
/python/src/euler/exercises/ex0033.py
1,940
3.546875
4
"""The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ from fractions import Fraction from functools import reduce from itertools import count, islice from euler.lib.compat import gcd from euler.lib.util import digits, undigits def reduced(num, den): ndigits = list(digits(num)) ddigits = list(digits(den)) for dig in tuple(ndigits): if dig in ddigits: ndigits.remove(dig) ddigits.remove(dig) return undigits(ndigits), undigits(ddigits) def is_curious(num, den): try: nnum, nden = reduced(num, den) return (num != nnum and den != nden and Fraction(nnum, nden) == Fraction(num, den)) except (ValueError, ZeroDivisionError): return False def is_trivial(num, den): """A fraction is trivial if: a) Both he numerator and denominator end in the same number of zeros, and b) They share no other common digits beyond the trailing zeros. """ return gcd(num, den) % 10 == 0 def curious(): for den in count(1): for num in range(1, den): if is_curious(num, den) and not is_trivial(num, den): yield num, den def nontrivial_curious(): return islice( ((n, d) for n, d in curious() if not is_trivial(n, d)), 4) def main(): return reduce( lambda acc, n: acc * Fraction(n[0], n[1]), nontrivial_curious(), Fraction(1, 1)).denominator
ed02a18515b4d0ba1f5ad0f8448fc3905e11fed8
ys558/FluentPython
/2.2.4_生成器表达式.py
496
3.859375
4
symbols = '☚☟♫☯☳' # 2.5 生成器表达式tuple,array tuple = tuple(ord(symbol) for symbol in symbols) print(tuple) # (9754, 9759, 9835, 9775, 9779) import array array = array.array('I', (ord(symbol) for symbol in symbols)) print(array) # array('I', [9754, 9759, 9835, 9775, 9779]) colors = ['black', 'white'] sizes = ['S', 'M', 'L'] for tshirt in ('%s, %s' % (c, s) for c in colors for s in sizes): print(tshirt) # black, S # black, M # black, L # white, S # white, M # white, L
3ca0f34e40e3e74d8366f5f9da35a89cea7dfeed
brianeflin/HFPython
/ch02/vowels.py
259
4.4375
4
vowels = ['a', 'e', 'i', 'o', 'u'] vowels_found = [] word = input("Input a word for a vowel search: ") for letter in word: if letter in vowels and letter not in vowels_found: vowels_found.append(letter) for vowel in vowels_found: print(vowel)
ad6da095092f38892c9233aeb2b0f8675edeb8af
Songlynn/myMLLearning
/01LinearRegression/demo.py
1,316
3.984375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import LinearRegression as lr # 1.数据处理 data = np.loadtxt('linear_regression_data1.txt', delimiter=',') print('Data:') print(data[0:5]) X = np.c_[np.ones(data.shape[0]), data[:, 0]] y = np.c_[data[:, 1]] # 2.绘制散点图 plt.scatter(X[:, 1], y,s=30, c='r', marker='x', linewidths=1) plt.xlim(4,24) plt.xlabel("Population of City in 10,000s") plt.ylabel("Profit in $10,000s") plt.show() # 3.绘制损失函数迭代变化 theta, cost_J = lr.gradientDescent(X, y) print('theta: ', theta.ravel()) plt.plot(cost_J) plt.ylabel('cost J') plt.xlabel('Iterations') plt.show() # 4.与sklearn的线性回归模型对比 xx = np.arange(5,23) yy = theta[0]+theta[1]*xx # 画出我们自己写的线性回归梯度下降收敛的情况 plt.scatter(X[:,1], y, s=30, c='r', marker='x', linewidths=1) plt.plot(xx,yy, label='Linear regression (Gradient descent)') # 和Scikit-learn中的线性回归对比一下 regr = LinearRegression() regr.fit(X[:,1].reshape(-1,1), y.ravel()) plt.plot(xx, regr.intercept_+regr.coef_*xx, label='Linear regression (Scikit-learn GLM)') plt.xlim(4,24) plt.xlabel('Population of City in 10,000s') plt.ylabel('Profit in $10,000s') plt.legend(loc=4); plt.show()
e80853e568d3b11e2fe6ab68fa0a0fff3728e396
goncalossantos/Algorithms
/Challenges/CCI/Chapter 01/rotate_matrix_inplace.py
1,970
3.96875
4
class Rotation(): def rotate(self, i, j): return (j, self.N - i -1) def __init__(self, i, j, N): self.N = N self.get_coordinates_to_rotate(i, j) def get_coordinates_to_rotate(self, i, j): self.top = (i,j) self.right = self.rotate(i,j) self.bottom = self.rotate(*self.right) self.left = self.rotate(*self.bottom) def apply_rotation(matrix, rotation): tmp = matrix[rotation.top[0]][rotation.top[1]] matrix[rotation.top[0]][rotation.top[1]] = matrix[rotation.left[0]][rotation.left[1]] matrix[rotation.left[0]][rotation.left[1]] = matrix[rotation.bottom[0]][rotation.bottom[1]] matrix[rotation.bottom[0]][rotation.bottom[1]] = matrix[rotation.right[0]][rotation.right[1]] matrix[rotation.right[0]][rotation.right[1]] = tmp return matrix def rotate_matrix(matrix): """Rotates a matrix 90 degrees Iterates through a matrix to rotate it in place. Arguments: matrix {list of lists} -- contains the matrix of ints Returns: [list of lists] -- rotated matrix """ N = len(matrix) # We only need to go to the middle row for i in range(N/2): # We only need to to the inside columns for j in range(i,N-i-1): rotation = Rotation(i, j, N) matrix = apply_rotation(matrix, rotation) return matrix def print_matrix(matrix): print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in matrix])) def test_matrix(): test_2 = ([[1, 2], [3, 4]] , [[3, 1], [4, 2]]) test_3 = ([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[7, 4, 1], [8, 5, 2], [9, 6, 3]]) test_4 = ( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]], ) for test in [test_2, test_3, test_4]: result = rotate_matrix(test[0]) assert result == test[1] test_matrix()
a3fad8cbc734f44c42f63bf9a8a0e6045db29d3d
NicholasDowell/DataAnalysis
/DataCleaning.py
5,626
3.9375
4
# -*- coding: utf-8 -*- """ @author: Nicholas Dowell """ import pandas as pd #Part A - Read the file into a pandas dataframe df = pd.read_csv('m1_w2_ds1.csv') #Part B - use Class Labelling on any string '1 5 255' from sklearn.preprocessing import LabelEncoder #The column named 'PUBCHEM_COORDINATE_TYPE' is the only column with '1 5 255' in it class_le = LabelEncoder() #the fit_transform method calculates labels for the provided column y = class_le.fit_transform(df['PUBCHEM_COORDINATE_TYPE'].values) df['PUBCHEM_COORDINATE_TYPE'] = y #sets each value in the column to its calculated label (in this case all zeroes) #note: labelEncoder takes care of the labelling process so the user need not specify labels ''' Part C- Map all ordinal data columns to numbers Ordinal data is data where the categories are in an implied order, but their magnitudes are not necessarily consistent. an example wouyld be Small, Medium, Large. Ordinal Data is in one column: PUBCHEM_TOTAL_CHARGE (POSITIVE, NEGATIVE, ZERO) ''' positivity_mapping = {'POSITIVE' : 1, 'NEGATIVE' : -1, 'ZERO' : 0} df['PUBCHEM_TOTAL_CHARGE'] = df['PUBCHEM_TOTAL_CHARGE'].map(positivity_mapping) ''' Part D - Handle the remaining categorical data in the last column: 'apol' ''' #getdummies using pandas #literally does the whole thing in one line of code. df = pd.get_dummies(df) #The apol column is now One-Hot encoded #get_dummies actually encodes every column that has strings in it, # so the user needs to be careful! In this case if we had not already encoded two columns in our desired way, they would have been encoded here. ''' Part E - replace missing values with the mean from the column ''' for column in df: #This loop iterates over the column names in a dataframe df[column] = df[column].fillna(df[column].mean(skipna = True)) #each column finds its own mean (skipping nan), and replaces nans with the mean ''' Part F - find mean of each row, mean of each column, sd of columns, sd of rows. ''' # (i)The mean of values in each column print("MEAN VALUES OF COLUMNS") print(df.mean(axis = 0)) #(ii) The mean values in each row print("MEAN VALUES OF EACH ROW") print(df.mean(axis = 1)) # (iii)The standard deviation (STD) of the values in each column and  print the result print("STANDARD DEVIATION OF EACH COLUMN") print(df.std(axis = 0)) # (iv) The standard deviation (STD) of the values in each row and  print the result print("STANDARD DEVIATION OF EACH ROW") print(df.std(axis = 1)) ############################### ### PART 2 ### ############################### # 1. Scatter Plot first 10 columns and rows #I will use seaborn pairplot to do this. import seaborn as sns #cols stores the head of each column as a string - This will make access easier cols = ['CID', 'IC50', 'class', 'PUBCHEM_XLOGP3_AA', 'PUBCHEM_EXACT_MASS', 'PUBCHEM_MOLECULAR_WEIGHT', 'PUBCHEM_CACTVS_TPSA', 'PUBCHEM_MONOISOTOPIC_WEIGHT', 'PUBCHEM_TOTAL_CHARGE', 'PUBCHEM_HEAVY_ATOM_COUNT', ] #plots each column against all the others sns.pairplot(df.loc[0:10, cols]) # 2. Heatmap the first 10 columns and rows #This Heatmap is a correlation matrix like we saw in a previous example import numpy as np #This code is the same code from the code samples provided. plt.figure() cm = np.corrcoef(df[cols].values.T) # calculates a correlation coefficient for each pair of columns sns.set(font_scale=0.6) #formatting for the visual #plots the heatmap hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 8}, yticklabels=cols, xticklabels=cols) plt.show() #df[cols].values.T What is going on in this packed line of code?? #df[cols] is a dataframe #.values returns a numpy array containing the same values #np_array.T returns the transpose of the array. #so the whole thing just turns the dataframe on its own side. #3. Are there any Outlier points? # To answer this, I will look at the pairplot above. # the outliers I find here are relative to the small subset of the data I am looking at in the 10 rows and 10 columns #row indexes are provided in terms of their position within the data, not within the csv file, so row 0 is the first row of data ''' Two of the CID values in the 22 million range are far apart from the other 8 at 11 million 26000 and 18000 are outliers in the IC50 column the Class column is completely uniform PUBCHEM_XLOGP3_AA - 5.1 and 4.1 are outliers PUBCHEM_EXACT_MASS 353, 353, and 395 are all outliers PUBCHEM_MOLECULAR_WEIGHT - There don't seem to be any outliers- the data is spread widely though PUBCHEM_CACTVS_TPSA - One value is an outlier all the awy up at 109 PUBCHEM_MONOISOTOPIC_WEIGHT - no outliers PUBCHEM_TOTAL_CHARGE - All values are -1, so there are no outliers PUBCHEM_HEAVY_ATOM_COUNT - One outlier at value of 32 ''' #4. Find Quantiles # I will assume quartiles are what is wanted since the n is not specified for n-quantile import matplotlib.pyplot as plt #make my own dataframe ftr with only the first 10 rows of data - should have dont this first # FTR stands for First Ten Rows ( and ten columns) ftr = df.loc[0:10, cols] fix, axs = plt.subplots(1, 10) for i in range(10): plt.sca(axs[i]) ftr.boxplot(column=cols[i]) #prints the 25%, 50%, and 75% quantiles for each column in the entire dataframe q = df.quantile(q = [.25, .50, .75], axis=0) print(q)
d6344c930d8f4d1262ebf8e401838c7c3155aac7
jochigt87/PythonCrashCourse
/Chapter8/8-8.py
826
4.5625
5
#!/usr/bin/env python # -*- coding: utf-8 -*- # User Album: Start with you program from Exercise 8-7. Write a while loop that # allows users to enter an album's artist and title. Once you have that # information, call make_album() with the user's input and print the dictionary # that's created. Be sure to include a quit value in the while loop. def make_album(artist_name, album_title): album = {'artist': artist_name, 'title': album_title} return album while True: print("\nPlease insert info about your artist name and album title" ) print("(enter 'q' at any time to quit)") artist_name = input("Artist Name:" ) if artist_name == 'q': break album_title = input("Album Title: ") if album_title == 'q': break musico = make_album(artist_name, album_title) print(musico)
84aeee91c58c3720f3e155714cde999e7ec0a8ec
theWellHopeErr/data-structures-and-algorithms
/1. Algorithmic Toolbox/Week 2 - Algorithmic Warm-up/3gcd.py
180
3.75
4
def gcd(a,b): if a == 0: return b if b == 0: return a a,b = b,a%b return gcd(a,b) if __name__ == "__main__": a,b = map(int,input().split()) print(gcd(a,b))
596deb171e3dc78af8a312611e0afd02604982fc
shants/LeetCodePy
/322.py
604
3.625
4
class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ tbl = [float("inf")]*(amount+1) tbl[0]=0 for i in range(1, amount+1): for j in coins: if i-j >=0 and tbl[i-j]+1 < tbl[i]: tbl[i]= tbl[i-j]+1 if tbl[amount]!= float("inf"): return tbl[amount] else: return -1 if __name__ == "__main__": s = Solution() print(s.coinChange([1, 2, 5], 11)) print(s.coinChange([ 2], 3))
deffadfaae30fe43cf7200b5dde02f9cc441dc8d
sendurr/spring-grading
/submission - lab5/set1/RYAN W BARRS_9404_assignsubmission_file_lab5.py
228
3.59375
4
#1 def printstar(n): answer = n*"*" return answer print printstar(1), printstar(10), printstar(100) 2 def printstarx(n,rows=1): for i in range(rows): print ''*rows + '*'*n print printstarx(10) print printstarx(10,5)
45138350372cfae854f134ce0d7abc85bb28011a
omranzboon/Python-Course
/Week 1/Practise1-B.py
444
4
4
#!/usr/bin/env python # coding: utf-8 # In[4]: x=float(input("Enter your number ")) if x < -100 : result = -1*x print(result) elif x>=-100 and x<= -25 : result = x**4 print(result) elif x> -25 and x <= 0 : result = 3*(x**2) -1 print(result) elif x>0 and x<= 100: result = (22/14)*x +(3**x) print(result) elif x>100 : result = x print(result)
1ace81ea0bbeecff60d63f3f6b5cbea7fa923df5
zeeshan495/Python_programs
/Algorithm/InsertionSort.py
600
3.765625
4
from Utility import * class InsertionSort: utility = Utility() print("enter the number of words for insertion sort : ") var_input = utility.input_int_data() if (var_input <= 0): print("please check the input : ") else: my_array = [None] * var_input print(" enter values ") for x in range(0, var_input): my_array[x] = utility.input_int_data() sort_array = utility.insertion_sort(my_array) print("after insertion sort : ") for x in range(0, len(sort_array)): print(sort_array[x]), print("\n")
82a95867a93267fddfb1b8149f2632feaa4a1746
slowtrain/jython-study
/study/study04.py
439
3.734375
4
#-*- coding: utf-8 -*- from java.util import ArrayList class Lesson(object): def array1(self): arr = ['a','b','c'] arr.append('d') for ar in arr: print ar for number in range(len(arr)): print str(number)+' '+ arr[number] def array2(self): arr = ArrayList() arr.add('a') arr.add('b') arr.add('c') for ar in arr: print ar
7b0f21c6daadddd2779ead82c07c74eae0978572
emmafine/graphes-eclairage
/Graph_Class.py
7,463
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 17 08:17:20 2020 @author: Asus """ import random class Vertex: def __init__(self, node): self.id = node self.light = 1 self.adjacent = [] def __str__(self): return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent]) def add_neighbour(self, neighbour): if neighbour not in self.adjacent: self.adjacent.append(neighbour) def get_connections(self): return self.adjacent.keys() def get_id(self): return self.id # def swtich_on(self): # self.light = 1 # def switch_off(self): # self.light = 1 class Graph: def __init__(self): self.vert_dict = {} self.num_vertices = 0 self.edges = [] def __iter__(self): return iter(self.vert_dict.values()) def add_vertex(self, node, light): self.num_vertices = self.num_vertices + 1 new_vertex = Vertex(node) self.vert_dict[node] = new_vertex self.vert_dict[node].light = light return new_vertex def get_vertex(self, n): if n in self.vert_dict: return self.vert_dict[n] else: return None def add_edge(self, frm, to, frm_l = random.randrange(2), to_l= random.randrange(2)): if frm not in self.vert_dict: self.add_vertex(frm,frm_l) if to not in self.vert_dict: self.add_vertex(to,to_l) self.vert_dict[frm].add_neighbour(self.vert_dict[to]) self.vert_dict[to].add_neighbour(self.vert_dict[frm]) self.edges.append({frm,to}) def get_vertices(self): return self.vert_dict.keys() def how_many_lights(self): count = 0 for node in self.vert_dict.keys(): if self.vert_dict[node].light ==1: count= count+1 return count def lit_lists(self): lit_dict = {} vertex_list = [] light_list = [] for node in self.vert_dict.keys(): lit_dict[node] = self.vert_dict[node].light vertex_list.append(node) light_list.append(self.vert_dict[node].light) return lit_dict, vertex_list, light_list def lit_dict_neighbour(self): lit_dict = {} for node in self.vert_dict.keys(): lit_node = 0 lit_neighbour = 0 for neighbour in self.vert_dict[node].adjacent: #for neighbour in self.vert_dict[node].adjacent.keys(): if neighbour.light == 1: lit_neighbour = 1 if self.vert_dict[node].light == 1 or lit_neighbour ==1: lit_node = 1 else: lit_node = 0 lit_dict[node] = lit_node return lit_dict def is_lit_node(self): lit_dict = self.lit_dict_neighbour() if 0 in lit_dict.values(): return 0 else: return 1 def switch_off(self,i): self.vert_dict[i].light = 0 def switch_on(self,i): self.vert_dict[i].light = 1 def is_opti_lit_nodes(self): ok = 1 if self.is_lit() == 0: return 0 #check is the leaves are lit -> they can be always off #in a minimally lit graph for node in self.vert_dict.keys(): if len(self.vert_dict[node].adjacent) == 1: if self.vert_dict[node].light == 1: ok = 0 #check if it's optimally lit for node in self.vert_dict.keys(): if self.vert_dict[node].light == 1: self.vert_dict[node].light = 0 if self.is_lit() == 1: ok = 0 self.vert_dict[node].light = 1 if ok == 0: return 0 else: return 1 def is_lit(self): #checks if every street is enlightened ok = 1 for edge in self.edges: l = list(edge) if self.vert_dict[l[0]].light == 0 and self.vert_dict[l[1]].light == 0: ok = 0 return ok def is_min_lit(self): #enlever un lampadaire plonge au moins une rue dans l'obscurite if self.is_lit() == 0: return 0 ok = 1 for node in self.vert_dict.keys(): if self.vert_dict[node].light == 1: self.switch_off(node) if self.is_lit() == 1: ok = 0 self.switch_on(node) return ok def switch_graph_on(self): for i in self.vert_dict.keys(): self.vert_dict[i].light = 1 def switch_graph_off(self): for i in self.vert_dict.keys(): self.vert_dict[i].light = 0 ##############################################Class Ends def con_graf(nr_nodes,nr_edges): """ spawning a connected graph with nr_nodes nodes and nr_edges edges nr_edges in [nr_nodes - 1, nr_nodes*(nr_nodes-1)/2 ] """ if nr_edges < nr_nodes-1 or nr_edges > nr_nodes*(nr_nodes-1)/2: print('nr_edges not in [nr_nodes - 1, nr_nodes*(nr_nodes-1)/2 ]') return 0 fop = Graph() fop_l = [] fop.add_vertex(0, random.randrange(2)) for i in range(1,nr_nodes): r = random.choice(list(fop.vert_dict.keys())) fop.add_vertex(i, random.randrange(2)) fop.add_edge(i,r) fop_l.append((i,r)) fop_l.append((r,i)) for i in range(nr_nodes-1, nr_edges): fr = random.choice(list(fop.vert_dict.keys())) to = random.choice(list(fop.vert_dict.keys())) while to == fr: to = random.choice(list(fop.vert_dict.keys())) while (fr,to) in fop_l: fr = random.choice(list(fop.vert_dict.keys())) to = random.choice(list(fop.vert_dict.keys())) while to == fr: to = random.choice(list(fop.vert_dict.keys())) fop.add_edge(fr, to) fop_l.append((fr,to)) fop_l.append((to,fr)) return fop if __name__ == '__main__': g = Graph() g.add_vertex('a',0) g.add_vertex('b',0) g.add_vertex('c',1) g.add_vertex('d',0) g.add_vertex('e',1) g.add_vertex('f',0) g.add_edge('a', 'b') g.add_edge('a', 'c') g.add_edge('a', 'f') g.add_edge('b', 'c') g.add_edge('b', 'd') g.add_edge('c', 'd') g.add_edge('c', 'f') g.add_edge('d', 'e') g.add_edge('e', 'f') g.add_edge('a','b') f = Graph() f.add_vertex(1,0) f.add_vertex(2,1) f.add_vertex(3,0) f.add_vertex(4,0) f.add_vertex(5,1) f.add_vertex(6,1) f.add_vertex(7,1) f.add_edge(1, 2) f.add_edge(2, 3) f.add_edge(4, 2) f.add_edge(4, 5) f.add_edge(4, 6) f.add_edge(5, 6) f.add_edge(6, 7) f.add_edge(4, 7)
0bf814f53e7edba8ec6c1d476c23772fa73c95a5
mattpopovich/TestMergeRepo
/CMPSC443/CTF/countingToFile.py
324
3.96875
4
# This is a python file to write binary values of 0-256 to a file 'count.txt' outfile = 'count.txt' fout = open(outfile, 'w') count = 0; # Loop through infile byte by byte while (count <= 255): # converts count to a 8-bit binary string binary = bin(count)[2:].zfill(8) fout.write(binary) count += 1
cce5df8e589d8a0874071d4ed165e446682e241b
endermeihl/deeplearning.github.io
/leetcode/isPalindrome.py
295
3.859375
4
def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False if x % 10 == 0 and x != 0: return False cur = 0 num = x while int(num) != 0: cur = cur * 10 + int(num) % 10 num /= 10 return cur == x isPalindrome(1,121)
d0e7b726aa7c97ef52e24d72b9146a6ba8f334af
avcopan/fermitools
/fermitools/math/findif.py
1,245
3.640625
4
import numpy import scipy.misc def central_difference(f, x, step=0.01, nder=1, npts=None): """differentiate a function using central differences :param f: the function :type f: typing.Callable :param x: the point at which to evaluate the derivative :type x: float or numpy.ndarrray :param step: step size, or a grid of step sizes corresponding to `x` :type step: float or numpy.ndarray :param nder: return the nth derivative :type nder: int :param npts: the number of grid points, default `nder` + `1` + `nder % 2` :type npts: int """ if npts is None: npts = nder + 1 + nder % 2 if numpy.ndim(step) == 0: step = float(step) * numpy.ones_like(x) weights = scipy.misc.central_diff_weights(Np=npts, ndiv=nder) def derivative(index): dx = numpy.zeros_like(x) dx[index] = step[index] grid = [numpy.array(x) + (k - npts//2) * dx for k in range(npts)] vals = map(f, grid) return (sum(numpy.multiply(w, v) for w, v in zip(weights, vals)) / (step[index] ** nder)) der = tuple(map(derivative, numpy.ndindex(numpy.shape(x)))) shape = numpy.shape(x) + numpy.shape(f(x)) return numpy.reshape(der, shape)
e3a0c6b88eb3ff3a0ead39f7388b4c5e1aca7d39
adepeter/sleekforum
/src/sleekapps/cores/utils/choice.py
985
3.578125
4
from collections import ValuesView from typing import Tuple, List, Dict class Choicify: """This is a utility class which returns tuple of choices calculates length of individual choices for use in CharField """ def __init__(self, choices: Tuple) -> None: self.__choices = sorted(choices) def __dictify_choices(self, choices: Tuple) -> ValuesView: "Return length of dict_value for each choices" choices_to_dict = dict(choices) # convert tuple to dictionary count = {k: len(k) for k, v in choices_to_dict.items()} return count.values() def to_dict(self): """Return key: value mapping""" return dict(self.__choices) @property def get_choices(self) -> List: "Return list of choice" return self.__choices def __len__(self) -> int: """Returns length of longest choice tuple""" return max(self.__dictify_choices(self.__choices))
9f6a663f6d0c00da2d7a78b838d60e8ab731fb10
sadullahmutlu/GAIH_Python_Course
/Homeworks/HW1.py
698
4.46875
4
odd_num = [0,2,4,6,8] even_num = [1,3,5,7,9] print("Odd Numbers: " , odd_num) #burayı tek satırda da aralarına \n koyarak da yazılabilir. print("Even Numbers: " , even_num, "\n") numbers = odd_num + even_num #İki listeyi birleştirdik. print("All Numbers:",numbers, "\n") new_list = [i*2 for i in numbers] #İki Listenin elemanlarını birleştirip 2 ile çarptık print("Multiplication list :",new_list, "\n") new_list.sort() #listeyi sıralayın demiyordu fakat daha düzgün gözükmesi açısından listeyi sıraladık. print("Sorted list :", new_list, "\n") print("New_List Data type of:",type(new_list),"\n") for i in new_list: print(i, ": data type of",type(i))
1a4e8cbacee031cd3ce3750d094ef2553972d0b5
AnshumanSinghh/DSA
/data_structure/queue/queue.py
1,048
4.53125
5
# Queue implementation in Python """ The complexity of enqueue and dequeue operations in a queue using an array is O(1). """ class Queue: def __init__(self): self.queue = [] # Add an element def enqueue(self, item): self.queue.append(item) # Remove an element def dequeue(self): if len(self.queue) < 1: # check if queue is empty return None print("popped:", self.queue[0]) return self.queue.pop(0) # delete the first element always # Display the queue def display(self): print(self.queue) # To get the length of the queue def size(self): return len(self.queue) # Driver Code Starts if __name__ == "__main__": q = Queue() # object creation # now calling methods using object q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) q.enqueue(5) print("After 5 enqueue:", q.size()) q.enqueue(6) q.display() q.dequeue() q.dequeue() q.display() print("At end:", q.size())
2e9879692636e97c36e9b1ed536b218228cf8d62
SamIlic/AAT
/Algorithmic Trading/Bayesian Statistics/beta_binomial_MCMC.py
3,300
3.71875
4
# RUN TIME - ~ 2 min import matplotlib.pyplot as plt import numpy as np import pymc3 import scipy.stats as stats plt.style.use("ggplot") ### Specify & Sample Model # Set prior parameters # Parameter values for prior and analytic posterior n = 50 # number of coin flips z = 10 # number of observed heads alpha = 12 # beggining num heads beta = 12 # beginning num tails alpha_post = 22 # end num heads beta_post = 52 # end num tails # How many iterations of the Metropolis algorithm to carry out for MCMC iterations = 100000 # num iterations of Metropolis algo for MCMC # define our beta distribution prior and Bernoulli likelihood model. # 1) Firstly, we specify the theta parameter as a beta distribution, taking the prior alpha and beta values as parameters. # Remember that our particular values of α = 12 and β = 12 imply a prior mean μ = 0.5 and a prior s.d. σ = 0.1. # 2) We then define the Bernoulli likelihood function, specifying the fairness parameter p=theta, the number of trials n=n and the observed heads observed=z # all taken from the parameters specified above. # 3) At this stage we can find an optimal starting value for the Metropolis algorithm using the PyMC3 Maximum A Posteriori (MAP) optimisation, the details of which we will omit here. # 4) Finally we specify the Metropolis sampler to be used and then actually sample(..) the results. These results are stored in the trace variable: # Use PyMC3 to construct a model context basic_model = pymc3.Model() # create a model and call it basic_model with basic_model: # Define our prior belief about the fairness of the coin using a Beta distribution theta = pymc3.Beta("theta", alpha=alpha, beta=beta) # Define Beta distributio y = pymc3.Binomial("y", n=n, p=theta, observed=z) # Define the Bernoulli likelihood function # Carry out the MCMC analysis using the Metropolis algorithm # Use Maximum A Posteriori (MAP) optimisation as initial value for MCMC start = pymc3.find_MAP() # Use the Metropolis algorithm (as opposed to NUTS or HMC, etc.) step = pymc3.Metropolis() # Calculate the trace (trace = list of all accepted samples) trace = pymc3.sample( iterations, step, start, random_seed=1, progressbar=True ) ### Now that the model has been specified and sampled, we wish to plot the results. # We create a posterior histogram from the trace of the MCMC sampling using 50 bins. # Then, plot the analytic prior and posterior beta distributions using the SciPy stats.beta.pdf(..) method. # Finally, we add some labelling to the graph and display it: # Plot the posterior histogram from MCMC analysis bins=50 plt.hist( trace["theta"], bins, histtype="step", normed=True, label="Posterior (MCMC)", color="red" ) # Plot the analytic prior and posterior beta distributions x = np.linspace(0, 1, 100) plt.plot( # Prior x, stats.beta.pdf(x, alpha, beta), "--", label="Prior", color="blue" ) plt.plot( # Posterior x, stats.beta.pdf(x, alpha_post, beta_post), label='Posterior (Analytic)', color="green" ) # Update the graph labels plt.legend(title="Parameters", loc="best") plt.xlabel("$\\theta$, Fairness") plt.ylabel("Density") plt.show() # Show the trace plot pymc3.traceplot(trace) plt.show()
d7269f0c1aaffa5129c3f5e18c4a3bba51d65620
drforse/snake
/game/types/food.py
908
3.84375
4
import turtle import random class Food(turtle.Turtle): def __init__(self, game, x: int = None, y: int = None, visible: bool = True, **kwargs): """ Food for the Snake :param x: x-coord where to appear, if None, it's chosen randomly :param y: y-coord where to appear, if None, it's chosen randomly :param visible: if the Snake should be visible when appears """ super().__init__(visible=False, **kwargs) self.penup() if not x: x = random.randint(-300, 300) if not y: y = random.randint(-300, 300) self.goto(x, y) self.shape(random.choice(('circle', 'square'))) self.game = game if visible: self.showturtle() def delete(self): self.clear() self.reset() del self.game.foods[self.game.foods.index(self)] self.hideturtle()
02592aa520f5d50012b4e643a77ac89fb59f5109
daniel-reich/turbo-robot
/iuenzEsAejQ4ZPqzJ_19.py
656
4.0625
4
""" This is a **reverse coding challenge**. Normally you're given explicit directions with how to create a function. Here, you must generate your own function to satisfy the relationship between the inputs and outputs. Your task is to create a function that, when fed the inputs below, produce the sample outputs shown. ### Examples 3 ➞ 21 9 ➞ 2221 17 ➞ 22221 24 ➞ 22228 ### Notes If you get stuck, check the **Comments** for help. """ def mystery_func(num): temp = num resultS = '' while (temp >= 2): temp = temp/2 resultS += '2' resultS += str(num-2**len(resultS)) return int(resultS)
96cf21691b4f95085bf70e04bee5a350fce189c5
pennmem/ptsa_plot
/ptsa_plot/coords.py
1,409
4.09375
4
"""Coordinate system conversion utilities.""" import numpy as np def deg2rad(degrees): """Convert degrees to radians.""" return degrees / 180. * np.pi def rad2deg(radians): """Convert radians to degrees.""" return radians / np.pi * 180. def pol2cart(theta, radius, z=None, radians=True): """Converts corresponding angles (theta), radii, and (optional) height (z) from polar (or, when height is given, cylindrical) coordinates to Cartesian coordinates x, y, and z. Theta is assumed to be in radians, but will be converted from degrees if radians==False. """ if radians: x = radius * np.cos(theta) y = radius * np.sin(theta) else: x = radius * np.cos(deg2rad(theta)) y = radius * np.sin(deg2rad(theta)) if z is not None: return x, y, z else: return x, y def cart2pol(x, y, z=None, radians=True): """Converts corresponding Cartesian coordinates x, y, and (optional) z to polar (or, when z is given, cylindrical) coordinates angle (theta), radius, and z. By default theta is returned in radians, but will be converted to degrees if radians==False. """ if radians: theta = np.arctan2(y, x) else: theta = rad2deg(np.arctan2(y, x)) radius = np.hypot(x, y) if z is not None: return theta, radius, z else: return theta, radius
b07f1458f07d286d8bdb807d0af870c832367dfa
venkatsvpr/Problems_Solved
/LC_Capacity_to_ship_packages_within_d_days.py
2,143
4.375
4
""" 1011. Capacity To Ship Packages Within D Days A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 Constraints: 1 <= days <= weights.length <= 5 * 104 1 <= weights[i] <= 500 """ class Solution(object): def shipWithinDays(self, weights, days): """ :type weights: List[int] :type days: int :rtype: int """ def feasible(shipweight): expectedDays = 1 rSum = 0 for weight in weights: rSum += weight if (rSum > shipweight): expectedDays += 1 rSum = weight if expectedDays > days: return False return True left = max(weights) right = sum(weights) while (left < right): mid = left + (right -left)//2 if feasible(mid): right = mid else: left = mid + 1 return left
4c86a9dc55134b7daae36bedcefc72dbfcfb3c1b
AlisonMcGuinness/UCDExercises
/mod5_3indexes.py
7,833
4.3125
4
import pandas as pd file = "C:\\Users\\Admin\\Documents\\UCD_Data\\temp.csv" temperatures = pd.read_csv(file, sep=",", parse_dates=['date']) temperatures['avg_temp_c'] = temperatures['temperature'] # Look at temperatures print(temperatures.info()) # Index temperatures by city temperatures_ind = temperatures.set_index('city') # Look at temperatures_ind ''' Setting an index allows more concise code for subsetting for rows of a categorical variable via .loc[]. ''' print(temperatures_ind) # Reset the index, keeping its contents print(temperatures_ind.reset_index()) # Reset the index, dropping its contents print(temperatures_ind.reset_index(drop=True)) # Make a list of cities to subset on cities = ["Moscow", "Saint Petersburg"] # Subset temperatures using square brackets print(temperatures[temperatures['city'].isin( cities)]) # Subset temperatures_ind using .loc[] # pass list of cities OR use double [[]] and pass direct print(temperatures_ind.loc[cities].head()) print('') print('multiple indexes') ''' Setting multi-level indexes Indexes can also be made out of multiple columns, forming a multi-level index (sometimes called a hierarchical index). There is a trade-off to using these. The benefit is that multi-level indexes make it more natural to reason about nested categorical variables. For example, in a clinical trial, you might have control and treatment groups. Then each test subject belongs to one or another group, and we can say that a test subject is nested inside the treatment group. Similarly, in the temperature dataset, the city is located in the country, so we can say a city is nested inside the country. The main downside is that the code for manipulating indexes is different from the code for manipulating columns, so you have to learn two syntaxes and keep track of how your data is represented. ''' # Index temperatures by country & city temperatures_ind = temperatures.set_index(["country", "city"]) # List of tuples: Brazil, Rio De Janeiro & Pakistan, Lahore rows_to_keep = [("Brazil", "Rio De Janeiro"), ("Pakistan", "Lahore")] rows_to_keep = [("Russia", "Moscow")] # Subset for rows to keep THIS CRAShES IF THE values in rows to keep do not exist in the index. print(temperatures_ind.loc[rows_to_keep].head()) print('') print('sorting by index examples') ''' Sorting index values is similar to sorting values in columns, except that you call .sort_index() instead of .sort_values(). ''' # Sort temperatures_ind by index values print(temperatures_ind.sort_index()) # Sort temperatures_ind by index values at the city level print(temperatures_ind.sort_index(level = ["city"])) # Sort temperatures_ind by country then descending "city print(temperatures_ind.sort_index(level = ["country", "city"], ascending=[True, False])) print('') print('SLICING INDEX ROWS') ''' Slicing index values Slicing lets you select consecutive elements of an object using first:last syntax. DataFrames can be sliced by index values or by row/column number; we'll start with the first case. This involves slicing inside the .loc[] method. Compared to slicing lists, there are a few things to remember. You can only slice an index if the index is sorted (using .sort_index()). To slice at the outer level, first and last can be strings. To slice at inner levels, first and last should be tuples. If you pass a single slice to .loc[], it will slice the rows. ''' # Sort the index of temperatures_ind temperatures_srt = temperatures_ind.sort_index() # Subset rows from Pakistan to Russia print(temperatures_srt.loc["Pakistan":"Russia"]) # Try to subset rows from Lahore to Moscow #print(temperatures_srt.loc["Lahore":"Moscow"]) # Subset rows from Pakistan, Lahore to Russia, Moscow print(temperatures_srt.loc[("Pakistan", "Lahore"):("Russia", "Moscow")]) print('') print('Slicking in both directions') ''' Slicing in both directions You've seen slicing DataFrames by rows and by columns, but since DataFrames are two-dimensional objects, it is often natural to slice both dimensions at once. That is, by passing two arguments to .loc[], you can subset by rows and columns in one go. ''' # Subset rows from India, Hyderabad to Iraq, Baghdad print(temperatures_srt.loc[("India", "Hyderabad"):("Iraq","Baghdad")]) # Subset columns from date to avg_temp_c print(temperatures_srt.loc[:, "date":"avg_temp_c"]) # Subset in both directions at once print(temperatures_srt.loc[("India", "Hyderabad"):("Iraq","Baghdad"), "date":"avg_temp_c"]) print('') print('Slicing TIME SERIES') ''' Slicing is particularly useful for time series since it's a common thing to want to filter for data within a date range. Add the date column to the index, then use .loc[] to perform the subsetting. The important thing to remember is to keep your dates in ISO 8601 format, that is, yyyy-mm-dd. Recall from Chapter 1 that you can combine multiple Boolean conditions using logical operators (such as &). To do so in one line of code, you'll need to add parentheses () around each condition. Using .loc[] in conjunction with a date index provides an easy way to subset for rows before or after some date. ''' print('without an index! ') # Use Boolean conditions to subset temperatures for rows in 2010 and 2011 temperatures_bool = temperatures[(temperatures["date"] >= "2010-01-01") & (temperatures["date"] <= "2011-12-31")] print(temperatures_bool) print('with an index!!') # Set date as an index and sort the index temperatures_ind = temperatures.set_index("date").sort_index() # Use .loc[] to subset temperatures_ind for rows in 2010 and 2011 print(temperatures_ind.loc["2010":"2011"]) # Use .loc[] to subset temperatures_ind for rows from Aug 2010 to Feb 2011 print(temperatures_ind.loc["2010-08":"2011-02"]) print('') print('USING ILOC') # Get 23rd row, 2nd column (index 22, 1) print(temperatures.iloc[22:23, 1:2]) # Use slicing to get the first 5 rows print(temperatures.iloc[:5]) # Use slicing to get columns 3 to 4 print(temperatures.iloc[:,2:5]) # Use slicing in both directions at once print(temperatures.iloc[:5,2:5]) print('') print('pivot by city and year') # Add a year column to temperatures temperatures["year"] = temperatures["date"].dt.year # Pivot avg_temp_c by country and city vs year temp_by_country_city_vs_year = temperatures.pivot_table(values="avg_temp_c", index=["country","city"], columns="year") # See the result print(temp_by_country_city_vs_year) print('') print('can slice the pivot table same as usual') # Subset for Egypt to India print(temp_by_country_city_vs_year.loc["Egypt":"India"]) # Subset for Egypt, Cairo to India, Delhi print(temp_by_country_city_vs_year.loc[("Egypt","Cairo"):("India", "Delhi")]) # Subset in both directions at once print(temp_by_country_city_vs_year.loc[("Egypt","Cairo"): ("India", "Delhi"), "2005":"2010"]) print('') print('calculating on a pivot table') ''' Pivot tables are filled with summary statistics, but they are only a first step to finding something insightful. Often you'll need to perform further calculations on them. A common thing to do is to find the rows or columns where the highest or lowest value occurs. Recall from Chapter 1 that you can easily subset a Series or DataFrame to find rows of interest using a logical condition inside of square brackets. For example: series[series > value]. ''' # Get the worldwide mean temp by year mean_temp_by_year = temp_by_country_city_vs_year.mean() print(mean_temp_by_year) # Filter for the year that had the highest mean temp print(mean_temp_by_year[mean_temp_by_year == mean_temp_by_year.max()]) # Get the mean temp by city mean_temp_by_city = temp_by_country_city_vs_year.mean(axis = "columns") print(mean_temp_by_city) # Filter for the city that had the lowest mean temp print(mean_temp_by_city[mean_temp_by_city == mean_temp_by_city.min()])
337e4ff8767b921cfbc8e96d45c40aadd76dde1e
igortereshchenko/amis_python
/km73/Savchuk_Ivan/3/task10.py
493
3.734375
4
x = int(input('please enter init coordinate x:',)) y = int(input('please enter init coordinate y:',)) x1 = int(input('please enter coordinate x1:',)) y1 = int(input('please enter coordinate y1:',)) d1 = abs(x/y) d2 = abs(x1/y1) d3 = abs(y+y1) d4 = abs(x+x1) if (x == x1) & (1 <= y <= 8) & (1 <= y1 <= 8): print('YES') elif (y == y1) & (1 <= x <= 8) & (1 <= x1 <= 8): print('YES') if d3 == d4 : print('YES') elif d1 != d2 : print('NO') else: print('NO')
ea8dfb12fe58963c09f3c66d8cb691e12522e2ca
kiettran95/Wallbreakers_Summer2019
/week4/python/ReverseLinkedList_206.py
987
4.0625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: # 1st approach: recursion # root = [head] # def recurse_reverse(node: ListNode) -> ListNode: # if not node or not node.next: # root[0] = node # return node # prev_node = recurse_reverse(node.next) # prev_node.next = node # node.next = None # return node # recurse_reverse(head) # return root[0] # 2nd approach: iteration if not head or not head.next: return head prev_node = None cur_node = head while cur_node: tmp = cur_node.next cur_node.next = prev_node prev_node, cur_node = cur_node, tmp return prev_node
7f94413223fdca646f2481557083a675d8438b1c
denisAronson/morning_star
/utilites/gui_test.py
887
4.03125
4
#импортируем модуль для создания GUI from tkinter import * #создаем окно, задаем его размер и заголовок window = Tk() window.geometry('800x500') window.title("Мое перове GUI на питоне") #функционал кнопки def clicked(): lbl.configure(text='Зачем нажал') #добавляем текст, задем локацию lbl = Label(window, text="Hello", font=("Verdana", 30)) lbl.grid(column=0, row=0) #пользовательский ввод txt = Entry(window,width=10) txt.grid(column=1, row=0) #добавляем кнопку (Button виджет), задаем локацию, цвет фона и переднего плана(текст) btn = Button(window, text="Кнопка", bg='black', fg='silver', command=clicked) btn.grid(column=2, row=0) window.mainloop()
c4c110e70287e360a6173f4d2842d81afe60c6df
v-franco/Facebook-ABCS
/strings & arrays/arrays_DS.py
451
3.90625
4
import math import os import random import re import sys # # Complete the 'reverseArray' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY a as parameter. # def reverseArray(a): # Write your code here return a[::-1] if __name__ == '__main__': arr_count = int(input().strip()) arr = list(map(int, input().rstrip().split())) res = reverseArray(arr) print(res)
378d51fa1e9d5afdfe7c55c33d3887d6858ea344
nicoprocessor/Digital-Art-Collection
/Processing sketches/Line Stitching/cardioid_mesh/cardioid_mesh.pyde
1,023
3.703125
4
import math lines = 300 line_skip = 1 radius_x, radius_y = 900, 900 def frange(start, stop, step): while start < stop: yield start start += step def setup(): size(1200, 1200) background(51) ellipseMode(RADIUS) stroke(255) noFill() strokeWeight(1) # center the coordinate system translate(width/2, height/2) rotate(math.pi/3) scale(1, -1) ellipse(0, 0, radius_x, radius_y) p1 = [0,0] p2 = [0,0] counter = 0 for theta in frange(0, 2*math.pi, 2*math.pi/lines): # calculate intermediate points p1[0] = radius_x * math.cos(theta) p1[1] = radius_y * math.sin(theta) counter += 1 theta_skip = theta + (2*math.pi/lines)*line_skip*counter p2[0] = radius_x * math.cos(theta_skip) p2[1] = radius_y * math.sin(theta_skip) # draw lines line(p1[0], p1[1], p2[0], p2[1]) save("cardioid_standard" + str(random(1000))) print("Done")
54917c736c892fa54304c8e32be483a174e8209b
willgood1986/myweb
/pydir/callable.py
645
4.21875
4
# -*- coding: utf-8 -*- class TestCall(object): ''' Use callable to test if a function is callable override __call__ to make a class callable ''' def __init__(self, name): self._name = name def __call__(self): print('My name is {name}'.format(name = self._name)) def __str__(self): return self.__doc__ if __name__ == '__main__': tc = TestCall('Rainy') print('We can call the instance directly like tc():') tc() print('We can use callable to check if the object is callabe like callable(max)') print(callable(max)) print(callable(tc)) print(None) print(tc)
b98693c35d17c4d4f0f4f6be9323e824e25d1258
evelyn-pardo/segundo_parcial
/menu.py
1,062
3.859375
4
class Menu: def __init__(self,titulo,opciones=[]): self.titulo=titulo self.opciones=opciones def menu(self): print(self.titulo) for opcion in self.opciones: print(opcion) opcion=input("Elija opcion[1...{}]:".format(len(self.opciones))) menu1=Menu("Menu Principal",["1) Calculadora","2)Numeros","3)Lista","4)Calculos","5)Salir"]) menu1.menu() if opcion == "1": print("Calculadora") elif opc == "2": print("Operaciones con Numeros") print("1) perfecto") print("2)Primo ") print("3)Salir ") opc2=input("Elija opcion[1...3]: ") if opc2 == "1": print("Nuevos Perfectos") num= int(input("Ingrese Numero:")) #llamar el metodo percfecto print("El numero es pefecto") elif opc == "3": print("Listas") elif opc == "4": print("Cadena") elif opc == "5": print("Salir") else: print("Opcion no valida")
323c30c40df31402b5bd8d72379a78d653e5c3a2
mikeckennedy/DevWeek2015
/python_demos/shopping.py
573
3.8125
4
class CartItem: def __init__(self, name, price): self.name = name self.price = price class Cart: def __init__(self): self.items = [] def add(self, item): self.items.append(item) def __iter__(self): return self.items.__iter__() def main(): cart = Cart() cart.add(CartItem('Bread', 2.99)) cart.add(CartItem('Milk', 4.99)) cart.add(CartItem('Tesla', 120000)) total = 0 for i in cart: total += i.price print("The total is {0:,} today.".format(total)) main()
e0f3f71e743669ba318ac8101bf3ce5872dd3783
h-mayorquin/text_to_image
/test_fonts.py
2,216
3.71875
4
""" This script produces the whole alphabet (and all the other symbols for a given font) for a given corpus. This serves as test for all the font parameters and the font itself. """ from PIL import ImageDraw from PIL import Image, ImageFont import numpy as np import matplotlib.pyplot as plt from random import sample # from string import ascii_lowercase # Now we import the particular corpus that we are intested in from nltk.book import text7 as text letters = ' '.join(text) symbols = set(letters) # Get a dictionary of difficult symbols difficult_symbols = {' ': 'space', '.':'point', '/':'diagonal'} store_directory = './alphabet/' # Define the font font_directory = './fonts/' font_name = 'Cocomat Ultralight-trial.ttf' font_name = 'secrcode.ttf' font_name = 'Chunk.ttf' font_name = 'hellovetica.ttf' font_name = 'arcade.ttf' font_source = font_directory + font_name # Now we chose how the image will be layed out pixels = 10 # Number of pixels coord_x = 2 # coord_y = 0 size = 15 font = ImageFont.truetype(font=font_source, size=size) # Go through all the symbols and print them as images for symbol in symbols: # 256 is the color and 1 is only for one pixel img = Image.new('1', (pixels, pixels), 256) d = ImageDraw.Draw(img) d.text((coord_x, coord_y), symbol, font=font) if symbol in difficult_symbols: symbol = difficult_symbols[symbol] name = store_directory + symbol + '.png' print('saving name', name) img.save(name) # We also have a function to transform to numpy arrays def symbol_to_array(symbol, font, pixels, coord_x, coord_y, size): """ Return a numpy array for a given symbol with a given font """ # 256 is the color and 1 is only for one pixel img = Image.new('1', (pixels, pixels), 256) d = ImageDraw.Draw(img) d.text((coord_x, coord_y), symbol, font=font) img.save(name) numpy_array = np.array(img.getdata()).reshape(img.size[0], img.size[1]) return numpy_array # Show random image shows_random_image = True if shows_random_image: symbol = sample(symbols, 1)[0] # symbol = '\\' pix = symbol_to_array(symbol, font, pixels, coord_x, coord_y, size) plt.matshow(pix) plt.show()
10fd0046689ab52ed47b6e6a3e171266c1962f76
DoAnhTuan98/doanhtuan-fundamental-c4e
/session3/list_intro.py
199
3.546875
4
# items = [] # empty list (rong) # print(items) # print(type(items)) items = ["bun dau","bun bo","bun rieu"] print(items[1]) items[1] = "bun bo nam bo" # thay doi bien print(items[1]) print(items)
1c6df9b7bd12317b23acf107c05cc505df78b1e9
vijaykumarrpai/mca-code
/3rd Sem/Python/Programs/day2-functions/displayNo.py
180
4.15625
4
# # WAP to read a number and display its value inside the function def value(): num = int(input("Enter the number : ")) return num print("The entered value is :", value())
229b042ca75f8c26a446adb6a4fa2dd74903005b
RushToNeverLand/DataMining-MachineLearning-LanMan
/L02-PythonBasic/code/rawinput.py
403
3.625
4
#!/opt/anaconda2/bin/python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('GBK') # 在当前笔记本电脑上 # sys.setdefaultencoding('utf-8') age = int(raw_input(u"请输入你的年龄: ")) if age >= 18: print u"你是个adult." elif age >= 12: # 可以有多个elif语句 print "You are a teenager." else: print u"你还是个小朋友呦."
4477299218318057350c7c317887103137ebf2d8
RoshanADK/Tensorflow-Learn-and-Code
/TFImageTranspose.py
976
3.75
4
# Lets make an use of matplotlib to Load Image using imread function import matplotlib.image as mp_image import matplotlib.pyplot as plt import tensorflow as tf # Lets read using imread() function filename = "TensorImage.jpg" # Take one image from the same directory or give relative path to an image input_image = mp_image.imread(filename) # Lets Perform Some Geometric Transformation here # We'll start by Transposing the image # Assign image to Variable x for easy reference x = tf.Variable(input_image, name="x") # Now as usual lets initialize the model as model = tf.global_variables_initializer() # Transpose Function Invocation x = tf.transpose(x, perm=[1,0,2]) # Lets now create Session with tf.Session() as sess: sess.run(model) result = sess.run(x) # plt.imshow(input_image) # This is the original image plt.imshow(result) # If there are two imshow function , last one only gets executed so only result image is displayed plt.show()
ecaed1679031dfef618084865187106973e68568
Aka-Ikenga/Daily-Coding-Problems
/merge_colors.py
1,324
4.03125
4
"""This problem was asked by Facebook. On a mysterious island there are creatures known as Quxes which come in three colors: red, green, and blue. One power of the Qux is that if two of them are standing next to each other, they can transform into a single creature of the third color. Given N Quxes standing in a line, determine the smallest number of them remaining after any possible sequence of such transformations. For example, given the input ['R', 'G', 'B', 'G', 'B'], it is possible to end up with a single Qux through the following steps: Arrangement | Change ---------------------------------------- ['R', 'G', 'B', 'G', 'B'] | (R, G) -> B ['B', 'B', 'G', 'B'] | (B, G) -> R ['B', 'R', 'B'] | (R, B) -> G ['B', 'G'] | (B, G) -> R ['R'] |""" def merge_colors(c): return list(set(c)^{'R', 'G', 'B'})[0] def return_pair(a): if len(set(a)) == 1: return a[:1], 0 for i in range(len(a)-1): if a[i] != a[i+1]: return a[i:i+2], i # return the new pair to merge and there position def cc(a): b, i = return_pair(a) if len(b) == 1: return b[0] d = merge_colors(b) a.pop(i) a.pop(i) a.insert(0, d) print(d, a) return cc(a) a = ['R', 'G', 'B', 'G', 'B'] cc(a)
62e3fd42d51658190b0bc959184e1ea6a04a6f4b
danevputra/Python-ai-code
/hillclimbing.py
1,576
3.578125
4
# You can extend this code to implement: # Stochastic Hill climbing # Random-restart Hill-climbing import math fabs=math.fabs sin=math.sin cos=math.cos exp=math.exp pi=math.pi #scalar multiple for grad-ascent scalar=0.005 # I am doing gradient ascent here, since I want to maximize the function def grad_ascent(x): #for func1 #delta_x = -2.0*x #for func2 #delta_x = -2.0*x*exp(-x*x) #for func3 delta_x = (exp(-x*x)*(6.0*sin(3*pi*x)*cos(3*pi*x)) - 2.0*x*sin(3.0*pi*x)*exp(-x*x)) #for func4 #scalar=0.008 #delta_x = -exp(-x) + exp(x) return x + (scalar*delta_x) # simple objective functions with # one global maxima and no local minima def func1(x): return -x*x def func2(x): return exp(-x*x) #local/global maxima def func3(x): return exp(-x*x)*(sin(3.0*pi*x)**2) #with a plateau in between def func4(x): return (1.0 + exp(-x)) + (1.0 + exp(x)) #Definition of the simple hill climbing search def hill_climb(objfunc,x,next_move): current = x while True: current_val=objfunc(current) next = next_move(current) if objfunc(next) > current_val: current = next print current,current_val else: break; if __name__=='__main__': x_init = 0.95 # Hill climbing stops at the nearest hill it finds. # call the hill_climb function with the function # you want to optimize, the initial point and the 'move' # method, that you want to use for moving to a nearby solution hill_climb(func3,x_init,grad_ascent)
ee5c78045357d5d035e9561d2ebc0b9de254e0af
TangJiahui/cs107_system_devlopment
/pair_programming/PP9/fibo.py
1,055
3.734375
4
#group members: Gabin Ryu, Jiahui Tang, Qinyi Chen import reprlib class Fibonacci: def __init__(self, n): self.n = n def __iter__(self): return FibonacciIterator(self.n) def __repr__(self): return 'Fibonacci(%s)' % reprlib.repr(self.n) class FibonacciIterator: def __init__(self,n): self.index = 0 self.prev0 = 0 self.prev1 = 1 self.curr = 1 self.n = n # has __next__ and __iter__ def __next__(self): if self.index < self.n: self.curr = self.prev0 + self.prev1 self.index += 1 self.prev0 = self.prev1 self.prev1 = self.curr return self.curr else: raise StopIteration() def __iter__(self): return self #demo fib = Fibonacci(10) # Create a Fibonacci iterator called fib that contains 10 terms list(iter(fib)) # Iterate over the iterator and create a list. fib2 = Fibonacci(13) # Create a Fibonacci iterator called fib that contains 13 terms list(iter(fib2))
2665d438cbd264c04fb32ea7fc8100cf520abda9
falaybeg/BigData-MachineLearning-Notes
/Statistics-Notes/07-Regression/01-Linear Regression/01-Linear Regression.py
1,847
4.34375
4
''' Linear Regression ''' import pandas as pd import matplotlib.pyplot as plt import numpy as np # Load dataset df = pd.read_csv("linear_regression_dataset.csv") # Dataset is visualized by using Scatter Plot plt.scatter(df["Experience"], df["Salary"]) plt.title("Scatter Plot graphics for Experience and Salary", fontsize=14) plt.xlabel("Experience (year)", fontsize=14) plt.ylabel("Salary", fontsize= 14) #Scatter Plot graph shows us that salary increases according to experience year plt.show() # Linear Regression is defined from sklearn library from sklearn.linear_model import LinearRegression # Created a instance from LinearRegression() class for prediction linear_regression = LinearRegression() # X and Y values is transformed to numpy array and reshaped for model xset = df["Experience"].values.reshape(-1,1) yset = df["Salary"].values.reshape(-1,1) # Fit process is carried out linear_regression.fit(xset,yset) # Manuel Prediction method ______________________ # y = b0 + b1*x b0 = linear_regression.predict(np.array([[0]])) b1 = linear_regression.coef_ # We found constant and coefficieny/slope # We are going to predict salary in 11th year experience = 11 y = b0 + b1*experience print("b0 : ",b0,"\nb1 : ",b1) print("Salary (manual method) : ",y.item(0)) #_________________________________________________ # Automatic Prediction method ----------------------- salary = linear_regression.predict(np.array([[11]])) print("Salary (function method): ",salary.item(0)) experienceYear = np.array([0,1,2,3,5,7,10,11,15,18,20]).reshape(-1,1) predictedSalary = linear_regression.predict(experienceYear) plt.scatter(xset,yset) plt.plot(experienceYear, predictedSalary, color="red" ) plt.xlabel("Experience (Year)", fontsize=14) plt.ylabel("Salary",fontsize=14) plt.show() #_________________________________________________
1ed29f3c223416ecff54ccd119d79db8d7473a75
aalmsaodi/Algorithms
/after-session-3.py
2,444
3.546875
4
#BST: Implement Power Function ********************************* class Solution: # @param x : integer # @param n : integer # @param d : integer # @return an integer def pow(self, x, n, d): if n == 0: return 1 % d ans = 1 base = x while n > 0: if n % 2 == 1: ans = ans*base % d n -= 1 else: base = base*base % d n /= 2 return ans #BST: Matrix Search ********************************* class Solution: def binarySearch(self, flatA, B): if len(flatA) == 1: if flatA[0] == B: return 1 else: return 0 mid = len(flatA)/2 if B >= flatA[mid]: return self.binarySearch(flatA[mid:], B) else: return self.binarySearch(flatA[:mid], B) # @param A : list of list of integers # @param B : integer # @return an integer def searchMatrix(self, A, B): if A == None or len(A) == 0: return 1 if len(A) == 1: return self.binarySearch(A[0], B) for row in A: if B >= row[0] and B <= row[len(row)-1]: return self.binarySearch(row, B) return 0 #Trees: Identical Binary Trees ************************************ class Solution: # @param A : root node of tree # @param B : root node of tree # @return an integer def isSameTree(self, A, B): if A == None or B == None: if A == B: return True else: return False if A.val == B.val: return self.isSameTree(A.left, B.left) and self.isSameTree(A.right, B.right) else: return False #Trees: Balanced Binary Tree ************************************ class Solution: def depth (self, tree): if (tree == None): return 0 return max(self.depth(tree.left), self.depth(tree.right)) + 1 # @param A : root node of tree # @return an integer def isBalanced(self, A): if (A == None): return True l = self.depth(A.left) r = self.depth(A.right) return abs(l-r) <= 1 and self.isBalanced(A.left) and self.isBalanced(A.right)
96a5b6e822ebe3d46bebbce0e3559b4697643298
dtekluva/class9_code
/Python-class-codes-master/beesolah.py
411
4
4
file = open('docword.txt','r') text = file.read() text = (text.split('\n')) #convert each newline into a list (split by newline \n) for line in text: splitted_line = line.split(' ') #convert each of the splited valeus into list of three numbers (split by spaces) single_value = splitted_line[1] single_value #<===== i believe this is what you need the middle value print('\n',single_value)
bd7acbecff8cb21655a61100fee24e3d71307c87
chhavimittal123/Hangman-Game
/main.py
1,030
3.953125
4
from replit import clear import random from hangman_words import word_list chosen_word = random.choice(word_list) word_length = len(chosen_word) end_of_game = False lives = 11 from hangman_art import logo, stages print(logo) display = [] for _ in range(word_length): display += "_" while not end_of_game: guess = input("Guess a letter: ").lower() clear() if guess in display: print(f"You've already chosen {guess}, see.") for position in range(word_length): letter = chosen_word[position] if letter == guess: display[position] = letter if guess not in chosen_word: print(f"You've guessed {guess}, that's not in the word. You lose a life.") lives -= 1 if lives == 0: clear() end_of_game = True print(f"You lose, The word was '{chosen_word}' \n Try again.") print(f"{' '.join(display)}") if "_" not in display: end_of_game = True print("Congratulations, You win.") print(stages[lives])
d56699e55bc4f29e4383b426d2fe2458e1c1ba29
Pavel-Kuchmenko/FirstRepository
/HW2.1/HW2.1.py
6,353
3.84375
4
print("\"Homework #3\"\n05.06.2021\ ") print("-------------------------- START -----------------------------") integer1 = 300 integer2 = 55 float1 = 311.24 float2 = 575.59 result = 0 #-------------------------------------------------- ** --------------------------------------------------------- print("---------------------------- ** ------------------------------") print("_______Integers_______") result = 3**4 print(3, 4, sep="\u002A\u002A", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Floats_______") result = 3.4**4. print(3.4, 4., sep="\u002A\u002A", end="="+str(result)+"\n") print("Functions: bin(), oct() and hex() works only with integers. So we will use int() function to convert float to integer.") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Integer X Float_______") result = 3**4.3 print(3, 4.3, sep="\u002A\u002A", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") #-------------------------------------------------- / --------------------------------------------------------- print("---------------------------- / -------------------------------") print("_______Integers_______") result = integer1/integer2 print(integer1, integer2, sep="\u002F", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Floats_______") result = float1/float2 print(float1, float2, sep="\u002F", end="="+str(result)+"\n") print("Functions: bin(), oct() and hex() works only with integers. So we will use int() function to convert float to integer.") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Integer X Float_______") result = integer1/float2 print(integer1, float2, sep="\u002F", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") #-------------------------------------------------- * --------------------------------------------------------- print("---------------------------- * -------------------------------") print("_______Integers_______") result = integer1*integer2 print(integer1, integer2, sep="\u002A", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Floats_______") result = float1*float2 print(float1, float2, sep="\u002A", end="="+str(result)+"\n") print("Functions: bin(), oct() and hex() works only with integers. So we will use int() function to convert float to integer.") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Integer X Float_______") result = integer1*float2 print(integer1, float2, sep="\u002A", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") #-------------------------------------------------- // --------------------------------------------------------- print("---------------------------- // ------------------------------") print("_______Integers_______") result = integer1//integer2 print(integer1, integer2, sep="\u002F\u002F", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Floats_______") result = float1//float2 print(float1, float2, sep="\u002F\u002F", end="="+str(result)+"\n") print("Functions: bin(), oct() and hex() works only with integers. So we will use int() function to convert float to integer.") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Integer X Float_______") result = integer1//float2 print(integer1, float2, sep="\u002F\u002F", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") #-------------------------------------------------- % --------------------------------------------------------- print("---------------------------- % -------------------------------") print("_______Integers_______") result = integer1%integer2 print(integer1, integer2, sep="\u0025", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Floats_______") result = float1%float2 print(float1, float2, sep="\u0025", end="="+str(result)+"\n") print("Functions: bin(), oct() and hex() works only with integers. So we will use int() function to convert float to integer.") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("_______Integer X Float_______") result = integer1%float2 print(integer1, float2, sep="\u0025", end="="+str(result)+"\n") result = int(result) print(bin(result).replace("0b", ""), end="->bin\n") print(oct(result).replace("0o", ""), end="->oct\n") print(hex(result).replace("0x", ""), end="->hex\n\n") print("--------------------------- END ------------------------------")
c77cbde04a5077ca91be7f0569c64630393e4855
Unkovskyi/PyBase08
/hw_3_1.py
1,659
3.9375
4
# Task_3_1 import string from string import whitespace, punctuation print('whitespace = {}'.format(repr(whitespace))) print('punctuation = {}'.format(repr(punctuation))) print('---------------------------------------------') def dict_(inp): # функция которая считает слова в веденной строке inp = inp.lower().split() dict_ = dict() for i in inp: if i in dict_: dict_[i] = dict_[i] + 1 else: dict_[i] = 1 return dict_ def del_punctuation(inp_text): # функция удаления знаков пунктуации for i in string.punctuation: if i != "'": inp_text = inp_text.replace(i, "") else: continue return inp_text def leng_max(inp_list): # функция для подсчета максимальной длинны слова из списка inp_list = inp_list.lower().split() leng = [] for i in inp_list: leng_i = len(i) leng.append(leng_i) max_len = max(leng) return max_len def print_table(inp_dict): res = ' ' outp = dict_(inp_dict) out_keys = outp.keys() for i in out_keys: res = '|' + i + (' ' * (leng_max(inp_dict) - len(i))) + '|' + str(outp[i]) + '|' print(res) start_inp = False inp_ = '' while start_inp == False: inp = input('Input text: ') if inp not in string.whitespace: inp_ = inp_ + ' ' + inp.replace('\n', '') else: inp_ = del_punctuation(inp_) inp_ = print_table(inp_) start_inp = True
7aade650f272934575a5351a6817d86caa197b6a
Antpoizen/Python-Programs
/Base conversions and decryption.py
6,766
4.40625
4
# ▄▄▄ ███▄ █ ▄▄▄█████▓ ██▓███ ▒█████ ██▓ ██████ ▓█████ ███▄ █ #▒████▄ ██ ▀█ █ ▓ ██▒ ▓▒▓██░ ██▒▒██▒ ██▒▓██▒▒██ ▒ ▓█ ▀ ██ ▀█ █ #▒██ ▀█▄ ▓██ ▀█ ██▒▒ ▓██░ ▒░▓██░ ██▓▒▒██░ ██▒▒██▒░ ▓██▄ ▒███ ▓██ ▀█ ██▒ #░██▄▄▄▄██ ▓██▒ ▐▌██▒░ ▓██▓ ░ ▒██▄█▓▒ ▒▒██ ██░░██░ ▒ ██▒▒▓█ ▄ ▓██▒ ▐▌██▒ # ▓█ ▓██▒▒██░ ▓██░ ▒██▒ ░ ▒██▒ ░ ░░ ████▓▒░░██░▒██████▒▒░▒████▒▒██░ ▓██░ # ▒▒ ▓▒█░░ ▒░ ▒ ▒ ▒ ░░ ▒▓▒░ ░ ░░ ▒░▒░▒░ ░▓ ▒ ▒▓▒ ▒ ░░░ ▒░ ░░ ▒░ ▒ ▒ # ▒ ▒▒ ░░ ░░ ░ ▒░ ░ ░▒ ░ ░ ▒ ▒░ ▒ ░░ ░▒ ░ ░ ░ ░ ░░ ░░ ░ ▒░ # ░ ▒ ░ ░ ░ ░ ░░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ # ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ # print (" Welcome to Base conversions!") while True: print ("") print ("-------------------------------------------") print ("What would you like to do?") print ("-Decimal to Binary:-----1") print ("-Decimal to Octal:------2") print ("-Decimal to Any Base:---3") print ("-Any Base to Decimal:---4") print ("-Encypt Word:-----------5") print ("-Decrypt Word:----------6") print ("Remember '!' will always kill the program.") print ("------------------------------------------- \n") choice = input ("") if choice == "!": break if choice == "1": # blank variable number="" #checks if input is a number while(not(number.isnumeric())): number = input("What is the decimal you want to convert to binary? \n") # takes the input and converts from string to integer tempnumb = int(number) #setting an empty variable so we can print a result bin_output = "" # while the integer is greater than 0 run while(tempnumb > 0): #does the math to conver the number into a binary number bin_output = str(tempnumb % 2) + bin_output tempnumb = int(tempnumb / 2) #prints the final result print (bin_output) elif choice == "2": number="" while(not(number.isnumeric())): number = input("What is the decimal you want to convert to octal? \n") tempnumb = int(number) bin_output = "" while(tempnumb > 0): bin_output = str(tempnumb % 8) + bin_output tempnumb = int(tempnumb / 8) print (bin_output) elif choice == "3": def reVal(num): if (num >= 0 and num <= 9): return chr(num + ord('0')); else: return chr(num - 10 + ord('A')); def strev(str): len = len(str); for i in range(int(len / 2)): temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; def fromDeci(res, base, inputNum): index = 0; while (inputNum > 0): res+= reVal(inputNum % base); inputNum = int(inputNum / base); res = res[::-1]; return res; inputNum = input("Select a decimal to be converted \n"); base = input("Select a base for your decimal to be converted by. \n"); inputNum = int(inputNum) base = int(base) res = ""; print("Equivalent of", inputNum, "in base", base, "is", fromDeci(res, base, inputNum)); # This code is contributed by mits https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/ # with input modified to work for user input elif choice == "4": def val(c): if c >= '0' and c <= '9': return ord(c) - ord('0') else: return ord(c) - ord('A') + 10; def toDeci(str,base): llen = len(str) power = 1 num = 0 for i in range(llen - 1, -1, -1): if val(str[i]) >= base: print('Invalid Number') return -1 num += val(str[i]) * power power = power * base return num strr = input("Please input a base number to be converted. \n") base = int(input("What base is that? \n")) print('Decimal equivalent of', strr, 'in base', base, 'is', toDeci(strr, base)) # This code is contributed by sahil shelangia https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/ #modified to work for user inputs elif choice == "5": alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " word = input("What is the word or phrase to encrypt? \n").upper() shift = int(input("How many places would you like to shift it? \n")) newletter = "" newword = "" for letter in word: newletter = alphabet[(alphabet.find(letter)+shift)%27] newword += newletter print (word+" = "+newword) elif choice == "6": alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " word = input("What is the word or phrase to decrypt? \n").upper() shift = int(input("How many places is it shifted? \n")) newletter = "" newword = "" for letter in word: newletter = alphabet[(alphabet.find(letter)-shift)%27] newword += newletter print (word+" = "+newword) else: print("") print("-----------------------------") print("Please choose a valid option.") print("------------------------------") print("") exit
6dcc01807ce1fe9e161edbce40b7d01c5f34789a
McKenzieGary/LearningPython
/Business & Finance/ChaseBankCSVAnalysis.py
763
3.6875
4
#when I run the script I'd like to export a CSV of all transactions from the month. #Date range: (complete) #Sum of outgoing: (complete) #Sum of incoming: (complete) #Net for the time period: (complete) #Total Balance: (complete) #present it somewhere. import pandas as pd df = pd.read_csv('Enter CSV Path Here') Start = df.iloc[:,0].tail(1).sum() End = df.iloc[:,0].head(1).sum() Income = df.iloc[:,2].where(df.iloc[:,2]>0).dropna().sum() Outflow = df.iloc[:,2:].where(df.iloc[:,2:]<0).sum(axis=1).sum() Net = Income + Outflow Balance = df.iloc[0,4] print ("Start Date", Start) print ("End Date", End) print ("Income for time period", Income) print ("Outflow for time period", Outflow) print ("Net for time period", Net) print ("Current Balance", Balance)
ead272526a56d7f6c9e1db1ef750438d18506a05
aidataguy/python_learn
/lambda.py
372
3.75
4
#! /usr/bin/python3 # lambda arguments: expression cube = lambda x: x * 3 print(cube(9)) # filtering using lambda my_list = [10, 21, 44, 54, 72, 22, 30, 50] new_list = list(filter(lambda x: (x%2 == 0 ), my_list)) print(new_list) # map using lambda list_map = [10, 21, 44, 54, 72, 22, 30, 50] mapped_list = list(map(lambda x:x * 2, list_map)) print(mapped_list)
5c43871d33a0b6d5de424adc02b2e8f8e9914f41
lafetamarcelo/CoRoTContributions
/utils/visual.py
14,439
3.71875
4
""" This module simplifies the usage of the bokeh library by reducing the amount of code to plot some figures. For example, without this library, to plot a simple line with the bokeh library, one must do something like:: from bokeh.palettes import Magma from bokeh.layouts import column from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource from bokeh.io import output_notebook, push_notebook p = figure( title="Some title", plot_width=400, plot_height=600) # Style the figure image p.grid.grid_line_alpha = 0.1 p.xgrid.band_fill_alpha = 0.1 p.xgrid.band_fill_color = Magma[10][1] p.yaxis.axis_label = "Some label for y axis" p.xaxis.axis_label = "Some label for x axis" # Place the information on plot p.line(x_data, y_data, legend_label="My legend label", line_width=2, color=Magma[10][2], muted_alpha=0.1, line_cap='rounded') p.legend.location = "right_top" p.legend.click_policy = "disable" show(p) Wich, with the visual library one might do with just:: p = visual.line_plot(x_data, y_data, legend_label='My legend label', title='Some title', y_axis={'label': 'Some label for y axis'}, x_axis={'label': 'Some label for x axis'}) visual.show_plot(p) Simple as that... It follows a defualt plotting style for each plot, presented in the */utils/configs/plot.yaml*. And the user just need to pass the parameters that he want to change from this default style. It also provides some pre-computation to make more complex graphs, such as box plots, histograms and so on. .. note:: This is just a library to simplify most plots used during the notebooks to not populate the study with unecessary code... The user can use any library desired to do this same plots. Also the user can change the *plot.yaml* file to set any default plot style that one might want. Please, for that check out the file in */utils/configs/plot.yaml*. """ import os import logging from copy import deepcopy from ruamel.yaml import YAML import pandas as pd import numpy as np from datetime import datetime from ipywidgets import interact from bokeh.palettes import Magma from bokeh.layouts import column from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource, LassoSelectTool, HoverTool from bokeh.io import output_notebook, push_notebook def handle_opts(default, provided): """ Merge the default (set by the plot.yaml file) and user provided plot options into one dictionary. :param dict default: The default style guide dict from *plot.yaml* :param dict provided: The user provided properties :return: A dict with the merged default and provided plot options :rtype: dict """ z = {} try: overlapping_keys = default.keys() & provided.keys() for key in overlapping_keys: z[key] = handle_opts(default[key],provided[key]) for key in default.keys() - overlapping_keys: z[key] = deepcopy(default[key]) for key in provided.keys() - overlapping_keys: z[key] = deepcopy(provided[key]) return z except: if provided is None: return default else: return provided output_notebook() color_theme = Magma[10] logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) plotLog = logging.getLogger("plot_log") yaml = YAML() try: conf_path = './utils/configs/plot.yaml' with open(conf_path, 'r') as conf_file: def_fig_opts = yaml.load(conf_file) except: conf_path = '../utils/configs/plot.yaml' with open(conf_path, 'r') as conf_file: def_fig_opts = yaml.load(conf_file) def line_plot( x_data=None, y_data=None, opts=None, **kwargs): """ Create a Bokeh figure object and populate its line propertie with the provided information. :param ndarray x_data: The ndarray with x axis values :param ndarray y_data: The ndarray with y axis values :param dict opts: The desired options of the *plot.yaml* in dictionary format :param kwargs: The desired options of the *plot.yaml* in directive format :return: A Bokeh figure object with the line properties filled :rtype: bokeh.Figure """ # Define the figure options yopts = dict() if opts is not None: for opt in opts: yopts[opt] = opts[opt] if kwargs is not None: for opt in kwargs: yopts[opt] = kwargs[opt] fopts = handle_opts( def_fig_opts['line_plot'], yopts) # Check axis data if x_data is None: plotLog.warning("No x axis data was provided...") if y_data is None: plotLog.error("Please provide y axis data!!") return 0 # Create the figure image p = figure( title=fopts['title'], x_axis_type=fopts['x_axis']['type'], y_axis_type=fopts['y_axis']['type'], plot_width=fopts['fig_size'][0], plot_height=fopts['fig_size'][1]) # Style the figure image p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha'] p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha'] p.xgrid.band_fill_color = color_theme[0] p.yaxis.axis_label = fopts['y_axis']['label'] p.xaxis.axis_label = fopts['x_axis']['label'] # Place the information on plot p.line(x_data, y_data, legend_label=fopts['legend_label'], line_width=fopts['line_width'], color=color_theme[fopts['color_index']], muted_alpha=fopts['muted_alpha'], line_cap=fopts['line_cap']) p.add_tools(LassoSelectTool()) p.add_tools(HoverTool()) p.legend.location = fopts['legend']['location'] p.legend.click_policy = fopts['legend']['click_policy'] return p def box_plot( score=None, labels=None, opts=None, **kwargs): """ Create a Bokeh figure object and populate its box plot properties with the provided information. To create a box plot, you actually need to combine two segment, a vbar, and a rect object from Bokeh. This method already does that for you. It also already computes the statistical median, mean and each quantile. :param list score: The list with all values of the distributions :param list labels: The list with the group label for each value of score :param dict opts: The desired options of the *plot.yaml* in dictionary format :param kwargs: The desired options of the *plot.yaml* in directive format :return: A Bokeh figure object with the box plot necessary properties filled :rtype: bokeh.Figure """ # Define the figure options yopts = dict() if opts is not None: for opt in opts: yopts[opt] = opts[opt] if kwargs is not None: for opt in kwargs: yopts[opt] = kwargs[opt] fopts = handle_opts( def_fig_opts['box_plot'], yopts) # Check axis data if labels is None: plotLog.warning("No labels for x axis data was provided...") if score is None: plotLog.error("Please provide scores data!!") return 0 # Place the information on plot # Create a data frame for the values df = pd.DataFrame(dict(score=score, group=labels)) # Find the quartiles and IQR groups = df.groupby('group') q1 = groups.quantile(q=0.25) q2 = groups.quantile(q=0.5) q3 = groups.quantile(q=0.75) iqr = q3 - q1 upper = q3 + 1.5*iqr lower = q1 - 1.5*iqr # Find the outliers for each category def outliers(group): cat = group.name return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score'] out = groups.apply(outliers).dropna() # Prepare outlier data for plotting, # we need coordinates for every outlier if not out.empty: outx, outy = [], [] for keys in out.index: outx.append(keys[0]) outy.append(out.loc[keys[0]].loc[keys[1]]) fopts['x_range'] = df.group.unique() # Create the figure image p = figure( title=fopts['title'], x_axis_type=fopts['x_axis']['type'], y_axis_type=fopts['y_axis']['type'], plot_width=fopts['fig_size'][0], plot_height=fopts['fig_size'][1], x_range=fopts['x_range'], y_range=fopts['y_range']) # Style the figure image p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha'] p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha'] p.xgrid.band_fill_color = color_theme[0] p.yaxis.axis_label = fopts['y_axis']['label'] p.xaxis.axis_label = fopts['x_axis']['label'] # If no outliers, shrink lengths of stems to be no longer than the minimums or maximums qmin, qmax = groups.quantile(q=0.00), groups.quantile(q=1.00) upper.score = [min([x,y]) for (x,y) in zip(list(qmax.loc[:,'score']),upper.score)] lower.score = [max([x,y]) for (x,y) in zip(list(qmin.loc[:,'score']),lower.score)] # Stems p.segment(fopts['x_range'], upper.score, fopts['x_range'], q3.score, line_color="black") p.segment(fopts['x_range'], lower.score, fopts['x_range'], q1.score, line_color="black") # Boxes p.vbar(fopts['x_range'], 0.7, q2.score, q3.score, fill_color=color_theme[2], line_color="black") p.vbar(fopts['x_range'], 0.7, q1.score, q2.score, fill_color=color_theme[8], line_color="black") # Whiskers (almost-0 height rects simpler than segments) p.rect(fopts['x_range'], lower.score, 0.001, 0.005, line_color="black") p.rect(fopts['x_range'], upper.score, 0.001, 0.005, line_color="black") # Outliers if not out.empty: p.circle(outx, outy, size=6, color="#F38630", fill_alpha=0.6) return p def hist_plot( hist=None, edges=None, opts=None, **kwargs): """ Create a Bokeh figure object and populate its histogram plot propertie with the provided information. To create a histogram plot, you actually need to the correct properties of the quad object from Bokeh. This method already does that for you. It also already computes the correct values, and create the bins correctly. :param ndarray hist: The hist output from numpy.histogram :param ndarray edges: The histogram edges output from numpy.histogram :param dict opts: The desired options of the plot.yaml in dictionary format :param kwargs: The desired options of the plot.yaml in directive format :return: A Bokeh figure object with the line properties filled :rtype: bokeh.Figure """ # Define the figure options yopts = dict() if opts is not None: for opt in opts: yopts[opt] = opts[opt] if kwargs is not None: for opt in kwargs: yopts[opt] = kwargs[opt] fopts = handle_opts( def_fig_opts['histogram_plot'], yopts) # Check axis data if hist is None: plotLog.error("Please provide the proper hist parameter.") return 0 if edges is None: plotLog.error("Please provide the proper edges parameter.") return 0 # Create the figure image p = figure( title=fopts['title'], x_axis_type=fopts['x_axis']['type'], y_axis_type=fopts['y_axis']['type'], plot_width=fopts['fig_size'][0], plot_height=fopts['fig_size'][1]) # Style the figure image p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha'] p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha'] p.xgrid.band_fill_color = color_theme[0] p.yaxis.axis_label = fopts['y_axis']['label'] p.xaxis.axis_label = fopts['x_axis']['label'] # Place the information on plot p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color=color_theme[fopts['color_index']], line_color="white", alpha=0.5) # Include some plot tools p.add_tools(LassoSelectTool()) p.add_tools(HoverTool()) return p def multline_plot( x_data=None, y_data=None, opts=None, **kwargs): """ Create a Bokeh figure object and populate a line object of the bokeh library for each line data provided in the y_data list parameter of this function. :param list x_data: The list with a ndarray data for the x axis of each line :param list y_data: The list with a ndarray data for the y axis of each line :param dict opts: The desired options of the *plot.yaml* in dictionary format :param kwargs: The desired options of the *plot.yaml* in directive format :return: A Bokeh figure object with the line properties filled :rtype: bokeh.Figure """ # Define the figure options yopts = dict() if opts is not None: for opt in opts: yopts[opt] = opts[opt] if kwargs is not None: for opt in kwargs: yopts[opt] = kwargs[opt] fopts = handle_opts( def_fig_opts['multline_plot'], yopts) # Check axis data if x_data is None: plotLog.warning("No x axis data was provided...") if y_data is None: plotLog.error("Please provide y axis data!!") return 0 # Create the figure image p = figure( title=fopts['title'], x_axis_type=fopts['x_axis']['type'], y_axis_type=fopts['y_axis']['type'], plot_width=fopts['fig_size'][0], plot_height=fopts['fig_size'][1]) # Style the figure image p.grid.grid_line_alpha = fopts['dec']['grid']['line_alpha'] p.xgrid.band_fill_alpha = fopts['dec']['x_grid']['band_alpha'] p.xgrid.band_fill_color = color_theme[0] p.yaxis.axis_label = fopts['y_axis']['label'] p.xaxis.axis_label = fopts['x_axis']['label'] # Place the information on plot data, ind_track = x_data, 0 if type(x_data) is not list: x_data = list() for k in range(len(y_data)): x_data.append(data) for x, y in zip(x_data, y_data): try: p.line(x, y, legend_label=fopts['legend_label'][ind_track], line_width=fopts['line_width'][ind_track], color=color_theme[fopts['color_index'][ind_track]], muted_alpha=fopts['muted_alpha'], line_cap=fopts['line_cap']) except: p.line(x, y, legend_label=fopts['legend_label'][ind_track], line_width=fopts['line_width'][0], color=color_theme[fopts['color_index'][ind_track]], muted_alpha=fopts['muted_alpha'], line_cap=fopts['line_cap']) ind_track += 1 p.add_tools(LassoSelectTool()) p.add_tools(HoverTool()) p.legend.location = fopts['legend']['location'] p.legend.click_policy = fopts['legend']['click_policy'] return p def show_plot(*args): """ This function shows the figures provided as arguments by default, in a column manner. :param args: The bokeh.Figure objects to be show in a figure """ if args is not None: show(column(*args)) else: plotLog.error("No plot was provided!!")
8f6f1c0d061286714082808561826191e60c5e1b
ramankarki/learning-python
/computer_scientist/list_algorithms/quick_sort.py
659
3.90625
4
def quick_sort(array): if len(array) <= 1: return array else: pivot = array.pop() highest = [] lowest = [] for i in array: if i < pivot: lowest.append(i) else: highest.append(i) return quick_sort(lowest) + [pivot] + quick_sort(highest) if __name__ == "__main__": import time, random # tim sorting algorithm num_list = [] for i in range(1000000): num = random.randint(1, 1000000) num_list.append(num) print(num_list[:10]) t0 = time.time() print(quick_sort(num_list)[:10]) t1 = time.time() print("time taken:", t1-t0)
394878cb9f863fdfa16d2e49e4fef80c67a4a038
IanMadlenya/BYUclasses
/CS_598R/Week1/lagrange_4square.py
659
3.59375
4
from math import sqrt, pow import sys def n_4_squares(nn): """ Determine the number of ways the number n can be created as the sum of 4 squares. """ how_many = 0 n = nn for a in xrange(0, int(sqrt(n)) + 1): for b in xrange(0, min(a, int(sqrt(n - pow(a, 2)))) + 1): for c in xrange(0, min(a, int(sqrt(n - pow(a, 2) - pow(b, 2)))) + 1): temp_d = n - pow(a, 2) - pow(b, 2) - pow(c, 2) if temp_d >= 0: print(a, b, c) how_many += 1 return how_many if __name__ == '__main__': arg = sys.argv[1] print arg n_4_squares(int(arg))
8ef74e48bbafe733aeedb7a2f69c1e4e8bc58edb
WilliamReynolds/exercism_python
/two-fer/two_fer.py
202
3.8125
4
import sys name = raw_input("What is your name?") def two_fer(name): if name: print("One for " + name + ", one for me.") else: print("One for you, one for me.") two_fer(name)