blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a608ecf745ee5e7759b13d12e80d1b1d5be51221
opatiny/mobile-robotics
/exercices/w1/LA/__tests__/squareErr.test.py
243
3.59375
4
from squareErr import squareErr matrix = [[1, 2], [3, 4]] print("matrix") squareErr(matrix) matrix1 = [[1, 2], [3, 4, 5]] print("matrix1") squareErr(matrix1) matrix2 = [[1, 2, 5], [3, 4, 5], [4, 7, 9]] print("matrix2") squareErr(matrix2)
6e501cf6917de0acfeffee29671e4e9a67b6ca99
impacevanend/unalPython
/clase/while.py
1,147
3.78125
4
# *explicaciòn inicial # i = 0 # while i <=6: # print(i) # i +=1 # * Comparación de varialbes hasta salir del ciclo # i = 2 # j = 25 # while i < j: # print(i,j, sep = ", ") # i *= 2 # j += 10 # print("The end.") # print(i,j, sep =", ") #*Uso del break # suma = 0 # while True: # dato = int(input("Ingrese un número entero "+"a sumar o 0 para salir:")) # if dato == 0: # break # suma += dato # print("La suma es: "+str(suma)) # *Cambio de break por hacer mientras # dato = 0 # suma = 0 # bandera = True # while bandera or dato != 0: # bandera = False # dato = int(input("Ingrese un número entero "+"a sumar o 0 para salir:")) # suma += dato # print("La suma es: " + str(suma)) #todo problemas #*listado del uno al 100 # i = 1 # while i<=100: # print(f'numero: {i} cuadrado: {i**2}') # i +=1 #* pares impares # i = 1 # while i <=1000: # if i%2 == 0: # print(f'Número par: {i}') # else: # print(f'Número impar: {i}') # i += 1 i = 10 while i>0: if i%2 == 0: print(f'Número par: {i}') i -= 1
fbb50eaf8ef8d106919d23f9c380ef6b9d241280
tonmoy71/MITx-6.00x
/Excercise/Comparison.py
169
4.28125
4
# Comparison between three numbers x = int(raw_input('x : ')) y = int(raw_input('y : ')) z = int(raw_input('z : ')) if x>y and x>z: print(' x is largest')
813eecc574c7918642e706196a0efe193d912148
extremums/the-simplest-programs
/Sodda dasturlar/Nechta parta kerakligini aniqlovchi dastur.py
344
3.59375
4
#Nechta parta kerakligini aniqlovchi dastur a=int(input("Birintchi guruhdagi o'quvchilari sonini kiriting - ")) b=int(input("Ikkinchi guruhdagi o'quvchilar sonini kiriting - ")) c=int(input("Uchinchi guruhdagi o'quvchilar sonini kiriting - ")) d=a+b+c a1=d//2 a2=d%2 if a2>0 : a1=a1+1 else : a1=a1 print(a1," ta parta kerak bo'ladi .")
0299f028d184c6a77d12f8b3a5f22a4f410c5917
dylandelacruz/pig-latin
/pig_latin.py
1,528
3.890625
4
def logo(): print ("███████████████▀█████████████████████████████████") print ("█▄─▄▄─█▄─▄█─▄▄▄▄███▄─▄████▀▄─██─▄─▄─█▄─▄█▄─▀█▄─▄█") print ("██─▄▄▄██─██─██▄─████─██▀██─▀─████─████─███─█▄▀─██") print ("▀▄▄▄▀▀▀▄▄▄▀▄▄▄▄▄▀▀▀▄▄▄▄▄▀▄▄▀▄▄▀▀▄▄▄▀▀▄▄▄▀▄▄▄▀▀▄▄▀") print (" By. Dylan Dela Cruz.") logo() def consonant(word): index =0 while (word[index]not in["a","e","i","o","u","A","E","I","O","U"]): index=index+1 return word[index:]+word[0:index]+"ay" def vowel(word): return word+"way" def main(): text = input("Please enter the text you would like to translate:") splitText = text.split(" ") pigLatinText ="" for word in splitText: if(word[0]in["a","e","i","o","u","A","E","I","O","U"]): pigLatinText+=vowel(word)+" " else: pigLatinText+=consonant(word)+" " print(pigLatinText[:-1]) if __name__=="__main__": main() restart=input("Would you like to translate another text y/n?:") if restart=="y": main() else: exit() main()
7190cfe8bc742a170deff7cdde7fcd80d33bf36e
SeNSE-lab/SeNSE-lab.github.io
/pubs/sortRefs.py
1,672
3.921875
4
#!/usr/bin/python import sys import re if (len(sys.argv) != 2): print 'You need to pass in the unsorted HTML file.' sys.exit(1) try: htmlfile=open(sys.argv[1],'r') except IOError: print 'Invalid file. Does it exist?' sys.exit(2) allLines=htmlfile.readlines() htmlfile.close() tupleList=[] for line in allLines: # Remove the newline and carriage return sansNewline = line.strip('\n') sansNewline = sansNewline.strip('\r') # Find a group of 4 digits in a row (yeah, we'll have a year-10000 # problem, but what're ya gonna do?) and put it in a group called yearstr p_year = re.compile('\((?P<yearstr>[0-9]{4})\)') m_year = p_year.search(sansNewline) if m_year: try: year = int(m_year.group('yearstr')) except ValueError: print 'RegEx matched something wrong. Check the file.' sys.exit(3) else: print 'There\'s a line without a valid year!' sys.exit(4) # Let's bundle the line with the year in a tuple temptuple = (year, sansNewline) tupleList.append(temptuple) # Now let's sort the tupleList by the year in ascending order, then reverse tupleList = sorted(tupleList, key=lambda oneTuple: oneTuple[0]) tupleList.reverse() # Get the first year from the first item currYear = tupleList[0][0] print '<h3>{0}</h3>'.format(currYear) print '<ul>' for eachTuple in tupleList: if (eachTuple[0] == currYear): print eachTuple[1] else: currYear = eachTuple[0] print '</ul>' print '<h3>{0}</h3>'.format(currYear) print '<ul>' print eachTuple[1] # Close the last ul tag print '</ul>'
806f5826f9e0bdf970e06e8911fee374c498b168
Abarbasam/Langtons-Ant-Terminal
/Langtons_Ant.py
2,908
3.859375
4
# Jan 27, 2017 - Sam Abarbanel # This script models "Langtons Ant." Search it up for a better understanding from time import sleep # Setting up directions for the ant UP = [-1, 0] RIGHT = [0, 1] DOWN = [1, 0] LEFT = [0, -1] directions = [UP, RIGHT, DOWN, LEFT] # This makes changing directions easier direction_Pointer = 3 # Left grid = [[0]] # 2D array that expands as ant crawls over it ant_Position = [0, 0] # Where the ant is on the grid ant_Direction = directions[direction_Pointer] # Left def add_Boundary(): if ant_Position[0] == 0 and ant_Direction == UP: # If the ant is going to step out of range in the up direction, grid.insert(0, [' '] * len(grid[0])) # Append a blank row to where the ant is going to step if ant_Position[0] == (len(grid) - 1) and ant_Direction == DOWN: # If the ant is going to step out of range in the down direction, grid.append([' '] * len(grid[0])) # Add a row below where it is going to step if ant_Position[1] == 0 and ant_Direction == LEFT: # If the ant is going to step out of range in the left direction, for i in range(len(grid)): grid[i].insert(0, ' ') # Add a row where the ant is going to step if ant_Position[1] == (len(grid[0]) - 1) and ant_Direction == RIGHT: # If the ant is going to step out of range in the right direction, for i in range(len(grid)): grid[i].append(' ') # Add a row where the ant is going to step for i in range(11000): # Number of steps the ant takes. if grid[ant_Position[0]][ant_Position[1]] == 0 or grid[ant_Position[0]][ant_Position[1]] == ' ': # If ant lands on 0 or empty tile, left_Or_Right = 1 # Right bit = 1 # Flip bit to 1 if original bit is 0 or ' ' else: left_Or_Right = -1 # Left bit = 0 # Flip bit to 0 if original bit is 1 grid[ant_Position[0]][ant_Position[1]] = bit # Change bit direction_Pointer = (direction_Pointer + left_Or_Right) % 4 # Turn left or right ant_Direction = directions[direction_Pointer] # Redefine ant direction add_Boundary() # If the ant is going to step out of the grid, expand the grid to make room ant_Position[0] += ant_Direction[0] # Ant takes a step ant_Position[1] += ant_Direction[1] if ant_Position[1] == -1: # If ant causes the grid to expand in the negative direction, ant_Position[1] = 0 # then change the ant's coordinates so as not to cause an out-of-range error. if ant_Position[0] == -1: # See two comments above ant_Position[0] = 0 # This prints the grid like a square for i in range(len(grid)): # Each row for j in range(len(grid[0])): # Elements in each row print grid[i][j], # Prints each element of a whole row on one line print # Prints the finished line of elements sleep(0.1) # Buffer so you can see the ant step print "\n" * 50 # Refresh "frame"
a27dc183388f48c8f53e21df914dc48d969b6c92
ChaitanyaPuritipati/CSPP1
/CSPP1-Practice/cspp1-assignments/m7/Functions - Square Exercise 20186018/square.py
512
4.0625
4
''' Author: Puritipati Chaitanya Prasad Reddy Date: 6-8-2018 ''' # Exercise: square of a number # This function takes in one number and returns one number. def square(x_num): ''' x: int or float. ''' return x_num**2 def main(): ''' main function starts here ''' input_num = input() input_num = float(input_num) temp = str(input_num).split('.') if temp[1] == '0': print(square(int(float(str(input_num))))) else: print(square(input_num)) if __name__ == "__main__": main()
c841a23e4ce7eebee2e1edce47e9bfec3be92338
trunghieu11/PythonAlgorithm
/Contest/HackerRank/Python/DataTypes/Lists.py
500
3.703125
4
__author__ = 'trunghieu11' n = int(input()) list = [] for i in range(n): line = input().split() if line[0] == "insert": list.insert(int(line[1]), int(line[2])) elif line[0] == "print": print(list) elif line[0] == "remove": list.remove(int(line[1])) elif line[0] == "append": list.append(int(line[1])) elif line[0] == "sort": list.sort() elif line[0] == "pop": list.pop() elif line[0] == "reverse": list.reverse()
fa6b793eaaa31ff4853aa8a2327222e1aae42994
jessehagberg/python-playground
/ex22.py
2,070
4.03125
4
#Exercise 22: What do you know so far? print -- String Delimiters, operators, conversion and formatting "" '' "'" '"' \[char] escape sequences \n for newline \t for tab, etc... -- String methods [string].split -- command line arguments from sys import argv argv script, arg1 = argv -- user input raw_input(["prompt"]) -- type casting int() float() -- importing modules from packages from [package] import [module] """[multi-line text]""" construct for specifying multi-line strings '''[multi-line text]''' Another way to do it. -- format strings # , String concatentation operator, field delimiter print "blah", % conversion operator %d integer (digits) conversion format flag %s string conversion format flag %r representation conversion format flag "a","r" * 10, "g", "h" * 3 + precise concatenation operator , concatenation operator inserting a space between strings -- Variable types int 100 float 100.0 -- Mathematic and logial operators + Addition operator - Subtraction operator * multiplication operator \ Division operator % modulo < Less than > Greater than >= Greater than or equal to <= Less than or equal to == Comparison operator (string comparison is case sensitive) -2 negative numbers = Assignment operator variable_name_syntax -- Looping structures while while not -- exception handling try: except ValueError, e : [exception].args -- conditional structures if: elif: else: -- file class open(filename[,("r" | "w" | "a")]) [file].read() [file].seek() [file].readline() [file].close() [file].truncate() [file].write() how to copy one file to another -- functions def [function_name]([arg(s)]): function input parameters function return values
05dfac5b442e518a2a177dfc39c8ea899f4fc6f8
frankfka/LabelWise-Backend
/nutrition_parser/parser_functions.py
3,636
3.546875
4
import re from typing import Optional from nutrition_parser.util import get_float def parse_calories(clean_text: str) -> Optional[float]: """ Returns calories parsed from the text Regex: - Look for "calorie" - Match anything except for digits - Match 1-3 digits (the capturing group) - Match a non-digit character """ match_regex = r"calorie[^0-9]*(\d{1,3})[^0-9]" return __parse_with_regex__(clean_text, match_regex) def parse_carbohydrates(clean_text: str, parsed_calories: Optional[float] = None) -> Optional[float]: match_regex = r"(?:carbohydr|glucid)[^0-9\.]*(\d{1,2})\s*g[^0-9]" return __parse_with_regex__(clean_text, match_regex, cal_per_gram=4, parsed_calories=parsed_calories) def parse_sugar(clean_text: str, parsed_calories: Optional[float] = None) -> Optional[float]: match_regex = r"(?:sugar|sucre)[^0-9\.]*(\d{1,2})\s*g[^0-9]" return __parse_with_regex__(clean_text, match_regex, cal_per_gram=4, parsed_calories=parsed_calories) def parse_fiber(clean_text: str, parsed_calories: Optional[float] = None) -> Optional[float]: match_regex = r"(?:fiber|fibre)[^0-9\.]*(\d{1,2})\s*g[^0-9]" return __parse_with_regex__(clean_text, match_regex, cal_per_gram=4, parsed_calories=parsed_calories) def parse_protein(clean_text: str, parsed_calories: Optional[float] = None) -> Optional[float]: match_regex = r"(?:protei)[^0-9\.]*(\d{1,2})\s*g[^0-9]" return __parse_with_regex__(clean_text, match_regex, cal_per_gram=4, parsed_calories=parsed_calories) def parse_fat(clean_text: str, parsed_calories: Optional[float] = None) -> Optional[float]: match_regex = r"(?:fat|lipid)[^0-9\.]*(\d{1,2})\s*g[^0-9]" return __parse_with_regex__(clean_text, match_regex, cal_per_gram=9, parsed_calories=parsed_calories) def parse_sat_fat(clean_text: str, parsed_calories: Optional[float] = None) -> Optional[float]: match_regex = r"saturate[^0-9\.]*(\d{1,2})\s*g[^0-9]" return __parse_with_regex__(clean_text, match_regex, cal_per_gram=4, parsed_calories=parsed_calories) def parse_cholesterol(clean_text: str) -> Optional[float]: match_regex = r"cholestero[^0-9\.]*(\d{1,3})\s*mg[^0-9]" return __parse_with_regex__(clean_text, match_regex) def parse_sodium(clean_text: str) -> Optional[float]: match_regex = r"sodium[^0-9\.]*(\d{1,4})\s*mg[^0-9]" return __parse_with_regex__(clean_text, match_regex) def __parse_with_regex__(clean_text: str, match_regex: str, cal_per_gram: Optional[float] = None, parsed_calories: Optional[float] = None) -> Optional[float]: """ Return possible match with given regex, will check that calories from nutrient < total calories if given """ all_matches = re.findall(match_regex, clean_text) fallback = None # A fallback value for match in all_matches: # Attempt to parse the number success, val = get_float(match) if success: if __check_calories__(val, cal_per_gram, parsed_calories): # Best case scenario return val elif fallback is None: # Init fallback if it hasn't been initialized fallback = val return fallback def __check_calories__(parsed_grams: float, cal_per_gram: Optional[float], parsed_calories: Optional[float]) -> bool: """ Return True if parsed_gram * cal_per_gram < parsed_calories, or if the optional values are not given """ if parsed_calories is None or cal_per_gram is None: return True return parsed_grams * float(cal_per_gram) < parsed_calories
ce74beb2b5d043dcd2016b1a6d8d9d69c9e48a3d
maniCitizen/-100DaysofCode
/W3Schools Exercises/Strings/String from 1st and last chars.py
260
3.671875
4
def return_word(word): if len(word) < 2: return None else: position = len(word)-2 new_word = word[:2]+word[position:] return new_word print(return_word("w3resource")) print(return_word("w3")) print(return_word("w"))
0e53b1768e71f20bbec0d618f7375fa3ab81633c
shiki7/leetcode
/0007: Reverse Integer/solution.py
417
3.515625
4
class Solution: def reverse(self, x: int) -> int: str_x = str(x) if str_x[-1] == 0: str_x = str_x[:-1] if str_x[0] == "-": temp = str_x[1:] str_x = str_x[0] + temp[::-1] else: str_x = str_x[::-1] int_x = int(str_x) if int_x > 2**31 - 1 or int_x < -(2**31): return 0 else: return int_x
543f2cd03bc71fda93cd78d7f2d06095961251ec
l3e0wu1f/python
/Final Project/ShoppingCart.py
5,945
3.8125
4
# INF322 Python # Josh Lewis # Final Project: Interactive Shopping Cart # An application for users to shop at a farmer's market produce stand. It pulls the inventory from an external file, logs errors to an # external log file if the inventory file is not found, and uses OOP to modify and display the contents of a shopping cart, via three # classes for Item, Quantity, and ShoppingCart objects. import os import logging # Log error externally to log file logging.basicConfig(filename='myCartLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') # Toggle below to turn off logging. Even if there's no error to log, a blank log file will be created unless below is un-commented. # logging.disable(logging.DEBUG) allItems = [] # Item object class class Item: def __init__(self, name, price): self.name = name self.price = price def getName(self): return self.name def getPrice(self): return self.price # Quantity object class class Quantity: def __init__(self, name, qty): self.name = name self.qty = qty def getName(self): return self.name def getPrice(self): return self.qty # Cart object class class ShoppingCart: def __init__(self): self.list = [] def addItem(self, quantity): # Adds the specified quantity of an item to cart self.list.append(quantity) def getTotal(self): # Tallies up the price of all items in cart total = 0 price = 0 for item in self.list: name = item.name for it in allItems: if name == it.name: price = it.price qty = item.qty total = total + (price * qty) return total def getNumItems(self): # Counts the number of each item in cart count = 0 for c in self.list: count = count + 1 return count def removeItem(self, name): # Removes all of one type of item from the cart's item list for it in self.list: if name == it.name: self.list.remove(it) def itemsInCart(self): # Displays a list of all items in cart if self.getNumItems() == 0: print("Your cart is currently empty.") else: print("\nItems currently in your cart: ") for it in self.list: if it.qty > 1: print("%i %ss"%(it.qty, it.name)) else: print("%i %s"%(it.qty, it.name)) def welcomeMessage(): print("Welcome to the farmstand! Please use the menu below to browse our inventory.") def getInventory(): # Check for valid inventory file. Log the error to external log if file not found. try: with open("inventory.txt") as fd: for line in fd: name, price = line.split(",") it = Item(name, float(price.strip())) allItems.append(it) except: # if os.path.isfile("inventory.txt") == False: logging.debug("Attempted to open 'inventory.txt'. File does not exist!") print("Inventory file not found!") def listAll(): # List every item available for purchase if os.path.isfile("inventory.txt") == False: print("Inventory file not found!") else: print("Inventory of produce: ") for it in allItems: print("%s $%.2f"%(it.name, it.price)) # Main program def main(): c = ShoppingCart() # Retrieve inventory from file getInventory() # Welcome user to shop welcomeMessage() choice = 1 while choice != 6: print ("\n*** MAIN MENU ***") print ("1. List avaiable items and their prices.") print ("2. Add an item to your cart.") print ("3. List items in your cart.") print ("4. Remove an item from your cart.") print ("5. Go to checkout.") print ("6. Exit.") try: choice = int(input("Enter your choice: ")) if choice == 6: print("Thanks for stopping by!") return elif choice == 1: listAll() elif choice == 2: name = input("Add the following product to cart: ") quantity = int(input("Quantity: ")) q = Quantity(name.lower(), quantity) c.addItem(q) elif choice == 3: c.itemsInCart() elif choice == 4: name = input("Remove all of the following product from cart: ") c.removeItem(name.lower()) elif choice == 5: if c.getNumItems() == 0: print("Your cart is currently empty. Please add an item.") else: print("You are purchasing: ") for it in c.list: if it.qty > 1: print("%i %ss"%(it.qty, it.name)) else: print("%i %s"%(it.qty, it.name)) if c.getTotal() == 0.0: print ("The item(s) you have enetered are invalid. \nThey will not be included with your purchase.\nPlease add some valid items and try again.") subTotal = c.getTotal() tax = subTotal * 0.08 total = subTotal + tax print("Order subtotal: $%.2f" %(subTotal)) print("Tax: $%.2f" %(tax)) print("Order total: $%.2f" %(total)) elif choice > 6: print("Please choose a valid option (1 – 6).") continue except: print("You've entered non-numeric characters. Please choose a valid option between 1 and 6.") continue # Run the program main()
f0c27551d40250870b62861bf5d30eaefc5adcc4
tyellaineho/python-related-code
/Python-HackerRank/solutions.py
523
3.59375
4
# Solve Me First: https://www.hackerrank.com/challenges/solve-me-first/problem def solveMeFirst(a,b): # Hint: Type return a+b below return a+b num1 = input() num2 = input() res = solveMeFirst(num1,num2) print res # A Very Big Sum: https://www.hackerrank.com/challenges/a-very-big-sum def aVeryBigSum(ar): sum = 0 for i in ar: sum += i return sum # Staircase: https://www.hackerrank.com/challenges/staircase/problem def staircase(n): for i in range (1, n+1): print(" "*(n-i) + "#"*i)
f6568553aaf759e0e0a72f15e2f50eddf0327b58
godiatima/Python_app
/calc.py
146
3.8125
4
number_one = input() number_two = input() print('Calculating results...') result = number_one * number_two print('The result is: ' + str(result))
f5553c68550c4db682fe771bd0148265862d3cea
SuperMartinYang/learning_algorithm
/leetcode/python_learning/file_pattern.py
764
3.90625
4
import re def build_matches_and_apply_function(pattern, search, replace): def matches_rule(noun): return re.search(pattern, noun) def apply_rule(noun): return re.sub(search, replace, noun) rules = [] # with can define a file context, after this context, file will automaticaly closed with open('plural-rules.txt', encoding='utf-8') as pattern_file: for line in pattern_file: pattern, search, replace = line.split(None, 3) rules.append(build_matches_and_apply_function(pattern, search, replace)) def plural(noun): ''' use rules to do this job :param noun: need to deal :return: plural noun ''' for matches_rule, apply_rule in rules: if matches_rule(noun): apply_rule(noun)
648acb0ceedb04aed7fd7f062ec177a529f2bb5e
caodongxue/python_all-caodongxue
/day-11/airconditioner/demo4.py
4,039
3.671875
4
class Student: __num = None __name = None __age = None __sex = None __hight = None __weight = None __grade = None __address = None __phone_code = None def __init__(self,num,name,age,sex,hight,weight,grade,address,phone_code): self.__num = num self.__name = name self.__age = age self.__sex = sex self.__hight = hight self.__weight = weight self.__grade = grade self.__address = address self.__phone_code = phone_code def setNum(self,num): self.__num = num def getNum(self): return self.__num def setName(self, name): self.__name = name def getName(self): return self.__name def setAge(self,age): self.__age = age def getAge(self): return self.__age def setSex(self, sex): self.__sex = sex def getSex(self): return self.__sex def setHight(self,hight): self.__hight = hight def getHight(self): return self.__hight def setWeight(self,weight): self.__weight = weight def getWeight(self): return self.__weight def setGrade(self,grade): self.__grade = grade def getGrade (self): return self.__grade def setAddress(self,address): self.__address = address def getAddress(self): return self.__address def setPhone_Code(self,phone_code): self.__phone_code = phone_code def getPhone_Code(self): return self.__phone_code def learn(self,time): print("我学习了",time,"个小时了!") def playGames(self,games_name): print("我在玩",games_name) def programme(self,lines): print("我写了",lines,"行代码!") def summation(self,*args): sum=0 for i in args: sum+=i return sum class Car: __type = None __wheels = None __color = None __weight = None __storage = None def __init__(self,type,wheels,color,weight,storage): self.__type = type self.__wheels = wheels self.__color = color self.__weight = weight self.__storage = storage def setType(self,type): self.__type = type def getType(self): return self.__type def setWheels(self,wheels): self.__wheels = wheels def getWheels(self): return self.__wheels def setColor(self,color): self.__color = color def getColor(self): return self.__color def setWeight(self,weight): self.__weight = weight def getWeight(self): return self.__weight def setStorage(self,storage): self.__storage = storage def getStorage(self): return self.__storage p=Car("宝马",4,"白色","40kg",60) x=Car("法拉利",4,"红色","20kg",50) l=Car("铃木",4,"咖色","20kg",50) h=Car("五菱",4,"黑色","20kg",50) v=Car("拖拉机",6,"蓝色","20kg",50) print("车的型号是",p.getType(),"有",p.getWheels(),"个轮胎,颜色是",p.getColor(),"重达",p.getWeight(),"容积是",p.getStorage()) print("车的型号是",x.getType(),"有",x.getWheels(),"个轮胎,颜色是",x.getColor(),"重达",x.getWeight(),"容积是",x.getStorage()) print("车的型号是",l.getType(),"有",l.getWheels(),"个轮胎,颜色是",l.getColor(),"重达",l.getWeight(),"容积是",l.getStorage()) print("车的型号是",h.getType(),"有",h.getWheels(),"个轮胎,颜色是",h.getColor(),"重达",h.getWeight(),"容积是",h.getStorage()) print("车的型号是",v.getType(),"有",v.getWheels(),"个轮胎,颜色是",v.getColor(),"重达",v.getWeight(),"容积是",v.getStorage()) # 笔记本:属性:型号,待机时间,颜色,重量,cpu型号,内存大小,硬盘大小。 行为:打游戏(传入游戏的名称),办公 class Notebook: __type = None
9bb40839b999bd07713fffd803acd72c6035dec7
GParolini/python_ab
/exceptionhandling/demo_withlog.py
699
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 30 08:20:56 2019 @author: giudittaparolini """ import logging logging.basicConfig(filename="mylogdemo.log", level=logging.DEBUG) try: f= open("myfile.txt", "w") a, b = [int(x) for x in input("Enter two numbers: ").split()] logging.info("Division in progress") c = a/b f.write("Writing %d into file" %c) except ZeroDivisionError: print("Division by zero is not allowed") print("Please enter a non zero numbers") logging.error("Division by zero") else: print("You have entered a non zero number") finally: f.close() print("File closed") print("Code after the exception")
81c28e966fa2f07ffdfc1b7951815c5ac9602c1c
saenyakorn/2110101-COMP-PROG
/05/05_List_12.py
388
3.703125
4
name = ["Robert","William","James","John","Margaret","Edward","Sarah","Andrew","Anthony","Deborah"] nick = ["Dick","Bill","Jim","Jack","Peggy","Ed","Sally","Andy","Tony","Debbie"] t1 = {k:v for k,v in zip(name,nick)} t2 = {k:v for k,v in zip(nick,name)} n = int(input()) for i in range(n): s = input() print("{}".format(t1[s] if s in t1 else (t2[s] if s in t2 else "Not found")))
622b9a8709ff4997119601f51708bc2958fb1c34
mexcaptain93/channelstat
/gui.py
575
3.78125
4
import tkinter as tk import tkinter.ttk as ttk class GUI(): """Класс для графического интерфейса""" def __init__(self, function): window = tk.Tk() window.title("Парсер событий") heading = tk.Label(text="Парсер событий") text_box = tk.Text( width=160, height=16 ) but = tk.Button(text="Старт!") but.bind('<Button-1>', function) heading.pack() text_box.pack() but.pack() window.mainloop()
4e85db84d8e3dd606689e3af6ff7fe973ac9fb85
jeckles/crypto
/numtheory.py
977
3.546875
4
from decimal import * getcontext().prec = 50 # set our precision to be very high # Euler's totient function def phi(n): result = n # initialze result as n # consider all prime factors of n for every prime < square root of n p = 2 while(p * p <= n): # for primes less than the square root of n # check if p is a prime factor. if (n % p == 0): # if yes, update n and result while (n % p == 0): n = n // p # factor out p from n result = Decimal(result) * Decimal((Decimal(1.0) - (Decimal(1.0) / Decimal(p)))) # following book approach for calculating totient p = p + 1 # if it is the case that n has a prime factor greater than its square root, then this can be the # only one that is greater than n if (n > 1) : result = result * Decimal(Decimal(1.0) - Decimal(Decimal(1.0) / Decimal(n))) return int(result)
618dff8a282152092def4435ebafbfd8f718a136
shuyangw/cs585-final-project-submission
/src/runner.py
14,150
3.765625
4
from rnn import * from preprocessor import Preprocessor import tensorflow as tf import numpy as np import os import sys import time class Runner(object): """ The Runner class is the main class that will perform the entirety of the training and the predicting. The constructor will take in all of the relevant information: - subreddit: A string denoting the subreddit that we would like to train on. This string should not include the "r/" prefix of the subreddit. - sample_size: An integer denoting how many of the input comments we would like to train on. If this value is None, we train on the entire dataset. - percentile: An integer denoting the percentile of comments that will be accepted. For example, an input of 90 will ensure that the comments we train on will only be in the top 10% of rated comments. - custom: A boolean that denotes whether or not we are using a file that is not in the format of a reddit comment. For example, if we simply just want to train on any body of text, we can specify that here. The name of the input file is specified in the following parameter. - custom_file: An optional file that is only considered if custom=True. Specifies the name of the file that we want to train on. - seq_length: An integer denoting how many comments we would train on at once. - load: Specifies whether or not we're loading from a previously trained checkpoint. """ def __init__( self, subreddit, sample_size, percentile, custom=False, custom_file="", seq_length=100, load_vocab=False, save_vocab=False ): self.subreddit = subreddit self.sample_size = sample_size self.percentile = percentile self.seq_length = seq_length dataset, vocab, char2idx, idx2char, text_as_int = None, None, None, None, None """ If we are using a custom file, we pass it into the preprocessor so that it'll know that we won't be taking in text in the format of Reddit comments """ if custom: dataset, vocab, char2idx, idx2char, text_as_int = self.preprocess( custom=True, custom_file=custom_file ) else: dataset, vocab, char2idx, idx2char, text_as_int = self.preprocess( load_vocab=load_vocab, save_vocab=save_vocab ) self.dataset = dataset self.vocab = vocab self.char2idx = char2idx self.idx2char = idx2char self.text_as_it = text_as_int """ Splits a portion of the input text into a input, target pair. To only be used internally within this module. Inputs: - chunk: A Tensor of varying shape Returns: - Two tensors """ def _split_input_target(self, chunk): input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text """ After we vectorize the data, we format it so that it is in a form that is acceptable by tensorflow. Input: - The values returned by vectorize() found in rnn.py Output: - Returns the same values but including a dataset parameter, representing the input data that is easily readable by Tensorflow. """ def setup_vectorized_data(self, vocab, char2idx, idx2char, text_as_int): chunks = tf.data.Dataset.from_tensor_slices(text_as_int).batch( self.seq_length+1, drop_remainder=True ) dataset = chunks.map(self._split_input_target) return dataset, vocab, char2idx, idx2char, text_as_int """ This performs the second batch of preprocessing. Inputs: - custom_file: A string denoting the custom file that we wish to use. Only considered if custom=True. - custom: A boolean denoting whether or not we would like to use a custom file. - load_vocab: A boolean denoting whether or not we would like to load a vocabulary from checkpoint. - save_vocab: A boolean denoting whether or not we would like to save a vocabulary from a checkpoint. """ def preprocess( self, custom_file="", custom=False, load_vocab=False, save_vocab=False ): print("Preprocessing") """ The main function of this is that we would like to vectorize our input. We have the choice of two vectorization methodologies, but for the purpose of our final product, we choose a char based vectorization as opposed to a word based one, which is still defined in rnn.py for reference. """ if custom: pp = Preprocessor(self.subreddit, self.sample_size, self.percentile, custom=True, custom_file=custom_file ) """ If we do use a custom file, we need to map each instance to a string, integer pair where the integer denotes a fictitious score that would've been used if it were a comment instead. """ output, _ = pp.process(custom=True, custom_file=custom_file) output = [(str(output[i]), 0) for i in range(len(output))] vocab, char2idx, idx2char, text_as_int = vectorize(output) """ Perform additional processing. """ return self.setup_vectorized_data( vocab, char2idx, idx2char, text_as_int ) else: good_comments = None if not load_vocab: pp = Preprocessor(self.subreddit, self.sample_size, self.percentile) comments, num = pp.process() good_comments = pp.statistics(comments) vocab, char2idx, idx2char, text_as_int = vectorize( good_comments, load_vocab=load_vocab, save_vocab=save_vocab ) print("Vocab size of ", len(vocab)) return self.setup_vectorized_data( vocab, char2idx, idx2char, text_as_int ) """ This function performs the entirety of the training. Inputs: - save: A boolean denoting whether or not we would like to save the model as a checkpoint. - epochs: An integer denoting the number of epochs we would like to train over. """ def regular_train(self, save=True, epochs=5): print("Regular training") """ We shuffle the data to reduce bias. """ batch_size = 1 buffer_size = 10000 self.dataset = self.dataset.shuffle(buffer_size).batch( batch_size, drop_remainder=True ) """ We specify some parameters specific to the neural network such as the input dimensions, the number of units and which architecture we would like to use. We have the choice between two architectures. One is our original 3 layer simple network defined in ModelOld in rnn.py that we used for our progress report. The second is a much more complicated network that is being used here for our final product. We use the Adam optimizer because it's good and its the best one that was taught in cs682. We also define the loss function with a softmax loss function. """ vocab_size = len(self.vocab) embedding_dim = 256 units = 1024 model = ModelTest(vocab_size, embedding_dim, units) optimizer = tf.train.AdamOptimizer() def loss_function(real, preds): return tf.losses.sparse_softmax_cross_entropy( labels=real, logits=preds ) model.build(tf.TensorShape([batch_size, self.seq_length])) """ We define some structures that we need to keep and some final variables. """ checkpoint_dir = './training_checkpoints/' losses = [] iterations = [] iteration = 1 batchsize = len(list(self.dataset)) for epoch in range(epochs): hidden = model.reset_states() """ Setup some variables for timekeeping purposes """ start = time.time() first_batch = True total_time = 0 avg_batch_time = 0 begin = time.time() for (batch, (inp, target)) in enumerate(self.dataset): """ Perform forward and backpropagation. """ with tf.GradientTape() as tape: predictions = model(inp) loss = loss_function(target, predictions) grads = tape.gradient(loss, model.variables) optimizer.apply_gradients(zip(grads, model.variables)) """ Print our progress every 100 batches. """ if batch % 100 == 0: """ Here, we calculate the approximate time remaining in minutes. """ end = time.time() total_time += end - begin avg_batch_time = int(total_time/float(iteration)) remaining_time = (((batchsize - batch)/100)*avg_batch_time)/60. print ('Epoch {} Batch {} of {} Loss {:.4f} Time {:.4f} secs, remaining time {:.4f} mins'.format(epoch+1, batch, batchsize, loss, end-begin, remaining_time)) """ Add our progress. """ losses.append(loss) iterations.append(iteration) iteration += 1 begin = time.time() print ('Epoch {}'.format(epoch+1)) print ('Time taken for 1 epoch {} sec\n'.format(time.time()-start)) if save: model.save_weights(checkpoint_dir + "checkpoint") return model, losses, iterations """ This function loads a model from a perviously trained checkpoint. Inputs: - dir: A string denoting the directory of the checkpoint. Returns: - model: The model object with the trained weights. """ def load(self, dir): embedding_dim = 256 units = 1024 vocab_size = len(self.vocab) batch_size = 1 buffer_size = 10000 model = ModelTest(vocab_size, embedding_dim, units) model.build(tf.TensorShape([batch_size, self.seq_length])) model.load_weights(dir) return model """ This function performs the entirety of the predictions. We essentially take our model, specify a start string and parse it through or model. Inputs: - model: A Tensorflow object denoting our trained model. - num_generate: The number of samples that we wish to generate. In the case of a char based model, this denotes the number of characters to generate. In the case of a word based model, this denotes the number of words to generate. - start_string: In the case of a char based model, this denotes the start char of our prediction. In the case of a word based model, this denotes the start word of our prediction. - out: A boolean denoting whether or not we would like to write our output to a file. - temperature: A float in the range [0.0, 1.0] that denotes the temperature of our prediction. This value corresponds to the softmax equation denoted by the value T: q_i = exp(z_i/T)/sum(exp(z_j/T)) The smaller the temperature value is, the higher the above probability is. Our prediction will be more confident but it will also be more conservative and boring. A high temperature value will yield a smaller probability, rendering a more varied prediction. But a too high temperature could give a prediction so varied that it will no longer make sense. """ def predict(self, model, num_generate, start_string, out=False, temperature=1.0): print("Predicting...") num_generate = num_generate start_string = "a" input_eval = [self.char2idx[s] for s in start_string] # input_eval = [self.char2idx[start_string]] input_eval = tf.expand_dims(input_eval, 0) text_generated = [] model.reset_states() for i in range(num_generate): predictions = model(input_eval) # remove the batch dimension predictions = tf.squeeze(predictions, 0) # using a multinomial distribution to predict the word returned by the model predictions = predictions / temperature predicted_id = tf.multinomial(predictions, num_samples=1)[-1,0].numpy() # We pass the predicted word as the next input to the model # along with the previous hidden state input_eval = tf.expand_dims([predicted_id], 0) text_generated.append(self.idx2char[predicted_id]) print (start_string + ''.join(text_generated)) print("Writing to output") if out: if not os.path.exists("outputs/" + "Out111" + ".txt"): output = open("outputs/" + "Out111" + ".txt", "w+", encoding="utf-8") output.write(start_string + ''.join(text_generated)) output.close() else: count = 1 while os.path.exists("outputs/" + "Out111" + str(count) + ".txt"): count += 1 output = open("outputs/" + "Out111" + str(count) + ".txt", "w+", encoding="utf-8") output.write(start_string + ''.join(text_generated)) output.close()
334dfe01053f3590f454ad06ee7aa17b0120ebb1
dineshpabbi10/DS-Itronix
/Day7/4.py
643
4
4
class Employee: increment=1.5 #This is common for all the employee def __init__(self,fname,lname,salary): self.fname=fname self.lname=lname self.salary=salary def increase(self): #self.salary=int(self.salary * increment) #self.salary=int(self.salary * Employee.increment) self.salary=int(self.salary * self.increment) # first it will search in __init__ if not found then search in class. robin = Employee('Robin','Mahajan',54000) rajat = Employee('Rajat','Sharma',54000) print(robin.salary) robin.increase() print(robin.salary) print(robin.__dict__) robin.dept="Sales" print(robin.__dict__) print(Employee.__dict__)
6330d2af47c509182fcd6ae51036d7b4b8c20b62
chrisgay/dev-sprint1
/my_first_app/my_first_app.py
1,724
3.90625
4
# This is whre you can start you python file for your week1 web app # Name: from flask import Flask, flash #import Flask class (classes are templates for creating objects through inheritance, e.g., an child object inherits the traits (functions and attributes) of its parent class) import flask.views import os app = Flask('my_first_app') # create instance of Flask object (a WSGI application to handle client requests) # the my_first_app parameter is used to look-up resources in the file system. In a single module (like our example) __name__ is also a correct value. app.secret_key = "Apple" class View(flask.views.MethodView) : def get(self) : # HTTP Request to Get data from sever (in this case index.html file) return flask.render_template('index.html') # use jinja templates, which are part of Flask, to render templates/index.html file, note file path in templates folder is default path def post(self) : # HTTP Request to Post (posting may involve a variety of tasks including update data displayed on page, sending and email etc.), post method triggered on form submission as declared in method property # Note - make sure there's no extra spaces at the end of each line or you'll throw an indention error result = eval(flask.request.form['expression']) #evaluate 'expression' data and read in output to result variable flask.flash(result) # create flash session to view result variable in loop defined in index.html return self.get() # update view of index.html with flash variable # evaluate text in 'expression' field from index.html file app.add_url_rule('/', view_func=View.as_view('main'), methods=['GET', 'POST']) app.run() #launch app object
039d4124c652cf19f0bfc667fd87da0f795cb411
rockingrohit9639/pythonBasics
/generatorss.py
883
4.21875
4
""" Iterable - __iter__() or __getitem__() Iterator - __next__() Iteration - Process of Iterator and Iterable """ def fibo(m): n1 = 1 n2 = 1 for i in range(m): n3 = n1 n1 = n2 n2 = n1 + n3 yield n3 def facto(n): n1 = 1 for i in range(1,n+1): n1 *= i yield n1 def main(): print("---------MENU--------") print("1 : Fibonnaci Series") print("2 : Factorial ") choice = int(input("Enter Your Choice : ")) if choice == 1: m = int(input("Enter Number : ")) fibo(m) a = fibo(m) for i in range(0,m): print(a.__next__()) elif choice == 2: n = int(input("Enter Number : ")) facto(n) for i in facto(n): print (i) else: print("Invalid Input !!! Choose from the Menu") if __name__ == '__main__': main()
ba7dd5e6f508fc5654bf7705b174497f3a038cb1
xiesong521/my_leetcode
/链表/双指针/快慢指针/#141_环形链表.py
1,216
3.828125
4
#!/user/bin/python3 #coding:utf-8 """ Author:XieSong Email:18406508513@163.com Copyright:XieSong Licence:MIT """ class ListNode: def __init__(self,x): self.val = x self.next = None #计数法 class Solution: def hasCycle(self,head): hashset = [] while(head): if head in hashset: return True else: hashset.append(head) head = head.next return False #快慢指针 class Solution: def hasCycle(self,head): if head == None: return False fast = head low = head while(fast): if fast.next and fast.next.next: fast = fast.next.next low = low.next else: return False if fast == low: return True if __name__ == '__main__': l1 = ListNode(3) l2 = ListNode(2) l3 = ListNode(1) l4 = ListNode(5) # l5 = ListNode(3) # l6 = ListNode(2) # l7 = ListNode(1) l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l1 # l5.next = l6 # l6.next = l7 s = Solution() ret,re,_ = s.hasCycle(l1) print(ret,re)
0afd84094197e2a6b594920d95c2dc402ce77aac
Ruknin/Day-13
/Practice/review1.py
1,075
4.0625
4
strings = "This is Python" char = "C" multiline_str = """This is a multiline string with more than one line code.""" unicode = u"\u00dcnic\u00f6de" raw_str = r"raw \n string" print(strings) print(char) print(multiline_str) print(unicode) print(raw_str) fruits = ["apple", "mango", "orange"] #list numbers = (1, 2, 3) #tuple alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary vowels = {'a', 'e', 'i' , 'o', 'u'} #set print(1,2,3,4,sep='*') # Output: 1*2*3*4 positional_order = "{1}, {0} and {2}".format('John','Bill','Sean') print('\n--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "Id name salary \n {s} {b} {j}".format(j='360',b='Bill',s='1') print('\n--- Keyword Order ---') print(keyword_order,end='\t') def print_inventory(dct): print("\nItems held:") for item, amount in dct.items(): # dct.iteritems() in Python 2 print("{} ({})".format(item, amount)) inventory = { "shovels": 3, "sticks": 2, "dogs": 1, } print_inventory(inventory)
4b03a4979bf4443709b4de8e804fa3b4ba41d804
gallonp/TumorKiller
/datastorage.py
7,938
4.3125
4
"""Methods for storing and retrieving files in the database.""" import cPickle import sqlite3 # Name of file for SQLite database. # Note: In-memory database (":memory:") is erased after closing the connection. SQLITE_DATABASE_FILE = 'database.db' # Name of table containing brain scan data. TABLE_NAME_BRAINSCANS = 'BrainScans' # Column description for table containing brain scan data. TABLE_COLS_BRAINSCANS = '(Id TEXT, FileName TEXT, FileContents BLOB, GroupLabel TEXT)' # Name of table containing classifiers. TABLE_NAME_CLASSIFIERS = 'Classifiers' # Column description for table containing classifiers. # pylint:disable=line-too-long TABLE_COLS_CLASSIFIERS = '(Id TEXT, ClassifierName TEXT, ClassifierType TEXT, SerializedClassifier TEXT)' def create_sqlite_connection(db_filename=SQLITE_DATABASE_FILE): """Creates a connection to the SQLite database in the specified file. Args: db_filename: Path to the SQLite database file. Returns: A database Connection object. """ return sqlite3.connect(db_filename) def _table_exists(conn, table_name): """Determines whether or not the given table exists in the database. Args: conn: A database Connection object. table_name: Name of table. Returns: True if a table the with given name is found in the database, otherwise returns false. """ # Query for the table. with conn: cur = conn.cursor() cur.execute(('SELECT name FROM sqlite_master' ' WHERE type="table" AND name="%s"') % table_name) return len(cur.fetchall()) == 1 def _create_table(conn, table_name, columns): """Creates a new table in the given database. Args: conn: A database Connection object. table_name: Name of the table to create. columns: Column definition for the table. """ # Create the table. with conn: cur = conn.cursor() cur.execute('CREATE TABLE IF NOT EXISTS %s%s' % (table_name, columns)) def _fetch_entry_from_table(conn, table_name, entry_id): """Fetches entry with specified ID from table. Args: conn: A database Connection object. table_name: Name of the table to query. entry_id: ID of the entry to fetch. Returns: The entry with specified ID if found. Otherwise returns None. """ # Make sure the table exists. if not _table_exists(conn, table_name): return None # Query for the classifier. with conn: cur = conn.cursor() cur.execute( 'SELECT * FROM %s WHERE Id=\"%s\"' % (table_name, entry_id)) query_result = cur.fetchone() # If found, return the classifier. return query_result if query_result else None def _fetch_all_from_table(conn, table_name): """Fetches all rows from the specified table. Args: conn: A database Connection object. table_name: Name of the table to query. Returns: A list of all entries in the specified table. """ # Make sure the table exists. if not _table_exists(conn, table_name): return [] # Query for all entries in the table. with conn: cur = conn.cursor() cur.execute('SELECT * FROM %s' % table_name) return cur.fetchall() def _store_entry_in_table(conn, table_name, entry): """Stores given data in a new row of the specified database table. Args: conn: A database Connection object. table_name: Name of table where entry should be stored. entry: Tuple of values to insert into table. """ # Create entry insertion template. template = ('?, ' * len(entry)).rstrip(', ') # "?" for each value template = '(%s)' % template # enclose in parentheses # Try to insert a new row into the table. with conn: cur = conn.cursor() cur.execute('INSERT INTO %s VALUES%s' % (table_name, template), entry) def store_mrs_data(conn, file_id, file_name, file_contents, group_label): """Stores given MRS data in the database. Args: conn: A database Connection object. file_id: Unique identifier for the file. file_name: Name of the file. file_contents: Raw file contents. group_label: Name of the therapy group that the given patient data belongs to. """ # Create the table if it does not exist. _create_table(conn, TABLE_NAME_BRAINSCANS, TABLE_COLS_BRAINSCANS) # Try to insert a new row into the table. table_entry = (file_id, file_name, file_contents, group_label) _store_entry_in_table(conn, TABLE_NAME_BRAINSCANS, table_entry) def fetch_mrs_data(conn, file_id): """Fetches the specified MRS data from the database. Args: conn: A database Connection object. file_id: Unique identifier for the file. Returns: If an entry with specified ID is found, the MRS data is returned in a 4-tuple of the form (file_id, file_name, file_contents, group_label). Otherwise, the method returns None. """ # Fetch specified MRS data from the database. return _fetch_entry_from_table(conn, TABLE_NAME_BRAINSCANS, file_id) def fetch_all_mrs_data(conn): """Fetches all MRS data from the database. Args: conn: A database Connection object. Returns: List of all MRS data entries in the database. Each item in the list is a 4-tuple of the form (ID, filename, MRS file contents, group label). """ # Fetch all MRS data from the database. return _fetch_all_from_table(conn, TABLE_NAME_BRAINSCANS) def store_classifier(conn, classifier_id, classifier_name, classifier_type, classifier): """Stores the given classifier in the database. Args: conn: A database Connection object. classifier_id: ID to associate with the saved classifier. Must be unique. classifier_name: String description for the classifier. classifier_type: The classifier type (e.g. neural network, SVM). classifier: The classifier that should be saved. """ # Serialize the classifier. classifier = cPickle.dumps(classifier) # Create the table if it does not exist. _create_table(conn, TABLE_NAME_CLASSIFIERS, TABLE_COLS_CLASSIFIERS) # Store classifier in the database. table_entry = (classifier_id, classifier_name, classifier_type, classifier) _store_entry_in_table(conn, TABLE_NAME_CLASSIFIERS, table_entry) def fetch_classifier(conn, classifier_id): """Queries the database for a classifier with specified ID. Args: conn: A database Connection object. classifier_id: Unique identifier for the classifier. Returns: A 4-tuple containing (classifier_id, classifier_name, classifier_type, classifier). This method will return None if a classifier with the specified ID is not found in the database. """ # Fetch specified classifier from the database. db_entry = _fetch_entry_from_table(conn, TABLE_NAME_CLASSIFIERS, classifier_id) if db_entry is None: return None # Convert serialized classifier to object. return (db_entry[0], db_entry[1], db_entry[2], cPickle.loads(str(db_entry[3]))) def fetch_all_classifiers(conn): """Fetches all classifiers from the database. Args: conn: A database Connection object. Returns: List of all classifiers in the database. Each item in the list is a 4-tuple of the form (classifier_id, classifier_name, classifier_type, classifier). """ # Fetch all classifiers from the database. db_entries = _fetch_all_from_table(conn, TABLE_NAME_CLASSIFIERS) # Convert serialized classifiers to objects. converted_entries = [] for entry in db_entries: converted_entries.append( (entry[0], entry[1], entry[2], cPickle.loads(str(entry[3])))) return converted_entries
78907035c1a8f6a33e085f7915835fd8c5d72f5e
LishuaiBeijing/OMOOC2py
/_src/om2py2w/2wex0/main_3.py
1,116
3.65625
4
# -*- coding:utf-8 -*- # title:简单日记软件 # description: 支持日记写入,支持日记输出 # layout: 主界面是日记显示界面,按钮1--写入日记,点击后弹出对话框,写入日记,点击确定后保存,按钮2--退出软件 # extention: # 1.支持简单的版本控制,可以回溯此前的N个版本 # 2.直接改造成一个界面,与记事本类似,显示已有日记,并直接续写,设置保存和回退按钮(这跟记事本不是一样了? ) import Tkinter as tk class Diary: def __init__(self , master): frame = tk.Frame(master , width=300, height=400 , bg="" , colormap="new") frame.pack() ''' self.button = tk.Button(frame , text="Quit" , fg="red" , command=frame.quit) self.button.pack(side=tk.LEFT) self.hi_there = tk.Button(frame , text="Hello" , command=self.say_hi) self.hi_there.pack(side=tk.LEFT)''' def say_hi(self): input_str = raw_input(" > ") print input_str if __name__=='__main__': root = tk.Tk() diary = Diary(root) root.mainloop()
675dc08ab210bc45d09847d35a79ecd88fee9c1d
danielaloperahernandez/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
295
4
4
#!/usr/bin/python3 """Module for save_to_json_file method""" import json def save_to_json_file(my_obj, filename): """ Method that writes an Object to a text file, using a JSON representation """ with open(filename, "w") as write_file: json.dump(my_obj, write_file)
66bd10f0c5157714f2ed1ce86f3a8b4ead3a2ffb
gsudarshan1990/PythonSampleProjects
/Random/random_example.py
128
3.5625
4
import random values=[1,2,3,4,5] for i in range(0,5): print(random.choice(values)) random.shuffle(values) print(values)
2a2b39f0bbb03d3b72a69bbe4a49c3584b0131ad
iankorf/elvish
/elvish.py
2,557
3.6875
4
#!/usr/bin/env python3 import sys import fileinput import random import json random.seed(1) # you may need to add more puncs = '.,1?!:;-*"_()[]{}<>/1234567890—“”’‘–$«»\'=#@%&+' spaces = ' ' * len(puncs) wordcount = {} for rawline in fileinput.input(): # convert to lowercase lower = rawline.lower() # convert punctuation to spaces table = lower.maketrans(puncs, spaces) line = lower.translate(table) # count all words because unique words may be errors of some kind for word in line.split(): word += '*' if word not in wordcount: wordcount[word] = 0 wordcount[word] += 1 # letter frequencies - looking for punctuation and such """ lettercount = {} for word in wordcount: for letter in word: if letter not in lettercount: lettercount[letter] = 0 lettercount[letter] += wordcount[word] for let in lettercount: print(let, lettercount[let]) """ count1 = {} # count of first letter count2 = {} # count of second letter, given the first letter count3 = {} # counts of third, given first and second for word in wordcount: if len(word) < 4: continue # first letter counting c1 = word[0] # first letter if c1 not in count1: count1[c1] = 0 count1[c1] += 1 #count1[c1] += wordcount[word] # second letter counting, given the first letter c2 = word[1] # second letter if c1 not in count2: count2[c1] = {} if c2 not in count2[c1]: count2[c1][c2] = 0 count2[c1][c2] += 1 #count2[c1][c2] += wordcount[word] # third and alll other letters, given the first two for i in range(2, len(word)): c1 = word[i-2] c2 = word[i-1] c3 = word[i] if c1 not in count3: count3[c1] = {} if c2 not in count3[c1]: count3[c1][c2] = {} if c3 not in count3[c1][c2]: count3[c1][c2][c3] = 0 count3[c1][c2][c3] += 1 #count3[c1][c2][c3] += wordcount[word] rs1 = '' # random source for 1st character for c in count1: rs1 += c * count1[c] rs2 = {} # random source for 2nd character for c1 in count2: if c1 not in rs2: rs2[c1] = '' for c2 in count2[c1]: rs2[c1] += c2 * count2[c1][c2] rs3 = {} # random source for 3rd and all other letter for c1 in count3: if c1 not in rs3: rs3[c1] = {} for c2 in count3[c1]: if c2 not in rs3[c1]: rs3[c1][c2] = '' for c3 in count3[c1][c2]: rs3[c1][c2] += c3 * count3[c1][c2][c3] while True: word = '' c1 = random.choice(rs1) c2 = random.choice(rs2[c1]) word += c1 word += c2 for j in range(10): c3 = random.choice(rs3[c1][c2]) if c3 == '*': break word += c3 c1 = c2 c2 = c3 if len(word) > 4: c1 = word[0].upper() print(f'{c1}{word[1:]}')
22b375fdc5890ca2f365bab4455fc7e66775b761
Dtaylor709/she_codes_python
/loops_playground.py
2,074
4.375
4
# HAYLEYS LOOP COURSE EXAMPLES # num = number. You can actualy use any word you wnat # use range() instead of [0:10]. range =up to number so range (10) only prints 0 to 9 as it prints 10 items but te list starts with 0 # # for loop starts with 'for' # for num in range(10): # print(num) # # (1, 11) means start at position 1 and go up to 11 items. It will list 0 to 10 but because we said start at 1 # for num in range(1, 11): # print(num) # # fist number what item to start list with. # # second number what number to go up to # # third number what increment to go up numbers with. 2 is every second number # for num in range(0, 11, 2): # print(num) # # use a for loop to print numbers 0 to 100 (inclusive) # for index in range(101) # print(index) # # # use a for loop to print numbers # # 0 to 100 in steps of 5 (5, 10) # for chocolate in range (0, 101, 5) # print(chocolate) # # you can put text next to each item in a list by doing the below # chilli_wishlist = [ # "igloo", # "chicken", # "donut toy", # "cardboard box" # ] # for item in chilli_wishlist: # print(f"Chilli wants: {item}") # WHILE LOOPS # != exlamation mark= means not equal to # guess = "" # while guess != "a": # # guess = input("Guess a letter") # counter = 0 # while counter <= 5: # print(counter) # # counter = counter + 1 # EXERCISE: FOR LOOPS # QUESTION 1A # number = input("Enter a number: ") # for list in range (1,4): # answer = list * int(number) # print(f"{number} * {list} = {answer}") # # QUESTION 1B # number = input("Enter a number: ") # for list in range (1,8): # answer = list * int(number) # print(f"{number} * {list} = {answer}") # QUESTION 2 number = int(input("Enter a number: ")) sum = 0 upto = (1,n) for item in range [1, int(number)]: answer = item + int(number) print(f"{answer}") # Ask the user for a number. Use a for loop to sum from 0 to that number # addition = int(input("Enter a number.")) # sum = 0 # for i in range(addition + 1): # sum = sum + i # i = i + 1 # print("Sum is ", sum)
88e5cc9fd9822eab7345fb675f3e10c4eb272f14
young31/TIL
/startCamp/02_day/csv_handling/csv_read.py
431
3.640625
4
#read csv # 1. split # with open('dinner.csv', 'r', encoding='utf-8') as f: # lines = f.readlines() # for line in lines: # print(line.strip().split(',')) # ','기준으로 문자열 split # 2. csv reader import csv with open('dinner.csv', 'r', encoding='utf-8') as f: items = csv.reader(f) #print(items) # 이렇게 하면 <csv object라는 말도 함께 나옴> for item in items: print(item)
bc54ac59d0b5016a0a169d94b70606489ebdf5d5
sahkal/dynamic-programming
/003_Longest Palindromic Sequence.py
2,251
3.796875
4
#%% Imports and functions declarations def matrix_constructor(string_col: str, string_row: str) -> list: """ Construct a matrix suited for lcs :param string_col: string occupying the columns position :param string_row: string occupying the rows position :return: matrix on the proper format """ string_col = '0' + string_col string_row = '0' + string_row matrix = [] for i_row, row in enumerate(string_row): row_list = [] for i_col, col in enumerate(string_col): if i_row == 0: # Naming column row_list.append(col) else: if i_col == 0: # Naming row row_list.append(row) elif i_col == i_row: row_list.append(1) else: row_list.append(0) matrix.append(row_list) return matrix def lps(input_string: str) -> int: """ Given a string, returns the maximum palindrome lenght :param input_string: string to find palindromes on :return: maximum palindrom length """ matrix = matrix_constructor(string_col=input_string, string_row=input_string) for i_row in range(len(matrix)-2, 0, -1): for i_col in range(i_row+1, len(matrix)): if matrix[i_row][0] == matrix[0][i_col]: # Match - Equals to the bottom-left of that cell plus two. bottom_left_cell = matrix[i_row+1][i_col-1] matrix[i_row][i_col] = bottom_left_cell + 2 else: # Non Match - Maximum value from either directly to the left or the bottom cell. left_cell = matrix[i_row][i_col-1] bottom_cell = matrix[i_row+1][i_col] matrix[i_row][i_col] = max(left_cell, bottom_cell) return matrix[1][len(matrix)-1] #%% Test - Dev string = 'TACOCAT' solution = 7 assert solution == lps(input_string=string), 'Error on the algorithm implementation' string = 'BANANA' solution = 5 assert solution == lps(input_string=string), 'Error on the algorithm implementation' string = 'BANANO' solution = 3 assert solution == lps(input_string=string), 'Error on the algorithm implementation'
02498cd9d9507090390f1f56014b866ff89f7e5f
Bandita69/TFF
/Event.py
4,417
3.859375
4
from _datetime import datetime preparation_time = 30 donation_time = 30 class EventData(object): # @Nori # Definition explanation comes here... @staticmethod def get_event_date(): global ev_date isvaild = False while not isvaild: data = input("Enter your Event date (YYYY.MM.DD):") try: ev_date = datetime.strptime(data, "%Y.%m.%d") # Csak akkor engedi tovább az adatot ha ilyen formátumba van if ev_date.isoweekday() != 6 and ev_date.isoweekday() != 7: if (ev_date.date() - datetime.now().date()).days > 10: isvaild = True else: print("Your donation date have to be 10 days later from now") else: print("Event of date must not be on weekends") except ValueError: print(data, "is not vaild date! Try again(YYYY.MM.DD): ex: 2010.10.10") return ev_date # @Nori # Definition explanation comes here... @staticmethod def get_donation_start(): global don_start isvaild = False while not isvaild: data = input("Enter your Start of donation (HH:MM):") try: don_start = datetime.strptime(data, "%H:%M") # Csak akkor engedi tovább az adatot ha ilyen formátumba van isvaild = True except ValueError: print(data, "is not a valid time! HH:MM. ex: 13:10") return don_start # @Bandi # Definition explanation comes here... A donation event vége. HH:MM formátmban, pl 12:10 @staticmethod def get_donation_end(): global don_end isvaild = False while not isvaild: data = input("Enter your End of donation (HH:MM):") try: don_end = datetime.strptime(data, "%H:%M") # Csak akkor engedi tovább az adatot ha ilyen formátumba van if don_start < don_end: isvaild = True else: print("Donation End have to be later thad Donation Start! (Donation start:", don_start.strftime("%H:%M"), "):") except ValueError: print(data, "is not a valid time! HH:MM. ex: 13:10") return don_end # @Bandi # Definition explanation comes here... nem nulla az első szám, és 4 karakter valamint csak számok. @staticmethod def get_zip_code(): isvaild = False while not isvaild: ZIP = input("Enter your ZIP CODE (XXXX):") try: if int(ZIP) and len(ZIP) == 4: if ZIP[0] != "0": isvaild = True else: print(ZIP, "is not vaild! 1. number must not be 0!") else: print("ZIP must be 4 digits!") except ValueError: print("Only Numbers!") return ZIP # @Atilla # Asks for the donor's city. @staticmethod def get_city(): cities = ["Miskolc", "Kazincbarcika", "Szerencs", "Sarospatak"] # Asks for the input here first. city = input("Please enter the donor's city: ") # Keeps asking for the city while it does not match one from the cities list. while city not in cities: city = input("Donor's are accepted only from the following cities:\ Miskolc, Kazincbarcika, Szerencs and Sarospatak: ") # Returns with the city. return city # @Atilla # Asks for the donor's address. @staticmethod def get_address(): # Asks for the input here first. street = input("Please enter the donor's address: ") # Keeps asking for the address while it does not less or equal than 25 characters. while len(street) <= 25: street = input("The address should be less than 25 characters!: ") # Returns with the address. return street # @Mate # Definition explanation comes here... @staticmethod def get_available_beds(): return True # @Mate # Definition explanation comes here... @staticmethod def get_planned_donor_number(): return True # @Adam # Definition explanation comes here... @staticmethod def success_rate(): return True
3cc47bd3173415aad33f83187b36ce24833904c4
turamant/ToolKit
/PyQt_ToolKit/Layout/box_layout_1.py
1,049
3.609375
4
""" Контейнер коробка либо один столбец или строку виджетов. Меняется динамически в зависимости от количество виджетов Подобен GridLayout """ from PyQt5.QtWidgets import * import sys class Window(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): layout = QBoxLayout(QBoxLayout.LeftToRight) self.setLayout(layout) label = QLabel("Label 1") label.setToolTip("This ToolTip simply displays text.") layout.addWidget(label, 0) label = QLabel("Label 2") layout.addWidget(label, 0) layout2 = QBoxLayout(QBoxLayout.TopToBottom) layout.addLayout(layout2) label = QLabel("Label 3") layout2.addWidget(label, 0) label = QLabel("Label 4") layout2.addWidget(label, 0) self.show() if __name__=='__main__': app = QApplication(sys.argv) screen = Window() sys.exit(app.exec_())
fb69b302f7847eb8a3c4a621c131642b930b96a8
mingchia-andy-liu/practice
/daily/solved/1_easy_sum_k_in_an_array_COMPLETED/test.py
3,418
3.875
4
import unittest class Answer(): def __init__(self, k, arr): self.k = k self.arr = arr self.dict = {} def solve(self): if (len(self.arr) < 2): return False for element in self.arr: diff = self.k - element self.dict[diff] = True for element in self.arr: if (element in self.dict): return True return False class Answer2(): def __init__(self, k, arr): self.k = k self.arr = arr self.add = {} self.minus = {} def solve(self): if (len(self.arr) < 2): return False for element in self.arr: diff = self.k - element # diff in add for matching up with actual element in the array if (diff in self.add): return True # element in minus for matching current element with the diff of previous elements if (element in self.minus): return True self.minus[diff] = True self.add[element] = True return False class TestCase(unittest.TestCase): def test_num_1(self): ans = Answer(1, []) self.assertEqual(False, ans.solve()) def test_num_2(self): ans = Answer(5, [2, 1, 10, 5, 6, 2]) self.assertEqual(False, ans.solve()) def test_num_3(self): ans = Answer(1, [1, 1, 1, 1, 1]) self.assertEqual(False, ans.solve()) def test_num_4(self): ans = Answer(2, [2, 1, 2, 1, 2, 1]) self.assertEqual(True, ans.solve()) def test_num_4(self): ans = Answer(17, [10, 5, 2, 3, 7]) self.assertEqual(True, ans.solve()) def test_num_5(self): ans = Answer(1, [2, -1, 0, 1]) self.assertEqual(True, ans.solve()) def test_num_6(self): ans = Answer(-1, [-2, 1, 0, 1, 2, 3, 4, 5]) self.assertEqual(True, ans.solve()) def test_num_7(self): ans = Answer(1, [1]) self.assertEqual(False, ans.solve()) def test_num_8(self): ans = Answer(-5, [1, 10, 2, 4, 5, 61, 2, -2, -5]) self.assertEqual(False, ans.solve()) def test_num_9(self): ans = Answer(0, [0, 0, 0, 0, 0]) self.assertEqual(True, ans.solve()) def test_num_10(self): ans = Answer(5, [1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -5, 10]) self.assertEqual(True, ans.solve()) class TestCase2(unittest.TestCase): def test_num_1(self): ans = Answer2(1, []) self.assertEqual(False, ans.solve()) def test_num_2(self): ans = Answer2(5, [2, 1, 10, 5, 6, 2]) self.assertEqual(False, ans.solve()) def test_num_3(self): ans = Answer2(1, [1, 1, 1, 1, 1]) self.assertEqual(False, ans.solve()) def test_num_4(self): ans = Answer2(2, [2, 1, 2, 1, 2, 1]) self.assertEqual(True, ans.solve()) def test_num_4(self): ans = Answer2(17, [10, 5, 2, 3, 7]) self.assertEqual(True, ans.solve()) def test_num_5(self): ans = Answer2(1, [2, -1, 0, 1]) self.assertEqual(True, ans.solve()) def test_num_6(self): ans = Answer2(-1, [-2, 1, 0, 1, 2, 3, 4, 5]) self.assertEqual(True, ans.solve()) def test_num_7(self): ans = Answer2(1, [1]) self.assertEqual(False, ans.solve()) def test_num_8(self): ans = Answer2(-5, [1, 10, 2, 4, 5, 61, 2, -2, -5]) self.assertEqual(False, ans.solve()) def test_num_9(self): ans = Answer2(0, [0, 0, 0, 0, 0]) self.assertEqual(True, ans.solve()) def test_num_10(self): ans = Answer2(5, [1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -5, 10]) self.assertEqual(True, ans.solve()) def main(): unittest.main() if __name__ == "__main__": main()
4e5032b8f64f6d3e5b155ca31e2e245cf74a117b
mavega998/python-mintic-2022
/TALLER3/diaSemana.py
1,063
3.90625
4
semana = [ {"id": 0,"name": 'domingo'}, {"id": 1,"name": 'lunes'}, {"id": 2,"name": 'martes'}, {"id": 3,"name": 'miercoles'}, {"id": 4,"name": 'jueves'}, {"id": 5,"name": 'viernes'}, {"id": 6,"name": 'sabado'}, ] opcionValor = input("1. Buscar el número del día por nombre.\n2. Buscar el nombre del día por el nombre.\n") if opcionValor == '': print("Debe ingresar una opción.") elif int(opcionValor) == 1: nombre = input("Ingrese el nombre: ") if nombre == '': print("El nombre no es válido.") else: for i in range(0, len(semana)): if nombre == semana[i].get("name"): print(semana[i].get("id")) break elif int(opcionValor) == 2: número = input("Ingrese el número: ") if número == '': print("El número no es válido.") else: for i in range(0, len(semana)): if int(número) == semana[i].get("id"): print(semana[i].get("name")) break else: print("No es una opción válida.")
ae82e77f65b0a099e9e28a48578b13b80705bf65
svdmaar/tkinter1
/basics.py
652
3.96875
4
import tkinter as tk def OnButtonClick(): #print(entry.get()) #entry.delete(0,tk.END) #entry.insert(0, "Python") #print(text_box.get("1.0", tk.END)) #text_box.delete("1.0", tk.END) text_box.insert(tk.END, "Put me at the end!") window = tk.Tk() greeting = tk.Label( text="Hello, Tkinter!", foreground="white", background="black", width=10, height=10) greeting.pack() button = tk.Button(text="Click me!", width=25, height=5, bg="blue", fg="yellow", command=OnButtonClick) button.pack() #entry = tk.Entry(fg="yellow", bg="blue", width=50) #entry.pack() text_box = tk.Text() text_box.pack() window.mainloop()
1d4e4e92312cf922ca8574afc55540cff65d7004
wszeborowskimateusz/cryptography-exam
/ciphers_podstawieniowe.py
882
3.765625
4
alphabet = "AĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻ" def przesuwajacy(plain, k): cipher = "" for c in plain: if c in alphabet: cipher += alphabet[(alphabet.find(c) + k) % len(alphabet)] else: cipher += c return cipher def vigenere(plain, k): cipher = "" key_index = 0 for c in plain: if key_index >= len(k): key_index = 0 if c in alphabet: cipher += alphabet[(alphabet.find(c) + alphabet.find(k[key_index])) % len(alphabet)] key_index += 1 else: cipher += c return cipher # print(przesuwajacy("SZYFR␣CEZARA␣JEST␣PRZYKŁADEM␣SZYFRU␣PRZESUWAJĄCEGO", 2)) print(vigenere("ZDO SNMUBO LTXC YĄS Z JVBBV PŃPŃEEMSÓV AHŹFŚR FVŃŹOO ÓŹ CIJOPFMP ĆDŁLŚ OH ĆCDFG DVKGĆJŃBQ ŃĆŚĄŃMEK IITVCJU DĘ DĆĘV PPYŃYVMDŚĄ ŹJ", "GĄŚN"))
1154b10df64aec04468a891e966b86b342a6bb60
RiyazShaikAuxo/datascience_store
/2.numpy/FindRandomValues.py
250
3.6875
4
import numpy as np nrand=np.random.random() print(nrand) #Printing random value from 2 to 50 somevariable1=50*np.random.random()+2 print(somevariable1) #Creating a matrix with random values somevariable2=np.random.random([3,2]) print(somevariable2)
9c823eb8750c14c5bcd236c9db4f71e446f17028
janosgyerik/advent-of-code
/2018/day11/part2.py
1,492
3.8125
4
#!/usr/bin/env python import sys class Computer: def __init__(self, serial): self.serial = serial def power(self, row, col): rack_id = row + 10 return self.hundreds((rack_id * col + self.serial) * rack_id) - 5 def hundreds(self, n): return (n // 100) % 10 def print_grid(self, left, top, n): for y in range(top, top + n): for x in range(left, left + n): print('{:>3}'.format(self.power(x, y)), end=' ') print() def compute(self): highest, mx, my, mw = 0, 0, 0, 0 for w in range(3, 30): v, x, y = self.compute_w(w) print(v, x, y, w) if highest < v: highest, mx, my, mw = v, x, y, w return highest, mx, my, mw def compute_w(self, w): left = 1 top = 1 n = 300 grid = [] for y in range(top, top + n): row = [] for x in range(left, left + n): row.append(self.power(x, y)) grid.append(row) highest = -5 * w * w mx = 0 my = 0 for y in range(n - w - 1): for x in range(n - w - 1): p = sum(sum(grid[y2][x:x+w]) for y2 in range(y, y+w)) if highest < p: highest, mx, my = p, x, y return highest, mx + 1, my + 1 if __name__ == '__main__': serial = int(sys.argv[1]) c = Computer(serial) print(c.compute())
0fd9f4bf61a7857a2d06fc02b440ebfca578c112
haijiwuya/python-collections
/base/9.exception/introduce.py
687
4.125
4
""" 异常:程序在运行过程当中,不可避免的会出现一些错误,这些错误,称其为异常。 程序在运行过程中,一旦出现异常会导致程序立即终止,异常以后的代码不会被执行 """ try: print(10 / 1) except NameError as e: print('参数不存在', e, type(e)) except ZeroDivisionError as e: print('出错了', e, type(e)) else: print('程序执行完成') finally: print('方法调用完成') # raise抛出异常,raise语句后需要跟一个异常类 def add(a, b): if a < 0 or b < 0: # raise Exception raise Exception('参数不能小于0') r = a + b return r print(add(123, -1))
5411d553baced57db79465ad88f8ca5a7f4909c9
palakbaphna/pyprac
/print function/print Numbers/3PrintNumbers.py
384
4.125
4
print("*Multiplication Example*") print("a = ") a= int(input()) print("b = ") b = int(input()) print("c = ") c = int(input()) answer = a * b * c print( 'The answer of a*b*c = ' , answer ) if( answer > 100): #or if( a * b * c > 100) print( "Answer is greater than 100" ) else: print("Answer is not greater than 100")
b972f1541906f8fbc71fb7e031cca0c1c00dd99b
MSaaad/Basic-python-programs
/Leap year.py
409
4.03125
4
print('\tLEAP YEAR!') year='string' while True: year=int(input('Enter the year: ')) if len(str(year))!=4: print('Please enter a four digit input!') break if year%4==0: print('This is a leap year') elif year%400==0: print('This is a Leap year') elif year%100==0: print('This is a Leap year') else: print('Not a leap year')
e8d82e06c8b7bc60e5fd4d83d13cddccbd8510af
cpatrasciuc/algorithm-contests
/hackercup/2012/qualification/auction.py
1,845
3.5
4
def lcm(a,b): gcd, tmp = a,b while tmp: gcd,tmp = tmp, gcd % tmp return a*b/gcd def isBetter(A, B): return (A[0] < B[0] and not A[1] > B[1]) or (A[1] < B[1] and not A[0] > B[0]) def solve(line): N, P1, W1, M, K, A, B, C, D = tuple([int(x) for x in line.split()]) LCM = lcm(M, K) #print LCM products = [(P1, W1)] for i in range(1): break P1 = ((A*P1 + B) % M) + 1 W1 = ((C*W1 + D) % K) + 1 #print "%s %s" % (P1, W1) products.append((P1, W1)) if products[0] == products[-1]: products = products[:-1] break return "%s %s" % (LCM, N) bargain = [True for _ in products] terrible = [True for _ in products] for i in range(len(products)): for q in products: if products[i] != q: if isBetter(q, products[i]): bargain[i] = False break for q in products: if products[i] != q: if isBetter(products[i], q): terrible[i] = False break print bargain print terrible total_bargains = 0 for i in range(len(products)): if bargain[i]: total_bargains += N / len(products) if N % len(products) > i: total_bargains += 1 total_terrible = 0 for i in range(len(products)): if terrible[i]: total_terrible += N / len(products) if N % len(products) > i: total_terrible += 1 print "=" * 20 return "%s %s" % (total_terrible, total_bargains) lines = open("in.txt", "r").readlines() T = int(lines[0]) out = open("out.txt", "w") for test in range(1, T+1): result = solve(lines[test].strip()) out.write("Case #%s: %s\n" % (test, result)) out.close()
4349cea2e2653bbbb9e6610b8060af52251295e6
hojunee/20-fall-adv-stat-programming
/sol8/ex17-5.py
603
3.796875
4
class Point(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return ("점 ({}, {})".format(self.x, self.y)) def __add__(self, other): if isinstance(other, Point): return self.point_add(other) elif isinstance(other, tuple): return self.tuple_add(other) def point_add(self, other): return (self.x + other.x, self.y + other.y) def tuple_add(self, other): return (self.x + other[0], self.y + other[1]) a = Point(3, 4) b = Point(8, 2) print(a + b) print(a + (8, 2))
e9f5bab0dd2dfff9a442594b0de53e642a98c870
kimtk94/test1
/025.py
216
3.546875
4
#25 문자열 n씩 건너뛰며 출력하기 seq1 = "ATGTTATAG" Ans = [] for i in range(0,len(seq1), 3): Ans.append(seq1[i]) print(Ans) #강사님 답안 for i in range(0, len(seq1),3): print(i, seq1[i])
67201135a55281c1fb08080e1e839a8c92fc3908
pisceskelsey/class-work
/chapter 7.py
3,916
4.21875
4
people = input("How many people are in your party?" ) people = int(people) if(people > 8): print("There may be some delays.") else: print("Your table is ready.") number = input("Give me a number. ") number = int(number) if number % 10 == 0: print("\nThe number " + str(number) + " is a multiple of 10.") else: print("\nThe number " + str(number) + " is not a multiple of 10.") prompt = "\nPlease enter requested pizza toppings:" prompt +="\n(Enter 'quit' when done.)" while True: toppings = input(prompt) if toppings == 'quit': break else: print("We will put " + toppings.title() + " on your pizza.") age = input("How old are you? ") age = int(age) if age >= 3: print("Your ticket is free!") elseif: print("Your ticket is $10.") else: print("Your ticket is $12.") message = "Please input your age." active == True while active: message = input(prompt) if message == 'quit': active = False else: print(message) x = 1 while x <= 5: print(x) sandwich_orders = ['ham,' 'cheese,' 'tuna,' 'chicken'] finished_sandwiches = [] for sandwich in sandwich_orders: print("I made you a " + sandwich.title() + " for lunch.") while sandwich_orders: finished_sandwiches = sandwich_orders.pop() print("Making sandwich: " + finished_sandwiches.title()) finished_sandwiches.append(sandwich_orders) sandwich_orders = ['ham,' 'cheese,' 'pastrami,' 'tuna,' 'pastrami,' 'chicken,' 'pastrami'] print("The deli has run out of pastrami.") while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') print(sandwich_orders) polling_active == True place = input("\nWhere would you like to visit? ") dream_vacation = input("\nIf you could only go one place, where would you go? ") vacations[place] == dream_vacation polling_active == False print(\n--- Poll Results ---") for place, dream_vacation in vacations.items(): print("I would go to " + place.title() " or go to " + dream_vacation.title() + "!") def make_shirt(shirt_size, shirt_message): make_shirt('Medium,' 'I love python!') make_shirt('Large,' 'I love python!') make_shirt('Small,' 'Tastes like chicken!') def describe_city(city, country): describe_city('Atlanta,' 'United States') print("I live in " + city.title() + " in " + country.title() + "!") describe_city('Seattle,' 'United States') describe_city('San Francisco,' 'United States') describe_city('Vancouver,' 'Canada') def city_place(city_name, city_country): place = {'city': city_name, 'country': city_country} return place home = city_place('seattle', 'United states') print(home) def make_album(artist_name, album_title, album_tracks) album = {'artist': artist_name, 'title': album_title, 'tracks': album_tracks} return album gorillaz = make_album('Gorillaz', 'Demon Days', '12') beatles = make_album('The Beatles', 'Hard Days Night', '6') fleetwood = make_album('Fleetwood Mac', 'Rumors', '13') print(gorillaz) print(fleetwood) print(beatles) while True: print("\nTell me an album you like: ") ar_name = input("Artist Name: ") al_name = input("Album Name: ") if ar_name == 'q' break if al_name == 'q' break magicians = ['David Copperfield', 'David Blane', 'Houdini'] show_magicians(magicians) great_magicians = [] while magicians: make_great = magicians.pop() great_magicians.append(make_great) print(great_magicians) print("Presenting the Great " + great_magicians.title() + "!") def make_sandwich(*toppings): print(toppings) make_sandwich('ham', 'turkey', 'pastrami', 'blt') print("\nWe are building your sandwich with:") for topping in toppings: print("- " + topping)
5b0546838cf01fa00c20ccd4ef6fd8d36cc325c5
Kuomenghsin/my-learning-note
/HW3/binary_search_tree_06111306.py
3,624
3.90625
4
#!/usr/bin/env python # coding: utf-8 # In[16]: class TreeNode(object): def __init__(self,x): self.val=x self.left=None self.right=None class Solution(object): #新增 def insert(self,root,val): #root空 if root == None: N_node = TreeNode(val) return N_node #加入數值=root else root.val == val: root.left = TreeNode(val) N_node.left = root.left root.left = N_node return N_node #加入數值小於root的情況 if root.val > val and root != None and root.val != val: # 左邊沒有子數,直接加入 if root.left == None: N_node = TreeNode(val) root.left =N_node return N_node else: #把左子樹(root.left)當作root #並遞迴直到找出val應加入的位置 return Solution().insert(root.left,val) #加入數值大於root的情況 if root.val < val and root != None and root.val != val: if root.right == None: N_node=TreeNode(val) root.right = N_node return N_node else: #把右子樹(root.right)當作root #並遞迴直到找出val應加入的位置 ruturn Solution().insert(root.right,val) #搜尋 def search(self,root,target): #目標小於root if target < root.val: return Solution().search(self,root.left,target) #目標大於root elif target > root.val: return Solution().search(self,root.right,target) #目標等於root elif target == root.val: return root #找不到 else: return None #左邊最大function def maxVal(self,root) Max = root while(root.right != None): Max = Max.right return Max #刪除(正確) def delete(self,root,target): #找到目標 if root.val = target: root.val = None return root #欲刪除的目標在右邊 if target > root.val: root.right = Solution().delete(root.right, target) #欲刪除的目標在左邊 elif target < root.val: root.left = Solution().delete(root.left, target) else: #若沒有子樹或只有一個 if root.right != None: temp = root.left root = None return temp else root.left != None: tem = root.right root = None return temp #左右皆有子樹,找左邊最大補 tem = maxVal(root.left) #複製他到刪除的node root.val = temp.val #刪掉原本左邊最大的節點 root.left = Solution().delete(root.left, temp.val) return root #修改 def modify(self,root,target,val): if target != val: #透過前面的insert加入欲輸入的值 Solution().insert(root,val) #透過刪除刪掉原先的值 return Solution().delete(root,target) else: return root # In[ ]:
376d3a72f63754dea7e56c03976d9d8213752e01
theJMC/codeProjects
/Python/MIsc/ProductInventorySystem.py
541
3.921875
4
import sqlite3 from employee import Employee conn = sqlite3.connect('employee.db') c = conn.cursor() # c.execute("""CREATE TABLE employees ( # first text, # last text, # pay integer # )""") emp_1 = Employee('John', 'Doe', 80000) emp_2 = Employee('Tom', 'Smith', 100000) c.execute("INSERT INTO employees VALUES (?, ?, ?)", (emp_1.first, emp_1.last, emp_1.pay)) conn.commit() c.execute("SELECT * FROM employees") print(c.fetchall()) conn.commit() conn.close()
aceb6a8e8345755d90401ca892be0271d85adfb3
sjogden/Bones-of-the-Earth
/camera.py
1,735
3.59375
4
import pygame class Background(): """Background image that can scroll infinitely""" def __init__(self): self.image = pygame.image.load("data/background/Background.png") self.x1 = 0 self.x2 = 1000 def update(self, screen): #if about to scroll off the screen, move back to center if self.x1 < -900: self.x1 = self.x2 self.x2 += 1000 if self.x1 > -100: self.x2 = self.x1 self.x1 -= 1000 #draw screen.blit(self.image, (self.x1, 0)) screen.blit(self.image, (self.x2, 0)) def shift(self, diff): self.x1 += diff self.x2 += diff class Camera(): """Moves the stage and background when the player moves too close to the edge""" def __init__(self, enemies, platforms, arrows, lasers, player, background): #gets copies of all game items self.items = [enemies, platforms, arrows, lasers] self.player = player self.background = background self.displacement = 0 def update(self): #checks player position on screen if self.player.rect.right > 500: diff = 500 - self.player.rect.right self.player.rect.right = 500 self.shift(diff) if self.player.rect.left < 300: diff = 300 - self.player.rect.left self.player.rect.left = 300 self.shift(diff) def shift(self, diff): #shifts level & enemies & background for item in self.items: for sprite in item: sprite.rect.x += diff self.background.shift(diff // 2) self.displacement -= diff
c9f25aca7ea58e7d82edaf38b8d9782de2a92b87
orangepips/hackerrank-python
/artificialintelligence/botbuilding/bot_saves_princess2.py
873
3.5
4
#!/bin/python from operator import sub # https://www.hackerrank.com/challenges/saveprincess2 _bot = 'm' _princess = 'p' def nextMove(n,r,c,grid): bot_loc = (c, r) princess_loc = (None, None) for lineIdx, line in enumerate(grid): for cIdx, c in enumerate(line): if c == _princess: princess_loc = (cIdx, lineIdx) distance = tuple(map(sub, bot_loc, princess_loc)) output = '' if distance[1] != 0: output = 'UP\n' if distance[1] > 0 else 'DOWN\n' if len(output) == 0 and distance[0] != 0: output = ('LEFT\n' if distance[0] > 0 else 'RIGHT\n') return output def main(): n = input() r, c = [int(i) for i in raw_input().strip().split()] grid = [] for i in xrange(0, n): grid.append(raw_input()) print nextMove(n, r, c, grid) if __name__ == '__main__': main()
ccdc4db9344138446c252e7d0d887cdc1b3b0b95
SUMANTHTP/launchpad-assignment
/p2.py
93
3.671875
4
a = [1,1,2,3,5,8,13,21,34,55,89] b = [] for i in a: if i < 5: b.append(i) print(b);
527e9d076eaaf15c0ff3fca037d088f84fd86037
AlexSopa/Python
/CommentedTutorialScripts/SecondProject/LearningNumpy.py
1,133
4.28125
4
import numpy as np a = np.arange(15).reshape(3, 5) #What does this look like? print(a) #How many axis does this have? print('There is %d axis' % a.ndim) print(('The shape of a is {}').format(a.shape)) #Creating a zero array zeros = np.zeros((10,10), dtype=np.int16) #dtype decides what kind of number it is(int16 is an int, the default is float I believe) print(zeros) #What is the shape of this one? print(zeros.shape) #If you want an array instead of a list do this stuff arraysRbetter = np.array([10,5,2,3,4,2,]) print(('Arrays are just this much better >> {}').format(arraysRbetter)) #Asking for numbers for an array #five_num = input("Give me 5 numbers seperated by commans ex : 1,2,3,4,5") #This sends the message and waits for input #type(five_num) #five_num should now be = to the 5 numbers they gave or whatever else they typed in #More types of arrays you can make a2 = np.ones( (5,3,8), dtype=np.int16) print(a2) a = np.array([(1,2,3)]) #You can find datatypes of an array print(a.dtype) #You can reshape array data a = np.array([(8,9,10),(11,12,13)]) print(a) #Reshapes it into a 3x2 array a=a.reshape(3,2) print(a)
48033675cfcbd3596218c7a6cdaa4d197ddc1a9f
DeepakMulakala/my-files
/happy.py
282
3.625
4
n=int(input()) temp=0 i=0 k=n while n: r=n%10 n=n//10 i=i+pow(r,2) if n==0 and i>=10: n=i print(n) i=0 if i<10: print (i) if i==1: print(k,"is a happy number") else: print(k,"is not a happy number")
65d2d8ad77e3d01bfb69216caf5be601c5b42350
xuedong/hacker-rank
/Tutorials/10 Days of Statistics/Day 7/spearman_rank_correlation.py
620
3.59375
4
#!/bin/python3 def get_rank(arr): n = len(arr) rank = [0 for i in range(n)] for i in range(n): rank_i = 0 for j in range(n): if arr[j] > arr[i]: rank_i += 1 rank[i] = rank_i + 1 return rank def spearman(rank1, rank2, n): total = 0 for i in range(n): total += (rank1[i] - rank2[i]) ** 2 return 1 - 6*total/(n*(n**2-1)) n = int(input()) arr1 = [float(arr_i) for arr_i in input().strip().split(' ')] arr2 = [float(arr_i) for arr_i in input().strip().split(' ')] print(round(spearman(get_rank(arr1), get_rank(arr2), n), 3))
b20de2a69ac0602069305f11b08338b1089c9905
Mia416/PythonPratices
/chentestPython1/ListExample/ListExample2.py
156
3.671875
4
''' Created on May 23, 2017 @author: chenz ''' items = ["1","2","3","4"] [int(item) for item in items] for item_value in items: print (item_value)
3be70e8cdceffb51e28747b42804ec3b1e1f2c10
r-azh/TestProject
/TestPython/test_lambda_map_filter_reduce/test_filter.py
484
3.953125
4
__author__ = 'R.Azh' # filter(function, sequence) # offers an elegant way to filter out all the elements of a sequence "sequence", # for which the function function returns True. fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] print(fibonacci) odd_numbers = list(filter(lambda x: x % 2, fibonacci)) print(odd_numbers) even_numbers = list(filter(lambda x: x % 2 == 0, fibonacci)) print(even_numbers) even_numbers = list(filter(lambda x: x % 2 - 1, fibonacci)) print(even_numbers)
fcbf00154a07283b4e7fce5bd3d33bd9fe3e9854
RicardoMart922/estudo_Python
/Exercicios/Exercicio019.py
445
3.96875
4
# faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. from math import hypot catetooposto = float(input('Informe o comprimento do cateto oposto: ')) catetoadjacente = float(input('Informe o comprimento do cateto adjacente: ')) hipotenusa = hypot(catetooposto, catetoadjacente) print('O comprimento da hipotenusa é {:.2f}'.format(hipotenusa))
273ad71cc3482fac24489d1c67cc8021e376d3f7
pmkhedikar/python_practicsRepo
/concepts/class/opps_1.py
9,911
4.375
4
## Class # class phone(): # # def __init__(self, ram, memory): # self.ram = ram # self.memory = memory # # def config(self, ram, memory): # print( 'config is :', self.ram, self.memory ) # # # phone1 = phone('2','32gb') # phone1.config('2','32gb') ## Self & Constructor ## Self represents the instance of the class. ## By using the “self” keyword we can access the attributes(Variable) and methods(Function) of the class in python. ## "__init__" is a reserved method in python classes. ## It is called as a constructor in object oriented terminology. ## This method is called when an object is created from a class and it allows the class to initialize the attributes of the class. # # class Phone: # # def __init__(self): # self.name = 'Moto' # self.price = 10 # # def update(self): #update name inside the class # self.name ='new Phone' # self.price = 20 # # def compare(self,other): # if self.price == other.price: # return True # else: # return False # # # p1 = Phone() # p2 = Phone() # # p1.name ='iphone' #update name 1 outside the class # print(p1.name) # # # # p2.update() #called update method to change the name # print(p2.name) # # p2.update() # p2.price =30 # print(p1.price) # print(p2.price) # print(p1.compare(p2)) # # Type of Variable - Instance/Static Variable & Class variable # class Car(): # # wheels = 4 #class variable # # def __init__(self): # self.name = 'VOLVO' # Instance Variable # self.color = 'RED' # c1 = Car() # c2 = Car() # c2.name = 'BMW' # update the name of an object c2 # Car.wheels = 8 # update the class variable Variables # c2.color = 'Black' # # print(c1.name,c1.color,c1.wheels) # print(c2.name,c2.color,c2.wheels) ## Instance Method , Class method ,Static Method # class School(): # # schoolName = 'NPK SCHOOL' # # def __init__(self,m1,m2,m3): # self.m1 = m1 # self.m2 = m2 # self.m3 = m3 # # def avg(self): # return (self.m1+self.m2+self.m3)/3 # # @classmethod # class Method # def GetSchoolName(cls): # return cls.schoolName # # @staticmethod # def principle(): # Static Method # print('This is static method not passing any self keyword') # # # # s1 = School(10,20,30) # print(s1.avg()) # calling instance method # print(School.GetSchoolName()) # calling class method # School.schoolName = 'MIET' # Updated the class/static variable # print(School.GetSchoolName()) # calling class method # School.principle() # calling static method not passed an argument ## Inner Class in Python ## Can create the object of child class in parent class ## Can create the object of child class outside the parent class - but u have to call the parent class # class Student(): # # def __init__(self,name,rollNo): # self.name = name # self.rollNo = rollNo # self.lap = self.laptop() # # def show(self): # print(self.name,self.rollNo) # self.lap.show() # # class laptop(): # def __init__(self): # self.brand = 'Mac' # self.ram = '4gb' # self.cpu = 'ios5' # # def show(self): # print(self.brand,self.ram,self.cpu) # # s1 = Student('Parag',684) # s2 = Student('Arvind',101) # print(s1.name,s1.rollNo,s2.name,s2.rollNo) # lap1 = s1.laptop() # print(lap1.brand) # s1.show() # print(lap1.brand,lap1.ram) # lap1 = Student.laptop() # print(lap1.brand,lap1.ram,lap1.cpu) ############################################################################# ## Inheritance Parent - child relation ## Inheritance allows us to define a class that inherits all the methods and properties from another class # class A: # def feature1(self): # print('Class A - Feature 1') # def feature2(self): # print('Class A - Feature 2') # # class B(A): # def feature3(self): # print('Class B - Feature 3') # def feature4(self): # print('Class B - Feature 4') # def feature1(self): # print('Class B - Feature 1') # # class C(B,A): # def feature5(self): # print( 'Class C - Feature 5' ) # def feature1(self): # print('Class C - Feature 1') # a1 = A() # As its parent class ,uses the method of class A only # a1.feature1() # # b1 = B() #Can access all the methods in A & B class # b1.feature2() # c1 = C() # # c1.feature4() # Multilevel inheritance can access method in both A & B class # c1.feature1() ################################################################# ## - Constructor in inheritance ## 1. if __init__ method not found in sub-class execute the __init__ in parent class ## 2. if __init__ method found in sub-class execute the __init__ in subclass ## 3. if want to call __inti__ in parent class use the keyword super to call the method in parent class ## MRO - method resolution order - Give the preference from left to right C(B,A) # # # class A: # def __init__(self): # print('Class -A ,init method') # def feature1(self): # print('Class A - Feature 1') # def feature2(self): # print('Class A - Feature 2') # def feature3(self): # print('Class A - Feature 3') # # class B: # def __init__(self): # #super().__init__() # print('Class -B ,init method') # def feature3(self): # print('Class B - Feature 3') # def feature4(self): # print('Class B - Feature 4') # # class C(A,B): # def __init__(self): # super().__init__() # print('Class -C ,init method') # def feature5(self): # print( 'Class C - Feature 5' ) # # def feature3(self): # # print('Class C - Feature 3') # # # c1 = C() # c1.feature3() ################################################################################# ## Polymorphism (Many + Form) ## concept of using common operation in diff ways for diff data inputs ## 1.Duck typing - Interface / class should have that method that what we concern ## you shouldn't care what type of object you have - just whether or not you can do the required action with your object. # class Pycharm: # def execute(self): # print('Compliling') # print('Error Checking') # # class Myeditor: # def execute(self): # print('Spell checking') # print('Syntax checking') # print('Compliling') # print('Error Checking') # # # class Laptop: # def code(self,ide): # ide.execute() # # ide1 = Pycharm() # ide2 = Myeditor() # lap1 = Laptop() # lap1.code(ide2) ### Operator Overloading - Every operator has its own behaviour and that define behind the screen, if we want to change the behaviour of that operator depends upon our need thats called operator overloading ### Same method with different argument eg. __add__() ## We can overload all existing operators but we can't create a new operator # class Student: # def __init__(self,m1,m2): # self.m1 = m1 # self.m2 = m2 # # def __add__(self, other): # a1 = self.m1 + other.m1 # a2 = self.m2 + other.m2 # add = a1 + a2 # return add # # def __str__(self): # #return self.m1,self.m2 -return a tuple # return '{} {}'.format(self.m1,self.m2) #converted into string # # s1 = Student(10,20) # s2 = Student(100,200) # print(s1.m1,s1.m2) # s3 = s1 + s2 # print(s3) # # a = 5 # print(a) # print(s1.__str__()) # uncomment - return self.m1,self.m2 -return a tuple # print(s1) ### Method Overloading ### A class having same method with different parameter/argument called method overloading # class Student(): # def __init__(self): # self.m1 = 10 # self.m2 = 20 # # def sum(self,a=None,b=None,c=None): # if a != None and b != None and c != None: # return a+b+c # elif a != None and b !=None: # return a+b # else: # return a # s1 = Student() # print(s1.sum(1,2)) ## Method Over-ridding ## Override means having two methods with the same name but doing different tasks. ## It occurs by simply defining in the child class a method with the same name of a method in the parent class # class A: # def show(self): # print('Show Method in Class A') # # class B(A): # def show(self): # print('Show Method in Class B') # # pass # # a = B() #Created a object for class B # a.show() # It will first search the method in class B & if not found then check in class A # ### Abstrcat class & method ### ABC - abostract base classes ### Encapsulation : Restrict the access the variable and methods// Hiding private details of class from other objects ## Private(use with in class) & Public method (access outside the class) # class Car: # __speed = 0 # Private Variable modify only inside class # __name = '' # def __init__(self): # self.__speed = 100 # self.__name = 'BMW' # #self.__update() # Define inside __init method # # def drive(self): # #self.__update() # Define inside method inside class # print('Drive pubic method') # print(self.__name) # print(self.__speed) # # def __update(self): # can't access outside the class # print('updating - Private Method') # # def newUpdate(self,newname,maxspeed): # self.__speed =maxspeed # self.__name =newname # print(newname,maxspeed) # # c1 = Car() # c1.drive() # c1.newUpdate('Audi',500) ################################################################################################################################################################ # class dance(): # def __init__(self,a): # self.a = a # o1 = dance(15) # print(o1.a)
e3332df1f6d90a6fe18046ce55614a9f2934f632
epersike/py-simple-structs
/queue.py
1,530
3.8125
4
class SimpleQueueDequeueException(Exception): pass class SimpleQueueItem: def __init__(self, obj=None, prev=None, nxt=None): self.obj = obj self.prev = prev self.next = nxt def __str__(self): return str(self.obj) class SimpleQueue: def __init__(self): self.len = 0 self.first = None self.q = None def add(self, obj): ''' Add obj to the end of the queue. ''' newObj = SimpleQueueItem(obj) if self.first == None: self.first = self.q = newObj else: self.q.next = newObj newObj.previous = self.q self.q = newObj self.len += 1 def dequeue (self): ''' Return the first(est) item queued. ''' if self.first is None: raise SimpleQueueDequeueException('Empty queue.') item = self.first.obj self.first = self.first.next self.len -= 1 return item def is_empty(self): ''' Returns false if the queue size is equal 0. ''' return self.size() == 0 def push(self, obj): ''' Alias for 'SimpleQueue.add'. ''' self.add(obj) def pop(self): ''' Alias for 'SimpleQueue.dequeue'. ''' return self.dequeue() def __len__(self): ''' Returns the length of the list. ''' return self.len def size(self): ''' Alias for 'SimpleQueue.__len__'. Returns the length of the list. ''' return len(self) def __str__(self): ''' Shows the content of queued objects. ''' ret = '' obj = self.first while obj is not None: ret += str(obj) obj = obj.next if obj is not None: ret += ' -> ' return ret
8e64a982c51e2fa487239581b8210e69611a0dae
emmassr/MM_python_quiz
/week2_exercise.py
2,519
4.53125
5
# For this exercise you will need the Pandas package. You can import this using: #Q1: Create a Pandas dataframe with 3 columns: User, Fruit and Quantity. #Insert Junaid, Tom, Dick, Harry as Users. #Insert Apple, Oranges, Bananas, Mango as Fruit #Insert 4, 3, 11, 7 as Quantity #Each user should have their own row, this table should have 4 rows, you may name this dataframe what you like. import pandas as pd data = [['Junaid', 'Apple',4 ], ['Tom', 'Oranges', 3], ['Dick', 'Bananas', 11], ['Harry', 'Mango', 7]] df = pd.DataFrame(data, columns=['User', 'Fruit', 'Quantity']) #df = pd.DataFrame({'Users': ['Junaid', 'Tom', 'Dick', 'Harry'], 'Fruit' : ['Apple', 'Oranges', 'Bananas', 'Mango'], 'Quantity': [4,3,11,7]}) #print(df) #Q2: Read in the transactions CSV file into Python, call this df and print the first 5 rows csv_file = pd.read_csv("transactions.csv") #print(csv_file.head(5)) #Q3: List the column names in the df dataframe. Express the answer as a list #new_df_list = list(df) #print(new_df_list) #Q4: Count the number of rows in the dataframe total_rows = len(csv_file) print(total_rows) #Q5: How many unique customer ids do we have? print(len(csv_file.customer_id.unique())) ## Q6: What is the minimum value, maximum value, mean value and median value for the price column print(csv_file.price.describe()) # Q7: Filter the dataframe so that only the transactions for customer_id 'ABC' are returned. Call this ABC_df ABC_df = csv_file[csv_file.customer_id == 'ABC'] print(ABC_df) # Q8: Filter the dataframe so that only the transactions with quantity more than 10 are returned and occurred later than the 1st of January new_filter = csv_file[(csv_file.quantity > 10) & (csv_file.date >= '02/01/2020')] print(new_filter) # Q9: How many rows are there in df where the price more than £10? Note: Pounds only, ignore the pence print(len(csv_file[csv_file.price >10])) # Q10: Add a new column to df where you multiply price and quantity - call this revenue csv_file['revenue'] = csv_file['price'] * csv_file['quantity'] print(csv_file) # Q11: Add a new column to df where you report the price in pounds only E.g. 12.05 becomes 12. Round up to the nearest pound - call this price_pounds. Hint: look up ceiling function import numpy as np csv_file['price in pounds'] = np.ceil(csv_file['price']) print(csv_file) #Q12: Create an indicator column where True marks if the quantity is a multiple of 2 # and False otherwise - call this quantity_indicator Hint: Look at Numpy Select and or Lambda functions
3143a93e7964b09a65770f893960771ac70c6fbf
qmnguyenw/python_py4e
/geeksforgeeks/python/medium/17_12.py
4,834
4.21875
4
GridLayouts in Kivy | Python Kivy is a platform independent as it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Use this command To install kivy: pip install kivy > 👉🏽 Kivy Tutorial – Learn Kivy with Examples. **Gridlayout** is the function which creates the children and arrange them in a matrix format. It takes the available space(square) and divides that space into rows and columns then add the widgets accordingly to the resulting cells or grids. We can not explicitly place the widgets in a particular column/row. Each child is assigned a particular position automatically determined by the layout configuration and the child index in children list. A gridlayout must contain at least on input constraints i.e. cols and rows. If we do not specify the cols or rows to it, the layout gives you an exception. #### Coloumn and Row – Now the Coulums represent the width and the rows represents the hight just like matrix. * Initial the size is given by the col_default_width and row_default_height properties. We can force the default size by setting the col_force_default or row_force_default property. This will force the layout to ignore the width and _size_hint_ properties of children and use the default size. * To customize the size of a single column or row, use cols_minimum or rows_minimum. * It is not necessary to give both rows and columns, it depends on the requirement. We can provide either both or anyone accordingly. In the given below example, all the widgets will have the same or equal size. By default, the size is (1, 1) so the child will take full size of the parent. __ __ __ __ __ __ __ # main.py # import the kivy module import kivy # It’s required that the base Class # of your App inherits from the App class. from kivy.app import App from kivy.uix.gridlayout import GridLayout # This class stores the info of .kv file # when it is called goes to my.kv file class MainWidget(GridLayout): pass # we are defining the Base Class of our Kivy App class myApp(App): def build(self): # return a MainWidget() as a root widget return MainWidget() if __name__ == '__main__': # Here the class MyApp is initialized # and its run() method called. myApp().run() --- __ __ **Note :** For understanding how to use .kv files, just visit this. **Code #1:** __ __ __ __ __ __ __ # my.kv file code here <MainWidget>: cols: 2 rows: 2 Button: text: 'Hello 1' Button: text: 'World 1' Button: text: 'Hello 2' Button: text: 'World 2' --- __ __ **Output:** ![](https://media.geeksforgeeks.org/wp- content/uploads/20190329120905/gridlayout_1.jpg) **Note:** To run this code you have to make the main.py python file for the above python code and another file my.kv file. **Code #2:** Now let’s fix the size of the buttons to 100px instead of default _size_hint_x = 1_. __ __ __ __ __ __ __ # just do change in the above my.kv # (code #1) file else all are same. <MainWidget>: cols: 2 rows: 2 Button: text: 'Hello 1' size_hint_x: None width: 100 Button: text: 'World 1' Button: text: 'Hello 2' size_hint_x: None width: 100 Button: text: 'World 2' --- __ __ **Output :** ![](https://media.geeksforgeeks.org/wp- content/uploads/20190329121406/gridlayout_2.jpg) **Code #3:** We can also fix the row hight to a specific size. __ __ __ __ __ __ __ # just do change in the above my.kv # (code #1)file else all are same. <MainWidget>: cols: 2 rows: 2 row_force_default: True row_default_height: 40 Button: text: 'Hello 1' size_hint_x: None width: 100 Button: text: 'World 1' Button: text: 'Hello 2' size_hint_x: None width: 100 Button: text: 'World 2' --- __ __ **Output:** ![](https://media.geeksforgeeks.org/wp- content/uploads/20190329122653/gridlayout_3.jpg) Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
c49e1ac865a378daf4877c5f0438d04a4483dcc6
Sheepsftw/attack-cities-v2
/logic.py
1,965
3.578125
4
import math import play_board class Path: def __init__(self, city_array): self.path = city_array def add(self, city): self.path.append(city) def to_string(self): ret = "" for c in self.path: ret += str(c.hash) + " " return ret def clear(self): self.path.clear() # make a new class called board with City() as a class and then import board on both scripts def find_path(start_city, end_city, cities): visited = [] vals = [] paths = [] # really need to find a way to change this for a in range(0, len(cities)): vals.append(float('inf')) visited.append(False) paths.append(Path([])) vals[start_city.hash] = 0 paths[start_city.hash] = Path([start_city]) return dijkstra(start_city, end_city, visited, vals, paths, cities) # right now cant move from city 2 to city 1 (army sieges/battles nothing?) def dijkstra(start_city, end_city, visited, vals, paths, cities): # dont like this if start_city.hash == end_city.hash: return paths[end_city.hash].path visited[start_city.hash] = True for e in start_city.edges: if visited[e.hash]: continue temp_dist = vals[start_city.hash] + calc_dist(start_city, e) if vals[e.hash] > temp_dist: vals[e.hash] = temp_dist paths[e.hash].clear() temp_path = paths[start_city.hash].path temp_path = temp_path + [e] paths[e.hash] = Path(temp_path) # find the next closest city to our visited lowest_val = float('inf') temp = -1 for a in range(0, len(vals)): if not visited[a] and vals[a] < lowest_val: lowest_val = vals[a] temp = a return dijkstra(cities[temp], end_city, visited, vals, paths, cities) def calc_dist(city1, city2): return math.sqrt((city1.loc_x - city2.loc_x) ** 2 + (city1.loc_y - city2.loc_y) ** 2)
40cd76a18d4938c6d71b846488dc65039b00f972
samuelvgv/122
/Ex_3_8.py
337
3.875
4
dia = int( input('Introduce un día de la semana (entre 1 y 7) : ') ) print('El día es ... ', end='') if dia == 1: print('lunes') elif dia == 2: print('martes') elif dia == 3: print('miércoles') elif dia == 4: print('jueves') elif dia == 5: print('viernes') elif dia == 6 or dia == 7: print('festivo') else: print('incorrecto')
c15e68f4a0fe1eccfa6636047b8fe3d63cb97af7
MikeOcc/MyProjectEulerFiles
/Euler_8_356.py
1,927
3.703125
4
from math import cos from decimal import Decimal def newt(n): roots = [] b = float(2**n) bp = 2*b d = float(n) A0=-1 A=A0 while 1: #print A #if A==0:A=1 for x in xrange(1000): A -= (A**3 -b*A**2 + d)/(3.*A**2 -bp*A ) #A -= (A*A)*(A**3 -b*A**2 + d)/(3.*A**2 -bp*A ) #print A0,x, A #if A**3 -b*A**2 + d==0:break #print if 1: # (A**3 -b*A**2 + d==0): if A not in roots: match=False for r in roots: if round(r,9)==round(A,9): match = True if match == False: roots.append(A) print "!!!",A, roots print if A0==-1:A0=1 else: A0+=1 A = A0 if len(roots)==3: #print "time to break" break print "Roots:",roots print "A0",A0 return max(roots) def cubic(a, b, c, d=None): if d: # (ax^3 + bx^2 + cx + d = 0) a, b, c = b / float(a), c / float(a), d / float(a) t = a / 3.0 p, q = b - 3 * t**2, c - b * t + 2 * t**3 u, v = quadratic(q, -(p/3.0)**3) if type(u) == type(0j): # complex cubic root r, w = polar(u.real, u.imag) y1 = 2 * cbrt(r) * cos(w / 3.0) else: # real root y1 = cbrt(u) + cbrt(v) y2, y3 = quadratic(y1, p + y1**2) return y1 - t, y2 - t, y3 - t def delta(a,b,d): return -4*b**3*d - 27*a**2*d**2 def g(n): pass # x**3 - 8x**2 + 2 = 0 # x2*(x-8)+2= 0 # a = 1,b=8,c=0,d=2 # while 1: ''' for n in xrange(1,31): b = -2**n d = n a = 1 #print n, delta(1,-2**n,n) f1= ((2*b**3 +27*d)**2-4*b**2)**.5 p = -b/3. q = p**3 -d/2 r = 0 #x = (q + (q**2 +(-p**2)**3)**.5)**(1/3.) + (q - (q**2 +(-p**2)**3)**.5)**(1/3.) + p print n, f1 ''' ''' a = 3.86619826 b = a for i in xrange(1000): b*=a #b=b%10*16 print i, int(b)%10**8 ''' #print cubic(1,-8,0,2) for v in xrange(19,20): print v,Decimal(newt(v)) print
20f9849db6e62466f651162888f610db71d51ea6
phaniteja1/PythonWorks
/python_works/pixel_transformations.py
537
3.71875
4
__author__ = 'phaniteja' # This file is to apply operations on each pixel of the file # Import the modules to perform operations on Image - PIL is used for operations from PIL import Image try: # Load an image from the hard drive original = Image.open("steve.jpg") except FileNotFoundError: print("Unable to load image") # Apply pixel transformations edited_region = original.point(lambda i: i * 1.5) # Display both images original.show() edited_region.show() # save the new image # edited_region.save("edited.png")
b2c799c723e3c4fbd96fc34035546b6c3445ef1a
jihoonyou/problem-solving
/Educative/bfs/example4.py
1,085
3.75
4
""" Problem Statement Given a binary tree, populate an array to represent the averages of all of its levels. """ from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None def find_level_averages(root): result = [] nodes = deque() if root: nodes.append(root) while nodes: length = len(nodes) nodes_sum = 0 for _ in range(len(nodes)): current_node = nodes.popleft() nodes_sum += current_node.val if current_node.left: nodes.append(current_node.left) if current_node.right: nodes.append(current_node.right) result.append(nodes_sum/length) return result def main(): root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(9) root.left.right = TreeNode(2) root.right.left = TreeNode(10) root.right.right = TreeNode(5) print("Level averages are: " + str(find_level_averages(root))) main()
3f39c74a5bf2aeaf06d59e4039f93c5262fdef8f
Anshul-GH/youtube
/archive/pandas/dataframe101.py
2,102
4.09375
4
# # # # select * from table where # # # # column_name = some_value # # # import pandas as pd # # # import numpy as np # # # df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), # # # 'B': 'one one two three two two one three'.split(), # # # 'C': np.arange(8), 'D': np.arange(8) * 2}) # # # # print(df) # # # # print(df.loc[df['A'] == 'foo']) # # # # print(df.loc[df['B'].isin(['one', 'three'])]) # # # df = df.set_index(['B']) # # # # print(df.loc['one']) # # # print(df.loc[df.index.isin(['one', 'three'])]) # # # Learn Pandas - how to iterate over rows in a dataframe in pandas # # import pandas as pd # # inp = [{'c1':10, 'c2':20}, {'c1': 11, 'c2': 21}, {'c1': 12, 'c2': 22}] # # df = pd.DataFrame(inp) # # # print(df) # # for index, row in df.iterrows(): # # print(row['c1'], row['c2']) # ''' # year key val # 2019 a 3 # 2019 a 4 # 2019 b 3 # 2019 c 5 # 2020 d 6 # 2020 e 1 # 2020 f 2 # ''' # # import pandas as pd # # df = pd.read_clipboard() # # # print(df) # # # df.insert(1, 'prev_year', df['year'] - 1) # # df['prev_year'] = df['year'] - 1 # # print(df) # ''' # brand model year engine transmission suspension brakes Overall_Score # Acura CL 1999 3 2 1 3 1 # Acura CL 2000 5 3 7 2 3 # BMW 520 2015 22 4 10 11 2 # BMW 520 2008 1 6 3 6 4 # Chevrolet Impala 1997 0 2 2 5 1 # Chevrolet Impala 2002 9 3 8 4 1 # ''' # import pandas as pd # df = pd.read_clipboard() # cols = df.select_dtypes(include='int').columns # df[cols] = df[cols].astype(float) # print(df) ''' col1 col2 col3 col4 col5 False False True True False False True True False False '''
73c98b59c7c77878318782cbb66c247715207f82
gdfelt/competition
/advent_of_code/advent_2020/day_05/day_05.py
1,358
3.578125
4
class Day05(object): def __init__(self): self.passes = [] with open("advent_2020/day_05/day_05.dat", "r") as data: for l in data: self.passes.append(l.strip()) def calc_seat(self, seat_string, seat_range): # print(seat_string, seat_range) lower, upper = seat_range for c in seat_string: if c == "F" or c == "L": upper -= (upper + 1 - lower) / 2 elif c == "B" or c == "R": lower += (upper + 1 - lower) / 2 else: print("unexpected input:", c) return -1 # these values should be the same by now return int(lower) def part_01(self): highest = 0 for line in self.passes: id = self.calc_seat(line[:7], (0, 127)) * 8 + self.calc_seat( line[7:], (0, 7) ) if id > highest: highest = id return highest def part_02(self): pass_list = [int(x) for x in range(self.part_01())] for line in self.passes: id = self.calc_seat(line[:7], (0, 127)) * 8 + self.calc_seat( line[7:], (0, 7) ) try: pass_list.remove(id) except ValueError: pass return pass_list.pop()
43a92c6ded640d75ec2a8d6f610b5bf2ebab68ab
okeonwuka/PycharmProjects
/ThinkPython/swampy-2.1.5/mycircle.py
674
3.796875
4
# Exercise 4.3 # 4.3.4 from math import * from TurtleWorld import * # For some reason we need to initialise TurtleWorld() otherwise # error world = TurtleWorld() bob = Turtle() # Speed things up by reducing delay bob.delay = 0.1 # Refined polygon description def polygon(thing, lengthOfSide, numberOfSides): thing = Turtle() for i in range(numberOfSides): fd(thing, lengthOfSide) lt(thing, 360/numberOfSides) # circle1() function def circle1(): t = Turtle() r = 200 polygon(bob, (2*pi*r/40), 40) # Run circle1() # more useful form def circle2(thing, radius): polygon(thing, (2*pi*radius/40), 40) # Run circle2(bob, 100)
977c4015a95d1784e92b9df84982f3c60f795a35
rehassachdeva/UDP-Pinger
/UDPPingerServer.py
834
3.546875
4
import random import sys from socket import * # Check command line arguments if len(sys.argv) != 2: print "Usage: python UDPPingerServer <server port no>" sys.exit() # Create a UDP socket # Notice the use of SOCK_DGRAM for UDP packets serverSocket = socket(AF_INET, SOCK_DGRAM) # Assign IP address and port number to socket serverSocket.bind(('', int(sys.argv[1]))) while True: # Generate random number in the range of 0 to 10 rand = random.randint(0, 10) # Receive the client packet along with the address it is coming from message, address = serverSocket.recvfrom(1024) # Capitalize the message from the client message = message.upper() # If rand is less is than 4, we consider the packet lost and do not respond if rand < 4: continue # Otherwise, the server responds serverSocket.sendto(message, address)
04d6088fa694599b5e634cae6ac37a87bcd5c34f
niketanmoon/Programming-in-Python
/DataStructure/Array/reversal_array_rotate.py
995
4.25
4
""" This is a GeekForGeeks Problem on Array Rotaion using Reversal Here's the link to the problem: geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/ """ #Function for reversing. This is the main logic def reverseArray(arr,s,e): while s<e: temp = arr[s] arr[s] = arr[e] arr[e] = temp s = s+1 e= e-1 #Funcrion to call reverse functions in algorithmic steps def rotate(arr,d): #corner cases: if shift is 0 then simply return if d == 0: return #1.Reverse the array from start to d reverseArray(arr,0,d-1) #2.Reverse the array from d+1 to n reverseArray(arr,d,n-1) #3.Reverse now the whole Array reverseArray(arr,0,n-1) # Standard Input arr = [1,2,3,4,5,6,7] n = len(arr) d = int(input("Enter how many shifts you wanna do: ")) #If the shifts are greater than array length d = d % n #Function call to rotate rotate(arr,d) #Printing the array for i in range(n): print(arr[i],end=" ")
69fd8f5cf68cbbb4e786e486515e8883d3fed568
maroro0220/maroroPython
/day8_test.py
1,286
3.65625
4
class Student: def __init__(self,ID, name, major) self.id=ID self.name=name self.major=major def common(self): class MajorPoint(Student): def __init__(self,ID,name,major, clist): super().__init__(self,ID,name,major) self.mlist=[] self.clist=clist self.Comcnt=2 self.Electcnt=3 def mpoint(self): if Student.major=='computer': for x in range(self.Comcnt): majorp=int(input('enter major point')) mlist.append(majorp) elif Student.major=='Electronic': for x in range(self.Electcnt): majorp=int(input('enter major point')) mlist.append(majorp) class ViewScoreTable: MAX=10 count=0 def __init__(self): self. def ViewMenu(self): def inputStudentInfo(self): print('\n') sid=int(input('enter ID number')) name=input('enter name') major=input('enter major') while name!='end' and self.count<=self.MAX:
03440310c95988947c99d3032fe6e54dc48a0513
inovei6un/SoftUni-Studies-1
/FirstStepsInPython/Fundamentals/Exercice/Dictionaries/More Exercises/05. Dragon Army.py
1,825
3.828125
4
incoming_dragons = int(input()) dragons_den = {} while incoming_dragons: dragon_spawn = input() # {type} {name} {damage} {health} {armor} rarity, name, damage, health, armor = dragon_spawn.split(" ") # default values: health 250, damage 45, and armor 10 if damage == "null": damage = "45" damage = int(damage) if health == "null": health = "250" health = int(health) if armor == "null": armor = "10" armor = int(armor) if rarity not in dragons_den: dragons_den[rarity] = [{"name": name, "damage": damage, "health": health, "armor": armor}] else: new = True for check in dragons_den[rarity]: if check["name"] == name: check.update({'name': name, 'damage': damage, 'health': health, 'armor': armor}) new = False break if new: dragons_den[rarity].append({"name": name, "damage": damage, "health": health, "armor": armor}) incoming_dragons -= 1 # print(dragons_den) for x, y in dragons_den.items(): # {Type}::({damage}/{health}/{armor}) average = {"damage": 0, "health": 0, "armor": 0} for rec in y: average["damage"] += rec["damage"] average["health"] += rec["health"] average["armor"] += rec["armor"] print(f"{x}::({average['damage'] / len(y):.2f}/{average['health'] / len(y):.2f}/{average['armor'] / len(y):.2f})") for dragon in sorted(y, key=lambda r: r["name"]): print(f"-{dragon['name']} -> damage: {dragon['damage']}, health: {dragon['health']}, armor: {dragon['armor']}") # 5 # Red Bazgargal 100 2500 25 # Black Dargonax 200 3500 18 # Red Obsidion 220 2200 35 # Blue Kerizsa 60 2100 20 # Blue Algordox 65 1800 50 # # TEST # 2 # Red Bazgargal 100 2500 25 # Red Bazgargal 100 2500 24
62a72b06520039a88a143a016bbad0dbcb445f1a
mtoricruz/code_practice
/misc/isSubTree4.py
453
3.796875
4
def isSubTree(t1, t2): if t1 is None: return t2 is None if t2 is None: return True if isEqual(t1, t2): return True return isSubTree(t1.left, t2) or isSubTree(t1.right, t2) def isEqual(t1, t2): if t1 is None: return t2 is None if t2 is None: return False if t1.value != t2.value: return False return isEqual(t1.right, t2.right) and isEqual(t1.left, t2.left)
a4401ea546d5b15ac4d3ad651e8fa057691c5a5d
yunusemree55/PythonBTK
/functions-methods/lambda.py
228
3.6875
4
def square(number) : return number**2 numbers = [1,2,3,4,5,6,7,8,9,10] result = list(map(square,numbers)) print(result) check_even = lambda number : number % 2 == 0 result = list(filter(check_even,numbers)) print(result)
09ebbeabfb1de92ea5cf40873787ee6c8050568c
Vakicherla-Sudheethi/Python-practice
/fact.py
387
4.03125
4
#Scope variables """local variable--global variable""" s=int(input("enter number: "))#global variable def factorial(num): fact=1#local variable and scope is limited to factor for i in range (1,num+1): fact=fact*i print("fact of %d is %d "%(s,fact))#s is global is used #call the function factorial(s) """output:enter number: 5 fact of 5 is 120"""
90003c7f04c2bc55d5d4e2539415765521f7f0a2
KeoneShyGuy/DailyProgrammer
/medium/SingleSymbolSquares.py
3,124
3.609375
4
#!/usr/bin/env python3 #https://www.reddit.com/r/dailyprogrammer/comments/9z3mjk/20181121_challenge_368_intermediate_singlesymbol/ #compiled with python 3.5.3 from random import choice from time import clock def createGrid(gridSize): gridOG = [['U'] * gridSize for j in range(gridSize)] for j in range(len(gridOG)): columnTemp = [] countA = 0 while (countA < gridSize): columnTemp.insert(len(columnTemp), choice(['X','O'])) countA += 1 gridOG[j] = columnTemp return gridOG def printGrid(someList): for rowB in someList: for char in rowB: print (char, end=' ') print('') print('\n ') def checkGrid(gridArr): oCorners = ['O', 'O', 'O', 'O'] xCorners = ['X', 'X', 'X', 'X'] length = 0 allCorners = [] while (length < arrSize): length += 1 xIdx, yIdx = 0, 0 while (arrSize and ((xIdx + length) < arrSize)): while ((yIdx +length) < arrSize and (xIdx +length) < arrSize): corners = [gridArr[xIdx][yIdx], gridArr[xIdx][yIdx + length], gridArr[xIdx + length][yIdx], gridArr[xIdx + length][yIdx + length]] if (corners == oCorners or corners == xCorners): allCorners.append([xIdx, yIdx]) allCorners.append([xIdx, yIdx + length]) allCorners.append([xIdx + length, yIdx]) allCorners.append([xIdx + length, yIdx + length]) yIdx += 1 if ((yIdx + length) == arrSize): xIdx += 1 yIdx = 0 filteredCorners = [] for idx in allCorners: if (idx not in filteredCorners): filteredCorners.append(idx) allCorners = filteredCorners return allCorners def fixGrid(gridArr, idxList): if (len(idxList) % 2 == 0): for idx in idxList[1::2]: if (gridArr[idx[0]][idx[1]] == 'X'): gridArr[idx[0]][idx[1]] = 'O' else: gridArr[idx[0]][idx[1]] = 'X' if not checkGrid(gridArr): break else: for idx in idxList[::2]: if (gridArr[idx[0]][idx[1]] == 'X'): gridArr[idx[0]][idx[1]] = 'O' else: gridArr[idx[0]][idx[1]] = 'X' if not checkGrid(gridArr): break return gridArr arrSize = abs(int(input('Enter the size of the array.\nEnter 0 to exit: '))) startTime = clock() grid = createGrid(arrSize) attempts = 0 while arrSize: while checkGrid(grid): if (attempts % (arrSize**2)== 0): grid = createGrid(arrSize) attempts += 1 grid = fixGrid(grid, checkGrid(grid)) if ((clock() - startTime) > 600): print("This taking too long! We out!") break print('Done in %i attempts and %.2f seconds!' % (attempts, clock() - startTime)) printGrid(grid) arrSize = abs(int(input('Enter the size of the array.\nEnter 0 to exit: '))) startTime = clock() grid = createGrid(arrSize) attempts = 0
10855c232ba401f5eb169c6ab7e563067b1fbc8b
cuent/comp551
/practice/linear_regression/main.py
2,625
3.609375
4
from utils import * from linear import * import matplotlib.pyplot as plt def more_points(n): f = lambda x: 2 * x + 3 x, y = generate_1d_data(f, n, 30) # Execute LR lr = LinearRegressionMSE() lr.fit(x, y) y_pred = lr.pred(x) fig, ax = plot_data(x, y, y_pred) # ax.plot([np.min(x), np.max(x)], [f1(np.min(x)), f1(np.max(x))], 'r-', lw=1, label="Prediction") plt.legend(loc='best') fig.savefig('result/more_points.png') def course_example(): x = np.array([.86, .09, -.85, .87, -.44, -.43, -1.1, .40, -.96, .17]) y = np.array([2.49, .83, -.25, 3.1, .87, .02, -.12, 1.81, -.83, .43]) # Execute LR lr = LinearRegressionMSE() lr.fit(x, y) y_pred = lr.pred(x) # Linear equation m, b = lr.w[0, 0], lr.w[1, 0] f1 = lambda x: m * x + b # Plot results f, ax = plot_data(x, y, y_pred) ax.plot([np.min(x), np.max(x)], [f1(np.min(x)), f1(np.max(x))], 'r-', lw=1, label="Prediction") plt.legend(loc='best') f.savefig('result/course_example_mse.png') def lr_gradient_descent(): x = np.array([.86, .09, -.85, .87, -.44, -.43, -1.1, .40, -.96, .17]) y = np.array([2.49, .83, -.25, 3.1, .87, .02, -.12, 1.81, -.83, .43]) # Execute LR lr = LinearRegressionGD() lr.fit(x, y) y_pred = lr.pred(x) # Linear equation m, b = lr.w[0, 0], lr.w[1, 0] f1 = lambda x: m * x + b # Plot results f, ax = plot_data(x, y, y_pred) ax.plot([np.min(x), np.max(x)], [f1(np.min(x)), f1(np.max(x))], 'r-', lw=1, label="Prediction") plt.legend(loc='best') f.savefig('result/course_example_gd.png') def features_linear_dependent(): f1 = np.array([.86, .09, -.85, .87, -.44, -.43, -1.1, .40, -.96, .17]) X = np.stack((f1, f1 + 2)).T y = np.array([2.49, .83, -.25, 3.1, .87, .02, -.12, 1.81, -.83, .43]) lr = LinearRegressionMSE() try: lr.fit(X, y) except: print("Singular Matrix") def polynomial_fit(): # data x = np.array([.86, .09, -.85, .87, -.44, -.43, -1.1, .40, -.96, .17]) X = np.stack((x ** 2, x)).T y = np.array([2.49, .83, -.25, 3.1, .87, .02, -.12, 1.81, -.83, .43]) # model lr = LinearRegressionMSE() lr.fit(X, y) w = lr.w.flatten() # plotting f = lambda x: w[2] * x ** 2 + w[1] * x + w[0] fig, ax = plot_data(x, y, f(x)) x.sort() ax.plot(x, f(x), 'k-', label="model") plt.legend() fig.savefig('result/course_example_polynimial.png') if __name__ == "__main__": course_example() lr_gradient_descent() more_points(500) features_linear_dependent() polynomial_fit()
72f8cb2859697c496ccdc692b2a0f424c4afbbdc
54lihaoxin/leetcode_python
/src/CopyListWithRandomPointer/solution.py
1,520
3.84375
4
# Copy List with Random Pointer # # A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. # # Return a deep copy of the list. from CommonClasses import * # hxl: comment out this line for submission debug = True debug = False class Solution: # @param head, a RandomListNode # @return a RandomListNode def copyRandomList(self, head): if head == None: return None self.insertNodesInBetween(head) self.setUpRandomPointerForNewNodes(head) return self.getListOfNewNodes(head) def insertNodesInBetween(self, head): cur = head while cur != None: new = RandomListNode(cur.label) new.next = cur.next cur.next = new cur = new.next def setUpRandomPointerForNewNodes(self, head): cur = head while cur != None: new = cur.next if cur.random == None: new.random = None else: new.random = cur.random.next cur = new.next def getListOfNewNodes(self, head): r = head.next cur = head while cur != None: new = cur.next cur.next = new.next cur = cur.next if cur != None: new.next = cur.next return r
5e6303e8b24601b4d6a367dabdceaa655b3bfd53
hoangcaobao/Learning-Python-in-1-month
/Week1/sol_inclass1.py
1,007
4
4
#Exercise 1: Assign value 10 to variable x and print x x=10 print(x) #Exercise 2: Assign value "Vietcode academy" to variable x and print x x="Vietcode academy" print(x) #Exercise 3: Assign value 10 to varibale a and value 5 to variable b and print sum of a and b a=10 b=5 print(a+b) #Exercise 4: Assign sum of a and b to varibale c and print c c=a+b print(c) #Exercise 5: Assign value "1000" to varibale x and assign intenger of varible x to varible y and print y x="1000" y=int(x) print(y) #Exercise 6: Reverse of exercise 5 x=1000 y=str(x) print(y) #Exercise 7: Use input ask a number, then print this number x=input() print(x) #Exercise 8: Use input ask 2 number, number1 and number2 #Print "Number 1 is {0} and number 2 is {1}" with 0 is value of number1 and 1 is value of number2. x=input("Enter your first number: ") y=input("Enter your second number:") print("Number 1 is {0} and number 2 is {1}".format(x,y))
f1d29adaa2ed265e743032a3e65c109d4b03f5cf
sineczek/Automated-Software-Testing-with-Python
/Python Refresher/30_type_hinting.py
1,104
3.6875
4
from typing import List # Tuple, set etc. def list_avg(sequence: List) -> float: # przyjmuje liste -> a zwraca float return sum(sequence) / len(sequence) list_avg(123) class Book: TYPES = ("hardcover", "paperback") def __init__(self, name: str, book_type: str, weight: int): # hinting, czyli podpowie, że name ma być stringiem ... self.name = name self.weight = weight self.book_type = book_type def __repr__(self) -> str: return f"BookShelf {self.name}, {self.book_type}, weight {self.weight} g." @classmethod def hardcover(cls, name: str, page_weight: int) -> "Book": # zwracają obiekt taki jak klasa, muszą być "" return cls(name, cls.TYPES[0], page_weight + 100) @classmethod def paperback(cls, name: str, page_weight: int) -> "Book": return cls(name, cls.TYPES[1], page_weight) class BookShelf: def __init__(self, book: List[Book]): # hint: book to lista książek - inna klasa self.books = book def __str__(self) -> str: return f"BookShelf with {len(self.books)} books."
879cb5cfd4b8dc9b6b288aa69e668e453690cfbf
Banehowl/MayDailyCode2021
/DailyCode05032021.py
683
3.5
4
# ------------------------------------------------------ # # Daily Code 05/03/2021 # "Among Us Imposter Formula" Lesson from edabit.com # Coded by: Banehowl # ------------------------------------------------------ # Create a function that calculates the chance of being an imposter. The formula for the chances of being an imposter # is 100 * (i / p) where i is the imposter count and p is the player count. Make sure to round the value to the nearest # integer and return the value as a percentage. def imposter_formula(i, p): impOdds = 100 * (i/p) return impOdds print imposter_formula(1, 10) print imposter_formula(2, 5) print imposter_formula(1, 8)
94ae8a89ea97fda10cda5177058161bf244f808b
kernellmd/100-Python-examples
/example074.py
446
3.546875
4
#!/usr/bin/env python3 #-*- coding: utf-8 -*- ############################ #File Name: example074.py #Author: kernellmd #Created Time: 2018-05-23 12:21:47 ############################ """ 题目描述:连接两个链表。 """ #原始程序 if __name__ == '__main__': arr1 = [3,12,4,8,9] arr2 = [1,2,4] arr3 = ['I','am'] arr4 = ['hero'] ptr1 = arr3 + arr4 ptr = list(arr1) print(ptr) ptr = arr1 + arr2 print(ptr) print(ptr1)
76a0f67ba2943e097eeb65825643c922ec646b17
amaguri0408/AtCoder-python
/ABC162/c.py
461
3.671875
4
import math def gcd(a, b, c): tmp = math.gcd(a, b) tmp = math.gcd(tmp, c) return tmp K = int(input()) K += 1 ans = 0 for i in range(1, K): for j in range(i, K): for k in range(j, K): if i == j == k: ans += gcd(i, j, k) elif i == j or j == k or k == i: ans += gcd(i, j, k) * 3 else: # i != j != k ans += gcd(i, j, k) * 6 print(ans)
4aa645198601271d83f779815a3402ce50bb3456
muxueChen/pythonPractice
/IO.py
985
3.8125
4
#文件读写 # 读取文件 # 读取单个文本文件 import os import os.path # 遍历文件 # 深层遍历 rootdir = "./" # for parent, dirnames, filenames in os.walk(rootdir): # # for dirname in dirnames: # # print("{}".format(dirname)) # for filename in filenames: # print("{}".format(filename)) # 单层遍历 for filename in os.listdir(rootdir): print("{}".format(filename)) fo = open("file_to_read.txt", "w") # print("文件名:{}".format(fo.name)) # print("是否关闭:{}".format(fo.closed)) # print("访问模式:{}".format(fo.mode)) # 写文件 fo.write('This is a test.\nReally,it is.') fo.close() # 读文件 file = open('file_to_read.txt') # file.read() print("{}".format(file.read())) file.close() # 基于行的读写 line file1 = open("file_to_read.txt") print(file1.readline()) print(file1.readline()) file1.close() file2 = open("file_to_read.txt") print(file2.read(1)) print(file2.seek(4)) print(file2.read(1)) file2.close()
2ca8e19e2447a2b4809a012ece25512c50a69e82
EJTTianYu/DL3_RNN
/src/model.py
2,489
3.546875
4
import torch import torch.nn as nn class LMModel(nn.Module): # Language model is composed of three parts: a word embedding layer, a rnn network and a output layer. # The word embedding layer have input as a sequence of word index (in the vocabulary) and output a sequence of vector where each one is a word embedding. # The rnn network has input of each word embedding and output a hidden feature corresponding to each word embedding. # The output layer has input as the hidden feature and output the probability of each word in the vocabulary. def __init__(self, nvoc, ninput, nhid, nlayers): super(LMModel, self).__init__() self.drop = nn.Dropout(0.5) self.encoder = nn.Embedding(nvoc, ninput) # WRITE CODE HERE witnin two '#' bar ######################################## # Construct you RNN model here. You can add additional parameters to the function. # self.rnn = None self.rnn = nn.LSTM( # if use nn.RNN(), it hardly learns input_size=ninput, hidden_size=nhid, # rnn hidden unit num_layers=nlayers, # number of rnn layer batch_first=False, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size) ) ######################################## self.decoder = nn.Linear(nhid, nvoc) self.init_weights() self.nhid = nhid self.nlayers = nlayers def init_weights(self): init_uniform = 0.1 self.encoder.weight.data.uniform_(-init_uniform, init_uniform) self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-init_uniform, init_uniform) def forward(self, input): embeddings = self.drop(self.encoder(input)) # WRITE CODE HERE within two '#' bar ######################################## # With embeddings, you can get your output here. # Output has the dimension of sequence_length * batch_size * number of classes # output = None # hidden = None output, hidden = self.rnn(embeddings, None) # None represents zero initial hidden state # hidden = self.out(output[:, -1, :]) ######################################## output = self.drop(output) decoded = self.decoder(output.view(output.size(0) * output.size(1), output.size(2))) return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden
d2f633cfa4b79fafd6bc81521a4dfd777957d13f
Jordan-Floyd/python-day-3
/hw_module.py
599
4.03125
4
# 2) Create a Module in VS Code and Import It into jupyter notebook # Module should have the following capabilities: # 1) Has a function to calculate the square footage of a house # Reminder of Formula: Length X Width == Area # 2) Has a function to calculate the circumference of a circle # Program in Jupyter Notebook should take in user input and use imported functions to calculate # a circle's circumference or a houses square footage def circumference(): print("Enter Radius of Circle: ") r = float(input()) c = 3.14*r*r print("\nCircumference = ", c) circumference()
b9f61e0836917fabb07e4f30802783d3af514e32
sselinkurt/bilimsel-hesaplama
/2003.py
795
3.6875
4
#girilen baslangic ve bitis tahminleri arasinda denklemin kokunu bulan program #orta nokta bularak gitmek iyi bir yontem cunku aralik ne kadar buyuk olursa olsun ikiye bolerek cok cabuk kisaltiyoruz def f(x): return(x**2-4*x+3) x1 = int(input("Baslangic tahmini giriniz: ")) x2 = int(input("Bitis tahmini: ")) if(f(x1)*f(x2)==0): #girilen tahmin kok mu kontrolu print("tahminlerinizden biri denklemin kokudur") elif(f(x1)*f(x2)>0): print("girdiginiz aralikta tek sayida kok yoktur") else: for i in range(100): xr = (x1+x2)/2 if(f(xr)==0): print("kok bulundu: ", xr, i) # i, kacinci seferde bulundugunu soylemek icin konuldu break elif(f(x1)*f(xr)<0): x2 = xr else: x1 = xr # print(xr)
ba47abb8bf0e6aecaf26acc13e669de3756aad44
KrisAsante/Unit-8-02
/car_program.py
613
4
4
# Created by: Chris Asante # Created on: 6-May-2019 # Created for: ICS3U # Unit 8-02 # This main program will create a car object from car import * #create a vehicle car1 = Car() car2 = Car() print("Speed: " + str(car1.speed)) car1.accelerate(100) print("Speed: " + str(car1.speed)) car1.license_plate_number = "QWE123R4" print("License plate number: " + str(car1.license_plate_number) + '\n') print("Speed: " + str(car2.speed)) car2.accelerate(50) print("Speed: " + str(car2.speed)) car2.brake(70) print("Speed: " + str(car2.speed)) car2.colour = "blue" print("Colour: " + str(car2.colour))
b2a0449e71ad18337831b05c3e5797d3f61666ec
vijay6781/Python_Tutrials
/python_tutorials/RegularExpression.py
121
3.5
4
import re line = "cats are smater then dogs dogs dogs" line = print(re.sub("dogs", "cats",line )) print(line)
e2eef70b3b806c23b93051ee86afd0bc88077413
charlesreid1/probability-puzzles
/scripts/newton_helps_pepys.py
1,394
4.40625
4
# Isaac Newton Helps Samuel Pepys # Pepys wrote Newton to ask which of three events is more likely: # that a person get (a) at least 1 six when 6 dice are rolled, # (b) at least 2 sixes when 12 dice are rolled, or (c) at least 3 # sixes when 18 dice are rolled. What is the answer? # # From: Fifty Challenging Problems in Probability # by Frederick Mosteller # Problem 19 import random def newton_helps_pepys(): samples = 10000 totals = [ 0, 0, 0 ] for i in range(samples): # roll 6 dice sixes = 0 for j in range(6): if(random.randint(1, 6) == 6): sixes += 1 if(sixes >= 1): totals[0] += 1 # roll 12 dice sixes = 0 for j in range(12): if(random.randint(1, 6) == 6): sixes += 1 if(sixes >= 2): totals[1] += 1 # roll 18 dice sixes = 0 for j in range(18): if(random.randint(1, 6) == 6): sixes += 1 if(sixes >= 3): totals[2] += 1 averages = [x / samples for x in totals] print("Probability of at least 1 six when 6 dice are rolled:", averages[0]) print("Probability of at least 2 sixes when 12 dice are rolled:", averages[1]) print("Probability of at least 3 sixes when 18 dice are rolled:", averages[2]) if __name__ == '__main__': newton_helps_pepys()
5e40f10e299104484aad00104d51df73693f20fb
Gergana-Madarova/SoftUni-Python
/Programming-Basic-Python/For_Loop_Lab/03_Even_powers_of_2.py
94
3.640625
4
import math end = int(input()) for n in range(0, end + 1, 2): print(int(math.pow(2, n)))
ad42b8d75b1cba7bd07c255b376e54aa6a2e732c
leclm/CeV-Python
/PythonDesafios/desafio79.py
817
4.15625
4
''' Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro ele não será adicionado. No final serão exibidos todos os valores únicos digitados, em ordem crescente.''' resp = ' ' numeros = [] while resp != 'N': n = int(input('Digite um valor: ')) if n in numeros: print('Número duplicado. O armazenamento não foi realizado!') if n not in numeros: numeros.append(n) print('Número armazenado com sucesso!') resp = str(input('Deseja continuar (S/N)? ')).strip().upper()[0] while resp not in 'SN': resp = str(input('Deseja continuar (S/N)? ')).strip().upper()[0] if resp == 'N': break numeros.sort() print(f'Os números armazenados são: {numeros}')
0321cd8da230aaee8c048ca46d1565eba005d924
kaelynn-rose/Earthquake_Detection
/LSTM_scripts/seismic_LSTM.py
14,807
3.609375
4
''' This script contains two LSTM model classes, which can be used to run regression or classification RNN models. See below each class for examples of how to use each class. This script: 1. Calculates signal envelopes from raw signal data 2. Contains the ClassificationLSTM Class to perform classification using an LSTM RNN model on signal data, to classify signals as 'earthquakes' or 'noise'. Outputs: * Confusion matrix and plot * Accuracy history plot * Test accuracy values 3. Contains the RegressionLSTM Class to perform regression using an LSTM regression model on signal data. The model can be used to predict several different target labels for earthquake signals, including earthquake magnitude, earthquake p-wave arrival time, and earthquake s-wave arrival time. * Model loss (MSE) values * Loss (MSE) history plot * Observed vs. predicted output scatterplot This script requires that the user has already created signal traces using the get_signal_traces.py file in this repo. If needed, use the LSTM_grid_search.py file contained in this repo to run a grid search for best parameters for the model. Created by Kaelynn Rose on 4/22/2021 ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import h5py import tensorflow as tf from tensorflow.keras import layers keras = tf.keras from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import accuracy_score, precision_score, recall_score, mean_squared_error from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay from datetime import datetime from joblib import Parallel,delayed from scipy import signal from scipy.signal import resample,hilbert # set data paths dataset_path = 'partial_signal_dataset100000.npy' envelopes_path = 'envelopes100k.npy' label_csv_path = 'partial_signal_df100000.csv' # get signal envelopes for every signal dataset = np.load(dataset_path,allow_pickle=True) counter = 0 envelopes = [] for i in range(0,len(dataset)): counter += 1 print(f'Working on trace # {counter}') data = dataset[i][:,2] sos = signal.butter(4, (1,49.9), 'bandpass', fs=100, output='sos') # filter signal from 1-50 Hz, 4th order filter filtered = signal.sosfilt(sos, data) analytic_signal = hilbert(filtered) # apply hilbert transform to get signal envelope amplitude_envelope = np.abs(analytic_signal) # get only positive envelope env_series = pd.Series(amplitude_envelope) # convert to a series to be compatible with pd.Series rolling mean calc rolling_obj = env_series.rolling(200) # 2-second rolling mean (100 Hz * 2 sec = 200 samples) rolling_average = rolling_obj.mean() rolling_average_demeaned = rolling_average[199:] - np.mean(rolling_average[199:]) rolling_average_padded = np.pad(rolling_average_demeaned,(199,0),'constant',constant_values=(list(rolling_average_demeaned)[0])) # pad with zeros to remove nans created by rolling mean resamp = signal.resample(rolling_average_padded, 300) # resample signal from 6000 samples to 300 envelopes.append(resamp) np.save('envelopes100k.npy',envelopes) # LSTM Classification Class class ClassificationLSTM: def __init__(self,envelopes_path,label_csv_path,target): self.envelopes_path = envelopes_path self.label_csv_path = label_csv_path self.target = target self.envelopes = [] self.X_train = [] self.X_test = [] self.y_train = [] self.y_test = [] self.model = [] self.ypred = [] self.cm = [] self.history = [] self.epochs = [] self.accuracy = [] self.precision = [] self.recall = [] self.envelopes = np.load(self.envelopes_path,allow_pickle=True) # load envelopes from file self.label_csv = pd.read_csv(self.label_csv_path) self.labels = self.label_csv[target] self.labels = np.array(self.labels.map(lambda x: 1 if x == 'earthquake_local' else 0)) def train_test_split(self, test_size,random_state): self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.envelopes, self.labels,random_state = random_state,test_size=test_size) # train test split self.X_train = np.reshape(self.X_train, (np.array(self.X_train).shape[0], 1, np.array(self.X_train).shape[1])) # reshape self.X_test = np.reshape(self.X_test, (np.array(self.X_test).shape[0], 1, np.array(self.X_test).shape[1])) # reshape self.X_train.shape, self.X_test.shape, self.y_train.shape, self.y_test.shape def LSTM_fit(self,epochs,metric,batch_size): self.epochs = epochs # set callbacks to save model at each epoch callbacks = [ keras.callbacks.ModelCheckpoint( filepath=f'./saved_models/LSTM_100000_dataset_classification_epochs{epochs}_{format(datetime.now().strftime("%Y%m%d%h%m%s"))}', save_freq='epoch') ] # model design model = keras.Sequential() model.add(keras.layers.SimpleRNN(64, input_shape=(1,self.X_train.shape[2]), return_sequences=True)) model.add(keras.layers.LSTM(64, input_shape=(1,self.X_train.shape[2]), return_sequences=True)) model.add(keras.layers.Dropout(0.2)) model.add(keras.layers.LSTM(32, return_sequences=False)) model.add(keras.layers.Dense(16, activation='relu')) model.add(keras.layers.Dense(1, activation='sigmoid')) opt = keras.optimizers.Adam(learning_rate=4e-5) model.compile(optimizer=opt, loss='binary_crossentropy', metrics=metric) # fit and predict self.model = model self.history = model.fit(self.X_train, self.y_train, batch_size=batch_size, epochs=self.epochs,callbacks=callbacks,validation_split=0.2) # plot train/test accuracy history plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(7,7)) ax.plot(self.history.history['accuracy']) ax.plot(self.history.history['val_accuracy']) ax.set_title('Model Accuracy') ax.set_ylabel('Accuracy') ax.set_xlabel('Epoch') ax.legend(['train','test']) plt.savefig('model_accuracy.png') plt.show() def LSTM_evaluate(self): self.y_pred = self.model.predict(self.X_test) # get predictions print('Evaluating model on test dataset') # evaluate model test_loss, test_acc = self.model.evaluate(self.X_test, self.y_test, verbose=1) print(f'Test data accuracy: {test_acc}') predicted_classes = self.model.predict_classes(self.X_test) # predicted class for each image self.accuracy = accuracy_score(self.y_test,predicted_classes) # accuracy of model self.precision = precision_score(self.y_test,predicted_classes) # precision of model self.recall = recall_score(self.y_test,predicted_classes) # recall of model print(f'The accuracy of the model is {self.accuracy}, the precision is {self.precision}, and the recall is {self.recall}') # save model saved_model_path = f'./saved_models/LSTM_classification_acc{self.accuracy}_prec{self.precision}_rec{self.recall}_epochs{self.epochs}_{format(datetime.now().strftime("%Y%m%d"))}' # _%H%M%S # Save entire model to a HDF5 file self.model.save(saved_model_path) # confusion matrix self.cm = confusion_matrix(self.y_test,predicted_classes) # plot confusion matrix plt.style.use('default') disp = ConfusionMatrixDisplay(confusion_matrix=self.cm, display_labels=['not earthquake','earthquake']) disp.plot(cmap='Blues', values_format='') plt.title(f'Classification LSTM Results ({self.epochs} epochs)') plt.tight_layout() plt.savefig('confusion_matrix.png') plt.show() # use ClassificationLSTM model_c2 = ClassificationLSTM(envelopes_path,label_csv_path,'trace_category') # initialize class model_c2.train_test_split(test_size=0.25,random_state=44) # train test split model_c2.LSTM_fit(epochs=50,metric='accuracy',batch_size=64) # fit model model_c2.LSTM_evaluate() # evaluate model # LSTM Regression Class class RegressionLSTM: def __init__(self,envelopes_path,label_csv_path,target): self.envelopes_path = envelopes_path self.label_csv_path = label_csv_path self.target = target self.envelopes = [] self.X_train = [] self.X_test = [] self.y_train = [] self.y_test = [] self.model = [] self.ypred = [] self.cm = [] self.history = [] self.epochs = [] self.test_loss = [] self.envelopes = np.load(self.envelopes_path,allow_pickle=True) # load signal envelopes from file self.label_csv = pd.read_csv(self.label_csv_path) # load labels from csv that correspond to enveloeps self.labels = self.label_csv[target] # find labels for specified target eq_envelopes = np.array(self.envelopes)[self.label_csv['trace_category'] == 'earthquake_local'] # only find signals corresponding to earthquakes, not noise print(len(eq_envelopes)) eq_labels = self.label_csv[self.target][self.label_csv['trace_category'] == 'earthquake_local'] # only find labels corresponding to earthquakes, not noise print(len(eq_labels)) self.envelopes = eq_envelopes self.labels = eq_labels def train_test_split(self, test_size,random_state): self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.envelopes, self.labels,random_state = random_state,test_size=test_size) # train test split self.X_train = np.reshape(self.X_train, (np.array(self.X_train).shape[0], 1, np.array(self.X_train).shape[1])) self.X_test = np.reshape(self.X_test, (np.array(self.X_test).shape[0], 1, np.array(self.X_test).shape[1])) self.X_train.shape, self.X_test.shape, self.y_train.shape, self.y_test.shape def LSTM_fit(self,epochs,batch_size): self.epochs = epochs # set callbacks to save model at each epoch callbacks = [ keras.callbacks.ModelCheckpoint( filepath=f'./saved_models/LSTM_100000_dataset_regression_epochs{epochs}_{format(datetime.now().strftime("%Y%m%d%h%m%s"))}', save_freq='epoch') ] # model design model = keras.Sequential() model.add(keras.layers.LSTM(32, input_shape=(1, 300), return_sequences=True)) model.add(keras.layers.LSTM(32, return_sequences=False)) model.add(keras.layers.Dropout(0.2)) model.add(keras.layers.Dense(32, activation='relu')) model.add(keras.layers.Dense(16, activation='relu')) model.add(keras.layers.Dense(1, activation='linear')) opt = keras.optimizers.Adam(learning_rate=1e-4) model.compile(optimizer=opt, loss='mse') self.model = model # fit self.model = model self.history = self.model.fit(self.X_train, self.y_train, batch_size=batch_size,epochs=epochs,callbacks=callbacks,validation_split=0.2) # plot train/test accuracy history plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(7,7)) ax.plot(self.history.history['loss']) ax.plot(self.history.history['val_loss']) ax.set_title('Model Loss (MSE)') ax.set_ylabel('MSE') ax.set_xlabel('Epoch') ax.legend(['train','test']) plt.savefig('model_loss.png') plt.show() def LSTM_evaluate(self): self.y_pred = self.model.predict(self.X_test) # get predictions print('Evaluating model on test dataset') # evaluate model self.test_loss = self.model.evaluate(self.X_test, self.y_test, verbose=1) # get MSE print(f'Test data loss: {self.test_loss}') # save model saved_model_path = f'./saved_models/LSTM_regression_loss{self.test_loss}_epochs{self.epochs}_{format(datetime.now().strftime("%Y%m%d"))}' # _%H%M%S # Save entire model to a HDF5 file self.model.save(saved_model_path) plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(7,7)) ax.scatter(self.y_test,self.y_pred,alpha=0.01) point1 = [0,0] point2 = [1200,1200] xvalues = [point1[0], point2[0]] yvalues = [point1[1], point2[1]] ax.plot(xvalues,yvalues,color='blue') ax.set_ylabel('Predicted Value',fontsize=14) ax.set_xlabel('Observed Value',fontsize=14) ax.set_title(f'Regression LSTM Results | ({self.epochs} epochs)',fontsize=14) ax.tick_params(axis='x', labelsize=14) ax.tick_params(axis='y', labelsize=14) ax.set_xlim([0,1200]) ax.set_ylim([0,1200]) plt.tight_layout() plt.savefig('true_vs_predicted.png') plt.show() # use RegressionLSTM model_r1 = RegressionLSTM(envelopes_path,label_csv_path,'p_arrival_sample') # initialize regression LSTM model model_r1.train_test_split(test_size=0.25,random_state=44) # train test split model_r1.LSTM_fit(epochs=50,batch_size=32) # fit model model_r1.LSTM_evaluate() # get model mse # nicer plots if needed # p-wave plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(7,7)) ax.scatter(model_r1.y_test,model_r1.y_pred,alpha=0.01) point1 = [0,0] point2 = [1200,1200] xvalues = [point1[0], point2[0]] yvalues = [point1[1], point2[1]] ax.plot(xvalues,yvalues,color='blue') ax.set_ylabel('Predicted Value',fontsize=14) ax.set_xlabel('Observed Value',fontsize=14) ax.set_title(f'Regression LSTM Results S-Wave Arrival Times | (50 epochs)',fontsize=14) ax.tick_params(axis='x', labelsize=14) ax.tick_params(axis='y', labelsize=14) ax.set_xlim([200,1200]) ax.set_ylim([200,1200]) plt.tight_layout() plt.savefig('true_vs_predicted.png') plt.show() # s-wave plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(7,7)) ax.scatter(model_r1.y_test,model_r1.y_pred,alpha=0.05) point1 = [0,0] point2 = [5000,5000] xvalues = [point1[0], point2[0]] yvalues = [point1[1], point2[1]] ax.plot(xvalues,yvalues,color='blue') ax.set_ylabel('Predicted Value',fontsize=14) ax.set_xlabel('Observed Value',fontsize=14) ax.set_title(f'Regression LSTM Results S-Wave Arrival Times | (50 epochs)',fontsize=14) ax.tick_params(axis='x', labelsize=14) ax.tick_params(axis='y', labelsize=14) ax.set_xlim([0,5000]) ax.set_ylim([0,5000]) plt.tight_layout() plt.savefig('true_vs_predicted.png') plt.show()
6cbc312c1b83f6d2ea4e2d98e559d76c857b7383
santiagomariani/Six-Degrees-of-Kevin-Bacon-Python
/pila.py
723
3.90625
4
class Pila: def __init__(self): """Crea pila vacia""" self.items = [] def esta_vacia(self): """Devuelve True si la lista esta vacia""" return len(self.items) == 0 def apilar(self,x): """apila elemento x""" self.items.append(x) def __str__(self): return str(self.items) def desapilar(self): """Devuelve el elemento tope y lo elimina de la pila. Si la pila esta vacia levanta una excepcion""" if self.esta_vacia(): raise ValueError("La pila esta vacia") return self.items.pop() def ver_tope(self): if self.esta_vacia(): raise ValueError("La pila esta vacia") return self.items[-1]