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
620a13aae294cf0dee055327413e5c426638f216
a-soliman/python-2019
/06-files/copying/app.py
810
3.953125
4
def get_friends(): friends = input("provide three name: ") return [friend.strip() for friend in friends.split(",")] def is_near_by(friends, people): peopleMap = create_map(people) near_by = [] for friend in friends: if friend in peopleMap: print(f"{friend} is near by!") near_by.append(friend) write_file(near_by) def create_map(filename): readable_file = open(filename, "r") content = readable_file.readlines() striped_content = {person.strip("\r\n"): person.strip( "\r\n") for person in content} readable_file.close() return striped_content def write_file(content): file = open("nearby.txt", "w") file.writelines([f"{name}\n" for name in content]) file.close() is_near_by(get_friends(), "people.txt")
5e91d7c550fb894ab16c9b2ed84a9fb3f18db73e
cnrmck/static_spines
/config.py
3,705
3.5625
4
class Config(object): def __init__(self): """ Options that are listed one on top of the other are linked. E.g. # set the config for car to True if you want cars car = True # how many wheels does your car have? wheels = 4 If car were not true then there would not be any wheels to define Options that have a newline between them are separate # what color are your trees? tree_color = 'green' # what color is the sky sky_color = 'blue' """ self.log_level = 'CRITICAL' # the path to the location you want images (and other data) to be saved self.image_path = '/Users/Connor/code/static_spines/data/' # specifies the number of colors to color exponents with self.num_colors = 18 self.base = 2 # if True saves having to redraw the image every time, but less beautiful # test this self.reverse_display_order = False # clear the screen before every step self.clear_before_each_step = True # if True, don't draw all nodes at once, just draw one at a time self.draw_individually = False # the width of the canvas self.canvas_width = 1000 # the height of the canvas self.canvas_height = 1000 # default is 60, but most of the time that cannot be achieved self.frame_rate = 60 # if True the next display will be range(n^exp - n^(exp - 1), n^(exp)) # if False the next step will be the next number self.step_by_exponential_range = True self.color_primes = True self.prime_gaps = False # save prime gaps self.save_prime_gaps = True # writes the number associated with the each SpinePoint self.write_text = False # writes the fraction associated with the each SpinePoint self.write_fraction = False # draw spines as long as their number (if 5 spine is 5 units long) self.spine_length_is_its_number = False # TODO: Make this work # draw the connecting lines with an offset self.offset_connecting_lines = False # draw the connecting lines in the current color self.connections_in_current_color = True # draw the spines self.draw_spines = False # draws shadows for the spines self.draw_shadows = False # draw the connecting lines self.draw_connecting_lines = True # draw points at the end of each self.indicate_end_of_spine = False self.only_indicate_primes = False # if not using spine_length_is_its_number, should be < canvas_height/2 self.scale_factor = 490 # plot the number and magnitude as if they were cartesian (x,y) coordinates self.cartesian_plot = False # plot just like above, but don't limit to the size of the screen self.expansionary_plot = False # how many units to step by for each increment (in expansionary_plot) self.expansion_increment = 2 self.config_tests() def config_tests(self): """ Some simple tests that you can run to find out whether you have any undesireable config settings """ if self.only_indicate_primes == True and self.indicate_end_of_spine == False: print("CONFIG WARNING: Cannot indicate primes if spine indication is false." "\n Change indicate_end_of_spine to True") if self.offset_connecting_lines is True: print("CONFIG WARNING: offsetting connecting lines doesn't work. Change so that offset_connecting_lines = False")
ea2db29b964f64e51d936af9ea3227a93e3230a9
Arya16ap/c-1oo3oo1oo3
/103/bar.py
175
3.609375
4
import pandas as pd import plotly.express as px #reading data from csv files df = pd.read_csv("data.csv") fig = px.line(df,x = "Country",y = "InternetUsers") fig.show()
06c673fa8648dbefda846f6c319bbe64e946df49
adwynn/comp110-21f-workspace
/exercises/ex03/tar_heels.py
306
3.84375
4
"""An exercise in remainders and boolean logic.""" __author__ = "730443412" # Begin your solution here... nmbr = int(input("Enter an int: ")) if nmbr % 2 == 0 and nmbr % 7 == 0: print("TAR HEELS") elif nmbr % 2 == 0: print("TAR") elif nmbr % 7 == 0: print("HEELS") else: print("CAROLINA")
e81bc87412564d855401c2722ff436d3e13a20fe
niki4/leetcode_py3
/easy/1748_sum_of_unique_elements.py
1,424
3.953125
4
""" You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums. Example 1: Input: nums = [1,2,3,2] Output: 4 Explanation: The unique elements are [1,3], and the sum is 4. """ import collections from typing import List class Solution: """ Runtime: 44 ms, faster than 6.40% of Python3 Memory Usage: 14.3 MB, less than 42.72% of Python3 """ def sumOfUnique(self, nums: List[int]) -> int: ctr = collections.Counter(nums) return sum(k for k in ctr if ctr[k] == 1) class Solution2: """ Num range is constant as it was set in Constraints, so we can pre-allocate array where index represent the num (1-100) and value is the count of the num from source array. Runtime: 44 ms, faster than 6.44% of Python3 Memory Usage: 14.1 MB, less than 90.38% of Python3 """ def sumOfUnique(self, nums: List[int]) -> int: num_ctr = [0] * (100 + 1) for n in nums: num_ctr[n] += 1 return sum(i for (i, n) in enumerate(num_ctr) if n == 1) if __name__ == '__main__': solutions = [Solution()] tc = ( ([1, 2, 3, 2], 4), ([1, 1, 1, 1, 1], 0), ([1, 2, 3, 4, 5], 15), ) for sol in solutions: for inp_nums, exp_sum in tc: assert sol.sumOfUnique(inp_nums) == exp_sum
82b80b43b723d3d5ca93520cd3af6e45ec12965a
Maelstroms/euler
/p4.py
613
3.75
4
""" Fourth problem of project Euler """ def string_reverse(string): rev = "" mark = [] for i in range(len(string)): mark.append(i) mark.reverse() for i in mark: rev += string[i] return rev print string_reverse("9010308") palindromes = [] count1 = 999 count2 = 999 while count2 > 100: sum = count1 * count2 track = str(sum) kcart = string_reverse(track) if track == kcart: palindromes.append(sum) print ("count1 is" , count1) print ("count2 is", count2) print ("together they are", track) else: if count1 == 100: count2 -= 1 count1 = count2 count1 -= 1 print max(palindromes)
ae7c6fb32f635a0734cb1b392275d8a99e4c28fa
code-project-done/Algorithms_for_Competitive_Programming_in_Python
/Number_theory_and_Other_Mathematical/Prime_number_and_Prime_Factorization/gcd_euclid.py
301
3.84375
4
from math import gcd def gcd_euclid(a, b): """ actually no need it, it is in the module math """ if a < b: return gcd(b, a) while b != 0: a, b = b, a % b return a for a in range(500): for b in range(500): assert(gcd(a,b) == gcd_euclid(a,b))
74b39b23a6d3064849fddc0abe26c3cee11c959c
VijayKumarPrakash/Design-And-Analysis-Of-Algorithms
/QuickSort.py
566
3.953125
4
def quicksort(a, low, high): left = low right = high x = a[int((left+right)/2)] while left <= right: while x > a[left]: left+=1 while x < a[right]: right-=1 if left <= right: temp = a[left] a[left] = a[right] a[right] = temp left+=1 right-=1 if low < right: quicksort(a, low, right) if left < high: quicksort(a, left, high) a = [9, 44, 32, 20, 8, 3, 2, 11, 25] quicksort(a,0,8) print(a)
a5751b20e9931346afc66f7ba12aab182c51efed
celeste16/gwc-2017
/trans.py
608
3.71875
4
class vehicle: def __init__(self, newName): self.name = newName self.wheels = 0 self.ignition = False self.passengers = [] def num_wheels(self, newWheels): self.wheels = newWheels def ignition(self, key): self.ignition = key def add_passenger(self, newPassenger): self.passengers.append(newPassenger) def main(): myCar = Vehicle("Convertible") myCar.num_wheels(4) myCar.add_passenger("CeCe") print(myCar.name, myCar.wheels, myCar.passengers) if __name__ =='__main__':
a12a56a7b8ed71919888333e7b25a0a403f88e22
AbdullahAleiti/Python-CMD-Tools
/pycont.py
5,273
3.671875
4
import sqlite3 import os import platform import re version = 4.4 #get platform type platform = platform.system() # the contacts list con_list = [] conn = sqlite3.connect("") def connect(): global conn; conn = sqlite3.connect("contacts.db") connect() try: conn.execute("CREATE TABLE contacts (name TEXT, number TEXT,address TEXT,email TEXT);") except sqlite3.OperationalError: pass def isContactInList(name): contacts_list() if name not in con_list: print "there is no contact named",name else: return True def help(): print "*** PyCont contacts manager <powerd by Aleiti Technologies all rights reserved> v {0} ***\ \ntype a to add a new contact.\ \ntype \"rm contactName\" to remove contact.\ \ntype \"ls\" to print out all the contacts.\ \ntype \"p contactName\" to print out contact information.\ \ntype \"edit contactName\" to update contact.\ \ntype \"exit\" to exit.\ \ntype \"clear\" to clear the screen.\ \ntype h to see this help list again.".format(version) def contacts_list(): cursor = conn.execute("SELECT * from contacts") for column in cursor: con_list.append(column[0]) return con_list def clear_screen(): if platform == "Windows": os.system('cls') elif platform == "Linux": os.system("clear") #program's main loop def start(): clear_screen() help() connect() while 1: del con_list[:] user_input = raw_input(); if user_input == "a": add_contact(); elif user_input == "exit": conn.close() if __name__ == '__main__': exit() else: break elif user_input == "clear": clear_screen() elif user_input == "h": help() elif user_input == "ls": print_all(); elif user_input == "": pass else : args = user_input.split() arg_length = len(args) if args[0] == "rm": if arg_length < 2: print "please identity a contact to delete." if arg_length is 2: if isContactInList(args[1]): rm_contact(args[1]) elif args[0] == "p": if arg_length < 2: print "please identity a contact to show." elif isContactInList(args[1]): print_contact(args[1]) elif args[0] == "edit": if arg_length < 2: print "please identity a contact to edit." elif isContactInList(args[1]): update(args[1]) else : print "unknown command." def add_contact(): #keep the contacts list up to date contacts_list() # get the name and make sure that it is not repeated and it has charcters while True: name = raw_input("enter contact's name : ") if name in con_list: print "contact name \"{0}\" is already in use.".format(name) if len(name) < 1: pass else: break #get number and make sure that it dosn't contain any letters while True: number = raw_input("number : ") if number.isalpha(): print "enter a vaild number ." else: break address = raw_input("address : ") email = raw_input("email : ") conn.execute("INSERT INTO contacts (name,number,address,email) VALUES (\"{0}\",\"{1}\",\"{2}\",\"{3}\");"\ .format(name,number,address,email)) conn.commit() def rm_contact(argument): conn.execute("DELETE FROM contacts WHERE name IS \"{0}\"".format(argument)) print "contact {0} deleted successfuly.".format(argument) conn.commit() # print the list of available contacts def print_all(): enum_contacts = contacts_list() x = 1 length = len(enum_contacts) if length is 0: print "sorry there is no contacts yet :(" return while True: if x == 1: print "**********" print enum_contacts[x - 1] if x is not length: print "----" if x is length: print "**********" break x += 1 def print_contact(argument): info = conn.execute("SELECT * FROM contacts WHERE name IS \"%s\""% argument) for column in info: print "\n< {0} >".format(column[0]) print "number : {0}".format(column[1]) print "address : {0}".format(column[2]) print "email : {0}".format(column[3]) print "***************" def update(name): #keep the contacts list up to date contacts_list() argument = name info = conn.execute("SELECT * FROM contacts WHERE name IS \"%s\""% argument) for column in info: name = column[0] number = column[1] address = column[2] email = column[3] print "press enter to keep it as it is" # get the name and make sure that it is not repeated while True: new_name = raw_input("name : {0} =====> ".format(name)) if new_name in con_list: print "contact name \"{0}\" is already in use.".format(new_name) elif len(new_name) is 0: new_name = name break else: break #get number and make sure that it dosn't contain any letters while True: new_number = raw_input("number : {0} =====> ".format(number)) if new_number.isalpha(): print "please enter a vaild number ." elif len(new_number) is 0: new_number = number break else: break new_address = raw_input("address : {0} =====> ".format(address)) if len(new_address) is 0: new_address = address new_email = raw_input("email : {0} =====> ".format(email)) if len(new_email) is 0: new_email = email conn.execute("UPDATE contacts SET name = \"{1}\",number = \"{2}\",address = \"{3}\",email = \"{4}\" WHERE name IS \"{0}\""\ .format(argument,new_name,new_number,new_address,new_email)) conn.commit() #starts the program if __name__ == '__main__': start()
e5b1a67469d88ea2a601046cec1b4bcf376e3de0
luckychummy/practice
/BalancedBrackets.py
894
3.921875
4
class Stack: def __init__(self): self.items=[] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if not self.is_empty(): return self.items[-1] def is_empty(self): return self.items==[] def getStack(self): return self.items def is_match(p1, p2): if p1 == '(' and p2 == ')': return True elif p1 == '{' and p2 == '}': return True elif p1 == '[' and p2 == ']': return True return False def isBalanced(pattern): index=0 isBalanced=True s=Stack() while isBalanced and index<len(pattern): p=pattern[index] if p=='(' or p=='{' or p=='[': s.push(p) else: if not s.is_empty(): p1=s.pop() if not is_match(p1, p): isBalanced=False else: isBalanced=False index+=1 return isBalanced print ("String : (((({})))) Balanced or not?") print(isBalanced("(((({})))"))
88eac262387beebc991ddff85fd38ed433c3e2ae
deisaack/SqlBeginerPractice
/main.py
7,433
3.765625
4
""" Module to read data from CSV files and HTML file to populate an SQL database ITEC649 2018 """ import csv import sqlite3 from database import DATABASE_NAME from bs4 import BeautifulSoup def read_csv_file(filename): """Read a csv file and return a list of dictionaries. :param filename: The file to be read. :return: The list of dictionaties. """ with open(filename, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') data = [] for row in reader: data.append(row) return data def load_person(c, person): """ Save a single person to database. :param db: The database connection. :param person: The person to be loaded :param c: Cuursor :return: None """ c.execute("INSERT INTO people VALUES (:id, :first_name, :middle_name, :last_name, :email, :phone)", { 'id': person['person_ID'], "first_name": person['first'], "middle_name": person['middle'], "last_name": person['last'], "email": person['email'], "phone": person['phone'] }) def load_people(db, c): """Insert people data from a csv file to database. :param db: An active database connection :param c: Cuursor :return: None """ people = read_csv_file("people.csv") for person in people: with db: load_person(c, person) def load_company(c, company): """ Save a single company to database. :param db: The database connection. :param person: The person to be loaded :param c: Cuursor :return: None """ c.execute("INSERT INTO companies VALUES (:id, :name, :url, :contact)", { "id": company['id'], "name": company['company'], "url": company['url'], "contact": company['contact'] }) def get_person_by_name(c, name): """ Provide the name from company contact and find the person from people table. :param c: Cursor :param name: Person name :return: Person tuple """ name_list = name.replace(',', '').split(' ') first_name = name_list[0] middle_name = name_list[1] try: last_name = name_list[2] except IndexError: last_name = name_list[1] middle_name = '' c.execute("SELECT * FROM people WHERE " "((((last_name=:first_name OR middle_name=:first_name) OR (first_name=:first_name OR middle_name=:first_name)) AND " "((last_name=:last_name OR middle_name=:last_name) OR (first_name=:last_name OR middle_name=:last_name))) AND " "((last_name=:middle_name OR middle_name=:middle_name) OR (first_name=:middle_name OR middle_name=:middle_name)))", {'first_name': first_name, "middle_name": middle_name, "last_name": last_name}) obj = c.fetchone() return obj def load_companies(db, c): """Insert companies data from a csv file to database. :param db: An active database connection :param c: Cuursor :return: None """ companies = read_csv_file("companies.csv") id = 1 for company in companies: company["id"]=id with db: p = get_person_by_name(c, company['contact']) company["contact"] = p[0] load_company(c, company) id+=1 """ <div class="card" style="width: 18rem;"> <div class="card-header"> <h5 class="card-title">Full Stack Developer</h5> <div class="company">Booking.com BV</div> </div> <div class="card-body"> <h6 class="card-subtitle mb-2 text-muted"> <span class="user">@Mandible:</span> <span class="timestamp">2018-03-01 16:22:28</span> </h6> <p class="card-text"> <p>Job Description:</p> <p>Booking.com is looking for Full Stack Developers all around the globe! </p> <a class="card-link" href="/positions/50">Read More</a> </p> </div> </div> """ def process_company_html(raw_html): """Process raw html from beautifulsoup :param raw_html: Raw soup instance object :return: Company Dict """ obj = { "title": raw_html.find("h5").text, "company": raw_html.find("div", class_="company").text, "location": raw_html.find("span", class_="user").text.replace('@', "").replace(':', ''), "timestamp": raw_html.find("span", class_="timestamp").text, "description": raw_html.p.text.strip().replace('Job Description:\n', '').replace("\nRead More", '') } return obj def html_job_reader(): """Reads the index.htmland returns list of Jaob objects. :return: """ with open("index.html") as fp: soup = BeautifulSoup(fp, features="html.parser") all_companies = soup.find_all("div", class_="card") data = [] for company in all_companies: data.append(process_company_html(company)) return data def get_company_by_name(c, name): """Given a merchant name, get and return the company from database :param c: cursor :param name: :return: company """ c.execute("SELECT * FROM companies WHERE name=:name", {'name': name}) obj = c.fetchone() return obj def save_job(db, c, job): """Save a job :param db: Database connection :param c: Cursor :return: """ c.execute("INSERT INTO positions VALUES (:id, :title, :location, :company)", { **job }) def save_jobs(db, c): """Reads and saves jobs :param db: Database connection :param c: Current cursor :return: None """ jobs = html_job_reader() id = 1 for job in jobs: with db: company = get_company_by_name(c, job['company']) job['company'] = company[0] job['id'] = id save_job(db, c, job) id +=1 def read_given_fields(c): """Read the fields tor generating csv :param db: Connection :param c: Cursor :return: """ # c.execute(""" # SELECT companies.id, companies.name, people.email # FROM # companies # INNER JOIN # people # ON # companies.contact=people.id # """) # print(c.fetchall()) c.execute(""" SELECT positions.title, positions.location, companies.name, people.first_name, people.last_name, people.email FROM positions JOIN companies ON positions.company = companies.id JOIN people ON companies.contact = people.id """) data = c.fetchall() return data def save_to_csv(db, c): """Fetch from database and save the final report to csv :param db: :param c: :return: """ with db: data = read_given_fields(c) with open("final.csv", "w", newline='') as f: writer = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerow(['Company Name', 'Position Title', 'Company Location', 'Contact FirstName', "Contact LastName", "Contact Email"]) for job in data: writer.writerow( [job[2], job[0].replace(',', ''), job[1], job[3], job[4], job[5]]) if __name__=='__main__': db = sqlite3.connect(DATABASE_NAME) c = db.cursor() load_people(db, c) load_companies(db, c) save_jobs(db, c) save_to_csv(db, c)
839cde49dfe44fc3131f96bd4268d59b48ce4bde
qimanchen/Algorithm_Python
/Chapter1/example_2_traffic_light.py
318
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def coloring(G): color = 0 groups = set() verts = vertices(G) while verts: new_group = set() for v in list(verts): if not_adjacent_with_set(v, newgroup, G): new_group.add(v) verts.remove(v) groups.add((color, new_group)) colort += 1 return groups
09242505e165c9f19b55d3e3c7bc2dba7b748c98
MastProTech/Advent-of-Code
/2020/03.py
1,374
3.828125
4
import re def read_file(file:str('03.txt')): try: fh=open(file) except FileNotFoundError: print('File Not Found. Exiting...') exit(1) line_list=list() for line in fh: line_sp=re.split('|\n', line) # Splitting each line character by character into a list line_sp=[i for i in line_sp if i!='' and i!=None] # For removing empty enteries in list line_list.append(line_sp) return line_list def count_trees(start:tuple((0,0)), right:int, down:int, line_list:list): row, col=start # NOTE: Even if start is out of range, it will be adjusted as col=col%len(line_list[0]) count=0 while True: row=row+down if row>=len(line_list): break # Break when reached at the bottom of line_list col=(col+right)%len(line_list[0]) if line_list[row][col]=='#': count=count+1 print('Right',right,'Down',down,':',count) return count line_list=read_file('03.txt') r1d1=count_trees(start=(0,0), right=1, down=1, line_list=line_list) r3d1=count_trees(start=(0,0), right=3, down=1, line_list=line_list) r5d1=count_trees(start=(0,0), right=5, down=1, line_list=line_list) r7d1=count_trees(start=(0,0), right=7, down=1, line_list=line_list) r1d2=count_trees(start=(0,0), right=1, down=2, line_list=line_list) total=r1d1*r3d1*r5d1*r7d1*r1d2 print('Total=',total)
635afdaf8e0885d93bbcb71963930502ab7cdca0
sari22patel/OperlappingElipsesUsingMonteCarloSimulation
/ellipse.py
9,982
4.5
4
#Point Class for cal distance from math import sqrt from math import pi class Point: """ This class store information about a point in a catersian coordinate system and perform operations on these points. Attributes: x (int): x coordinate of point y (int): y coordinate of point """ def __init__(self, x=0, y=0): """ The constructor of Point class. Parameters: x (int): x coordinate of point y (int): y coordinate of point """ self.x = x self.y = y def __str__(self): """ The string representation of Point class. Returns: st: String representation of Point class. """ st = "Point({}, {})".format(self.x, self.y) return st def setX(self, x): """ Class method to set x coordinate of Point. Parameters: x (int): x coordinate of point """ self.x = x def setY(self, y): """ Class method to set x coordinate of Point. Parameters: y (int): y coordinate of point """ self.y = y def getX(self): """ Class method to return x coordinate of Point. Returns: x (int): x coordinate of point """ return self.x def getY(self): """ Class method to return y coordinate of Point. Returns: y (int): y coordinate of point """ return self.y def getDistanceTo(self, b): """ This method calculates teh distance between the point and an another point passed to the method as parameter. Parameters: b (Point): Point to compute distance to. Returns: dist (float): distance of given point to another point """ dist = sqrt((((b.getX() - self.getX())**2) + ((b.getY() - self.getY())**2))) return round(dist, 4) class Rectangle: """ This class store information about a Rectance object and returns imoprtant properties of a Rectangle. Attributes: lowerLeftX (int): x coordinate of the lower left point of Rectagle lowerLeftY (int): y coordinate of the lower left point of Rectagle upperRightX (int): x coordinate of the upper right point of Rectagle upperRightY (int): y coordinate of the upper right point of Rectagle """ def __init__(self, lowerLeftX=0, lowerLeftY=0, upperRightX=1, upperRightY=1): """ The constructor of Rectangle class. Parameters: lowerLeftX (int): x coordinate of the lower left point of Rectagle lowerLeftY (int): y coordinate of the lower left point of Rectagle upperRightX (int): x coordinate of the upper right point of Rectagle upperRightY (int): y coordinate of the upper right point of Rectagle """ self.lowerLeftX = lowerLeftX self.lowerLeftY = lowerLeftY self.upperRightX = upperRightX self.upperRightY = upperRightY def __repr__(self): return "Rectangle({}, {}, {}, {})".format(self.lowerLeftX, self.lowerLeftY, self.upperRightX, self.upperRightY) def __eq__(self, obj): return self.getLowerLeftX() == obj.getLowerLeftX() and self.getLowerLeftY() == obj.getLowerLeftY() and self.getUpperRightX() == obj.getUpperRightX() and self.getUpperRightY() == obj.getUpperRightY() def setLowerLeftX(self, lowerLeftX): """ Class method to set lowerLeftX of Rectangle. Parameters: lowerLeftX (int): x coordinate of the lower left point of Rectagle """ self.lowerLeftX = lowerLeftX def setLowerLeftY(self, lowerLeftY): """ Class method to set lowerLeftY of Rectangle. Parameters: lowerLeftY (int): y coordinate of the lower left point of Rectagle """ self.lowerLeftY = lowerLeftY def setUpperRightX(self, upperRightX): """ Class method to set upperRightX of Rectangle. Parameters: upperRightX (int): x coordinate of the upper right point of Rectagle """ self.upperRightX = upperRightX def setUpperRightY(self, upperRightY): """ Class method to set upperRightY of Rectangle. Parameters: upperRightY (int): y coordinate of the upper right point of Rectagle """ self.upperRightY = upperRightY def getLowerLeftX(self): """ Class method to return lowerLeftX of Rectangle. Returns: lowerLeftX (int): x coordinate of the lower left point of Rectagle """ return float(self.lowerLeftX) def getLowerLeftY(self): """ Class method to return lowerLeftY of Rectangle. Returns: lowerLeftY (int): y coordinate of the lower left point of Rectagle """ return float(self.lowerLeftY) def getUpperRightX(self): """ Class method to return upperRightX of Rectangle. Returns: upperRightX (int): x coordinate of the upper right point of Rectagle """ return float(self.upperRightX) def getUpperRightY(self): """ Class method to return upperRightY of Rectangle. Returns: upperRightY (int): y coordinate of the upper right point of Rectagle """ return float(self.upperRightY) def getArea(self): """ Method to compute the area of Rectangle. Returns: area: Area of rectangle. """ length = self.getUpperRightX() - self.getLowerLeftX() width = self.getUpperRightY() - self.getLowerLeftY() area = length*width return area class Ellipse: """ This class store information about an Ellipse and returns important properties of Ellipse. Attributes: focalPoint1 (Point): Focal Point 1 of Ellipse focalPoint2 (Point): Focal Point 2 of Ellipse width (float): width of the Ellipse. """ def __init__(self, focalPoint1, focalPoint2, width): """ Constructor for Ellipse class. Parameters: focalPoint1 (Point): Focal Point 1 of Ellipse focalPoint2 (Point): Focal Point 2 of Ellipse width (float): width of the Ellipse. """ self.focalPoint1 = focalPoint1 self.focalPoint2 = focalPoint2 self.width = width def __str__(self): """ String repesentation for Ellipse. Returns: st: String represntation of Ellipse. """ st = "Focal Point 1: {}\n"\ "Focal Point 2: {}\n"\ "Width: {}\n"\ "Major Axis: {}\n"\ "Minor Axis: {}\n"\ "Area: {}\n"\ "Circumference: {}\n".format(self.focalPoint1, self.focalPoint2, self.width, self.getMajorAxis(), self.getMinorAxis(), self.getArea(), self.getCircumference()) return st def setFocalPoint1(self, focalPoint1): """ Class method to set focalPoint1 of Ellipse. Parameters: focalPoint1 (Point): Focal Point 1 of Ellipse """ self.focalPoint1 = focalPoint1 def setFocalPoint2(self, focalPoint2): """ Class method to set focalPoint2 of Ellipse. Parameters: focalPoint2 (Point): Focal Point 2 of Ellipse """ self.focalPoint2 = focalPoint2 def setWidth(self, width): """ Class method to set width of Ellipse. Parameters: width (float): width of the Ellipse. """ self.width = width def getFocalPoint1(self): """ Class method to return focalPoint1 of Ellipse. Returns: focalPoint1 (Point): Focal Point 1 of Ellipse """ return self.focalPoint1 def getFocalPoint2(self): """ Class method to return focalPoint2 of Ellipse. Returns: focalPoint2 (Point): Focal Point 2 of Ellipse """ return self.focalPoint2 def getWidth(self): """ Class method to return width of Ellipse. Returns: width (float): width of the Ellipse. """ return self.width def getDistanceBetweenFoci(self): """ Calculate and return the distance between two focal points of Ellipse Returns: getDistanceBetweenFoci (float): width of the Ellipse. """ distanceBetweenFoci = self.focalPoint1.getDistanceTo(self.focalPoint2) return distanceBetweenFoci def getMajorAxis(self): """ Return the length of Major axis of Ellipse Returns: majorAxis (float): Length of Major Axis of the Ellipse. """ majorAxis = self.width return majorAxis def getMinorAxis(self): """ Calculate and Return the length of Minor axis of Ellipse Returns: minorAxis (float): Length of Minor Axis of the Ellipse. """ minorAxis = round((sqrt(((self.getMajorAxis()/2)**2) - ((self.getDistanceBetweenFoci()/2)**2)))*2, 4) return minorAxis def getArea(self): """ Calculate and Return the area of Ellipse Returns: area (float): Area of the Ellipse. """ area = round(pi*(self.getMajorAxis()/2)*(self.getMinorAxis()/2), 4) return area def getCircumference(self): """ Calculate and Return the circumference of Ellipse Returns: circumference (float): Circumference of the Ellipse. """ circumference = pi*((3*((self.getMajorAxis()/2) + (self.getMinorAxis()/2))) - (sqrt((3*(self.getMajorAxis()/2) + (self.getMinorAxis()/2))* (3*(self.getMinorAxis()/2) + (self.getMajorAxis()/2))))) return round(circumference, 4)
d72a59f45d0fd857125d1f37fd3d7c22d7dc69e8
Maksssusaxa/AByteOfPython
/func_doc.py
413
4.1875
4
def printMax(x,y): '''Выводит максимально из двух чисел. Оба числа должны быть целыми числами.''' x = int(x) # Конвертируем в целые, если возможно y = int(y) if x > y: print(x, 'Наибольшее') else: print(y, 'Нибольшее') printMax(3, 5) print(printMax.__doc__)
f77092fd3f80e017e48b5a9cc8ff929b0277b264
pydevjason/Python-VS-code
/classes_protected_attributes_and_methods.py
2,754
4.3125
4
# the Python community standard for promoting encapsulation of attributes on an object are to declare an _underscore before the attribute name. This lets other developers know that these attributes should not be modified. class SmartPhone(): def __init__(self): self._company = "Apple" self._firmware = 10.0 def update_firmware(self): print("contacting server for available updates...") self._firmware += 1 iphone = SmartPhone() print(iphone._company) print(iphone._firmware) iphone.update_firmware() print(iphone._firmware) print() # book.py # Let’s say we want to model a Book as a Python object. # A Book has an author and a publisher, which are characteristics that cannot change. # A Book also has a page_count, which could be altered if you rip some pages from the book. # Declare a Book class that accepts author, publisher, and page_count parameters. # Each of the parameters should be assigned to an attribute. # The author and publisher attributes should be designated as protected (use an underscore). # The page_count attribute should be designated public. # Define a copyright instance method that returns a string with information about the copyright. # It should look the string below, where “Grant Cardone” is the value of the protected # author attribute and “10X Enterprises” is the value of the protected publisher attribute. # => Copyright Grant Cardone, 10X Enterprises # The public page_count attribute can always be manually modified. # However, we can still define an instance method that modifies it. # Declare a rip_in_half instance method. # If the book has more than 1 page, it should halve the page_count. # If the book has 1 page or less, it should set the page_count to 0. # See sample execution below class Book(): def __init__(self, author, publisher, page_count): self._author = author self._publisher = publisher self.page_count = page_count def copyright(self): return f"Copyright {self._author}, {self._publisher}" def rip_in_half(self): if self.page_count > 1: self.page_count /= 2 else: self.page_count = 0 book = Book(author = "Grant Cardone", publisher = "10X Enterprises", page_count = 10) print(book.copyright()) # Copyright Grant Cardone, 10X Enterprises print(book.page_count) # 10 book.rip_in_half() print(book.page_count) # 5.0 book.rip_in_half() print(book.page_count) # 2.5 book.rip_in_half() print(book.page_count) # 1.25 book.rip_in_half() print(book.page_count) # 0.625 book.rip_in_half() print(book.page_count) # 0 book.rip_in_half() print(book.page_count) # 0
af3cf77b5536621c42c7ec4c5a0d7dea6752840f
SYSH/python_project
/python_ebook_01/exceptionexample/exceptionexample.py
1,332
3.953125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Exception example 01-->try...except...的用法 try: file("hello.txt",'r') print "读文件" except IOError: print "文件不存在" except: print "程序异常" print '--------------------------------------' # Exception example 02 try: result = 10/0 except ZeroDivisionError: print "0不能做除数" else: print result print '--------------------------------------' # Exception example 03 try: s = 'hello' try: print s[0] + s[1] print s[0] - s[1] except TypeError: print "字符串不支持减法运算" except: print '异常' print '--------------------------------------' # Exception example 04-->try...finally...的用法 # finally错误的用法 try: f=open('hello.txt','r') try: print f.read(5) except: print "读取文件错误" finally: print "释放资源" f.close() except IOError: print '文件不存在' print '--------------------------------------' # Exception example 05-->使用raise抛出异常 try: s = None if s is None: print "s是空对象" raise NameError print len(s) except TypeError: print "空对象没有长度"
9c0f4d8a08d58fbcfe679279d196834c3d7c3b8e
FernandoReyesV2/Tarea-S1---ED
/S1 Tarea While - Ed.py
144
3.53125
4
#Elabore código para el caso en que se desean escribir los números del 1 al 100 i = 1 while i<=100: print(i) i = i+1
254b8e50d3adfb4776da00f548c0e55a07c3a9fa
codeCrown12/Python-Algorithms
/problem5.py
769
4.09375
4
# An english student named John is currently doing an internship program in a grammar school. # He has been given a task to document the number of vowels and consonants in a given word. So you have # been hired by John to help automate the process by writing a program to solve the problem # Example: countletters("King") -> [vowels: 1, consonants: 3] def countvowels(word): answer = [] vowelcount = 0 conscount = 0 vowels = "aeiou" for letter in word: if letter in vowels: vowelcount += 1 else: conscount += 1 answer.append(vowelcount) answer.append(conscount) return answer val = input("Enter word: ") ansarr = countvowels(val.lower()) print(f"[vowels: {ansarr[0]}, consonants: {ansarr[1]}]")
d6ab94a5449e968ccf027d3110bee9b749519386
casey-stephens/Retirement_Home
/FloorNode.py
1,711
3.890625
4
from RoomNode import * class FloorNode(): def __init__(self, up =None, down = None, room_header = None, floor_number = None, is_head = False): self.up = FloorNode #up and down are each a floor node. if ground level, down will be null. vice versa for top level self.down = FloorNode self.room_header = RoomNode #each floor will have a room header to start the room linked list, think of it as the elevator exit, next room is the first on the floor self.floor_number = None self.is_head = False #used to indicate if the floor node is the header node, aka: ground floor def setUp(self,up_node): if isinstance(up_node,FloorNode): self.up = up_node else: print("Must be a floor node") def setDown(self,down_node): if isinstance(down_node,FloorNode): self.down = down_node else: print("Must be a floor node") def setFloor(self,new_floor): if isinstance(new_floor,int): self.floor_number = new_floor else: print("Floor number must be an integer") def setIsHead(self, is_ground): if isinstance(is_ground,bool): self.is_head = is_ground def getFloor(self): return self.floor_number def getUp(self): return self.up def getDown(self): return self.down def getRoomHeader(self): return self.room_header def setRoomHeader(self,new_room_node): if isinstance(new_room_node, RoomNode): self.room_header = new_room_node else: print("Room header must be a floor node")
9fed83ba29bf349d6ce8029f2e470191c4e35646
Error401-Unauthorized/snapsInSpace
/PythonDemo/GenerateStamp.py
2,876
3.53125
4
# -*- coding: utf-8 -*- from PIL import Image, ImageFilter, ImageDraw, ImageFont # params are string, float, float. keep the floats to 3 digits left of decimal (ex: 140.44) def Generate_Stamp(satellite_name, elevation_degrees, azmith_degrees): # background base = Image.open("BlankStamp2.png") # transparent layer for the text txt = Image.new('RGBA', base.size, (255, 255, 255, 0)) #add the font for big text, 2nd param is the font point size leng = len(satellite_name) if (leng < 10): fnt = ImageFont.truetype('nasalization-rg.ttf', 220) #print("1") elif (leng >= 10 and leng < 12): fnt = ImageFont.truetype('nasalization-rg.ttf', 180) #print("2") elif (leng >= 12 and leng < 15): fnt = ImageFont.truetype('nasalization-rg.ttf', 150) #print("3") elif (leng >= 15 and leng < 17): fnt = ImageFont.truetype('nasalization-rg.ttf', 130) #print("4") elif (leng >= 17 and leng < 19): fnt = ImageFont.truetype('nasalization-rg.ttf', 120) #print("5") else: fnt = ImageFont.truetype('nasalization-rg.ttf', 100) # "get a drawing context" -from PIL website # basically makes an image drawable (maybe???) d = ImageDraw.Draw(txt) # converting to the internal variable I used, a vestage from the previous development satName = satellite_name # constants for satellite text x, y = (2280, 1200) w, h = fnt.getsize(satName) # Draw some text # Params: # 1. tuple (x, y) # 2. text string # 3. font=the_font_you_import # 4. fill=(r,g,b,alpha) d.text(((x-w)/2,(y-h)/2), satName, font=fnt, fill=(255,255,255,255)) # , align="center" # print((y-h)/2) debugging # Make the font for the elivation and azmith fnt2 = ImageFont.truetype('nasalization-rg.ttf', 60) elevationNum = elevation_degrees elevationStr = "elevation: " + '%.1f' % elevationNum + "°" azmithNum = azmith_degrees azmithStr = "azmith: " + '%.1f' % azmithNum + "°" # Draw the azmith and elevation rightCorner = (x+w)/2 # to left justify these width, height = fnt2.getsize(elevationStr) # to place the text box on leftCorner = rightCorner - width fnt2.getsize(elevationStr) # to place the text box on # the y cordinate that the two strings are based on eleAsmHeight = 710 # draw elevation d.text((leftCorner, eleAsmHeight), elevationStr, font=fnt2, fill=(255,255,255,255)) # Azmith line setup azmithOffset = 0 azmithTop = eleAsmHeight + height + azmithOffset width2, height2 = fnt2.getsize(azmithStr) # to place the text box on leftCorner2 = rightCorner - width2 # drawing the azmith line d.text((leftCorner2, azmithTop), azmithStr, font=fnt2, fill=(255,255,255,255)) # make the two images into one by superimposing out = Image.alpha_composite(base, txt) out.save(satellite_name + "_" + str(elevation_degrees) + "_" + str(azmith_degrees) + ".png") satName = "Example Sat" satEle = 144.2 satAzm = 281.7 Generate_Stamp(satName, satEle, satAzm)
d54ac4eaa14c79c859441bd5bf9b34e549f55217
theguyoverthere/CMU15-112-Spring17
/src/Week10/Recursion/Getting Started/vowelCount.py
335
3.828125
4
def vowelCount(s): if len(s) == 0: return 0 elif len(s) == 1: return s[0].upper() in "AEIOU" else: thisCount = vowelCount(s[0]) restCount = vowelCount(s[1:]) return thisCount + restCount assert(vowelCount("") == 0) assert(vowelCount("I am reeeallly happy!!! :-)") == 7) print("ok!")
e9b8ec5b74984d3a814936467d60e5b5d24c6c89
Joebomb34/gitRemoteRepoSE126
/SE126/Lab4/Bombassei_4A.py
4,223
3.671875
4
#Joe Bombassei #SE126.02 #Lab 4A #8/11/21 #Program Prompt: Process the text file to a list, and reprocess the file to print the House motto, print each house fully with motto, total number of people in the list, average age, and tallies for each alliance. #Variable Dictionary: #records - number of records processed #age_total - total of added ages #house_stark - number of tallies for #nights_watch - number of tallies for #house_tully - number of tallies for #house_lannister - number of tallies for #house_baratheon - number of tallies for #house_taragaryen - number of tallies for #fname - first name in the list #lname - last name in list #age - age in the list #nickname - nickname in the list #allegiance - allegiance in the list #motto_list - house motto list #csvfile - lab4 txt file #file - csvfile after reader #average - average age of all charectors in record #Main Code------ import csv records = 0 age_total = 0 house_stark = 0 nights_watch = 0 house_tully = 0 house_lannister = 0 house_baratheon = 0 house_targaryen = 0 fname = [] lname = [] age = [] nickname = [] allegiance = [] motto_list = [] with open("Lab4/lab4A_GOT_NEW.txt") as csvfile: file = csv.reader(csvfile) for rec in file: records += 1 fname.append(rec[0]) lname.append(rec[1]) age.append(int(rec[2])) nickname.append(rec[3]) allegiance.append(rec[4]) # for i in range(0, records): nooooooooooooooooooo if rec[4] == "House Stark": motto = "Winter is Coming." elif rec[4] == "House Baratheon": motto = "Ours is the fury." elif rec[4] == "House Tully": motto = "Family. Duty. Honor." elif rec[4] == "Night's Watch": motto = "And now my watch begins" elif rec[4] == "House Lannister": motto = "Hear me roar!" elif rec[4] == "House Targaryen": motto = "Fire & Blood" motto_list.append(motto) if rec[4] == "House Stark": house_stark += 1 elif rec[4] == "House Baratheon": house_baratheon += 1 elif rec[4] == "House Tully": house_tully += 1 elif rec[4] == "Night's Watch": nights_watch += 1 elif rec[4] == "House Lannister": house_lannister += 1 elif rec[4] == "House Targaryen": house_targaryen += 1 print("---ORIGINAL FILE DATA----------------------------------------------------") print("{0:15}\t{1:15}\t{2:3}\t{3:10}\t{4:5}".format("FIRST", "LAST", "AGE", "NICKNAME", "ALLEGIANCE")) print("-------------------------------------------------------------------------") for i in range(0, records): print("{0:15}\t{1:10}\t{2:3}\t{3:18}\t{4:5}".format(fname[i], lname[i], age[i], nickname[i], allegiance[i])) print("--------------------------------") print("{0:27}".format("HOUSE MOTTO")) print("--------------------------------") for i in range(0, records): print("{0:27}".format(motto_list[i])) print("--------------------------------------------------------------------------------------------------------------") print("{0:15}\t{1:15}\t{2:3}\t{3:18}\t{4:18}\t{5:27}".format("FIRST", "LAST", "AGE", "NICKNAME", "ALLEGIANCE", "MOTTO")) print("--------------------------------------------------------------------------------------------------------------") for i in range(0, records): print("{0:15}\t{1:15}\t{2:3}\t{3:18}\t{4:18}\t{5:27}".format(fname[i], lname[i], age[i], nickname[i], allegiance[i], motto_list[i])) print("-----------------") print("NUMBER OF RECORDS") print("-----------------") print("{0:3}".format(records)) print("-----------") print("AVERAGE AGE") print("-----------") for i in range(0, records): age_total += age[i] average = age_total / records print("{0:3.2f}".format(average)) print("--------------------------------") print(" House Stark: {0}".format(house_stark)) print(" House Tully: {0}".format(house_tully)) print(" Night's Watch: {0}".format(nights_watch)) print("House Lannister: {0}".format(house_lannister)) print("House Baratheon: {0}".format(house_baratheon)) print("House Targaryen: {0}".format(house_targaryen))
20ebb9f69b947d1fccd11059d29a77490566ac53
Echowwlwz123/learn7
/python_practice/内置函数-高阶函数.py
4,115
3.890625
4
# -*- coding: utf-8 -*- # @Time : 2021/6/19 15:27 # @Author : WANGWEILI # @FileName: 内置函数-高阶函数.py # @Software: PyCharm # sorted() """ 功能:排序 把可迭代数据里的元素,一个一个取出来,放到KEY这个函数中处理 并按照函数中return的结果进行排序,返回一个新的列表 参数: iterable 可迭代的数据 reverse 可选,是否反转,默认False,不反转,True 反转 key 可选,函数,可以自定义函数,也可以是内置函数 """ from functools import reduce arr = [3, 7, 1, -9, 10] # res = sorted(arr)#[-9, 1, 3, 7, 10] # res = sorted(arr,reverse=True)#[10, 7, 3, 1, -9] # res = sorted(arr,key=abs)#[1, 3, 7, -9, 10] arr = [3, 7, 1, -9, 10] def func(num): return num % 2 res = sorted(arr, key=func) print(res) # [10, 3, 7, 1, -9] # 优化 res = sorted(arr, key=lambda x: x % 2) print(res) # [10, 3, 7, 1, -9] # map() """ map(func,*iterable) 功能:对传入的可迭代数据中的每个元素放入到函数中进行处理,返回一个新的迭代器 参数: func 函数 自定义函数|内置函数 iterables:可迭代数据 返回值:迭代器 """ # varlist = ['1','2','3','4'] # newlist = [] # for i in varlist: # newlist.append(int(i)) # print(newlist) # 案例1 varlist = ['1', '2', '3', '4'] res = map(int, varlist) res2 = map(str, *map(res)) print(list(res), list(res2)) # 案例2 [1,2,3,4]==>[1,4,9,16] # 方法1: num = [1, 2, 3, 4] newlist = [] for i in num: newlist.append(i ** 2) print(newlist) # 方法2: num = [1, 2, 3, 4] res = map(lambda x: x ** 2, num) print(list(res)) # 案例3 ['a','b','c','d']==>[65,66,67,68] varlist = ['a', 'b', 'c', 'd'] newlist = [] # 分配一个新的列表 # 先把列表中的每个元素都变成大写字符 for i in varlist: newlist.append(i.upper()) # 用map函数,ord(把字母转换成asci码值) res = map(ord, newlist) print(list(res)) # reduce() """ reduce(func,*iterable) 功能: 每一次从iterable中拿出两个元素,放入到func中处理,得出一个计算结果 然后把这个计算结果和iterable中的第三个元素,放入到func函数中继续运算 得出的结果和之后的第四个元素,加入到func函数中进行处理,以此类推, 直到最后一个元素参与运算 参数: func : 内置函数|自定义函数 iterable: 可迭代数据 返回值:最终的运算处理结果 注意:使用reduce函数时需要导入from functools import reduce """ # 案例1:[5,2,1,1]==>5211 # 方法1: varlist = [5, 2, 1, 1] res = '' for i in varlist: print(i, type(i)) res += str(i) res = int(res) print(res) # 方法2: varlist = [5, 2, 1, 1] res = reduce(lambda i, j: i * 10 + j, varlist) print(res) # 案例2:把字符串'456'==>456 # 方法1: varlist = '456' res = int(varlist) print(res) # 方法2: varlist = '456' # it1 = map(int,varlist) res = reduce(lambda x, y: x * 10 + y, map(int, varlist)) print(res) # 方法3:不使用int函数 varlist = '456' def func(s): dic = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return dic[s] # iter1 = map(func,varlist) res = reduce(lambda x, y: x * 10 + y, map(func, varlist)) print(res) # filter() """ filter(func,iterable) 功能:过滤数据,把iterable中的每个元素拿到func函数中进行处理, 如果函数返回True则保留这个数据,返回False则丢弃这个数据 参数: func :自定义函数 iterable: 可迭代的数据 返回值:保留下来的数据组成的迭代器 """ # 案例1:要求保留所有的偶数,丢弃所有的奇数 varlist = [1, 2, 3, 4, 5, 6, 7, 8, 9] newlist = [] for i in varlist: if i % 2 == 0: newlist.append(i) print(newlist) # 方法2: def func(n): if n % 2 == 0: return True else: return False varlist = [1, 2, 3, 4, 5, 6, 7, 8, 9] res = filter(func, varlist) print(list(res)) # 方法3: varlist = [1, 2, 3, 4, 5, 6, 7, 8, 9] res = filter(lambda x: True if x % 2 == 0 else False, varlist) print(list(res))
9040c018dbb23e4676bb909f850e248aa1d91f4e
mathdoll/python
/OldPythonCode/sum up to n.py
71
3.5
4
n=11 sum=0 for i in range(1,n+1): sum=sum+i print(i, sum) print(sum)
0085ad787af1a26a9f6bac02c9e4a0332658adbb
Fadarrizz/LAD
/amstelhaege/algorithms/simulatedannealing.py
2,331
3.984375
4
# course: Heuristieken # team: LADs # names: Daniel Walters, Auke Geerts, Leyla Banchaewa # file: simulatedannealing.py # description: This file contains the Simulated Annealing algorithm. from classes.classes import * from functions.helpers import * from algorithms import randomfunction import math import matplotlib.pyplot as plt import random def SimulatedAnnealing(count): # empty array TotalScore.Scores = [] # scores Array Scores = TotalScore.Scores # calculate total score oldScore = TotalScore.totalScore() # save begin score beginScore = oldScore # define newScore newScore = 0 # define iterations SIZE = 20 # define initial temperature and minimal temperature c = 1 c_min = 0.000001 # define alpha, the cooling factor a = 0.9 while c > c_min: for i in range(SIZE): # choose random building from Building.buildingsPlaced b1 = Building.buildingsPlaced[RandomBuilding()] oldX = b1.x oldY = b1.y # define acceptance probility ap = (oldScore - newScore) / c # generate new coords and calculate new total score newScore = ImproveScoreByGeneratingNewCoords(b1, oldScore) # if score has improved, accept improvement if CheckScoreImprovement(oldScore, newScore): oldScore = newScore # randomly decide to accept deteriorations elif ap > random.random(): # Calculate total score oldScore = newScore # else, change back coordinates else: b1.x = oldX b1.y = oldY # decrease temperature c = c * a TotalScore.Scores.append(oldScore) oldScore = GetHighestScore(TotalScore.Scores) # variables for printing endScore = oldScore - beginScore iterationScore = endScore / SIZE with open('SA60.txt', 'a') as f: print("iteration:", count, file=f) print("Begin score:", beginScore, file=f) print("New score", oldScore, file=f) print("Improvement on score: ${:,.2f}".format(endScore), file=f) print("Average improvement per iteration: ${:,.2f}".format(iterationScore), file=f) print("\n", file=f) return oldScore
8b0e9faa943d462e7e44bcc90587ecd94b5f2e1a
edbeeching/ProjectEuler
/Problem_036.py
367
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 29 17:33:12 2017 @author: Edward """ def is_palindromic_b10b2(n): return str(n) == str(n)[::-1] and str(bin(n))[2:] == str(bin(n))[:1:-1] sum_palindromes = 0 for i in range(1000000): if is_palindromic_b10b2(i): sum_palindromes += i print(sum_palindromes)
a0625940a171325595703fd28df0898c9691a191
saleem-hadad/codeforces
/520A.py
109
3.71875
4
n = int(raw_input()) s = raw_input() s = set(s.lower()) if len(s) == 26: print "YES" else: print "NO"
9edc26099e8e8f9161a2702817f7c669ac9c33d4
grivanov/python-basics-sept-2021
/V.02-exam-preparation.py
713
3.90625
4
limit_bad_grades = int(input()) count_bad_grades = 0 count_grades = 0 sum_grades = 0 problem_name = str() while count_bad_grades < limit_bad_grades: user_input = input() if user_input != "Enough": problem_name = user_input problem_grade = int(input()) else: break if problem_grade <= 4: count_bad_grades += 1 sum_grades += problem_grade count_grades += 1 if count_bad_grades == limit_bad_grades: print(f"You need a break, {count_bad_grades} poor grades.") else: average = sum_grades / count_grades print(f"Average score: {average:.2f}") print(f"Number of problems: {count_grades}") print(f"Last problem: {problem_name}")
e6f52fc3435d925165c8c68ca92a16d4203f7c63
ketasaka/Python_study
/11.ユーザー定義クラス(オブジェクト)/11_1.py
518
3.796875
4
class Circle: PI = 3.1415 def ensyu(r): m = int(r * 2 * Circle.PI * 1000) m = m / 1000 return m def menseki(r): m = int(r * r * Circle.PI * 1000) m = m / 1000 return m def print(r) -> None: ensyu = Circle.ensyu(r) menseki = Circle.menseki(r) print("円周の長さは{}です。".format(ensyu)) print("円周の面積は{}です。".format(menseki)) a = int(input("半径を整数値で入力:")) Circle.print(a)
dc9998563d621636d9e08f27851b9ae6e2ef9305
genji10122/python
/randint.py
680
3.953125
4
from random import randint name = ['Genji', 'Widowmaker' , 'Junkrat'] verb = ['kicks' , 'destroyes' , 'bombs'] noun = ['Hanzo' , 'gerrard' , 'people'] def sentences(words): ''' (list of strings) -> (string) returns any word from a list of words >>> sentences(['Genji', 'Widowmaker' , 'Junkrat']) >>> Widowmaker ''' ## ['Genji', 'Widowmaker' , 'Junkrat'] ## 0 1 2 ## LENGTH = 3 numwords = len(words) - 1 ##length of 3, acces last element which is 2 pick = randint(0, numwords) return words[pick] print(sentences(name) , sentences(verb) , sentences (noun) , end= '.\n')
574511ca43be65e87f6d834f1c015d1ca98b7522
farinfallah/Python-for-Beginners
/Week3/Vote.py
252
3.5625
4
#Farinaz Fallahpour n = int(input()) country = {} for i in range(0, n): element = input() if element in country.keys(): country[element] += 1 else: country[element] = 1 for key in sorted(country.keys()): print(key, country[key])
8e492e64498639ac66e97c977ca6849f83b9f683
oo1993448102/Grab
/Expection.py
669
3.765625
4
# import logging # # # like try..catch.. # try: # text = input('Try now') # # 指明错误类型 # # except EOFError: # # print('EOFError') # # print('EOFError') # # # 未知错误类型 # except : # print('fail') # else: # print(text) # 自定义异常 import logging class TooShortException(Exception): def __init__(self,description): self.description = description print(description) try: text = input("Exception") if(len(text)<3): # 异常抛出 raise TooShortException("too short") except: print("raise") else: print('success') finally: print('always') logging.info('logging')
2dd279d2ca7b6507dfa654fd8ba3f3ca22399833
R-3030casa/Scripte_Python
/Donwload_python/Script cursoemvideo/exer006.py
332
4.03125
4
'''Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.''' import math num =int(input('Digite um número : ')) n=num d = num*2 t = num*3 r = math.sqrt(num) print('O dobro de {} vale ={} , o triplo de {} vale = {} e a raiz de {} vale = {:.3f}'.format(n,d,n,t,n,r)) print('Raiz quadrado é =',num**0.5)
64afc226827c140ad00e3ebfe22463b85a265cc5
laurelwilliamson/python-challenge
/PyPoll/main.py
1,758
3.6875
4
#Import modules import pandas as pd import sys stdoutOrigin=sys.stdout sys.stdout = open("log.txt", "w") #Create reference to CSV file csvpath = "Resources/election_data.csv" #Import the CSV into a pandas DataFrame election_df = pd.read_csv(csvpath, low_memory=False) print("Election Results") print("-------------------------") #The total number of votes cast total_votes = len(election_df.index) print(f"Total Votes: " + str(total_votes)) print("-------------------------") #The percentage of votes each candidate won, total number of votes each candidate won, winner of the election based on popular vote. candidates_names = election_df["Candidate"].unique() candidates_count = election_df["Candidate"].value_counts() candidates_percent = election_df["Candidate"].value_counts(normalize=True).mul(100).round(3).astype(str)+ '%' max = 0 for i in range(0,len(candidates_percent)): if max < candidates_count[i]: max = candidates_count[i] winner = candidates_names[i] print(str(candidates_names[i])+':', candidates_percent[i], '('+ str(candidates_count[i])+ ')') print("-------------------------") print("Winner:", winner) print("-------------------------") #Export a text file with the results sys.stdout.close() sys.stdout=stdoutOrigin print("Election Results") print("-------------------------") print(f"Total Votes: " + str(total_votes)) print("-------------------------") max = 0 for i in range(0,len(candidates_percent)): if max < candidates_count[i]: max = candidates_count[i] winner = candidates_names[i] print(str(candidates_names[i])+':', candidates_percent[i], '('+ str(candidates_count[i])+ ')') print("-------------------------") print("Winner:", winner) print("-------------------------")
47e36b15a1989106ba119f5f04298e016e6d77f0
chriswood/eulerproject
/p41-60/prob48.py
187
3.59375
4
# Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000. limit = 1000 total = 0 for i in range(1, limit + 1): total += pow(i, i) print("sum = {0}".format(total))
51c3189f617de01ec1b85c12681504f03a8abb6c
lrlab-nlp100/nlp100
/masuda/nlp00.py
116
3.609375
4
str = "stressed" rev = "" for i in range(len(str)): rev = rev + str[-i-1] print(rev) # print(str[::-1])
8e048a9dbd83d4106768ca6630ac445ebbcb9375
BmHB0tcHi/Python-
/Basics/basics-1.py
647
4.21875
4
#working with vairable # price = 10 # print(price) #input style #\\\\\\ # name = input('what is your name?: ') # print('hi ' +name) # color = input('whats ur favorite color?: ') # print(name + ' likes ' +color) # /////// #whatever is wrote in terminal is treated as a string## #converting variable from one type to other #example # birth_year = input('What is your birth year?: ') # age = 2022 - int(birth_year) # print('your are ' +str(age) +' years old!') #//// # weight_lbs = input('Your weight in pounds: ') # weight_kg = float(weight_lbs) *0.45 # print(str(weight_kg)) #///
1b26947b9464d308803e99b794f8a9b11fd76816
jahokas/Python_Workout_50_Essential_Exercises_by_Reuven_M_Lerner
/exercise_12_word_with_most_repeated_letters/exercise_12_word_with_most_repeated_letters.py
376
4.0625
4
from collections import Counter def most_repeating_letter_count(word): return Counter(word).most_common(1)[0][1] def most_repeating_word(words): """ Function that takes a sequence of strings as input. The function should return the string that contains the greatest number of repeated letters """ return max(words, key=most_repeating_letter_count)
bfce90df81d846a317456efccf614e1b2558a113
GitBis/-FP-_Labo06_-00370819-
/Adivinar_el_numero.py
842
3.859375
4
import random print("ADIVINA EL NUMERO") comprobar = True contador = 1 while comprobar == True: n = int(input("Ingrese un numero del 1 al 10: ")) if n > 0 and n < 11: all = random.randrange(1,10) if n == all: print(all) print(f"numero de intentos: {contador}") else: while n != all: if n > all: n = int(input("¡Te pasastes! vuelve a intentar: ")) contador += 1 elif n < all: n = int(input("¡Prueba un numero mayor! : ")) contador += 1 print(f"El numero aleatorio era: {all}") print(f"numero de intentos: {contador}") comprobar = False else: print("Ese no es un numero del 1 al 10 vuelve a intentar")
071520333ddd55bb3539d507c1a1fc34f85b6a64
Saish10/TSV-CSV-Converter
/converter.py
1,169
3.921875
4
#Requirements: pip install argparse #To run the program - converter.py inputfile outputfile import argparse def convert(inputfile, outputfile, to=None): if to == 'csv': join_delimeter = ',' split_delimeter = '\t' elif to == 'tsv': join_delimeter = '\t' split_delimeter = ',' else: return with open(inputfile, encoding='utf-8') as ifile, open(outputfile, 'w') as ofile: rows = ifile.readlines() for row in rows: line = join_delimeter.join(row.split(split_delimeter)) ofile.write(line) print("Converted to " + to) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('inputfile', type=str, help='Input file') parser.add_argument('outputfile', type=str, help='Output file') args = parser.parse_args() if args.inputfile.endswith('.csv') & args.outputfile.endswith('.tsv'): convert(args.inputfile, args.outputfile, to='tsv') elif args.inputfile.endswith('.tsv') & args.outputfile.endswith('.csv'): convert(args.inputfile, args.outputfile, to='csv') else: print('Invalid conversion')
48586fcbff78846e0c10d36f9f17b15783edaa4c
anilkohli98/My-Assignments
/arrays/matrix/matrix_add_multi.py
3,727
4.03125
4
#for multiplication from strings_questions import A def Addmatrix(M,N,mat1,mat2,AddMat): for i in range(M): A=[] for j in range(N): a=0 a+=mat1[i][j]+mat2[i][j] A.append(a) AddMat.append(A) def multiMat(M,N,mat1,mat2,mat3): for i in range(M): A=[] for j in range(N): a=0 for k in range(M): a+=mat1[i][k]*mat2[k][j] A.append(a) mat3.append(A) def main(): M,N=map(int,input().split()) mat1=[] mat2=[] AddMat=[] mat3=[] for i in range(0,M): mat1.append([int(j) for j in input().split()]) for i in range(0,N): mat2.append([int(j) for j in input().split()]) Addmatrix(M,N,mat1,mat2,AddMat) multiMat(M,N,mat1,mat2,mat3) for l in range(M): for m in range(N): print(AddMat[l][m], end = " ") print() for i in range(M): for j in range(N): print(mat3[i][j], end = " ") print() if __name__=='__main__': main() # Aveek sir's logic def PrintA(mat3,M,N): for i in range(M): for j in range(N): print(mat3[i][j],end=' ') print() mat3=[] for i in range(M): mat3.append([0]*N) M,N=map(int,input().split()) mat1=[] for i in range(M): mat1.append(list(map(int,input().split()))) mat2=[] for i in range(M): mat2.append(list(map(int,input().split()))) mat3=[] for i in range(M): mat3.append([0]*N) #addition for i in range(M): for j in range(N): mat3[i][j]=mat1[i][j]+mat2[i][j] PrintA(mat3,M,N) #for multiplication for i in range(M): for j in range(N): for k in range(M):#this loop is for multiplying the row to collumn so basically this loop is for accessing the elements of columns mat3[i][j]=mat3[i][j]+(mat1[i][k]*mat2[k][j])#now here k loop will run M times so when k =o m[0][0]==0,after this mutplication of row 0 and column 1 of mat2 is added to mat[0][0] #here the value of mat[0][0] will updateb M times PrintA(mat3,M,N) #for upper and lower trianglor matrix def LowerTriMat(M,N,Arr1): K=M-(M-1) for i in range(M): for j in range(K,N): Arr1[i][j]=0 K+=1 for i in range(M): for j in range(N): print(Arr1[i][j],end=" ") print() def UpperTriMat(M,N,A): K=1 for i in range(K,M): for j in range(0,K): A[i][j]=0 K+=1 for i in range(M): for j in range(N): print(A[i][j],end=" ") print() def main(): M,N=map(int,input().split()) A=[] Arr1=[] for i in range(M): A.append([int(j) for j in input().split()]) for i in range(M): a=[] for j in range(N): a.append(A[i][j]) Arr1.append(a) LowerTriMat(M,N,Arr1) UpperTriMat(M,N,A) if __name__=="__main__": main() #Upper and lower trianglor matrix using class def Lower_Tri_Mat(mat1,mat2,M,N): K=1 for i in range(M): for j in range(K): mat2[i][j]=mat1[i][j] K+=1 def Upper_Tri_Mat(mat1,mat3,M,N): K=0 for i in range(K,M): for j in range(K,N): mat3[i][j]=mat1[i][j] K+=1 class PrintArr: def Mat2(self,mat2,M,N): for i in range(M): for j in range(N): print(mat2[i][j],end=' ') print() def Mat3(self,mat3,M,N): for i in range(M): for j in range(N): print(mat3[i][j],end=' ') print() def main(): M,N=map(int,input().split()) mat1=[] for i in range(M): mat1.append(list(map(int,input().split()))) mat2=[] for i in range(M): mat2.append([0]*N) mat3=[] for i in range(M): mat3.append([0]*N) A=PrintArr() Lower_Tri_Mat(mat1,mat2,M,N) A.Mat2(mat2,M,N) Upper_Tri_Mat(mat1,mat3,M,N) A.Mat3(mat3,M,N) if __name__=='__main__': main()
1c8b00def9b930ab491e85c9d106f535781a5bf6
Charity-Njoroge/web-scrapping-Python-
/beautifulsoup-project.py
1,599
3.90625
4
""" scraping weather forecasts from the National Weather Service, and then analyzing them using the Pandas library""" from bs4 import BeautifulSoup import requests import pandas as pd # download the page page = requests.get( "https://forecast.weather.gov/MapClick.php?lat=" "37.7772&lon=-122.4168#.XL7k5aKEa00") # create a BeautifulSoup object soup = BeautifulSoup(page.content, 'html.parser') # the div containing the forecast has id "seven-day-forecast" seven_day = soup.find(id="seven-day-forecast") # use css selectors to find all the periods, short descriptions, temperatures, # and the description. Use list comprehension to return them periods = [pt.get_text() for pt in seven_day.select(".tombstone-container .period-name")] short_desc = [sd.get_text() for sd in seven_day.select(".tombstone-container .short-desc")] temperature = [tp.get_text() for tp in seven_day.select(".tombstone-container .temp")] descriptions = [d["title"] for d in seven_day.select(".tombstone-container img")] # use DataFrame class to store the data in a table weather = pd.DataFrame({ "Periods": periods, "Short_desc": short_desc, "Temperature": temperature, }) # find all the temperatures (integers) using the Series.str.extract method temp_nums = weather["Temperature"].str.extract("(?P<temp_num>\d+)", expand=False) weather["temp_num"] = temp_nums.astype('int') # find the lows that happen at night is_night = weather["Temperature"].str.contains("Low") weather["is_night"] = is_night
598e59fab9540c966b91433f035a93e1a0e9e534
riamittal8/Engineering-Assignments
/BE/LP4/SCOA/6. Back Propagation Algorithm/back_propagation.py
1,947
3.65625
4
alpha = 0.1 x1 = 1 x2 = 0 y = 1 w11 = 1 w12 = 1 w21 = 1 w22 = 1 w31 = 1 w32 = 1 h1 = x1 * w11 + x2 * w12 h2 = x1 * w21 + x2 * w22 y_hat = h1 * w31 + h2 * w32 y_hat def loss(target, predicted): return ((target - predicted) ** 2) / 2 def print_update_weight(weight, val, gradient): print("Update {} value: {}. Gradient: {}".format(weight, val, gradient)) def output_layer(w31, w32): # Output Layer delta_L_by_y_hat = -(y - y_hat) delta_y_hat_by_w31 = h1 delta_L_by_w31 = delta_L_by_y_hat * delta_y_hat_by_w31 # update w31 w31 = w31 - alpha * delta_L_by_w31 print_update_weight('w31', w31, delta_L_by_w31) delta_L_by_y_hat = -(y - y_hat) delta_y_hat_by_w32 = h2 delta_L_by_w32 = delta_L_by_y_hat * delta_y_hat_by_w32 # update w32 w32 = w32 - alpha * delta_L_by_w32 print_update_weight('w32', w32, delta_L_by_w32) output_layer(w31, w32) def hidden_layer(w11, w12, w21, w22): # Hidden Layer neuron 1 delta_L_by_h1 = -(y - y_hat) * w31 delta_h1_by_w11 = x1 delta_L_by_w11 = delta_L_by_h1 * delta_h1_by_w11 # update w11 w11 = w11 - alpha * delta_L_by_w11 print_update_weight('w11', w11, delta_L_by_w11) delta_L_by_h1 = -(y - y_hat) * w31 delta_h2_by_w12 = x2 delta_L_by_w12 = delta_L_by_h1 * delta_h2_by_w12 # update w12 w12 = w12 - alpha * delta_L_by_w12 print_update_weight('w12', w12, delta_L_by_w12) # Hidden Layer neuron 2 delta_L_by_h2 = -(y - y_hat) * w32 delta_h2_by_w21 = x1 delta_L_by_w21 = delta_L_by_h2 * delta_h2_by_w21 # update w21 w21 = w21 - alpha * delta_L_by_w21 print_update_weight('w21', w21, delta_L_by_w21) delta_L_by_h2 = -(y - y_hat) * w32 delta_h2_by_w22 = x2 delta_L_by_w22 = delta_L_by_h2 * delta_h2_by_w22 # update w22 w22 = w22 - alpha * delta_L_by_w22 print_update_weight('w22', w22, delta_L_by_w22) hidden_layer(w11, w12, w21, w22)
cbf6eb9e6bd511ff4c0d676f0360cbd27fa4e4cb
asdf2014/algorithm
/Codes/gracekoo/96_unique-binary-search-trees.py
526
3.515625
4
# -*- coding: utf-8 -*- # @Time: 2020/4/13 18:49 # @Author: GraceKoo # @File: 96_unique-binary-search-trees.py # @Desc: https://leetcode-cn.com/problems/unique-binary-search-trees/ class Solution: def numTrees(self, n: int) -> int: if n < 0: return 0 dp = [0 for _ in range(n + 1)] dp[0] = 1 dp[1] = 1 for i in range(2, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[-1] so = Solution() print(so.numTrees(3))
59f41d40b3f00bee849085f55dbd420f73cc43e0
jasiek-k/SISE
/src/Calculator.py
1,803
3.5
4
class Calculator: def __init__(self, files, algo, param): self.files = files self.fix_paths() self.algo = algo self.param = param self.current_file ="" def fix_paths(self): for i in range(len(self.files)): self.files[i] = self.files[i].translate({ord('\\'): '/'}) def compute_files(self): file_content = [] content = "" summary = [0.0] * 5 for i in range(len(self.files)): file_content = self.read_from_file(self.files[i]) for i in range(len(summary)): summary[i] += file_content[i] for i in range(len(summary)): summary[i] = float(summary[i] / len(self.files)) content += str(summary[i]) content += " " self.save_solution(content) def read_from_file(self, file_name): lines_number = 5 content = [] f = open(f"{file_name}", "r") self.current_file = file_name for i in range(lines_number): single_line = f.readline() single_line = single_line.translate({ord('\n'): None}) if i == 4: single_line = float(single_line) else: single_line = int(single_line) if single_line == (-1): print("UWAGA BŁĄD") content.append(single_line) return content def save_to_file(self, file_name, content): file = open(f"{file_name}.txt", "w") file.write(content) file.close() def save_solution(self, content): saved_string = f"{self.current_file[19:20]} level {self.algo} {self.param}\n{content}" self.save_to_file(f"./glob/{self.algo}_{self.param}_{self.current_file[19:20]}_computed", saved_string)
932ee0088d29ddbfe5613f3428b265d5dad7a76f
nisarg-ss/Python_Codes
/DSA/DSA/binary tree.py
3,168
3.65625
4
class node: def __init__(self,data): self.data=data self.left=None self.right=None def addchild(self,data): if data==self.data: return if data<self.data: if self.left: self.left.addchild(data) else: self.left=node(data) else: if self.right: self.right.addchild(data) else: self.right=node(data) def pri(self): if self.left: self.left.pri() print(self.data,end=" ") if(self.right): self.right.pri() def search(self,val): if self.data==val: return True if val>self.data: if self.right: return self.right.search(val) if val<self.data: if self.left: return self.left.search(val) return False def findmin(self): a=self while(a.right): a=a.right print(a.data) def summ(self): if self.left==None and self.right==None: return self.data elif self.left==None: return self.data+self.right.summ() elif self.right==None: return self.data+self.left.summ() else: return self.data+self.left.summ()+self.right.summ() def minval(self): if self.left: return self.left.minval() else: return self.data def delete(self,val): if val > self.data: if self.right: self.right=self.right.delete(val) if val < self.data: if self.left: self.left= self.left.delete(val) else: if self.left==None and self.right==None: return None if self.right==None: return self.left if self.left==None: return self.right min_value=self.right.minval() self.data=min_value self.right=self.right.delete(min_value) return self def height(node): if node is None: return 0 else: lh=height(node.left) rh=height(node.right) if lh > rh: return lh+1 else: return rh+1 def levelorderpri(node): h=height(node) for i in range(1,h+1): prigivenlevel(node,i) def prigivenlevel(root,lvl): if root is None: return if lvl==1: print(root.data,end=" ") elif(lvl >1): prigivenlevel(root.left,lvl-1) prigivenlevel(root.right,lvl-1) if __name__=='__main__': root=node(17) #root.addchild(17) root.addchild(4) root.addchild(1) root.addchild(20) root.addchild(9) root.addchild(23) root.addchild(18) root.addchild(34) root.pri() print(root.search(21)) root.findmin() print(root.summ()) root.delete(17) root.pri() print() print(height(root)) levelorderpri(root)
cc7074edb77899b183d57ce34e78b8069afd4cdf
goranobad1407/python_learn
/3_bootstrapping.py
2,054
3.765625
4
#Felix Bittmann, 2020 import random from statistics import mean, median, stdev def histogram(data, bins=None): """Draws a histogram from numerical data""" maxvalue = max(data) minvalue = min(data) totalwidth = abs(maxvalue - minvalue) ndata = len(data) if not bins: #Rice's rule or 20 bins max bins = int(min((2 * ndata**(1/3)), 20)) binwidth = totalwidth / bins bindata = [] maxelements = 0 for i in range(bins): lowerbound = minvalue + i * binwidth upperbound = lowerbound + binwidth nelements = sum(1 for element in data if lowerbound <= element < upperbound) if nelements > maxelements: maxelements = nelements midvalue = lowerbound + 0.5 * binwidth bindata.append([nelements, midvalue]) maxheight = 25 print("-" * 40) for row in bindata: binheight = int((maxheight / maxelements) * row[0]) print(f"{row[1]: 4.2f} {'#' * binheight}") print("-" * 40) print(f"N: {ndata}") print(f"Mean: {mean(data):4.02f}") print(f"Median: {median(data):4.02f}") print(f"Standard deviation: {stdev(data):4.02f}") def bootstrap(func, data, n): empvalue = func(data) resamples = [func(random.choices(data, k=len(data))) for i in range(n)] stderr = stdev(resamples) ci = (round(empvalue - 1.96 * stderr, 2), round(empvalue + 1.96 * stderr, 2)) histogram(resamples) print(f"Empirical value: {empvalue:4.02f} | Bootstrap Stderr: {stderr:4.02f} | 95%-CI: {ci}") if __name__ == '__main__': random.seed(1234) data = [round(random.normalvariate(0, 1), 3) for i in range(300)] histogram(data) # ~ testresults = [4, 5, 7, 7, 9, 10, 11, 13, 15, 18, 19, 19, 22, 23] # ~ bootstrap(median, testresults, 2000) # Assignments def spent_money(): """How much money must be spent until the collection is complete on average?""" collection = [] total_sum = 0 while len(collection) < 36: total_sum += 10 smurf = random.randint(1, 36) if smurf not in collection: collection.append(smurf) return total_sum # ~ simulation_smurfs = [spent_money() for i in range(9000)] # ~ histogram(simulation_smurfs)
050ecd29b3d3ec5db7848775138e752eee8321f1
egyilmaz/mathQuestions
/questions/src/question/year6/Question123.py
1,601
3.515625
4
from questions.src.question.BaseQuestion import BaseQuestion from questions.src.question.year6.Types import Types, Complexity import random import math import matplotlib.pyplot as plt from matplotlib.patches import Arc from io import BytesIO class Question123(BaseQuestion): def __init__(self): self.type = [Types.Geometry_triangle, Types.sat_reasoning] self.complexity = Complexity.Moderate self.a = random.choice([20, 25, 30, 35, 40, 45, 50, 55, 60]) self.b = random.choice([20, 25, 30, 35, 40, 45, 50, 55, 60]) self.body = "In the given figure, what is the unknown angle?" def question(self): return self.body def answer(self): return "{0}\u00b0".format(180.0 - self.a -self.b) def graphic(self): plt.axis('equal') plt.gcf().set_size_inches(4, 4) #write down all the coordinates and write first one again, to form a closed loop, #separate the x's and y's into two lists as below. plt.plot([0, 1.7, 2, 0],[0, 2, 0, 1]) r=2 angle = max(30,self.a) # dont want to draw too narrow. limit to 30 degree rad=(angle*math.pi)/180.0 plt.gca().add_patch(Arc([2,0], 0.2, 0.2, angle=200, theta1=255, theta2=310, color="blue")) plt.gca().add_patch(Arc([0.6,0.7], 0.2, 0.2, angle=300, theta1=220, theta2=290, color="blue")) plt.text(1.77,0.15,str(self.a)+u"\u00b0") plt.text(0.27,0.60,str(self.b)+u"\u00b0") plt.text(1.63,1.75,"?") buf = BytesIO() plt.savefig(buf, format='PNG') return self.toBuffer( buf )
2b28b0827e82cf83c24a603b74f06f80fe0dca48
winarcooo/algorithm-playground
/Count_triplets/solution.py
606
3.75
4
def countTriplets(arr, n): arrLength = len(arr) ratio = n counter = 0 for i in range(arrLength - 2): firstnum = arr[i] for j in range(i+1, arrLength - 1): secondnum = arr[j] if secondnum != firstnum * ratio: continue for k in range(j+1, arrLength): thirdnum = arr[k] if thirdnum != secondnum * ratio: continue counter += 1 return counter if __name__ == "__main__": arr = [1,3,9,9,27,81] arr1 = [1,2,2,4] n = 2 countTriplets(arr1, n)
de0aeefef470f48717789440b9d0cb9a3bcd8944
AdamZhouSE/pythonHomework
/Code/CodeRecords/2981/60649/273236.py
728
3.625
4
def change(start,end,p1,p2,p3): res="" i=chr(ord(start)+1) while i<end: if p1==3: c='*' else: if i.isalpha(): if p1 == 1: c = i.lower() elif p1 == 2: c = i.upper() else: c = i for j in range(p2): res=c+res if p3==2 else res+c i=chr(ord(i)+1) return res p1,p2,p3=map(int,input().split()) s=input() res="" for i in range(len(s)): if i!=0 and s[i]=='-' and s[i+1]>s[i-1] and ((s[i+1].isalpha() and s[i-1].isalpha())or(s[i+1].isdigit() and s[i-1].isdigit())): res+=change(s[i-1],s[i+1],p1,p2,p3) else: res+=s[i] print(res)
3f70724e3dd411f83301f0e27a35aacb8cd6f159
zakir360hossain/MyProgramming
/Languages/Python/Learning/functions/recursive.py
278
4.21875
4
# Recursion function is a function that calls itself until a condition for the recusion is # reached. # Returns nth factorial def factorial(n): if n == 1: return 1 return n * factorial(n - 1) # Returns the product of all the numbers that are multple of n
eb4c5c5fd90fbe803ce40905d84b4f1a71b6e12a
CodeVeish/py4e
/Completed/ex_09_01/ex_09_01.py
616
4
4
# Write a program that reads the words in words.txt and stores them as keys in a dictionary. # It doesn't matter what the values are. Then you can use the in operator as a fast way to check # whether a string is in the dictionary. count = 0 dictionary = dict() handle = open('words.txt') for line in handle : words = line.split() for word in words : count = count + 1 dictionary[word] = count # print(dictionary) usercheck = input('What word would you like to find? ') if usercheck in dictionary : print(usercheck,dictionary[usercheck]) else : print('Value Not Found')
dfc95c4413dbbc0645c42c66536f9993624c43ce
mildredgil/computer_vision
/Act_1.py
5,756
4.40625
4
#!/usr/bin/env python # coding: utf-8 # # HMW1 # ## Lists # 1) Create a list with the following color names: ‘blue’, ‘white’, ‘green’, ‘red’, ‘pink’, ‘yellow’. # In[1]: list = ['blue', 'white', 'green', 'red', 'pink', 'yellow'] # 2) Print the number of elements in the list. # In[2]: print(list) # 3) Search for the ‘blue’ element in the list. Search for the ‘purple’ element in the list # In[3]: for i in list: if i == 'blue': print('blue is in the list!') # In[4]: for i in list: if i == 'purple': print('purple is in the list!') # 4) Print the index for the element ‘white’ and ‘black’ in the list. Use an exception handler to deal with the error when the element is not in the list. # In[5]: try: print('white index is: ' + str(list.index('white'))) except ValueError: print('white is not an element of list') try: print('black index is: ' + str(list.index('black'))) except ValueError: print('black is not an element of list') # 5) Add the following elements to the list ‘violet and ‘grey’. # In[6]: list.extend(['violet', 'grey']) print(list) # 6) Add the following list to the color list, [‘brown’, ‘black’] # In[7]: list.append(['brown', 'black']) print(list) # 7) Replace the first three elements of the list with the element ‘cyan’ # In[8]: list[0] = 'cyan' del list[1:3] # In[9]: print(list) # 8) Add the element ‘orange’ to the list that is in the list: # In[10]: list[6].append('orange') # 9) Delete all the elements from the list, except the first two. # In[11]: del list[2:] # 10) Create a the following 2D list # [[0, 1, 2, 3, 4], # [5, 6, 7, 8, 9], # [10, 11, 12, 13, 14], # [15, 16, 17, 18, 19], # [20, 21, 22, 23, 24]] # In[12]: list2D = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] # 11) From the following list of lists, print the number of elements from the last list: # In[13]: numbers = [[1,2],[3,4],[5,6],[7,8,9]] print(len(numbers[3])) # 12) Create a list which elements are the odd square from 1 to 10: # In[14]: listOdd = [] for i in range(1,10): if i % 2 == 1: listOdd.extend([i * i]) print(listOdd) # 13) Create a 2D list which represent the multiplication table of 3 from 1 to 10: # In[15]: list3 = [] for i in range (1,11): list3 += [[3, i, i*3]] print(list3) # 14) Write a Python program to generate a 4 * 3 * 2 3D array whose element are '?'. # # In[16]: listQ = [] for i in range(1,5): listAux = [] for i in range(1,4): listAux.append(['?','?']) listQ.append(listAux) print(listQ) # ## Dictionaries # 1. Create a dictionary which keys are the numbers from 1 to 5 and which individual values are the corresponding letter of the alphabet # In[17]: dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} print(dict) # 2. Search for the 4 key in the dictionary. Search for the 7 key in the dictionary. # # In[18]: if 4 in dict.keys(): print(dict[4]) if 7 in dict.keys(): print(dict[7]) # 3. Search for the value ‘a’ in the dictionary. Search for the value ‘z’ in the dictionary. # # In[19]: for val in dict.values(): if val == 'a' or val == 'z': print(val) # 4. Add an extra element to the dictionary, which key is 6 and value is f. # # In[20]: dict[6] = 'f' print(dict) # 5. Delete the element from the dictionary whose key is 2 # In[21]: del dict[2] print(dict) # 6. Find the maximum and minimum value in a dictionary # In[22]: dictNum = {'x':700, 'y':56874, 'z': 990} maxK = max(dictNum.keys(), key=(lambda key: dictNum[key])) minK = min(dictNum.keys(), key=(lambda key: dictNum[key])) print('Max : ' + str(dictNum[maxK]) + '\nMin : ' + str(dictNum[minK])) # ## Numpy # 1. Generate an array from 0 to 19. # In[23]: import numpy as np # 1. Generate an array from 0 to 19. # In[24]: arr = np.arange(20) print(arr) # 2. Generate an array from 30 to 39 # In[25]: arr = np.arange(30, 39, 1) print(arr) # 3. Generate a 6x6 matrix of 0s # In[26]: matZeros = np.zeros((6,6)) print(matZeros) # 4. Generate a 4x4 matris of 1s # In[27]: matOnes = np.ones((4,4)) print(matOnes) # 5. Following the provided numPy array, return an array with the last element of each row: # # sampleArray = numpy.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]]) # In[28]: sampleArray = np.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]]) last = sampleArray[:,2] print(last) # 6. Reverse the following array (first element becomes last). # # [12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37] # In[29]: npArray = np.array([12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37]) np.flip(npArray) # 7. Create the following matrix and name it CwHwMat: # # In[30]: CwHwMat = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) print(CwHwMat) # From CwHwMat generate the following slice: # # [[2 3] # [6 7]] # # In[31]: CwHwMat[[[0,0],[1,1]],[[1,2],[1,2]]] # 8. From CwHwMat generate the following slice: # In[32]: CwHwMat[[[1,1],[2,2],[3,3]],[[2,3],[2,3],[2,3]]] # 9. Slice CwHwMat into two ndarrays, name one as X and the other as y: # # X: # array([[ 1, 2, 3], # [ 5, 6, 7], # [ 9, 10, 11], # [13, 14, 15]]) # # y: # array([ 4, 8, 12, 16]) # # In[33]: x = CwHwMat[:,0:3] y = CwHwMat[:,3] print('x:') print(x) print('y:') print(y) # 10. Split the X into two ndarray named train and test, train will have 75% of the observations and test will have 25%. # # In[34]: train= x[[1,2,3],:] test = x[0,:] print('test:') print(test) print('train:') print(train)
c79363a895ed89f6f114569eb21c399d06433985
lance2038/lanceEdit
/python3Base/v001/classTest/class_base.py
2,247
3.875
4
# 类(Class)(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。 class Student(object): # 由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。 # 通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去由于类可以起到模板的作用, # 因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法, # 在创建实例的时候,就把name,score等属性绑上去 # __init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身 # 有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去 def __init__(self, name, score): self.name = name self.score = score # 和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。除此之外, # 类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数 def print_score(self): print('%s: %s' % (self.name, self.score)) def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' # 实例(Instance)定义好了Student类,就可以根据Student类创建出Student的实例,创建实例是通过类名+()实现的 bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) print(Student) print(bart) print('bart.name =', bart.name) print('bart.score =', bart.score) bart.print_score() print('grade of Bart:', bart.get_grade()) print('grade of Lisa:', lisa.get_grade())
5294b731478e04800f9c24802d9d4cc5cd6e3687
NajibAdan/adventofcode2019
/day01/fuel_consumption.py
375
3.921875
4
import math def getConsumption(mass): return math.floor(int(mass)/3)-2 def recursiveConsumption(mass): if math.floor(mass/3) >= 0: return mass + recursiveConsumption(getConsumption(mass)) else: return 0 modules = open("./day01/input.txt",'r') sum = 0 for module in modules: sum = sum + recursiveConsumption(getConsumption(module)) print(sum)
ea6a4934bd6551604e664b510a169ad31f1eb5e9
SergeyPush/python-dev
/3_exceptions/exceptions_task_3.py
1,547
4.25
4
""" Опишите класс сотрудника, который включает в себя такие поля, как имя, фамилия, отдел и год поступления на работу. Конструктор должен генерировать исключение, если заданы неправильные данные. Введите список работников с клавиатуры. Выведите всех сотрудников, которые были приняты после заданного года. """ class WorkerException(Exception): pass class Worker: def __init__(self, name, surname, year) -> None: if not name or not surname or not year: raise WorkerException( "Invalid data, enter correct name, surname and year") self.name = name self.surname = surname self.year = int(year) @classmethod def create_worker_from_string(cls): name = input("Enter name: ") surname = input("Enter Surname: ") year = input("Enter year: ") return cls(name, surname, year) def __repr__(self) -> str: return f"{self.name} - {self.surname} - {self.year}" def __str__(self) -> str: return f"{self.name} - {self.surname} - {self.year}" w1 = Worker.create_worker_from_string() w2 = Worker.create_worker_from_string() w3 = Worker.create_worker_from_string() workers = [w1, w2, w3] year = 2019 for worker in workers: if worker.year >= year: print(worker)
d214ab9e54c07054880b3ce63570b2f979a9eadc
Biraja007/Python
/Functions.py
293
3.78125
4
# Function is a named block of reusable code that performs a specific task. def findMaximum (NumberOne , NumberTwo): if NumberOne > NumberTwo: return NumberOne else: return NumberTwo NumberOne=10 NumberTwo=20 greater= findMaximum (NumberOne,NumberTwo) print (greater)
1d049b77d008595ea3ecbf29f0bb93cda4d621e7
akshaymandhan/Python-for-Data-Science
/List.py
1,805
4.625
5
# List functions # Generate List print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] print(thislist) # append element in existing list print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) # This will pop the last element of lIST print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) # This will remove specific item print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) # insert element at specific position print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) # this will clear the list print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) # print length of list print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] print(len(thislist)) # print second index item print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] print(thislist[1]) # change value of an item print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) # remove item from specific position print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist)
3d8ab04788eb3bcad2035400233290c646c9a115
ajfm88/PythonCrashCourse
/Ch5/alien_colors_3.py
1,138
4.15625
4
#Turn your if-else chain from alien_colors_2 into an if-elif-else chain #If the alien is green, print a message that the player earned 5 points. #If the alien is yellow, print a message that the player earned 10 points. #If the alien is red, print a messsage that the player earned 15 points. #Write three versions of this program, #making sure each message is printed for the appropriate color alien. alien_color = 'green' if alien_color == 'green': print("The player has earned 5 points!") elif alien_color == 'yellow': print("The player has earned 10 points!") elif alien_color == 'red': print("The player has earned 15 points!") #Version 2 alien_color = 'yellow' if alien_color == 'green': points = 5 elif alien_color == 'yellow': points = 10 elif alien_color == 'red': points = 15 print(f"\nFor this new and improved program. The player has earned {points} points!") #Version 3 alien_color = 'red' if alien_color == 'green': points = 5 elif alien_color == 'yellow': points = 10 elif alien_color == 'red': points = 15 print(f"\nThird version. The player has earned {points} points!")
9249b1dcdc705c061bf7cf2e993ee060e3367ac0
Avogar/MyGame
/Game.py
10,994
3.578125
4
import pygame,random, sys pygame.init() class direction(): right = 1 left = 2 straight_r = 3 straight_l = 4 class figure: def __init__(self,x,y,dx,dy,color): self.x = x self.y = y self.dx = dx self.dy = dy self.color = color def draw(self): if self.color == brown: screen.blit(image_brick,[self.x,self.y]) elif self.color == yellow: screen.blit(image_coin,[self.x,self.y]) else: pygame.draw.rect(screen,self.color,[self.x,self.y,self.dx,self.dy],0) def ishit(self,main): if main.x < self.x + self.dx and main.x + main.dx > self.x and main.y < self.y + self.dy and main.y + main.dy > self.y: return True return False class character(figure): def __init__(self,x,y): self.x = x self.y = y self.dx = 15 self.d = 5 self.dy = 50 self.speed_x = 2 self.speed_y = 0 self.jump = False self.fall = False self.create = False self.create_k = 0 self.destroy = False self.color = red self.direction = direction.straight_r self.move_count = 1 self.collect_coins = 0 self.t = 1 self.floor = [] def f(self): return int(7 * self.t - 0.25 * self.t ** 2) def move(self): if self.direction == direction.right: self.move_count += 0.2 self.x += self.speed_x if self.direction == direction.left: self.x -= self.speed_x self.move_count += 0.2 if self.move_count >= 5: self.move_count = 1 if self.floor == [] or self.x > self.floor.x + self.floor.dx or self.x + self.dx < self.floor.x: self.floor = [] if not(self.jump): self.t = 13 self.speed_y = self.f() self.t += 1 self.jump = True if self.jump: self.y += self.speed_y self.speed_y = self.f() self.y -= self.speed_y self.t += 1 if self.floor != [] and self.y >= self.floor.y - self.dy: self.jump = False self.y = self.floor.y - self.dy self.speed_y = 0 self.t = 1 def new_block(self): y = self.y + self.dy // self.create_k if self.direction == direction.right or self.direction == direction.straight_r: x = self.x + self.dx else: x = self.x - self.dx - 2*self.d self.create = False return [x, y, self.dx + 2*self.d, self.dy//2, brown] def key_down(self,key): if key == pygame.K_RIGHT: self.direction = direction.right elif key == pygame.K_LEFT: self.direction = direction.left if key == pygame.K_SPACE: self.jump = True if key == pygame.K_q: self.create = True self.create_k = 2 if key == pygame.K_w: self.create = True self.create_k = 1 if key == pygame.K_e: self.destroy = True def key_up(self,key): if key == pygame.K_LEFT and self.direction == direction.left: self.direction = direction.straight_l self.move_count = 1 elif key == pygame.K_RIGHT and self.direction == direction.right: self.direction = direction.straight_r self.move_count = 1 def draw(self): draw_x = self.x - self.d if self.jump: if self.direction == direction.right or self.direction == direction.straight_r: screen.blit(image_jump_r,[draw_x, self.y]) else: screen.blit(image_jump_l,[draw_x, self.y]) elif self.direction == direction.straight_l: screen.blit(image_stay_l,[draw_x,self.y]) elif self.direction == direction.straight_r: screen.blit(image_stay_r,[draw_x,self.y]) elif self.direction == direction.right: if 1 <= self.move_count < 2: screen.blit(image_run1_r,[draw_x,self.y]) elif 2 <= self.move_count < 3: screen.blit(image_run2_r,[draw_x,self.y]) elif 3 <= self.move_count < 4: screen.blit(image_run3_r,[draw_x,self.y]) elif 4 <= self.move_count < 5: screen.blit(image_run4_r,[draw_x,self.y]) elif self.direction == direction.left: if 1 <= self.move_count < 2: screen.blit(image_run1_l,[draw_x,self.y]) elif 2 <= self.move_count < 3: screen.blit(image_run2_l,[draw_x,self.y]) elif 3 <= self.move_count < 4: screen.blit(image_run3_l,[draw_x,self.y]) elif 4 <= self.move_count < 5: screen.blit(image_run4_l,[draw_x,self.y]) def get_next_pos(self): pers = character(self.x, self.y) pers.direction, pers.jump, pers.t, pers.floor, pers.speed_y = self.direction, self.jump, self.t, self.floor, self.speed_y pers.move() return pers def ishit(self,block): if block.ishit(self.get_next_pos()): if block.color == yellow: all_blocks.destroy(block) self.collect_coins += 1 else: if self.y + self.dy <= block.y: self.floor = block elif self.x >= block.x + block.dx: self.direction = direction.straight_l elif self.x + self.dx <= block.x: self.direction = direction.straight_r elif self.y >= block.y + block.dy: self.t += (14 - self.t) * 2 - 1 self.speed_y = self.f() self.t += 1 else: if self.direction == direction.right or self.direction == direction.straight_r: self.x = block.x - self.dx else: self.x = block.x + block.dx return True return False class blocks: def __init__(self): self.list = [] def draw(self): for i in self.list: i.draw() def ishit(self,block): for i in self.list: if block.ishit(i): return True def destroy(self,block): self.list.remove(block) return False def create_coins(): block_points = figure(10,10,size[0]-20,30,black) all_blocks.list.append(block_points) def create_coin(): coin_d = 15 x = random.randrange(size[0] - coin_d + 1) y = random.randrange(size[1] - coin_d + 1) coin = figure(x, y, coin_d,coin_d, yellow) return coin for i in range(coins_n): coin = create_coin() while all_blocks.ishit(coin): coin = create_coin() all_blocks.list.append(coin) all_blocks.list.remove(block_points) def create_all_blocks(): y = (size[1] - (size[1]//120 - 2)*120)//2 dy = 10 dx = 80 for i in range(size[1]//120 - 1): n = random.randrange(3, 5) for j in range(n): x = random.randrange(j * size[0] // n + 3, (j + 1) * size[0] // n - dx) elem = figure(x, y, dx, dy, black) all_blocks.list.append(elem) y += 120 def create_block(mas): brick = figure(mas[0],mas[1],mas[2],mas[3],mas[4]) if not(all_blocks.ishit(brick)): all_blocks.list.append(brick) def destroy_block(): for item in all_blocks.list: if item.color == brown and 0 <= item.y - pers.y <= pers.dy // 2 + 10 and ( 0 <= item.x - pers.x - pers.dx <= 1 or - 1 <= item.x + item.dx - pers.x <= 0): all_blocks.destroy(item) break def draw_fon(): screen.blit(image_fon,[0,0]) black = (0,0,0) white = (255,255,255) green = (0,255,0) red = (255,0,0) blue = (0,0,255) yellow = (255,255,0) sky = (200,255,255) grey = (190,190,190) orange = (255,165,0) brown = (139,69,19) purple = (160,32,240) DarkGreen = (0,128,0) trip = sys.path[0] image_fon = pygame.image.load(trip + '/data/fon.png') image_run1_r = pygame.image.load(trip + '/data/run1r.png') image_run1_r.set_colorkey(white) image_run2_r = pygame.image.load(trip + '/data/run2r.png') image_run2_r.set_colorkey(white) image_run3_r = pygame.image.load(trip + '/data/run3r.png') image_run3_r.set_colorkey(white) image_run4_r = pygame.image.load(trip + '/data/run4r.png') image_run4_r.set_colorkey(white) image_stay_r = pygame.image.load(trip + '/data/stayr.png') image_stay_r.set_colorkey(white) image_jump_r = pygame.image.load(trip + '/data/jumpr.png') image_jump_r.set_colorkey(white) image_run1_l = pygame.image.load(trip + '/data/run1l.png') image_run1_l.set_colorkey(white) image_run2_l = pygame.image.load(trip + '/data/run2l.png') image_run2_l.set_colorkey(white) image_run3_l = pygame.image.load(trip + '/data/run3l.png') image_run3_l.set_colorkey(white) image_run4_l = pygame.image.load(trip + '/data/run4l.png') image_run4_l.set_colorkey(white) image_stay_l = pygame.image.load(trip + '/data/stayl.png') image_stay_l.set_colorkey(white) image_jump_l = pygame.image.load(trip + '/data/jumpl.png') image_jump_l.set_colorkey(white) image_coin = pygame.image.load(trip + '/data/coin.png') image_coin.set_colorkey(white) image_brick = pygame.image.load(trip + '/data/brick.png') size = [700,700] block_d = 10 screen = pygame.display.set_mode(size) pygame.display.set_caption('New Game') clock = pygame.time.Clock() done2 = True while done2: all_blocks = blocks() all_blocks.list = [figure(0,size[1]-3,size[0],block_d,black),figure(0,-7,size[0],block_d,black),figure(-7,0,block_d,size[1],black),figure(size[0]-3,0,block_d,size[1],black)] create_all_blocks() pers = character(100,520) coins_n = random.randrange(30, 50) create_coins() done = True while done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = False done2 = False if event.type == pygame.KEYDOWN: pers.key_down(event.key) if event.type == pygame.KEYUP: pers.key_up(event.key) if pers.collect_coins == coins_n: done = False if pers.destroy: destroy_block() pers.destroy = False if pers.create: create_block(pers.new_block()) all_blocks.ishit(pers) pers.move() screen.fill(sky) all_blocks.draw() pers.draw() pygame.display.flip() clock.tick(60) pygame.quit()
134ac0de80431f263d3c72c5c04455d4b6e7c6eb
turamant/MySQLDeep
/data_cl.py
2,054
3.546875
4
from dataclasses import dataclass, field from dataclasses import make_dataclass from collections import namedtuple from math import radians, sin, cos, asin, sqrt RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() SUITS = '♣ ♢ ♡ ♠'.split() @dataclass class DataClassCard: rank: str suit: str def make_french_deck(): return [DataClassCard(r, s) for s in SUITS for r in RANKS] @dataclass class Deck: cards: list[DataClassCard] = field(default_factory=make_french_deck) @dataclass class Position: name: str longitude: float = 0.0 latitude: float = 0.0 def distance_to(self, other): r = 6371 # Earth radius in kilometers lam_1, lam_2 = radians(self.longitude), radians(other.longitude) phi_1, phi_2 = radians(self.latitude), radians(other.latitude) h = (sin((phi_2 - phi_1) / 2) ** 2 + cos(phi_1) * cos(phi_2) * sin((lam_2 - lam_1) / 2) ** 2) return 2 * r * asin(sqrt(h)) if __name__=='__main__': position = Position('Oslo', 'fignja', 59.9) print(position) print(position.latitude) position = Position('Moscow') print(position) print(position.latitude) Car = make_dataclass('Car', ['model', 'color', 'year']) car = Car('mersedes', 'blue', 1990) print(Car) print(car) print(car.model, car.color, car.year) Car2 = namedtuple('Car2', ['model2', 'color2', 'year2']) car2 = Car2('audi', 'red', 2010) print(Car2) print(car2) print(car2.model2, car2.color2, car2[2]) print("============") oslo = Position('Oslo', 10.8, 59.9) vancouver = Position('Vancouver', -123.1, 49.3) distans = oslo.distance_to(vancouver) print('Расстояние от Осло до Ванкувера', distans) one_deck = Deck() print("Hello", one_deck.cards) queen_of_hearts = DataClassCard('Q', 'Hearts') ace_of_spades = DataClassCard('A', 'Spades') two_cards = Deck([queen_of_hearts, ace_of_spades]) print(two_cards) for card in make_french_deck(): print(card)
c2907f2e3628e31d2be2c98f17dbe03b2ee75d7e
kavinsenthil21/programs
/vote.py
83
3.65625
4
a=int(input("enter your age")) if(a>18): print ("eligible") else: print("not")
5aa38a4e4d3091d263a01777ec5a747b8160f114
zconner-09/GTECH_731_01
/ZacharyConner_01.py
1,008
4.15625
4
import platform Zack_Conner = "Second year MS student in Geoinformatics. Background in Environmental Science" Interests = "Currently interning at the DOT in the GIS unit. Interested in water quality and spatial analysis" ## Platform output ##3.7.3 ##Windows-10-10.0.17134-SP0 print(platform.python_version()) print(platform.platform()) print(Zack_Conner) print(Interests) ## To calculate population variance ## given a set of numbers(p) ## 1. set the output to zero ## 2. for each number in set(p) ## a) add number to the output ## 3. return output number ## 4. divide output number by total numbers in p to get mean ## 5. for each number in p, ## a) subtract each value (i) from the mean ## b) square the differences ## 6. return output numbers in set (x) ## 7. for every number in x ## a) add the total ## 8. return output ## 9. divide output by total numbers in set (p) ## 10. print(output)
ed4c4156b721a61f4cc7ee0e0ab2641d50a776d6
rafaelperazzo/programacao-web
/moodledata/vpl_data/119/usersdata/191/27355/submittedfiles/al1.py
120
3.71875
4
# -*- coding: utf-8 -*- c=float(imput('digite o valor de c:')) f=(9*c+160)/5 print('o valor convertido é %.2f'%f)
aaaee2446f2444a07d5003b35b53891b3e2c6aed
FawneLu/leetcode
/872/Solution.py
1,683
4.0625
4
```python3 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: if not root1 and not root2: return True else: list1=[] list2=[] self.root_recursion(root1,list1) self.root_recursion(root2,list2) if list1==list2: return True else: return False def root_recursion(self,root,list): if root==None: return if not root.left and not root.right: list.append(root.val) self.root_recursion(root.left,list) self.root_recursion(root.right,list) ``` ```python3 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: if not root1 and not root2: return True def helper(root,list): if not root: return None if not root.left and not root.right: list.append(root.val) helper(root.left,list) helper(root.right,list) return list list1=[] list2=[] helper(root1,list1) helper(root2,list2) if list1==list2: return True else: return False ```
045d3ccdf9f46807d7fd50889e5b06d83e88e94a
lxjlovewcx/source_code
/study/fun_pro/fun_pro_.py
1,904
3.984375
4
''' Created on 2018年8月16日 @author: lixue ''' from builtins import map ''' 高阶函数 把函数作为参数使用的函数 变量可以赋值 函数名称就是一个变量 ''' #证明函数名称就是一个变量 def funA(): print("funA Hello") print(funA)#funA是一个变量,其值为<function funA at 0x02F934B0> print(funA())#执行funA中的程序,但是无返回值默认为none。 funB=funA#将特殊的函数变量赋值给funB funB()#funA Hello ''' 函数名是变量 funB和funA指向同一片代码 既然函数名称是变量,则应该可以被作为参数传入另一个函数 ''' # 普通函数 def funC(n): return n *100 def funB(n): return funC(n) *3 print(funB(9)) #高阶函数 def funD(n,f): return f(n) *3 print(funD(9, funC)) #从上可知,使用高阶函数闲的更加灵活,多变 ''' 系统高阶函数-map - 愿意就是映射,即把集合或者列表的元素,每一个元素都按照一定规则进行操作,生成一个新的列表或者集合 -map函数时系统提供的具有映射功能的函数,返回值是一个迭代对象。 python2和python3的却别在map函数这个上,python2里处理的数据时什么类型,map玩后还是那个类型 而在python3中不管可迭代独享是什么类型,结果都是map类型 ''' l1 = [i for i in range(10)] print(l1) l2 = [] for i in l1: l2.append(i*10) print(l2) #利用map实现 def multen(n): return n*10 rst = map(multen,l1) print(rst) for i in rst: print(i,end=",") print(type(rst)) ss = [i for i in rst] print(type(ss)) print(ss) ''' reduce -愿意是归并,缩减 -把一个可迭代对象最后归并为一个结果 -对于作为参数的匿名函数:必须由两个参数,必须由返回结果 ''' from functools import reduce def funE(x,y): return x + y rst = reduce(funE, [i for i in range(10)]) print(rst)
02f91df596719c6cbc129cc70e33b6153b1c7ca1
LoopSun/PythonWay
/PythonLearn/Python Basic/PythonFuction.py
2,307
3.75
4
#!/user/bin/python3 #^.^ coding=utf-8 ^.^# from time import ctime from functools import partial # 1. function define # 2. function arguments # 3. recursive function # 4. closure # 5. lambda # 6. decorator # 7. Partial function #************* function define *************# def fib(limit): a, b = 0, 1 while a < limit: print(a, end= ' ') a, b = b, a+b print() fib(1000) #************* function arguments *************# def fib(): limit = 1000 a, b = 0, 1 while a < limit: print(a, end= ' ') a, b = b, a+b #fib() def fib(end_flag ,limit = 1000): limit = 1000 a, b = 0, 1 while a < limit: print(a, end= end_flag) a, b = b, a+b #fib('|') def fib(*args): limit = args[0] flag = args[1] a, b = 0, 1 while a < limit: print(a, end= end_flag) a, b = b, a+b return 0 #fib(1000, '|') def fib(**kwargs): limit = kwargs['limit'] flag = kwargs['flag'] a, b = 0, 1 while a < limit: print(a, end=end_flag) a, b = b, a + b return 0 #fib(limit = 1000, flag = '|') def fib(name, *args,**kwargs): #comfuse arguments, use it less. print(len(args)) limit = kwargs['limit'] flag = kwargs['flag'] a, b = 0, 1 while a < limit: print(a, end=end_flag) a, b = b, a + b return 0 print("*"*20) #************* recursive function *************# def factorial(n): if n <= 1: return n else: return n * factorial(n-1) print(factorial(5)) #***************** closure *****************# def lazy_sum(*args): def sum_args(): return sum(args) return sum_args f = lazy_sum(1, 2, 3 ,4 ,5) print("f:", f) print("f type:", type(f)) print("result:", f()) print("*"*20) #***************** lambda *****************# # lambda x: x * x # lambda x, y: x + y #***************** decorator *****************# def log(func): def wrapper(*args, **kwargs): print("called {}()".format(func.__name__)) return func(*args, **kwargs) return wrapper @log def now_time(): print(ctime()) # now_time() = log(wrapper(func)) now_time() print("*"*20) #***************** Partial function *****************# int2 = partial(int, base = 2) print("binary 10101011 to int:", int2("10101011"))
7c3e901aa82fa6b9025ca540184197c60554f4f2
MadTofu22/MCTC_Python_Assignments
/Lab Assignment/Loops/Loops lab.py
921
4.15625
4
''' Program: Problem #1 - I got a dollar! Author(s): Tom Stutler, Seth Stoxen, Ashton Kelley Last Date Modified: 9/29/14 The intent of this program is to prompt the user for a number of cents they have and return whether or not they have a dollar. ''' #Define function to see if you have less than a dollar, exactly one dollar, or you have more than a dollar. def dollar(cents): if cents > 100: print ("You have more than one dollar!") elif cents == 100: print ("You have exactly one dollar!") elif 0 < cents < 100: print ("You don't quite have a dollar.") else: print ("Please retry and enter a positive amount of cents.") #Prompt user for the amount of cents they have and assign to a variable. cents = int(input("Enter how many cents you have: ")) #Use dollar() to calculate how many dollars, if any, the user has. dollar(int(input("Enter how many cents you have: ")))
268748cbe55b1071418e114ad6c2ed05ed073813
josevga/exercism_py
/protein-translation/protein_translation.py
821
3.640625
4
def proteins(strand): """Translate RNA sequences into proteins""" translate = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": "", "UAG": "", "UGA": "" } proteins = [] for condon in (strand[i:i + 3] for i in range(0, len(strand), 3)): protein = translate[condon] if not protein: return proteins if not protein in proteins: proteins.append(protein) return proteins
ec3d9d6e9a5895afffb0e7e15373f7c5dd230abb
qqccmm/wikitablestosql
/wikitablestosql/wikitableparser.py
28,030
3.5625
4
import copy def check_in(position, info_pos_line_pairs): """ Check if position corresponds to the starting position of a pair in info_pos_line_pairs (return pair if found, empty list otherwise) :param position: list :param info_pos_line_pairs: list of lists :return: list """ # pos_pair form: [info, [in_line_position_1, line_number_1], [in_line_position_2, line_number_2]] for i in info_pos_line_pairs: if position[0] == i[1][0] and position[1] == i[1][1]: return i return [] def tag_type_check(tag_buffer, tag_list): """ Check if tag buffer is in or is potentially in tag list :param tag_buffer: string :param tag_list: list of strings :return: indicator as list """ temp = [] for i in tag_list: if i == tag_buffer: return [tag_buffer] elif i.startswith(tag_buffer): temp = [''] return temp def curly_braces_matching(opening_stack_element, closing_stack_element, matches=None): """ Greedily match curly braces by groups of 2 or 3 (priority to groups of 3 when they can be matched) :param opening_stack_element: list of lists :param closing_stack_element: list of lists :param matches: list of lists :return: list of lists """ if matches is None: matches = [] if len(closing_stack_element) < 2 or len(opening_stack_element) < 2: return [opening_stack_element, closing_stack_element, matches] elif len(closing_stack_element) == 2 or len(opening_stack_element) == 2: start = opening_stack_element[-2][1:3] end = closing_stack_element[1][1:3] closing_stack_element = closing_stack_element[2:] opening_stack_element = opening_stack_element[:-2] matches.append(['template', start, end]) return curly_braces_matching(opening_stack_element, closing_stack_element, matches) else: start = opening_stack_element[-3][1:3] end = closing_stack_element[2][1:3] closing_stack_element = closing_stack_element[3:] opening_stack_element = opening_stack_element[:-3] matches.append(['tplarg', start, end]) return curly_braces_matching(opening_stack_element, closing_stack_element, matches) def square_brackets_matching(opening_stack_element, closing_stack_element, matches=None): """ Match brackets by groups of 2 :param opening_stack_element: list of lists :param closing_stack_element: list of lists :param matches: list of lists :return: list of lists """ if matches is None: matches = [] if len(closing_stack_element) < 2 or len(opening_stack_element) < 2: return [opening_stack_element, closing_stack_element, matches] else: start = opening_stack_element[-2][1:3] end = closing_stack_element[1][1:3] closing_stack_element = closing_stack_element[2:] opening_stack_element = opening_stack_element[:-2] matches.append(['link', start, end]) return square_brackets_matching(opening_stack_element, closing_stack_element, matches) def consume_stacks(last_raw_stack, open_stack): """ Consume stacks according to type of brackets :param last_raw_stack: list of lists :param open_stack: list of lists :return: list of lists """ pairs = [] if last_raw_stack[0][0] == 'closingsquare': while len(open_stack) > 0 and open_stack[-1][0][0] == 'openingsquare': [opening_stack_element, last_raw_stack, pairs] = square_brackets_matching(open_stack[-1], last_raw_stack, pairs) open_stack.pop() if len(opening_stack_element) >= 2: open_stack.append(opening_stack_element) if len(last_raw_stack) < 2: break else: while len(open_stack) > 0 and open_stack[-1][0][0] == 'openingcurly': [opening_stack_element, last_raw_stack, pairs] = curly_braces_matching(open_stack[-1], last_raw_stack, pairs) open_stack.pop() if len(opening_stack_element) >= 2: open_stack.append(opening_stack_element) if len(last_raw_stack) < 2: break last_raw_stack.clear() return pairs def brackets_proc(i, element, line_number, last_raw_stack, open_stack, last, pairs_list): """ Subroutine for first_pass function. Processes curly and square brackets. :param i: :param element: :param line_number: :param last_raw_stack: :param open_stack: :param last: :param pairs_list: :return: """ if element != last: if len(last_raw_stack) >= 2: if last == '[' or last == '{': open_stack.append(copy.deepcopy(last_raw_stack)) else: pairs_list.extend(consume_stacks(last_raw_stack, open_stack)) last_raw_stack.clear() if element == '{': last_raw_stack.append(['openingcurly', i, line_number]) elif element == '}': last_raw_stack.append(['closingcurly', i, line_number]) elif element == '[': last_raw_stack.append(['openingsquare', i, line_number]) elif element == ']': last_raw_stack.append(['closingsquare', i, line_number]) # First pass parsing def first_pass(text): """ Find links, comments, escaped (or non wiki-formatted text), templates and template arguments :param text: :return: list containing 2 lists (first one gives the locations of links, templates and template arguments, second one gives the locations of comments, escaped text and non wiki-formatted text) """ # For templates and template arguments template_other_list = [] # list of [begin, end (inclusive), line number] last_open_stack = [] last_raw_stack = [] last = '' # For escape and comments escape_comment_pos_list = [] # list of [begin, end (inclusive), line number] temp_begin = '' tag_buffer = '' escape_type = '' tag_mode = False comment_tag_mode = False escape_mode = False comment_mode = False if text == '': return text line_number = None i = None for line_number, line in enumerate(text): for i, element in enumerate(line): if comment_mode: if comment_tag_mode: if element == '>' and tag_buffer == '-': comment_tag_mode = False comment_mode = False tag_buffer = '' escape_comment_pos_list.append([temp_begin, [i, line_number]]) temp_begin = '' elif element == '>' and tag_buffer != '-': tag_buffer = '' comment_tag_mode = False elif element == '-': tag_buffer = '-' else: comment_tag_mode = False tag_buffer = '' else: if element == '-': comment_tag_mode = True elif escape_mode: if tag_mode: tag_buffer += element # Check against closing escape tags tag_var = tag_type_check(tag_buffer, ['/' + escape_type + '>']) if tag_var and tag_var[0]: escape_mode = False tag_mode = False escape_type = '' tag_buffer = '' escape_comment_pos_list.append([temp_begin, [i, line_number]]) temp_begin = '' elif not tag_var: tag_mode = False tag_buffer = '' else: if element == '<': tag_mode = True else: if tag_mode: tag_buffer += element # Check against escape and comment tags tag_var = tag_type_check(tag_buffer, ['nowiki>', 'pre>', '!--']) if tag_var and tag_var[0]: if tag_var[0] == '!--': comment_mode = True else: escape_mode = True escape_type = tag_buffer[:-1] tag_buffer = '' tag_mode = False elif not tag_var: if element == '<': tag_buffer = '' temp_begin = [i, line_number] else: tag_mode = False tag_buffer = '' temp_begin = '' brackets_proc(i, element, line_number, last_raw_stack, last_open_stack, last, template_other_list) else: if element == '<': tag_mode = True temp_begin = [i, line_number] brackets_proc(i, element, line_number, last_raw_stack, last_open_stack, last, template_other_list) last = element element = '' brackets_proc(i, element, line_number, last_raw_stack, last_open_stack, last, template_other_list) return [template_other_list, escape_comment_pos_list] def table_proc(feed, feed_index, line_number, buffers, table_state, wikitabledata): """ Subroutine for wikitable_parser function :param feed: :param feed_index: :param line_number: :param buffers: :param table_state: :param wikitabledata: :return: """ if not buffers['templateindex']: buffers['templateindex'] = check_in([feed_index, line_number], buffers['templatesotherpospairs']) if not buffers['escapecommentindex']: buffers['escapecommentindex'] = check_in([feed_index, line_number], buffers['escapecommentpospairs']) if table_state['cellmode']: if buffers['templateindex'] or buffers['escapecommentindex']: if table_state['pipemode'] and table_state['attributerecorded']: table_state['pipemode'] = False buffers['tempunit'] += '|' buffers['tempunit'] += feed elif table_state['pipemode'] and not table_state['attributerecorded']: table_state['pipemode'] = False table_state['attributerecorded'] = True if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = feed elif table_state['newlinemode']: buffers['tempunit'] += '\n' + feed elif table_state['interogmode']: table_state['interogmode'] = False buffers['tempunit'] += '!' buffers['tempunit'] += feed else: buffers['tempunit'] += feed if buffers['templateindex'][0] == 'link' or buffers['templateindex'][0] == 'template': table_state['attributerecorded'] = True if buffers['tempdata']['fullattribute'] == '': buffers['tempdata']['fullattribute'] = buffers['tempdata']['rowattribute'] else: if table_state['newlinemode']: if feed == '|': if table_state['pipemode'] and table_state['attributerecorded']: table_state['pipemode'] = False table_state['attributerecorded'] = False buffers['tempunit'] += '|' elif table_state['pipemode'] and not table_state['attributerecorded']: table_state['pipemode'] = False if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '' # *** STORAGE *** store cell and reset buffers['tempdata']['celldata'] = copy.deepcopy(buffers['tempunit']) if table_state['captionmode']: wikitabledata['caption']['name'] = copy.deepcopy(buffers['tempdata']['celldata']) wikitabledata['caption']['attribute'] = copy.deepcopy(buffers['tempdata']['fullattribute']) table_state['captionmode'] = False else: buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) buffers['tempdata']['fullattribute'] = '' buffers['tempdata']['isheader'] = False buffers['tempdata']['celldata'] = '' buffers['tempunit'] = '' table_state['attributerecorded'] = False table_state['cellmode'] = False table_state['headerrowmode'] = False table_state['startmode'] = True elif feed == '!': if table_state['pipemode'] and table_state['attributerecorded']: table_state['pipemode'] = False table_state['attributerecorded'] = False buffers['tempunit'] += '|' elif table_state['pipemode'] and not table_state['attributerecorded']: table_state['pipemode'] = False if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '' # *** STORAGE *** store cell and reset buffers['tempdata']['celldata'] = copy.deepcopy(buffers['tempunit']) if table_state['captionmode']: wikitabledata['caption']['name'] = copy.deepcopy(buffers['tempdata']['celldata']) wikitabledata['caption']['attribute'] = copy.deepcopy(buffers['tempdata']['fullattribute']) table_state['captionmode'] = False else: buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) buffers['tempdata']['fullattribute'] = '' buffers['tempdata']['isheader'] = False buffers['tempdata']['celldata'] = '' buffers['tempunit'] = '' table_state['attributerecorded'] = False table_state['headerrowmode'] = True table_state['newlinemode'] = False table_state['cellmode'] = True buffers['tempdata']['isheader'] = True else: if table_state['interogmode']: buffers['tempunit'] += '!' buffers['tempunit'] += '\n' + feed table_state['interogmode'] = False elif table_state['pipemode'] and table_state['attributerecorded']: buffers['tempunit'] += '|' buffers['tempunit'] += '\n' + feed table_state['pipemode'] = False elif table_state['pipemode'] and not table_state['attributerecorded']: if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '\n' + feed table_state['attributerecorded'] = True table_state['pipemode'] = False else: buffers['tempunit'] += '\n' + feed elif feed == '[' and buffers['last'] == '[': buffers['tempunit'] += feed table_state['attributerecorded'] = True if buffers['tempdata']['fullattribute'] == '': buffers['tempdata']['fullattribute'] = buffers['tempdata']['rowattribute'] elif feed == '|': if table_state['pipemode']: table_state['pipemode'] = False if table_state['captionmode']: buffers['tempdata']['celldata'] += '\n' else: buffers['tempdata']['celldata'] = copy.deepcopy(buffers['tempunit']) buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) buffers['tempdata']['fullattribute'] = '' buffers['tempdata']['isheader'] = False buffers['tempdata']['celldata'] = '' buffers['tempunit'] = '' else: table_state['pipemode'] = True elif feed == '!': if table_state['headerrowmode'] and table_state['interogmode']: # *** STORAGE *** buffers['tempdata']['celldata'] = copy.deepcopy(buffers['tempunit']) buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) buffers['tempdata']['fullattribute'] = '' buffers['tempdata']['celldata'] = '' buffers['tempunit'] = '' table_state['interogmode'] = False elif table_state['headerrowmode'] and not table_state['interogmode']: if table_state['pipemode'] and table_state['attributerecorded']: buffers['tempunit'] += '|' table_state['pipemode'] = False elif table_state['pipemode'] and not table_state['attributerecorded']: if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '' table_state['attributerecorded'] = True table_state['pipemode'] = False table_state['interogmode'] = True else: if table_state['pipemode'] and table_state['attributerecorded']: buffers['tempunit'] += '|' buffers['tempunit'] += '!' table_state['pipemode'] = False elif table_state['pipemode'] and not table_state['attributerecorded']: if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '!' table_state['attributerecorded'] = True table_state['pipemode'] = False else: buffers['tempunit'] += '!' else: if table_state['interogmode']: buffers['tempunit'] += '!' buffers['tempunit'] += feed table_state['interogmode'] = False elif table_state['pipemode'] and table_state['attributerecorded']: buffers['tempunit'] += '|' buffers['tempunit'] += feed table_state['pipemode'] = False elif table_state['pipemode'] and not table_state['attributerecorded']: if buffers['tempdata']['rowattribute'] != '': buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = feed table_state['attributerecorded'] = True table_state['pipemode'] = False else: buffers['tempunit'] += feed elif table_state['startmode']: if table_state['newlinemode']: # if feed is '|' dump tempdata and stay in startmode if feed == '|': buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) # if feed is '!' dump tempdata, leave startmode and enter headerrowmode, header attribute and cellmode elif feed == '!': buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) table_state['startmode'] = False table_state['headerrowmode'] = True table_state['cellmode'] = True buffers['tempdata']['isheader'] = True # else add feed to tempunit, leave startmode and enter cellmode else: buffers['tempunit'] += '\n' + feed table_state['startmode'] = False table_state['cellmode'] = True elif feed == '+': table_state['captionmode'] = True table_state['cellmode'] = True table_state['startmode'] = False elif feed == '-': if len(buffers['temprow']) != 0: wikitabledata['rows'].append(copy.deepcopy(buffers['temprow'])) buffers['temprow'].clear() table_state['startmode'] = False table_state['newrowmode'] = True else: table_state['startmode'] = False table_state['cellmode'] = True if feed != ' ': buffers['tempunit'] += feed else: if table_state['newlinemode']: if table_state['newrowmode']: buffers['tempdata']['rowattribute'] = copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '' table_state['newrowmode'] = False if feed == '|': table_state['startmode'] = True elif feed == '!': table_state['headerrowmode'] = True buffers['tempdata']['isheader'] = True table_state['cellmode'] = True else: buffers['tempunit'] += '\n' + feed else: buffers['tempunit'] += feed if buffers['templateindex'] and [feed_index, line_number] == buffers['templateindex'][2]: buffers['templateindex'] = 0 if buffers['escapecommentpospairs'] and [feed_index, line_number] == buffers['escapecommentindex'][2]: buffers['escapecommentindex'] = 0 table_state['newlinemode'] = False def wikitable_parser(raw_wikitable, page_name, table_count): """ Wikitable parser :param raw_wikitable: string :param page_name: string :param table_count: int :return: dict """ # Initialize buffers buffers = {} # table buffers buffers['tempunit'] = '' buffers['tempdata'] = {} buffers['tempdata']['isheader'] = False buffers['tempdata']['celldata'] = '' buffers['tempdata']['rowattribute'] = '' buffers['tempdata']['fullattribute'] = '' buffers['temprow'] = [] # other buffers buffers['templatesotherpospairs'] = [] buffers['escapecommentpospairs'] = [] buffers['templateindex'] = [] buffers['escapecommentindex'] = [] buffers['last'] = '' buffers['problem'] = {} # Initialize tablestate tablestate = {} tablestate['problem'] = False tablestate['newlinemode'] = True tablestate['startmode'] = False tablestate['cellmode'] = False tablestate['pipemode'] = False tablestate['newrowmode'] = False tablestate['headerrowmode'] = False tablestate['interogmode'] = False tablestate['attributerecorded'] = False tablestate['captionmode'] = False # prepare wikitabledata wikitabledata = {'pagename': page_name, 'tablecount': table_count, 'tableattribute': '', 'caption': {}, 'rows': []} wikitabledata['caption']['name'] = '' wikitabledata['caption']['attribute'] = '' wikitabledata['tableattribute'] = raw_wikitable.splitlines()[0][2:] tablecontent = raw_wikitable.splitlines()[1:-1] [buffers['templatesotherpospairs'], buffers['escapecommentpospairs']] = first_pass(tablecontent) for linenumber, line in enumerate(tablecontent): tablestate['newlinemode'] = True tablestate['headerrowmode'] = False for i, feed in enumerate(line): table_proc(feed, i, linenumber, buffers, tablestate, wikitabledata) if tablestate['problem']: buffers['problem']['line-number'] = linenumber buffers['problem']['index'] = i buffers['problem']['raw'] = tablecontent break if tablestate['problem']: return [{'pagename': page_name, 'tablecount': table_count, 'problem': buffers['problem']}] if tablestate['pipemode'] and tablestate['attributerecorded']: buffers['tempunit'] += '|' elif tablestate['pipemode'] and not tablestate['attributerecorded']: if buffers['tempdata']['rowattribute'] == '': buffers['tempdata']['fullattribute'] = copy.deepcopy(buffers['tempunit']) else: buffers['tempdata']['fullattribute'] = copy.deepcopy( buffers['tempdata']['rowattribute']) + ' ' + copy.deepcopy(buffers['tempunit']) buffers['tempunit'] = '' # store cell buffers['tempdata']['celldata'] = copy.deepcopy(buffers['tempunit']) buffers['temprow'].append(copy.deepcopy(buffers['tempdata'])) # add last row wikitabledata['rows'].append(copy.deepcopy(buffers['temprow'])) return wikitabledata
5a6a92e25befada35067326682f27505d1f9eceb
namhyun-gu/algorithm
/programmers/stock_price.py
602
3.71875
4
def solution(prices): answer = [0] * len(prices) stack = [] for idx in range(len(prices)): while stack and prices[stack[-1]] > prices[idx]: top = stack.pop() answer[top] = idx - top stack.append(idx) while stack: top = stack.pop() answer[top] = len(prices) - 1 - top return answer if __name__ == "__main__": examples = [ ({"prices": [1, 2, 3, 2, 3]}, [4, 3, 1, 1, 0]), ] for example, expected in examples: ret = solution(example["prices"]) print("acutal:", ret, "expected:", expected)
1130139e1f30e7047004c5258b62d948bf7d9b99
FindIshita/OpenCV
/Video13/Video13Code.py
815
3.703125
4
import numpy as np import cv2 # Importing libraries img = cv2.imread('corner_image.jpg') # Importing the image whose corners have to be detected. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Convert to grayscale. gray = np.float32(gray) corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10) # This finds the corners of the image by Shi-Tomasi method. The image has to be in grayscale for this. Inside the # brackets, we specify the source, maximum corners to be found, quality level and the minimum distance in order. corners = np.int0(corners) for corner in corners: x, y = corner.ravel() cv2.circle(img, (x, y), 3, (0,255,255), -1) # We make circle around each corner of the specified radius and color, thickness etc. cv2.imshow('Corner', img) cv2.waitKey() cv2.destroyAllWindows()
cae4e56d504c19cfb400a671f289f88b943f3b5b
BlueSky23/MyLeetCode
/链表相关/P92:ReverseLinkListII.py
1,356
3.8125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if not head: return if m == n: return head cnt = 0 node = head pre, post = None, None h, t = None, None flag = False while node: cnt += 1 # 反转 if flag: tmp = node.next node.next = h h = node node = tmp # 保存后一个节点 if cnt == n: post = node break # 寻找反转起始点 else: # 保存前一个节点 if cnt == m: h = node t = node flag = True else: pre = node node = node.next # 链接起来 if pre: pre.next = h t.next = post return head else: t.next = post return h ln1 = ListNode(3) ln2 = ListNode(5) ln1.next = ln2 s = Solution() h = s.reverseBetween(ln1, 1, 2) while h: print(h.val) h = h.next
3876d7326683daef6c2faee97b3f258ae1c0954f
rghosh8/capstone-1
/src/.ipynb_checkpoints/timeit-checkpoint.py
320
3.5
4
import time def timeit(method): def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() print("{0} took {1:0.3e} seconds".format(method.__name__, te-ts)) return (result, te-ts) return timed
b9a0798c3f8880307d30acec1aca72efc8a7b557
Margasoiu-Luca/Chatbot-Project
/database.py
4,391
3.859375
4
import sqlite3 import os #Check to see if the database files do not exist if os.path.isfile('userinfo.db') is False: #Creates the staff login database userinfo_db = sqlite3.connect('userinfo.db') #Creates a connection to the database file cursor = userinfo_db.cursor() #Cursor object is called up using this variable cursor.execute(''' CREATE TABLE IF NOT EXISTS logindetails( userID INTEGER PRIMARY KEY, username TEXT NOT NULL, password TEXT NOT NULL, firstname TEXT NOT NULL, lastname TEXT NOT NULL); ''') #Creates the table if it does not exist in the database cursor.execute(''' CREATE TABLE IF NOT EXISTS extrainfo( ID INTEGER PRIMARY KEY, twitter TEXT NOT NULL, favteam TEXT NOT NULL, favplayer TEXT NOT NULL, FOREIGN KEY(ID) REFERENCES logindetails(userID)); ''') userinfo_db.commit() #Commits the statements, which saves changes made userinfo_db.close() #Closes the database def start(): login = 0 user_info_db = sqlite3.connect('userinfo.db') cursor = user_info_db.cursor() startup = input("are you a new user? (y/n): ") if startup == 'y': newusername = input('Please enter a new username: ') newpassword = input('Please enter a new password: ') newfirstname = input('Please enter a new first name: ') newlastname = input('Please enter a new last name: ') TwitterHandle = input('Please enter your Twitter Handle: ') FavTeam = input('Please enter your favourite team: ') FavPlayer = input('Please enter your favourite player: ') if len(newusername) == False or len(newpassword)== False or len(newfirstname)== False or len(newlastname)== False or len(TwitterHandle)== False or len(FavTeam)== False or len(FavPlayer)== False: print("Please fill in all boxes. Start Again.") start() else: if newfirstname.isalpha() is False or newlastname.isalpha() is False: print("First Name and Last Name must be characters. Start Again") start() else: #Checks to see if user input matches data in database cursor.execute(('SELECT username FROM logindetails WHERE username=?'),[newusername]) exists=cursor.fetchone() if exists: print("Username already exists. Start Again.") else: cursor.execute('''INSERT INTO logindetails(username,password,firstname,lastname) VALUES(?,?,?,?)''',[newusername,newpassword,newfirstname,newlastname]) cursor.execute('''INSERT INTO extrainfo(twitter,favteam,favplayer) VALUES(?,?,?)''',[TwitterHandle,FavTeam,FavPlayer]) user_info_db.commit() print("New User Created") print("Welcome",newfirstname,newlastname) print("Your favourite team is:",FavTeam) print("Your favourite player is:",FavPlayer) cursor.execute(('SELECT userID FROM logindetails WHERE username=?'),[newusername]) log=cursor.fetchone() login = log print("userid",login) elif startup == 'n': print("Please Log In!") username = input("Username: ") password = input("Password: ") user_info_db = sqlite3.connect('userinfo.db') cursor = user_info_db.cursor() cursor.execute(('SELECT * FROM logindetails WHERE username = ? AND password = ?'),[username,password]) verify=cursor.fetchall() if verify: for i in verify: name = (i[3],i[4]) print("Welcome",name) cursor.execute(('SELECT userID FROM logindetails WHERE username=?'),[username]) log=cursor.fetchone() login = log print("userid",login) else: print('Denied') else: print('That input is not recognised') start() start()
89a904389542128039479b52d6d1cc129367201d
bipinmilan/python
/remove_multiple_items_from_list.py
192
3.734375
4
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] new_color = [] for index, item in enumerate(color): if index not in (0, 4, 5): new_color.append(item) print(new_color)
8c0b22f2c3174d8a62452d7c7f94e44a08cadd14
skriLLeX123/Python
/Python Exception/Regex Module.py
159
3.546875
4
# program to implement Regex Module import re for i in range(int(input())): try: print(bool(re.compile(input()))) except: print(False)
af3a58d9c91737fc493149638ff5e144b23cdd00
Gilmardealcantara/Treinamento2
/flask1/app.py
544
3.6875
4
#!/usr/bin/python # -*- coding: iso-8859-15 -*- #http://pythonclub.com.br/what-the-flask-pt-1-introducao-ao-desenvolvimento-web-com-python.html from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "Olá mundo!! <strong> E viva o galo <strong>", 200 from flask import jsonify def json_api(): pessoas = [{"nome": "Bruno Rocha"}, {"nome": "Arjen Lucassen"}, {"nome": "Anneke van Giersbergen"}, {"nome": "Steven Wilson"}] return jsonify(pessoas=pessoas, total=len(pessoas)) app.run()
be9ad64ea4e1d7f204f59b519ecf29a0e4cfc0d5
erickgust/python-exercises
/mundo-02/ex058.py
514
3.546875
4
from random import randint print('Pensando... Um número entre 0 e 10...') r = randint(0, 10) p, s = 11, 0 while p != r: p = int(input('Em qual número eu pensei? ')) print('-='*13) print('PROCESSANDO...') print('-=' * 13) s += 1 if p == r: print('\033[32mPARABÉNS! Você acertou!\033[m') if s > 1: print('\033[33mMas você precisou de {} tentativas.\033[m'.format(s)) else: print('\033[31mNão foi dessa vez! Tente novamente.\033[m') print('-='*13)
93d45cbfcf645732e2126b28459e1376266e7814
Murilloalves/estudos-python
/mundo-1/utilizando-modulos/Seno_Cosseno_Tangente.py
390
3.984375
4
from math import radians, sin, cos, tan angulo = int(input('Digite o ângulo que você deseja: ')) seno = sin(radians(angulo)) print('O ângulo de {} te o SENO de {}'.format(angulo, seno)) cosseno = cos(radians(angulo)) print('O ângulo de {} te o COSSENO de {}'.format(angulo, cosseno)) tangente = tan(radians(angulo)) print('O ângulo de {} te o TANGENTE de {}'.format(angulo, tangente))
7ea58c7c3fbaf1bb06dda85dfd60d762ef7fc9f2
chaizhongming/algorithm008-class01
/Week_03/77.组合.py
810
3.59375
4
# # @lc app=leetcode.cn id=77 lang=python3 # # [77] 组合 # # @lc code=start class Solution: def combine(self, n: int, k: int) -> List[List[int]]: def backtrack(first=1,cur=[]): # print("cur:",cur) if len(cur)==k: print("cur:",cur) print("cur[:]:",cur[:]) output.append(cur[:]) output1.append(cur) # output.append(cur) print("output:",output) print("output1:",output1) return for i in range(first,n+1): cur.append(i) # print(cur) backtrack(i+1,cur) cur.pop() output=[] output1=[] backtrack() return output1 # @lc code=end
d6f82ee61d4adb912d62a4828bb909db2fb5d321
urielgoncalves/training-python
/exception.py
375
3.75
4
def dividir(primeiro_valor, segundo_valor): if segundo_valor == 0: raise ValueError("Não é permitido fazer divisão por 0.") return primeiro_valor / segundo_valor try: dividir(10,0) except ZeroDivisionError as erro: print("Tentativa de divisão por zero: {}".format(erro)) except Exception as erro: print("Exception genérica: {}".format(erro))
aae3ef0f6bb64ab5e29fea5e6e7c60400e219f64
julinvictus/python-noobs
/ex30.py
717
4.1875
4
# script to decide: take car or bus? people = 30 cars = 40 buses = 15 if cars > people: print "We should take the cars." # more cars than ppl elif cars < people: print "We should not take the cars." # less cars than ppl, not enough else: print "We can't decide." # same amount of both, whatever if buses > cars: print "That's too many buses." # more buses than cars elif buses < cars: print "Maybe we could take the buses." # less buses than cars else: print "We still can't decide." # same amount of buses and cars if people > buses: print "Alright, let's just take the buses." # more ppl than buses else: print "Fine, let's stay home then." # less ppl than buses, or same amount
07f3ae88343b8df114cdd5f877c428426afcfe33
fatecoder/Python-practices
/closest.py
797
3.734375
4
#!/bin/python #array = [4, 5, -1, 1, -2, -3] #array = [2, 4, -1, -3] #array = [5, 2, -2] array = [5, -2, -2, 0] def clos(array) : negative_closest = min(array) positive_closest = max(array) for i in range(0, len(array)) : if array[i] < 0 : if negative_closest < array[i] : negative_closest = array[i] elif array[i] == 0: return 0 else : if positive_closest > array[i] : positive_closest = array[i] if abs(negative_closest) < positive_closest : return negative_closest elif abs(negative_closest) > positive_closest : return positive_closest elif negative_closest == positive_closest : return positive_closest else : return print clos(array)
765e3057c97f4fb18d48be0fa48607b201173d45
Chris-Draper/quibid-scraper
/test_timer.py
400
3.84375
4
import random import time input("Testing timer functionality. Press enter to continue") end_wait = random.randint(1, 60) start_wait = time.time() duration_wait = 0 print("Random wait time is {} seconds".format(end_wait)) while end_wait > duration_wait: duration_wait = time.time() - start_wait print("Waited exactly {} seconds".format(duration_wait)) print("Now preform action after timer expires")
21d9f331f8410e3ba0ac93419cc7efb1b3ea0c31
BhatnagarKshitij/Algorithms
/Array/containDuplicate.py
478
3.78125
4
''' Question link: https://leetcode.com/problems/contains-duplicate/ Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. ''' class Solution: def containsDuplicate(self, nums: List[int]) -> bool: oldLength=len(nums) newLength=len(set(nums)) return False if oldLength == newLength else True solution=Solution() print(solution.containsDuplicate([]))
428cab9fd532ce2ea29eaa7c6dfbd2b81550c105
timswinkels/project-euler-answers
/3-largest-prime-factor.py
1,835
3.953125
4
# Project Euler #3: https://projecteuler.net/problem=3 import math def is_prime_number(n): # Returns boolean that indicates if the given value is a prime number if float(n).is_integer() is False: # Checks if "n" is full number return False elif n <= 1: return False else: for i in range(2, int(n)): if (n % i) == 0: return False break return True def get_next_prime_number(n): # Returns the first prime number that comes after "n" if is_prime_number(n) is False: raise Exception('Can only get next prime number if prime number is given. %s is not a prime number' % n) i = n + 1 while i: if is_prime_number(i): return i i += 1 def get_prime_factors(n): # Returns the list factors that consist of prime numbers only if is_prime_number(n): raise Exception('Cannot get prime factors for prime number: %s' % n) factors = [] n_decomposed = n while n_decomposed > 0: # Start discovering the prime factors by decomposing "n" square_root = math.sqrt(n_decomposed) prime_number = 2 while prime_number <= square_root: devision = n_decomposed / prime_number if devision.is_integer(): # Devision is full number then prime number should be added to list of factors factors.append(prime_number) n_decomposed = n_decomposed / prime_number if is_prime_number(devision): # Devision is prime number, which indicates all factors have been found factors.append(int(n_decomposed)) n_decomposed = 0 break # Try next prime number prime_number = get_next_prime_number(prime_number) return factors n = 600851475143 factors = get_prime_factors(n) print('The largest prime factor for %s is %s. Full list is: %s' % (n, max(factors), factors))
d20e14f2dbfa900e43f0ce0169535fd91859e4d9
owari-taro/concurrency_in_python
/concurrency_with_asyncio/ch6/process_pool.py
569
3.609375
4
from multiprocessing import Process def say_hello(name: str) -> str: return f"hi there {name}" import time def count(to: int) -> int: st = time.time() counter = 0 while counter < to: counter = counter + 1 ed = time.time() print(f"finished counting to {to} in {ed -st}") if __name__ == "__main__": st = time.time() one = Process(target=count, args=(100_000_000,)) two = Process(target=count, args=(200_000_000,)) one.start() two.start() one.join() two.join() ed = time.time() print(f"{ed-st}")
4db51224102831d8620284950da6d27258a5dd6e
Daniel-Osei/global-code2019
/dev-globalcode/basics/split.py
131
3.796875
4
sentence = "I am daniel, new to python and trying to split the sentence into words" print (sentence) print (sentence.split(" "))
416d6f319937934c843a9bfdc35b1deacd79d8e7
vladignatyev/markovfsm
/src/markovfsm/__init__.py
3,332
3.578125
4
from copy import copy from random import random class Chain(object): def __init__(self, states_count, initial_state): self._states_count = states_count self._initial_state = initial_state self.clear() """ Build Markov chain from data by feeding new state of the random process """ def learn(self, state): self.states[self.current_state][state] = self.states[self.current_state][state] + 1 self.current_state = state """ Get the transition matrix P of Markov chain """ def transition_matrix(self): m = copy(self.states) for i in range(self._states_count): s = 1.0 / sum([m[i][j] for j in range(self._states_count)]) m[i] = [m[i][j] * s for j in range(self._states_count)] return m """ Get probabilities of transitions to another states from current state """ def get_transitions_probs(self, state): s = 1.0 / sum([self.states[state][j] for j in range(self._states_count)]) c = copy(self.states[state]) return [c[i] * s for i in range(self._states_count)] """ Clear the model """ def clear(self): self.states = [[0 for j in range(self._states_count)] for i in range(self._states_count)] self.current_state = self._initial_state class FSM(object): def __init__(self, chain, initial_state, rnd=random): self.chain = chain self.current_state = initial_state self._rnd = rnd @property def state(self): return self.current_state def next(self): probs = self.chain.get_transitions_probs(self.current_state) r = self._rnd() p0 = 0.0 p1 = 0.0 for i in range(len(probs)): p1 = p0 + probs[i] if r >= p0 and r < p1: self.current_state = i return self.current_state else: p0 = p1 if __name__ == '__main__': from random import random # build Markov chain with 2 states, init with random state chain = Chain(2, 0 if random() > 0.5 else 1) # flip coin many times and build Markov chain for this process # let 0 be heads and 1 tails for i in range(1000000): chain.learn(0 if random() > 0.5 else 1) # get transition matrix # It should look like: # # P = | 0.5 0.5 | # | 0.5 0.5 | # P = chain.transition_matrix() print "%s %s" % (P[0][0], P[0][1]) print "%s %s" % (P[1][0], P[1][1]) # get probabilities of transition from state 0 to other states (0 and 1) # actually, the line in the transition matrix print chain.get_transitions_probs(0) # let's make a FSM with stochastic properties equal to described by Markov chain # use rnd() as a random numbers generator, and 0 (heads) as initial state fsm = FSM(chain, 0) # let's make another chain, build upon random process emulated by FSM chain2 = Chain(2, 0) # make a chain with states produced by FSM for j in range(1000000): chain2.learn(fsm.next()) # get transition matrix. it should be nearly equal P2 = chain2.transition_matrix() print "%s %s" % (P2[0][0], P2[0][1]) print "%s %s" % (P2[1][0], P2[1][1]) print chain2.get_transitions_probs(0)
78c06897311ac6f0ae78f9404579f8a99f043415
wayne1116/Uva-Online-programming
/Python/11219-How old are you.py
612
3.671875
4
#!/usr/bin/python import sys a=int(sys.stdin.readline()) b=1 while b<=a: line=sys.stdin.readline() line=sys.stdin.readline() line1=line.split('/') line=sys.stdin.readline() line2=line.split('/') for i in range(3): line1[i]=int(line1[i]) line2[i]=int(line2[i]) result=line1[2]-line2[2] if line1[1]<line2[1]: result-=1 elif line1[1]==line2[1] and line1[0]<line2[0]:result-=1 print('Case #{0}: '.format(b),end='') if result<0: print('Invalid birth date') elif result>130:print('Check birth date') else: print(result) b+=1
f9ec922804d221389023c9b8f8bec1ccc037ceab
jiri-skrobanek/abtrees
/abtree.py
8,602
3.96875
4
import math class InternalNode: """Represents a node in (a,b)-tree which is not a leaf.""" def __init__(self, parent=None): self.keys = [] self.children = [] self.parent = parent def __str__(self): return self.keys.__str__() class ExternalNode: """Represents a node in (a,b)-tree which is a leaf.""" def __init__(self, key: int, value=None): self.key = key self.value = value class ABTree: """(a,b)-search tree, receives (a,b) upon creation.""" def __init__(self, a: int, b: int): if a < 2: raise ValueError('Improper a,b choice.') if b < 2*a - 1: raise ValueError('Improper a,b choice.') self.a = a self.b = b self.root = None self.level = 0 self.count = 0 def item_count(self): return self.count def find(self, key: int): if not self.root: return None lev = 0 node = self.root while lev < self.level: i = 0 while node.keys[i] < key: i += 1 lev += 1 node = node.children[i] if node.key == key: return node.value return None def __getitem__(self, item): return self.find(item) def __len__(self): return self.count def insert(self, key: int, value=None): if self.root is None: self.root = InternalNode(None) self.root.keys.append(key) self.root.keys.append(math.inf) self.root.children.append(ExternalNode(key, value)) self.root.children.append(ExternalNode(math.inf, None)) self.level = 1 self.count = 1 return node = self.root for lev in range(self.level - 1): i = 0 while node.keys[i] < key: i += 1 node = node.children[i] i = 0 while node.keys[i] < key: i += 1 if node.keys[i] == key: raise ValueError('Repeating key') node.keys.insert(i, key) node.children.insert(i, ExternalNode(key, value)) self.__rebalance(node) self.count += 1 def __rebalance(self, node: InternalNode): children = len(node.children) if node.parent is None: if children < 2: if isinstance(node.children[0], ExternalNode): self.root = None del node.children[0] del node self.level = 0 else: self.root = node.children[0] self.root.parent = None del node self.level -= 1 elif children > self.b: lsize = (children + 1) // 2 left = InternalNode(node) left.children = node.children[:lsize] for child in left.children: child.parent = left left.keys = node.keys[:lsize] right = InternalNode(node) right.children = node.children[-lsize:] for child in right.children: child.parent = right right.keys = node.keys[-lsize:] self.level += 1 node.children = [left, right] node.keys = [left.keys[-1], right.keys[-1]] elif children > self.b: lsize = (children + 1) // 2 new_node = InternalNode(node.parent) new_node.children = node.children[:lsize] for child in new_node.children: child.parent = new_node new_node.keys = node.keys[:lsize] node.children = node.children[-lsize:] node.keys = node.keys[-lsize:] new_key = new_node.keys[-1] i = 0 while node.parent.keys[i] < new_key: i += 1 node.parent.keys.insert(i, new_key) node.parent.children.insert(i, new_node) self.__rebalance(node.parent) elif children < self.a: i = 0 continue_with = node.parent while node.parent.keys[i] < node.keys[-1]: i += 1 if i < len(node.parent.keys) - 1 and len(node.parent.children[i+1].keys) == self.a: self.__fuse_ith_with_right(node.parent, i) elif i < 0 and len(node.parent.children[i-1].keys) == self.a: self.__fuse_ith_with_right(node.parent, i - 1) elif i < len(node.parent.keys) - 1: self.__fuse_ith_with_right(node.parent, i) else: self.__fuse_ith_with_right(node.parent, i - 1) self.__rebalance(continue_with) def __fuse_ith_with_right(self, node: InternalNode, i: int): left = node.children[i] right = node.children[i+1] right.keys = left.keys + right.keys right.children = left.children + right.children del node.children[i] del node.keys[i] for child in right.children: child.parent = right def find_leq(self, key: int): if key == math.inf: raise ValueError('Infinity!') if self.root is None: return None node = self.root for lev in range(self.level - 1): i = 0 while i < len(node.keys) - 1 and node.keys[i+1] <= key: i += 1 node = node.children[i] i = 0 while i < len(node.keys) - 1 and node.keys[i + 1] < key: i += 1 return node.children[i].key, node.children[i].value def find_lesser(self, key: int): if key == math.inf: raise ValueError('Infinity!') if self.root is None: return None node = self.root for lev in range(self.level - 1): i = 0 while i < len(node.keys) - 1 and node.keys[i + 1] < key: i += 1 node = node.children[i] i = 0 while i < len(node.keys) - 1 and node.keys[i + 1] < key: i += 1 return node.children[i].key, node.children[i].value def find_geq(self, key: int): if key == math.inf: raise ValueError('Infinity!') if self.root is None: return None node = self.root for lev in range(self.level - 1): i = 0 while node.keys[i] < key: i += 1 node = node.children[i] i = 0 while node.keys[i] < key: i += 1 return node.children[i].key, node.children[i].value def find_greater(self, key: int): if key == math.inf: raise ValueError('Infinity!') if self.root is None: return None node = self.root for lev in range(self.level - 1): i = 0 while node.keys[i] <= key: i += 1 node = node.children[i] i = 0 while node.keys[i] <= key: i += 1 return node.children[i].key, node.children[i].value def contains(self, key: int): node = self.root lvl = 0 node = self.root while lvl < self.level: i = 0 while node.keys[i] < key: i += 1 if node.keys[i] == key: return True lvl += 1 node = node.children[i] return False def delete(self, key: int): if not self.root: raise ValueError('No such key in tree.') lev = 0 node = self.root while lev < self.level - 1: i = 0 while node.keys[i] < key: i += 1 lev += 1 node = node.children[i] i = 0 while node.keys[i] < key: i += 1 if node.keys[i] != key: raise ValueError('No such key in tree.') del node.children[i] del node.keys[i] if i == len(node.keys) and node != self.root: # Deleted last key, change keys in ancestors. parent = node.parent while lev > 0: j = 0 while parent.keys[j] < key: j += 1 if parent.keys[j] == key: parent.keys[j] = node.keys[i-1] else: break lev -= 1 parent = parent.parent self.__rebalance(node) self.count -= 1
763ea222ac0a5bb6e29d7a4627e1dc4c07e78dac
Singlea-lyh/LeetCode
/Python/61.rotate-list.py
2,954
3.953125
4
# # @lc app=leetcode id=61 lang=python3 # # [61] Rotate List # # https://leetcode.com/problems/rotate-list/description/ # # algorithms # Medium (29.10%) # Likes: 1168 # Dislikes: 988 # Total Accepted: 267.3K # Total Submissions: 901.7K # Testcase Example: '[1,2,3,4,5]\n2' # # Given a linked list, rotate the list to the right by k places, where k is # non-negative. # # Example 1: # # # Input: 1->2->3->4->5->NULL, k = 2 # Output: 4->5->1->2->3->NULL # Explanation: # rotate 1 steps to the right: 5->1->2->3->4->NULL # rotate 2 steps to the right: 4->5->1->2->3->NULL # # # Example 2: # # # Input: 0->1->2->NULL, k = 4 # Output: 2->0->1->NULL # Explanation: # rotate 1 steps to the right: 2->0->1->NULL # rotate 2 steps to the right: 1->2->0->NULL # rotate 3 steps to the right: 0->1->2->NULL # rotate 4 steps to the right: 2->0->1->NULL # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class ListNode: def __init__(self, val = 0, next = None): self.val = val self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: # ret = None # listlen = 0 # rotatenum = 0 # if head == None: # return None # temp = head # tail = None # while temp != None: # listlen += 1 # tail = temp # temp = temp.next # print(listlen) # rotatenum = k % listlen # if rotatenum == 0: # return head # idx = 0 # temp = head # while idx < (listlen - rotatenum - 1): # temp = temp.next # idx += 1 # newhead = temp.next # tail.next, temp.next = head, tail.next # ret = newhead # return ret ret = None listlen = 0 if head == None: return head temp = head while temp.next != None: temp = temp.next listlen += 1 listlen += 1 rotatenum = k % listlen if rotatenum == 0: return head temp.next = head temp = head idx = 0 while idx < (listlen - rotatenum - 1): temp = temp.next idx += 1 ret = temp.next temp.next = None return ret if __name__ == "__main__": solu = Solution() head = None for i in range(2, -1, -1): temp = ListNode(i,head) # temp.next = head head = temp temp = head while temp != None: print(temp.val, end = "->") temp = temp.next print("NULL") ret = solu.rotateRight(head, 4) temp = ret while temp != None: print(temp.val, end = "->") temp = temp.next print("NULL") # @lc code=end
37c2d435edea212f5260d0e9480e91c1ca5a28db
MarkLouren/EDU-PythonPrograms
/11-Udemy-ThePythonBible-CreateCoin[Class].py
892
3.609375
4
#classes coins.py [Methods] import random class Pound: def __init__(self, rare=False): self.rare = rare # the dame self.rare=True=> if self.rare: self.value = 1.25 else: self.value = 1.00 self.value = 1.00 self.colour = "gold" self. num_edges = 1 self.diameter = 22.5 # mm self.thickness = 3.15 # mm self.heads = True # create a method example: coin1.rust() => coin1.colour=> greenish def rust(self): self.colour="greenish" def clear (self): self.colour="gold" #flip coin => coin1.flip() => True or False def flip(self): heads_options =[True, False] choice = random.choice(heads_options) self.heads=choice #destructor method => del coin1 => Coin Spent=>not defined def __del__(self): print ("Coin Spent")
61a47cc902af5a6a9e64e663afdb0b8da357c64e
renjithrnair/training_renjithrnair
/python/set3/five.py
1,096
3.921875
4
class Calc(): def add(self,input1,input2): if((type(input1) or type(input2)) not in [int,float]): raise TypeError("Enter valid numbers") return input1+input2 def sub(self,input1,input2): if((type(input1) or type(input2)) not in [int,float]): raise TypeError("Enter valid numbers") return input1-input2 def mul(self,input1,input2): if((type(input1) or type(input2)) not in [int,float]): raise TypeError("Enter valid numbers") return input1*input2 def div(self,input1,input2): if((type(input1) or type(input2)) not in [int,float]): raise TypeError("Enter valid numbers") if(input2==0): raise ValueError("input2 cannot be zero") return input1/input2 obj=Calc() print "Enter 1st number : " input1=raw_input() print "Enter 2nd number : " input2=raw_input() input1=int(input1) input2=int(input2) sum=obj.add(input1,input2) difference=obj.sub(input1,input2) product=obj.mul(input1,input2) division=obj.div(input1,input2) print "Sum : " print sum print "Difference : " print difference print "Product : " print product print "Division : " print division
4b332d4aaa7d755bfdbfae48b064be2249d8ca9b
priyanshu-upadhyay/DSA-Programs--Java-
/stack.py
1,528
4.15625
4
# Stack Operation # 1 - Push # 2 - Pop # 3 - Display # 4 - Peek (Top Element of the Stack) # .................STARTING....................... # ................................................ stack = [] # List of Stack top = -1 # or None def push(stack): global top item = int(input("Enter the Element: ")) stack.append(item) top = top + 1 def pop(stack): global top if stack == []: print("Stack is Empty...... (Or Underflow)") else: print("Deleted Element:",stack.pop()) top = top - 1 def peek(stack): if stack == []: print("Stack is Empty.") else: print("Top of the Stack:",stack[top]) def display(stack): if stack == []: print("Stack is Empty.") else: print("\n\n......Stack.......\n") # Ignore for i in range(top,-1,-1): print(stack[i]) print("\n..................\n\n") # Ignore # Starting of the Program.. while(True): print(".......STACK OPERATIONS........") print("1 - PUSH") print("2 - POP") print("3 - DISPLAY") print("4 - PEEK (Top Element of the Stack)") print("5 - Exit from the System") ch = int(input("Enter Your Choice (1-5): ")) if ch == 1: push(stack) elif ch == 2: pop(stack) elif ch == 3: display(stack) elif ch == 4: peek(stack) elif ch == 5: exit(0) # We can also use Break else: print("Invaild Choice")
120c20328a78028c958f406b8f6f0de4e9705e2d
john544465165/CP1404-practicals
/prac_06/programming_language.py
747
3.953125
4
class ProgrammingLanguage: def __init__(self, name, typing, reflection, year): """Constructor that takes in parameters and create object""" self.name = name self.typing = typing self.reflection = reflection self.year = year def __str__(self): """return the detail of the language""" return "{}, {} Typing, Reflection={}, First appeared in {}".format(self.name, self.typing, self.reflection, self.year) def is_dynamic(self): """Judge if language is dynamic.""" return self.typing == "Dynamic" def test(): """To check with python""" python = ProgrammingLanguage("Python", "Dynamic", True, 1991) print(python) if __name__ == "__main__": test()
a9dd7a64363344bb114b5cdc1270c82a6dcaa94f
amankedia/Project-Euler
/Divby3or5.py
143
3.859375
4
def calculate(x): sum=0 for i in range(x): if(i%3 == 0 or i%5==0): sum=sum+i return sum print(calculate(1000))