blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
19e41d802893cecc1696d60f0bdba0f0b37fbe00
mshkdm/python_TheHardWay
/def_math.py
742
3.859375
4
def addition(a, b): print "%d plus %d:" % (a, b) return a + b def subtraction(a, b): print "%d minus %d" % (a, b) return a - b def multiplication(a, b): print "%d times %d" % (a, b) return a * b def division(a, b): print "%d devide %d" % (a, b) return a / b my_age = addition(20, 2) my_salary = subtraction(1000, 1000) my_bitcoin_wallet = multiplication(10, 10) my_iq = division(100, 1) print "my age is: %d, my salary is: %d, my bitcoins: %d, my_iq: %d" % (my_age, my_salary, my_bitcoin_wallet, my_iq) weird_string = addition(my_age, subtraction(my_salary, multiplication(my_bitcoin_wallet, division(my_iq, 4)))) print "the result of that weird_string is: " + str(weird_string) + ". Insane, isn't it?"
2e717f7d0655c94d9418f5bbcbab06e52b9dd4ca
JuanGinesRamisV/prueba
/p5e7.py
225
3.828125
4
#juan gines ramis vivancos p5e7 print('introduce la altura de tu trianuglo') altura = int(input()) anchura = altura for i in range(altura): print() anchura = altura-(1*i) for i in range(anchura): print('*', end='')
2f641407953a4ac12554fa669db3d207ed84eeba
JuanGinesRamisV/prueba
/ejercicio 1 practica 3.py
108
3.765625
4
#juan gines ramis vivancos práctica 3 ej1 print('introduzca su nombre') nombre = str(input()) print ('su nombre es', nombre,)
e6d2083ca51095635b17398a2beaa08378f92293
TestowanieAutomatyczneUG/laboratorium-11-marekpolom
/tests/test_friendships.py
1,960
3.5625
4
import unittest from unittest.mock import * from sample.friendships import FriendShips class TestFriendships(unittest.TestCase): def test_make_friends(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") self.assertEqual(temp.data, {"Kowalski": ["Nowak"], "Nowak": ["Kowalski"]}) def test_make_friends_2(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") temp.makeFriends("Kowalski", "Kwiatkowski") self.assertEqual(temp.data, {"Kowalski": ["Nowak", "Kwiatkowski"], "Nowak": ["Kowalski"], "Kwiatkowski": ["Kowalski"]}) def test_make_friends_again(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") temp.makeFriends("Kowalski", "Nowak") self.assertEqual(temp.makeFriends("Kowalski", "Nowak"), 'Already friends!') def test_get_friends_list(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") self.assertEqual(temp.getFriendsList("Kowalski"), ["Nowak"]) def test_get_friends_list_error(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") with self.assertRaises(KeyError): temp.getFriendsList("Kwiatkowski") def test_are_friends_true(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") temp.makeFriends("Kowalski", "Kwiatkowski") self.assertTrue(temp.areFriends("Kowalski", "Kwiatkowski")) def test_are_friends_false(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") temp.makeFriends("Kowalski", "Kwiatkowski") self.assertFalse(temp.areFriends("Nowak", "Kwiatkowski")) def test_are_friends_error(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") with self.assertRaises(KeyError): temp.areFriends("Kwiatkowski", "Kowalski") if __name__ == '__main__': unittest.main()
91855199661a07b6d4c2c3c4a97791445d32cd91
37stu37/Hikurangi_mhzrd
/mhzrd_hikurangi.py
666
3.5625
4
import pandas as pd import numpy as np import os def Earthquake(): # select a source area to trigger an earthquake # sample the probability magnitude relationship log(N) = a-bMw # generate shaking from Openquake maps def Landslide(): # get the shaking at node location # get the landslide suscpetibility # sample from the area / volume relationship # get a volume and runout + target node def Tsunami(): # where is the source ? # calculate Ht for all target areas (Bij) using the Earthquake Mw Ht = 10^Mw-Bij # from the distance to shore value, calculate the Water depth Wd = (Ht*2) - (distance from shore in meters/400)
de1515c2150e80505cca6fbec738b38bc896487f
KarenRdzHdz/Juego-Parabolico
/parabolico.py
2,756
4.34375
4
"""Cannon, hitting targets with projectiles. Exercises 1. Keep score by counting target hits. 2. Vary the effect of gravity. 3. Apply gravity to the targets. 4. Change the speed of the ball. Integrantes: Karen Lizette Rodríguez Hernández - A01197734 Jorge Eduardo Arias Arias - A01570549 Hernán Salinas Ibarra - A01570409 15/09/2021 Exercises marked by ***ejercicio realizado*** """ "Libraries used" from random import randrange from turtle import * from typing import Sized from freegames import vector "Global variables used in game" ball = vector(-200, -200) speed = vector(0, 0) gravity = 25 s = 200 targets = [] count = 0 def changeGravity(value): "Set gravity to global variable" global gravity gravity = value def changeSpeed(sp): # ***Exercise 4: change speed*** "Set speed to global variable" global s s = sp def tap(x, y): "Respond to screen tap." if not inside(ball): ball.x = -199 ball.y = -199 speed.x = (x + 200) / gravity speed.y = (y + 200) / gravity def inside(xy): "Return True if xy within screen." return -200 < xy.x < 200 and -200 < xy.y < 200 def draw(): "Draw ball and targets." clear() for target in targets: goto(target.x, target.y) dot(20, 'blue') if inside(ball): goto(ball.x, ball.y) dot(6, 'red') update() def move(): "Move ball and targets." if randrange(40) == 0: y = randrange(-150, 150) target = vector(200, y) targets.append(target) for target in targets: target.x -= 0.5 target.y -= 0.5 # ***Exercise 3: add gravity to targets*** if inside(ball): speed.y -= 0.35 ball.move(speed) dupe = targets.copy() targets.clear() for target in dupe: if abs(target - ball) > 13: targets.append(target) draw() "Count balls hit" # ***Exercise 1: count balls hit*** if len(dupe) != len(targets): global count diferencia = len(dupe)-len(targets) count += diferencia style = ('Courier', 30, 'bold') write(count, font=style, align='right') # Game never ends remove condition # ***Exercise 5: Game never ends*** #for target in targets: #if not inside(target): #return ontimer(move, s) setup(420, 420, 370, 0) hideturtle() up() tracer(False) listen() onkey(lambda: changeGravity(50), 'a') # ***Exercise 2: vary the effect of gravity*** onkey(lambda: changeGravity(25), 's') onkey(lambda: changeGravity(12), 'd') onkey(lambda: changeSpeed(100), 'q') onkey(lambda: changeSpeed(50), 'w') onkey(lambda: changeSpeed(25), 'e') onscreenclick(tap) move() done()
d32a35c007a710be6b852da523df21c8276a708d
ALai2/AWS-Flask-ML-App
/application/clean_info.py
1,337
3.546875
4
import keywords_dict as kd keywords = kd.get_keywords() def key_replace(x): if isinstance(x, str): for k in keywords: if str.lower(x).strip() in keywords[k]: return k return x else: return '' # Function to convert all strings to lower case and strip names of spaces def clean_data(x): if isinstance(x, list): return [str.lower(i).strip() for i in x] else: #Check if item exists. If not, return empty string if isinstance(x, str): # check dictionary return str.lower(x).strip() elif isinstance(x, int): return str(x) else: return '' def replace_space(x): return (x.replace(" ", "")).replace(",", " ") def trim_str(x): return x.strip() import pandas as pd # Load data from csv and organize def clean_df(m0, features, clean, key): for feature in features: m0[feature] = m0[feature].apply(clean_data) if feature in clean: m0[feature] = m0[feature].apply(replace_space) if feature in key: m0[feature] = m0[feature].apply(key_replace) return m0 # mylist = ['one','two','three'] # mylist.append(mylist[len(mylist)-1] + " " + mylist[len(mylist)-2]) # mylist.remove(mylist[len(mylist)-1]) # print(mylist)
d304780068e23850918d3670e21b4119963533fa
PluxMinux/Boxes_method
/main.py
663
4.0625
4
import encryption e_key = input("Key: ").upper() e_msg = input("Messege: ").upper() print("\nPress 1 for Encryption.") print("Press 2 for Decryption.") e_d = input("\nSelect: ") if e_d == "1": print("\nEncrypted Message: ", encryption.encrypt(e_key,e_msg)) elif e_d == "2": print("\nDecrypted Message: ", encryption.decrypt(e_key,e_msg)) else: print("\nInvalid Key: 1 or 2 only.") #Sample #Key: space | Key: red #Message: tommorow are quiz | Message: kill the bug #Encrypted Message: MWU MAI ORZ OOQ TRE | Encrypted Message: LHU ITB KLEG
9eabe314f17a7234abe20a782814d96d09d2580e
AakashSasikumar/StockMate
/DataStore/APIInterface.py
6,434
3.5
4
import yfinance as yf from lxml.html import fromstring import random import requests import os import pandas as pd class YFinance(): """A wrapper for the Yahoo Finance API This is actually a wrapper over a wrapper. This was done to implement some more specific behavior over the original. Attributes ---------- autoRotate: bool A feature that allows you to break the barrier of api limits. When provided a list of apiKeys, it will automatically rotate them along with different proxies to get data suffix: str A string indicating which exchange we want to get the stock data from intraDayIntervals: list A list of intervals supported by this API proxyList: list A list of proxy addresses """ def __init__(self, autoRotate=False, exchange="NSE"): self.autoRotate = autoRotate if exchange == "NSE": self.suffix = ".NS" else: self.suffix = "" if self.autoRotate: self.proxyList = self.getProxies() self.intraDayIntervals = ["1m", "2m", "5m", "15m", "30m", "1h"] def getIntraDay(self, ticker, start=None): """Method to get the intra-day data for a stock Parameters ---------- ticker: str The name of the stock start: str, optional A date indicating from which day we need the data. If None, returns the entire historical data Returns ------- data: pandas.DataFrame The dataframe object of the raw ticker data """ tickerSymbol = ticker+self.suffix tickerObj = yf.Ticker(tickerSymbol) interval = "1d" if start is None: period = "max" args = {"interval": interval, "period": period} return self.getData(tickerObj, args) else: start = start args = {"interval": interval, "start": start} return self.getData(tickerObj, args) def getInterDay(self, ticker, interval): """Method to get the inter-day data for a stock Parameters ---------- ticker: str The name of the stock interval: str The interval width of the data. The list of supported intervals are in the self.intraDayIntervals object. Returns ------- data: pandas.DataFrame The dataframe object of the raw ticker data """ tickerSymbol = ticker + self.suffix tickerObj = yf.Ticker(tickerSymbol) if interval == "1m": period = "7d" elif interval != "1m" and interval in self.intraDayIntervals: period = "60d" args = {"period": period, "interval": interval} return self.getData(tickerObj, args)[:-1] def getData(self, tickerObj, arguments): """Method to get the raw ticker data Parameters ---------- tickerObj: yfinance.Ticker The ticker object of the yfinance module arguments: dict A dictionary containing the parameters for getting the raw ticker data Returns ------- data: pandas.DataFrame The dataframe of the raw ticker data """ if self.autoRotate: proxy = random.choice(self.proxyList) else: proxy = None return tickerObj.history(proxy=proxy, **arguments) while True: try: data = tickerObj.history(proxy=proxy, **arguments) break except Exception as e: print(e) self.proxyList.remove(proxy) proxy = random.choice(self.proxyList) return data def saveIntraDay(self, ticker, start=None, savePath="DataStore/StockData"): """Method to save the ticker data to a specified location Parameters ---------- ticker: str The name of the stock start: str, optional A date indicating from which day we need the data. If None, returns the entire historical data """ data = self.getIntraDay(ticker, start=None) if not os.path.isdir(savePath+"/1D"): os.mkdir(savePath+"/1D") savePath = savePath + "/1D/{}.csv".format(ticker) data.to_csv(savePath) def saveInterDay(self, ticker, interval, savePath="DataStore/StockData"): """Method to save the interday data to a specified location Parameters ---------- ticker: str The name of the stock interval: str The interval width of the data. The list of supported intervals are in the self.intraDayIntervals object. """ savePath = savePath + "/{}".format(interval).upper() if not os.path.isdir(savePath): os.mkdir(savePath) data = self.getInterDay(ticker, interval) data.index.names = ["Date"] savePath = savePath + "/{}.csv".format(ticker) if os.path.isfile(savePath): # append to existing file oldData = pd.read_csv(savePath, index_col="Date", parse_dates=["Date"]) oldData = oldData.sort_index(ascending=True) data = data[data.index > oldData.index[-1]] data = pd.concat([oldData, data]) data.to_csv(savePath) def getProxies(self, num=20): """Method to scrape/load the list of valid proxies Parameters ---------- num: int The number of proxy addresses to scrape Returns ------- proxyList: list A list of all proxy addresses """ proxyList = [] # if "proxies.txt" in os.listdir(): # with open("proxies.txt") as f: # lines = f.readlines() # for line in lines: # proxyList.append(line.strip()) # return proxyList url = 'https://free-proxy-list.net/' response = requests.get(url) parser = fromstring(response.text) for i in parser.xpath('//tbody/tr')[:num]: proxy = ":".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]]) proxyList.append(proxy) return proxyList
02a01f7bc44fcdb31cef4c4ae58ea0b1ea573326
imruljubair/imruljubair.github.io
/_site/teaching/material/Functions_getting_started/16.py
235
4.15625
4
def main(): first_name = input('Enter First Name: ') last_name = input('Enter Last Name: ') print('Reverse: ') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) main()
23e4678e79473596cb5d8742831ad45fe4e42b97
imruljubair/imruljubair.github.io
/_site/teaching/material/Dictionary/3.py
153
3.828125
4
# Adding list as values for keys..... card = {} for letter in ["A", "B", "C", "D", "E"]: card[letter] = [] # empty list print(card)
627a95962abed7b46f673bf813375562b3fa1cd2
imruljubair/imruljubair.github.io
/teaching/material/List/7.py
413
4.375
4
# append() # Example 7.1 def main(): name_list = [] again = 'y' while again == 'y': name = input("Enter a name : ") name_list.append(name) print('Do you want to add another name ?') again = input('y = yes, anything else = no: ') print() print('The names you have listed: ') for name in name_list: print(name) main()
0c110fece3e121665c41b7f1c039c190ed1b7866
imruljubair/imruljubair.github.io
/teaching/material/List/5.py
268
4.28125
4
# Concating and slicing list # Example 5.1 list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print(list3) # Example 5.2 days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satureday'] mid_days = days[2:5] print(mid_days)
29a2a6bd2c367d30c883bfae9b2a8fa3deb5ceab
imruljubair/imruljubair.github.io
/teaching/material/Loop/2.py
115
4.09375
4
number = int(input("How long you want to add?: ")) sum = 0 for i in range(0,number+1): sum = sum + i print(sum)
6399bf8b03d1f6ef5a68bec3b6cc8baa26000edc
imruljubair/imruljubair.github.io
/_site/teaching/material/Functions_getting_started/17.py
266
4.4375
4
def main(): first_name = input('Enter First Name: ') last_name = input('Enter Last Name: ') N = reverse_name(first_name, last_name) print('Reverse: '+str(N)) def reverse_name(first, last): name = last+' '+ first return name main()
bd91c66c02435f8b47dea4f9275dc8a4f4e6c1ae
imruljubair/imruljubair.github.io
/_site/teaching/material/Functions_getting_started/5.py
217
3.703125
4
#Using variables from function to function def main(): get_name() print('Hi, ', name) # this will cause an error print('welcome') def get_name(): name = input('enter your name: ') main()
4cada66802a9817ec054ef1e6de12abcfff077fc
visitmsuresh/Python-Concepts
/task programs-formula7py.py
54
3.65625
4
r=int(input()) h=int(input()) pi=r**2*h print(pi)
82276c3aed35b68b4133264cd1ff40b7782dd0d2
MPTauber/Numpy
/MyArrays.py
1,674
3.875
4
## pip install numpy --user ## ctrl, SHIFT,P --> Python: Start REPL import numpy as np '''integers = np.array([x for x in range(2,21,2)]) ## gives even number (third values means steps of 2) print(integers) two_dim = np.array([[1,2,3],[4,5,6]]) ## dont forget inital [] around the two sets of bracketed lists print(two_dim) ## Find the type fo elements in array print(integers.dtype) ## Find the number of dimensions print(two_dim.ndim) ## Find shape print(two_dim.shape) ## Find total number of elements in array print(two_dim.size) ##Find number of bytes of item print(two_dim.itemsize) ## byte PER ITEM --> since it's 4, the whole array takes up 24 bytes (since 4x6 = 24) ##### CTRL+K+C comments out block print(np.full((3,5),13)) # np.full() let's zou specify number (13 in our case). Produces 3 rows, 5 elements of the number 13 print(np.arange(5)) # makes a range 0-4 print(np.arange(5,10)) # starts at 5, ends at 9 print(np.arange(5,1,-2)) # starts at 5 and goes down in increments of 2 print(np.linspace(0.0,1.0,num=6)) array1 = np.arange(1,21) # makes range from 1-20 print(array1) array2 = array1.reshape(4,5) ## arranges arra1 in shape of 4 rows, 5 items each print(array2) array3 = np.arange(1,100_001).reshape(4,25_000) ## shapes numbers 1-100,000 into an array of 4 rows and 25,000 columns. ### This doesnt show middle because it's too large print(array3) array4 = np.arange(1,100_001).reshape(100,1000) print(array4) ''' numbers = np.arange(1,6) print(numbers**2) # numbers += 10 # print(numbers) numbers2 = np.linspace(1.1,5.5,5) print(numbers2) print (numbers * numbers2) print(numbers >= 3) #gives logical array print(numbers2 < numbers)
17f5b5f1d7d79dff3c1eed3ef569397d10fa43a4
kilicars/WheelOfFortune
/board.py
1,832
3.65625
4
import json import random import constants class Board: def __init__(self, file): self.file = file self.category = "" self.phrase = "" self.guessed_letters = [] def get_phrases(self): with open(self.file, "r") as f: phrases = json.loads(f.read()) return phrases # Returns a category & phrase (as a tuple) to guess # Example: # ("Artist & Song", "Whitney Houston's I Will Always Love You") def get_random_category_and_phrase(self): phrases = self.get_phrases() category = random.choice(list(phrases.keys())) phrase = random.choice(phrases[category]) return category, phrase.upper() def set_category_phrase(self): self.category, self.phrase = self.get_random_category_and_phrase() # Given a phrase and a list of guessed letters, returns an obscured version # Example: # guessed: ['L', 'B', 'E', 'R', 'N', 'P', 'K', 'X', 'Z'] # phrase: "GLACIER NATIONAL PARK" # returns> "_L___ER N____N_L P_RK" @staticmethod def obscure_phrase(phrase, guessed): result = "" for s in phrase: if (s in constants.LETTERS) and (s not in guessed): result = result + "_" else: result = result + s return result # Returns a string representing the current state of the game def get_current_board(self): return f"Category: {self.category}\nPhrase: {self.obscure_phrase(self.phrase, self.guessed_letters)}\n" \ f"Guessed: {', '.join(sorted(self.guessed_letters))}" def add_guessed_letter(self, letter): self.guessed_letters.append(letter) def is_phrase_revealed(self): return self.obscure_phrase(self.phrase, self.guessed_letters) == self.phrase
aea3ddf894c253cfe9bcdae7a3878f67bf76a5b7
softwaresaved/docandcover
/fileListGetter.py
1,118
4.375
4
import os def fileListGetter(directory): """ Function to get list of files and language types Inputs: directory: Stirng containing path to search for files in. Outputs: List of Lists. Lists are of format, [filename, language type] """ fileLists = [] for root, dirs, files in os.walk(directory): for filename in files: file_extention = filename.split(".")[-1] languageType = getLanguageType(file_extention) filename = os.path.join(root, filename) fileLists.append([filename, languageType]) return fileLists def getLanguageType(file_extention): """ Function to assign language type based on file extention. Input: file_extention: String that lists file type. Output: languageType: string listsing identified language type. """ if file_extention == 'py': return 'python' else: return 'Unknown' def printFileLists(fileLists): """ Function to print out the contents of fileLists Main use is debugging """ for fileList in fileLists: print fileList
83b8e37944e3615d2db07ad95aec4c4d7579992d
skyrocxp/python_study
/exercises3.py
2,192
4.03125
4
# ZYF-03-基础-猜字游戏 # 10 < cost < 50的等价表达式 cost = 40 (10 < cost) and (cost < 50) # 使用int()将小数转换成整数,结果是向上取整还是向下取整 print (int(3.6)) # 写一个程序,判断给定年份是否为闰年 # 闰年,能被4整除的年份 # 我的代码 year = int(input('请输入一个年份')) if year % 4 == 0: print('该年为闰年') else: print('该年不是闰年') # 老师的代码 year = input('请输入一个年份') if year.isdigit(): year = int(year) if year % 4 == 0: print(str(year)+'年是闰年') else: print(str(year)+'年不是闰年') else: print('请输入阿拉伯数字') # 给用户三次机会,猜想我们程序生成的一个数字A,每次用户猜想提示用户大于还是小于A,三次机会后提示用户已经输掉了游戏 # 我的代码 import random a = random.randint(1,10) b = int(input('请输入一个1到10的数字:')) if int(a) == int(b): print('你好棒,答对啦!') exit() if int(b) > int(a): print('高了,再输入一次吧') if int(b) < int(a): print('低了,再输入一次吧') c = int(input()) if int(a) == int(c): print('你好棒,答对啦!') exit() if int(c) > int(a): print('高了,再输入一次吧') if int(c) < int(a): print('低了,再输入一次吧') d = int(input()) if int(a) == int(d): print('你好棒,答对啦!') exit() if int(d) > int(a): print('游戏结束,你输啦,答案是'+str(a)) if int(d) < int(a): print('游戏结束,你输啦,答案是'+str(a)) # 老师的代码 import random secret = random.randint(1,100) times = 3 #初始化用户的次数是3次 while times: num = input('请输入一个1到100的数字:') if num.isdigit(): tmp = int(num) if tmp == secret: print('你好棒,答对啦!') break elif tmp < secret: print('你的数字太小了!') times = times - 1 else: print('你的数字太大了!') times = times - 1 else: print('叫你输入数字') print('你的机会用完了!')
b39e036c77f2a03507d5f3e48a48c59e15126785
supergonzo812/Data-Structures
/binary_search_tree/binary_search_tree.py
4,289
4.21875
4
""" Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient at searching for a particular piece of data in the tree. This part of the project comprises two days: 1. Implement the methods `insert`, `contains`, `get_max`, and `for_each` on the BSTNode class. 2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods on the BSTNode class. """ from collections import deque class BSTNode: def __init__(self, value): self.value = value self.left = None self.right = None # Insert the given value into the tree def insert(self, value): if value < self.value: if self.left is None: self.left = BSTNode(value) else: self.left.insert(value) else: if self.right is None: self.right = BSTNode(value) else: self.right.insert(value) # Return True if the tree contains the value # False if it does not def contains(self, target): if self.value == target: return True if self.left and target < self.value: return self.left.contains(target) if self.right: return self.right.contains(target) return False # Return the maximum value found in the tree def get_max(self): # if self.value == None: # return if not self.right: return self.value else: return self.right.get_max() # Call the function `fn` on the value of each node def for_each(self, fn): fn(self.value) if self.right: self.right.for_each(fn) if self.left: self.left.for_each(fn) # Part 2 ----------------------- # Print all the values in order from low to high # Hint: Use a recursive, depth first traversal def in_order_print(self): if self.left: self.left.in_order_print() print(self.value) if self.right: self.right.in_order_print() # Print the value of every node, starting with the given node, # in an iterative breadth first traversal def bft_print(self): q = deque() q.append(self) while len(q) > 0: current_node = q.popleft() # check if this node has children if current_node.left: q.append(current_node.left) if current_node.right: q.append(current_node.right) print(current_node.value) # Print the value of every node, starting with the given node, # in an iterative depth first traversal def dft_print(self): print(self.value) if self.right: self.right.dft_print() if self.left: self.left.dft_print() # Stretch Goals ------------------------- # Note: Research may be required # # Print Pre-order recursive DFT def pre_order_print(self): # First return/print the value of the node. print(self.value) # Check if there is a left leaf, if so call call pre_order recursively on the leaf. if self.left: self.left.pre_order_print() # Check if there is a right leaf, if so call call pre_order recursively on the leaf. if self.right: self.right.pre_order_print() # # Print Post-order recursive DFT def post_order_print(self): # First check if there is a left leaf, if so, recursively call post_order_print on left leaf if self.left: self.left.post_order_print() # First check if there is a right leaf, if so, recursively call post_order_print on right leaf if self.right: self.right.post_order_print() # Return / print the value of self print(self.value) """ This code is necessary for testing the `print` methods """ bst = BSTNode(1) bst.insert(8) bst.insert(5) bst.insert(7) bst.insert(6) bst.insert(3) bst.insert(4) bst.insert(2) bst.bft_print() bst.dft_print() print("elegant methods") print("pre order") bst.pre_order_print() print("in order") bst.in_order_print() print("post order") bst.post_order_print()
3870904959fddbed67492507ad40db196b53acfa
arashsaber/Displaying-filters-of-a-convolutional-layer
/displayer.py
4,434
3.609375
4
""" Displaying the filters of a convolutional layer Arash Saber Tehrani """ import numpy as np import tflearn import matplotlib.pyplot as plt # --------------------------------------- def filter_displayer(model, layer, padding=1): """ The function displays the filters of layer :param model: tflearn obj, DNN model of tflearn :param layer: string or tflearn obj., the layer whose weights we want to display :param padding: The number of pixels between each two filters :return: imshow the purput image """ if isinstance(layer, str): vars = tflearn.get_layer_variables_by_name(layer) variable = vars[0] else: variable = layer.W filters = model.get_weights(variable) print(filters.shape[0], filters.shape[1], filters.shape[2], filters.shape[3]) # n is the number of convolutions per filter n = filters.shape[2] * filters.shape[3]/2 # Ensure the output image is rectangle with width twice as # big as height # and compute number of tiles per row (nc) and per column (nr) nr = int(np.ceil(np.sqrt(n))) nc = 2*nr # Assuming that the filters are square filter_size = filters.shape[0] # Size of the output image with padding img_w = nc * (filter_size + padding) - padding img_h = nr * (filter_size + padding) - padding # Initialize the output image filter_img = np.zeros((img_h, img_w)) # Normalize image to 0-1 fmin = filters.min() fmax = filters.max() filters = (filters - fmin) / (fmax - fmin) # Starting the tiles filter_x = 0 filter_y = 0 for r in range(filters.shape[3]): for c in range(filters.shape[2]): if filter_x == nc: filter_y += 1 filter_x = 0 for i in range(filter_size): for j in range(filter_size): filter_img[filter_y * (filter_size + padding) + i, filter_x * (filter_size + padding) + j] = \ filters[i, j, c, r] filter_x += 1 # Plot figure plt.figure(figsize=(10, 5)) plt.axis('off') plt.imshow(filter_img, cmap='gray', interpolation='nearest') plt.show() # --------------------------------------- if __name__ == '__main__': from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression LR = 1e-3 height, width = 50, 50 net = input_data(shape=[None, height, width, 1], name='input') #net = batch_normalization(net, scope='bN1') net = conv_2d(net, 32, 5, activation='relu', scope='conv1', bias=True, weights_init=tflearn.initializations.xavier(uniform=False), bias_init=tflearn.initializations.xavier(uniform=False)) net = max_pool_2d(net, 5, 2, name='maxP1') net = dropout(net, 0.8, name='drop1') net = conv_2d(net, 64, 5, activation='relu', scope='conv2', bias=True, weights_init=tflearn.initializations.xavier(uniform=False), bias_init=tflearn.initializations.xavier(uniform=False)) net = max_pool_2d(net, 5, name='maxP2') net = dropout(net, 0.8, name='drop2') #net = batch_normalization(net,scope='bN2') net = conv_2d(net, 128, 5, activation='relu', scope='conv3', bias=True, weights_init=tflearn.initializations.xavier(uniform=False), bias_init=tflearn.initializations.xavier(uniform=False)) net = max_pool_2d(net, 5, name='maxP3') net = dropout(net, 0.8, name='drop3') net = fully_connected(net, 1024, activation='relu', scope='fc1', bias=True, weights_init=tflearn.initializations.xavier(uniform=False), bias_init=tflearn.initializations.xavier(uniform=False)) net = dropout(net, 0.8, name='drop4') net = fully_connected(net, 2, activation='softmax', scope='output') net = regression(net, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets') model = tflearn.DNN(net, tensorboard_dir='logs', tensorboard_verbose=3) # --------------------------------------- model_name = 'DogCatClassifier-{}.model'.format(LR) model.load('saved_models/'+model_name+'.tflearn') filter_displayer(model, layer='conv2', padding=1)
be446c4913f4788750712edd413343654e77b6c2
priyatiru/Problem-solving
/2dArray.py
420
3.53125
4
def hourglassSum(arr): count=0 for i in range(len(arr)-2): for j in range(len(arr)-2): sum= arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2] if sum>count: count = sum return count arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) result = hourglassSum(arr) print(result)
7cf496c794995c44017e54c597422ac6d64e2d2a
mfbx9da4/neuron-astrocyte-networks
/backup/mypybrain/misc/stack_overflow.py
1,722
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 17 20:01:07 2013 @author: david """ #learn digit classification with a nerual network import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure.modules import SoftmaxLayer from pybrain.utilities import percentError import numpy print "Importing training and test data" data = numpy.genfromtxt('trainR.csv', delimiter = ',') data = data[1:] traindata = data[:(len(data)/2)] testdata = data[(len(data)/2)+1:] print "Importing actual data" actualdata = numpy.genfromtxt('trainR.csv', delimiter = ',') print "Adding samples to dataset and setting up neural network" ds = ClassificationDataSet(784, 10, nb_classes = 10) for x in traindata: ds.addSample(tuple(x[1:]),tuple(x[0:1])) ds._convertToOneOfMany( bounds=[0,1] ) net = buildNetwork(784, 100, 10, bias=True, outclass=SoftmaxLayer) print "Training the neural network" trainer = BackpropTrainer(net, dataset=ds, momentum = 0.1, verbose = True, weightdecay = 0.01) for i in range(3): # train the network for 1 epoch trainer.trainEpochs( 1 ) # evaluate the result on the training and test data trnresult = percentError( trainer.testOnClassData(), [x[0] for x in traindata] ) # print the result print "epoch: " + str(trainer.totalepochs) + " train error: " + str(trnresult) print "" print "Predicting with the neural network" answerlist = [] for row in testdata: answer = numpy.argmax(net.activate(row[1:])) answerlist.append(answer) tstresult = percentError(answerlist, [x[0] for x in testdata]) print "Test error: " + str(tstresult)
fbd7f180535a42c13cc834b0a723d19454fbdf14
LeTond/DEV_PY110
/less04.py
10,299
3.890625
4
''' >>> import os.path >>> os.path.join("/tmp/1", "temp.file") # конкатенация путей '/tmp/1/temp.file' >>> os.path.dirname("/tmp/1/temp.file") # имя каталога по заданному полному пути '/tmp/1' >>> os.path.basename("/tmp/1/temp.file") # имя файла по заданному полному пути 'temp.file' >>> os.path.normpath("/tmp//2/../1/temp.file") # нормализация пути '/tmp/1/temp.file' >>> os.path.exists("/tmp/1/temp.file") # существует ли путь? False ''' import os.path # # print(os.path.join("/tmp/1", "temp.file")) # print(os.path.dirname("/tmp/1/temp.file")) # print(os.path.basename("/tmp/1/temp.file")) # print(os.path.normpath("/tmp//2/../1/temp.file")) # print(os.path.exists("/tmp/1/temp.file")) ''' Python по умолчанию достаточно просто работает с файлами операционной системы, в C-подобном стиле. Перед работой с файлом надо его открыть с помощью команды open Результатом этой операции будет указатель на файл, в котором указатель текущей позиции поставлен на начало или конец файла. # f = open("path/to/file", "filemode", encoding="utf8") f = open(“path/to/file”, “rt”, encoding=“utf8”) “path/to/file” – путь до файла, можно указывать в Unix-style (path/to/file) или в Windows-style (path\\to\\file) “rt” – режим, в котором файл нужно открывать. Записывается в виде строки, состоит из следующих букв: r – открыть на чтение (по умолчанию) w – перезаписать и открыть на запись x – создать и открыть на запись (если уже есть – исключение) a – открыть на дозапись (указатель будет поставлен в конец) t – открыть в текстовом виде (по умолчанию) b – открыть в бинарном виде encoding – указание, в какой кодировке файл записан (utf8, cp1251 и т.д.) При открытии файла в режимах на запись ставится блокировка на уровне операционной системы ''' # f = open("test.txt", 'a') # # f2 = open("1.txt", 'r') # # f.write("This is a test string\n") # print(f.tell()) # # f = open('test.txt', 'r', encoding='utf-8') # print(f.tell()) # # print(f.read(10)) # print(f.tell()) # # f.seek(15) # print(f.read()) ''' Чтение и запись построчно ''' # f = open("test.txt", 'a', encoding='utf-8') # sequence = ["other string\n", "123\n", "test test string\n"] # f.writelines(sequence) # ''' Запись в файл ''' # for line in sequence: # f.write(line) # f.write('\n') # # f.close() # f = open("test.txt", 'r', encoding='utf-8') # print(f.readline()) # print(f.read(5)) # print(f.readline()) # # for line in f: # print(line.strip()) # f.close() # # print(f) # print(iter(f)) # # id(f) == id(iter(f)) ''' Менеджер контекста with Для явного указания места работы с файлом, а также чтобы не забывать закрыть файл после обработки, существует менеджер контекста with. В блоке менеджера контекста открытый файл «жив» и с ним можно работать, при выходе из блока – файл закрывается. Менеджер контекста неявно вызывает закрытие файла после работы ''' # f = open("test.txt", 'r', encoding='utf-8') # with open("test.txt", 'rb') as f: # a = f.read(10) # b = f.read(23) # c = f.read(45) # print(a) # print(b) # print(c) # f.read(3) ''' Сериализация Сериализация – процесс перевода какой-либо структуры данных в другой формат, более удобный для хранения и/или передачи. Основная задача сериализации – эффективно (т.е. обычно с наименьшим размером) сохранить или передать данные, при условии, что их можно десериализовать в исходные. Чаще всего это работа на низком уровне с байтами и различными структурами. Но не обязательно. ''' ''' JSON – JavaScript Object Notation – текстовый формат обмена данными. Легко читаем людьми, однозначно записывает данные, подходит для сериализации сложных структур. Много используется в вебе. ''' import json # print(json.dumps([1, 2, 3, {'4': 5, '6': 7}])) # print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))) # print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], indent=4)) # Задаем отступ # print(json.dumps([(1, 2, 3), (4, 5, 6)], indent='\t')) # json не поддерживает tuple # def check_code_decode_json(src): # json_str = json.dumps(src) # python_obj = json.loads(json_str) # # python_obj = json.loads(json_str, parse_int=True) # # print('src:', src) # print('json:', json_str) # print('result', python_obj) # # return src == python_obj # # src = [1, 2, 3, {'4': 5, '6': 7}] # # src = [(1, 2, 3)] # С тюпл не работает # check_code_decode_json(src) # print(check_code_decode_json(src)) ''' Не путайте dumps с dump, а loads с load! Последние функции предназначены для работы с каким-либо источником (файлом, потоком данных и т.д.) ''' # FileName = "test.txt" # src = [1, 2, 3, {'4': 5, '6': 1700}] # # with open(FileName, 'w') as file: # # file.write(json.dumps(src)) # json.dump(src, file) # # with open(FileName) as f: # python_obj = json.load(f) # # print(python_obj) ''' Pickle Сериализация в JSON полезна в мире веба, если вам нужно что-то сохранить на диск – используется бинарная сериализация. Самый популярный модуль для бинарной сериализации – Pickle. Сохраняет объекты в бинарный формат, который потом можно восстановить при другом запуске или на другом устройстве. Вследствие развития получилось, что у pickle есть несколько протоколов. Сохранять и загружать нужно с одним и тем же, по умолчанию в Python3 протокол – 3. ''' ''' В языке Python существуют и другие способы сериализации: Если объект можно перевести в байт-массив – можно с помощью struct перевести и сохранить в файл (преимущества – можно распарсить на другом языке) Если объект – NumPy массив, можно использовать np.save, np.savetxt, np.savez, np.savez_compressed Для хранения больших файлов (астрономические данные, веса больших нейронных сетей и т.д.) используется формат HDF5. Работа с такими файлами в Python осуществляется с помощью библиотеки h5py и методов create_dataset, File и т.д. Многие модули имеют собственные методы для сериализации данных (часто в основе – pickle или struct) ''' ''' Парсинг аргументов командной строки Официально запуск вашего скрипта выглядит следующим образом: /path/to/python.exe /path/to/file.py Сначала идет команда, которую нужно выполнить, далее – аргументы, которые в нее подаются, например, путь до скрипта. Аргументов может быть несколько. /path/to/python.exe /path/to/file.py –v –b –i “Test” Каждое слово (разделенное пробелом) – отдельный аргумент. ''' import sys print(sys.argv) # /path/to/python.exe /path/to/file.py # if len(sys.argv) < 2: # print("Мало") # elif len(sys.argv) > 3: # print("Много") # else: # print(f"Hello {sys.argv[1]}. Count: {sys.argv[2]}") # import argparse # # def create_parser(): # parser = argparse.ArgumentParser() # parser.add_argument('name', nargs="?", default=False) # создадим один необязательный позиционный аргумент # return parser # # if __name__ == "__main__": # parser = create_parser() # namespace = parser.parse_args() # print(namespace) # # if namespace.name: # print("привет, {}!".format(namespace.name)) # else: # print("Привет, Мир!") import argparse def create_parser(): parser = argparse.ArgumentParser() parser.add_argument('-name', nargs="?", dest='my_arg') # создадим один необязательный позиционный аргумент return parser if __name__ == "__main__": parser = create_parser() namespace = parser.parse_args() print(namespace) if namespace.name: print("привет, {}!".format(namespace.name)) else: print("Привет, Мир!")
36b0c1000d57e2b1058477025476a4cd564c975d
DuskPiper/Code-Puzzle-Diary
/LeetCode 0103 Binary Tree Zigzag Level Order Traversal.py
1,272
3.796875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # 99% Time, 60% RAM def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] stack = [root] # 流水线,所有数据都要后进前出一遍 ans = [] reverser = -1 # 用来确定该行是否reverse的,1则不reverse,-1则reverse while stack: # 单次loop对应树的一层 reverser = -reverser # 每层都改编一次reverser,达到zigzag效果 curLayer = [] # 本层的答案 for i in range(len(stack)): # 单次loop对应本层的单个数据,因为是BFS,顺序是本层左->右 node = stack.pop(0) # for循环会把该层所有元素从前面pop完 if node.left: stack.append(node.left) if node.right: stack.append(node.right) # 先左后右丢下一层的node进stack尾部 curLayer.append(node.val) # 记录答案进层答案 ans.append(curLayer[::reverser]) # 根据reverse信息记录本层答案 return ans
91b76a73d397f4820a23ff8aa6c0ddc3a00b204c
DuskPiper/Code-Puzzle-Diary
/LeetCode 1644 Lowest Common Ancestor of a Binary Tree II.py
1,111
3.609375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # 5 28 def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ def dfs(root, target): if not root: return None if root == target: return [root] leftRes = dfs(root.left, target) if leftRes: return [root] + leftRes rightRes = dfs(root.right, target) if rightRes: return [root] + rightRes return None pTrace = dfs(root, p) qTrace = dfs(root, q) if not pTrace or not qTrace: return None for i in range(min(len(pTrace), len(qTrace))): if pTrace[i] != qTrace[i]: return pTrace[i - 1] return qTrace[-1] if len(pTrace) > len(qTrace) else pTrace[-1]
c911e5db782c6320a69349ec9dd00e5cbf2c6109
DuskPiper/Code-Puzzle-Diary
/LeetCode 0075 Sort Colors.py
1,003
3.703125
4
class Solution(object): # 100%, 0% def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ zero_boarder = 0 # 此下标之前的部分已经全是0 two_boarder = len(nums) - 1 # 此下标之后的部分已经全是2 i = 0 # iterator while i <= two_boarder: while i < two_boarder and nums[i] == 2: # 一定要先操作2,先操作0的话,下标zero_boarder跟着移动会漏掉后面的2需要swap的 # swap(i, two_boarder) nums[i] = nums[two_boarder] #这两行是swap nums[two_boarder] = 2 #这两行是swap,2是写死的,等同nums[i] two_boarder -= 1 while i > zero_boarder and nums[i] == 0: # swap(i, zero_boarder) nums[i] = nums[zero_boarder] nums[zero_boarder] = 0 zero_boarder += 1 i += 1
26c107898fe41622d8abbc4c8b8d34f3116bc58d
DuskPiper/Code-Puzzle-Diary
/LeetCode 0490 The Maze.py
1,099
3.53125
4
class Solution: # 86 71 def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: rmax, cmax = len(maze), len(maze[0]) visited = set([]) q = [(start[0], start[1])] while q: r, c = q.pop() if r == destination[0] and c == destination[1]: return True visited.add((r, c)) # Find where can we reach leftMost = c while leftMost > 0 and maze[r][leftMost - 1] == 0: leftMost -= 1 rightMost = c while rightMost < cmax - 1 and maze[r][rightMost + 1] == 0: rightMost += 1 upMost = r while upMost > 0 and maze[upMost - 1][c] == 0: upMost -= 1 downMost = r while downMost < rmax - 1 and maze[downMost + 1][c] == 0: downMost += 1 for x, y in ((r, leftMost), (r, rightMost), (upMost, c), (downMost, c)): if (x, y) not in visited: q.append((x, y)) return False
a4b7855e174ee9ad620faf9b24ec1a8f938eadea
DuskPiper/Code-Puzzle-Diary
/LeetCode 0022 Generate Parentheses.py
803
3.5
4
class Solution: def generateParenthesis(self, n): """ :type n: int :rtype: List[str] 是一个递归的问题(但是可以用迭代代码实现 对于n的答案,其实是对n-1的答案的演绎,对n-1每个元素都进行以下两种操作之一: 1.在整个外面套一层() 2.在每个可能的slot(其实是所有length内所有下标)插入一个() 由此可以得到n的答案 以空string "" 为n=0的答案,由此可以递归演绎到n的答案 """ ans,i=set([""]),0 while i<n: ans_lo=ans.copy() ans=set() for x in ans_lo: ans.add("("+x+")") for j in range(len(x)): ans.add(x[:j]+"()"+x[j:]) i+=1 return list(ans)
273f5ce45b5bb1f787254540352893d4fad276eb
DuskPiper/Code-Puzzle-Diary
/LeetCode 1404 Number of Steps to Reduce a Number in Binary Representation to One.py
430
3.53125
4
class Solution: # 96 63 def numSteps(self, s: str) -> int: carry = 0 step = 0 for i in xrange(len(s) - 1, 0, -1): if int(s[i]) + carry == 1: # odd, +1÷2 => carry 1 to upper level, and remove current level (0) carry = 1 step += 2 else: # even, ÷2 => remove current level (0) step += 1 return step + carry
cbf78c124ce092e4d52d91baf052c9d79f7b07f7
lsDantas/Hacker-s-Guide-to-Neural-Networks-in-Python
/svm.py
5,096
3.703125
4
import math import random class Unit: def __init__(self, value, grad): # Value computed in the forward pass self.value = value # The derivative of circuit output w.r.t. this unit, computed in backward pass self.grad = grad class MultiplyGate(object): def __init__(self): pass def forward(self, u0, u1): # Store pointers to input Units u0 and u1 and output unit utop self.u0 = u0 self.u1 = u1 self.utop = Unit(u0.value * u1.value, 0.0) return self.utop def backward(self): # Take the gradient in output unit and chain # it with the local gradients, which we # derived for multiply gates before, then # write those gradients to those Units. self.u0.grad += self.u1.value * self.utop.grad self.u1.grad += self.u0.value * self.utop.grad class AddGate(object): def __init__(self): pass def forward(self, u0, u1): # Store pointers to input units self.u0 = u0 self.u1 = u1 self.utop = Unit(u0.value + u1.value, 0.0) return self.utop def backward(self): # Add Gate. Derivative wrt both inputs is 1 self.u0.grad += 1 * self.utop.grad self.u1.grad += 1 * self.utop.grad class SigmoidGate(object): def __init__(self): pass # Helper Function def sig(self, x): return 1 / (1 + math.exp(-x)) def forward(self, u0): self.u0 = u0 self.utop = Unit(self.sig(self.u0.value), 0.0) return self.utop def backward(self): s = self.sig(self.u0.value) self.u0.grad += (s * (1 - s)) * self.utop.grad class Circuit(): def __init__(self): self.mulG0 = MultiplyGate() self.mulG1 = MultiplyGate() self.addG0 = AddGate() self.addG1 = AddGate() def forward(self, x,y,a,b,c): self.ax = self.mulG0.forward(a,x) self.by = self.mulG1.forward(b,y) self.axpby = self.addG0.forward(self.ax, self.by) self.axpbypc = self.addG1.forward(self.axpby, c) return self.axpbypc def backward(self, gradient_top): self.axpbypc.grad = gradient_top self.addG1.backward() self.addG0.backward() self.mulG1.backward() self.mulG0.backward() # SVM class class SVM(): def __init__(self): # Random Initial Parameter Values self.a = Unit(1.0, 0.0) self.b = Unit(-2.0, 0.0) self.c = Unit(-1.0, 0.0) self.circuit = Circuit() def forward(self, x,y): # Assume x and y are Units self.unit_out = self.circuit.forward(x,y, self.a, self.b, self.c) return self.unit_out def backward(self, label): # Label is +1 or -1 # Reset pulls on a,b,c self.a.grad = 0.0 self.b.grad = 0.0 self.c.grad = 0.0 # Compute the pull based on what the circuit output was pull = 0.0 if(label == 1 and self.unit_out.value < 1): # The score was too low: pull up. pull = 1 if(label == -1 and self.unit_out.value > -1): # The score was too high for a positive example: pull down. pull = -1 self.circuit.backward(pull) # Add regularization pull for parameters: toward zero and proportional to value self.a.grad += -self.a.value self.b.grad += -self.b.value def learnFrom(self, x,y,label): # Forward pass (set .value in all Units) self.forward(x,y) # Backward Pass (set .grad in all Units) self.backward(label) # Parameters respond to through self.parameterUpdate() def parameterUpdate(self): step_size = 0.01 self.a.value += step_size * self.a.grad self.b.value += step_size * self.b.grad self.c.value += step_size * self.c.grad data = [] labels = [] data.append([1.2, 0.7]) labels.append(1) data.append([-0.3, -0.5]) labels.append(-1) data.append([3.0, 0.1]) labels.append(1) data.append([-0.1, -1.0]) labels.append(-1) data.append([-1.0, 1.1]) labels.append(-1) data.append([2.1, -3]) labels.append(1) svm = SVM() # A function that computes the classification accuracy def evalTrainingAccuracy(): num_correct = 0 for i in range(0, len(data)): x = Unit(data[i][0], 0.0) y = Unit(data[i][1], 0.0) true_label = labels[i] # See if the prediction matches the provided label if(svm.forward(x, y).value > 0): predicted_label = 1 else: predicted_label = -1 if(predicted_label == true_label): num_correct += 1 return num_correct/len(data) # The Learning Loop for iter in range(0, 400): # Pick a Random Data Point i = math.floor(random.random() * len(data)) x = Unit(data[i][0], 0.0) y = Unit(data[i][1], 0.0) label = labels[i] svm.learnFrom(x, y, label) if( iter % 25 == 0): # Every 10 interations... print("Training accuracy at iter " + str(iter) + ": " + str(evalTrainingAccuracy()))
309345f381b0576b3057b747da65578024f62a02
fantashley/scrabble-api-python
/board_game.py
1,552
3.640625
4
from collections import namedtuple class BoardGame: # Board coordinates BOARD_X = None BOARD_Y = None SQUARE_TYPES = {} SQUARE_COORDS = {} TILES = {} Square = namedtuple("Square", "tile type") SquareMultiplier = namedtuple("SquareMultiplier", "letter word") Tile = namedtuple("Tile", "count value") def __init__(self, default_square_type): self.default_square = self.Square(None, default_square_type) self.board = [] self.__populate_board() def __populate_board(self): # Populate with default squares for i in range(self.BOARD_Y): row = [] for j in range(self.BOARD_X): square = self.default_square row.append(square) self.board.append(row) # Populate special types for square_type in self.SQUARE_COORDS: for y, x in self.SQUARE_COORDS[square_type]: # Quadrant 1 self.board[y][self.BOARD_X - 1 - x] = self.Square(None, square_type) # Quadrant 2 self.board[y][x] = self.Square(None, square_type) # Quadrant 3 self.board[self.BOARD_Y - 1 - y][x] = self.Square(None, square_type) # Quadrant 4 self.board[self.BOARD_Y - 1 - y][self.BOARD_X - 1 - x] = \ self.Square(None, square_type)
084744ae994df621efafbc7429b1ed971be533a4
J-woooo/acmicpc
/5585.py
334
3.84375
4
def greedyChange(coin, money): count = 0 i = 0 while(money != 0): if(coin[i] <= money): money -= coin[i] count += 1 else: i += 1 return count count = 0 coin = [500, 100, 50, 10, 5, 1] price = int(input("")) money = 1000-price print(greedyChange(coin, money))
6b6af3ba954b7dd15178eeb1fdb2abbe42c7284a
beenjammin/AssistantBrewer
/Scripts/probeTypes/Float_Switch.py
1,409
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 12 11:23:08 2020 @author: pi """ try: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) except: pass from time import sleep class FloatSwitch(): """a class to handle the float switch pin, integer - the pin on the GPIO board that float switch is connected to switch, boolean - by default, a signal (true) from the float switch will turn the relays with the associated hardware off and vice versa """ def __init__(self, pin, switch=False): self.pin = pin self.switch = switch self.lastState = switch self.thisState = switch GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) def poll(self): input_state = GPIO.input(self.pin) self.lastState = self.thisState self.thisState = input_state def switchState(self): self.poll() if self.thisState != self.lastState: if self.thisState == self.switch: print('switch is false and relays connected to hw can be turned on') else: print('switch is true and relays connected to hw will be turned off') return True else: return False if __name__ == "__main__": fs = FloatSwitch(24) while True: if fs.switchState(): print(fs.thisState) sleep(1)
185753e77b00d7d077ac46c7b099ed46a5e82203
waiteb15/py3forsci3day
/lamda_functions.py
649
3.875
4
#!/usr/bin/env python # Return Value # lambda param-list: expression # only use lambda's when you are passing functions def doit(func): result = func() print(result) def hello(): return "HELLO" #call back functions doit(hello) doit(lambda : "wombats!") fruits = ["pomegranate", "cherry", "apricot", "apple", "lemon", "kiwi", "orange", "lime", "watermelon", "guava", "papaya", "fig", "pear", "banana", "tamarind", "persimmon", "elderberry", "peach", "Blueberry", "lychee", "grape", "date" ] print(sorted(fruits, key =lambda tre: tre.lower())) #inline Anomonyus funciton
f35afb7c52705c6067bdf0133df11358099ffaf4
waiteb15/py3forsci3day
/tuple_examples.py
1,055
3.703125
4
#!/usr/bin/env python person = 'Bill', 'Gates', 'Microsoft' junk1 = 'hello' # string junk2 = 'hello', # tuple print(person, len(person), person[0]) def greet(whom): print("Hello,", whom[0]) greet(person) first_name, last_name, product = person print(first_name, last_name, '\n') people = [ ('Melinda', 'Gates', 'Gates Foundation'), ('Steve', 'Jobs', 'Apple'), ('Larry', 'Wall', 'Perl'), ('Paul', 'Allen', 'Microsoft'), ('Larry', 'Ellison', 'Oracle'), ('Bill', 'Gates', 'Microsoft'), ('Mark', 'Zuckerberg', 'Facebook'), ('Sergey','Brin', 'Google'), ('Larry', 'Page', 'Google'), ('Linus', 'Torvalds', 'Linux'), ('John', 'Strickler'), ('Joe', 'Schmoe', 'MyProduct1', 'MyProduct2', 'MyProduct3'), ] for first_name, last_name, *products in people: # first_name, last_name, product = people[0] # first_name, last_name, product = people[1] # first_name, last_name, product = people[2] # ... print(first_name, last_name, products) print()
efb473a71123b8e6b4c31555e37a9bd82f74ec09
waiteb15/py3forsci3day
/io_examples.py
1,070
4.03125
4
#!/usr/bin/env python import getpass name = 'Anne' color = 'red' value = 27 print(name, color, value) print(name, color, value, sep='/') print('name', end="=>") print(name) with open('DATA/mary.txt') as mary_in: for raw_line in mary_in: line = raw_line.rstrip() print(line) with open('DATA/mary.txt') as mary_in: contents = mary_in.read() with open('DATA/mary.txt') as mary_in: lines = mary_in.readlines() fruits = ["pomegranate", "cherry", "apricot", "apple", "lemon", "kiwi", "orange", "lime", "watermelon", "guava", "papaya", "fig", "pear", "banana", "tamarind", "persimmon", "elderberry", "peach", "blueberry", "lychee", "grape", "date" ] with open('fruits.txt', 'w') as fruits_out: for fruit in fruits: fruits_out.write(fruit + '\n') full_name = input("PLease enter your full name? ") names = full_name.split() if len(names) < 2: full_name = input("Unless you're Cher or DeadMau5? Please enter your full name: ") password = getpass.getpass("Enter your password:")
ac3d8240eb5970374d0a0bf3f10199b63434f7c0
waiteb15/py3forsci3day
/EXAMPLES/pandas_selecting.py
1,023
3.75
4
#!/usr/bin/env python """ @author: jstrick Created on Sun Jun 9 21:36:10 2013 """ from pandas.core.frame import DataFrame from printheader import print_header cols = ['alpha','beta','gamma','delta','epsilon'] index = ['a','b','c','d','e','f'] values = [ [100, 110, 120, 130, 140], [200, 210, 220, 230, 240], [300, 310, 320, 330, 340], [400, 410, 420, 430, 440], [500, 510, 520, 530, 540], [600, 610, 620, 630, 640], ] df = DataFrame(values, index=index, columns=cols) print_header('DataFrame df') print(df, '\n') # select a column print_header("df['alpha']:") print(df['alpha'], '\n') # same as above print_header("df.alpha:") print(df.alpha, '\n') # slice rows print_header("df['b':'e']") print(df['b':'e'], '\n') # slice columns print_header("df[['alpha','epsilon','beta']]") print(df[['alpha','epsilon','beta']]) print() print(df['b':'b'],'\n \n') print(df.head()) print('\n',df.tail(),'\n') print(df.shape) print(df.describe())
aab502d04412167c2797bcbb7592221221966274
waiteb15/py3forsci3day
/ANSWERS/date_delta.py
473
4.09375
4
#!/usr/bin/python import sys import datetime if len(sys.argv) < 3: print("Please enter two dates in format YYYY-MM-DD") sys.exit(1) year, month, day = sys.argv[1].split("-") this_date = datetime.date(int(year), int(month), int(day)) year, month, day = sys.argv[2].split("-") that_date = datetime.date(int(year), int(month), int(day)) elapsed = that_date - this_date print("%d years %d days" % (elapsed.days / 365.25, elapsed.days % 365.25))
b713cfeb2d4ceb7eed21df67ffffefaaed03a1d9
waiteb15/py3forsci3day
/EXAMPLES/datetime_ex.py
821
3.734375
4
#!/usr/bin/python3 from datetime import datetime,date,time,timedelta print("date.today():",date.today()) now = datetime.now() print("now.day:",now.day) print("now.month:",now.month) print("now.year:",now.year) print("now.hour:",now.hour) print("now.minute:",now.minute) print("now.second:",now.second) d1 = datetime(2007,6,13) d2 = datetime(2007,8,24) d3 = d2 - d1 print("raw time delta:",d3) print("time delta days:",d3.days) interval = timedelta(10,0,0,0,0,0) print("interval:",interval) d4 = d2 + interval d5 = d2 - interval print("d2 + interval:",d4) print("d2 - interval:",d5) t1 = datetime(2007,8,24,10,4,34) t2 = datetime(2007,8,24,22,8,1) t3 = t2 - t1 print("datetime(2007,8,24,10,4,34):",t1) print("datetime(2007,8,24,22,8,1):",t2) print("time diff (t2 - t1):",t3)
0020353624117615495ebdba328323478038dd34
waiteb15/py3forsci3day
/csv_examples.py
909
3.84375
4
#!/usr/bin/env python import csv with open('DATA/presidents.csv') as pres_in: rdr = csv.reader(pres_in) for row in rdr: term, first_name, last_name, birthplace, birth_state, party = row term = int(term) print(last_name, party) print('-' * 60) with open('DATA/presidents.tsv') as pres_in: rdr = csv.reader(pres_in, delimiter='\t') for row in rdr: print(row) print('-' * 60) fruits = ["pomegranate", "cherry", "apricot", "apple", "lemon", "kiwi", "orange", "lime", "watermelon", "guava", "papaya", "fig", "pear", "banana", "tamarind", "persimmon", "elderberry", "peach", "blueberry", "lychee", "grape", "date" ] with open('fruitinfo.csv', 'w') as fruitinfo_out: wtr = csv.writer(fruitinfo_out, quoting=csv.QUOTE_ALL) for fruit in fruits: data = [fruit[0].upper(), fruit, len(fruit)] wtr.writerow(data)
b519465696765d49dd7279157de55c47be275cfd
waiteb15/py3forsci3day
/EXAMPLES/generator_expression.py
797
3.8125
4
#!/usr/bin/python import re # sum the squares of a list of numbers # using list comprehension, entire list is stored in memory s1 = sum([x*x for x in range(10)]) # only one square is in memory at a time with generator expression s2 = sum(x*x for x in range(10)) print(s1,s2) print() # set constructor -- does not put all words in memory pg = open("../DATA/mary.txt") s = set(word.lower() for line in pg for word in re.split(r'\W+',line)) pg.close() print(s) print() keylist = ['OWL','Badger','bushbaby','Tiger','GORILLA','AARDVARK'] # dictionary constructor d = dict( (k.lower(),k) for k in keylist) print(d) print() # with open("../DATA/mary.txt") as M: max_line_len = max(len(line) for line in M if line.strip()) print("Max line len:", max_line_len) 2
7714e16790dbfe022f4a86f3639c306808b919f6
waiteb15/py3forsci3day
/EXAMPLES/time_ex.py
490
3.71875
4
#!/usr/bin/python3 import sys import time right_now = time.time() print("It is {0} seconds since 1/1/70".format(right_now)) time.sleep(5) now_asc = time.asctime() print("it is now",now_asc) now_ctime = time.ctime() print("it is now",now_ctime) time_str = "Jan 14, 1971" print('Time string:',time_str) parsed_time = time.strptime(time_str, '%b %d, %Y') print("Parsed time is",parsed_time) print('Formatted time:',time.strftime("%m/%d/%y %I:%M",parsed_time))
a2c4fea201b97fe3367cb0f2e4aab0cfc842bbe9
waiteb15/py3forsci3day
/EXAMPLES/slicing.py
950
3.875
4
#!/usr/bin/python fruits = ['watermelon', 'apple', 'kiwi', 'lime', 'orange', 'cherry', 'banana', 'raspberry', 'grape', 'lemon', 'durian', 'guava', 'mango', 'papaya', 'mangosteen', 'breadfruit'] s = slice(5) # first 5 print(fruits[s]) print() s = slice(-5,None) # last 5 print(fruits[s]) print() s = slice(3,8) # 4th through 8th print(fruits[s]) print() s = slice(None,None,2) # every other fruit starting with element 0 print("slice(None,None,2)", fruits[s]) print('-' * 50) seq = ('red', 5, 'blue', 3, 'yellow', 7, 'purple', 2, 'pink', 8) key_slice = slice(None,None,2) # even elements print("keys:", seq[key_slice]) value_slice = slice(1,None,2) # odd elements print("values:", seq[value_slice]) kv_tuples = list(zip(seq[key_slice], seq[value_slice])) # generates key/value pairs as tuples color_dict = dict(kv_tuples) # initialize a dictionary from key/value pairs print("color_dict:", color_dict)
f6bc859f0fe1d5d1b8a7075b37bfca3cd311362d
jihunparkme/Problem-Solving
/PS_Study/BOJ/1920.py
422
3.78125
4
def binarySearch(N, A, key): lt, rt = 0, N-1 while lt <= rt: mid = (lt + rt) / 2 if A[mid] == key: return 1 elif A[mid] > key: rt = mid - 1 else: lt = mid + 1 return 0 N = int(input()) A = list(map(int, input().split())) M = input() B = list(map(int, input().split())) A.sort() for n in B: res = binarySearch(N, A, n) print(res)
8d16160a858fd7f6ec6c66aec68388d5cd65f2b6
joshanstudent/DPWP
/Madlib/main.py
1,794
4.09375
4
# My MadLib Program by Joseph Handy # This a title print "Welcome to my game!" # Guess the number import random guesses = 0 first = raw_input("What is your first name? ") number = random.randint(1,5) # Print out results print first + ", I am thinging of a number between 1 and 5 " # loop while guesses < 3: guess = int(raw_input("Take a guess. ")) guesses = guesses + 1 if guess < number: print "Your guess is too low!" if guess > number: print "Your guess is too high!" if guess == number: break if guess == number: guesses = str(guesses) print "Good job, " + first + " You guessed my number in " + guesses + " guesses" if guess != number: number = str(number) print "Nope. The number I was thinking about was actually " + number # Input data last = raw_input("Enter last name: ") city = raw_input("Enter your city: ") state = raw_input("Enter your state: ") address = raw_input("Enter your address: ") zip = raw_input("Enter your zip code: ") bathroom = ['floor', 'tube', 'wall'] #array additional = raw_input("Please add another task to do within your bathroom: ") # Print out results print "Hello ", first, last, "I see that you are looking for repairs within your house in", city, state, "at", address, zip, print bathroom print "additional task to fix within your bathroom is", additional, # Math def calcArea(h, w): area = h * w return area a = calcArea(40, 60); # Print out results print "with an area space of " + str(a) + "sqft" # Dictionary Object, I used this to update input data update = dict() update = {"wall":'Made update and change request from "wall" to "tiles" to be fix.'} print update["wall"] # Math a = 2400 print "Total for your bathroom repairs is $",eval('a * .75'), "dollars"
ebac95e891d818f1127e20969b9797da5c96d33e
bhaveshbaranda/library
/library.py
395
3.5625
4
import argparse parser = argparse.ArgumentParser(description='Add two numbers') parser.add_argument('--a', type = int ,metavar = '',required=True, help = 'First Number') parser.add_argument('--b', type = int ,metavar = '',required=True, help = 'Second Number') args = parser.parse_args() def myAdd(a,b): return a+b if __name__ == "__main__": print(myAdd(args.a,args.b))
d9cd91999238b4f74e30c66145cb7cecd38b2de4
Floou/python-basics
/200914/01.lists.py
546
3.828125
4
#student_marks = [] #while True: # mark = input('введите оценку студента:\n') # if mark: # student_marks.append(mark) # else: # break # #print('ввод завершен') #print(student_marks) mock_student_mark = ['5', '4', '3', '2', '5'] student_marks = mock_student_mark i = 0 avg_mark = 0 while i < len(student_marks) : #print(type(avg_mark), type(student_marks[i])) avg_mark +=int(student_marks[i]) i += i + 1 avg_mark /= len(student_marks) print('средний балл',avg_mark)
96b6fc9a3737846372715a16a7e96c5331bd2746
danny1000008/dec_to_roman
/tests.py
816
3.78125
4
import unittest from number import Number class decimalTestCase(unittest.TestCase): def test_1_is_roman_numeral_I(self): test_num = Number(1) self.assertTrue(test_num.convert_to_roman() == 'I') def test_2000_is_roman_numeral_MM(self): test_num = Number(2000) self.assertTrue(test_num.convert_to_roman() == 'MM') def test_minus_1_is_not_valid_input(self): test_num = Number(-1) self.assertFalse(test_num.convert_to_roman()) def test_I_is_decimal_1(self): test_num = Number('I', 'roman') self.assertTrue(test_num.convert_to_decimal() == 1) def test_MM_is_decimal_2000(self): test_num = Number('MM', 'roman') self.assertTrue(test_num.convert_to_decimal() == 2000) if __name__ == '__main__': unittest.main()
64a76f29640cfc0e116a2870d5393ab355c1e9d1
luke-hta/learn2git
/one_random_number.py
123
3.578125
4
import random print('Here is one random number between 1 and 3!') print(1 + 2 * random.random()) print('You\'re welcome!')
29e2f29b85215ff541c096551b39f8a3c223cede
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/2 week(loops-if-else)/sum_square.py
88
3.5625
4
n = int(input()) sum_sq = 0 while n != 0: sum_sq += n ** 2 n -= 1 print(sum_sq)
a7bc9fe5aaa1a6e847e49d7bcf3abfae6dfbdf00
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/8 week (paradigma)/5.py
362
3.5
4
""" На вход подаётся последовательность натуральных чисел длины n ≤ 1000. Посчитайте произведение пятых степеней чисел в последовательности. """ from functools import reduce print(reduce((lambda x, y: (x * y)), map(int, input().split())) ** 5)
b2a23485ea9b7c0a0a9cce101c020ee580b25431
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.4(replace-count)/1.py
207
3.5625
4
""" Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов. """ text = input() print(text.count(' ') + 1)
2a5d79386af0ae70441f607e383f3b7c61d7ef6e
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/5 week (list, set, for)/5.1(tuple, range)/3.py
316
3.59375
4
""" Дано натуральное число n. Напечатайте все n-значные нечетные натуральные числа в порядке убывания. """ n = int(input()) max_res = 10 ** n - 1 min_res = 10 ** (n - 1) for i in range(max_res, min_res - 1, -2): print(i, end=' ')
b71f08a1f51b10852a93f6ff23546806ba7472fe
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/7 week (set and dict)/7.2 (Dict)/5.py
509
3.859375
4
""" Дан текст. Выведите слово, которое в этом тексте встречается чаще всего. Если таких слов несколько, выведите то, которое меньше в лексикографическом порядке. """ file = open('input.txt') myDict = {} for word in file.read().split(): myDict[word] = myDict.get(word, 0) + 1 myList = sorted(myDict.items()) myList.sort(key=lambda x: x[1], reverse=True) print(myList[0][0])
b27bccccc94b7c0ebf3620bcd4f0c67801c18315
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/6 week (sort)/1.py
1,063
3.90625
4
""" Даны два целочисленных списка A и B, упорядоченных по неубыванию. Объедините их в один упорядоченный список С (то есть он должен содержать len(A)+len(B) элементов). Решение оформите в виде функции merge(A, B), возвращающей новый список. Алгоритм должен иметь сложность O(len(A)+len(B)). Модифицировать исходные списки запрещается. Использовать функцию sorted и метод sort запрещается. """ def merge(a, b): i = 0 j = 0 k = 0 c = list(range(len(a) + len(b))) while i < len(a) and j < len(b): if a[i] <= b[j]: c[k] = a[i] i += 1 else: c[k] = b[j] j += 1 k += 1 c[k:] = a[i:] + b[j:] return c A = list(map(int, input().split())) B = list(map(int, input().split())) print(*merge(A, B))
a5a247be32ad55eb47653a03a838578461345670
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/5 week (list, set, for)/5.1(tuple, range)/12.py
372
4
4
""" Даны два четырёхзначных числа A и B. Выведите все четырёхзначные числа на отрезке от A до B, запись которых является палиндромом. """ a, b = int(input()), int(input()) for i in range(a, b + 1): m = str(i) if m[0] == m[3] and m[1] == m[2]: print(i)
c571c4c36dbf81921bca4698ed33b166edef6480
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/4 week (fiunctions)/4.4(recursion)/9.py
334
3.921875
4
""" Дана последовательность чисел, завершающаяся числом 0. Найдите сумму всех этих чисел, не используя цикл. """ def my_sum(x): if x == 0: return x else: return x + my_sum(int(input())) n = int(input()) print(my_sum(n))
3c6ec8da3a07e7291823e088d450375f4d7f8280
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.4(replace-count)/5.py
293
3.8125
4
""" Дана строка. Получите новую строку, вставив между каждыми двумя символами исходной строки символ *. Выведите полученную строку. """ text = input() print(text.replace('', '*')[1:-1])
d553e8d28badaa94b4592ac6ac3a033ec7bd0d81
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.3(slice)/6.py
506
3.984375
4
""" Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в строку и выведите получившуюся строку. При решении этой задачи нельзя пользоваться циклами и инструкцией if. """ string = input() space = string.find(' ') print(string[space + 1:], string[:space])
06371106cc981aac3260a681d2868a4ccf24f5bf
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.3(slice)/2.py
782
4.28125
4
""" Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс. Если она встречается два и более раз, выведите индекс её первого и последнего появления. Если буква f в данной строке не встречается, ничего не выводите. При решении этой задачи нельзя использовать метод count и циклы. """ string = input() first = string.find('f') revers = string[::-1] second = len(string) - revers.find('f') - 1 if first == second: print(first) elif first == -1 or second == -1: print() else: print(first, second)
6b9179590f3a2bf82153a657064804ad0106a33b
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/2 week(loops-if-else)/num_polin.py
187
3.5625
4
n = int(input()) i = 1 counter = 0 while i <= n: int_to_str = str(i) reverse_num = (int_to_str[::-1]) if i == int(reverse_num): counter += 1 i += 1 print(counter)
407d7edba48b4a97c133ac7741ba6f1262cf3448
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/2 week(loops-if-else)/sum_follow.py
90
3.765625
4
n = int(input()) total = 0 while n != 0: total += n n = int(input()) print(total)
fe18a70582d9cd7d8d610b0b2a813a93fc9d3e5f
fantas1st0/network_scripts
/leetcode/top-interview-questions-easy/array/two_sum.py
730
4.0625
4
""" https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/546/ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. """ def main(nums, target): d = {} for i in range(len(nums)): if target - nums[i] in d: return i, d[target - nums[i]] d[nums[i]] = i if __name__ == "__main__": nums = [2,7,11,15] target = 6 i, j = main(nums, target) print(i, j)
ee8d032bb86b8f69a9c1f37f76ad888fe3eb563f
Tracy219/pieCharts
/pieCharts.py
1,139
3.578125
4
#!/usr/bin/env python import matplotlib matplotlib.use("agg") # the code 'import matplotlib.pyplot as plt' must come out after # import matplotlib and matplotlib.use("agg") import matplotlib.pyplot as plt labels = 'Reading', 'Sleeping', 'Others', 'Chatting' # Labels of the parts of the pie chart sizes = [15, 30.0, 45.0, 10] # Sizes of the parts of the carts colors = ['yellowgreen', 'gold', 'lightskyblue', 'red'] # Colors of the parts of the carts explode = (0, 0.1, 0, 0) # Explode means separate from the the graph, the numbers are the # distance of the part(s) from the main part plt.pie(sizes, explode = explode, labels = labels, colors = colors, autopct = '%0.1f%%', \ shadow = True) # sizes, explode(separate), labels, colors and autopct(can show the percent # of each part in the pie chart, '0.1' means the number will be the form xx.x(45.0)) plt.axis('equal') # x-axis and y-axis equals in this case, if x-axis is not equal to # y-axis, the form will be plt.axis(a, b, c, d)('a' for min of x-axis, 'b' for max of # x-axis, 'c' for min of y-axis, 'd' for max of x-axis) plt.show() plt.savefig("pieChartsExample.png")
707e6f8289e5fd9b8c7dea19a545e15aea587929
mostafaelgohry0/CSE-Courses
/AI/Robot_Emulator_final/Initial.py
1,787
3.671875
4
import Data import random class Initial: def __init__(self): self.chromosome = "" self.cost = 0 def set_height(self): h = random.randint(0, 3) self.chromosome = self.chromosome + Data.height[h][1] self.cost += Data.height[h][2] def set_width(self): w = random.randint(0, 3) self.chromosome = self.chromosome + Data.width[w][1] self.cost += Data.width[w][2] def set_speed(self): s = random.randint(0, 3) self.chromosome = self.chromosome + Data.speed[s][1] self.cost += Data.speed[s][2] def set_weight(self): g = random.randint(0, 3) self.chromosome = self.chromosome + Data.weight[g][1] self.cost += Data.weight[g][2] def set_material(self): m = random.randint(0, 3) self.chromosome = self.chromosome + Data.material[m][1] self.cost += Data.material[m][2] def set_wheelsnum(self): s = random.randint(0, 3) self.chromosome = self.chromosome + Data.wheelnum[s][1] self.cost += Data.wheelnum[s][2] def set_legsnum(self): l = random.randint(0, 3) self.chromosome = self.chromosome + Data.legnum[l][1] self.cost += Data.legnum[l][2] def set_limbs(self): r = random.randint(0, 1024) if r % 2 == 0: self.set_legsnum() self.chromosome += "0" else: self.set_wheelsnum() self.chromosome += "1" def create_chromosome(self): self.set_height() self.set_width() self.set_speed() self.set_material() self.set_weight() self.set_limbs() def get_chromosome(self): return self.chromosome def get_cost(self): return self.cost
777b1c54ca133bc9c82734c377f3b668bcf488ef
jaeheeLee17/BOJ_Algorithms
/Level3_ForStatements/11720.py
183
3.765625
4
def main(): N = int(input()) num_list = list(input()) total = 0 for num in num_list: total += int(num) print(total) if __name__ == "__main__": main()
203b06977b09e0d3c005a7797ff03fb4017a4973
jaeheeLee17/BOJ_Algorithms
/Level7_String/1316.py
607
3.953125
4
def groupword_checker(word): for i in range(len(word) - 1): if word[i] != word[i + 1]: if word[i] in word[i + 1:]: return False return True def count_group_words(word_list): groupword_cnt = 0 for word in word_list: if groupword_checker(word): groupword_cnt += 1 return groupword_cnt def main(): N = int(input()) word_list = [] for _ in range(N): word = input() word_list.append(word) group_word_cnt = count_group_words(word_list) print(group_word_cnt) if __name__ == "__main__": main()
a7b8ee727a6c139ff01d640a61d5aee451df1566
jaeheeLee17/BOJ_Algorithms
/Level7_String/2941.py
568
3.921875
4
def count_croatia_alpha(word): croatia_alpha_list = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='] croatia_alpha_cnt = 0 idx = 0 while len(word) > idx: if word[idx : idx + 2] in croatia_alpha_list: idx += 2 elif word[idx : idx + 3] in croatia_alpha_list: idx += 3 else: idx += 1 croatia_alpha_cnt += 1 return croatia_alpha_cnt def main(): word = input() croatia_alpha_num = count_croatia_alpha(word) print(croatia_alpha_num) if __name__ == "__main__": main()
6ede115cf6c103b9d518fa42aecbab018bb15062
gyubok-lee/algorithms
/week2/2_7.py
1,005
3.59375
4
# https://programmers.co.kr/learn/courses/30/lessons/42890 from itertools import combinations def solution(relation): rows = len(relation) cols = len(relation[0]) # 모든 조합 찾기 candidates = [] for i in range(1, cols + 1): candidates.extend(combinations(range(cols), i)) # 고유키 찾기 final = [] for keys in candidates: tmp = [tuple([item[key] for key in keys]) for item in relation] if len(set(tmp)) == rows: final.append(keys) # 후보키 찾기 answer = set(final[:]) for i in range(len(final)): for j in range(i + 1, len(final)): if len(final[i]) == len(set(final[i]).intersection(set(final[j]))): answer.discard(final[j]) return len(answer) rere= [["100","ryan","music","2"],["200","apeach","math","2"], ["300","tube","computer","3"],["400","con","computer","4"], ["500","muzi","music","3"],["600","apeach","music","2"]] print(solution(rere))
b8694f9b288a8904c59bb039cbcd1b29a9bc97c5
gyubok-lee/algorithms
/week7/7_2.py
1,987
3.5
4
# https://www.acmicpc.net/problem/16235 # 문제에서 주어진 조건을 빠짐없이 기록할것 def spring(): dead = [] for i in range(N): for j in range(N): if len(trees[i][j]) > 0: trees[i][j] = sorted(trees[i][j]) for k in range(len(trees[i][j])): if soil[i][j] < trees[i][j][k]: for _ in range(k,len(trees[i][j])): dead.append([i,j,trees[i][j][_]]) trees[i][j] = trees[i][j][:k] break else: soil[i][j] -= trees[i][j][k] trees[i][j][k] += 1 return dead def summer(dead): for i in dead: soil[i[0]][i[1]] += i[2]//2 return def autumn() : deltas = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)] growed = [] for i in range(N): for j in range(N): for k in range(len(trees[i][j])): if trees[i][j][k] % 5 ==0 and trees[i][j][k] >= 5: growed.append((i,j)) while growed : x,y = growed.pop() for d in deltas: nx, ny = x + d[0], y + d[1] if 0<=nx<N and 0<=ny<N : trees[nx][ny].append(1) return def winter(): for i in range(N): for j in range(N): soil[i][j] += feed[i][j] return if __name__ == '__main__' : N,M,K = map(int,input().split()) feed = [list(map(int, input().split())) for i in range(N)] soil = [[5]*N for i in range(N)] trees = [[[] for i in range(N)] for j in range(N)] for i in range(M): x,y,z = map(int,input().split()) trees[x-1][y-1].append(z) for _ in range(K): dead_trees = spring() summer(dead_trees) autumn() winter() cnt = 0 for i in range(N): for j in range(N): cnt += len(trees[i][j]) print(cnt)
da75c16f3f3c9d1d6f2d5822f48d82908133b407
gyubok-lee/algorithms
/week3/3_8.py
753
3.671875
4
# https://www.acmicpc.net/problem/2630 def check(x,y,n): if n == 1: return True for i in range(n): for j in range(n): if board[x+i][y+j] != board[x][y]: return False return True def divide(node): global blue global white x,y,size = node if check(x,y,size): if board[x][y] == 1: blue += 1 else: white += 1 else : ns = int(size/2) quadTree[node] = [(x,y,ns),(x+ns,y,ns),(x,y+ns,ns),(x+ns,y+ns,ns)] for i in quadTree[node]: divide(i) return N = int(input()) board = [list(map(int,input().split())) for i in range(N)] quadTree = dict() blue = 0 white = 0 divide((0,0,N)) print(white) print(blue)
384785ebd3f0e57cc68ac0cd00389f4bcfd8b245
AffanIndo/python-script
/caesar.py
702
4.21875
4
#!usr/bin/env python """ caesar.py Encrypt or decrypt text based from caesar cipher Source: http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python """ def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift if stayInAlphabet > ord('z'): stayInAlphabet -= 26 finalLetter = chr(stayInAlphabet) cipherText += finalLetter print("Your ciphertext is: ", cipherText) return cipherText if __name__ == '__main__': plainText = input("Insert your text:\n") shift = int(input("Insert how many shift:")) caesar(plainText, shift)
9f7de4fb5c580d257b47385f8342e126dba99b79
AffanIndo/python-script
/kasir.py
1,084
3.734375
4
""" kasir.py The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. """ from math import floor uang = int(input("Masukkan uang (Rp): ")) harga = int(input("Masukkan harga barang (Rp): ")) if (uang < harga): print("Uang kurang") else: kembalian = uang - harga print("Kembalian: " + str(kembalian)) sisa = kembalian print(str(floor(sisa / 100000)) + " x Rp100000") sisa = sisa % 100000 print(str(floor(sisa / 50000)) + " x Rp50000") sisa = sisa % 50000 print(str(floor(sisa / 20000)) + " x Rp20000") sisa = sisa % 20000 print(str(floor(sisa / 10000)) + " x Rp10000") sisa = sisa % 10000 print(str(floor(sisa / 5000)) + " x Rp5000") sisa = sisa % 5000 print(str(floor(sisa / 2000)) + " x Rp2000") sisa = sisa % 2000 print(str(floor(sisa / 1000)) + " x Rp1000") sisa = sisa % 1000 print(str(floor(sisa / 500)) + " x Rp500") sisa = sisa % 500 print("Sisa: Rp" + str(sisa))
afb0f6d0fdc125db455ac4b06330beacaf90e6fa
stoianmihail/EnsembleLearning
/classifiers/adaboost.py
9,074
3.53125
4
from classifiers.baseline import Classifier import numpy import math # The dataclass type and its features from dataclasses import dataclass from typing import List # The binary search for the performant prediction from bisect import bisect_left #### # A performant implementation with auto-tuning of AdaBoost ensemble learning algorithm #### class AdaBoost(Classifier): # The constructor def __init__(self, iterations = 0): self.MAX_T = iterations self.DEFAULT_NUM_LEARNERS = 5 self.MAX_EFFORT = 1e5 pass #### # A decision stump (one-level decision tree) #### @dataclass class Stump: error: float = 1 # Used for computing the minimum error alpha: float = 1 # This stump can be the best one feature: float = 0 threshold: float = 0 side: int = 0 # binary value: 0 -> less or equal values are "-", 1 -> otherwise PERM = numpy.array([[1, -1], [-1, 1]]) # Print the stump def __repr__(self) -> str: return "Stump: alpha=" + str(self.alpha) + " feature=" + str(self.feature) + " threshold=" + str(self.threshold) + " side=" + str(self.side) # Set the parameters when updating the best stump def setParameters(self, error, feature, threshold, side) -> None: self.error = error self.feature = feature self.threshold = threshold self.side = side # Compute alpha which reduces the error bound of the total error def computeAlpha(self) -> None: if not (self.error in [0, 1]): print(self.alpha) self.alpha = 0.5 * math.log((1 - self.error) / self.error) elif not self.error: self.alpha = math.inf else: self.alpha = -math.inf # Return the prediction of this stump def predict(self, sample) -> int: return self.PERM[self.side][int(sample[self.feature] <= self.threshold)] # Rescale the weights, as described in MIT youtube video (https://www.youtube.com/watch?v=UHBmv7qCey4) def updateWeights(self, X, y, weights, totalMinusWeight) -> None: # First compute alpha self.computeAlpha() # Remark: 'predict' returns a value from {-1, 1} and y is a binary value # Also update the sum of weights of those samples in the minus class totalMinusWeight[0] = 0 expr = [0.5 / self.error, 0.5 / (1 - self.error)] for index, sample in enumerate(X): weights[index] *= expr[int(int(self.predict(sample) > 0) == y[index])] totalMinusWeight[0] += weights[index] if not y[index] else 0 pass # Combine the prediction of this stump with its vote weight def vote(self, sample) -> float: return self.alpha * self.predict(sample) #### # End of the decision stump (one-level decision tree) #### # The fitter def fit(self, X, y) -> None: # Preprocess the data y = self.preprocessing(X, y, "withLists") # Initialize the weights weights = numpy.array([1.0 / self.size] * self.size) # Compute the initial weights of the "-" class totalMinusWeight = [(1.0 / self.size) * len(list(filter(lambda index: not y[index], range(self.size))))] # Compute the number of rounds to run T = self.MAX_T if not T: T = self.DEFAULT_NUM_LEARNERS if self.size < self.MAX_EFFORT: T = int(self.MAX_EFFORT / self.size) # And compute self.learners = [] for iteration in range(T): print("now: " + str(iteration)) learner = self.Stump() for feature in range(self.numFeatures): # Note that the last iteration is in vain # Why? It simply tells us if the entire column is either minus or plus # If we wanted to get rid of it, in preprocessing we could remove the feature which has only one value partialSumOfDeltas = 0 for (discreteValue, [minusList, plusList]) in self.store[feature]: partialSumOfDeltas += weights[plusList].sum() - weights[minusList].sum() # Compute the sum of weights of the mispredicted samples. # We can compute only the error when, for the current feature, # the samples with a less or equal value receive a 'minus' classification, # since the other case around is symmetric. minusError = partialSumOfDeltas + totalMinusWeight[0] plusError = 1 - minusError # And update the learner (only one error could influence the current learner) if minusError < min(plusError, learner.error): learner.setParameters(minusError, feature, discreteValue, 0) elif plusError < min(minusError, learner.error): learner.setParameters(plusError, feature, discreteValue, 1) # Compute alpha of learner and update weights if learner.error: learner.updateWeights(X, y, weights, totalMinusWeight) self.learners.append(learner) pass # Receives a query and outputs the hypothesis def predict(self, sample): H = 0 for learner in self.learners: H += learner.vote(sample) return int(H > 0) # Compute test accuracy def score(self, X, y, size = -1) -> float: # Check the test data self.checkTestData(X, y) tmp = self.learners if size != -1: tmp = self.learners[:size] # Put the learners with the same feature into the same bucket commonFeature = [] for feature in range(self.numFeatures): commonFeature.append(list()) for learner in tmp: commonFeature[learner.feature].append(learner) # Take only those features, the buckets of which are not empty mapFeature = [] for feature in range(self.numFeatures): if commonFeature[feature]: mapFeature.append(feature) # And get rid of those empty buckets commonFeature = list(filter(lambda elem: elem, commonFeature)) # We preprocess the sum votes from each classifier, by sorting the thresholds (which should be unique) # The first sum 'sumGreaterOrEqualThanSample' sums up the votes of those classifiers, the thresholds of which # are greater of equal than the value of the current sample # The second sum, in the same way, but note that the construction differs # In order to cover the case, in which a sample comes and its value is strictly greater than all thresholds # of the respective feature (in which case the binary search will return as index the size of learners), # we insert a sentinel at the end of 'votes' for each feature. prepared = [] onlyThresholds = [] for index, bucketList in enumerate(commonFeature): sortedBucketList = sorted(bucketList, key=lambda learner: learner.threshold) # Build up the partial sum 'sumGreaterOrEqualThanSample' # Note that we start from the beginning, since all elements which are on our right have a greater or equal threshold votes = [] sumGreaterOrEqualThanSample = 0 for ptr, learner in enumerate(sortedBucketList): votes.append(sumGreaterOrEqualThanSample) sumGreaterOrEqualThanSample += learner.alpha * learner.PERM[learner.side][int(False)] # And add the sentinel: gather all votes, when the value of the sample is simply strictly greater than all thresholds of this feature votes.append(sumGreaterOrEqualThanSample) # Build up the partial sum 'sumLowerThanSample' # Note that we start from the end, since all elements which are on our left have a threshold strictly lower than the threshold of the current learner sumLowerThanSample = 0 ptr = len(sortedBucketList) while ptr != 0: learner = sortedBucketList[ptr - 1] sumLowerThanSample += learner.alpha * learner.PERM[learner.side][int(True)] # And add it to the already computed partial sum in 'votes' votes[ptr - 1] += sumLowerThanSample ptr -= 1 # Add the votes of this feature and keep only the thresholds from each learner prepared.append(votes) onlyThresholds.append(list(map(lambda learner: learner.threshold, sortedBucketList))) # And compute the score correctClassified = 0 for index in range(self.size): # Note that 'shrinked' has already been sorted expected = int(y[index] == self.shrinked[1]) # This is an improved way to compute the prediction # If for any reasons, you want to go the safe way, # you can use the function 'self.predict(X[index])', which computes it in the classical way predicted = 0 for notNullFeature, votes in enumerate(prepared): # Note that 'votes' has a sentinel at the end to capture the case where the value of sample is strictly greater than all thresholds of 'mapFeature[notNullFeature]' pos = bisect_left(onlyThresholds[notNullFeature], X[index][mapFeature[notNullFeature]]) predicted += votes[pos] predicted = int(predicted > 0) correctClassified += int(expected == predicted) accuracy = float(correctClassified / self.size) return accuracy
02045de66eac587a4510f6a868a8a0fad0b1685c
anirudh99bot/Restaurant-Finder
/zomato.py
2,313
3.515625
4
import requests import json import random def SearchRestaurant() : params = { 'entity_id' : city_id, 'entity_type' : 'city', } response = requests.get('https://developers.zomato.com/api/v2.1/search', headers=headers, params=params) data = json.loads(response.text) #converting json file into python list n = data['results_shown'] i= 0 v=[] k=[data['restaurants'][i]['restaurant']['name']] for i in range (i,n): #for loop for getting all the restaurants in one list k=data['restaurants'][i]['restaurant']['name'] v.append(k) restaurant= v print("Your Restaurant: %s "%random.choice(restaurant)) def LocationAndEstimate() : from geopy.geocoders import Nominatim from geopy.distance import geodesic geolocator = Nominatim(user_agent="google maps", timeout=None) x = geolocator.geocode((a)) c =((x.latitude,x.longitude)) #Coordinates of current city print ("Current destination coordinates: ") print(c) city_2 = geolocator.geocode((city2)) d = ((city_2.latitude,city_2.longitude)) #Coordinates of destination city e =(geodesic(c,d).km) #Calculate the Distance between the two cities #Fare estimate w.r.t to Uber if ( e <= 20 ): fare = 60 + (e * 6) print("Your estimate fare for ride will be = %d Rs"%(fare)) elif (e > 20) : fare = 60 + (20 * 6 ) + ((e-20)*12) print("Your estimate fare for ride will be = %d Rs"%(fare)) else: print("No fare") if __name__ == "__main__": print("Welcome to Restaurant Finder") a=input("Enter current city : ") city2=input("Enter destination city: ") headers = { 'Accept': 'application/json', 'user-key': '8f43e5828484c5a3673c0ed6b14583b5', } params = { 'q': city2, } response = requests.get('https://developers.zomato.com/api/v2.1/cities', headers=headers, params=params) data=response.json() city_id = data['location_suggestions'][0]['id'] SearchRestaurant() LocationAndEstimate() print("Thank you for choosing our service")
6889a03ce265b3569258d07818044ae768c5ccc7
Florian-Moreau/maison
/data_manager/utils/file_manager.py
246
3.625
4
import os def list_files(path): return [name for name in os.listdir(path) if (os.path.isfile("{}/{}".format(path,name)))] def list_folders(path): return [name for name in os.listdir(path) if (os.path.isdir("{}/{}".format(path,name)))]
81a80dd01d35084988abe7748a317e28d56f4735
yrsong15/shuffle
/shuffle.py
1,468
4.09375
4
from random import randint from queue import * def shuffle_with_queue(artists, num_of_songs, init_val): list_length = 0 for elem in num_of_songs: list_length += elem res = [init_val] * list_length q = init_queue(list_length) #maybe consider using PQueue? def init_queue(list_length): q = Queue(maxsize=list_length) for i in range(list_length): q.put(i) return q def shuffle(artists, num_of_songs, init_val): list_length = 0 for elem in num_of_songs: list_length += elem res = [init_val] * list_length for i in range(len(artists)): song_number = num_of_songs[i] for j in range(song_number): max_offset = list_length / song_number offset = get_offset(max_offset) place(res, offset + (max_offset*j), init_val, artists[i]) return res def place(res, start_index, init_val, artist): i = start_index while res[i] != init_val: if i==len(res)-1: i = 0 else: i += 1 res[i] = artist def get_offset(max_offset): return randint(0, max_offset-1) if __name__ == '__main__': temp = raw_input("Enter the number of artists: ").strip() artist_number = int(temp) artists = [] num_of_songs = [] for i in range(artist_number): question = "What is the name of Artist " + str(i) + "? :" artist = raw_input(question) artists.append(artist) question = "How many songs does " + artist + " have? :" song_number = raw_input(question) num_of_songs.append(int(song_number)) res = shuffle(artists, num_of_songs, -1) print "RES: ", res
4ca600725e8a20b1710b0faba653edb55167d6ba
diego-d5000/algorithms
/sameStrings.py
208
3.6875
4
#Given 2 arrays of string, print an array of strings common in the two arrays def sameStrings(arg1, arg2): sameStrs = [] for i in arg1: for k in arg2: if k == i: sameStrs.append(k) print sameStrs
828d76bedb9a3ef460e719f6c589018c0c6b8f8b
foxcodenine/books
/Python 3 Object-Oriented Programming Third Edition/chapter-3/chapter3_1.py
3,144
4.21875
4
# Basic inheritance class Contact: all_contacts = [] def __init__(self, name, email): self.name = name self.email = email Contact.all_contacts.append(self) # The all_contacts list is shared by all inctances of the class because # it is part of the class definition. class Supplier(Contact): def order(self, order): return( "If this were a real system we would send" f" {order!r} order to {self.name!r}" ) # Trying above classes c = Contact("Some Body", "somebody@example.net") s = Supplier("Sup Plier", "supplier@example.net") print(c.name, c.email, s.name, s.email) print(s.all_contacts) print(s.order("I need coffee")) # print('\n\n') #_______________________________________________________________________ # Extending built-insjhf # extended list class ContactList(list): def search(self, name): """Return all contacts that contain the search value in their name.""" matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts class Contacts: all_contacts = ContactList() def __init__(self, name, email): self.name = name self.email = email Contacts.all_contacts.append(self) # Trying the above code: c1 = Contacts("John A", 'johna@example.net') c2 = Contacts("John B", 'johnb@example.net') c3 = Contacts("Jenna C", 'jennac@example.com') print(Contacts.all_contacts.search('John')) print([c.name for c in Contacts.all_contacts.search('John')]) print('\n\n') # extended dict class LongNameDict(dict): def longest_key(self): """ a function that return the longest key in the inctanse(that is a dict)""" longest = None for key in self: if not longest or len(key) > len(longest): longest = key return longest # Testing class LongName(dict) longkeys = LongNameDict() longkeys['hello'] = 1 longkeys['longest yet'] = 5 longkeys['hello2'] = 'world' print(longkeys.longest_key()) print('\n\n') #_______________________________________________________________________ # Overriding and super class Friend(Contacts): def __init__(self, name, email, phone): super().__init__(name, email) self.phone = phone # Trying class Friend(Contacts) J = Friend('James Magri', 'james.magri@gmail.com', 79797979) print(Contacts.all_contacts.search('James')) print([J.name, J.email, J.phone]) print('\n\n') #_______________________________________________________________________ #Multiple inheritance class MailSender: def send_mail(self, message): print("Sending mail to " + self.email) # Add e-mail logic here class EmailableContact(Contacts, MailSender): pass # Try classes MailSender and EmaiableContact: e = EmailableContact("John Smith", "johnsmith@writeme.com") print(Contacts.all_contacts) e.send_mail("Hello there! testing my e-mail here!") #_______________________________________________________________________
fcaebb4eab29606515f3e80bc7d9a6d9b8c1b8a3
Jeremalloch/Project_Euler
/Python/In Progress/Problem 267/Problem 267.py
994
3.875
4
def finalMoney(numWins, fValue): ''' Returns the amount of money returned with a given number of wins and a specific fValue (proportion of money being gambled with each turn, as a decimal). ''' return ((1+2*fValue)**numWins)*((1-fValue)**(1000-numWins)) - (10**9) def fMDerivative(numWins, fValue): ''' Derivative of the finalMoney function. ''' return 2*numWins*((1+2*fValue)**(numWins-1))*((1-fValue)**(1000-numWins)) - ((1+2*fValue)**numWins)*(1000-numWins)*((1-fValue)**(999-numWins)) fValMin = 0 fValMax = 1 numWins = 1000 fMinTemp = fValMin + 1 fMaxTemp = fValMax + 1 #print fValMin #print fMinTemp #Find lower bound of fVal #while (abs(fValMin-fMinTemp) > 10**-13): ##for x in range(2): ## fMinTemp = fValMin ## fValMin = fValMin - (finalMoney(1000,fValMin)/fMDerivative(1000, fValMin)) ## print fValMin # print fMinTemp #print fValMin #print (finalMoney(1000,fValMin)/fMDerivative(1000, fValMin)) print fMDerivative(1000,0.1)
ce7deae553575c90fdaf6bd9f1ab622841749202
Jeremalloch/Project_Euler
/Python/Completed Problems/Problem 2/Problem 2.py
237
3.546875
4
Fibonacci = [1,1,2] sum = 0 n=2 while Fibonacci[n] <= 4000000: Fibonacci.append(Fibonacci[n] + Fibonacci[n-1]) n+=1 for item in Fibonacci: if item <= 4000000 and item%2 == 0: sum+=item print(Fibonacci) print(sum)
2b0c73ae595c61e78780ace7d64021c54f47b702
ZCW-Data1dot2/scicalc-team-cocoa
/getValue.py
2,498
3.875
4
class Value: def getAddNum(self): global val_in_mem a = input("Enter the first number that you want to add: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the second number that you want to add: \n") if b == 'mrc': b = float(val_in_mem) else: b = float(b) return a, b def getSubNum(self): global val_in_mem a = input("Enter the first number that you want to subtract: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the second number that you want to subtract: \n") if b == 'mrc': b = float(val_in_mem) else: b = float(b) return a, b def getMultiNum(self): global val_in_mem a = input("Enter the first number that you want to multiply: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the second number that you want to multiply: \n") if b == 'mrc': b = float(val_in_mem) else: b = float(b) return a, b def getDivNum(self): global val_in_mem a = input("Enter the first number that you want to divide: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the second number that you want to divide: \n") if b == 'mrc': b = float(val_in_mem) else: b = float(b) return a, b def getSquared(self): global val_in_mem a = input("Enter the number that you want to square: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) return a def getRoot(self): global val_in_mem a = input("Enter the number that you want to find the square root of : \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) return a def getExponent(self): global val_in_mem a = input("Enter the base number : \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the exponent number : \n") if b == 'mrc': b = float(val_in_mem) else: b = float(b) return a, b
43a256e40b7956658e7ce928c469ea15c0e223ac
JuanRx19/ProyectoFinal
/Proyecto final - Juan Miguel Rojas.py
12,910
3.59375
4
import json #Carga de archivos. #Se hace la lectura del archivo donde se encuentran los usuarios con vehiculo registrado. Load = open("usuarios.json", "r", encoding="utf-8") usuarios = json.load(Load) #Se hace la lectura del archivo donde se encuentra la información acerca del parqueadero Load2 = open("tiposParqueaderos.json", "r", encoding="utf-8") tiposParqueaderos = json.load(Load2) #Se hace la lectura y luego se modificara la ocupación del parqueadero Load3 = open("ocupacionParqueaderos.json", "r", encoding="utf-8") ocupacionParqueaderos = json.load(Load3) #user es la variable en la cual guardo todo los usuarios con su informacion(nombre, identificación, tipo de usuario, etc...) user = usuarios["usuarios"] #parqueadero1 es la variable en la cual guardo mi segundo archivo de parqueadero el cual se modificara. parqueadero1 = ocupacionParqueaderos #parqueadero2 es la variable en la cual tendremos nuestro parqueadero original, donde al retirar los vehiculos se reemplazara el puesto dado. parqueadero2 = tiposParqueaderos n = 0 par = list(parqueadero1.keys()) dude = 0 #Apartado de funciones. #Función la cual me permite digite una opción del menú def op(): n = 0 while n == 0: try: opc = int(input("1. Ingreso de vehiculo\n2. Registro de vehiculo\n3. Retirar vehiculo\n4. Salir\nPor favor digite la opción que desea utilizar: ")) n = 1 except: print("Por favor digite una opción adecuada.") n = 0 return opc #Función que me permite registrar nuevos usuarios def regV(usuarios, user, nom, id): n = 0 for i in range(len(user)): if (user[i][1] == id): n+=1 if(n == 1): print("El usuario ya ha registrado un vehiculo.") else: tu = input("1. Estudiante\n2. Profesor\n3. Personal Administrativo\nPor favor ingrese que tipo de usuario es: ") if(tu == "1"): tu = "Estudiante" elif(tu == "2"): tu = "Profesor" elif(tu == "3"): tu = "Personal Administrativo" placa = input("Por favor ingrese la placa del vehiculo: ") tv = input("1. Automóvil\n2. Automóvil eléctrico\n3. Motocicleta\n4. Discapacitado\nPor favor ingrese que tipo de vehiculo es: ") if(tv == "1"): tv = "Automóvil" elif(tv == "2"): tv = "Automóvil Eléctrico" elif(tv == "3"): tv = "Motocicleta" elif(tv == "4"): tv = "Discapacitado" pp = input("1. Mensualidad\n2. Diario\nPor favor ingrese que plan de pago tendrá: ") if(pp == "1"): pp = "Mensualidad" elif(pp == "2"): pp = "Diario" user.append([nom, id, tu, placa, tv, pp]) usuarios["usuarios"] = user return usuarios #Funcion la cual me permite hacer el parqueadero. def parQ(parqueadero1, parqueadero, n1, n2): c = 1 pro = "" for p in range(len(parqueadero[0])): pro+= " " + str(c) + " " c+=1 print(pro) c = 1 for x in range(len(parqueadero)): print(str(c), end="") c+=1 for y in range(len(parqueadero[0])): if(parqueadero[x][y] == n1 or parqueadero[x][y] == n2): print(" 0 ", end="") else: print(" X ", end="") print("\n") carr = 0 while carr == 0: col = int(input("Por favor ingrese el numero de la columna a parquear: ")) fil = int(input("Por favor ingrese el numero de la fila a parquear: ")) col = col - 1 fil = fil - 1 #Condición para evaluar y parquear el vehiculo dentro de ocupacionParqueaderos. if(parqueadero[fil][col] == n1 or parqueadero[fil][col] == n2): parqueadero[fil][col] = placa parqueadero1[piso] = parqueadero with open("ocupacionParqueaderos.json", "w", encoding= "utf-8") as file: json.dump(parqueadero1, file, indent=1, ensure_ascii = False) print("¡El vehiculo se parqueado correctamente!") carr = 1 else: print("Este lugar se encuentra ocupado o no disponible, por favor vuelva a intentarlo.") return parqueadero1 #Proceso para el desarrollo del parqueadero. #Menú de opciones para el parqueardero. opc = op() while(opc != 4): #Opción para el ingreso de vehiculos if(opc == 1): n = 0 placa = input("Por favor ingrese la placa del vehiculo: ") for i in range(len(user)): if(user[i][3] == placa): ingreso = user[i][0] tp = user[i][4] n+=1 for p in par: for i in range(len(parqueadero1[p])): for y in range(len(parqueadero1[p][0])): if(parqueadero1[p][i][y] == placa): dude+=1 if(dude == 1): print("El vehiculo con la placa " + str(placa) + " ya ha sido ingresada en el parqueadero.") else: if(n == 1): print("Bienvenido señor(a) " + str(ingreso) + ", por favor ingrese en que lugar desea parquear.") else: print("Tu placa no se encuentra registrada, por lo tanto seras tomado como visitante.") tp = input("1. Automóvil\n2. Automóvil eléctrico\n3. Motocicleta\n4. Discapacitado\nPor favor ingrese que tipo de vehiculo es: ") if(tp == "1"): tp = "Automóvil" elif(tp == "2"): tp = "Automóvil Eléctrico" elif(tp == "3"): tp = "Motocicleta" elif(tp == "4"): tp = "Discapacitado" piso = input("1. Piso 1\n2. Piso 2\n3. Piso 3\n4. Piso 4\n5. Piso 5\n6. Piso 6\nPor favor seleccione el piso que desea parquear: ") if(piso == "1"): piso = "Piso1" elif(piso == "2"): piso = "Piso2" elif(piso == "3"): piso = "Piso3" elif(piso == "4"): piso = "Piso4" elif(piso == "5"): piso = "Piso5" elif(piso == "6"): piso = "Piso6" parqueadero = parqueadero1[piso] n1 = 0 n2 = 0 if(tp == "Automóvil"): n1 = 1 n2 = 0 parqueadero1 = parQ(parqueadero1, parqueadero, n1, n2) elif(tp == "Automóvil Eléctrico"): n1 = 1 n2 = 2 parqueadero1 = parQ(parqueadero1, parqueadero, n1, n2) elif(tp == "Motocicleta"): n1 = 3 parqueadero1 = parQ(parqueadero1, parqueadero, n1, n2) elif(tp == "Discapacitado"): n1 = 1 n2 = 4 parqueadero1 = parQ(parqueadero1, parqueadero, n1, n2) #Opción para el registro de vehiculos if(opc == 2): n = 0 nom = input("Por favor ingrese su nombre: ") id = int(input("Por favor ingrese su identificación: ")) #Llamado a la función para crear usuarios usuarios = regV(usuarios, user, nom, id) with open("usuarios.json", "w", encoding = "utf-8") as file: json.dump(usuarios, file, indent=4, ensure_ascii = False) #Opción para retirar vehiculos if(opc == 3): tdp = "" l = 0 n = 0 nac = 0 placa = input("Por favor ingrese la placa del vehiculo a retirar: ") canh = int(input("Por favor digite la cantidad de horas que permanecio el vehiculo en el parqueadero: ")) for p in par: for i in range(len(parqueadero1[p])): for y in range(len(parqueadero1[p][0])): if(str(parqueadero1[p][i][y]) == placa): parqueadero1[p][i][y] = parqueadero2[p][i][y] nac+=1 if(nac == 1): for i in range(len(user)): if(user[i][3] == placa): vp = user[i][2] tdp = user[i][5] n+=1 if(n == 1 and tdp == "Diario"): if(vp == "Estudiante"): total = canh * 1000 print("Como Estudiante tendras el cobro de: $" + str(total)) elif(vp == "Profesor"): total = canh * 2000 print("Como Profesor tendras el cobro de: $" + str(total)) elif(vp == "Personal Administrativo"): total = canh * 1500 print("Como Personal Administrativo tendras el cobro de: $" + str(total)) else: if(tdp == "Mensualidad"): print("Usted tiene mensualidad, por lo tanto no necesita de cobro, puede salir.") else: total = canh * 3000 print("Como visitante tendras el cobro de: $" + str(total)) else: print("¡La placa no ha sido registrada en ningun momento!\nAsegurate de que hayas digitado la correcta.") with open("ocupacionParqueaderos.json", "w", encoding = "utf-8") as file: json.dump(parqueadero1, file, indent=1, ensure_ascii = False) opc = op() print("El programa a finalizado correctamente.") #Procedimiento para generar el archivo final y el reporte placaspar = [] #Aquí generamos el reporte final de ocupación, tipos de usuarios, etc... og = 0 pis1 = 0 pis2 = 0 pis3 = 0 pis4 = 0 pis5 = 0 pis6 = 0 estu = 0 prof = 0 persa = 0 car = 0 care = 0 mot = 0 disc = 0 #Ciclos los cuales me permiten recorrer completamente el diccionario del parqueadero. for p in par: for i in range(len(parqueadero1[p])): for y in range(len(parqueadero1[p][0])): if(parqueadero1[p][i][y] != 1 and parqueadero1[p][i][y] != 2 and parqueadero1[p][i][y] != 3 and parqueadero1[p][i][y] != 4): placaspar.append(parqueadero1[p][i][y]) if(p == "Piso1"): pis1+=1 elif(p == "Piso2"): pis2+=1 elif(p == "Piso3"): pis3+=1 elif(p == "Piso4"): pis4+=1 elif(p == "Piso5"): pis5+=1 elif(p == "Piso6"): pis6+=1 og+=1 pis1 = (pis1/100)*100 pis2 = (pis2/100)*100 pis3 = (pis3/100)*100 pis4 = (pis4/100)*100 pis5 = (pis5/100)*100 pis6 = (pis6/50)*100 og = (og/550)*100 if(len(placaspar) >= 1): for i in range(len(user)): for j in range(len(placaspar)): if(user[i][3] == placaspar[j]): #Condicionales para evaluar tipo de usuario if(user[i][2] == "Estudiante"): estu+=1 elif(user[i][2] == "Profesor"): prof+=1 elif(user[i][2] == "Personal Administrativo"): persa+=1 #Condicionales para evaluar el tipo de vehiculo if(user[i][4] == "Automóvil"): car+=1 elif(user[i][4] == "Automóvil Eléctrico"): care+=1 elif(user[i][4] == "Motocicleta"): mot+=1 elif(user[i][4] == "Discapacitado"): disc+=1 reporte = open("Reporte.txt", "w") reporte.writelines("Vehículos estacionados según el tipo de usuario:\n") reporte.writelines("Estudiantes: " + str(estu) + "\n") reporte.writelines("Profesores: " + str(prof) + "\n") reporte.writelines("Personal administrativo: " + str(persa) + "\n") reporte.writelines("\n") reporte.writelines("Vehículos estacionados según el tipo de vehiculo:\n") reporte.writelines("Automóvil: " + str(car) + "\n") reporte.writelines("Automóvil Eléctrico: " + str(care) + "\n") reporte.writelines("Motocicleta: " + str(mot) + "\n") reporte.writelines("Discapacitado: " + str(disc) + "\n") reporte.writelines("\n") reporte.writelines("Porcentaje de ocupación global: " + str(og) + "%\n") reporte.writelines("Porcentaje de ocupación por pisos:\n") reporte.writelines("Piso 1: " + str(pis1) + "%\n") reporte.writelines("Piso 2: " + str(pis2) + "%\n") reporte.writelines("Piso 3: " + str(pis3) + "%\n") reporte.writelines("Piso 4: " + str(pis4) + "%\n") reporte.writelines("Piso 5: " + str(pis5) + "%\n") reporte.writelines("Piso 6: " + str(pis6) + "%\n") #Finalización del programa. Load.close() Load2.close() Load3.close() reporte.close()
1a497b06e8a13ded103f6241b59e11eb2d919956
beccafeen/fromhomegroup
/Final Project/Number_guessing_game.py
697
3.96875
4
#Number guessing game def number_guessing(): import random play_again = True while play_again == True: while(True): guess = input('Guess a number between 1 to 100: ') ran = random.randint(1,101) if(guess==ran): print("You guessed the exact number\n") else: print("You guessed the wrong number, better luck next time") break answer = input("Would you like to play again? ") if answer == "yes" or answer == "y": play_again = True else: play_again = False print("Thanks for playing!") return #number_guessing()
20ffbd80d572fd4b75db8860c04c034cb6d87ab0
midephysco/midepython
/exercises2.py
250
4.125
4
#this is a program to enter 2 numbers and output the remainder n0 = input("enter a number ") n1 = input("enter another number") div = int(n0) / int(n1) remainder = int(n0) % int(n1) print("the answer is {0} remainder {1}".format(div, remainder))
cd99b934bb253952d9cd53a49b2d0e1f9965bd1e
midephysco/midepython
/forloop2.py
320
3.921875
4
def forExamples(): print('Example 1') #The varialble counter is a stpper variable. for counter in range (1,10): print(counter) print() print('Example 2') for counter in range (2,11,2): print(counter) print() print('Example 3') for counter in range(1,22): print(counter,end='') forExamples()
19665f62b7fa38f9cbc82e17e02dacd6de092714
midephysco/midepython
/whileloop2.py
452
4.21875
4
#continous loop print("Adding until rogue value") print() print("This program adds up values until a rogue values is entered ") print() print("it then displays the sum of the values entered ") print() Value = None Total = 0 while Value != 0: print("The total is: {0}.".format(Total)) print() Value = int(input("Please enter a value to add to total: ")) Total = Total + Value print() print("The final total is: {0}.".format(Total))
3c306ab7b4a909a2f503e43f4d85d6383449daa7
ygma/INTRO_TO_COMPUTERS_INTERNET_THE_WEB
/prime_from_fibonaci.py
441
3.75
4
def is_prime(integer): i = integer - 1 while i > 1: if integer % i != 0: i -= 1 continue return False return True item1 = 1 item2 = 1 print(item1) print(item2) #i = 3 #while i <= 100: while True: nextItem = item1 + item2 if nextItem > 1000: break if is_prime(nextItem): print(nextItem) item1 = item2 item2 = nextItem # i += 1
f40f6318bab35ea4da5fd874ee2b4d132448deb9
ygma/INTRO_TO_COMPUTERS_INTERNET_THE_WEB
/simple_calculator.py
186
4.03125
4
def cal(a, b, operator): return a + b if operator == '+' else a - b if operator == '-' else a * b if operator == '*' else a / b if operator == '/' else 'error' print(cal(1, 5, '/'))
9ab60290494f8f8d69dab08c20329a752d689c36
ygma/INTRO_TO_COMPUTERS_INTERNET_THE_WEB
/assignment_2/5_max_and_min.py
330
3.84375
4
import sys def get_max_and_min(a, b, c): # list = [a, b, c] # return (min(a, b, c), max(a, b, c)) if a < b: min, max = a, b else: min, max = b, a if c < min: min = c if c > max: max = c return (min, max) print(get_max_and_min(3,8,2))
4d07bb6ee86d032dfc56c9065b20186808c9d01e
constans73/extructura
/ejercicio1.py
2,326
3.5
4
############################# EJERCICIOS 1 Y 2 ############################# """Dado un diccionario, el cual almacena las calificaciones de un alumno, siendo las llaves los nombres de las materia y los valores las calificación, mostrar en pantalla el promedio del alumno.""" #A partir del diccionario del ejercicio anterior, mostrar en pantalla la materia con mejor promedio. calificaciones = {"matematicas":6.5,"ciencia":7.3, "lengua":5.4, "dibujo":6.3, "tecnologia":9.2, "taller":9.6} promedio = (calificaciones.get("matematicas") + calificaciones.get("ciencia") + calificaciones.get("lengua") + calificaciones.get("dibujo") + calificaciones.get("tecnologia") + calificaciones.get("taller"))/6 print (round (promedio, 2)) #redondeo a dos decimales #################################################################################################################### tupla_calificaciones = tuple(calificaciones.values()) #he convertido en diccionario en una tupla resultado = 0 for lector in tupla_calificaciones: resultado = lector + resultado #voy sumando los datos y lo incluyo en resultado print (round(resultado/len(tupla_calificaciones),2)) #divido los datos entre la longuitud de la tupla y # a su vez lo redondeo a 2 decimales ###################### RESPUESTA DE OTRO ALUMNO ########################## calificaciones = { 'dibujo': 12, 'calculo': 10, "fisica":14} sumatoria = 0 for valor in calificaciones.values(): sumatoria += valor promedio=sumatoria/len(calificaciones) print("Promedio del alumno es =", promedio) mejor_promedio=max(zip(calificaciones.values(),calificaciones.keys())) #HA CREADO UNA MATRIZ print ("Materia con el mejor promedio es:",mejor_promedio[1]) ################################ LO HE INTENTADO MEJORA ############################### calificaciones = { 'dibujo': 12, 'calculo': 10, "fisica":14} sumatoria = 0 for valor in calificaciones.values(): sumatoria += valor promedio=sumatoria/len(calificaciones) print("Promedio del alumno es =", promedio) mejor_promedio=max(calificaciones) #HE QUITADO LA MATRIZ Y VO,SCA EL MAXIMO EN EL print ("Materia con el mejor promedio es:",mejor_promedio) #DICCIONARIO print ("y su puntuacion es de ",calificaciones.get(mejor_promedio))
d925de37c979f9c98a0fd58ca113683536e528e5
villoro/villoro_posts
/0006-singleton/4_mloader.py
880
3.875
4
""" Mixing both types of class instances """ class mloader: value = 0 def sync(self, new_value): """ This will only sync the current instance. If you use that one time the sync all won't work """ self.value = new_value @staticmethod def sync_all(new_value): """ This will update the value in ALL instances""" mloader.value = new_value def get_value(self): return self.value if __name__ == "__main__": mloader_1 = mloader() mloader_2 = mloader() mloader.sync_all(5) print(f"Loader_1: {mloader_1.get_value()}. Loader_2: {mloader_2.get_value()}") mloader_1.sync(2) print(f"Loader_1: {mloader_1.get_value()}. Loader_2: {mloader_2.get_value()}") mloader.sync_all(7) print(f"Loader_1: {mloader_1.get_value()}. Loader_2: {mloader_2.get_value()}")
a5566b92a8ad36bddb0fc2a9b51bad72abc5ab10
zylianyao/PythonPPT
/运算符.py
4,764
3.953125
4
# coding=utf-8 # "+":两个对象相加 # 两个数字相加 a = 7 + 8 # $print a # 两个字符串相加 b = "GOOD" + " JOB!" # print b # "-":取一个数字的相反数或者实现两个数字相减 a = -7 # print a b = -(-8) # print b c = 19 - 1 # print c # "*":两个数相乘或者字符串重复 a = 4 * 7 # print a b = "hello" * 7 # print b # "/":两个数字相除 a = 7 / 2 # print a b = 7.0 / 2 c = 7 / 2.0 # print b # print c # java无此运算符 # "**":求幂运算 a = 2 ** 3 # 相当于2的3次幂,就是2*2*2 # print a # "<":小于符号,返回一个bool值 a = 3 < 7 # print a b = 3 < 3 # print b # ">":大于符号,返回一个bool值 a = 3 > 7 # print a b = 3 > 1 # print b # "!=":不等于符号,同样返回一个bool值 a = 2 != 3 # print a b = 2 != 2 # print b # java为/ # "//":除法运算,然后返回其商的整数部分,舍掉余数 a = 10 // 3 # print a # "%":除法运算,然后返回其商的余数部分,舍掉商 a = 10 % 3 # print a b = 10 % 1 # 没有余数的时候返回什么? # print "没有余数的时候返回什么 %d" % b a = 10 // 3 # a为商的整数部分 b = 10 % 3 # b为 c = 3 * a + b # c为除数乘以商的整数部分加上余数,应该c的值就是被除数 # print c # "&":按位与运算,所谓的按位与是指一个数字转化为二进制,然后这些二进制的数按位来进行与运算 a = 7 & 18 # 执行一下,为什么7跟18与会得到2呢?? print a '''首先我们打开计算器,然后我们将7转化为二进制,得到7的二进制值是:111,自动补全为8位,即00000111 然后我们将18转化为二进制,得到18二进制的值是10010,同样补全为8位,即00010010 再然后,我们将00000111 ,跟 00010010按位进行与运算, 得到的结果是:00000010,然后,我们将00000010转化为十进制 得到数字二,所以7跟18按位与的结果是二进制的10,即为十进制的2 ''' # "|":按位或运算,同样我们要将数字转化为二进制之后按位进行或运算 a = 7 | 18 # print a '''我们来分析一下,同样我们的7的二进制形式是00000111,18的二进制形式是00010010 我们将 00000111 跟 00010010按位进行或运算, 得到的结果是 00010111,然后,我们将00010111转化为十进制 得到数字23,所以7跟18按位或的结果是二进制的10111,即为十进制的23 ''' # "^"按位异或 a = 7 ^ 18 # print a ''' 首先,异或指的是,不同则为1,相同则为0. 我们来分析一下,同样我们的7的二进制形式是00000111,18的二进制形式是00010010 我们将 00000111 跟 00010010按位进行异或运算, 得到的结果是 00010101,然后,我们将00010101转化为十进制 得到数字21,所以7跟18按位异或的结果是二进制的10101,即为十进制的21 ''' # "~":按位翻转~x=-(x+1) a = ~18 # ~18=-(18+1)=-19 # print a # "<<":左移 ''' 比如18左移就是将他的二进制形式00100100左移,即移后成为00100100,即成为36,左移一个单位相当于乘2,左移动两个单位 相当于乘4,左移3个单位相当于乘8,左移n个单位相当于乘2的n次幂。 ''' a = 18 << 1 # print a b = 3 << 3 # print b # "<<":右移 ''' 右移是左移的逆运算,即将对应的二进制数向右移动,右移一个单位相当于除以2,右移动两个单位相当于除以4,右移3个单位相当于 除以8,右移n个单位相当于除以2的n次幂。 ''' a = 18 >> 1 # print a b = 18 >> 2 # print b # "<=":小于等于符号,比较运算,小于或等于,返回一个bool值 a = 3 <= 3 # print a b = 4 <= 3 # print b # ">=" a = 1 >= 3 # print a b = 4 >= 3 # print b # "==":比较两个对象是否相等 a = 12 == 13 # print a # java中字符串==判断的是内存地址,并不一定相等 # 使用equals() b = "hello" == "hello" # print b # java没有not运算单可以使用! # not:逻辑非 a = True b = not a # print b c = False # print not c # java && # and:逻辑与 ''' True and True等于True True and False等于False False and True等于False ''' # print True and True # java || # or:逻辑或 ''' True and True等于True True and False等于True False and False等于False ''' print True or False # x is y x和y是同一个对象 # x is not y x和y是不同的对象 # x in y x是y容器(序列等)的成员 # x not in y x不是y容器(序列等)的成员 x=1 y="1" print id(x) print id(y) print "赋值前" print x is y print x is not y x=y print "赋值后" print x is y print x is not y list=[1,2,3,4] print "in比较" print 1 in list print 1 not in list print 5 in list print 5 not in list
77f574a1b2f43d54c6d348e762709d0d2454d431
0x0f0f/Practice
/Python/Pythonista/searchSubStr.py
314
3.65625
4
import string def search(s, sub): flag = True cnt = 0 index = -1 while(flag): index = string.find(s, sub, index +1) if index == -1: break cnt = cnt + 1 return cnt if __name__ == '__main__': s = raw_input() sub = raw_input() print search(s, sub)
9c047f21e5dddf8ea33e2012e46a9310a570760a
Witterone/cs-module-project-hash-tables
/applications/word_count/word_count.py
791
4.03125
4
def word_count(s): dic = {} words_raw = s.split() words = [] for x in words_raw: new = x.lower().strip('":;,.-+=/\\|[]{}()*^&') words.append(new) u_words = set(words) for i in u_words: count = 0 if i != "": for j in words: if i == j: count += 1 dic[i]=count return dic if __name__ == "__main__": print(word_count("")) print(word_count("Hello")) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count('This is a test of the emergency broadcast network. This is only a test.')) print(word_count('a a\ra\na\ta \t\r\n'))
f5bbfa0d8559e6c8dce6a2d55edfe6f2622eee81
IamMarcIvanov/ImplementedAlgorithms
/dijkstra_algorithm.py
1,555
3.625
4
import typing import heapq import math def dijkstra(adjacency_list: typing.Dict[int, typing.Dict], source_vertex: int) -> typing.Tuple[typing.Dict[int, float], typing.Dict[int,int]]: # No negative edge weights allowed. Adj_list is of form {s_vertex: {t_vertex1: d1,...},...} # Returns a dictionary of shortest path distances to all vertices from the specified vertex # Also returns a parent vertex list so that shortest paths can be reconstructed n: int = len(adjacency_list) # Number of vertices min_distance: typing.List[typing.Tuple] = [(0,source_vertex)] distances: typing.Dict[int, float] = {i: math.inf for i in range(n)} distances[source_vertex] = 0 parent: typing.Dict[int, int] = {i: -1 for i in range(n)} visited: typing.Set[int] = set() while len(min_distance) > 0: v: typing.Tuple = heapq.heappop(min_distance) vertex_ind = v[1] if vertex_ind in visited: continue visited.add(vertex_ind) # Relaxing all edges of vertex v for target_ind in adjacency_list[vertex_ind]: weight = adjacency_list[vertex_ind][target_ind] if distances[target_ind] > distances[vertex_ind] + weight: distances[target_ind] = distances[vertex_ind] + weight parent[target_ind] = vertex_ind heapq.heappush(min_distance, (distances[target_ind], target_ind)) return distances, parent # example adj_list = {0: {1: 1, 2: 1, 3: 3}, 1: {2: 2}, 2: {3: 1}, 3: {}} print(dijkstra(adj_list, 0))
67e167414717bdd471f5e373d224e5b111a1ed79
saipavans/pythonrepo
/lab3/3Task13.py
442
3.734375
4
def is_abcderian(word): word_len = len(word) result = True for iterator in range(len(word) - 1): if word[iterator] <= word[iterator+1]: iterator += 1 continue else: result = False break return result words_abcderian = 0 words_file_path = "../resources/words.txt" fin = open(words_file_path) for line in fin: word = line.strip() if is_abcderian(word): print(word) words_abcderian += 1 print(words_abcderian)