blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
37a0f93ac1edcf603418a28c35b5204c20f45409
khoipn1504/Practices
/Data Structures/Sorting and Selection/QuickSort.py
519
4
4
def quickSort(inputList): processList = inputList.copy() # dòng này là để thuật toán không ảnh hưởng List gốc bên ngoài if len(processList) < 2: return processList pivot = processList.pop() lowList = [] highList = [] for i in processList: if i < pivot: lowList.append(i) else: highList.append(i) return quickSort(lowList)+[pivot]+quickSort(highList) a = [2, 5, 2, 7, 9, 0, 7, 3, 4, 67] print(quickSort(a)) print(a)
84789747d282e9a72adbf3b7cac8b9659ad46ea2
akshayskumar94/Stock-Details-of-Tesla-and-Gamestop-DV
/Python Project 1- Extracting and Visualizing Stock Data.py
3,600
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # Extracting and Visualising Stock and Revenue Data # ***Using Tesla and Gamestop as example*** # Entering 2021 we have seen a huge surge in the share prices of Tesla and Gamestop, Let us compare this surge with the quarterly revenue data for the respective companies using Data Scraping and Data Visualisation Techniques. # ***Install necessary packages*** # In[1]: get_ipython().system('pip install yfinance') #!pip install pandas #!pip install requests get_ipython().system('pip install bs4') #!pip install plotly # In[2]: import yfinance as yf import pandas as pd import requests from bs4 import BeautifulSoup import plotly.graph_objects as go from plotly.subplots import make_subplots # ***Defining the graph function*** # In[3]: def make_graph(stock_data, revenue_data, stock): fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3) fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data.Date, infer_datetime_format=True), y=stock_data.Close.astype("float"), name="Share Price"), row=1, col=1) fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data.Date, infer_datetime_format=True), y=revenue_data.Revenue.astype("float"), name="Revenue"), row=2, col=1) fig.update_xaxes(title_text="Date", row=1, col=1) fig.update_xaxes(title_text="Date", row=2, col=1) fig.update_yaxes(title_text="Price ($US)", row=1, col=1) fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1) fig.update_layout(showlegend=False, height=900, title=stock, xaxis_rangeslider_visible=True) fig.show() # ***Extracting Tesla Stock Data*** # In[5]: data=yf.Ticker("TSLA") # In[6]: tesla_data=data.history(period='max') tesla_data.reset_index(inplace=True) tesla_data.head() # ***Webscraping using beautifulsoup to extract tesla quarterly revenue*** # In[11]: data1=requests.get('https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue').text soup=BeautifulSoup(data1,'html5lib') #Parsing withbeautiful soup tables = soup.find_all('table') data=pd.read_html(str(tables[1]), flavor='bs4') #Selecting tables with revenue data tesla_revenue=data[0] #Extracting tesla quarterly revenue tesla_revenue.columns=["Date","Revenue"] tesla_revenue["Revenue"]=tesla_revenue["Revenue"].str.replace('$',"").str.replace(",","") #Removing special charatcer from Revenue tesla_revenue.dropna(subset=['Revenue'], inplace=True) #Removing Null values print(tesla_revenue) # ***Extracting Gamestop Stock Data*** # In[12]: data=yf.Ticker("GME") gme_data=data.history(period='max') gme_data.reset_index(inplace=True) gme_data.head() # ***Webscraping using beautifulsoup to extract GameStop quarterly revenue*** # In[14]: url="https://www.macrotrends.net/stocks/charts/GME/gamestop/revenue" html_data=requests.get(url).text soup=BeautifulSoup(html_data,"html5lib") #Parsing with beautiful soup tables=soup.find_all("table") data=pd.read_html(str(tables[1]), flavor='bs4') #Selecting tables with revenue data gme_revenue=data[0] #Extracting quarterly revenue gme_revenue.columns=["Date","Revenue"] gme_revenue["Revenue"]=gme_revenue["Revenue"].str.replace('$','').str.replace(",","") #Removing special characters gme_revenue.dropna(subset=['Revenue'], inplace=True) #Removing NULL values print(gme_revenue) # ***Plotting graphs of Historical Share Price and Historical Revenue for Tesla and GameStop*** # In[15]: make_graph(tesla_data,tesla_revenue,'Tesla') # In[16]: make_graph(gme_data,gme_revenue,'GameStop')
beb65d91449d6aa32bce7b1d10d2264e3ab5f5ea
Levintsky/topcoder
/python/leetcode/locked/1102_answer.py
938
3.515625
4
""" Since heappop() only pop the smallest number from the queue, but what I want is the element with the highest score so far, so I change all scores to negative number, so that I can pop the element with highest score. Notice: memo is used to store the cells that have been visited. """ class Solution: def maximumMinimumPath(self, matrix: List[List[int]]) -> int: de = ((1,0),(0,1),(-1,0),(0,-1)) rl, cl = len(matrix), len(matrix[0]) q = [(-matrix[0][0],0,0)] memo = [[1 for _ in range(cl)] for _ in range(rl)] while q: t, x, y = heapq.heappop(q) if x == rl - 1 and y == cl - 1: return -t for d in de: nx = x + d[0] ny = y + d[1] if 0 <= nx < rl and 0 <= ny < cl and memo[nx][ny]: memo[nx][ny] = 0 heapq.heappush(q, (max(t, -matrix[nx][ny]), nx, ny))
66d708b47773445f60ec800651a2b768ba11675c
zhrcosta/string-functions
/reverse_string_method_1.py
250
4.3125
4
def reverseString(string): # Função para inverter os caracteres de uma STRING método 1 reversed = "" for index in range(1, len(string)+1): reversed += string[-index] return reversed print(reverseString("zhrcosta"))
1b7e0ab5398dd3ef24558a6c4804274104beffc5
chullee123/learnPython
/pythonScripts/MIT6.00.1x/unit1/alphabetString.py
643
4.125
4
""" Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. """ s = "abcdefghijklmnopqrstuvwxyz" highest = "" def getIfNext(s, i, c = ""): currentString = s[i] c += currentString if i+1 >= len(s): return c nextString = s[i+1] if int(ord(currentString)) <= int(ord(nextString)): i += 1 return getIfNext(s, i, c) else: return c for i in range(len(s)): r = getIfNext(s, i) if len(r) > len(highest): highest = r print("Longest substring in alphabetical order is: " + highest)
ccbc930c8468c54eb05c74d8db0d198109de3be9
danyaeche/simple_todo_list-
/todo_list.py
1,284
3.890625
4
class Todo_list(object): def __init__(self): self.items_dict = {} self.counter = 0 def add_item(self, item): if type(item) != str: print("input item has to be a string") elif item in self.items_dict: pass else: self.counter += 1 self.items_dict[item] = self.counter def edit_item(self, item, new_item): if item in self.items_dict: self.items_dict[new_item] = self.items_dict.pop(item) else: print("Item is not in todo_list") def delete_item(self, item): if item in self.items_dict: del self.items_dict[item] else: print("Item is not placed in the list") def return_length(self): return len(self.items_dict) def delete_n_item(self, n): if n <= len(self.items_list): for key, val in self.items_dict.items: if val == n: del self.items_dict[key] else: print("item doesn't exist in to do list") def delete_select_items(self, delete_list): for x in delete_list: for key, val in self.items_dict.items: if key == x: del self.items_dict[key] def sort_list(self): sorted_items_list = sorted(self.items_dict.items(), key=lambda x: x[1]) self.items_dict = sorted_items_list
cd0505699a00ee2e329797df12349aa658714de3
niyaznigmatullin/nncontests
/utils/IdeaProject/archive/unsorted/2015.05/2015.05.16 - IPSC 2000/e.py
108
3.5625
4
def fact(n): return 1 if n == 0 else n * fact(n - 1) print(fact(300) // fact(50) // fact(250))
287de0f286cc95e46efd818d43cb48f8341e9546
Ylfcynn/Python_Practice
/quantify_words.py
2,777
4.09375
4
""" Write a function that quantifies word occurrences in a given string. >>> quantify_words("Red touching black is a friend of Jack, Red touching yellow can kill a fellow.") Lexis: 'a', occurrences: 2 Lexis: 'black', occurrences: 1 Lexis: 'can', occurrences: 1 Lexis: 'fellow', occurrences: 1 Lexis: 'friend', occurrences: 1 Lexis: 'is', occurrences: 1 Lexis: 'jack', occurrences: 1 Lexis: 'kill', occurrences: 1 Lexis: 'of', occurrences: 1 Lexis: 'red', occurrences: 2 Lexis: 'touching', occurrences: 2 Lexis: 'yellow', occurrences: 1 >>> quantify_words("In the end, it's concluded that the airspeed velocity of a (European) unladen swallow is about 24 miles per hour or 11 meters per second.") (european), occurrences: 1 '11', occurrences: 1 '24', occurrences: 1 'a', occurrences: 1 'about', occurrences: 1 'airspeed', occurrences: 1 'concluded', occurrences: 1 'end', occurrences: 1 'hour', occurrences: 1 'in', occurrences: 1 'is', occurrences: 1 'it's', occurrences: 1 'meters', occurrences: 1 'miles', occurrences: 1 'of', occurrences: 1 'or', occurrences: 1 'per', occurrences: 2 'second', occurrences: 1 'swallow', occurrences: 1 'that', occurrences: 1 'the', occurrences: 2 'unladen', occurrences: 1 'velocity', occurrences: 1 """ """ Doby's work. Please don't laugh. I'm new at this. """ import os import re def display(tallies: dict) -> None: """ Prints the dictionary 'tallies' and prints them out, sorted by values. """ for key, value in sorted(tallies.items(), key=lambda t: t[1], reverse=True)[:10]: print(f'Lexis: \'{key}\',', f'occurrences: {value}') def lexeis_gen(phrase: str) -> str: """ Scrubs punctuation, converts to lowercase >>> lexeis_gen('Test: An ungulatory proposition; The llamma, (John), asked, "Let us eat spam and Eggs!".') 'Test An ungulatory proposition The llamma John asked Let us eat spam and Eggs' """ pattern = re.compile(r'[\d!:;,\.\"()-]') no_punc = pattern.sub(' ', phrase) wee_no_punc = no_punc.lower() return wee_no_punc def quantify(生: str) -> None: """ Analyzes textual input for lexical frequencies and displays the most frequent occurrences in the terminal. :param 生: """ cooked = lexeis_gen(生) lexeis = cooked.split() tallies = dict() for word in lexeis: try: tallies[word] += 1 except KeyError: tallies[word] = 1 display(tallies) def loader() -> None: # 'file handler' """ A 'boilerplate' construction, returns file contents as a string. """ path = input('Path to codex to analyze: ') # Ex. '/Users/ylf/Git/Python_Practice/Bēowulf.txt' with open(path, 'r') as file: codex = file.read() quantify(codex) loader()
6f5d94a4b46cc10c2b0a0603ea517aab6ba58930
vsham20/hackerrank
/second_largest.py
333
3.6875
4
__author__ = 'vaishali' # Enter your code here. Read input from STDIN. Print output to STDOUT N = int(raw_input()) A = map(int,raw_input().split(" ")) first, second = None, None for n in A: if n > first: first, second = n, first elif first > n > second: second = n print second #def second_largest(numbers):
e8150d2ee944b6795c252b3c281fec7d0708a731
rahil1303/Hackerrank_Python_Solutions_Repository
/String_Validators.py
372
4
4
#### You are given a string . ##Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. s = str(input()) print(any(a.isalnum()) for a in s) print(any(a.isalpha()) for a in s) print(any(a.isdigit()) for a in s) print(any(a.islower()) for a in s) print(any(a.isupper()) for a in s)
848aa4f4a8da11c94bda810393aead647ef56461
JakobKallestad/Python-Kattis
/src/tester2.py
404
3.640625
4
from collections import deque, defaultdict def bfs(adj, start, goal): visited = set() parentOf = defaultdict(int) queue = deque while queue: current = queue.pop() for nbr in adj[current]: if nbr not in visited: visited.add(nbr) parentOf[nbr] = current if nbr == goal: return True return False
5d93f3b2f75baa24314b65ee08104457628cb928
DenisaGal/Syneto-Lab
/Lab2_HW/HW2_E2.py
283
4.28125
4
capitals = { 'Timis': 'Timisoara', 'Bihor': 'Oradea', 'Arad': 'Arad', 'Hunedoara': 'Deva', 'Caras-Severin': 'Resita', } def judet(capital): for c in capitals: if(capitals[c] == capital): return c return 'Unknown' print(judet('Arad'))
e3b6bcc3d57ca36c85b6116f9beb9e1a74f8ac08
adamandersen/learnpythonthehardway
/ex15.py
557
3.90625
4
from sys import argv # take one argument in. Any text file script, filename = argv; # prompt format prompt = '> ' # open the passed textfile txt = open(filename); # print the textfile name to the console print "Here's your file %r:" % filename; # read the open textfile and print the context in the console print txt.read(); # user information print "Type the filename again:"; # enter another textfile file_again = raw_input(prompt); # open the textfile txt_again = open(file_again); # print out the cached opened textfile print txt_again.read();
39853c4e1ef2950b255bf433ef5b3127161aa1d7
mpereza42/toy-robot-task
/test/test_toyrobotinterpreter.py
1,631
3.53125
4
import unittest from unittest.mock import Mock, call from inputparser import InputParser from toyrobotinterpreter import ToyRobotInterpreter from toyrobot import ToyRobot class Test(unittest.TestCase): def testName01(self): """ Testing ToyRobotInterpreter place() handler """ toy = ToyRobot() toy.place = Mock() tri = ToyRobotInterpreter(toy) tri.cmd_PLACE_handler('1,2,NORTH') toy.place.assert_called_once_with(1, 2, 'NORTH') def testName02(self): """ Testing multiple ToyRobotInterpreter place() calls """ toy = ToyRobot() toy.place = Mock() tri = ToyRobotInterpreter(toy) tri.cmd_PLACE_handler('1,2,NORTH') tri.cmd_PLACE_handler('3,4,EAST') expected = [call(1,2,'NORTH'), call(3,4,'EAST')] self.assertEqual(toy.place.call_args_list, expected,"method_calls not initialised correctly") def testName03(self): """ Testing correct ToyRobot calls """ robot_attrs = {'TRANSITIONS': ToyRobot.TRANSITIONS, 'FACINGS': ToyRobot.FACINGS} toy = Mock(**robot_attrs) ip = InputParser(ToyRobotInterpreter(toy)) ip.process_line('PLACE 1,2,NORTH MOVE LEFT PLACE 3,4,EAST RIGHT REPORT') expected = [call.place(1, 2, 'NORTH'), call.move(), call.rotate_left(), call.place(3, 4, 'EAST'), call.rotate_right(), call.report()] self.assertEqual(toy.method_calls, expected, "methods not invoked correctly") if __name__ == "__main__": unittest.main()
e549eacb5a552d3124bab1c0a90ec3ee3c1dfbdb
L-Glogov/crypto-python
/freqAnalysis.py
2,483
3.65625
4
# Frequency Finder # # Based on chapter 19 of Cracking Codes with Python by Al Sweigart # https://www.nostarch.com/crackingcodes/ (BSD Licensed) ETAOIN = 'ETAOINSHRDLCUMWFGYPBVKJXQZ' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def getLettersCount(message): # Returns a dictionary with keys of single letters and values of the # count of how many times they appear in the message parameter: letterCount = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0} for letter in message.upper(): if letter in LETTERS: letterCount[letter] += 1 return letterCount def getItemAtIndexZero(items): return items[0] def getFrequencyOrder(message): # Returns a string of the alphabet letters arranged in order of most # frequently occurring in the message parameter. # A dictionary of each letter and its frequency count: letterToFreq = getLettersCount(message) freqToLetter = {} for letter in LETTERS: if letterToFreq[letter] not in freqToLetter: freqToLetter[letterToFreq[letter]] = [letter] else: freqToLetter[letterToFreq[letter]].append(letter) for freq in freqToLetter: freqToLetter[freq].sort(key=ETAOIN.find, reverse=True) freqToLetter[freq] = ''.join(freqToLetter[freq]) freqPairs = list(freqToLetter.items()) freqPairs.sort(key=getItemAtIndexZero, reverse=True) freqOrder = [] for freqPair in freqPairs: freqOrder.append(freqPair[1]) return "".join(freqOrder) def englishFreqMatchScore(message): # Return the number of matches that the string in the message # parameter has when its letter frequency is compared to English # letter frequency. A "match" is how many of its six most frequent # and six least frequent letters are among the six most frequent and # six least frequent letters for English. freqOrder = getFrequencyOrder(message) matchScore = 0 # Find how many matches for the six most common letters there are: for commonLetter in ETAOIN[:6]: if commonLetter in freqOrder[:6]: matchScore += 1 # Find how many matches for the six least common letters there are: for uncommonLetter in ETAOIN[-6:]: if uncommonLetter in freqOrder[-6:]: matchScore += 1 return matchScore
5e1281580da0e8e37870bfcec89eba9f42f6d292
jernej555/adventofcode
/day4/Day4.py
2,641
3.546875
4
# https://adventofcode.com/2020/day/4#part2 import re with open("input.txt") as f: lines = f.read() passports = lines.split("\n\n") def propertyCheck(passportProperties): isValid = True for property in passportProperties: split = property.split(":") if split[0] == "byr": isValid = yearCheck(split[1], 4, 1920, 2002, "byr") if split[0] == "iyr": isValid = yearCheck(split[1], 4, 2010, 2020, "iyr") if split[0] == "eyr": isValid = yearCheck(split[1], 4, 2020, 2030, "eyr") if split[0] == "hgt": isValid = hgtCheck(split[1]) if split[0] == "hcl": isValid = hclCheck(split[1]) if split[0] == "ecl": isValid = eclCheck(split[1]) if split[0] == "pid": isValid = pidCheck(split[1]) if not isValid: return False return isValid def yearCheck(input, digits, minYear, maxYear, typeOfCheck): if (len(input) > digits): print("Invalid year ({}) length: {}".format(typeOfCheck, input)) return False numCheck = int(input) if numCheck < minYear or numCheck > maxYear: print("Invalid year ({}) length: {}".format(typeOfCheck,numCheck)) return False return True def hgtCheck(input): split = re.split('(\d+)', input.strip()) size = int(split[1]) metric = split[2] if metric == "cm": return 150 <= size <= 193 if metric == "in": return 59 <= size <= 76 print("Invalid hgt: {} {}".format(size, metric)) return False def hclCheck(input): pattern = re.compile("^[#][0-9a-f]{6}$") match = pattern.match(input) if not match: print("Invalid hcl: {}".format(input)) return match def eclCheck(input): contains = input in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] if not contains: print("Invalid ecl: {}".format(input)) return contains def pidCheck(input): if len(input) != 9: print("Invalid pid: {}".format(input)) return False return True # CID requiredFieldCount = 0 validPassportCount = 0 requiredFields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] for passport in passports: if all(x in passport for x in requiredFields): requiredFieldCount += 1 passportProperties = passport.split() if propertyCheck(passportProperties): print("Valid passports") validPassportCount += 1 else: print("Invalid passport") print("Required fields count: {}".format(requiredFieldCount)) print("Valid count: {}".format(validPassportCount))
0b70c2280931cf4f88fce27f1a8eb1b119d45928
joelmedeiros/studies.py
/Fase19/Challange91.py
390
3.5625
4
from random import randint from time import sleep from operator import itemgetter dice = {} for i in range(1,5): dice[f'player{i}'] = randint(1, 6) print(f'The player{i} got {dice[f"player{i}"]} in the dice') sleep(0.5) i = 1 ranking = sorted(dice.items(), key=itemgetter(1), reverse=True) for player, value in ranking: print(f'{i} place: {player} with {value}') i += 1
43c2063674be6e5452d27797beca0ad19e98f49c
DanielDJAM/imw
/ut2/a3/program2.py
245
3.65625
4
import sys num = int(sys.argv[1]) sequence=0 if num < 0: sys.exit('Error. Solo admite números positivos') else: for loop1 in range(1, num+1): value1 = loop1 ** 2 sequence = sequence + value1 print(sequence)
7dd2d3ce1269075970f34d3f57041b55ed549232
rbracht/Rock_Physics_python
/LogManipulation/PyExamples/TkButtonPythonExample.py
367
3.75
4
import Tkinter import tkMessageBox top = Tkinter.Tk() def helloCallBack(): tkMessageBox.showinfo( "Hello Python", "Hello World you know not what is to be coming next") B = Tkinter.Button(top, width=7, padx=20, pady=20, bg ="black", activebackground="green", activeforeground="yellow", fg="white", text ="Hello", command = helloCallBack) B.pack() top.mainloop()
fd89810819b26f68793bc1c895b58360b28a23a5
calmcat/Algorithm
/insertion_sort.py
250
3.796875
4
def insertion_sort(A): for j in xrange(1, len(A)): key = A[j] i = j-1 while i >= 0 and A[i] > key: A[i+1] = A[i] i = i-1 A[i+1] = key A = [31, 41, 59, 26, 41, 58] insertion_sort(A) print A
1b3e5d7a9c71f962d40fdb4c769a9885dc409739
jacob-hudson/ProjectEuler
/python/euler.py
304
3.609375
4
#!/usr/bin/env python def soe(n): is_prime = [True]*n is_prime[0] = False is_prime[1] = False for i in xrange(2,int(n**0.5+1)): index = i*2 while index < n: is_prime[index] = False index = index+i prime = [] for i in xrange(n): if is_prime[i] == True: prime.append(i) return prime
4ee4fa4cd5223a913096f8562e8b3dd495908c34
msaf1980/scan
/fill_borders.py
6,203
3.640625
4
#!/usr/bin/python import sys, os from PIL import Image, ImageDraw # Try to clean black borders of scanned image (usually black & white) # !!!! wery alfa state, not tested on color or grayscale images #xborder1 = 80 #yborder1 = 80 #xborder2 = 80 #yborder2 = 80 #threshold = 30 bw_threshold = 80 def rgb_to_grayscale(r, g, b): return (r * 299 + g * 587 + b * 114) // 1000 def fill_xborder_b2w(pix, x1, y1, x2, y2): xdec = 1 if x2 >= x1 else -1 ydec = 1 if y2 >= y1 else -1 changed = False #print("[%d:%d] [%d:%d]" % (x1, y1, x2, y2)) x = x1 try: while x != x2: y = y1 t = 0 while y != y2 and t < threshold: #print("[%d:%d] = %s" % (x, y, str(pix[x, y]))) if img.mode in ("P", "L"): if pix[x, y] == 0: pix[x, y] = 255 changed = True #print("[%d:%d] => %s" % (x, y, str(pix[x, y]))) elif threshold > 0: if (ydec == 1 and y - y1 > threshold) or (ydec == -1 and y2 - y > threshold): t += 1 elif img.mode == "RGBA": (r, g, b, a) = pix[x, y] bw = rgb_to_grayscale(r, b, b) if bw < bw_threshold: pix[x, y] = (255, 255, 255, a) changed = True #print("[%d:%d] => %s" % (x, y, str(pix[x, y]))) elif threshold > 0: if (ydec == 1 and y - y1 > threshold) or (ydec == -1 and y2 - y > threshold): t += 1 else: bw = rgb_to_grayscale(r, b, b) if bw < bw_threshold: pix[x, y] = (255, 255, 255) changed = True #print("[%d:%d] => %s" % (x, y, str(pix[x, y]))) elif threshold > 0: if (ydec == 1 and y - y1 > threshold) or (ydec == -1 and y2 - y > threshold): t += 1 y += ydec x += xdec #print("") except: print("[%d:%d] start [%d:%d] end [%d:%d]" % (x, y, x1, y1, x2, y2)) raise def fill_yborder_b2w(pix, x1, y1, x2, y2): xdec = 1 if x2 >= x1 else -1 ydec = 1 if y2 >= y1 else -1 changed = False #print("[%d:%d] [%d:%d]" % (x1, y1, x2, y2)) y = y1 try: while y != y2: x = x1 t = 0 while x != x2 and t < threshold: #print("[%d:%d] = %s" % (x, y, str(pix[x, y]))) if img.mode in ("P", "L"): if pix[x, y] == 0: pix[x, y] = 255 changed = True #print("[%d:%d] => %s" % (x, y, str(pix[x, y]))) elif (xdec == 1 and x - x1 > threshold) or (xdec == -1 and x2 - x > threshold): t += 1 elif img.mode == "RGBA": (r, g, b, a) = pix[x, y] bw = rgb_to_grayscale(r, b, b) if bw < bw_threshold: pix[x, y] = (255, 255, 255, a) changed = True #print("[%d:%d] => %s" % (x, y, str(pix[x, y]))) elif (xdec == 1 and x - x1 > threshold) or (xdec == -1 and x2 - x > threshold): t += 1 else: bw = rgb_to_grayscale(r, b, b) if bw < bw_threshold: pix[x, y] = (255, 255, 255) changed = True #print("[%d:%d] => %s" % (x, y, str(pix[x, y]))) elif (xdec == 1 and x - x1 > threshold) or (xdec == -1 and x2 - x > threshold): t += 1 x += xdec y += ydec #print("") except: print("[%d:%d] start [%d:%d] end [%d:%d]" % (x, y, x1, y1, x2, y2)) raise if not len(sys.argv) in (6, 7): sys.stderr.write("use: %s image xborder1 yborder1 xborder2 yborder2 threshold\n") sys.exit(1) filename = sys.argv[1] xborder1 = int(sys.argv[2]) yborder1 = int(sys.argv[3]) xborder2 = int(sys.argv[4]) yborder2 = int(sys.argv[5]) img = Image.open(filename) (width, height) = img.size if len(sys.argv) == 7: threshold = int(sys.argv[6]) pix = img.load() changed = fill_yborder_b2w(pix, 0, 0, xborder1, height) if fill_yborder_b2w(pix, width - 1, 0, width - xborder2, height): changes = True if fill_xborder_b2w(pix, xborder1 + 1, 0, width - xborder2, xborder1): changes = True if fill_xborder_b2w(pix, width - xborder2, height - 1, xborder1, height - yborder2): changes = True else: changed = True if img.mode in ("P", "L"): bgcolor = 255 elif img.mode == "RGBA": bgcolor = (255, 255, 255, 255) elif img.mode == "RGB": bgcolor = (255, 255, 255) draw = ImageDraw.Draw(img) #print("[%d:%d] [%d:%d]" % (0, 0, xborder1, height)) draw.rectangle((0, 0, xborder1, height), fill=bgcolor) #print("[%d:%d] [%d:%d]" % (width - 1, 0, width - xborder2, height)) draw.rectangle((width - 1, 0, width - xborder2, height), fill=bgcolor) #print("[%d:%d] [%d:%d]" % (xborder1 + 1, 0, width - xborder2, yborder1)) draw.rectangle((xborder1 + 1, 0, width - xborder2, yborder1), fill=bgcolor) #print("[%d:%d] [%d:%d]" % (width - xborder2, height - 1, xborder1, height - yborder2)) draw.rectangle((width - xborder2, height - 1, xborder1, height - yborder2), fill=bgcolor) if changed: filename_back = filename + ".back" if os.path.isfile(filename_back): os.remove(filename_back) os.rename(filename, filename_back) img.save(filename) #filename_back = "_" + filename #img.save(filename_back)
e329fd14e69ce7bb5fdc63c235a32bc589f33e85
PemLer/Journey_of_Algorithm
/leetcode/501-600/T572_isSubtree.py
690
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: if not s or not t: return False def is_same(a, b): if not a and not b: return True elif not a or not b or a.val != b.val: return False return is_same(a.left, b.left) and is_same(a.right, b.right) if s.val == t.val and is_same(s, t): return True else: return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
ac2b0a090d1e08ec129053ee92db8a912c9a35be
dbsgh9932/TIL
/variable/01_variable.py
528
3.609375
4
# 변수의 값을 저장 # 변수=값 result = 10 print(result) # 화면에 변수값을 출력하는 명령어 result = 'a' print(result) # 여러개의 변수에 여러개의 값을 한번에 저장 가능 # 변수1, 변수2, 변수3,...=값1, 값2, 값3 # 파이썬 코드는 맨 앞칸에서 시작 (공백x) a,b,c,d=1,2,3,4 print(a) print(b) print(c) print(d) # 변수이름 = 실제값이나 값이 들어있는 식별자도 가능 e,f,g=a,b,c a,b=10,20 #a,b 값은? 10 20 print(a) a,b=b,a #a,b 값은? 20 10 print(a)
ec505ce2f31ceb36096d4f9aa91a094b26640d9c
rcanepa/cs-fundamentals
/python/interview_questions/odd_man_out.py
1,041
4.1875
4
"""Given an unsorted array of integers where every integer appears exactly twice, except for one integer which appears only once. Implement an algorithm that finds the integer that appears only once.""" def find_odd_integer(integers): """The time complexity of this algorithm is O(N), where N is the number of integers in `integers`.""" odds = set() for i in integers: # O(N) if i in odds: odds.remove(i) # O(1) else: odds.add(i) # O(1) return odds.pop() if len(odds) else None if __name__ == "__main__": test_cases = [ ([1, 2, 3, 2, 1], 3), ([1, 2, 1], 2), (list(range(100)) + [200] + list(range(100)), 200), # The next are edge cases, maybe they aren't even valid. ([], None), ([1], 1), ([1, 1], None), ] for array, expected in test_cases: print("Running test on integers", array) result = find_odd_integer(array) print("-> Result", result) assert result == expected
5e3a18d135dd8c68f2eb310c0a81bfffd2f8ed74
mentecatoDev/python
/UMDC/03/08b.py
703
3.984375
4
""" Ejercicio 08b Potencias de 2 b) Escribir una función que, dados dos números naturales pasados como parámetros, devuelva la suma de todas las potencias de 2 que hay en el rango formado por esos números (0 si no hay ninguna potencia de 2 entre los dos). Utilizar la función es_potencia_de_dos, descrita en el punto anterior. """ def es_potencia_de_dos(n): while n != 1: if (n % 2) == 0: n = n / 2 else: return False return True def suma_potencias_de_2(a, b): suma = 0 for n in range(a, b+1): if es_potencia_de_dos(n): suma += n return suma print(suma_potencias_de_2(6, 15)) print(suma_potencias_de_2(17, 30))
fe2f7b6cc0272571d36c2209459aa68de19a6026
dagar/project_euler
/problem_37.py
804
4
4
#! /usr/bin/env python from common import isprime def truncate_left(number): N = str(number) return int(N[1:]) def truncate_right(number): N = str(number) return int(N[:-1]) def truncatable_prime(n, truncate_fn): N = str(n) original_n = N while True: if isprime(int(N)): if len(N) == 1: return True else: N = str(truncate_fn(N)) else: return False prime_list = [] for n in xrange(10, 1000000): if truncatable_prime(n, truncate_left): prime_list.append(n) # final sum of primes sum = 0 for n in prime_list: if truncatable_prime(n, truncate_right): sum += n print n, "is a truncatable prime (left and right)" print "sum of all truncatable primes is", sum
9ee97d097427800e0fde72a9500793d970b1e67e
Mark-Gustincic/Bioinformatics-in-Python
/Research Programming/Basic DNA-Protein Statistics/Protein Coordinates.py
5,531
3.984375
4
#!/usr/bin/env python3 # Name: Mark Gustincic # Group Members: Thomas Richards (tarichar) import math class ProteinCoordinates : """ Author: David Bernick Date: March 21, 2013 This class calculates angles and distances among a triad of points. Points can be supplied in any dimensional space as long as they are consistent. Points are supplied as tupels in n-dimensions, and there should be three of those to make the triad. Each point is positionally named as p,q,r and the corresponding angles are then angleP, angleQ and angleR. Distances are given by dPQ(), dPR() and dQR() Required Modules: math initialized: 3 positional tuples representing Points in n-space p1 = Triad( p=(1,0,0), q=(0,0,0), r=(0,1,0) ) attributes: p,q,r the 3 tuples representing points in N-space methods: angleP(), angleR(), angleQ() angles measured in radians dPQ(), dPR(), dQR() distances in the same units of p,q,r """ def __init__(self,p,q,r) : """ Construct a Triad. p1 = Triad( p=(1,0,0), q=(0,0,0), r=(0,0,0) ). """ self.p = p self.q = q self.r = r # private helper methods def d2 (self,a,b) : # calculate squared distance of point a to b return float(sum((ia-ib)*(ia-ib) for ia,ib in zip (a,b))) def dot (self,a,b) : # dotProd of standard vectors a,b return float(sum(ia*ib for ia,ib in zip(a,b))) def ndot (self,a,b,c) : # dotProd of vec. a,c standardized to b return float(sum((ia-ib)*(ic-ib) for ia,ib,ic in zip (a,b,c))) # calculate lengths(distances) of segments PQ, PR and QR def dPQ (self): """ Provides the distance between point p and point q """ return math.sqrt(self.d2(self.p,self.q)) def dPR (self): """ Provides the distance between point p and point r """ return math.sqrt(self.d2(self.p,self.r)) def dQR (self): """ Provides the distance between point q and point r """ return math.sqrt(self.d2(self.q,self.r)) def angleP (self) : """ Provides the angle made at point p by segments pq and pr (radians). """ return math.acos(self.ndot(self.q,self.p,self.r) / math.sqrt(self.d2(self.q,self.p)*self.d2(self.r,self.p))) def angleQ (self) : """ Provides the angle made at point q by segments qp and qr (radians). """ return math.acos(self.ndot(self.p,self.q,self.r) / math.sqrt(self.d2(self.p,self.q)*self.d2(self.r,self.q))) def angleR (self) : """ Provides the angle made at point r by segments rp and rq (radians). """ return math.acos(self.ndot(self.p,self.r,self.q) / math.sqrt(self.d2(self.p,self.r)*self.d2(self.q,self.r))) def main(): """ Prompts the user to enter three coordinates, and splits the inputted string at each ")" symbol. Assigns value to string in coords1[0] one position after the "(" symbol. This string is split again after each "," symbol, resulting in a list of three float values Cx, Cy, Cz. Object name Carbon is assigned to Cx, Cy, and Cz. """ coordsX = input("Please enter three atomic coordinates: ") coords1 = coordsX.split(")") """ Assigns value to string in coords1[0] one position after the "(" symbol. This string is split again after each "," symbol, resulting in a list of three float values Cx, Cy, Cz. Object name Carbon is assigned to Cx, Cy, and Cz. """ start = coords1[0].find('(')+1 C = coords1[0][start:] CNew = C.split(",") Cx = float(CNew[0]) Cy = float(CNew[1]) Cz = float(CNew[2]) Carbon = (Cx,Cy,Cz) """ Assigns value to string in coords1[1] one position after the "(" symbol. This string is split again after each "," symbol, resulting in a list of three float values Nx, Ny, Nz. Object name Nitrogen is assigned to Nx, Ny, and Nz. """ start = coords1[1].find('(')+1 N = coords1[1][start:] NNew = N.split(",") Nx = float(NNew[0]) Ny = float(NNew[1]) Nz = float(NNew[2]) Nitrogen = (Nx,Ny,Nz) """ Assigns value to string in coords1[2] one position after the "(" symbol. This string is split again after each "," symbol, resulting in a list of three float values Cax, Cay, Caz. Object name Carbon is assigned to Cax, Cay, and Caz. """ start = coords1[2].find('(')+1 Ca = coords1[2][start:] CaNew = Ca.split(",") Cax = float(CaNew[0]) Cay = float(CaNew[1]) Caz = float(CaNew[2]) Calcium = (Cax,Cay,Caz) """ Instantiates name1 as instance of ProteinCoordinates with arguments Carbon, Nitrogen, and Calcium. Names are assigned to methods used with name1, and these names are formatted/printed to output. Main method is called. """ name1 = ProteinCoordinates(Carbon, Nitrogen, Calcium) C_N = name1.dPQ() N_Ca = name1.dQR() C_N_Ca = (name1.angleQ()*180)/math.pi print("N-C bond length = %0.2f" % C_N) print("N-Ca bond length = %0.2f" % N_Ca) print("C-N-Ca bond angle = %0.1f" % C_N_Ca) ProteinCoordinates.main()
51bf182f27477df8771a14d5eb199bfd2392a772
getabear/leetcode
/合并K个排序链表.py
3,037
3.84375
4
from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution1: def mergeKLists(self, lists: List[ListNode]) -> ListNode: def merge(list1,list2): #功能,和并两个排序链表 ret=ListNode(None) res=ret #返回值 temp=ret while(list1!=None and list2!=None): if(list1.val<list2.val): ret.val=list1.val list1=list1.next else: ret.val=list2.val list2=list2.next ret.next = ListNode(0) temp=ret ret = ret.next while(list1!=None): ret.val = list1.val list1 = list1.next ret.next = ListNode(0) temp=ret ret = ret.next while (list2 != None): ret.val = list2.val list2=list2.next ret.next = ListNode(0) temp=ret ret = ret.next if temp==res and temp.val==None: return None temp.next=None return res def divide(lists): length=len(lists) if(length==0): return None if(length==1): return merge(lists[0],None) else: temp=merge(lists[0],lists[1]) return merge(temp,divide(lists[2:])) return divide(lists) #暂时是对的,只是超时了 class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: def merge(Node1,Node2): Node=ListNode(-1) res=Node while Node1 and Node2: if Node1.val<=Node2.val: Node.next=ListNode(Node1.val) Node1=Node1.next else: Node.next = ListNode(Node2.val) Node2 = Node2.next Node=Node.next while Node1: Node.next=ListNode(Node1.val) Node1=Node1.next Node = Node.next while Node2: Node.next=ListNode(Node2.val) Node2=Node2.next Node = Node.next return res.next def divide(lists): length=len(lists) if length==1: return lists[0] # if length==2: # return merge(lists[0],lists[1]) left=divide(lists[:length//2]) right=divide(lists[length//2:]) return merge(left,right) if len(lists) == 0: return [] return divide(lists) def creat(nums): #构造一个链表的函数 ret=ListNode(-1) res=ret for i in nums: ret.next=ListNode(i) ret=ret.next return res.next node1=creat([1,4,5]) node2=creat([1,3,4]) lists=[node1,node2] a=Solution() print(a.mergeKLists(lists))
84d3cf93690246057b1ed6e70e6a4cbf53d0f184
berkkurt/PythonTryouts
/deneme.py
285
3.640625
4
print("bu bir denemedir") def berk(): pass num1 = 10 def toplama(num1, num2): num1 = 1 return num1 + num2 def çıkarma(num1, num2): pass berk() print(toplama(2, 3)) for x in range(100, -1): if x == 80: continue print(x) def rrr(): pass
fb8502d74927d8fa67cf756cc0f682c5a83fe506
dkippes/Python-Practicas
/Introduccion a Python/condicionales-encadenados.py
342
3.953125
4
x=1 y=2 #Encadenando if x < y: print(x, "es menor que", y) elif x > y: print(x, "es mayor que", y) else: print(x, "es igual a", y) #Anidando -> dificultan la lectura del programa if x == y: print(x, "es igual a", y) else: if x < y: print(x, "es menor que", y) else: print(x, "es mayor que", y)
083f063bcb96b2af4e43b4e3c88c3e6abaf355ca
jrbella/python_open_work
/more_functions.py
1,168
3.625
4
#imports #basic function for area def area(a, b): return a * b print(area(4,5)) #explicit function argument def area_2(a,b): try: if(isinstance(a, (int, float)) and isinstance(b, (int, float))): return a * b else: return (float(a) * float(b)) except ValueError: return "The first parameter: [%s] or the second parameter [%s] were not valid arguments please enter either a float or an int" % (a, b) #quick test print(area_2(4,5)) #should be 20 print(area_2(4.1, 5.1)) #should be 20.909... print(area_2("4.1", "5.1")) #shoudl be 20.909.. print(area_2("this should fail", "this should fail")) #should throw #indefinate paramters def average_basic(*args): return (sum(args)/len(args)) #quick test print(average_basic(1,2,3,4,5,6,7)) #sorting strings alphabetically def alphabetize_list(*args): #converting the tuple to a list for processing args = [i.upper() for i in args] return sorted(args) #quick test print(alphabetize_list("twinkle","twinkle","little", "star")) #kwargs (key word arguments) def mean(**kwargs): return kwargs #quick test print(mean(a=1, b=2, c=3))
c05ea0a19880e8f0d13529cd0ed08036adbde963
Luke-Kelly/CodeCraft2018Python
/something.py
265
3.796875
4
print("What year were you born?") born = raw_input() born = int(born) print("What year would you like to see your age?") year = raw_input() year = int(year) ageIn2050 = year - born print("In " + str(year) + " you will be " + str(ageIn2050) + " years old!")
87ffa0d2edf57a63d057cda63627ecaff0edcab7
alexcatmu/CFGS_DAM
/PRIMERO/python/ejercicio43 listasF.py
316
3.921875
4
''' hasta que no F seguir con - \ | / ''' #programa F #variables array = ["-","\ ","|","/"] valor = "" cont = 0 #codigo while (valor != "F"): print (array[cont]) #array_final.append(array[cont]) cont = cont + 1 if (cont > 3): cont = 0 valor = input() #print (array_final)
5425c442348c9a7d14f5a6e95ca61f051f6e15dc
victorrenop/algorithm-analysis-final-assignment
/algorithm_analysis_final_assignment/data_structures/tree/tree.py
765
3.59375
4
from abc import ABCMeta, abstractmethod class Tree(metaclass=ABCMeta): @abstractmethod def insert(self, key: object, val: int, current_root: object = None) -> None: pass @abstractmethod def search_key(self, key: object) -> object: pass @abstractmethod def search_val(self, val: int) -> object: pass @abstractmethod def get_height(self, current_root: object) -> int: pass @abstractmethod def traverse_in_order(self, current_root: object) -> None: pass @abstractmethod def traverse_pre_order(self, current_root: object) -> None: pass @abstractmethod def traverse_post_order(self, current_root: object) -> None: pass
44ffe20f4909d58a2c218ee53be667e4d723fdbd
iyuandeng/LearningPython
/pycharmprojects/zodiac.py
705
3.578125
4
# # 根据出生日期判断星座 # zodiac_name = (u'摩羯座',u'水瓶座',u'双鱼座',u'白羊座',u'金牛座',u'双子座', # u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座') # zodiac_days = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22), # (7,23),(8,23),(9,23),(10,23),(11,23),(12,23)) # (month,day) = (12,6) # zodiac_day = list(filter(lambda x: x<=(month,day),zodiac_days)) # print(zodiac_day) # zodiac_len = list(zodiac_day) # print(list(zodiac_day)) # zodiac_len = len(list(zodiac_day))%12 # print(zodiac_name[zodiac_len]) a_list = ['456','abc','xyz'] a_list.append('D') # 添加大写字母D print(a_list) a_list.remove('456') print(a_list)
95b3b3f152090b50133ca63c6e63f6c573357d10
dcandrade/machine-learning-a-z
/1 - Data Preprocessing/data-preprocessing_template.py
567
3.625
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing datasets dataset = pd.read_csv("Data.csv") X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 3].values #Splitting in training and testing sets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) #Feature Scaling #from sklearn.preprocessing import StandardScaler #sc_X = StandardScaler() #X_train = sc_X.fit_transform(X_train) #X_test = sc_X.transform(X_test) #already fitted on training set
e1d41cf9634505b2757fdc26d30923b568b9812e
orazioc17/python-avanzado
/generators.py
602
3.671875
4
from time import sleep def fibonacci_generator(max=None): n1 = 0 n2 = 1 counter = 0 max = max while True: if max: if n1 + n2 > max: break if counter == 0: counter += 1 yield n1 elif counter == 1: counter += 1 yield n2 else: aux = n1 + n2 n1, n2 = n2, aux counter += 1 yield aux if __name__ == '__main__': fibonacci = fibonacci_generator(1000) for element in fibonacci: print(element) sleep(0.4)
135c820971838480e4137c76242f98209c8237c0
vishsanghishetty/LC-Python
/medium/Generate Parentheses/solution.py
715
3.671875
4
# Time complexity: O(2^(2n)) # Approach: Simple recursion solves the problem. We need to make sure that whenever we want to insert closing bracket, then number opening brackets must be less than number of closing brackets. class Solution: def stringGenerator(self, i, j, rem, ans): if i == 0 and j == 0: ans.append(rem) return if i != 0: self.stringGenerator(i-1, j, rem + "(", ans) if j != 0 and i<j: self.stringGenerator(i, j-1, rem + ")", ans) def generateParenthesis(self, n: int) -> List[str]: ans = [] if n == 0: return ans self.stringGenerator(n, n, "", ans) return ans
4484e6c9cdeda15a3d9772b8acbd77444a6d7ed9
esouzasp/1-data_science_foundations_I
/data_science_mod002_class002_lesson041 (using dictionary).py
371
4
4
elements = {'hydrogen': 1, 'helium': 2, 'carbon': 6} print elements print elements['hydrogen'] print elements['carbon'] #print elements['lithium'] #keyError print 'lithium' in elements elements['lithium'] = 3 #add new+value elements['nitrogen'] = 8 #add new+value print elements elements['nitrogen'] = 7 print elements print elements['nitrogen']
ca1e87d5dc6740aa5ede54542318f1d20249ff69
antoniojkim/AlgLib
/Algorithms/Greedy/Odd One Out/odd_one_out.py
401
4.03125
4
# -*- coding: utf-8 -*- from typing import List def odd_one_out(A: List[int]) -> int: """ Given a list of integers where every single element repeats an even number of times except for one element who repeats an odd number of times. The following algorithm finds the element that repeats an odd number of times. """ n = 0 for a in A: n ^= a return n
32176c8cddaf92810ecf01472065f2dc7528a1c2
tcooi/solutions
/kattis/hissingmicrophone.py
265
3.671875
4
from sys import stdin input = list(stdin.readline().rstrip('\n')) hiss = False for x in range(0, len(input)-1): if input[x] == "s" and input[x+1] == "s": hiss = True break if hiss: print("hiss") else: print("no hiss")
12b49d9d3ce4a8bb9867f9c169ebe7673fee5740
JeffFirmin/Projects
/Théorie des jeux/joueur.py
575
3.734375
4
class Joueur: def yes(self): return False def lancer_pierre(self): # La fonction pour le lancer de pierre print("nombre de pierres restantes", chateau.pierre) chateau.nb_pierre_envoyee = int( input("Nombre de pierre à envoyer ?")) # Si on entre plus de pierres qu'on en a on refait while chateau.nb_pierre_envoyee > chateau.pierre or chateau.nb_pierre_envoyee < 1: chateau.nb_pierre_envoyee = int(input("Nombre de pierre à envoyer ?")) chateau.pierre = chateau.pierre - chateau.nb_pierre_envoyee
ad70e7504cf2b84171c34db5703588844d7032cf
rayankikavitha/InterviewPrep
/leetcode/560_Subarray_Sum_Equals_K.py
1,975
3.8125
4
""" Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 https://leetcode.com/problems/subarray-sum-equals-k/solution/ The idea behind this approach is if you are caluclating the cumulative sum of an array and at sum[i] and sum[j] , the cumulative sum is same, that means the values lying in between i and j add up to zero. If we extend the same logic to K, if the cumulative sum difference of s[i] - s[j] = k, then the values in between i, j add up to k. """ def subarraySum(nums, k): """ using constant o(n) :type nums: List[int] :type k: int :rtype: int """ d = {0:1} # prefix sum array, so starting position also falls in the logic res = s = 0 for n in nums: s = s + n # increment current sum res = res+ d.get(s - k, 0) # check if there is a prefix subarray we can take out to reach k d[s] = d.get(s, 0) + 1 # add current sum to sum count print d, res, s return res def subarray2(nums,k): """ o(n2) brute force :param nums: :param k: :return: """ count = 0 for i in range(len(nums)): s = 0 for j in range(i,len(nums)): s += nums[j] if s == k: count += 1 return count def subarraySum3(nums, k): """ using constant o(n) :type nums: List[int] :type k: int :rtype: int """ d = {nums[0]:1} # prefix sum array, so starting position also falls in the logic res = s = 0 for n in nums[1:]: s = s + n # increment current sum res = res+ d.get(s - k, 0) # check if there is a prefix subarray we can take out to reach k d[s] = d.get(s, 0) + 1 # add current sum to sum count print d, res, s return res input = [3,4,7,2,-3,1,4,2] print subarraySum(input,7) print '*************' print subarraySum3(input,7)
c6161cd5bab4cff004f3bdb9477bfd396a07de06
Springo/AdventOfCode2018
/d13.py
5,703
3.515625
4
def readFile(filename): lines = [] with open(filename, 'r') as f: for line in f: lines.append(line[:-1]) return lines lines = readFile("d13input.txt") #lines = readFile("test.txt") grid = [] c_list = [] locs = dict() for y in range(len(lines)): line = lines[y] g_line = [] for x in range(len(line)): c = line[x] if c == '>': g_line.append('-') c_list.append([y, x, 0, 0]) locs[(y, x)] = 1 elif c == '<': g_line.append('-') c_list.append([y, x, 2, 0]) locs[(y, x)] = 1 elif c == 'v': g_line.append('|') c_list.append([y, x, 1, 0]) locs[(y, x)] = 1 elif c == '^': g_line.append('|') c_list.append([y, x, 3, 0]) locs[(y, x)] = 1 else: g_line.append(c) grid.append(g_line) done = False while not done: c_list = sorted(c_list, key=lambda a: a[1]) c_list = sorted(c_list, key=lambda a: a[0]) i = 0 while i < len(c_list): if i < 0: print("NOOOOOO") pair = c_list[i] y = pair[0] x = pair[1] dir = pair[2] turn = pair[3] locs[(y, x)] = 0 if dir == 0: x = x + 1 if (y, x) in locs and locs[(y, x)] == 1: print("COLLISION") print("{},{}".format(x, y)) print(c_list) print(c_list.pop(i)) for j in range(len(c_list)): newy = c_list[j][0] newx = c_list[j][1] if newy == y and newx == x: print(c_list.pop(j)) if j < i: i -= 1 break print(c_list) locs[(y, x)] = 0 continue if grid[y][x] == '/': dir = 3 elif grid[y][x] == '\\': dir = 1 elif grid[y][x] == '+': if turn == 0: dir = 3 turn = 1 elif turn == 1: turn = 2 elif turn == 2: dir = 1 turn = 0 elif dir == 1: y = y + 1 if (y, x) in locs and locs[(y, x)] == 1: print("COLLISION") print("{},{}".format(x, y)) print(c_list) print(c_list.pop(i)) for j in range(len(c_list)): newy = c_list[j][0] newx = c_list[j][1] if newy == y and newx == x: print(c_list.pop(j)) if j < i: i -= 1 break locs[(y, x)] = 0 print(c_list) continue if grid[y][x] == '/': dir = 2 elif grid[y][x] == '\\': dir = 0 elif grid[y][x] == '+': if turn == 0: dir = 0 turn = 1 elif turn == 1: turn = 2 elif turn == 2: dir = 2 turn = 0 elif dir == 2: x = x - 1 if (y, x) in locs and locs[(y, x)] == 1: print("COLLISION") print("{},{}".format(x, y)) print(c_list) print(c_list.pop(i)) for j in range(len(c_list)): newy = c_list[j][0] newx = c_list[j][1] if newy == y and newx == x: print(c_list.pop(j)) if j < i: i -= 1 break locs[(y, x)] = 0 print(c_list) continue if grid[y][x] == '/': dir = 1 elif grid[y][x] == '\\': dir = 3 elif grid[y][x] == '+': if turn == 0: dir = 1 turn = 1 elif turn == 1: turn = 2 elif turn == 2: dir = 3 turn = 0 elif dir == 3: y = y - 1 if (y, x) in locs and locs[(y, x)] == 1: print("COLLISION") print("{},{}".format(x, y)) print(c_list) print(c_list.pop(i)) for j in range(len(c_list)): newy = c_list[j][0] newx = c_list[j][1] if newy == y and newx == x: print(c_list.pop(j)) if j < i: i -= 1 break locs[(y, x)] = 0 print(c_list) continue if grid[y][x] == '/': dir = 0 elif grid[y][x] == '\\': dir = 2 elif grid[y][x] == '+': if turn == 0: dir = 2 turn = 1 elif turn == 1: turn = 2 elif turn == 2: dir = 0 turn = 0 else: print("AAAAAA") locs[(y, x)] = 1 new_pair = [y, x, dir, turn] c_list[i] = new_pair i += 1 if len(c_list) < 2: print("FINAL:") print("{},{}".format(c_list[0][1], c_list[0][0])) done = True
1be0bc2dc5cd95f50e32a632ea5dfdb0b910d665
shinhn/python_web_basic
/python_basic/8_exception_hadling.py
2,168
3.578125
4
# 예외 종류 # linter : 코드 스타일, 문법 체크 # syntaxError : 잘못된 문법 # ZeroDivisionError : 0 나누기 에러 # IndexError : 인덱스 범위 오버 # keyError : 주로 딕셔너리에서 발생 # AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용시에 예외 # ValuError : 참조 값이 없을 때 발생 # FileNotFoundError : 파일이 현재 경로에 없을 때 발생 # TypeError # 예외 처리 # try : 에러가 발생할 가능성이 있는 코드 실행 # except : 에러명1 # except : 에러명2 # else : 에러가 발생하지 않았을 경우 실행 # finally : 항상 실행 name = ['Kim', 'Lee', 'Park'] # list에 있는 경우 try: z = 'Lee' x = name.index(z) print('{} found it! in name'.format(z, x+1)) except: print('Not found it! - Occured Error!') else: print('예외 없을 경우') finally: print('무조건 실행') print() # list에 없는 경우 try: z = 'Kang' x = name.index(z) print('{} found it! in name'.format(z, x+1)) except: print('Not found it! - Occured Error!') else: print('예외 없을 경우') finally: print('무조건 실행') print() # 예외 처리는 하지 않지만, 무조건 수행하는 코딩 패턴 try: print('작업') finally: print('작업 후 무조건 실행') # 다양한 예외 처리 # except 문이 순차적으로 수행되기 때문에 전체 예외를 처리하는 Exception을 마지막에 둬야 함 try: z = 'Lee' x = name.index(z) print('{} found it! in name'.format(z, x+1)) except ValueError: print('Not found it! - Occured ValueError!') except IndexError: print('Not found it! - Occured IndexError!') except Exception: print('Not found it! - Occured EveryError!') else: print('예외 없을 경우') finally: print('무조건 실행') print() # 예외 발생 # raise # 일부러 예외를 발생시켜 특정 상황에 관리자가 로그 기록을 알아야 하는 경우 등에 활용 가능 try: a = 'Kim' if a == 'Kim': print('ok!') else: raise ValueError except ValueError: print('문제 발생') else: print('ok!')
5d08a71776a0c76be59401da041e5e55111f3cca
huyndo/Learning-python
/Chapter 2/area_rectangle.py
157
4.15625
4
height = int(input("Please input rectangle height ")) width = int(input("Please input rectangle width ")) area = height * width print("The area is: ", area)
cf2422b5dd44196d3ef280cce4967cd8cbd0cc0a
boknowswiki/mytraning
/lintcode/python/0541_zigzag_iterator_II.py
761
3.640625
4
#!/usr/bin/python -t class ZigzagIterator2: """ @param: vecs: a list of 1d vectors """ def __init__(self, vecs): # do intialization if necessary self.q = [v for v in vecs if v] """ @return: An integer """ def next(self): # write your code here v = self.q.pop(0) val = v.pop(0) if v: self.q.append(v) return val """ @return: True if has next """ def hasNext(self): # write your code here return len(self.q) > 0 # Your ZigzagIterator2 object will be instantiated and called as such: # solution, result = ZigzagIterator2(vecs), [] # while solution.hasNext(): result.append(solution.next()) # Output result
e7ce55fb26707864d310ca2d792e8260ab2d8075
gabrielwai/Exercicios-em-Python
/ex076.py
563
3.546875
4
listagem = ('Pão', 3.50, 'Leite', 4, 'Lápis', 1.75, 'Borraha', 2, 'Caderno', 15.9, 'Estojo', 25, 'Transferidor', 4.2, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.3, 'Livro', 34.9) print('-'*40) print(f'{"LISTAGEM DE PREÇOS":^40}') #print('{:^40}'.format('LISTAGEM DE PREÇOS')) # <<< Também funciona assim print('-'*40) for count in range(0, len(listagem)): if count % 2 == 0: print(f'{listagem[count]:.<30}', end='') else: print(f'R${listagem[count]:>7.2f}') print('-'*40)
34ae2d65c7eb8f1f79156edb4487da0911be7642
cudjoeab/Object-Oriented_Programming-3
/02-Inheritance_Pt1/people.py
678
4.125
4
class Person: def __init__(self, name): self.name = name def __str__(self): return f'Hi, my name is {self.name}!' class Instructor(Person): def teach(self): return f'An object is an instance of a class.' class Student(Person): def learn(self): return f'I get it!' nadia = Instructor('Nadia') chris = Student('Chris') print(chris) print(nadia) print(nadia.teach()) print(chris.learn()) print(chris.teach()) """ Comment on calling the teach method on student instance: We cannot call the teach instance method on chris because chris is an instance of Student, which does not have a teach instance method. """
92b1bcd1c245d9108ddfd26364888037437bf476
smorenburg/python
/src/old/variations.py
388
3.75
4
#!/usr/bin/env python3 message = input('Enter a message: ') print('Lowercase:', message.lower()) print('Uppercase:', message.upper()) print('Capitalized:', message.capitalize()) print('Title', message.title()) words = message.split() print('Words:', words) sorted_words = sorted(words) print('Alphabetic first word:', sorted_words[0]) print('Alphabetic last word:', sorted_words[-1])
27a906a0b15d03dc8073017fa5ee3f37442dce54
vidaljose/pruebasPython
/modulos/funciones_matematicas.py
285
3.765625
4
"""Este modulo permite realizar opeaciones matematicas""" def sumar(op1,op2): print("El resultado de la suma es ",op1 + op2) def restar(op1,op2): print("El resultado de la suma es ",op1 - op2) def multiplicar(op1,op2): print("El resultado de la suma es ",op1 * op2)
790d3ad9bf9414a2619558dd78fe7190d507e3bd
NikitaFir/Leetcode
/Contains Duplicate II.py
611
3.5
4
class Solution(object): def containsNearbyDuplicate(self, nums, k): elems = {} for i in range(0, len(nums)): if nums[i] in elems: value = elems[nums[i]] if i - value <= k: return True else: elems[nums[i]] = i else: elems.update({nums[i]: i}) return False print(Solution.containsNearbyDuplicate(0,[1,2,3,1], 3)) print(Solution.containsNearbyDuplicate(0,[1,0,1,1], 1)) print(Solution.containsNearbyDuplicate(0,[1,2,3,1,2,3], 2))
d43e8cc4a9d05faf1cd602688dd109700a72cd46
mashilu/hello-python
/pytest/file_test/file_reader.py
286
3.625
4
# -*- coding: utf-8 -*- if __name__ == '__main__': with open('text_files/pi_digits.txt') as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip().lstrip() print(pi_string) print(len(pi_string))
7d1ea0afc67ddc00ffd27ad923d48677eaf42b00
stevenfisher22/python-exercises
/Homework 16 Nov 2018/16-nov-2018.py
1,401
3.734375
4
#// DICTIONARIES # myContactList = { # 'dog' : 'Savannah', # 'wife' : 'Amanda', # 'me' : 'Steven', # 12 : 'Whatever' ## This segment throws an error: # 'friends' : { # 'first_name' : 'Brent' # 'last_name' : 'Hibbard' # } # } # dog = myContactList['dog'] # print(dog) #// GET # dog2 = myContactList.get("dog") # print(dog2) #// IN # dog3 = 'dog' in myContactList # print(dog3) #// IN IF STATEMENTS # if ('dog' in myContactList): # print("Yay, you have a dog!") # if ('wife' in myContactList): # print("Your wife,", myContactList['wife'],", is hot!") #// SETTING VALUES # myContactList['wife'] = 'Amanda2' # print(myContactList['wife']) #// KEYS AND VALUES #// *** DOESN'T WORK # print(myContactList.key()) # print(myContactList.values()) #// DELETE ITEMS # del myContactList[12] # print(myContactList) # print(myContactList.keys()) # print(myContactList.values()) #// ITERATING # for key, value in myContactList.items(): # print(key) # print('value: ',value) # print('{key}: {value}'.format(key=key, value=value)) #// NESTING # contact = [ # {'name':'Steven', # 'age': 33, # 'phone': { # 'home': "", # 'cell': "918.555.5555" # } # } # ] # THIS IS A LIST, CONTACT[0] IS THE FIRST DICTIONARY IN THE LIST. # print(contact[0]['age']) # print(contact[0]['phone']['cell'])
139b588593bfe7f95dbfb91c090cf8f8c3441812
Utukoori/Innomatics_Internship
/Day_5/Regex_substitution.py
190
3.890625
4
import re for line in range(int(input())): string = '' string = re.sub(r'(?<= )&&(?= )','and',input()) string = re.sub(r'(?<= )\|\|(?= )','or',string) print (string)
fcd49db4681f68160c2a7b8380208f62a58c026c
vpunugupati/CodingPuzzles
/LeetCode/LongestSubString.py
376
3.765625
4
def LongestSubString(s): print(s) ar = [] maxlength = 0 for ch in s: if (ch in ar): ar = ar[ar.index(ch)+1:] ar.append(ch) if(len(ar) > maxlength): maxlength = len(ar) return maxlength if maxlength > len(ar) else len(ar) if __name__ == "__main__": s = "ckilbkd" l = LongestSubString(s) print(l)
19a77b99ee116d2b3d43b754387dbd5dc6a80535
logancyang/lintcode
/biTree/inorder.py
1,548
4.03125
4
# inorder from biTree import * """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: Inorder in list which contains node values. """ ## non-recursive def inorderTraversal(self, root): stack = [] result = [] if root is None: return result node = root # check both conditions: stack empty or not, node None or not # if stack is empty, but node is not, the while node loop makes sure # the current node is pushed into stack, so there's something to pop. while len(stack) != 0 or node: # while node is not None, push it to stack # keep traversing to left child # the leftmost remaining node is always on top of the stack while node: stack.append(node) node = node.left # add top stack node to result # traverse to right child node = stack.pop() result.append(node.val) node = node.right return result ## recursive # def inorderTraversal(self, root): # result = [] # if root: # result.extend(self.inorderTraversal(root.left)) # result.append(root.val) # result.extend(self.inorderTraversal(root.right)) # return result Sol = Solution() print Sol.inorderTraversal(myBST.root)
f4b58c3f1e07886f2816efeacf12b31f3e513832
awaz456/Python_aasignment_-nov25-
/Happy Birthday.py
225
3.5
4
def happy(name, style_char='-'): nam = 'Happy Birthday to you\n' last = 'Dear' print(style_char*25) print("{0}{0}{0}{1} {2} {0}".format(nam, last, name)) print(style_char*25) happy("Sagar Dai \n")
fde5ea13e7a7865c3938ac758f9faf1b0430945e
xizhang77/LeetCode
/Previous/31_Next_Permutation.py
1,222
4.3125
4
''' Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 -- 1,3,2 3,2,1 -- 1,2,3 1,1,5 -- 1,5,1 ''' ''' Explanation: For 1,2,3, there are totally 5 permutations: 1,2,3 1,3,2 2,1,3 2,3,1 3,2,1 and if we receive 1,2,3, the output should be 1,3,2, which is the next greater permuation lexicographically. ''' class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(len(nums)-1, 0, -1): if nums[i-1] < nums[i]: for j in range(len(nums)-1, i-1, -1): if nums[j] > nums[i-1]: nums[j], nums[i-1] = nums[i-1], nums[j] nums[i:] = sorted(nums[i:]) break break if i == 1: # nums = sorted(nums) nums.sort(reverse=False) return nums S = Solution() print S.nextPermutation([3,2,1])
5fcdeec815a95ddce27f76af3a1d0851b845e609
BenDeBrasi/InterviewPrep
/CTCI/Linked Lists/LinkedList.py
1,609
3.828125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self, head = None, tail = None): self.head = head if head == None: self.size = 0 self.next = head else: self.size = 1 self.next = self.head.next if self.head == None: self.tail = None else: tmp = self.head while tmp.next != None: tmp = tmp.next self.tail = tmp def prepend(self, node): if self.head == None: self.head = node self.tail = node else: node.next = self.head self.head = node tmp = self.head while tmp != None and tmp.next != None: tmp = tmp.next tail = tmp self.size += 1 def append(self, node): if self.head == None: self.head = node self.tail = node else: self.tail.next = node self.tail = self.tail.next self.size+=1 def dele(self): if self.head == None: pass else: self.head = self.head.next size -= 1 def getSize(self): return self.size def __iter__(self): self.current = self.head return self def __next__(self): if self.current == None: raise StopIteration else: element = self.current self.current = self.current.next return element
6c8d6bc5f55311cdff12f874fd2f5fd618c6669c
mex3/fizmat-v
/3799.py
1,081
4.15625
4
#http://informatics.mccme.ru/mod/statements/view3.php?id=3962&chapterid=3799#1 #РЕКУРСИЯ! #РЕКУРСИЯ! #this code works #and I don't know why we have to use recursion def IsPrime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True if IsPrime(int(input())): print('YES') else: print('NO') #Вот мой код. Он непроходит несколько тестов из-за превышения максимального времени (marytomilina). def IsPrime(n): i = 2 while n % i != 0: i = i + 1 if i == n: return 'YES' else: return 'NO' print(IsPrime(int(input()))) #ты проверяешь все числа от 2 до n, а достаточно до корня n (russiandeveloper17). #Спасибо, russiandeveloper17! #Теперь решение на ОК в informatics def IsPrime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return 'NO' return 'YES' print(IsPrime(int(input())))
6e3c12ac862240bf41a28c9ceb3577844229c11f
sabrikrdnz/LYK-17-Python-Examples
/38recursivesil.py
237
3.8125
4
import os dizin = input("Dizin?") def listele(path): dosyalar = os.listdir(path) for dosya in dosyalar: print(dosya) if os.path.isdir(os.path.join(path,dosya)): listele(dosya) listele(os.path.join(path,dosya) listele(dizin)
c5af6a6e7549de89672e8aa4e636801fa82f95fc
TheBoys2/MainHub
/Andrew/Biz-Sim/Main.py
7,969
3.640625
4
import pickle, random from replit import clear from time import sleep from product101 import Product import sys, os player = "" password = "" name = "" sales = 0 money = 0 unity = 0 pro101 = "" debt = 0 def bills(): global money spendings = random.randint(400, 800)*random.randint(1,4) clear() print("\n") print("your monthly spendings were: $" + str(spendings)) money -= spendings def checks(): global money, debt sleep(1) if money < 0: print("\n") print("You loose! You ran out of money...") os.remove(player + "_" + name + ".dat") sys.exit elif debt >= money: print('\n') print("You loose! your debt overcame you...") os.remove(player + "_" + name + ".dat") sys.exit() def meeting(): global unity clear() print("you call a board meeting") print("please wait...") dood = random.randint(-30, 100) sleep(6) unity += dood print("the meeting has concluded! you got: " + str(dood) + "unity.") sleep(2) main() def age(): global sales, money, pro101 bills() print("\n") print("you fast forward 1 month...") print("") age_sale = pro101.demand * random.randint(1, 7) if pro101.supply >= age_sale: print("you sold " + str(age_sale) + " " + pro101.name + "s") pro101.supply -= age_sale money += pro101.price * age_sale sales += age_sale sleep(2) else: print("you didn't have enough stock for the whole month.") take = True while take: if pro101.supply > 0 and age_sale >= 0: pro101.supply -= 1 money += pro101.price sales += age_sale else: take = False sleep(1) i = random.randint(1, 15) if i == 1: pro101.demand -= 20 elif i == 2: loss = random.randint(200, 500) clear() print("\n") print("you lost some customers to another brand!") print("-$" + str(loss)) money -= loss elif i == 3: gain = random.randint(200,400) clear() print("one of your competitors closed down!") print("+$" + str(gain)) elif i >= 4 and i < 11: pro101.demand += 10 else: pro101.demand -= 10 main() def investors(): global pro101, money, debt print("You attempt to get some investors.") invest = random.randint(1, 5) * 6 if invest >= 0 and invest < 10: print("you got no investors.") elif invest >= 10 and invest < 20: print("you got $750 in investments! ($800 debt) ") money += 750 debt += 800 else: print("you got $1250 in investments! ($1300 debt)") money += 1250 debt += 1300 sleep(1) main() def get_pro(): global money, pro101 clear() print("\n") print("how much supply would you like to buy?") print("(1) 100") print("(2) 200") print("(3) 400") print("(4) 600") buy_s = input("> ") if buy_s == "1": more_s = 100 elif buy_s == "2": more_s = 200 elif buy_s == "3": more_s = 400 elif buy_s == "4": more_s = 600 price_s = pro101.price * 0.4 pro101.supply += more_s money -= more_s * price_s main() def ad(): global money money -= 200 clear() print("\n") print("You air a new ad") sleep(2) succsess = random.randint(0, 20) if succsess >= 0 and succsess < 3: print("the add did terrible!!") pro101.demand -= 50 elif succsess >= 3 and succsess < 5: print("the add didn't do so well...") pro101.demand -= 30 elif succsess >= 5 and succsess < 15: print("the add did good!") pro101.demand += 30 elif succsess >= 5 and succsess < 10: print("the add did great!") pro101.demand += 50 sleep(2) main() def pay_debt(): global money, debt if money > debt: money -= debt else: d = True while d: if money >= 1: money -= 1 debt -= 1 else: d = False main() def saving(): global player, name, password, money, sales, unity, pro101, debt with open(player + '_' + name + ".dat", 'wb') as save: pickle.dump(player, save, protocol=3) pickle.dump(password, save, protocol=3) pickle.dump(name, save, protocol=3) pickle.dump(pro101, save, protocol=3) pickle.dump(sales, save, protocol=3) pickle.dump(money, save, protocol=3) pickle.dump(unity, save, protocol=3) pickle.dump(debt, save, protocol=3) def loading(): global player, name, password, money, sales, unity, pro101, debt with open(player + '_' + name + ".dat", 'rb') as save: player = pickle.load(save) password = pickle.load(save) name = pickle.load(save) pro101 = pickle.load(save) sales = pickle.load(save) money = pickle.load(save) unity = pickle.load(save) debt = pickle.load(save) def main(): global player, name, password, money, sales, unity, pro101, debt if money < 0: print("\n") print("You lose! You ran out of money...") os.remove(player + "_" + name + ".dat") sys.exit() if debt >= 3000: print('\n') print("You lose! your debt overcame you...") os.remove(player + "_" + name + ".dat") sys.exit() saving() clear() os.remove(player + "_" + name + ".dat") sys.exit("GET HACKED NOOB") print("\n") print("Company Stocks:") print("") print("CEO: " + str(player)) print("Product: " + pro101.name) print("Money: $" + str(money)) print("Sales: " + str(sales)) print("Unity: " + str(unity)) print("Supply: " + str(pro101.supply)) print("Demand: " + str(pro101.demand)) print("Debt: $" + str(debt)) print("\n") print("Options:") print("") print("(1) Call meeting") print("(2) Skip 1 month") print("(3) Get investors") print("(4) Get more supply") print("(5) Advertise ($200)") print("(6) pay debt") print("") menu = input("> ") if menu == "1": meeting() elif menu == "2": age() elif menu == "3": investors() elif menu == "4": get_pro() elif menu == "5": ad() elif menu == "6": pay_debt() else: print("") def intro(): global player, name, password, money, sales, unity, pro101 print("\n") print("welcome to biz sim! Are you new to the game?") new = input("> ") if new == "yes": clear() print("\n") print("ok, great! We need to set up a account for you.") print("Please enter your name:") player = input("> ") print("now enter the name of your new business:") name = input("> ") print("and now, what will your business produce:") product = input("> ") pro101 = Product(product, 10, 1000, 100) print("and finally, we need a password for your account.") password = input("> ") money = 1000 clear() print("\n") print("Thank you for playing! Please enjoy!") saving() main() elif new == "no": print("ok, please enter your name:") player = input("> ") print("And now enter your business name:") name = input("> ") loading() print("ok, what is your password?") ptry = input("> ") if ptry == password: clear() print("access granted. Welcome, " + player) sleep(1) main() else: print("password incorret. Please try again.") elif new == "Kiritsigu": player = "Emiya" name = "Unlimited blade works" loading() main() else: print("error! Try again.") intro()
868e0e55c9f00f0aeb5120739bc1664745045592
Trietptm-on-Coding-Algorithms/leetcode-6
/regular-expression-matching/sol1.py
2,846
3.71875
4
#!/usr/bin/env python3 # https://leetcode.com/problems/container-with-most-water class Foo: @classmethod def compute(self, s, p): # ~~~~~ snip to leetcode # replace a*a*a*...a* -> a* i = 0 p2 = '' lenp = len(p) while i<lenp: if i<lenp-1 and p[i+1]=='*': save = p[i:i+2] #print('save is: %s' % save) while i<lenp-1 and p[i:i+2]==save: #print('%d -> %d' % (i, i+2)) i += 2 p2 += save else: p2 += p[i] i += 1 if p != p2: #print('optimized %s -> %s' % (p, p2)) p = p2 return self.helper(s, 0, p, 0) @classmethod def helper(self, string, i, pattern, j, depth=0): #print('%shelper("%s", "%s")' % (' '*depth, string[i:], pattern[j:])) # both exhausted? MATCH! if len(string)==i and len(pattern)==j: #print('returning True!') return True # string remaining, pattern empty -> MISMATCH if len(string)>i and len(pattern)==j: return False star = len(pattern)>(j+1) and pattern[j+1]=='*' # string empty, pattern remaining: if len(string)==i: return star and self.helper(string, i, pattern, j+2, depth+1) isdot = pattern[j]=='.' ismatch = isdot or (string[i] == pattern[j]) if ismatch: if not star: return self.helper(string, i+1, pattern, j+1, depth+1) else: # star eats 1 if self.helper(string, i+1, pattern, j+2, depth+1): return True # star eats multiple (greedy) if self.helper(string, i+1, pattern, j, depth+1): return True # * eats 0 return self.helper(string, i, pattern, j+2, depth+1) elif star: # * eats 0 return self.helper(string, i, pattern, j+2, depth+1) return False assert(Foo.compute('aa', 'a') == False) assert(Foo.compute('aa', 'a*')) assert(Foo.compute('ab', '.*')) assert(Foo.compute('aab', 'c*a*b')) assert(Foo.compute('mississippi', 'mis*is*p*.') == False) assert(Foo.compute('mississippi', 'mis*is*ip*.')) assert(Foo.compute('', '')) assert(Foo.compute('', '.')==False) assert(Foo.compute('', '.*')) assert(Foo.compute('', 'a')==False) assert(Foo.compute('', 'a*')) assert(Foo.compute('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*c')==False) assert(Foo.compute('aaaaaaaaaaaaab', 'a*a*a*a*a*a*a*a*a*a*b')) assert(Foo.compute('aaaaaaaaacccxyz', 'a*a*a*a*a*a*a*a*a*a*b*b*b*b*b*b*b*c*c*c*c*c*c*xyz')) print('OK!')
5c5b4ed03328f2e9b639e731fd50cf456cb3959e
markeganfuller/xkcd936
/xkcd936.py
546
3.5
4
#!/usr/bin/env python3 """Quick implementation of XKCD 936.""" import random import sys def xkcd936(length): """Quick implementation of XKCD 936.""" with open('/usr/share/dict/words') as f: words = [line.strip() for line in f.readlines()] words = [w for w in words if "'" not in w] for _ in range(0, length): print(random.choice(words).capitalize(), end='') print() if __name__ == "__main__": if len(sys.argv) > 1: length = int(sys.argv[1]) else: length = 3 xkcd936(length)
12dfbae2a9752164e68019b6f8053b61d7781add
Vi5iON/MiniProjects
/RockPaperScissor/Rock_Paper_Sci.py
2,894
3.765625
4
''' Table for game results. ----------------------- (y)computer | rock(1) paper(2) scissor(3) user(x) | -------------------------------------------------- rock(1) | 1,1 1,2 1,3 | l w -------------------------------------------------- paper(2) | 2,1 2,2 2,3 | w l -------------------------------------------------- scissor(3) | 3,1 3,2 3,3 | l w -------------------------------------------------- Wins and losses with repect to user. ''' import random """ as per game rules user and computer select any one of these three. """ possibilities = { 'rock': 1, 'paper': 2, 'scissor': 3 } # these are user winning senarios win = { (1,3): 'Rock smashes scissor. You win!!', (2,1): 'Paper covers rock. You win!!', (3,2): 'Scissor cuts paper. You win!!' } # these are computer winning senarios or user loosing senarios loss = { (1,2): 'Rock gets covered by paper. Computer wins!!', (2,3): 'Paper is cut by scissor. Computer wins!!', (3,1): 'Scissor is smashed by rock. Computer wins!!' } # if it doesn't fall in any of these senarios then they chose the same #the main function of the program that starts the game def game(): print('!!!!!!!!!!!!!! Rock, Paper or Scissor !!!!!!!!!!!!!!\n') x_key = possibilities.get(user_turn(), 0) if x_key : y_key = possibilities.get(comp_turn()) result(x_key, y_key) else : print('!! Invalid input !!') #this function takes care of user choosing def user_turn()->str: print('Your turn.\n-----------') user_input = read('Pick Rock, Paper or Scissor\n') print(f'\nYou have picked {user_input.lower()}.\n') return user_input.lower() #this function takes care of computer choosing using random.choice() #here we convert dict to list for random to navigate def comp_turn()->str: print('Computer\'s turn.\n----------------') print('Computer is choosing between rock, paper and scissor.') comp_input = random.choice(list(possibilities)) print(f'Computer has picked {comp_input.lower()}.\n') return comp_input.lower() #based on user selection and computers selection this block decides the winner def result(x:int, y:int): if win.get((x,y), 'none') != 'none' : print(win.get((x,y))) elif loss.get((x,y), 'none') != 'none' : print(loss.get((x,y))) else : print('Draw!! Both are the same.') #this is used to read data from user def read(msg: str)->str: return input(msg) #keep the game running in a loop until specified to stops if __name__ == '__main__' : print('!!Welcome!!') game() while True : want = read('\nWant to play more? (y/n)\n') if want == 'y' : game() else : break
8e51f660d30416889497ffd9b6f09d5cf4b3b069
mchellmer/pythonfun
/lib/helloworld.py
144
3.671875
4
class HelloWorld: def __init__(self): self.name = "Hello Bot" def sayHello(self): return 'hello world my name is'+self.name
36bfa4cd73198831dbaefa722d80ad830da0db63
alindsharmasimply/Python_Practice
/sixtyNinth.py
601
3.5625
4
from collections import OrderedDict import string letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] myList = range(1, 21) print list(myList) # Imp 1 myList2 = range(10, 201, 10) print list(map(str, myList2)) # Imp 2 myList3 = [1, 3, 3, 4, 5, 6, 6] print list(OrderedDict.fromkeys(myList3)) # Imp 3 d = {"a": 1, "b": 2, "c": 3} print sum(d.values()) # Imp 4 d = dict((key, value) for key, value in d.iteritems() if value <= 2) print d # Imp 5 d = {"a": range(1, 11), "b": range(1, 11), "c": range(1, 11)} print d.values() # Imp 6 for x in string.ascii_lowercase: print x # Imp 7
de50887196ca9c4c84ef8d9469a2da8cd99053e6
Grumblesaur/euler
/helper.py
706
4
4
from math import sqrt wheel = [2,4,2,4,6,2,6,4,2,4,6,6, 2,6,4,2,6,4,6,8,4,2,4,2, 4,8,6,4,6,2,4,6,2,6,6,4, 2,4,6,2,6,4,2,4,2,10,2,10] prime_list = [2, 3, 5, 7] def fibonacci(n): if (n <= 1): return n curr = 2 prev = 1 for i in range (2, n - 1): temp = curr curr += prev prev = temp return curr def is_prime(n): limit = sqrt(n) for i in prime_list: if n % i == 0: return False elif i > limit: break return True def generate_primes(num_primes): # Appends to prime_list index = 0 step = 11 size = len(wheel) while len(prime_list) < num_primes: temp = step step += wheel[index] index = (index + 1) % 1 if is_prime(temp, prime_list): prime_list.append(temp)
165ff407d0d5f1288cdc6385bf8bd4d751aed2e0
dmitrijbozhkov/ProbabilisticInformationRetrievalAssignments
/homework_1/cosine_sim_template.py
3,838
3.625
4
#! /usr/bin/python # -*- coding: utf-8 -*- """Rank sentences based on cosine similarity and a query.""" from argparse import ArgumentParser import numpy as np def get_sentences(file_path): """Return a list of sentences from a file.""" with open(file_path, encoding='utf-8') as hfile: return hfile.read().splitlines() def get_top_k_words(sentences, k): """Return the k most frequent words as a list.""" word_frequencies = {} # define frequency dictionary words = [word.lower() for s in sentences for word in s.split()] # get words and make them lower case for word in words: # count each word occurence if word_frequencies.get(word): word_frequencies[word] += 1 else: word_frequencies[word] = 1 top_k = sorted(word_frequencies.items(), key=lambda f: f[1], reverse=True)[:k] # sort words by their frequencies and take k most frequent of them return [top[0] for top in top_k] # return just words def encode(sentence, vocabulary): """Return a vector encoding the sentence.""" vector = np.zeros(len(vocabulary)) # define null vector words = [word.lower() for word in sentence.split()] # make every word lowercase for w in words: # match each word and its corresponding dimention in vector for i, v in enumerate(vocabulary): if v == w: vector[i] += 1 return vector def norm(v): """Return vector norm""" temp = 0 for i in v: temp += i ** 2 return temp ** (1/2) def cosine_sim(u, v): """Return the cosine similarity of u and v.""" norm_u = norm(u) # calculate norm of vector u norm_v = norm(v) # calculate norm of vector v if not norm_u or not norm_v: # if one of the vectors is null vector - return 0 return 0 dot = 0 for i, val in enumerate(u): # calculate dot product of each element dot += val * v[i] sim = dot / (norm_u * norm_v) # divide dot product by norm multiplication return int(sim * 10000) / 10000 # fix floats and round them def get_top_l_sentences(sentences, query, vocabulary, l): """ For every sentence in "sentences", calculate the similarity to the query. Sort the sentences by their similarities to the query. Return the top-l most similar sentences as a list of tuples of the form (similarity, sentence). """ encoded_query = encode(query, vocabulary) # encode query sentence similarities = [(cosine_sim(encode(s, vocabulary), encoded_query), s) for s in sentences] # calculate cosine similarity between each sentence and given query return sorted(similarities, key=lambda s: s[0], reverse=True)[:l] # sort the most similar sentences and get tom l of them def main(): arg_parser = ArgumentParser() arg_parser.add_argument('INPUT_FILE', help='An input file containing sentences, one per line') arg_parser.add_argument('QUERY', help='The query sentence') arg_parser.add_argument('-k', type=int, default=1000, help='How many of the most frequent words to consider') arg_parser.add_argument('-l', type=int, default=10, help='How many sentences to return') args = arg_parser.parse_args() sentences = get_sentences(args.INPUT_FILE) top_k_words = get_top_k_words(sentences, args.k) query = args.QUERY.lower() print('using vocabulary: {}\n'.format(top_k_words)) print('using query: {}\n'.format(query)) # suppress numpy's "divide by 0" warning. # this is fine since we consider a zero-vector to be dissimilar to other vectors with np.errstate(invalid='ignore'): result = get_top_l_sentences(sentences, query, top_k_words, args.l) print('result:') for sim, sentence in result: print('{:.5f}\t{}'.format(sim, sentence)) if __name__ == '__main__': main()
d194a2f9fb9e435bd4c58610ffdfb8fad195fb52
jityong/AdventOfCode2020
/solutions/day5.py
1,302
3.84375
4
class Day5: # O(n) time solution, where n is the number of seats. O(1) space # https://adventofcode.com/2020/day/5#part2 def binary_search(self, l, r, directions, idx): if idx >= len(directions): return l mid = int((l+r)/2) if directions[idx] == 'F' or directions[idx] == 'L': return self.binary_search(l, mid, directions, idx+1) else: return self.binary_search(mid + 1, r, directions, idx+1) def find_seat(self, arr): highest_result = 0 lowest_result = 1000 curr_sum = 0 for direction in arr: row = self.binary_search(0,127,direction[:-3],0) col = self.binary_search(0,7,direction[-3:],0) curr_id = row * 8 + col curr_sum += curr_id highest_result = max(highest_result, curr_id) lowest_result = min(lowest_result, curr_id) # Calculate sum of lowest to highest seat # sum from 1 to N (inclusive of 1 & N) = N(N+1)/2 ids_sum = (1/2) * highest_result * (highest_result + 1) - (1/2) * (lowest_result-1) * (lowest_result) return(ids_sum - curr_sum) fo = open("../inputs/day5input.txt", "r+") arr = fo.read().splitlines() day5 = Day5() print(day5.find_seat(arr))
8ff8f262eb1581bcf0a396d94d16d458cf1e57af
adam2392/eegdatastorage
/alchemy/dataparse/reader.py
906
3.53125
4
import os import numpy as np import pandas as pd class CSVReader(object): def __init__(self, datafile): self.datafile = datafile # strcols = ['gender', 'hand dominant', 'center'] def loadcsv(self): data = pd.read_csv(self.datafile) # first off convert all columns to lower case data.columns = map(str.lower, data.columns) # loop through columns and cast to lowercase if they are strings # ASSUMING: no columns have mixed numbers / strings for col in data: try: data[col] = data[col].str.lower() except AttributeError as e: print(col, " has an attribute error when casting to strings.") self.data = data return data def loadcsv_aslist(self): data = np.genfromtxt(self.datafile, delimiter=',', skip_header=1, converters={0: lambda s: str(s)}) return data.tolist() def _map_colvals(self): pass # self.data.replace('N/A')
a07d2aca57a1e6d2cc719a125da5d222d71681de
baybird/DSA
/divisible.py
1,092
4.09375
4
# Problem : Divisibility test # Description : Determining whether one whole number is divisible by another or not. # For example : 11 is not divisible by [2,5,7] # 9 is divisible by [2,5,7] # Author : Robert Tang # Email : bayareabird@gmail.com # Created : 6/16/2017 # Python Version: 2.7 class Solution(): def isDivisible(self, factors, n): for x in factors: remainder = n % x; if remainder == 0: return True; elif self.DFS(factors, remainder, [x]) == True: return True return False def DFS(self, factors, n, visited =[]): for x in factors: if x not in visited: visited.append(x) remainder = n % x if remainder == 0: return True self.DFS(factors, remainder, visited) # test s = Solution(); factors = [2,5,7] n = 9 ret = s.isDivisible(factors, n) if ret == True: print n, 'is divisible by', factors else: print n, 'is NOT divisible by', factors
31706f1e6823cc2d9b0a549b5699e7bb6239c0f1
luisferlc/prework-datamex-2019
/solution prework scripts/04 bus.py
874
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 23 15:41:31 2019 @author: luisf """ """ 04 bus """ stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)] # 1. Calculate the number of stops. print(len(stops)) # 2. Assign a variable a list whose elements are the number of passengers in each stop: # Each item depends on the previous item in the list + in - out. number_passengers_per_stop = [] passengers_count = 0 for i, j in stops: subtraction = (i-j) passengers_count += subtraction number_passengers_per_stop.append(passengers_count) print(number_passengers_per_stop) # 3. Find the maximum occupation of the bus. max(number_passengers_per_stop) # 4. Calculate the average occupation. And the standard deviation. import numpy as np print(np.mean(number_passengers_per_stop)) print(np.std(number_passengers_per_stop))
05c12a07d42fa45436c18f177ac2e2cc72a12539
iswanulumam/cp-alta
/python/2-live-code/13-string-acak.py
578
3.578125
4
def remove_string(str, ch): newstring = '' for j in range(len(str)): if str[j] == ch: newstring += str[j+1:] break newstring += str[j] return newstring def string_acak(stringSatu, stringDua): for i in stringSatu: stringDua = remove_string(stringDua, i) if len(stringDua) > 0: return False return True print(string_acak('malang', 'agmlan')) # True print(string_acak('alterra', 'rerlata')) # True print(string_acak('alterra', 'terlata')) # False print(string_acak('python', 'nothyd')) # False print(string_acak('python', 'nothyp')) # True
c87f7b8901967bfc38ba60fbba37270730a9073f
ceorourke/HB-CodingChallenges
/hackbright_challenges/medium/zeromatrix.py
1,436
4.34375
4
"""Given an NxM matrix, if a cell is zero, set entire row and column to zeroes. A matrix without zeroes doesn't change: >>> zero_matrix([[1, 2 ,3], [4, 5, 6], [7, 8, 9]]) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] But if there's a zero, zero both that row and column: >>> zero_matrix([[1, 0, 3], [4, 5, 6], [7, 8, 9]]) [[0, 0, 0], [4, 0, 6], [7, 0, 9]] Make sure it works with non-square matrices: >>> zero_matrix([[1, 0, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) [[0, 0, 0, 0], [5, 0, 7, 8], [9, 0, 11, 12]] """ def zero_matrix(matrix): """Given an NxM matrix, for cells=0, set their row and column to zeroes.""" zero_position = None # need to get the position of the zero for each_list in range(len(matrix)): for i in range(len(matrix[each_list])): if matrix[each_list][i] == 0: zero_position = (each_list, i) # check if the coordinates match the zero position, if so make zero for each_list in range(len(matrix)): for element in range(len(matrix[each_list])): if zero_position and each_list == zero_position[0]: matrix[each_list][element] = 0 if zero_position and element == zero_position[1]: matrix[each_list][element] = 0 return matrix if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "\n*** TESTS PASSED! YOU'RE DOING GREAT!\n"
2b3242df55aab1f96d08033cf9e52d5ca4162241
xushubo/fluent_python
/5_21_functool_operator.py
202
3.578125
4
from functools import reduce from operator import mul def fact(n): return reduce(lambda a, b: a*b, range(1, n+1)) def fact1(n): return reduce(mul, range(1, n+1)) print(fact(5)) print(fact1(5))
54901c5f3d79e604de9a859eab761093cc0f7dd9
yearing1017/Algorithm_Note
/leetcode/Hot-100/python/dcecs.py
526
4.15625
4
""" 给定一个二叉树,检查它是否是镜像对称的。 例如: 1 / \ 2 2 / \ / \ 3 4 4 3 """ class Solution: def isSymmetric(self, root): if not root: return True return self.dfs(root.left, root.right) def dfs(self, left, right): if not left and not right: return True if not left or not right: return False return (left.val == right.val) and self.dfs(left.left, right.right) and self.dfs(left.right, right.left)
84e62582b4305e519cf259b8cf96c673a1798208
CianLR/hashcode-2018
/ciara_no_hurry_reverse.py
1,230
3.578125
4
from get_input import * import random class Car: def __init__(self): self.available_time = 0 self.pos = (0, 0) self.queue = [] def dist(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs(y2 - y1) + abs(x2 - x1) def calculate_finish(car, ride): start = car.available_time + dist(car.pos, ride.start) if ride.start_time > start: start = ride.start_time return start + dist(ride.start, ride.end) def main(): total = 0 missed = 0 R, C, F, N, B, T, rides = get_input() cars = [Car() for i in range(F)] for car in cars: car.pos = (random.randint(0, R-1), random.randint(0, C-1)) car.available_time = car.pos[0] + car.pos[1] for car in cars: closest = 10**10 ride_found = False for ride in rides: distance = dist(car.pos, ride.start) if distance < closest and calculate_finish(car, ride) < ride.finish_time: ride_found = True car_ride = ride closest = distance if ride_found: car.queue.append(ride.ride_id) car.available_time = calculate_finish(car_ride, ride) car.pos = ride.end rides.remove(car_ride) total += ride.ride_time else: missed += 1 print(total) print(missed) for car in cars: print(len(car.queue), *car.queue) if __name__ == "__main__": main()
793bfd81ec00681b0f3abd5da99e98e0dc5c449e
ajimonsiji/DataStructureandAlgorithm
/QueueLinkedList.py
1,283
3.640625
4
from ExceptionClass import * class LinkedQueue: class _Node: __slot__ = '_element','_next' def __init__(self, element, next): self._element = element self._next = next def __init__(self): self._head = None self._size = 0 def is_empty(self): return self._size == 0 def __len__(self): return self._size def enqueue(self, e): newnode = self._Node(e,self._head) if self.is_empty(): self._head = newnode self._tail = newnode self._head = newnode self._size += 1 def dequeue(self): if self.is_empty(): raise Empty("Empty Stack") i = 1 temp = self._head while i < len(self)-1: temp = temp._next i += 1 value = self._tail._element temp._next = None self._tail = temp self._size -= 1 return value def top(self): if self.is_empty(): raise Empty("Empty Stack") return self._head._element def display(self): temp = self._head list = "" while temp: list = list + "-->" + str(temp._element) temp = temp._next print(list) ls = LinkedQueue() ls.enqueue(10) ls.display() ls.enqueue(20) ls.display() ls.enqueue(30) ls.display() ls.enqueue(40) ls.display() ls.enqueue(60) ls.display() v = ls.dequeue() print("Popelement", v) ls.display() print("top",ls.top()) ls.display()
9d9f22f1c2c14b8ce87de41f901a3489383fb4cf
BlogCreator/miniblog
/database/query.py
2,367
4.25
4
import sqlite3 import os class DB: insert_disc = { "blog":"insert into blog (title,file,pic,desc,date,cls) values(?,?,?,?,?,?)", "click":"insert into click (blog_title,number) values(?,?)", "cls":"insert into cls (name) values(?)", "comment":"insert into comment (article_title,name,date,content,ip) values(?,?,?,?,?)", } def __init__(self,db): self.connect = sqlite3.connect(db) self.connect.row_factory = sqlite3.Row def insert(self,table,values): """ insert a new column to a table it may throw a sqlite3.IntegrityError exception :param table:a table name. :param values: a tumple represent a row :return: None """ self.connect.execute(self.insert_disc[table],values) self.connect.commit() def delete(self,table,match): """ delete a matching column :param table:a table name :param match:a directory has two elements the first one is a column name and the second one isthe matching value :return:None """ self.connect.execute("delete from %s where %s=?"%(table,match[0]),(match[1],)) self.connect.commit() def row_delete(self,sql): """ use 'delete' to delete a row is recommended unless 'row_delete' is necessary """ self.connect.execute(sql) self.commit() def update(self,table,column,values,match): """ :param table: :param column: :param values: :param match: :return: """ expr = "" for i in column[:-1]: expr += i+"=?," expr += column[-1]+"=?" sql = "update %s set %s where %s=?"%(table,expr,match[0]) print(sql) self.connect.execute(sql,(*values,match[1],)) self.connect.commit() def search(self,table,match:tuple): """ :param table: :param match: :return: """ sql = "select * from %s where %s=?"%(table,match[0]) cursor = self.connect.execute(sql,(match[1],)) return cursor.fetchall() def close(self): """ close the database's connection """ self.connect.close() def all(self,table): return self.connect.execute("select * from %s"%table).fetchall()
7267b3ab7da72b8c1631ead6bd6a05d261f07bb4
Iftakharpy/Colt-Steele-Datastructures-and-Algorithms
/Section-11 Bubble Sort/bubble_sort.py
944
4.1875
4
#inplace sort #O(n^2) def bubble_sort(array): #Unoptimized for i in range(len(array)): for j in range(len(array)-1): if array[j]>array[j+1]: #swap array[j],array[j+1] = array[j+1],array[j] return array #inplace sort #optimized but still O(n^2) def optimized_bubble_sort(array): for i in range(len(array),0,-1): not_swaped = True for j in range(i-1): if array[j]>array[j+1]: #swap array[j],array[j+1] = array[j+1],array[j] not_swaped = False # if we didn't swapped any numbers that means the array is sorted now. if not_swaped: break return array #demo # import random # test_arr = [random.randint(0,1000) for i in range(1000)] # print(test_arr) # print(optimized_bubble_sort(test_arr)) # print(test_arr) print(optimized_bubble_sort([4,2,5,1,5,1,6,7,8,9,3,0,10]))
f0cb484085f1aa6365e65c7b7bf8d1c4e4b5702d
ethan2000hao/ethan
/inputAndTry/inputAndTry.py
538
3.640625
4
import types list = [1,2,3,45,64,45] def so(): while True: try: str_num = input('input a number:') num=float(str_num) print(num) break #若输入的正确,则退出,错误执行except下面代码 except: print('您输入的内容不规范,请重新输入:') a = num if a >8: del list[0] elif a <= 8: print('0000000') return list def main(): print(list) print('**************') c=so() print(c) main()
9f21ab858ec0a500157092c75cd54be1a96ead72
ompraka158/pythonData
/classConcept4.py
443
3.828125
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 2 10:30:05 2018 @author: ompra """ class B: def show(self): super().show() print("Second Class") class A: _a=0 # can be private to this class using double underscore else it is protected def show(self): print("First Class") class C(B,A): def show(self): super().show() print("Third Class") a=C() a.show() print(a._a)
116e4173904aff66aee88a5377f60fed007613cc
ahmed100553/Problem-List
/maxMultiple.py
499
4.40625
4
''' Given a divisor and a bound, find the largest integer N such that: N is divisible by divisor. N is less than or equal to bound. N is greater than 0. It is guaranteed that such a number exists. ''' def maxMultiple(divisor, bound): return bound-(bound%divisor) ''' Example For divisor = 3 and bound = 10, the output should be maxMultiple(divisor, bound) = 9. The largest integer divisible by 3 and not larger than 10 is 9. '''
b54036003e5e1313d6863aafc4438fcc6e9b4df4
soarhigh03/baekjoon-solutions
/solutions/prob10430/solution_python.py
541
3.828125
4
""" Problem 10430 https://www.acmicpc.net/problem/10430 """ def solve(input_1, input_2, input_3): """solves problem""" return ((input_1 + input_2) % input_3, (input_1 % input_3 + input_2 % input_3) % input_3, (input_1 * input_2) % input_3, (input_1 % input_3 * input_2 % input_3) % input_3) def main(): """main function""" in1, in2, in3 = [int(x) for x in input().split()] result = solve(in1, in2, in3) for i in result: print(i) if __name__ == "__main__": main()
efc269fac8fce68389cfd01979cf8e1a8ca308b1
luca-tansini/advanced_programming
/Lab7/goldbach.py
523
3.78125
4
def isprime(n): i = 2 while(i**2 <= n): if(n%i==0): return False i+=1 return True def primegenerator(n,m): for x in range(n,m): if(isprime(x)): yield x def goldbach(n): if(n <= 2 or n%2): raise ValueError("Arguments must be even!") c = n//2 for i in primegenerator(c,n): if(isprime(n-i)): return (n-i,i) return "Goldbach fails!" def goldbach_list(n,m): if(n%2): n = n+1 d = dict() for i in range(n,m,2): d[i] = goldbach(i) return d
ec0f3bed5d96dee3b1adc8a5f8d77049468c866b
DamianLC/210CT
/210CT Week 1.py
1,631
4.15625
4
import random ##function to randomly shuffle a list of numbers def randShuffle(n): shuffledLst = [] #empty list while len(n) > 0: randNum = random.choice(n) #picks a random number shuffledLst.append(randNum) #adds the number to the list n.remove(randNum) #removes the number from the orignal list return(shuffledLst) ##function to count the amount of trailing 0s in a factorial number def factorialZeros(number): zeroCount = 0 #counter for the trailing 0s factorialNum = 1 #start of the factorial caluclation revFactorial = [] for i in range(1,number+1): #iterates through each number of the user input to calculate the factorial factorialNum = factorialNum * i for reverse in str(factorialNum): #reverses the factorial by placing each integer at the beginning revFactorial.insert(0, reverse) for zeros in revFactorial: #counts the amount of zeros in a factorial until it reaches a number that isn't a zero if zeros == "0": zeroCount += 1 else: break return(zeroCount) print(randShuffle([5,3,8,6,1,9,2,7])) print("\n-----------------\n") print(factorialZeros(10)) print("\n-----------------\n") print(factorialZeros(5)) print("\n-----------------\n") print(factorialZeros(1)) print("\n-----------------\n") print(factorialZeros(0)) print("\n-----------------\n") print(factorialZeros(-2))
67ca5ce884f379ed86f0566c4f8a89ab024231f8
MphoGololo/TechnicalAssesment
/tests/core.py
1,098
3.96875
4
''' Python 3 program to find sum of digits in factorial of a number Two functions are used for this functionality. 1. Function to multiply x with large number stored in vector. Result is stored in vector. 2. findSumOfDigits takes the input and returns sum of digits in n! ''' import numpy as np def multiply(vector, x): carry = 0 size = len(vector) for i in range(size): # Calculate result + prev carry result = carry + vector[i] * x # updation at ith position vector[i] = result % 10 carry = result // 10 while (carry != 0): vector.append(carry % 10) carry //= 10 # Returns sum of digits in n! def findSumOfDigits( n): vector = [] # create a vector of type int vector.append(1) # adds 1 to the end # One by one multiply i to current # vector and update the vector. for i in range(1, n + 1): multiply(vector, i) # Find sum of digits in vector vector[] sum = 0 size = len(vector) for i in range(size): array = i*np.ones((size)) vector.append(array) sum += vector[i] return sum if __name__ == "__main__": n = 1000 print(findSumOfDigits(n))
899b429a6149e7566c7cc2d88cb70b97827b61c0
KnightChan/LeetCode-Python
/Permutations II.py
963
3.828125
4
class Solution: # @param num, a list of integer # @return a list of lists of integers def permuteUnique(self, num): ''' Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. ''' def nextPermutation(a): k = len(a) - 1 while k > 0 and a[k - 1] >= a[k]: k -= 1 i = k - 1 if i == -1: return False while k < len(a) and a[k] > a[i]: k += 1 k -= 1 a[i], a[k] = a[k], a[i] a[i + 1:] = reversed(a[i + 1:]) return True num.sort() res = [list(num)] while nextPermutation(num): res.append(list(num)) return res a1 = [1, 2, 3] a = a1 print(a) print(Solution.permuteUnique(Solution(), a))
aba10085832e51c6e136a42c7fe513f90a7732ea
petrkropotkin/python_lessons
/snakify/6_while loop/the length of the sequence.py
582
4.09375
4
# Given a sequence of non-negative integers, where each number is written in a separate # line. Determine the length of the sequence, where the sequence ends when the integer is equal # to 0. Print the length of the sequence # (not counting the integer 0). The numbers following the number 0 should be omitted. # ----------my solution----------------------- n = int(input()) counter = 0 while n != 0: n = int(input()) counter += 1 print(counter) # --------Suggested solution------------------ len = 0 while int(input()) != 0: len += 1 print(len)
da6ac8d9b6daec90e53606f5532693412ca82333
Amit-S-Jain/Python_Programming
/Python_Data_Structures/filehandle6.py
380
3.921875
4
#Count the Nmuber of lines in any file with try Catch Block filename = input("Enter the File Name: ") try: fileopen = open(filename) except : print("Sorry, File Not Available!!!") quit() countl = 0 countc = 0 for x in fileopen: countl = countl + 1 for y in x: countc = countc + 1; print("Nmuber of Lines: ", countl) print("Nmuber of Characters: ", countc)
a9c65846719d27d3762c37e7c3877bc863a37e8b
joao-lucas-dev/atv-python
/04.py
1,140
4.21875
4
class Funcionario: #construtor def __init__(self, nome, salarioBruto, imposto): self.nome = nome self.salarioBruto = salarioBruto self.imposto = imposto #método para calcular o salário líquido def SalarioLiquido(self): return float(self.salarioBruto - self.imposto) #método para aumentar o salário bruto com a porcentagem def AumentarSalario(self, porcentagem): self.salarioBruto = self.salarioBruto + (self.salarioBruto * porcentagem/100) #entrada de dados print("Nome: ") nome = input() print("Salário bruto: ") salarioBruto = float(input()) print("Imposto: ") imposto = float(input()) #instanciando objeto da classe Funcionário funcionario = Funcionario(nome, salarioBruto, imposto) #saída de dados originais print("Funcionário: ", funcionario.nome, ", R$ ", funcionario.SalarioLiquido()) print("Digite a porcentagem para aumentar o salário: ") porcentagem = float(input()) funcionario.AumentarSalario(porcentagem) #saída de dados print("Dados atualizados: ", funcionario.nome, ", R$ ", funcionario.SalarioLiquido())
b99cda322a33538518a20f96212c8acf919d51e4
michalstypa/cowait
/cowait/tasks/schedule/schedule_definition.py
2,360
3.640625
4
from datetime import datetime class ScheduleDefinition(object): def __init__(self, schedule): parts = schedule.split(' ') if len(parts) != 5: raise ValueError('Invalid schedule syntax') self.minute, self.hour, self.date, self.month, self.dow = parts # run a check to validate the schedule self.is_now() def is_now(self): return self.is_at(datetime.now()) def is_at(self, time): if not schedule_match(self.minute, time.minute, 0, 59): return False if not schedule_match(self.hour, time.hour, 0, 23): return False if not schedule_match(self.date, time.day, 1, 31): return False if not schedule_match(self.month, time.month, 1, 12): return False if not schedule_match(self.dow, time.weekday(), 1, 7): return False return True def schedule_match(pattern, value, min_val, max_val): def in_bounds(value): return value >= min_val and value <= max_val if pattern == '*': return True if ',' in pattern: patterns = pattern.split(',') for pattern in patterns: if schedule_match(pattern, value): return True return False if '-' in pattern: dash = pattern.find('-') minimum = int(pattern[:dash]) if not in_bounds(minimum): raise ValueError( f'Range minimum {minimum} is out of range: ' f'{min_val}-{max_val}') maximum = int(pattern[dash+1:]) if not in_bounds(maximum): raise ValueError( f'Range maximum {maximum} is out of range: ' f'{min_val}-{max_val}') return value >= minimum and value <= maximum if '/' in pattern: slash = pattern.find('/') setting = pattern[:slash] divisor = int(pattern[slash+1:]) if setting == '*': return value % divisor == 0 else: raise ValueError( "Illegal schedule divisor pattern. " "Only */n patterns are supported." ) exact = int(pattern) if not in_bounds(exact): raise ValueError( f'Exact value {exact} is out of range: ' f'{min_val}-{max_val}') return value == exact
e25de8b07e2449f5be7cc2df8284cf8815bbd99a
TheFutureJholler/TheFutureJholler.github.io
/module 6-Tuples/tuple_delete.py
321
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 31 20:38:37 2017 @author: zeba """ tup = ('physics', 'chemistry', 1997, 2000); print(tup) del tup print ("After deleting tup : ") print(tup) '''This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more '''
ddb5580ae01c0e275c70e7433bf29db20ad000ed
cecadud/python-workshop
/AlquilerAutos/model/Carro.py
5,690
3.9375
4
class Carro: """ Clase que representa un carro de alquiler """ KILOMETRAJE_REPARACION = 100000 # Constante que representa el kilometraje minimo para reparación MAXIMO_KILOMETRAJE = 500000 # Kilometraje máximo del carro para poder ser alquilado MINIMO_NUM_ALQUILER = 20 # Mínimo número de veces que se tiene que alquilar un carro para hacer reparación def __init__(self, modelo, marca, precio_alquiler, precio_reparacion): """ Constructor de la clase Carro. Se inicializaron los atributos modelo, marca, precioAlquiler y precioReparación con los valores recibidos por parámetro. Los atributos total_alquileres, alquileres_desde_reparacion y kilometraje se inicializaron en cero :param modelo: Modelo del carro. != "". != None :param marca: Marca del carro. != "". != None :param precio_alquiler: Precio de alquiler del carro. > 0 :param precio_reparacion: Precio de reparación del carro. > 0 """ self.__modelo = modelo self.__marca = marca self.__precio_alquiler = precio_alquiler self.__precio_reparacion = precio_reparacion self.__alquilado = False self.__total_alquileres = 0 self.__kilometraje = 0 self.__alquileres_desde_reparacion = 0 @property def modelo(self): """ Retorna el modelo del carro :return: Modelo del carro """ return self.__modelo @property def marca(self): """ Retorna la marca del carro :return: Marca del carro """ return self.__marca @property def kilometraje(self): """ Retorna el kilometraje del carro :return: Kilometraje del carro """ return self.__kilometraje @property def precio_alquiler(self): """ Retorna el precio de alquiler del carro :return: Precio de alquiler del carro """ return self.__precio_alquiler @property def precio_reparacion(self): """ Retorna el precio de reparacion del carro :return: Precio de reparacion """ return self.__precio_reparacion @property def alquileres_desde_reparacion(self): """ Retorna la cantidad de veces que ha sido alquilado el carro desde su última reparación :return: Cantidad de alquileres desde última reparacion """ return self.__alquileres_desde_reparacion @property def total_alquileres(self): """ Retorna la cantidad total de veces que ha sido alquilado el carro :return: """ return self.__total_alquileres @property def alquilado(self): """ Indica si el carro está actualmente alquilado :return: True si el carro está alquilado. False de lo contrario. """ return self.__alquilado def alquilar(self): """ Alquila el carro cuando se cumplen las siguientes condiciones: 1. El carro no está alquilado 2. El kilometraje es menor al máximo kilmoetraje permitido Cuando el carro cumple las condiciones para ser alquilado: 1. El carro pasa a estado alquilado 2. Se incrementa en 1 el número total de alquileres 3. Se incrementa en 1 el número de veces que ha sido alquilado desde reparación :return: True si se pudo alquilar el carro. False en caso contrario. """ if( not self.__alquilado and self.__kilometraje < Carro.MAXIMO_KILOMETRAJE): self.__alquilado = True self.__total_alquileres += 1 self.__alquileres_desde_reparacion += 1 return self.__alquilado def devolver(self, kilometros): """ Devuelve el carro cuando se cumplen las siguientes condiciones: 1. El kilometraje reportado es mayor al registrado. 2. El carro está alquilado Cuando el carro cumple las condiciones para la devolución del carro 1. El carro pasa a estado alquilado 2. El kilometraje se actualiza con el valor pasado por parámetro :param kilometros: Cantidad de kilómetros con que se devuelve el carro. >= 0 :return: True si se pudo devolver el carro. False de lo contrario. """ if( kilometros > self.__kilometraje and self.__alquilado): self.__alquilado = False self.__kilometraje = kilometros return (not self.__alquilado) def reparar(self): """ Repara un carro cuando se cumplen las siguientes condiciones: 1. El carro no está alquilado y se cumple una entre 2 y 3 2. El kilometraje actual es mayor al kilometraje mínimo de reparación y se ha alquilado más de 2 veces después de la última reparación 3. La cantidad de veces que ha sido alquilado el carro después de la reparación es mayor al mínimo número de alquileres Cuando el carro cumple con las condiciones para la reparación: 1. Se reinicia el kilometraje del carro 2. Se reinicia el total de alquileres desde reparación. :return: True si se pudo reparar el carro. False en caso contrario. """ if( not self.__alquilado and ( ( self.__kilometraje > Carro.KILOMETRAJE_REPARACION and self.__alquileres_desde_reparacion > 2 ) or ( self.__alquileres_desde_reparacion > Carro.MINIMO_NUM_ALQUILER) ) ): self.__kilometraje = 0 self.__alquileres_desde_reparacion = 0 return True return False
91034674d978bf5525e64678ca56d57c66397a2a
Ananthu/think-python-solutions
/9.03.py
192
3.9375
4
word = str("steven") string = str("qx") def avoids(word, string): for letter in string: if letter in word: return False return True print avoids(word, string)
e9929a8a5af50bba2e1a55e1b3af275a95525896
GINK03/atcoder-solvers
/arc002_a.py
147
3.53125
4
Y = int(input()) if Y%400 == 0: print('YES') exit() if Y%100 == 0: print('NO') exit() if Y%4 == 0: print('YES') exit() print('NO')
ca0285ab474a9b123b20f7aba5394cb65c085866
charlesluch/Code
/Scripting_tutes_labs/Lab_9 (named 8)/q1.py
442
4.1875
4
# 1. Modify the stack class in the lecture notes to make a queue class. Name it “queue”. #! /usr/bin/env python3 class Queue(object): # "A class implementing a queue data structure." def __init__(self): self.thequeue = [] def queue(self, a): # "Make a value enter the back of the queue thequeue[0]." self.thequeue.insert(0,a) def leave(self): # "Make a value leave the front of the queue." return self.thequeue.pop()