blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
0ae1145610b852e8f50363c1221cb96d74162a32
krstevkoki/vestacka-inteligencija
/lab1/tablica2.py
407
3.78125
4
# -*- coding: utf-8 -*- if __name__ == "__main__": m = input() n = input() x = input() # vasiot kod pisuvajte go tuka tablica = {} scope = range(int(m), int(n) + 1) for i in scope: result = i ** 3 tablica[result] = i if int(x) not in tablica.keys(): print("nema podatoci") else: print(tablica[int(x)]) print(sorted(tablica.items()))
2abf7670c4d02183632cf57708a69b8e95176d0a
GolamRabbani20/PYTHON-A2Z
/1000_PROBLEMS/ExamplesOnLists/Problem-11.py
415
3.734375
4
#Python Program to Find all Numbers in a Range which are Perfect Squares and Sum #of all Digits in the Number is Less than 10 m=int(input("Enter lower range:")) n=int(input("Enter upper range:")) x=[x for x in range(m,n+1) if (int(x**0.5)**2==x) and sum(list(map(int,str(x))))<10] print(x) ''' x=[] for i in range(m,n+1): if int(i**0.5)**2==i and sum(list(map(int,str(i))))<10: x.append(i) print(x) '''
dd857bf6348fbe9fc68affd328c24e1cb35cc085
lizhixin3016/leetcode-cn
/110.平衡二叉树.py
2,101
3.6875
4
# # @lc app=leetcode.cn id=110 lang=python3 # # [110] 平衡二叉树 # # https://leetcode-cn.com/problems/balanced-binary-tree/description/ # # algorithms # Easy (49.17%) # Likes: 209 # Dislikes: 0 # Total Accepted: 45.2K # Total Submissions: 91.2K # Testcase Example: '[3,9,20,null,null,15,7]' # # 给定一个二叉树,判断它是否是高度平衡的二叉树。 # # 本题中,一棵高度平衡二叉树定义为: # # # 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 # # # 示例 1: # # 给定二叉树 [3,9,20,null,null,15,7] # # ⁠ 3 # ⁠ / \ # ⁠ 9 20 # ⁠ / \ # ⁠ 15 7 # # 返回 true 。 # # 示例 2: # # 给定二叉树 [1,2,2,3,3,null,null,4,4] # # ⁠ 1 # ⁠ / \ # ⁠ 2 2 # ⁠ / \ # ⁠ 3 3 # ⁠ / \ # ⁠4 4 # # # 返回 false 。 # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.cache = {} # 从根节点开始,计算出左右子树的高度差,如果满足条件,就继续检验左右子树, # 如果出现不满足条件的子树,说明这棵树不是平衡二叉树 def isBalanced(self, root: TreeNode) -> bool: if root is None: return True lh = self.getHeight(root.left) rh = self.getHeight(root.right) if abs(lh - rh) <= 1: return self.isBalanced(root.left) and self.isBalanced(root.right) else: return False # 为了提速,使用了cache字典来缓存每个子树的高度,避免多次递归计算 def getHeight(self, root: TreeNode) -> int: if root is None: return 0 if root in self.cache: return self.cache[root] lh = self.getHeight(root.left) rh = self.getHeight(root.right) height = max(lh, rh) + 1 self.cache[root] = height return height # @lc code=end
3f0e431c42b28bc5594479fffe0eb0cc18e468d7
Shakirsadiq6/Create-Users
/Create-Users/src/WithDatabase/emails.py
556
4.3125
4
'''Email Validation''' __author__ = "Shakir Sadiq" class users_email: '''class for users email''' def __init__(self,email): '''constructor''' self.email = email email = input("Enter your email address: ") while "@" not in email: print("Your email address must have '@' in it") email = input("Please write your email address again: ") while "." not in email: print("Your email address must have '.' in it") email = input("Please write your email address again: ") email_of_users = users_email(email) email_of_users.email
20409fa8e57e35e126db9fc33a38300702db62db
jduan/learn_python_the_hard_way
/ex12.py
354
3.515625
4
# You can use 'pydoc raw_input' to get documentation from the command line. age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weight? ") address = raw_input("Where do you live? ") print "So, you are %s old, %s tall, %s heavy, and you live in %s." % ( age, height, weight, address)
a746ec1793d79679247384bcb8d9c3fed617d5fb
iagoamaro/aprendendo_python
/fatpy.py
174
4.0625
4
#calculador de fatorial fat = int(input("Digite um numero: ")) fat_total = 1 for i in range(1,fat+1): #print(i) fat_total = i * fat_total print(i, fat_total) input("")
8b98793b05a32f25b0738853bf460041d8901145
GBoshnakov/SoftUni-Fund
/RegEx/Furniture.py
526
3.578125
4
import re data = input() regex = r">>(?P<furniture>[a-zA-Z]+)<<(?P<price>\d+(\.\d+)?)!(?P<quantity>\d+)" total_money = 0 items = [] while data != "Purchase": match = re.match(regex, data) if match: current_furniture = match.groupdict() total_money += float(current_furniture["price"]) * int(current_furniture["quantity"]) items.append(current_furniture["furniture"]) data = input() print("Bought furniture:") for el in items: print(el) print(f"Total money spend: {total_money:.2f}")
ba34f74ea2735e54c54e3e7889f24a6a2748c8a4
PolishDom/COM411
/basics/functions/beepbopreturn.py
599
3.875
4
def sum_weights (beepweight, bopweight): sumweight = int(beepweight + bopweight) return sumweight def calc_avg_weight(beepweight, bopweight): avgweight = (int(beepweight + bopweight) /2) return avgweight def run(): beepweight = int(input("What is beeps weight?")) print (beepweight) bopweight = int(input("What is bops weight?")) print (bopweight) avgorsum = input("Would you like to calculate the sum or average?") if avgorsum == "sum": print (sum_weights(beepweight, bopweight)) elif avgorsum == "average": print (calc_avg_weight(beepweight, bopweight)) run()
cebebbb9f959e581d3a237a7fbaa75eefc9fb1ef
jperrycode/full-python-scripts
/Module Scripts/abstraction.py
1,014
3.90625
4
# abstraction assignment from abc import ABC, abstractmethod # define a parent class class loan(ABC): l_amount = 5000 def loan_amount(self, l_amount): ## loan = l_amount print('Your owe {} on your car..'.format(l_amount)) return l_amount def monthly_payment(self, pay_amount): print('Your monthly payment is: {}'.format(pay_amount)) return pay_amount # this is the abstract method that will be defined in the child classes @abstractmethod def payment_actual(self, act_amount): pass # child class class leased_suv(loan): # abstract parent class defined def payment_actual(self, act_amount): ## loan = 5000 total_amount = self.l_amount - act_amount print('After your monthly payment of {} this month, you still owe {} on the rav4.'.format(act_amount, total_amount)) if __name__ == '__main__': money = leased_suv() money.loan_amount(5000) money.monthly_payment(300) money.payment_actual(100)
1ae0bea74eadc754596700c6a5f6dfda8b35e51b
nighat3/breakout-game
/play.py
8,014
3.8125
4
# play.py # Nighat Ansari (na295), Kati Hsu (kyh24) # 8 December 2016 """Subcontroller module for Breakout This module contains the subcontroller to manage a single game in the Breakout App. Instances of Play represent a single game. If you want to restart a new game, you are expected to make a new instance of Play. The subcontroller Play manages the paddle, ball, and bricks. These are model objects. Their classes are defined in models.py. Most of your work on this assignment will be in either this module or models.py. Whether a helper method belongs in this module or models.py is often a complicated issue. If you do not know, ask on Piazza and we will answer.""" from constants import * from game2d import * from models import * import colormodel # PRIMARY RULE: Play can only access attributes in models.py via getters/setters # Play is NOT allowed to access anything in breakout.py (Subcontrollers are not # permitted to access anything in their parent. To see why, take CS 3152) class Play(object): """An instance controls a single game of breakout. This subcontroller has a reference to the ball, paddle, and bricks. It animates the ball, removing any bricks as necessary. When the game is won, it stops animating. You should create a NEW instance of Play (in Breakout) if you want to make a new game. If you want to pause the game, tell this controller to draw, but do not update. See subcontrollers.py from Lecture 25 for an example. INSTANCE ATTRIBUTES: _paddle [Paddle]: the paddle to play with _bricks [list of Brick]: the list of bricks still remaining _ball [Ball, or None if waiting for a serve]: the ball to animate _tries [int >= 0]: the number of tries left As you can see, all of these attributes are hidden. You may find that you want to access an attribute in class Breakout. It is okay if you do, but you MAY NOT ACCESS THE ATTRIBUTES DIRECTLY. You must use a getter and/or setter for any attribute that you need to access in Breakout. Only add the getters and setters that you need for Breakout. You may change any of the attributes above as you see fit. For example, you may want to add new objects on the screen (e.g power-ups). If you make changes, please list the changes with the invariants. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY _offScreen [bool]: True if _ball is offscreen, False otherwise """ # GETTERS AND SETTERS def getTries(self): """Returns: _tries attribute (number of tries left)""" return self._tries def setTries(self,value): """Sets the value of self._tries""" assert type(value)==int and value>=0 self._tries=value def setBricks(self,left,y,color): """Helper method to draw the bricks Parameter left: x-coordinate of left boundary of brick Precondition: left is a number >= BRICK_SEP_H/2 (REMEMbER UPPER BOUND) Parameter y: y-coordinate of the center of the brick Precondition: y is a float between 0 and GAME_HEIGHT Parameter color: corresponds to row brick is in (color starts at 1) Precondition: color is an integer >0 """ assert type(left) in [int, float] and left >= BRICK_SEP_H/2 assert type(y) == float and y in range(0, GAME_HEIGHT+1) assert type(color) == int and color >0 for z in range(BRICKS_IN_ROW): self._bricks.append(Brick(left, y,color)) left=left+ BRICK_WIDTH + BRICK_SEP_H def getBricks(self): """Returns: attribute self._bricks""" return self._bricks # INITIALIZER (standard form) TO CREATE PADDLES AND BRICKS def __init__(self): """Initializes an instance of Play (a new game) A game (instance of Play) consists of a paddle (Paddle object), bricks(list of Brick objects), and ball (Ball object). Initializes the self._bricks attribute with a list of Brick objects. Initializes self._paddle with a Paddle object. However, sets self._ball to None. A ball is not created at the start. Initializes self._tries to NUMBER_TURNS (3) because a player always starts off with three lives. Initializes self._offScreen to False because when the ball is created, it is not initially off the screen.""" self._paddle = Paddle() # Initializes _paddle attribute # Initializes _brick attribute self._bricks = [] left=float(BRICK_SEP_H/2) y=float(GAME_HEIGHT-BRICK_Y_OFFSET) color_counter=1 for q in range(BRICK_ROWS): self.setBricks(left,y,color_counter) y= y- (BRICK_HEIGHT+BRICK_SEP_V) color_counter=color_counter+1 self._ball= None # Initializes _ball attribute; no ball present at start self.setTries(NUMBER_TURNS) # Initializes _tries attribute self._offScreen = False # UPDATE METHODS TO MOVE PADDLE, SERVE AND MOVE THE BALL def updatePaddle(self, input): """This method checks for whether or not the 'left' or 'right' arrow key is pressed. If the 'left' arrow is pressed, the paddle will move to the left 6 units. If the 'right' arrow key is pressed, the paddle will shift to the right 6 units. The paddle will not move to the left if the x-coordinate of its left boundary is (0,PADDLE_OFFSET). It will not move to the right if the x-coordinate of its right boundary is (GAME_WIDTH, PADDLE_OFFSET). The paddle does not move up or down.""" assert isinstance(input, GInput) if input.is_key_down('left'): if self._paddle.left >= 0: self._paddle.left -= 6 if input.is_key_down('right'): if self._paddle.right <= GAME_WIDTH: self._paddle.x += 6 def makeBall(self): """When called, this method constructs a Ball object and assigns it to the _ball attribute of Play. This Ball is initiatelly placed at the center of the screen.""" self._ball= Ball() def updateBall(self): """When called, this method moves the ball and handles any physics regarding the ball's movements. This method is called in update when self._state = STATE_ACTIVE""" self._ball.moveBall(self._paddle.collides(self._ball),\ self.collisionWithBricks()) self._offScreen = self._ball.checkOffScreen() # DRAW METHOD TO DRAW THE PADDLES, BALL, AND BRICKS def playDraw(self, view): """This method draws the paddle, ball, and bricks to the game view. Parameter view: the game view used for drawing Precondition: view is an instance of GView""" assert isinstance(view, GView) # Draw bricks if self._bricks is not []: for b in self._bricks: b.draw(view) # Draw paddle if self._paddle is not None: self._paddle.draw(view) #Draw Ball if self._ball is not None: self._ball.draw(view) # HELPER METHODS FOR PHYSICS AND COLLISION DETECTION def collisionWithBricks(self): """Returns: True if ball (self) collides with a brick. False otherwise.""" if len(self._bricks)>0: for b in self._bricks: collideWithBrick = b.collides(self._ball) if collideWithBrick==True: self._bricks.remove(b) break return collideWithBrick else: return False # ADD ANY ADDITIONAL METHODS (FULLY SPECIFIED) HERE
370fc45b3df47accb59bb98ae9b11a56f9bd5511
willxie/action-conditional-video-prediction-with-motion-equivariance-regularizer
/scripts/format_image_file_names.py
773
3.65625
4
import sys import os def is_int(s): try: int(s) return True except ValueError: return False def main(): """ Put enough prepending 0 padding according to the README """ if len(sys.argv) != 2: print("Usage: target_dir") exit() root_dir = os.getcwd() target_dir = root_dir + "/" + sys.argv[1] for input_file in os.listdir(target_dir): filename, file_extension = os.path.splitext(input_file) if is_int(filename): new_filename = "{num:05d}".format(num=int(filename)) os.rename(target_dir + input_file, target_dir + new_filename+file_extension) else: print(input_file + " does not have an number filename") if __name__ == "__main__": main()
d403bbe92dc8dde267a3507c652739a0ca8becf4
wajeeh20-meet/meet2018y1lab5
/stringfun.py
89
3.609375
4
our_list = [1,2,1] if len(our_list) > 2 and our_list[0] == our_list[-1]: print(True)
4d28fed739a598dd48ee9504a81b4df526ed47db
arthtyagi/C02Emissions
/Multiple_Linear_Regression/C02Multiple.py
2,643
3.671875
4
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np # get the dataset using the link or download the dataset using curl in your Terminal curl -O https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv df = pd.read_csv('FuelConsumptionCo2.csv') df.head() cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_CITY','FUELCONSUMPTION_HWY','FUELCONSUMPTION_COMB','CO2EMISSIONS']] cdf.head(9) #to check whether linear regression good for making predictions on this data plt.scatter(cdf.ENGINESIZE,cdf.CO2EMISSIONS,color='blue') plt.xlabel('Engine Size') plt.ylabel('Emission') plt.show() # Create a Training and Testing Dataset¶ # I'll be using 80% of the data for Training and the rest for testing. It will be mutually exclusive msk = np.random.rand(len(df))<0.8 train = cdf[msk] test =cdf[~msk] # Train Data Distribution plt.scatter(train.ENGINESIZE,train.CO2EMISSIONS, color='blue') plt.xlabel('EngineSize') plt.ylabel('C02Emissions') plt.show() #Multiple Regression Model #We will be using Fuel Consumption, Cylinders and Engine size to predict the CO2 Emissions. from sklearn import linear_model as lm regr= lm.LinearRegression() x= np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]) y=np.asanyarray(train[['CO2EMISSIONS']]) regr.fit(x,y) #THE COEFFICIENTS print('Coefficients :', regr.coef_) #Prediction from sklearn.metrics import r2_score y_hat = regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]) x_test= np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']]) y_test=np.asanyarray(test[['CO2EMISSIONS']]) #rse print('RSE : %.2f' % np.mean((y_hat - y_test)**2)) #variance score : 1 is perfect print('Variance Score: %.2f' %regr.score(x_test,y_test)) #R^2 Score print("R2-score: %.2f" % r2_score(y_hat , y_test) ) #With independent variables as Fuel Consumption on City and Highway instead of combined. from sklearn import linear_model as lm regr= lm.LinearRegression() x= np.asanyarray(train[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_HWY','FUELCONSUMPTION_CITY']]) y=np.asanyarray(train[['CO2EMISSIONS']]) regr.fit(x,y) #THE COEFFICIENTS print('Coefficients :', regr.coef_) y_hat = regr.predict(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_HWY','FUELCONSUMPTION_CITY']]) x_test= np.asanyarray(test[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_HWY','FUELCONSUMPTION_CITY']]) y_test=np.asanyarray(test[['CO2EMISSIONS']]) #rse print('RSE : %.2f' % np.mean((y_hat - y_test)**2)) #variance score : 1 is perfect print('Variance Score: %.2f' %regr.score(x_test,y_test))
4a7021073a55374c42c8d446556650a94ad7528d
s33Y377/Scripting
/Python/ItertoolsExp.py
105
3.640625
4
import itertools data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] print(list(itertools.accumulate(data, max)))
2838860cc444b0b55b9e55c5153426e784995436
lex-koelewijn/handwritingrecog
/levenshtein.py
749
3.625
4
#Made by: s295454 #NLP, week 2 exercise 6 import sys import numpy as np def main(argv): s1 = sys.argv[1] s2 = sys.argv[2] min_distance(s1,s2) def min_distance(s1, s2): m = len(s1) n = len(s2) d = np.zeros((m+1,n+1)) for i in range(1,m): d[i,0] = i for j in range(1,n): d[0,j] = j for j in range(1,n+1): for i in range(1,m+1): if(s1[i-1] == s2[j-1]): substitutionCost = 0 else: substitutionCost = 2 d[i, j] = min(d[i-1, j] + 1, #deletion d[i, j-1] + 1, #insertion d[i-1, j-1] + substitutionCost) #substitution print(d[m,n]) if __name__ == "__main__" : main(sys.argv)
d959306eb3c33020b46ef7e88e0a6785813a5f40
duwaar/BalloonSat-Flight-Controller
/flight_controller_2.py
5,205
3.53125
4
#!/usr/bin/python3.4 ''' This is the flight controller program for a high-altitude balloon payload. The process herein allows for easy adding and removing of sensors, and simple, clear user interface on launch day. Elaine Jeffery 14 July 2017 ''' from fl_objects_2 import * def main(): #------------------------------------------------------------------ ''' This is the body of the program. ''' #------------------------------------------------------------------ try: ############################################################### ''' If you are in the business of adding or removing sensors, you are in the right place! To add a sensor, you must at least instantiate the object and add it to the queue. It may also be helpful to define some common variables if you have, for example, several sensors that will use the same ADC chip. --Variables: Define any variables that you will need for several sensors. --Sensors: Instantiate the sensor objects. --Queue: Add the sensors to the start/write/stop queue. ''' #Variables. Vref = 5.09 CLK = 11 Dout = 13 Din = 15 CS = 16 #Sensors. #convert volts to *F then *F to *C for the inside temp. inside = MCP3008('Inside_temp', Vref, CLK, Dout, Din, CS, [0,0,0], '((volts * 100) - 32) / 9 * 5') outside = MCP3008('Outside_temp', Vref, CLK, Dout, Din, CS, [0,0,1], '(volts - 1.25) / 0.005') light = MCP3008('Light', Vref, CLK, Dout, Din, CS, [0,1,0], 'volts') pressure = MCP3008('Pressure', Vref, CLK, Dout, Din, CS, [0,1,1], '(volts - 4.57) / -0.0040') gps = GPS('GPS') camera = Camera('Camera', vid_period=10, vid_length=5) #Queue. #If camera fails, the next thing in the queue gets messed up. IDK why. #queue = [inside, outside, light, pressure, gps, camera] queue = [inside, outside, light, pressure, gps, camera] ############################################################### #Here the indicator LED is set up. comfort_led = 32 GPIO.setup(comfort_led, GPIO.OUT) #Here, the heater pin is defined and set up. heater_pin = 33 GPIO.setup(heater_pin, GPIO.OUT) #Try to start all the sensors with their identically named "start()" #methods, but kick them out if they give you any trouble. for sensor in queue: try: sensor.start() except: queue.remove(sensor) print(sensor.name, 'failed to start. It was kicked out of the queue.') finally: pass #This is the main loop that is going to be running for most of the flight. flying = True while flying: #Get all the data. for sensor in queue: try: sensor.write() print(sensor.name, sensor.get()) #Use this and a bit below for debugging in the terminal. #except: # print(sensor.name, 'raised an error.') finally: pass #Report success. Shout it from the rooftops . . . or from a balloon. print('Data collected at', asctime()) blinky(comfort_led, 1) #Check the temperature, and turn on the heater if necesary. try: temp = inside.get() heater(heater_pin, temp) except: print('The heater has failed.') finally: pass blinky(comfort_led, 1) #Use the following (and a bit of code above) for debugging in the terminal. #Make the display easier to read. #sleep(1) #system('clear') #Here are statements for dealing with errors that the rest of the code cannot handle. except KeyboardInterrupt: print('The flight controller was terminated by the user.') #Here is the shutdown procedure that must always take place. #* * * * * IMPORTANT * * * * * #Note that all the code in the "finally:" clause is useless if you choose to #start and stop by supplying and/or cutting power. If you don't actually end #the program through software, none of this will run. finally: #We want to stop the sensors, but things may have gotten a bit out of hand by #this time. Hence, the try: finally: statement. for sensor in queue: try: sensor.stop() except: print(sensor.name, 'failed while stopping.') finally: pass print('Payload was recovered safely at', asctime()) for i in range(5): #blinky(comfort_led, 0.2) pass #Put this at the end, ding-dong. You know, AFTER all the GPIO operations. GPIO.cleanup() system('mv *.txt data/') system('mv *.jpg pictures/') main()
64ff852d3897e637d4edd55a9953c1f5425eae0b
MisterXY89/intro-to-python
/session_4/section_1/tasks.py
871
4.1875
4
#------------------------------------------------------------------------------# # (1) # Write min. 2 functions which handle the reading, processing and visualization # of a time series of transactions for one location (dependet on an argument) # (you can use the sum, mean or median) for the transactions on one day. # test your function(s) for <Coffee Cameleon> and <Brew've Been Served> # plot("Coffee Cameleon") # plot("Brew've Been Served") # (2) - optional # Create a heatmap (https://seaborn.pydata.org/generated/seaborn.heatmap.html) # using seaborn for every location (y) and every date (x) and the # sum of the price on the specific day (z). # Hints: 1 - first build a list of dictionaires and convert it then to # a df to visualize # 2 - use iterrows in this way to iterate through a df: # for index, row in df.iterrows: # row.location
19cab897d6ab33337061078cfeff89eea56594b7
quanee/Note
/Python/leaning python/base/Python_dict.py
302
3.609375
4
D = {'a': 1, 'd': 3, 'c': 2} print(D) Ks = list(D.keys()) Ks.sort() for key in Ks: print(key, '=>', D[key]) for key in sorted(D): print(key, '=>', D[key]) for c in 'moonboss': print(c.upper()) if 'f' in D: print(D['f']) else: print('None') value = D.get('x', 0) print(value)
f8b8bdf875b8cdbeda34e360d3950297a8fff6a1
roshangardi/Leetcode
/21.Merge Two Sorted Lists.py
2,119
4.25
4
# Developed this on my own after reading of algorithm: # Algorithm is : compare first element in each list, whichever ele is smaller, create its node and increment # the pointer for that list # Read comments for why recursive approach can lead to stackoverflow error for large lists: # https://leetcode.com/problems/merge-two-sorted-lists/discuss/9713/A-recursive-solution class Node: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, node1, node2): if not node1 and not node2: # If both nodes are empty, we reached end of the lists. return if not node1: # One of the lists ran out of nodes, so now point return nodes from the second list. return node2 # No need to create new nodes for remaining nodes, we can just point it to existing node. if not node2: return node1 # if not node1 or not node2: # Above can also be written in this manner # return node1 or node2 if node1.val == node2.val: newnode = Node(node1.val) # Could have also used node2, doesn't matter since node values are same newnode.next = self.mergeTwoLists(node1.next, node2) return newnode if node1.val < node2.val: newnode = Node(node1.val) # Since node1 is small, create new node1 and increment existing one's pointer newnode.next = self.mergeTwoLists(node1.next, node2) # Sending node.next / i.e. Incrementing pointer return newnode if node2.val < node1.val: newnode = Node(node2.val) newnode.next = self.mergeTwoLists(node1, node2.next) return newnode if __name__ == "__main__": node1 = Node(1) node1.next = Node(3) node1.next.next = Node(5) node1.next.next.next = Node(7) node2 = Node(2) node2.next = Node(4) node2.next.next = Node(6) node2.next.next.next = Node(8) sol = Solution() solnode = sol.mergeTwoLists(node1, node2) while solnode: print(solnode.val) solnode = solnode.next
3d7a0ffe60a88f50ceb3a32498299f921aeba787
ctajii/pathfinder_scripts
/poison_crafting.py
1,306
3.890625
4
def poison(): # Find original market value mvalue = input("What is the market value of the poison \n Value in GP: ") # Convert string to int mvalue = int(mvalue) # change market value to crafting value cvalue = .3333333 * mvalue difficulty_check = input("What is the DC you would like to use? (base is DC for poison) \n You can voluntarily increase the DC to increase the speed at which you craft \n DC: ") difficulty_check = int(difficulty_check) roll = input("What did you roll? \n ") roll = int(roll) top = roll * difficulty_check bottom = 10 * cvalue number_completed_week = top / bottom number_completed_day = number_completed_week / 7 print(f"You have completed {number_completed_week} of your item this week") print(f"You have completed {number_completed_day} of your item today") user_continue = input("Would you like to run this again? Y/N\n") user_continue = user_continue.upper() if (user_continue == 'Y'): poison() if (user_continue != 'Y'): exit # print("mvalue: " + str(mvalue)) # print("cvalue: " + str(cvalue)) # print("difficulty_check: " + str(difficulty_check)) # print("roll: " + str(roll)) #while True: poison()
d70762c81281a0edd10bee7a37907be83a7721fb
bschwyn/Think-Python
/exercises/2_Variables/exercise1.py
739
4
4
# Evaluate the following numerical expressions in your head, #then use the active code window to check your results: #This uses booleans to check whether my guess(on the right) is TRUE or FALSE # 1. 5 ** 2 print(5**2==25) # 2. 9 * 5 print(9 * 5 == 45) # 3. 15 / 12 print(15/12 == 1.25) # 4. 12 / 15 print(12/15 == 0.8) # 5. 15 // 12 print(15//12 == 1) # 6. 12 // 15 print(12 // 15 == 0) # 7. 5 % 2 print(5%2 == 1) # 8. 9 % 5 print(9 % 5 == 4) # 9. 15 % 12 print(15 % 12 ==3) # 10. 12 % 15 print(12 % 15 ==12) # 11. 6 % 6 print (6 % 6 ==0 ) # 12. 0 % 7 print (0 % 7) #I suspect an error #I guess 0 divided by anything is 0. #there is an error for a number % 0 because this is asking what the remainder of an illegal division is.
4c1827393ed0bae3dcb10e51acb4daf6985db686
atorch/markov_decision_process
/python/cake_eating.py
9,114
4.0625
4
import os import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression DISCOUNT_FACTOR = 0.9 VALUE_FUNCTION_CONSTANT_TERM = ( np.log(1 - DISCOUNT_FACTOR) + np.log(DISCOUNT_FACTOR) * DISCOUNT_FACTOR / (1 - DISCOUNT_FACTOR) ) / (1 - DISCOUNT_FACTOR) PLOT_DIR = "plots" # These grids are used for naive searches over the action space # action = fraction_consumed * wealth FRACTION_CONSUMED_GRID_COARSE = np.linspace(0.01, 0.99, 4) FRACTION_CONSUMED_GRID_FINE = np.linspace(0.01, 0.99, 8) def reward_function(action): # The agent's action is the amount they consume in the current period # If they consume nothing, they receive a reward of negative infinity (they die!) # If they consume everything, they receive a large reward in the current period, but they die tomorrow # The optimal action must therefore be to consume something today (while also saving for tomorrow) return np.log(action) def optimal_policy(state): # The agent's state variable is their wealth (their "amount of cake") # They need to decide how much to consume today and how much to leave for future periods # The agent lives forever and is unemployed: their wealth can never increase; it can only # decrease depending on how much they consume. The optimal policy can be solved with # pen and paper. A more patient agent (with a higher discount factor) consumes less today # and saves more for future periods return (1 - DISCOUNT_FACTOR) * state def optimal_value_function(state): # This is the value of pursuing the optimal policy, and it can be solved exactly with pen and paper return (1 / (1 - DISCOUNT_FACTOR)) * np.log(state) + VALUE_FUNCTION_CONSTANT_TERM def get_next_state(state, action): # The agent's action is how much to consume today. # Whatever is not consumed today is available tomorrow. # Wealth is a stock, consumption is a flow. return state - action def optimal_policy_grid_search( state, approximate_value_function, fraction_consumed_grid ): # The fraction consumed is in [0, 1], and the action is equal to wealth * fraction_consumed state_mesh, fraction_consumed_mesh = np.meshgrid(state, fraction_consumed_grid) actions = state_mesh * fraction_consumed_mesh rewards = reward_function(actions) next_states = get_next_state(state_mesh, actions) log_next_states = np.log(next_states.reshape(-1, 1)) continuation_values = approximate_value_function.predict(log_next_states).reshape( actions.shape ) candidate_values = rewards + DISCOUNT_FACTOR * continuation_values argmax_candidate_values = np.argmax(candidate_values, axis=0) return actions[argmax_candidate_values, range(state.size)] def optimal_policy_given_approximate_value_function(state, approximate_value_function): log_wealth_coefficient = approximate_value_function.coef_[0] # On the first iteration, the coefficient on log wealth is zero (future wealth has no value), # so, without this shortcut, the agent would consume everything immediately and get a -Inf continuation value if log_wealth_coefficient <= 0.0: return state * 0.99 # To arrive at this policy, write down the Bellman equation using the # approximate value function as the continuation value, and optimize with respect to the action return state / (DISCOUNT_FACTOR * log_wealth_coefficient + 1) def get_estimated_values( states, approximate_value_function, get_optimal_policy, **kwargs ): actions = get_optimal_policy(states, approximate_value_function, **kwargs) rewards = reward_function(actions) next_states = get_next_state(states, actions) # The approximated value function takes log(state) as input and returns an estimated value log_next_states = np.log(next_states.reshape(-1, 1)) continuation_values = approximate_value_function.predict(log_next_states) # This is the Bellman equation return rewards + DISCOUNT_FACTOR * continuation_values def get_coefficients(linear_regression): return np.vstack([linear_regression.intercept_, linear_regression.coef_]) def calculate_approximate_solution( get_optimal_policy, max_iterations=10000, n_simulations=2000, **kwargs ): X = np.zeros((n_simulations, 1)) y = np.zeros((n_simulations,)) approximate_value_function = LinearRegression() approximate_value_function.fit(X=X, y=y) print( f"running solver using {get_optimal_policy} to find actions given estimated value function" ) for i in range(max_iterations): states = np.random.uniform(low=0.001, high=5.0, size=n_simulations) X[:, 0] = np.log(states) estimated_values = get_estimated_values( states, approximate_value_function, get_optimal_policy, **kwargs ) y = estimated_values previous_coefficients = get_coefficients(approximate_value_function) approximate_value_function.fit(X=X, y=y) current_coefficients = get_coefficients(approximate_value_function) if np.allclose( current_coefficients, previous_coefficients, rtol=1e-04, atol=1e-06 ): print(f"converged at iteration {i}!") break print( f"true value is {(1 / (1 - DISCOUNT_FACTOR))}, estimate is {approximate_value_function.coef_}" ) print( f"true value is {VALUE_FUNCTION_CONSTANT_TERM}, estimate is {approximate_value_function.intercept_}" ) return approximate_value_function def save_value_function_plot( approximate_value_function, approximate_value_function_coarse_grid, approximate_value_function_fine_grid, ): fig, ax = plt.subplots(figsize=(10, 8)) # Note: wealth is the state variable wealth = np.linspace(0.01, 100, 1000) log_wealth = np.log(wealth).reshape(-1, 1) correct_value = optimal_value_function(wealth) approximate_value = approximate_value_function.predict(log_wealth) approximate_value_coarse_grid = approximate_value_function_coarse_grid.predict( log_wealth ) approximate_value_fine_grid = approximate_value_function_fine_grid.predict( log_wealth ) plt.plot( wealth, correct_value, label="true value function (analytical solution)", linewidth=2, ) # Note: don't show the left and right ends of the estimated value functions # so that they don't entirely cover/hide the true value function on the plot idx_start, idx_stop = (1, -10) plt.plot( wealth[idx_start:idx_stop], approximate_value[idx_start:idx_stop], "--", label="estimated value function (using log-linear regression & first order condition for action)", ) plt.plot( wealth[idx_start:idx_stop], approximate_value_coarse_grid[idx_start:idx_stop], ":", label="estimated value function (using log-linear regression & coarse grid search for action)", ) plt.plot( wealth[idx_start:idx_stop], approximate_value_fine_grid[idx_start:idx_stop], ":", label="estimated value function (using log-linear regression & fine grid search for action)", ) plt.xlabel("wealth (state variable)") plt.ylabel("value function") ax.legend() outdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), PLOT_DIR) outfile = "cake_eating_problem_value_function.png" plt.savefig(os.path.join(outdir, outfile)) plt.close() fig, ax = plt.subplots(figsize=(10, 8)) plt.plot( wealth, optimal_policy(wealth), label="optimal action (analytical solution)" ) plt.plot( wealth, optimal_policy_grid_search( wealth, approximate_value_function_coarse_grid, FRACTION_CONSUMED_GRID_COARSE, ), label="action (using log-linear regression & coarse grid search for action)", ) plt.plot( wealth, optimal_policy_grid_search( wealth, approximate_value_function_fine_grid, FRACTION_CONSUMED_GRID_FINE ), label="action (using log-linear regression & fine grid search for action)", ) plt.xlabel("wealth (state variable)") plt.ylabel("amount consumed (action)") ax.legend() outfile = "cake_eating_problem_action.png" plt.savefig(os.path.join(outdir, outfile)) def main(): approximate_value_function = calculate_approximate_solution( optimal_policy_given_approximate_value_function ) approximate_value_function_coarse_grid = calculate_approximate_solution( optimal_policy_grid_search, fraction_consumed_grid=FRACTION_CONSUMED_GRID_COARSE ) approximate_value_function_fine_grid = calculate_approximate_solution( optimal_policy_grid_search, fraction_consumed_grid=FRACTION_CONSUMED_GRID_FINE ) save_value_function_plot( approximate_value_function, approximate_value_function_coarse_grid, approximate_value_function_fine_grid, ) if __name__ == "__main__": main()
3e00e3a9107d097afa6fc17f93addffd7ddbd979
JorrgeX/CMPSC132
/Hsieh_Program9.py
3,274
3.953125
4
#Hsieh_Program9 #Yuan-Chih Hsieh #CMPSC132 Program9 import matplotlib.pyplot as plt class sales: def __init__(self, dollars, date): self.dollars = dollars self.date = date #dollars getter def get_dollars(self): return self.dollars #data getter def get_date(self): return self.date #dollars setter def set_dollars(self, new): self.dollars = new def menu(): choice = '' #use hash table to store the data table = dict() while choice != '6': #quit if choice equals 6 print('----------') print('Menu') print('----------') print('1) Add\n2) View\n3) Delete\n4) Modify\n5) Plot\n6) Quit') print('----------') choice = input('Enter your choice: ') #Add if choice == '1': try: dollars = float(input('Please enter the amount of dollars: ')) date = int(input('Enter the date(MMDD): ')) table[date] = sales(dollars, date) #use the date as the key for dictionary except ValueError: print('Invalid input') #View elif choice == '2': for _ in table: #goes through all the elements in the dictionary print('Dollars: {} Date: {}'.format(table[_].get_dollars(), table[_].get_date())) #Delete elif choice == '3': try: key = int(input('Enter the date of data you want to delete: ')) while key not in table.keys(): #if the user enter a key value that is not a dictionary key print('Invalid input') key = int(input('Enter the date of data you want to delete: ')) del table[key] #find the data and delete by using the dictionary key except ValueError: print('Invalid input') #Modify elif choice =='4': try: key = int(input('Enter the date of data you want to modify: ')) while key not in table.keys(): #if the user enter a key value that is not a dictionary key print('Invalid input') key = int(input('Enter the date of data you want to delete: ')) dollars = float(input('Please enter the amount of dollars: ')) table[key].set_dollars(dollars) #use the dollars setter except ValueError: print('Invalid input') #Plot elif choice =='5': xaxis = sorted(table.keys()) #sort the date in a list yaxis = [] for i in xaxis: yaxis.append(table[i].get_dollars()) #match the date to the dollars plt.plot(xaxis, yaxis, 'ro-', linewidth=5, markersize=5, alpha=0.35) plt.title('Sales') plt.xlabel('Date (MMDD)') plt.ylabel('Amount of Dollars') plt.show() #Quit elif choice == '6': print('Thank you!') else: print('Invalid input') return if __name__ == '__main__': menu()
11734e142f8710406d7003e27ca5000bf28356c7
mengyeli/HackerRank
/Python/DataTypes/NestedLists.py
204
3.640625
4
L = [] for _ in range(int(input())): L.append([input(), float(input())]) score = sorted(list(set([mark for name, mark in L])))[1] print('\n'.join([name for name, mark in sorted(L) if mark == score]))
b40ffe5b7b7a83f71824f279cc36527c12b33ad1
krasigarev/functions
/def_square.py
595
4.09375
4
n = int(input()) # вариант 1 def print_dashes(num): print("-"*(num*2)) def print_body(number): for i in range(1, number - 1): print("-" + "\\/"*int((2*number-2)/2) + "-") print_dashes(n) print_body(n) print_dashes(n) print("--"*2) # вариант 2 def print_dashes(num): print("-"*(num*2)) def print_body(number): print("-" + "\\/"*int((2*number-2)/2) + "-") print_dashes(n) for i in range(1, n-1): print_body(n) print_dashes(n) ''' решение == изход -------- -\/\/\/- -\/\/\/- -------- ---- -------- -\/\/\/- -\/\/\/- -------- '''
7ef3b3d9ca4778da0e93147c13d545db8e315ef9
pombredanne/suffix_tree-1
/test_suffix_tree.py
2,749
3.5
4
import unittest from suffix_tree import SuffixTree class SuffixTreeTestCase(unittest.TestCase): def test_init(self): st = SuffixTree('foo') rows = st.get_rows() self.assertEqual(len(rows), 5) # root plus len(foo) + null term self.assertEqual(len(rows[0]), 1) # The root level self.assertEqual(len(rows[1]), 3) # 'f', 'o', and '\0' self.assertEqual(len(rows[2]), 3) # 'o' (of f), 'o' (of o), # '\0' (of o) self.assertEqual(len(rows[3]), 2) # 'o' (of o of f), '\0' (of o of o) self.assertEqual(len(rows[4]), 1) # '\0' (of o) root_item = rows[0][0] self.assertEqual(root_item.let, None) self.assertEqual(root_item.parent, None) self.assertEqual(root_item.depth, 0) self.assertEqual(root_item.positions, set([None])) self.assertIn('f', root_item.children) self.assertIn('o', root_item.children) self.assertIn("\0", root_item.children) f_item = root_item.children['f'] o_item = root_item.children['o'] null_item = root_item.children['\0'] row1 = (f_item, o_item, null_item) self.assertEqual([item.let for item in row1], ['f', 'o', '\0']) self.assertEqual([item.parent for item in row1], 3 * [rows[0][0], ]) self.assertEqual([item.depth for item in row1], [1, 1, 1]) self.assertEqual([item.positions for item in row1], [set([0]), set([1, 2]), set([3])]) f_child_o = f_item.children['o'] self.assertEqual(f_child_o.let, 'o') self.assertEqual(f_child_o.parent, f_item) self.assertEqual(f_child_o.depth, 2) self.assertEqual(f_child_o.positions, set([1])) o_child_o = o_item.children['o'] self.assertEqual(o_child_o.let, 'o') self.assertEqual(o_child_o.parent, o_item) self.assertEqual(o_child_o.depth, 2) self.assertEqual(o_child_o.positions, set([2])) # FIXME: Comprehensive testing is really called for here. Test every # node in the tree. lowest_null_parent = f_child_o.children['o'] lowest_null = lowest_null_parent.children['\0'] self.assertEqual(lowest_null.let, '\0') self.assertEqual(lowest_null.parent, lowest_null_parent) self.assertEqual(lowest_null.depth, 4) self.assertEqual(lowest_null.positions, set([3])) def test_search(self): st = SuffixTree('This is a test') self.assertEqual(st.search('T'), [0]) self.assertEqual(st.search('Th'), [0]) self.assertEqual(st.search('h'), [1]) self.assertEqual(st.search('is'), [2, 5]) self.assertEqual(st.search('qqqqq'), None)
57bd1595ead671cbc0118ef3de8a5a018d693a32
sinooko/tinkering
/star.py
4,343
3.796875
4
from planet import Planet from roman import toRoman from random import randrange, randint from solar_calc import namer, log, radius_gen def planet_pop(mass, num=None, star_name=None): """ Takes in a number, star mass, and the star's name Returns a list of planet objects Roche Limit describes min distance between two orbital bodies The min distance will be derived from the roche limit roche limit = 1.26 * radius of planet * (( mass of sun / mass of planet) ** (1/3)) The max distance a planet will be from the sun is 10 ** 10 km """ log("Populating the solar system with planets.") planets = [] distance_max = 10 ** 10 for x in range(0, num): log("Creating planet " + str(x + 1)) if star_name: name = str(star_name) + ' ' + toRoman(x + 1) else: name = namer() log("Planet's name is " + name) planet_mass = randrange((8 * (10 ** 22)), (2 * (10 ** 29))) log(name + "'s mass is " + str(planet_mass)) planet_radius = radius_gen(planet_mass) log(name + "'s radius is " + str(planet_radius)) distance_min = int( 1.26 * planet_radius * ((mass / planet_mass) ** (1 / 3)) ) log("Minimum distance is " + str(distance_min)) # Test for planetary roche limits while True: collision = False distance = randrange(distance_min, distance_max) if len(planets) > 0: for planet in planets: # Find and assign large and small planet stats if planet.mass > planet_mass: lplanet_mass = planet.mass splanet_mass = planet_mass splanet_radius = planet_radius else: lplanet_mass = planet_mass splanet_mass = planet.mass splanet_radius = planet.radius # Use large and small planet stats to calculate roche limit roche_limit = 1.26 * \ splanet_radius * \ ((lplanet_mass / splanet_mass) ** (1 / 3)) if abs(distance - planet.orbit_distance) < roche_limit: log( "Planetary collision detected, calculating new " "distance." ) collision = True # If no collision has been found break leaving distance intact if not collision: log("Planetary orbits do not overlap, keeping orbit distance.") break planets.append( Planet(distance, mass, name, planet_mass, planet_radius) ) log("Planet " + name + " Created") return planets class Star(object): """ An object to create solar systems star_mass: Mass (KG) of the central star within the solar system (Min = 2 * (10 ** 29)) (Max = 3 * (10 ** 32)) """ def __init__(self, mass=0, planets=0, name=None): log("A new solar system has been requested") self.radius = radius_gen(mass) log("Radius: " + str(self.radius)) if name: self.name = name log("Star name: " + self.name + "\n") else: self.name = namer() log("Star name randomly generated as: " + self.name + "\n") if mass == 0: self.mass = randint((2 * (10 ** 29)), (3 * (10 ** 32))) log("Star mass randomly generated as: " + str(self.mass) + "\n") else: self.mass = mass log("Star mass: " + str(self.mass) + "\n") if planets == 0: self.planets = planet_pop( self.mass, num=randint(1, 15), star_name=self.name ) log(str(len(self.planets)) + " planets randomly generated.") else: self.planets = planet_pop(self.mass, num=planets) log(str(len(self.planets)) + " planets generated.") log("star.py loaded")
9f789d705f17c187306d3023e89460955c6f786d
Runthist/like
/krasov2.py
471
3.984375
4
a = float(input('Введите координаты центра круга:\nx = ')) b = float(input('y = ')) с = float(input('Радиус круга: ')) if с > 0: x = float(input('Введите координаты точки:\nx = ')) y = float(input('y = ')) if (((x-a)**2+(y-b)**2)<=(с**2)): print('Точка попала в круг!') else: print('Точка не попала в круг!') else: print('Ошибка')
c10b0e4daf1735f0e4384fe51ce65b87bb0825f3
santiagoom/leetcode
/solution/python/155_MinStack_2.py
756
3.703125
4
from typing import List from utils import * class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, x: int) -> None: self.stack.append(x) if not self.min_stack or x <= self.min_stack[-1]: self.min_stack.append(x) def pop(self) -> None: if self.min_stack[-1] == self.stack[-1]: self.min_stack.pop() self.stack.pop() def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return self.min_stack[-1] if __name__ == "__main__": nums = [2, 7, 11, 15] target = 26 s = "aa" arrays = [[1, 2, 3], [4, 5, 6]] print(arrays)
4a828ad2d0b8e6b6ff18f7b14ac139a631ef6ea9
RobolinkInc/RoPi
/RoPi_Python_Samples/1_topIRSensors.py
470
3.5
4
import RoPi as rp ropi = rp.RoPi() #create a while loop so we can read the top IR sensors while(1): leftIR, middleIR, rightIR = ropi.readTopIRsensors() print(leftIR, middleIR, rightIR) #this will print the information #you can test it this by placing your fingers #in front of the smart inventor board #the info it is showing is a number between 0-1023 #notice what happens with the number as you bring your #hand closer to the sensor
581f61c95f2cec725e1101f08fa3f3a7e74d4d76
Darshitpipariya/Information_technology
/playfair.py
3,632
3.59375
4
def key_genarator(key): alphabet='abcdefghiklmnopqrstuvwxyz' key=key.replace(" ","") table=[] for char in key.lower(): if char not in table: if char=='j': char='i' table.append(char) for char in alphabet: if char not in table: table.append(char) j=0 final=[] for i in range(5): l=[] for k in range(5): if(j<len(table)): l.append(table[j]) j+=1 final.append(l) return final def to_diagraph(text): table=[] text=text.replace(" ","") for i in range(len(text)-1): table.append(text[i]) if(text[i]==text[i+1]): if(text[i]=='x'): table.append('y') else: table.append('x') table.append(text[-1]) if(len(table)%2!=0): if(text[-1]=='x'): table.append('y') else: table.append('x') l1=[] for i in range(0,len(table),2): l1.append([table[i],table[i+1]]) return l1 def encryption(): plaintext=input("Enter plaintext: " ) key=input("Enter key: ") diagraph=to_diagraph(plaintext) key_matrix=key_genarator(key) cipher=[] #find co-ordinates of dia-graph in key metrix for d in diagraph: e1,e2=d[0],d[1] for i in range(len(key_matrix)): if(e1 in key_matrix[i]): j=key_matrix[i].index(e1) e1_x,e1_y=i,j if(e2 in key_matrix[i]): j=key_matrix[i].index(e2) e2_x,e2_y=i,j if(e1_x==e2_x): # if row is same e1=key_matrix[e1_x][(e1_y+1)%5] e2=key_matrix[e2_x][(e2_y+1)%5] elif(e1_y==e2_y): # if column is same e1=key_matrix[(e1_x+1)%5][e1_y] e2=key_matrix[(e2_x+1)%5][e2_y] else: e1=key_matrix[e1_x][e2_y] e2=key_matrix[e2_x][e1_y] cipher.append(e1) cipher.append(e2) cipher="".join( i for i in cipher) print("Ciphertext:-{}".format(cipher)) def decryption(): ciphertext=input("Enter ciphertext: ") key=input("Enter key:") diagraph=to_diagraph(ciphertext) key_matrix=key_genarator(key) plaintext=[] #find co-ordinates of dia-graph in key metrix for d in diagraph: e1,e2=d[0],d[1] for i in range(len(key_matrix)): if(e1 in key_matrix[i]): j=key_matrix[i].index(e1) e1_x,e1_y=i,j if(e2 in key_matrix[i]): j=key_matrix[i].index(e2) e2_x,e2_y=i,j if(e1_x==e2_x): # if row is same e1=key_matrix[e1_x][(e1_y-1)%5] e2=key_matrix[e2_x][(e2_y-1)%5] elif(e1_y==e2_y): # if column is same e1=key_matrix[(e1_x-1)%5][e1_y] e2=key_matrix[(e2_x-1)%5][e2_y] else: e1=key_matrix[e1_x][e2_y] e2=key_matrix[e2_x][e1_y] plaintext.append(e1) plaintext.append(e2) plaintext="".join( i for i in plaintext) plaintext=plaintext.replace('x','') print("Plaintext:- {} ".format(plaintext)) if __name__ == "__main__": print("________ Playfair cipher________") while True: choice=int(input("Enter choice\n1:Encryption\n2:Decryption\n3:Exit\n")) if (choice==1): encryption() elif(choice==2): decryption() elif(choice==3): break else: print("Invalid choice")
b4e18ca9e22ecde70bfa17eb2b596fa5846d6de8
PnuLikeLion9th/Summer_algorithm
/joonghoo/1주차/0621 행렬의 덧셈.py
551
3.8125
4
# 프로그래머스_행렬의 덧셈_자료구조_레벨 1 # 자료구조 리스트를 이용하여 같은열, 같은행에 있는 값을 더해주면 된다. def solution(arr1, arr2): answer = [[]] for i in range(len(arr1)): # arr1의 1차원 list 갯수만큼 반복 for j in range(len(arr1[i])): # arr[i]의 길이만큼 반복 arr1[i][j] += arr2[i][j] # arr1와 arr2의 같은열, 같은행의 원소를 더해준다 return arr1 arr1 = [[1, 2], [2, 3]] arr2 = [[3, 4], [5, 6]] print(solution(arr1, arr2))
34787232a2c7603d09d79e47f5819af3761176b2
savanibharat/PythonPrograms
/com/Core/Searching/RecursiveBinarySearch.py
847
3.96875
4
''' Created on Feb 8, 2014 @author: Savani Bharat ''' def binary_search(number_list, key, lower_bound, upper_bound): if (upper_bound < lower_bound): return None else: middle_position = lower_bound + ((upper_bound - lower_bound) / 2) if number_list[middle_position] > key: return binary_search(number_list, key, lower_bound, middle_position-1) elif number_list[middle_position] < key: return binary_search(number_list, key, middle_position+1, upper_bound) else: return middle_position if __name__ == "__main__": number_list = [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12] lower_bound = 0 key=8 upper_bound = len(number_list)-1 #for key in [8, 6, 1, 12, 7]: index = binary_search(number_list, key, lower_bound, upper_bound) print key, index
9d24312111414e67a1d03b3f279a707dd2d5a6fa
samedhaa/Problem-Solving
/Random Questions from books/LinkedLists & Arrays/(2.1).py
862
3.671875
4
''' Write code to remove duplicates from an unsorted linked list. Follow up : how would you solve this problem is a temporary buffer is not allower ''' class Node: def __init__(self, val): self.val = val self.next = None def traverse(self): node = self while node != None: print(node.val) node = node.next ## the function that removes the dublicates def removeDub(self): node = self answerNode = self mp = {} mp[node.val] = True while(node != None): if node.val not in mp.keys(): mp[node.val] = True answerNode.next = node answerNode = answerNode.next else: answerNode.next = None node = node.next return answerNode node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(2) node1.next = node2 node2.next = node3 node3.next = node4 node1 = node1.removeDub() node1.traverse()
7eb550737172eee56de37a9c71928cecb2a98c39
ppnp-2020/02-exercicios-funcoes
/saque/funcoes.py
569
3.8125
4
saldo = 1000 numero_conta = '1234-5' senha_conta = '112233' def efetuar_saque(): valor = input('Digite o valor desejado: ') if not valor.isnumeric(): print('O valor digitado é inválido') return valor = float(valor) if valor <= saldo: print('Saque efetuado') else: print('Saldo insuficiente') def autenticar(conta_informada, senha_informada): if numero_conta == conta_informada or senha_conta == senha_informada: print('Acessando a conta...') return True else: print('Crendenciais inválidas') return False
29815dca943113fa31358d86bb17baf8ef6368f6
moontree/leetcode
/version1/457_Circular_Array_Loop.py
1,786
4.1875
4
""" You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first element. Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be "forward" or "backward'. Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0. Example 2: Given the array [-1, 2], there is no loop. Note: The given array is guaranteed to contain no element "0". Can you do it in O(n) time complexity and O(1) space complexity? """ def circular_array_loop(nums): """ :type nums: List[int] :rtype: bool """ step, idx, n = 0, 0, len(nums) for i, v in enumerate(nums): start, cur, step = i, i, 0 flag = 1 if v > 0 else -1 while True: ni = (n + nums[cur] + cur) % n if cur == ni: break else: cur = ni # print cur if nums[cur] * flag < 0: break step += 1 if cur == start: break if step < 2: continue else: return True return False examples = [ { "nums": [2, -1, 1, 2, 2], "res": True }, { "nums": [-1, 2], "res": False }, { "nums": [-1, -2, -3, -4, -5], "res": True }, { "nums": [2, -1, 1, -2, -2], "res": False } ] for example in examples: print "---" print circular_array_loop(example["nums"])
efd6df70b69011835ba89a46941a9697bfa933a6
LonelyRider-cs/Low_Resource_MT
/python/pipeline/pipeline_tokenizer.py
1,312
3.703125
4
from nltk.tokenize import word_tokenize from nltk.tokenize import RegexpTokenizer #this file is called when needing to tokenize anything. #the language's three letter code is used to distinguish between different types of tokenizers #to add a new langauge tokenizer follow the syntax below and replace 'tag' with the languages 3 letter lang_code #elif tokenizer_type.lower() == 'tag' or tokenizer_type.lower()[:3] == 'tag': def basic_tokenizer(text: str, tokenizer_type = None) -> str: """ segment punctuations from words """ #none if tokenizer_type is None: segmented = text #English elif tokenizer_type.lower() == 'eng' or tokenizer_type.lower()[:3] == 'eng': tokens = word_tokenize(text.replace("’", "'").replace("—", " — ")) segmented = ' '.join(tokens) #Navajo elif tokenizer_type.lower() == 'nav' or tokenizer_type.lower()[:3] == 'nav': tokenizer = RegexpTokenizer("[^\s.\";:,.“”\[\(\)?!]+|[^\w\d'\s\-]") tokens = tokenizer.tokenize(text.replace("’", "'").replace("ʼ", "'")) segmented = ' '.join(tokens) #other else: tokenizer = RegexpTokenizer("[^\s.\";:,.“”\[\(\)?!]+|[^\w\d'\s\-]") tokens = tokenizer.tokenize(text) segmented = ' '.join(tokens) return segmented
f688bc7238a07c93485c2cd57e09044849c9b00b
GuanzhouSong/Leetcode_Python
/Leetcode/119. Pascal's Triangle II.py
371
3.5
4
class Solution: def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ rowIndex += 1 if rowIndex is 0: return [] res = [1] for i in range(1, rowIndex): temp1 = res + [0] temp2 = [0] + res res = [temp1[i] + temp2[i] for i in range(len(temp2))] return res s = Solution() print(s.getRow(3))
1398d87af178f0755b20592c064f4141e4773779
AdamZhouSE/pythonHomework
/Code/CodeRecords/2972/60678/294074.py
246
3.625
4
def findDifferIndex(s, t): for i in range(len(s)): if s[i] != t[i]: return i return len(s) n = int(input()) if n == 2: for i in range(n): s = input() t = input() print(s) print(t)
8d18fd059ff3de3a7634166389a03fe8c6a8b6ef
wanda93/Exercise-Chapter-4
/4.6.py
438
3.703125
4
def total (hour,rate): #bagian dari pendeklerasian fungsi jam = float(hour) byr = float(rate) if jam < 40: #bagian pengecekan byarn = jam * byr print byarn else : nrmal = 40 * byr ext = jam - 40 rte = (byr*3/2) * ext total = nrmal + rte print "pay :", float(total) hours = raw_input ('Enter Hours:') rates = raw_input ('Enter Rate:') total(hours,rates) #bagian memanggil fungsi
e5372e17bf9fa0e0337ed84cb4bfec86264bc88f
gurusms/stepik-base_and_use-python
/lesson13-step9.py
203
3.65625
4
def closest_mod_5(x): # y = int(x / div) * div + div y = x+5-x%5 if y % 5 == 0: return y return "I don't know :(" i = int(input ()) print (f"решение = {closest_mod_5(i)}")
5ece1f55959663326f7e20894ac5d7129f43375b
UendelSoares/Atividades_Python
/Lista de atividades 1/Atividade 02.py
401
3.875
4
#2. Fazer um algoritmo que leia o valor do salário mínimo e o valor do salário de uma #pessoa. Calcular e escrever quantos salários mínimos essa pessoa ganha. salario = float(input("Qual seu salario (R$)? ")) s_min = 1100 if (salario < s_min): print("Você recebe menos que um salario minimo") else: t_salario = salario / s_min print (f"Você recebe {t_salario:.2f} em salarios minimos")
2afcb05988a59fa6e6d9d080ef88fced9c83ebe0
ronak007mistry/Python-programs
/palindrome.py
161
4.28125
4
string = input("Enter the string: ") rev_string = string[::-1] if string == rev_string: print("String is Palindrome ") else: print("String is not Palindrome")
efd3a4d8c53ce3baa477a6f6ed0174f0fe34a168
Ogaday/aoc19
/day_2_1.py
1,029
3.9375
4
""" Solution to Day 2 Part I of the Advent of Code https://adventofcode.com/2019/day/2 To get the answer, run: python -m day_2_1 """ from itertools import zip_longest from typing import List class OpCodeError(Exception): """ Raise when an invalid opcode is encountered. """ def run(intcode: List[int]) -> None: """ Process an intcode program. Mutates the input in place - does not return the modified program. """ for opcode, arg1, arg2, output in zip_longest(*[iter(intcode)] * 4): if opcode == 1: intcode[output] = intcode[arg1] + intcode[arg2] elif opcode == 2: intcode[output] = intcode[arg1] * intcode[arg2] elif opcode == 99: break else: raise OpCodeError(f'{opcode=} is not a recognised opcode') if __name__ == "__main__": with open('input/day_2.txt') as f: program = [int(n) for n in f.read().split(',')] program[1] = 12 program[2] = 2 run(program) print(program[0])
abe1211d505721bce3bf37cd5633cf31097c56d7
DarshanaPorwal07/Python-Programs
/%Calc.py
532
4.03125
4
total=int(input("enter the total marks:")) sub1=int(input("enter the marks of 1st subject:")) sub2=int(input("enter the marks of 2ns subject:")) sub3=int(input("enter the marks of 3rd subject:")) sub4=int(input("enter the marks of 4th subject:")) sub5=int(input("enter the marks of 5th subject:")) marks_obtained=sub1+sub2+sub3+sub4+sub5 print("---------------------------------------------") print("Total marks obtained is: ",marks_obtained) percentage=(marks_obtained/total)*100 print("Percentage is :",percentage)
e1da8793a96bcca9eeed3836dc90565105508914
sanketag/startxlabs-assignment
/minTime.py
1,772
3.96875
4
"""Time required by all the customers to checkout.""" def get_checkout_time(cust,c_r): rem = c_r-1 """Recursive function to process next customers.""" def fun(e,f): nonlocal rem """Checking if suitable amount of cash registers are available""" if f==0: return max(e) else: temp = min(e) zero = e.count(temp) """Reducing time spent by the customer with minimum time requirement from every cash register""" temp1 = [i-temp for i in e if (i-temp)!=0] rem+=1 """Adding next customers in the line""" if rem<len(cust)-zero: return temp+fun(temp1+cust[rem:rem+zero],1) else: return temp+fun(temp1+cust[rem:],0) """Checking if suitable amount of cash registers are available""" """Assigning a customer to every cash register along with the flag of remaining customers""" if c_r>=len(cust): return fun(cust,0) elif c_r==0: return 0 else: return fun(cust[:c_r],1) print(get_checkout_time([5, 1, 3], 1)) print(get_checkout_time([10, 3, 4, 2], 2)) """ cust : original list of customers c_r : number of open cash registers rem : pointer according to number of open cash registers e : number of customers equivalent to number of open cash registers f : flag for availability of more customers zero : number of 0 left after completing of customer time with least time requirement in the line temp : least time required by customer in line temp1 : new line of available customers and customers with remaining time """
0f81635e6ef977e7c31a35363d8382fe1d70195b
cesarco/MisionTic
/s5/5.1_input.py
106
3.703125
4
numero = input("Por favor digite un número: ") print("El número que el usuario ingreso es: ", numero)
08cf5a07d3fdfeb45b310796d0af907284c76dd9
tushargoyal02/PythonBasicsToAdVance
/sortingFunctions.py
511
4.1875
4
# sort the data structure in python nums = [1,0,-1,23,445] #using sorted function to sort the values - Return a list output =sorted(nums) print(output) #sorting result in reverse order output =sorted(nums, reverse=True) print(output) #sorting the data as per the length of the string #-- HERE WE HAVE KEY PARAMETER , where we can define our logic def lengthSorting(x): return len(x) data = ['a','fdsafas','tushar'] finalOut = sorted(data , key=lengthSorting) print(finalOut)
09e682fafcf6a4cf0dea5f064563967d8b2a89e2
justin-zimmermann/coursera-Data-Manipulation-at-Scale-Systems-and-Algorithms
/thinking-in-mapreduce/multiply.py
982
3.78125
4
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): matrix = record[0] row = record[1] column = record[2] value = record[3] if matrix == 'a': for column in range(5): mr.emit_intermediate((row, column), record) if matrix == 'b': for row in range(5): mr.emit_intermediate((row, column), record) def reducer(key, list_of_values): # key: row, column tuple # value: record value = 0 for v in list_of_values: if v[0] == 'a': for v2 in list_of_values: if v2[0] == 'b' and v2[1] == v[2]: value += v[3] * v2[3] mr.emit(key + (value,)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
2b9703089160f683f812bd7652de065df3a1093c
spandanag333/python-programming-tasks
/task6.py
438
4.0625
4
A = int(input("enter the length of the first side of the triangle :")) B = int(input("enter the length of the second side of the triangle :")) C = int(input("enter the length of the third side of the triangle :")) if A==B and B==C and C==A: print("EQUILATERAL TRIANGLE") elif A!=B and B!=C and C!=A: print("SCALENE TRIANGLE") elif A==B or B==C or C==A: print("ISOSCELES TRIANGLE") else: print("INVALID TRIANGLE")
ee15c8ead7f3e7ec6edff1572906a5a8b5cf6d35
chrislevn/Coding-Challenges
/Blue/Stack&Queue/Mass_of_Molecule.py
690
3.625
4
formula = input() result = 0 new_arr = [] for i in range(len(formula)): if formula[i] == "C": new_arr.append(12) if formula[i] == "O": new_arr.append(16) if formula[i] == "H": new_arr.append(1) if formula[i].isnumeric(): if formula[i-1] != ")": new_arr.append(new_arr.pop() * int(formula[i])) else: new_arr.append(new_arr.pop() * int(formula[i])) if formula[i] == "(": new_arr.append("(") if formula[i] == ")": sub_list = [] while new_arr[-1] != "(": sub_list.append(new_arr.pop()) new_arr.pop() new_arr.append(sum(sub_list)) print(sum(new_arr))
8ec6285f15711b4090cd655372fe62935d44919c
hariomvc/python
/Savings_account.py
819
3.96875
4
annual_Inter_rate = 0 class SavingAccount: def set_balance(self, balance): self.saving_balance = balance def cal_monthly_interest(self, annual_Inter_rate): self.saving_balance += self.saving_balance * annual_Inter_rate /12 saver1 = SavingAccount() saver2 = SavingAccount() saver1.set_balance(2000) saver2.set_balance(3000) annual_Inter_rate = 0.05 saver1.cal_monthly_interest(annual_Inter_rate) saver2.cal_monthly_interest(annual_Inter_rate) print(f'Balance for Saver1: Rs.{saver1.saving_balance}; Balance for Saver2: Rs.{saver2.saving_balance}') annual_Inter_rate = 0.07 saver1.cal_monthly_interest(annual_Inter_rate) saver2.cal_monthly_interest(annual_Inter_rate) print(f'Balance for Saver1: Rs.{saver1.saving_balance}; Balance for Saver2: Rs.{saver2.saving_balance}')
e742f6301f749f957d2a01ff0c5087ee43ce4ac0
sendurr/spring-grading
/submission - Homework3/set2/JEREMY W ABRAMS_11058_assignsubmission_file_abramsjw_homework3/abramsjw_homework3/P1.py
329
3.796875
4
# Jeremy Abrams # CSCE 206 # Homework 3 - P1.py # February 18 2016 def area(vertices): x1 = vertices[0][0] x2 = vertices[1][0] x3 = vertices[2][0] y1 = vertices[0][1] y2 = vertices[1][1] y3 = vertices[2][1] area = (0.5)*((x2*y3) - (x3*y2) - (x1*y3) + (x3*y1) + (x1*y2) - (x2*y1)) return area print area([[0,0],[1,0],[0,2]])
6f7c8757988f6374e915560267af5dfd34c69b32
gunnerVivek/Foretelling-Retail-price-using-Multivariate-Regression
/utility_functions.py
1,591
3.890625
4
''' This module defines the various utility functions needed in the project. ''' import numpy as np import pandas as pd def threshold_data(data): ''' Apply thresholding to data. Threshold values are decided by using IQR. Maximum threshold value is 3rd Quartile added to 1.5 times the IQR(Inter QuartileRange) Minimum threshold value is 1st Quartile minus 1.5 times IQR(Inter QuartileRange) Parameters: ----------- data: the range of values to be thresholded. Returns: ------- A dictionary containing minimum threshold, maximum threshold, Thresholded values ''' data = pd.Series(data) q1, q3 = np.percentile(data, [25, 75]) IQR = q3 - q1 min_threshold = q1 - 1.5*IQR max_threshold = q3 + 1.5*IQR thresholded_data = data.apply(lambda x: min(max(min_threshold, x), max_threshold)) return {'min_th': min_threshold, 'max_th': max_threshold, 'th_data': thresholded_data} def median_transformation(variable): ''' Z - transformation uses mean and is provided as: z = (x - u) / s However, to use it in presence of outliers, we replace mean statistics with median, and standard deviation with Median Absolute deviation. As below: z = (x - median) / mad ''' median = np.median(variable) mad = stats.median_abs_deviation(variable, nan_policy='omit') return pd.Series(variable).apply(lambda x: (x-median)/mad)
35df57baf6fefa64ee4ef97d32123dd9a82969f0
dangrenell/exercism
/raindrops/raindrops.py
361
3.625
4
def convert(number): return_string = '' factor_dict = {3: "Pling", 5: "Plang", 7: "Plong"} try: for factor, string in factor_dict.items(): return_string += string if number % factor == 0 else '' return str(number) if return_string == '' else return_string except: raise Exception("Something went wrong!")
abe7e86864388aac5be95aab89f0317f37a567c8
SThornewillvE/Udemy_LazyProgrammer_Courses
/Linear_Regression/R_sq.py
722
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 7 10:49:43 2019 @author: sthornewillvonessen """ # Import Packages import numpy as np def R_sq_eval(y, y_pred): """ Compares predicted independant values and compares it with the real value to compare the R-squared value. :returns: r_sq """ # Convert to array y = np.array(y) y_pred = np.array(y_pred) if len(y) != len(y_pred): print("Input y and y_pred are not the same length") return None d1 = y - y_pred d2 = y - y.mean() r2 = 1 - (d1.dot(d1) / d2.dot(d2)) return r2 def Main(): pass if __name__ == '__main__': Main()
1dcebde42e7512b66620deb4ab99c6491a7c2060
Aasthaengg/IBMdataset
/Python_codes/p02256/s461624254.py
240
3.65625
4
def gcd(x, y): if x < y: tmp = x x = y y = tmp while y > 0: r = x % y x = y y = r return print(x) x_y = input() tmp = list(map(int, x_y.split())) x = tmp[0] y = tmp[1] gcd(x, y)
cb056e5898becf7722fef06fb09dc529973156bf
sirius0503/my_python_crash_course_codes
/transportation.py
223
3.921875
4
vehicles = ["trains" , 'vistara flight' , 'bullet train' , 'bicycle' , 'fast cars'] for index in range(len(vehicles)): print("I like to travel by " + vehicles[index] + " since ,I haven't driven cars or motorcyles ,etc")
7bd34ff0009b598c8185c67308a78a0fe5deb90d
SamuelMarsaro/Listas-Python-CESAR
/Lista 7/sam/q2_sam.py
847
3.734375
4
genetic_map = input() base = input() list_order = [] first = genetic_map[0] i = 0 biggest_sequence = -1 big_sequence = 0 if base in genetic_map: # Finding the position and the lenght of the biggest base sequence for character in genetic_map[1:]: if character == first[-1]: first += character else: list_order.append(first) first = character list_order.append(first) while i < len(list_order): if base in list_order[i]: x = len(list_order[i]) if x > biggest_sequence: biggest_sequence = x big_sequence = list_order[i] i = i + 1 position_biggest_sequence = genetic_map.find(big_sequence) print(position_biggest_sequence) print(biggest_sequence) else: print("ERRO")
d07527da91f4b3b54ef9ecb6c7cecb8d6c732f2b
fourohfour/HubskiScript
/Hubski/Hubski.py
1,637
3.53125
4
import requests import json from sys import exit from operator import itemgetter #Ask user for pub ID inputURL = input("Please paste the Hubski URL here: ") #Check if it's a full URL. If so, slice it to only have the pub ID left. if inputURL.startswith("https://hubski.com/pub?id="): pubID = inputURL[26:] else: print('Incorrect URL. Needs to be in the format "https://hubski.com/pub?id=[number]"') input("Press Enter to exit...") raise SystemExit #Check if that ID exists in the publications list. If it doesn't, stop the script. pubIDlistURL = requests.get("http://api.hubski.com/publications") pubIDlist = pubIDlistURL.text if pubID in pubIDlist: pass else: print('Post/comment does not exist or is not accessible') input("Press Enter to exit...") raise SystemExit #Concenate to create new URL url = "http://api.hubski.com/publication/" + pubID print(url) #Open url, get data into a json http = requests.get(url) data = http.json() #Sort votes from first to last. votes = data['votes'] sortedVotes = sorted(votes, key=itemgetter('id'), reverse=False) #Print the names and add a number in front as a count count = 0 print ('Pub ID: ' + pubID + '\nTitle: ' + str(data["title"]) + \ '\nList of votes, sorted from first voter to last:') for user in sortedVotes: count += 1 if user['up'] == True: vote = 'up' else: vote = 'down' print(str(count) + ': ' + user['user'] + ' voted ' + vote) input("Press Enter to exit...") #__________________________________________________ #Legacy code: Pretty Json printer #print(json.dumps(data, indent=4, sort_keys=True))
20ab9ad351538e367b9c65edee43a7659f0a908d
AngelSosaGonzalez/IntroduccionMachineLearning
/Machine Learning/IntroduccionML/Algoritmos/IntroKNNClasific.py
3,286
3.890625
4
""" Introduccion a la clasificacion: Este proyecto pondrmos ya a prueba lo aprendido en los otros proyectos de introduccion a los modulos encargados en Machine Learning, pero ahora no enfocaremos en la clasificacion pero antes de esto, ¿Que es clasificacion?: En pocas palabras un sistema de clasificación predice una categoría ya sabiendo esto vamos con el codigo """ """ Para este proyecto nos basaremos en un curso dado por: AMP Tech Fuente (o video): https://www.youtube.com/watch?v=hzOCDgfsSSQ&list=PLA050nq-BHwMr0uk7pPJUqRgKRRGhdvKb&index=2&pbjreload=101 digo esto porque usaremos una clasificacion de sklearn de iris """ #Importacion de los modulos requeridos #NumPy (Arreglos) import numpy as np #Sklearn (Algoritmos de clasificacion) import sklearn #DataSet de las Iris (la flor) from sklearn.datasets import load_iris #Para dividir nuestra Data en pruebas y entrenamiento from sklearn.model_selection import train_test_split #Importaremos un algoritmo de Sklearn de KNN o vecinos cercanos from sklearn.neighbors import KNeighborsClassifier #Llamamos al set de datos (Iris) FlorIris = load_iris() #NOTA (y dato curioso que comparte el curso): El tipo de dato de nuestro DataSet es de tipo Bunch que se parece a los diccionarios #Vamos a conocer las llaves (o las columnas de nuestro DataSet) print(FlorIris.keys()) """ Para conocer el contenido de datos de cada llave solo basta con llamarlo la variable + el nombre de la llave como este ejemplo. """ #Esto arrojara una matriz de datos de cada flor iris obtenida print(FlorIris['data']) #Este arrojara los tipos de Flores que se obtuvieron (o las etiquetas) print(FlorIris['target']) #Este arrojara el nombre de las etiquetas print(FlorIris['target_names']) #Este arroja en el nombre al que pertenece los datos print(FlorIris['feature_names']) """ Vamos a ocupar la funcion para el entrenamiento y pruebas (train_test_split) para el uso de esta funcion lo dividiremos en 4 variables donde se guardara los valores de entrenamiento y purebas, para esto los dividiremos en X y Y (para pruebas y entrenamiento) """ X_Entrenamiento, X_Prueba, Y_Entrenamiento, Y_Prueba = train_test_split(FlorIris['data'], FlorIris['target']) """ Vamos a darle un valor a nuestra K, esto significa cuantos vecinos vamos a tomar como referencia para saber al momento de ingresar un nuevo registro o clasificar un registro nuevo, este toma como referencia el numero de vecino introducidos (osea el valor de K) al momento de darle un valor este tomara el valor de los vecinos que el nuevo registro tomara de referencia para asi clasificarlo """ #Como en el curso toma 7 vecino igual tomaremos 7 vecinos K = KNeighborsClassifier(n_neighbors=7) #Ahora vamor a entrenar nuestro clasificador, para entrenarlo usaremos los valores de X_Entrenamiento y Y_Entrenamiento, usando la funcion "fit" K.fit(X_Entrenamiento, Y_Entrenamiento) #Calcularemos la presicion de nuestro clasificador print(K.score(X_Prueba, Y_Prueba)) #Por ultimo probamos, para esto le mandamos un arreglo bidimencional para que prediga los datos, este arreglo lo llenaremos con los valores basados en la llave de 'data' y usando la funcion 'predict' print(K.predict([[6.2, 3.1, 5.3, 2.4]])) #Los datos que le arrojamos se acerca a los virginica o de etiqueta '2'
175bf3ad3c5888c6e9b7bbdccc5090980569fab9
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Mock Interviews/Social Network Company/On-Site-Question-2.py
587
3.65625
4
#!/usr/bin/env python3 def solution(id_list): # Initiate unique ID unique_id = 0 # XOR for every ID in id list for i in id_list: print('Current ID:\t' + str(i)) print('Unique ID:\t' + str(unique_id)) print('XOR result:\t' + str((unique_id^i))) # XOR operation unique_id ^= i return unique_id print('### Account ID') print('\nList: [1,1,2,2,3]') print('Account ID: ' + str(solution([1,1,2,2,3]))) print('\nList: [1,2,3,1,2,3]') print('Account ID: ' + str(solution([1,2,3,1,2,3]))) print('\nList: [1,2,4,2,3,6,5]') print('Account ID: ' + str(solution([1,2,4,2,3,6,5])))
857a99f2e300cf22d440a7596534962fdc8a1f52
FancyYan123/LeetcodeExercises
/lengthOfLongestSubstring.py
1,075
3.796875
4
""" 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if s == '': return 0 unique_chars, start, end, max_len = set(s[0]), 0, 0, 1 while end < len(s) - 1: end += 1 new_char = s[end] while new_char in unique_chars and start < end: unique_chars.remove(s[start]) start += 1 unique_chars.add(new_char) max_len = max(max_len, len(unique_chars)) return max_len
04d8ea5e254d434f0ef9f4a93fd9bf3febf49b05
DawnEve/learngit
/Python3/pythonCodeGit/day11-RegExp/re2_split.py
785
3.875
4
import re # 用正则表达式切分字符串比用固定的字符更灵活 r='a b c'.split(' ') print('1: ',r) #['a', 'b', '', '', 'c'] #无法识别连续的空格,用正则表达式试试: r=re.split(r'\s+', 'a b c') print('2: ',r) # ['a', 'b', 'c'] #无论多少个空格都可以正常分割。 #加入,试试: r=re.split(r'[\s\,]+', 'a,b, c d ,e fg') print('3: ',r) #再加入;试试: r=re.split(r'[\s\,\;]+', 'a,b;; c d') print('4: ',r) #用一切非字母元素分割 r=re.split(r'[^a-zA-Z]+', 'a,b;; -c d+e|f__g') print('5: ',r) r=re.split(r'[^\w]+', 'a,b;; -c d2+e|f__(g)h') print('6: ','为什么去不掉下划线f__g',r) #因为\w是字母、数字和下划线 r= re.split(r'[\W_]+', 'a,b;; -c d2+e|f__(g)h') print('7: ',r) #去掉了下划线
e352dd1f5e45fe4ade46c5e20b6c100046797af5
sibhatmeq/Python_simple-projects
/Slider.py
551
3.5
4
from tkinter import * from PIL import ImageTk, Image root= Tk() root.title("sliders in python") root.geometry("500x500") vertical = Scale(root, from_=0, to=200).pack() def slide(): my_label = Label(root, text=horizontal.get()).pack() root.geometry(str(horizontal.get()) + "x" + str(vertical.get())) horizontal = Scale(root, from_=0, to=300, orient=HORIZONTAL) horizontal.pack() my_label = Label(root, text=horizontal.get()).pack() my_btn = Button(root, text="click me!", command=slide).pack() root.mainloop()
18fc753813b05b116e0b06e5cbaae9232b03dc1f
adithya1010/Numerics-Solver
/Bigdata/pearson_correlation.py
1,464
3.53125
4
import numpy as np import math from numpy.core.fromnumeric import var print("Pearson Correlation (r)\nEnter the x values :") x = [] temp = float(input()) while(temp!=-1): x.append(temp) temp = float(input()) print("\nEnter the y values :") y = [] temp = float(input()) while(temp!=-1): y.append(temp) temp = float(input()) mean_x = np.mean(x) mean_y = np.mean(y) print("Mean of x : " + str(round(mean_x,2))) print("Mean of y : " + str(round(mean_y,2))) variance = [] variancex = [] variancey = [] print("\nXi-Mean(x)\tYi-Mean(y)\tProduct") for i in range(0, len(x)): variance.append((x[i]-mean_x)*(y[i]-mean_y)) print(str(round((x[i]-mean_x),2)) + "\t\t" + str(round((y[i]-mean_y),2)) + "\t\t" + str(round(variance[i],2))) variancex.append((x[i]-mean_x)*(x[i]-mean_x)) variancey.append((y[i]-mean_y)*(y[i]-mean_y)) print("\t\t\t\t-----") print("\t\t\t\t" + str(round(sum(variance),2))) print("\n(Xi-Mean(x))^2\tYi-Mean(y))^2") for i in range(0, len(x)): print(str(round(variancex[i],2)) + "\t\t" + str(round(variancey[i],2))) print("-----\t\t-----\t\tProduct") print(str(round(sum(variancex),2)) + "\t\t" + str(round(sum(variancey),2)) + "\t\t" + str(round(sum(variancex)*sum(variancey),2))) print("\t\t\t\tRoot()") print("\t\t\t\t" + str(round(math.sqrt(sum(variancex)*sum(variancey)),2))) num = sum(variance) denom = math.sqrt(sum(variancex)*sum(variancey)) pc = num / denom print("\n\nPerson Coefficient : " + str(pc))
a125f72b1242f8793626f03cfd4ec920f2b09bd7
tabish606/python
/threelarge.py
336
4.21875
4
def greater(num1,num2,num3): if num1>num2 and num1>num3: return f"{num1} is greater" elif num2 > num3: return f"{num2} is large" return f"{num3} is large" a = int(input("enter first number : ")) b = int(input("enter second number : ")) c = int(input("enter third number : ")) print(greater(a,b,c))
b9160c083aead29a15a5dacc7f85ac22f33dbd0e
Cptgreenjeans/python-workout
/ch02-strings/e08_sort_string.py
215
3.9375
4
#!/usr/bin/env python3 """Solution to chapter 2, exercise 8: strsort""" def strsort(a_string): """Takes a string as input, returns a string with its characters sorted. """ return ''.join(sorted(a_string))
2158e87d8dada59686aa0c7202de825cf17acb5a
Marumarum/algorithms-practice
/#7Reverse_Integer.py
298
3.8125
4
def reverse(x): if x >= 2**31-1 or x <= -2**31: return 0 else: if x > 0: rever = int(str(x)[::-1]) else: rever = -int(str(-x)[::-1]) if rever >= 2**31-1 or rever <= -2**31: return 0 return rever print(reverse(120000000000))
770b3029b0da01d7f99e118bc8534187075b9507
philiprj/math_4_ml
/distances.py
8,452
3.625
4
# coding: utf-8 # ## Distances and Angles between Images import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy import sklearn from ipywidgets import interact from load_data import load_mnist MNIST = load_mnist() images = MNIST['data'].astype(np.double) labels = MNIST['target'].astype(np.int) # Plot figures so that they can be shown in the notebook get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'") # For this assignment, you need to implement the two functions (`distance` and `angle`) # in the cell below which compute the distance and angle between two vectors. def distance(x0, x1): """Compute distance between two vectors x0, x1 using the dot product""" distance = np.sqrt(np.dot(x0-x1,x0-x1)) return distance def angle(x0, x1): """Compute the angle between two vectors x0, x1 using the dot product""" angle = np.arccos((np.dot(x0,x1)/(np.dot(x0,x0)*np.dot(x1,x1))**(0.5))) return angle def plot_vector(v, w): fig = plt.figure(figsize=(4,4)) ax = fig.gca() plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.grid() ax.arrow(0, 0, v[0], v[1], head_width=0.05, head_length=0.1, length_includes_head=True, linewidth=2, color='r'); ax.arrow(0, 0, w[0], w[1], head_width=0.05, head_length=0.1, length_includes_head=True, linewidth=2, color='r'); # Some sanity checks, you may want to have more interesting test cases to test your implementation a = np.array([1,0]) b = np.array([0,1]) np.testing.assert_almost_equal(distance(a, b), np.sqrt(2)) assert((angle(a,b) / (np.pi * 2) * 360.) == 90) plot_vector(b, a) plt.imshow(images[labels==0].reshape(-1, 28, 28)[0], cmap='gray'); # But we have the following questions: # # 1. What does it mean for two digits in the MNIST dataset to be _different_ by our distance function? # 2. Furthermore, how are different classes of digits different for MNIST digits? Let's find out! # For the first question, we can see just how the distance between digits compare among all distances for # the first 500 digits. The next cell computes pairwise distances between images. distances = [] for i in range(len(images[:500])): for j in range(len(images[:500])): distances.append(distance(images[i], images[j])) # Next we will find the index of the most similar image to the image at index 0. # We will do this by writing some code in another cell. # # Write some code in this scratch cell below to find out the most similar image # Then copy the solution you found (an index value) and replace the -1 in the function `most_similar_image` with this value. # GRADED FUNCTION: DO NOT EDIT THIS LINE def most_similar_image(): """Find the index of the digit, among all MNIST digits that is the second-closest to the first image in the dataset (the first image is closest to itself trivially). Your answer should be a single integer. """ index = 61 #<-- Change the -1 to the index of the most similar image. # You should do your computation outside this function and update this number # once you have computed the result return index result = most_similar_image() # For the second question, we can compute a `mean` image for each class of image, i.e. we compute mean image for digits of `1`, `2`, `3`,..., `9`, then we compute pairwise distance between them. We can organize the pairwise distances in a 2D plot, which would allow us to visualize the dissimilarity between images of different classes. # First we compute the mean for digits of each class. means = {} for n in np.unique(labels): means[n] = np.mean(images[labels==n], axis=0) # For each pair of classes, we compute the pairwise distance and # store them into MD (mean distances). We store the angles between the mean digits in AG MD = np.zeros((10, 10)) AG = np.zeros((10, 10)) for i in means.keys(): for j in means.keys(): MD[i, j] = distance(means[i], means[j]) AG[i, j] = angle(means[i].ravel(), means[j].ravel()) # Now we can visualize the distances! Here we put the pairwise distances. The colorbar # shows how the distances map to color intensity. fig, ax = plt.subplots() grid = ax.imshow(MD, interpolation='nearest') ax.set(title='Distances between different classes of digits', xticks=range(10), xlabel='class of digits', ylabel='class of digits', yticks=range(10)) fig.colorbar(grid) plt.show() # Similarly for the angles. fig, ax = plt.subplots() grid = ax.imshow(AG, interpolation='nearest') ax.set(title='Angles between different classes of digits', xticks=range(10), xlabel='class of digits', ylabel='class of digits', yticks=range(10)) fig.colorbar(grid) plt.show(); # ## K Nearest Neighbors # # In this section, we will explore the [KNN classification algorithm](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm). # A classification algorithm takes input some data and use the data to # determine which class (category) this piece of data belongs to. from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets iris = datasets.load_iris() print('data shape is {}'.format(iris.data.shape)) print('class shape is {}'.format(iris.target.shape)) # For the simplicity of the exercise, we will only use the first 2 dimensions (sepal length and sepal width) of as features used to classify the flowers. X = iris.data[:, :2] # use first two version for simplicity y = iris.target # We create a scatter plot of the dataset below. The x and y axis represent the sepal length and sepal width of the dataset, and the color of the points represent the different classes of flowers. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets iris = datasets.load_iris() cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) K = 3 x = X[-1] fig, ax = plt.subplots(figsize=(4,4)) for i, iris_class in enumerate(['Iris Setosa', 'Iris Versicolour', 'Iris Virginica']): idx = y==i ax.scatter(X[idx,0], X[idx,1], c=cmap_bold.colors[i], edgecolor='k', s=20, label=iris_class); ax.set(xlabel='sepal length (cm)', ylabel='sepal width (cm)') ax.legend(); def pairwise_distance_matrix(X, Y): """Compute the pairwise distance between rows of X and rows of Y Arguments ---------- X: ndarray of size (N, D) Y: ndarray of size (M, D) Returns -------- distance_matrix: matrix of shape (N, M), each entry distance_matrix[i,j] is the distance between ith row of X and the jth row of Y (we use the dot product to compute the distance). """ N, D = X.shape M, _ = Y.shape distance_matrix = np.sqrt((np.square(X[:,np.newaxis]-Y).sum(axis=2))) # <-- EDIT THIS to compute the correct distance matrix. return distance_matrix def KNN(k, X, y, xtest): """K nearest neighbors k: number of nearest neighbors X: training input locations y: training labels x: test input """ N, D = X.shape num_classes = len(np.unique(y)) dist = pairwise_distance_matrix(X,xtest).ravel() # Next we make the predictions ypred = np.zeros(num_classes) classes = y[np.argsort(dist)][:k] # find the labels of the k nearest neighbors for c in np.unique(classes): ypred[c] = len(classes[classes == c]) # <-- EDIT THIS to compute the correct prediction return np.argmax(ypred) # We can also visualize the "decision boundary" of the KNN classifier, which is the region of a problem space # in which the output label of a classifier is ambiguous. This would help us develop an intuition of how KNN # behaves in practice. The code below plots the decision boundary. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 step = 0.1 xx, yy = np.meshgrid(np.arange(x_min, x_max, step), np.arange(y_min, y_max, step)) ypred = [] for data in np.array([xx.ravel(), yy.ravel()]).T: ypred.append(KNN(K, X, y, data.reshape(1,2))) fig, ax = plt.subplots(figsize=(4,4)) ax.pcolormesh(xx, yy, np.array(ypred).reshape(xx.shape), cmap=cmap_light) ax.scatter(X[:,0], X[:,1], c=y, cmap=cmap_bold, edgecolor='k', s=20);
2c8a11a731093485853d385c5a822de8e53d2f7d
juliandunne1234/pands-problems-2020gmit
/w4_collatz/collatz.py
383
4.34375
4
#This program takes a number and # completes a calculation based # on whether the number is even or odd. x = int(input("Please enter any number: ")) # Even number is divided by 2; # odd number is * 3 and then add 1. while x != 1: if x == 0: break elif x % 2 == 0: x = x / 2 else: x = (x * 3) + 1 print (int(x), end=' ')
a8ca9cc1a40397654c9791ec592176daa437bf14
fgokdata/python
/extra/def.py
131
3.84375
4
def multiply(mylist): mult = 1 for x in mylist: mult *= x return mult list1 = [3, 5, 6] print(multiply(list1))
0bbb8d620a8b0252054802c284035ed0004048be
qichaozhao/MIT-600v2
/lec4_problems/ps2/ps2_newton.py
2,819
4.03125
4
# 6.00 Problem Set 2 # # Successive Approximation # def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: # >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 # >>> x = -13 # >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 poly: tuple of numbers, length > 0 x: number returns: float """ if len(poly) < 1: print "Invalid poly, please enter at least length=1 poly." assert False result = 0 for idx, s in enumerate(poly): result = result + s * (x ** idx) return result def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns (0.0,). Example: # >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x^4 + 3x^3 + 17.5x^2 - 13.39 # >>> print compute_deriv(poly) # 4x^3 + 9x^2 + 35^x (0.0, 35.0, 9.0, 4.0) poly: tuple of numbers, length > 0 returns: tuple of numbers """ if len(poly) < 1: print "Invalid poly, please enter at least length=1 poly." assert False result = [] for idx, s in enumerate(poly): if idx == 0: term = 0.0 result.append(term) elif s == 0.0: pass else: term = idx * s result.append(term) result = tuple(result) return result def compute_root(poly, x_0, epsilon): """ Uses Newton's method to find and return a root of a polynomial function. Returns a tuple containing the root and the number of iterations required to get to the root. Example: # >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39 # >>> x_0 = 0.1 # >>> epsilon = .0001 # >>> print compute_root(poly, x_0, epsilon) (0.80679075379635201, 8.0) poly: tuple of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: tuple (float, int) """ # first we have to calculate f(x_0) f_x_0 = evaluate_poly(poly, x_0) f_x_n = f_x_0 x_n = 0.0 while abs(f_x_n) > epsilon: # get the next guess x_n = x_0 - f_x_0 / evaluate_poly(compute_deriv(poly), x_0) print x_n # evaluate next guess f_x_n = evaluate_poly(poly, x_n) print f_x_n # set our base for the next loop x_0 = x_n f_x_0 = evaluate_poly(poly, x_0) print "Root found: " + str(x_n) print "Evaluates to: " + str(f_x_n) poly = (-13.39, 0.0, 17.5, 3.0, 1.0) x_0 = 0.1 epsilon = 0.0001 compute_root(poly, x_0, epsilon)
be35f85f1b6859335374959ff46d1c850c46c17c
douradodev/Algoritmos-ADS
/ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio01/Fabio01_16_AREA-QUADRADO.py
162
3.671875
4
# Entrada lado= int(input("Digite a medida do lado do quadrado: ")) # Processamento area= lado**2 # Saída print("A área do quadrado é {} .".format(area))
e8fc585e04e258910256e881025b1ab08a060ccf
songponlekpetch/coin_change
/src/coin_change.py
1,134
3.625
4
class CoinChange: def __init__(self, num_denomination, money, denomination): self.num_denomination = num_denomination self.money = money self.denomination = self._cut_coin_not_compute(denomination) def _cut_coin_not_compute(self, denomination): money = self.money for coin in denomination: if money % coin == money: denomination.remove(coin) return denomination def get_smallest_coin(self): cal = self._make_change(self.money, self.denomination, []) results = [result for result in cal] return min(results, key=len) def _make_change(self, money, denomination, posible_coin): if sum(posible_coin) == money: yield posible_coin elif sum(posible_coin) > money: pass elif denomination == []: pass else: for posible in self._make_change(money, denomination[:], posible_coin + [denomination[0]]): yield posible for posible in self._make_change(money, denomination[1:], posible_coin): yield posible
7519c4f6bf50c475c2b597cf4862dabba703cb6c
JustinZeyeum/Python3_Learning
/userInput.py
340
4.40625
4
# A program asking user to input hours and rate per hour, # which display the pay on the screen hrs = input("Enter Hours:") # user input hours rate = input("Enter Rate:") # user input pay rate gross_pay = float(hrs) * float(rate) # program compute the gross pay calculation print("Pay:", gross_pay) # the gross pay is printed out as pay.
b47aed781388cd6c991c56dfb51d74877616f138
Ethan2957/p03.1
/square_diff.py
871
4.25
4
""" Problem: The function sq_diff takes a number, n, and then: * Adds all of the numbers from 1 to n and squares the answer. * Adds all of the square numbers from 1*1 to n*n It then subtracts the second number from the first and prints the answer. For example: sq_diff(4) = (1 + 2 + 3 + 4)^2 - (1*1 + 2*2 + 3*3 + 4*4) = 10^2 - (1 + 4 + 9 + 16) = 100 - 30 = 70 Tests: >>> sq_diff(4) 70 >>> sq_diff(12) 5434 >>> sq_diff(33) 302192 """ # Use this to test your solution. Don't edit it! import doctest def run_tests(): doctest.testmod(verbose=True) # Edit this code def sq_diff(n): addsq = 0 sqadd = 0 for i in range(1, n+1): sqadd = sqadd + i**2 addsq = addsq + i print(addsq**2 - sqadd)
5cb79f80399bd51c417b4c1d354585e58a6a71b8
anish531213/Interesting-Python-problems
/ads.py
350
3.53125
4
import os def rename_files(): file_list = os.listdir("/home/anish/Documents/prank") print(file_list) cur_dir = os.getcwd() os.chdir("/home/anish/Documents/prank") for file_name in file_list: os.rename(file_name, file_name.translate(None, "0123456789") os.chdir(cur_dir) rename_files()
346afe7c4658363984e716c793bbc87856d70108
focks98/TesteFundamentos
/question5.py
1,018
3.9375
4
def multMatrix(matrixA, matrixB): matrixResult = [] for i in range(len(matrixA)): vectorAux = [] for j in range(len(matrixB[0])): sumAux = 0 for k in range(len(matrixB)): sumAux += matrixA[i][k] * matrixB[k][j] vectorAux.append(sumAux) matrixResult.append(vectorAux) return matrixResult def main(): matrixA =[[3, 5, 1], [1, 7, 2]] matrixB =[[1, 3], [2, 4], [1, 1]] print("Questão 4: Implemente uma função que receba duas matrizes de inteiros e efetue sua multiplicação.\n") matrixResult = multMatrix(matrixA, matrixB) print("MatrixA: ") for row in matrixA: print(row) print("\nMatrixB: ") for row in matrixB: print(row) print("\nResult: ") for row in matrixResult: print(row) if __name__ == "__main__": main()
8fa909ac2202ce75995408d2150755753751a2a8
eduvallejo/gauss
/pythonFractal.py
2,292
4.125
4
# <-- in python, hashtags are used to tell the computer that a line is not worth reading # much like in social media ##to run this you code need, python 2.7 and numpy ## here we have a scripted program, the computer reads each line, line by line, and then #excecutes them ## this section imports libraries the program needs (code written by other people) import numpy as np from pylab import imshow, show ## below is a variable, a name that stores numbers or words thisISaVariable = 5 #here we set the variable "thisISaVariable" equal to 5 as an illustration #this variable sets how many iterations we perform max_iters = 20 ##below is a "function" called "mandel", it takes some variables "(x, y, max_iters)" to do some task ## this one checks if our value in each box is bigger than 4 def mandel(x, y, max_iters): c = complex(x, y) # here we are setting c equal to the coordinate of the box z = 0.0j # here we set our initial conditions for z = 0 for i in range(max_iters): #this is a "for" loop- it runs from i = 1 to i = max_iters z = z*z + c if (z.real*z.real + z.imag*z.imag) >= 4: #this tests if the magnitude is larger than 4 return i #this returns to the main program how many iterations it took before z became > 4 return max_iters ##this is the main "function" of the program calls "mandel" at each pixel, then builds it into an image def create_fractal(min_x, max_x, min_y, max_y, image, iters): height = image.shape[0] width = image.shape[1] pixel_size_x = (max_x - min_x) / width pixel_size_y = (max_y - min_y) / height for x in range(width): # this loops through all the points in a row real = min_x + x * pixel_size_x for y in range(height): # this loops through all the points in a column imag = min_y + y * pixel_size_y color = mandel(real, imag, iters) #this calls the mandel function on each point image[y, x] = color imshow(image) #this plots the image show() image = np.zeros((1024, 1536), dtype = np.uint8) #this generates the image the data will be saved to create_fractal(-2.0, 1.0, -1.0, 1.0, image, max_iters) #this calls the main function and gives it some values # imshow(image) #this plots the image # show()
d140691a8644f3f254f12dd252dd8370bf6dd83f
wfeng66/DB_Course
/HW/Assignment1/HW1_weicong_#4.py
418
4.09375
4
# Write a program that accepts a sentence and calculate the number of uppercase letters and lowercase letters. # Suppose the following input is supplied to the program. # Input: Hello World # Output: UPPERCASE: 1, LOWERCASE: 9 s = input("Please input a string: ") cUpp, cLow = 0,0 for i in s: if i.isupper(): cUpp += 1 elif i.islower(): cLow += 1 print("UPPERCASE: ", cUpp, ",\tLOWERCASE: ", cLow)
5aa0aaed074667ae52a38736a4c3507d01c07166
SoniaZhu/Lintcode
/linkedin/191. Maximum Product Subarray [M].py
643
3.53125
4
# pay attention to 0 class Solution: """ @param nums: An array of integers @return: An integer """ def maxProduct(self, nums): # write your code here if not nums: return 0 res = prevMax = prevMin = nums[0] for num in nums[1:]: if num > 0: localMax = max(num, prevMax * num) localMin = min(num, prevMin * num) else: localMax = max(num, prevMin * num) localMin = min(num, prevMax * num) res = max(res, localMax) prevMax, prevMin = localMax, localMin return res
11f434e211696e4d29a73b3ff21878b093faed1e
gamedevpy/python-projects-for-kids
/python-projects-for-kids/backpack1.py
6,503
3.796875
4
##------------------------------------------------------ ## ## By: Jessica Ingrassellino ## Publisher: Packt Publishing ## Pub. Date: April 14, 2016 ## Web ISBN-13: 978-1-78528-585-1 ## Print ISBN-13: 978-1-78217-506-3 ## ## Python Projects for Kids ## Chapter 7 - What's in your backpack? ## ## Did not follow the recipe in the book chapter- merely ## implemented myself based on the specifications outlined ## in the book chapter. ## ##------------------------------------------------------ # imported libraries go here import os import collections import random from colorama import Fore, Back, Style # global variables go here game_on = None players_list = [] player_count = 0 def reset_game(): global players_list global player_count players_list = [] player_count = 0 def add_personal_items(new_player_lookup): print("Now add your personal items") for j in range(4): item_num = j + 1 while True: item = raw_input('Enter name of item %d : ' % item_num) if len(item) > 0: if item in new_player_lookup['items_list'].keys(): print("You already have that item in your backpack, please try something else.") else: new_player_lookup['items_list'][item] = 'personal' break else: print("You need to enter something. Please try again.") def add_extra_items(new_player_lookup): print("Now add some exta items") for k in range(4): item_num = k + 1 while True: item = raw_input('Enter name of item %d : ' % item_num) if len(item) > 0: if item in new_player_lookup['items_list'].keys(): print("You already have that item in your backpack, please try something else.") else: new_player_lookup['items_list'][item] = 'extra' break else: print("You need to enter something. Please try again.") def initialize_game(): global player_count global players_list players_list = [] for i in range(player_count): os.system('cls' if os.name == 'nt' else 'clear') num = i + 1 player_name = raw_input('Enter name for player %d : ' % num) new_player_lookup = {} new_player_lookup['name'] = player_name new_player_lookup['score'] = 0 new_player_lookup['items_list'] = {} add_personal_items(new_player_lookup) add_extra_items(new_player_lookup) printGreen('Backpack is ready for %s' % player_name) players_list.append(new_player_lookup) def begin_challenge(): os.system('cls' if os.name == 'nt' else 'clear') print("Let the challenge begin!") play_on = True current_player_num = 0 other_player_num = 1 while (play_on): current_player = players_list[current_player_num] current_player_name = current_player['name'] other_player = players_list[other_player_num] other_player_name = other_player['name'] print("%s, it is your turn to guess what personal items are in %s's backpack " % (current_player_name, other_player_name)) other_player_item_dict = other_player['items_list'] display_backpack_items(other_player_item_dict) good_guess = False guess = raw_input("What's your guess? ") if len(guess) > 0: # if guess in other_player_item_dict.keys(): for key in other_player_item_dict: if key == guess: good_guess = True val = other_player_item_dict[key] if val == 'personal': printGreen("Correct!") current_player['score'] = current_player['score'] + 1 if current_player['score'] == 4: printGreen("%s has one the game!!!" % current_player_name) start_game() else: printYellow("That is not one of the personal items") del other_player_item_dict[guess] break else: print("You need to type something. Please try again.") next if not good_guess: printRed("Umm, that is not one of the items in the backpack") if current_player_num == 1: current_player_num = 0 other_player_num = 1 else: current_player_num = 1 other_player_num = 0 def display_backpack_items(items_dict): printBlue("\nHere are the contents of the backpack:") od = collections.OrderedDict(sorted(items_dict.items())) for item in od: print(item) # function to start game def start_game(): global game_on global player_count game_on = True reset_game() try: printBlue('Welcome. How many players?. (0 to quit) ') player_count = int(raw_input('')) if player_count > 1: initialize_game() begin_challenge() else: printRed('Need at least 2 players') except: printYellow('Encountered some exception. Will try again.') start_game() # function to stop game def stop_game(): global game_on game_one = False # function calls go here def play_again(): global game_on game_on = True try: play = raw_input('Play again? Yes or No. ') if play == 'Yes': start_game() else: game_On = 'false' except: printYellow('Encountered some exception. Will try again.') start_game() def printBlue(msg): print(Fore.BLUE + msg) print(Fore.RESET) def printRed(msg): print(Fore.RED + msg) print(Fore.RESET) def printGreen(msg): print(Fore.GREEN + msg) print(Fore.RESET) def printYellow(msg): print(Fore.YELLOW + msg) print(Fore.RESET) start_game()
d94bc89530529c5c0f5de33ddf7dd4afb73aa184
operation-lakshya/BackToPython
/MyOldCode-2008/JavaBat(now codingbat)/Logic/luckySum.py
349
3.75
4
a=int(raw_input("\nEnter the value containing A\t")) b=int(raw_input("\nEnter the value containing B\t")) c=int(raw_input("\nEnter the value containing C\t")) if (a==13): print "\nThe sum is: 0" elif (b==13): print "\nThe sum is:",a elif (c==13): print "\nThe sum is:",a+b else: print "\nThe sum is:",a+b+c raw_input("\nPress enter to finish")
b355bd5a519d65ea35d4e8d5e6a384424d79130a
lorischl-otter/Intro-Python-II
/src/player.py
1,237
3.75
4
# Write a class to hold player information, e.g. what room they are in # currently. class Player(): def __init__(self, name, location, items=[]): self.name = name self.location = location self.items = items # def try_direction(self, user_action): # attribute = user_action + '_to' # # see if the current room has an attribute # # we can use 'hasattr' (has attribute) # if hasattr(self.location, attribute): # # can use 'getattr' to move to room # self.location = getattr(self.location, attribute) # else: # print("Nothing to find here!") def pick_up_item(self, item): if len(self.items) <= 3: self.items.append(item) print(f"""\n\nNOW YOU HAVE THE {item}! You can drop it at any time by typing 'drop {item}'\n""") else: print("Sorry you'll have to drop something to pick this up.") def drop_item(self, item): if len(self.items) > 0: self.items.remove(item) print(f"YOU HAVE DROPPED THE {item}.") else: print("You don't have any items to drop!") # add for player to print what items they have # def print_items
d28a40a2bcc907182e7f131cbbed62f4cb871607
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/159_9.py
1,163
4.34375
4
Python | Sort all sublists in given list of strings Given a list of lists, the task is to sort each sublist in the given list of strings. **Example:** **Input:** lst = [['Machine', 'London', 'Canada', 'France'], ['Spain', 'Munich'], ['Australia', 'Mandi']] **Output:** flist = [['Canada', 'France', 'London', 'Machine'], ['Munich', 'Spain'], ['Australia', 'Mandi']] There are multiple ways to sort each list in alphabetical order. **Method #1 : Using map** __ __ __ __ __ __ __ # Python code to sort all sublists # in given list of strings # List initialization Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # Using map for sorting Output = list(map(sorted, Input)) # Printing output print(Output) --- __ __ **Output:** > [[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], > [‘Australia’, ‘Mandi’]]
1fc6f6a2eda50f4e8029d1146530762bebaafd38
sumanth8ch/Python
/heap.py
926
3.78125
4
""" Max heap is implemented. For min heap, reverse the heapify function.""" def heapify(ar,size,i): largest = i lc = 2*i+1 rc = 2*i+2 if lc<size and ar[lc]>ar[i]: largest = lc if rc<size and ar[rc]>ar[largest]: largest = rc if largest != i : ar[i],ar[largest] = ar[largest],ar[i] heapify(ar,size,largest) def insert(ar,value): size = len(ar) if size ==0: ar.append(value) else: ar.append(value) for i in range((size//2)-1,-1,-1): heapify(ar,size,i) def removeNode(ar, value): size = len(ar) i = 0 for i in range(size): if value == ar[i]: break ar[i],ar[size-1] = ar[size-1],ar[i] ar.remove(value) size = len(ar) for i in range((size//2)-1,-1,-1): heapify(ar,size,i) ar =[] insert(ar,5) insert(ar,8) insert(ar,3) print(ar) removeNode(ar,8) print(ar)
6c67b4004c296b7b85c553873f77fb90c0629b31
DragonWarrior15/tensorflow_and_mnist
/01_tensorflow_core.py
2,884
4.21875
4
# taken from # https://www.tensorflow.org/get_started/get_started # the central unit of data in tensorflow is called tensor # rank of a tensor is the no of dimensions in it # tensorflow graph is created using computational nodes import tensorflow as tf node1 = tf.constant(3.0, tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly print(node1, node2) # Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32) # note that the nodes need to be evaluated in order to produce the values stored in them as the outputs # To actually evaluate the nodes, we must run the computational graph within a session. # A session encapsulates the control and state of the TensorFlow runtime sess = tf.Session() print(sess.run([node1, node2])) # [3.0, 4.0] # can combine the nodes through operators node3 = tf.add(node1, node2) print("node3: ", node3) print("sess.run(node3): ",sess.run(node3)) # node3: Tensor("Add:0", shape=(), dtype=float32) # sess.run(node3): 7.0 # here we are completely dealing with constants.. # we can use variables/placeholders also a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) adder_node = a + b # + provides a shortcut for tf.add(a, b) # we can pass a dictionary of inputs to the above, of any dimensions print(sess.run(adder_node, {a: 3, b:4.5})) print(sess.run(adder_node, {a: [1,3], b: [2, 4]})) # 7.5 # [ 3. 7.] # we can make the operation slightly more complex add_and_triple = adder_node * 3. print(sess.run(add_and_triple, {a: 3, b:4.5})) print(sess.run(add_and_triple, {a: [3, 4], b:[4.5, 8]})) # 22.5 # [ 22.5 36. ] # all the above placeholders are constants and cannot be modified on the go # for the purposes of training a model # variables give us this freedom they are constructed with a type and initial value W = tf.Variable([.3], tf.float32) b = tf.Variable([-.3], tf.float32) x = tf.placeholder(tf.float32) linear_model = W * x + b # constants are initialized when tf.constant is called, avariables don't hold this property # they need to be initialized with a initializer call init = tf.global_variables_initializer() sess.run(init) print(sess.run(linear_model, {x:[1,2,3,4]})) # [ 0. 0.30000001 0.60000002 0.90000004] # after building the model, we would also like to be able to convey a loss function for the same y = tf.placeholder(tf.float32) squared_deltas = tf.square(linear_model - y) # reduce_sum reduces the vector sum of squares to a scalar equivalent loss = tf.reduce_sum(squared_deltas) print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]})) # 23.66 # we would like to be able to change the values of W and b in order # to tune our model. variables initialiized using tf.Variable() can be # modified through tf.assign fixW = tf.assign(W, [-1.]) fixb = tf.assign(b, [1.]) sess.run([fixW, fixb]) print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]})) # 0.0
6a0c4897a20935cad7962c7270cd25fbf0d244dc
prathamesh201999/python1
/Exception_handling.py
365
3.90625
4
a = int(input('Enter the first value')) b = int(input('Enter the second value')) try: print("Connection open") print(a/b) k = int(input('Enter the value')) print(k) except ZeroDivisionError as e: print("Zero is not a valid input",e) except ValueError as e: print("Give the integer as input",e) finally: print("Connection closed")
bb244880046b70001ab2353bf87b9708a29f3b72
Aniket-Bhagat/Computing_tools
/Files/Q15.py
407
3.9375
4
import sqlite3 conn = sqlite3.connect('company.db') x=raw_input('Employees having alphabets in there First Name\nAlphabet1 : ') y=raw_input('Alphabet2 : ') cursor = conn.execute('''SELECT F_NAME FROM EMPLOYEES WHERE F_NAME LIKE '%{}%' AND F_NAME LIKE '%{}%';'''.format(x,y)) # print "First name of all employees having both an \"b\" and \"c\" :" print '' for i in cursor: print i[0] conn.close()
0ff4eb91c18c217fccce8250b86f4125e9018d28
adam-holder/python-4-everybody-michigan
/Python Code/Courses 1-4/numbersInHaystack.py
750
3.9375
4
import re #I called the file "actualfile.txt" name = input("Enter file:") handle = open(name) numberSum = 0 #This code goes line by line and finds each number in the line using Regular Expressions #for each line it saves a list in findNumbers (skips the line if there are no results to find) for line in handle: line = line.rstrip() findNumbers = re.findall('[0-9]+', line) if len(findNumbers) == 0 : continue #This loop takes the pieces of each iteration of findNumbers and converts them to #integers. It then adds the integers to the running total, numberSum. for piece in findNumbers: num = int(piece) numberSum = numberSum + num #USED FOR TESTING #print (findNumbers, numberSum) print(numberSum)
168d811f616b28a9ad338c195785ed6760fe069c
adhishvishwakarma/DS-Algo
/Recursion/print_n.py
194
3.578125
4
def print_n_1(n): if n == 0: return print(n) print_n_1(n-1) print_n_1(10) def print_1_n(n): if n == 0: return print_1_n(n-1) print(n) print_1_n(10)
afd2b11dfaf18a6ec6bc4d2ea7d5f5979ec1d3ad
FedorPolyakov/python-algorithms
/Lesson3/les3_task5.py
1,326
4.15625
4
#В массиве найти максимальный отрицательный элемент. # Вывести на экран его значение и позицию в массиве. # Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». # Это два абсолютно разных значения. import random SIZE = 1_000 MIN_ITEM = -1_000 MAX_ITEM = 1_000 array = [random.randint(MIN_ITEM,MAX_ITEM) for _ in range(SIZE)] MIN_ID = -1 for i in range(len(array)): if array[i] < 0 and MIN_ID == -1: MIN_ID = i elif (array[i] < 0 and array[i] >= array[MIN_ID]): MIN_ID = i print(array) # если в исходном массиве вести позиции с нуля, то выводим следующее print(f'максимальный отрицательный элемент {array[MIN_ID]} номер последнего такого элемента {MIN_ID}') # если в исходном массиве вести позиции с единицы, то выводим следующее print(f'максимальный отрицательный элемент {array[MIN_ID]} номер последнего такого элемента {MIN_ID+1}')
1e6d2cba06eff3f5d66107b19f00db3d27beb431
inest-us/python
/tiny_python/list.py
460
3.859375
4
people = ['Paul', 'John', 'George'] people.append('Ringo') print('Yoko' in people) #False for i, name in enumerate(people, 1): print('{} - {}'.format(i, name)) print(people[0]) #Paul print(people[-1]) #len(people) - 1 => Ringgo print(people[1:2]) #['John'] print(people[:1]) #implicit start at 0 => ['Paul'] print(people[1:]) #['John', 'George', 'Ringo'] print(people[::2])#take every other item ['Paul', 'George'] print(people[::-1]) #reverse sequence
92d70c1468dfa691a3360ed9fa11783bc1dd36fd
stkobsar/MasterDegreeDS
/MasterDegreeDS/second_semester_2020/DataScience_programming/activity_1/activity_7.py
626
3.515625
4
import pandas as pd import re import ssl ssl._create_default_https_context = ssl._create_unverified_context json_data = "https://data.nasa.gov/resource/y77d-th95.json" df_nasa = pd.read_json(json_data) #Names with more than 5 characters in the dataframe # Make a regular expression # to accept string starting with vowel regex = '^[aeiouAEIOU][A-Za-z0-9_]*' names = df_nasa["name"] valid = [name for name in names if(re.search(regex, name) and len(name) > 5 )] #print(valid) #names ending with vowel regex2 = "^(?=.+)[^aeiou]*[aeiou]+$" valid_1 = [name for name in names if(re.search(regex2, name))] print(valid_1)
4b3b35a33069d5dedc9a538629fb3bd8092f8807
qwe321as/Python
/06_함수/Ex02_func.py
829
4.09375
4
#-*- coding:utf-8 ''' Created on 2020. 10. 30. @author: user ''' def add(a,b=99,c=100): return a+b+c print(add(1)) print(add(1,2)) print(add(1,2,3)) def func(*args): for i in args: print(i,'/',end=' ') print('-----') func(1,2) func(1,2,3,4,5) func() d = {'b':2,'a':1,'c':3} def func2(a,b,c): print(a,b,c) # func2(d) func2(*d) func2(**d) x=10 # 전역변수 def func3(): # x=20 global x y=99 # 지역변수 x = x+3 print('x:',x,'y:',y) func3() print('전역변수x:',x) # print('y:',y) print('======================') def func4(x): return x**2 print(func4(8)) # lambda 매개변수 : 반환값 a = lambda x : x**2 print(a(8)) b = lambda x,y : x+y print(b(10,20))
888bf34a36f7c72fd034733e5ed8606b4978b217
nerolin91/pythonPractice
/addValueAllCols.py
340
3.53125
4
def addValuesInAllCols (mat): colSum=[] sum=0 for i in range (len(mat)): for j in range (len(mat)): sum+=mat[j][i] colSum.append(sum) sum=0 return colSum mat = [ [1,2,3], [10,20,30], [100,200,300] ] list_sums_cols = addValuesInAllCols(mat) print (list_sums_cols)
4bca31d8426933bdce30a0a93e22cf0b9bcd0cbb
miguelesli/Prueba-Python
/ejercicio8d2upperylower.py
297
3.9375
4
### en una cadena se le puede cambiarel las letras de mayusculaa minuscula con Upper y lower mensaje7="HOLA MUNDO" mensaje7=mensaje7.lower() print(mensaje7) mensaje7=mensaje7.upper() print(mensaje7) mensaje2=input() mensaje2=mensaje2.lower() print("m2",mensaje2) input("::::::")
5790e7f5bebd1ec6b9bac89ee78951e0b7ab8457
tijus/machine-learning-projects
/Linear Regression/Main/sgd/sgd.py
2,049
3.578125
4
import numpy as np import matplotlib.pyplot as mp import random import os class SGD(): ''' Name: sgd type: class objective: This function is used to instantiate SGD class to train data using stochastic gradient descent ''' def __init__(self): ''' Constructor used for enabling SGD class instantiation ''' self.directory = os.path.dirname(__file__) def sgd(self,learning_rate,minibatch_size,num_epochs,L2_lambda,design_matrix,output_data): ''' sgd: this function is used to perform training using stochastic gradient descent Input: learning_rate: learning rate used while training data minibatch_size: batch size of the training dataset used in each iteration num_epochs: Number of epochs L2_lambda: Regularization Factor design_matrix: Design matrix of NXM dimension output_data: target vector Output: retuns the weight calculated using stochastic gradient descent ''' N, _ = design_matrix.shape weights = np.zeros([1, len(design_matrix[0])]) lastError=100 for epoch in range(num_epochs): for i in range(N / minibatch_size): lower_bound = i * minibatch_size upper_bound = min((i+1)*minibatch_size, N) Phi = design_matrix[lower_bound : upper_bound, :] t = output_data[lower_bound : upper_bound] E_D = np.matmul( (np.matmul(Phi, weights.T)-t).T, Phi ) E = (E_D + L2_lambda * weights) / minibatch_size weights = weights - learning_rate * E # stopping condition if (np.linalg.norm(E) < lastError): lastError = np.linalg.norm(E) else: return weights[len(weights) - 1] return weights[len(weights)-1] sgdObject = SGD()
49f532079dff2a55d5e2d07851049f2228de1710
DiaAzul/healthdes
/healthdes/Check.py
6,459
3.796875
4
""" HealthDES - A python library to support discrete event simulation in health and social care """ from typing import ( TYPE_CHECKING, ClassVar, ContextManager, Generic, MutableSequence, Optional, Type, TypeVar, Union, ) class Check: """ Class containing functions to check whether values meet certain conditions In Data Science analysis it is more important to ensure that data is correct than code is fast. Therefore, a greater degree of parameter checking may be appropriate to ensure that parameters meet defined criteria. This Class contains common checks that are applied to base types (int, float, string) to confirm data integrity. """ @staticmethod def is_equal_to_zero(x: Union[int, float]) -> None: """Check that variable is equal to zero. Args: x (int or float): The variable to be tested. Raises: ValueError: The variable is not an int or float. ValueError: The variable is not equal to zero. """ if not(type(x) is int or type(x) is float): raise ValueError('value must be a number') if not (x == 0): raise ValueError('value must be equal to zero') @staticmethod def is_not_equal_to_zero(x: Union[int, float]) -> None: """Check that variable is not equal to zero. Args: x (int or float): The variable to be tested. Raises: ValueError: The variable is not an int or float. ValueError: The variable is equal to zero. """ if not(type(x) is int or type(x) is float): raise ValueError('value must be a number') if not (x != 0): raise ValueError('value must not equal zero') @staticmethod def is_greater_than_zero(x: Union[int, float]) -> None: """Check that variable is greater than zero. Args: x (int or float): The variable to be tested. Raises: ValueError: The variable is not an int or float. ValueError: The variable is not greater than zero. """ if not(type(x) is int or type(x) is float): raise ValueError('value must be a number') if not (x > 0): raise ValueError('value must be greater than zero') @staticmethod def is_greater_than_or_equal_to_zero(x: Union[int, float]) -> None: """Check that variable is greater than or equal to zero. Args: x (int or float): The variable to be tested. Raises: ValueError: The variable is not an int or float. ValueError: The variable is not greater than or equal to zero. """ if not(type(x) is int or type(x) is float): raise ValueError('value must be a number') if not (x >= 0): raise ValueError('value must be greater than, or equal to, zero') @staticmethod def is_less_than_zero(x: Union[int, float]) -> None: """Check that variable is less than zero. Args: x (int or float): The variable to be tested. Raises: ValueError: The variable is not an int or float. ValueError: The variable is not less than zero. """ if not(type(x) is int or type(x) is float): raise ValueError('value must be a number') if not (x < 0): raise ValueError('value must be less than zero') @staticmethod def is_less_than_or_equal_to_zero(x: Union[int, float]) -> None: """Check that variable is less than or equal to zero. Args: x (int or float): The variable to be tested. Raises: ValueError: The variable is not an int or float. ValueError: The variable is not less than or equal to zero. """ if not(type(x) is int or type(x) is float): raise ValueError('value must be a number') if not (x <= 0): raise ValueError('value must be less than, or equal to, zero') class CheckList: """ Class containing functions to check whether lists have certain characteristics """ @staticmethod def is_a_list(li): """Check whether the variable is a list Args: li (list): The variable to be tested. Raises: ValueError: The variable is not a list """ if not isinstance(li, list): raise ValueError('This must be a list') @staticmethod def fail_if_list_empty(li): """Check with a list is empty Args: li (list): The variable to be tested Raises: ValueError: The list is empty """ if not li: raise ValueError('list must have at least one entry') @staticmethod def fail_if_not_in_list(test_item, li): """Check with an item is in the list Args: test_item (obj): Item to be checked against the list li (list): List potentially containing the item Raises: ValueError: The item is not in the list """ in_list = False for item in li: if item == test_item: in_list = True break if not in_list: raise ValueError('Item not in list') @staticmethod def is_a_dictionary(di): """Check whether item is a dictionary Args: di (dict): The variable to be tested Raises: ValueError: The item is not a dictionary """ if not isinstance(di, dict): raise ValueError('This must be a dictionary') @staticmethod def fail_if_dict_empty(li): """Check whether a dictionary is empty Args: li (dict): The dictionary to be tested Raises: ValueError: The dictionary is not empty """ if not li: raise ValueError('list must have at least one entry') @staticmethod def fail_if_this_key_in_the_dictionary(test_key, di): """Fail if the given key is in the dictionary Args: test_key (obj): Key to test di (dict): Dictionary that we want to test for presence of key Raises: ValueError: The key is in the dictionary """ if test_key in di: raise ValueError('Cannot have duplicate keys in dictionary')