blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
dabdd0f7221f0a2e98b1dec3af341b11c80205f4
DanielAlmajano/Introjavascript
/src/funciones/lambda/lambda.py
160
3.890625
4
#Iteración en python funcion lambda iterar = (lambda vector: [print(vector[i], end=', ') for i in range(0, len(vector))]) print(iterar(vector = [2, 3, 4, 5]))
851ac8edb85e418023094b846f2c561b932fb01a
sdlipp/GP_Python210B_Winter_2019
/students/ScottL/session09/mailroom_donor.py
4,981
3.953125
4
#!/usr/bin/env python3 """ Purpose: store data for Donors and provide useful functionality with the data Developed by: Scott Lipp Revision History: 3/16/19 -- Created """ class Donor: """Store and process data regarding individual donors.""" def __init__(self, first, last): """ Initialize new donor object with name and list to record donations. :param first: string, first name :param last: string, last name """ self.first_name = first.capitalize() self.last_name = last.capitalize() self.donations = [] def add_donation(self, amount): """ Add new donation to an existing donor in the system. :param amount: float, donation amount :return string, personalized 'thank-you' email """ self.donations.append(amount) return self.solo_email(amount) @property def count(self): """:return integer, the number of donations for a particular donor.""" return len(self.donations) @property def total(self): """:return float, the total dollar amount of donations for a single donor.""" return sum(self.donations) @property def full_name(self): """:return string, the first and last name in a single string.""" return f"{self.first_name} {self.last_name}" def solo_email(self, amount): """ Generate the text simulating a 'Thank You' email for a donation. :param amount: float, amount of donation :return string, personalized 'thank-you' text """ return "\nDear {} {},\nThanks for the generous donation of ${:,.2f}." \ "\n\nSincerely,\nFundraising Team".format( self.first_name, self.last_name, amount) class DonorCollection: """Store the collection of donor objects, analyze and manipulate the data set.""" donor_list = [] def new_donor(self, first, last): """ Create new donor object and store in donor list. :param first: string, first name of donor :param last: string, last name of donor """ self.donor_list.append(Donor(first, last)) def new_donation(self, first, last, amount): """ Add new donation to an existing donor object. :param first: string, first name :param last: string, last name :param amount: float, donation amount :return: string, text for a 'thank-you' email """ email = "" if self.search(first, last) is False: self.new_donor(first, last) for donor in self.donor_list: if donor.first_name == first and donor.last_name == last: email = donor.add_donation(amount) return email def search(self, first, last): """ Return a boolean if a donor name already exists in the list. :param first: string, first name :param last: string, last name :return: Boolean """ found = False for donor in self.donor_list: if donor.first_name == first and donor.last_name == last: found = True return found def name_list(self): """ :return: list of names sorted by 1) last name, 2) first name """ donors = [[donor.last_name, donor.first_name] for donor in self.donor_list] donors.sort(key=lambda x: x[1]) donors.sort(key=lambda x: x[0]) return [f"{donor[0]}, {donor[1]}" for donor in donors] def report(self): """ :return: list, summarizing all donors sorted by total donation amount. """ sorted_list = [] for donor in self.donor_list: try: avg_amount = donor.total / donor.count except ZeroDivisionError: avg_amount = 0 finally: sorted_list.append([donor.full_name, round(donor.total, 0), donor.count, round(avg_amount, 0)]) sorted_list.sort(key=lambda x: x[1], reverse=True) return sorted_list def group_email(self): """ :return: dict, key is donor name, value is string of 'thank-you' text """ email_dict = {} for donor in self.donor_list: if donor.count not in (None, 0): if donor.count > 1: plurality = "s totaling" else: plurality = " of" email_dict[donor.full_name] = "Dear {},\n\nThank you so much for your very " \ "generous donation{} ${:,}.\nWe wouldn't be " \ "able to do this without you.\n\nSincerely," \ "\nFundraising Team" \ "".format(donor.full_name, plurality, donor.total) return email_dict
2f6e6801bedabf6497a1124b3e6459e32b333246
PovedaJose/EjerciciosDePython
/Practicas#1/Ejercicio#3.py
639
3.71875
4
class Condicion: contador=0 def __init__(self,num1=1,num2=1): self.number1=num1 self.number2=num2 number = num1+num2 self.number3 = number def usoif(self): if self.number1 == self.number2: print("numero1:{}, numero2:{}: son iguales".format(self.number1,self.number2)) elif self.number1 == self.number3: print("numero1:{}, numero3:{}: son iguales".format(self.number1,self.number3)) else: print("No son iguales") Ejm1 = Condicion(10,25) Ejm1.usoif() # print(Ejm1.number1) # print(Ejm1.number2) print(Ejm1.number1)
9a3d7a27c70aed859579c0b044101e3cc03a84df
nyksy/data-analysis-with-python-2021
/part01/part01-e20_usemodule/src/triangle.py
615
3.5
4
""" kolmion funktioita """ __author__ = "Juho Nykänen, UEF" __version__ = "0.0.1" from math import sqrt def hypothenuse(s1, s2): """palauttaa hypotenuusan pituuden Args: s1 (float): kolmion kanta s2 (float): kolmion korkeus Returns: float: hypotenuusan pituus laskettuna kannasta ja korkeudesta """ return sqrt(float(s1**2) + float(s2**2)) def area(s1, s2): """palautetaan kolmion pinta-ala Args: s1 (float): kolmion kanta s2 (float): kolmion korkeus Returns: Float: pinta-ala (kanta*korkeus)/2 """ return (s1 * s2) / 2
4889bbdbd1f8351d4de89a4dbd9d1849fec8729b
VivekRedD1999/Daily_Code_Challenge
/Run_Length_coding.py
816
4.15625
4
# Run-length encoding is a fast and simple method of encoding strings. # The basic idea is to represent repeated successive characters as a single count and character # For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". #===================================================================================================== def Run_Length_Coding(x): result, final = [], "" count = 1 for i in range(len(x)): if i == len(x) - 1: result.append(count) result.append(x[i]) elif x[i] == x[i + 1]: count += 1 else: result.append(count) result.append(x[i]) count = 1 for val in result: val = str(val) final += val return final print(Run_Length_Coding(input()))
4c573b6aa28f034d94f246c573ad9e8fce4b0612
krolique/project_euler
/solutions/042_coded_triangle_numbers.py
1,263
3.859375
4
# -*- coding: utf-8 -*- """ Problem #42 - Coded triangle numbers ------------------------------------ The n-th term of the sequence of triangle numbers is given by: t(n) = n*(n+1)/2; so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ def problem(): """ Attempt to solve the problem... """ print 'problem #42' t_inv = lambda x: int(((1+8*x)**(0.5) - 1) / 2) t = lambda x: x*(x+1)/2 with open('042_words.txt', 'r') as f: words = [x.replace('"', '').lower() for x in f.read().split(',')] sums = [sum(ord(i) - 96 for i in x) for x in words] triangle_words = sum(1 for x in sums if x == t(t_inv(x))) print 'the number of triable words in the file is: %s' % triangle_words if __name__ == "__main__": problem()
19adf8ce9c18a3978f7f02918b95899aa909d37e
JuanOlivares1/holbertonschool-higher_level_programming
/0x0A-python-inheritance/10-square.py
466
4.21875
4
#!/usr/bin/python3 """Module - defing 'is_same_class' function """ Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """Class Square - defines a square inherits from: Rectangle """ def __init__(self, size): """Constructor Args: size (int): size of square """ Rectangle.integer_validator(self, "size", size) Rectangle.__init__(self, size, size) self.__size = size
da64084e8c429099d66899888d21551a826c975f
foureyes/csci-ua.0479-spring2021-001
/assignments/hw06/secret_messages.py
3,529
4.625
5
""" secret_messages.py ===== Write a program that encrypts a message (encodes a message so that it's "secret") by shifting every letter in the message a number of spaces to the left or right. This simple encryption technique is called a Caesar Cipher: https://en.wikipedia.org/wiki/Caesar_cipher For example, shifting by three maps the original letters of a message to a letter 3 places to the right from the original letter. If there are no more letters to the right, continue by going back to the beginning of the alphabet. For a shift of three, the letters would be mapped as follows: A → D B → E C → F . . . Y → B Z → C So... encrypting the message "ABC" would yield "DEF". A few more examples: "Hello There" → "Khoor Wkhuh" "Oxen and Zebra" → "Rahq dqg Cheud" In our implementation of Casear's Cipher: * IF A SHIFTED LETTER GOES BEYOND 'Z' or 'z', continue counting places from the left (that is, go back to A, and continue your shift from there) * DO NOT SHIFT ANY CHARACTER THAT'S NOT A LETTER (retain punctuation, spaces, etc.): ... with a shift of 10, "a! b! c!" → "k! l! m!" * CASING (upper/lower case) SHOULD BE PRESERVED: shift by 1, "aRe" → "bSf" To write this program, create 3 functions: * encrypt - encrypt a string using Caesar's Cipher * input: a string to encrypt and the number of letters to shift * processing: use Caesar's Cipher to encrypt the string passed in based on the specified shift value * output: returns a string * decrypt - decrypt a string using Caesar's Cipher * input: a string to decrypt and the number of letters that the original message was shifted * processing: use Caesar's Cipher to decrypt the string passed in assuming that the original shift is the shift value passed in * output: returns a string * main - contains the main logic of your program * input: none * processing: continually asks the user for input... (see specifications below) * output: does not return anything * remember to call main at the end of your program! The program will: * continually ask "(e)ncrypt, (d)ecrypt or (q)uit?" until the user enters q to quit * it should accept both upper and lowercase versions of e, d, and q * if the user chooses encrypt * ask the user for a message... and how many letters to shift by * display the encrypted message * if the user chooses decrypt * ask the user for a message... and how many letters the original message was shifted by * display the decrypted message * hint: one way to solve this is to use chr and ord * what are the unicode code points of boundaries of letters? * check out the following chart: http://www.utf8-chartable.de/unicode-utf8-table.pl?utf8=dec * remember that the boundaries differ for upper and lowercase letters Example output below: ----- (e)ncrypt, (d)ecrypt or (q)uit? > ??? Sorry, I can only (e)ncrypt, (d)ecrypt or (q)uit... (e)ncrypt, (d)ecrypt or (q)uit? > e How many places should each letter be shifted? > 3 What is the message? > Hello There Khoor Wkhuh (e)ncrypt, (d)ecrypt or (q)uit? > d How many places was each letter shifted? > 3 What was the message? > Vhfuhw Secret (e)ncrypt, (d)ecrypt or (q)uit? > e How many places should each letter be shifted? > -1 What is the message? > bcd abc (e)ncrypt, (d)ecrypt or (q)uit? > q Bye! (Optional) Your encrypt functions probably look very similar. Try moving out the common code into another function that both encrypt and decrypt call. """
66301e31e13ef4d5e643788b939b960fb7f384f3
gaddiss3651/cti110
/P4LAB1_NestedLoop_Gaddis.py
884
3.765625
4
# CTI-110 # P4LAB Nested Loop # Shannon Gaddis # March 25, 2018 import turtle import random # setup the window with a background colour wn = turtle.Screen() wn.setup(width=250, height=250) # assign a name to your turtle t = turtle.Turtle() colors = ["blue"] t.pensize(4) # increase pensize (takes integer) def snowflake(size, pensize, x, y): t.penup() t.goto(x, y) t.forward(10*size) t.left(45) t.pendown() t.color((colors)) for i in range(8): branch(size) t.left(45) def branch(size): for i in range(3): for i in range(3): t.forward(10.0*size/3) t.backward(10.0*size/3) t.right(45) t.left(90) t.backward(10.0*size/3) t.left(45) t.right(90) t.forward(10.0*size) snowflake(6, 4, 0, 0) wn.exitonclick()
7f00877f4055384fa65c3592f3549afd4e620995
toohottostop/algorithms
/decrypt/decrypt.py
316
3.671875
4
def decrypt(s: str) -> str: result = [] for ch in s: result.append(ch) if len(result) > 2 and (result[-1], result[-2]) == (".", "."): result.pop() result.pop() if result: result.pop() return "".join(ch for ch in result if ch != ".")
752e96cc5aa3ec7668807b213b4cfd53f36e59f1
Rajatkhatri7/Rock_paper_sizors
/rock_paper_sizor.py
3,194
4.0625
4
print("Welcome to Pyython Developer's Rock Paper sizors game !!!!") import tkinter from tkinter import * from tkinter import ttk import random rock = 1 paper = 2 sizor = 3 names = {rock:"Rock",paper: "Paper",sizor:"Sizor"} rules = {rock: sizor,paper:rock,sizor:paper} def gui(): names = {rock: "Rock",paper: "Paper",sizor: "Sizor"} rules = {rock: sizor,paper: rock,sizor: paper} #computer_score = 0 #player_score = 0 #print ("press start to begain the game ") def start(): print("start the game") while game(): pass def game(): player = player_choice.get() computer = random.randint(1,3) computer_choice.set(names[computer]) result (player,computer) # def move(): # while True: # print (" press 1 for rock\n press 2 for paper\n press 3 for sizor") # player = input() # try: # player = int(player) # if player in (1,2,3): # return player # except ValueError: # print("sorry didn't get tht ") def result(player,computer): global rules new_score = 0 # print( "1....") # time.sleep(1) # print("2...") # time.sleep(2) # print("3..") # time.sleep(0.5) # computer_input = "computer through {0}:".format(names[computer]) # global player_score,computer_score if player == computer: result_set.set("tie game") else: if rules[player] == computer: result_set.set("you won the game") new_score = player_score.get() new_score+=1 player_score.set(new_score) else: result_set.set("you lose the game better luck nxt time") new_score=computer_score.get() new_score+=1 computer_score.set(new_score) print ("thnx for playing") rps_window = Toplevel() rps_window.title ("Rock, Paper, Scissors") player_choice = IntVar() computer_choice = StringVar() result_set = StringVar() player_choice.set(1) player_score = IntVar() computer_score = IntVar() rps_frame = Frame(rps_window, padx = 12,pady = 12, width = 300) rps_frame.grid(column=0, row = 0, sticky=(N,W,E,S) ) rps_frame.columnconfigure(0, weight=1) rps_frame.rowconfigure(0,weight=1) Label(rps_frame, text='Player').grid(column=1, row = 1, sticky = W) Radiobutton(rps_frame, text ='Rock', variable = player_choice, value = 1).grid(column=1,row=2, sticky=W) Radiobutton(rps_frame, text ='Paper', variable = player_choice, value = 2).grid(column=1,row=3, sticky=W) Radiobutton(rps_frame, text ='Scissors', variable = player_choice, value =3).grid(column=1, row=4, sticky=W) Label(rps_frame, text='Computer').grid(column=3, row = 1, sticky = W) Label(rps_frame, textvariable = computer_choice).grid(column=3, row=3, sticky = W) Button(rps_frame, text="Play", command = start()).grid(column = 2, row = 2) Label(rps_frame, text = "Score").grid(column = 1, row = 5, sticky = W) Label(rps_frame, textvariable = player_score).grid(column = 1, row = 6, sticky = W) Label(rps_frame, text = "Score").grid(column = 3, row = 5, sticky = W) Label(rps_frame, textvariable = computer_score).grid(column = 3, row = 6, sticky = W) Label(rps_frame, textvariable = result_set).grid(column = 2, row = 7) #def score(): # global computer_score , player_score # print( "high scores:") # print("player: ",player_score) # print("cpmputer: ",computer_score) start()
baa6d672a773984118b6c398c4d877660b20ab83
tomcroll/mitpython
/lenIter.py
181
3.765625
4
def lenIter(aStr): ''' aStr: a string returns: int, the length of aStr ''' i = 0 for char in aStr: i += 1 return i print lenIter('asdfdfgasdf')
232045ecf9852e7df11243c9e8f2f94793d5d977
jana-choi/PythonCodingTest
/21.GreedyAlgorithm/1.best-time-to-buy-and-sell-stock-ii/2_pythonic.py
204
3.546875
4
def maxProfit(prices): # 0 보다 크면 무조건 합산 return sum(max(prices[i+1] - prices[i], 0) for i in range(len(prices)-1)) if __name__ == "__main__": print(maxProfit([7,1,5,3,6,4]))
ce056e2d20ce71eeb712d63524dea62121554a2a
turion/enigmake
/examples.py
2,973
3.59375
4
#! /usr/bin/python # -*- coding: utf-8 -*- """enigmake.examples""" import enigmake target1 = enigmake.Parameter(3.0, title = "target1") # The basis to build the dependent targets upon print target1() target2 = target1**4 # Operators are implemented for targets and numbers. Use numbers instead of targets if you are sure that the number won't change. target3 = target1 + target2 # Operators are implemented for targets and other targets. print target3() print target1 in target3.dependencies, target2 in target3.dependencies # The + operator automagically detected the dependcies of target3 on target1 and target2. some_parameter = enigmake.Parameter(1) divisor = some_parameter * 2 answer = target3/divisor print "and the answer is...", answer() def decide_if_target3_is_large_enough(): return target3() > 100 target4 = enigmake.Target(decide_if_target3_is_large_enough, dependencies = [target3]) # Define a target this way if the function to calculate the data cannot be written with the implemented operators. print target4() # target1 to 3 won't be recalculated target1.data = 5 print "and the new answer is...", answer() # This automagically determines which parts of the data have to be recalculated, namely target1 to 3 and answer, but not divisor. target5 = enigmake.Target(enigmake.not_available, title="target5 (will be done later)") # Do this if you want to implement the target later but define it already now. target6 = target5 + 7 # Raises no error. You can construct all dependencies upon target5... try: print target6() # ...unless you call any target that depends upon target5. This raises a NotAvailableError. except enigmake.NotAvailableError: print "A target needed for calculation is not yet available." def some_idea(): return 1000 # One day later, the implementation of target5 now comes to your mind. No problem! Just replace enigmake.not_available in the definition of target5 with some_idea. # Or the calculation method of target5 is known only at runtime. In this case, do late binding... target5.calc_data = some_idea print "Now available:", target6() # ...and target6 can be calculated! import enigmake.files some_answer = enigmake.files.PickleRuntimeConstant(42, 'some_answer.pickle') some_other_stuff = enigmake.files.PickleFileTarget(some_answer, [some_answer], 'some_other_stuff.pickle') print some_other_stuff() # Will refresh some_answer only if some_answer.pickle doesn't exist or the value 42 is changed. even_other_stuff = enigmake.files.PickleFileTarget(some_answer/42.0*23, [some_answer], 'even_other_stuff.pickle') # Will create internals Targets some_answer/42.0 and some_answer/42.0*23 whose dirtynesses aren't tracked since they are left out in the dependency list intentionally. The latter of those targets plays the role of even_other_stuff's calc_data. This way, one can create instances of Target subclasses (here a PickleFileTarget) without having to define calc_data explicitly. print even_other_stuff()
407cc77577a6c1639d5f5b311d2dbc558a25a1b6
liyueliyue/py3Test
/Chapter 2/2.1python的内置类型/2.1.1字符串与字节.py
1,627
4.3125
4
""" 1.python3中只有一种能够保存文本信息的数据类型,就是str字符串,它是不可变序列,保存的是Unicode码位。 2.字符串可以保存的数据类型就是Unicode文本; 3.字符串:所有没有前缀的字符串都是Unicode,被''、""、''''''包围且没有前缀的值都是str数据类型; 4.字节:被,''、""、'''''' 包围但必须有一个b或B前缀都是bytes字节; """ print(bytes([102,111,111])) list1 = list(b'foo bar') print(list1) tuple1 = tuple(b'foo bar') print(tuple1) print(type(b'some bytes')) print(type('string')) #一、字符串和字节的转换: # 1.str(字符串)encode()为bytes(字节):srt.encode()\bytes(source,encoding='字节序列则需要指定该参数') string1 = 'i am coming!' bytes1 = str.encode(string1) print(bytes1) print(type(bytes1)) print(bytes(string1,encoding='utf-8')) # 2.bytes(字节)decode()为str(字符串):bytes.decode()/str(source,encoding='字节序列则需要指定该参数') bytes2 = b'i am bytes!' string2 = bytes.decode(bytes2) print(string2) print(str(bytes2,encoding='utf-8')) # 二、python字符串是不可变的,字节序列也是不可变的。 # 三、字符串拼接 # 1、str.join()方法接受可迭代的字符串作为参数,返回合并后的字符串,把序列(string\list\tuple\)合并返回一个新的字符串! list = ['i','am','coming','!'] string3 = ' '.join(list) print(string3) tuple1 = ('i','am','coming','!') string4 = ' '.join(tuple1) print(string4) # 2、使用+拼接字符串 a = '123' b = '456' print(a+b) # 3、字符串格式化可以用str.format()或%运算符
6e97a53c3a45644628b118bca98caa03d50e06f8
petecarr/Japanese_Theorem
/tk_quad.py
6,920
3.734375
4
#!/usr/bin/python # In geometry, the Japanese theorem states that the centers of the # incircles of certain triangles inside a cyclic quadrilateral are # vertices of a rectangle. # Theorem may have actually come from China but, apparently, Japanese # people during the early 19th Century used to do geometry for fun and one # of them (anonymously) came up with this. The problem or solution # was written on a wooden tablet and placed as an offering at a Shinto # shrine. # There is also a theory of cyclic polygons. from tkinter import * from math import sqrt CANVASWIDTH=600 CANVASHEIGHT=CANVASWIDTH cx = CANVASWIDTH cy = CANVASHEIGHT BGCOLOR="black" LINECOLOR="green" linecolor=LINECOLOR colors = ("red", "orange", "yellow", "green", "cyan", "blue", "magenta") # Nice 345 triangles to start with A = [cx/6, cy/4] #[100,150] B = [cx-cx/6, cy/4] #[500,150] C = [cx-cx/6, cy*3/4] #[500,450] D = [cx/6, cy*3/4] #[100,450] Ox = cx/2 # 300 Oy = cy/2 R = (cx-cx/6)/2 # 250 global inner_q inner_q = [0,0,0,0,0,0,0,0] #---------------------------------------------------------------------------- def rect(x1,y1,x2,y2,x3,y3,x4,y4): # compare diagonals - leave a little slack l1 = sqrt((x3-x1)*(x3-x1) +(y3-y1)*(y3-y1)) l2 = sqrt((x4-x2)*(x4-x2) +(y4-y2)*(y4-y2)) if abs(l2-l1) >= 2: # If you see this the program is wrong (or inaccurate) print("Not a rectangle") print("Diagonal difference ={0:.1f}-{1:.1f}={2:.1f}".format( l2,l1,abs(l2-l1))) return abs(l2-l1) < 2 def inscribe_circle(A,B,C): bcx = B[0]-C[0] bcy = B[1]-C[1] a = sqrt(bcx*bcx+bcy*bcy) acx = A[0]-C[0] acy = A[1]-C[1] b = sqrt(acx*acx+acy*acy) bax = B[0]-A[0] bay = B[1]-A[1] c = sqrt(bax*bax+bay*bay) p = a+b+c halfp = p/2.0 # Center of incircle x = (a*A[0] +b*B[0] +c*C[0])/p y = (a*A[1] +b*B[1] +c*C[1])/p # Heron's method area = sqrt(halfp*(halfp-a)*(halfp-b)*(halfp-c)) r = 2.0*area/p #print("a={0:.0f}, b={1:.0f}, c={2:.0f}".format(a,b,c)) #print("perimeter = {0:.0f}".format(p)) #print("x={0:.0f}, y={1:.0f}, area={2:.0f}, r={3:.0f}".format(x,y,area,r)) return int(x),int(y),int(r) def draw(canvas): global linecolor canvas.delete(ALL) canvas.create_oval(50,50,550,550, outline = "blue") canvas.create_polygon(A[0],A[1],B[0],B[1],C[0],C[1],D[0],D[1], fill="", outline=linecolor) canvas.create_text(A[0],A[1],offset="-20,-10", fill="red", text="A") canvas.create_text(B[0],B[1],offset="20,-10", fill="red", text="B") canvas.create_text(C[0],C[1],offset="20,10", fill="red", text="C") canvas.create_text(D[0],D[1],offset="-20,10", fill="red", text="D") canvas.create_line(A[0],A[1],C[0],C[1], fill = linecolor) canvas.create_line(B[0],B[1],D[0],D[1], fill = linecolor) x1,y1,r1 = inscribe_circle(A,B,C) canvas.create_oval(x1+r1,y1+r1,x1-r1,y1-r1, outline = "orange") x2,y2,r2 = inscribe_circle(B,C,D) canvas.create_oval(x2+r2,y2+r2,x2-r2,y2-r2, outline = "orange") x3,y3,r3 = inscribe_circle(C,D,A) canvas.create_oval(x3+r3,y3+r3,x3-r3,y3-r3, outline = "orange") x4,y4,r4 = inscribe_circle(D,A,B) canvas.create_oval(x4+r4,y4+r4,x4-r4,y4-r4, outline = "orange") canvas.create_polygon(x1,y1,x2,y2,x3,y3,x4,y4, outline="blue", fill="") global inner_q inner_q = [x1,y1,x2,y2,x3,y3,x4,y4] def vertex(x,y): dx = 10 dy = 10 if x < (A[0]+dx) and x > (A[0]-dx) and y < (A[1]+dy) and y> (A[1]-dy): return 1 elif x < (B[0]+dx) and x > (B[0]-dx) and y < (B[1]+dy) and y> (B[1]-dy): return 2 elif x < (C[0]+dx) and x > (C[0]-dx) and y < (C[1]+dy) and y> (C[1]-dy): return 3 elif x < (D[0]+dx) and x > (D[0]-dx) and y < (D[1]+dy) and y> (D[1]-dy): return 4 else: return 0 def fix_on_circle(x, y): # Wherever you release the mouse button keep the same angle but # make sure it is on the circle defined by Ox, Ox, R # i.e. snap the quadrilateral back to being cyclic # Current radius CR = sqrt((x-Ox)*(x-Ox)+(y-Oy)*(y-Oy)) if abs(CR-R) < 1: return x,y xr = Ox+ (x-Ox)*R/CR yr = Oy+ (y-Oy)*R/CR return xr,yr def quitNow(): global root root.destroy() #-------------------------------------------------------------------------- def key(event): if (event.keysym == 'Escape'): print("Pressed Escape, quitting") quitNow() #elif (event.keycode == <Print>): #doesn't work #print("Print") else: print ("pressed", repr(event.keysym)) print ("pressed", repr(event.keycode)) def callback_click(event): global v canvas = event.widget x = canvas.canvasx(event.x) y = canvas.canvasy(event.y) canvas.focus_set() #print ("clicked at", event.x, event.y) # these will be the same unless the display becomes more complex #print ("canvas coords at", x, y) v = vertex(x,y) def callback_motion(event): canvas = event.widget x = canvas.canvasx(event.x) y = canvas.canvasy(event.y) #print ("motion to", event.x, event.y) global v #print("vertex ", v) if v > 0: if v == 1: A[0] = x A[1] = y elif v == 2: B[0] = x B[1] = y elif v == 3: C[0] = x C[1] = y elif v == 4: D[0] = x D[1] = y draw(canvas) def callback_release(event): global v canvas = event.widget x = canvas.canvasx(event.x) y = canvas.canvasy(event.y) #print ("released at", event.x, event.y) #print("vertex ", v) x,y = fix_on_circle(x, y) #print("fix_on_circle at x={0:.0f}, y={1:.0f}".format(x,y)) if v > 0: if v == 1: A[0] = x A[1] = y elif v == 2: B[0] = x B[1] = y elif v == 3: C[0] = x C[1] = y elif v == 4: D[0] = x D[1] = y draw(canvas) is_r = rect(inner_q[0],inner_q[1],inner_q[2], inner_q[3], inner_q[4],inner_q[5],inner_q[6], inner_q[7]) v = 0 #-------------------------------------------------------------------------- def main(): global root root = Tk() cf = Frame(root, borderwidth=4, relief=RAISED) cf.pack(side =LEFT) cf.master.title("Japanese Theorem for a Cyclic Quadrilateral") global canvas canvas = Canvas(cf, width = CANVASWIDTH, height = CANVASHEIGHT, bg=BGCOLOR) canvas.pack() canvas.bind("<Key>", key) canvas.bind("<Button-1>", callback_click) canvas.bind("<B1-Motion>", callback_motion) canvas.bind("<ButtonRelease-1>", callback_release) draw(canvas) root.mainloop() if __name__ == '__main__': main()
e9ff7eb4900d893cf5423adb468f4873c1ccfe58
gauravlochab/cvu
/cvu/utils/colors.py
909
4
4
"""This file contains various color utility functions. """ from typing import Tuple import random # initially taken from Ultralytics color palette https://ultralytics.com/ RGB_PALETTE = ((255, 56, 56), (255, 157, 151), (255, 112, 31), (255, 178, 29), (207, 210, 49), (72, 249, 10), (146, 204, 23), (61, 219, 134), (26, 147, 52), (0, 212, 187), (44, 153, 168), (0, 194, 255), (52, 69, 147), (100, 115, 255), (0, 24, 236), (132, 56, 255), (82, 0, 133), (203, 56, 255), (255, 149, 200), (255, 55, 199)) def random_color(bgr: bool = True) -> Tuple[int]: """Return a random RGB/BGR Color Args: bgr (bool, optional): whether to return bgr color or rgb. Defaults to True. Returns: Tuple[int]: list of 3 ints representing Color """ color = random.choice(RGB_PALETTE) return color[::-1] if bgr else color
923af5800e83e465f03617031bdcb239e5fb0d00
Gibran2001/CursoPython
/CURSO PYTHON/FactorialWhile.py
416
4.1875
4
''' EJERCICIO 7 Programa hecho por Mauricio Gibrán Colima Flores Curso de Introducción a Python ''' #Importar librería para limpiar pantalla import os os.system("cls") #mensajes iniciales print("\t\t\tEste programa calcula el factorial de un numero\n\n") n=int(input("Ingresa un numero para calcular su factorial: ")) #Proceso x=1 i=1 while(i<=n): x=x*i i=i+1 print("El factorial de tu numero es: "+str(x))
edda29e8c9602fc8aff204cdad20d80fbefb6b6c
olexandrkucher/ProgramingLanguages
/Lab1/RegisterOfLetters.py
649
3.84375
4
from functools import reduce __author__ = 'Olexandr' """ Tasks: 4, 5 """ #change register of letters to upper to_upper_case = lambda m: reduce(lambda x, y: x + y, map(lambda c: c.upper(), m)) print(to_upper_case("qwERTy")) #change register of letters to lower to_lower_case = lambda m: reduce(lambda x, y: x + y, map(lambda c: c.lower(), m)) print(to_lower_case("qwERTy")) #change register of letters to inverse # inverse_case = lambda m: reduce(lambda x, y: x + y, map(lambda c: c.upper() if c != c.upper() else c.lower(), m)) inverse_case = lambda m: reduce(lambda x, y: x + y, map(lambda c: c.swapcase(), m)) print(inverse_case("qwERTy"))
42d6023c1b1b0c5a3e8e3362ef32fb7a6be32fc9
IskanderMahambet/Control-test
/Актёр и фильм.py
742
3.5
4
actors={'Дуэйн Джонсон':' Джуманджи: Зов джунглей, Путешествие 2: Таинственный остров, Полтора шпиона, Быстрее пули, Спасатели Малибу', 'Зак Эфрон':' Величайший шоумен, Этот неловкий момент, Счастливчик, Двойная жизнь Чарли Сан-Клауда, Спасатели Малибу', 'Хью Джекман':' Величайший шоумен, Престиж, Робот по имени Чаппи, Отверженные, Живая сталь'} name = input('Введите имя :') if name in actors: print(actors[name]) else: print('Актёра в списке нет')
7dd3bac472f7ed45e6b2b595eca3243cc25ad18b
mgbo/My_Exercise
/2017/Numpy/_MATRICES/solve.py
702
3.875
4
# -*- coding:utf-8 -*- import numpy as np import numpy.linalg as lg # запоминаем библиотеку numpy.linalg под коротким именем lg # Решим систему линейных уравнений # 3 * x0 + x1 = 9 и x0 + 2 * x1 = 8 A = np.array([[3,1],[1,2]]) B = np.array([9,8]) print "Matrices A is : " print A print "\nMatrices B is : " print B X = lg.solve(A,B) print "X is : " print X print "\n------ ПО ДРУГОМУ -------\n" A_d = lg.det(A) print "Determinant" print A_d Ai = lg.inv(A) print "Ai matrices is " print Ai Aii = np.dot(A,Ai) print "A*Ai is : " print Aii print "ПОСЛЕДНОЕ РЕШЕНИЕ " ans = np.dot(Ai,B) print ans
d62ea36f667cdb07c73beea4610343f14026ea06
eileenjang/algorithm-study
/src/dongjoo/week8/rectangle.py
656
3.71875
4
# https://programmers.co.kr/learn/courses/30/lessons/62048 from fractions import Fraction def solution(w, h): if w == h: return w ** 2 - w frac = Fraction(w,h) new_w = frac.numerator new_h = frac.denominator num_split = new_w + new_h - 1 # print(num_split, "num split") num_rectangles = w // new_w # print(num_rectangles, "num recta") return w * h - num_rectangles * num_split print(solution(8,12)) # space complexity: 1 # time complexity: log(n) for fractionizing -> gcd # some other guy's solution # def gcd(a, b): return b if (a == 0) else gcd(b % a, a) # def solution(w, h): return w*h-w-h+gcd(w, h)
195042f9be01fe3b2fcb6f9eab3be4cafbbc856c
thedeepakchaturvedi/PythonCodes
/finite_for_loop.py
360
3.9375
4
for i in [1,2,3,4,5]: print(i) friends = ["Deepak", "Anurag", "Saurabh", "Hani"] for name in friends: print("Hello", name) #Finding Largest number largest_num=None num=[28,57,92,19,63] for i in num: if largest_num is None: largest_num=i elif i>largest_num: largest_num=i print(largest_num) print("Okay Done")
745ccf38c8af03c2c2137275141b9d079cd223db
Vivi55/practices
/ML_nonDim.py
1,904
3.53125
4
from sklearn.preprocessing import MinMaxScaler,StandardScaler from sklearn.feature_selection import VarianceThreshold from scipy.stats import pearsonr import pandas as pd def minmax_demo(): """ normalization:data in [0,1] Max & Min are outliers :return: """ #1.obtain dataset data = pd.read_csv("iris.txt") data=data.iloc[:,:3] print("data:\n", data) #2.instance transfer transfer=MinMaxScaler(feature_range=[2,3]) #3.fit_tranform data_new=transfer.fit_transform(data) print("data_new:\n",data_new) return None #(x-mean)/std-> depend on degree of concentration def std_demo(): """ standard :return: """ # 1.obtain dataset data = pd.read_csv("iris.txt") data = data.iloc[:, :3] print("data:\n", data) # 2.instance transfer transfer = StandardScaler() # 3.fit_tranform data_new = transfer.fit_transform(data) print("data_new:\n", data_new) return None def variance_demo(): """ filter low variance feature :return: """ #1. obtain the dataset data=pd.read_csv("~~") #print(data) data=data.iloc[:,1:-2] #confirm the range of dataset #2. instance transfer transfer=VarianceThreshold(threshold=5) #3. fit_transfer data_new=transfer.fit_transform(data) print("data_new:\n", data_new, data_new.shape) #Pearson correlation coefficient->[-1,1] #r>0, positive correlation; r<0, negative correlation; |r|=1,same ;r=0,no correlation #|r|<0.4,low correlation;0.4<|r|<0.7,significant correlation;|r|<1, high correlation #calulate two variables correlation coefficient r=pearsonr(data["pe_ratio"],data["pb_ratio"]) print("correlation coefficient:\n",r) return None if __name__=="__main__": minmax_demo() # std_demo() # variance_demo()
07cb4d963ffaf3a009c32ca34cf0fc5950bd32c6
Tommaso-09/helloworld
/Volume.py
601
3.640625
4
import math print "Inserisci 1 per calcolare il volume del cubo , inserisci 2 per calcolare il volume della sfera : " scelta = input() if scelta == 1 : lato = input("Inserisci le misure del lato del cubo : ") vcubo = lato*lato*lato print "Il volume del cubo di lato ", lato ," e' : ",vcubo elif scelta == 2 : raggio = input("Inserisci le misure del raggio della sfera : ") vsfera = 4. / 3. * math.pi * (raggio * raggio * raggio) print "Il volume della sfera di raggio ",raggio," e' : ",vsfera else : print "La scelta effettuata non corrisponde a nessuna azione. "
ba41ebf1190a33e98050448914a931b4142633ec
JuanDiazUPB/LogicaProgramacionUPB
/Laboratorios/Lab1903/Ejercicios for 4.py
255
3.78125
4
print('Ejercicio 4: Pedir al usuario que ingrese un número entero positivo e imprimir todos los números correlativos entre el ingresado por el usuario y uno menos del doble del mismo.') n = int(input("Número: ")) for n in range(n, n*2): print(n)
0193dfffc5119de2076a2b3c841dc7a227413606
ivo-bass/SoftUni-Solutions
/python_advanced/modules_LAB/triangle/draw.py
285
3.84375
4
#!/usr/bin/env python3 def print_line(n): ll = [] for i in range(1, n+1): ll.append(i) print(' '.join(map(str, ll))) def print_triangle(size): for row in range(1, size + 2): print_line(row) for row in range(size, 0, -1): print_line(row)
4b8dc505893d7fa4bdd2ee61c1dacb94981750af
RayACC/Pokepractica
/Pokedex_data.py
2,451
3.625
4
""""" Programa para crear un archivo y agregar los datos de los pokemon Numero: Nombre: Descripcion: funcion open("nombre del archivo","modo") modos: w , a , r w: crear y escribe archivo a: si el archivo existe agrega al final r: solo lectura C:/Users/tsuku/PycharmProjects/Pokepractica/Dex/ ubicacion pc ray """"" pathdatadex= input("introduce la ubicacion en la que guardaras la informacion: ") salir_programa="" contador_descripcion = 0 poke_des = "" puntuacion = [".",","," "] longitud = 0 menos_de_30 = 0 while salir_programa != "no" : diferencia = 0 salir_programa = "" contador_descripcion = 0 poke_des = "" puntuacion = [".", ",", " "] longitud = 0 menos_de_30 = 0 poke_num = input("Numero del pokemon: ") poke_nom = input("Nombre del pokemon: ") poke_desA = input("Descripcion: ") longitud= len(poke_desA) residuo_longitud = longitud%40 if residuo_longitud > 0 : menos_de_30 = False if longitud < 40: menos_de_30 = True else: if longitud < 40: menos_de_30 = True pokearchivo = open(pathdatadex + poke_num + '.-' + poke_nom +'.txt' ,'w') pokearchivo.write("Numero: {} \n".format(poke_num)) pokearchivo.write("Nombre: {} \n" .format(poke_nom)) pokearchivo.write("Descripcion:\n") pokearchivo.close() if menos_de_30 == True: for letra in poke_desA: poke_des += letra pokearchivo = open(pathdatadex + poke_num + '.-' + poke_nom + '.txt', 'a') pokearchivo.write("{} \n".format((poke_des))) pokearchivo.close() contador_descripcion = 0 poke_des = "" else: for letra in poke_desA: poke_des += letra if contador_descripcion >=40: contador_descripcion += 1 if letra in puntuacion : pokearchivo = open(pathdatadex + poke_num + '.-' + poke_nom + '.txt', 'a') pokearchivo.write("{} \n".format((poke_des))) pokearchivo.close() poke_des = "" contador_descripcion = 0 else: contador_descripcion +=1 pokearchivo = open(pathdatadex + poke_num + '.-' + poke_nom + '.txt', 'a') pokearchivo.write("{} \n".format((poke_des))) pokearchivo.close() poke_des = "" salir_programa= input("Si/No: ") salir_programa = salir_programa.lower()
5a2465bead4a05483ef8245f5516c71f4eb1f0aa
rafaelgustavofurlan/basicprogramming
/Programas em Python/01 - Basico - entrada e saida de dados/Script6.py
324
3.703125
4
# Tendo como dados de entrada a altura de uma pessoa, # construa um algoritmo que calcule seu peso ideal, # usando a seguinte formula: (72.7 * altura) - 58 #entrada altura = float(input("Qual sua altura? ")) #processamento peso_ideal = (72.7 * altura) - 58 #saída print("Seu peso ideal seria {0:.2f}".format(peso_ideal))
255f92bf4f92a8064d0993f5b619d9fd0fa72400
KojoSwiss/us-states-game-start
/main.py
1,028
3.625
4
import turtle import pandas screen = turtle.Screen() screen.title("U.S States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) states = pandas.read_csv("50_states.csv") all_states = states.state.to_list() guessed_states = [] while len(guessed_states) < 50: answer_state = screen.textinput(title=f"{len(guessed_states)}/ 50 states", prompt="Name a state ").title() if answer_state == "Exit": missing_states = [] for state in all_states: if state not in guessed_states: missing_states.append(state) df = pandas.DataFrame(missing_states) df.to_csv("States_to_learn.csv") break if answer_state in all_states and answer_state not in guessed_states: guessed_states.append(answer_state) t = turtle.Turtle() t.penup() t.hideturtle() state_info = states[states.state == answer_state] t.goto(int(state_info.x), int(state_info.y)) t.write(state_info.state.item())
48a97189d6dff7399067a2a8d0e18f489de4160e
taddeus/advent-of-code
/2020/07_bags.py
918
3.640625
4
#!/usr/bin/env python3 import re import sys def parse(f): contains = {} contained_by = {} for line in f: parent, children = line.split(' bags contain ') contains[parent] = parent_contains = [] for match in re.findall(r'\d+ \w+ \w+', children): num, child = match.split(' ', 1) parent_contains.append((child, int(num))) contained_by.setdefault(child, []).append(parent) return contains, contained_by def containers(color, contained_by): def traverse(child): for parent in contained_by.get(child, []): yield parent yield from traverse(parent) return set(traverse(color)) def count(color, contains): return sum(n + n * count(c, contains) for c, n in contains[color]) contains, contained_by = parse(sys.stdin) print(len(containers('shiny gold', contained_by))) print(count('shiny gold', contains))
044925a2ab073cf1876619255f7d9d3a4b0061f7
pengshu3312323/spitfire
/search/interface.py
660
3.625
4
#! /usr/bin/env python3 # -*- coding:utf-8 -*- from abc import ABCMeta, abstractmethod class SearchAbstract(metaclass=ABCMeta): @property def keywords(self): return self._keywords @keywords.setter def keywords(self, value): if isinstance(value, str): self._keywords = value else: raise TypeError('Keywords must be str') @property def search_target(self): return self._search_target @search_target.setter def search_target(self, value): self._search_target = value @abstractmethod def keywords_handle(self): pass
368ba5e62fdbf36344d1506afbd7988dd760ac28
Venkataragavan/Python_First_Project
/Crawl_web_2.py
1,587
3.65625
4
import requests from bs4 import BeautifulSoup import html.parser import pdb from pdb import set_trace as bp def crawl_web(max_page): fw = open("Data_From_Webpage_2.txt", 'w') fr = open('Data_From_Webpage_2.txt', 'r') page=2 #bp() while page<max_page: url="https://www.snapdeal.com/products/mobiles-mobile-phones?q=Price%3A2000%2C4999%7C&sort=plrty" text = requests.get(url)#gets all stuff from that url into text plain_data = text.text#converts text into string format with naem plain_data soup = BeautifulSoup(plain_data,"html.parser")#Beautiful Soup objects can be manipulated in many ways hence the creation of soup for headerfiles in soup.findAll('a',{'target':'_blank'}): href=headerfiles.get('href') print(str(href)) fw.write(str(href)+"\n") page+=1 def get_price_of_item(item_url): fw = open('Data_From_Webpage_1.txt', 'w') text = requests.get(item_url) # gets all stuff from that url into text plain_data = text.text # converts text into string format with naem plain_data soup = BeautifulSoup(plain_data,"html.parser") # Beautiful Soup objects can be manipulated in many ways hence the creation of soup for headerfiles in soup.findAll('span', {'itemprop': 'price'}):#a is the anchor for links and attribute:pair is specified for selecting specific elements in the page classattributedata = headerfiles.get('href') print(classattributedata) fw.write(str(classattributedata) + "\n") #fw.close() crawl_web(3)
0347ec640ec243dea473fb18d2e35516d78cd841
bad1987/webscraper
/database.py
2,824
3.5
4
import sqlite3 from datetime import datetime class Scraperdatabase: def __init__(self): self.conn = sqlite3.connect('scraper.db') self.cur = self.conn.cursor() self.createtable() self.date = self.buildTime() self.deleteOldData() def createtable(self): self.cur.executescript(""" create table if not exists news ( id integer primary key, title text not null, body text not null, website text not null, date text not null, link text ); """) def insertdata(self, datalist): for data in datalist: #check if the item already exists before inserting tmp = list(data) tmp.pop() tmp = tuple(tmp) self.cur.execute("select title, body from news where title=? and body=?",tmp) if not self.cur.fetchone(): #add the date t = list(data) t.append(self.date) data = tuple(t) try: self.cur.execute("insert into news(title,body,website,date) values (?,?,?,?)",data) print('item inserted') except: print('something went wrong while trying to insert {}'.format(data)) try: self.conn.commit() except: self.conn.rollback() def closeconnection(self): self.conn.close() def retreivedata(self): result = self.cur.execute("select title, body, website, date from news") rows = result.fetchall() return rows def retreivePerWebsiteData(self,web): result = self.cur.execute("select title, body, website from news where website=?", (web,)) rows = result.fetchall() return rows def buildTime(self): date = datetime.now().date() y = date.year m = date.month d = date.day fdate = str(y) + '/' + str(m) + '/' + str(d) return fdate def deleteOldData(self): todayDate = self.date res = self.cur.execute("select date from news") d = res.fetchone() print('[+] trying to delete old data\n') if len(d) > 0: if todayDate != d[0]: res = self.cur.execute("delete from news where date=?",d) try: self.conn.commit() print('[+]old news deleted\n') except: print('[+]something went wrong, data not deleted\n') self.conn.rollback() else: print('[+] there are no old data to delete\n') else: print('[+] database is empty\n')
8887214515549118df06febf80ca3420952d6719
Uthaeus/codewars_python
/7kyu/coloured_triangles.py
750
4.21875
4
# You will be given the first row of the triangle as a string and its your job to return the final colour which would appear in the bottom row as a string. In the case of the example above, you would the given RRGBRGBB you should return G. def triangle(row): diction = { 'GG': "G", 'BG': 'R', 'RG': 'B', 'BR': 'G', 'RB': 'G', 'GR': 'B', 'GB': 'R', 'RR': 'R', 'BB': 'B' } while len(row) > 1: temp = '' x = 0 while x < len(row) - 1: temp += diction[row[x:x+2]] x += 1 row = temp return row print(triangle('RBRGBRBGGRRRBGBBBGG')) #, 'G') print(triangle('RBRGBRB')) #, 'G') print(triangle('B')) #, 'B')
5f6508e7368364ca2ead465d036e661717c6e032
ach0o/python3-leetcode
/algorithms/roman_to_integer.py
722
3.578125
4
# https://leetcode.com/problems/roman-to-integer/ class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ sym = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} expt = {'I': 'VX', 'X': 'LC', 'C': 'DM'} res = 0 prev = None # temporarily store prev character for c in s: if c in expt.get(prev, ''): # check if exceptional case matches. # `prev` * 2 means, subtracting from `res` and `c` res -= sym.get(prev) * 2 prev = c res += sym.get(c) # always add up the symbol values. return res
46908e72ff8e2eea70ce0ab0fa89ae3a678fbdfd
akashgupta-ds/Python
/49. del & None- Statement.py
813
4.40625
4
#----------------del statement-------------- # del is keyword in python for managing memory. # Garbage collector works with 'del'. # this will delete the variable # if the variable is no more needed then we can delete the variable # it improves the memory utilization by defualt improved # del x s1="Akash" s2="Gupta" print(s1) #del(s1) # deleted s1 variable print(s1) # NameError: name 's1' is not defined # del Vs None # if we require the variable and object then use 'None' # However, if we don't require variable or object then use 'del' # if multiple object reference one variable then if delete one object then only one object effected del s2 y=None s1='Test' s2='Test' s3='Test' del s1 #print(s1) #NameError: name 's1' is not defined print(s2) print(s3)
f06d399c934fd18a0619076240dad3de3740ca06
shuangyichen/leetcode_python_0311
/SearchinRotatedSortedArray.py
1,169
3.53125
4
class Solution: def search(self, nums: List[int], target: int) -> int: if len(nums)==0: return -1 elif len(nums)==1: if target==nums[0]: return 0 else: return -1 middle = int(len(nums)/2) left = 0 right = len(nums)-1 while left<right: mid = int((left+right)/2) if target==nums[left]:return left elif target==nums[right]:return right elif target==nums[mid]:return mid if left==mid or mid==right: return -1 if nums[mid]>nums[right]:#左边是顺序的 if target>=nums[left] and target<=nums[mid]:#在左边 left = left right = mid else: left = mid right = right else:#右边是顺序的 if target>nums[mid] and target<nums[right]:#在右边 left = mid right = right else: left = left right = mid
4c44fd7dee915733eead968a00d72f761f5a29f7
arvino-98/HavSysPythonExample
/angle-hex.py
3,330
4.3125
4
#!/usr/bin/python3 ''' Arvin Aya-ay 9-22-20 Haverford Systems Inc. - Application Programmer Python Example Submission ''' import math # Prompts user for degrees, ourputs radian value def deg_to_rad(): while True: try: user_in_raw = input(">> Input a Degree (q to return): ") if user_in_raw == "q": break else: user_in_float = float(user_in_raw) radian_val = math.radians(user_in_float) print("Your input in Radians is: " + str(radian_val)) except ValueError: print("Please input a valid Degree") # Prompts user for radian, outputs degree value def rad_to_deg(): while True: try: user_in_raw = input(">> Input a Radian (q to return): ") if user_in_raw == "q": break else: user_in_float = float(user_in_raw) degree_val = math.degrees(user_in_float) print("Your input in Degrees is: " + str(degree_val)) except ValueError: print("Please input a valid Radian") # Prompts user for integer, outputs hexadecimal value def int_to_hex(): while True: try: user_in_raw = input(">> Input an Integer (q to return): ") if user_in_raw == "q": break else: user_in_int = int(user_in_raw) hex_val = hex(user_in_int) print("Your input in Hexadecimal is: " + str(hex_val)) except ValueError: print("Please input a valid Integer") # Prompts user for hexadecimal, outputs integer value def hex_to_int(): while True: try: user_in_raw = input(">> Input a Hexadecimal (q to return): ") if user_in_raw == "q": break else: user_in_int = int(user_in_raw, 16) # cast to base 16 int, ie. a hexadecimal print("Your input as an Integer is: " + str(user_in_int)) except ValueError: print("Please input a valid Hexadecimal") # Prints initial program instructions, starts main loop def main(): # string to be printed when user types '0' for help help_str =\ "[1] Degree to Radian\n"\ "[2] Radian to Degree\n"\ "[3] Integer to Hexadecimal\n"\ "[4] Hexadecimal to Integer\n"\ "[5] Exit Program" # Print welcome message when program initially launched print("\n" + "Welcome to Angle-Hex. Here are the possible commands:\n" + help_str + "\n") # Main Loop while True: try: user_in = int(input(">> Please select a command (0 to view commands): ")) if user_in == 0: print(help_str + "\n") elif user_in == 1: deg_to_rad() elif user_in == 2: rad_to_deg() elif user_in == 3: int_to_hex() elif user_in == 4: hex_to_int() elif user_in == 5: break else: raise ValueError except ValueError: print("Invalid Command (0 to view list of commands)\n") # Run program main()
f271033124bcbdbd1aec9105184d03317c61d928
shreyassgs00/game_of_life
/main.py
828
3.6875
4
import math import iteration import set_field import sys import conditions def main(): height = int(input('Enter the height of the bounded field in units: ')) if not conditions.validity(height): print("Height must be a positive number.") sys.exit() width = int(input('Enter the width of the unbounded field in units: ')) if not conditions.validity(width): print("Width must be a positive number.") sys.exit() field = set_field.Field(height,width) field_array = field.form_field_array() field_array = set_field.place_random_ones(field_array) set_field.build_field(field_array) n = 1 while n == 1: field_array = iteration.next_iteration(field_array) set_field.build_field(field_array) if __name__ == '__main__': main()
b3fed9c00b21e9ff534c971e2ea117f9443da3f5
mammothb/syndata-generation
/util_bbox.py
804
3.828125
4
def overlap(a, b, max_allowed_iou): """Find if two bounding boxes are overlapping or not. This is determined by maximum allowed IOU between bounding boxes. If IOU is less than the max allowed IOU then bounding boxes don't overlap Args: a(Rectangle): Bounding box 1 b(Rectangle): Bounding box 2 Returns: bool: True if boxes overlap else False """ dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin) dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin) if ( dx >= 0 and dy >= 0 and ( float(dx * dy) > max_allowed_iou * (a.xmax - a.xmin) * (a.ymax - a.ymin) or float(dx * dy) > max_allowed_iou * (b.xmax - b.xmin) * (b.ymax - b.ymin) ) ): return True else: return False
e49452df0a2ec9970dec7f295fad915ad4f018b6
UWPCE-PythonCert/Py300
/Examples/testing/context_manager/exercise1.py
497
3.734375
4
class YourExceptionHandler(object): def __enter__(self): pass def __exit__(self, ex_type, value, traceback): print("there was a {} error".format(ex_type)) if ex_type is ZeroDivisionError: return True else: return False with YourExceptionHandler(): print("do some stuff here") 1 / 0 print("should still reach this point") with YourExceptionHandler(): print("do more") fasldkj print("you should not get here")
552d8d062147e96e46e982e1e1d3ccaf2a6ceccd
sonaPag/python-first-strike
/my_unittest.py
3,901
3.546875
4
import unittest from check_email import check_email class Test(unittest.TestCase): def test_basic_email_true(self): #check "@" self.assertTrue(check_email("username@domain.com")) def test_basic_email_true(self): #check "." self.assertTrue(check_email("username@do.main.com")) def test_basic_email_false(self): #check "@" self.assertFalse(check_email("usernamedomain.com")) def test_double_email_false(self): #check "@" self.assertFalse(check_email("usernam@@edo@main.com")) def test_domain_true(self): #domain [a-z 0-9_-] self.assertTrue(check_email("username@do_main-007.com")) def test_domain_false_symbol(self): #domain [a-z 0-9_-] self.assertFalse(check_email("username@do_main:007.com")) def test_domain_dot_false(self): #domain none dot self.assertFalse(check_email("username@com")) def test_domain_false(self): #domain {3,256} self.assertFalse(check_email("username@co")) def test_domain_false257(self): #domain {3,256} my_email = "username@" + 'a'*300+".com" self.assertFalse(check_email(my_email)) def test_domain_symbol(self): #domain [^-] self.assertFalse(check_email("username@-domain_007.com")) def test_domain_symbol_error(self): #domain [^-] self.assertFalse(check_email("username@domain_007-.com")) def test_domain_symbol_error2(self): #domain [^-] self.assertFalse(check_email("username@domain_007.com-")) def test_domain_space(self): #space domain error self.assertFalse(check_email("username@do main.com")) def test_domain__dot2(self): #dot error self.assertFalse(check_email("username@domcom.")) def test_domain__dot3(self): #dot error self.assertFalse(check_email("username@dom..com")) def test_domain__dot4(self): #dot error self.assertFalse(check_email("username@.domcom.")) def test_name_error(self): #name {128} my_email = 'a'*129 + "@domain.com" self.assertFalse(check_email(my_email)) def test_name_none(self): #none name error self.assertFalse(check_email("@domain.com")) def test_name_space(self): #space name error self.assertFalse(check_email("a @domain.com")) def test_name_double_dot(self): #double dot error self.assertFalse(check_email("user..name@domain.com")) def test_name_double_dot2(self): #dot error self.assertFalse(check_email("username@domcom.")) def test_name_even_quotes(self): #even quotes self.assertTrue(check_email('"us"er"name"@domain.com')) def test_name_odd_quotes(self): #odd quotes error self.assertFalse(check_email('us"er"name"@domain.com')) def test_name_odd_quotes2(self): #odd quotes error self.assertFalse(check_email('us"ername@domain.com')) def test_name_symbol1_check(self): # "!" rule self.assertTrue(check_email('username"!"@domain.com')) def test_name_symbol1_false(self): # "!" rule self.assertFalse(check_email('user!name@domain.com')) def test_name_symbol2_check(self): # "," rule self.assertTrue(check_email('user","name@domain.com')) def test_name_symbol2_false(self): # "," rule self.assertFalse(check_email('user",name@domain.com')) def test_name_symbol3_check(self): # ":" rule self.assertTrue(check_email('us":"ername@domain.com')) def test_name_symbol3_check2(self): # ":" rule self.assertFalse(check_email('us":er"name@domain.com')) def test_name_symbol3_false(self): # ":" rule self.assertFalse(check_email('us:ername@domain.com')) def test_name_uppercase_false(self): # Uppercase rule self.assertFalse(check_email('usAername@domain.com')) if __name__ == '__main__': unittest.main()
bd944539281c4f6bca29c077f44e1d51ec8ff49b
zjj9527/pythonStuday
/class/def_init.py
502
4.09375
4
# 要理解类的含义,我们必须先了解内置的 __init__() 函数。 # 所有类都有一个名为 __init__() 的函数,它始终在启动类时执行。 # 使用 __init__() 函数将值赋给对象属性,或者在创建对象时需要执行的其他操作: class Person(): def __init__(self,name,age): self.name = name self.age = age p1 = Person("Bill",26) print(p1.name) print(p1.age) # 注释:每次使用类创建新对象时,都会自动调用 __init__() 函数。
03c93d911411d418eccce0d3888351144766287b
zerocod3r/InterviewQuestions
/Hashing/check_palindrome.py
836
3.75
4
# Problem Description # Given a string A consisting of lowercase characters. # Check if characters of the given string can be rearranged to form a palindrome. # Return 1 if it is possible to rearrange the characters of the string A such that it becomes a palindrome else return 0. # Example Input # Input 1: # A = "abcde" # Input 2: # A = "abbaee" # Example Output # Output 1: # 0 # Output 2: # 1 class Solution: def solve(self, A): hs = {} if len(A) == 1: return 1 for i in A: if i not in hs.keys(): hs[i] = 1 else: hs[i] = hs[i] - 1 if hs[i] == 0: del hs[i] ct = 0 for key in hs.keys(): if hs[key] == 1: ct = ct + 1 return 0 if ct > 1 else 1
f1dd6acde15b4d0b787dd6b66a3e091c0ae98424
ajayaggarwal79/Pythonmusings
/TWO_STRINGS.py
1,807
4.15625
4
""" Differences """ def singleline_diff(line1, line2): """ function to return the point or index when the string changes """ len_s1=len(line1) len_s2=len(line2) len_s3=min(len_s1,len_s2) #print(s3) count=0 # x=None if len_s1==0 and len_s2==0: return -1 elif len_s1==0 or len_s2==0: return min(len_s1,len_s2) while True and count<len_s3: if line1==line2: return -1 elif len_s1<len_s2 and line1==line2[:len_s1]: return len_s1 elif len_s1>len_s2 and line1[:len_s2]==line2: return len_s2 elif line1[count]==line2[count]: count=count+1 #print(count) continue elif line1[count]!=line2[count]: return count break #print (singleline_diff('', 'a')) def singleline_diff_format(line1, line2, idx): """ function to highlight when a string is difference with the string and the reference for the difference. """ if (idx>len(line1) or idx >len(line2)) or idx==-1: return "" elif "\n" in line1: return "" elif "\n" in line2: return "" elif "\r" in line1: return "" elif "\r" in line2: return "" else: return(line1+"\n"+"="*idx+"^"+"\n"+line2+"\n") def multiline_diff(lines1, lines2): lst_1=list() lst_2=list() for lines in lines1: lines=lines.strip() #print(lines.strip()) lst_1.append(lines) return lst_1 #return test lines1="""Ajay was here yesterday he was at home looking after his son Test123""" lines2=" " print(multiline_diff(lines1, lines2))
7f8d33cf296f3d5e2d5af29910121fc8230e1612
FunchadelicAD/FUNCHEON_ADRYAN_DSC510
/Learning/Wk 4.py
1,506
4.25
4
''' Name - Adryan Funcheon Date - 04/04/2019 Course - DSC - 510, Intro to Programming File - Assignment 4.1 Purpose - Create a program using funcitons with 2 variables requesting the amount of fiber optic cable to be installed and applying a "bulk rate" and outputting the costs and receipt. ''' # Greeting and product inputs to calculate installation costs print("Hello, and welcome to Frankies fiber optic warehouse!") company_name = str(input('Please enter your company name so we can better assist you?\n')) print('Great! Thank you,', company_name) #validate numeric value of requested input ft = input('Please enter the amount of fiber optic cable you need installed.\n') try: ft = int(ft) except: print('Please enter a numeric value.') #apply bulk discount rate "tier" using the ft input def bulk_cost(): tiers = [.87, .80, .70, .50] # Bulk discount cost tiers if ft <= 100: return tiers[0] elif ft <= 250: return tiers[1] elif ft <= 500: return tiers[2] elif ft >= 501: return tiers[3] #determine costs using bulk discount entered from customer def calc_cost(ft, bulk_cost): cost = float(ft * bulk_cost()) return cost #output receipt to customer print('Thank you, your order has been processed.\n') print('Company:', company_name) print('Fiber optic cable ordered (ft):',ft ) print('Your calculated cost:', ft, 'x', format(bulk_cost(),',.2f')) print('Your total installation cost: $', format(calc_cost(ft,bulk_cost),",.2f"))
eae6ea74f036fbe17160d935847cbafca07b7bd0
riemaxi/evolution
/inference/flatten.py
214
3.5625
4
#!/usr/bin/env python3 import sys print(next(sys.stdin).strip()) seq = '' for line in sys.stdin: if line.startswith('>'): print(seq) seq = '' print(line.strip()) else: seq += line.strip() print(seq)
e2f19eef4938055fa9c6ad6be6fb19e039f640bb
Mitchellb16/NeuroKit
/neurokit2/complexity/entropy_fuzzy.py
1,937
3.609375
4
# -*- coding: utf-8 -*- from .utils import _get_r, _phi, _phi_divide def entropy_fuzzy(signal, delay=1, dimension=2, r="default", **kwargs): """Fuzzy entropy (FuzzyEn) Python implementations of the fuzzy entropy (FuzzyEn) of a signal. This function can be called either via ``entropy_fuzzy()`` or ``complexity_fuzzyen()``. Parameters ---------- signal : Union[list, np.array, pd.Series] The signal (i.e., a time series) in the form of a vector of values. delay : int Time delay (often denoted 'Tau', sometimes referred to as 'lag'). In practice, it is common to have a fixed time lag (corresponding for instance to the sampling rate; Gautama, 2003), or to find a suitable value using some algorithmic heuristics (see ``delay_optimal()``). dimension : int Embedding dimension (often denoted 'm' or 'd', sometimes referred to as 'order'). Typically 2 or 3. It corresponds to the number of compared runs of lagged data. If 2, the embedding returns an array with two columns corresponding to the original signal and its delayed (by Tau) version. r : float Tolerance (i.e., filtering level - max absolute difference between segments). If 'default', will be set to 0.2 times the standard deviation of the signal (for dimension = 2). **kwargs Other arguments. Returns ---------- float The fuzzy entropy as float value. See Also -------- entropy_shannon, entropy_approximate, entropy_sample Examples ---------- >>> import neurokit2 as nk >>> >>> signal = nk.signal_simulate(duration=2, frequency=5) >>> entropy = nk.entropy_fuzzy(signal) >>> entropy #doctest: +SKIP """ r = _get_r(signal, r=r, dimension=dimension) phi = _phi(signal, delay=delay, dimension=dimension, r=r, approximate=False, fuzzy=True, **kwargs) return _phi_divide(phi)
44feedce7b25cd1531144706f23ed7016b423213
paulseward/kicad-strowger
/tools/circular-array.py
836
4.0625
4
#!/usr/bin/env python import math # Draw an arc of equally spaced circles arcRadius = 400 # Radius of the arc to place the circles on arcDegrees = 180 # Number of degrees to spread the circles over arcOffset = 0 # Angle to start from pinRadius = 7 # Radius of the circles pinCount = 25 # How many circles to place pinFill = '0' # not filled # pinFill = 'f' # filled with bg colour # pinFill = 'F' # filled with pen colour # Draw origin pin print("C 0 0 {} 1 0 N".format(pinRadius)) # arc of pins for pin in range(0,pinCount): angle = math.radians(arcOffset + (pin*arcDegrees/float(pinCount-1))) X = int(round(math.sin(angle)*arcRadius)) Y = int(round(math.cos(angle)*arcRadius)) # Draw the circle: # C X Y radius part dmg pen fill print("C {} {} {} 1 0 N".format(X,Y,pinRadius))
2ffe12ecc224dc3f545d32c67730736ed92245ad
simeiyu/python
/basic_knowledge/8.3-def.py
2,175
3.9375
4
''' 8.3 返回值 ---------- 函数返回的值被称为返回值。 在函数中,可使用return语句将值返回到调用函数的代码行。 返回值能够让你将程序的大部分繁重工作移到函数中去完成,从而简化主程序。 ''' # 简单返回值 def get_formatted_name(first_name, last_name): full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print(musician) # 让实参变成可选的 使用默认值让实参变成可选的 def get_formatted_name2(first_name, last_name, middle_name=''): if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name2('jimi', 'hendrix') print(musician) musician = get_formatted_name2('john', 'hooker', 'lee') print(musician) # 返回字典 函数可返回任何类型的值,包括列表和字典等较复杂的数据结构 def build_person(first_name, last_name, middle_name='', age=''): if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name person = {'name': full_name.title()} if age: person['age'] = age return person musician = build_person('jimi', 'hendrix', age=32) print(musician) # 结合使用函数和while循环 while True: f_name = input('First name: ') if f_name == 'q': break l_name = input('Last name: ') if l_name == 'q': break formatted_name = get_formatted_name2(f_name, l_name) print('\nHello, ' + formatted_name + '.') ''' 练一练 ''' def mark_album(name, editor, count=''): album = {'name': name, 'editor': editor} if count: album['count'] = count return album while True: print('请输入专辑名称和歌手名字,或键入"q"退出程序') name = input('专辑名称:') if name == 'q': break editor = input('歌手:') if editor == 'q': break marked_album = mark_album(name, editor) print('\nThis album is ' + str(marked_album))
cd4811040f6a3b74b75e1399056491b5aa7340a9
juliamoreira/trabs-fonfon
/bins.py
253
4.09375
4
numero = int(input('Digite um numero: ')) show = ' ' while numero != 0 : resto = numero % 2 if resto == 0: show = show + '0' else : show = show + '1' numero = numero // 2 print (show[::-1])
c94a63e3eb696050786b3da8141f6cfade884e61
eduardomendozavillar/PytohonEjer
/ejercicio3.py
240
3.921875
4
num1= int (input ("digite primer numero: ")) num2= int (input ("digite segundo numero: ")) if num1>num2: print (" el numero " , num1 , " es mayor " , num2) else: print (" el numero " , num2 , " es meyor " , num1)
c7104809dda861968fede8fffc2c2bd1431c19d8
ctrl-z-x-c/for_fun
/avoid balls.py
3,603
3.5625
4
import pygame import pygame.font from random import randint from math import sqrt #font1 = pygame.font.SysFont(None, 16) class Bullet(object): """子弹""" def __init__(self, x, y, radius, sx, sy): """初始化方法""" self.x = x self.y = y self.radius = radius self.sx = randint(0, 20) / 10 * ((sx - x) / ((sx - x) ** 2 + sy ** 2) ** (1 / 2)) self.sy = randint(0, 20) / 10 * ((sy - y) / (sx ** 2 + (sy - y) ** 2) ** (1 / 2)) self.alive = True def move(self, screen): """移动""" self.x += self.sx self.y += self.sy def draw(self, screen): """在窗口上绘制球""" pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), self.radius, 0) def outside(self, screen): if self.x < 0 or \ self.x > screen.get_width(): self.alive = False if self.y < 0 or \ self.y > screen.get_height(): self.alive = False def touch(self, x, y): if -10 < self.x - x < 10 and -10 < self.y - y < 10: exit() #self.alive = False def main(): bullets = [] pygame.init() screen = pygame.display.set_mode((800, 800)) pygame.display.set_caption('pygame') ss = 0 x = 400 y = 400 kr = False kl = False ku = False kd = False running = True while running: #surface1 = font1.render(u'当前得分:'+ss, True, [255, 0, 0]) #screen.blit(surface1, [20, 20]) pygame.display.flip() screen.fill((0, 242, 242)) pygame.draw.circle(screen, (255, 0, 0,), (x, y), 5) b_x = randint(0, 800) b_y = randint(0, 800) # aim_x = x-b_x/(x**2+y**2)**1/2 # if aim_x < 0: # aim_x = -aim_x # aim_y = y/(x**2+y**2)**1/2 if len(bullets) < 100: bullet = Bullet(b_x, 0, 5, x, y) bullets.append(bullet) bullet = Bullet(b_x, 800, 5, x, y) bullets.append(bullet) bullet = Bullet(0, b_y, 5, x, y) bullets.append(bullet) bullet = Bullet(800, b_y, 5, x, y) bullets.append(bullet) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: kr = True elif event.key == pygame.K_LEFT: kl = True elif event.key == pygame.K_UP: ku = True elif event.key == pygame.K_DOWN: kd = True elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: kr = False elif event.key == pygame.K_LEFT: kl = False elif event.key == pygame.K_UP: ku = False elif event.key == pygame.K_DOWN: kd = False if kr and x < 800: x += 5 if kl and x > 0: x -= 5 if ku and y > 0: y -= 5 if kd and y < 800: y += 5 for bullet in bullets: bullet.outside(screen) bullet.touch(x, y) if bullet.alive: bullet.move(screen) bullet.draw(screen) else: bullets.remove(bullet) ss += 1 print('sorce' + str(ss)) if __name__ == '__main__': main()
1dca63c8958ff10346f5b1221fc5d88a17bd3bb1
Sitych/wednesday18_00
/lesson5/3.py
765
3.546875
4
class SchoolClass: def __init__(self, students, name): self.stds = students self.name = name def math_mark(self, marks): self.mark = marks def sort_by_marks(self): for i in range(len(self.stds)): for f in range(len(self.stds) - 1): if self.mark[f] > self.mark[f + 1]: self.stds[f], self.stds[f + 1] = self.stds[f + 1] , self.stds[f] self.mark[f], self.mark[f + 1] = self.mark[f + 1] , self.mark[f] students = ["Кирилл", "Валера", "Egor", "Sasha"] python = SchoolClass(students, "11Е") python.math_mark([7, 5, 9, 6]) python.sort_by_marks() print(python.stds)
dbd4cbab74cdac47d5f60e1935f65ec33f0db640
sainihimanshu1999/Data-Structures
/Practice Ds - Prev/array_advance.py
316
3.578125
4
def array_advance(A): furthest_reached = 0 last_indx = len(A) - 1 i = 0 while i <= furthest_reached and furthest_reached < last_indx: furthest_reached = max(furthest_reached, A[i]+i) i += 1 return furthest_reached >= last_indx B = [3, 0, 0, 0, 2, 0, 1] print(array_advance(B))
14864988893cab219cb0e757fc466a3a2b810aa5
nravesz/Listas-Enlazadas
/DobleEnlazada.py
1,667
3.84375
4
class Nodo: def __init__(self,dato,prox=None,ant=None): self.dato=dato self.prox=prox self.ant=ant class ListaDoble: def __init__(self): """Crea una lista doble enlazada vacía""" self.prim = None self.len = 0 def append(self,dato): """Agrega un nodo al final de la lista""" if self.len == 0: self.prim = Nodo(dato) else: nodo = self.prim while nodo.prox!=None: nodo = nodo.prox' nodo.prox = Nodo(dato) def insert(self,dato,pos) """Recibe un dato y una posición e inserta el nodo en la posición correspondiente""" if pos == self.len: self.append(dato) else: for i in range(pos-1): nodo = nodo.prox anterior = nodo prox = nodo.prox nodo_nuevo = Nodo(dato,prox,anterior) def pop(self,pos): """Recibe una posición, elimina el nodo que se encuentra ahí y devuelve el dato""" nodo = self.prim if pos==0: dato = nodo.dato nodo_sig = nodo.prox nodo_sig.ant = None self.prim = nodo_sig elif pos == self.len-1: while nodo.prox!=None: nodo = nodo.prox dato = nodo.dato nodo_anterior = nodo.ant nodo_anterior = None else: for i in range(pos-1): nodo = nodo.prox dato = nodo.prox.dato nodo_siguiente = nodo.prox.prox nodo_siguiente.ant = nodo nodo.prox = nodo_siguiente return dato
0479210b349d9648dac093912a59ad97e230aaa0
marcovankesteren/MarcovanKesteren_V1B
/Les5/pe5_5.py
371
3.65625
4
def gemiddelde(): willekeurigeZin = input('Voer een willekeurige zin in: ') alleWoorden = willekeurigeZin.strip().split() aantalWoorden = len(alleWoorden) accumulator = 0 for woord in alleWoorden: accumulator += len(woord) print('De gemiddelde lengte van de woorden in deze zin is: {}'.format(accumulator/aantalWoorden)) gemiddelde()
d4ba4f0a72a7ca4cf0b5c1b90eab117d7d169448
JeffreyAsuncion/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/chinook_class_queries.py
3,326
3.84375
4
""" ## TablePlus and DB Brower for sqlite3 ## PgAdmin for PostgreSQL """ query = """ SELECT CustomerId, LastName FROM customers WHERE State = 'CA'; """ # -- who are our customers? (59) query = """ SELECT CustomerId ,FirstName ,LastName FROM customers; """ # -- which customers are from the US? (13) query = """ SELECT CustomerId ,FirstName ,LastName FROM customers WHERE Country = "USA"; """ # -- example of ORDER BY (16) query = """ SELECT * FROM customers WHERE Country in ("USA", "United Kingdom") ORDER BY Country ASC, State DESC; -- ASC is the default """ # --can I have a list of email address for all customers who live in the US? # -- 59 rows (one per customer) # -- 13 rows (one per customer, only those in the US) query = """ SELECT CustomerId ,FirstName ,LastName ,Email ,Country FROM customers WHERE Country = "USA"; """ # -- how many customers do we have? query = """ SELECT count(*) as customer_count -- counts number of rows (59) ,count(CustomerId) as customer_count2 -- counts number of rows (59) ,count(DISTINCT CustomerId) as customer_count_3 ---> counts actual unique values FROM customers; """ # -- how many customers are from the US? query = """ SELECT count(DISTINCT CustomerId) FROM customers WHERE Country = "USA"; """ # -- how many customers in each country? query = """ SELECT Country ,count(distinct CustomerId) as customer_count ---> (59) FROM customers GROUP BY Country; """ #-- which 5 countries have the most customers? (makes a nice chart) query = """ SELECT Country ,count(distinct CustomerId) as customer_count ---> (59) FROM customers GROUP BY Country ORDER BY customer_count DESC LIMIT 5; """ #-- on average, how many customers in each country? query = """ SELECT AVG(customer_count) --> (2.45) FROM ( SELECT Country ,COUNT(DISTINCT CustomerId) as customer_count -- > 59 FROM customers GROUP BY Country ) subq; """ # -- Multi-Table SQL # -- for each album, what is the name of the artist # -- 347 rows (row per album) query = """ SELECT albums.AlbumId ,albums.Title ,artists.Name FROM albums JOIN artists ON albums.ArtistId = artists.ArtistId; """ # -- for each artist, # -- how many albums? # -- and how many tracks? # -- row per artist (275) # -- row per artist (204???) bay_query = """ SELECT artists.ArtistId ,artists.Name ,count(DISTINCT albums.AlbumId) as AlbumCount ,count(DISTINCT tracks.TrackId) as TrackCount FROM artists JOIN albums ON artists.ArtistId = albums.ArtistId JOIN tracks ON tracks.AlbumId = albums.AlbumId GROUP BY artists.ArtistId; """ # -- for each artist, # -- how many albums? # -- and how many tracks? # -- row per artist (275) analyze_ba_query = """ SELECT artists.ArtistId ,artists.Name as ArtistName ,albums.AlbumId ,tracks.TrackId FROM artists LEFT JOIN albums ON artists.ArtistId = albums.ArtistId LEFT JOIN tracks ON albums.AlbumId = tracks.AlbumId; """ # -- for each artist, # -- how many albums? # -- and how many tracks? # -- row per artist (275) # -- row per artist (204???) fixed_bad_query = """ SELECT artists.ArtistId ,artists.Name ,count(DISTINCT albums.AlbumId) as AlbumCount ,count(DISTINCT tracks.TrackId) as TrackCount FROM artists LEFT JOIN albums ON artists.ArtistId = albums.ArtistId LEFT JOIN tracks ON albums.AlbumId = tracks.AlbumId GROUP BY artists.ArtistId; """
04e1b827a4660a3d01ca97573146a303e23b2c54
Oliveira-Js/Python
/Python/004.py
234
4.0625
4
print("Multiplicando 2 números em python!") n1 = int(input("Digite um número: ")) n2 = int(input("Digite outro número: ")) multiplicacao = n1 * n2 print("A multiplicação entre {} e {} é igual a {}!".format(n1,n2,multiplicacao))
43ba82629b772a7ceb2b43515631aaae1366c60e
MariVM/Python
/lesson12_1.py
424
3.75
4
import random dishes_string = input('What would you like? ') # This is a string #dishes_string = 'eggs, spam, eggs, spam, tomato juice, spam' if len(dishes_string): print('Please see time to cook dishes: ') #dishes_list = set(dishes_string.split(' ')) #dishes = [] dishes = [print(dishes.title().strip().capitalize(), '.' * (30-len(dishes)), random.randint (0, 60), 'min') for dishes in set(dishes_string.split(' '))]
be27a91563288aeb290ae27a64ff9096bd6ada18
Lwk1071373366/zdh
/S20/day02/01格式化输出.py
1,151
3.625
4
# # name = input('请输入姓名:') # age = input('请输入年龄:') # job = input('请输入工作:') # hobby = input('请输入爱好:') # # # # # msg = '''------userinfo of %s------ # Name :%s # Age : %d # job : %s # Hobby :%s # -----end-----''' %(name,name,int(age),job,hobby) # print(msg) # msg = '我的姓名是%s,我的年龄是%s,我的学习进度是0.5%%' %('李',30) # print(msg) # 利用while 循环打印 1-100 # count = 1 # flag = True # while flag: # print(count) # count = count + 1 # if count == 101 : # flag = False # 打印1-100所以偶数 # count = 2 # flag = True # while flag: # print(count) # count = count +2 # if count == 102: # break # # # #计算1+2+...100 # count = 1 # s = 0 # while True: # s = s +count # count = count +1 # if count > 100: # break # # print(s) # # # # 老师方法: # s = 0 # count = 1 # while count < 101: # s = s + count # count = count + 1 # print(s) # count = 1 # # while count <101 : # print(count) # count = count + 1 # count = 2 # while count < 102: # print(count) # count = count +2
d156d7d1b4fa4edc4377304d44130e3747b6efc9
mrfawy/ModernEnigma
/RandomGenerator.py
694
3.5625
4
from random import Random from CharIndexMap import CharIndexMap """This class is to abstract random generation , as Per protocol specs we will need to implement certain Secure Random Generator for now it just wrapps python Random Class which is based on PRNG of Mersenne twister """ class RandomGenerator(object): def __init__(self,seed=None): self.random=Random() if seed: self.random.seed(seed) def seed(self,seed): self.random.seed(seed) def sample(self,seq,k): return self.random.sample(seq,k) def nextInt(self,a=0,b=None): if not b: b=CharIndexMap.getRangeSize()-1 return self.random.randint(a,b)
cc52f74ff9015be1d1dfd4b4bb3ac8db94aaa340
gghezzo/prettypython
/PythonEveryDay2015/FindingPrimes.py
814
4.0625
4
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10,001st prime number? # http://nbviewer.ipython.org/gist/rpmuller/5920182 # Typer: Ginny C Ghezzo # What I learned: Python was silly to change things like range. Python is very picky about types, # Retur a list of prime nubmers from 2 to < n def primes(n): if n==2: return[2] elif n<2: return[] s=list(range(3, n+1, 2)) # range(start, stop, step) mroot = n ** 0.5 half = (n+1)/2-1 # round down I guess i = 0 m = 3 while m <= mroot: if s[i]: # not sure, does this check if it is in range j=int((m*m-3)/2) s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x] num = input("What numer do you want to check?") print(primes(int(num)))
4586b18e896d2cc8f0fb06d3b595554e20cd757d
luisfsangil/Tutorial-Python
/2.Python_Functions/main.py
91
3.5625
4
def sum(_n1,_n2): n1=_n1 n2=_n2 return (n1+n2) print(sum(5,5)) print(sum(2,3))
7d4d02ad293f0d44f0beeb63bca898ff73f9fc25
seohyoj55/Baekjoon
/python/13015.py
1,176
3.953125
4
n = int(input()) for j in range(0, n): print('*', end='') for k in range(2*n -3): print(' ', end='') for j in range(0, n): print('*', end='') print() for i in range(0, n - 2): for j in range(0, i+1): print(' ', end='') print('*', end='') for k in range(0, n-2): print(' ', end='') print('*', end='') for j in range(0, (n-i)*2 - 5): print(' ', end='') print('*', end='') for k in range(0, n-2): print(' ', end='') print('*') for i in range(0, n-1): print(' ', end='') print('*', end='') for i in range(0, n-2): print(' ', end='') print('*', end='') for i in range(0, n-2): print(' ', end='') print('*') for i in range(0, n - 2): for j in range(0, n-i-2): print(' ', end='') print('*', end='') for k in range(0, n-2): print(' ', end='') print('*', end='') for j in range(0, i*2+1): print(' ', end='') print('*', end='') for k in range(0, n-2): print(' ', end='') print('*') for j in range(0, n): print('*', end='') for k in range(2 * n - 3): print(' ', end='') for j in range(0, n): print('*', end='') print()
88979af275f2562c8d3a08ceccbc98dbd0eef489
JonathanKBP/data_science_algebra_linear
/aula.py
4,136
3.78125
4
import math heigth_weight_age = [ 170, 70, 40 ] grades = [ 95, 90, 75, 62 ] def vector_add (v, w): #v = [1, 2, 3] #w = [4, 5, 6] #zip (v, w) = [(1, 4), (2, 5), (3, 6)] return [v_i + w_i for v_i, w_i in zip (v, w)] def vector_add_test (): v = [5, 4] w = [2, 1] r = vector_add (v, w) print (r) def vector_subtract (v, w): return [v_i - w_i for v_i, w_i in zip (v, w)] def vector_subtract_test (): v = [5, 4] w = [2, 1] r = vector_subtract (v, w) print (r) def vector_sum (vectors): result = vectors[0] for vector in vectors[1:]: result = vector_add (result, vector) return result def vector_sum_test (): v1 = [1, 2, 5, 6] v2 = [4, 3, 2, 1] v3 = [1, 1, 1, 1] r = vector_sum ([v1, v2, v3]) print (r) def scalar_multiply (c, v): return [c * v_i for v_i in v] def scalar_multiply_test (): c = 5 v = [4, 1, 2, 5] r = scalar_multiply (c, v) print (r) def vector_mean (vectors): n = len (vectors) return scalar_multiply (1 / n, vector_sum(vectors)) def vector_mean_test (): v1 = [1, 2, 5, 6] v2 = [4, 3, 2, 1] v3 = [1, 1, 1, 1] r = vector_mean ([v1, v2, v3]) print (r) def dot (v, w): #v = [1, 2, 5] #w = [3, 2, 1] #dot (v, w) = 1 * 3 + 2 * 2 + 5 * 1 = 12 return sum([v_i * w_i for v_i, w_i in zip (v, w)]) def dot_test (): v = [1, 2, 5] w = [3, 2, 1] r = dot (v, w) print (r) def sum_of_squares (v): #v = [1, 2, 3] #sum_of_squares(v) = 1 * 1 + 2 * 2 + 3 * 3 = 1 + 4 + 9 = 14 return dot (v, v) def sum_of_squares_test (): v = [1, 2, 3] r = sum_of_squares(v) print (r) def magnitude(v): return math.sqrt(sum_of_squares(v)) def magnitude_test (): v = [1, 2, 3] r = magnitude (v) print (r) def squared_distance (v, w): #v = [1, 2] #w = [3, 5] #vector_subtract(v, w) = [-2, -3] #sum_of_squares(vector_subtract(v,w)) = (-2 * -2) + (-3 * -3) = 4 + 9 = 13 return sum_of_squares(vector_subtract (v, w)) def squared_distance_test (): v = [1, 2] w = [3, 5] r = squared_distance (v, w) print (r) def distance (v, w): return math.sqrt(squared_distance(v, w)) def distance_test (): v = [1, 2] w = [3, 5] r = distance (v, w) print (r) def distance_test2 (): u1 = [27, 80, 180] u2 = [58, 100, 198] u3 = [29, 79, 179] print (f'u1 vs u2: {distance (u1, u2)}') print(f'u1 vs u3: {distance (u1, u3)}') print(f'u2 vs u3: {distance (u2, u3)}') def qtde_amigos_minutos_passados (): return ([1, 10, 50, 2, 150], [5, 200, 350, 17, 1]) def variance (v): mean = sum(v) / len(v) return[v_i - mean for v_i in v] def variance_test(): v = [1, 2, 3] r = variance (v) print (r) def covariance (x, y): n = len(x) return dot (variance(x), variance(y)) / (n - 1) def covariance_test (): x = [3, 12, 3] y = [1, 7, 4] print (f'covariancia: {covariance(x, y)}') def correlation (x, y): desvio_padrao_x = math.sqrt (sum_of_squares (variance(x)) / (len(x) - 1)) desvio_padrao_y = math.sqrt(sum_of_squares(variance(y)) / (len(y) - 1)) if desvio_padrao_x > 0 and desvio_padrao_y > 0: return covariance(x, y) / desvio_padrao_y / desvio_padrao_x else: return 0 def correlation_test (): x = [3, 12, 3] y = [1, 7, 4] print (f'correlation: {correlation(x, y)}') x = [-1, 8, 11] y = [8, 2, 24] print(f'correlation: {correlation(x, y)}') x = [8, 6, 4] y = [2, 6, 4] print(f'correlation: {correlation(x, y)}') def correlation_test_with_outlier(): data = qtde_amigos_minutos_passados() resultado = correlation(data[0], data[1]) print(resultado) def correlation_test_without_outlier (): data = qtde_amigos_minutos_passados() resultado = correlation(data[0][:len(data[0])-1], data[1][:len(data[1])-1]) print (resultado) def main(): print (correlation_test_without_outlier()) #correlation_test_with_outlier() #correlation_test() #covariance_test() #variance_test() #distance_test2() # distance_test() #squared_distance_test() #print (magnitude_test()) #sum_of_squares_test() #dot_test() #vector_mean_test() #scalar_multiply_test() #vector_sum_test() #vector_subtract_test() #vector_add_test() main()
615fc16769e331e90b56b098b97ff9a1e665e037
jackketteler/Jack-Ketteler
/calculator JACK.py
1,261
4.1875
4
# Calculator import math import random from math import sqrt def welcome(): menu=input('''Welcome to your destiny my child... Press 1 for basic operations Press 2 for more advanced math operations ''') if menu=='1': calculate_basic() elif:menu=='2': calculate_adv() def calculate_basic(): operation= input(''' Please type the math operation you want to complete + for addition - for subtraction * for multiplication % for modulus / regular division // integer division ''') firstNumber=float(input("Please enter the first number")) secondNumber = float(input("Please enter the second number")) if operation =='+': print('{}+{}='.format(firstNumber, secondNumber)) print(firstNumber+secondNumber) elif operation == '-': print('{}-{}='.format(firstNumber, secondNumber)) print() else: print("You have not typed a valid operator. Run the program again") runAgain() def runAgain(): again= input('''Do you want to calculate this again? Y/N''') if again.upper()="Y": print() welcome() elif again.upper()=="N": print("Exit") else: runAgain() Welcome()
3e85229a34b1017112d1dd6ba9726b5cf90fe10d
mrayeung/pdsnd_github
/bikesharing/bikeshare.py
12,978
4.09375
4
import time import pandas as pd import numpy as np from datetime import datetime import datetime as dt #New Comment CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def sweek(i): switcher={ 0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday', 5:'Friday', 6:'Saturday' } return switcher.get(i,"Invalid day of week") def smonth(i): switcher={ 1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December' } return switcher.get(i,"Invalid month") def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print ("Hello Lets explore some US bikeshare data") # Get user input for city (chicago, new york city, washington) with exception handling while True: try: city = input ("Enter name of city: ") city = city.lower() if (city == 'chicago') or (city == 'new york city') or (city == 'washington'): break else : print("Oops! We don\'t have data for this city yet. Please try again...") except : print('An error occurred.') # Get user input for month (all, january, february, ... , june)) with exception handling while True: try: month = input ("Enter specific month to filter (ie. January or All): ") month = month.lower() if (month == 'january') : month = 1 break elif (month == 'february') : month = 2 break elif (month == 'march') : month = 3 break elif (month == 'april') : month = 4 break elif (month == 'may') : month = 5 break elif (month == 'june') : month = 6 break elif (month == 'july') : month = 7 break elif (month == 'august') : month = 8 break elif (month == 'september') : month = 9 break elif (month == 'october') : month = 10 break elif (month == 'november') : month = 11 break elif (month == 'december') : month = 12 break elif (month == 'all') : month = 0 break else : print("Oops! Invalid Input. Please try again...") except : print('An error occurred.') # Get user input for day of week (all, monday, tuesday, ... sunday) with exception handling while True: try: day = input ("Enter specific day to filter (ie. Monday or All): ") day = day.lower() if (day == 'monday') : day = 1 break elif (day == 'tuesday') : day = 2 break elif (day == 'wednesday') : day = 3 break elif (day == 'thursday') : day = 4 break elif (day == 'friday') : day = 5 break elif (day == 'saturday') : day = 6 break elif (day == 'sunday'): day = 7 break elif (day == 'all'): day = 0 break else : print("Oops! Invalid Input. Please try again...") except : print('An error occurred.') print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ df = pd.read_csv(CITY_DATA[city]) if df.isnull().values.any(): print ('There is NAN record!') df.dropna() print ('Data is clean NOW!') else: print ('Data is clean!') if df.empty == True: print('No Records Returned!! Please try again...') if (month == 0) and (day == 0) : print ('Applying no filter on month and day...') return df elif (month > 0) and (day == 0) : print ('Applying filter on month only...') df['month'] = pd.to_datetime(df['Start Time']) df=df.loc[df['month'].dt.month==month] return df elif (month == 0) and (day > 0) : print ('Applying filter on day only...') df['day'] = pd.to_datetime(df['Start Time']) df=df.loc[df['day'].dt.weekday==day] return df elif (month > 0) and (day > 0): print ('Applying filter on month and day...') df['both'] = pd.to_datetime(df['Start Time']) df=df.loc[df['both'].dt.month==month] df=df.loc[df['both'].dt.weekday==day] return df else : print("Oops! Invalid Input. Please try again...") def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() df['dtime'] = pd.to_datetime(df['Start Time']) # Find the most occurance for month cm_month = int(df['dtime'].dt.month.mode()) # Count the occurance for month month_count = df['dtime'].dt.month.value_counts() # Find the most occurance for day of week cm_wday = int(df['dtime'].dt.weekday.mode()) # Count the occurance for day of week wday_count = df['dtime'].dt.weekday.value_counts() # Find the most occurance for hour of day cm_hour = int(df['dtime'].dt.hour.mode()) # Count the occurance for hour of day hour_count = df['dtime'].dt.hour.value_counts() # TO DO: display the most common month print ("Most common month: ", smonth(cm_month), " Count: ", month_count[cm_month] ) # TO DO: display the most common day of week print ("Most common day: ", sweek(cm_wday), " Count: ", wday_count[cm_wday] ) # TO DO: display the most common start hour print ("Most common start hour: ", cm_hour , " Count: ", hour_count[cm_hour] ) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station # Find the occurance of each start station cm_start_st = df["Start Station"].value_counts() # Count the most occurance for start station start_count = cm_start_st.max() # Lookup the start station name based on the count start_stn = cm_start_st.loc[cm_start_st.values==start_count].index[0] print ("Most commonly used start station: ",start_stn , " Count: ", start_count ) # TO DO: display most commonly used end station # Find the occurance of each end station cm_end_st = df["End Station"].value_counts() # Count the most occurance for end station end_count = cm_end_st.max() # Lookup the end station name based on the count end_stn = cm_end_st.loc[cm_end_st.values==end_count].index[0] print ("Most commonly used end station: ", end_stn , " Count: ", end_count ) # TO DO: display most frequent combination of start station and end station trip df["Trip"]=df["Start Station"]+" TO "+df["End Station"] # Find the occurance of each trip cm_trip = df["Trip"].value_counts() # Count the most occurance for each trip trip_count = cm_trip.max() # Lookup the trip name based on the count trip_stn = cm_trip.loc[cm_trip.values==trip_count].index[0] print ("Most commonly trip is: ", trip_stn , " Count: ", trip_count ) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() sum_time=dt.timedelta() mean_time=dt.timedelta() ttime=dt.timedelta() # Display total travel time df['duration'] = pd.to_datetime(df['End Time'])-pd.to_datetime(df['Start Time']) for i in df['duration']: i=str(i) temp = i.replace(i[:7], '') (h,m,s) = temp.split(':') d = dt.timedelta(hours=int(h), minutes=int(m), seconds=int(s)) sum_time = sum_time+d print ("Total Travel Time: ", str(sum_time)) # Display mean travel time mean_time=sum_time/df['duration'].count() print("Avg Travel Time: ", mean_time) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types if 'User Type' in df.columns: cm_type = df["User Type"].value_counts() # Count the most occurance for gender type_count = cm_type.max() # Lookup the gender based on the count usertype = cm_type.loc[cm_type.values==type_count].index[0] print ("Most common user type: ", usertype , " Count: ", type_count ) else : print('** Warning! Missing User Type Data!') # Display counts of gender if 'Gender' in df.columns: # Find the occurance of gender cm_sex = df["Gender"].value_counts() # Count the most occurance for gender sex_count = cm_sex.max() # Lookup the gender based on the count gender = cm_sex.loc[cm_sex.values==sex_count].index[0] print ("Most commonly gender: ", gender , " Count: ", sex_count ) else : print('** Warning! Missing Gender Data!') # Display earliest, most recent, and most common year of birth if 'Birth Year' in df.columns: byear_early = df["Birth Year"].min() byear_recent = df["Birth Year"].max() # Count the most occurance for birth year cm_byear = df["Birth Year"].mode() print ("Earliest birth year: ", int(byear_early) ) print ("Most recent birth year: ", int(byear_recent) ) print ("Most common year of birth: ", int(cm_byear) ) else : print('** Warning! Missing Birth Year Data!') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) c = 0 datacount=df.shape[0] if int(datacount) > 0: while True: raw_view = input('\nWould you like to preview raw data? (Enter yes or no): ') if raw_view.lower() == 'yes': num_row = input('How many row(s) you like to see? (Enter a number): ') if int(num_row) > int(datacount): print('Error! Input exceed number of row in data file!') else: while c < int(num_row): print(df.iloc[c],'\n') c+=1 elif raw_view.lower() == 'no': break time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) else: print('\nError! No Data Records Returned. Try again...') restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
ed5646504738954404aed1d9410219c39c668e4e
David-V-McIntyre/Day2_lists_homework
/day_02/start_point/exercise_a_stops.py
1,768
4.5
4
stops = [ "Croy", "Cumbernauld", "Falkirk High", "Linlithgow", "Livingston", "Haymarket" ] print(stops) print("This is the list with no alterations") print(" ") #1. Add "Edinburgh Waverley" to the end of the list stops.append("Edinburgh Waverley") print(stops) print("this is the list of stops with waverley added!") print(" ") #2. Add "Glasgow Queen St" to the start of the list stops.insert(0, "Glasgow Queen St") print(stops) print("this is the list of stops with GSQ added!") print(" " ) #3. Add "Polmont" at the appropriate point (between "Falkirk High" and "Linlithgow") stops.insert(4, "Polmont") print(stops) print("this is the list of stops with Polmont added between Falkirk High and Linlithgow!") print(" ") #4. Print out the index position of "Linlithgow" item = "Linlithgow" index = stops.index(item) print(index) print("this is supposed to be the index position of Linlithgow!") print(" ") # very very stuck on how to do this #5. Remove "Livingston" from the list using its name stops.remove("Livingston") print(stops) print("this is the list with Livingston removed!") print(" ") #6. Delete "Cumbernauld" from the list by index stops.remove(stops[2]) print(stops) print("This is the list with Cumbernauld removed by it's index number!") print(" ") #7. Print the number of stops there are in the list print(len(stops)) print("this is the number of stops in the list!") print(" ") #8. Sort the list alphabetically sorted(stops) print(sorted(stops)) print("This is the list organised alphabetically!") print(" ") #9. Reverse the positions of the stops in the list reversed_list = stops[::-1] print(reversed_list) print("This is the list of stops reversed!") print(" ") #10 Print out all the stops using a for loop for stop in stops: print(stop)
58820751e3a2b0029f0cf56b7392ee3d3a7275ca
ChicksMix/programing
/unit 5/Hicksrandom.py
392
4.1875
4
#Carter Hicks #1/19/18 import random h= int(input("Enter the highest possible value for the number: ")) l= int(input("Enter the lowest possible value for the number: ")) num1 = 0 num2 = 0 num3 = 0 while num1== num2 or num1== num3 or num2 == num3 : num1 = random.randrange(l,h) num2 = random.randrange(l,h) num3 = random.randrange(l,h) print num1,",",num2,",",num3
6ae27e7b2ea4977130aad7f36b541bd7c5e60ded
cszhu/exercism_python
/pangram/pangram.py
241
3.828125
4
def is_pangram(sentence): alphabet = [] sentence = sentence.lower() for c in sentence: if c not in alphabet and c.isalpha(): alphabet.append(c) if len(alphabet) == 26: return True return False
e12acf8eb99c76eddb187d77db0b2285d7857186
gitshangxy/tutorial
/L2基础类型控制语句/11 continue.py
363
3.8125
4
# 循环中断之continue while True: s = input('随便输入点什么:') if len(s) < 3: print('太短了,请输入三个以上字符的内容。') continue print('你输入的内容是:{},长度是{}'.format(s, len(s))) #continue: 中断一次循环,但没有跳出循环语句块,下次循环正 # 场景:清洗数据
633ade87e1c95aa15109d3abeb20548222664b28
chrisesharp/aoc-2020
/day6/groups.py
738
3.703125
4
def count_questions(group): answers = set() for line in group.split(): for answer in line: answers.add(answer) return len(answers) def count_common(group): participants = group.split() answers = {} for line in participants: for answer in line: answers[answer] = answers.get(answer, 0) + 1 return sum([1 for count in answers.values() if count == len(participants)]) def total_yes(codes): return sum(map(count_questions, codes.split("\n\n"))) def common_yes(codes): return sum(map(count_common, codes.split("\n\n"))) if __name__ == '__main__': data = open("input.txt","r").read() print("Part 1:", total_yes(data)) print("Part 2:", common_yes(data))
c5c9fb8ff6baa3576738cbb15f0978e189648813
BA-CalderonMorales/DebuggingProject
/dCC_Python_SodaMachine/wallet.py
1,047
3.625
4
from dCC_Python_SodaMachine import coins class Wallet: def __init__(self): self.money = [] # AttributeError: 'Wallet' had a missing attribute in 'fill_wallet' error was due to scope. # Sometimes, devs forget that having the methods left justified instead of inline with the # scope of each method can lead to this error. def fill_wallet(self): """Method will fill wallet's money list with certain amount of each type of coin when called.""" # Missing import: from dCC_Python_SodaMachine import coins for index in range(8): self.money.append(coins.Quarter()) for index in range(10): self.money.append(coins.Dime()) for index in range(20): self.money.append(coins.Nickel()) for index in range(50): self.money.append(coins.Penny()) # Missing return statement. Needs to return the money in the current wallet # Will just return the wallet with the money[] list. return self.money
c1a5fdf014c213a12eebec5a49436bdd44bd3486
ichinichichi/06-homework
/Dataset TWO - Dogs.py
8,080
3.96875
4
#!/usr/bin/env python # coding: utf-8 # # Homework 6, Part Two: A dataset about dogs. # # Data from [a FOIL request to New York City](https://www.muckrock.com/foi/new-york-city-17/pet-licensing-data-for-new-york-city-23826/) # ## Do your importing and your setup # In[1]: import pandas as pd import numpy as np pd.set_option("display.max_columns",100) pd.set_option("display.max_rows",100) # ## Read in the file `NYC_Dog_Licenses_Current_as_of_4-28-2016.xlsx` and look at the first five rows # In[2]: df = pd.read_excel("NYC_Dog_Licenses_Current_as_of_4-28-2016.xlsx") df.head(5) # ## How many rows do you have in the data? What are the column types? # # If there are more than 30,000 rows in your dataset, go back and only read in the first 30,000. # In[3]: len(df) # In[4]: df.dtypes # ## Describe the dataset in words. What is each row? List two column titles along with what each of those columns means. # # For example: “Each row is an animal in the zoo. `is_reptile` is whether the animal is a reptile or not” # The dataset describes dog licensing data in New York City along with the dog name under `Animal Name `, the gender of the dog under `Animal Gender `. The column `Vaccinated ` answers the questions whether the dog got vaccinated with a **Yes** or **No**. # # Each row describes a single dog and its data. # # Your thoughts # # Think of four questions you could ask this dataset. **Don't ask them**, just write them down in the cell below. Feel free to use either Markdown or Python comments. # 1. What dog breed is the most populat one? # 2. What are the most popular dog names in New York City? # 3. Which breed of dogs are spayed or neutered the most? # 4. Were do most dog owners live? # # Looking at some dogs # ## What are the most popular (primary) breeds of dogs? Graph the top 10. # In[5]: df["Primary Breed"].value_counts().head(10).plot(kind='bar') # ## "Unknown" is a terrible breed! Graph the top 10 breeds that are NOT Unknown # In[6]: df[df["Primary Breed"]!="Unknown"]["Primary Breed"].value_counts().head(10).plot(kind='bar') # ## What are the most popular dog names? # In[7]: df[df["Animal Name"]!="UNKNOWN"]["Animal Name"].value_counts().head(10).plot(kind='bar') # ## Do any dogs have your name? How many dogs are named "Max," and how many are named "Maxwell"? # In[8]: df[df["Animal Name"].str.contains("^MAX$", case=False,na= False)]["Animal Name"].count() # 652 dogs have the name Max. # In[9]: df[df["Animal Name"].str.contains("^MAXWELL$", case=False,na= False)]["Animal Name"].count() # 37 dogs have the name Maxwell. # ## What percentage of dogs are guard dogs? # # Check out the documentation for [value counts](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html). # In[10]: df["Guard or Trained"].value_counts(normalize=True) # 0,1029% od the dogs are guard dogs. # ## What are the actual numbers? # In[11]: df["Guard or Trained"].value_counts() # 51 dogs are guard dogs. # ## Wait... if you add that up, is it the same as your number of rows? Where are the other dogs???? How can we find them?????? # # Use your `.head()` to think about it, then you'll do some magic with `.value_counts()` # In[12]: df["Guard or Trained"].value_counts(dropna=False) # It is less than the numbers of rows since there are also missing values. # ## Fill in all of those empty "Guard or Trained" columns with "No" # # Then check your result with another `.value_counts()` # In[13]: df["Guard or Trained"]=df["Guard or Trained"].replace( np.nan, 'No') # In[14]: df["Guard or Trained"].value_counts(dropna=False) # ## What are the top dog breeds for guard dogs? # In[15]: df[df["Guard or Trained"]=='Yes']["Primary Breed"].value_counts() # ## Create a new column called "year" that is the dog's year of birth # # The `Animal Birth` column is a datetime, so you can get the year out of it with the code `df['Animal Birth'].apply(lambda birth: birth.year)`. # In[16]: df['year']=df['Animal Birth'].apply(lambda birth: birth.year) # ## Calculate a new column called “age” that shows approximately how old the dog is. How old are dogs on average? # In[17]: df['age']=2021-df.year # # Joining data together # ## Which neighborhood does each dog live in? # # You also have a (terrible) list of NYC neighborhoods in `zipcodes-neighborhoods.csv`. Join these two datasets together, so we know what neighborhood each dog lives in. **Be sure to not read it in as `df`, or else you'll overwrite your dogs dataframe.** # In[18]: df_zip= pd.read_csv('zipcodes-neighborhoods.csv') df= df.merge(df_zip, left_on="Owner Zip Code", right_on="zip", how="outer") df=df.drop(columns=['zip']) df.sample(5) # ## What is the most popular dog name in all parts of the Bronx? How about Brooklyn? The Upper East Side? # In[19]: df[df.borough=='Bronx']["Animal Name"].value_counts().head(1) # The most popular dog name in the Bronx is Rocky. # In[20]: df[df.borough=='Brooklyn']["Animal Name"].value_counts() # The most popular dog name in Brooklyn is Max. # In[21]: df[df.neighborhood=="Upper East Side"]["Animal Name"].value_counts().head(1) # The most popular dog name in the Upper East Side is Lucy. # ## What is the most common dog breed in each of the neighborhoods of NYC? # In[22]: df[df["Primary Breed"]!="Unknown"] .groupby(by="neighborhood")["Primary Breed"] .value_counts().groupby(by='neighborhood').nlargest(1) # ## What breed of dogs are the least likely to be spayed? Male or female? # In[23]: df[df["Spayed or Neut"]=="Yes"]["Primary Breed"].value_counts().tail(20) # ## Make a new column called monochrome that is True for any animal that only has black, white or grey as one of its colors. How many animals are monochrome? # In[24]: df["Monochrome"]= ( (df['Animal Dominant Color'].str.lower().isin(['black', 'white' ,'grey', 'gray']) | df['Animal Dominant Color'].isna() ) & (df['Animal Secondary Color'].str.lower().isin(['black', 'white' ,'grey','gray']) | df['Animal Secondary Color'].isna() ) & (df['Animal Third Color'].str.lower().isin(['black', 'white' ,'grey','gray']) | df['Animal Third Color'].isna() ) ) # In[25]: df.sample(5) # loc is used to Access a group of rows and columns by label(s) or a boolean array # # As an input to label you can give a single label or it’s index or a list of array of labels # # Enter all the conditions and with & as a logical operator between them # ## How many dogs are in each borough? Plot it in a graph. # In[26]: df.borough.value_counts(dropna=False).plot(kind='barh',title='Dog Count in each borough') # ## Which borough has the highest number of dogs per-capita? # # You’ll need to merge in `population_boro.csv` # In[27]: df_pop=pd.read_csv("boro_population.csv") # In[28]: dogcount=df.groupby(by='borough').size().reset_index() dogcount=dogcount.merge(df_pop, on='borough',how='outer') # In[29]: dogcount["Dogs per-capita"]=dogcount[0]/dogcount["population"] # In[30]: dogcount.sort_values(by="Dogs per-capita", ascending= False).head(1).borough # Manhattan has the highest number of dogs per-capita. # `size` includes **NaN** values, `count` does not. # ## Make a bar graph of the top 5 breeds in each borough. # # How do you groupby and then only take the top X number? You **really** should ask me, because it's kind of crazy. # In[31]: top5= df[df["Primary Breed"]!="Unknown"] .groupby(by="borough")["Primary Breed"] .value_counts().groupby(level=0, group_keys=False).nlargest(5) .to_frame(name='breed counts').reset_index() top5 # `group_keys=False` to avoid the double columns. `to_frame(name='breed counts').reset_index()` # In[32]: pivot_df = top5.pivot(index='borough', columns='Primary Breed', values='breed counts') pivot_df pivot_df.plot.bar(stacked=True, figsize=(10,7)) # ## What percentage of dogs are not guard dogs? # In[33]: df["Guard or Trained"].value_counts(dropna=False, normalize= True) # 99,9% of the dogs are not guard or trained dogs.
e3e9fd1e1ab6f71fb462d60a7fd6550674683906
sensito/Aprendiendo-py
/aleph.py
322
3.734375
4
# -*- coding: utf-8 -*- def run(word): counter = 0 with open('aaaa.txt', encoding='utf8') as f: for line in f: counter += line.count(word) print('{} esta {}'.format(word, counter)) if __name__ == '__main__': word = str(input('Dame la palabra a buscar en el texto: ')) run(word)
d23e0e96536ccc5be3bdf6a578b7cd0601e4f909
mytram/learning-python
/projecteuler.net/problem_049.py
1,320
3.53125
4
# Prime permutations # Problem 49 # The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. # There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. # What 12-digit number do you form by concatenating the three terms in this sequence? from common import PrimeGenerator def solve(): primes = PrimeGenerator(lt = 10 ** 4) perms_of_4_digits_primes = {} for prime in primes: if prime < 1000: continue perm_key = ''.join(sorted(str(prime))) if perm_key == '1478': continue perm_primes = perms_of_4_digits_primes.get(perm_key, []) perm_primes.append(prime) perms_of_4_digits_primes[perm_key] = perm_primes for _, prime_set in perms_of_4_digits_primes.items(): if len(prime_set) < 3: continue for index in range(0, len(prime_set) - 2): if prime_set[index + 1] - prime_set[index] == prime_set[index + 2] - prime_set[index + 1]: return ''.join(map(str, prime_set[index:index+3])) if __name__ == '__main__': print(__file__ + ':', solve())
ecb17a59b6a7f5ee6d4164c8f5da7999cfcfa48d
ChrisLee0211/-python-
/date_count.py
1,471
3.953125
4
#_*_coding:utf-8_*_ __author__ = 'Chrislee' class Date_count(): def __init__(self): self.date=input() self.month=int(self.date[4:6]) self.day =int(self.date[6:]) self.part_one = 31 self.month_dict={ 3:self.March(), 4:self.April(), 5:self.May(), 6:self.June(), 7:self.July(), 8:self.August(), 9:self.September(), 10:self.October(), 11:self.November(), 12:self.December() } def March(self): return 0 def April(self): return 90 - 59 def May(self): return 120 - 59 def June(self): return 151 - 59 def July(self): return 181 - 59 def August(self): return 212 - 59 def September(self): return 243 - 59 def October(self): return 273 - 59 def November(self): return 304 - 59 def December(self): return 334 - 59 def date_count(self): date=self.date month=self.month day =self.day part_one = 31 if month <= 2: part_one= 31 result = part_one + day else: part_one = 59 part_two= self.month_dict.get(month) result = part_one+part_two+day print(result) if __name__=="__main__": Day=Date_count() Day.date_count()
0ff1f1a8ee83073cc202b07d81eb8d188a7d52df
jfidelia/python_exercises
/exercises/15-Techno_beat/app.py
604
3.640625
4
def lyrics_generator(beat): items = [] count = 0 for x in beat: if x == 0: count = 0 items.append("Boom") if x == 1: count = count + 1 items.append("Drop the base") if count == 3: items.append("!!!Break the base!!!") return ' '.join([str(elem) for elem in items]) # Your code go above, nothing to change after this line: print(lyrics_generator([0,0,1,1,0,0,0])) print(lyrics_generator([0,0,1,1,1,0,0,0])) print(lyrics_generator([0,0,0])) print(lyrics_generator([1,0,1])) print(lyrics_generator([1,1,1]))
04ad7e7941b550d02a2dd65188bd32cda7c8c7bd
LuisTarma/random-python-scripts
/a.py
4,083
3.625
4
#1 - Identificar tarjeta #2 - "Habilitar" #3 - Comprobacion de contraseña #4 - Habilitar menu #5 - Emision de ticket #6 - Redondeo de billetes Ej: no billetes de 10mil import os import getpass class Cajero: def Datos(self, saldo): self.saldo = saldo #self.can100 = can100 class Usuario: def Datos(self, nombre, contrasena, fecha_nac, saldo): self.nombre = nombre self.contrasena = contrasena self.fecha_nac = fecha_nac self.saldo = saldo def Retirar(): os.system("cls") titulo() s = Cliente.saldo print(" Su saldo disponible es de "+str(s)) if s<=0: print(" No es posible hacer retiros - Saldo insuficiente") return r = int(input(" Ingresa cantidad a retirar: ")) if r>s: print(" La cantidad sobrepasa el saldo disponible en su cuenta") Retirar() else: Cliente.saldo = s - r #b = pdf(Detalles_retiro); #imprimir(b) sobra = [] sobra = CalcularBilletes(r) if sobra[0] > 0: print(" La cantidad " + str(sobra[0]) + " no puede ser retirada. Se volvera a agregar a su cuenta") Cliente.saldo += int(sobra[0]) print(" Cantidad retirada: "+ str(r-sobra[0])) print(" Saldo disponible: "+ str(Cliente.saldo)) def titulo(): print("----------------------------------------------".center(110, "-")) print("----------| CAJERO AUTOMATICO |---------------".center(110, "-")) print("----------------------------------------------".center(110, "-")) print(" ") def Depositar(): os.system("cls") titulo() s = Cliente.saldo print(" Su saldo disponible es de "+str(s)) r = int(input("Ingresa cantidad a depositar: ")) if r<=0: print(" Ingrese una cantidad valida") Depositar() else: Cliente.saldo = s + r sobra = [] sobra = CalcularBilletes(r) if sobra[0] > 0: print(" La cantidad " + str(sobra[0]) + " no puede ser depositada.") Cliente.saldo -= int(sobra[0]) print(" Cantidad depositada: "+ str(r-sobra[0])) print(" Saldo disponible: "+ str(Cliente.saldo)) def CalcularBilletes(monto): #x = int(input("Ingresa cantidad: ")) #monto = 520000 c100 = 0 c50 = 0 c20 = 0 sobra = 0 while monto>0: if monto>=100000: c100 += 1 monto -=100000 # monto = 420000 2) 320000 3) 220000 4) 120000 5) 20000 6)0 else: if monto>=50000: c50 += 1 monto -=50000 # monto = 20000 else: if monto>=20000: c20 += 1 monto -= 20000 # monto = 0 else: sobra = monto break print(" Cantidad de billetes de 100.000 G: "+ str(c100)) print(" Cantidad de billetes de 50.000 G: "+ str(c50)) print(" Cantidad de billetes de 20.000 G: "+ str(c20)) print("Sobra: "+ str(sobra)) return [sobra, c100, c50, c20] def Menu(): while 1: print(" -------------------------------".center(110, " ")) print(" 1- Retirar Dinero -".center(110, " ")) print(" 2- Depositar Dinero -".center(110, " ")) print(" 3- Saldo disponible en cuenta -".center(110, " ")) print(" 4- Cerrar Sesion -".center(110, " ")) print(" -------------------------------".center(110, " ")) op = int(input(" Opcion: ".center(80, " "))) if op == 1: Retirar() elif op == 2: Depositar() elif op == 3: print("Su saldo disponible es: " + str(Cliente.saldo)) continue elif op == 4: os.system("cls") break else: print("Ingrese una opcion valida") def ValidarPin(x): pin = getpass.getpass("Ingrese pin: ") if int(pin) == int(Cliente.contrasena): print("Pin correcto") Menu() else: if x>1: print("Limite de intentos alcanzado.") return 1 else: print("Pin Incorrecto - vuelva a intentarlo") x += 1 ValidarPin(x) while 1: #Datos del cajero Caja = Cajero() Caja.Datos(4300000) titulo() print("") print(" Ingresa tarjeta de credito".center(110, " ")) print("") s = input("") #Datos del cliente prueba Cliente = Usuario() #Cliente de prueba Cliente.Datos("luis", 1234, "02/10/96", 3500000) #Comprobacion de pin ValidarPin(0) """ a = int(input("Numero: ")) c = "" e = "" for i in range(a): c += "*" if i<a-2: e += " " print(c) for i in range(a-2): print("*"+e+"*") print(c) """
2ce013f8e124200e2511c84613904c18f02d3a3a
falsifian/plusone
/src/datageneration/util.py
7,846
4.15625
4
"""Contains some useful classes and methods """ import numpy as np import operator import pickle import math from math import e from math import gamma import random from random import random as rand import matplotlib from matplotlib.pyplot import * class Poisson(object): """A class to represent a poisson distribution. Attributes: lamb: the parameter to the poisson distribution Methods: sample(): returns a sample from the distribution """ def __init__(self, L=15): self.lamb = L def sample(self): """Samples the poisson distribution. Args: none Returns: a number sampled from the poisson distribution with parameter self.lamb """ L = e ** (-self.lamb) k, p = 1, rand() while p > L: k += 1 p *= rand() return k - 1 def get_cdf(dist): """Calculates the cdf of a distribution. Given a distribution, calculates (and stores) the cdf for quick sampling. Args: dist: distribution to construct a cdf from Returns: cdf to sample from """ cdf = [] total = 0 for i in range(len(dist)): total += dist[i] cdf.append(total) return cdf def sample(cdf): """Takes a distribution and samples from it. Given a list of probabilities (that obey a distribution), samples from it and returns an index of the list. This method assumes that dist obeys a multinomial distribution. Args: dist: A multinomial distribution represented by a list, where each entry is the index's probability. Returns: a sample from the distribution, a random index in the list Sample usage: sample([.5, .5]) sample a distribution with two elements, each equally likely """ p = rand() #this line is for rounding errors which will cause binary_search to return #an index that is out of bounds if p == 1.0: return cdf[-1] else: return binary_search(cdf, p) def binary_search(elements, to_find, lo=0, hi=None): """Performs a binary search on an array. Unlike standard binary search, this will return the index of the nearest index (rounding down) if the element to find is between two values. This is because here binary_search is being used for the purpose of sampling from a cdf (see anomaly below). Args: elements: an array of values to_find: the value desired lo: the leftward bound of the search hi: the rightward bound of the search Returns: the index corresponding to where to_find is in elements; if to_find is between two indices, returns the lower one **ANOMALY** binary_search will return len(elements) if to_find is equal to the last element of elements (ie if to_find == 1.0) """ if hi is None: hi = len(elements) while lo < hi: mid = (lo+hi)//2 midval = elements[mid] if midval < to_find: lo = mid+1 elif midval > to_find: hi = mid else: return hi return hi def normalize(dist): """Normalizes an array so it obeys a multinomial distribution. Assumes dist is a numpy array. Divides each element in dist by the total so that all entries add up to 1. Args: dist: an array of numbers Returns: a normalized version of dist """ return np.array(dist, 'double') / np.sum(dist) def dirichlet_pdf(x, alpha): """Calculates the probability of the given sample from a dirichlet distribution. Given a sample x and parameter alpha, calculates the probability that x was sampled from Dirichlet(alpha). Args: x: a list of numbers in the interval [0,1] that sum to 1 alpha: the parameter to a dirichlet distribution; represented as a list Returns: the probability that x was sampled from Dirichlet(alpha) """ density = reduce(operator.mul, [x[i]**(alpha[i]-1.0) for i in range(len(alpha))]) norm_top = gamma(np.sum(alpha)) norm_bot = reduce(operator.mul, [gamma(a) for a in alpha]) return (norm_top / norm_bot) * density def count(words): """Creates a histogram of occurrences in an array. Given a list, counts how many times each instance occurs. Args: words: a list of values Returns: a dictionary with keys as the values that appear in words and values as the number of times they occur """ word_count = {} num_words = 0 unique_words = 0 for word in words: num_words += 1 if word_count.has_key(word): word_count[word] += 1 else: word_count[word] = 1 unique_words += 1 word_count["total"] = num_words word_count["unique"] = unique_words return word_count def plot_dist(types, color='b', labels=None, bottom=0): """Plots a distribution as a bar graph. Given a distribution, plots a bar graph. Each bar is an element in the distribution, and its value is the element's probability. Args: types: a distribution, represented as a list Returns: none, but plots the distribution """ offset = 0 width = 0.01 if labels == None: labels = range(len(types)) for type in types: bar(offset, type, width, bottom, color=color) offset += width xticks(np.arange(width / 2, width * len(types), .01), labels) def plot_dists(types, color='b', labels=None, scale=0): """plots several distributions vertically stacked for easier visualization TODO: scale y-axis so labels make sense """ bottom = 0 for type in types: if len(type) > 100: plot(type + bottom) else: plot_dist(type, color, labels, bottom) if scale == 1.0: to_add = scale else: to_add = max(type) * 1.1 bottom += to_add def plot_hist(words, vocab_size, color='b'): hist(words, range(vocab_size + 1), color=color) def perplexity(docs, probabilities, indices=None): if indices == None: indices = range(len(docs)) numerator, denominator = 0.0, 0.0 for i in indices: p = 0 words = int(len(docs[i]) * 0.7) for word in docs[i][:words]: p += np.log(probabilities[i, word]) numerator += p denominator += words print i, p, words print denominator perp = np.exp(-(numerator / denominator)) print "LDA perplexity:", perp return perp def get_probabilities(pickle_file): if len(pickle_file) >= 6 and pickle_file[-6:] != "pickle": with open('src/datageneration/output/documents_model-out', 'r') as f: v = False rbeta = [] rgamma = [] for line in f.readlines(): if line == 'V\n': v = True continue if v: rgamma.append([float(word) for word in line.strip(' \n').split(' ')]) else: rbeta.append([float(word) for word in line.strip(' \n').split(' ')]) rbeta = np.matrix(rbeta) rgamma = np.matrix(rgamma) probabilities = rgamma * rbeta else: with open(pickle_file, 'r') as f: docs, words, topics = pickle.load(f) probabilities = np.matrix(topics) * np.matrix(words) return probabilities
62bff7f62430f2a0c224ffbfa88e3ad1ffe1382c
kemar1997/TSTP_Programs
/Challenges/Ch14_Challenges/Challenge1.py
330
4.28125
4
""" 1. Add a square_list class variable to a class called Square so that every time you create a new Square object, the new object gets added to the list. """ class Square: square_list = [] def __init__(self): self.square_list.append(self) s1 = Square() s2 = Square() s3 = Square() print(Square.square_list)
162bf89159b65464857c0a3976ebe16cb1c127d5
Md-Monirul-Islam/Python-code
/Pattern-Python/K shape.py
305
3.84375
4
i = 0 j = 4 for row in range(7): for col in range(5): if (col==0) or (row==col+2 and (col>1)): print("*",end='') elif ((row==i and col==j) and col>0): print("*",end='') i = i+1 j = j-1 else: print(end=' ') print()
861f86621aac580b86e75820c09ecfd5be4abf1a
fjctp/quicksort
/python/quicksort.py
434
3.921875
4
#!/usr/env python2 def quicksort(numbers): #print(numbers) if len(numbers)>1: left = numbers[0] return quicksort(filter(lambda x: x<left, numbers))+ \ [left]+ \ quicksort(filter(lambda x: x>left, numbers)) else: return numbers if __name__ == '__main__': from random import sample arr = sample(range(100), 20) print(arr) print(quicksort(arr))
6354a73fb05f970f24392f48a6816c8fd2c6ad9b
ifpb-cz-ads/pw1-2020-2-ac04-team-josecatanao
/questao_10.py
462
3.90625
4
#10) Escreva um programa que pergunte o depósito inicial e a taxa de juros de uma poupança. Exiba os valores mês a mês para os 12 primeiros meses. Escreva o total ganho com juros no período. valor = float(input("Inicial: ")) taxa = float(input("Taxa:")) cont = 1 saldo = valor while cont <= 12: saldo = saldo + (saldo * (taxa / 100)) print(f"{cont}° Saldo: R${saldo:5.2f}.") cont = cont + 1 print(f"O valor obtido: R${saldo-valor:8.2f}.")
4664a909dbb38b3c5fbaf4ee95f6dd3a68cbd75d
chepkoy/python_basics
/logic/statements.py
548
4.03125
4
# Working with if else and elif statements if 5 > 2: print("Well, Yeah 5 is greater than 2") age = 34 * 365 if age > 10000: print("You are over 10,000 days old") # using else age = 5000 if age > 10000: print("You are over 10,000 years old") else: print("Keep going you will get there") # using the elif age = 9000 if age > 20000: print("Time to retire") elif age > 10000: print("Lots of time left") else: print("Keep going you will get there") age = 22000 if not age > 30000: print("No present")
18781748cd4cb700bb45f08e02197ee9cbe9da14
mike1130/boot-camp
/week-05/week-05-04.py
900
3.765625
4
# Thursday: Scope from os import system clear = lambda: system('clear') clear() # use it to clear the terminal output # where global variables can be accessed # number = 5 # def scopeTest(): # number += 1 # not accessible due to function level scope # scopeTest() # accessing variables defines in a function def scopeTest(): word = 'Function' return word value = scopeTest() print(value) # changing list item values by index sports = ['Baseball','Football','Hockey','Basketball'] def change(aList): aList[0] = 'Soccer' print('Before altering: {}'.format(sports)) change(sports) print('After altering: {}'.format(sports)) # Thursday Exercises # Names names = ['Bob', 'Rich', 'Amanda'] def changeValue(aList, name, index): aList[index] = name print('Before altering: {}'.format(names)) changeValue(names, 'Bill', 1) print('After altering: {}'.format(names))
c42ebfb9a3d8ca1ec67e4e23fc6869ec4022f08c
Taewan-P/python_study
/exercise_2017/12th_week/blackjack/reader.py
482
3.765625
4
# Reader class Reader(object): @staticmethod def ox(message): response = input(message).lower() while not (response == 'o' or response == 'x'): response = input(message).lower() return response == 'o' @staticmethod def get_number(message,low,high): response = input(message) while not (response.isdigit() and low <= int(response) <= high): response = input(message) return int(response)
30f62ec9de4c6821762708d89ea1f4023c9b9cca
parshuramsail/python_exersises
/BEGINNER_EXERCISES/02.LIST_AND_TUPLES/LEVEL-1/a1.py
285
3.828125
4
# Multifly all elements in a list # option->1 my_list = [3, 4, 5, 6, 7] factor = 2 for i in range(len(my_list)): my_list[i] *= factor print(my_list) # option->2 my_list = [3, 4, 5, 6, 7] factor = 2 for i, elem in enumerate(my_list): my_list[i] = elem*factor print(my_list)
1fc080ef9d247d186cbdbb50fe593e19935c3854
Iansdfg/9chap
/5Two pointers/143. Sort Colors II.py
1,155
3.625
4
class Solution: """ @param colors: A list of integer @param k: An integer @return: nothing """ def sort_colors2(self, colors, k): # write your code here # why use k, its not index, its color number so we need use k intsead of k+1/k-1 self.rainbow_sort(colors, 1, k, 0, len(colors) - 1) def rainbow_sort(self, colors, form_color, to_color, from_index, to_index): if from_index == to_index or form_color == to_color: return left, right = from_index, to_index pivot = (form_color + to_color) // 2 while left <= right: #use <= and > cam seperate colors while left <= right and colors[left] <= pivot: left += 1 while left <= right and colors[right] > pivot: right -= 1 if left <= right: colors[left], colors[right] = colors[right], colors[left] left += 1 right -= 1 self.rainbow_sort(colors, k, form_color, pivot, from_index, right) self.rainbow_sort(colors, k, pivot + 1, to_color, left, to_index)
3624b85027a992a60cea167d62584e493dbbc25c
ryanatgz/data_structure_and_algorithm
/jianzhi_offer/59_扑克牌中的顺子.py
697
3.734375
4
# encoding: utf-8 """ @project:data_structure_and_algorithm @author: Jiang Hui @language:Python 3.7.2 [GCC 7.3.0] :: Anaconda, Inc. on linux @time: 2019/8/9 11:26 @desc: """ class Solution(object): def isContinuous(self, numbers): """ :type numbers: List[int] :rtype: bool """ if not numbers: return False numbers.sort() k = 0 while not numbers[k]: # 找到第一个不为0的元素下标 k += 1 for i in range(k + 1, len(numbers)): if numbers[i] == numbers[i - 1]: # 有序数组,重复元素必相邻 return False return numbers[-1] - numbers[k] <= 4
bc80a8c915d7e7380435ff568103addb9eacf8bb
duyquang6/py-side-project
/cookbook/chap1/main.py
5,781
4
4
# 1.10. Removing Duplicates from a Sequence while Maintaining Order # a = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}] # # # def dedupe(items, key=None): # seen = set() # for item in items: # val = item if key is None else key(item) # if val not in seen: # yield item # seen.add(val) # # # print(list(dedupe(a, key=lambda d: (d['x'], d['y'])))) # 1.11. Naming a Slice # ###### 0123456789012345678901234567890123456789012345678901234567890' # record = '....................100 .......513.25 ..........' # cost = int(record[20:32]) * float(record[40:48]) # SHARES = slice(20, 32) # PRICE = slice(40, 48) # # cost = int(record[SHARES]) * float(record[PRICE]) # 1.12. Determining the Most Frequently Occurring Items in a Sequence # words = [ # 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', # 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', # 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', # 'my', 'eyes', "you're", 'under' # ] # # from collections import Counter # # word_counts = Counter(words) # top_three = word_counts.most_common(3) # print(top_three) # # # update # more_words = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes'] # word_counts.update(more_words) # # # perform operations # a = Counter(words) # b = Counter(more_words) # a + b # a - b # 1.13. Sorting a List of Dictionaries by a Common Key # rows = [ # {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, # {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, # {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}, # {'fname': 'Big', 'lname': 'Jones', 'uid': 1004} # ] # # from operator import itemgetter # # rows_by_name = sorted(rows, key=itemgetter('fname')) # rows_by_uid = sorted(rows, key=itemgetter('uid')) # rows_by_name # rows_by_uid # # rows_by_name = sorted(rows, key=lambda d: d['fname']) # rows_by_uid = sorted(rows, key=lambda d: d['uid']) # rows_by_name # rows_by_uid # # rows_by_lfname = sorted(rows, key=itemgetter('lname', 'fname')) # rows_by_lfname # # rows_by_lfname = sorted(rows, key=lambda d: (d['lname'], d['fname'])) # rows_by_lfname # 1.14. Sorting Objects Without Native Comparison Support # class User: # def __init__(self, user_id): # self.user_id = user_id # # def __repr__(self): # return 'User({})'.format(self.user_id) # # # users = [User(23), User(3), User(99)] # users # sorted(users, key=lambda u: u.user_id) # # from operator import attrgetter # sorted(users, key=attrgetter('user_id')) # 1.15. Grouping Records Together Based on a Field # rows = [ # {'address': '5412 N CLARK', 'date': '07/01/2012'}, # {'address': '5148 N CLARK', 'date': '07/04/2012'}, # {'address': '5800 E 58TH', 'date': '07/02/2012'}, # {'address': '2122 N CLARK', 'date': '07/03/2012'}, # {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, # {'address': '1060 W ADDISON', 'date': '07/02/2012'}, # {'address': '4801 N BROADWAY', 'date': '07/01/2012'}, # {'address': '1039 W GRANVILLE', 'date': '07/04/2012'}, # ] # # from operator import itemgetter # from itertools import groupby # # # Sort by the desired field first # rows.sort(key=itemgetter('date')) # # # Iterate in groups # for date, items in groupby(rows, key=itemgetter('date')): # print(date) # for i in items: # print(' ', i) # 1.16. Filtering Sequence Elements # mylist = [1, 4, -5, 10, -7, 2, 3, -1] # [n for n in mylist if n > 0] # pos = (n for n in mylist if n > 0) # pos # next(pos) # # values = ['1', '2', '-3', '-', '4', 'N/A', '5'] # def is_int(val): # try: # x = int(val) # return True # except ValueError: # return False # # ivals = list(filter(is_int, values)) # print(ivals) # 1.17. Extracting a Subset of a Dictionary # prices = { # 'ACME': 45.23, # 'AAPL': 612.78, # 'IBM': 205.55, # 'HPQ': 37.20, # 'FB': 10.75 # } # # # Make a dictionary of all prices over 200 # p1 = {key: prices[key] for key in prices.keys() if prices[key] > 200} # p1 = {key: value for key, value in prices.items() if value > 200} # # # Make a dictionary of tech stocks # tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'} # p2 = {key: value for key, value in prices.items() if key in tech_names} # 1.18. Mapping Names to Sequence Elements # from collections import namedtuple # # Subscriber = namedtuple('Subscriber', ['addr', 'joined']) # sub = Subscriber('jonesy@example.com', '2012-10-19') # sub # sub.addr # sub.joined # len(sub) # # Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time']) # # Create a prototype instance # stock_prototype = Stock('', 0, 0.0, None, None) # # Function to convert a dictionary to a Stock # def dict_to_stock(s): # return stock_prototype._replace(**s) # # a = {'name': 'ACME', 'shares': 100, 'price': 123.45} # dict_to_stock(a) # 1.19. Transforming and Reducing Data at the Same Time # nums = [1, 2, 3, 4, 5] # # bad performance # s = sum([x * x for x in nums]) # # recommend # s = sum(x * x for x in nums) # equivalent to sum((x * x for x in nums)) # 1.20. Combining Multiple Mappings into a Single Mapping # from collections import ChainMap # # a = {'x': 1, 'z': 3} # b = {'y': 2, 'z': 4} # c = ChainMap(a, b) # c # c['z'] = 10 # c['w'] = 40 # del c['x'] # a # # values = ChainMap() # values['x'] = 1 # # Add a new mapping # values = values.new_child() # values['x'] = 2 # # Add a new mapping # values = values.new_child() # values['x'] = 3 # values # ChainMap({'x': 3}, {'x': 2}, {'x': 1}) # values['x'] # 3 # # Discard last mapping # values = values.parents # values['x'] # 2 # # Discard last mapping # values = values.parents # values['x'] # 1 # values # ChainMap({'x': 1})
aa04fe4b19d65d664a4efc5a537b8c4cb19c892e
lizhuhe0323/Python
/stack.py
729
4
4
stack = [] def pushit(): item = input('item:') stack.append(item) print (stack) def popit(): if stack: print ('poped itme:' ,stack.pop()) else: print ("Empty stack.") def viewit(): if stack: print (stack) else: print ("Empty stack.") def show_menu(): CMDs = {'0':pushit,'1':popit,'2':viewit} prompt = """(0) push it (1) pop it (2) view it (3) quit Please input your choice(0/1/2/3): """ while True: choice = input(prompt).strip()[0] if choice not in '0123': print ('Invalid input,Try again.') continue if choice == '3': break CMDs[choice]() if __name__ == '__main__': show_menu()
190866f5b4f520a44fb9c9837a58cb378367e109
nklnarayana/projects
/Trees/mergeBSTs.py
3,995
3.953125
4
#1) Do inorder traversal of first tree and store the traversal in one temp array arr1[]. This step takes O(n1) time. #2) Do inorder traversal of second tree and store the traversal in another temp array arr2[]. This step takes O(n2) time. #3) The arrays created in step 1 and 2 are sorted arrays sicne they are BSTs. Merge the two sorted arrays into one array of size n1 + n2. This step takes O(n1+n2) time. #4) Construct a balanced tree from the merged array using merge sort (excep splliting the list). This step takes O(n1+n2) time. #Time complexity of this method is O(n1+n2) from collections import deque #create binary tree node class class btnode: def __init__(self,item): self.data = item self.left = None self.right = None #Do an inorder traversal #append the root's data to an array def storeInorder(node,inorder): if node == None: return storeInorder(node.left,inorder) inorder.append( node.data) #index_ptr += 1 storeInorder(node.right,inorder) #merge two arrays def merge(arr1,arr2): m = len(arr1) n = len(arr2) mergedArr = [None] * ( m + n ) i = 0 j = 0 k = 0 # traverse through each array until their ends while i < m and j < n: # Idea is to find which element is small compared to two numbers in arr1 & arr2 # Assign the smalles number to mergesArr # if arra1 element is small if arr1[i] < arr2[j]: mergedArr[k] = arr1[i] i += 1 #if arr2 element is small else: mergedArr[k] = arr2[j] j += 1 k += 1 # scan the remainining elements in each array and append them to mergedArray while i < m: mergedArr[k] = arr1[i] i += 1 k += 1 while j < n: mergedArr[k] = arr1[j] j += 1 k += 1 return mergedArr #function to construct BST from a sorted list def sortedArraytoBST(arr,start,end): if start> end : return None mid = (start + end ) / 2 #make mid element as root to keep search tree balanced root = btnode(arr[mid]) #recursively construct left subtree and assign as left node of root root.left = sortedArraytoBST(arr,start,mid-1) #recirsively construct right subtree and assign it as right node of root root.right = sortedArraytoBST(arr,mid+1,end) return root def printInorder(node): if node is None: return printInorder(node.left) print node.data, printInorder(node.right) def treeLevels(root): # Two queues, one for the nodes one for the level of the nodes. Q = deque() L = deque() #enque the root Q.append(root) level = 0 L.append(level) print level, [root.data] while len(Q) > 0: u = Q.popleft() l = L.popleft() # For the current node if it has a left or right child, # add it to the queue and with its corresponding level + 1. if u.left: Q.append(u.left) L.append(l+1) if u.right: Q.append(u.right) L.append(l+1) # If there is a node still in the queue and all the nodes in the queue # are at the same level, then increment the level and print. if len(L) > 0 and L[0] > level and L[0] == L[-1]: level += 1 print level,[x.data for x in Q] if __name__ == "__main__" : root1 = btnode(100) root1.left = btnode(50) root1.right = btnode(300) root1.left.left = btnode(20) root1.left.right = btnode(70) root2 = btnode(80) root2.left = btnode(40) root2.right = btnode(120) inorder1 = [] inorder2 = [] # storeInorder traversals of the trees in inorder1 and inorder2 storeInorder(root1,inorder1) storeInorder(root2,inorder2) mergedArr = merge(inorder1,inorder2) start =0 end = len(mergedArr)-1 # construct Binary search tree from sorted merged array root = sortedArraytoBST(mergedArr,0,end) printInorder(root) print treeLevels(root)
f9b7e4ebd2e0ba3cfa5d3aa3b186e75166375ede
lldenisll/learn_python
/Exercícios/testefatorial.py
598
3.796875
4
def fatorial(n): fat=1 while (n>1): fat=fat*n n=n-1 return fat def binomial (n,k): return fatorial(n)/(fatorial(k)*fatorial (n-k)) def teste (): if fatorial(1)==1: print("funciona para 1") else: print("Não funciona para 1") if fatorial(2)==2: print("funciona para 2") else: print("Não funciona para 2") if fatorial(0)==1: print("Funciona para 0") else: print("Não funciona para 0") if fatorial(5)==120: print("Funciona para 5") else: print("Não funciona para 5")
69d4dad68e11cb064543d294c11a7644c4779471
cuihaoleo/exercises
/LeetCode/algorithms/binary-tree-right-side-view/solution.py
731
3.546875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from math import log class Solution: # @param {TreeNode} root # @return {integer[]} def rightSideView(self, root): def dfs(node, pos): if not node: return row = int(log(pos, 2)) if row >= len(ans): ans.append((node, pos)) elif pos > ans[row][1]: ans[row] = (node, pos) dfs(node.left, pos*2) dfs(node.right, pos*2+1) ans = [] dfs(root, 1) return [p[0].val for p in ans]
e7bda166d1f0ecbae9ef1f0479ffa2a40c5403f2
juanmbraga/CS50-2021-Seminars
/Taste of Python/5.loops.py
142
4.03125
4
n = int(input("Number: ")) i = 0 while i < n: print("Hello, world") i = i + 1 i = 0 for i in range(n): print("Hello, world")
7d090650fc7fc908e6a8914310b12878ce38dd80
SpencerBeloin/Python-files
/factorial.py
228
4.21875
4
#factorial.py #computes a factorial using reassignment of a variable def main(): n= eval(input("Please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact*factor print fact main()
6829d1735bfaf5e84f43b23b79f2c55c2e10de6a
edu-athensoft/stem1401python_student
/py200325_python1/py200508/string_format_2.py
433
4.0625
4
""" """ # print("Hello {0}, your balance is {1}.".format("Peter", 230.2346)) # formatting print("Hello {0}, your balance is {1:9.3f}.".format("Peter", 230.2346)) print("Hi, your balance is {1:9.3f}, {0}!".format("Peter", 230.2346)) # formatting 2 print("Hello {name}, your balance is {balance:9.3f}.".format(name="Peter", balance=230.2346)) # formatting 3 print("Hello {}, your balance is {:9.3f}.".format("Peter", 230.2346))