blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
8ab27a2740fb89fe98d49ea63d334f7e5caec3c0
kenu/g-coin
/gcoin/proof.py
756
3.84375
4
import hashlib DIFFICULTY = 1 # number of digits is difficulty VALID_DIGITS = '0' * DIFFICULTY def valid_proof(last_proof, proof): """ Validates proof last digits of hash(last_proof, proof) == VALID_DIGITS Args: last_proof (int): previous proof proof (int): proof to validate Returns: bool: """ proof_seed = '{0}{1}'.format(last_proof, proof).encode() proof_hash = hashlib.sha256(proof_seed).hexdigest() return proof_hash[:DIFFICULTY] == VALID_DIGITS def find_proof(last_proof): """proof of work Args: last_proof (int): Returns: int: proof """ proof = 0 while valid_proof(last_proof, proof) is False: proof += 1 return proof
86850fbb6c751efce65db5088fb83dee06b6ae84
chrisullyott/wordsearch-solver
/app/file.py
205
3.9375
4
""" Helpers for files. """ def read_file_upper(filename): """Read a file as an uppercase string.""" with open(filename) as file: contents = file.read().strip().upper() return contents
d11c1c967cc19dff7e538080266d08eb9f148366
GSacchetti/Segmentation-of-multispectral-and-thermal-images-with-U-NET
/Construction_data/excel_to_tif_array.py
5,669
3.578125
4
#######. This algorithm is to convert the excel files into tiff images and arrays. ####### #Our dataset were in the form of excel tables, to convert these tables into a tiff image, I created this Convert function. #To perform this conversion, we have calculated a displacement step called "step", #because this table represents a multispectral and thermal georeferential part (you can see the different #columns in the data / Excel folder) extracted from ERDAS software, so the step represents its resolution. #We can display them all 7 at once, for that we saved them in pictures but each length differently #(You can see it in the data / TIFandNPY folder #Loading packages from PIL import Image import xlrd import numpy as np import os,sys from skimage.io import imsave,imread import math from os.path import join #import pathproject as pp #TODO creation of a file containing every paths def mymkdir(path): if not os.path.exists(path): os.mkdir(path) def Convert(PathImportExcel,PathExportTif, channels=[3,4,5,6,7,8,9], step=12,factor=1000): print('The channels used are : ',channels) #Initialization of indices of images for each channel print(os.listdir(PathImportExcel)) for element in list(os.listdir(PathImportExcel)): if element.find('~$')==-1 and element.find('.D')==-1: name=element.replace('.xlsx','') print(element) file= xlrd.open_workbook(PathImportExcel+element) #Initilization of indice of subsets for k in file.sheet_names(): tableau = file.sheet_by_name(str(k)) # Writting the number of lines of each subset print('le nombre de lignes de '+str(k)+' %s ' % tableau.nrows) # Writting the number of lines of each subset print('le nombre de colonnes '+str(k)+' '+'%s ' % tableau.ncols) minX=sys.maxsize maxX=-sys.maxsize minY=sys.maxsize maxY=-sys.maxsize for l in range(1,tableau.nrows): x=tableau.cell_value(l,1)*factor minX=min(minX,x) maxX=max(maxX,x) y=tableau.cell_value(l,2)*factor minY=min(minY,y) maxY=max(maxY,y) #Determination's resolution tab=[] for i in range(1,4000): tab.append(tableau.cell_value(i,1)*factor) table=[] for i in tab: if not i in table: table.append(i) step=int(table[2]-table[1]) xSize=1+(maxX-minX)/step ySize=1+(maxY-minY)/step size =(round(xSize),round(ySize)) print('the image"s size:',size) namesubset=name+'_'+str(k) image_tif_path = join(PathExportTif,namesubset,'ImageTif') image_array_path = join(PathExportTif,namesubset,'ImageArray') mask_tif_path = join(PathExportTif,namesubset,'MaskTif') mask_array_path = join(PathExportTif,namesubset,'MaskArray') mymkdir(join(PathExportTif,namesubset)) mymkdir(image_tif_path) mymkdir(image_array_path) mymkdir(mask_tif_path) mymkdir(mask_array_path) matrix=np.zeros([size[0],size[1],len(channels)], dtype=np.float32) for cid, h in enumerate(channels): image= np.zeros((size[0],size[1]), dtype=np.float32) for l in range(1,tableau.nrows): i=math.floor((tableau.cell_value(l,1)*factor-minX+step/2.)/step) j=math.floor((tableau.cell_value(l,2)*factor-minY+step/2.)/step) image[i,j]=(tableau.cell_value(l,h)) matrix[i,j,cid]=tableau.cell_value(l,h) imageint=(255*(image-image.min())/(image.max()-image.min())).astype(np.uint8) imsave(join(image_tif_path,name+'_'+str(k)+'_B'+str(cid)+'.tif'),imageint) #np.save(join(image_array_path,namesubset,'_image.npy'),matrix) np.save(PathExportTif+'/'+namesubset+'/'+'ImageArray'+'/'+namesubset+'_image.npy',matrix) #SAVE MASK image= np.zeros((size[0],size[1],1), dtype=np.uint8) for l in range(1,tableau.nrows): i=int((tableau.cell_value(l,1)*factor-minX)/step) j=int((tableau.cell_value(l,2)*factor-minY)/step) v=tableau.cell_value(l,11) if v=="other": image[i,j]=0 else: image[i,j]=255 #else: #print('UNNKOWN '+v) #quit() imsave(PathExportTif+'/'+namesubset+'/'+'MaskTif'+'/'+name+'_'+str(k)+'_mask.tif',image) np.save(PathExportTif+'/'+namesubset+'/'+'MaskArray'+'/'+namesubset+'_mask.npy',np.float32(image/255.0)) print(np.shape(image)) del image #mainPath=os.getcwd() #mainPath = '/content/gdrive/My Drive/U-NET' #PathImportExcel=mainPath+'/data/Excel/' #mymkdir(mainPath+'/data/TIFandNPY') #PathExportTif=mainPath+'/data/TIFandNPY/' PathImportExcel='/content/gdrive/My Drive/U-NET/data/Excel/' mymkdir('/content/gdrive/My Drive/U-NET/data/TIFandNPY') PathExportTif='/content/gdrive/My Drive/U-NET/data/TIFandNPY/' #Application of method convert Convert(PathImportExcel,PathExportTif)
73097e79c8ed996ebe58bc1638b3dfc938750d0e
abishamathi/python-program-
/even numbers.py
120
3.546875
4
even = [] for n in l : if(n % 2 == 0): even.appened(n) return even print(even num([1,2,3,4,5,6,7,8,9]))
8b3f291d7d9b0ecd8bc8584833a650e913c94773
abishamathi/python-program-
/number of spaces.py
124
3.703125
4
fname=input('Enter file name:') words=line.splits() if(letter.isspace): k=k+1 print('Occurrance of blank spaces:') print(k)
0a4cc84bd54d8e538b82324172d78b145d7df88e
abishamathi/python-program-
/largest.py
226
4.21875
4
num1=10 num2=14 num3=12 if (num1 >= num2) and (num1 >= num3): largest=num1 elif (num2 >= num1) and (num2 >=num3): largest=num2 else: largest=num3 print("the largest num between",num1,"num2,"num3,"is",largest)
54ed98a7d0f6c1fdde317afe0b8ff53b0cefe343
LucaRuggeri17/pdsnd_github
/script.py
7,337
4.125
4
# Explore Bikeshare data # Data creation May 2020 import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs error_inputs = "ERROR. Please try again" while True : city_input = input("\nEnter the city to analyze: \nchicago,\nnew york,\nwashington. \n").lower() if city_input in ['chicago', 'new york', 'washington']: break else: print(error_inputs) # TO DO: get user input for month (all, january, february, ... , june) while True : month_input = input("\nenter the month that you are interesting: \njanuary,\nfebruary,\nmarch," "\napril,\nmay,\njune\nto filter by, or \"all\" to apply no month filter\n").lower() if month_input in ["january", "february", "march", "april", "may", "june", "all"]: break else: print(error_inputs) # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) while True : day_input = input("\nenter day of the week that you are interesting: \nmonday,\ntuesday,\nwednesday,\nthursday," "\nfriday,\nsaturday,\nsunday\nof week to filter by, or \"all\" to apply no day filter\n").lower() if day_input in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "all"]: break else: print(error_inputs) return city_input, month_input, day_input def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ input_file = CITY_DATA[city] #define input file for city and select from the dictionary the corresponding csv file df = pd.read_csv(input_file) #dataframe variable to read the file csv df["start_time_dt"] = pd.to_datetime(arg = df['Start Time'], format = '%Y-%m-%d %H:%M:%S') # convert the string start time in a data format df["month"] = df['start_time_dt'].dt.month # extract the month from the date column df["day_of_week"] = df['start_time_dt'].dt.day_name() # extract the day of the week from the date column if month != 'all': #if you select different from all you have to filter according the different months months_map = { "january":1,"february":2,"march":3,"april":4,"may":5,"june":6} #create a map where each month has an associated number month_id = months_map[month] df = df.loc[df['month'] == month_id] # dataframe becomes filter by month = to month_id if day != 'all': df = df.loc[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() df['Start Time'] = pd.to_datetime(arg = df['Start Time'], format = '%Y-%m-%d %H:%M:%S') month = df['Start Time'].dt.month weekday_name = df['Start Time'].dt.day_name() hour = df['Start Time'].dt.hour # TO DO: display the most common month most_common_month = month.mode()[0] print('The month most frequent is:', most_common_month) # TO DO: display the most common day of week most_common_day_week = weekday_name.mode()[0] print('The day of the week most frequent is:', most_common_day_week) # TO DO: display the most common start hour most_common_start_hour = hour.mode()[0] print('The hour most frequent is:', most_common_start_hour) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station print('The start station most frequent is:', df['Start Station'].value_counts().idxmax()) # TO DO: display most commonly used end station print('The end station most frequent is:', df['End Station'].value_counts().idxmax()) # TO DO: display most frequent combination of start station and end station trip start_end_stations = df["Start Station"] + "_" + df["End Station"] #concatenate the start station and end station strings common_station = start_end_stations.value_counts().idxmax() # count the start and end station combination print('Most frequent start+end stations are:\n{} \nto\n{}'.format(common_station.split("_")[0], common_station.split("_")[1])) # print the most frequent combination def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" start_time = time.time() # TO DO: display total travel time total_travel_time = df["Trip Duration"].sum() print("Total travel time:\n", total_travel_time) # TO DO: display mean travel time mean_travel_time = df["Trip Duration"].mean() print("Mean travel time:\n", mean_travel_time) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types typology_of_user = df["User Type"].value_counts() # TO DO: Display counts of gender if "Gender" in df.columns: gender_counter = df["Gender"].value_counts() print(gender_counter) else: print("This dataset has no information about gender") # TO DO: Display earliest, most recent, and most common year of birth if "Birth Year" in df.columns: earliest_year_of_birth = df["Birth Year"].min() most_recent_year_of_birth = df["Birth Year"].max() common_year_of_birth = df['Birth Year'].mode()[0] print("\nthis is the earliest year of birth: " + str(earliest_year_of_birth)) print("\nthis is the most recent year of birth: " + str(most_recent_year_of_birth)) print("\nthis is the most common year of birh: " + str(common_year_of_birth)) else: print("This dataset has no information about birth year") def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
935f658529bd76c0f58a1dc795567d10ead00b20
mhtarek/Uri-Solved-Problems
/1049.py
648
3.78125
4
x= input() y= input() z= input() if x == "vertebrado": if y=="ave": if z=="carnivoro": print("aguia") elif z == "onivoro": print("pomba") elif y=="mamifero": if z=="onivoro": print("homem") elif z == "herbivoro": print("vaca") elif x == "invertebrado": if y=="inseto": if z=="hematofago": print("pulga") elif z == "herbivoro": print("lagarta") elif y=="anelideo": if z=="hematofago": print("sanguessuga") elif z == "onivoro": print("minhoca")
cf3ef53dc91ea47ef1cdd9cc7c5fc36c05732d61
mhtarek/Uri-Solved-Problems
/1216.py
205
3.734375
4
sum = 0 count = 0 while True: try: input() sum+=int(input()) count+=1 except EOFError: avg = float(sum/count) print("%.1f" % avg) break
033a7a9082b24b1ba9781d4ae26c98eac30cf805
mhtarek/Uri-Solved-Problems
/1161.py
249
3.5625
4
def fact(m): if m==1 or m==0: return 1 else: return m*fact(m-1) while True: try: ar = [int(i) for i in input("").split()] print(fact(ar[0])+fact(ar[1])) except EOFError: break
c289e68604c1ec7c15f08f2ab33b64e44a63983e
FuelDoks48/Project
/command_if.py
1,410
3.515625
4
# Обработка специальных значений # requsted_topping = ['mushrooms', 'green peppers', 'extra chesse'] # for requsted_topping in requsted_topping: # print (f'Adding {requsted_topping}.') # print(f'Finished make your pizza!') # __________________________________________________________ # # Проверка вхождений # banned_user = ['marie', 'clare', 'holly', 'Robby'] # user = 'Jannet' # if user not in banned_user: # print(f'{user.title()}, you cant post a response if you wish') # __________________________________________________________ # Простые команды if else # age = 18 # if age >= 18: # print('You are ready old') # else: # print('Sorry, you are too young to vote.') # __________________________________________________________ # Цепочки if-elif-else # age = 12 # if age < 5: # print('Your admission cost is 0$') # elif age < 18: # print('Your admission cost is 18$') # else: # print('Your admission cost is 25$') # __________________________________________________________ # # number = int(input('enter your number:')) # isPrime = True # for divider in range(2, nubmer): # if number % divider == 0: # isPrime = False # break # if isPrime: # print('Prime Number') # else: # print('Composite Prime') # __________________________________________________________
c76282a14c6a1c54f0566890377035a533786f6c
Engineering-Course/LIP_JPPNet
/get_maximum_square_from_segmented_image.py
3,716
3.609375
4
# This function is used to get the largest square from the cropped and segmented image. It can be further used to find patterns import cv2 import numpy as np import matplotlib.pyplot as plt from PIL import Image import time from collections import namedtuple import glob def printMaxSubSquare(M): """" find the largest square """ R = len(M) # no. of rows in M[][] C = len(M[0]) # no. of columns in M[][] S = [[0 for k in range(C)] for l in range(R)] # here we have set the first row and column of S[][] # Construct other entries for i in range(1, R): for j in range(1, C): if (M[i][j] == 1): S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1 else: S[i][j] = 0 # Find the maximum entry and # indices of maximum entry in S[][] max_of_s = S[0][0] max_i = 0 max_j = 0 for i in range(R): for j in range(C): if (max_of_s < S[i][j]): max_of_s = S[i][j] max_i = i max_j = j print("Maximum size sub-matrix is: ") count_i = 0 count_j = 0 position_matrix = [] for i in range(max_i, max_i - max_of_s, -1): for j in range(max_j, max_j - max_of_s, -1): position_matrix.append((i,j)) count_i+=1 print('count_i :' + str(count_i)) print('count_j :' + str(count_j)) return position_matrix def crop_square_portion(image_file_name): """" crop and save image """ image_file_name_list = image_file_name.split('_') vis_file_name = '_'.join(image_file_name_list[:2])+'_vis.png' save_file_name = '_'.join(image_file_name_list[:3])+'_square.png' cloth_type = image_file_name_list[-2] list_index = cloth_type_list.index(cloth_type) light_shade = light_shade_list[list_index] dark_shade = dark_shade_list[list_index] print(light_shade,dark_shade) #read input image img = cv2.imread(INPUT_DIR+vis_file_name,cv2.COLOR_BGR2RGB) #detect shades from vis: hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) mask = cv2.inRange(hsv, light_shade, dark_shade) #coverting to binary array: np_img = np.array(mask) np_img[np_img == 255] = 1 #coverting to binary array: np_img = np.array(mask) np_img[np_img == 255] = 1 #find and plot the largest square var = printMaxSubSquare(np_img) for point in var: a,b = point pt = (b,a) cv2.circle(np_img,pt,5,(200,0,0),2) ##convert mask to bunary mask np_img[np_img != 200] = 0 print('final mask shape:') print(np_img.shape) ##crop and save the square image img = cv2.imread(INPUT_DIR+image_file_name,cv2.COLOR_BGR2RGB) print('input image shape:') print(img.shape) x,y,w,h = cv2.boundingRect(np_img) crop_img = img[y:y+h,x:x+w] print('cropped image shape:') print(crop_img.shape) cv2.imwrite(OUTPUT_DIR+save_file_name, crop_img) if __name__ == "__main__": INPUT_DIR = r' set your input folder where segmented images are there' OUTPUT_DIR = r' set your output images' cloth_type_list = ['UpperClothes','Dress','Pants','Scarf','Skirt','Coat'] light_shade_list = [(100, 240, 255),(0,255,70),(0,255,70),(10,150,125),(50,0,70),(10,100,200)] dark_shade_list = [(190, 255, 255),(0,255,200),(100,255,200),(100,160,130),(60,255,200),(20,255,255)] #for each bgcropped file read, pass to crop_image function for file in glob.glob(INPUT_DIR+'*_cropped.png'): print(file) image_file_name = file.split('\\')[-1] crop_square_portion(image_file_name)
da16b14210a67f0b8bff8212d023eff2040e5424
AlifeLine/toolkit
/tools/quick_sort2.py
617
4
4
def quick_sort(arr, left=0, right=None): if right is None: right = len(arr) - 1 if left >= right: return l = left r = right key = arr[left] while left < right: while left < right and arr[right] >= key: right -= 1 arr[left] = arr[right] while left < right and arr[left] <= key: left += 1 arr[right] = arr[left] arr[right] = key quick_sort(arr, l, right-1) quick_sort(arr, right+1, r) if __name__ == "__main__": arr = [6,3,8,1,4,6,9,2] #quick(arr, 0, len(arr)-1) quick_sort(arr) print(arr)
72a89c29b77bca2fcada96ce5a4b46cc965128c4
AlifeLine/toolkit
/tools/lru.py
815
3.8125
4
class Node(object): def __init__(self, val): self.val = val self.next = None class Lru(object): def __init__(self, vals): self._head = None for val in vals: node = Node(val) if self._head: self._head.next = node else: self._head = node def hit(self, val): cur = self._head while cur: if cur.val == val and cur is not self._head: next = cur.next if next: cur.next = next.next cur.next.next = cur next.next = self._head self._head = next return True elif cur is not self._head: return True return False
bd001f39c500f13c409b9e4f22f41156cabc636d
leolion0/490-Lesson-3
/question 1.py
1,451
3.890625
4
class Employee: numEmployees = 0 def __init__(self, name="", family="", salary="", department=""): self.name = name self.family = family self.salary = salary self.department = department Employee.numEmployees += 1 def fillFromUser(self): self.name = str(input("Name of the employee: ")) self.family = str(input("Family of the employee: ")) self.salary = str(input("Salary of the employee: ")) self.department = str(input("Department of the employee: ")) def __str__(self): outStr: str = "Name: " + self.name + "\n" outStr += "Family: " + self.family + "\n" outStr += "Salary: " + str(self.salary) + "\n" outStr += "Department: " + self.department + "\n" return outStr def avgSal(employees): average = 0 numEmps = employees[0].__class__.numEmployees for i in employees: average += int(i.salary) return average / numEmps class FulltimeEmployee(Employee): def __init__(self, name="", family="", salary="", department="", hours=40): Employee.__init__(self, name, family, salary, department) self.hours = hours theEmps = list() theEmps.append( Employee("John", "White", 3600, "Sales")) theEmps.append(FulltimeEmployee("Alice", "Wonderland", 74000, "IT", 43)) theEmps.append(FulltimeEmployee()) theEmps[2].fillFromUser() for i in theEmps: print(i) print(avgSal(theEmps))
6ee056c951856f4bc7e8e6bd7d95b10865c3085b
rohitbapat/NQueensNRooks-Problem
/a0.py
8,287
4.1875
4
#!/usr/bin/env python3 # nrooks.py : Solve the N-Rooks problem! # # The N-Queens problem is: Given an empty NxN chessboard, place N queens on the board so that no queens # can take any other, i.e. such that no two queens share the same row,column or are on the same diagonal # # Citations mentioned at the end of the code import sys # Count number of pieces in given row def count_on_row(board, row): count=0 # Iterate each node in every row #[2] for i in board[row]: if(i==1): count+=1 return count # Count number of pieces in given column def count_on_col(board, col): count=0 # Iterate over every column node of every row for x in ([a[col] for a in board]): if(x==1): count+=1 return count # Count total number of pieces on board def count_pieces(board): count=0 # Double for loop to check each node and update count for row in range(N): for col in range(N): if(board[row][col]==1): count+=1 return count # Return a string with the board rendered in a human-friendly format def printable_board(board): # Modifications done in display function to incorporate unusable nodes and tag them as X with -1 as value #[4] if(problem_type=="nqueen"): return "\n".join([ " ".join([ "Q" if col==1 else "X" if col==-1 else "_" for col in row ]) for row in board]) elif(problem_type=="nrook"): return "\n".join([ " ".join([ "R" if col==1 else "X" if col==-1 else "_" for col in row ]) for row in board]) else: return "\n".join([ " ".join([ "K" if col==1 else "X" if col==-1 else "_" for col in row ]) for row in board]) # Add a piece to the board at the given position, and return a new board (doesn't change original) def add_piece(board, row, col): return board[0:row] + [board[row][0:col] + [1,] + board[row][col+1:]] + board[row+1:] # Successor function to place N rooks if given as the input argument. # Sucessor function same as nrooks.py successors3() def nrooks_successors(board): rook_number=count_pieces(board) if(rook_number<N and board!=[]): return [ add_piece(board, r, c) for c in range(0, rook_number+1) for r in range(0,N) if count_on_row(board,r)!=1 and count_on_col(board,c)!=1 and board[r][c]!=-1] else: return [] # Function to check if the queen is under attack with checking of diagonals def check_position(board,r,c): if((count_on_row(board,r))==1 or (count_on_col(board,c)==1)): return True #Iterate from start of Board to check the presence of a queen with respect to current queen position for board_row in range(0,N): for board_col in range(0,N): # The first condition checks if the diagonals perpendicular to current queen diagonal have any Queens already # The second condition checks for presence of queen above or below the current queen diagonal # [5] if((board_row+board_col==r+c) or (board_row-board_col==r-c)): if(board[board_row][board_col]==1): return True return False # Function to find and return successors of current board of N queens def nqueen_successors(board): # Accumaulate result state result=[] rook_number=count_pieces(board) # Find all successors for current board in next column for c in range(0,rook_number+1): for r in range(0,N): # If any inner conditions is true the piece is not appended as a valid successor if(not(check_position(board,r,c)) and board[r][c]!=1 and board[r][c]!=-1): result.append(add_piece(board,r,c)) return result # Function to check if the knight is under attack def check_position_nknight(board,r,c): #Iterate from start of Board to check the presence of a queen with respect to current queen position for board_row in range(0,N): for board_col in range(0,N): # The first condition checks if the diagonals perpendicular to current queen diagonal have any Queens already # The second condition checks for presence of queen above or below the current queen diagonal # [5] #print(board_row) #print(board_col) if(board[board_row][board_col]==1): if((int(r-board_row)**2)+(int(c-board_col)**2)==5): return True return False # Function to find and return successors of current board of N Knights def nknight_successors(board): # Accumaulate result state result=[] #rook_number=count_pieces(board) # Find all successors for current board in next column for c in range(0,N): for r in range(0,N): # If any inner conditions is true the piece is not appended as a valid successor #print(check_position_nknight(board,r,c)) if(not(check_position_nknight(board,r,c)) and board[r][c]!=1 and board[r][c]!=-1): #print(r) #print(c) #print("Rohit") result.append(add_piece(board,r,c)) return result # Check if board is a goal state without count_on_row or count_on_col function already checked in the successor def is_goal(board): return count_pieces(board) == N # Solve for n-queen def solve_dfs_nqueen(initial_board): fringe = [initial_board] while len(fringe) > 0: for s in nqueen_successors( fringe.pop() ): if(count_pieces(s)==N): if is_goal(s): return(s) fringe.append(s) return False # Solve for n-rooks def solve_dfs_nrooks(initial_board): fringe = [initial_board] while len(fringe) > 0: for s in nrooks_successors( fringe.pop() ): # Check only if N rooks are placed if(count_pieces(s)==N): if is_goal(s): return(s) fringe.append(s) return False # Solution for n-knights def solve_dfs_nknights(initial_board): fringe = [initial_board] while len(fringe) > 0: for s in nknight_successors( fringe.pop() ): # Check only if N knights are placed if(count_pieces(s)==N): if is_goal(s): return(s) fringe.append(s) return False # This is N, the size of the board. It is passed through command line arguments. problem_type=str(sys.argv[1]) N = int(sys.argv[2]) # Set initial board nodes to Zero initial_board=[0]*N for i in range(N): initial_board[i]=[0]*N initial_board = [[0]*N for _ in range(N)] #[3] #Check if further arguments are provided for blocked positions if(len(sys.argv)>3): blocked_places=int(sys.argv[3]) for place in range(0,blocked_places): blocked_row=int(sys.argv[(place*2)+4]) blocked_column=int(sys.argv[(place*2)+5]) # Decide a blocked position with node filled as -1 #[1] initial_board[blocked_row-1][blocked_column-1]=-1 print ("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for solution...\n") # Call to different solve functions based on user input if(problem_type=="nqueen"): solution = solve_dfs_nqueen(initial_board) elif(problem_type=="nrook"): solution = solve_dfs_nrooks(initial_board) else: solution = solve_dfs_nknights(initial_board) print (printable_board(solution) if solution else "Sorry, no solution found. :(") ''' [1] https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/ Check solution states for N=4 for verification [2] https://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list Iterating over a 2D array in python [3] https://www.programiz.com/python-programming/matrix https://stackoverflow.com/questions/2739552/2d-list-has-weird-behavor-when-trying-to-modify-a-single-value Way of creating a 2D matrix with different references [4] https://stackoverflow.com/questions/20888693/python-one-line-if-elif-else-statement/20888751 if elif else statements on one line [5] https://www.codesdope.com/blog/article/backtracking-explanation-and-n-queens-problem/ Perpendicular Diagonal Check for current Queen Diagonal '''
bad58f360c606e5a92312ffd2115872b42fffd57
tenasimi/Python_thero
/Class_polymorphism.py
1,731
4.46875
4
# different object classes can share the same name class Dog(): def __init__(self, name): self.name = name def speak(self): # !! both Nico and Felix share the same method name called speak. return self.name + " says woof!" class Cat(): def __init__(self, name): self.name = name def speak(self): return self.name + " says meow!" #creating 2 instances one for each class niko = Dog("niko") felix = Cat("felix") print(niko.speak()) print(felix.speak()) # metod 1 iterasiya ile gormek olur polimprfizmi for pet in [niko,felix]: # pet!! iterating via list of items print(type(pet)) print(type(pet.speak())) # both class instances share the same method name called speak print() print(pet.speak()) # however they are different types here main__.Cat' , main__.Dog' print() # metod 2 funksiya ile: def pet_speak(pet): print(pet.speak()) pet_speak(niko) pet_speak(felix) # Method3, abstract base class use class Animal(): def __init__(self,name): self.name = name def speak(self): # we a raising an error, It's expecting you to inherit the animal class and then overwrite the speak method. raise NotImplementedError("Subclass must implement this abstarct method") # bunlari acsan erroru gorersen #myanimal = Animal('fred') #print(myanimal.speak()) class Dog(Animal): def speak(self): return self.name+ " says woof!" class Cat(Animal): def speak(self): return self.name + " says meow!" fido = Dog("Fido") isis = Cat("isis") # different object classes can share the same method name print(fido.speak()) print(isis.speak())
5cd6aae2bacc1b6626dafbc541c626c811e67aac
tenasimi/Python_thero
/Class_Inheritance.py
717
4.15625
4
class Animal(): def __init__(self): print("ANIMAL CREATED") def who_am_i(self): print("I am animal") def eat(self): print("I am eating") myanimal = Animal() #__init__ method gets automatically executed when you # create Anumal() myanimal.who_am_i() myanimal.eat() print() #Dog is a Derived class from the base class Animal class Dog(Animal): def __init__(self): Animal.__init__(self) print("Dog Created") def who_am_i(self): print("I am a dog!") def bark(self): print("WOOF!") def eat(self): print("I am a dog and eating") mydog = Dog() mydog.eat() mydog.who_am_i() mydog.bark() mydog.eat()
ef64e2b1091b79e6c1df275002c49bb501b70759
tenasimi/Python_thero
/test_test_test.py
1,345
3.828125
4
print(1 % 2) print(2 % 2) print(3 % 2) print(4 % 2) print(5 % 2) print(6 % 2) print(7 % 2) print(8 % 2) print(9 % 2) def almost_there(n): return (abs(100-n) <= 10) or (abs(200-n) <= 10) print(almost_there(190)) print(abs(20-11)) #help(map) print() def square(num): return num**2 print(square(6)) def up_low(s): d={"upper":0, "lower":0} for c in s: if c.isupper(): d["upper"]+=1 elif c.islower(): d["lower"]+=1 else: pass print ("Original String: ", s) print("No. of Upper case characters: ", d["upper"]) print("No. of Lower case characters: ", d["lower"]) #vizivaem s='Hello mr. Rogers, how are you, this fine Tuesday?' up_low(s) print() def unique_list(l): x=[] for a in l: if a not in x: x.append(a) return x l = [1,1,1,1,3,3,4,6,5,6,9,46] print(unique_list(l)) print() def multiply(numbers): total = numbers[0] for x in numbers: total *= x return total numbers = [1,2,3,-4] print(multiply(numbers)) print() def palindrome(s): return s == s[::-1] print(palindrome('alla')) print() import string def ispangram(str1, alphabet = string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(str1.lower()) print(ispangram("The quick brown fox jumps over the lazy dog"))
6abeba2d5f744e34aa97a48fe06a5dac4cf27207
tenasimi/Python_thero
/sec4_comparison_operators.py
7,715
4.46875
4
print(1 < 2 and 2 > 3) print(1 < 2 and 2 < 3) print('h' == 'h' and 2 == 2) # AND!! both of them must be true print(1 == 2 or 2 < 3) # OR!! one of them must be true print(not 1 == 1) # NOT !! for opposite boolean result # if True: print('ITS TRUE!') # if False: print('ITS False!') else: print('Its always True') # if 3>2: print('3 greater 2, TRUE') else: print('3 is not greater 2, False') # if 3<2: print('3 greater 2, TRUE') else: print('3 is not greater 2, False') # hungry = True if hungry: print('FEED ME!') # hungry = True if hungry: print('FEED ME!') #empty output else: print('Im not hungry') # loc = 'Bank' if loc == 'Auto Shop': print('Cars are cool!') else: print('I do not know much, maybe its bank') #for checking other conditions use ELIF # we can add and more lives for more conditions. loc = 'Bank' #loc = 'Auto Shop' loc = 'Store' if loc == 'Auto Shop': print('Cars are cool!') elif loc == 'Bank': print('Money is cool!') elif loc == 'Store': print('Welcome to the store!') else: print('I do not know much') # #name = 'Jose' # esli nicto ne podoydet #name = 'Frankie' name = 'Sammy' if name == 'Frankie': print('Hello Frankie!') elif name == 'Sammy': print('Hello Sammy') else: print('What is your name?') # for loop my_iterable = [1,2,3] for item_name in my_iterable: print(item_name) print() # mylist = [1,2,3,4,5,6,7,8,9,10] for num in mylist: print(num) # mylist = [1,2,3,4,5,6,7,8,9,10] for jelly in mylist: print(jelly) # mylist = [1,2,3,4,5,6,7,8,9,10] for jelly in mylist: print('hello') # mylist = [1,2,3,4,5,6,7,8,9,10] for num in mylist: # check for even if num % 2 ==0: print(num) print() # snacala iz spiska otbiraem cetnie cisla (if), a potom (else) vivodin to cto ostalos (necetnie) mylist = [1,2,3,4,5,6,7,8,9,10] for num in mylist: if num % 2 == 0: # to cto delitsa na 2 bez ostatka print(num) else: print(f'Odd Number: {num}') print() # to je samoe, naoborot, cnacala necetnie, potom to cto ostalos - cetnie mylist = [1,2,3,4,5,6,7,8,9,10] for num in mylist: if num % 2 == 1: # to cto delitsa na 2 s ostatkom 1 print(num) else: print(f'Even Number: {num}') print() # mylist = [1,2,3,4,5,6,7,8,9,10] list_sum = 0 for num in mylist: list_sum = list_sum + num #0+1=1, 1+2=3, 3+3=6, 6+4=10, 10+5=15,15+6=21,21+7=28,28+8=36,36+9=45,45+10=55 print(list_sum) print() # mylist = [1,2,3,4,5,6,7,8,9,10] list_sum = 0 for num in mylist: list_sum = list_sum + num # to je samoe no podrobno v stolbike uvidim process slojeniya print(list_sum) # placing print inside of for loop print() # # iterating letters i string: mystring = 'Hello World' for letter in mystring: print(letter) print() # ex. Print cool for as many times as your characters in string for ggg in 'Hello World': print('Cool!') # You can also use the same iteration for each tuple. # pecataem cto xotim v cislo raz soderjimoqo tu;ipa tup = (1,2,3) for item in tup: print('cislo raz') # print() # pecataem soderjanie tulip-a tup = (1,2,3) for item in tup: print('item') print() # mylist = [(1,2),(3,4),(5,6),(7,8)] print(len(mylist)) for item in mylist: print(item) #unpack tuple ex. print() mylist = [(1,2),(3,4),(5,6),(7,8)] for (a,b) in mylist: print(a) print(b) #unpack tuple ex. print() mylist = [(1,2),(3,4),(5,6),(7,8)] for a,b in mylist: print(b) #unpack tuple ex . print() mylist = [(1,2,3),(5,6,7),(8,9,10)] for item in mylist: print(item) print() # But I can do tuple unpacking here, only print 2 6 9 ex.: mylist = [(1,2,3),(5,6,7),(8,9,10)] for a,b,c in mylist: print(b) print() # Dictionary iteration #by default when you iterate through a dictionary you only iterate through the Keys. d = {'k1':1, 'k2':2, 'k3':3} for item in d: print(item) print() # if you want iterate through items themselves call .items(: d = {'k1':1, 'k2':2, 'k3':3} for item in d.items(): print(item) print() # primenyaya priem visheprivedenniy v tuple, mojno delat UNPACKING d = {'k1':1, 'k2':2, 'k3':3} for key,value in d.items(): print(value) print() # only value ex. d = {'k1':1, 'k2':2, 'k3':3} for value in d.values(): print(value) print() # WHILE loop ex. x = 0 while x < 5: print(f'The current value of x is {x}') x = x + 1 #or x +=1 is more compact print() # WHILE + else x = 0 while x < 5: print(f'The current value of x is {x}') x += 1 else: print('X is NOT less than 5') print() # pass keyword ex. x = [1,2,3] for item in x: # many times programmers keep it as a placeholder to kind of avoid a syntax error b pass print('end of my script') # print() mystring = 'Sammy' for letter in mystring: print(letter) # I'm not actually printing out the letter. print() mystring = 'Sammy' for letter in mystring: if letter == 'a': continue print(letter) # break ex. - stopping loop. print() mystring = 'Samrikitmo' for letter in mystring: if letter == 'k': break print(letter) # break ex. - stopping loop at 2. print() x = 0 while x < 5: if x == 2: # dobavlyaem break # break uslovie print(x) x += 1 # print() #mylist = [a,b,c] for bam in range(3): #all range from 0 to 3 print(bam) print() #mylist = [a,b,c] for num in range(2,5): #start from 2 not include 5 print(num) print() #mylist = [a,b,c] for num in range(3,10,2): #start from 3 not include 5 + step size 2 print(num) k = list(range(3,28,2)) print(k) print() # enumerate with format + for index_count = 0 for letter in 'abcde': print('At index {} the letter is {}'.format(index_count,letter)) index_count += 1 print() # to je samoe no s funksiey enumerate word = 'abcde' for item in enumerate(word): # v enumerate stavim iterable var - word print(item) print() # delaem enumerate + tuple unpacking word = 'abcde' for ind,let in enumerate(word): # znaya cto vivedet tuple, delaem unpack naxodu print(ind) print(let) print('\n') # zip - funksiya sozdayuwaya tuple iz listov mylist1 = [1,2,3] mylist2 = ['a','b','c'] for item in zip(mylist1,mylist2): print(item) print() # zip - funksiya sozdayuwaya tuple iz listov mylist1 = [1,2,3] mylist2 = ['a','b','c'] mylist3 = [100,200,300] for item in zip(mylist1,mylist2,mylist3): print(item) print() # zip - Zipp is only going to be able to go and zip together as far as the list which is the shortest. mylist1 = [1,2,3,4,5,6] mylist2 = ['a','b','c'] mylist3 = [100,200,300] for item in zip(mylist1,mylist2,mylist3): print(item) print() #list + zip - zipping together 2 lists l = list(zip(mylist1,mylist2)) print(l) # in # in keyword PROVERKA USLOVIYA, est li x v spiske? # is X in the list 1 to 3 and 0 return back a boolean true or false. print('x' in ['x','y','z']) print() print('a' in 'a world') # string ex print() print('mykey' in {'mykey':345}) # dict ex. print() d={'mykey':345} print(345 in d.keys()) print(345 in d.values()) print() # min max functions mylist = [10,20,30,40,100] print(min(mylist)) print(max(mylist)) # random library use from random import shuffle mylist = [1,2,3,4,5,6,7,8,9,10] shuffle(mylist) # peremewivaet (shuffle) print(mylist) print() # ramdom integer function , grabs random int from interval from random import randint print(randint(0,100)) # also i can save its random output and use later mynum = randint(0,10) print(mynum) # # input print(input('Enter a number here: ')) result = input('What is your name? ') print(result) print(type(result)) result = input('What is your favorite number? ') print(float(result)) print(int(result))
def301bd04c9524897496e3935cc1b319b47c3dc
fgiraudo/aoc-2019
/Sources/2019-4.py
1,219
3.671875
4
import math import os import copy #Change Python working directory to source file path abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) def main(): count = 0 print(is_valid(112233)) print(is_valid(123444)) print(is_valid(112223)) for password in range(256310, 732737): if is_valid(password): count += 1 print(count) def is_valid(password): digits = [int(d) for d in str(password)] last_digit = digits.pop(0) has_adjacent = False adjacent_digit = None invalid_adjacent = None has_valid_adjacent = False for digit in digits: if digit < last_digit: return False if digit > last_digit and has_adjacent: has_valid_adjacent = True if digit == last_digit: if (has_adjacent and adjacent_digit == digit) or invalid_adjacent == digit: adjacent_digit = None invalid_adjacent = digit has_adjacent = False else: adjacent_digit = digit has_adjacent = True last_digit = digit return has_adjacent or has_valid_adjacent main()
147c00e912fdc1a94a01fdd2b558a67eaf5db87f
jaykaneriya6143/python
/day5/overriding.py
211
3.59375
4
class Parent: def fun1(self): print("This method is parent.......") class Child(Parent): def fun1(self): print("This method is child.......") c1 = Child() c1.fun1()
3f3241fe77bdc53edde180117cf4a7943f363411
jaykaneriya6143/python
/day2/jk5.py
142
3.78125
4
name = "jay kaneriya" print("Name is :",name) print(name[0]) print (name[2:5]) print(name[2:]) print(name * 2) print(name + "Hello")
85361ac8a3ba55f2cbe9f0420c48f81dfe0127fb
DRV1726018/vehicle-testing
/gui-alpha/gui.py
17,628
3.671875
4
import math import tkinter as tk from tkinter import Label, ttk from tkinter import font from PIL import ImageTk,Image from tkinter import filedialog from tkinter import * root = tk.Tk() root.title("Centro de Gravedad") root.geometry("1000x600") root.iconbitmap(file="carro.ico") #Panel para las pestañas nb = ttk.Notebook(root) nb.pack(fill="both", expand="yes") #Pestañas p1 = ttk.Frame(nb) p2 = ttk.Frame(nb) p3 = ttk.Frame(nb) nb.add(p1, text = "Registro de Operarios") nb.add(p2, text = "Datos del Vehiculo") nb.add(p3, text = "Calculo del Centro de Gravedad") #Pestaña 1 #Funciones de la pestaña 1 def ingresar_operario_uno(registrar): print("El operario uno es: ", registrar) def ingresar_operario_dos(registrar): print("La operario dos es: ", registrar) label = tk.Label(p1, text="Registro de los Operarios", font=40) label.place(relx=0.5, rely=0, relwidth=0.75, relheight=0.4, anchor="n" ) label2 = tk.Label(p1, text="Operario 1", font=40) label2.place(relx=0.3, rely=0.3, relwidth=0.4, relheight=0.1, anchor="n") label3 = tk.Label(p1, text="Operario 2", font=40) label3.place(relx=0.3, rely=0.5, relwidth=0.4, relheight=0.1, anchor="n") operario_uno = tk.Entry(p1, font=40) operario_uno.place(relx=0.5, rely=0.3, relwidth=0.4, relheight=0.1) operario_dos = tk.Entry(p1, font=40) operario_dos.place(relx=0.5, rely=0.5, relwidth=0.4, relheight=0.1) registro = Button(p1, text="Registrar", command=lambda: [ingresar_operario_uno(operario_uno.get()),ingresar_operario_dos(operario_dos.get())]) registro.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1) #Pestaña 2 #Funciones de la pestaña 2 def imagen_carro(): global my_image root.filename = filedialog.askopenfilename(initialdir="C:/Users/David Ramírez/Desktop/CDG", title="Upload the car image") my_label = Label(p2, text=root.filename).pack() my_image = ImageTk.PhotoImage(Image.open(root.filename)) my_label_image = Label(image=my_image).pack() def ingresar_matricula(registro): return print("La matricula del vehículo es: ", registro) def ingresar_fecha(registro): return print("La fecha del ensayo es: ", registro) #Seleccionar la foto del vehiculo texto_carro = tk.Label(p2, text="Ingrese la foto del Vehículo",font="20",) texto_carro.place(relx=0.1, rely=0.6, relwidth=0.5, relheight=0.1) btn_imagen_carro = Button(p2, text="Open File", command=imagen_carro) btn_imagen_carro.place(relx=0.65, rely=0.6, relwidth=0.3, relheight=0.1) #Ingresar la matricula del vehiculo texto_matricula = tk.Label(p2,text="Ingrese la matricula del vehículo", font=40) texto_matricula.place(relx=0.1, rely=0.4, relwidth=0.5, relheight=0.1) ent_matricula = tk.Entry(p2, font=40 ) ent_matricula.place(relx=0.65, rely=0.4, relwidth=0.3, relheight=0.1) #Ingresar la fecha del ensayo. texto_fecha = tk.Label(p2,text="Ingrese la fecha", font=40) texto_fecha.place(relx=0.1, rely=0.2, relwidth=0.5, relheight=0.1) ent_fecha = tk.Entry(p2, font=40 ) ent_fecha.place(relx=0.65, rely=0.2, relwidth=0.3, relheight=0.1) #Boton para aceptar registrar = Button(p2, text="Registrar", command=lambda: [ingresar_matricula(ent_matricula.get()),ingresar_fecha(ent_fecha.get())]) registrar.place(relx=0.4, rely=0.8, relwidth=0.3, relheight=0.1) #Pestaña 3 def get_lift_height(calcular_centro_de_gravedad): """Get lift height from user input in mm""" return print("Please enter the lift height in mm: ",calcular_centro_de_gravedad) def get_left_wheelbase(calcular_centro_de_gravedad): """Get left wheelbase from user input in mm.""" return print("Please enter the left wheelbase in mm: ",calcular_centro_de_gravedad) def get_right_wheelbase(calcular_centro_de_gravedad): """Get right wheelbase from user input in mm.""" return print("Please enter the right wheelbase in mm: ",calcular_centro_de_gravedad) def get_mean_wheelbase(left_wheelbase, right_wheelbase): """Return mean wheelbase from vehicle's left and right wheelbases in mm. Arguments: left_wheelbase -- vehicle's left wheelbase in mm. right_wheelbase -- vehicle's right wheelbase in mm. Return values: The mean vehicle wheelbase. """ return (left_wheelbase + right_wheelbase) / 2 def get_rear_track(calcular_centro_de_gravedad): """Return vehicle rear track from user input in mm.""" return print("Please enter vehicle rear track in mm: ", calcular_centro_de_gravedad) def get_front_track(calcular_centro_de_gravedad): """Return vehicle front track from user input in mm.""" return print("Please enter vehicle front track in mm: ", calcular_centro_de_gravedad) def get_wheel_diameter(calcular_centro_de_gravedad): """Get lifted vehicle wheel diameter from user input in mm.""" return print("Please enter lifted vehicle wheel diameter in mm: ", calcular_centro_de_gravedad) def get_flattened_wheel_diameter(calcular_centro_de_gravedad): """Get lifted vehicle flattened wheel diameter from user input in mm.""" return print("Please enter lifted vehicle flattened wheel diameter in mm: ", calcular_centro_de_gravedad) def get_static_wheel_radius(wheel_diameter, flattened_wheel_diameter): """Return static wheel radius. Arguments: wheel_diameter -- lifted vehicle wheel_diameter in mm flattened_wheel_diameter -- lifted vehicle flattened_wheel_diameter in mm Return values: The static wheel radius in mm. """ return flattened_wheel_diameter - (wheel_diameter / 2) def get_rear_left_wheel_mass(calcular_centro_de_gravedad): """Get rear left wheel mass from user input in kg.""" return print("Please enter the rear left wheel mass in kg: ", calcular_centro_de_gravedad) def get_rear_right_wheel_mass(calcular_centro_de_gravedad): """Get rear right wheel mass from user input in kg.""" return print("Please enter the rear right wheel mass in kg: ", calcular_centro_de_gravedad) def get_front_left_wheel_mass(calcular_centro_de_gravedad): """Get front left wheel mass from user input in kg.""" return print("Please enter the front left wheel mass in kg: ", calcular_centro_de_gravedad) def get_front_right_wheel_mass(calcular_centro_de_gravedad): """Get front right wheel mass from user input in kg.""" return print("Please enter the front right wheel mass in kg: ", calcular_centro_de_gravedad) def get_rear_axle_mass(rear_left, rear_right): """Return rear axle mass from wheel masses in kg. Arguments: rear_left -- rear left wheel mass in kg. rear_right -- rear right wheel mass in kg. """ return rear_left + rear_right def get_front_axle_mass(front_left, front_right): """Return front axle mass form wheel masses in kg. Arguments: front_left -- front left wheel mass in kg. front_right -- front right wheel mass in kg. Return values: The frontal axle mass in kg. """ return front_left + front_right def get_vehicle_mass(rear_axle_mass, front_axle_mass): """Return vehicle mass from wheel masses in kg. Arguments: rear_axle_mass -- vehicle rear axle mass in kg. front_axle_mass -- vehicle front axle mass in kg. Return values: The total vehicle mass in kg. """ return rear_axle_mass + front_axle_mass def get_lifted_angle(lift_height, mean_wheelbase): """Return lifted angle from vehicle lift height and mean wheelbase. Arguments: lift_height -- lift height in mm. mean_wheelbase -- mean wheelbase in mm. Return values: The lifted angle in radians. """ return math.atan(lift_height / mean_wheelbase) def get_lifted_rear_left_wheel_mass(calcular_centro_de_gravedad): """Get lifted rear left wheel mass from user input in kg.""" return print("Please enter the lifted rear left wheel mass in kg: ", calcular_centro_de_gravedad) def get_lifted_rear_right_wheel_mass(calcular_centro_de_gravedad): """Get lifted rear right wheel mass from user input in kg.""" return print("Please enter the lifted rear right wheel mass in kg: ", calcular_centro_de_gravedad) def get_lifted_rear_axle_mass(lifted_rear_left_wheel_mass, lifted_rear_right_wheel_mass): """Return rear axle mass from wheel masses in kg. Arguments: rear_left -- rear left wheel mass in kg. rear_right -- rear right wheel mass in kg. """ return lifted_rear_left_wheel_mass + lifted_rear_right_wheel_mass def get_longitudinal_distance(vehicle_mass, rear_axle_mass, mean_wheelbase): """Return longitudinal distance in mm. Arguments: vehicle_mass -- vehicle total mass in kg.. rear_axle_mass -- rear axle mass in kg. mean_wheelbase -- mean wheelbase in mm. Return values: The longitudinal distance of the center of gravity in mm. """ return (rear_axle_mass / vehicle_mass) * mean_wheelbase def get_transverse_distance(front_track, rear_track, rear_right_mass, rear_left_mass, front_left_mass, front_right_mass, vehicle_mass): """Return transverse distance in mm. Arguments: front_track -- front track in mm. rear_track -- rear track in . rear_right_mass -- rear right wheel mass in kg. rear_left_mass -- rear left wheel mass in kg. front_left_mass -- front left wheel mass in kg. front_right_mass -- front right wheel mass in kg. vehicle_mass -- total vehicle mass in kg. Return values: The transverse distance of the center of gravity in mm. """ return ((front_track * (front_left_mass - front_right_mass)) + (rear_track * (rear_left_mass - rear_right_mass))) / (2 * vehicle_mass) def get_height(mean_wheelbase, lifted_rear_axle_mass, rear_axle_mass, vehicle_mass, lifted_angle, static_wheel_radius): """Return height of the center of gravity in mm. Arguments: Return values: The height of the center of gravity in mm. """ return ((mean_wheelbase * (lifted_rear_axle_mass - rear_axle_mass)) / (vehicle_mass * math.tan(lifted_angle))) + static_wheel_radius def get_center_of_gravity(vehicle_mass, rear_axle_mass, mean_wheelbase, front_track, rear_track, rear_right_mass, rear_left_mass, front_left_mass, front_right_mass, lifted_rear_axle_mass, lifted_angle, static_wheel_radius): """Return a vehicle's center of gravity. Argument: longitudinal_distance -- the longitudinal distance of the center of gravity. transverse_distance -- the transverse distance of the center of gravity. height -- the height of the center of gravity. Return values: A tuple made up from the XYZ coordinates of the center of gravity in mm. """ longitudinal_distance = get_longitudinal_distance(vehicle_mass, rear_axle_mass, mean_wheelbase) transverse_distance = get_transverse_distance(front_track, rear_track, rear_right_mass, rear_left_mass, front_left_mass, front_right_mass, vehicle_mass) height = get_height(mean_wheelbase, lifted_rear_axle_mass, rear_axle_mass, vehicle_mass, lifted_angle, static_wheel_radius) return longitudinal_distance, transverse_distance, height #enter the lift height in mm lbl_lift_height = tk.Label(p3,text="Please enter the lift height in mm: ") lbl_lift_height.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.04) lift_height = tk.Entry(p3) lift_height.place(relx=0.65, rely=0.1, relwidth=0.1, relheight=0.04) #enter the left wheelbase in mm lbl_left_wheelbase = tk.Label(p3,text="Please enter the left wheelbase in mm: ") lbl_left_wheelbase.place(relx=0.1, rely=0.15, relwidth=0.3, relheight=0.04) left_wheelbase = tk.Entry(p3) left_wheelbase.place(relx=0.65, rely=0.15, relwidth=0.1, relheight=0.04) #Enter the right wheelbase in mm lbl_right_wheelbase = tk.Label(p3,text="Please enter the right wheelbase in mm: " ) lbl_right_wheelbase.place(relx=0.1, rely=0.2, relwidth=0.3, relheight=0.04) right_wheelbase = tk.Entry(p3) right_wheelbase.place(relx=0.65, rely=0.2, relwidth=0.1, relheight=0.04) #Enter vehicle rear track in mm lbl_rear_track = tk.Label(p3,text="Please enter vehicle rear track in mm: " ) lbl_rear_track.place(relx=0.1, rely=0.25, relwidth=0.3, relheight=0.04) rear_track = tk.Entry(p3) rear_track.place(relx=0.65, rely=0.25, relwidth=0.1, relheight=0.04) #Enter vehicle front track in mm lbl_front_track = tk.Label(p3,text="Please enter vehicle front track in mm: ") lbl_front_track.place(relx=0.1, rely=0.3, relwidth=0.3, relheight=0.04) front_track = tk.Entry(p3) front_track.place(relx=0.65, rely=0.3, relwidth=0.1, relheight=0.04) #Enter lifted vehicle wheel diameter in mm lbl_wheel_diameter = tk.Label(p3,text="Please enter lifted vehicle wheel diameter in mm: ") lbl_wheel_diameter.place(relx=0.1, rely=0.35, relwidth=0.3, relheight=0.04) wheel_diameter = tk.Entry(p3) wheel_diameter.place(relx=0.65, rely=0.35, relwidth=0.1, relheight=0.04) #enter lifted vehicle flattened wheel diameter in mm lbl_flattened_wheel_diameter = tk.Label(p3,text="Please enter lifted vehicle flattened wheel diameter in mm: ") lbl_flattened_wheel_diameter.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.04) flattened_wheel_diameter = tk.Entry(p3) flattened_wheel_diameter.place(relx=0.65, rely=0.4, relwidth=0.1, relheight=0.04) #Enter the rear left wheel mass in kg lbl_rear_left_wheel_mass = tk.Label(p3,text="Please enter the rear left wheel mass in kg: ") lbl_rear_left_wheel_mass.place(relx=0.1, rely=0.45, relwidth=0.3, relheight=0.04) rear_left_wheel_mass = tk.Entry(p3) rear_left_wheel_mass.place(relx=0.65, rely=0.45, relwidth=0.1, relheight=0.04) #Enter the rear right wheel mass in kg lbl_rear_right_wheel_mass = tk.Label(p3,text="Please enter the rear right wheel mass in kg: ") lbl_rear_right_wheel_mass.place(relx=0.1, rely=0.5, relwidth=0.3, relheight=0.04) rear_right_wheel_mass = tk.Entry(p3) rear_right_wheel_mass.place(relx=0.65, rely=0.5, relwidth=0.1, relheight=0.04) #Enter the lifted rear left wheel mass in kg lbl_front_left_wheel_mass = tk.Label(p3,text="Please enter the lifted rear left wheel mass in kg: ") lbl_front_left_wheel_mass.place(relx=0.1, rely=0.55, relwidth=0.3, relheight=0.04) front_left_wheel_mass = tk.Entry(p3) front_left_wheel_mass.place(relx=0.65, rely=0.55, relwidth=0.1, relheight=0.04) #Enter the lifted rear right wheel mass in kg lbl_front_right_wheel_mass = tk.Label(p3,text="Please enter the lifted rear right wheel mass in kg: ") lbl_front_right_wheel_mass.place(relx=0.1, rely=0.6, relwidth=0.3, relheight=0.04) front_right_wheel_mass = tk.Entry(p3) front_right_wheel_mass.place(relx=0.65, rely=0.6, relwidth=0.1, relheight=0.04) #Enter the lifted rear left wheel mass in kg lbl_lifted_rear_left_wheel_mass = tk.Label(p3,text="Please enter the lifted rear right wheel mass in kg: ") lbl_lifted_rear_left_wheel_mass.place(relx=0.1, rely=0.65, relwidth=0.3, relheight=0.04) lifted_rear_left_wheel_mass = tk.Entry(p3) lifted_rear_left_wheel_mass.place(relx=0.65, rely=0.65, relwidth=0.1, relheight=0.04) #Enter the lifted rear right wheel mass in kg lbl_lifted_rear_right_wheel_mass = tk.Label(p3,text="Please enter the lifted rear right wheel mass in kg: ") lbl_lifted_rear_right_wheel_mass.place(relx=0.1, rely=0.7, relwidth=0.3, relheight=0.04) lifted_rear_right_wheel_mass = tk.Entry(p3) lifted_rear_right_wheel_mass.place(relx=0.65, rely=0.7, relwidth=0.1, relheight=0.04) #Boton para calcular el centro de gravedad calcular_centro_de_gravedad = Button(p3, text="Calcular", command=lambda: [ get_lift_height(lift_height.get()), get_left_wheelbase(left_wheelbase.get()), get_right_wheelbase(right_wheelbase.get()), get_rear_track(rear_track.get()), get_front_track(front_track.get()), get_wheel_diameter(wheel_diameter.get()), get_flattened_wheel_diameter(flattened_wheel_diameter.get()), get_rear_left_wheel_mass(rear_left_wheel_mass.get()), get_rear_right_wheel_mass(rear_right_wheel_mass.get()), get_front_left_wheel_mass(front_left_wheel_mass.get()), get_front_right_wheel_mass(front_right_wheel_mass.get()), get_lifted_rear_left_wheel_mass(lifted_rear_left_wheel_mass.get()), get_lifted_rear_right_wheel_mass(lifted_rear_right_wheel_mass.get()) ]) calcular_centro_de_gravedad.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1) root.mainloop()
69b00f30de1e437d363502c96cc4e0956416dddb
FelipeTacara/code-change-test
/greenBottles.py
423
3.921875
4
def greenbottles(bottles): for garrafas in range(bottles, 0, -1): # for loop counting down the number of bottles print(f"{garrafas} green bottles, hanging on the wall\n" f"{garrafas} green bottles, hanging on the wall\n" f"And if 1 green bottle should accidentally fall,\n" f"They'd be {garrafas - 1} green bottles hanging on the wall." f"...\n")
6f0283e896b0a758c9eb88198b2c9718c564aa1b
SurabhiTosh/AI_MazeSolving
/mazedemo.py
684
3.828125
4
from PIL import Image import numpy as np # Open the maze image and make greyscale, and get its dimensions im = Image.open('examples/small.png').convert('L') w, h = im.size # Ensure all black pixels are 0 and all white pixels are 1 binary = im.point(lambda p: p > 128 and 1) # Resize to half its height and width so we can fit on Stack Overflow, get new dimensions # binary = binary.resize((w//2,h//2),Image.NEAREST) w, h = binary.size # Convert to Numpy array - because that's how images are best stored and processed in Python nim = np.array(binary) # Print that puppy out for r in range(h): for c in range(w): print(nim[r,c],end='') print()
434f69b6fd36753ac13589061bec3cd3da51124a
Alex0Blackwell/recursive-tree-gen
/makeTree.py
1,891
4.21875
4
import turtle as t import random class Tree(): """This is a class for generating recursive trees using turtle""" def __init__(self): """The constructor for Tree class""" self.leafColours = ["#91ff93", "#b3ffb4", "#d1ffb3", "#99ffb1", "#d5ffad"] t.bgcolor("#abd4ff") t.penup() t.sety(-375) t.pendown() t.color("#5c3d00") t.pensize(2) t.left(90) t.forward(100) # larger trunk t.speed(0) self.rootPos = t.position() def __drawHelp(self, size, pos): """ The private helper method to draw the tree. Parameters: size (int): How large the tree is to be. pos (int): The starting position of the root. """ if(size < 20): if(size % 2 == 0): # let's only dot about every second one t.dot(50, random.choice(self.leafColours)) return elif(size < 50): t.dot(50, random.choice(self.leafColours)) # inorder traversial t.penup() t.setposition(pos) t.pendown() t.forward(size) thisPos = t.position() thisHeading = t.heading() size = size - random.randint(10, 20) t.setheading(thisHeading) t.left(25) self.__drawHelp(size, thisPos) t.setheading(thisHeading) t.right(25) self.__drawHelp(size, thisPos) def draw(self, size): """ The method to draw the tree. Parameters: size (int): How large the tree is to be. """ self.__drawHelp(size, self.rootPos) def main(): tree = Tree() tree.draw(125) t.hideturtle() input("Press enter to terminate program: ") if __name__ == '__main__': main()
1f4efdbabe7ec92db5d9a4d9f287de6c82988634
scott-yj-yang/cogs118a-final
/data_cleaning.py
3,909
3.59375
4
import pandas as pd from my_package import clean_course_num def clean_all_dataset(): # Clean the adult dataset columns = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", ">50K"] adult = pd.read_csv('data/adult.data', names=columns) adult['>50K'] = adult['>50K'].apply(lambda x: 1 if x.strip() != "<=50K" else -1) encoded = pd.get_dummies(adult, drop_first=True) with open("data/adult_clean.csv", 'w') as file: file.write(encoded.to_csv()) file.close() # Clean the cape dataset cape = pd.read_csv("data/CAPE_all.csv") cape = cape.assign(course_code=cape['Course'].apply(lambda course: str(course).split('-')[0][:-1])) cape = cape.assign(department=cape["course_code"].apply(lambda code: str(code).split()[0])) cape = cape.assign(course_num=cape["course_code"].apply( lambda code: str(code).split()[1] if len(str(code).split()) == 2 else code)) cape = cape.assign(course_description=cape['Course'].apply( lambda course: str(course).split('-')[1] if len(str(course).split('-')) == 2 else course)) grade = cape[['department', 'course_num', 'Term', 'Study Hrs/wk', 'Avg Grade Expected', 'Avg Grade Received']][ (cape["Avg Grade Expected"].notna()) & (cape["Avg Grade Received"].notna()) ] grade = grade.assign( GPA_Expected=grade['Avg Grade Expected'].apply(lambda grade_: float(grade_.split()[1][1:-1])), GPA_Received=grade['Avg Grade Received'].apply(lambda grade_: float(grade_.split()[1][1:-1])), letter_Recieved=grade['Avg Grade Received'].apply(lambda grade_: grade_.split()[0]) ) grade["GPA_Received"] = grade["GPA_Received"].apply(lambda grade_: 1 if grade_ > 3.2 else -1) grade = grade.drop(columns=['Avg Grade Expected', 'Avg Grade Received', 'letter_Recieved']) grade['is_upper'] = grade['course_num'].apply(clean_course_num) grade = grade.drop(columns=['course_num']) grade_encoded = pd.get_dummies(grade, drop_first=True) with open('data/cape_clean.csv', 'w') as file: file.write(grade_encoded.to_csv()) file.close() # Clean the COV dataset columns = ["Elevation", "Aspect", "Slope", "Horizontal_Distance_To_Hydrology", "Vertical_Distance_To_Hydrology", "Horizontal_Distance_To_Roadways", "Hillshade_9am", "Hillshade_Noon", "Hillshade_3pm", "Horizontal_Distance_To_Fire_Points"] + \ ["Wilderness_Area_" + str(i) for i in range(4)] + \ ["Soil_Type_" + str(i) for i in range(40)] + \ ['Cover_Type'] cov_raw = pd.read_csv("data/covtype.data.gz", names=columns) cov_raw['Cover_Type'] = cov_raw['Cover_Type'].apply( lambda type_num: 1 if type_num == 7 else -1) with open('data/cover_clean.csv', 'w') as file: file.write(cov_raw.to_csv()) file.close() # Clean the Letter dataset columns = ['letter', 'x-box', 'y-box', 'width', 'high', 'onpix', 'x-bar', 'y-bar', 'x2bar', 'y2bar', 'xybar', 'x2ybr', 'xy2br', 'x-ege', 'xegvy', 'y-ege', 'yegvx'] letter_raw = pd.read_csv("data/letter-recognition.data", names=columns) letter_p1 = letter_raw.assign( letter=letter_raw['letter'].apply(lambda letter: 1 if letter == 'O' else -1) ) positive_class = [chr(i) for i in range(ord("A"), ord("M") + 1)] letter_p2 = letter_raw.assign( letter=letter_raw['letter'].apply(lambda letter: 1 if letter in positive_class else -1) ) with open("data/letter_clean_p1.csv", 'w') as file: file.write(letter_p1.to_csv()) file.close() with open("data/letter_clean_p2.csv", 'w') as file: file.write(letter_p2.to_csv()) file.close()
e02add5ed76d468dc7ba4ec07060daeb1e069be3
tjbonesteel/ECE364
/Labfiles/Lab13/flow1.py~
2,174
3.53125
4
#! /usr/bin/env python2.6 # $Author: ee364d02 $ # $Date: 2013-11-19 22:43:05 -0500 (Tue, 19 Nov 2013) $ # $HeadURL: svn+ssh://ece364sv@ecegrid-lnx/home/ecegrid/a/ece364sv/svn/F13/students/ee364d02/Lab13/flow.py $ # $Revision: 63131 $ from Tkinter import * import os import sys import math import re fileIN = sys.argv[1] class Game(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="gray") self.parent = parent self.initUI() def initUI(self): count=2 self.parent.title("FLOW") fileObj = open(fileIN) def callback(m,n,color): row=n col=m btn = Button(self, text=line[x],width=10, height=5, command=lambda x=m, y=n: callback(x,y)) btn.config(bg="red") btn.grid(column=col, row=row) print n,m for line in fileObj: line = line.strip() line = line.split(",") width = len(line) for x in range(width): btn = Button(self, text=line[x],width=10, height=5, command=lambda x=x,color=line[x], y=count: callback(x,y,color)) if line[x] == "1": btn.config(bg = "red") elif line[x] == "2": btn.config(bg = "orange") elif line[x] == "3": btn.config(bg = "green") btn.grid(column=x, row=count) count += 1 quitButton = Button(self, text="Quit",width=10, command=self.quit) quitButton.grid(row=1, column=width-1) self.pack(fill=BOTH,expand=1) def main(): root=Tk() root.geometry("700x700+300+300") app=Game(root) if len(sys.argv) != 2: print "Usage: ./flow.py <inputfile>" exit(1) fileIN = sys.argv[1] if not os.access(fileIN,os.R_OK): print "%s is not a readable file" % (fileIN) exit(1) root.mainloop() if __name__ == '__main__': main()
d94f04f820ec9c6a0eb6b19c3e998384966b55aa
ProgFuncionalReactivaoct19-feb20/practica04-royerjmasache
/practica4.py
1,239
3.90625
4
""" Práctica 4 @royerjmasache """ # Importación de librerías import codecs import json # Lectura de archivos con uso de codecs y json file = codecs.open("data/datos.txt") lines = file.readlines() linesDictionary = [json.loads(a) for a in lines] # Uso de filter y función anónima para evaluar la condición requerida y filtrar los resultados goals = list(filter(lambda a: list(a.items())[1][1] > 3, linesDictionary)) # Presentación de resultados en forma de lista print("Players with more than 3 goals scored:\n", list(goals)) # Uso de filter y función anónima para cumplir evaluar la condición requerida y filtrar los resultados country = list(filter(lambda a: list(a.items())[0][1] == "Nigeria", linesDictionary)) # Presentación de resultados en forma de lista print("Nigeria players:\n", list(country)) # Uso de función anónima para seleccionar la posición height = lambda a: list(a.items())[2][1] # Uso de función min, map para la iteración y presentación de resultados en forma de lista print("Minimum height:\n", min(list(map(height, linesDictionary)))) # Uso de función max, map para la iteración y presentación de resultados en forma de lista print("Maximum height:\n", max(list(map(height, linesDictionary))))
8a39ae38331f518ac8c64d6d74dee4a89534f559
lfarhi/scikit-learn-mooc
/python_scripts/feature_selection.py
11,193
3.828125
4
# --- # jupyter: # jupytext: # cell_metadata_filter: -all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.6.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Feature selection # # %% [markdown] # ## Benefit of feature selection in practice # # ### Speed-up train and scoring time # The principal advantage of selecting features within a machine learning # pipeline is to reduce the time to train this pipeline and its time to # predict. We will give an example to highlights these advantages. First, we # generate a synthetic dataset to control the number of features that will be # informative, redundant, repeated, and random. # %% from sklearn.datasets import make_classification X, y = make_classification( n_samples=5000, n_features=100, n_informative=2, n_redundant=0, n_repeated=0, random_state=0, ) # %% [markdown] # We chose to create a dataset with two informative features among a hundred. # To simplify our example, we did not include either redundant or repeated # features. # # We will create two machine learning pipelines. The former will be a random # forest that will use all available features. The latter will also be a random # forest, but we will add a feature selection step to train this classifier. # The feature selection is based on a univariate test (ANOVA F-value) between # each feature and the target that we want to predict. The features with the # two most significant scores are selected. # %% from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.pipeline import make_pipeline model_without_selection = RandomForestClassifier(n_jobs=-1) model_with_selection = make_pipeline( SelectKBest(score_func=f_classif, k=2), RandomForestClassifier(n_jobs=-1), ) # %% [markdown] # We will measure the average time spent to train each pipeline and make it # predict. Besides, we will compute the generalization score of the model. We # will collect these results via cross-validation. # %% import pandas as pd from sklearn.model_selection import cross_validate cv_results_without_selection = pd.DataFrame( cross_validate(model_without_selection, X, y) ) cv_results_with_selection = pd.DataFrame( cross_validate(model_with_selection, X, y, return_estimator=True), ) # %% cv_results = pd.concat( [cv_results_without_selection, cv_results_with_selection], axis=1, keys=["Without feature selection", "With feature selection"], ).swaplevel(axis="columns") # %% [markdown] # Let's first analyze the train and score time for each pipeline. # %% import matplotlib.pyplot as plt cv_results["fit_time"].plot.box(vert=False, whis=100) plt.xlabel("Elapsed time (s)") _ = plt.title("Time to fit the model") # %% cv_results["score_time"].plot.box(vert=False, whis=100) plt.xlabel("Elapsed time (s)") _ = plt.title("Time to make prediction") # %% [markdown] # We can draw the same conclusions for both training and scoring elapsed time: # selecting the most informative features speed-up our pipeline. # # Of course, such speed-up is beneficial only if the performance in terms of # metrics remain the same. Let's check the generalization score. # %% cv_results["test_score"].plot.box(vert=False, whis=100) plt.xlabel("Accuracy score") _ = plt.title("Test score via cross-validation") # %% [markdown] # We can observe that the model's performance selecting a subset of features # decreases compared with the model using all available features. Since we # generated the dataset, we can infer that the decrease is because the # selection did not choose the two informative features. # # We can quickly investigate which feature have been selected during the # cross-validation. We will print the indices of the two selected features. # %% import numpy as np for idx, pipeline in enumerate(cv_results_with_selection["estimator"]): print( f"Fold #{idx} - features selected are: " f"{np.argsort(pipeline[0].scores_)[-2:]}" ) # %% [markdown] # We see that the feature `53` is always selected while the other feature # varies depending on the cross-validation fold. # # If we would like to keep our score with similar performance, we could choose # another metric to perform the test or select more features. For instance, we # could select the number of features based on a specific percentile of the # highest scores. Besides, we should keep in mind that we simplify our problem # by having informative and not informative features. Correlation between # features makes the problem of feature selection even harder. # # Therefore, we could come with a much more complicated procedure that could # fine-tune (via cross-validation) the number of selected features and change # the way feature is selected (e.g. using a machine-learning model). However, # going towards these solutions alienates the feature selection's primary # purpose to get a significant train/test speed-up. Also, if the primary goal # was to get a more performant model, performant models exclude non-informative # features natively. # # ## Caveats of the feature selection # When using feature selection, one has to be extra careful about the way it # implements it. We will show two examples where feature selection can # miserably fail. # # ### Selecting features without cross-validation # The biggest mistake to be made when selecting features is similar to one that # can be made when optimizing hyperparameters of a model: find the subset of # features on the same dataset as well used to evaluate the model's # generalization performance. # # We will generate a synthetic dataset with a large number of features and a # few samples to emphasize the issue. This use-case is typical in # bioinformatics when dealing with RNA-seq. However, we will use completely # randomized features such that we don't have a link between the data and the # target. Thus, the performance of any machine-learning model should not # perform better than the chance-level. In our example, we will use a logistic # regressin classifier. # %% rng = np.random.RandomState(42) X, y = rng.randn(100, 100000), rng.randint(0, 2, size=100) # %% from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression model = LogisticRegression() test_score = cross_val_score(model, X, y, n_jobs=-1) print(f"The mean accuracy is: {test_score.mean():.3f}") # %% [markdown] # There is no surprise that the logistic regression model performs as the # chance level when we provide the full dataset. # # We will then show the **wrong** pattern that one should not apply: select the # feature by using the entire dataset. We will choose ten features with the # highest ANOVA F-score computed on the full dataset. Subsequently, we # subsample the dataset `X` by selecting the features' subset. Finally, we # train and test a logistic regression model. # %% from sklearn.model_selection import cross_val_score feature_selector = SelectKBest(score_func=f_classif, k=10) test_score = cross_val_score(model, feature_selector.fit_transform(X, y), y) print(f"The mean accuracy is: {test_score.mean():.3f}") # %% [markdown] # Surprisingly, the logistic regression succeeded in having a fantastic # accuracy using data with no link with the target, initially. We, therefore, # know that these results are not legit. # # The reasons for obtaining these results are two folds: the pool of available # features is large compared to the number of samples. It is possible to find a # subset of features that will link the data and the target. By not splitting # the data, we leak knowledge from the entire dataset and could use this # knowledge will evaluating our model. # # Instead, we will now split our dataset into a training and testing set and # only compute the univariate test on the training set. Then, we will use the # best features found on the training set during the scoring. # %% model = make_pipeline(feature_selector, LogisticRegression()) test_score = cross_val_score(model, X, y) print(f"The mean accuracy is: {test_score.mean():.3f}") # %% [markdown] # We see that selecting feature only on the training set will not help when # testing our model. In this case, we obtained the expected results. # # Therefore, as with hyperparameters optimization or model selection, tuning # the feature space should be done solely on the training set, keeping a part # of the data left-out. # # ### Limitation of selecting feature using a model # An advanced strategy to select features is to use a machine learning model. # Indeed, one can inspect a model and find relative feature importances. For # instance, the parameters `coef_` for the linear models or # `feature_importances_` for the tree-based models carries such information. # Therefore, this method works as far as the relative feature importances given # by the model is sufficient to select the meaningful feature. # # Here, we will generate a dataset that contains a large number of random # features. # %% X, y = make_classification( n_samples=5000, n_features=100, n_informative=2, n_redundant=5, n_repeated=5, class_sep=0.3, random_state=0, ) # %% [markdown] # First, let's build a model which will not make any features selection. We # will use a cross-validation to evaluate this model. # %% model_without_selection = RandomForestClassifier(n_jobs=-1) cv_results_without_selection = pd.DataFrame( cross_validate(model_without_selection, X, y, cv=5) ) # %% [markdown] # Then, we will build another model which will include a feature selection # step based on a random forest. We will also evaluate the performance of the # model via cross-validation. # %% from sklearn.feature_selection import SelectFromModel model_with_selection = make_pipeline( SelectFromModel( estimator=RandomForestClassifier(n_jobs=-1), ), RandomForestClassifier(n_jobs=-1), ) cv_results_with_selection = pd.DataFrame( cross_validate(model_with_selection, X, y, cv=5) ) # %% [markdown] # We can compare the generalization score of the two models. # %% cv_results = pd.concat( [cv_results_without_selection, cv_results_with_selection], axis=1, keys=["Without feature selection", "With feature selection"], ).swaplevel(axis="columns") cv_results["test_score"].plot.box(vert=False, whis=100) plt.xlabel("Accuracy") _ = plt.title("Limitation of using a random forest for feature selection") # %% [markdown] # The model that selected a subset of feature is less performant than a # random forest fitted on the full dataset. # # We can rely on some aspects tackled in the notebook presenting the model # inspection to explain this behaviour. The decision tree's relative feature # importance will overestimate the importance of random feature when the # decision tree overfits the training set. # # Therefore, it is good to keep in mind that feature selection relies on # procedures making some assumptions, which can be perfectible.
c006402cf62530d0b685d5becf283a9f43d1796d
UCMHSProgramming16-17/file-io-HikingPenguin17
/PokeClass.py
344
3.5
4
import random class Pokemon(object): def __init__(self, identity): self.name = identity self.level = random.randint(1, 100) bulb = Pokemon('Bulbasaur') char = Pokemon('Charmander') squirt = Pokemon('Squirtle') print(bulb.name, bulb.level) print(char.name, char.level) print(squirt.name, squirt.level)
002464d45f720f95b4af89bfa30875ae2ed46f70
spencerhcheng/algorithms
/codefights/arrayMaximalAdjacentDifference.py
714
4.15625
4
#!/usr/bin/python3 """ Given an array of integers, find the maximal absolute difference between any two of its adjacent elements. Example For inputArray = [2, 4, 1, 0], the output should be arrayMaximalAdjacentDifference(inputArray) = 3. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer inputArray Guaranteed constraints: 3 ≤ inputArray.length ≤ 10, -15 ≤ inputArray[i] ≤ 15. [output] integer The maximal absolute difference. """ def maxDiff(arr): max_diff = float('-inf') for idx in range(1, len(arr)): max_diff = max(max_diff, abs(arr[idx] - arr[idx - 1])) return max_diff if __name__ == "__main__": arr = [2, 4, 1, 0] print(maxDiff(arr))
1283bc076c088f5f3ef66ba11af46cdb39aae2cd
cjohlmacher/PythonDataStructures
/37_sum_up_diagonals/sum_up_diagonals.py
662
4
4
def sum_up_diagonals(matrix): """Given a matrix [square list of lists], return sum of diagonals. Sum of TL-to-BR diagonal along with BL-to-TR diagonal: >>> m1 = [ ... [1, 2], ... [30, 40], ... ] >>> sum_up_diagonals(m1) 73 >>> m2 = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9], ... ] >>> sum_up_diagonals(m2) 30 """ i = 0 j = len(matrix)-1 k = 0 sum = 0 while j > -1 and i < len(matrix): sum += matrix[k][i] sum += matrix[k][j] i += 1 j -= 1 k += 1 return sum
2252436f7d0b24feb0c6e518ce47f4b85b68bd40
saumak/AI-projects
/map-search-algorithm/problem3/solver16.py
7,136
3.859375
4
#!/usr/bin/env python # # solver16.py : Solve the 16 puzzle problem - upto 3 tiles to move. # # (1) # State space: All possible formulation of the tiles in 16 puzzle problem. # For example, a sample of the state look like this, # S0 = array([[ 2, 3, 0, 4], # [ 1, 6, 7, 8], # [ 5, 10, 11, 12], # [ 9, 13, 14, 15]]) # # Successor function: Possible position of the tiles after 1 move (either moving 1, 2, or 3 tiles at ones) # I marked the each successor function with its appropriate move with the 3 character notation. # # The successor gets in the input of current state and the move up to the state. # Then it returns list of all the possible next states paired with moves taken upto that state, heuristic, and the cost. # # >>> successor(S0, []) # [[array([[ 1, 2, 3, 4], # [ 5, 6, 7, 8], # [ 9, 10, 0, 12], # [13, 14, 11, 15]]), ['D14'], 1.3333333333333333, 2.333333333333333], # [array([[ 1, 2, 3, 4], # [ 5, 6, 0, 8], # [ 9, 10, 7, 12], # [13, 14, 11, 15]]), ['D24'], 2.0, 3.0], # [array([[ 1, 2, 0, 4], # [ 5, 6, 3, 8], # [ 9, 10, 7, 12], # [13, 14, 11, 15]]), ['D34'], 2.6666666666666665, 3.6666666666666665], # [array([[ 1, 2, 3, 4], # [ 5, 6, 7, 8], # [ 9, 10, 11, 12], # [13, 0, 14, 15]]), ['R13'], 1.3333333333333333, 2.333333333333333], # [array([[ 1, 2, 3, 4], # [ 5, 6, 7, 8], # [ 9, 10, 11, 12], # [ 0, 13, 14, 15]]), ['R23'], 2.0, 3.0], # [array([[ 1, 2, 3, 4], # [ 5, 6, 7, 8], # [ 9, 10, 11, 12], # [13, 14, 15, 0]]), ['L13'], 0.0, 1.0]] # # Edge weights: 1 (One valid move is calculated as cost of 1) # # Goal state: Following is the goal state # # array([[ 1, 2, 3, 4], # [ 5, 6, 7, 8], # [ 9, 10, 11, 12], # [13, 14, 15, 0]]) # Heuristic function: (Sum of Manhattan cost) / 3 # # If I use the sum of the Manhattan cost as in the notes, it would be not admissble due to the over-estimating. # I can move the tiles upto 3, which means that Dividing the sum of Manhattan cost by 3 won't over-estimate. # Hence, this huristic function is admissible. # Also, it is consistent, because it meets the triangle inequality. # # (2) How the search algorithm work # # For each step, the algorithm chooses to branch the node with the minimum f value, which is (heuristic + cost). The algorithm also keeps track of the revisited states. In the successor function, if the child state is previously visited, then it doesn't return the visited child state. It keeps branching until it reaches the goal state. # # (3) Any problem I faced, assumptions, simplifications, design decisions # # The heuristic function I am using is admissble, hence it would be complete and optimal. # However, when the input board gets very complicated, the power of the heuristics to find the goal state tend to get weaker. # I found that instead of using the admissible heuristic, if I used a heuristic with sum of Manhattan distance without dividing it by 3, # the performance got much better. Here is the comparison of the two heuristics. # # < Heuristic: sum of Manhattan distance divided by 3 > # # [hankjang@silo problem3]$ time python solver16.py input_board10.txt # D14 R24 U13 L22 D24 R14 D12 R23 U31 L31 # real 0m22.801s # user 0m22.755s # sys 0m0.030s # # < Heuristic: sum of Manhattan distance (not dividing by 3)> # # [hankjang@silo problem3]$ time python solver16.py input_board10.txt # D14 R24 U13 L22 D24 R14 D12 R23 U31 L31 # real 0m0.587s # user 0m0.558s # sys 0m0.026s # # The difference in performance was stable for over 10 different input boards I tested. # However, since the heuristic of using sum of Manhattan distance (not dividing by 3) is not admissible, # I decided to stick with the slower, but admissible heuristic. # from __future__ import division import sys import numpy as np from scipy.spatial.distance import cdist n_tile = range(4) col_move = {0:["L11","L21","L31"],1:["R12","L12","L22"],2:["R13","R23","L13"],3:["R14","R24","R34"]} row_move = {0:["U11","U21","U31"],1:["D12","U12","U22"],2:["D13","D23","U13"],3:["D14","D24","D34"]} G = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,0]]) # Save the position to dictionary # Each dictionary holds the row, col index as value in a numpy array # Then, returns the sum of the mahattan distances per all tiles divided by 3. def manhattan_distance(s1, s2): s1_dict = {} s2_dict = {} for i in n_tile: for j in n_tile: s1_dict[s1[i][j]] = np.array([i, j]) s2_dict[s2[i][j]] = np.array([i, j]) return sum([np.abs(s1_dict[key]-s2_dict[key]).sum() for key in s1_dict]) / 3 def initial_state(filename): file = open(filename, "r") return np.array([[int(tile) for tile in line.split()] for line in file]) def swap(s, r1, c1, r2, c2): temp = s[r1,c1] s[r1,c1] = s[r2,c2] s[r2,c2] = temp def successor(s, cur_m): successor_list = [] # Get the index of the blank tile row, col = np.where(s==0) row_idx, col_idx = row[0], col[0] # Get the 6 possible moves possible_move = row_move[row_idx] + col_move[col_idx] for move in possible_move: row, col = row_idx, col_idx s_next = np.copy(s) # Get direction and the number of tiles to move direction, n, _ = move n = int(n) if direction=='D': for i in range(n): swap(s_next,row,col,row-1,col) row -= 1 elif direction=='U': for i in range(n): swap(s_next,row,col,row+1,col) row += 1 elif direction=='R': for i in range(n): swap(s_next,row,col,row,col-1) col -= 1 elif direction=='L': for i in range(n): swap(s_next,row,col,row,col+1) col += 1 # Don't add the child if it's already checked if any((s_next == s).all() for s in puzzle_tracking): continue h = heuristic(s_next, G) m = cur_m + [move] c = h + len(m) successor_list.append([s_next, m, h, c]) return successor_list def is_goal(s): return (s == G).all() def heuristic(s1, s2): return manhattan_distance(s1, s2) # return number_of_misplaced_tiles(s1, s2) # f = heuristic + cost so far def find_best_state(fringe): f_list = [s[3] for s in fringe] return f_list.index(min(f_list)) def solve(initial_board): global puzzle_tracking h = heuristic(initial_board, G) fringe = [[initial_board, [], h, h]] while len(fringe) > 0: s, m, _, c = fringe.pop(find_best_state(fringe)) puzzle_tracking.append(s) if is_goal(s): return fringe, m fringe.extend(successor(s, m)) return False def printable_result(path): return " ".join(path) filename = sys.argv[1] S0 = initial_state(filename) puzzle_tracking = [] fringe, path = solve(S0) print printable_result(path)
624fc12118833578813725bbb15e2477e04e587e
borisnorm/codeChallenge
/practiceSet/redditList/general/rotatedBSearch.py
1,074
4
4
#Binary Search on a Rotated Array #Find the pivot point on a rotated array with slight modificaitons to binary search #There is reason why the pivoting does not phase many people #[5, 6, 7, 8, 1, 2, 3, 4] def find_pivot_index(array, low, hi): #DONT FORGET THE BASE CASE if hi < low: return 0 if hi == low: return low mid = (low + hi) / 2 #pivot turns when, mid and mid - 1 work #If indicies are correct, and pivot starts at mid if (mid < hi && arr[mid] > array[mid + 1]): return mid #hi low are correct, and pivot starts ad mide -1 if (mid > low && arr[mid] < array[mid - 1]): return mid - 1 #two other check cases which are key #if lower is greater than mid pivot, the pivot is between them if array[low] >= array[mid]: #why is it mid - 1? return find_pivot_index(array, low, mid - 1): #if array[low] < array[mid]: if hi is greater than mid, pivot is not here else: #If it is not between them, they must be somewhere else #slowly incremenet this thing by 1? return find_pivot_index(array, mid + 1, hi)
ecaa063b18366d5248e01f5392fcb51e59612c1e
borisnorm/codeChallenge
/practiceSet/levelTreePrint.py
591
4.125
4
#Print a tree by levels #One way to approach this is to bfs the tree def tree_bfs(root): queOne = [root] queTwo = [] #i need some type of switching mechanism while (queOne or queTwo): print queOne while(queOne): item = queOne.pop() if (item.left is not None): queTwo.append(item.left) if (item.right is not None): queTwo.append(item.right) print queTwo while(queTwo): item = queTwo.pop() if (item.left is not None): queOne.append(item.left) if (item.right is not None): queOne.append(item.right)
d3ad65cbc6ec353c964cb8fb7202b0156f2fb150
borisnorm/codeChallenge
/practiceSet/g4g/DP/cover_distance.py
803
4
4
#Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps. #distance, and array of steps in the step count #1, 2, 3 is specific - general case is harder because of hard coding #RR solution def cover(distance): if distance < 0: return 0 if distance = 0: return 1 else: return cover(distance - 1) + cover(distance - 2) + cover(distance - 3) #DP solution def cover(distance): memo = [0 for x in range(distance) + 1] memo[1] = 1 memo[2] = 2 memo[3] = 3 for i in range(4, len(distance)): #I am not sure if i need to add anything onto this or not, no add because its the same number of ways - we are not counting total number of step #we can do that too memo[i] = memo[i-1] + memo[i -2] + memo[i-3] return memo[distance]
bd2ec1025a05a2b3b3a8cb0188762d620090c328
borisnorm/codeChallenge
/practiceSet/intoToBinary.py
407
3.828125
4
#Math Way def binary_to_int(number): result = "" while (number > 0): result.insert(0, number % 2) number = number % 2 return result #BitShifting Way def b_to_int(number): result = [] for i in range(0, 32): result.insert(number && 1, 0) number >> 1 return result #Python convert array of numbers to string # ''.join(map(str, myList)) #This works with the array 123,
409c1452aaaa56dfc51186c75c8a1bbaefece675
borisnorm/codeChallenge
/practiceSet/phoneScreen/num_reduce.py
1,074
3.578125
4
#Given a list o numbers a1/b1, a2/b2, return sum in reduced form ab #Sum it in fractional form, or keep decimals and try to reverse #This is language specific question #(0.25).asInteger_ratio() #Simplify #from Fractions import fraction #Fraction(0.185).limit_denominator()A #A fraction will be returned from Fractions import fraction class Solution: #Array of tuples () def reduced_sum(array): #Fraction array is here deci_array = [] for fraction in array: deci_array.append(fracion[0] / fraction[1]) #Fraction array is here sum_value = reduce(lambda x: x + y, deci_array) return Fraction(sumValue).limit_denominator() #Find the amx difference in array such that larges appears after the smaller def max_diff(array): min_val = 1000000 #Max integer max_diff = 0 for value in array: if value < min_val: min_val = value diff = value - min_val if diff > max_diff: max_diff = diff return diff
5efebfc8ae11c7ae96bfb8c263b5320e48a2a582
borisnorm/codeChallenge
/practiceSet/redditList/trees/kOrderBST.py
627
3.75
4
#Find Second largest number in a BST #Must be the parent of the largest number, logn time def secondLargest(root): if root.right.right is None: return root.right.value else: return secondLargest(root.right): #Find The K largest number in a BST #Initalize counter to 1, could put it into an array, but wastes space def k_largest(root, counter, k): if root is None: return else: k_largest(root.left, counter + 1, k) #THE Location must be here not above or it will print pre, order after every hit if (counter == k): return root.value k_largest(root.right, counter + 1, k)
74e6ec63b7f3f50cb964f5c0959e4b6b224bbf05
borisnorm/codeChallenge
/practiceSet/g4g/graph/bridge.py
759
3.53125
4
#Given a graph find all of the bridges in the graph #Remove every edge and then BFS the graph, fi not all veriicies touched then that is it #get neighbors - would recursive solution be better here? Naieve solution def dfs(source, graph, size): visited = set() stack = [source] while stack: item = stack.pop(0) if item not in visited: visited.add(item) for item in getNeighbors(item): stack.insert(0, item) if len(visited) = len(graph.keys()) return True return False def bridge_find(graph): bridges = [] for key in graph.keys(): for edge in graph[key]: temp_holder = edge graph[key].remove(edge) if dfs: bridges.append(edge) return bridges #Most efficent algorithm for this
77806d17215fc004445465e5c06714662f4deadf
borisnorm/codeChallenge
/practiceSet/redditList/trees/printTree.py
657
3.8125
4
#Print Tree using BFS and DFS def dfs_print(root): if root is None: return else: #shift print down, for pre, in, or post order print root.value dfs_print(root.left) dfs_print(root.right) def bfs_print(root): queOne = [root] queTwo = [] while (queOne && queTwo): print queOne while (queOne): item = queOne.pop(0) if (item.left): queTwo.append(item.left) if (item.right) queTwo.append(item.right) print queTwo while (queTwo): item = queTwo.pop(0) if (item.left): queOne.append(item.left) if (item.right): queTwo.append(item.right)
1052e9187b6693114b6472dbfc4aebef9ec5e368
borisnorm/codeChallenge
/practiceSet/unionFind.py
937
3.765625
4
class DisjoinstSet: #This does assume its in the set #We should use a python dictionary to create this def __init__(self, size): #Make sure these are default dicts to prevent the key error? self.lookup = {} self.rank = {} self.size = 0 def add(self, item): self.lookup[item] = -1 #Union by rank def union(self, itemOne, itemTwo): rankOne = find_rank(itemOne) rankTwo = find_rank(itemTwo) if rankOne >= rankTwo: self.lookup[itemOne] = find(itemTwo) self.rank[itemTwo] += 1 return self.lookup[itemTwo] = find(itemOne) self.lookup[itemOne] = self.lookup[itemTwo] return #Find Rank def find_rank(self, item): return self.rank[item] #Find the parent set def find(self, item): pointer = self.lookup[item] while (pointer != -1): if (self.lookup[pointer] == -1): return pointer pointer = self.lookup[pointer] return pointer
2c76d8ff3516b065bcf92f674a847640f0896153
borisnorm/codeChallenge
/practiceSet/g4g/tree/bottom_top_view.py
1,168
3.71875
4
#Print the bottom view of a binary tree lookup = defaultdict([]) def level_serialize(root, lookup): queueOne = [(root, 0, 0)] queueTwo = [] while (queueOne && queueTwo): while (queueOne): item = queueOne.pop() lookup[item[1]].append(item[0].value) if (item[0].left): queueTwo.insert(0, (item[0].left, item[1] - 1, item[2] + 1)) if (item[0].right): queueTwo.insert(0, (item[0].left, item[1] + 1, item[2] + 1)) while (queueTwo): item = queueTwo.pop() lookup[item[1]].apppend(item[0].value) if (item[0].left): queueOne.insert(0, (item[0].left, item[1] - 1, item[2] + 1)) if (item[1].right): queueOne.insert(0, (item[0].left, item[1] - 1, item[2] + 1)) return def bottom_view(root): lookup = defaultdict([]) level_serialize(root, lookup) solution = [] for key in sorted(lookup.keys()): solution.append(lookup[key][0]) return solution def top_view(root): lookup = defaultdict([]) level_serialize(root, lookup) solution = [] for key in sorted(lookup.keys()): length = len(lookup[key]) - 1 solution.append(lookup[key][length] return solution
7efe77de55bd3666271186c9e8537f4228eb300d
borisnorm/codeChallenge
/practiceSet/allPartitions.py
808
3.71875
4
def isPal(string): if string = string[::-1] return True return False def isPal(array): lo = 0 hi = len(array) - 1 while lo < hi: if array[lo] != array[hi]): return False return True def arrayElmIsPal(array): for i in range(len(array)): if isPal(array[i]) is False: return False return True def partition(string) array = string.split() solution = [] return solution def parted(array, current, final, solution): if len(array) == 0: if len(current) == 0: solution.append(final) if len(current) > 0: #This is because mandatory brackets if arrayElemIsPal([current] + final): solution.append([current] + final) else: parted(array[:1], current + array[0], final) parted(array[:1], current, final + [[array[0]])
15deda40cadaee36bf146665d48fd507d33baaad
borisnorm/codeChallenge
/practiceSet/g4g/stringArray/special_reverse.py
364
3.671875
4
#Reverse reverse then add back in def s_rev(string, alphabet): string_builder = "" for i in range(len(string)): if string[i] in alphabet: string_builder += string[i] rev = string_builder[::-1] rev_counter = 0 for j in range(len(string)): if string[j] in alphabet: string[j] = rev[rev_counter] rev_counter += 1 return string
bb6ec537a4019717fcb9f4d9be38d30bd84c31c5
borisnorm/codeChallenge
/practiceSet/g4g/stringArray/count_trip.py
370
3.921875
4
#Count Triplets with sum smaller than a given value in an array #Hashing does not help because there is no specific target to look for? def count_trip(array, value): counter = 0 for i in range(len(array)): for j in range(len(array)): for k in range(len(array)): if array[i] + array[j] + array[k] < value: counter += 1 return counter
07e6ccccbbd50cbb91199588006e07afc89887af
sbsreedh/DP-3
/minFallingPathSum.py
1,042
3.84375
4
#Time Complexity=O(m*n)m-length of A, n-length of A[0] #Space Complexity-O(m*n) #we first initialize a 2D DP matrix, and then iterate the original matrix row by row. For each element in DP matrix, we sum up the corresponding element from original matrix with the minimum neighbors from previous row in DP matrix.Here instead of using a new matrix I have made computations in the existing one. Does this alter my SPACE COMAPLEXITY ? I guess it will be still O(m*n). Correct me if I am wrong. class Solution: def minFallingPathSum(self, A: List[List[int]]) -> int: if len(A)==0 or len(A[0])==0: return 0 m=len(A) n=len(A[0]) for i in range(1,m): for j in range(n): if j==0: A[i][j]+=min(A[i-1][j+1],A[i-1][j]) elif j==n-1: A[i][j]+=min(A[i-1][j-1],A[i-1][j]) else: A[i][j]+=min(A[i-1][j-1],A[i-1][j],A[i-1][j+1]) return min(A[-1])
fe8abe9c0010c34ac01963ffa8032930c899625c
FailedChampion/CeV_Py_Ex
/ex049.py
316
4.0625
4
# Exercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada # de um número que o usuário escolher, só que agora utilizando um laço for. num_escolhido = int(input('Insira o número que deseja ver a tabuada: ')) for a in range(1, 11): print('{} x {} = {}'.format(num_escolhido, a, num_escolhido * a))
7d610d3df84b0abb5c39d03fd658cd1f0f0b0e81
FailedChampion/CeV_Py_Ex
/ex006.py
329
3.984375
4
# Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. n1 = int(input('Digite um número: ')) dou = n1 * 2 tri = n1 * 3 rq = n1 ** (1/2) print('\n O dobro de {} é: {}'.format(n1, dou), '\n \n O triplo de {} é: {}'.format(n1, tri), '\n \n A raíz quadrada de {} é: {:.3f}'.format (n1, rq))
65d580e0f81ba9c29d3e6aa97becd5c83bd36aaf
FailedChampion/CeV_Py_Ex
/ex30.py
164
3.9375
4
num = int(input('Insira um número: ')) res = num % 2 print('\n') print(res) print('\nSe o resultado for 1, o número é ímpar,\n se for 0, é par.')
81575a05e053e8fb26e75a18deeb4b2db6105a65
FailedChampion/CeV_Py_Ex
/ex007.py
357
4
4
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. n1 = float(input('Insira a primeira nota: ')) n2 = float(input('Insira a segunda nota: ')) print('A média entre {:.1f} e {:.1f} é igual a {:.1f}.'.format(n1, n2, (n1 + n2 / 2))) print('Com isso em mente, a média do aluno foi {:.1f}.'.format(n1 + n2 / 2))
7e9255240d93efca2d010bb9f290520d56dd9dad
FailedChampion/CeV_Py_Ex
/ex018.py
422
4.03125
4
# Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. from math import sin, cos, tan, radians n = float(input('Insira um ângulo: ')) r = radians(n) print('Os valores de seno, cosseno e tangente do ângulo {:.0f} são:'.format(n)) print('\nSeno: {:.2f}'.format(sin(r))) print('Cosseno: {:.2f}'.format(cos(r))) print('Tangente: {:.2f}'.format(tan(r)))
fd181116ec4204dc513a88bad5efbe5057fe2096
FailedChampion/CeV_Py_Ex
/ex008.py
387
4.09375
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. m = float(input('Insira uma distância em metros: ')) dm = m * 10 cm = m * 100 mm = m * 1000 print('A medida de {}m corresponde a \n{:.3f} Km \n{:.2f} Hm \n{:.1f} Dam'.format(m, (m / 1000), (m / 100), (m / 10))) print('{:.0f} Dm \n{:.0f} Cm \n{:.0f} mm'.format(dm, cm, mm))
4f99ebc36affe769b3f861b7353e26dd8bc61f17
ANANDMOHIT209/PythonBasic
/11opera.py
255
4.09375
4
#1.Arithmatic Operators x=2 y=3 print(x+y) print(x-y) print(x*y) print(x/y) #2.Assignment Operators x+=2 print(x) a,b=5,6 print(a) print(b) #3.Relational Operators-- <,>,==,<=,>=,!= #4.Logical Operators-- and ,or,not #5.Unary Operators--
ef1808200296b1e75862f604def553543e94c246
ANANDMOHIT209/PythonBasic
/4.py
209
3.765625
4
x=2 y=3 print(x+y) x=10 print(x+y) name='mohit' print(name[0]) #print(name[5]) give error bound checking print(name[-1]) #it give last letter print(name[0:2]) print(name[1:3]) print(name[1:])
21d5842cfc55a1ee5d742eab7ca8f4a89278de30
usert5432/cafplot
/cafplot/plot/rhist.py
3,128
3.546875
4
""" Functions to plot RHist histograms """ from .nphist import ( plot_nphist1d, plot_nphist1d_error, plot_nphist2d, plot_nphist2d_contour ) def plot_rhist1d(ax, rhist, label, histtype = None, marker = None, **kwargs): """Plot one dimensional RHist1D histogram. This is a wrapper around `plot_nphist1d` function. Parameters ---------- ax : Axes Matplotlib axes on which histogram will be plotted. rhist : Rhist1D Histogram to be plotted. histtype : { 'line', 'step', 'bar' } or None, optional Histogram style. None by default. marker : str or None, optional If not None this function will add markers on top of histogram bins. c.f. help(matplotlib.pyplot.scatter). kwargs : dict, optional Additional parameters to pass directly to the matplotlib plotting funcs """ plot_nphist1d( ax, rhist.hist, rhist.bins_x, label, histtype, marker, **kwargs ) def plot_rhist1d_error( ax, rhist, err_type = 'bar', err = None, sigma = 1, **kwargs ): """Plot error bars for one dimensional RHist1D histogram Parameters ---------- ax : Axes Matplotlib axes on which histogram will be plotted. rhist : Rhist1D Histogram to be plotted. err_type : { 'bar', 'margin' } or None Error bar style. err : { None, 'normal', 'poisson' } Type of the statistics to use for calculating error margin. c.f. `RHist.get_error_margin` sigma : float Confidence expressed as a number of Gaussian sigmas c.f. `RHist.get_error_margin` kwargs : dict, optional Additional parameters to pass directly to the matplotlib plotting funcs c.f. `plot_nphist1d_error` """ hist_down, hist_up = rhist.get_error_margin(err, sigma) plot_nphist1d_error( ax, hist_down, hist_up, rhist.bins_x, err_type, **kwargs ) def plot_rhist2d(ax, rhist, **kwargs): """Draw a two dimensional RHist2D histogram as an image. Parameters ---------- ax : Axes Matplotlib axes on which histogram will be plotted. rhist : RHist2D Histogram to be plotted. kwargs : dict, optional Additional parameters to pass directly to the matplotlib NonUniformImage function Returns ------- NonUniformImage Matplotlib NonUniformImage that depicts `rhist`. """ return plot_nphist2d(ax, rhist.hist, rhist.bins, **kwargs) def plot_rhist2d_contour(ax, rhist, level, **kwargs): """Draw level contour for a two dimensional RHist2D histogram. Parameters ---------- ax : Axes Matplotlib axes on which contours will be plotted. rhist : RHist2D Histogram to be plotted. level : float or list of float Value of level(s) at which contour(s) will be drawn. kwargs : dict, optional Additional parameters to pass to the `plot_nphist2d_contour` function. Returns ------- pyplot.contour.QuadContourSet Matplotlib contour set """ return plot_nphist2d_contour(ax, rhist.hist, rhist.bins, level, **kwargs)
11ff9ab018629fccbc71bbde47158ae1c8f0a0af
bamundi/python-cf
/diccionario.py
373
3.625
4
#no se pueden usar diccionarios y listas #no tienen indice como las listas #no se puede hacer slidesing (?) [0:2] #se debe hacer uso de la clave para llamar a un elemento diccionario = {'Clave1' : [2,3,4], 'Clave2' : True, 'Clave00' : 4, 5 : False } diccionario['clave00'] = "hola" print diccionario['Clave2'] print diccionario[5] print diccionario['clave00']
925cdc22f6be9a7103ba64204e1c54aa31db0f4c
jpclark6/adventofcode2019
/solutions/20day.py
4,467
3.578125
4
import re, time class Puzzle: def __init__(self, file_name): self.tiles = {} file = open(file_name).read().splitlines() matrix = [[x for x in line] for line in file] for y in range(len(matrix)): for x in range(len(matrix[0])): if bool(re.search('[#.]', matrix[y][x])): tile = Tile(x, y, matrix[y][x]) self.tiles[str(x) + "," + str(y)] = tile if bool(re.search('[A-Z]', matrix[y - 1][x])): tile.portal = True tile.portal_key = matrix[y - 2][x] + matrix[y - 1][x] elif bool(re.search('[A-Z]', matrix[y + 1][x])): tile.portal = True tile.portal_key = matrix[y + 1][x] + matrix[y + 2][x] elif bool(re.search('[A-Z]', matrix[y][x - 1])): tile.portal = True tile.portal_key = matrix[y][x - 2] + matrix[y][x - 1] elif bool(re.search('[A-Z]', matrix[y][x + 1])): tile.portal = True tile.portal_key = matrix[y][x + 1] + matrix[y][x + 2] def get_tile(self, x, y): key = str(x) + "," + str(y) return self.tiles[key] def find_end(self): start = self.find_portal("AA")[0] i = 0 visited = {start.make_key(): [i]} queue = self.check_surrounding_spaces(start, visited, i) while True: i += 1 new_queue = [] for tile in queue: # import pdb; pdb.set_trace() if tile.portal_key == "ZZ": print("Found end:", i) return if visited.get(tile.make_key()): visited[tile.make_key()].append(i) else: visited[tile.make_key()] = [i] new_queue += self.check_surrounding_spaces(tile, visited, i) queue = new_queue def check_surrounding_spaces(self, tile, visited, i): queue = [] if tile.portal: portal_locs = self.find_portal(tile.portal_key) for portal in portal_locs: try: if self.recently_visited(visited[portal.make_key()], i): continue except KeyError: return [portal] for tile in tile.make_key_check(): try: tile = self.tiles[tile] except KeyError: continue try: if tile.space == "." and not self.recently_visited(visited[tile.make_key()], i): queue.append(tile) except KeyError: queue.append(tile) return queue def recently_visited(self, visited, i): if len(visited) > 4: return True for time in visited: if time >= i - 1: return True return False def find_portal(self, letters): tiles = [] for loc, tile in self.tiles.items(): if tile.portal == True and tile.portal_key == letters: tiles.append(tile) return tiles class Tile: def __init__(self, x, y, space, portal=False, portal_key=None): self.x = x self.y = y self.space = space self.portal = portal self.portal_key = portal_key def __repr__(self): if self.portal: add_key = self.portal_key else: add_key = "" return "(" + str(self.x) + "," + str(self.y) + ")" + self.space + add_key def __str__(self): return self.__repr__ def wall(self): if self.space == "#": return True else: return False def passage(self): if self.space == ".": return True else: return False def make_key(self): return str(self.x) + "," + str(self.y) def make_key_check(self): return [ str(self.x + 1) + "," + str(self.y), str(self.x - 1) + "," + str(self.y), str(self.x) + "," + str(self.y + 1), str(self.x) + "," + str(self.y - 1), ] s = time.time() puzzle = Puzzle('./puzzledata/20day.txt') puzzle.find_end() e = time.time() print("Time for part 1:", round(e - s, 3), "Seconds")
53f08e65cc83ea5040a6477e363a487a59d343ed
jpclark6/adventofcode2019
/solutions/8day.py
2,043
3.53125
4
# For example, given an image 3 pixels wide and 2 pixels tall, # the image data 123456789012 corresponds to the following image layers: # Layer 1: 123 # 456 # Layer 2: 789 # 012 # The image you received is 25 pixels wide and 6 pixels tall. def input(): return open("puzzledata/8day.txt", "r").read().rstrip('\n') def slice_layers(wide, tall, data): if len(data) % wide * tall != 0: print("Data is not correct length") return image = [] layer = [] while data: row = list(data[0:wide]) row = [int(n) for n in row] data = data[wide:] layer.append(row) if len(layer) == tall: image.append(layer) layer = [] return image wide = 25 tall = 6 data = input() def find_fewest_0_layer_multi_1_by_2(image): wide = len(image[0][0]) tall = len(image[0]) fewest = wide * tall for i, layer in enumerate(image): pixels = [pixel for row in layer for pixel in row] num_zeros = pixels.count(0) if num_zeros < fewest: fewest = num_zeros fewest_layer = i pixels = [pixel for row in image[fewest_layer] for pixel in row] return pixels.count(1) * pixels.count(2) def print_image(image): wide = len(image[0][0]) tall = len(image[0]) final_image = [[-1 for _ in range(wide)] for _ in range(tall)] for l, layer in enumerate(image): for r, row in enumerate(layer): for p, pixel in enumerate(row): if final_image[r][p] != -1 or pixel == 2: pass else: if pixel == 1: final_image[r][p] = "X" elif pixel == 0: final_image[r][p] = " " print("\n") for row in final_image: print("".join(row)) print("\n") # import pdb; pdb.set_trace() image = slice_layers(wide, tall, data) ans_part_1 = find_fewest_0_layer_multi_1_by_2(image) print("Part 1 answer", ans_part_1) print_image(image)
e27e14c82cf4b8a8a76981ae7ff87ec882ca35d8
oarriaga/PyGPToolbox
/src/genBivarGaussGrid.py
1,072
3.890625
4
## This code is modified from: https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/ ## How to use output: ## plt.figure() ## plt.contourf(X, Y, Z) ## plt.show() import numpy as np def genBivarGaussGrid(mu, cov, numSamples = 60): size = np.sqrt(np.amax(cov)) X = np.linspace(mu[0]-4*size, mu[0]+4*size, numSamples) Y = np.linspace(mu[1]-3*size, mu[1]+3*size, numSamples) X, Y = np.meshgrid(X, Y) pos = np.zeros((X.shape[0], X.shape[1], 2)) pos[:, :, 0] = X pos[:, :, 1] = Y def multivariate_gaussian(pos, mu, Sigma): """Return the multivariate Gaussian distribution on array pos. pos is an array constructed by packing the meshed arrays of variables x_1, x_2, x_3, ..., x_k into its _last_ dimension. """ n = mu.shape[0] Sigma_det = np.linalg.det(Sigma) Sigma_inv = np.linalg.inv(Sigma) N = np.sqrt((2*np.pi)**n * Sigma_det) fac = np.einsum('...k,kl,...l->...', pos-mu, Sigma_inv, pos-mu) return np.exp(-fac / 2) / N Z = multivariate_gaussian(pos, mu, cov) return X,Y,Z
0f41df799989322b73f8aad2a7d00cac3ecdd7e7
nadyndyaa/BASIC_PYTHON5-C
/day3.py
1,858
4.0625
4
#For Loop = mengulang suatu program sebanyak yg kita inginkan # fruits = ["apple","banana","cherry","manggis","buah naga"] #print(fruits[0]) #print(fruits[1]) #print(fruits[2]) #print(fruits[3]) #fruits = ["apple","banana","cherry"] #for x in fruits: #print(x) #range #menggunakan batasan stop saja #for i in range(6): #print("i") #menggunakan batasan start dan stop #for x in range(3,6): #print(x) #menggunakan batasan start, stop dan step(kelipatan) #for m in range(0,20,2): #print(m) #for loop(inisialisasi ; kondisi;increment) #for i in range(0,6,2): # 0,1,2,3,4,5, #print(i) #print("======") #while loop (inisialisasi ; kondisi;increment) #i = 0 #inisialisasi #while i < 6: #print(i) #i += 2 #increment i = i +1 #CONTINUE = untuk melompati suatu kondisi #for i in range (5): #if i == 3: #continue #program tidak akan dicetak # print(i) #for i in range (5): #q = input("Masukkan kode : ") # if q == 'm': # print("angka diskip") # continue #program dibawah ini tidak akan akan dieksekusi #ketika continue aktif # print(i) #BREAK #for i in range(5): # if i == 3: # break #print(i) #for i in range(10): # q = input("Apakah anda yakin keluar ? :") # if q == 'y' : ## print("anda keluar") # break #INFINTITE LOOP #for i in range(2): #print("i = {}".format(i)) #print("Perulangan I ") #for j in range(3): # print("j ={}".format(j)) # print("perulangan j") # print() #satu_d = [1,2,3,4,5,6,] #dua_d =[ [1,2,3] , [4,6,6] ] #tiga_d = [ [ [1,2],[3,4] ] , [ [5,6],[7,8] ] ] #PKE NESTED LOOP #for i in tiga_d: # for j in i: # for k in j: # print(k) # coba = [ [ "nadya","nami","key"] , [20,2,3] ] # for i in coba: # print() # for j in range(5):
a7da7e51ab20d1a4122af8458847451696bf500e
nadyndyaa/BASIC_PYTHON5-C
/func_example.py
323
3.65625
4
def luas_lingkaran(r): return 3.14 * (r*r) r = input('Masukan jari lingkaran :') luas = luas_lingkaran(int(r)) print('Luasnya: {}'.format(luas)) def keliling_lingkaran(R): return 2 * 3.14 *(R) R = input( "masukkan keliling :") keliling = keliling_lingkaran(int(R)) print('Kelilingnya :{}'.format(keliling))
582d85050e08a6b8982aae505cdc0acc273aec74
Kyle-Koivukangas/Python-Design-Patterns
/A.Creational Patterns/4.Prototype.py
1,661
4.1875
4
# A prototype pattern is meant to specify the kinds of objects to use a prototypical instance, # and create new objects by copying this prototype. # A prototype pattern is useful when the creation of an object is costly # EG: when it requires data or processes that is from a network and you don't want to # pay the cost of the setup each time, especially when you know the data won't change. from copy import deepcopy class Car: def __init__(self): self.__wheels = [] self.__engine = None self.__body = None def setBody(self, body): self.___body = body def attachWheel(self, wheel): self.__wheels.append(wheel) def setEngine(self, engine): self.__engine = engine def specification(self): print(f"body: {self.__body.shape}") print(f"engine horsepower: {self.__engine.horsepower}") print(f"tire size: {self.__wheels[0].size}") #it's pretty similar to the builder pattern, except you have a method that will easily allow you to copy the instance # this stops you from having to def clone(self): return deepcopy(self) # Here is another separate example class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): print(f"({self.x}, {self.y})") def move(self, x, y): self.x += x self.y += y def clone(self, move_x, move_y): """ This clone method allows you to clone the object but it also allows you to clone it at a different point on the plane """ obj = deepcopy(self) obj.move(move_x, move_y) return obj
1d55b37fbef0c7975527cd50a4b65f2839fd873a
Kyle-Koivukangas/Python-Design-Patterns
/A.Creational Patterns/2.Abstract_Factory.py
1,420
4.375
4
# An abstract factory provides an interface for creating families of related objects without specifying their concrete classes. # it's basically just another level of abstraction on top of a normal factory # === abstract shape classes === class Shape2DInterface: def draw(self): pass class Shape3DInterface: def build(self): pass # === concrete shape classes === class Circle(Shape2DInterface): def draw(self): print("Circle.draw") class Square(Shape2DInterface): def draw(self): print("Square.draw") class Sphere(Shape3DInterface): def draw(self): print("Sphere.build") class Cube(Shape3DInterface): def draw(self): print("Cube.build") # === Abstract shape factory === class ShapeFactoryInterface: def getShape(self, sides): pass # === Concrete shape factories === class Shape2DFactory(Shape2DInterface): @staticmethod def getShape(sides): if sides == 1: return Circle() if sides == 4: return Square() assert 0, f"Bad 2D shape creation: shape not defined for {sides} sides" class Shape3DFactory(Shape3DInterface): @staticmethod def getShape(sides): """technically, sides refers to faces""" if sides == 1: return Sphere() if sides == 6: return Cube() assert 0, f"Bad 3D shape creation: shape not defined for {sides} sides"
4eb05cf9d3d3b4dba91e659cc75882b5d35f9955
FunkMarvel/CompPhys-Project-1
/project.py
3,546
3.734375
4
# Project 1 FYS3150, Anders P. Åsbø # general tridiagonal matrix. from numba import jit import os import timeit as time import matplotlib.pyplot as plt import numpy as np import data_generator as gen def main(): """Program solves matrix equation Au=f, using decomposition, forward substitution and backward substitution, for a tridiagonal, NxN matrix A.""" init_data() # initialising data # performing decomp. and forward and backward sub.: decomp_and_forward_and_backward_sub() save_sol() # saving numerical solution in "data_files" directory. plot_solutions() # plotting numerical solution vs analytical solution. plt.show() # displaying plot. def init_data(): """Initialising data for program as global variables.""" global dir, N, name, x, h, anal_sol, u, d, d_prime, a, b, g, g_prime dir = os.path.dirname(os.path.realpath(__file__)) # current directory. # defining number of rows and columns in matrix: N = int(eval(input("Specify number of data points N: "))) # defining common label for data files: name = input("Label of data-sets without file extension: ") x = np.linspace(0, 1, N) # array of normalized positions. h = (x[0] - x[-1]) / N # defining step-siz. gen.generate_data(x, name) # generating dataanal_name set. anal_sol = np.loadtxt("%s/data_files/anal_solution_for_%s.dat" % (dir, name)) u = np.empty(N) # array for unkown values. d = np.full(N, 2) # array for diagonal elements. d_prime = np.empty(N) # array for diagonal after decom. and sub. a = np.full(N - 1, -1) # array for upper, off-center diagonal. b = np.full(N - 1, -1) # array for lower, off-center diagonal. # array for g in matrix eq. Au=g. f = np.loadtxt("%s/data_files/%s.dat" % (dir, name)) g = f * h ** 2 g_prime = np.empty(N) # array for g after decomp. and sub. def decomp_and_forward_and_backward_sub(): """Function that performs the matrix decomposition and forward and backward substitution.""" # setting boundary conditions: u[0], u[-1] = 0, 0 d_prime[0] = d[0] g_prime[0] = g[0] start = time.default_timer() # times algorithm for i in range(1, len(u)): # performing decomp. and forward sub. decomp_factor = b[i - 1] / d_prime[i - 1] d_prime[i] = d[i] - a[i - 1] * decomp_factor g_prime[i] = g[i] - g_prime[i - 1] * decomp_factor for i in reversed(range(1, len(u) - 1)): # performing backward sub. u[i] = (g_prime[i] - a[i] * u[i + 1]) / d_prime[i] end = time.default_timer() print("Time spent on loop %e" % (end - start)) def save_sol(): """Function for saving numerical solution in data_files directory with prefix "solution".""" path = "%s/data_files/solution_%s.dat" % (dir, name) np.savetxt(path, u, fmt="%g") def plot_solutions(): """Function for plotting numerical vs analytical solutions.""" x_prime = np.linspace(x[0], x[-1], len(anal_sol)) plt.figure() plt.plot(x, u, label="Numerical solve") plt.plot(x_prime, anal_sol, label="Analytical solve") plt.title("Integrating with a %iX%i tridiagonal matrix" % (N, N)) plt.xlabel(r"$x \in [0,1]$") plt.ylabel(r"$u(x)$") plt.legend() plt.grid() if __name__ == '__main__': main() # example run: """ $ python3 project.py Specify number of data points N: 1000 Label of data-sets without file extension: num1000x1000 """ # a plot is displayed, and the data is saved to the data_files directory.
ae0cc41da83e3c9babb8b2363ddab700cb375179
drewthayer/intro-to-ds-sept9
/week2/day05-strings_tuples/strings_tuples_lecture.py
5,481
4.65625
5
# create, analyze and modify strings # strings are like immutable lists # def iterate_through_str(some_str): # for i, char in enumerate(some_str): # print(i, char) # # some_str_lst = list(some_str) # # for char in some_str_lst: # # print(char) test_str = 'We need to pass something in this function' # test_str[0] = 'w' # iterate_through_str(test_str) # commonly declare strings using the syntax string = 'some text here # utilize the three types of string bounding characters # 'some text' : most widely used # some_string = 'with "single" \'quotes\'' # print(some_string) # some_string = "with 'double' \"quotes\"" # print(some_string) # some_string = '''with single quotes # some more text # ''' # print(some_string) # some_string = """with single quotes""" # "more text" : also used, less often # ''' multi-line strings''' : used when \n is to be implicitly stated, through # a simple carriage return # used in function Docstrings def count_unique_chars_in_str(some_string): '''takes a string and returns a count of that string's unique characters, not including empty spaces Parameters ---------- some_str: (str) we count the characters of this string Returns ------- count: (int) number of characters in the string ''' output = [] for char in some_string: if char != ' ' and char not in output: output.append(char) return len(output) # print(count_unique_chars_in_str(test_str)) # in operator # print('a' in 'plant') # print(4 in [1,4,7,8,2,4,6,4]) def find_anagrams(list_of_words): output = [] for word1 in list_of_words: for word2 in list_of_words: print(sorted(word1), sorted(word2)) if word1 != word2: if sorted(word1) == sorted(word2): if word1 not in output: output.append(word1) return output word_list = ['levis', 'elvis', 'bat', 'tab', 'tab', 'car', 'ark', 'tabb'] # print(find_anagrams(word_list)) # can be used for multi-line comments # can also be """ like this """ # operating on strings with + # 'str' + 'ing' def concatenate_strings(str1, str2): return str1 + ' ' + str2 str1 = 'black' str2 = 'cat' # print(concatenate_strings(str1, str2)) # casting data to a string with str() # print(type(str(type(str(43.7))))) # print(type(concatenate_strings)) # str(['hey', 'you', 'guys']) : might not do what you expect it do do # print(str(['hey', 'you', 'guys'])) # if you want to combine characters in a string, use def create_sentence_from_list(some_list): some_list[0] = some_list[0][0].upper() + some_list[0][1:] return ' '.join(some_list) + '.' # 'this'[0] #-> 't' test_list = ['this', 'will', 'combine', 'words'] # print(create_sentence_from_list(test_list)) # str slicing print('not all cats hate water'[8:]) #-> 'cats hate water' print('not all cats hate water'[0:7]) #-> 'not all' # using for loops to iterate through strings: # for char in 'some_string': print(char) # str indexing # 'some_str'[0] #--> 's' # 'some string'[0] = 'f' will throw an error # Write a function that returns 2 parallel lists, based on counts of letters in an input string: # letters : list of letters in the input string # counts : parallel list with the counts of each letter def get_letter_counts(some_str): letters = [] for char in some_str: if char not in letters and char != ' ': letters.append(char.lower()) some_str_ = some_str.lower() counts = [0] * len(letters) for i, char in enumerate(letters): counts[i] = some_str_.count(char) return (letters, counts) # tuples some_str = 'I am a happy string' results = get_letter_counts(some_str) letters = results[0] counts = results[1] # print(results) animal_tup = ('dog', 'cat', 'badger') animal_tup = ('plover', animal_tup[1], animal_tup[2]) # hashable # only immutable types can be used as keys in a dict def get_three_note_perms(): notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G','G#', 'A', 'A#', 'B'] chords = [] for note1 in notes: for note2 in notes: if note1 == note2: continue for note3 in notes: if note1 != note2 and note1 != note3 and note2 != note3: chords.append(tuple(sorted([note1, note2, note3]))) return sorted(chords) print(len(get_three_note_perms())) # Membership in strings # similar to lists # 'club' in 'very important club' #-> True # Important string functions and methods # len('some string') # list('splits characters') # 'split separates on a character'.split(' ') # 'SoMe StRiNg'.lower() # 'SoMe StRiNg'.upper() # 'time tome'.replace('t', 'l') # String interpolation with format() and fstrings # '{}x{}x{}'.format(length, width, height) # f'{length}x{width}x{height}' # more on formatting for rounding and justification # Write the is_palindrome() function # Write the is_anagram() function # Create and use tuples # tuples are like immutable lists # access elements in the tuple using our common indexing approach # tuple values cannot be changed! # some_tuple = ('item1', 'item2', 'item3') # tuple_from_list = tuple([3,4,5]) # functions that return multiple values return tuples!! # def generic_func(): return 25, 17 # type(generic_func()) #--> tuple # unpack tuples: # var1, var2, var3 = (1, 2, 3) # why tuples?
54b83e0a80cb5ddf23722b4170d671e6974686c8
shahZ51/python-challenge
/PyPoll/main.py
1,345
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[13]: import os import csv import pandas as pd # In[14]: csvpath = ("Resources/election_data.csv") df = pd.read_csv(csvpath) df.head() # In[15]: total_votes = df['Voter ID'].count() total_votes # df.groupby('Candidate').sum() # In[16]: candidate_vote =df.groupby('Candidate').count() candidate_vote = candidate_vote.reset_index(drop = False) candidate_vote = candidate_vote.rename(columns={"Voter ID": "Number of Votes"}) candidate_vote = candidate_vote.drop(columns =['County']) candidate_vote # In[17]: max_vote = candidate_vote['Number of Votes'].max() max_vote # In[18]: unique_candidate =df.Candidate.unique() unique_candidate # In[19]: df.head() # In[20]: vote_received = df.Candidate.value_counts() vote_received # In[21]: percent_count = (vote_received / total_votes)*100 percent_count # In[22]: winner = candidate_vote.loc[candidate_vote['Number of Votes' ] == max_vote ] ['Candidate'].iloc[0] winner # In[25]: # Printing terminal output = ( f"Election Results\n" f"---------------------------------\n" f"Total Votes: {total_votes}\n" f"---------------------------------\n" f"{percent_count}% {vote_received} \n" f"---------------------------------\n" f" Winner: {winner}\n" f"---------------------------------\n" f"```\n" ) print(output)
e24fe24b95d36d74782e57d0754e6fac56007425
tofuu/CSE-Novello-Final
/__main__.py
676
3.84375
4
# -*- coding: utf-8 -*- #Before you push your additions to the code, make sure they exactly fit the parameters described in the project! #Let's write delicious code. がんばってくらさい! # Abirami import math def list_prime_factors(num): n = int(num) prime = [] k=1 if n%2==0: prime.append(2) flag = 0 while (2*k+2)**2 < n: if n%(2*k+1)==0: for p in prime: if (2*k+1)%p ==0: flag = 1 if flag ==+ 0: prime.append(2*k+1) flag = 0 k=k+1 if len(prime)== 0: prime.append(n) print prime return prime
d40f8d250528001d359c09eecf6505e970cb426e
vbodell/ii1304-modellering
/simulation.py
2,885
3.625
4
from population import Population class Simulation: def __init__(self, N, probInfect, minDaysSick, maxDaysSick, probDeath, initialSick, VERBOSE, SEED): self.N = N self.probInfect = probInfect self.totalSickCount = len(initialSick) self.totalDeathCount = 0 self.printInitString(VERBOSE, SEED, N, probInfect, minDaysSick, maxDaysSick, probDeath, initialSick) self.currentSimulationDay = 0 self._population = Population(N, probInfect, minDaysSick, maxDaysSick, probDeath, initialSick, VERBOSE, SEED) print(self._population) def start(self): while not self.simulationFinished(): self.currentSimulationDay += 1 values = self._population.simulateDay(self.currentSimulationDay) self.printDailyReport(values) self.totalSickCount += values['gotInfected'] self.totalDeathCount += values['died'] self.printCumulativeReport() def simulationFinished(self): return self._population.allDead or self._population.allLivingHealthy def printDailyReport(self, values): print("Day %d:" % self.currentSimulationDay) print(" # got infected: %d" % values['gotInfected']) print(" # deaths: %d" % values['died']) print(" # got healthy: %d" % values['gotHealthy']) print(" # infected: %d" % values['infected']) print(self._population) def printCumulativeReport(self): if not self.simulationFinished(): print("Simulation hasn't terminated yet!") return print("===Simulation ran a total of %d days===" % self.currentSimulationDay) print(" Total # of infected: %d" % self.totalSickCount) print(" Total # of deaths: %d" % self.totalDeathCount) print(" Proportion infected: %.3f" % (self.totalSickCount/(self.N*self.N))) print("CSV:%.3f,%.3f" % (self.probInfect, self.totalSickCount/(self.N*self.N))) def printInitString(self, VERBOSE, SEED, N, probInfect, minDaysSick, maxDaysSick, probDeath, initialSick): initSimString = "\n### Initializing simulation with the" +\ " following parameters ###\n" initSimString += " Verbose=%s\n" % VERBOSE initSimString += " SEED=%s\n" % SEED initSimString += " N=%d\n" % N initSimString += " probInfect=%.2f\n" % probInfect initSimString += " minDaysSick=%d\n" % minDaysSick initSimString += " maxDaysSick=%d\n" % maxDaysSick initSimString += " probDeath=%.2f\n" % probDeath initSimString += " initialSick=%d\n" % len(initialSick) for ndx in range(len(initialSick)): initSimString += " Sick position #%d: [%d,%d]\n" % (ndx+1, initialSick[ndx][0], initialSick[ndx][1]) print(initSimString)
7b8625d7a26569c437a7ea560b2c56596db48fb1
atomsk752/study
/180806_oop/dragon_game_item.py
4,697
3.703125
4
import random class Dragon: def __init__(self, lev, name): self.lev = lev self.hp = lev * 10 self.jewel = lev % 3 self.name = name self.attack = self.lev * 10 def giveJewel(self): return self.jewel def attackHero(self): print(self.name + ": 캬오~~~~~~~`ㅇ'") return random.randint(1, self.attack) def damage(self, amount): print(self.name + ": 꾸엑....................ㅠ_ㅠ") self.hp -= amount if self.hp > 0: print("[드래곤의 체력이", self.hp, "로 줄었다]") else: print(self.name + ": 크으으... 인간따위에게......") return self.hp def __str__(self): return self.name + " 레벨: " + str(self.lev)+ " HP:" + str(self.hp) class Hero: def __init__(self, name, hp): self.name = name self.hp = hp self.mp = 100 - hp self.min_mp = 1 def attackDragon(self): return random.randint(self.min_mp, self.mp) def damage(self, amount): print(self.name+": 윽....................ㅠ_ㅠ") self.hp -= amount if self.hp > 0: print("[플레이어의 체력이", self.hp, "로 줄었다]") return self.hp def __str__(self): return self.name class DragonContainer: def __init__(self, name_list): self.dragons = [Dragon(idx + 1, x) for idx, x in enumerate(name_list)] def getNext(self): if len(self.dragons) == 0: return None return self.dragons.pop(0) class Colosseum: def __init__(self,container): self.container = container self.player = None def makePlayer(self): name = input("플레이어의 이름을 입력하시오: ") hp = int(input("HP는 얼마나 하겠습니까? (최대 100) ")) self.player = Hero(name,hp) print("[캐릭터 "+ self.player.name,"이/가 만들어 졌습니다]") print("[게임을 시작합니다]") print("[BGM.... Start.............]") def fight(self): dragon = self.container.getNext() if dragon == None: print("[용사는 전설이 되었다]") return print("") print("====================================") print("["+dragon.name+"]"," [레벨:", str(dragon.lev)+"]","[데미지: 1 ~ "+str(dragon.attack)+"]") print("["+self.player.name+"]"," [HP:", str(self.player.hp)+"]", "[데미지: "+str(self.player.min_mp)+" ~ "+str(self.player.mp)+"]") print("====================================") while True: power = self.player.attackDragon() input("") print("[용사가 공격했다", "데미지:", power,"]") dragonhp = dragon.damage(power) if dragonhp <= 0: print("[현재 플레이어 HP: ", self.player.hp,"]") print("[Next Stage~]") jewel = dragon.giveJewel() if jewel == 0: self.player.hp += 30 print("[보너스 체력이 30이 추가되었습니다]") random_box=random.randint(0,3) if random_box == 1: print("[롱소드를 얻으셨습니다. 최소 공격력 증가(+10)]") self.player.min_mp += 10 elif random_box == 2: print("[물약을 얻으셨습니다. HP 증가(+20)]") self.player.hp += 20 elif random_box == 3: print("[갑옷을 얻으셨습니다. 드래곤 최대 데미지 감소(-10)]") for x in self.container.dragons: x.attack -= 10 else: print("[드래곤 사체에서 아무것도 나오지 않았습니다]") print("[Mission Complete]") break dragonattack=dragon.attackHero() print("[드래곤이",dragonattack,"만큼 데미지를 주었다]") herohp = self.player.damage(dragonattack) if herohp <= 0: print("["+self.player.name + "은/는 " + dragon.name +"에게 죽었습니다]") print(" [Game Over]") return self.fight() name_list=["해츨링","그린드래곤","블랙드래곤","화이트드래곤","블루드래곤","실버드래곤", "레드드래곤","골드드래곤","레인보우드래곤","G-dragon"] container = DragonContainer(name_list) ground = Colosseum(container) ground.makePlayer() ground.fight()
66484192d25bf31838df22abe82623a8e11567b9
atomsk752/study
/180806_oop/lucky_box.py
461
3.515625
4
import random class Item: def __init__(self, str): self.str = str def __str__(self): return "VALUE: " + self.str class Box: def __init__(self, items): self.items = items random.shuffle(self.items) def selectOne(self): return self.items.pop() item_list = [Item('O') ] * 5 item_list.append(Item('X')) box = Box(item_list) for x in range(6): print(box.selectOne())
2350246ad0d7208ad8a2136740f6fb83f1b662bb
kenjirotorii/burger_war_kit
/autotest/draw_point_history.py
781
3.5625
4
#!/usr/bin/env python import pandas as pd import matplotlib.pyplot as plt import sys def draw_graph(csv_file, png_file): df = pd.read_csv(csv_file, encoding="UTF8", names=('sec', 'you', 'enemy', 'act_mode', 'event', 'index', 'point', 'before', 'after'), usecols=['sec', 'you', 'enemy'], index_col='sec') df.plot(color=['r','b'], drawstyle='steps-post', fontsize=15) plt.title("Point history") plt.xlabel("timestamp [sec]") plt.ylabel("point") plt.savefig(png_file) if __name__ == "__main__": if (len(sys.argv) != 3): print("[usage]" + sys.argv[0] + " CSV_FILE PNG_FILE") exit(1) draw_graph(sys.argv[1], sys.argv[2])
7d5e1744f843893d418819a14cfc6c7f200de686
yunakim2/Algorithm_Python
/프로그래머스/level2/짝지어 제거하기.py
326
3.78125
4
def solution(s): stack = [] for char in s: if not stack: stack.append(char) elif stack[-1] == char: stack.pop() else: stack.append(char) return 1 if not stack else 0 if __name__ == "__main__": print(solution("baabaa")) print(solution("cdcd"))
fb317af1c41098a48c682ba0ec9337d69b165fda
yunakim2/Algorithm_Python
/백준/재귀/baekjoon10872.py
141
3.625
4
num = int(input()) def fac (i) : if(i == 1 ) : return 1 if(i ==0) : return 1 else : return i*fac(i-1) print(fac(num))
f422a1ef411b40fb0553d8e34ca2c780980dd223
yunakim2/Algorithm_Python
/프로그래머스/level2/가장 큰 수.py
457
3.5625
4
def solution(numbers): combi_number = [] bigger_number = '' for number in numbers: tmp_number = (str(number)*4)[:4] combi_number.append([''.join(tmp_number), number]) combi_number.sort(reverse=True) for _, item in combi_number: bigger_number += str(item) return str(int(bigger_number)) if __name__ == '__main__': print(solution([0,0,0,1000])) print(solution([6,10,2])) print(solution([0,0,0,0]))
b0eb26a51875aaa4516f1e8db4c2d9a23ec444a0
yunakim2/Algorithm_Python
/백준/실습 1/baekjoon10996.py
105
3.953125
4
a = int(input()) even = a//2 odd = a- a//2 for i in range(a) : print("* "*odd) print(" *"*even)
93337a29ae77fba36b750bcbf5aeaa16e6e996ee
yunakim2/Algorithm_Python
/알고리즘특강/그리디_숫자카드게임.py
292
3.515625
4
data = """3 3 3 1 2 4 1 4 2 2 2""" data = data.split("\n") n, m = map(int, data[0].split()) arr = [] small= [] arr.append(map(int,data[1].split())) arr.append(map(int,data[2].split())) arr.append(map(int,data[3].split())) for i in range(n): small.append(min(arr[i])) print(max(small))
eb309a4c1f80124cfba320759ad9e35c5840c7d5
yunakim2/Algorithm_Python
/코테/1.py
1,044
3.578125
4
''' 정렬 은 우선 빈도, 같으면 크기 순 ''' from collections import defaultdict from collections import deque def sorting(arr): tmp_arr = [] for i in range(len(arr)): size = arr[i][1] for j in range(i+1,len(arr)): if size != arr[j][1]: break else: else: for i in range(len(arr)): for j in range(i, len(arr)): if arr[i] > arr[j]: arr[i], arr[j] = arr[j], arr[i] return arr def coutingSort(arr): count_arr = defaultdict() for item in arr: if item not in count_arr.keys(): count_arr[item] = 1 else: count_arr[item] += 1 count_arr = sorting(count_arr) # count_arr = list(sorted(count_arr.items(), key=lambda x : -x[1])) res = [] for idx in count_arr: for _ in range(int(idx[1])): res.append(idx[0]) return res if __name__ == '__main__': arr = [1,3,3,5,5,6,7,8] print(coutingSort(arr))
e98f224870424065636d98b986db536bb8fe0296
yunakim2/Algorithm_Python
/프로그래머스/level1/세 소수의 합.py
866
3.796875
4
def solution(n): def sieve(n): is_prime = [True] * (n + 1) is_prime[0] = False is_prime[1] = False for candidate in range(2, n + 1): if not is_prime[candidate]: continue for multiple in range(candidate * candidate, n + 1, candidate): is_prime[multiple] = False return [idx for idx, value in enumerate(is_prime) if value] def dfs(cur_idx, count, total): if count == 3: if total == n: return 1 else: return 0 if cur_idx >= len(prime_num): return 0 return dfs(cur_idx + 1, count, total) + dfs(cur_idx + 1, count + 1, total + prime_num[cur_idx]) prime_num = sieve(n) return dfs(0, 0, 0) if __name__ == "__main__": print(solution(33)) print(solution(9))
5f30daf7d6e6fca7a3d058e9834ce3d2faf63234
yunakim2/Algorithm_Python
/프로그래머스/level4/버스 여행 - DFS.py
725
3.796875
4
def solution(n,signs): def dfs(source, signs, visited_stations): if len(visited_stations) == len(signs): return for destination in range(len(signs)): if signs[source][destination] == 1 and destination not in visited_stations: visited_stations.add(destination) dfs(destination, signs, visited_stations) for source in range(n): visited_stations = set() dfs(source, signs, visited_stations) for destination in visited_stations: signs[source][destination] = 1 return signs if __name__ == "__main__": print(solution(3, [[0, 1, 0], [0, 0, 1], [1, 0, 0]])) print(solution(3,[[0,0,1],[0,0,1],[0,1,0]]))
424206f92ae36b0920b12bd37b657e4a432ef419
yunakim2/Algorithm_Python
/프로그래머스/level2/전화번호 목록.py
634
3.796875
4
def solution(phone_book): phone_book.sort() phone_book = dict([(index, list(phone)) for index, phone in enumerate(phone_book)]) for i in range(len(phone_book)): size = len(phone_book[i]) for j in range(i+1, len(phone_book)): if len(phone_book[j]) >= size: if phone_book[j][0:size] == phone_book[i]: return False else: return True if __name__ == "__main__": print(solution(["0", "97674223", "1195524421"])) print(solution(["123","456","789"])) print(solution(["123", "456", "4567", "999"])) print(solution(["113","44","4544"]))
6d2877bb66b8da148e0e06c272588b4e5bc2dfdf
yunakim2/Algorithm_Python
/카카오/2021 카카오 공채/6.py
631
3.546875
4
from collections import deque def solution(board, skill): for types, r1, c1, r2, c2, degree in skill: for r in range(r1, r2+1): for c in range(c1, c2+1): if types == 1: board[r][c] -= degree else: board[r][c] += degree answer = [b for board_list in board for b in board_list if b > 0] return len(answer) if __name__ == "__main__": print(solution([[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5]], [[1, 0, 0, 3, 4, 4], [1, 2, 0, 2, 3, 2], [2, 1, 0, 3, 1, 2], [1, 0, 1, 3, 3, 1]]))
adfa7b36c3cfef17161452849821e96b7a887607
yunakim2/Algorithm_Python
/백준/실습 1/baekjoon10039.py
109
3.6875
4
sum = 0 for i in range(0,5) : a = int(input()) if a<40 : sum+=40 else : sum += a print(sum//5)
89197c0273cfaf25f86785d59634cc8470f27713
yunakim2/Algorithm_Python
/백준/1차원 배열/baekjoon4344.py
270
3.578125
4
num = int(input()) for i in range(num) : data = list(map(int, input().split(' '))) cnt = data[0] del data[0] avg = sum(data) / cnt k = 0 for j in range(cnt) : if(data[j]>avg) : k+=1 print("%.3f"%round((k/cnt*100),3)+"%")
4d4626a0cdfaf504bc794b78b806e2ac10cd1ee6
yunakim2/Algorithm_Python
/프로그래머스/level1/짝수와 홀수.py
96
3.671875
4
def solution(num): if num%2 !=0 : answer ="Odd" else : answer = "Even" return answer
c264959d445653be32a98b1838bd10132ceaa205
JinhanM/leetcode-playground
/19. 删除链表的倒数第 N 个结点.py
607
3.734375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = ListNode(0, head) front, back = dummy, head for _ in range(n): back = back.next while back: back = back.next front = front.next front.next = front.next.next return dummy.next
1994561a1499d77769350b55a6f32cdd111f31fa
Ajat98/LC-2021
/easy/buy_and_sell_stock.py
1,330
4.21875
4
""" You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. """ class Solution: def maxProfit(self, prices: List[int]) -> int: maxProfit = 0 minProfit = float('inf') #to represent largest possible val #TOO SLOW on large arrays # for i in range(len(prices)): # for x in range(i, len(prices)): # profit = prices[x] - prices[i] # if profit > maxProfit: # maxProfit = profit #compare min buy price difference to max sell price at every step, keep tracking as you go. for i in prices: minProfit = min(i, minProfit) profit = i - minProfit maxProfit = max(profit, maxProfit) return maxProfit
0b19bc5f6af31fb9ef1e9b217e0f99405b139986
mchristofersen/tournament-project
/vagrant/tournament/tournament.py
9,965
3.578125
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # # This file can be used to track the results of a Swiss-draw style tournament # First use set_tournament_id() to generate a new tournament # Register new players with register_player() # Once all players are registered, assign pairings with swiss_pairings() # As matches are finished, report the winner with report_match() # For a simple match with a clear winner: # use report_match(winner, loser) where winner and loser are player_ids # For a match that resulted in a draw: # use report_match(player1_id, player2_id, True) # Use swiss_pairings() again once the round is finished. # Once the tournament is over, run finalRankings() to print the final results. import psycopg2 import random import re tournament_id = None def set_tournament_id(t_id=0): """ Sets a global tournament_id to keep track of the current tournament. Takes an optional argument to assign a tournament other than the first. """ new_tournament(t_id) global tournament_id tournament_id = t_id return t_id def new_tournament(t_id): pg, c = connect() try: c.execute("INSERT INTO tournaments \ VALUES ('GENERATED_TOURNAMENT', %s)", (t_id,)) pg.commit() except psycopg2.IntegrityError: pg.rollback() finally: pg.close() def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" pg = psycopg2.connect("dbname = tournament") c = pg.cursor() return pg, c def execute_query(query, variables=()): pg, c = connect() c.execute(query, variables) if re.match("(^INSERT|^UPDATE|^DELETE)", query, re.I) is not None: pg.commit() pg.close() else: fetch = c.fetchall() pg.close() return fetch def delete_matches(): """Remove all the match records from the database.""" execute_query("DELETE FROM matches WHERE tournament_id = %s", (tournament_id,)) def delete_players(): """Remove all the player records from the database.""" execute_query("DELETE FROM players WHERE tournament_id = %s", (tournament_id,)) def count_players(): """Returns the number of players currently registered.""" return_value = execute_query("SELECT COUNT(*) FROM players\ WHERE tournament_id = %s", (tournament_id,)) return return_value[0][0] def register_player(name): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ execute_query("INSERT INTO players (name, tournament_id, prev_opponents)\ VALUES (%s, %s, %s)", (name, tournament_id, [],)) def player_standings(): """Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by the database) name: the player's full name (as registered) wins: the number of matches the player has won matches: the number of matches the player has played """ r_value = execute_query("SELECT * FROM tournament_filter(%s)", (tournament_id,)) return r_value def report_match(winner, loser, draw=False): """Records the outcome of a single match between two players. For a simple match with a clear winner: use report_match(winner, loser) where winner and loser are player_ids For a match that resulted in a draw: use report_match(player1_id, player2_id, True) Args: winner: the player_id of the player who won loser: the player_id of the player who lost draw: boolean on whether the match was a draw or split. Defaults to False """ if not draw: execute_query("""UPDATE players SET matches_played = matches_played +1, prev_opponents = prev_opponents || %s WHERE player_id = %s and tournament_id = %s""", (winner, loser, tournament_id)) execute_query("UPDATE players SET points = points + 1.0,\ matches_played = matches_played +1,\ prev_opponents = prev_opponents || %s\ WHERE player_id = %s and tournament_id = %s", (loser, winner, tournament_id)) else: for player in range(0, 1): execute_query("""UPDATE players SET points = (points + 0.5) WHERE (player_id = %s or player_id = %s) and tournament_id = %s""", (winner, loser, tournament_id)) execute_query("INSERT INTO matches VALUES (%s, %s, %s, %s)", (winner, loser, tournament_id, draw)) def pick_random_player(players): """ Picks a player at random from the standings, checks that they haven't already received a bye, and if not, assigns them a bye. Returns an even list of players to be assigned pairings. """ global bye_player prev_bye = True while prev_bye: random.shuffle(players) bye_player = players[0] prev_bye = execute_query("Select bye from players\ WHERE player_id = %s", (bye_player[0],))[0][0] standings = player_standings() standings.remove(bye_player) assign_bye(bye_player[0]) return standings def swiss_pairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standings. Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first player's name id2: the second player's unique id name2: the second player's name """ standings = player_standings() pairings = [] if len(standings) % 2 != 0: pick_random_player(standings) while len(standings) > 1: idx = 1 prev_opponents = execute_query("""SELECT prev_opponents from players WHERE player_id = %s""", (standings[0][0],)) while True: if standings[idx][0] in prev_opponents and\ idx != len(standings)-1: idx += 1 else: pairings.append(sum([list(standings[0][0:2]), list(standings[idx][0:2])], [])) standings.pop(idx) standings.pop(0) break return pairings def final_rankings(): """ Calculates any tie-breakers and prints the rankings in table form. Can be used on any round. """ ties = 1 # used to keep track of how many players tied at a certain rank last_record = [0, 0] # used to track the previous players record rank = 0 # keeps track of the current rank during iteration players = execute_query("""SELECT player_id, prev_opponents FROM players WHERE tournament_id = %s ORDER BY points DESC, name""", (tournament_id,)) for (player, opponents) in players: player_sum = 0 # tracks a certain player's opponent points for opponent in opponents: player_sum += execute_query("""SELECT points FROM players WHERE player_id = %s""", (opponent,))[0][0] execute_query("""UPDATE players SET opp_win = %s WHERE player_id = %s""", (float(player_sum)/len(opponents), player,)) standings = execute_query("""SELECT name, points, opp_win FROM players ORDER BY points DESC, opp_win DESC, name""") print "\nCurrent Rankings:" for player in standings: if [player[1], player[2]] != last_record: rank += 1 * ties ties = 1 else: # Must be a tie, increment ties multiplier ties += 1 last_record = [player[1], player[2]] print("%d.: %s" % (rank, player)) def assign_bye(player): """ Assigns a bye to a player and updates their points. Should be called automatically when necessary. :param player: The player's id. """ execute_query("""UPDATE players SET bye = TRUE, points = points + 1 WHERE player_id = %s and tournament_id = %s """, (player, tournament_id,)) def main(): """ Sets the tournament_id if it is not already. Runs on initialization. """ if tournament_id is None: print("""Tournament id not found...\ \nChecking for existing tournaments...""") t_id = set_tournament_id() t_name = execute_query(""" Select tournament_name from tournaments WHERE tournament_id = %s """, (t_id,))[0][0] print("""Using tournament: %s\ \nTo change this, use setTournament(t_id)""" % t_name) if __name__ == '__main__': main()
3b76875ec54479b956a45331c3863f956a61df9a
mounui/python
/examples/use_super.py
643
4.125
4
# -*- coding: utf-8 -*- # super使用 避免基类多次调用 class Base(object): def __init__(self): print("enter Base") print("leave Base") class A(Base): def __init__(self): print("enter A") super(A, self).__init__() print("leave A") class B(Base): def __init__(self): print("enter B") super(B, self).__init__() print("leave B") class C(A, B): def __init__(self): print("enter C") super(C, self).__init__() print("leave C") C() # 测试结果 # enter C # enter A # enter B # enter Base # leave Base # leave B # leave A # leave C
7290d9abe62da81613c2bc7a12b0aead3b5e8ae4
mounui/python
/examples/demo1.py
387
4
4
print('hello world!') name = input('please enter your name:') print('hello,',name) print(1024 * 768) print(5^2) print('haha') bmi = 80.5 / (1.75 ** 2) if bmi >= 32: print('严重肥胖') elif bmi >= 28: print('肥胖') elif bmi >= 25: print('过重') elif bmi >= 18.5: print('正常') else: print('过轻') sum = 0 for x in range(101): sum += x print(sum)
0b495e493aaf605222998fee8c76b4d02062a94a
RomanKlimov/PythonCourse
/HomeW_13.09.17/MultiTable.py
136
3.609375
4
def mt(number): for i in range(1, 10): print(str(number) + " x " + str(i) + " = " + str(number * i)) i += 1 mt(5)
ce6e1845c663b30f80d21a5481249fdf685cfef8
ML-Baidu/classification
/ml/classfication/ID3.py
4,407
3.75
4
import numpy as np import math ''' @author: FreeMind @version: 1.1 Created on 2014/2/26 This is a basic implementation of the ID3 algorithm. ''' class DTree_ID3: def __init__(self,dataSet,featureSet): #Retrieve the class list self.classList = set([sample[-1] for sample in dataSet]) if ((len(featureSet)+1) != (len(dataSet[1]))): print("The feature set do not match with the data set,please check your data!") #Set the feature set self.featureSet = featureSet def runDT(self,dataSet): ##recursive run DT, return a dictionary object ##1.check boundary: two case - only one tuple ## or all tuples have the same label ##2.compute inforGain for each feature, select ## feature corresponding to max inforGain ##3.split data set on that feature, recursively ## call runDT on subset until reaching boundary classList = set([sample[-1] for sample in dataSet]) #If the data set is pure or no features if len(classList)==1: return list(classList)[-1] if len(self.featureSet)==0: #no more features return self.voteForMost(dataSet,classList) bestSplit = self.findBestSplit(dataSet) bestFeatureLabel = self.featureSet[bestSplit] dTree = {bestFeatureLabel:{}} featureValueList = set([example[bestSplit] for example in dataSet]) for value in featureValueList: subDataSet = self.splitDataSet(dataSet,bestSplit,value) self.featureSet.remove(self.featureSet[bestSplit]) dTree[bestFeatureLabel][value] = self.runDT(subDataSet) self.featureSet.insert(bestSplit,bestFeatureLabel) return dTree #Find the most in the set def voteForMost(self,dataSet,classList): count = np.zeros(len(self.classList)) for sample in dataSet: for index in range(len(self.classList)): if sample[-1]==list(self.classList)[index]: count[index] = count[index]+1 maxCount = 0 tag = 0 for i in range(len(count)): if count[i]>maxCount: maxCount = count[i] tag = i return list(self.classList)[tag] #Compute all infoGains,return the best split def findBestSplit(self,dataSet): #initialize the infoGain of the features infoGain = 0 tag = 0 for i in range(len(self.featureSet)): tmp = self.infoGain(dataSet,i) if(tmp > infoGain): infoGain = tmp tag = i return tag def entropy(self,dataSet): total = len(dataSet) cal = np.zeros(len(self.classList)) entropy = 0 for sample in dataSet: index = list(self.classList).index(sample[-1],) cal[index] = cal[index]+1 for i in cal: proportion = i/total if proportion!=0: entropy -= proportion*math.log(proportion,2) return entropy def infoGain(self,dataSet,featureIndex): origin = self.entropy(dataSet) featureValueList = set([sample[featureIndex] for sample in dataSet]) newEntropy = 0.0 for val in featureValueList: subDataSet = self.splitDataSet(dataSet,featureIndex,val) prob = len(subDataSet)/(len(dataSet)) newEntropy += prob*self.entropy(subDataSet) return origin-newEntropy def splitDataSet(self,dataSet,featureIndex,value): subDataSet = [] for sample in dataSet: if sample[featureIndex] == value: reducedSample = sample[:featureIndex] reducedSample.extend(sample[featureIndex+1:]) subDataSet.append(reducedSample) return subDataSet def predict(self,testData): ##predict for the test data pass if __name__ == "__main__": dataSet = [["Cool","High","Yes","Yes"],["Ugly","High","No","No"], ["Cool","Low","No","No"],["Cool","Low","Yes","Yes"], ["Cool","Medium","No","Yes"],["Ugly","Medium","Yes","No"]] featureSet = ["Appearance","Salary","Office Guy"] dTree = DTree_ID3(dataSet,featureSet) tree = dTree.runDT(dataSet) print(tree)
ac697cfc455c987e41da0e89fc33de44e13b7d28
Raunaka/guvi
/ideone_JwxIRn.py
201
3.71875
4
x = int(input()) y = int(input()) if x > y: smaller = y else: smaller = x for i in range(1,smaller + 1): if((x % i == 0) and (y % i == 0)): hcf = i print( hcf)
e8f2b3ddb028397e083bad8369be3589e3e73405
Raunaka/guvi
/palin.py
98
3.546875
4
a=input() a=list(a) if a==a[::-1]: while a==a[::-1]: a[-1]="" q="" for i in a: q=q+i print(q)
63a9898b547389e60826521a27a60a8ca4c6d70b
rsirs/foobar
/dont_mind_map.py
2,368
3.78125
4
def answer(subway): dest = [{},{},{}] max_route_length = len(subway) import itertools directions = '01234' for closed_station in range(-1, len(subway)): for path_length in range(2,6): current_directions =directions[:len(subway[0])] for route in itertools.product(current_directions,repeat = path_length): dest[0][route] = destination(route,0,subway,closed_station) dest[2][route] = destination(route,2,subway,closed_station) dest[1][route] = destination(route,1,subway,closed_station) for route in dest[0]: if (dest[0][route] == dest[1][route]) and closed_station == -1: satisfy = True for station in range(2,3): if (dest[0][route] != destination(route,station,subway,closed_station)): satisfy = False if satisfy: return -1 elif closed_station == 1 and (dest[0][route] == dest[2][route]): satisfy = True if len(subway) == 3: return closed_station elif (dest[0][route] != destination(route,3,subway,closed_station)): satisfy = False if satisfy: return closed_station elif closed_station != -1 and (dest[0][route] == dest[1][route]): satisfy = True for station in range(2,3): if (dest[0][route] != destination(route,station,subway,closed_station)): satisfy = False if satisfy: return closed_station return -2 def destination(path, station, subway,closed_station): current_station = station for direction in path: direction = int(direction) previous_station = current_station current_station = subway[current_station][direction] if current_station == closed_station: if subway[current_station][direction] == closed_station: current_station = previous_station else: current_station = subway[current_station][direction] destination = current_station return destination
aebfbbd797d10209adeca8e2005940939f7198f6
bugmany/nlp_demo
/src/Basic_knowledge/Manual_implementation_neural_network/简单感知器.py
1,481
4.03125
4
''' 1. 处理单个输入 2. 处理2分类 ''' class Perceptron(object): ''' 初始化参数lr(用于调整训练步长,即 learning),iterations(迭代次数),权重w 与 bias 偏执 ''' def __init__(self,eta=0.01,iterations=10): self.lr = eta self.iterations = iterations self.w = 0.0 self.bias = 0.0 #''' #公式: #Δw = lr * (y - y') * x #Δbias = lr * (y - y') #''' def fit(self,X,Y): for _ in range(self.iterations): for i in range(len(X)): x = X[i] y = Y[i] #首先获得真实值 y 与预测值 y' 的偏差,乘以一个较小的参数 # 【lr 值过小导致训练时间过长,难以判断是否收敛】 # 【lr 值过大则容易造成步长过大而无法收敛】 update = self.lr * (y - self.predict(x)) self.w += update * x self.bias += update # y'(预测值) = w * x + bias def net_input(self,x): return self.w * x + self.bias def predict(self,x): return 1.0 if self.net_input(x) > 0.0 else 0.0 x = [1, 2, 3, 10, 20, -2, -10, -100, -5, -20] y = [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0] model = Perceptron(0.01,10) model.fit(x,y) test_x = [30, 40, -20, -60] for i in range(len(test_x)): print('input {} => predict: {}'.format(test_x[i],model.predict(test_x[i]))) print(model.w) print(model.bias)
1e598b5c0e8208f88db6eda0aecddbc0f1b05b2c
Quyxor/project_euler
/problem_002/fibonacci.py
526
3.9375
4
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' def fib_generator(n): a, b = 1, 1 while b <= n: a, b = b, a + b yield a def calculate(n): return sum(i for i in fib_generator(n) if not i % 2) if __name__ == "__main__": print(calculate(4000000))
e4b6dd203d9d6cbb9a0da72e15f3e382cc765305
jameslamb/doppel-cli
/doppel/PackageCollection.py
3,609
3.59375
4
""" ``PackageCollection`` implements methods for comparing a list of multiple ``PackageAPI`` objects. """ from typing import Dict, List, Set from doppel.PackageAPI import PackageAPI class PackageCollection: """ Create a collection of multiple ``PackageAPI`` objects. This class contains access methods so you don't have to keep doing ``for package in packages`` over a collection of ``PackageAPI`` instances. """ def __init__(self, packages: List[PackageAPI]): """ Class that holds multiple ``PackageAPI`` objects. :param packages: List of ``PackageAPI`` instances to be compared to each other. """ for pkg in packages: assert isinstance(pkg, PackageAPI) pkg_names = [pkg.name() for pkg in packages] if len(set(pkg_names)) < len(packages): msg = "All packages provided to PackageCollection must have unique names" raise ValueError(msg) self.pkgs = packages def package_names(self) -> List[str]: """ Get a list of all the package names in this collection. """ return [p.name() for p in self.pkgs] def all_classes(self) -> List[str]: """ List of all classes that exist in at least one of the packages. """ out: Set[str] = set([]) for pkg in self.pkgs: out = out.union(pkg.class_names()) return list(out) def shared_classes(self) -> List[str]: """ List of shared classes across all the packages in the collection """ # Only work on shared classes out = set(self.pkgs[0].class_names()) for pkg in self.pkgs[1:]: out = out.intersection(pkg.class_names()) return list(out) def non_shared_classes(self) -> List[str]: """ List of all classes that are present in at least one but not ALL packages """ all_classes = set(self.all_classes()) shared_classes = set(self.shared_classes()) return list(all_classes.difference(shared_classes)) def all_functions(self) -> List[str]: """ List of all functions that exist in at least one of the packages. """ out: Set[str] = set([]) for pkg in self.pkgs: out = out.union(pkg.function_names()) return list(out) def shared_functions(self) -> List[str]: """ List of shared functions across all the packages in the collection """ # Only work on shared classes out = set(self.pkgs[0].function_names()) for pkg in self.pkgs[1:]: out = out.intersection(pkg.function_names()) return list(out) def non_shared_functions(self) -> List[str]: """ List of all functions that are present in at least one but not ALL packages """ all_funcs = set(self.all_functions()) shared_funcs = set(self.shared_functions()) return list(all_funcs.difference(shared_funcs)) def shared_methods_by_class(self) -> Dict[str, List[str]]: """ List of public methods in each shared class across all packages """ out = {} shared_classes = self.shared_classes() for class_name in shared_classes: methods = set(self.pkgs[0].public_methods(class_name)) for pkg in self.pkgs[1:]: methods = methods.intersection(pkg.public_methods(class_name)) out[class_name] = list(methods) return out