blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
1d79b77b523389ebee91680fb2b561c966b22016
Euler-Project-Colab/Project-Euler
/problem10_neel.py
956
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 29 17:12:56 2020 @author: neel """ """ Program to calculate sum of all Prime numbers less than 20000000 Note: Python libraries are superfast, always implement them wherever possible """ import sympy import time import numpy as np t=time.time() prime_list=list(sympy.primerange(1,2000000)) print (sum(prime_list)) print(time.time()-t) def chk_prime(num): if num == 1: return False i = 2 if not((num+1)%6==0 or (num-1)%6==0): return False # This will loop from 2 to sqrt(x) while i*i <= num: if num % i == 0: return False i += 1 return True t=time.time() sum=5 for i in range(1, 2000000): if(chk_prime(i)): sum+=i print(sum) print(time.time()-t) t=time.time() sum=0 for i in range(1, 2000000): if(sympy.isprime(i)): sum+=i print(sum) print(time.time()-t)
2a41c7e7daa757da63509df059f027e044574cd2
Euler-Project-Colab/Project-Euler
/problem4_tanay.py
328
3.890625
4
greatest = 0 for num1 in range(100,1000): #finds product of all 3 digits numbers for num2 in range(100,1000): product = num1*num2 if str(product) == str(product)[::-1] and product>greatest: #checks if product is palindrome greatest = product print(greatest) #ans 906609
a2b419084bafcc112f88f99a6d3bd327db5e983d
Python-lab-cycle/jeri
/string,py.py
130
4.09375
4
str1= input("Enter the string:") print("String after swapping first and last character:",(str1[-1:] + str1[1:-1] + str1[:1]))
1e771bd8f9fc6ca26a9575a892f0a3c9ba5864c0
Python-lab-cycle/jeri
/largest1.py
167
3.921875
4
a=int(input("Enter the first number")) b=int(input("Enter the second number")) c=int(input("Enter the third number")) big=max(a,b,c) print("Largest number=",big)
cf7baf68cf0e24c45dd48a47ea1b0e2b114304a5
amitwats/toy-robot-on-table
/table.py
1,138
4.03125
4
import utility class Table: """The class that represents the table on which the Robot is kept. """ def __init__(self,count_x=5,count_y=5): """The constructor Arguments: count_x {int} -- The number of squares on the table on the x-axis. (default=5) count_y {int} -- The number of squares on the table on the y-axis. (default=5) """ self.count_x=utility.validateInteger(count_x) self.count_y=utility.validateInteger(count_y) #x,y are zero indexed positions def isPositionValid(self,x,y): """Checks is the position x (0-indexed) and y (0-indexed) are valid on the table. Arguments: x {int} -- The 0-indexed position in x-direction. y {int} -- The 0-indexed position in y-direction. Returns: boolean -- If the 0-indexed position of x and y are on the table returns True else False """ x=utility.validateInteger(int(x)) y=utility.validateInteger(int(y)) return 0<=x<=self.count_x-1 and 0<=y<=self.count_y-1
421758619c755c68a9eab48db5f268875f2d748d
amitwats/toy-robot-on-table
/robot.py
3,885
4.3125
4
from direction import Directions import utility class Robot: """The class represents the Robot. The main parameters are direction - This is the direction in which the Robot is facing and can move in if move command is called. x_pos - The current x position(0-Indexed) of the Robot on the table. y_pos - The current y position(0-Indexed) of the Robot on the table. Raises: ValueError: If invalid values are passed as parameters this exception is raised. """ def __init__(self,tableRef,init_x=0,init_y=0,direction=Directions.NORTH): """The constructor of the Robot Arguments: tableRef {Table} -- The Table object on which the robot is kept. Keyword Arguments: init_x {int} -- The initial x position (0-indexed) of the Robot (default: {0}) init_y {int} -- The initial y position (0-indexed) of the Robot (default: {0}) direction {int} -- Valid values for this are Directions.NORTH,Directions.SOUTH,Directions.EAST,Directions.WEST (default: {Directions.NORTH}) Raises: ValueError: in case the parameters passed are invalid or the position of the Robot is outside the table. """ self._direction=Directions.NORTH self.direction=direction #validates the value self._table=tableRef self._x_pos=utility.validateInteger(init_x) self._y_pos=utility.validateInteger(init_y) #to-do Add table check if 0>=init_x>self._table.count_x-1 or 0>=init_y>self._table.count_y-1 : raise ValueError(f"The robot is being placed out of the table. Cannot place the Robot") @property def table(self): return self._table @property def x_pos(self): return self._x_pos @property def y_pos(self): return self._y_pos @property def direction(self): return self._direction # # to-do Write test cases for value <0 and >3 # # to-do write test cases for values non numerical @x_pos.setter def x_pos(self, x): if self.table.isPositionValid(x,self.y_pos): self._x_pos = x # # to-do Write test cases for value <0 and >3 # # to-do write test cases for values non numerical @y_pos.setter def y_pos(self, y): if self.table.isPositionValid(self.x_pos,y): self._y_pos = y # to-do Write test cases for value <0 and >3 # to-do write test cases for values non numerical @direction.setter def direction(self, value): value=utility.validateInteger(int(value)) self._direction = value%4 def turn(self,value): """Makes the Robot turn left or Right Arguments: value {int} -- Valid values are Directions.LEFT or Directions.RIGHT Raises: ValueError: In case the value is not Directions.LEFT or Directions.RIGHT """ #validate parameter values if value not in Directions.validTurns(): raise ValueError(f"The values can be only from the Directions class. valid values are Directions.RIGHT and Directions.LEFT") directionsArr=Directions.validDirections() index=directionsArr.index(self.direction) self.direction=index+value def move(self): """Moves the Robot one step ahead in the direction it is facing. If the step will make the Robot fall off the table the Robot remains in their position. """ if self.direction==Directions.NORTH: self.y_pos=self.y_pos+1 if self.direction==Directions.EAST: self.x_pos=self.x_pos+1 if self.direction==Directions.SOUTH: self.y_pos=self.y_pos-1 if self.direction==Directions.WEST: self.x_pos=self.x_pos-1
7eb00d5cde0db196e7354ffe2480d22c3dcbf1e2
kailee-madden/Data-Science
/kmadden5-hw1-programming/kmadden5-hw1-2-3.py
973
3.546875
4
#!/usr/bin/env python3 import matplotlib.pyplot as plt import pandas from pandas import Series, DataFrame import numpy as np D = pandas.read_csv("Dataset-film-data.csv") A = [] C = [] R = [] for index, row in D.iterrows(): if row["GENRE"] == "ROMANCE": R.append(row["AVGRATING_WEBSITE_1"]) elif row["GENRE"] == "ACTION": A.append(row["AVGRATING_WEBSITE_1"]) elif row["GENRE"] == "COMEDY": C.append(row["AVGRATING_WEBSITE_1"]) def average(lst): return sum(lst) / len(lst) A_mean = average(A) C_mean = average(C) R_mean = average(R) Genre = ["Action", "Comedy", "Romance"] Mean = [A_mean, C_mean, R_mean] def bar(x, y): fig, ax = plt.subplots() index = np.arange(3) bar_width = 0.4 ax.bar(index, y, bar_width, align = "center") ax.set_xticks(index + bar_width / 2) ax.set_xticklabels(x) ax.set_xlabel("Genres") ax.set_ylabel("Means") plt.savefig("barchart") barchart = bar(Genre, Mean)
83c51994945f1fc21ad3cd97c257143b23604909
LukaszRams/WorkTimer
/applications/database/tables.py
1,559
4.15625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file will store the data for the database queries that will be called to create the database """ # Table of how many hours an employee should work per month class Monthly_working_time: table_name = "MONTHLY_WORKING_TIME" data = { "id": ("integer", "PRIMARY KEY"), "year": ("integer", "NOT NULL"), "month": ("text", "NOT NULL"), "hours": ("integer", "NOT NULL") } # A table that will contain data on the time worked by the employee during the month class Working_time: table_name = "WORKING_TIME" data = { "id": ("integer", "PRIMARY KEY"), "user": ("text", "NOT NULL"), "year": ("YEAR", "NOT NULL"), "month": ("text", "NOT NULL"), "total_hours": ("integer", "NOT NULL"), # number of hours worked by the employee "base_hours": ("integer", "NOT NULL"), # the number of hours the employee was to work "overtime_hours": ("integer", "NOT NULL"), # number of overtime hours } # Detailed data from employees' work, the amount of data grows very quickly so it needs to be cleaned class Detailed_working_time: table_name = "DETAILED_WORKING_TIME" data = { "id": ("integer", "PRIMARY KEY"), "user": ("text", "NOT NULL"), "date": ("DATE", "NOT NULL"), # detailed_working_time "start_at": ("TIME", "NOT NULL"), # start time "end_at": ("TIME", "NOT NULL"), # end time } tables = [Monthly_working_time, Working_time, Detailed_working_time]
3c856ac8d28b260a2906f6f1404ac0fe91f5cf0a
saiduc/Calculating-Pi-With-Collisions
/picalc.py
3,799
3.984375
4
from fractions import Fraction import argparse class block: def __init__(self, position, mass): self.x = position # block position self.m = mass # block mass self.v = Fraction(0, 1) # block velocity def reflect(self): """ reverses velocity for elastic collision with wall of infinite mass """ self.v = -1*self.v def collide(leftBlock, rightBlock): """ collides the two blocks and updates their velocities uses formulae derived from conservation of energy and momentum expressions """ v_A = leftBlock.v v_B = rightBlock.v m_A = leftBlock.m m_B = rightBlock.m v_A_new = (2*v_B*m_B + m_A*v_A - m_B*v_A)/(m_A + m_B) v_B_new = (2*v_A*m_A + m_B*v_B - m_A*v_B)/(m_A + m_B) leftBlock.v = v_A_new rightBlock.v = v_B_new return def update(leftBlock, rightBlock): """ updates position of blocks by adding velocity multiplied by timeToCollide this is necessary instead of moving by fixed time quanta, since otherwise there is a possibility of blocks passing over each other """ t = timeToCollide(leftBlock, rightBlock) leftBlock.x = leftBlock.x + t*leftBlock.v rightBlock.x = rightBlock.x + t*rightBlock.v return def timeToCollide(leftBlock, rightBlock): """ calculates time before the next collision between the two blocks """ # both blocks moving right but rightBlock is faster, so no future collision if rightBlock.v >= leftBlock.v >= 0: return float("inf") # blocks moving towards each other elif leftBlock.v >= 0 >= rightBlock.v: return Fraction(rightBlock.x - leftBlock.x, leftBlock.v - rightBlock.v) # blocks moving left but leftBlock is faster so will collide with wall first elif (rightBlock.v >= 0 and leftBlock.v < 0) or (leftBlock.v <= rightBlock.v < 0): return Fraction(-leftBlock.x, leftBlock.v) # leftBlock currently at wall elif leftBlock.x == 0: # rightBlock too fast for leftBlock to catch up so no future collisions if rightBlock.v >= abs(leftBlock.v): return float("inf") # rightBlock moving left or slow enough for leftBlock to catch up else: return Fraction(rightBlock.x, abs(leftBlock.v)-rightBlock.v) # blocks moving left but rightBlock faster so will collide with leftBlock else: return min(Fraction(-leftBlock.x, leftBlock.v), Fraction(rightBlock.x-leftBlock.x, leftBlock.v-rightBlock.v)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "precision", help="input number of decimal places required") args = parser.parse_args() n = int(args.precision) # define initial values for blockA and blockB # mass of blockB is a power of 100. Number of digits of pi is power+1 blockA = block(Fraction(1, 1), 1) blockB = block(Fraction(2, 1), 100**n) blockB.v = Fraction(-1, 1) counter = 0 while timeToCollide(blockA, blockB) != float("inf"): update(blockA, blockB) if blockA.x == blockB.x != 0: collide(blockA, blockB) counter += 1 elif blockA.x == 0 != blockB.x: blockA.reflect() counter += 1 elif blockA.x == blockB.x == 0: blockA.reflect() blockB.reflect() counter += 2 else: pass # speeds up program by limiting float length blockA.x = blockA.x.limit_denominator(2**32) blockB.x = blockB.x.limit_denominator(2**32) blockA.v = blockA.v.limit_denominator(2**32) blockB.v = blockB.v.limit_denominator(2**32) pi = str(counter)[:1]+'.'+str(counter)[1:] print('pi is', pi)
61b8af60be81eabf43772e6f24e77b5422e5fbb8
Eladfundo/m101p
/01_Introduction/fruits.py
135
4.0625
4
fruits = ['apple', 'pear', 'banana'] new_fruits = [] for item in fruits: print item new_fruits.append(item) print new_fruits
138e4d255a76da4d6ddceb6936b1bf58342348c0
kelsiehargita/Python-Challenge
/PyBank/main.py
2,105
3.5
4
import os import csv csvpath = os.path.join('.', 'Resources', 'budget_data.csv') with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) csv_header = next(csvreader) number_of_months = 0 net_total = 0 previous_profit = 0 total_profit_change = 0 greatest_profit_increase = 0 greatest_profit_decrease = 0 GPI_month = "" GPD_month = "" print("Financial Analysis") print("----------------------------") for row in csvreader: number_of_months += 1 net_total += int(row[1]) total_profit_change += int(row[1])-previous_profit profit_difference = int(row[1])- previous_profit previous_profit = int(row[1]) if profit_difference > greatest_profit_increase: GPI_month = row[0] greatest_profit_increase = profit_difference if profit_difference < greatest_profit_decrease: GPD_month = row[0] greatest_profit_decrease = profit_difference print("Total Months: " + str(number_of_months)) print("Total: " + str(net_total)) average_profit_change = total_profit_change/number_of_months print("Average Change: " + str(average_profit_change)) print("Greatest Increase in Profits: " + GPI_month + " " + str(greatest_profit_increase)) print("Greatest Decrease in Profits: " + GPD_month + " " + str(greatest_profit_decrease)) output_path = os.path.join(".", "Analysis", "PyBankReport.txt") with open(output_path, 'w') as txtfile: txtfile.write("Financial Analysis"+"\n") txtfile.write("----------------------------"+"\n") txtfile.write("Total Months: " + str(number_of_months)+"\n") txtfile.write("Total: " + str(net_total)+"\n") txtfile.write("Average Change: " + str(average_profit_change)+"\n") txtfile.write("Greatest Increase in Profits: " + GPI_month + " " + str(greatest_profit_increase)+"\n") txtfile.write("Greatest Decrease in Profits: " + GPD_month + " " + str(greatest_profit_decrease)+"\n") txtfile.close()
9e1f9ad4df8273b5424331171a482210ac26f073
NamLa7499/convert_pencil
/pencil_convert.py
571
3.578125
4
import cv2 # get the image location img_location = 'D:\\' filename = 'test.jpg' #read in the image img = cv2.imread(img_location+filename) #convert gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #invert the image inverted_gray_image = 255 - gray_image #blur the image by gauss blurred_img = cv2.GaussianBlur(inverted_gray_image,(21,21),0) inverted_blurred_img = 255- blurred_img pencil_sketch = cv2.divide(gray_image,inverted_blurred_img,scale=256.0) #show image cv2.imshow('Orgiginal Image', img) cv2.imshow('New Image',pencil_sketch) cv2.waitKey(0)
1fb91f30505cd5788789aece21d26f6dded67255
snehadujaniya/SIH-2020
/Scripts/future predict.py
1,122
3.640625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt #2. Import the datetime library and use 'datetime' function: from datetime import datetime # Now, we will load the data set and look at some initial rows and data types of the columns: plt.figure(figsize=(20,10)) # The data contains a particular month and number of passengers travelling in that month. In order to read the data as a time series, we have to pass special arguments to the read_csv command: dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m') data = pd.read_csv('ML Future.csv', parse_dates=['Month'], index_col='Month',date_parser=dateparse) ts = data['Jobs'] ts_log = np.log(ts) from statsmodels.tsa.arima_model import ARIMA model = ARIMA(ts_log, order=(2, 1, 2)) results_ARIMA = model.fit(disp=-1) results_ARIMA.plot_predict(1,216).savefig("mlfuture") x=results_ARIMA.forecast(steps=65) y=np.exp(x[0]) arrcount=[] arrcount.append(int(sum(y[5:17]))) arrcount.append(int(sum(y[17:29]))) arrcount.append(int(sum(y[29:41]))) arrcount.append(int(sum(y[41:53]))) arrcount.append(int(sum(y[53:65]))) print(arrcount) plt.show()
4c7a2abd22c9836f841454dbf15f74ff1b8686f5
johnflavin/hanging
/hanging.py
4,200
3.734375
4
import sys import csv from string import ascii_uppercase as upperc target = sys.argv[1] target = target.upper() wordlen = len(target) char_per_line = 100 def print_words(word_list,word_length): num_words = len(word_list) #words/line = (chars/line) / (chars/word including a space) words_per_line = int(char_per_line/(word_length+1)) #remainder: number extra words = (number words) mod (words/line) remainder = num_words % words_per_line #lines: number full char_per_line-character lines = (number words) / (words/line) lines = int( num_words/words_per_line ) for line in range(lines): print(' '.join( word_list[words_per_line*line : words_per_line*(line +1)] )) if remainder > 0: print(' '.join( word_list[-remainder:] )) if '.' in target: wronglets = sys.argv[2:] wronglets = [l.upper() for l in wronglets] if wordlen>8: sys.exit('Target word too long') letters = [char for char in target if char != '.'] indices = [target.index(char) for char in letters] num_letters = len(letters) try: last_vowel_pos = max([indices[i] for i in range(num_letters) if letters[i] in 'AEIOU']) except ValueError: last_vowel_pos = -1 #Read in the string of words from the dictionary file dictfile = 'dict{0}.csv'.format(wordlen) try: f = open(dictfile,'r') except: sys.exit('could not open dictionary file') reader = csv.reader(f) #List of all words in the dictionary that are the same length as target fulldict = [] for line in reader: fulldict += line f.close() #Keep only those words with the target letters in proper spaces filterdict = [word for word in fulldict if all( [letters[i]==word[indices[i]] for i in range(num_letters) ] )] #Keep only those words with none of the already guessed wrong letters filterdict = [word for word in filterdict if all([lett not in word for lett in wronglets])] #Keep only those words with correct letters ONLY in correct spaces, nowhere else filterdict = [word for word in filterdict if all([target.count(lett)==word.count(lett) for lett in set(letters)])] #Keep only words with no vowels beyond last known vowel (which is always given) filterdict = [word for word in filterdict if all([lett not in 'AEIOU' for lett in word[last_vowel_pos+1:] ])] # filterdict now holds only valid words. We must find the most common letter. # We create an array to hold a count of how many words contain each letter. if len(filterdict) == 0: sys.exit("You've eliminated all valid words!") lettersbyword = [0]*26 for word in filterdict: for letter in set(word): if letter not in letters: lettersbyword[upperc.index(letter)]+=1 # The max value of this array is the frequency of most common letter. maxletternum = max(lettersbyword) # There might be more than one letter with this frequency, so list them all. maxletterlist = [upperc[i] for i in range(26) if lettersbyword[i] == maxletternum] if len(maxletterlist)>1: print('Letters in most words: '+' '.join(maxletterlist)) else: print('Letter in most words: '+maxletterlist[0]) # Print all the valid states (if there are fewer than 200) if len(filterdict)>200: sys.exit('{0} words fit'.format(num_words)) else: print_words(filterdict,wordlen) else: if wordlen != 12: sys.exit("Put in 12 letters to get all words.") raw_wants = sys.argv[2:] wants = [lett.upper() for lett in set(raw_wants)] for i in range(5): x = 8-i #Read in the string of words from the dictionary file dictfile = 'dict{0}.csv'.format(x) try: f = open(dictfile,'r') except: sys.exit('could not open dictionary file') reader = csv.reader(f) #List of all words in the dictionary that are the same length as target fulldict = [] for line in reader: fulldict += line f.close() #Filter out words that have any non-target letters filterdict = [word for word in fulldict if all( [word.count(lett)<=target.count(lett) for lett in set(word)] )] #Filter out words that don't have all the letters we want filterdict = [word for word in filterdict if all( [lett in word for lett in wants] )] # Printing the words print('{0} letter words:'.format(x)) if len(filterdict) == 0: print('----') else: print_words(filterdict,x)
14ec0c44b73f099627cc5b6c488fe694dd32ceda
Silentsoul04/FTSP_2020
/Summer Training ML & DL/Classification_KNN.py
2,213
3.84375
4
# Import the Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # To Import csv file dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\caesarian.csv') dataset.head() ------------------- Age DeliveryNumber DeliveryTime BloodPressure HeartProblem Caesarian 0 22 1 0 2 0 0 1 26 2 0 1 0 1 2 26 2 1 1 0 0 3 28 1 0 2 0 0 4 22 2 0 1 0 1 dataset.isnull().any(axis=0) # There is No Nan Valeus into dataset. features = dataset.iloc[:,:-1].values labels = dataset.iloc[:,-1].values from sklearn.model_selection import train_test_split features_train , features_test , labels_train , labels_test =\ train_test_split(features,labels,test_size=0.2,random_state=41) # Now we do the Feature Scaling here with features_train. from sklearn.preprocessing import StandardScaler sc = StandardScaler() features_train = sc.fit_transform(features_train) # Now we have already calculated the mean & SD then just do the transform only. features_test = sc.transform(features_test) # Fitting Logistics Regression to the Train set data. from sklearn.neighbors import KNeighborsClassifier # We are not mentioning k & p values then by default it will be taking the k = 5 , p = 2 # p = 2 means Equaliden distance , p = 1 menas Manhattan distance. classifier = KNeighborsClassifier(n_neighbors = 5 , p = 2) classifier.fit(features_train,labels_train) # Calculating the Probability. probability = classifier.predict_proba(features_test) print(probability) # Predicting the class labesl like (0 or 1) labels_pred = classifier.predict(features_test) # Making Dataframe & doing the Comparison. df = pd.DataFrame({'Actual':labels_test , 'Predicated':labels_pred}) df.head() # To make the Confusion Matrix. from sklearn.metrics import confusion_matrix cm = confusion_matrix(labels_test , labels_pred) print(cm) ---------------- [[7 2] [2 5]] print(12/16) # 0.75
3c0a8d993d3c7ac14489e252b3a2cbaa5f508b93
Silentsoul04/FTSP_2020
/Extra Lockdown Tasks/Copy()_Method_Python.py
393
4.0625
4
''' Copy() Method in Python :- --------------------------- ''' l1 = [10,20,30,40,50] l2 = l1 print(l1) print(l2) l1.append(99) print(l1) print(l2) l2.remove(20) print(l1) print(l2) # copy() method l1 = [10,20,30,40] l2 = l1.copy() print(l1) --- > Original list1 print(l2) ---> Dulpicate list2 -->shallow l2.append('Python') print(l2) print(l1) l2.remove(30) print(l2) print(l1)
9791c4c5ee8e950342e21d73e372315203fe9bac
Silentsoul04/FTSP_2020
/Hacker Rank/Day6_Strings.py
911
3.5
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 07:43:01 2020 @author: Rajesh """ s = 'RAJESH' list1 = s.split() print(list1) ##################### list1=[] s = 'RAJESH' for i in s: list1.append(i) print(list1) ########################## s = 'RAJESH KUMAR SHARMA' cnt = s.count('R') print(cnt) ######################### s = 'RAJESH KUMAR SHARMA' low = s.lower() print(low) ##################### s = 'rajesh sharma from forsk' upp = s.upper() print(upp) ###################### s='RAJESH' l=[] j=0 k=2 for i in range(int(len(s)/2)): a=s[j:k] l.append(a) j+=2 k+=2 print(l) ########################### s='rAJEsH shArmA' capital_letter = s.capitalize() print(capital_letter) ############################ s='rAJEsH shArmA' s.casefold() ##################################### s='ABCDEFGHIJKLMNOPQRSTUVWXYZ' n = int(input()) j=0 k=n for i in range(int(len(s)/2)): a=s[j:k] j+=n k+=n print(l)
834fd97da46558ba454a7f7b8d7756f67366b080
Silentsoul04/FTSP_2020
/Durga OOPs/Operator_Overloading1_OOPs.py
6,817
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 26 18:17:57 2020 @author: Rajesh """ Operator Overloading :- -------------------- class Book: def __init__(self,pages): self.pages = pages def __add__(self,other): return self.pages + other.pages b1 = Book(100) b2 = Book(200) b3 = Book(700) print(b1+b2) # 300 print(b1+b3) # 800 print(b2+b3) # 900 NOTE :- The return type of the __add__() magic method will be integer type. --------------------------------------------------------------------------------------------------------------- Ex :- class Book: def __init__(self,pages): self.pages = pages def __str__(self): return 'Forsk' b1 = Book(100) print(b1) # Forsk b2 = Book(200) print(b2) # Forsk NOTE :- Actually, we need to print the no. of pages in a book not a printing simply any return string name. class Book: def __init__(self,pages): self.pages = pages def __str__(self): # magic method for single object like b1 printing. return 'The No. of Pages :' + str(self.pages) b1 = Book(100) print(b1) # The No. of Pages :100 NOTE :- We are using __str__() method to print a single values like print(b1). then we should this method and return the string values and always we need to type cast of these values. ----------------------------------------------------------------------------------------------------------------- class Book: def __init__(self,pages): self.pages = pages def __str__(self): # magic method for single object like b1 printing. return 'The No. of Pages :' + str(self.pages) def __add__(self,other): return self.pages + other.pages b1 = Book(100) b2 = Book(200) b3 = Book(300) print(b1) # The No. of Pages :100 print(b1+b2) # 300 print(b1+b2+b3) # unsupported operand type(s) for +: 'int' and 'Book'. -------------------------------------------------------------------------------------------------- Question :- How to print the values of like print(b1+b2+b3) by using operator overloading in python. class Book: def __init__(self,pages): self.pages = pages def __str__(self): # magic method for single object like b1 printing. return 'The No. of Pages :' + str(self.pages) def __add__(self,other): total = self.pages + other.pages # total no. of pages of b1+b2 b = Book(total) # creating one more object like b return b b1 = Book(100) b2 = Book(200) b3 = Book(300) b4 = Book(700) b5 = Book(1000) print(b1) # The No. of Pages :100 print(b1+b2) # The No. of Pages :300 print(b1+b2+b3) # The No. of Pages :600 print(b1+b2+b3+b4) # The No. of Pages :1300 print(b1+b2+b3+b4+b5) # The No. of Pages :2300 -------------------------------------------------------------------------------------------------------------- NOTE :- Whenever we are calling + operator then __add__() method will be called. + operator return type will become __add__() method return type. NOTE :- Whenever we are printing book object reference / object then __str__() method will be called. If we are not providing this method then default implemention will be executed. class Book: def __init__(self,pages): self.pages = pages def __str__(self): # magic method for single object like b1 printing. return 'The No. of Pages :' + str(self.pages) def __add__(self,other): total = self.pages + other.pages # total no. of pages of b1+b2 b = Book(total) # creating one more object like b return b def __mul__(self,other): total = self.pages * other.pages # total no. of pages of b2*b3 b = Book(total) # creating one more object like b return b b1 = Book(100) b2 = Book(200) b3 = Book(300) b4 = Book(700) b5 = Book(1000) print(b1) # The No. of Pages :100 print(b1+b2) # The No. of Pages :300 print(b1+b2+b3) # The No. of Pages :600 print(b1+b2*b3+b4) # The No. of Pages :60800 ------------------------------------------------------------------------------------------------------- class student: def __init__(self,name,marks): self.name = name self.marks = marks s1 = student('Rajesh',100) s2 = student('sharma',200) print(s1<s2) # TypeError: '<' not supported between instances of 'student' and 'student'. ----------------------------------------------------------------------------------------------------- Question :- How to check the 2 students marks are greater or less then between them by using operator loading ? Answer :- Yes, We can do it by using the __lt__() magic method and can check the condition is True or False. class student: def __init__(self,name,marks): self.name = name self.marks = marks def __lt__(self,other): return self.marks < other.marks s1 = student('Rajesh',100) s2 = student('sharma',200) print(s1<s2) # True print(s1>s2) # False ---------------------------------------------------------------------------------------------------- Question :- How to display the employee salary as per operator overloading ? Answer :- Yes, We can display it by using __mul__() magic method. class Employee: def __init__(self,name,salary): self.name = name self.salary = salary def __mul__(self,other): return self.salary * other.days class TimeSheet: def __init__(self,name,days): self.name = name self.days = days e = Employee('Rajesh',500) t = TimeSheet('Rajesh',25) print('This Month Salary :', e*t) # This Month Salary : 12500 print('This Month Salary :', t*e) # TypeError: unsupported operand type(s) for *: 'TimeSheet' and 'Employee' -------------------------------------------------------------------------------------------------- class Employee: def __init__(self,name,salary): self.name = name self.salary = salary def __mul__(self,other): return self.salary * other.days class TimeSheet: def __init__(self,name,days): self.name = name self.days = days def __mul__(self,other): return self.days * other.salary e = Employee('Rajesh',500) t = TimeSheet('Rajesh',25) print('This Month Salary :', e*t) # This Month Salary : 12500 print('This Month Salary :', t*e) # This Month Salary : 12500
a09833e63f1fd9b89778cacfda01331b0dd5888d
Silentsoul04/FTSP_2020
/Durga OOPs/Method_Overriding_OOPs.py
3,038
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 19:14:46 2020 @author: Rajesh """ Method Overriding :- ----------------- Inheritance :- ----------- class P: 10 methods are there class C extends P: # In Java child class created. 5 more methods are there class C(P): # In Python child class created. 5 more methods are there class C(P1,P2,P3 .....Pn): # In Python child class created by any no. of parents classes. 5 more methods are there NOTE :- Parent class is having only 10 methods. NOTE :- Child class is having 15 methods coz 10 methods from parent class & 5 from itself and Total = 15 methods. NOTE :- We can see that Inheritance is very powerful concept in the python. 1) Code Re-usability. 2) Existing functionality we can extend. -------------------------------------------------------------------------------------------------------------- class P: # parent class def property(self): # parent class Method print('cash+land+gold+power') def marry(self): # parent class Method print('Marry with Deepka sharma') class C(P):pass # pass c = C() # Object creation for child class. c.property() # cash+land+gold+power c.marry() # Marry with Deepka sharma ************ Result ********** cash+land+gold+power Marry with Deepka sharma NOTE :- We can see that the child is capable to use parent things without any issue. ------------------------------------------------------------------------------------------------------ class P: def property(self): # parent class Method print('cash+land+gold+power') def marry(self): # parent class Method print('Marry with Deepka sharma') class C(P): def marry(self): # Child class Method print('Marry with Sunny Leoney from Forsk') c = C() # Object creation for child class. c.property() # cash+land+gold+power c.marry() # Marry with Sunny Leoney from Forsk ************ Result ********** cash+land+gold+power Marry with Sunny Leoney from Forsk ---------------------------------------------------------------------------------------------------- class P: def property(self): # parent class Method print('cash+land+gold+power') def marry(self): # parent class Method print('Marry with Deepka sharma') class C(P): def marry(self): # Child class Method super().marry() print('Marry with Sunny Leoney from Forsk') c = C() # Object creation for child class. c.property() # cash+land+gold+power c.marry() # Marry with Sunny Leoney from Forsk ************ Result ********** cash+land+gold+power Marry with Deepka sharma Marry with Sunny Leoney from Forsk --------------------------------------------------------------------------------------------------
a1e5fef7ebf21e348da661f3115a309c74f5c75f
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Income_Data_fields_ML.py
3,144
3.5
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 7 18:02:02 2020 @author: Rajesh """ """ Explain the Income Data fields Divide into features and labels with explanation HR Tool to offer a salary to new candidate of 15 yrs Explain the plotting of two list with range data Explain best fit line concept, Calculate slope and constant y = mx + c Gradient Descent concept to find best fit line to minimise the loss or cost function For Linear Regression the cost function = Mean Square error its diffetent for different algorithms. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\Income_Data.csv') print(dataset) # We know that , y = mx+c # We need to use first we need to find the feartures(Experience) & Labels(Income). features = dataset.iloc[:,: 1].values labels = dataset.iloc[:,-1].values from sklearn.linear_model import LinearRegression regg = LinearRegression() # Object creation / Model Creation. regg.fit(features,labels) # Trainig the model / Fitting the model. # regg.predict(features) regg.predict() # If we will pass the directly 12 it will through some error coz # it need data into numpy array form. # regg.predict([[12]]) 139191.74805613 x = [12] x = np.array(x) x = x.reshape(1,1) a = regg.predict(x) a[0] # 139191.7480561296 x = [20] x = np.array(x) x = x.reshape(1,1) a = regg.predict(x) a[0] # 214791.4466277702 x = [4.5] x = np.array(x) x = x.reshape(1,1) a = regg.predict(x) a[0] # 68317.03064521654 plt.scatter(features,labels,color='green') plt.plot(features,regg.predict(features),color='red') plt.xlabel('No. of Experience') plt.ylabel('Salaries Details') plt.title('Experience & Salaries Graph') plt.savefig('E:\Mechine Learning Forsk\Exp_sal.jpg') plt.show() ----------------------------------------------------------------------------------------- NOTE :- We will be solving this problem by using the train_test_split() method. import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\Income_Data.csv') print(dataset) # We know that , y = mx+c # We need to use first we need to find the feartures(Experience) & Labels(Income). features = dataset.iloc[:,: 1].values labels = dataset.iloc[:,-1].values from sklearn.model_selection import train_test_split features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0) from sklearn.linear_model import LinearRegression regg = LinearRegression() # Object creation / Model Creation. regg.fit(features_train,labels_train) # Trainig the model / Fitting the model. labels_pred = regg.predict(features_test) df = pd.DataFrame({'Actual':labels_test,'Predicated':labels_pred}) print(df) # We will plot the graph of these values. plt.scatter(features_test,labels_test,color='blue') plt.plot(features_train,regg.predict(features_train),color='orange') plt.xlabel('No. of Experience') plt.ylabel('Salaries Details') plt.title('Experience & Salaries Graph') plt.savefig('E:\Mechine Learning Forsk\Exp_sal1.jpg') plt.show()
a55705a3921e16f5eeaa8bfa1034baabf7bca022
Silentsoul04/FTSP_2020
/CodeBasics_Pandas/Numpy_CB/slicing_stacking_arrays_Numpy.py
3,637
4.0625
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 11:23:26 2020 @author: Rajesh """ slicing/stacking arrays, indexing with boolean arrays : - ------------------------------------------------------- import numpy as np n = [6,7,8,9] n[1] # 7 n[-1] # 9 n[1:3] # [7,8] a = np.array([6,7,8,9]) a[0] # 6 a[-2] # 8 a[1:3] # [7,8] NOTE :- Here we can see that Python basic list and Numpy arrays are almost same. # If we have values into multidimensional then how to slicing the values. a = np.array([[6,7,8],[1,2,3],[9,3,2]]) a --- array([[6, 7, 8], [1, 2, 3], [9, 3, 2]]) a[1,2] # 3 , # Here 1,2 Means Row , column like first row & 2nd column. te a[0:2,2] # [8,3] a[1: , 0] # [1,9] a[-1] # [9, 3, 2] a[0: , -1] # [8, 3, 2] a[-1,0:2] # [9, 3] a[:,1:3] ---- ([7, 8], [2, 3], [3, 2]]) a[:,1:] ------ ([[7, 8], [2, 3], [3, 2]]) # If we want to get values through any loop then we should use the for loop. a = np.array([[6,7,8],[1,2,3],[9,3,2]]) # We will just iterate the row-wise values. for row in a: print(row) ----- [6 7 8] [1 2 3] [9 3 2] # Now we use the flatting here. # Numpy has one method is called as flat. for cell in a.flat: print(cell) ----- 6 7 8 1 2 3 9 3 2 ----------------------------------------------------------------------------------------- Stacking two arrays Together :- ---------------------------- import numpy as np a = np.arange(6).reshape(3,2) ---- array([[0, 1], [2, 3], [4, 5]]) b = np.arange(6,12).reshape(3,2) --- array([[ 6, 7], [ 8, 9], [10, 11]]) # If we want to stack them together. # We have one method is called as np.vstack((a,b)) np.vstack((a,b)) ----- array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11]]) np.hstack((a,b)) ----- array([[ 0, 1, 6, 7], [ 2, 3, 8, 9], [ 4, 5, 10, 11]]) a = np.arange(30).reshape(2,15) ------ array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) np.hsplit(a,3) --------- [array([[ 0, 1, 2, 3, 4], [15, 16, 17, 18, 19]]), array([[ 5, 6, 7, 8, 9], [20, 21, 22, 23, 24]]), array([[10, 11, 12, 13, 14], [25, 26, 27, 28, 29]])] # Here we are not able to visualise properly so we will store this Array into a variable. result = np.hsplit(a,3) result[0] ----- array([[ 0, 1, 2, 3, 4], [15, 16, 17, 18, 19]]) result[1] ------- array([[ 5, 6, 7, 8, 9], [20, 21, 22, 23, 24]] result[2] ----- array([[10, 11, 12, 13, 14], [25, 26, 27, 28, 29]]) result = np.vsplit(a,2) ------- [array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]]), array([[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])] result[0] ------ array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]]) result[1] ------ array([[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) ''' indexing with boolean arrays :- ------------------------------ ''' a = np.arange(12).reshape(3,4) ---- array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) b = a > 4 b ---- array([[False, False, False, False], [False, True, True, True], [ True, True, True, True]]) a[b] ----- [ 5, 6, 7, 8, 9, 10, 11] # If we want to replace greater than 4 elements with -1. a[b] = -1 ----- array([[ 0, 1, 2, 3], [ 4, -1, -1, -1], [-1, -1, -1, -1]]) a[b] = 100 ----- array([[ 0, 1, 2, 3], [ 4, 100, 100, 100], [100, 100, 100, 100]])
0b8edc36cd1736354e08a6cb5791a150d6f67478
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Test_Data_ML.py
1,081
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 6 07:39:27 2020 @author: Rajesh """ Question :- There are some values have given and pls find the solution for those values by using Linear Regresssion. import pandas as pd import numpy as np import matplotlib.pyplot as plt x = [1,2,3,4,5,6,7,8] y = [1,2,3,4,5,6,7,8] for what values of x = 15 and y = ?: We know that, y = f(x) straight Line = y = mx+c where c = Intercept means where y-axis cuts. and m = slope(Coefficent) = m = (y2-y1)/(x2-x1) and where x, y co-ordinates are (x1,y1) , (x2,y2) we can see that now straight line equation. (5,4) , (5,4) ==> (x1,y1) , (x2,y2) (y2-y1)/(x2-x1) (5-4)/(5-4) = 1.0 c = 0 and where x = 15 straight line equation. y = mx+c y = 1(15)+0 y = 15 y = f(x) featues = [1,2,3,4,5,6,7,8] labels = [1,2,3,4,5,6,7,8] plt.scatter(featues,labels) plt.plot(featues,labels,color='Pink') plt.xlabel('features(Indepandent variables)') plt.ylabel('labels(Depandent variables)') plt.title('Simple Guessing Values for labels') # plt.savefig('path') plt.show()
8a279d2f585a3cb655252fb5e379a89c6feb0a66
Silentsoul04/FTSP_2020
/W3_2020_School/Python_Try_Except_Finally_Blocks.py
4,091
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 25 11:17:16 2020 @author: Rajesh """ ''' Python Try Except Finally :- ----------------------------- ''' NOTE :- There are we have mainly 3 blocks like listed below. 1) try block 2) except block 3) finally block 1) try block :- ---------------- It is used to test the errors which is available into written codes. 2) except block :- ---------------- It is used to handle the errors. 3) finally block :- ------------------- It will be always executed irrespective of try and except blocks and whether the exception raised or not. ''' Exception Handling :- ----------------------- When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement. ''' Ex :- The try block will generate an exception, because x is not defined. try: print(x) except: print('An Exception Occured') ----------- Result --------- An Exception Occured NOTE :- Since the try block raises an error, the except block will be executed. NOTE :- Without the try block, the program will crash and raise an error. Ex :- This statement will raise an error, because x is not defined. print(x) # NameError: name 'x' is not defined ''' Many Exceptions :- --------------------- You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error: ''' Ex :- Print one message if the try block raises a NameError and another for other errors. try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") ----------- Result --------- Variable x is not defined Ex :- try: print(20/0) except: print('There is some error into codes') ----------- Result --------- There is some error into codes Ex :- try: print(10/0) except NameError: print("Variable x is not defined") except FileNotFoundError: print('File is not found error') except ZeroDivisionError: print('division by zero') ----------- Result --------- division by zero ''' Else :- ------------- You can use the else keyword to define a block of code to be executed if no errors were raised. ''' Example In this example, the try block does not generate any error: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") ----------- Result --------- Hello Nothing went wrong ''' Finally :- ------------ The finally block, if specified, will be executed regardless if the try block raises an error or not. ''' Ex :- try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished") ----------- Result --------- Something went wrong The 'try except' is finished NOTE :- This can be useful to close objects and clean up resources. Ex :- Try to open and write to a file that is not writable: try: f = open("E:\W3_2020_School\demofile.txt") f.write("FORSK CODING SCHOOL , JAIPURA. This is Rajesh sharma from Sikar,Rajasthan.") except: print("Something went wrong when writing to the file") finally: f.close() ''' Raise an exception :- ----------------------- As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. ''' Ex :- Raise an error and stop the program if x is lower than 0. x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") ------- Result -------- Exception: Sorry, no numbers below zero x = 125 if x < 250: raise Exception('Is it X value is greather than given value.') ------- Result -------- Exception: Is it X value is greather than given value. NOTE :- The raise keyword is used to raise an exception. NOTE :- You can define what kind of error to raise, and the text to print to the user. Ex :- Raise a TypeError if x is not an integer. x = "hello" #x = 120 if not type(x) is int: raise TypeError("Only integers are allowed") ------- Result -------- TypeError: Only integers are allowed
d093fb66538b6974d06cf68b96ae210cef93a738
Silentsoul04/FTSP_2020
/Forsk Pandas/Male_Female_Pie_Details.py
909
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 23 17:29:02 2020 @author: Rajesh """ 5. How many are Male Staff and how many are Female Staff. Show both in numbers and Graphically using Pie Chart. Show both numbers and in percentage. import pandas as pd df = pd.read_csv('E:\PYTHON CODE Challenges\Pandas\Salaries.csv') df[(df['sex'] == 'Female')].count() df[(df['sex'] == 'Male')].count() df['sex'].count() df[(df['sex'] == 'Female')].count() --------------------------------------------------------------------------------------------------- import matplotlib.pyplot as plt labels = 'Female','Male' sizes = [39 , 39] colors = ['green','skyblue'] explode = (0,0) plt.pie(sizes , explode = explode , labels = labels , colors = colors , autopct = '%1.2f%%' , shadow = True , startangle = 270) plt.axis('equal') plt.savefig('E:\Forsk Pandas\Male_Female_Pie_Details.jpg') plt.show
8edd3a0d64fb139017c1d9a1c682c507d462e10d
Silentsoul04/FTSP_2020
/Summer Training ML & DL/Backward_Elimination_Features_Selection_Features_Extraction.py
2,948
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 15:02:35 2020 @author: Rajesh """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\Salary_Classification.csv') dataset.head() **************** Department WorkedHours Certification YearsExperience Salary 0 Development 2300 0 1.1 39343 1 Testing 2100 1 1.3 46205 2 Development 2104 2 1.5 37731 3 UX 1200 1 2.0 43525 4 Testing 1254 2 2.2 39891 features = dataset.iloc[:,:-1].values labels = dataset.iloc[:,-1].values # Encoding Categorial columns data. from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder columnTransformer = ColumnTransformer([('encoder',OneHotEncoder(),[0])] , remainder = 'passthrough') features = np.array(columnTransformer.fit_transform(features) ,dtype = np.float32) # Avoiding the Dummy Variable Trap # Dropping the first columan features = features[:,1:] print(features) # Now we will be applying the Stats Model like Linear Regression only. # OLS Means Optimal Least Square method or Linear Regression both are same only. import statsmodels.api as sm # Add the Constant column to dataset. features = sm.add_constant(features) print(features) # Now we will do the Copy of the Original features data & we perform the OLS on that itself. features_opt = features[:,[0,1,2,3,4,5]] regressor_OLS = sm.OLS(endog = labels , exog = features_opt).fit() regressor_OLS.summary() # Here we have the x2 has the highest p value and we need to remove it. features_opt = features[:,[0,1,3,4,5]] # x2 remove from features_opt regressor_OLS = sm.OLS(endog = labels , exog = features_opt).fit() regressor_OLS.summary() features_opt = features[:,[0,1,3,5]] # x3 means Certification Column remove from features_opt regressor_OLS = sm.OLS(endog = labels , exog = features_opt).fit() regressor_OLS.summary() features_opt = features[:,[0,3,5]] # x4 means WorkedHours Column remove from features_opt regressor_OLS = sm.OLS(endog = labels , exog = features_opt).fit() regressor_OLS.summary() features_opt = features[:,[0,5]] # x1 means Dummy variable1 Column remove from features_opt regressor_OLS = sm.OLS(endog = labels , exog = features_opt).fit() regressor_OLS.summary() # Add these code to Automatic Removes p values from the Dataset. import statsmodels.api as sm import numpy as np features_obj = features[:,[0,1,2,3,4]] features_obj = sm.add_constant(features_obj) while(True): regressor_OLS = sm.OLS(endog=labels,exog=features).fit() pvalues = regressor_OLS.pvalues if pvalues.max() > 0.05: features_obj = np.delete(features_obj, pvalues.argmax(),1) else: break
b62b7a448bdf7cd15cb1e32e3a023194703b0c77
Silentsoul04/FTSP_2020
/Knowledge Shelf/set_index_reset_index()_Pandas_9.py
3,614
3.75
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 1 11:01:59 2020 @author: Rajesh """ """ set_index & .reset_index() in Pandas :- ------------------------------------- """ import pandas as pd bond = pd.read_csv('E:\Knowledge Shelf\csv Files\jamesbond.csv') bond.head() # Here IF we want we can change the index of the any columns like by passing index_col = 'column name' into reading csv file. # Other we can set the index also. bond.set_index('Film' , inplace = True) bond.head() # NOTE :- Now here Film column is used as Index values but if we want remove that column also. bond.reset_index(drop=True , inplace =True) bond.reset_index() bond.reset_index(drop=True) bond.set_index('Year' , inplace = True) bond.reset_index(inplace = True) bond.set_index(drop=True , inplace = True) ------------------------------------------------------------------------------------------------------------ """ Retrieve Row Values Using loc in Pandas :- ----------------------------------------- """ import pandas as pd bond = pd.read_csv('E:\Knowledge Shelf\csv Files\jamesbond.csv' , index_col = 'Film') bond.sort_index(inplace= True) bond.head() bond.loc['Goldfinger'] ****************** Year 1964 Actor Sean Connery Director Guy Hamilton Box Office 820.4 Budget 18.6 Bond Actor Salary 3.2 Name: Goldfinger, dtype: object bond.loc['GoldenEye'] ****************** Year 1995 Actor Pierce Brosnan Director Martin Campbell Box Office 518.5 Budget 76.9 Bond Actor Salary 5.1 Name: GoldenEye, dtype: object # If the passes Movie is not in the dataset. Then it will throw an error. bond.loc['Dangal'] # It the Repaeted movie also in the different year by different Actor. bond.loc['Casino Royale'] # Here loc we can use as the Range function. bond.loc['Diamonds are Forever' : 'Moonraker'] # It starts from GoldenEye & ends with the last one. bond.loc['GoldenEye':] # It starts from first movie name & ends with the GoldenEye. bond.loc[:'GoldenEye'] # To get the multiple values details. bond.loc[['Moonraker','GoldenEye']] # Here 2 movie details are matched and 1 is not matched then it will show as Nan into result. bond.loc[['Diamonds are Forever','GoldenEye','dangal']] # NOTE :- We have one Interseting thing to get the details like this partcular movie # is there or not into dataset. 'Dangal' in bond.index # False 'GoldenEye' in bond.index # True ---------------------------------------------------------------------------------------------- """ Retrieve Row Values Using iloc in Pandas :- ----------------------------------------- """ import pandas as pd bond = pd.read_csv('E:\Knowledge Shelf\csv Files\jamesbond.csv') # NOTE :- Here ' iloc ' does not consider the last one. bond.iloc[[10,20]] bond.iloc[:4] bond.iloc[4:8] bond.iloc[23:] bond.iloc[5:15:2] bond.iloc[10:20:4] bond.iloc[[5,7,10,21]] ---------------------------------------------------------------------------------------------- """ Retrieve Row Values Using ix in Pandas :- --------------------------------------- """ import pandas as pd bond = pd.read_csv('E:\Knowledge Shelf\csv Files\jamesbond.csv' , index_col = 'Film') bond.sort_index(inplace= True) bond.head() # NOTE :- Here we can use of the method and both will give the same Result. bond.loc['GoldenEye'] bond.ix['GoldenEye'] bond.ix[['Moonraker','GoldenEye']] bond.ix['Goldfinger':'GoldenEye'] bond.iloc[14] bond.iloc[14, 2:5] bond.iloc[20, [3,5,2]]
c6f55ab676a899e115bda4f5316e408f2710f1bd
Silentsoul04/FTSP_2020
/Extra Lockdown Tasks/Operators_Python.py
405
4.15625
4
# Operators in Python :- 1) Arithematic 2) Assignement 3) Comparison 4) Logical 5) Membership 6) Identity 7) Bitwise Ex :- x = 2 y = 3 print(x+y) print(x-y) print(x*y) print(x/y) print(x//y) print(x%y) print(x**y) Ex :- x = 1001 print(x) x+=9 print(x) x-=9 print(x) x*=9 print(x) Ex :- == > < >= , <= , != x = 100 y = 500 print(x==y) print(x<y) print(y>x)
bbd493c80b0bac169c1315a83ecc6dbc8f7fc031
Silentsoul04/FTSP_2020
/Python_CD6/list_dict.py
953
3.859375
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 20 17:04:48 2020 @author: Rajesh """ """ Filename: list_dict.py Problem Statement: Assume you’re given the following list of files: ist_of_files = ['data0001.txt', 'data0002.txt','data0003.txt'] Create a dictionary filenum where the keys are the filenames and the value is the file number (i.e., data0001.txt has a file number of 1) as an integer. Make your code fill the dictionary automatically, assuming that you have a list list of files. Data: Not required Extension: Not Available Hint: To convert a string to an integer, use the int function on the string, and the list and array sub-range slicing syntax also works on strings """ ist_of_files = ['data0001.txt', 'data0002.txt','data0003.txt'] dict1={} # Empty dictionary v=1 for k in ist_of_files: dict1[k]=v v=v+1 print(dict1)
75491c0af8bf38a3559541610a49781277015070
Silentsoul04/FTSP_2020
/W3_2020_School/Python_Data Types.py
3,105
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 19 10:41:11 2020 @author: Rajesh """ ''' Python Data Types :- Python has some of the Build-in data types. ------------------ ''' In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: 1) Text Type: str 2) Numeric Types: int, float, complex 3) Sequence Types: list, tuple, range 4) Mapping Type: dict 5) Set Types: set, frozenset 6) Boolean Type: bool 7) Binary Types: bytes, bytearray, memoryview NOTE :- We can check the data type of any object by using the type() function. Ex :- x = 100 print('The Value of x :', x) print(type(x)) y = 'Forsk Coding School' print('The Value of y :', y) print(type(y)) --------------- Result ------------------ The Value of x : 100 <class 'int'> The Value of y : Forsk Coding School <class 'str'> Examples :- 1) Text Type: str x = "Hello World" print(x) print(type(x)) --------------- Result ------------------ Hello World <class 'str'> 2) Numeric Types: int, float, complex x = 20 print(x) print(type(x)) --------------- Result ------------------ 20 <class 'int'> x = 50.5 print(x) print(type(x)) --------------- Result ------------------ 50.5 <class 'float'> x = 10+20j print(x) print(type(x)) --------------- Result ------------------ (10+20j) <class 'complex'> 3) Sequence Types: list, tuple, range list1 = ['Rajesh',10,20.5,-15] print(list1) print(type(list1)) --------------- Result ------------------ ['Rajesh', 10, 20.5, -15] <class 'list'> t1 = ('Rajesh',10,20.5,-15) print(t1) print(type(t1)) --------------- Result ------------------ ('Rajesh', 10, 20.5, -15) <class 'tuple'> x = range(10) print(x) print(type(x)) --------------- Result ------------------ range(0, 10) <class 'range'> 4) Mapping Type: dict dict1 = {'Name':'Rajesh','Age':26} print(dict1) print(type(dict1)) --------------- Result ------------------ {'Name': 'Rajesh', 'Age': 26} <class 'dict'> 5) Set Types: set, frozenset set1 = {10,20,'Rajesh','x',20.5,20,10} print(set1) print(type(set1)) --------------- Result ------------------ {'Rajesh', 'x', 10, 20, 20.5} <class 'set'> x = frozenset({10,20,'Rajesh','x',20.5,20,10}) print(x) print(type(x)) --------------- Result ------------------ frozenset({'Rajesh', 'x', 20, 20.5, 10}) <class 'frozenset'> 6) Boolean Type: bool x = True y = False print(x) print(type(x)) print(y) print(type(y)) --------------- Result ------------------ True <class 'bool'> False <class 'bool'> 7) Binary Types: bytes, bytearray, memoryview x = B'Hello World' # x = b'Hello World' # bytes. print(x) print(type(x)) --------------- Result ------------------ b'Hello World' <class 'bytes'> x = bytearray(5) print(x) print(type(x)) --------------- Result ------------------ bytearray(b'\x00\x00\x00\x00\x00') <class 'bytearray'> x = memoryview(bytes(5)) print(x) print(type(x)) --------------- Result ------------------ <memory at 0x000000000A878288> <class 'memoryview'>
233e0324d6c7a092508701f2777771aaa33f3da2
Silentsoul04/FTSP_2020
/NumPy Forsk/NumPy_Basic_Details.py
8,135
4.03125
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 21 15:39:36 2020 @author: Rajesh """ # Numerical Python '''Introduction to NumPy''' my_list = [0,1,2,3,4,5,6,7,8] print (type(my_list)) print (my_list) # Convert your list data to NumPy arrays. import numpy as np arr = np.array(my_list) print(type(arr)) # <class 'numpy.ndarray'> print('Array :\n', arr) # [0 1 2 3 4 5 6 7 8] --> It always prints the values WITHOUT comma seperated , thats ndarray ------------------------------------------------------------------------------------------------ my_tuple = 10,20,30,40,50 print(type(my_tuple)) print(my_tuple) # Convert your tuple data to NumPy arrays. import numpy as np arr = np.array(my_tuple) print(type(arr)) print('Array :\n', arr) # [10 20 30 40 50]. Array gives the result always into list but elements will separated by space. --------------------------------------------------------------------------------------------- my_dict = {10:1 , 20:2 , 30:4 , 40:5,'Name':'Rajesh','Class':'Forsk'} print(type(my_dict)) # <class 'dict'> print(my_dict) import numpy as np arr = np.array(my_dict) print(type(arr)) print('Array :\n', arr) ************* Result ************** Array : {10: 1, 20: 2, 30: 4, 40: 5, 'Name': 'Rajesh', 'Class': 'Forsk'} --------------------------------------------------------------------------------------------- """ Ex :- Take a list and perfrom some of the operations. """ import numpy as np my_list = [10,20,30,40,50,60,70,80,90,100] arr = np.array(my_list) print('Array :', arr) # [ 10 20 30 40 50 60 70 80 90 100] print('size :', arr.size) # 10 print('DataType :',arr.dtype) # int32 print('Dimensions :', arr.ndim) # 1 print('Shape :', arr.shape) # (10,) print('ItemSize :', arr.itemsize) # 4 . It always gives the 4 Bytes for each element. print('No. of Bytes :', arr.nbytes) # 40 print('Strides :', arr.strides) # (4,) --> It always show that how the element will be going into next line. # Array Indexing will always return the data type object. print (arr[0]) # 10 print (arr[2]) # 30 print (arr[-1]) # 100 ---------------------------------------------------------------------------------------------- import numpy as np my_list = [10.5,20.5,30.1,80.2,75.0] print(my_list) arr = np.array(my_list) print('Array :', arr) # [10.5 20.5 30.1 80.2 75. ] print('size :', arr.size) # 5 print('DataType :', arr.dtype) # float64 print('Dimnesions :', arr.ndim) # 1 print('shape :', arr.shape) # (5,) print('Itemsize :', arr.itemsize) # 8 print('No. of Byte: ', arr.nbytes) # 40 print('strides :', arr.strides) # (8,) # Array Indexing will always return the data type object. print(arr[3]) # 80.2 print(arr[-1]) # 75.0 print(arr[1]) # 20.5 ----------------------------------------------------------------------------------------------------- import numpy as np my_list = ['Rajesh',10,20,30,'Sharma','Yogi',20.50,-30.5] print(my_list) arr = np.array(my_list) print('Array :', arr) # ['Rajesh' '10' '20' '30' 'Sharma' 'Yogi' '20.5' '-30.5'] print('size :', arr.size) # 8 print('DataType :', arr.dtype) # <U6 print('Dimnesions :', arr.ndim) # 1 print('shape :', arr.shape) # (8,) print('Itemsize :', arr.itemsize) # 24 print('No. of Byte: ', arr.nbytes) # 192 print('strides :', arr.strides) # (24,) # Array Indexing will always return the data type object. print(arr[3]) # 30 print(arr[-1]) # -30.5 print(arr[1]) # 10 ------------------------------------------------------------------------------------------------------- """ Reshaping is changing the arrangement of items so that shape of the array changes Flattening, however, will convert a multi-dimensional array to a flat 1d array. And not any other shape. """ NOTE :- There are 2 types of arranging the data into different Arrays. Reshaping :- Convert from small to big data types. Flattening :- Convert from big to small data types. # Reshaping to 2 Dimensional Array - 3 Rows and 3 Columns. Ex :- For 2D Arrays :- for integer number. import numpy as np my_list = [10,20,30,40,50,60,70,80] arr = np.array(my_list) print('Array :', arr) # [ 10 20 30 40 50 60 70 80 ] print('size :', arr.size) # 8 print('DataType :', arr.dtype) # int32 print('Dimnesions :', arr.ndim) # 1 print('shape :', arr.shape) # (8,) print('Itemsize :', arr.itemsize) # 4 print('No. of Byte: ', arr.nbytes) # 32 print('strides :', arr.strides) # (4,) Case - 1 :- -------- res = arr.reshape(4,2) print('The New Array :\n', res) print('size :', res.size) # 8 print('DataType :', res.dtype) # int32 print('Dimnesions :', res.ndim) # 2 print('shape :', res.shape) # (4,2) print('Itemsize :', res.itemsize) # 4 print('No. of Byte: ', res.nbytes) # 32 print('strides :', res.strides) # (8,4) --> It represent the one line how many bytes total bytes required for next line and then int/float. ********* Result ********** The New Array : [[10 20] [30 40] [50 60] [70 80]] size : 8 DataType : int32 Dimnesions : 2 shape : (4, 2) Itemsize : 4 No. of Byte: 32 strides : (8, 4) ------------------------------------------------------------------------------------------------------- Case - 2 :- -------- res = arr.reshape(2,4) print('The New Array :\n', res) print('size :', res.size) # 8 print('DataType :', res.dtype) # int32 print('Dimnesions :', res.ndim) # 2 print('shape :', res.shape) # (2,4) print('Itemsize :', res.itemsize) # 4 print('No. of Byte: ', res.nbytes) # 32 print('strides :', res.strides) # (16,4) --> It represent the one line how many bytes total bytes required for next line and then int/float. ********* Result ********** The New Array : [[10 20 30 40] [50 60 70 80]] size : 8 DataType : int32 Dimnesions : 2 shape : (2, 4) Itemsize : 4 No. of Byte: 32 strides : (16, 4) -------------------------------------------------------------------------------------------------- Ex :- For 2D Arrays :- for Float number. ------------- import numpy as np my_list = [10.5,20.5,30.1,80.2,75.0,80.50] # 1-D Array. print(my_list) arr = np.array(my_list) print('Array :', arr) # [10.5 20.5 30.1 80.2 75. 80.50] print('size :', arr.size) # 6 print('DataType :', arr.dtype) # float64 print('Dimnesions :', arr.ndim) # 1 print('shape :', arr.shape) # (6,) print('Itemsize :', arr.itemsize) # 8 print('No. of Byte: ', arr.nbytes) # 48 print('strides :', arr.strides) # (8,) Case - 1 :- -------- res = arr.reshape(3,2) print('The New Array :\n', res) print('size :', res.size) # 6 print('DataType :', res.dtype) # float64 print('Dimnesions :', res.ndim) # 2 print('shape :', res.shape) # (3,2) print('Itemsize :', res.itemsize) # 8 print('No. of Byte: ', res.nbytes) # 48 print('strides :', res.strides) # (16,8) --> It represent the one line how many bytes total bytes required for next line and then int/float. ************ Result ********** The New Array : [[10.5 20.5] [30.1 80.2] [75. 80.5]] size : 6 DataType : float64 Dimnesions : 2 shape : (3, 2) Itemsize : 8 No. of Byte: 48 strides : (16, 8) ---------------------------------------------------------------------------------------------------- Case - 2 :- -------- res = arr.reshape(2,3) print('The New Array :\n', res) print('size :', res.size) # 6 print('DataType :', res.dtype) # float64 print('Dimnesions :', res.ndim) # 2 print('shape :', res.shape) # (2,3) print('Itemsize :', res.itemsize) # 8 print('No. of Byte: ', res.nbytes) # 48 print('strides :', res.strides) # (24,8) --> It represent the one line how many bytes total bytes required for next line and then int/float. ************ Result ********** The New Array : [[10.5 20.5 30.1] [80.2 75. 80.5]] size : 6 DataType : float64 Dimnesions : 2 shape : (2, 3) Itemsize : 8 No. of Byte: 48 strides : (24, 8) ---------------------------------------------------------------------------------------------------- """ For 1D array, shape return a tuple with only 1 component (i.e. (n,)) For 2D array, shape return a tuple with only 2 components (i.e. (n,m)) For 3D array, shape return a tuple with only 3 components (i.e. (n,m,k) ) """
80495410c0f20b979837fefe392820179f28f4ba
Silentsoul04/FTSP_2020
/Durga OOPs/Python_Assertions_OOPs.py
4,839
4.375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 13 16:12:06 2020 @author: Rajesh """ Python Assertions in Simple Way :- ------------------------------- Assertions :- ---------- Assertions are used / perform in Debuging purposes. What is the Meaning of Debugging ? Debugging means removing buggs from the programs. Debugging :- --------- The process of identifying the bugs and fixing of those bugs in the program and getting the expected result/output is called as debugging. NOTE :- The most usages of debugging is using the print statements. NOTE :- Once we have got the expected Result then we need to remove all those print statements from the program. If we are not removing all those print statements from the program then the performance will be down and unwanted print msgs will be on server console and server logs will be disturbed. No use for it. NOTE :- To remove such kind of above server logs & Performance Issue we will go for a Concept is called Assertions. ------------------------------------------------------------------------------------------- There are 3 Enviroments : ------------------------- 1) Development Enviroment 2) Test Enviroment 3) Production / Live Enviroment NOTE :- Usually we can perform debugging only in Development or Test Enviroment. We can not perform debugging on Production / Live Enviroment. NOTE :- To remove such kind of above server logs & Performance Issue we will go for a Concept is called Assertions. The Main purposes of Assertations are to performing debugging. NOTE :- What is the biggest Advantage of print statements and Assertations ? Here after fixing the bugs we are not required to delete the asserations statements. because those Assertations statements will not be executed. NOTE :- Based on our requirements we can enable or disable the Asserations statements. NOTE :- Asseratations we can perform only in Development or Test Enviroment. We can not perform Asseratations on Production / Live Enviroment. Question :- Is there any difference between bug and runtime error ? Answer :- Defect , Bug , Error NOTE :- Any mismatched identified by testing team between expected result and Original result is called as Defect. NOTE :- If testing team got the defect and after they send a defect build to developer and once the developer as accepted then that defect will become as Bug. NOTE :- Once the developer has fixed the bug then moved to production enviroment and while executing the program in production if we are getting any identified mismatched then that will be called -------------------------------------------------------------------------------------------- Types of assert Statements :- -------------------------- 1) Simple Version 2) Augmented Version ------------------------------------------------------------------------------------- 1) Simple Version :- ----------------- syntax :- assert conditional_experssion AssertionError ------------------------------------------------------------------------------ Ex :- x = 10 # some lines codes assert x==10 # some lines codes print(x) ************* Result ******** 10 ----------------------------------------------------------------------------------------------------------- Ex :- x = 10 # some lines codes assert x > 10 # AE # some lines codes print(x) ************* Result ******** AssertionError --------------------------------------------------------------------------------------------------------- Ex :- x = 20 # some lines codes assert x > 10 # AE # some lines codes print(x) ************* Result ******** 20 ------------------------------------------------------------------------------------------------------------------------------------ 2) Augmented Version :- -------------------- syntax :- assert conditional_experssion,msg AssertionError Ex :- x = 10 # some lines codes assert x > 10,'Here X value should be greater than 10 but it is not' # some lines codes print(x) ************* Result ******** AssertionError: Here X value should be greater than 10 but it is not ---------------------------------------------------------------------------------------------------------------------- Ex :- def squareIt(x): return x*x assert squareIt(2) == 4 , 'The square of 2 should be 4' assert squareIt(3) == 9 , 'The square of 3 should be 9' assert squareIt(4) == 16 , 'The square of 4 should be 16' print(squareIt(2)) print(squareIt(3)) print(squareIt(4)) ************* Result ******** 4 9 16 ------------------------------------------------------------------------------------------------------------------------- NOTE :- How to use Asstertations concept into python and spyder Anaconda?
928511975d3b85c7be7ed6c11c63ce33078cc5a1
Silentsoul04/FTSP_2020
/Python_CD6/reverse.py
874
4.25
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 24 11:41:04 2020 @author: Rajesh """ """ Name: Reverse Function Filename: reverse.py Problem Statement: Define a function reverse() that computes the reversal of a string. Without using Python's inbuilt function Take input from User Sample Input: I am testing Sample Output: gnitset ma I """ def reverse(x): return x[: : -1] x = input('Enter the string from user :') print('The Reverse string :', reverse(x)) ################ OR ################# def rev_string(str1): return str1[: : -1] str1 = input('Enter the string from user :') print('The Reverse string :', rev_string(str1)) ################ OR ################# def rev_num(num): return num[: : -1] num = input('Enter any number to reverse :') print('The Reversed number :', rev_num(num))
7d7777a67696251e2ea31bc2f7fd775ddae69546
Silentsoul04/FTSP_2020
/Extra Lockdown Tasks/Pattern_Programming_2.py
519
3.5
4
# How to print this below Pattern in Python :- # Pattern :- 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 n = int(input('Enter n value :')) for i in range(n): # 0,1,2,3,4 print((str(i+1)+' ') * n) s1 = 'Andy' s2 = ' Candy' print(s1+s2) # Pattern :- A A A A B B B B C C C C D D D D n = int(input('Enter n value :')) for i in range(n): # 0,1,2,3,4 print((chr(65+i)+' ') * n) print(chr(65)) # A print(chr(66)) print(chr(67)) print(chr(68)) print(ord('A')) print(ord('B')) print(ord('z'))
8053520749bfa7e4274beebadc8d6ae1d10a91cc
Silentsoul04/FTSP_2020
/Durga OOPs/ClassMethod_OOps.py
4,951
4.375
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 16 21:44:42 2020 @author: Rajesh """ NOTE :- Inside method body if we are accessing only class level(static variables) data. what is the need of declaring as instance method. s = student() # object creation for class student. s.m1() # Accessing the method m1() by using the 's' object reference. NOTE :- It is very costlty operation coz we need to create the object then access. NOTE :- In Instance method we can't access without object creation coz we need the object reference. NOTE :- Inside class methos easily we can access. We just need to use the classname.method name. Ex :- student.m1() student.Average() NOTE :- Internally, performance will be there. NOTE :- If you are accessing only static variables in the class then better to use the @classmethod decorators. NOTE :- If we are using atleast one instance variable then compulsory we have to declared that method as Instance method. NOTE :- Until, If not necessary then pls do not go for Instance method coz we need to accessing method by using object reference & it is very costly operation. so, better to use @classmethod. ------------------------------------------------------------------------------ How to accessing by using Instance method :- ----------------------------------------- def m1(self): # self is the reference variable to pointing to the current object. print(self.name) print(self.marks) print(self.rollno) -------------------------------------------------------------------------- How to Declare & Accessing by using Class method :- ------------------------------------------------ NOTE :- Every class method compulsory should contains atleast one argument like 'cls'. NOTE :- cls means current class object. def m1(cls): print(cls.collegename) print(cls.bankname) NOTE :- We are able to access class level variables means static variables. NOTE :- Instance method does not use any decorators but class method compulsory shoud use the @classmethod decorators. @classmethod def m1(cls): print(cls.collegename) NOTE :- By using self we can access only Instance variables & by using cls we can access only class level variables or static variables. NOTE (Question) :- Anyway, we are passing cls variable which is used as class then why we are again using @classmethod ??? Answer :- We are passing @classmethod coz there is one more concept like @staticmethod. and it can treated as @staticmethod. So to differentiate in both of it. NOTE :- Inside Instance method we can access the Instance variables as well as static variables also. NOTE :- Inside static method we can only access class level variables means static variables. Instance methos vs. Class method :- -------------------------------- 1) Inside method body if we are using atleast one instance variable then compulsory we should declare that method as Instance method. 1) Inside method body we are using only static variable then it is highly recommanded to declare that metod as Class method. 2) To declare any instance method we are not required to use any decorators. 2) To declare class method compulsory we must have to use @classmethod decorators. 3) The first argument to the instance method should be self; and which is refering to the current object by using self, we can access instance variables inside the method. 3) The argument to the classmethod should be the cls and which is refereing to the current class object and by using that we can access static variables. 4) Inside instance method we can access both instance variables and static variables 4) Inside classmethod we can access only the static variables and we can not access instance variables. 5) We can call instance method by using object reference. 5) We can call classmethod either by using object referencce or by using classname. but recommanded to use classname. Ex :- --- class Animal: legs = 4 # static variable. @classmethod def walk(cls,name): print('{} walks with {} legs'.format(name,cls.legs)) Animal.walk('dog') # We can access by using classname and NO need to create oject and which is called as level variables. Animal.walk('cat') ------------------------------------------------------------------------------ ## WAP to track no. of objects created for a class ??. class Test: count = 0 # static variable def __init__(self): Test.count = Test.count+1 @classmethod def getNoOfObjects(cls): print('The No. of objects are created :', cls.count) t1 = Test() t2 = Test() t3 = Test() t4 = Test() Test.getNoOfObjects() # Accessing the method by using the classname.
f76176ac85522e740f6b3079d06c545002813302
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Basics_Of_Data_Analytics.py
6,663
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 10:55:15 2020 @author: Rajesh """ Pandas :- panel data set. # How to import pandas into our program. # Pandas is the very powerful libraries in the python. import pandas as pd ps = pd.Series(['a','b','c','d']) print(ps) ******* Result ******* 0 a 1 b 2 c 3 d dtype: object ts = pd.Series(('a','b','c','d')) print(ts) ******* Result ******* 0 a 1 b 2 c 3 d dtype: object data = pd.Series([10,20,30,40,50]) print(data) type(data) # pandas.core.series.Series 0 10 1 20 2 30 3 40 4 50 dtype: int64 ---------------------------------------------------------------------------------------------------- NOTE :- We can see that Series is the one-dimensional data type. ------------------------------------------------------------------------------------------- ''' How to customized the Indexes ''' ---------------------------------------- data = pd.Series(['Python','Mechine Learning','Deep Learning','Analytics']) print(data) 0 Python 1 Mechine Learning 2 Deep Learning 3 Analytics data = pd.Series(['Python','Mechine Learning','Deep Learning','Analytics'] , index=[100,101,102,103]) print(data) 100 Python 101 Mechine Learning 102 Deep Learning 103 Analytics ----------------------------------------------------------------------------------------------------------- import pandas as pd df = pd.read_csv('E:\Forsk Pandas\CSV files\Salaries.csv') print(df) df.columns ['rank', 'discipline', 'phd', 'service', 'sex', 'salary'] --------------------------------------------------------------------------------------------- df[(df['service']==49) & (df['sex']=='Male')] rank discipline phd service sex salary 0 Prof B 56.0 49 Male 186960.0 df[(df['salary']==88000) & (df['sex']=='Male')] rank discipline phd service sex salary 12 AsstProf B 1.0 0 Male 88000.0 df[(df['rank']=='Prof')].count() ank 46 discipline 46 phd 45 service 46 sex 46 salary 45 df[(df['rank']=='Prof')].count()['rank'] # 46 df['salary'].count() # 76 df['salary'].value_counts(normalize = True) # 71 df[df['salary'].isnull()] rank discipline phd service sex salary 7 Prof A 18.0 18 Male NaN 28 AsstProf B 7.0 2 Male NaN df.count() rank 78 discipline 78 phd 76 service 78 sex 78 salary 76 dtype: int64 df[df['salary'].isnull()].count()['rank'] # 2 ---------------------------------------------------------------------------------------------------------- df[(df['rank']=='Prof')].count()['rank'] # 46 df[(df['rank']=='AsstProf')].count()['rank'] # 19 df[(df['rank']=='AssocProf')].count()['rank'] # 13 df.groupby('rank').max() df.groupby('salary').max() df.groupby('salary').count() df.groupby(['rank','sex']).max() df.columns df.groupby('discipline').max() rank phd service sex salary discipline A Prof 51.0 51 Male 155865.0 B Prof 56.0 49 Male 186960.0 df.groupby('discipline').min() rank phd service sex salary discipline A AssocProf 2.0 0 Female 57800.0 B AssocProf 1.0 0 Female 71065.0 df.groupby('discipline').count() rank phd service sex salary discipline A 36 36 36 36 35 B 42 40 42 42 41 df[(df['salary'] > 150000) & (df['sex']=='Male')] rank discipline phd service sex salary 0 Prof B 56.0 49 Male 186960.0 13 Prof B NaN 33 Male 162200.0 14 Prof B 25.0 19 Male 153750.0 15 Prof B 17.0 3 Male 150480.0 19 Prof A 29.0 27 Male 150500.0 27 Prof A 45.0 43 Male 155865.0 31 Prof B 22.0 21 Male 155750.0 df[(df['salary'] > 150000) & (df['sex']=='Female')] rank discipline phd service sex salary 44 Prof B 23.0 19 Female 151768.0 72 Prof B 24.0 15 Female 161101.0 df.shape # (78, 6) df.ndim # 2 df.size # 468 df.head() # First 5 records from database file. df.tail() # Last 5 records from database file. df.index # RangeIndex(start=0, stop=78, step=1) df.columns Index(['rank', 'discipline', 'phd', 'service', 'sex', 'salary'], dtype='object') df.dtypes rank object discipline object phd float64 service int64 sex object salary float64 dtype: object df.values # It provides all values into dataframe. dv = df.values for item in dv: print(item) df.loc[:1] # It includes from start to end range and last number also will be included. rank discipline phd service sex salary 0 Prof B 56.0 49 Male 186960.0 1 Prof A 12.0 6 Male 93000.0 df.loc[10:20 , ['rank','sex']] df[1:4] # 4th line will be exclusive in the data. rank discipline phd service sex salary 1 Prof A 12.0 6 Male 93000.0 2 Prof A 23.0 20 Male 110515.0 3 Prof A 40.0 31 Male 131205.0 df.loc[1:4] # 4th line will be Inclusive in the data. rank discipline phd service sex salary 1 Prof A 12.0 6 Male 93000.0 2 Prof A 23.0 20 Male 110515.0 3 Prof A 40.0 31 Male 131205.0 4 Prof B 20.0 18 Male 104800.0 df.loc[1:4 , 'rank'] 1 Prof 2 Prof 3 Prof 4 Prof df.loc[1:4 , ['rank','sex']] rank sex 1 Prof Male 2 Prof Male 3 Prof Male 4 Prof Male df['rank'].unique() array(['Prof', 'AssocProf', 'AsstProf'], dtype=object) df_list = df['rank'].unique().tolist() print(df_list) ['Prof', 'AssocProf', 'AsstProf'] df.iloc[1:4] rank discipline phd service sex salary 1 Prof A 12.0 6 Male 93000.0 2 Prof A 23.0 20 Male 110515.0 3 Prof A 40.0 31 Male 131205.0 df['rank'].iloc[1:4] 1 Prof 2 Prof 3 Prof df['rank'].unique().tolist(). ['Prof', 'AssocProf', 'AsstProf'] df['discipline'].unique().tolist() ['B', 'A'] df['sex'].unique().tolist() ['Male', 'Female'] df_list = df['salary'].unique().tolist() df_list
993056dc5240d5162ab5966159049dd91ad52719
Silentsoul04/FTSP_2020
/W3Schools/Day1_09_02_20.py
12,224
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 9 13:06:57 2020 @author: Rajesh """ " There are some basic python programs. " print("Hello, world!") # Valid code. print('Hello, world!') # Valid code. print('Hello, world!'); # Valid code. ################# Python Indentation ############################# if 5 > 2: print('Five is greater than two !') # Valid code coz there is indentation mentioned. ################################################### if 5 > 2: print('Five is greater then two !') # Not Valid coz expected an indented block. ##################################################### if 5 > 2: print('Five is greater than two !') if 5 > 2: print('Five is greater than two !') # Valid code coz proper Indentation given into code. ######################################################### if 5 > 2: print("Five is greater than two!") print("Five is greater than two!") # unexpected indent block error. ######################################################### if 5 > 2: print("Five is greater than two!") print("Five is greater than two!") # It is valid code coz there is proper indentation mentioned. print("Hello, World") print("Forsk jaipur !!!") ######################################################### if (10 > 5): print('TRUE') # It is valid code and you can use the paraenthesis for condition. ############## Python variables ###################################### # NOTE :- In python, variables are created when you assign a value to it. x = 5 y = 'Hello , World!' print(x) print(y) print(type(x)) print(type(y)) #################### Comments ###################### # This is single comment line. print('forsk jaipur, sitapura') # It is valid code. 'rajesh sharma' # It is valid code. ''' This is multi commamd line. codes are available in this file. ''' """ This is multi commamd line. codes are available in this file. """ print("Hello, World!") # This is a comment. # print("Hello, World!") --> It won't execute coz single line comment is there. print("Cheers, Mate!") --> It will execute. ############## Multiline Comments #################### #This is a comment #written in #more than just one line print("Hello, World!") # specially, in python there is no multiline cooments. we can use like this # put into triple quotes means multiline strings. """ This is a comment written in more than just one line """ print("Hello, World!") """ ###### NOTE ######### Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. """ #################### Creating Variables ################################## Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. x = 5 y = "John" print(x) print(y) ################# NOTE :- whenever you want you can re-assign the value to variables. x = 4 # x is type od int. x = "Rajesh" # now, X is type of string. print(x) # O / P :- Rajesh ############### String Variables ############ NOTE :- String variables can be declared either by using single or double quotes. x = "forsk jaipur" print(x) x = 'Rajesh sharma' print(x) ################ Variable Names ###################### A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables) #Legal variable names: myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" #Illegal variable names: 2myvar = "John" my-var = "John" my var = "John" NOTE :- Remember that variable names are case-sensitive. ################## Assign Value to Multiple Variables ##################### NOTE :- Python allows you to assign values to multiple variables in one line. x , y , z = 'Orange' , 'Banana' , 'Cherry' print(x) print(y) print(z) print(x,y,z) a , b , c = 10, 20 , 30 print(a,b,c) #################### Assign the same value to multiple variables in one line ######## x = y = z = 'Orange' print(x) print(y) print(z) print(x,y,z) print(type(x)) ------------------------------------ raj = ravi = suri = 10000 print(raj) print(ravi) print(suri) print(raj,ravi,suri) print(type(suri)) ###################### Output Variables ##################### The Python print statement is often used to output variables. To combine both text and a variable, Python uses the + character. x = 'Awesome' print('Python is very ' + x) s = 'Jaipur,(Rajasthan)' print('Forsk technologies in ' + s) ############################# You can also use the + character to add a variable to another variable. x = "Python is " y = "Very Awesome" z = x + y print(z) ###################################################### For numbers, the + character works as a mathematical operator. x = 5 y = 10 print(x + y) ###################################################### If you try to combine a string and a number, Python will give you an error. x = 5 ---> Int Type y = "John" ----> Str Type print(x + y) ---> It gives error like unsupported operand type(s) for +: 'int' and 'str'. ##################### Global Variables ########################################### Variables that are created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function x = "awesome" def myfunc(): # functionn defining. print("Python is " + x) myfunc() ----------------------------------- s = 'forsk coding school' # Global variable coz it is outside the function declared. def student_details(): # functionn defining. print('Rajesh sharma from '+s) # using inside the function and its working fine.No issue at all. student_details() print('There are so many students from '+s) # using inside the function and its working fine.No issue at all. ########################### Local Variables ############################### If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function.The global variable with the same name will remain as it was, global and with the original value.Create a variable inside a function, with the same name as the global variable. x = "awesome" # Global variable coz it is outside the function declared. y = 'forsk' def myfunc(): # function defining. x = "fantastic" # Local variable coz it is inside the function declared. print("Python is " + x) print("Python is very easy and " + x) print('Coding school at jaipur ' + y) myfunc() print("Python is " + x) print("Python is Excellent and " + x) print('Coding school at jaipur ' + y) ####################### global Keyword ###################### Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword. If you use the global keyword, the variable belongs to the global scope. def myfunc(): # functionn defining. global x # local variable but its working as global coz we have used global keyword inside function. x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x) # This is outside the function. ################# change value of global variable inside a function ################# global keyword if you want to change a global variable inside a function. To change the value of a global variable inside a function, refer to the variable by using the global keyword. x = "awesome" # Global variable. def myfunc(): # function defining. global x x = "fantastic" # local variable but it works as global coz we changed the scope of it inside function. myfunc() print("Python is " + x) ####################### Python Data Types ############################ Built-in Data Types :- In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories. Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview Getting the Data Type :- You can get the data type of any object by using the type() function. x = 10 print(x) print(type(x)) x = 20.20 print(x) print(type(x)) x = 'forsk jaipur' print(x) print(type(x)) x = 10+20j print(x) print(type(x)) ################################################################# x = str("Hello World") ----> str x = int(20) ---->int x = float(20.5) ---->float x = complex(1j) ---->complex x = list(("apple", "banana", "cherry")) ----> list x = tuple(("apple", "banana", "cherry")) ----> tuple x = range(6) ----> range x = dict(name="John", age=36) ----> dict x = set(("apple", "banana", "cherry")) ----> set x = frozenset(("apple", "banana", "cherry")) ----> frozenset x = bool(5) ----> bool x = bytes(5) ----> bytes x = bytearray(5) ----> bytearray x = memoryview(bytes(5)) ----> memoryview ###################### Python Numbers ################## There are three numeric types in Python. ----> int ----> float ----> complex Variables of numeric types are created when you assign a value to them: x = 1 # int y = 2.8 # float z = 1j # complex To verify the type of any object in Python, use the type() function. print(type(x)) print(type(y)) print(type(z)) ------------------------------------------ Int :- Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) ------------------------------------------------------- Float :- Float, or "floating point number" is a number, positive or negative, containing one or more decimals. x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) Float can also be scientific numbers with an "e" to indicate the power of 10. x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z)) ------------------------------------------------------------- Complex :- Complex numbers are written with a "j" as the imaginary part: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) ######################## Type Conversion ###################### You can convert from one type to another with the int(), float(), and complex() methods. Convert from one type to another: x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) Note: You cannot convert complex numbers into another number type. ############################### Random Number ########################### Random Number :- Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1,10))
3b99dbfee67d5405bdbbf59b6e48b9ba24d924bd
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Multiple Linear Regression_ML.py
6,967
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 17 15:14:09 2020 @author: Rajesh """ """ # Open Salary_Classification.csv # Teach how to read the dataset # Sandeep is working in the Development Department, # have worked for 1000 hours # Has 1 Certificate and have 2 years experience # Now predict the salary for Sandeep ?? # Which are the features and labels ?? # So there are 4 features and 1 Label ( Multivariate Data) # Multiple Linear Regression """ Multiple Linear Regression :- -------------------------- import pandas as pd import numpy as np dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\Salary_Classification.csv') print(dataset) # To Check the columns Name. dataset.columns ==> Index(['Department', 'WorkedHours', 'Certification', 'YearsExperience', 'Salary'], dtype='object'). # To Check the data Types. print(dataset.dtypes) ==> Department object WorkedHours int64 Certification int64 YearsExperience float64 Salary int64 dtype: object NOTE :- Here we can se that all the columns have integer values apart from Department column. # NDArray # Introduce the concept of Categorical and Numerical Data Types temp = dataset.values print(temp) type(dataset) # pandas.core.frame.DataFrame type(temp) # numpy.ndarray # Seperate Features and Labels. features = dataset.iloc[ : , : -1].values labels = dataset.iloc[ : , -1].values # Check Column wise is any data is missing or NaN. dataset.isnull().any(axis=0) Department False WorkedHours False Certification False YearsExperience False Salary False dtype: bool NOTE :- In the above line we can understand if axis=0 means that we are checking any columns value is Nan. # For applying Regression Algorithm, it is mandatory that there should not be # any Categorial Data in the dataset # Decission Tree and Random Forest Algo can take Categorical Data # Converting your categorical data to Numerical Data is known as Label Encoding # Encoding categorical data from sklearn.preprocessing import LabelEncoder # Create objct of LabelENcoder labelencoder = LabelEncoder() # Fit and Use the operation Transform features[:,0] = labelencoder.fit_transform(features[:,0]) print(features) # Development = 0 # Testing = 1 # UX = 2 # There is a problem in Label Encoding, our algo would understand # that UX has more preference/priority than Testing and Development # or reverse 0 is high priority # So there is a ORDER Generation after Label Encoding # So there should be a solution to fix it # Show One_hot_encoding_colors.png # Calculate the unique values in Column # Create new columns for each unique value # Is your value is equal to Column Name, make it 1 .. others 0 # Show One_hot_encoding_week_days.png # This way of representation of data is known as One Hot Encoding from sklearn.preprocessing import OneHotEncoder # Creation of Object onehotencoder = OneHotEncoder(categorical_features=[0]) # Convert to NDArray format onehotencoder.fit_transform(features).toarray() # OneHotEncoder always puts the encoded values as the first columns # irrespective of the column you are encoding print(features) # Development = 1 0 0 # Testing = 0 1 0 # UX = 0 0 1 # Now sklearn has new way of using Transformer # Pandas has pd.get_dummies(dataset) will directly OneHotEncode your data # Pandas always adds the encoded columns as the last columns # If there is a new column of Qualification which has B.Tech, M.Tech, Ph.D values # Then we DO NOT need to OneHotEncode the column, only Label Encoding is required # Since we do not require to remove the ORDERING issue # If we know the values of first two columns, then can we know the value in third col # That means one column out of three is redundant # And its value is dependent on the other columns # Predictions will be poor if there are redundant columns in dataset # This problem is known as Dummy Variable Trap # We can drop any one column to solve this problem # We should have singularity in the dataset and not have redundancy # Avoiding the Dummy Variable Trap # dropping first column features = features[ : , 1:] # Now our data is ready for Modelling . # Splitting the dataset into the Training set and Test set. from sklearn.model_selection import train_test_split features_train , features_test , labels_train , labels_test = train_test_split(features, labels , test_size=0.2 , random_state=0) # Fitting Multiple Linear Regression to the Training set # Whether we have Univariate or Multivariate, class is LinearRegression from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features_train,labels_train) # Check the value of intercept and slope # y = ax + by + cz + d # Here a, b and c are the coefficients and d is the intercept print(regressor.intercept_) print (regressor.coef_) # we will have 5 values since we have 5 columns (5dimension) # We cannot show a line on a graph as we did for 2D data, since we have 5D data # Predicting the Test set results. labels_pred = regressor.predict(features_test) df = pd.DataFrame({'Actual':labels_test,'Predicted':labels_pred}) print(df) # Prediction for a new values for a person in 'Development', hours worked 1150, # 3 certificates , 4yrs of experience. What would be his salary ?? regressor.predict(['Development',1150,3,4]) x = ['Development',1150,3,4] print(type(x)) x = np.array(x) print(type(x)) print(x.shape) x = x.reshape(1,4) # x.reshape(1,-1) print(x.shape) regressor.predict(x) x = [1,0,0,1150,3,4] x = np.array(x) x = x.reshape(1,4) regressor.predict(x) # Again we will get error # This again throws error, cannot cast array data from float to x32 # Since it requires 5 columns but you are passing only 4 columns # make this according to the data csv format # We need to OneHotEncode the data # Development is replaced by 1,0,0 to 0,0 to remove dummy trap x = [0,0,1150,3,4] x = np.array(x) x = x.reshape(1,5) x = regressor.predict(x) x[0] # 62362.14371687774 # General Way of solving the above problem le = labelencoder.transform(['Development']) print(le) # le = labelencoder.transform(['Testing']) # print(le) # le = labelencoder.transform(['UX']) # print(le) # le = labelencoder.transform(['CSE']) # print(le) ohe = onehotencoder.transform(le.reshape(1,1)).toarray() print(ohe) x = [ohe[0][1],ohe[0][2],1150,3,4] x = np.array(x) x = x.reshape(1, -1) x = regressor.predict(x) x[0] # 62362.14371687774 """ x = np.array(columnTransformer.transform(x), dtype = np.float32) x = x[:,1:] regressor.predict(x) """ # Getting Score for the Multi Linear Reg model Score = regressor.score(features_train, labels_train) Score = regressor.score(features_test, labels_test) """ If the training score is POOR and test score is POOR then its underfitting If the training score is GOOD and test score is POOR then its overfitting """
229bab0555b7768103b620a08459fb99126689b8
Silentsoul04/FTSP_2020
/W3_2020_School/ML Concepts/Machine_Learning_Mean _Median_Mode.py
3,364
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 28 17:32:02 2020 @author: Rajesh """ ''' Machine Learning - Mean Median Mode :- ------------------------------------------ ''' What can we learn from looking at a group of numbers ? In Machine Learning (and in mathematics) there are often three values that interests us: 1) Mean - The average value 2) Median - The mid point value 3) Mode - The most common value Ex :- We have registered the speed of 13 cars. speed = [99,86,87,88,111,86,103,87,94,78,77,85,86] Q1. What is the average, the middle, or the most common speed value ? 1) Mean :- ----------- The mean value is the average value. To calculate the mean, find the sum of all values, and divide the sum by the number of values: (99+86+87+88+111+86+103+87+94+78+77+85+86) / 13 = 89.77 Ex :- Use the NumPy mean() method to find the average speed: import numpy speed = [99,86,87,88,111,86,103,87,94,78,77,85,86] x = numpy.mean(speed) print(x) # 89.76 2) Median :- --------------- The median value is the value in the middle, after you have sorted all the values: 77, 78, 85, 86, 86, 86, 87, 87, 88, 94, 99, 103, 111 It is important that the numbers are sorted before you can find the median. The NumPy module has a method for this: import numpy speed = [99,86,87,88,111,86,103,87,94,78,77,85,86] x = numpy.median(speed) print(x) # 87.0 NOTE :- If there are two numbers in the middle, divide the sum of those numbers by two. 77, 78, 85, 86, 86, 86, 87, 87, 94, 98, 99, 103 (86 + 87) / 2 = 86.5 Ex :- import numpy speed = [99,86,87,88,86,103,87,94,78,77,85,86] x = numpy.median(speed) print(x) # 86.5 3) Mode :- ------------- NOTE :- The Mode value is the value that appears the most number of times. 99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86 = 86 The SciPy module has a method for this. Ex :- Use the SciPy mode() method to find the number that appears the most: from scipy import stats speed = [99,86,87,88,111,86,103,87,94,78,77,85,86] x = stats.mode(speed) print(x) # ModeResult(mode=array([86]), count=array([3])) NOTE :- Now we will take one more example. Ex :- list1 = [10,20,30,40,50] import numpy as np x = np.mean(list1) print('The Mean of List :', x) ------- Result --------- The Mean of List : 30.0 ------------------------------------------------------ Ex :- If we have 5 elements into the list. list1 = [10,20,30,40,50] import numpy as np x = np.median(list1) print('The Median of List :', x) ------- Result --------- The Median of List : 30.0 Ex :- If we have 6 elements into the list. list1 = [10,20,30,40,50,60] import numpy as np x = np.median(list1) print('The Median of List :', x) ------- Result --------- The Median of List : 35.0 ------------------------------------------------------------------ Ex :- If we have 6 elements into the list. list1 = [10,20,30,40,50,60,70,30,99,30,101,30] from scipy import stats x = stats.mode(list1) print('The Mode of List :', x) ------- Result --------- The Mode of List : ModeResult(mode=array([30]), count=array([4])) Ex :- If we have 6 elements into the list. list1 = [10,20,30,40,50,60,70,30,99,30,101,30,30,201,30] from scipy import stats x = stats.mode(list1) print('The Mode of List :', x) ------- Result --------- The Mode of List : ModeResult(mode=array([30]), count=array([6]))
953ebb6e03cbac2798978798127e144ac2eee85f
Silentsoul04/FTSP_2020
/Python_CD6/generator.py
930
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 28 17:46:18 2020 @author: Rajesh """ """ Name: generator Filename: generator.py Problem Statement: This program accepts a sequence of comma separated numbers from user and generates a list and tuple with those numbers. Data: Not required Extension: Not Available Hint: Not Available Algorithm: Not Available Boiler Plate Code: Not Available Sample Input: 2, 4, 7, 8, 9, 12 Sample Output: List : ['2', ' 4', ' 7', ' 8', ' 9', '12'] Tuple : ('2', ' 4', ' 7', ' 8', ' 9', '12') """ " NOTE :- split() function always split the given string and stored the values into list." s = input('Enter some value :').split(',') print('The List :', s) print('The Tuple :', tuple(s)) ############# OR ############### str1 = input('enter any number :').split() print('List :', str1) print('Tuple :', tuple(str1))
12430ff52d75dee8bae34b58f3a5164d585c4ec9
Silentsoul04/FTSP_2020
/Durga OOPs/Nested_Classes_OOPs.py
2,534
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 14 15:37:38 2020 @author: Rajesh """ Nested Classes :- -------------- class Person: def __init__(self): self.name = 'Forsk Coding School' self.dob = self.DOB() def display(self): print('Name :', self.name) self.dob.display() class DOB: def __init__(self): self.dd = 27 self.mm = 4 self.yyyy = 2018 def display(self): print('Date of Birth :{}/{}/{}'.format(self.dd,self.mm,self.yyyy)) p = Person() p.display() *********** Result ************ Name : Forsk Coding School Date of Birth :27/4/2018 --------------------------------------------------------------------------------------------------------- class Person: def __init__(self,name,dd,mm,yyyy): self.name = name self.dob = self.DOB(dd,mm,yyyy) def display(self): print('Name :', self.name) self.dob.display() class DOB: def __init__(self,dd,mm,yyyy): self.dd = dd self.mm = mm self.yyyy = yyyy def display(self): print('Date of Birth :{}/{}/{}'.format(self.dd,self.mm,self.yyyy)) p1 = Person('Rajesh sharma',6,1,2020) p2 = Person('Sandeep Jain',16,6,2019) p3 = Person('Mohit Sharma',8,11,2015) p1.display() p2.display() p3.display() *********** Result ************ Name : Rajesh sharma Date of Birth :6/1/2020 Name : Sandeep Jain Date of Birth :16/6/2019 Name : Mohit Sharma Date of Birth :8/11/2015 ------------------------------------------------------------------------------------------------------------------ class Human: def __init__(self): self.name = 'Forsk coding school' self.head = self.Head() def display(self): print('Name :',self.name) self.head.talk() self.head.brain.think() class Head: def __init__(self): self.brain = self.Brain() def talk(self): print('Talking ........') class Brain: def think(self): print('Thinking .........') h = Human() h.display() *********** Result ************ Name : Forsk coding school Talking ........ Thinking ......... -----------------------------------------------------------------------------------
49942a142abf3432f1fd6c0d651f85c7ebd35894
Silentsoul04/FTSP_2020
/Summer Training ML & DL/Performance_Measurement_8.py
2,892
3.578125
4
# Import the Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # To Import csv file dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\student_scores.csv') dataset.isnull().any(axis=0) # To seggrating the features & lables from dataset. features = dataset.iloc[:,:-1].values labels = dataset.iloc[:,1].values from sklearn.model_selection import train_test_split features_train , features_test , labels_train , labels_test =\ train_test_split(features,labels,test_size=0.2,random_state=41) # Now we apply the Linear Regression. from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features_train,labels_train) labels_pred = regressor.predict(features_test) df = pd.DataFrame({'Actual':labels_test , 'Predicated':labels_pred}) print(df) ----------- Actual Predicated 0 20 15.964757 1 69 74.613283 2 17 11.988585 3 85 77.595411 4 60 55.726469 df.head() ''' Now we will be calculating Performance Measurement ''' # Evaluate the Algorithms. from sklearn import metrics print('Means Absolute Error(MAE) :', metrics.mean_absolute_error(labels_test , labels_pred)) # Means Absolute Error(MAE) : 5.267612082160115 print('Mean Squared Error(MSE) :', metrics.mean_squared_error(labels_test , labels_pred)) # Mean Squared Error(MSE) : 29.199482214072795 print('Root Mean Squared Error(RMSE) :', np.sqrt(metrics.mean_squared_error(labels_test , labels_pred))) # Root Mean Squared Error(RMSE) : 5.403654523937739 print(np.mean(dataset.values[:,1])) # 51.48 # 10% of 51.48 = 5.15 dataset['Scores'].mean() # 51.48 # RMSE < np.mean(labels)*10% # NOTE :- If the above condition satisfy then our Model is correct & prediction also fine. print('R Squared Error(R2 Score):', metrics.r2_score(labels_test , labels_pred)) # R Squared Error(R2 Score): 0.9602706511727539 # NOTE :- Max R2 score is the 1. # In our case we have got 0.96 and it is almost nearest to 1 only. # It is very good model & best model which R2 score is almost nearest by 1. ''' To get the Model Accuracy ''' print(regressor.score(features_test , labels_test)) # 0.96027 print(regressor.score(features_train , labels_train)) # 0.94946 # Underfitting :- training score is poor & test score is also poor. # Overfitting :- training score is Good & test score is poor. # NOTE :- Neither our model should not be the Underfitting nor Overfitting as well. # To fix such issues we have to follow some points like below listed. # In the case of Underfitting we can do one thing that Increase the Training data and then # Obvisouly the Test score will be more the ealier. # In the case of Overfitting there we have some other technique to get the better test score. # We need to apply the Regularazation to avoid Overfitting issue at data. 1) L1 (Lasso) 2) L2 (Ridge) 3) Elastic Net (L1+l2)
2eb8ad52b31fa0d66b3b94d9c5dc007e5e09e472
Silentsoul04/FTSP_2020
/Ritchie Ng Pandas/Changing_datatype_Pandas.py
2,877
3.609375
4
# Changing data type in Pandas :- import pandas as pd url = 'http://bit.ly/drinksbycountry' df = pd.read_csv(url) df.head() df.columns df.dtypes -------------- country object beer_servings int64 spirit_servings int64 wine_servings int64 total_litres_of_pure_alcohol float64 continent object dtype: object # Data type summary 3 integers (int64) 1 floating (float64) 2 objects (object) # Method 1: Change datatype after reading the csv # to change use .astype() df['beer_servings'] = df['beer_servings'].astype(float) df.dtypes -------------- country object beer_servings float64 spirit_servings int64 wine_servings int64 total_litres_of_pure_alcohol float64 continent object dtype: object # Method 2: Change datatype before reading the csv df = pd.read_csv(url , dtype = {'spirit_servings' : float}) df.dtypes ----------- country object beer_servings int64 spirit_servings float64 wine_servings int64 total_litres_of_pure_alcohol float64 continent object dtype: object # Check for this type of DataFrames. url = 'http://bit.ly/chiporders' df = pd.read_csv(url , delimiter = '\t') df.head() df.dtypes order_id int64 quantity int64 item_name object choice_description object item_price object dtype: object df['item_price'].head() print(type('item_price')) # <class 'str'> # The issue here is how pandas don't recognize item_price as # a floating object # we use .str to replace and then convert to float df['item_price'] = df['item_price'].str.replace('$', '') print(type('item_price')) df['quantity'] = df['quantity'].astype(float) df['quantity'].head() ----------------- 0 1.0 1 1.0 2 1.0 3 1.0 4 2.0 Name: quantity, dtype: float64 print(type(df['quantity'])) # <class 'pandas.core.series.Series'> # we can now calculate the mean. df['item_price'] = df['item_price'].str.replace('$', '') df['item_price'].mean() df['item_price'].head() # To find out whether a column's row contains a certain string # by return True or False df['item_name'].str.contains('Chicken').head() ------------------------ 0 False 1 False 2 False 3 False 4 True Name: item_name, dtype: bool # convert to binary value. df['item_name'].str.contains('Chicken').astype(int).head(10) -------------------- 0 0 1 0 2 0 3 0 4 1 5 1 6 0 7 0 8 0 9 0 df['item_name'].str.contains('Chicken').astype(float).head(6) ----------------- 0 0.0 1 0.0 2 0.0 3 0.0 4 1.0 5 1.0 Name: item_name, dtype: float64
bc8e51371dbfeee174a2a9e150a353a46ebb8a38
Silentsoul04/FTSP_2020
/Durga OOPs/Empclass_Obj_ref_variable.py
840
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 10:21:43 2020 @author: Rajesh """ class Employee: '''doc string(description)''' def __init__(self,eno,ename,esal,eaddr): self.eno = eno self.ename = ename self.esal = esal self.eaddr = eaddr def info(self): print('*'*25) print('Employee number :', self.eno) print('Employee name :', self.ename) print('Employee salary :', self.esal) print('Employee address :', self.eaddr) #print('*'*20) e1 = Employee(100,'Rajesh',10000,'sikar') e2 = Employee(200,'sharma',20000,'jaipur') e1.info() e2.info() """ NOTE :- Class ==> Employee. Employee(100,'Rajesh',10000,'sikar') ==> Object. e1 , e2 :- are reference variables. """
325deda4f80c3273ac77a80f9583658c76efbcb3
Silentsoul04/FTSP_2020
/Durga Flow Control/InfiniteLoops_NestedLoops.py
1,461
3.828125
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 24 21:58:06 2020 @author: Rajesh """ ########### Infinite loops ################ i = 1 # while True: while(True): print('Forsk coding school',i) i = i + 1 print('Rajesh sharma') break # It's used to stop the execution of next lines. print('Jaipur Rajasthan , India ') # This line will be never executed coz its already loop has been breaked. ################## Nested Loops ############# # NOTE :- Range always start from 0 to n-1 form. # Nested Loops :- Loops inside the loops are called Nested loops. for i in range(3): # 0 , 1 , 2 => Outer loop for j in range(2): # 0 , 1 => Inner Loop print('Hello') ### output ### """ Hello Hello Hello Hello Hello Hello """ ################## Nested Loops ############# for i in range(3): # 0 , 1 , 2 => Outer loop for j in range(2): # 0 , 1 => Inner Loop print('i = {} , j = {}'.format(i,j)) ### output ### i = 0 , j = 0 i = 0 , j = 1 i = 1 , j = 0 i = 1 , j = 1 i = 2 , j = 0 i = 2 , j = 1
ccfcd60b764c69152a7d8843dc02c197798863bf
Silentsoul04/FTSP_2020
/CodeBasics_Pandas/Handle_Group_By_(Split Apply Combine).py
3,242
4
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 12 15:42:16 2020 @author: Rajesh """ 1) Find maximum temperature at each city. 2) Find avarage wind speed for every city. import pandas as pd import numpy as np df = pd.read_csv('E:\CodeBasics_Pandas\Pandas_CSV_CB\weather_by_cities.csv') df.head() ************* day city temperature windspeed event 0 1/1/2017 new york 32 6 Rain 1 1/2/2017 new york 36 7 Sunny 2 1/3/2017 new york 28 12 Snow 3 1/4/2017 new york 33 7 Sunny 4 1/1/2017 mumbai 90 5 Sunny # Now we will do the groupny() method of pandas. g = df.groupby('city') print(g) # We are using the python Iterator concept here. for city,city_df in g: print(city) print(city_df) ********************* mumbai day city temperature windspeed event 4 1/1/2017 mumbai 90 5 Sunny 5 1/2/2017 mumbai 85 12 Fog 6 1/3/2017 mumbai 87 15 Fog 7 1/4/2017 mumbai 92 5 Rain new york day city temperature windspeed event 0 1/1/2017 new york 32 6 Rain 1 1/2/2017 new york 36 7 Sunny 2 1/3/2017 new york 28 12 Snow 3 1/4/2017 new york 33 7 Sunny paris day city temperature windspeed event 8 1/1/2017 paris 45 20 Sunny 9 1/2/2017 paris 50 13 Cloudy 10 1/3/2017 paris 54 8 Cloudy 11 1/4/2017 paris 42 10 Cloudy # If we want to get the specific data. g.get_group('mumbai') *************** day city temperature windspeed event 4 1/1/2017 mumbai 90 5 Sunny 5 1/2/2017 mumbai 85 12 Fog 6 1/3/2017 mumbai 87 15 Fog 7 1/4/2017 mumbai 92 5 Rain # How to get the maximum Temperature. g.max() ******* day temperature windspeed event city mumbai 1/4/2017 92 15 Sunny new york 1/4/2017 36 12 Sunny paris 1/4/2017 54 20 Sunny # For single city. df[df['city']=='mumbai'].max() ************** day 1/4/2017 city mumbai temperature 92 windspeed 15 event Sunny # To get the mean or average of the cities. g.mean() ******** temperature windspeed city mumbai 88.50 9.25 new york 32.25 8.00 paris 47.75 12.75 # If we want to get the details of the all cities at the same time. g.describe() # It will be working as combine the values. # We can use like this also. df[df['city']=='mumbai'].describe() ****** temperature windspeed count 4.000000 4.000000 mean 88.500000 9.250000 std 3.109126 5.057997 min 85.000000 5.000000 25% 86.500000 5.000000 50% 88.500000 8.500000 75% 90.500000 12.750000 max 92.000000 15.000000 # We will the some the graph here. %matplotlib inline g.plot()
7ad064ce2fc4150f351ef3ce360dd3d7230a34f6
Silentsoul04/FTSP_2020
/Python_CD6/weeks.py
2,024
4.28125
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 22 17:01:28 2020 @author: Rajesh """ """ Name: weeks Filename: weeks.py Problem Statement: Write a program that adds missing days to existing tuple of days Sample Input: ('Monday', 'Wednesday', 'Thursday', 'Saturday') Sample Output: ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') """ t = ('Monday', 'Wednesday', 'Thursday', 'Saturday') l1=list(t) # Now Tuple will be converted into list and then we will be appending some of the values into it. print('The tuple becomes into List : ', l1) l1.append('Tuesday') l1.append('Friday') l1.append('Sunday') print('The List after Adding some missing Items are :', l1) t1 = tuple(l1) sorted(t1) print('The final output will be in Tuple only :', t1) ########### OR ############## tuple = (10,20,30,40,50) type(t) list1 = list(tuple) # Now Tuple will be converted into list and then we will be appending some of the values into it. print(list1) list1.append(100) list1.append(250) list1.append(350) print(list1) for i in list1: list2 = list1.count(i) i+=1 print(list1) list1.index(100) list1.index(30) list1.insert(5,0) list1.insert(0,7) list1.insert(2,450) list1.remove(6) # We need to pass the particular element in list not index number. [ NOT Valid ] list1.remove(0) list1.pop() print(list1) list1.append(7) list1.index(20) list1.pop(3) print(list1) list2 = [] # Empty list. print(list2) # It will be printing empty list. list2.clear() # It is used to clear all the data from the list2. print(list2) list2.extend(list1) # It will be combining both lists each other. list2.append(list1) # It will be combining list2 then whole list1 full without removing [] bracket like single character. list1.sort() list1.reverse() print(type(t)) print(t) print(t[0]) print(t[3]) print(t[-1]) print(t[:2]) t=() # Data type is empty tuple t=(10,) # Single value tuple value always ends with comma ( ,).
313a93ce8a62c64e9697bfdde61f2b38b4280721
Silentsoul04/FTSP_2020
/DataBase Forsk/db_University.py
1,326
3.8125
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 13:31:27 2020 @author: Rajesh """ """ Code Challenge 1 Write a python code to insert records to a sqlite named db_University for 10 students with fields like Student_Name, Student_Age, Student_Roll_no, Student_Branch. """ import sqlite3 from pandas import DataFrame conn = sqlite3.connect('db_University.db') c = conn.cursor() conn.commit() c.execute('DROP TABLE db_University') c.execute("""create table db_University( Student_Name text, Student_Age integer, Student_Roll_no integer, Student_Branch text ) """) conn.commit() c.execute("INSERT INTO db_University VALUES('Rajesh', 25,1001,'CSE')") c.execute("INSERT INTO db_University VALUES('Ravi', 30,1002,'EEE')") c.execute("INSERT INTO db_University VALUES('Gandhi', 35,1002,'Civil')") c.execute("INSERT INTO db_University VALUES('Rahul', 45,1004,'Arch')") c.execute("INSERT INTO db_University VALUES('Kamesh', 55,1005,'CS-IT')") conn.commit() c.execute('select * from db_University') print(c.fetchone()) print(c.fetchmany(2)) print(c.fetchall()) c.execute("SELECT * FROM db_University") df = DataFrame(c.fetchall()) df.columns = ('Student_Name','Student_Age','Student_Roll_no','Student_Branch') conn.close() # print(c.fetchone())
ce643b9df8113ce2ea53623aecf9d548398eea7e
Silentsoul04/FTSP_2020
/Durga Strings Pgms/Words_Str_Reverse.py
299
4.21875
4
# WAP to print the words from string in reverse order and take the input from string. # s='Learning Python is very easy' s=input('Enter some string to reverse :') l=s.split() print(l) l1=l[: :-1] # The Output will be in the form of List. print(l1) output=' '.join(l1) s.count(l1) print(output)
4afacd3477d602c6019875ebeb4451b2d2ae4446
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Without_Random_State_ML.py
3,006
3.96875
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 7 21:52:26 2020 @author: Rajesh """ # Now explain the random state by pring features_test with and without random state set. import numpy as np X,y = np.arange(10).reshape(5,2),list(range(5)) print(type(X)) # <class 'numpy.ndarray'> print(type(y)) # <class 'list'> print(X) [[0 1] [2 3] [4 5] [6 7] [8 9]] print(y) [0, 1, 2, 3, 4] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_label = train_test_split(X,y,test_size=0.33) from sklearn.linear_model import LinearRegression regg = LinearRegression() regg.fit(X_train,y_train) labels_pred = regg.predict(X_test) import pandas as pd df = pd.DataFrame({'Actual':y_label,'Predicaated':labels_pred}) print(df) ********* Result *********** Actual Predicaated 0 3 3.0 1 2 2.0 ----------------------------------------------------------------------------------------------------------- # If you use random_state=some_number, # then you can guarantee that your split will be always the same. # This is useful if you want reproducible results, # I would say, set the random_state to some fixed number while you test stuff, # but then remove it in production if you need a random (and not a fixed) split. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) print (X_train) [[4 5] [0 1] [6 7]] print (X_test) [[2 3] [8 9]] print (y_train) [2, 0, 3] print (y_test) [1, 4] from sklearn.linear_model import LinearRegression regg = LinearRegression() regg.fit(X_train,y_train) labels_pred = regg.predict(X_test) import pandas as pd df = pd.DataFrame({'Actual':y_label,'Predicaated':labels_pred}) print(df) ********* Result *********** Actual Predicaated 0 3 1.0 1 2 4.0 -------------------------------------------------------------------------------------------------------------- # This result would be different from last one, but if you run it again and again it will be same from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=100) print (X_train) print (X_test) print (y_train) print (y_test) from sklearn.linear_model import LinearRegression regg = LinearRegression() regg.fit(X_train,y_train) labels_pred = regg.predict(X_test) import pandas as pd df = pd.DataFrame({'Actual':y_label,'Predicaated':labels_pred}) print(df) ********* Result *********** Actual Predicaated 0 3 1.0 1 2 2.0 ------------------------------------------------------------------------------------- # Model accuracy print (regg.score(X_test, y_test)) # 1.0 print (regg.score(X_train, y_train)) # 1.0 # Now lets talk about two terms - overfitting and underfitting the data # Do we have case of underfitting? # Do we have case of overfitting?
76c8230dd98a70bb2c742a6efcdcbf5a4d842940
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Student_Details_ML1.py
1,237
3.78125
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 6 16:27:43 2020 @author: Rajesh """ # Now if I want to get 100 Scores.(features=which is given in the question) # How much hours do i need to study.(Labels=which we need to find out ?) # Reverse the features and labels and try the model and prediction again # You might need to reshape the features by features = featurtes.reshape(25,1) # Now regressor.predict(100) import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\student_scores.csv') labels = dataset.iloc[:,-2].values features = dataset.iloc[:,1].values features=features.reshape(25,1) from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features,labels) print(regressor.coef_) print(regressor.intercept_) print (regressor.coef_*(100) + regressor.intercept_) print(regressor.predict([[100]])) # Visualising the results plt.scatter(features, labels, color = 'red') plt.plot(features, regressor.predict(features), color = 'blue') plt.title('Study Hours and Exam Score') plt.xlabel('Exam Score: Marks') plt.ylabel('Study Hours') plt.savefig('E:\Mechine Learning Forsk\Student4.jpg') plt.show()
38587606ca1f9e5f6e553e319b41b633feddd966
Silentsoul04/FTSP_2020
/CodeBasics_Pandas/Handle_Missing_Data_replace()_function.py
3,832
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 12 13:21:35 2020 @author: Rajesh """ import pandas as pd import numpy as np dataset = pd.read_csv('E:\CodeBasics_Pandas\Pandas_CSV_CB\weather_data.csv') dataset.head() **************** day temperature windspeed event 0 1/1/2017 32 6 Rain 1 1/2/2017 -99999 7 Sunny 2 1/3/2017 28 -99999 Snow 3 1/4/2017 -99999 7 0 4 1/5/2017 32 -99999 Rain # NOTE :- It takes always 2 parameters like old to new value. df = dataset.replace(-99999,np.NaN) df.head() ************ day temperature windspeed event 0 1/1/2017 32.0 6.0 Rain 1 1/2/2017 NaN 7.0 Sunny 2 1/3/2017 28.0 NaN Snow 3 1/4/2017 NaN 7.0 0 4 1/5/2017 32.0 NaN Rain # NOTE :- If there are more the one values and we need to replace the NaN then we will put # all the values into the list and replace with NaN and it will work it easily. # like : df = dataset.replace([-99999,-88888] ,np.NaN) NOTE :- If we want to replace the values for the specific columns like. NOTE :- For that we need to use the Dictionary concept. df = dataset.replace({'temperature':-99999, 'windspeed':-99999, 'event':'0' }, np.NaN) df.head() ************ day temperature windspeed event 0 1/1/2017 32.0 6.0 Rain 1 1/2/2017 NaN 7.0 Sunny 2 1/3/2017 28.0 NaN Snow 3 1/4/2017 NaN 7.0 NaN 4 1/5/2017 32.0 NaN Rain # If we want to change the -99999 values to NaN & 'No Event' as 'Sunny'. df = dataset.replace({-99999:np.NaN, 'No Event':'sunny' }) df.head() ************** day temperature windspeed event 0 1/1/2017 32.0 6.0 Rain 1 1/2/2017 NaN 7.0 Sunny 2 1/3/2017 28.0 NaN Snow 3 1/4/2017 NaN 7.0 sunny 4 1/5/2017 32.0 NaN Rain NOTE :- For an example our dataset contains the temeperature like 32F , 32C , windspeed like 6mph , 7mph and etc and we just want to replace the charaters from the dataset then we will for concept like Regex experssion. dataset.head() ********************* day temperature windspeed event 0 1/1/2017 32F 6mph Rain 1 1/2/2017 -99999 7mph Sunny 2 1/3/2017 28 -99999 Snow 3 1/4/2017 -99999 7 No Event 4 1/5/2017 32C -99999 Rain df = dataset.replace('[A-Za-z]','',regex=True) # It will work but it will remove all the values from event col. df.head() # Here we will be using the Dictionary Concept like. df = dataset.replace({'temperature':'[A-Za-z]', 'windspeed':'[A-Za-z]'}, '', regex=True) df.head() **************** day temperature windspeed event 0 1/1/2017 32 6 Rain 1 1/2/2017 -99999 7 Sunny 2 1/3/2017 28 -99999 Snow 3 1/4/2017 -99999 7 No Event 4 1/5/2017 32 -99999 Rain NOTE :- Replacing list with another list:- ----------------------------------------- df = pd.DataFrame({ 'score': ['exceptional','average', 'good', 'poor', 'average', 'exceptional'], 'student': ['rob', 'maya', 'parthiv', 'tom', 'julian', 'erica'] }) df ********** score student 0 exceptional rob 1 average maya 2 good parthiv 3 poor tom 4 average julian 5 exceptional erica df = df.replace(['poor', 'average','good','exceptional'],[1,2,3,4]) df *********** score student 0 4 rob 1 2 maya 2 3 parthiv 3 1 tom 4 2 julian 5 4 erica
899db6e84ffad7514dbac57c7da77d04d78acb70
Silentsoul04/FTSP_2020
/Python_CD6/pangram.py
1,480
4.3125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 17:37:41 2020 @author: Rajesh """ """ Name: Pangram Filename: pangram.py Problem Statement: Write a Python function to check whether a string is PANGRAM or not Take input from User and give the output as PANGRAM or NOT PANGRAM. Hint: Pangrams are words or sentences containing every letter of the alphabet at least once. For example: "the quick brown fox jumps over the lazy dog" is a PANGRAM. Sample Input: The five boxing wizards jumps. Sphinx of black quartz, judge my vow. The jay, pig, fox, zebra and my wolves quack! Pack my box with five dozen liquor jugs. Sample Output: NOT PANGRAM PANGRAM PANGRAM PANGRAM """ s = input('Enter any string :') def Pangram(): str1 = 'abcdefghijklmnopqrstuvwxyz' for i in str1: if i in s: if i == str1[-1]: print('PANGRAM') else: print('NOT PANGRAM') break Pangram() #################### OR ########################### str1 = 'abcdefghijklmnopqrstuvwxyz' inp = input(">>") inpp = inp.split() d = "".join(inpp) x = sorted(d) z= set(x) x = list(z) x1 = sorted(x) z = "".join(x1) if z == str1: print("pangram") else: print("not pangram")
a494f9441b74e00203c782305b3f10324785260d
Silentsoul04/FTSP_2020
/Ritchie Ng Pandas/Using_String_Methods_Pandas.py
3,816
4.4375
4
# Using String Methods in Pandas :- # convert string to uppercase in Python s1 = 'hello'.upper() print(s1) # 'HELLO' Q.1. How about string methods in pandas? Answer :- There are many! import pandas as pd url = 'http://bit.ly/chiporders' df = pd.read_csv(url , delimiter = '\t') df.head() df.columns -------------- Index(['order_id', 'quantity', 'item_name', 'choice_description', 'item_price'], dtype='object') df['item_name'].head() ----------------- 0 Chips and Fresh Tomato Salsa 1 Izze 2 Nantucket Nectar 3 Chips and Tomatillo-Green Chili Salsa 4 Chicken Bowl Name: item_name, dtype: object # Making the item_name uppercase. df['item_name'].str.upper().head() ------------------------ 0 CHIPS AND FRESH TOMATO SALSA 1 IZZE 2 NANTUCKET NECTAR 3 CHIPS AND TOMATILLO-GREEN CHILI SALSA 4 CHICKEN BOWL Name: item_name, dtype: object # you can overwrite with the following code. df['item_name'] = df['item_name'].str.upper().head() df['item_name'] df['item_name'].head(10) # Check presence of substring # This is useful to filter data df['item_name'].str.contains('Chicken').head() --------------- 0 False 1 False 2 False 3 False 4 True Name: item_name, dtype: bool # Chain string methods # replacing elements df['choice_description'].head() --------------------- 0 NaN 1 [Clementine] 2 [Apple] 3 NaN 4 [Tomatillo-Red Chili Salsa (Hot), [Black Beans... Name: choice_description, dtype: object df['choice_description'].str.replace('[' , '').head() -------------------------- 0 NaN 1 Clementine] 2 Apple] 3 NaN 4 Tomatillo-Red Chili Salsa (Hot), Black Beans, ... Name: choice_description, dtype: object # chain string methods. df['choice_description'].str.replace('[' , '').str.replace(']','').head() ---------------------------- 0 NaN 1 Clementine 2 Apple 3 NaN 4 Tomatillo-Red Chili Salsa (Hot), Black Beans, ... Name: choice_description, dtype: object # Using regex to simplify the code above. df['choice_description'].str.replace('[\[\]]' , '').head() -------------------- 0 NaN 1 Clementine 2 Apple 3 NaN 4 Tomatillo-Red Chili Salsa (Hot), Black Beans, ... Name: choice_description, dtype: object df.columns df['item_price'].head() -------------------- 0 $2.39 1 $3.39 2 $3.39 3 $2.39 4 $16.98 Name: item_price, dtype: object # Remove the $ and Put INR Symobl. df['item_price'].str.replace('$' , 'INR ').head() ----------------- 0 INR 2.39 1 INR 3.39 2 INR 3.39 3 INR 2.39 4 INR 16.98 Name: item_price, dtype: object df['quantity'].head() for qty in df['quantity'].head(): print(qty) 1 1 1 1 2 for index,qty in df['quantity'].items(): print(index,qty) df.count()['quantity'] # 4622 ------------------------------------------------------------------ list1 = [10,20,30,40,50,'Rajesh','forsk'] for i in list1: print(i)
8ee60a4dcca73c9d5ffa1ca30acc3132ccd6af7c
Silentsoul04/FTSP_2020
/CodeBasics_Pandas/Matplotlib_CB/Axes_labels_Legend_Grid_Matplotlib.py
974
3.828125
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 15:25:58 2020 @author: Rajesh """ ''' Axes labels, Legend, Grid :- --------------------------- ''' import matplotlib.pyplot as plt days = [1,2,3,4,5,6,7] max_t = [45,56,50,35,47,35,40] min_t = [25,30,40,42,48,50,52] avg_t = [10,25,15,22,31,45,44] plt.plot(days,max_t) plt.plot(days,min_t) plt.plot(days,avg_t) plt.xlabel('Days') plt.ylabel('Temperature') plt.title('Weather') plt.legend() plt.show() # For the legend we just need to set the labels values to the particular rows. plt.plot(days,max_t ,label='Max') plt.plot(days,min_t , label='Min') plt.plot(days,avg_t , label='Average') plt.xlabel('Days') plt.ylabel('Temperature') plt.title('Weather') plt.legend() #plt.show() # If we want to set the Legend location then we can use the legend function. # plt.legend(loc='upper right') # plt.legend(loc='best') # loc= 'Best' is the default. plt.legend(loc='Best' , shadow=True , fontsize='small') plt.grid()
efa52f8382abeeadecad3fd2e63983fcda0800ce
Silentsoul04/FTSP_2020
/Durga OOPs/Python_Variables.py
5,003
4.3125
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 22:28:43 2020 @author: Rajesh """ Inside Python class 3 types of variables :- ---------------------------------------- 1) Instance variables / Object level variables. Ex :- class student: def __init__(self,name,rollno): print('Constructor will be executed') self.name = name self.rollno = rollno # Object level variables def display(self): print('Method will be executed') print('Hello My Name is :', self.name) print('My rollno is :', self.rollno) s1 = student('Rajesh',1001) s2 = student('Kamesh',1002) s3 = student('Mohit',1003) s1.display() s2.display() s3.display() ------------------------------------------------------------------------------ 2) static variables / class level variables :- Ex :- class student: cname = 'DURGASOFT' # class level variable and declared with in class only. def __init__(self,name,rollno): print('Constructor will be executed') self.name = name self.rollno = rollno def display(self): print('Method will be executed') print('Hello My Name is :', self.name) print('My rollno is :', self.rollno) s1 = student('Rajesh',1001) s2 = student('Kamesh',1002) s3 = student('Mohit',1003) print(s3.cname) print(s2.cname) print(s1.cname) s1.display() s2.display() s3.display() print(id(s1)) print(id(s2)) print(id(s3)) print(id('cname')) ------------------------------------------------------------------------------ 3) Local variables :- Ex :- class student: def __init__(self,name,rollno): print('Constructor will be executed') count=0 # Local variables. self.name = name self.rollno = rollno def display(self): x = 10 # Local variables. print('Method will be executed') print('Hello My Name is :', self.name) print('My rollno is :', self.rollno) s1 = student('Rajesh',1001) s2 = student('Kamesh',1002) s3 = student('Mohit',1003) NOTE :- Local variables are declared inside the constructor or method and accessed within the constructor and method itself and we can't accessed outside of it. --------------------------------------------------------------------------- Inside Python class 3 types of Methods :- ---------------------------------------- 1) Instance method / object related methods :- To Access the instance variables inside the method, we need the self variable and then we can called as this kind of method as instance method. where we are using the instance variables such kind of method is called instance or object related methods. Ex :- class student: cname = 'DURGASOFT' # Class level variable def __init__(self,name,rollno): self.name = name self.rollno = rollno def display(self): print('Hello My Name is :', self.name) print('My rollno is :', self.rollno) @classmethod def getCollegeName(cls): print('The College Name :', cls.cname) @staticmethod def findAverage(x,y): print('The Average :', (x+y)/2) s1 = student('Rahul',501) s2 = student('Yogi',502) s3 = student('Mohit',503) s1.display() s2.display() s3.display() student.getCollegeName() # DURGASOFT s1.getCollegeName() # DURGASOFT s1 = student('Rahul',501) s1.findAverage(10,20) student.findAverage(30,40) ----------------------------------------------------------------------------- 2) Class method :- Ex :- class student: cname = 'DURGASOFT' # Class level variable def __init__(self,name,rollno): self.name = name self.rollno = rollno def display(self): print('Hello My Name is :', self.name) print('My rollno is :', self.rollno) @classmethod def getCollegeName(cls): print('The College Name :', cls.cname) s1 = student('Rahul',501) s2 = student('Yogi',502) s3 = student('Mohit',503) s1.display() s2.display() s3.display() student.getCollegeName() # DURGASOFT s1.getCollegeName() # DURGASOF ----------------------------------------------------------------------------- 3) static method :- Ex :- class student: def __init__(self,name,rollno): self.name = name self.rollno = rollno def display(self): print('Hello My Name is :', self.name) print('My rollno is :', self.rollno) @staticmethod def findAverage(x,y): print('The Average :', (x+y)/2) s1 = student('Rahul',501) s2 = student('Yogi',502) s3 = student('Mohit',503) s1.display() s2.display() s3.display() s1.findAverage(10,20) student.findAverage(30,40) NOTE :- If we are calling without using static method in any function then we should use class name for the accessing the methods.:
4056e210dfddbe7b6b416e80b816f4d1754328a6
Silentsoul04/FTSP_2020
/Mechine Learning Forsk/Language_Growth_Year.py
1,199
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 6 10:41:02 2020 @author: Rajesh """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('E:\ML Code Challenges\ML CSV Files\Lanuages_growth_Year.csv') print(dataset) features = dataset.iloc[:, :1].values # It ontains rows & Columns in syntax. labels = dataset.iloc[:,-1].values """ Now use a LinearRegression algorithm to train the model now """ from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features,labels) print(regressor.intercept_) # -15463.54545454546 print(regressor.coef_) # [7.69090909] # what would be prediction of score if someone studies 2026 Year. # y = (m)x + (c) where m is the slope and c is the inetrcept. print(regressor.coef_*(2026) + regressor.intercept_) # [118.23636364] # This can also be predicted using a function print(regressor.predict([[2026]])) # [118.23636364] # Visualising the results plt.scatter(features, labels, color = 'Blue') plt.plot(features, regressor.predict(features), color = 'Green') plt.title('Lanuages growth Year') plt.xlabel('Years') plt.ylabel('Percentage') plt.show()
5538f10eb0dacb1ef813af17e263058bbda4a950
Silentsoul04/FTSP_2020
/Knowledge Shelf/KS_Machine_Learning_2020/Homeprices.csv_SLR.py
2,443
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 8 17:32:49 2020 @author: Rajesh """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('E:\Knowledge Shelf\KS_Machine_Learning_2020\ML_CSV\homeprices.csv') dataset.head() ********* area price 0 2600 550000 1 3000 565000 2 3200 610000 3 3600 680000 4 4000 725000 features = dataset.iloc[:,:1].values labels = dataset.iloc[:,[1]].values plt.scatter(features,labels,color='Blue') plt.xlabel('Area (Sqft)') plt.ylabel('Price (U$)') plt.title('New House Price Pridiction Graph') #plt.savefig('path') plt.show() # Now we will apply the SLR algorithm. from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features,labels) # Now we will predict the Area = 3300 & what will be the price of new House ? x = regressor.predict([[3300]]) x[0] # 628715.75342466 # We know that straight Line Equation # y = mx+c # where m = slope , c = Intercept. print('The Slope(m) :', regressor.coef_) # The Slope(m) : [[135.78767123]] print('The Intercept(c) :', regressor.intercept_) # The Intercept(c) : [180616.43835616] y = (135.78767123*3300)+(180616.43835616) print(y) # 628715.75341516 # Now we will predict the Area = 5000 & what will be the price of new House ? x = regressor.predict([[5000]]) # [859554.79452055 ----------------------------------------------------------------------------------------------- dataset = pd.read_csv(r'E:\Knowledge Shelf\KS_Machine_Learning_2020\ML_CSV\areas.csv') dataset.head() ******* area 0 1000 1 1500 2 2300 3 3540 4 4120 p = regressor.predict(dataset) # Now we will add new column to dataset like Prices. dataset['Prices'] = p dataset.head() ************ area Prices 0 1000 316404.109589 1 1500 384297.945205 2 2300 492928.082192 3 3540 661304.794521 4 4120 740061.643836 dataset.to_csv('E:\Knowledge Shelf\KS_Machine_Learning_2020\ML_CSV\Price_Predictions.csv' , index = False) print(dataset) # Here index = False Means earlier it was giving the Default Index also bit now it will remove it. # Now we will plot the graph. features = dataset.iloc[:,:1].values labels = dataset.iloc[:,[1]].values plt.scatter(features,labels,color='Blue') plt.xlabel('Area') plt.ylabel('Price') plt.title('New House Price Pridiction Graph') plt.plot(features,regressor.predict(features),color='Red') #plt.savefig('path') plt.show()
83597aff81e13fd2b6aa4f510e64b208ef058d10
Silentsoul04/FTSP_2020
/Knowledge Shelf/Rank()_Method_Pandas_6.py
6,870
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 30 12:56:35 2020 @author: Rajesh """ """ Rank Method in Pandas :- --------------------- """ import pandas as pd nba = pd.read_csv(r'E:\Knowledge Shelf\csv Files\nba.csv') # To check the Nan into the dataset we can check like this. # It shows the all Nan values into dataset from top 5 from upper side & Last 5 from down side. nba.head() nba.tail() nba.shape # (458, 9) # Here we will drop all those values which are Nan into Dataset. nba.dropna(how = 'all' , inplace = True) nba.shape # (457, 9) # It will work as same as the below line only like Inplace = True nba['Salary'] = nba['Salary'].fillna(0) nba['Salary'].fillna(0 , inplace = True) print(type(nba['Salary'])) # <class 'pandas.core.series.Series'> # We want to convert salaries into Integer Type. nba['Salary'] = nba['Salary'].fillna(0).astype(int) nba['Salary'] nba['Salary'].rank(ascending = False).astype(int) # Here astype(int) or astype('int') both will work it. nba['Salary_Rank'] = nba['Salary'].rank(ascending = False).astype(int) nba.sort_values(by='Salary' , ascending = False , inplace = True) nba.head() Salary Salary_Rank 25000000.0 1 22970500.0 2 22875000.0 3 22359364.0 4 22192730.0 5 ---------------------------------------------------------------------------------------------------------- """ Filtering Dataframe in Pandas :- ----------------------------- """ import pandas as pd df = pd.read_csv('E:\Knowledge Shelf\csv Files\employees.csv') df.head() df.info() # It contains lots of information but some times it will be wrong information and Wasting of m/y. ******************* <class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 8 columns): First Name 933 non-null object Gender 855 non-null object Start Date 1000 non-null object Last Login Time 1000 non-null object Salary 1000 non-null int64 Bonus % 1000 non-null float64 Senior Management 933 non-null object Team 957 non-null object dtypes: float64(1), int64(1), object(6) memory usage: 62.6+ KB df['Start Date'].head() **************************** 0 8/6/1993 1 3/31/1996 2 4/23/1993 3 3/4/2005 4 1/24/1998 Name: Start Date, dtype: object pd.to_datetime(df['Start Date']).head() **************************** 0 1993-08-06 1 1996-03-31 2 1993-04-23 3 2005-03-04 4 1998-01-24 Name: Start Date, dtype: datetime64[ns] df['Start Date'] = pd.to_datetime(df['Start Date']) df['Last Login Time'].head() # This is not object coz it is numbers. ********************************* 0 12:42 PM 1 6:53 AM 2 11:17 AM 3 1:00 PM 4 4:47 PM Name: Last Login Time, dtype: object df['Last Login Time'] = pd.to_datetime(df['Last Login Time']) df['Senior Management'].head() # This is not object coz it is Boolean values. ********************************* 0 True 1 True 2 False 3 True 4 True Name: Senior Management, dtype: object df['Senior Management'] = df['Senior Management'].astype(bool) # .astype('bool') df['Senior Management'].head() ********************************** 0 True 1 True 2 False 3 True 4 True Name: Senior Management, dtype: bool df['Gender'].head() ************************** 0 Male 1 Male 2 Female 3 Male 4 Male Name: Gender, dtype: object df['Gender'] = df['Gender'].astype('category') df['Gender'].head() ************************ 0 Male 1 Male 2 Female 3 Male 4 Male Name: Gender, dtype: category Categories (2, object): [Female, Male] df.info() ******************** <class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 8 columns): First Name 933 non-null object Gender 855 non-null category Start Date 5 non-null datetime64[ns] Last Login Time 1000 non-null datetime64[ns] Salary 1000 non-null int64 Bonus % 1000 non-null float64 Senior Management 1000 non-null bool Team 957 non-null object dtypes: bool(1), category(1), datetime64[ns](2), float64(1), int64(1), object(2) memory usage: 49.0+ KB NOTE :- We can see that the total difference b/w print(49.0/62.6) # 0.78 -------------------------------------------------------------------------------------------- NOTE :- All these above operations we can perform like this also. import pandas as pd df = pd.read_csv('E:\Knowledge Shelf\csv Files\employees.csv' , parse_dates = ['Start Date','Last Login Time']) df['Senior Management'] = df['Senior Management'].astype('bool') df['Gender'] = df['Gender'].astype('category') df.head() df.info() *************** <class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 8 columns): First Name 933 non-null object Gender 855 non-null category Start Date 1000 non-null datetime64[ns] Last Login Time 1000 non-null datetime64[ns] Salary 1000 non-null int64 Bonus % 1000 non-null float64 Senior Management 1000 non-null bool Team 957 non-null object dtypes: bool(1), category(1), datetime64[ns](2), float64(1), int64(1), object(2) memory usage: 49.0+ KB -------------------------------------------------------------------------------------------------------- """ Filtering a Dataframe Based on a Condition :- ----------------------------------------------- """ import pandas as pd df = pd.read_csv('E:\Knowledge Shelf\csv Files\employees.csv') df['Gender'] == 'Male' df[df['Gender'] == 'Male'].shape # (424, 8) df['Team'] == 'Finance' df[df['Team'] == 'Finance'].shape # (102, 8) NOTE :- The above task you can also performed like this also. mask = df['Team'] == 'Finance' df[mask] df[mask].head() # Here in the senior Management we have already values are True & False condition. df[df['Senior Management'] == True] df[df['Senior Management'] == False] NOTE :- To find the employees details those are not working into Marketing Team. df['Team'] != 'Marketing' df[df['Team']!= 'Marketing'] df[df['Team'] != 'Marketing'].shape # (902, 8) df[df['Team'] != 'Marketing'].head() df['Salary'] > 110000 df[df['Salary'] > 110000].shape # (322, 8) df[df['Salary'] > 110000].head(10).count() df[df['Salary'] > 110000].count() *********************************************** First Name 295 Gender 282 Start Date 322 Last Login Time 322 Salary 322 Bonus % 322 Senior Management 295 Team 306 df[df['Bonus %'] < 1.5].shape # (28, 8) mask = df['Start Date'] < '1985-01-01' df[mask].head() df[mask].shape # (332, 8)
54205a92ca861e9bdd76fdac6fa291e3dafa3efb
Silentsoul04/FTSP_2020
/Knowledge Shelf/Pandas_1.py
4,204
3.703125
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 27 22:46:52 2020 @author: Rajesh """ import pandas as pd dataset = pd.read_csv('E:/Knowledge Shelf/csv Files/Salary_Classification.csv' , squeeze = True) print(dataset) dataset.head() ********************* Department WorkedHours Certification YearsExperience Salary 0 Development 2300 0 1.1 39343 1 Testing 2100 1 1.3 46205 2 Development 2104 2 1.5 37731 3 UX 1200 1 2.0 43525 4 Testing 1254 2 2.2 39891 dataset.count() *********************** Department 30 WorkedHours 30 Certification 30 YearsExperience 30 Salary 30 dtype: int64 len(dataset) # 30 ; NOTE :- It is almost same like count() function but it shows over all length of every row. dataset.sum() ************************ Department DevelopmentTestingDevelopmentUXTestingUXDevelo... WorkedHours 51425 Certification 62 YearsExperience 159.4 Salary 2280090 dataset.mean() ************* WorkedHours 1714.166667 Certification 2.066667 YearsExperience 5.313333 Salary 76003.000000 dtype: float64 (dataset.sum())/( dataset.count()) ****************************************** WorkedHours 1714.166667 Certification 2.066667 YearsExperience 5.313333 Salary 76003.000000 dataset.std() ****************************************** WorkedHours 480.554068 Certification 1.112107 YearsExperience 2.837888 Salary 27414.429785 dataset.min() ****************************************** Department Development WorkedHours 1000 Certification 0 YearsExperience 1.1 Salary 37731 dataset.max() ****************************************** Department UX WorkedHours 3000 Certification 4 YearsExperience 10.5 Salary 122391 dataset['Salary'].min() # 37731 dataset['Salary'].max() # 122391 dataset.median() ********************* WorkedHours 1520.0 Certification 2.0 YearsExperience 4.7 Salary 65237.0 ---------------------------------------------------------------------------------------------- """ .idxmax(), .idxmin() Methods in Pandas :- -------------------------------------- """ import pandas as pd dataset = pd.read_csv('E:/Knowledge Shelf/csv Files/Salary_Classification.csv') # print(dataset) dataset.head() ********************* Department WorkedHours Certification YearsExperience Salary 0 Development 2300 0 1.1 39343 1 Testing 2100 1 1.3 46205 2 Development 2104 2 1.5 37731 3 UX 1200 1 2.0 43525 4 Testing 1254 2 2.2 39891 NOTE :- If we are using squeeze = True , or not but there will be the same result as earlier. dataset.max() ********************* Department UX WorkedHours 3000 Certification 4 YearsExperience 10.5 Salary 122391 dataset.min() ************************ Department Development WorkedHours 1000 Certification 0 YearsExperience 1.1 Salary 37731 dataset['Salary'].idxmax() # 28 dataset['Salary'].idxmin() # 2 dataset['Salary'][28] # 122391 dataset['Salary'][2] # 37731 dataset['Certification'].idxmax() # 22 dataset['Certification'].idxmin() # 0 dataset['Certification'][22] # 4 dataset['Certification'][0] # 0 NOTE :- Here we can use these above codes like this also. dataset['Certification'][dataset['Certification'].idxmax()] # 4 dataset['Salary'][dataset['Salary'].idxmax()] # 122391
891bcde12d8917ffac1788ed28133d8eece93122
Jan428/NYU-Introduction-To-Python-Jeffrey-An
/umbrella.py
155
4.28125
4
rain = input("Is it raining? Yes or No? \n") if rain == 'yes' or 'Yes': print('You need an umbrella!') else: print('You do not need an umbrella')
4c0f5aae4f560c37d452179d2aae905659729d96
rmeji1/Python
/Homework - Animals/Animals.py
1,417
4.0625
4
class Animal: """A simple animal class""" def __init__(self,name): elephant=("I have exceptional memory", "I am the largest land-living mammal in the world", "I can swim and use my trunk to brathe like a snorkel."); tiger=("I am the biggest cat", "I come in black and white or orange and black", "We are good swimmers and can swim up to 6 kilometres"); bat=("We are the only flying mamals", "I can live for a long time.", "I use echo-location"); self.animal_name = name; self.facts = {"elephant":elephant, "tiger":tiger,"bat":bat} def guess_who_am_i(self): temp = self.facts[self.animal_name] ; tries = 0 ; for fact in temp: print(fact); attempted_answer = input("Who am I? "); if attempted_answer == self.animal_name: print("You got it! I am a", self.animal_name); break ; else: tries = tries + 1 ; if tries == 3: print("I'm out of hints! The answer is", self.animal_name) else: print("Nope, try again"); continue ; e = Animal("elephant") t = Animal("tiger") b = Animal("bat") e.guess_who_am_i() t.guess_who_am_i() b.guess_who_am_i()
f64663726ed78fc680fbae42072d81360c319cb1
Sandibintara/Pertemuan6
/lab1.1.py
445
3.546875
4
# lab 1 ( Penggunaan {end=}) print('A', end='') print('B', end='') print('C', end='') print() print('x') print('Y') print('Z') # Sparator / Penghubung sep= # Deklarasi variabel beserta nilainya w, x, y, z = 10, 15, 20, 25 # Menampilkan tiap hasil variable print(w, x, y, z) # Penulisan pengunaan sparator print(w, x, y, z, sep=' ') print(w, x, y, z, sep=',') print(w, x, y, z, sep=';') print(w, x, y, z, sep=':') print(w, x, y, z, sep='----')
51f6c00289ce747ec14d8a0e6886eed7f45d0e36
Luckercorgi240/python_codes
/Chapter13/paddleball.py
4,647
3.875
4
from tkinter import * import random import time def RepresentsInt(s): try: int(s) return True except ValueError: return False speed = input('How fast do you want the ball to be? (between 1 and 5)') while RepresentsInt(speed) != True or int(speed) < 0 or int(speed) > 5: print('Your number is either not a number or is out of range. Please try again with a different number') speed = input('How fast do you want the ball to be? (between 1 and 5)') speed = int(speed) # speed = input('How fast do you want the ball to be? (between 1 and 5) ') # while RepresentsInt(speed) != True: # print('Please enter a number') # speed = input('How fast do you want the ball to be? (between 1 and 5) ') # while int(speed) < 0 or int(speed) > 5: # print('Your speed is too fast or too slow please change') # speed = input('How fast do you want the ball to be? (between 1 and 5) ') # while RepresentsInt(speed) != True: # print('Please enter a number') # speed = input('How fast do you want the ball to be? (between 1 and 5) ') # speed = int(speed) class Ball: def __init__(self, canvas, paddle, color, speed): self.canvas = canvas self.paddle = paddle self.id = canvas.create_oval(10, 10, 25, 25, fill=color) self.canvas.move(self.id, 245, 100) starts = [-3, -2, -1, 1, 2, 3] random.shuffle(starts) self.x = starts[0] self.y = starts[4] # self.y = speed # self.x = speed self.canvas_height = self.canvas.winfo_height() self.canvas_width = self.canvas.winfo_width() self.hit_bottom = False self.speed = speed self.score = 0 def hit_paddle(self, pos): paddle_pos = self.canvas.coords(self.paddle.id) if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]: if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]: return True return False def draw(self): self.canvas.move(self.id, self.x, self.y) pos = self.canvas.coords(self.id) if pos[1] <= 0: self.y = self.speed # self.speed = self.speed + 1 if pos[3] >= self.canvas_height: self.y = -self.speed # self.speed = self.speed + 1 if pos[3] >= self.canvas_height: self.hit_bottom = True if self.hit_paddle(pos) == True: self.y = -self.speed self.score = self.score + 10 # self.speed = self.speed + 1 if pos[0] <= 0: self.x = self.speed # self.speed = self.speed + 1 if pos[2] >= self.canvas_width: self.x = -self.speed # self.speed = self.speed + 1 class Paddle: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color) self.canvas.move(self.id, 200, 300) self.x = 0 self.canvas_width = self.canvas.winfo_width() self.canvas.bind_all('<KeyPress-Left>', self.turn_left) self.canvas.bind_all('<KeyPress-Right>', self.turn_right) def draw(self): self.canvas.move(self.id, self.x, 0) pos = self.canvas.coords(self.id) if pos[0] <= 0: self.x = 0 elif pos[2] >= self.canvas_width: self.x = 0 def turn_left(self, evt): self.x = -5 def turn_right(self, evt): self.x = 5 tk = Tk() tk.resizable(0, 0) tk.wm_attributes("-topmost", 1) canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) tk.title('Game') canvas.pack() tk.update() color = input('What color do you want the ball to be? ') # color2 = input('What color do you want the ball to be? ') # color3 = input('What color do you want the ball to be?') paddle = Paddle(canvas, 'blue') ball1 = Ball(canvas, paddle, color, speed) # ball2 = Ball(canvas, paddle, color2, speed) # ball3 = Ball(canvas, paddle, color3, speed) time.sleep(3) previous_text_id = 0 while 1: if ball1.hit_bottom == False: #and ball2.hit_bottom == False and ball3.hit_bottom == False: ball1.draw() # ball2.draw() # ball3.draw() paddle.draw() score = str(ball1.score) if previous_text_id != 0: canvas.delete(previous_text_id) text_id = canvas.create_text(390, 10, text=score, font=('Systemfixed', 15)) previous_text_id = text_id else: canvas.create_text(200, 200, text='GAME OVER!!', fill='red', font=('Helvetica', 30)) tk.update_idletasks() tk.update() time.sleep(0.02)
9bd958f1f64ad989b42902812520681e66ee4140
Luckercorgi240/python_codes
/Python drawing/mysquare.py
649
4.09375
4
import turtle t = turtle.Pen() def mysquare(size, filled, color): t.fillcolor(color) if filled == True: t.begin_fill() for x in range(1, 5): t.forward(size) t.left(90) if filled == True: t.end_fill() turtle.done() print('How big do you want the square to be?') size = input() size = int(size) print('Type True or False') filled = input() filled = bool(filled) print('What color do you want your square to be?') color = input() color = str(color) if filled == False: print('IF YOU TYPE FALSE THE PROGRAM WILL NOT DRAW THE SQUARE YOU WANTED. PLEASE TYPE TRUE.') mysquare(size, filled, color)
271d19d9e2b49eb1eae1cb2dba6f4ff010793e29
madnoh/Work-in-Progress
/Tai Sai Simulator/Tai Sai simulator.py
1,460
3.90625
4
# Tai Sai simulator '''from itertools import combinations_with_replacement threeDice = combinations_with_replacement(range(1, 7), 3) #print(list(threeDice)) print(type(threeDice))''' # Small is between 4 to 10, except triples Pay 1:1 # Big is between 11 to 17, except triples Pay 1:1 # Triples pay 1:30 # Specific triples Pay 1:180 # Doubles Pay 1:11 # Total 4 or 17 Pay 1:60 # Total 5 or 16 Pay 1:20 # Total 6 or 15 Pay 1:18 # Total 7 or 14 Pay 1:12 # Total 8 or 13 Pay 1:8 # Total 9, 10, 11 or 12 Pay 1:6 from random import randint # Look at def dice_roll (num_dice = 0 , num_sides = 0): # Look at return sum(random.randint(1,num_sides) for die in range(num_dice)) positive, negative = 0, 0 for _ in range(1000): cash, win = 100, 0 bet1, bet2 = 1, 1 winresult = [9, 10 , 11, 12] iterations = 100 def isTriple(d1, d2, d3): if d1 == d2 and d2 == d3: return bet1 * 31 return 0 def NineToTwelve(d1, d2, d3): if d1+ d2 + d3 in winresult: return bet2 * 7 return 0 for i in range(0,iterations): dice1, dice2, dice3 = randint(1,6), randint(1,6), randint(1,6) win = isTriple(dice1, dice2, dice3) + NineToTwelve(dice1, dice2, dice3) cash = win - bet1 - (4 * bet2) if cash > 0: positive += 1 else: negative += 1 print(f'Win = {positive} times, Lose = {negative} times.')
292293054f619d32f783c329280d8eaef9b96515
DestructHub/ProjectEuler
/Problem058/Python/solution_1.py
1,134
3.765625
4
import math def is_prime(n): if n%2 == 0: return False for i in range(3, math.floor(math.sqrt(n)) + 1, 2): if n%i == 0: return False return True class Problem058(object): def __init__(self): self.nprimes = 8 self.level = 7 self.prime_ratio = 0.62 def _diag_primes(self): # Count primes on top left 3 corners # 3n - k(n + 1) / k => {1, 2, 3} return [is_prime(self.level**2 - self.level + 1), is_prime(self.level**2 - 2*self.level + 2), is_prime(self.level**2 - 3*self.level + 3)].count(True) def _record_next_diag_primes(self): self.level += 2 self.nprimes += self._diag_primes() self.prime_ratio = self.nprimes / (self.level * 2 - 1) def _solve(self, ratio_limit): while self.prime_ratio > ratio_limit: self._record_next_diag_primes() return self.level @classmethod def solve(cls): obj = object.__new__(cls) obj.__init__() return obj._solve(0.1) if __name__ == "__main__": print(Problem058.solve())
bf04c58cb7481b0b85f5c2c3a601c912cd18e76b
DestructHub/ProjectEuler
/Problem473/Python/solution_slow_2.py
2,058
3.796875
4
# -*- coding: utf-8 -*- #problem 473 """ Let φ be the golden ratio: φ=1+5√2. Remarkably it is possible to write every positive integer as a sum of powers of φ even if we require that every power of φ is used at most once in this sum. Even then this representation is not unique. We can make it unique by requiring that no powers with consecutive exponents are used and that the representation is finite. E.g: 2=φ+φ^-2 and 3=φ^2+φ^-2 To represent this sum of powers of φ we use a string of 0's and 1's with a point to indicate where the negative exponents start. We call this the representation in the phigital numberbase. So 1=1φ, 2=10.01φ, 3=100.01φ and 14=100100.001001φ. The strings representing 1, 2 and 14 in the phigital number base are palindromic, while the string representating 3 is not. (the phigital point is not the middle character). The sum of the positive integers not exceeding 1000 whose phigital representation is palindromic is 4345. Find the sum of the positive integers not exceeding 10^10 whose phigital representation is palindromic. """ from math import * from kbhit_unix import KBHit as kbhit phi = ((1+sqrt(5))/2) def phi_pre_gen(n): resto = n while resto >= 1: last = 0 for i in xrange(n): if phi ** i > resto: break last = i resto -= phi ** last yield last yield resto def phi_suf_gen(n, resto): while resto >= 0.0001: last = -n for i in xrange(-n, -1): if phi ** i - 0.0001 > resto: break last = i resto -= phi ** last yield last def checkpal(n): if n == 1: return True pre = [x for x in phi_pre_gen(n)] pre, resto = pre[:-1], pre[-1] suf = [x for x in phi_suf_gen(n, resto)] for i in xrange(len(pre)): try: if pre[i] != ~suf[~i]: return False except IndexError: return False return len(pre) == len(suf) sum = 0 kb = kbhit() total = 10 ** 10 for i in xrange(total): if checkpal(i): sum += i if kb.kbhit() and kb.getch(): print 'Atual: %*s / %d | %4.2f %% | Sum: %d' %(len(str(total)), str(i), total, i * 100 / total, sum) print sum
f79711022bc93da97ccfa84e5b9b2601792564df
DestructHub/ProjectEuler
/Problem040/Python/solution_1.py
821
3.625
4
#!/usr/bin/env python # coding=utf-8 # Python Script # # Copyleft © Manoel Vilela # # from functools import reduce from itertools import count def frac_series_generator(): '''each n after 0.1 from 0.12345678910111213...''' for w in count(start=1, step=1): for s in str(w): yield s def search_digit_by_index(indexes): '''get the digits of indexes of frac_series''' limit = max(indexes) digits = {x: 0 for x in indexes} for c, n in enumerate(frac_series_generator()): if c + 1 in digits: digits[c + 1] = int(n) if c + 1 >= limit: break return digits.values() def main(): indexes = [1, 10, 100, 1000, 10000, 100000, 1000000] print(reduce(int.__mul__, search_digit_by_index(indexes))) if __name__ == '__main__': main()
27d0dc5f8356439abdd0e5cc8af0d15560e99f0d
DestructHub/ProjectEuler
/Problem018/Python/solution_1.py
1,052
3.53125
4
#search the biggest sum nums adjacent on the row of the triangle below #python3.4 triangle = '''\ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23''' def int_triangle(data): return [[int(x) for x in y.split()] for y in [x for x in data.split('\n')]] def arrows_recursive(data, total = [], main = [], x = 0, y = 0): temp = [] + main if x < len(data) and y < len(data): temp.append(data[y][x]) total = arrows_recursive(data, total = total, main = temp, x = x, y = y + 1) total = arrows_recursive(data, total = total, main = temp, x = x + 1, y = y + 1) if len(temp) >= len(data): total.append(temp) return total if __name__ == '__main__': lista = int_triangle(triangle) p = arrows_recursive(lista) print(max(map(sum, p)))
60da672cad8c329e17433f34116812baa1435a80
DestructHub/ProjectEuler
/Problem012/Python/solution_2.py
1,137
3.765625
4
# Good Solution found on forum thread in the projecteuler from functools import reduce def divisors(x): ''' exponents(28) --> 6 because 28 = 2**2 * 7*1: total number of divisors of 28: (2+1)*(1+1) = 6 ''' expList = [] count = 0 divisor = 2 while divisor <= x: while x % divisor == 0: x = x/divisor count += 1 if count != 0: expList.append(count+1) divisor += 1 count = 0 return reduce(lambda x, y: x * y, expList, 1) # Find the first triangle number to have over n divisors def diviTri(n): ''' Triangle numbers = sum of all previous the natural numbers Ex: The 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 The first triangular number to have over 5 divisors is 28, whose divisors are 1, 2, 4, 7, 14, 28 ''' natural = 1 triangular = 0 while True: triangular += natural natural += 1 if divisors(triangular) > n: break # print "First triangular number to have over", n, "divisors:", triangular return triangular print(diviTri(500))
d9e68f34571c9c628ae3b776e77958c94a601db5
DestructHub/ProjectEuler
/Problem080/Python/solution_1.py
594
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright © Manoel Vilela 2017 # # @team: DestructHub # @project: ProjectEuler # @author: Manoel Vilela # @email: manoel_vilela@engineer.com # import decimal import math def solution(limit): decimal.getcontext().prec = 102 # more than 100 to avoid round errors result = 0 for n in range(limit + 1): if not math.sqrt(n).is_integer(): # check if is irrational # sum digits result += sum(decimal.Decimal(n).sqrt().as_tuple()[1][:100]) return result if __name__ == '__main__': print(solution(100))
ddaf9f636b0b9bba95c74a83c1ae0cbc636bb7fa
DestructHub/ProjectEuler
/Problem026/Python/solution_1.py
2,170
4.09375
4
#!/usr/bin/env python # coding=utf-8 # Python Script # # Copyleft © Manoel Vilela # # # A unit fraction contains 1 in the numerator. # The decimal representation of the unit fractions # with denominators 2 to 10 are given: # 1/2 = 0.5 # 1/3 = 0.(3) # 1/4 = 0.25 # 1/5 = 0.2 # 1/6 = 0.1(6) # 1/7 = 0.(142857) # 1/8 = 0.125 # 1/9 = 0.(1) # 1/10 = 0.1 # 0.142857... = x # 0.142857... * 1000000 = 1000000x # 142857.142857... -0.142857... = 1000000x - x # 142857 = 999999x # x = 142857/999999 # Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. # It can be seen that 1/7 has a 6-digit recurring cycle. # Find the value of d < 1000 for which 1/d contains the longest # recurring cycle in its decimal fraction part. # replicação crua do algoritmo de divisão # manualmente, aplica uma memória dos divisores já efetuados # quando resto da divisão chegar num ponto onde se repete # retorna a quantidade de divisões menos a quantidade de vezes # que se repetiu # Exemplo [1/7] # # 10 |7 # 30 |_______ # 28 0,(1434851)... # 20 # 14 # 60 # 56 # 40 # 35 # 50 # 49 # (1) <= chegou ao remainder # retorna a função menos o número de iterações. # para o último dividendo # se resto for zero, retorna zero, pois não há recurring cycle # exemplos: 1/2, 1/4, 1/8 # only odd numbers need to be compute def get_rec_cycle(n): """1/x get the max abc recurring cycle length of 0.(abc) num""" dividend, times = 1, 1 remainder = [0 for x in range(n + 1)] while dividend != 0: times += 1 if (remainder[dividend]): return times - remainder[dividend] remainder[dividend] += times if dividend == 0: break if dividend < n: dividend *= 10 dividend %= n return 0 def get_max_rec(limit): return max([x for x in range(3, limit, 2)], key=get_rec_cycle) test = get_rec_cycle(7) assert test == 6, "Some wrong; got {}, expected 6.".format(test) if __name__ == '__main__': print(get_max_rec(1000))
2672577bfdb548ec015a64122742d90f5cdb901a
xzj963179571/python_demo
/python_demo/python_demo_05.py
2,401
4.03125
4
# coding = UTF-8 # 字符串的使用 |字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串。 # var1 = 'Hello World!' # var2 = "Alex" # Python 访问子字符串,可以使用方括号来截取字符串 # print ("var1[0]: ", var1[0]) # print ("var2[1:4]: ", var2[1:4]) # Python 字符串更新 # var1 = 'Hello World!' # print ("已更新字符串 : ", var1[:6] + 'Runoob!') # 列表 # 序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。 # 创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可 # # list1=[] #创建一个空列表 # list2=[1,2,3,4] # list3= ["b","b","c","d"] # # 使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符 # print("list2[0]:",list2[0]) # print("list2[1:5]:",list2[1:5]) # 你可以对列表的数据项进行修改或更新 # list = ['Google', 'Runoob', 1997, 2000] # print("第三个元素为:",list[2]) # list[2]=2001 #修改列表中的单个元素 # print("更改后的第三个元素为:",list[2]) # 可以使用 del 语句来删除列表的的元素 # list = ['Google', 'Runoob', 1997, 2000] # print("原始列表:",list) # del list[2] # print("删除第三个元素:",list) # 切片 # # Python中符合序列的有序序列都支持切片(slice),例如列表,字符串,元组 # 格式:【start: end:step】 # # start: 起始索引,从0开始,-1 # 表示结束 # # end:结束索引 # # step:步长,end - start,步长为正时,从左向右取值。步长为负时,反向取值 # list = ['Google', 'Runoob', 1997, 2000] print(list[:3]) print(list[3:]) print(list[::3]) print(list[::-1]) print(list[4:2:-2]) # 实例 s = 'abcdefg' # 返回从起始位置到索引位置 2 处的字符串切片 print(s[:3]) # 输出 'abc' # 返回从第三个索引位置到结尾的字符串切片 print(s[3:]) # 输出 'defg' # 字符串逆序输出 print(s[::-1]) # 输出 'gfedcba' # 输出从开始位置间隔一个字符组成的字符串 print(s[::2]) # 输出 'aceg' print(range(10)[::2]) # 输出偶数:[0, 2, 4, 6, 8] # 它们也可以相互结合使用。 # 从索引位置 6 到索引位置 2,逆向间隔一个字符 print(s[6:2:-2]) # 输出'ge'
a0abd3a16d2daa13fc8b8676cd5ff785aeb5386f
baralganesh/Python-SimpleMaths
/sum_of_odd_even_negative_numbers.py
462
3.984375
4
nums = int(input("Enter how many numbers you want to calculate: ")) user_numbers =[] for c1 in range (nums): no = int(input("Enter numbers: ")) user_numbers.append(no) sum1 = 0 sum2 = 0 sum3 = 0 for nos in user_numbers: if nos >1: if nos%2 ==0: sum1 += nos else: sum2 +=nos else: sum3 +=nos print ("sum of even nos: ", sum1) print ("sum of odd nos: ", sum2) print ("sum of negative nos: ", sum3)
cd37d581b392dcf3768206c4d7f045fab686d590
mpss2019fn1/filemerge
/file_merge.py
1,093
3.546875
4
import os import sys import argparse from validate_directory import ValidateDirectory def main(): parser = _create_arg_parser() args = parser.parse_args() output = args.output if output: output = open(output, "w") else: output = sys.stdout for filename in os.listdir(args.source): with open(f"{args.source}/{filename}") as file: line = file.readline() while line: _print_line(line, output) line = file.readline() def _print_line(line, output): if len(line.strip()) < 1: return if "<doc" in line or "</doc" in line: return print(line, file=output, end="") def _create_arg_parser(): parser = argparse.ArgumentParser(description="merge files into a single document") parser.add_argument("--source", required=True, help="source directory, which contains the files to be merged", action=ValidateDirectory) parser.add_argument("--output", required=False, help="output file to write to") return parser if __name__ == "__main__": main()
54ed0799fe9f25cb775bcdbab10bab905414cfd2
ANU197/CodeChef-Contest1
/Chewing.py
1,960
3.640625
4
""" Zonal Computing Olympiad 2013, 10 Nov 2012 Hobbes has challenged Calvin to display his chewing skills and chew two different types of Chewing Magazine's Diabolic Jawlockers chewing gum at the same time. Being a generous sort of tiger, Hobbes allows Calvin to pick the two types of gum he will chew. Each type of chewing gum has a hardness quotient, given by a non-negative integer. If Calvin chews two pieces of gum at the same time, the total hardness quotient is the sum of the individual hardness quotients of the two pieces of gum. Calvin knows that he cannot chew any gum combination whose hardness quotient is K or more. He is given a list with the hardness quotient of each type of gum in the Diabolic Jawlockers collection. How many different pairs of chewing gum can Calvin choose from so that the total hardness quotient remains strictly below his hardness limit K? For instance, suppose there are 7 types of chewing gum as follows: Chewing gum type 1 2 3 4 5 6 7 Hardness quotient 10 1 3 1 5 5 0 If Calvin's hardness limit is 4, there are 4 possible pairs he can choose: type 2 and 7 (1+0 < 4), type 3 and 7 (3+0 < 4), type 2 and 4 (1+1 < 4) and type 4 and 7 (1+0 < 4). Input format Line 1 : Two space separated integers N and K, where N is the number of different types of chewing gum and K is Calvin's hardness limit. Line 2: N space separated non-negative integers, which are the hardness quotients of each of the N types of chewing gum. Output format The output consists of a single non-negative integer, the number of pairs of chewing gum with total hardness quotient strictly less than K. Sample Input 7 4 10 1 3 1 5 5 0 Sample Output 4 """ x = list(map(int, input().strip().split())) y = list(map(int, input().strip().split())) count = 0 y.sort() n = x[0] k = x[1] for i in range(n): for j in range(i+1, n): if (y[i]+y[j] < k): count = count + 1 print(count)
b517ce0c1dbeb92b861ef793437df017d1cae695
astamicu/Whist-Scorer
/old_versions/whistv0.4.py
10,571
3.796875
4
##players = [] ##def howManyPlayers(): ## while True: ## try: ## no_players = int(input('Enter number of players(3-6): ')) ## except ValueError: ## print('Enter a number between 3 and 6): ') ## continue ## if no_players not in range(3, 7): ## print('BETWEEN 3 AND 6 I SAID!') ## else: ## break ## while len(players) != no_players: ## name = input('Enter player name: ') ## players.append(name) ## ##howManyPlayers() ##print('And the players are: ', end='') ##print(*players, sep=', ') ## ##bids = len(players) ##print(bids) p1 = 'a' p2 = 'b' p3 = 'c' p4 = 'd' p5 = 'e' base_score = 5 pbid = [] def round1(): global p1bid, p2bid, p3bid, p4bid, p5bid print('Round 1. Bid.') while True: try: p1bid = int(input(p1 + ': ')) except ValueError: print("Insert a number.") continue if p1bid > 1: print("You can't bid more than 1.") else: break while True: try: p2bid = int(input(p2 + ': ')) except ValueError: print("Insert a number.") continue if p2bid > 1: print("You can't bid more than 1.") else: break while True: try: p3bid = int(input(p3 + ': ')) except ValueError: print("Insert a number.") continue if p3bid > 1: print("You can't bid more than 1.") else: break while True: try: p4bid = int(input(p4 + ': ')) except ValueError: print("Insert a number.") continue if p4bid > 1: print("You can't bid more than 1.") else: break while True: if (p1bid + p2bid + p3bid + p4bid) == 0: p5bid = 0 break elif (p1bid + p2bid + p3bid + p4bid) == 1: p5bid = 1 break else: while True: try: p5bid = int(input(p5 + ': ')) except ValueError: print("Insert a number.") continue if p5bid > 1: print("You can't bid more than 1.") continue else: break break print(p1 + ' bid: ' + str(p1bid)) print(p2 + ' bid: ' + str(p2bid)) print(p3 + ' bid: ' + str(p3bid)) print(p4 + ' bid: ' + str(p4bid)) print(p5 + ' bid: ' + str(p5bid)) def round2(): global p1bid, p2bid, p3bid, p4bid, p5bid print('Round 2. Bid.') while True: try: p2bid = int(input(p2 + ': ')) except ValueError: print("Insert a number.") continue if p2bid > 1: print("You can't bid more than 1.") else: break while True: try: p3bid = int(input(p3 + ': ')) except ValueError: print("Insert a number.") continue if p3bid > 1: print("You can't bid more than 1.") else: break while True: try: p4bid = int(input(p4 + ': ')) except ValueError: print("Insert a number.") continue if p4bid > 1: print("You can't bid more than 1.") else: break while True: try: p5bid = int(input(p5 + ': ')) except ValueError: print("Insert a number.") continue if p5bid > 1: print("You can't bid more than 1.") continue else: break if (p2bid + p3bid + p4bid + p5bid) == 0: p1bid = 0 elif (p2bid + p3bid + p4bid + p5bid) == 1: p1bid = 1 else: while True: try: p1bid = int(input(p1 + ': ')) except ValueError: print("Insert a number.") continue if p1bid > 1: print("You can't bid more than 1.") else: break print(p2 + ' bid: ' + str(p2bid)) print(p3 + ' bid: ' + str(p3bid)) print(p4 + ' bid: ' + str(p4bid)) print(p5 + ' bid: ' + str(p5bid)) print(p1 + ' bid: ' + str(p1bid)) def score1(): global p1score, p2score, p3score, p4score, p5score print('Round 1. Insert results.') while True: try: p1result = int(input(p1 + ': ')) except ValueError: print("Insert a number.") continue if p1result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result == 1: p2result = 0 p3result = 0 p4result = 0 p5result = 0 break try: p2result = int(input(p2 + ': ')) except ValueError: print("Insert a number.") continue if p2result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result or p2result == 1: p3result = 0 p4result = 0 p5result = 0 break try: p3result = int(input(p3 + ': ')) except ValueError: print("Insert a number.") continue if p3result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result or p2result or p3result == 1: p4result = 0 p5result = 0 break try: p4result = int(input(p4 + ': ')) except ValueError: print("Insert a number.") continue if p4result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result or p2result or p3result or p4result == 1: p5result = 0 break try: p5result = int(input(p5 + ': ')) except ValueError: print("Insert a number.") continue if p5result > 1: print("You couldn't bid more than 1.") continue else: break if p1result == p1bid: p1score = base_score + p1result else: p1score = -1 if p2result == p2bid: p2score = base_score + p2result else: p2score = -1 if p3result == p3bid: p3score = base_score + p3result else: p3score = -1 if p4result == p4bid: p4score = base_score + p4result else: p4score = -1 if p5result == p5bid: p5score = base_score + p5result else: p5score = -1 print('Score after round 1') print(p1 + ": " + str(p1score)) print(p2 + ": " + str(p2score)) print(p3 + ": " + str(p3score)) print(p4 + ": " + str(p4score)) print(p5 + ": " + str(p5score)) def score2(): global p1score, p2score, p3score, p4score, p5score print('Round 2. Insert results.') while True: try: p1result = int(input(p1 + ': ')) except ValueError: print("Insert a number.") continue if p1result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result == 1: p2result = 0 p3result = 0 p4result = 0 p5result = 0 break try: p2result = int(input(p2 + ': ')) except ValueError: print("Insert a number.") continue if p2result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result or p2result == 1: p3result = 0 p4result = 0 p5result = 0 break try: p3result = int(input(p3 + ': ')) except ValueError: print("Insert a number.") continue if p3result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result or p2result or p3result == 1: p4result = 0 p5result = 0 break try: p4result = int(input(p4 + ': ')) except ValueError: print("Insert a number.") continue if p4result > 1: print("You couldn't bid more than 1.") continue else: break while True: if p1result or p2result or p3result or p4result == 1: p5result = 0 break try: p5result = int(input(p5 + ': ')) except ValueError: print("Insert a number.") continue if p5result > 1: print("You couldn't bid more than 1.") continue else: break if p1result == p1bid: p1score = p1score + base_score + p1result elif p1result < p1bid: p1score = p1score - (p1bid - p1result) else: p1score = p1score - (p1result - p1bid) if p2result == p2bid: p2score = p2score + base_score + p2result elif p2result < p2bid: p2score = p2score - (p2bid - p2result) else: p2score = p2score - (p2result - p2bid) if p3result == p3bid: p3score = p3score + base_score + p3result elif p3result < p3bid: p3score = p3score - (p3bid - p3result) else: p3score = p3score - (p3result - p3bid) if p4result == p4bid: p4score = p4score + base_score + p4result elif p4result < p4bid: p4score = p4score - (p4bid - p4result) else: p4score = p4score - (p4result - p4bid) if p5result == p5bid: p5score = p5score + base_score + p5result elif p5result < p5bid: p5score = p5score - (p5bid - p5result) else: p5score = p5score - (p5result - p5bid) print('Score after round 2') print(p1 + ": " + str(p1score)) print(p2 + ": " + str(p2score)) print(p3 + ": " + str(p3score)) print(p4 + ": " + str(p4score)) print(p5 + ": " + str(p5score)) round1() score1() wait = input("PRESS ENTER TO CONTINUE.") round2() score2()
dd686a279acc19bd6a62276b52ec7e96a4d8cf1b
jangseokgyu/python-algorithm
/Recursive_hanoi.py
231
3.890625
4
def TowerofHanoi(n,a,b,c): if(n==1) : print(str(a)+" "+str(b)) return TowerofHanoi(n-1,a,c,b) print(str(a)+" "+str(b)) TowerofHanoi(n-1,c,b,a) n = int(input("넣어라")) a=1 b=2 c=3; TowerofHanoi(n, a, b, c)
5d6daf2f364ee0c9e1d38effcee91273e51a7523
MichaelWalker-git/Ud_Ai_Course
/Scales_and_Transformations_Practice.py
1,981
3.84375
4
# coding: utf-8 # In[1]: # prerequisite package imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb get_ipython().run_line_magic('matplotlib', 'inline') from solutions_univ import scales_solution_1, scales_solution_2 # Once again, we make use of the Pokémon data for this exercise. # In[2]: pokemon = pd.read_csv('./data/pokemon.csv') pokemon.head() # **Task 1**: There are also variables in the dataset that don't have anything to do with the game mechanics, and are just there for flavor. Try plotting the distribution of Pokémon heights (given in meters). For this exercise, experiment with different axis limits as well as bin widths to see what gives the clearest view of the data. # In[22]: bin_edges = np.arange(0, pokemon['height'].max()+0.2, 0.2) plt.hist(data=pokemon, x = 'height', bins=bin_edges) plt.xlim(0, 6) # In[17]: # run this cell to check your work against ours scales_solution_1() # **Task 2**: In this task, you should plot the distribution of Pokémon weights (given in kilograms). Due to the very large range of values taken, you will probably want to perform an _axis transformation_ as part of your visualization workflow. # In[35]: # def sqrt_trans(x, inverse = False): # if not inverse: # return np.sqrt(x) # else: # return x ** 2 # bin_edges = np.arange(0, sqrt_trans(pokemon['weight'].max()) + 1, 1) # plt.hist(pokemon['weight'].apply(sqrt_trans), bins=bin_edges) # tick_locs= np.arange(0, sqrt_trans((pokemon['weight']).max())+8, 8) # plt.xticks(tick_locs, sqrt_trans(tick_locs, inverse=True).astype(int)) bins = 10 ** np.arange(-1, 3.0+0.1, 0.1) ticks = [0.1, 0.3, 1, 3, 10, 30, 100, 300, 1000] labels = ['{}'.format(val) for val in ticks] plt.hist(data = pokemon, x = 'weight', bins = bins) plt.xscale('log') plt.xticks(ticks, labels) plt.xlabel('Weight (kg)') # In[19]: # run this cell to check your work against ours scales_solution_2()
91c4d0a08b923202a02d9c9c30c400e0daf59f29
MichaelWalker-git/Ud_Ai_Course
/Scatterplot_Practice.py
1,992
3.859375
4
# coding: utf-8 # In[2]: # prerequisite package imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb get_ipython().run_line_magic('matplotlib', 'inline') from solutions_biv import scatterplot_solution_1, scatterplot_solution_2 # In this workspace, you'll make use of this data set describing various car attributes, such as fuel efficiency. The cars in this dataset represent about 3900 sedans tested by the EPA from 2013 to 2018. This dataset is a trimmed-down version of the data found [here](https://catalog.data.gov/dataset/fuel-economy-data). # In[3]: fuel_econ = pd.read_csv('./data/fuel_econ.csv') fuel_econ.head() # **Task 1**: Let's look at the relationship between fuel mileage ratings for city vs. highway driving, as stored in the 'city' and 'highway' variables (in miles per gallon, or mpg). Use a _scatter plot_ to depict the data. What is the general relationship between these variables? Are there any points that appear unusual against these trends? # In[7]: plt.scatter(data= fuel_econ, x= 'city', y='highway', alpha = 1/5) plt.xlabel('City efficiency') plt.ylabel('Highway efficiency') # In[5]: # run this cell to check your work against ours scatterplot_solution_1() # **Task 2**: Let's look at the relationship between two other numeric variables. How does the engine size relate to a car's CO2 footprint? The 'displ' variable has the former (in liters), while the 'co2' variable has the latter (in grams per mile). Use a heat map to depict the data. How strong is this trend? # In[15]: # bins_x = np.arange(0.5, 10.5+1, 1) # bins_y = np.arange(-0.5, 10.5+1, 1) bins_x = np.arange(0.6, fuel_econ['displ'].max()+0.4, 0.4) bins_y = np.arange(0, fuel_econ['co2'].max()+50, 50) plt.hist2d(data = fuel_econ, x = 'displ', y = 'co2', bins = [bins_x, bins_y], cmap = 'viridis_r', cmin = 0.5) plt.colorbar() # In[6]: # run this cell to check your work against ours scatterplot_solution_2()
752a06f025ba33f428a353466df9323f1a5d96b1
jprinaldi/algo1
/pa3/karger.py
4,340
3.515625
4
#!/usr/bin/env python3 """ Implementation of Karger's algorithm for computing a minimum cut of a connected graph. """ import argparse import copy class Vertex: def __init__(self, value): self.value = value self.parent = self def __eq__(self, that): return self.get_rep().value == that.get_rep().value def __hash__(self): return self.value def __repr__(self): return str(self.value) def get_rep(self): rep = self.parent while rep.value != rep.parent.value: rep = rep.parent return rep class Edge: def __init__(self, u, v): self.u = u self.v = v def __eq__(self, that): return (self.u == that.u and self.v == that.v) or (self.u == that.v and self.v == that.u) def __repr__(self): return str(self.u.value) + "-" + str(self.v.value) class Graph: def __init__(self): self.vertices = {} self.edges = [] self.vertex_count = 0 def parse_adjacency_lists(self, adjacency_lists): for adjacency_list in adjacency_lists: self.parse_adjacency_list(adjacency_list) def parse_adjacency_list(self, adjacency_list): vertex_value = adjacency_list[0] if vertex_value not in self.vertices.keys(): vertex = Vertex(vertex_value) self.vertices[vertex_value] = vertex self.vertex_count += 1 else: vertex = self.vertices[vertex_value] adjacency_list = adjacency_list[1:] for adjacent_vertex_value in adjacency_list: if adjacent_vertex_value not in self.vertices.keys(): adjacent_vertex = Vertex(adjacent_vertex_value) self.vertices[adjacent_vertex_value] = adjacent_vertex self.vertex_count += 1 else: adjacent_vertex = self.vertices[adjacent_vertex_value] edge = Edge(vertex, adjacent_vertex) if edge not in self.edges: self.edges.append(edge) def fuse(self, u, v): self.vertex_count -= 1 u_rep = u.get_rep() v_rep = v.get_rep() if u_rep.value <= v_rep.value: v_rep.parent = u_rep else: u_rep.parent = v_rep def choose_random_edge(self): import random i = random.randrange(0, len(self.edges)) random_edge = self.edges.pop(i) return random_edge def remove_self_loops(self): new_edges = [] for edge in self.edges: if edge.u != edge.v: new_edges.append(edge) self.edges = new_edges[:] def contract(self): while self.vertex_count > 2: random_edge = self.choose_random_edge() self.fuse(random_edge.u, random_edge.v) self.remove_self_loops() return len(self.edges), self.edges def parse_file(file_name): with open(file_name) as f: content = f.readlines() parsed_content = [] for line in content: line = [int(i) for i in line.split()] parsed_content.append(line) return parsed_content def karger(filename, verbose = False): adjacency_lists = parse_file(filename) min_cut_size = float("inf") min_cut = None original_graph = Graph() if verbose: print("Building graph...") original_graph.parse_adjacency_lists(adjacency_lists) if verbose: print("Running contractions...") for iteration in range(args.iterations): if verbose: print("Iteration:", iteration + 1) graph = copy.deepcopy(original_graph) cut_size, cut = graph.contract() if cut_size < min_cut_size: min_cut_size = cut_size min_cut = cut return min_cut_size, min_cut if __name__ == "__main__": parser = argparse.ArgumentParser(description="Compute minimum cut of a connected graph.") parser.add_argument('filename', type=str, help="file containing graph") parser.add_argument('iterations', metavar='iter', type=int, help="number of iterations to run") parser.add_argument('--verbose', action='store_true', help="print additional messages") args = parser.parse_args() min_cut_size, min_cut = karger(args.filename, args.verbose) print("Minimum cut size:", min_cut_size) print("Minimum cut:", min_cut)
f35d17401b20f52dd943239a2c40cb251fa53d03
jimkaj/PracticePython
/PP_6.py
342
4.28125
4
#Practice Python Ex 6 # Get string and test if palindrome word = input("Enter text to test for palindrome-ness: ") start = 0 end = len(word) - 1 while end > start: if word[start] != word[end]: print("That's not a palindrome!") quit() start = start + 1 end = end -1 print(word," is a palindrome!")
668b160fffc014a4ef3996338f118fc9d4f1db6a
jimkaj/PracticePython
/PP_9.py
782
4.21875
4
# Practice Python #9 # Generate random number from 1-9, have use guess number import random num = random.randrange(1,10,1) print('I have selected a number between 1 and 9') print("Type 'exit' to stop playing") count = 0 while True: guess = input("What number have I selected? ") if guess == 'exit': break count = count + 1 try: guess = int(guess) except: print("Invalid Input. You must input an integer or 'exit' to quit playing") count = count -1 continue if guess == num: print('You guessed it! That took you',count,'tries') exit() if guess < num: print('Too low! Guess again.') if guess > num: print('Too high! Guess again.')
b6bab19e22bf9813730482141391876a7fb71a05
andreandrade13/URI_Python3
/1143.py
83
3.65625
4
n = int(input()) for i in range(1, n + 1): print("%d %d %d" %(i, i**0, i**3))
5c790768bb5f5889453459f0b9eee19b6640141c
andreandrade13/URI_Python3
/1131.py
542
3.578125
4
resp = 1 soma = 0 somaE = 0 somaI = 0 somaG = 0 while resp == 1: a,b = map(int,input().split()) soma +=1 if(a > b): somaI += 1 elif(b > a): somaG += 1 elif(a == b): somaE += 1 resp = int(input('Novo grenal (1-sim 2-nao)')) print("%d grenais" %soma) print("Inter: %d" %somaI) print("Gremio: %d" %somaG) print("Empates: %d" %somaE) if(somaI > somaG): print("Inter venceu mais") elif(somaI < somaG): print("Gremio venceu mais") elif(somaI == somaG): print("Nao houve vencedor")
4c2b3e93037fbdc5a0c750f3cd106a1dac584ca8
sunweiwei45/twitter
/test.py
3,263
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/11/25 19:12 # @Author : Sww # @Site : # @File : test.py # @Software: PyCharm Community Edition import csv import pandas def stitching_columns(row): """ 将pandas中的两列简单拼接,such as:column1=[a,c,3], column2=[3,2,d], res = [a3,c2,3d] :param x:(Dataform),一行 :return:(object) """ id_1 = str(row[0]).zfill(20) #将id从int转为string,并 id_2 = str(row[1]).zfill(20) res = id_1 + '#' + id_2 + '#' + str(row[2]) return res def main(): data = pandas.read_csv(r"") # with open(r"E:/Sunweiwei/eHealth/twitter/temp/2016-03-23-dateedge_network", r"rb") as csvfile: # read = csv.reader(csvfile) # for each in read: # temp_list = each[0].split("\t") # # print repr(temp_list) # with open(r"E:/Sunweiwei/eHealth/twitter/temp/2016-03-23-dateedge_network.csv",r"ab") as csvfile: # write = csv.writer(csvfile) # write.writerow(temp_list) df = pandas.read_csv(r"E:/Sunweiwei/eHealth/twitter/temp/123.csv", header=None, index_col=None) df = df.T df.to_csv("E:/Sunweiwei/eHealth/twitter/temp/123.csv", header=None, index=False, mode="a") # for i in range(2): # df.dropna() # df.to_csv(r"E:/Sunweiwei/eHealth/twitter/temp/123.csv", mode="a") # df = df.drop_duplicates() # print df # df = pandas.read_table("E:/Sunweiwei/eHealth/twitter/temp/total_network", header=None) # df.to_csv() # with open(r"E:/Sunweiwei/eHealth/twitter/temp/123.icpm", r"rb") as csvfile: # read = csvfile.readlines() # for each in read: # line = each.strip().split(' ') # 一个line便是一个community # # print line # df_list = [] # for use in line: # # 在network中获得该社区所有用户发出的edge # use_in = df[df[0] == int(use)].apply(stitching_columns, axis=1) # df_list.append(use_in) # for use in line: # # 在network中获得该社区所有用户接受的edge # use_out = df[df[1] == int(use)].apply(stitching_columns, axis=1) # df_list.append(use_out) # temp_use_community = pandas.concat(df_list).dropna(axis=1) # 将同一个社区内的用户涉及的边合并,去除为空的行 # use_community = temp_use_community.drop_duplicates() # 去重 # # # list = [] # ss1 = "00000000000708212528" # res1 = df[df[0] == int(ss1)].apply(stitching_columns, axis=1) # print res1 # # list.append(res1) # # print res1 # ss2 = "00000000000711716023" # res1 = df[df[0] == int(ss2)].apply(stitching_columns, axis=1) # # sdf = [res1,res2] # # print sdf # # res = pandas.concat(sdf, axis=1) # # print res # list.append(res1) # ss3 = "00000000000346667546" # res1 = df[df[0] == int(ss2)].apply(stitching_columns, axis=1) # list.append(res1) # # res = pandas.concat(list,axis=1) # print list # # res = res.drop_duplicates() # # res.to_csv("E:/Sunweiwei/eHealth/twitter/temp/123.csv", index=False) if __name__ == '__main__': main()
029378b419f547f54a38cd8f203816b05e50dec8
thecrossed/chess_square
/chess_square.py
4,429
3.625
4
# coding: utf-8 # https://www.kaggle.com/datasnaek/chess import numpy as np import pandas as pd # pandas import csv import re import matplotlib import matplotlib.pyplot as plt # Steps # 1 extract moves from each game # 2 turn move string into a new column # 3 extract occupied squares from moves in each game # 4 build a dictionary and store frequency of square occupied as values (normalized) # 5 draw a board and visualize data chess = pd.read_csv('games.csv') chess.head() # extract moves from each game chess_moves = chess[['moves']].copy() chess_moves.head() # Step 2 turn move string into a new column each_move def each_move(chess_moves): each = (chess_moves['moves']).split(' ') return each chess_moves['each_move'] = chess_moves.apply(each_move, axis=1) chess_moves.head() # Step 3 extract occupied squares from moves in each game def square(chess_moves): squares = [] for m in chess_moves['each_move']: if m == 'O-O' or m == 'O-O+': if chess_moves['each_move'].index(m)%2 == 0: squares.append('g1') squares.append('f1') elif chess_moves['each_move'].index(m)%2 == 1: squares.append('g8') squares.append('f8') elif m == 'O-O-O' or m =='O-O-O+': if chess_moves['each_move'].index(m)%2 == 0: squares.append('c1') squares.append('d1') elif chess_moves['each_move'].index(m)%2 == 1: squares.append('c8') squares.append('d8') else: if '=' in m: squares.append(m.split('=')[0][-2:]) elif m[-1] == '+' or m[-1] =='#': squares.append(m[-3:-1]) else: squares.append(m[-2:]) return squares chess_moves['square'] = chess_moves.apply(square, axis=1) chess_moves.head() # Step 4 build a dictionary and store frequency of square occupied as values (normalized) sq_count = {} for s in chess_moves['square']: for i in s: sq_count[i] = sq_count.get(i, 0) + 1 # normalize value def normalize(d, target=1.0): raw = sum(d.values()) factor = target/raw return {key:round(value*factor*100,2) for key,value in d.items()} sq_norm = normalize(sq_count) letter = ['a','b','c','d','e','f','g','h'] eight = [] for k in letter: eight.append(sq_norm[k+'8']) sev = [] for k in letter: sev.append(sq_norm[k+'7']) six = [] for k in letter: six.append(sq_norm[k+'6']) fiv = [] for k in letter: fiv.append(sq_norm[k+'5']) four = [] for k in letter: four.append(sq_norm[k+'4']) thr = [] for k in letter: thr.append(sq_norm[k+'3']) two = [] for k in letter: two.append(sq_norm[k+'2']) one = [] for k in letter: one.append(sq_norm[k+'1']) # turn dictionary values into lists, for data visualization in next steps letter = ['a','b','c','d','e','f','g','h'] eight = [] for k in letter: eight.append(sq_norm[k+'8']) sev = [] for k in letter: sev.append(sq_norm[k+'7']) six = [] for k in letter: six.append(sq_norm[k+'6']) fiv = [] for k in letter: fiv.append(sq_norm[k+'5']) four = [] for k in letter: four.append(sq_norm[k+'4']) thr = [] for k in letter: thr.append(sq_norm[k+'3']) two = [] for k in letter: two.append(sq_norm[k+'2']) one = [] for k in letter: one.append(sq_norm[k+'1']) # Step 5 draw a board and visualize data number = ["8","7", "6", "5", "4", "3", "2", "1"] alphabet = ["a", "b", "c", "d", "e", "f", "g","h"] board = np.array([eight,sev,six,fiv,four,thr,two,one]) fig, ax = plt.subplots() im = ax.imshow(board) # We want to show all ticks... ax.set_xticks(np.arange(len(alphabet))) ax.set_yticks(np.arange(len(number))) # ... and label them with the respective list entries ax.set_xticklabels(alphabet) ax.set_yticklabels(number) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. for i in range(len(number)): for j in range(len(alphabet)): text = ax.text(j, i, board[i, j], ha="center", va="center", color="w") ax.set_title("square occupied frequency(normalized)") fig.tight_layout() plt.show()
6f96eb05253b016cf9ec61f688f4c996dd964191
marielle1022/mass_charities_project
/language.py
9,835
3.734375
4
""" language.py file contains functions used to create and update languages. """ import re import organization import validity_check import lang_serv import textwrap # Constant: regex pattern for language names (allows uppercase, lowercase, spaces, and hyphens) lang_pattern = re.compile("[a-zA-Z\\s\\-]*") # Constant: number of characters to wrap output wrap_char = 70 ''' Name: update_languages Parameters: database connection object; string (organization name) Returns: N/A Does: Updates (adds new, modifies existing, or deletes existing) languages associated with the given organization ''' # Note: only called by user_interactions.update_operation, which already verifies that organization name is valid def update_languages(cnx, org_name): user_exit = False while not user_exit: org_languages = lang_serv.get_org_lang_serv(cnx, org_name, "view_org_languages") if org_languages: print("Languages offered by this organization are:") lang_serv.display_org_lang_serv(org_languages, 'languageName') options = ['1', '2', '3'] user_choice = input("How would you like to update organization languages? Your options are:\n" "[1] do nothing\n[2] add new\n[3] delete existing\n" "Please input the number corresponding to your selection.\n") while user_choice not in options: print("This is not a valid option. Please try again.") user_choice = input("Your options are:\n[1] do nothing\n[2] add new\n" "[3] delete existing\nPlease input the number corresponding to your selection.\n") else: options = ['1', '2'] user_choice = input("There are no existing languages for this organization.\nWhat you like to do? Your " "options are:\n[1] do nothing\n[2] add new\nPlease input the number corresponding to " "your selection.\n") while user_choice not in options: print("This is not a valid option. Please try again.") user_choice = input("Your options are:\n[1] do nothing\n[2] add new\nPlease input the number " "corresponding to your selection.\n") if user_choice == '1': return elif user_choice == '2': add_org_languages(cnx, org_name) else: delete_org_lang(cnx, org_name) update_another = input("Would you like to update more languages for this organization? (y/n)\n").lower() if update_another != 'y': user_exit = True ''' Name: create_language Parameters: database connection object Returns: True if successful; False otherwise Does: creates a new language in the database ''' def create_language(cnx): while True: valid_language = False while not valid_language: language = input("Please enter a language name.\n") # Note: not using validity check function to add language name so that more informative error messages can # be displayed. check_len = validity_check.check_length_valid(language, validity_check.max_language_name) check_pattern = re.fullmatch(lang_pattern, language) if not check_len or not check_pattern or not language: if not check_len: print("This language name is too long (limit is " + str(validity_check.max_language_name) + " characters).") elif not language: print("You did not enter a language name.") else: print("This language name is not valid. Only include letters, spaces, and/or hyphens.") try_again = input("Would you like to try again? (y/n)\n").lower() if try_again != 'y': return False else: valid_language = True lang_arr = [language] lang_cursor = cnx.cursor() lang_cursor.callproc("create_language", lang_arr) error_check = lang_cursor.fetchone() lang_cursor.close() if error_check: print(error_check['error'] + "\n") recent_language_valid = False else: print("Language was created successfully.") recent_language_valid = True cnx.commit() add_another = input("Would you like to enter another language? (y/n)\n").lower() if add_another != 'y': return recent_language_valid ''' Name: add_org_languages Parameters: database connection object, string representing organization name Returns: False if trying to add to an organization that does not exist Does: adds existing languages to an organization ''' # Note: this is only called by create_obj.create_full_process and update_languages # Both paths already check that organization is valid def add_org_languages(cnx, org_name): if organization.check_organization(cnx, org_name) == 0: print("This organization does not exist in the database.") return False display_existing_languages(cnx) lang_list_str = input("Please list all desired languages, separated a comma\n(format: lang1, lang2).\n") lang_arr = lang_list_str.split(',') for lang in lang_arr: lang = lang.strip() if validity_check.check_language_name(lang): add_lang_cursor = cnx.cursor() add_lang_cursor.callproc("add_org_language", [lang, org_name]) error_check = add_lang_cursor.fetchone() add_lang_cursor.close() if error_check: print(lang + ": " + error_check['error']) else: print(lang + " was added successfully.") cnx.commit() else: print(lang + ": This is not a valid language name.") ''' Name: delete_org_lang Parameters: database connection object; string (organization name) Returns: N/A Does: deletes the desired record connecting a language to the organization ''' # Note: this is only called by update_languages # This path already checks that organization name is valid AND that at least one language exists for this organization def delete_org_lang(cnx, org_name): langs = lang_serv.get_org_lang_serv(cnx, org_name, "view_org_languages") print("The languages associated with this organization are:") lang_serv.display_org_lang_serv(langs, 'languageName') lang = input("What language would you like to delete?\n").lower() check_lang = 0 for l in langs: if l["languageName"].lower() == lang: check_lang += 1 if check_lang == 0: print("The language you selected does not exist for this organization.") return False else: print("You have selected the following language: " + lang) delete_check = input("Are you sure you want to delete this language? (y/n)\n").lower() if delete_check == 'y': delete_cursor = cnx.cursor() delete_cursor.callproc("delete_org_language", [org_name, lang]) rows = delete_cursor.fetchall() delete_cursor.close() if rows: for row in rows: print(row['error']) else: cnx.commit() else: return False ''' Name: get_existing_languages Parameters: database connection object Returns: N/A Does: gets a list of languages that already exist in the database ''' def get_existing_languages(cnx): get_lang_cursor = cnx.cursor() get_lang_cursor.callproc("list_languages", []) rows = get_lang_cursor.fetchall() get_lang_cursor.close() all_lang_arr = [] for row in rows: all_lang_arr.append(row["languageName"]) return all_lang_arr ''' Name: display_existing_languages Parameters: database connection object Returns: N/A Does: displays a list of languages that already exist in the database ''' def display_existing_languages(cnx): all_lang_arr = get_existing_languages(cnx) all_lang_str = ' | '.join(all_lang_arr) print("Available languages are:\n" + textwrap.fill(all_lang_str, wrap_char) + "\n") ''' Name: prompt_valid_lang Parameters: database connection object Returns: string with language name if valid, None otherwise Does: prompts user for valid language (ie. one that exists in the database) until user enters valid information or quits ''' def prompt_valid_lang(cnx): view_all = input("Would you like to see a list of the languages in the database? (y/n)\n").lower() if view_all == 'y': display_existing_languages(cnx) lang = input("Please enter the language you wish to select.\n") lang_check = check_lang_exists(cnx, lang) while lang_check == 0: print("This language does not exist in the database.\n") try_again = input("Would you like to try entering another language? (y/n)\n").lower() if try_again == 'y': lang = input("Please enter the language you wish to select.\n") lang_check = check_lang_exists(cnx, lang) else: return None return lang ''' Name: check_lang_exists Parameters: database connection object, string representing language Returns: 1 if language exists in database; 0 otherwise Does: checks if language exists in database ''' def check_lang_exists(cnx, lang_name): if validity_check.check_language_name(lang_name): lang_cursor = cnx.cursor() lang_stmt = "SELECT lang_exists(%s) AS lang_check" lang_cursor.execute(lang_stmt, lang_name) check = lang_cursor.fetchone()["lang_check"] lang_cursor.close() return check else: return 0
2f9421d2d6cd6411864b2ef503d7ff8e27ea9e94
kbjung/Likelion
/온라인 교육 파이썬 파일 모음/01. 일단 만드는 Python/01-01-13. 오늘 뭐 드실2.py
228
3.875
4
lunch = ["된장찌개","피자","짜장면","치킨"] while True: print(lunch) item = input("추가할 메뉴를 입력하세요 : ") if item == "q": break else: lunch.append(item) print(lunch)
81e9c881e3ab79f780401b8e0172dcc94005941d
kbjung/Likelion
/01. 일단 만드는 Python/2. Python으로 만드는 익명 질문 게시판(2021.08.23)/질문과 답변(딕셔너리)(내 코드).py
436
3.859375
4
#질문 입력 #답변 입력 #딕셔너리 출력 total_dictionary = {} while True: question = input("질문을 입력해주세요('q'를 입력하면 종료) : ") if question == "q": break else: total_dictionary[question] = "" for i in total_dictionary: print(i) answer = input("답변을 입력하세요('q'를 입력하면 종료) : ") total_dictionary[i] = answer print(total_dictionary)
5c95c07ab8aec96fd8dd1b487b01abb90aa72320
kbjung/Likelion
/02. [기초] 같이 푸는 PYTHON/03. 조건 - 상황에 따라 다르게/05. 학번 계산기 5 - 동기에게 인사하기/02-03-05. 학번 계산기 5 - 동기에게 인사하기.py
213
3.96875
4
myGrade = int(input("학번을 입력하세요 : ")) yourGrade = int(input("학번을 입력하세요 : ")) if myGrade == yourGrade : print("앗 동기네요!") else : print("앗 동기가 아니네요!")
ff6c4fd245f10f9b99b2e04530109830c80882cd
thefulltimereader/mint
/src/winner.py
7,647
3.640625
4
''' Created on Sep 25, 2010 Assignment 1: Mint Problem: Given: Multiple of 5 cents (any 5c multiple) price is N times more likely than a non-multiple of 5cents. Design a set of 5 coin denominations for US $ s.t.: 1. The number of coins required for 'Exact Change" is minimized 2. Another set of 5 coin denominations s.t. Exchange Number is minimized Score: score = sum of the costs of all !5mult+ sum of N*costs of 5mult = @author: ajk377 ''' #cost = [float('inf')]*100; import time, math, sys counter=0 maxN = 100 def calcCost(d, cost): cost[0]=0 for i in xrange(1, maxN): if(cost[i] == float('inf')): minList = [] for index in xrange(len(d)): if i-d[index] > 0: minList += [cost[(i-d[index])] ] cost[i] = 1+ min(minList) #print cost return cost def calcCostOld(cost): cost[0]=0 for i in xrange(2, maxN): if cost[i]==float('inf'): for j in range(1, i): #print "looking at j:",j,"i-j: ", (i-j)," cost[j]=", cost[j], " cost[i-j]=", cost[i-j]," cost[i]=", cost[i] if(cost[j]+cost[i-j] < cost[i]): cost[i]=cost[j]+cost[i-j] # print "at i: ",i," looking at j:",j,"i-j: ", (i-j)," cost[j]=", cost[j], " cost[i-j]=", cost[i-j]," cost[i]=", cost[i] # print "cost[",i,"] is now ", cost[i] print cost def getAvgCost(cost): total = score=0.0 for i in range(1, maxN): total+= cost[i] # print "# of coins for ", i," is ", cost[i]; if i % 5 is 0: score+=cost[i]*float(n) else: score+=cost[i] #print "total:",total,"avg cost:",(total/(len(cost)-1)) ,"\n score: ", score; return (score, (total/(len(cost)-1))); ''' Eliminating search space: (A: given an upper bound, B, which the highest # of coins needed to pay any amount from 1-99cent, you must have a coin at least total/B. i.e. if B = 4, your denomination must have 25. i.e. if maxN{denom}<25, useless. Say B = 5, you must have a 20) B: Who needs [1,2,3,4,9], or [1,2,3,4,99]?. Given d=[d1,d2,d3,d4,d5] Esp the distance bewteen d4, d5 should be big enough. Idea of Fast foward: when evaluating every x for [d1,d2,d3,d4,x]. If [d1,d2,d3,d4,x-1] does not do well, instead of incrementing by 1, fast forward. It's probably not because of the x, but the set [d1,d2,d3,d4] What is "not doing well"? have a running avg score so far, if that set [d1,d2,d3,d4] does not go above the running avg, fast forward = i.e. TAKE THE WINNERS OF SMALLER SET C: Do we need any coin bigger than .50?? Say there exists d5=.75, it is good for the last quarter of a dollar, we can use the first quarter to calculate the last quarter, but if 50cent coin allows us to use half of to copy over to the second half. i.e. with 75cent, you can copy the first 1/4, to the last 1/4 with all val +1 with 50cent, you can copy the first 1/2 to the last 1/2 with all val +1, 50cent is much more space efficient ''' def initCost(denom): cost = [float('inf')] * maxN for i in xrange(len(denom)): cost[denom[i]]=1 return cost def nextBest(lastWinner): global counter bestScore = (float('inf'), float('inf')) bestCost = [] bestSoFar = [] for i in xrange(lastWinner[len(lastWinner)-1], maxN/2): tryDenom = lastWinner+[i] cost = initCost(tryDenom) counter += 1 calcCost(tryDenom, cost) #print "for ", tryDenom result = getAvgCost(cost) if result[0] < bestScore[0]: bestScore = result bestSoFar = tryDenom bestCost = cost #print "bestCost!! %s" % bestCost #print "With N=%s and %s denom, the best score is: %s with avg # of coins:%s with denomination: %s" %(n, len(lastWinner)+1, bestScore[0], bestScore[1],bestSoFar) #print "With best cost %s"%bestCost return (bestSoFar, bestScore) def nextWinners(lastWinners): global counter newWinners = [([],(float('inf'), 1))]*outOf bestScore = [(float('inf'), float('inf'))] bestCost = [] bestSoFar = [] for eachWinner in lastWinners: #eachWinner is a tuple of ([denom], (score,avg)) thisDenom = eachWinner[0] if thisDenom[len(thisDenom)-1] > maxN/2: print thisDenom for i in xrange(thisDenom[len(thisDenom)-1], maxN/2): tryDenom = thisDenom+[i] cost = initCost(tryDenom) counter += 1 calcCost(tryDenom, cost) #result has [ (score), (avg)] result = getAvgCost(cost) contestant = (tryDenom, result) #print contestant newWinners = getTopX(contestant, newWinners) #print "bestCost!! %s" % bestCost #print "With N=%s and %s denom, the best score is: %s with avg # of coins:%s with denomination: %s" %(n, len(lastWinner)+1, bestScore[0], bestScore[1],bestSoFar) #print "With best cost %s"%bestCost return newWinners#(bestSoFar, bestScore) ''' winner is in tulple (bestDenomSoFar, itsScore) add it to the list of bestWinners, sort by their score and take the top 3 ''' def getTopX(winner, bestWinners): #winner = ([1,10], (900.0, 9)) #bestWinners = [([],(float('inf'), 1)),([],(float('inf'), 1)),([],(float('inf'), 1))] bestWinners+=[winner] #if i==11 or i==10 or i==9: print "with", i,"before sort: ", bestWinners bestWinners= list(sorted(bestWinners, key=lambda item:item[1][0], reverse=True)) #if i==11 or i==10 or i==9:print "with",i,"after sort: ", bestWinners[1:] return bestWinners[1:] def test(): global n, outOf n= 1 outOf = 30 bestTwos = nextWinners([ ([1], (0,0)) ]) print "bestTwos:", bestTwos bestThrees = nextWinners(bestTwos) print "bestThrees:", bestThrees bestFours = nextWinners(bestThrees) print "bestFours:", bestFours bestFives = nextWinners(bestFours) print "best5s:", bestFives print "the best is:", bestFives[outOf-1:] def contestOf(arg1, numberOfContestants): global n, outOf n= arg1 if (numberOfContestants >= maxN/2): raise Exception('the number of contestants per stage is too big') outOf = numberOfContestants bestTwos = nextWinners([ ([1], (0,0)) ]) #print "bestTwos:", bestTwos bestThrees = nextWinners(bestTwos) #print "bestThrees:", bestThrees bestFours = nextWinners(bestThrees) #print "bestFours:", bestFours bestFives = nextWinners(bestFours) #print "best5s:", bestFives best = bestFives[outOf-1:][0] print "the best is:", bestFives[outOf-1:] print "With N=%s the best denom is %s with score:%s, avg:%s"%(n, best[0], best[1][0], best[1][1]) print "# of contestants per stage=%s"% outOf def onlyBests(arg1): global counter, n n = arg1 counter = 0 bestTwo= nextBest([1]) bestThree = nextBest(bestTwo[0]) bestFour = nextBest(bestThree[0]) bestFive = nextBest(bestFour[0]) print "With N=%s the best denom is %s with score:%s, avg:%s"%(n, bestFive[0], bestFive[1][0], bestFive[1][1]) #print "Looked at %s denominations" % counter def main(): # n = raw_input("What's the N?") global n n = sys.argv[1] start = time.clock() contestOf(n, 20) print "It took", (time.clock()-start),"seconds to complete" print "now:", time.clock(), "start:", start if __name__ == '__main__': main();
b0ec44a2f01ffcda91228ad9b539f1d578117b2a
tdraebing/Data_Analyst_Nanodegree-Project3
/src/Project/createdb.py
480
3.53125
4
############################################################### #Script to load data from a JSON file into a MongoDB database.# ############################################################### import json #function that facilitates the insertion of the data stored in a JSON file into the database def insert_data(db, db_name, json_file): with open(json_file) as f: for line in f: data = json.loads(line) db[db_name].insert(data)
988467eeb77c89122a0a7d6ed42b3f192eda8fed
deadsummer/project
/попытки/window.py
382
3.640625
4
from tkinter import * from tkinter.filedialog import * import fileinput def _open(): op = askopenfilename() for l in fileinput.input(op): txt.insert(END,l) root = Tk() m = Menu(root) root.config(menu=m) fm = Menu(m) m.add_cascade(label="File",menu=fm) fm.add_command(label="Open...",command=_open) txt = Text(root,width=40,height=15,font="12") txt.pack() root.mainloop()
ddbc8bd50ff4975e6007358dc5ae97d8e09dcd39
MOUDDENEHamza/JustGetTen
/possibles.py
1,356
3.921875
4
""" n parameter can be found from the board """ ''' the funtion tests if the cells have an adjacents cells of same values ''' def has_adjacent_tile(board, x, y): adjacent = False n = len(board) value = board[x][y] xUp, xDown = x - 1, x + 1 yLeft, yRight = y - 1, y + 1 if xUp < 0: xUp = 0 if xDown > n - 1: xDown = n - 1 if yRight > n - 1: yRight = n - 1 if yLeft < 0: yLeft = 0 if xUp != x: if board[xUp][y] == value: adjacent = True if xDown != x: if board[xDown][y] == value: adjacent = True if yLeft != y: if board[x][yLeft] == value: adjacent = True if yRight != y: if board[x][yRight] == value: adjacent = True return adjacent ''' the function tests if the shot still playable on the grid ''' def is_move_available(board, x, y): for i in range(len(board)): for j in range(len(board)): if has_adjacent_tile(board, x, y) == False: print("no move still playable") return False return True ''' returns the max value of te given board ''' def get_max_board_value(board): max = 1 for line in board: for item in line: if item > max: max = item return max
b1dff1aea71ec7ebfec48db1ec029a2a7dd349d2
artneuronmusic/Exercise2_SoftwareTesting
/app.py
1,673
4.15625
4
from blog import Blog blogs = dict() MENU_PROMPT = "Enter 'c' to create a blog, 'l' to list blog, 'r' to read one, 'p' to create a post, 'q' to quit" POST_TEMPLATE = '''---{}---{}''' def menu(): print_blogs() selection = input(MENU_PROMPT) while selection != 'q': if selection == 'c': create_blog() elif selection == 'l': print_blogs() elif selection == 'r': read_blog() elif selection == 'p': ask_create_post() selection = input(MENU_PROMPT) print_blogs() def create_blog(): title = input("Whats the title of the post? ") author = input("Who is the writer? ") blogs[title] = Blog(title, author) #set the blogs as dict, then get value from blogs[key] print(blogs[title]) def print_blogs(): for key, blog in blogs.items(): print("- {}".format(blog)) #print(key) #print(blog) def read_blog(): blog_title = input("Enter the blog title you want to read:") for i in blogs[blog_title].posts: try: len(blogs[blog_title].posts) != 0 print(i) except KeyError: print("There is no such title") """ print_posts(blogs[blog_title]) def print_posts(blog): for post in blog.posts: print_post(post) def print_post(post): print(POST_TEMPLATE.format(post.name, post.content)) """ def ask_create_post(): blog_name = input("Enter the blog title you want to write post in: ") name = input("Whats the name of the post: ") content = input("enter ur post content: ") blogs[blog_name].create_post(name, content) menu()
dc7e951d4e963a584889ee005ac10ccb0aa747a1
teejas/PythonProjects
/ex5.py
606
3.734375
4
my_name = 'Tejas A. Siripurapu' my_age = 18 # years my_height = 73 # inches my_weight = 143 # pounds my_eyes = 'brown' my_teeth = 'white' my_hair = 'black' # Let's put these variables to use print "Let's talk about %r." % my_name print "He's %r inches tall" % my_height print "He weighs %r pounds" % my_weight print "That's actually not that light" print "He's got %r hair and %r eyes" % (my_hair, my_eyes) print "His teeth are usually %r if he brushes" % my_teeth # This line is tricky be careful when typing it print "If I add %r, %r, and %r I get %r" % (my_age, my_weight, my_height, my_age + my_weight + my_height)
3ae2bb1a9966ca89dad7c95282becb9871388efb
danidbarrio/App_Gestion_Instituto_FINAL
/codigo_fuente/database.py
30,819
3.796875
4
import sqlite3 from tkinter import messagebox # Clase de la base de datos class DataBase: def __init__(self): # Creación y conexión a la base de datos self.con = sqlite3.connect('prestamos.db') # Cursor para recorrer la base de datos self.cur = self.con.cursor() # Creación de las tablas self.cur.execute("""CREATE TABLE if NOT EXISTS departamentos( id INTEGER PRIMARY KEY, nombre text NOT NULL);""") self.cur.execute("""CREATE TABLE if NOT EXISTS permisos( id INTEGER PRIMARY KEY, nombre text NOT NULL);""") self.cur.execute("""CREATE TABLE if NOT EXISTS profesores( id INTEGER PRIMARY KEY, user text NOT NULL, password text NOT NULL, nombre text NOT NULL, ape1 text NOT NULL, ape2 text, id_permisos INTEGER NOT NULL, FOREIGN KEY(id_permisos) REFERENCES permisos(id));""") self.cur.execute("""CREATE TABLE if NOT EXISTS profesores_departamentos( id_profesor INTEGER NOT NULL, id_depart INTEGER NOT NULL, FOREIGN KEY(id_profesor) REFERENCES profesores(id), FOREIGN KEY(id_depart) REFERENCES departmentos(id));""") self.cur.execute("""CREATE TABLE if NOT EXISTS estado( id INTEGER PRIMARY KEY, nombre text NOT NULL);""") self.cur.execute("""CREATE TABLE if NOT EXISTS material( id INTEGER PRIMARY KEY, nombre text NOT NULL, codigo text NOT NULL, id_estado INTEGER NOT NULL, FOREIGN KEY(id_estado) REFERENCES estado(id));""") self.cur.execute("""CREATE TABLE if NOT EXISTS prestamos( id INTEGER PRIMARY KEY, id_material INTEGER NOT NULL, id_profesor INTEGER NOT NULL, dia_ini text NOT NULL, mes_ini text NOT NULL, ano_ini text NOT NULL, dia_fin text, mes_fin text, ano_fin text, FOREIGN KEY(id_material) REFERENCES material(id), FOREIGN KEY(id_profesor) REFERENCES profesor(id));""") # Generación automática de los permisos de ADMINISTRADOR, ENCARGADO y PROFESOR para los usuarios is_admin = False is_manager = False is_profe = False self.cur.execute("SELECT nombre FROM permisos;") estados = self.cur.fetchall() for est in estados: if str(est) == "('ADMINISTRADOR',)": is_admin = True elif str(est) == "('ENCARGADO',)": is_manager = True elif str(est) == "('PROFESOR',)": is_profe = True if not is_admin: self.cur.execute("""INSERT INTO permisos (nombre) VALUES ('ADMINISTRADOR');""") if not is_manager: self.cur.execute("""INSERT INTO permisos (nombre) VALUES ('MANAGER');""") if not is_profe: self.cur.execute("""INSERT INTO permisos (nombre) VALUES ('PROFESOR');""") # Generación automática de los usuarios ADMIN y MANAGER para la gestión de la base de datos desde su creación is_admin = False is_manager = False self.cur.execute("SELECT user FROM profesores;") profes_iniciales = self.cur.fetchall() for prof_ini in profes_iniciales: if str(prof_ini) == "('admin',)": is_admin = True elif str(prof_ini) == "('manager',)": is_manager = True if not is_admin: self.cur.execute("""INSERT INTO profesores (user, password, id_permisos, nombre, ape1, ape2) VALUES ('admin', 'admin', 1, 'ADMIN', 'ADMIN', '');""") if not is_manager: self.cur.execute("""INSERT INTO profesores (user, password, id_permisos, nombre, ape1, ape2) VALUES ('manager', 'manager', 2, 'MANAGER', 'MANAGER', '');""") # Generación automática de los ESTADOS DISPONIBLE y NO DISPONIBLE de los materiales a dar en los préstamos is_libre = False is_prestado = False self.cur.execute("SELECT nombre FROM estado;") estados = self.cur.fetchall() for est in estados: if str(est) == "('DISPONIBLE',)": is_libre = True elif str(est) == "('NO DISPONIBLE',)": is_prestado = True if not is_libre: self.cur.execute("""INSERT INTO estado (nombre) VALUES ('DISPONIBLE');""") if not is_prestado: self.cur.execute("""INSERT INTO estado (nombre) VALUES ('NO DISPONIBLE');""") # Ejecución de las instrucciones self.con.commit() # Finalización de la conexión a la base de datos def __del__(self): self.con.close() # Funciones para manejar la tabla DEPARTAMENTOS # Mostrar todos los departamentos def view_departs(self): # Seleccionamos y devolvemos todos los departamentos guardados self.cur.execute("SELECT * FROM departamentos;") result = self.cur.fetchall() return result #Añadir departamento def insert_depart(self, nombre): # Añadimos el departamento a la tabla con los datos dados self.cur.execute("INSERT INTO departamentos VALUES (NULL, '"+nombre.upper()+"');") self.con.commit() # Modificar departamento def update_depart(self, id_update, nombre): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no modificarla if messagebox.askokcancel("Atención", "¿Está seguro de modificar la entrada seleccionada con los datos que va a proporcionar?"): # Se actualiza la entrada con el id dado (id_update) y se le cambia el nombre por el introducido (nombre) self.cur.execute("UPDATE departamentos SET nombre = '"+nombre.upper()+"' WHERE id = "+id_update+";") self.con.commit() # Eliminar departamento def delete_depart(self, id_delete): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no eliminarla if messagebox.askokcancel("Atención", "¿Está seguro de borrar la entrada seleccionada?"): # Se eliminan las relaciones que tuviera en la tabla profesores_departamentos self.cur.execute("DELETE FROM profesores_departamentos WHERE id_depart = "+id_delete+";") self.con.commit() # Se elimina el departamento con el id dado (id_delete) self.cur.execute("DELETE FROM departamentos WHERE id = "+id_delete+";") self.con.commit() # Buscar departamento def search_depart(self, nombre): # Seleccionamos y devolvemos el departamento que coincida con los datos dados self.cur.execute("SELECT * FROM departamentos WHERE nombre = '"+nombre.upper()+"';") result = self.cur.fetchall() return result # Funciones para manejar la tabla MATERIAL # Mostrar todos los materiales def view_material(self): # Seleccionamos y devolvemos la información de todos los materiales guardados self.cur.execute("""SELECT material.id, material.nombre, material.codigo, estado.nombre FROM material, estado WHERE estado.id = material.id_estado;""") result = self.cur.fetchall() return result # Añadir material def insert_material(self, nombre, codigo, estado): id_estado = 0 # Valor para ID_ESTADO en caso de que el estado sea "Disponible" o está vacío (""). if estado.upper() == "DISPONIBLE" or estado == "": id_estado = 1 # Valor para ID_ESTADO en caso de que el estado sea "No Disponible". elif estado.upper() == "NO DISPONIBLE": id_estado = 2 # Se compeueba que se ha introducido un estado correcto if id_estado != 0: if estado == "": # Si no se ha introducido ningún estado, se alerta de que se establecerá el estado por defecto ("Disponible"). messagebox.showinfo("¡Atención!", "Se signará al material el estado por defecto ('Disponible').") # Añadimos el material a la tabla self.cur.execute("INSERT INTO material (nombre, codigo, id_estado) VALUES (?, ?, ?);", (nombre.upper(), codigo.upper(), id_estado)) self.con.commit() else: # En caso de no introducir un estado válido saltará una advertencia. messagebox.showwarning("Error", "El estado del material introducido no está permitido. Debe ser 'Disponible' o 'No Disponible'. Si no introduce ningún estado, se establecerá como 'Disponible'.") # Modificar material def update_material(self, id_update, nombre, codigo, estado): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no modificarla como ha indicado if messagebox.askokcancel("Atención", "¿Está seguro de modificar la entrada seleccionada con los datos que va a proporcionar?"): id_estado = 0 # Valor para ID_ESTADO en caso de que el estado sea "Disponible" o está vacío (""). if estado.upper() == "DISPONIBLE" or estado == "": id_estado = 1 # Valor para ID_ESTADO en caso de que el estado sea "No Disponible". elif estado.upper() == "NO DISPONIBLE": id_estado = 2 # Se compeueba que se ha introducido un estado correcto if id_estado != 0: # Se actualiza la entrada con el id seleccionado (id_update) self.cur.execute("UPDATE material SET nombre = ?, codigo = ?, id_estado = ? WHERE id = ?", (nombre, codigo, id_estado, id_update)) self.con.commit() else: # En caso de no introducir un estado válido saltará una advertencia. messagebox.showwarning("Error", "El estado del material introducido no está permitido. Debe ser 'Disponible' o 'No Disponible'. Si no introduce ningún estado, se establecerá como 'Disponible'.") # Eliminar material def delete_material(self, id_delete): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no eliminarla en realidad if messagebox.askokcancel("Atención", "¿Está seguro de borrar la entrada seleccionada?"): # Se eliminan las relaciones que tuviera en la tabla de préstamos self.cur.execute("DELETE FROM prestamos WHERE id_material = "+id_delete+";") self.con.commit() # Se elimina el material con el id dado (id_delete) self.cur.execute("DELETE FROM material WHERE id = "+id_delete+";") self.con.commit() # Buscar material def search_material(self, nombre, codigo, estado): query = """SELECT material.id, material.nombre, material.codigo, estado.nombre FROM material, estado WHERE estado.id = material.id_estado""" # Comprobamos sobre que datos se desea buscar if estado != "": query += " AND estado.nombre = '"+estado.upper()+"'" if nombre != "": query += " AND material.nombre = '"+nombre.upper()+"'" if codigo != "": query += " AND material.codigo = '"+codigo.upper()+"'" # Seleccionamos y devolvemos los materiales que coincidan con los parámetros dados self.cur.execute(query) result = self.cur.fetchall() return result # Funciones para la tabla PROFESORES # Mostrar todos los profesores y usuarios def view_profes(self): # Seleccionamos y devolvemos el todos los profesores guardados self.cur.execute("""SELECT profesores.id, permisos.nombre||'-', profesores.nombre, profesores.ape1, profesores.ape2, profesores.user, profesores.password FROM profesores, permisos WHERE permisos.id = profesores.id_permisos;""") result = self.cur.fetchall() return result # Añadir profesor def insert_profe(self, permisos, nombre, ape1, ape2, user, password): id_permisos = 0 # Valor para ID_PERMISOS en caso de que los permisos sean de "Administrador". if permisos.upper() == "ADMINISTRADOR": id_permisos = 1 # Valor para ID_PERMISOS en caso de que los permisos sean de "Encargado". elif permisos.upper() == "ENCARGADO": id_permisos = 2 # Valor para ID_PERMISOS en caso de que los permisos sean de "Profesor". elif permisos.upper() == "PROFESOR" or permisos == "": id_permisos = 3 # Se comprueba que se han introducido unos permisos correctos. if id_permisos != 0: if permisos == "": # Si no se ha introducido ningún tipo depermiso, se alerta de que se establecerán los permisos por defecto ("Profesor"). messagebox.showinfo("¡Atención!", "Se asignarán al nuevo usuario los permisos por defecto ('Profesor').") # Añadimos el profesor a la tabla self.cur.execute("INSERT INTO profesores (user, password, id_permisos, nombre, ape1, ape2) VALUES (?, ?, ?, ?, ?, ?);", (user, password, id_permisos, nombre.upper(), ape1.upper(), ape2.upper())) self.con.commit() else: # Alerta en caso de que los permisos sean incorrectos messagebox.showwarning("Error", "Los permisos que desea asignar al nuevo usuario son incorrectos. Deben ser de 'Administrador', 'Encargado' o 'Profesor'.") # Modificar profesor def update_profe(self, id_update, permisos, nombre, ape1, ape2, user, password): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no modificarla como ha indicado if messagebox.askokcancel("Atención", "¿Está seguro de modificar la entrada seleccionada con los datos que va a proporcionar?"): id_permisos = 0 if permisos.upper() == "ADMINISTRADOR": id_permisos = 1 elif permisos.upper() == "ENCARGADO": id_permisos = 2 elif permisos.upper() == "PROFESOR": id_permisos = 3 if id_permisos != 0: # Se actualiza la entrada con el id dado (id_update) y se le dan los parámetros introducidos self.cur.execute("UPDATE profesores SET user = ?, password = ?, id_permisos = ?, nombre = ?, ape1 = ?, ape2 = ? WHERE id = ?", (user, password, id_permisos, nombre.upper(), ape1.upper(), ape2.upper(), id_update)) self.con.commit() else: # Alerta en caso de que los permisos sean incorrectos messagebox.showwarning("Error", "Los permisos que desea asignar al usuario seleccionado son incorrectos. Deben ser de 'Administrador', 'Encargado' o 'Profesor'.") # Eliminar profesor def delete_profe(self, id_delete): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no eliminarla en realidad if messagebox.askokcancel("Atención", "¿Está seguro de borrar la entrada seleccionada?"): # Se eliminan las relaciones que tuviera en la tabla de préstamos self.cur.execute("DELETE FROM prestamos WHERE id_profesor ="+id_delete+";") self.con.commit() # Se eliminan las relaciones que tuviera en la tabla profesores_departamentos self.cur.execute("DELETE FROM profesores_departamentos WHERE id_profesor = "+id_delete+";") self.con.commit() # Se elimina el profesor con el id dado (id_delete) self.cur.execute("DELETE FROM profesores WHERE id = "+id_delete+";") self.con.commit() # Buscar profesor def search_profe(self, permisos, nombre, ape1, ape2, user, password): query = """SELECT profesores.id, permisos.nombre||'-', profesores.nombre, profesores.ape1, profesores.ape2, profesores.user, profesores.password FROM profesores, permisos WHERE permisos.id = profesores.id_permisos""" # Comprobamos sobre que datos se desea buscar if permisos != "": query += " AND permisos.nombre = '"+permisos.upper()+"'" if nombre != "": query += " AND profesores.nombre = '"+nombre.upper()+"'" if ape1 != "": query += " AND profesores.ape1 = '"+ape1.upper()+"'" if ape2 != "": query += " AND profesores.ape2 = '"+ape2.upper()+"'" if user != "": query += " AND profesores.user = '"+user+"'" if password != "": query += " AND profesores.password = '"+password+"'" # Seleccionamos y devolvemos la información del profesor que coincida con los parámetros dados self.cur.execute(query) result = self.cur.fetchall() return result # Relaciones entre profesores y departamentos # Mostrar todos los departamentos a los que pertenece el profesor seleccionado def view_profe_departs(self, id_user): # Seleccionamos y devolvemos todos los departamentos relacionados con el profesor indicado self.cur.execute("""SELECT departamentos.id, departamentos.nombre FROM departamentos, profesores_departamentos WHERE departamentos.id = profesores_departamentos.id_depart AND profesores_departamentos.id_profesor = """+id_user+""" ORDER BY departamentos.id""") result = self.cur.fetchall() return result # Buscar departamentos a los que pertenece el profesor seleccionado def search_profe_depart(self, nombre_depart, id_user): # Seleccionamos y devolvemos el departamento que coincida con el nombre dado self.cur.execute("""SELECT departamentos.id, departamentos.nombre FROM departamentos, profesores_departamentos WHERE departamentos.id = profesores_departamentos.id_depart AND profesores_departamentos.id_profesor = ? AND departamentos.nombre = ?""", (id_user, nombre_depart.upper())) result = self.cur.fetchall() return result # Eliminar departamento al que pertenece el profesor seleccionado def delete_profe_depart(self, id_depart, id_user): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no eliminarla en realidad if messagebox.askokcancel("Atención", "¿Está seguro de sacar al profesor del departamento seleccionado?"): # Se elimina el departamento del profesor con el id dado (id_delete) self.cur.execute("""DELETE FROM profesores_departamentos WHERE id_depart = ? AND id_profesor = ?""", (id_depart, id_user)) self.con.commit() # Buscar departamentos que añadir al profesor seleccionado def search_seldepart(self, nombre_depart, id_user): # Seleccionamos y devolvemos el departamento que coincida con el nombre dado self.cur.execute("""SELECT departamentos.id, departamentos.nombre FROM departamentos, profesores_departamentos WHERE departamentos.id = profesores_departamentos.id_depart AND profesores_departamentos.id_profesor = ? AND departamentos.nombre != ?""", (id_user, nombre_depart.upper())) result = self.cur.fetchall() return result # Añadir departamento que añadir al profesor seleccionado def add_seldepart(self, id_user, id_depart): # Comprobamos que el profesor no pertenezca ya al departamento al que se le va a añadir self.cur.execute("""SELECT id_depart FROM profesores_departamentos WHERE id_profesor = ? AND id_depart = ?""", (id_user, id_depart)) pertenece = self.cur.fetchall() if not pertenece: # Añadimos el departamento al profesor self.cur.execute("""INSERT INTO profesores_departamentos (id_profesor, id_depart) VALUES (?, ?);""", (id_user, id_depart)) self.con.commit() else: messagebox.showwarning("Error", "El profesor ya pertenece al departamento seleccionado.") # Funciones para la tabla PRESTAMOS cuando se accede como ADMIN # Mostrar todos los préstamos de todos los usuarios def view_prestamos_admin(self): #Visualizamos todos los prestamos self.cur.execute("""SELECT prestamos.id, profesores.user, material.nombre, material.codigo, prestamos.dia_ini, '/'||prestamos.mes_ini, '/'||prestamos.ano_ini, '-'||prestamos.dia_fin, '/'||prestamos.mes_fin, '/'||prestamos.ano_fin FROM prestamos, profesores, material WHERE profesores.id = prestamos.id_profesor AND material.id = prestamos.id_material""") result = self.cur.fetchall() return result # Modificar préstamo def update_prestamo(self, id_update, user, material, cod, dia_ini, mes_ini, ano_ini, dia_fin="", mes_fin="", ano_fin=""): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no modificarla como ha indicado if messagebox.askokcancel("Atención", "¿Está seguro de modificar la entrada seleccionada con los datos que va a proporcionar?"): # Obtenemos el id del profesor y del material para actualizar la tabla préstamos id_prof = "" id_mat = "" self.cur.execute("SELECT id FROM profesores WHERE user = '"+user+"'") id_profesor = self.cur.fetchall() for id_pr in id_profesor: for ip in id_pr: id_prof = ip self.cur.execute("SELECT id FROM material WHERE nombre = ? AND codigo = ?", (material.upper(), cod.upper())) id_material = self.cur.fetchall() for id_mt in id_material: for im in id_mt: id_mat = im # Se actualiza la entrada con el id dado (id_update) y se le cambia los parámetros introducidos self.cur.execute("""UPDATE prestamos SET id_material = ?, id_profesor = ?, dia_ini = ?, mes_ini = ?, ano_ini = ?, dia_fin = ?, mes_fin = ?, ano_fin = ? WHERE id = ?""", (id_mat, id_prof, dia_ini, mes_ini, ano_ini, dia_fin, mes_fin, ano_fin, id_update)) self.con.commit() # Eliminar préstamo def delete_prestamo(self, id_delete, cod): # Si se ha seleccionado una entrada, se avisa al usuario por si quiere no eliminarla en realidad if messagebox.askokcancel("Atención", "¿Está seguro de eliminar el préstamo seleccionado?"): # Se comprueba si el préstamo a eliminar finalizó self.cur.execute("SELECT dia_fin FROM prestamos WHERE id = "+id_delete) fin = self.cur.fetchall() for f in fin: # Si no ha finalizado, volvemos a poner el material del préstamo como DISPONIBLE (id_estado = 1) if str(f) == "('',)": self.cur.execute("UPDATE material SET id_estado = 1 WHERE codigo = '"+cod+"'") self.con.commit() # Se elimina el préstamo con el id dado (id_delete) self.cur.execute("DELETE FROM prestamos WHERE id = "+id_delete) self.con.commit() # Buscar préstamo de cualquier usuario def search_prestamo_admin(self, user, material, cod, dia_ini, mes_ini, ano_ini, dia_fin, mes_fin, ano_fin): query = """SELECT prestamos.id, profesores.user, material.nombre, material.codigo, prestamos.dia_ini, '/'||prestamos.mes_ini, '/'||prestamos.ano_ini, '-'||prestamos.dia_fin, '/'||prestamos.mes_fin, '/'||prestamos.ano_fin FROM prestamos, profesores, material WHERE profesores.id = prestamos.id_profesor AND material.id = prestamos.id_material""" # Comprobamos sobre que datos se desea buscar if user != "": query += " AND profesores.user = '"+user+"'" if material != "": query += " AND material.nombre = '"+material.upper()+"'" if cod != "": query += " AND material.codigo = '"+cod.upper()+"'" if dia_ini != "": query += " AND prestamos.dia_ini = '"+dia_ini+"'" if mes_ini != "": query += " AND prestamos.mes_ini = '"+mes_ini+"'" if ano_ini != "": query += " AND prestamos.ano_ini = '"+ano_ini+"'" if dia_fin != "": query += " AND prestamos.dia_fin = '"+dia_fin+"'" if mes_fin != "": query += " AND prestamos.mes_fin = '"+mes_fin+"'" if ano_fin != "": query += " AND prestamos.ano_fin = '"+ano_fin+"'" self.cur.execute(query) result = self.cur.fetchall() return result # Funciones para la tabla PRESTAMOS como profesor # Mostrar todos los préstamos del profesor que ha iniciado sesión def view_prestamos(self, user): # Visualizamos los prestamos con un usuario normal self.cur.execute("""SELECT prestamos.id, material.nombre, material.codigo, prestamos.dia_ini, '/'||prestamos.mes_ini, '/'||prestamos.ano_ini, '-'||prestamos.dia_fin, '/'||prestamos.mes_fin, '/'||prestamos.ano_fin FROM prestamos, profesores, material WHERE profesores.id = prestamos.id_profesor AND material.id = prestamos.id_material AND profesores.user = '"""+user+"'") result = self.cur.fetchall() return result # Buscar préstmos del profesor que ha iniciado sesión def search_prestamo(self, user, material, cod, dia_ini, mes_ini, ano_ini, dia_fin, mes_fin, ano_fin): query = """SELECT prestamos.id, material.nombre, material.codigo, prestamos.dia_ini, '/'||prestamos.mes_ini, '/'||prestamos.ano_ini, '-'||prestamos.dia_fin, '/'||prestamos.mes_fin, '/'||prestamos.ano_fin FROM prestamos, profesores, material WHERE profesores.id = prestamos.id_profesor AND material.id = prestamos.id_material""" # Comprobamos sobre que datos se desea buscar if user != "": query += " AND profesores.user = '"+user+"'" if material != "": query += " AND material.nombre = '"+material.upper()+"'" if cod != "": query += " AND material.codigo = '"+cod.upper() + "'" if dia_ini != "": query += " AND prestamos.dia_ini = '"+dia_ini+"'" if mes_ini != "": query += " AND prestamos.mes_ini = '"+mes_ini+"'" if ano_ini != "": query += " AND prestamos.ano_ini = '"+ano_ini+"'" if dia_fin != "": query += " AND prestamos.dia_fin = '"+dia_fin+"'" if mes_fin != "": query += " AND prestamos.mes_fin = '"+mes_fin+"'" if ano_fin != "": query += " AND prestamos.ano_fin = '"+ano_fin+"'" self.cur.execute(query) result = self.cur.fetchall() return result # Añadir préstamo para cualquier usuario def add_prestamo(self, user, id_material, dia_ini, mes_ini, ano_ini): # Obtenemos el id del profesor id_prof = "" self.cur.execute("SELECT id FROM profesores WHERE user = '"+user+"'") id_profesor = self.cur.fetchall() for id_pr in id_profesor: for ip in id_pr: id_prof = ip # Realizamos el préstamo self.cur.execute("""INSERT INTO prestamos (id_material, id_profesor, dia_ini, mes_ini, ano_ini, dia_fin, mes_fin, ano_fin) VALUES (?, ?, ?, ?, ?, ?, ?, ?);""", (id_material, id_prof, dia_ini, mes_ini, ano_ini, "", "", "")) self.con.commit() # Cambiamos el estado del material prestado a NO DISPONIBLE (id_estado = 2) self.cur.execute("UPDATE material SET id_estado = 2 WHERE id = "+id_material) self.con.commit() # Finalizar préstamo para cualquier usuario def finish_prestamo(self, id_prestamo, id_material, dia_fin, mes_fin, ano_fin): # Se alerta de la finalixzación del préstamo al usuario if messagebox.askokcancel("Atención", "¿Está seguro de terminar el préstamo?"): # Se le añade la fecha de finalización al préstamo indicado self.cur.execute("UPDATE prestamos SET dia_fin = ?, mes_fin = ?, ano_fin = ? WHERE id = ?", (dia_fin, mes_fin, ano_fin, id_prestamo)) self.con.commit() # Cambiamos el estado del material prestado a DISPONIBLE (id_estado = 1) self.cur.execute("UPDATE material SET id_estado = 1 WHERE id = "+id_material) self.con.commit()
f03bfa2da2b2c63e6b574a16c17b694a4b8a6424
diogo-as/codes
/randomize.py
700
3.84375
4
import random, collections items = ['here', 'are', 'some', 'strings', 'of', 'which', 'we', 'will', 'select', 'one'] rand_item = items[random.randrange(len(items))] #print(rand_item) participantes = { 'diogo':'', 'nanda':'', 'alice':'', 'tico':'', 'lorena':'', 'kleyton':'', 'pedro':'', 'regina':'', 'arthur':'', 'duda':'' } sorteio = {} for nome in participantes.keys(): a = random.choice(participantes.keys()) while (a == nome) or (a in participantes.values()): a = random.choice(participantes.keys()) participantes[nome] = a for a, b in sorted(participantes.items()): print("Participante: "+a+" Tirou: "+b)
9749245820a806a3da1f256446398a3558cabc6a
darthlyvading/fibonacci
/fibonacci.py
369
4.25
4
terms = int(input("enter the number of terms ")) n1 = 0 n2 = 1 count = 0 if terms <= 0: print("terms should be > 0") elif terms == 1: print("Fibonacci series of ",terms," is :") print(n1) else: print("Fibonacci series is :") while count < terms: print(n1) total = n1 + n2 n1 = n2 n2 = total count += 1