blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
9ffbfe4e1b57356f2580e02877faa3b7a8ae4f5b
pvictor222/ft_linear_regression
/model_training.py
2,348
3.984375
4
# import sources from src.read_data import read_data from src.gradient_descent import gradient_descent from src.data_visualisation import data_visualisation # import libraries import random import numpy as np if __name__ == '__main__': # initializing variables theta_0 = 0 theta_1 = 0 alpha = 1 # Read the data from "data.csv", remove first row and calculate m data = read_data("data.csv") data.pop(0) data = [[int(x),int(y)] for [x, y] in data] # Data normalisation using the maximum absolute scaling x_min = np.min([x for x,y in data]) y_min = np.min([y for x,y in data]) x_max = np.max([x for x,y in data]) y_max = np.max([y for x,y in data]) data_normalised = [[x / x_max, y / y_max] for x,y in data] # Define the maximum number of iterations max_iterations = input("Enter the maximum number of iterations (1000 if not specified): ") if (max_iterations == '' or max_iterations.isnumeric() == False): max_iterations = int(1000) else: max_iterations = int(max_iterations) print("The maximum number of iterations is: " + str(max_iterations) + "\n") # Gradient descent print("Starting the gradient descent with theta_0 = " + str(theta_0) + ", theta_1 = " + str(theta_1) + " and the learning rate = " + str(alpha) + "...") gradient_result = gradient_descent(theta_0, theta_1, alpha, data_normalised, max_iterations) # denormalize theta_0 and theta1 theta_0 = gradient_result[0] theta_1 = gradient_result[1] theta_0 = round(theta_0 * y_max, 4) theta_1 = round(theta_1 * y_max / x_max, 4) # Printing theta_0 and theta_1 print("\nLinear regression completed!") print("Theta_0 = " + str(theta_0)) print("Theta_1 = " + str(theta_1)) print("Hypothesis: h(x) = " + str(theta_0) + " + " + str(theta_1) + " * x") print("Number of iterations: " + str(gradient_result[2])) print ("Cost = " + str(round(gradient_result[3]))) print ("Learning rate = " + str(gradient_result[4])) # Open fiLe and overwrite the content with the new theta_0 and theta_1 theta = str(theta_0) + ';' + str(theta_1) f = open("theta.txt", "w") f.write(theta) f.close() # data visualisation data_visualisation(data, theta_0, theta_1)
f4601e78704147051c24b398c4e7be88ce30d6e1
mateszadam/Trapez_terulet_kerulet
/main.py
642
3.9375
4
def main() -> None: print('Trapéz kerület és terüet számolás!') A: float = float(input('a: ')) B: float = float(input('b: ')) C: float = float(input('c: ')) D: float = float(input('d: ')) M: float = float(input('m: ')) Terület: float = 0 Kerület: float = 0 if A <= 0 or B <= 0 or C <= 0 or D <= 0 or M <= 0: print("Nullával és annál kisebb számmal nem lehet számolni") else: Terület = ((A + B) * M) / 2 Kerület = A + B + C + D print(f'A trapéz területe: {Terület} és a kerülete {Kerület}') if __name__ == "__main__": main()
79ae50e42cf07d03df04a793b746a50618bde221
jcherubino/magic_hat
/scripts/hat.py
1,173
3.53125
4
#!/usr/bin/env python '''hat.py is a ROS node that publishes the output of a 'magic hat' that contains an infinite amount of turtles with an index and a quality. Date Last Updated: 22/9/19 by Josh Cherubino Purpose: Publish the output of the magic hat so that the corresponding subscriber node can determine whether to display the turtles Published topics: /magic_hat/hat_output ''' from random import randint import rospy from magic_hat.msg import TurtleInfo def magic_hat(): '''function to create a ros publisher to pull turtles out of the magic hat a at a rate of 5 hz with a random quality level between 1 to 10 and an index.''' pub = rospy.Publisher('/magic_hat/hat_output', TurtleInfo, queue_size=10) rospy.init_node('magic_hat', anonymous=True) rate = rospy.Rate(5) #hz #initialise counter variable for use in msg.index counter = 0 msg = TurtleInfo() while not rospy.is_shutdown(): msg.quality = randint(1, 10) msg.index = counter pub.publish(msg) counter += 1 rate.sleep() if __name__ == "__main__": try: magic_hat() except rospy.ROSInterruptException: pass
f82e38bddd2070804cd996299722b9bbae6c1d6b
Jason-pro1/-Python-
/例3、检测2的幂次/checkPowerOf2.py
730
3.921875
4
# 例3、检测2的幂次 """1、问题描述:检测一个整数n是否为2的幂次。 2、问题示例: n=4,返回True;n=5,返回False """ # 代码实现: # 采用UTF-8编码格式 # 参数n是一个整数 # 返回True或者False class Solution: def checkPowerOf2(self, n): ans = 1 for i in range(31): if ans == n: return True ans <<= 1 # 位运算 ans = ans << 1 return False if __name__ == "__main__": temp = Solution() nums1 = 16 nums2 = 62 print(("输入:" + str(nums1))) print(("s输出:" + str(temp.checkPowerOf2(nums1)))) print(("输入:" + str(nums2))) print(("s输出:" + str(temp.checkPowerOf2(nums2))))
ca2b34e1841ab838b5b74640bb1d6d843bec1710
Kr1eg3/ShinyTrafficModel
/vehicle.py
9,162
3.671875
4
#!/usr/bin/python3 from abc import ABC, abstractmethod from random import random, uniform class Vehicle(ABC): next_id = 1 def __init__(self, posx, posy, initial_speed, road_length, max_speed=3, vehicle_type='cooperator'): self.posx = posx self.posy = posy self.initial_speed = initial_speed self.road_length = road_length self.max_speed = max_speed self.vehicle_type = vehicle_type self.vehicle_speed = self.initial_speed self.previous_spd = self.vehicle_speed self.previous_posx = self.posx - 1 if self.previous_posx < 0: self.previous_posx += self.road_length self.f_speed = self.vehicle_speed self.new_speed = 0 self.my_lane = [] self.right_lane = [] self.left_lane = [] self.n_vehicle = None self.s_vehicle = None self.e_vehicle = None self.w_vehicle = None self.ne_vehicle = None self.se_vehicle = None self.sw_vehicle = None self.nw_vehicle = None self.si_vehicle = None self.road_length = road_length self.id = Vehicle.next_id Vehicle.next_id += 1 # Model parameters self.barking_prob = .2 self.G = 2 self.S = 2 self.s = 1 self.q = .99 self.r = .2 self.P1 = .999 self.P2 = .99 self.P3 = .98 self.P4 = .01 @abstractmethod def get_si_neighbor(self): pass @abstractmethod def get_neighbors(self): pass @abstractmethod def get_new_speed(self): pass @abstractmethod def move(self): pass @property def get_vehicle_info(self): info_dict = {'vehicle id': self.id, 'vehicle x position': self.posx, 'vehicle y position': self.posy, 'vehicle speed': self.vehicle_speed, 'vehicle max speed': self.max_speed, 'vehicle behavior type': self.vehicle_type, 'neighbors': {'n_neighbor': self.n_vehicle, 's_neighbor': self.s_vehicle, 'e_neighbor': self.e_vehicle, 'w_neighbor': self.w_vehicle, 'ne_neighbor': self.ne_vehicle, 'se_neighbor': self.se_vehicle, 'sw_neighbor': self.sw_vehicle, 'nw_neighbor': self.nw_vehicle } } return info_dict class Car(Vehicle): def get_si_neighbor(self): self.s = self.S if uniform(0, 1) <= self.r else 1 if self.s == 1: self.si_vehicle = self.n_vehicle elif self.s == 2: if len(self.my_lane) == 2: self.s = 1 self.si_vehicle = self.n_vehicle else: sv = self.n_vehicle self.si_vehicle = sv.n_vehicle def get_neighbors(self, list_of_lanes): #TODO # Initial conditions if self.posy == 0: self.my_lane = list_of_lanes[0] self.right_lane = list_of_lanes[1] self.left_lane = None else: self.my_lane = list_of_lanes[1] self.left_lane = list_of_lanes[0] self.right_lane = None for index, item in enumerate(self.my_lane): if item.id == self.id: my_index = index # North and South neighbors if my_index == len(self.my_lane) - 1: self.n_vehicle = self.my_lane[0] else: self.n_vehicle = self.my_lane[my_index + 1] if my_index == 0: self.s_vehicle = self.my_lane[len(self.my_lane) - 1] else: self.s_vehicle = self.my_lane[my_index - 1] # West and East neighbors if self.left_lane == None: for index, item in enumerate(self.right_lane): if item.posx == self.posx: self.e_vehicle = item else: self.e_vehicle = None elif self.right_lane == None: for index, item in enumerate(self.left_lane): if item.posx == self.posx: self.w_vehicle = item else: self.w_vehicle = None def _gap(self, neigb): gap = neigb.posx - self.posx if gap < 0: gap = neigb.posx + self.road_length - 1 - self.posx if gap < 0: print('Alert! Gap < 0 for id =', self.id,'!') return gap def _acceleration(self, speed, gap, neighb): if gap >= self.G and speed <= neighb.vehicle_speed: speed = min(self.max_speed, speed + 1) if speed < 0: print('Alarm in Acceleration, speed is negative for id =', self.id,'!') return 1 else: return min(self.max_speed, speed + 1) else: return speed def _slow_to_start(self, speed, road): if uniform(0, 1) <= self.q: si_prev_pos = self.si_vehicle.previous_posx if si_prev_pos < self.previous_posx: if (si_prev_pos + road - 1) - self.previous_posx == 0: speed = 0 return speed else: speed = min(speed, (si_prev_pos + road - 1) - self.previous_posx - self.s) if speed < 0: print('Alarm in Slow-to-start, speed is negative for id =', self.id,'!') return 1 else: return speed else: speed = min(speed, si_prev_pos - self.previous_posx - self.s) if speed < 0: print('Alarm in Slow-to-start, speed is negative for id =', self.id,'!') return 1 else: return speed else: return speed def _quick_start(self, speed, road): si_curr_pos = self.si_vehicle.posx si_gap = self._gap(self.si_vehicle) if si_curr_pos < self.posx: if si_gap == 0: speed = 0 return speed else: speed = min(speed, si_gap - self.s) return speed if speed < 0: print('Alarm in Quick Start, speed is negative for id =', self.id,'!') return 1 else: return speed else: speed = min(speed, si_curr_pos - self.posx - self.s) if speed < 0: print('Alarm in Quick Start, speed is negative for id =', self.id,'!') return 1 else: return min(speed, self.si_vehicle.posx - self.posx - self.s) def _random_brake(self, speed, gap): if uniform(0, 1) < 1 - self.barking_prob: speed = max(1, speed - 1) if gap >= self.G: self.barking_prob = self.P1 elif gap < self.G: if self.vehicle_speed < self.n_vehicle.vehicle_speed: self.barking_prob = self.P2 elif self.vehicle_speed == self.n_vehicle.vehicle_speed: self.barking_prob = self.P3 elif self.vehicle_speed > self.n_vehicle.vehicle_speed: self.barking_prob = self.P4 if speed < 0: print('Alarm in Random Brake, speed is negative for id =', self.id,'!') return 1 else: return speed else: return speed def _avoid_collision(self, speed, gap): speed = min(speed, gap - 1 + self.n_vehicle.f_speed) if speed < 0: print('Alarm in Avoid Collision, speed is negative for id =', self.id,'!') return 1 else: return speed def get_new_speed(self, road, show_speed=True): # Initial self.previous_spd = self.vehicle_speed __car_speed = self.vehicle_speed __gap = self._gap(self.n_vehicle) # rule 1. Acceleration __car_speed = self._acceleration(__car_speed, __gap, self.n_vehicle) # rule 2. Slow-to-start __car_speed = self._slow_to_start(__car_speed, road) # rule 3. Perspective (Quick Start) __car_speed = self._quick_start(__car_speed, road) # rule 4. Random brake __car_speed = self._random_brake(__car_speed, __gap) # rule 5. Avoid collision __car_speed = self._avoid_collision(__car_speed, __gap) # Get new speed self.new_speed = __car_speed if show_speed == True: print('id =', self.id, 'speed =', self.new_speed, 's =', self.s) def move(self, road): self.previous_posx = self.posx self.posx += self.new_speed if self.posx >= road: self.posx -= road self.vehicle_speed = self.new_speed
ab1b47cc4898449827fa0076c888e5410c52e6a7
Ebyy/python_projects
/Files/exercises_10_11.py
219
3.625
4
import json favorite_number = input("What is your favorite number? ") filename = 'favorite_number.json' with open(filename,'w') as f_obj: json.dump(favorite_number,f_obj) print("Thanks! I'll remember that.")
12b59f10d966f8f1fdd4d769419d7018c8144ef3
asan-itc/forkairat
/stroki/stroki25.py
238
3.515625
4
text = "У вас есть строка 'Запуск Ethereum 2.0 состоится 1 декабря. На депозитный контракт внесено более 524 288 ETH" x = text.split() for i in x: print(i,type(i))
ac2a912ade4f32e815321fd60c958980949895ae
shruti-2522/PYTHON
/filter.py
289
3.65625
4
# filter_function """num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 45, 67] def is_gretter_5(num): return num > 5 val = list(filter(is_gretter_5, num)) print(val)""" # REDUCE FUNCTION from functools import reduce num1 = [20, 30, 40, 59] a = reduce(lambda x, y: x + y, num1) print(a)
c2a4af0fd2733ce2a9dddb1ecc016095d91ba700
Kunal352000/python_program
/basicFunction5.py
110
3.75
4
def show(x,y): print("sum=",x+y) a=int(input("Enter no.1: ")) b=int(input("Enter no.2: ")) show(a,b)
89c3b11aeceb826125ab2ad51867858e8575df89
HuaMa001/python001
/d06/dictDemo3.py
304
3.515625
4
users=[ {"name": "John", "h": 170, "w": 60}, {"name":"Mary","h":160, "w":48} ] #請計算每一筆的bmi值=? for user in users: #print(user, type(user)) 判斷資料 h= user.get("h") w= user.get("w") bmi="%.2f"%(w/((h/100)**2)) print(user, type(user), bmi)
abab4fd984f6f893848170cc47a300c3c5281f8b
laysakura/relshell
/relshell/test/shellcmd/simplest
452
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ word_count ~~~~~~~~~~ :synopsis: input: word, output: occurence count of the word """ import sys if __name__ == '__main__': sys.stderr.write('input any word (Ctrl-D to finish)\n') while True: word = sys.stdin.readline() if word == '': # EOF sys.exit(0) word = word.strip() sys.stdout.write('%s\n' % (word)) sys.stdout.flush()
0db25cb29558167cc8cdcded4bbb455b71cab2e9
cyrillelamal/pogrom
/sem6/task1/primo.py
677
3.90625
4
# Разработка скрипта, вычисляющего статистические показатели (среднее # значение, дисперсия, среднее квадратичное отклонение) для данных, # считанных из CSV-файла. import csv import statistics with open("./data.csv", "rt") as f: reader = csv.reader(f) costs = list(map(lambda r: r[2], reader))[1:] mean = statistics.mean(costs) # среднее значение dispersion = statistics.pvariance(costs) # дисперсия stdev = statistics.stdev(costs) # среднее квадратичное отклонение
be423fa367e812582862592c6e0f02ae6d182bc1
shulp2211/SeeCiTe
/inst/python/datastructutils.py
1,116
4.0625
4
#!/usr/bin/env python3 ''' General utility functions concerning dictionaries, lists etc. ''' def get_range(d, begin, end): ''' Subset a dictionary, returning the elements in the given index range(treat dict as array) Args: d: python dictionary begin: first key element end: end key element Returns: subdictionary with keys 'ranging' from 'begin' to 'end' ''' return dict(e for i, e in enumerate(d.items()) if begin <= i <= end) def flatten_list_of_lists(nested_list): ''' Utility function. Flatten list of lists :param nested_list: list with 1-level deep nested structure :return: flat list ''' result =[] for sublist in nested_list: for item in sublist: result.append(item) return(result) def write_list(filename, listvar): ''' Write list to a file, one word per row Args: filename: name of the file out listvar: list of strings Returns: NA, writes out a file ''' out = open(filename, "w") for s in listvar: out.write("%s\n" % s) out.close()
5f789799044027f4fd60faeb090e047c1b7615d8
hyeseong-dev/2021-03-11-algorithms
/chap01/rectangle.py
473
3.5
4
# 가로, 세로 길이가 정수이고 넓이가 area인 직사각형에서 변의 길이 나열하기 area = int(input('직사각형의 넓이를 입력하세요.: ')) for i in range(1, area+1): # 1부터 사각형의 넓이를 계산 if i * i > area: break # 참이면 loop를 종료함. i가 가장 긴변의 길이가 되기 때문 if area % i : continue # i 가 area의 약수가 아닐 경우 실행, 나머지가 있는 경우 print(f'{i}*{area//i}')
2c3399b400cb560762edaeb896079aaadf33af76
python-elective-1-spring-2019/Lesson-12-Testing-Debugging-Exeptions
/code_from_today/if_bla.py
198
3.59375
4
def check(x): if x == 0: x += 1 elif x > 0: hksfhslkjafhlkafjdlkjdf else: adsjfhljakhlfkds return x print(check(0)) for i in range(20): print (i)
835ea47666d277e9e49bf098963c5b7c98fb028a
munirmaricar/Textual-Analysis
/TextualAnalysisForSpecificRegulator.py
22,408
3.5
4
""" SPECIFIC CODE FOR EACH REGULATOR Steps for Executing Code Specific For Regulator: 1. Import the data by uploading the CSV and XLSX files from the different regulators. Rename them as FDIC.csv, OCC.xlsx and FED.csv respectively. 2. Create a new empty folder called Pages. This will store all the converted pages of the downloaded PDF file in an image format. 3. Execute the main part of the code and provide information specific for the type of regulator requested. """ # Importing the previously installed libraries. import sys import os import re import requests import pytesseract import urllib.request import pandas as pd from pdf2image import convert_from_path from urllib.parse import urljoin from datetime import datetime from bs4 import BeautifulSoup from PIL import Image # This function is used to download a PDF given a link and it saves the PDF # using the given name. def downloadPDF(link, fileName): # This variable stores a list of the PDF files that have been downloaded # from the appropriate link. listOfFiles = [] # If the link provided in the argument of the function is a webpage instead # of a link that directly leads to a PDF download, we handle it differently # using a Python library called Beautiful Soup. This helps us pull data out # HTML files. if link[-3:] == "htm": # This is used to open the link provided as an argument to the function. response = requests.get(link) # This variable obtains the HTML code for the webpage. soup = BeautifulSoup(response.text, "html.parser") # We iterate through all the PDFs available in the webpage. for url in soup.select("a[href$='.pdf']"): # We name the PDF files using the last portion of each link which # are unique. filename = url['href'].split('/')[-1] # We append the listOfFiles variable. listOfFiles.append(filename) # If the file has successfully been downloaded, we make a note of # it. with open(filename, 'wb') as f: f.write(requests.get(urljoin(link, url['href'])).content) else: # This is used to open the link provided as an argument to the function. response = urllib.request.urlopen(link) # This opens the file in a binary-write mode. file = open(fileName + ".pdf", 'wb') # If the file has successfully been downloaded, we make a note of it. file.write(response.read()) # We close the file. file.close() # We append the listOfFiles variable. listOfFiles.append(fileName + ".pdf") # We return the listOfFiles variable so other functions can see how many # files were downloaded. return listOfFiles # This function is used to convert the different pages of the PDF with the name # provided as an argument into images which can be processed to look for dates. def processPDF(pdfFile): # Name of the PDF file. pdf = pdfFile + ".pdf" # This variable stores all the pages of the PDF. pages = convert_from_path(pdf, 500) # This variable is a counter to store each page of the PDF to an image. imageCounter = 1 # We iterate through all the pages stored above. for page in pages: # We are specifying the file name for each page of the PDF to be stored # as its corresponding image file. For instance, page 1 of the PDF will # be stored as an image with the name Page 1.jpg in the Pages folder. fileName = "Pages/Page " + str(imageCounter) + ".jpg" # This will save the image of the page in our system. page.save(fileName, 'JPEG') # This will increment the image counter to show how many images we have. imageCounter = imageCounter + 1 # This variable stores the total number of pages we have in our file. fileLimit = imageCounter - 1 # This list of sentences stores the sentence that contains a date that was # mentioned in the PDF. It is a list of lists with the first element being # the sentence and the second element being the date. listOfSentencesWithDate = [] # We iterate again from 1 to the total number of pages in the PDF. for i in range(1, fileLimit + 1): # We set the file name to recognize text from the respective image of # each page. Again, these files will be Page 1.jpg, Page 2.jpg, etc. fileName = "Pages/Page " + str(i) + ".jpg" # This recognizes the text as a string from the image using pytesseract. text = str(((pytesseract.image_to_string(Image.open(fileName))))) # This variable stores the recognized text. In many PDFs, at the ending # of a line, if a word cannot be written fully, a 'hyphen' is added and # the rest of the word is written in the next line. We are removing # that. text = text.replace('-\n', '') # We split the text up into a list of different sentences. sentences = text.split(". ") # We iterate through all the sentences. for sentence in sentences: # The date variable stores the date that occurs in the current # sentence we are looking at and stores it as a list using regular # expression. date = re.findall(r'((January|February|March|April|May|June|July|' + 'August|September|October|November|December' + ')\s+\d{1,2},\s+\d{4})', sentence) # We are checking if the current sentence does contain a date. if date != []: # We add the sentence and the date in the form of a list to the # listOfSentencesWithDate variable. listOfSentencesWithDate.append([sentence.replace('\n', ' '), date[0][0].replace('\n', ' ')]) # We are returning the listOfSentencesWithDate so it can be presented in a # CSV file. return listOfSentencesWithDate # This function is used to differentiate the operations for different # regulators. The regulator name is provided as argument to the function. def getDataFromDataframe(regulatorName): # We are checking if the regulator is FDIC. if regulatorName == "FDIC": # We read the FDIC data and load it using pandas into a dataframe. dataframe = pd.read_csv("FDIC.csv") # This variable stores the docket number that is provided as a user # input. docketNumber = input("Enter the FDIC docket number for the document " + "you would like to see the date information for: ") # This inserts a unique ID in the dataframe that is displayed in the # output. dataframe.insert(0, 'Unique ID', range(1, len(dataframe) + 1)) # This flag is used to indicate if we found the docket number requested # by the user in the dataframe. found = False # We iterate through all the rows in the dataframe. for index, row in dataframe.iterrows(): # We are updating the current docket number that we are going to # compare. Some rows may have multiple docket numbers and in such # scenarious, we are splitting them into a list of docket numbers. currentDocketNumber = str(row[" Docket Number"]) currentDocketNumber = currentDocketNumber.split(",") # If the docket number matches to the one requested by the user, we # download the PDF using the link for the documents for the # corresponding docket number in the same row. if docketNumber in currentDocketNumber: # We update the found flag to True. found = True # This variable stores the link to the PDF file. linkToFile = row[" File URL"] # This variable stores the name of the bank involved. institutionName = row[" Bank Name"] # This variable stores the unique ID of the row. uniqueID = row["Unique ID"] # We download the PDF using the previous function we created. listOfFiles = downloadPDF(linkToFile, docketNumber) # We find the list of sentences with date mentioned in the PDF # using the previous function we created. listOfSentencesWithDate = processPDF(docketNumber) # We create an appropriate output dataframe with four different # columns as requested. outputDataframe = pd.DataFrame(columns=['Unique ID', 'Name o' + 'f Institution', 'Date', 'Sentence Containing' + ' Date']) # We iterate through every sentence and date combination in the # list of sentences with date. for i in range(len(listOfSentencesWithDate)): # We convert the date to a datetime object. date = datetime.strptime(listOfSentencesWithDate[i][1], '%B %d, %Y') # We check the year of the date since we only include # dates that occur after 1990. if date.year >= 1990: # We output the relevant information in the output # dataframe we created earlier. outputDataframe = outputDataframe.append({'Unique ID': uniqueID, 'Name of Institution': institutionName, 'Date': listOfSentencesWithDate[i][1], 'Sentence Containing Date': listOfSentencesWithDate[i][0]}, ignore_index=True) # We display an error message if there are no dates after 1990 # that appear in the document. if outputDataframe.empty: print("There are no relevant dates after the year 1990 in" + " the document referred to with the FDIC docket num" + "ber of " + docketNumber + ".") else: # The outputDataframe is converted into an Output.csv file # which can be viewed by the user. outputDataframe.to_csv('Output.csv') print() print("Please open the Output.csv file to see the relevan" + "t date information.") # We display an error message if the FDIC docket number is not found in # the dataframe. if found == False: print("The FDIC docket number of " + docketNumber + " is incorrec" + "t. Please run the program again.") # We are checking if the regulator is OCC. elif regulatorName == "OCC": # We read the OCC data and load it using pandas into a dataframe. dataframe = pd.read_excel("OCC.xlsx") # This variable stores the docket number that is provided as a user # input. orderNumber = input("Enter the OCC order number for the document you " + "would like to see the date information for: ") # This flag is used to indicate if we found the docket number requested # by the user in the dataframe. found = False # We iterate through all the rows in the dataframe. for index, row in dataframe.iterrows(): # We are updating the current order number that we are going to # compare. currentOrderNumber = str(row["Order Number"]) # If the order number matches to the one requested by the user, we # download the PDF using the link for the documents for the # corresponding order number in the same row. if orderNumber == currentOrderNumber: # We update the found flag to True. found = True # This variable stores the link to the PDF file. linkToFile = row["Link to Enforcement Action"] # This variable stores the name of the bank involved. institutionName = row["Institution Name"] # This variable stores the unique ID of the row. uniqueID = row["Record ID"] # We download the PDF using the previous function we created. downloadPDF(linkToFile, orderNumber) # We find the list of sentences with date mentioned in the PDF # using the previous function we created. listOfSentencesWithDate = processPDF(orderNumber) # We create an appropriate output dataframe with four different # columns as requested. outputDataframe = pd.DataFrame(columns=['Unique ID', 'Name o' + 'f Institution', 'Date', 'Sentence Containing' + ' Date']) # We iterate through every sentence and date combination in the # list of sentences with date. for i in range(len(listOfSentencesWithDate)): # We convert the date to a datetime object. date = datetime.strptime(listOfSentencesWithDate[i][1], '%B %d, %Y') # We check the year of the date since we only include # dates that occur after 1990. if date.year >= 1990: # We output the relevant information in the output # dataframe we created earlier. outputDataframe = outputDataframe.append({'Unique ID': uniqueID, 'Name of Institution': institutionName, 'Date': listOfSentencesWithDate[i][1], 'Sentence Containing Date': listOfSentencesWithDate[i][0]}, ignore_index=True) # We display an error message if there are no dates after 1990 # that appear in the document. if outputDataframe.empty: print("There are no relevant dates after the year 1990 in" + " the document referred to with the OCC order numbe" + "r of " + orderNumber + ".") else: # The outputDataframe is converted into an Output.csv file # which can be viewed by the user. outputDataframe.to_csv('Output.csv') print() print("Please open the Output.csv file to see the relevan" + "t date information.") # We display an error message if the OCC order number is not found in # the dataframe. if found == False: print("The OCC order number of " + orderNumber + " is incorrect. " + "Please run the program again.") # We are checking if the regulator is FED. elif regulatorName == "FED": # We read the FED data and load it using pandas into a dataframe. dataframe = pd.read_csv("FED.csv") # This list of sentences stores the sentence that contains a date that # was mentioned in the PDF. listOfSentencesWithDate = [] # This variable stores the URL for the document that the user provides # as input. url = input("Enter the FED URL for the document you would like to see" + " the date information for: ") # This inserts a unique ID in the dataframe that is displayed in the # output. dataframe.insert(0, 'Unique ID', range(1, len(dataframe) + 1)) # This flag is used to indicate if we found the docket number requested # by the user in the dataframe. found = False # We iterate through all the rows in the dataframe. for index, row in dataframe.iterrows(): # We are updating the current URL that we are going to compare. currentURL = str(row["URL"]) # If the URL matches to the one requested by the user, we download # the PDF using the link for the documents. if url == currentURL: # We update the found flag to True. found = True # This variable stores the link to the PDF file. linkToFile = "https://www.federalreserve.gov/" + currentURL # This variable stores the name of the bank involved. institutionName = row["Banking Organization"] # This variable stores the unique ID of the row. uniqueID = str(row["Unique ID"]) # We download the PDF using the previous function we created. listOfFiles = downloadPDF(linkToFile, uniqueID) # Since the FED can result in multiple PDFs needing to be # analysed, we analyse each of them by iterating through all the # files in the listOfFiles variables that is returned as a # result of executing the downloadPDF function. for tempFile in listOfFiles: # We find the list of sentences with date mentioned in the # PDF using the previous function we created. We do this for # all the files in the list of files. listOfSentencesWithDate += processPDF(tempFile[:-4]) # We create an appropriate output dataframe with four different # columns as requested. outputDataframe = pd.DataFrame(columns=['Unique ID', 'Name o' + 'f Institution', 'Date', 'Sentence Containing' + ' Date']) # We iterate through every sentence and date combination in the # list of sentences with date. for i in range(len(listOfSentencesWithDate)): # We convert the date to a datetime object. date = datetime.strptime(listOfSentencesWithDate[i][1], '%B %d, %Y') # We check the year of the date since we only include # dates that occur after 1990. if date.year >= 1990: # We output the relevant information in the output # dataframe we created earlier. outputDataframe = outputDataframe.append({'Unique ID': uniqueID, 'Name of Institution': institutionName, 'Date': listOfSentencesWithDate[i][1], 'Sentence Containing Date': listOfSentencesWithDate[i][0]}, ignore_index=True) # We display an error message if there are no dates after 1990 # that appear in the document. if outputDataframe.empty: print("There are no relevant dates after the year 1990 in" + " the document referred to with the url of " + url) else: # The outputDataframe is converted into an Output.csv file # which can be viewed by the user. outputDataframe.to_csv('Output.csv') print() print("Please open the Output.csv file to see the relevan" + "t date information.") # We display an error message if the URL is not found in the dataframe. if found == False: print("The URL of " + url + " is incorrect. Please run the progra" + "m again.") # This is the main part of the program. if __name__ == "__main__": # This variable stores the regulator name that the user will provide as # input. regulatorName = input("Enter the regulator you would like to obtain docum" + "ents for (FDIC, OCC or FED): ") # The user will be asked to try again if the regulator is not one of the # three regulators allowed. while ((regulatorName != "FDIC") and (regulatorName != "OCC") and (regulatorName != "FED")): regulatorName = input("Please try a valid regulator (FDIC, OCC or FED" + "): ") # We use the function we defined previously to deal with the regulator # provided in an appropriate way. getDataFromDataframe(regulatorName)
e5ee29542abf83dd889ca4da7ada595548d198e9
Pat-Oz/basics
/createtext2.py
418
3.734375
4
# FILENAME INPUT filename = raw_input("Enter filename: ") target = open (filename, 'a') # USER INPUT print "Enter first two lines of text:" line1 = raw_input("Line 1: ") line2 = raw_input("Line 2: ") # WRITE INPUT print "Input text succesfully written to file." target.write(line1) target.write("n") target.write(line2) target.write("n") # FILE CREATION CONFIRMATION print "File succesfully created." target.close()
c460ef27036773580ae0691a9cdc7a77f785140b
rithwik00/practice-problems
/memoization/howSum.py
628
3.59375
4
# takes targetSum and array of numbers as input # return array of any combination of elements(repeated allowed) that add up to the targetsum def howSum(targetSum, numbers): if targetSum in visited: return visited[targetSum] if targetSum == 0: return [] if targetSum < 0: return None for num in numbers: remainder = targetSum - num result = howSum(remainder, numbers) if result != None: visited[targetSum] = result + [num] return visited[targetSum] visited[targetSum] = None return None visited = {} print(howSum(300, [2,4]))
5f2cba92becf82d1034de60b288808b7fe7fc2ee
subash319/PythonDepth
/Practice21_OOP_StaticMethods_ClassMethods/Prac21_1_HCF_two_numbers.py
1,202
4.03125
4
# 1. This is a function to find the highest common factor of two numbers # Make it a static method in the Fraction class that you had written in earlier exercise. class Fraction: def __init__(self, nr, dr=1): self.nr = nr # making the denominator postive if it is negative self.dr = dr if dr >=0 else -dr def show(self): print(f'{self.nr}/{self.dr}') def multiply(self, f1): if isinstance(f1, int): return Fraction((self.nr*f1), self.dr) else: return Fraction((self.nr*f1.nr), (self.dr*f1.dr)) def add(self, fa): if isinstance(fa, int): fa = Fraction(fa) return Fraction((self.nr * fa.dr + fa.nr * self.dr), (self.dr * fa.dr)) @staticmethod def hcf(x, y): x = abs(x) y = abs(y) smaller = y if x > y else x s = smaller while s > 0: if x % s == 0 and y % s == 0: break s -= 1 return s f1 = Fraction(2,3) f1.show() f2 = Fraction(3,4) f2.show() f3 = f1.multiply(f2) f3.show() f3 = f1.add(f2) f3.show() f3 = f1.add(5) f3.show() f3 = f1.multiply(5) f3.show() print(Fraction.hcf(20, 15))
35cdb6c79aa583a3b99d1da33de822bc20b04eeb
HarshaaArunachalam/guvi
/code/42.py
105
3.6875
4
x,y=input().split() if(len(x)>len(y)): print(x) elif(len(y)>len(x)): print(y) else: print(x)
9992b8dba03bd0a71ad709cb80ddf435517793ef
DierSolGuy/Python-Programs
/list_merge.py
132
3.765625
4
L1 = input("Enter the 1st list of numbers: ") L2 = input("Enter the 2nd list of numbers: ") L3 = L1 + L2 print(L3,sep='',end=' ')
059759cf158017763e93924b6a1afb06eb6c61cc
Balajikrishnan00/Python
/Operator,input,if else.py
2,075
4.03125
4
''' n=100 n1=n+10 print(n1) # eval() #1p total=eval('10+20+30+40+50+60+70+80+90+100') print(total) #2p total=eval(input("Enter total")) print(total) import math print(math.pow(3,2)) # end= ,sep= # formatted String # %i - integer # %d - integer # %s string # %f -float name='siva' age=24 weight=50.6 height=23 print('This is formatted string') print('hi this is %s i am %i year old my height %d and weight %.2f.'%(name,age,height,weight)) print('hi this is {} i am {} year old my height {} and weight {}'.format(name,age,height,weight)) print(f'hi this is {name} i am {age} year old my height {height} and weight {weight}') # replacement Operator name='Balaji' city='Madurai' print('This is {} from {}'.format(name,city)) print('This is {0} from {1}'.format(name,city)) print('This is {1} from {0}'.format(name,city)) print('This is {m} from {b}'.format(m=name,b=city)) # slicing #1p name='Balaji krishnan' length=len(name) len=len(name)//2 final_name=name[:len]+name[len].upper()+name[len+1:] print(final_name) print(len) i=0 while i<length: print(name,i,'=',name[i]) i+=1 #2p name='BALAJIKRISHNAN' final_name=name[0]+name[1:].lower() print(final_name) # control flow statemets #1p mark=90 if mark>=90: print('Excellent.') #2p mark=int(input('Enter your mark:')) if mark>=90: print('excellent.') elif mark>=80: print('very Good.') elif mark>=40: print('good') elif mark>=35: print('Your pass') else: print('Fail') #2p total=int(input('Enter Your Total:')) if total>=400: tamil=int(input('Enter Tamil:')) english=int(input('Enter English:')) maths=int(input('Enter Maths:')) science=int(input('Enter Science:')) social=int(input('Enter Social:')) tot=tamil+english+maths+science+social print(tot) ''' # iterative statements #while #for guess=0 computer_mind=30 while computer_mind!=guess: guess= int(input('tell your guess: ')) if guess==computer_mind: print('wow super:') elif guess>computer_mind: print('your number too big') else: print('your number too little')
3929ca35a89f25dd309e93a9c7b6ac8dbd189d7a
cIvanrc/problems
/ruby_and_python/4_string/ceasar_encryption.py
1,189
4.625
5
# Write a Python program to create a Caesar encryption # Note : In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. # It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. # For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. # The method is named after Julius Caesar, who used it in his private correspondence. # plaintext: defend the east wall of the castle # ciphertext: efgfoe uif fbtu xbmm pg uif dbtumf import string def caesar_encryption(): all_string = string.ascii_letters all_letters = [letter for letter in all_string] plain_text = "defend the east wall of the castlZ" text_encrypted = "" for letter in plain_text: if letter == "Z": text_encrypted += "a" elif letter != " ": index = all_letters.index(letter) text_encrypted += all_letters[index+1] else: text_encrypted += " " print(text_encrypted) caesar_encryption()
9c519052b0517ab15c895b4243d9fe68b1e3a2ce
ykzzyk/Networking
/P1/MultithreadServer/Method_1/server.py
2,108
3.59375
4
from socket import * import threading def tcp_server(TCP_IP, TCP_PORT, BUFFER_SIZE): # Prepare a server socket serverSocket = socket(AF_INET, SOCK_STREAM) try: # Bind TCP_IP address and TCP_PORT serverSocket.bind((TCP_IP, TCP_PORT)) except Exception: print("\n") threads = [] #listening for Client serverSocket.listen(5) serverSocket.settimeout(80) print('Multithread server ready to serve..') #Establish the connection while True: if len(threads) == 5: # Close Server serverSocket.close() break try: connectionSocket, addr = serverSocket.accept() newthread = threading.Thread(target = tcp_server, args = (TCP_IP, TCP_PORT, BUFFER_SIZE)) newthread.start() threads.append(newthread) # Receive the message from the Client message = connectionSocket.recv(BUFFER_SIZE) filename = message.split()[1].decode('utf-8') # filename = 'HelloWorld.html' with open(filename) as f: outputdata = f.read() # Send one HTTP header line into socket connectionSocket.send(b'\r\n\r\nHTTP/1.1 200 OK\r\n\r\n') # Send the content of the requested file to the client for i in range(0, len(outputdata)): connectionSocket.send(bytes(outputdata[i], 'utf-8')) #Close client socket connectionSocket.close() except IOError: #Send response message for file not found connectionSocket.send(b'404 Not Found') #Close client socket connectionSocket.close() # Join threads for t in threads: t.join() # Close Server #serverSocket.close() if __name__ == "__main__": # Parameters TCP_IP = 'localhost' TCP_PORT = 12003 BUFFER_SIZE = 1024 tcp_server(TCP_IP, TCP_PORT, BUFFER_SIZE)
c35e7249c22ad1c1f2734e133f2564d0bb377b8c
DenisLamalis/cours-python
/lpp101-work/index_34.py
592
4.0625
4
# For loop - exercise names = ['john ClEEse','Eric IDLE','michael'] names1 = ['graHam chapman', 'TERRY', 'terry jones'] all_names = set(names + names1) for name in all_names: print(f'{name.lower().title()}!, you are invited to the party saturday.') # Solution names = ['john ClEEse','Eric IDLE','michael'] names1 = ['graHam chapman', 'TERRY', 'terry jones'] msg = 'You are invited to the party on saturday.' #names.extend(names1) names += names1 for index in range(2): names.append(input('Enter a new name: ')) for name in names: #msg1 = f'{name.title()}! {msg}' msg1 = name.title() + '! ' + msg print(msg1)
f631c5f8c8a9a0bc0e92528200d542d7fe159550
marciof2/PYTHON-
/desafio06.py
190
3.8125
4
n= int(input('Digite um valor: ')) dobro= n*2 triplo= n*3 rq= n**(1/2) print('Você digitou {} \nO dobro é {} \nO triplo é {} \nA raiz quadrada é {:.2f}'.format(n, dobro, triplo, rq))
45bb91f30af902baf2a3bc6704f23982bf436973
hoobear15/secretmessages
/cipher.py
1,608
4.1875
4
class Cipher: """creates a new Cipher object; stores original user message as encrypted or decrypted message and creates a one time PAD to be used if user requests a decrypted message""" def __init__(self, text, status): self.message = str(text).upper().replace(" ", "") if status == "encrypt": while True: self.pad = int(input("A one time, four digit PIN will secure this message, " "what four digit pin would you like to use? >>> ")) if isinstance(self.pad, int) and len(str(self.pad)) == 4: break else: print("Please ensure the PIN you entered uses only numbers and is exactly four digits") self.encrypted = "" self.decrypted = "" self.padding = 0 def pad_check(self): """requests a user to enter a PAD number and returns boolean based on matching (or not) the objects PAD""" while True: try: return int(input("This message requires a PIN to decrypt, please enter it: >>> ")) == self.pad except ValueError: print("Please ensure the PIN is a number") def encrypt(self, message): """stub in place should user try to use encrypt method of a basic cipher class""" self.message = message raise NotImplementedError() def decrypt(self, message): """stub in place should user try to use decrypt method of a basic cipher class""" self.message = message raise NotImplementedError()
e962526e7bd974684c706c1ab083552b1b7afc37
timwisbauer/adventofcode2020
/1-2/repair.py
1,123
3.796875
4
# Advent of Code Day 1: Report Repair # Find the two entries that sum to 2020 and multiply them together. def find_match(expenses): # Sort the elements in the list first. expenses.sort(reverse=True) for a_index, a in enumerate(expenses): # Starting with a_index + 1, loop through rest of list. # Check to see if a + b < 2020. If so, start with b_index+1 # and check for acceptance. print(f"A: {a}") for b_index in range(a_index + 1, len(expenses)): b = expenses[b_index] print(f"A:{a}, B: {b}") if a + b < 2020: for c_index in range(b_index + 1, len(expenses)): c = expenses[c_index] print(f"A: {a}, B: {b}, C: {c}") if a + b + c == 2020: return a * b * c if __name__ == "__main__": with open("input.txt", 'r') as file: contents = file.read().splitlines() # Convert to ints. expenses = [int(i) for i in contents] answer = find_match(expenses) print(f"Answer: {answer}")
b59536efdf599c97a32d0e9e335615194efaccb5
shinjl/xcity-finder
/convert_data.py
2,261
3.65625
4
# Data preparation utility for runtime # Split large world city file into small chunks to save runtime memory # ============================================================================== import time import os import csv countries = {} cities = {} def read_country_code(): print('loading country code') with open('countries/country_code.csv', newline='') as csvfile: datareader = csv.reader(csvfile, delimiter=',') for one in datareader: countries[one[0]] = one[1] def read_city_list(): start = time.time() print('loading city list') errors = set() for i in ['1', '2']: with open('cities/worldcitiespop' + i + '.csv', newline='') as csvfile: datareader = csv.reader(csvfile, delimiter=',') next(datareader) # skip the header row for one in datareader: city_name_key = one[1].strip()[0:2] prev = cities.get(city_name_key) if (prev is None): prev = [] country_name = countries.get(one[0].upper()) if (country_name is None): errors.add(one[0].upper()) else: prev.append([one[1].lower(), one[2] + '(' + country_name + ')', float(one[5]), float(one[6])]) cities[city_name_key] = prev end = time.time() print("loaded city list with: ", (end - start), "sec") if (len(errors) > 0): print("the following country code was not found:") print(errors) def convert_city_data(): read_country_code() read_city_list() start = time.time() print('converting city list') output_dir = 'data/' os.makedirs(output_dir, exist_ok=True) for city_name_key in cities: with open(output_dir + city_name_key + '.csv', 'w', newline='') as csvfile: datawriter = csv.writer(csvfile, delimiter=',') values = cities.get(city_name_key) sorted_values = sorted(values, key=lambda item: item[0]) for one in sorted_values: datawriter.writerow(one) end = time.time() print("converted city list with: ", (end - start), "sec") convert_city_data()
caa078c65f99fcfe30088b1a5906e2cf751bc3f1
LucasFerreiraB/Teste
/guppe/Seção 7/Ordered_Dict.py
908
4.09375
4
""" Modulo Collections - OrderedDict # Ordem nao garantida em um dicionario dicio = {'a': 1, 'b': 2, 'c': 3, 'd': 4} print(dicio) for chave, valor in dicio.items(): print(f'chave={chave}: valor={valor}') OrderedDict -> É um dicionario, que nos garante a ordem da inserção dos elementos. # Fazendo import from collections import OrderedDict dicio = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) for chave, valor in dicio.items(): print(f'chaves = {chave}: valor = {valor}') """ from collections import OrderedDict # Entendendo a diferença entre Dict e OrderedDict # Dicionario Comum dict1 = {'a': 1, 'b': 2} dict2 = {'b': 2, 'a': 1} print(dict1 == dict2) # True, nao importa pro dicionario comum. # OrderedDict edict1 = OrderedDict({'a': 1, 'b': 2}) edict2 = OrderedDict({'b': 2, 'a': 1}) print(edict1 == edict2) # False, ja que a ordem do elementos importam para o OrderedDict
2433d96edb23d91661267f894851b2d5ebf4fa05
ant0nm/d13_assignment4_oop
/vampire.py
1,259
3.921875
4
class Vampire: """ A class representing a vampire. """ # class variables coven = [] # class methods @classmethod def create(cls, name, age): new_vampire = Vampire(name, age) cls.coven.append(new_vampire) return new_vampire @classmethod def sunrise(cls): print(len(cls.coven)) # list() creates a copy of the list passed to it # this way we can remove items from a list (mutate it) while iterating through it for vampire in list(cls.coven): if not (vampire.in_coffin and vampire.drank_blood_today): cls.coven.remove(vampire) @classmethod def sunset(cls): for vampire in cls.coven: vampire.drank_blood_today = False vampire.in_coffin = False # instance methods def __init__(self, name, age, in_coffin = False, drank_blood_today = False): # instance variables self.name = name self.age = age self.in_coffin = in_coffin self.drank_blood_today = drank_blood_today def __str__(self): return "Vampire: {}".format(self.name) def drink_blood(self): self.drank_blood_today = True def go_home(self): self.in_coffin = True
cfb3ab1044508afae6b84b559eacd6018db1f667
shuiblue/INTRUDE
/util/timeUtil.py
360
3.703125
4
from datetime import datetime def days_between_noTZ(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%d %H:%M:%S") d2 = datetime.strptime(d2, "%Y-%m-%d %H:%M:%S") return (d2 - d1).days def days_between(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%dT%H:%M:%SZ") d2 = datetime.strptime(d2, "%Y-%m-%dT%H:%M:%SZ") return abs((d2 - d1).days)
a2324c47605cceb1a02ab3edaec4f1ef4f00a73c
ThePro22/LearnPygame
/Python Challenges/Challenge 06 - Extention.py
499
4
4
#Challenge 6 - Extention week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] totalMoney = float(input("How much money did you have at the start of the week? £")) for day in range(5): cost = float(input("How much money did you spend on school dinner on " + week[day] +"? £")) totalMoney = totalMoney - cost if totalMoney < 0: totalMoney = -totalMoney print("\nYou do not have sufficient funds. You need £" + str(totalMoney), "more") else: print("\nYou have £" + str(totalMoney))
e1d4bca2e0c4884234c27f71c04782144408abf4
windy1/rdt-simulation
/rdt.py
9,697
3.5625
4
""" CS 265 programming assignment 2. Name: Walker J. Crouse Date: December 2018 In this assigment, you will implement a reliable data transfer protocol over an unreliable channel. Your solution should protect against packet loss and packet reorder. Corruption protection is not required. The protocol you implement should be pipelined and work many different window sizes. implementing the constructor, send_all, and recv_all functions of this file using the unreliable channel supported by udt.py. An example of how to use the udt.py functions, run receiver.py, then simultaneously run sender.py. All the code necessary for submission should be included in this file, and this should be the only file you submit. Please do not change the name of the file, but add your name and date in the lines above. You do not need to support full duplex communication with this assignment. It will be tested with a sender and receiver process that transmit a message from one to the other. Both the sender and the receiver will use this module. """ import time import socket from threading import Thread from udt import udt class rdt: handshake_code = -0xDEADBEEF def __init__(self, packet_loss=0, reorder=0, seg_size=16, wind=10, src_addr=None, dest_addr=None, server=False, timeout=1, buffer_size=1024): """ Initialize the reliable data connection in this function. Suggested udt functions: __init__, udt_send, udt_recv. INARGS: packet_loss : probability of a packet being lost. 0 ≤ pl ≤ 1 reorder : probability of packets being reordered. 0 ≤ r ≤ 1 seg_size : max body size of a segment in chars. We will test your code on a segment size of 16 wind : window size. src_addr : the tuple (self IP, self port) that identifies this socket dest_addr : the tuple (IP, port) that identifies the receiving socket server : true if the process will not begin the handshake (should already be on) RETURN: nothing - this is a void function """ self.buffer_size = buffer_size self.wind = wind self.packet_loss = packet_loss self.reorder = reorder self.dest_addr = dest_addr self.src_addr = src_addr self.timeout = timeout self.seg_size = seg_size self.is_server = server self.base_seg = 0 self.seg_num = -1 self.segments = None if self.is_server: self.bound_sock = udt(bind_args=self.src_addr) self.last_ack_out = -1 else: self.dest_sock = udt(self.packet_loss, self.reorder, self.src_addr, self.timeout) self.base_send_time = None ########################################################################### # # # == Client == # # # ########################################################################### def send_all(self, string): """ Given a large string (think hundreds or thousands of bytes) segment it into segments of seg_size, and reliably send them. This function should account for both packet loss and reorder. Suggested udt functions: udt_send, udt_recv INARGS: s : large string to be sent to a receiver RETURN: nothing - this is a void function """ print('[client] sending string of size %d' % len(string)) # perform handshake if not self._client_handshake(len(string)): return # begin listening for server acks ack_thread = Thread(target=self._ack_listener) ack_thread.start() # begin sending segments self.segments = list(self._segment_string(string)) while self.base_seg < len(self.segments): self._rewind(self.base_seg) print('[client] all segments sent') ack_thread.join() def _client_handshake(self, size): print('[client] sending handshake') try: self.dest_sock.udt_send(self.handshake_code, -1, 'size=%d' % size, self.dest_addr) seg_num, ack, body, addr = self.dest_sock.udt_recv(self.buffer_size) except socket.timeout: print('[client] ** handshake timed out **') return False if ack != self.handshake_code: print('[client] ** received invalid handshake code %d **' % ack) return False return True def _ack_listener(self): timeouts = 0 while self.base_seg < len(self.segments): try: self._recv_server_ack() timeouts = 0 except socket.timeout: timeouts += 1 print('[client] ** timed-out waiting for ack (#%d) **' % timeouts) def _recv_server_ack(self): # retrieve an incoming ack from the server seg_num, ack, body, addr = self.dest_sock.udt_recv(self.buffer_size) self.base_seg = ack + 1 if self.base_seg == self.seg_num: self.base_send_time = None else: self.base_send_time = time.time() print('[client] received ack #%d' % ack) def _rewind(self, seg_num): print('[client] rewind => seg #%d' % seg_num) self.seg_num = seg_num while self.seg_num < len(self.segments): if self._can_send_seg(self.seg_num): self.seg_num = self._send_seg(self.segments, self.seg_num) if self._has_timed_out(): self.seg_num = self._timeout() def _can_send_seg(self, seg_num): return seg_num < self.base_seg + self.wind def _send_seg(self, segments, seg_num, retry=0): # the segment is within the window and ready to be sent seg = segments[seg_num] print('[client] seg #%d => %s:%d (size = %d)' % (seg_num, self.dest_addr[0], self.dest_addr[1], len(seg))) try: self.dest_sock.udt_send(seg_num, -1, seg, self.dest_addr) except socket.timeout: print('[client] send of seg #%d timed-out (retry #%d)' % retry) return self._send_seg(segments, seg_num, retry + 1) # reset the timer if a "base" segment was just sent if seg_num == self.base_seg: self.base_send_time = time.time() return seg_num + 1 def _has_timed_out(self): return self.base_send_time is not None and time.time() - self.base_send_time > self.timeout def _timeout(self): print('[client] base seg #%d has timed out' % self.base_seg) self.base_send_time = time.time() return self.base_seg ########################################################################### # # # == Server == # # # ########################################################################### def recv_all(self): """ Receives a large string from a sender that calls s. When called, this function should wait until it receives all of s in order, then return all of s. Suggested udt functions: udt_recv, udt_send. INARGS: none RETURN: s : the large string received from a sender """ size = self._server_handshake() if size is None: return None string = '' while len(string) < size: string += self._recv_client_seg() return string def _server_handshake(self): # receive the incoming handshake seg_num, ack, body, addr = self.bound_sock.udt_recv(self.buffer_size) if seg_num != self.handshake_code: print('[server] ** received invalid handshake code %d **' % seg_num) return None # parse the body of the message header = body.split('=') if len(header) != 2: print('[server] ** received invalid header **') return None try: size = int(header[1]) except ValueError: print('[server] ** invalid size parameter in header **') return None # acknowledge the handshake try: udt().udt_send(-1, self.handshake_code, '', addr) except socket.timeout: print('[server] ** handshake ack timed-out **') return None return size def _recv_client_seg(self): # retrieve segment from the client seg_num, ack, body, addr = self.bound_sock.udt_recv(self.buffer_size) ack_out = seg_num # check the validity of the segment if ack_out != self.last_ack_out + 1: print('[server] ** received out-of-order segment %d **' % seg_num) ack_out = self.last_ack_out result = '' else: result = body # send back ack print('[server] received seg #%d, sending ack #%d' % (seg_num, ack_out)) try: udt().udt_send(-1, ack_out, '', addr) except socket.timeout: print('[server] ack #%d timed-out' % ack_out) # just allow the ack to be lost... self.last_ack_out = ack_out return result def _segment_string(self, string): for i in range(0, len(string), self.seg_size): yield string[i:i + self.seg_size]
f6a2c252f465db37cc009a26549c0daa1f31e2a5
TaineC/python_adv
/tkinter_gui.py
1,521
3.640625
4
import tkinter as tk import string import random #future improvements that I can do once I've gained more skills -- better syntax that I can only partially understand logically for now #function -- the print function for each password type could be integrted within the password generator function #a loop could be written for varying the range of which the string is defined def pw_weak(chars = string.ascii_letters+string.digits+string.punctuation): return ''.join([random.choice(chars) for n in range(5)]) def pw_medium(chars = string.ascii_letters+string.digits+string.punctuation): return ''.join([random.choice(chars) for n in range(10)]) def pw_strong(chars = string.ascii_letters+string.digits+string.punctuation): return ''.join([random.choice(chars) for n in range(15)]) weak = pw_weak() medium = pw_medium() strong = pw_strong() def show_weak(): print(weak) def show_medium(): print(medium) def show_strong(): print(strong) # the generator only allows for printing in the console instead of another GUI element root = tk.Tk() root.title('PASSWORD GENERATOR') root.geometry('300x300') label = tk.Label(root, text='Generate Password') label.pack() button1 = tk.Button(root, text='Weak', command=show_weak) button1.pack() button2 = tk.Button(root, text='Medium', command=show_medium) button2.pack() button3 = tk.Button(root, text='Strong', command=show_strong) button3.pack() #class: Popup #def __init__: #these all ask for self to be passed through root.mainloop()
be45c33bada9c2c0dce0d3963f5045cfabdc7b61
mini-ray/python
/ProjectStem/code3.2.1.py
90
3.9375
4
num = input("Enter a number: ") if float(num) > float(45.6): print ("Greater than 45.6")
60312668c58be539b17446d07b8fdbe6b5396412
ishantk/KnowledgeHutHMS2020
/Session4Q.py
2,344
3.640625
4
""" Multi Threading in Python :) """ import time import requests import json import threading """ class PrintingTask: def print_documents(self): for i in range(1, 11): print("[JOHN] Printing Document #{}".format(i)) time.sleep(1) class FetchNewsTask: def fetch_news(self): print("[NEWS] Fetching News...") api_key = "31c21508fad64116acd229c10ac11e84" url = "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey={}".format(api_key) time.sleep(10) response = requests.get(url) text = response.text print(text) print(type(text)) # converted JSON textual content as Python Dictionary data = json.loads(text) print(data) print(type(data)) print(data['totalResults']) print() for article in data['articles']: print(article['title']) print(article['author']) print() """ class PrintingTask(threading.Thread): # Override run from the Parent threading.Thread def run(self): for i in range(1, 11): print("[JOHN] Printing Document #{}".format(i)) time.sleep(1) class FetchNewsTask(threading.Thread): def run(self): print("[NEWS] Fetching News...") api_key = "31c21508fad64116acd229c10ac11e84" url = "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey={}".format(api_key) time.sleep(10) response = requests.get(url) text = response.text print(text) print(type(text)) # converted JSON textual content as Python Dictionary data = json.loads(text) print(data) print(type(data)) print(data['totalResults']) print() for article in data['articles']: print(article['title']) print(article['author']) print() def main(): print("Main Started") task1 = PrintingTask() task2 = FetchNewsTask() # task1.print_documents() task1.start() print() # task2.fetch_news() task2.start() print() for i in range(1, 11): print("[MAIN] Printing Document #{}".format(i)) time.sleep(1) print("Main Finished") if __name__ == '__main__': main()
5956b248b369fb4d1b01a08b6b4a0d3e21982ab1
kepengsen/study
/python/01/03.py
323
4.0625
4
#!/usr/local/bin/python3 num1,num2=-1,7 print('猜数字游戏!') while num1!=num2: num1=int(input('请输入一个数字')) if num1<num2: print('猜的数字小了。。。') elif num1>num2: print('猜的数字大了。。。') elif num1==num2: print('恭喜您!猜对了。')
ff332afd09bb1eef4115d1bfd332ac8a900af3d0
antondelchev/Advanced---Exams
/Numbers Search.py
532
3.65625
4
def numbers_searching(*args, info=None): if info is None: info = [] full_sequence = [int(el) for el in range(min(args), max(args) + 1)] info.append(*[el for el in full_sequence if el not in args]) duplicates = sorted(set([el for el in args if args.count(el) > 1])) info.append(duplicates) return info print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45, 44, 44, 48, 44, 48))
ccf34a70760195bfb5eef86930cfa2c438c7bd54
skshabeera/question-bank
/month.py
273
4.125
4
m=int(input("enter the number")) if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12: print(m," month number of days 31") elif m==4 or m==6 or m==9 or m==11: print(m,"month number of days 30") elif m==2: print(m,"month number if days 28") else: pass
200d496eacbc4be8c0229bcccd937ec7687e17f1
aahnik/mendi
/mendi/mendi.py
1,547
4.0625
4
"""Simple wrapper that helps you write a menu-driven program easily. > A menu-driven program is one, in which the user is provided a list of choices. > A particular action is done when the user chooses a valid option. > There is also an exit option, to break out of the loop. > Error message is shown on selecting a wrong choice. """ import os import sys from typing import Any, List from tabulate import tabulate def clear_screen() -> None: """Clear the current screen.""" input("ENTER to continue: ") # wait for user to see current screen if os.name == "posix": # for Linux and Mac os.system("clear") else: # for Windows os.system("cls") def end(): """Quit the program.""" print("Bye 🤗") sys.exit(0) def drive_menu(menus: List[Any], heading: str = "program") -> None: """Start the interactive menu driven program.""" table = [] menus.insert(0, end) for i, menu in enumerate(menus): desc = str(menu.__doc__).split("\n", 1)[0] row = [i, desc] table.append(row) menu_chart = f""" MENU for {heading} \n{tabulate(table,tablefmt='fancy_grid',headers=['Choice','Description'])} \n>>> """ choices = list(range(len(menus))) while True: clear_screen() try: choice = int(input(menu_chart)) assert choice in choices except: # pylint: disable=bare-except print(f"The choice must be an integer between {choices}") else: menus[choice]()
8a4535b44dce243b0ab23ffeac877c64cc4580e6
tisage/cs50
/pset6/sentiments/smile
1,133
3.515625
4
#!/usr/bin/env python3 import os import sys from analyzer import Analyzer from termcolor import colored def main(): # ensure proper usage of command line argument if len(sys.argv) != 2: sys.exit("Usage: ./smile word") # absolute paths to lists positives = os.path.join(sys.path[0], "positive-words.txt") # positives = ./positive-words.txt negatives = os.path.join(sys.path[0], "negative-words.txt") # instantiate analyzer analyzer = Analyzer(positives, negatives) # it uses "class" in python. # It is similar to structure in C but provides method of a structure # analyze word and retrieves score score = analyzer.analyze(sys.argv[1]) # passing the second argument to analyzer.analyze() method, #the return value was assigned to score if score > 0.0: # positive case print(colored(":)", "green")) # prints result, colored accordingly elif score < 0.0: print(colored(":(", "red")) else: print(colored(":|", "yellow")) if __name__ == "__main__": main()
07162239aad2a996a080f5e7b8ba2120d485a2d1
m4tti1/foundations-sample-website
/color_check/controllers/get_color_code.py
1,299
3.65625
4
# This file should contain a function called get_color_code(). # This function should take one argument, a color name, # and it should return one argument, the hex code of the color, # if that color exists in our data. If it does not exist, you should # raise and handle an error that helps both you as a developer, # for example by logging the request and error, and the user, # letting them know that their color doesn't exist. import json import logging logging.basicConfig(level=logging.DEBUG, filename='color_check/color_check.log', filemode='w', format='%(asctime)s - %(name)s - %(levelname)s -%("hello")s') def get_color_code(color_name): # this is where you should add your logic to check the color. # Open the file at data/css-color-names.json, and return the hex code # The file can be considered as JSON format, or as a Python dictionary. json_file = open("color_check/data/css-color-names.json") dict_data = json.load(json_file) if color_name in dict_data.keys(): return dict_data[color_name] else: return " is not a css color!" ##maybe change this return try: return dict_data[color_name] except KeyError as error: return " is not a css color!" logging.exception("Exception occurred") #recommit
0da86d28be945035e82d7b7ec83c0dce0c0d6b62
mrmaxguns/Misc-Python
/old/password-gen-v3.0.1.py
2,575
3.859375
4
''' Password Generator V3.0.l Maxim Rebguns ''' import random from proofread import * err = "Please select a natural number!" def run(): def generate(c, cap, numb, x): first = random.randint(1,2) if first == 1: vowel = True if first == 2: vowel = False passw = [1] if cap: passw.append(2) if numb: passw.append(3) if x: passw.append(4) caps_v = "AEIOU" caps_c = "QWRTYPSDFGHJKLZXCVBNM" lower_v = "aeiou" lower_c = "qwrtypsdfghjklzxcvbnm" num = "1234567890" xtra = "!@#$%^&*()_-+={}[]:;'<>?,./" password = [] print("") for _ in range (c): char = random.choice((passw)) if char == 1: if vowel == True: password.append(random.choice(lower_v)) vowel = False if vowel == False: password.append(random.choice(lower_c)) vowel = True if char == 2: if vowel == True: password.append(random.choice(caps_v)) vowel = False if vowel == False: password.append(random.choice(caps_c)) vowel = True if char == 3: password.append(random.choice(num)) if char == 4: password.append(random.choice(xtra)) return ''.join(password) #amount = int(input("How many characters do you want in your password? ")) amount = integer_check("How many characters do you want in your password? ", "x", "err", 1, err, err) if amount > 10000: areyousure = input("WARNING! Are you sure you want to proceed? This long of a password may slow your computer. Continue? Type n to quit. ") if areyousure == "n": quit() capitals1 = input("Do you want to include capitals? y/n ") if "y" in capitals1: capitals = True else: capitals = False numbers1 = input("Do you want to include numbers? y/n ") if "y" in numbers1: numbers = True else: numbers = False xtrachars1 = input("Do you want to include other characters? y/n ") if "y" in xtrachars1: xtrachars = True else: xtrachars = False print(generate(amount, capitals, numbers, xtrachars)) print("Welcome to password generator Version 3") run()
a2f92a85fe6b25d5ba95f249c0b6d4c62c3a7e7c
aksampath123/Python_Development_Projects
/python_beginner/function_list.py
667
4.0625
4
shopping_list = [] def show_help(): print("Enter the items/amount for your shopping list") print("Enter DONE once you have completed the list, Enter Help if you require assistance") def add_to_list(item): shopping_list.append(item) print("Added! List has {} items.".format(len(shopping_list))) def show_list(): print("Here is your list") for item in shopping_list: print(item) show_help() while True: new_item = input("item>") if new_item == 'DONE': break elif new_item == 'HELP': show_help() continue elif new_item == 'SHOW': show_list() continue else: add_to_list(new_item) continue show_list()
266663e673999577bb0cfb876dc5dafcb32eb910
sarahmaeve/lpthw
/guess1.py
965
4.0625
4
# inspired by https://www.youtube.com/watch?v=O17TzRU0Pss # but with a function. # this can be improved a lot. import random def analyze_guess(guess, target): guess = int(guess) if not type(guess) == 'int': msg = "I don't understand that." if guess < target: msg = "Too low!" elif guess > target: msg = "Too high!" elif guess == target: msg = "Correct! You win!" else: msg = "Huh?" return msg name = input("Hello, what is your name? ") if not name: name = 'Nemo' print(f"{name}, I am thinking of a number between one and ten.") number = random.randint(1,10) guesses = 0 while guesses < 3: print(f"What is your guess, {name}?") user_guess = input("> ") analysis = analyze_guess(user_guess, number) print(analysis) if analysis == "Correct! You win!": break else: guesses += 1 else: print(f"Aww, out of guesses. I win! I was thinking of {number}.")
2118f35dcad1d385af9cd0b13c273662f7c846eb
Cgalvispadilla/reto_sofka
/Juego.py
3,232
3.5
4
from Jugador import * from Conductor import * from Carro import * from Carril import * from Pista import * import random class Juego(): def __init__(self) -> None: self.__id=(random.randint(1, 100000)) def get_id(self): return self.__id def min_jugadores(self,num:int): if num>=3: return True else: return False def cant_jugadores(self): n = input(f'Ingrese la el numero de jugadores (debe ser mayor a 3): ') while(not n.isdigit()): print(f"el dato {n} ingresado no es un numero") n = input(f'Ingrese la el numero de jugadores (debe ser mayor a 3): ') while self.min_jugadores(int(n))==False: n = input('Ingrese la cantidada de jugadores (minimo deben ser 3): ') return int(n) def crear_jugadores(self,cant_jugadores:int): lista_jugadores=[] for i in range(cant_jugadores): nombre="jugador "+str(i+1) j=Jugador(nombre) lista_jugadores.append(j) return lista_jugadores def crear_pista(self,cantidad_jugadores: int): n = input(f'Ingrese la el numero de Kilometros de la pista: ') while(not n.isdigit()): print(f"el dato {n} ingresado no es un numero") n = input(f'Ingrese la el numero de Kilometros de la pista: ') p = Pista(random.randint(1, 100),cantidad_jugadores, int(n)) return p def crear_carros(self,jugadores: list,pista: Pista): lista_carros=[] for i in range(len(jugadores)): c = conductor(jugadores[i].get_nombre()) carro= Carro(c.getNombre()) carril= Carril(carro,(i+1),pista.kilometros) #el antepenultimo cero hace referencia a la distancia que ha recorrido el carro lista_carros.append([pista.get_id(),carro,carril.get_posicion(),carril.get_tamanio(),0]) return lista_carros def movimiento_del_carro(self, carro): movimiento= random.randint(1, 6)*100 return movimiento def info_carro(self, carro): texto=f" Pista: {carro[0]}, Conductor: {str(carro[1].get_conductor())}, Carril: {carro[2]},distacia recorrida: {carro[4]}" print(texto) def configurar_juego(self): cant= self.cant_jugadores() lista_jugadores=self.crear_jugadores(cant) pista=self.crear_pista(len(lista_jugadores)) carros= self.crear_carros(lista_jugadores,pista) return carros def iniciar_juego(self): carros=self.configurar_juego() cont,cont2=0,1 listaGanadores=[] while True: for carro in carros: if carro[-1]>=carro[-2]: cont+=1 listaGanadores.append(carro) carros.remove(carro) carro[-1]+= self.movimiento_del_carro(carro) print(f"-----movimiento {cont2}-----") self.info_carro(carro) cont2+=1 if cont==3: break if cont==3: break return listaGanadores
d00d24585038e7d6788e9c4d630bb6048802750f
jacksarick/My-Code
/Python/python challenges/euler/021_amicable_nums.py
595
3.5625
4
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). # If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers. # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. # Evaluate the sum of all the amicable numbers under 10000. k = {n:sum([x for x in range(1, n) if n%x==0]) for n in range(1, 10000)} print [x for x,y in k.iteritems() if k[y] == x]
1488f63b2f8723658ecc4758f6230294b1dec5e6
tnaswin/PythonPractice
/Aug21/file_io.py
791
4.09375
4
with open('app.log', 'w') as f: #first line f.write('my first file\n') #second line f.write('This file\n') #third line f.write('contains three lines\n') with open('app.log', 'r') as f: content = f.readlines() for line in content: print line #Read From A File In Python print "Read From A File In Python" with open('app.log', 'w') as f: #first line f.write('my first file\n') #second line f.write('This file\n') #third line f.write('contains three lines\n') f = open('app.log', 'r') print f.read(10) # read the first 10 data #'my first f' print f.read(4) # read the next 4 data #'ile\n' print f.read() # read in the rest till end of file #'This file\ncontains three lines\n' print f.read() # further reading returns empty sting #''
9db93618766ecfda89102ac1839716e457b7f167
alaminbhuyan/Python-solve
/problem/Finding the percentage.py
652
3.953125
4
Finding the percentage Dict = {} # num = int(input('enter num of elements: ')) # for i in range(num): # keys = input('Enter your keys: ') # values = list(map(float,input('enter your values: ').split())) # Dict.update({keys:values}) # #print(Dict) # for a in Dict.values(): # total = sum(a)/3 # Dict.update({keys:total}) # name = input('Enter the name: ') # print(Dict[name]) n = int(input()) Dictonary = {} for _ in range(n): line = input().split() name,mark = line[0],line[1:] mark = map(float,mark) Dictonary[name] = mark key = input() query_mark = Dictonary[key] total = sum(query_mark)/3 print("%.2f" % total)
3b3151a5e585a475b6880590b0d2a15b0d877fcc
Osheah/hospfcs2021
/semester1/week06/readsNumber.py
356
4.21875
4
# program read in a text file from an existing text # helen oshea # 20210224 fileName = 'count.txt' # location of the file def read_number(): # function to read in the text with open(fileName) as f: num = int(f.read()) # convert the number string to an integer return num # return the integer print(read_number()) # call and print the function
1a33a3181f104759dc583e408c5405286aab0e19
Bhagyashri1811/practised
/quick sort.py
596
3.71875
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 26 19:39:41 2021 @author: Bhagyashri """ def partition(arr,low,high): pivot=arr[high] pindex=low for j in range(low,high): if(arr[j]<pivot): arr[j],arr[pindex]=arr[j],arr[pindex] pindex=pindex+1 arr[pindex],arr[high]=arr[high],arr[pindex] return pindex def quicksort(arr,low,high): pindex=partition(arr, low, high) quicksort(arr, low, pindex-1) quicksort(arr, pindex+1, high) arr=[9,5,38,22,4,6,223,59,2239,0] n=len(arr) quicksort(arr,0,n-1) print(arr)
06d8f2b680bccb7906a9648ec841d096f6c95f8e
ostrowto/python
/Py_Math_Examples/is_Prime/prime_2_range.py
503
3.609375
4
# prime_2_range.py import sys list_of_primes = [] input_to_parameter = int(input('End parameter: ')) end_parameter = input_to_parameter p = 2 while p <= end_parameter: is_prime = True for i in range(2, p): if p % i == 0: is_prime = False break if is_prime == True: list_of_primes.append(p) print(p, end = ', ') p = p + 1 sys.stdout = open('Your_Prime_Numbers.txt', 'w') print('\n\nYour prime list is:', list_of_primes) sys.stdout.close()
6e1352d79ea1e6af0b8b451621ded2a2bdb3febe
RobertNguyen125/Datacamp---manipulatingDataFrame
/1_extractingTransformingData/6_filteringPractise.py
930
3.703125
4
import pandas as pd import numpy as np election = pd.read_csv('/Users/apple/desktop/manipulatingDataFrames/dataset/pennsylvania2012_turnout.csv', index_col='county') # create boolean array: high_turnout where the turnout rate is > 70 high_turnout = election['turnout'] > 70 # filter the df high_turnout_df = election[high_turnout] # print(high_turnout_df) # filtering columns using other columns too_close = election['margin']<1 election.loc[too_close, 'winner'] = np.nan # print(election) # FILTERING USING NANS titanic = pd.read_csv('/Users/apple/desktop/manipulatingDataFrames/dataset/titanic.csv') df =titanic[['age', 'cabin']] print(df.shape) # dropna(how='all') drop columns w/ 0 values print(df.dropna(how='all').shape) # dropna(how='any') select columns w/ any non-0 print(df.dropna(how='any').shape) # drop columns with less than 1000 non-missing values print(titanic.dropna(thresh=1000, axis='columns').info())
2947913b5b0d96742c91a7a11169b446c639fd72
antonpigeon/Inf_2021_python
/Lab1 python/Exercize 14/Exercize 14/Exercize_14.py
130
3.671875
4
import turtle turtle.shape('turtle') n = 11 for i in range(n): turtle.forward(100) turtle.left(180 - 180 / n)
ad6ffb9bc71fc4743f8fddb54f6d60b63d218da9
xiaolinz1987/Algorithm
/Python/utils/priorityqueue.py
1,483
3.75
4
class MyPriorityQueue: def __init__(self): self.array = [] self.size = 0 def __up_adjust(self): child_index = self.size - 1 parent_index = (child_index - 1) // 2 temp = self.array[child_index] while child_index > 0 and temp > self.array[parent_index]: self.array[child_index] = self.array[parent_index] child_index = parent_index parent_index = (parent_index - 1) // 2 self.array[child_index] = temp def __down_adjust(self): child_index = 1 parent_index = 0 temp = self.array[parent_index] while child_index < self.size: if child_index + 1 < self.size and self.array[child_index + 1] > self.array[child_index]: child_index += 1 if temp >= self.array[child_index]: break self.array[parent_index] = self.array[child_index] parent_index = child_index child_index = child_index * 2 + 1 self.array[parent_index] = temp def enqueue(self, element): self.array.append(element) self.size += 1 self.__up_adjust() def dequeue(self): if self.size < 0: raise Exception("Empty queue!") head = self.array[0] self.array[0] = self.array[self.size - 1] self.size -= 1 self.__down_adjust() return head
fcc7e0aa11a92b2b03492ff61a44fc309713b786
pchauha7/Hand-Classification-and-Search-System
/Phase-3/Code/decisiontreeclassifier.py
5,075
3.65625
4
import numpy as np class DecisionTreeClassifier: #Initialization def __init__(self, max_depth=None): self.max_depth = max_depth #fit transform def fit(self, X, y): """Build decision tree classifier.""" self.n_classes_ = len(set(y)) # classes are assumed to go from 0 to n-1 self.n_features_ = X.shape[1] self.tree_ = self._grow_tree(X, y) #predict single data def _predict(self, inputs): node = self.tree_ while node.left: if inputs[node.feature_index] < node.threshold: node = node.left else: node = node.right return node.predicted_class #predict labels def predict(self, X): """Predict class for X.""" return [self._predict(inputs) for inputs in X] #gini mpurity def _gini(self, y): """Compute Gini impurity of a non-empty node. Gini impurity is defined as 1 - Σ p^2 over all classes, with p the frequency of a class within the node. """ m = y.size return 1.0 - sum((np.sum(y == c) / m) ** 2 for c in range(self.n_classes_)) def bestsplit(self, X, y): # finds best split by computing information gain m = y.size if m <= 1: return None, None num_parent = [np.sum(y == c) for c in range(self.n_classes_)] #class count best_gini = self._gini(y) best_idx, best_thr = None, None # Loop through all features. for idx in range(self.n_features_): # Sort data along selected feature. thresholds, classes = zip(*sorted(zip(X[:, idx], y))) # We could actually split the node according to each feature/threshold pair # and count the resulting population for each class in the children, but # instead we compute them in an iterative fashion, making this for loop # linear rather than quadratic. num_left = [0] * self.n_classes_ num_right = num_parent.copy() for i in range(1, m): # possible split positions c = classes[i - 1] num_left[c] += 1 num_right[c] -= 1 gini_left = 1.0 - sum( (num_left[x] / i) ** 2 for x in range(self.n_classes_) ) gini_right = 1.0 - sum( (num_right[x] / (m - i)) ** 2 for x in range(self.n_classes_) ) # The Gini impurity of a split is the weighted average of the Gini impurity of the children. gini = (i * gini_left + (m - i) * gini_right) / m # continues when same point if thresholds[i] == thresholds[i - 1]: continue if gini < best_gini: best_gini = gini best_idx = idx best_thr = (thresholds[i] + thresholds[i - 1]) / 2 # midpoint return best_idx, best_thr def _grow_tree(self, X, y, depth=0,l=True): """Build a decision tree by recursively finding the best split.""" # Population for each class in current node. The predicted class is the one with # largest population. num_samples_per_class = [np.sum(y == i) for i in range(self.n_classes_)] predicted_class = np.argmax(num_samples_per_class) node = Node( gini=self._gini(y), num_samples=y.size, num_samples_per_class=num_samples_per_class, predicted_class=predicted_class, ) if(depth == 0 and l == True): print("Root Node") elif l : print("Left Node") else : print("right Node") print("num of sample per class : " , node.num_samples_per_class) print("predicted_class : " , node.predicted_class) # Split recursively until maximum depth is reached. if depth < self.max_depth: idx, thr = self.bestsplit(X, y) if idx is not None: indices_left = X[:, idx] < thr X_left, y_left = X[indices_left], y[indices_left] X_right, y_right = X[~indices_left], y[~indices_left] node.feature_index = idx node.threshold = thr print("selected feature : ", node.feature_index) print("Threshold value for selected feature : ", node.threshold) print("\n") node.left = self._grow_tree(X_left, y_left, depth + 1,True) node.right = self._grow_tree(X_right, y_right, depth + 1,False) return node class Node: def __init__(self, gini, num_samples, num_samples_per_class, predicted_class): self.gini = gini self.num_samples = num_samples self.num_samples_per_class = num_samples_per_class self.predicted_class = predicted_class self.feature_index = 0 self.threshold = 0 self.left = None self.right = None
886ad0dc409c7ed8ad80381a96e763e32eb9f127
yddong/Py3L
/src/Week2/for-test1.py
310
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- mytext = "Hello you world how are you" mycounts = {} for character in mytext: print(character) print("----") if character in mycounts: mycounts[character] = mycounts[character] + 1 else: mycounts[character] = 1 print(mycounts)
61a49f9d7960a550f6b7ac938a942fd46a6491e9
n8jhj/Parakletos
/Game.py
2,995
3.515625
4
import Player import Board import Charactor import pdb class Game(object): def __init__(self, DISPSURF): self.surf = DISPSURF # display surface game will be drawing on self.board = Board.Board(self) # Board on which Game is played self.plyrs = [] # Players list self.state = 'meatState' # setupState or meatState self.chgState = False # whether the state has changed self.selection = None # current selection to be displayed in HUD self.setup() def setup(self): # Add Players and Charactors self.addPlayer(1) self.addChar(self.plyrs[0], 3, 0) self.plyrs[0].chars[0].paintLOS(1) def draw(self): self.board.draw() # draw board for i in range(len(self.plyrs)): # draw players self.plyrs[i].draw() def addPlayer(self, num): self.plyrs.append(Player.Player(self, 'Player ' + str(num))) def addChar(self, player, x, y): # Create a Charactor. Add it to self, player, and the board. newChar = Charactor.Charactor(player) player.addChar(newChar) self.board.addChar(newChar,x,y) def clickOnChar(Charactor): """ if another Charactor is selected: if they're on the same team and in pair range: pair up! return if they're not on the same team and in attack range: attack! return select the clicked Charactor """ def clickOnTile(Tile): """ if a Charactor is selected and in move range: move that Charactor to the clicked Tile otherwise: display properties of the clicked Tile """ def clickOnItem(Item): """ if a Charactor is selected and in pickUp range: have that Charactor pickUp the Item """ def clickOnPlayer(Player): """ display the Player's stats """ def clickOnNothing(): """ display name of the game in HUD """ def keyPressUp(self): # handle UP key press self.plyrs[0].chars[0].move('ahead') def keyPressDown(self): # handle DOWN key press self.plyrs[0].chars[0].move('behind') def keyPressLeft(self): # handle LEFT key press self.plyrs[0].chars[0].turn('left') def keyPressRight(self): # handle RIGHT key press self.plyrs[0].chars[0].turn('right') def keyPressW(self): # handle W key press self.plyrs[0].chars[0].move('ahead') def keyPressS(self): # handle S key press self.plyrs[0].chars[0].move('behind') def keyPressA(self): # handle A key press self.plyrs[0].chars[0].move('left') def keyPressD(self): # handle D key press self.plyrs[0].chars[0].move('right')
89c048b5908d0fd6c471f66ff58e58eecc17bd71
karthi031000/Freshworks
/freshworks/code.py
1,693
3.9375
4
import threading from threading import* import time d={} # d is a dictionary used to store key-value datastore # Create operation def create(key,value,timeout=0): if key in d: print("error: Key already exist") else: if(key.isalpha()): if len(d)<(1024*1024*1024) and value<=(16*1024*1024): if timeout==0: l=[value,timeout] else: l=[value,time.time()+timeout] if len(key)<=32: d[key]=l else: print("error: Memory limit exceeded!! ") else: print("error: Invalid key_name!! key_name must contain only alphabets and no special characters or numbers") # Read operation def read(key): if key not in d: print("error: Key doesn't exist. Please enter a valid key") else: b=d[key] if b[1]!=0: if time.time()<b[1]: stri=str(key)+":"+str(b[0]) print(stri) else: print("error: time-to-live of",key,"has expired") else: stri=str(key)+":"+str(b[0]) return stri # Delete operation def delete(key): if key not in d: print("error: key doesn't exist. Please enter a valid key") else: b=d[key] if b[1]!=0: if time.time()<b[1]: del d[key] print("key successfully deleted") else: print("error: time-to-live of",key,"has expired") else: del d[key] print("key",key,"successfully deleted")
885780e5663418b8db7a814e5396cde21c295258
Rachel-99/Lab6-Seguridad
/elgamal.py
946
3.640625
4
import random from math import pow a=random.randint(2,10) #To fing gcd of two numbers def gcd(a,b): if a<b: return gcd(b,a) elif a%b==0: return b else: return gcd(b,a%b) #For key generation i.e. large random number def gen_key(q): key= random.randint(pow(10,20),q) while gcd(q,key)!=1: key=random.randint(pow(10,20),q) return key def power(a,b,c): x=1 y=a while b>0: if b%2==0: x=(x*y)%c; y=(y*y)%c b=int(b/2) return x%c #For asymetric encryption def encryption(msg,q,h,g): ct=[] k=gen_key(q) s=power(h,k,q) p=power(g,k,q) for i in range(0,len(msg)): ct.append(msg[i]) for i in range(0,len(ct)): ct[i]=s*ord(ct[i]) return ct,p #For decryption def decryption(ct,p,key,q): pt=[] h=power(p,key,q) for i in range(0,len(ct)): pt.append(chr(int(ct[i]/h))) return pt
d3ddae3ac90d709f6e340b363be93bb9ef8f6b83
vitorsv1/CamadaFisica
/PARTE 1/Projeto_6/exemplo.py
1,066
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 14 14:57:54 2018 @author: rcararrto """ #exemplos de manipulacao de bits def main(): q= 0b10011 data = 0b101101010000 shifitado = data >> 7 XorResultado = shifitado ^ q for b in range(1): print(" resultado em binario {}" .format(bin(XorResultado))) print(" numero de casas {}" .format(-2 + len(bin(XorResultado)))) print(" teste xor {}" .format(bin(XorResultado)[0])) print(" teste xor {}" .format(bin(XorResultado)[1])) print(" resultado em int {}" .format(XorResultado)) teste =bin(int.from_bytes(b"hello world", byteorder="big")).strip('0b') print ("Como sequencia de bits {}" .format(teste) ) teste =bin(int.from_bytes(bytes([0xFA]), byteorder="big")).strip('0b') print ("Como sequencia de bits {}" .format(teste) ) print(len(teste)) print(teste[5]) #so roda o main quando for executado do terminal ... se for chamado dentro de outro modulo nao roda if __name__ == "__main__": main()
45c81b8bb2b509061fb79a4d15caf8a4daa0b4b1
kajrud/begin-to-code-python
/simple-stuff/EG3-02 Głęboki namysł.py
203
3.640625
4
import time print("Pobawmy się w dodawanie") num1 = int(input("Podaj liczbę: ")) num2 = int(input("Podaj drugą liczbę: ")) suma = num1 + num2 print("Myślę, myślę... ") time.sleep(10) print(suma)
ad2c1017ab88a2cceec3ae7cfc012cec490db61f
transducens/gourmet-ua
/jw/filter-cld3.py
2,115
3.65625
4
import sys import cld3 import argparse oparser = argparse.ArgumentParser(description="Tool that reads a list of pairs of segments from the standard input in TSV " "format, this is: a pair of segments per line, segments separated by tabs. The script will discard any pair for " "which the langauge detector CLD3 identifies that one of the segments is not in the language expected, or if the " "identification is not reliable.") oparser.add_argument("--lang1", help="2-character code of the language to be detected by CLD3 in the first field of the input (for some languages, it could be a 3-character code; see CLD3 documentation for more information)", dest="lang1", required=True) oparser.add_argument("--lang2", help="2-character code of the language to be detected by CLD3 in the second fields of the input (for some languages, it could be a 3-character code; see CLD3 documentation for more information)", dest="lang2", required=True) oparser.add_argument("-v", "--verbose", help="If this option is enabled, the script outputs to the error output messages describing why a pair of segments has been discarded", action="store_true", default=False) options = oparser.parse_args() for line in sys.stdin: line=line.rstrip("\n") lines=line.split("\t") line1=lines[0].strip() lang1=cld3.get_language(line1) line2=lines[1].strip() lang2=cld3.get_language(line2) if len(line1) == 0 or len(line2) == 0: continue if lang1.is_reliable != True: if options.verbose: sys.stderr.write("LANG1 not reliable: "+str(lang1)+"\t"+line1+"\n") elif lang1.language!=options.lang1: if options.verbose: sys.stderr.write("LANG1 not "+options.lang1+": "+str(lang1)+"\t"+line1+"\n") elif lang2.is_reliable != True: if options.verbose: sys.stderr.write("LANG2 not reliable: "+str(lang2)+"\t"+line2+"\n") elif lang2.language!=options.lang2: if options.verbose: sys.stderr.write("LANG2 not "+options.lang2+": "+str(lang2)+"\t"+line2+"\n") else: print(line.strip())
443447b46851e4b2434eeef0dd3e04d613998514
kschlough/interview-prep
/valid_palindrome.py
1,040
4.09375
4
# Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # Example 1: # Input: s = "A man, a plan, a canal: Panama" # Output: true # Explanation: "amanaplanacanalpanama" is a palindrome. # Example 2: # Input: s = "race a car" # Output: false # Explanation: "raceacar" is not a palindrome. # Constraints: # 1 <= s.length <= 2 * 105 # s consists only of printable ASCII characters. class Solution: def isPalindrome(self, s: str) -> bool: arr_s = [] for char in s.lower(): if char.isalnum(): arr_s.append(char) print(arr_s) original = "".join(arr_s) arr_s.reverse() print(arr_s) reverse_arr = "".join(arr_s) if original == reverse_arr: return True else: return False # pseudocode # use .strip to remove white spaces and special characters # all .lower() too # if s == s.reverse() then it's a palindrome
51281bf0e03da216ab1b53d58008a7b0d2315b95
Azim-Islam/CSE208-Algorithm-Lab
/5/problem_1.py
1,814
4
4
import random #merging 3 of the sub-array def merge(arr, low, mid1, mid2, high): left_array = arr[low - 1 : mid1] mid_array = arr[mid1: mid2 + 1] right_array = arr[mid2 + 1 : high] left_array.append(float('inf')) #Inserting these because the array may not be properly divisible by 3 mid_array.append(float('inf')) right_array.append(float('inf')) index_left = 0 #Setting all indexs to start from 0 index_mid = 0 index_right = 0 print(left_array, mid_array, right_array) #merging 3 of the sub arrays. for i in range(low-1, high): #find the minimum values then assining them at array minimum = min([left_array[index_left], mid_array[index_mid], right_array[index_right]]) if minimum == left_array[index_left]: arr[i] = left_array[index_left] index_left += 1 elif minimum == mid_array[index_mid]: arr[i] = mid_array[index_mid] index_mid += 1 else: arr[i] = right_array[index_right] index_right += 1 #dividing the array into 3 sub arrays. base case if atleast one of the sub-array has atleast one element. def merge_sort(arr, low, high): if len(arr[low -1: high]) < 2: return arr else: mid1 = low + ((high - low) // 3) mid2 = low + 2 * ((high-low) // 3) merge_sort(arr, low, mid1) merge_sort(arr, mid1+1, mid2 + 1) merge_sort(arr, mid2+2, high) merge(arr, low, mid1, mid2, high) return arr arr = random.sample(range(1, 20), 15) #arr = [1,9,2,0,1,0,2,6] print("-"*50) print("Current array ", arr) print("-"*50) low = 1 #low starting from 1 high = len(arr) #length of array print(merge_sort(arr, low, high)) print("-"*50) print("Sorted array ", arr)
313db8557bd7633bbcbe1398245ecd017ec47252
artheadsweden/New_Courses_2020
/Python_Fundamentals/04_Variables_And_Data_Types/05 Strings Bytes and ByeArrays/03 Strings and Unicode.py
824
3.875
4
import sys def main(): # Since Python 3.0 all strings are stored in Unicode # Default Python will use UTF-8 message = "This is a Unicode string. See here: 你好." print(message) # Also identifiers can be in Unicode 你好 = 'Hello' print(你好) msg1 = 'AB' msg2 = 'ÅÄ' msg3 = '你好' print(sys.getsizeof(msg1)) print(sys.getsizeof(msg2)) print(sys.getsizeof(msg3)) # We can use character names to represent Unicode characters message = "\N{GREEK SMALL LETTER PI}" print(message) # Or we can use a 16-bit hex value message = '\u03C0' print(message) # Or a 32-bit hex value message = '\U000003C0' print(message) # We can even have emoji's message = '\U0001F920' print(message) if __name__ == '__main__': main()
90e9beefe021c308dc8d1517f75e1bdd4aa0b1f5
jeongukjae/terminal-palette
/example.py
2,170
3.515625
4
from terminal_palette import Palette palette = Palette() print( palette.black('Hello, World!') + palette.red('Hello, World!') + palette.green('Hello, World!') + palette.yellow('Hello, World!') + palette.blue('Hello, World!') + palette.magenta('Hello, World!') + palette.cyan('Hello, World!') + palette.white('Hello, World!')) print( palette.bright_black('Hello, World!') + palette.bright_red('Hello, World!') + palette.bright_green('Hello, World!') + palette.bright_yellow('Hello, World!') + palette.bright_blue('Hello, World!') + palette.bright_magenta('Hello, World!') + palette.bright_cyan('Hello, World!') + palette.bright_white('Hello, World!')) for i in range(4): string_for_print = "" for j in range(8): g = 8 * (i * 8 + j) string_for_print += palette.rgb(g, g, g)('Hello, World!') print(string_for_print) palette = Palette() print( palette.bg_black('Hello, World!') + palette.bg_red('Hello, World!') + palette.bg_green('Hello, World!') + palette.bg_yellow('Hello, World!') + palette.bg_blue('Hello, World!') + palette.bg_magenta('Hello, World!') + palette.bg_cyan('Hello, World!') + palette.bg_white('Hello, World!')) print( palette.bg_bright_black('Hello, World!') + palette.bg_bright_red('Hello, World!') + palette.bg_bright_green('Hello, World!') + palette.bg_bright_yellow('Hello, World!') + palette.bg_bright_blue('Hello, World!') + palette.bg_bright_magenta('Hello, World!') + palette.bg_bright_cyan('Hello, World!') + palette.bg_bright_white('Hello, World!')) for i in range(4): string_for_print = "" for j in range(4): g = 16 * (i * 4 + j) string_for_print += palette.bg_rgb(g, g, g)('Hello, World!') print(string_for_print) palette = Palette() print( palette.bold('Hello, World!') + palette.underline('Hello, World!') + palette.reversed('Hello, World!')) palette1 = Palette() palette2 = Palette() palette3 = Palette() print( palette1.red('Hello, World!' + palette2.blue( 'Hel' + palette3.black.bg_cyan.underline('lo, ') + 'World!') + 'Hello, World!'))
a43f41f281284a7d4a89ea197ba342d719a8943a
haeke/datastructure
/find-a-string.py
466
3.734375
4
# def count_substring(string, sub_string): #make sure string isn't smaller than one but not greater than 200 total = 0 #make sure it is in lower case string = string.lower() if( 1 <= len(string) <= 200): for i in range(0, len(string) - len(sub_string) + 1): if string[i:i+len(sub_string)] == sub_string: total += 1 return total else: return None print count_substring("Edwined", "ed")
2f694c787cbf0a2efd60b3afbae1c6bc89468d07
Ninosauleo/Python
/Cryptology/Vault/RSAdecr.py
2,628
3.703125
4
from Crypto.Hash import SHA512 from Crypto.PublicKey import RSA from Crypto import Random from collections import Counter from Tkinter import Tk from tkFileDialog import askopenfilename import ast import os import tkMessageBox import Tkinter import tkSimpleDialog import tkMessageBox fileDir = os.path.dirname(os.path.realpath('__file__')) def ask_user(prompt, command): root = Tkinter.Tk() var = tkSimpleDialog.askstring(str(prompt), str(command)) #print var return var def pop_window(title, message): tkMessageBox.showinfo(title, message) def select_file(): Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file return filename def hash_sha512(message): # SHA512 HASHING OF THE INPUT FILE h = SHA512.new() h.update(message) # digest() Return the binary (non-printable) digest of the message that has been hashed so far. # hexdigest() Return the printable digest of the message that has been hashed so far. signature = h.hexdigest() return signature def read_file_all(file_name): filename = os.path.join(fileDir, str(file_name)) with open(filename, 'r') as f: read_data = f.readlines() return read_data def main(): print "hello" # STEP TWO DECRYPTION: m = read_file_all("secret.txt") # REMOVE THE \n FROM ALL ELEMENTS IN THE LIST m = map(lambda s: s.strip(), m) pop_window("SELECT FILE FROM COMPUTER", "Please Select a file to decrypt") secret_file = select_file() # HASH THE FILE filename = open(secret_file, 'r').read() hashing = hash_sha512(filename) pop_window("SELECT PUBLIC KEY", "puKey.PEM from your computer") publicKeyName = select_file() f = open(publicKeyName, 'r') pubKeyObj = RSA.importKey(f.read()) # ENCRYPT THE MESSAGE FROM FILE n = [] signature2 = pubKeyObj.encrypt(str(hashing), 32) n.append("%s\n" % str(signature2)) n = map(lambda s: s.strip(), n) print "This is signature 2: " print n[0] f.close() # LOOP THROUGH ALL OF THE LIST index = 0 signatureFound = False while(index < (len(m) -1)): index += 1 if Counter(n[0]) == Counter(m[index]): signatureFound = True print "VERIFIED FILE" pop_window("VERIFIED FILE", "The file is verified, it has not changed!") break if signatureFound == False: pop_window("FILE not verified", "SORRY this file is not verified") print secret_file main()
e7d0e8a52d432acc383f63aa79680c0830289a37
transeos/hackerrank
/python/easy/list_comprehensions.py
717
3.625
4
#!/usr/bin/python3 # -*- Python -*- # #***************************************************************** # # hackerrank: https://www.hackerrank.com/challenges/list-comprehensions/problem # # WARRANTY: # Use all material in this file at your own risk. # # Created by Hiranmoy Basak on 18/05/18. # #***************************************************************** # if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) all_coordinates = []; for i in range(x + 1): for j in range(y + 1): for k in range(z + 1): if ((i + j + k) == n): continue coordinates = [i, j, k]; all_coordinates.append(coordinates); print (all_coordinates)
ba09804c435b584a397342f0f2745d434ec2166c
roflmaostc/Euler-Problems
/052.py
525
3.96875
4
#!/usr/bin/env python """ It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solve_problem(): """solves problem""" num = 0 while True: num += 1 for fac in range(2, 7): if set(str(num)) != set(str(num*fac)): break if fac == 6: return num print(solve_problem())
db0c54e4a8183292139ce4b18244f48b323d58e0
Cookieric/cs50
/pset6/hello.py
212
3.59375
4
import cs50 f=cs50.get_float() c=(5/9)*(f-32) print("{:.5f}".format(c)) char=cs50.get_char() if char == "Y" or char=="y": print("Yes") elif char == "N" or char=="n": print("No") else: print("error")
f7000c9b3b965f29e8853d29555e36bbc1a408cf
szhmery/leetcode
/Backtracking/17-LetterCombination.py
1,689
3.5625
4
from typing import List class Solution: # DFS, 递归 # 时间复杂度:O(2 ^ n) # 空间复杂度:O(n) def letterCombinations(self, digits: str) -> List[str]: number_mapping = [' ', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] result = [] if digits == '': return result self.findCombination(digits, number_mapping, 0, '', result) return result def findCombination(self, digits, mapping, index, string, res): if index == len(digits): res.append(string) return num = digits[index] letter = mapping[int(num)] for i in range(len(letter)): self.findCombination(digits, mapping, index + 1, string + letter[i], res) return # iterative def letterCombinations2(self, digits: str) -> List[str]: result = [] if digits == '': return result number_mapping = [' ', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] for i in range(len(digits)): t = [] string = number_mapping[int(digits[i])] for j in range(len(string)): if result: for s in result: t.append(s + string[j]) # append the second possible letters to the first one else: t.append(string[j]) #the first circle, add the first possible letter result = t return result if __name__ == '__main__': solution = Solution() result = solution.letterCombinations('29') print(result) result = solution.letterCombinations2('29') print(result)
aacec0437d15b8f3ea5db34fe14dcb89afe5e01e
lavalio/ChamplainVRSpecialist-PythonAlgorithms
/Week3/class2/upper_letter.py
252
4.1875
4
name = "champlain" #name_capital = name.upper() name_capital = name.capitalize() print(name_capital) print("I am taking this course at {}".format(name_capital)) # version 2 name = "champlain" print("V2: I am taking this course at " + name.title())
145745974607b80a59bea50ac0452eff9e85aca0
vincentinttsh/ncnu-program-class-python
/1/1-1.py
274
3.515625
4
import cmath import math a = float(input()) b = float(input()) c = float(input()) if b*b-4.0*a*c < 0: d=(-b+cmath.sqrt(b*b-4*a*c))/(2*a) e=(-b-cmath.sqrt(b*b-4*a*c))/(2*a) else : d=(-b+math.sqrt(b*b-4*a*c))/(2*a) e=(-b-math.sqrt(b*b-4*a*c))/(2*a) print(d,e)
d263b3f1e930ed6773ddd0d3c28c417038f3d560
CommitHooks/Python-Excercises
/Page77Proj.py
441
4.28125
4
def collatz(number): val = 0 if number % 2 == 0: val = number // 2 elif number % 2 == 1: val = 3 * number + 1 print(val) return val def enterInt(): print('Please enter an integer:') try: num = int(input()) return num except ValueError: print('An integer must be entered.') number = enterInt() while number and collatz(number) != 1: number = enterInt()
2b6eb38dfe0c3dba148c6a3cf810015e1dbcd0c1
ws2823147532/algorithm008-class01
/Week_02/[589]N叉树的前序遍历.py
1,625
3.65625
4
# 给定一个 N 叉树,返回其节点值的前序遍历。 # # 例如,给定一个 3叉树 : # # # # # # # # 返回其前序遍历: [1,3,5,6,2,4]。 # # # # 说明: 递归法很简单,你可以使用迭代法完成此题吗? Related Topics 树 # leetcode submit region begin(Prohibit modification and deletion) """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ from typing import List # 前序遍历:根->children class Solution: def preorder1(self, root: 'Node') -> List[int]: res = [] def func(node): if not node: return res.append(node.val) for _node in node.children: func(_node) func(root) return res def preorder2(self, root: 'Node') -> List[int]: if not root: return [] res = [] q = [root] while q: curr = q.pop() res.append(curr.val) if curr: q.extend(reversed(curr.children)) # for i in range(len(curr.children) - 1, -1, -1): # q.append(curr.children[i]) return res def preorder(self, root: 'Node') -> List[int]: if not root: return [] res = [] q = [root] while q: curr = q.pop() if isinstance(curr, Node): q.extend(list(reversed(curr.children)) + [curr.val]) else: res.append(curr) return res # leetcode submit region end(Prohibit modification and deletion)
4c90476603b12fcb5d68629ff4a18f704b6217cc
ugobachi/AtCoder
/BootCampforBiginners_Easy/パナソニックプログラミングコンテスト2020_B.py
173
3.5
4
n,m = (int(x) for x in input().split()) mul = int(n*m) if n == 1 or m == 1: print(1) elif mul % 2 == 1: print(mul // 2 + 1) elif mul % 2 == 0: print(mul //2)
f297902536572945deebf8cb55e76c72ce33ad38
graccse/program-assignments
/dictionary_practice.py
301
3.765625
4
groceries = {"chicken": 1.59 , "beef": 1.99, "cheese": 1.00, "milk": 2.50 } chicken_price= groceries["chicken"] print(chicken_price) beef_price = groceries["beef"] print(beef_price) cheese_price = groceries["cheese"] print(cheese_price) milk_price = groceries["milk"] print(milk_price)
b0f0bcfb5739d46de54cbe46614e82bf5a2d13fb
Kajol7052/Updated-Stage1-Fellowship
/Basic_Programs/PowersOf2.py
492
4.25
4
""" * author - kajol * date - 12/24/2020 * time - 1:24 PM * package - com.bridgelabz.basicprograms * Title - Print a table of the powers of 2 that are less than or equal to 2^N """ try: number = int(input("Enter number: ")) #print power of 2 within given range if number < 31: for num in range(1, number+1): print("2 ^", num, "=", 2**num) else: print("Enter number in valid range") except Exception: print("Exception occured")
815634df44131b4468d3c9c5029dc9908a5e9b24
anikpuranik/Machine-Learning
/Advanced House Prediction/exploratory_data_analysis.py
5,014
4
4
'''1. Exploratory Data Analysis''' # importing libraries import os import numpy as np import pandas as pd import matplotlib.pyplot as plt # loading dataset DIRECTORY = '/Users/aayushpuranik/.spyder-py3/dataset/house-prices-advanced-regression-techniques' train_data = pd.read_csv(os.path.join(DIRECTORY, 'train.csv')) test_data = pd.read_csv(os.path.join(DIRECTORY, 'test.csv')) print(train_data.shape) train_data.head() # Now ID is not the importannt column in dataset. So we can remove it. '''In data analysis we will analyze to find out: 1. Missing Values 2. Numerical Values 3. Categorical Variables 4. Cardinality of Categorical Variables 5. Outliers 6. Relationship between independent and dependent variables''' # 1. Missing values null_data = [features for features in train_data.columns if train_data[features].isnull().sum()>1 ] for feature in null_data: print(feature, np.round(train_data[feature].isnull().mean(), 4), '%missing values') # Impact of missing values on dependent variable for feature in null_data: data = train_data.copy() # conveting all null values to 1 and rest to 0 data[feature] = np.where(data[feature].isnull(), 1, 0) # Calculate the mean of SalePrice where data is missing data.groupby(feature)['SalePrice'].median().plot.bar() plt.title(feature) plt.show() '''For all the missing values the Dependent Variable is very high. Thus this comes as an important feature.''' # 2. Numerical Variables num_data = train_data.select_dtypes(include=['int64','float64']) # Temporal Variable (Eg: Datetime Variables) year_feature = [feature for feature in num_data if ('Yr' in feature or 'Year' in feature) ] print(feature, num_data[year_feature].head()) train_data.groupby('YrSold')['SalePrice'].median().plot() #Since price is dropping with the time which is usually not the behaviour in real life. #We will investigate furthur. We are checking SalePrice with repect no of years. for feature in year_feature: if feature!='YrSold': data = num_data.copy() data[feature] = data['YrSold']-data[feature] plt.scatter(data[feature], data['SalePrice']) plt.title(feature) plt.show() # Checking discreate feature discrete_feature = [feature for feature in num_data if (len(num_data[feature].unique())<25 and feature not in year_feature+['Id']) ] # Dependency of Discrete variable to SalePrice dependent variables for feature in discrete_feature: data = train_data.copy() data.groupby(feature)['SalePrice'].median().plot() plt.xlabel(feature) plt.ylabel('SalePrice') plt.title(feature) plt.show() # Checking continous feature continous_feature = [feature for feature in num_data if feature not in discrete_feature+year_feature+['Id'] ] # Dependency of Continous variable to SalePrice dependent variables for feature in continous_feature: data = train_data.copy() data[feature].hist(bins=25) plt.xlabel(feature) plt.ylabel('Count') plt.title(feature) plt.show() '''Now this data is not a gaussian distribution. For solving regression problem we need to work on gaussian distribution So we need to convert all the non-gaussian continous variables into gaussian variables.''' # Converting into logirithmic scale. for feature in continous_feature: data = train_data.copy() if 0 in data[feature].unique(): pass else: data[feature] = np.log(data[feature]) data['SalePrice'] = np.log(data['SalePrice']) plt.scatter(data[feature], data['SalePrice']) plt.title(feature + ' vs SalePrice') plt.show() # Outliars for feature in continous_feature: data = train_data.copy() if 0 in data[feature].unique(): pass else: data[feature] = np.log(data[feature]) data.boxplot(column=feature) plt.title(feature + ' vs SalePrice') plt.show() # There are multiple outliars # This only work for continous variable # 3.Categorical Feature cat_data = train_data.select_dtypes(include='O') print(cat_data.head()) '''cardinality means no. of unique category in categorical feature.''' # Cardinality of Categorical Features for feature in cat_data: print(feature, len(cat_data[feature].unique())) '''We have three class with greater than 10 unique categories. So, we avoid those variables to directly categorize to unique numbers. Other than than we can go ahead with one-hot encoding or pd_get_dummies.''' # Dependency of categorical variable to SalePrice for feature in cat_data: data = train_data.copy() data.groupby(feature)['SalePrice'].median().plot.bar() plt.title(feature) plt.show()
406c0dea4724248a638ae18a8feaad4aa8e4da3c
plependu/RCHI
/aggregation_scripts/HUDPointTemplate/ParentingYouth.py
21,891
3.515625
4
''' My Assumptions: 1) How my code works is that the helperfunction gets every ParentGlobalID (removing any duplicates) from a parenting Youth. How I do this is from creating a set with every youth and filter out any youth that is classified as a child status (Set 1). Create a new set (Set 2 ) of adults in order to do a set difference between set1 and set2 ( set3 ).Create a new set ( set 4) that contains children and have a child status in order to do a intersection between set3 and set 4 ( set 5 ). Set 5 contains the households that fits the defintion of Parenting Youth household and then remove any duplicate household. Def of Parenting Youth : A youth who identifies as the parent or legal guardian of one or more children who are present with or sleeping in the same place as that youth parent, where there is no person over age 24 in the household. In other words a household where the parent or gaurdian is a youth and he or she must contain a child. The household can not contain any adults else it gets discarded. 2) The rest of the functions use the helperfunction to get the household list( the new set ) and based on the function criteria filter it using the new set. ## TODO Create some test cases Chronically Homeless Function Wrote them based on the csv column 'Chronically Homeless Status' ''' import pandas as pd # in_df = pd.read_csv('../../../HouseholdQuestions_Cities_Districts_040119_1300.csv') #* Save to CSV FILE import tkinter as tk from tkinter import filedialog import os def exportCSV(): export_file_path = filedialog.asksaveasfilename(defaultextension='.csv') if not export_file_path: # asksaveasfile return `None` if dialog closed with "cancel". return data_Table().to_csv (export_file_path, index = None, header=True) def importCSV(): global in_df import_file_path = filedialog.askopenfilename(initialdir = os.getcwd(),filetypes=[("CSV Files",".csv")]) if import_file_path: in_df = pd.read_csv(import_file_path) print("Created") #* Helper Function to create tables for csv file def helperFunction_HouseHolds_Info(): total_num_of_households = total_number_of_households() total_num_persons = total_number_of_persons() total_num_parents = total_number_of_parents() total_num_children = total_children_in_Youth_Households() total_num_parents_under18 = total_parenting_youth_under18() total_num_children_household_under18 = total_children_in_Under18_Households() total_num_parents_18to24 = total_parenting_youth_18to24() total_num_children_household_18to24 = total_children_in_18to24_Households() data = {'Parenting Youth Households':['Total number of parenting youth households','Total number of persons in parenting youth households','Total Parenting Youth (youth parents only)','Total Children in Parenting Youth Households','Number of parenting youth under age 18','Children in households with parenting youth under age 18','Number of parenting youth age 18 to 24','Children in households with parenting youth age 18 to 24']\ , 'Unsheltered': [total_num_of_households,total_num_persons,total_num_parents,total_num_children,total_num_parents_under18,total_num_children_household_under18,total_num_parents_18to24,total_num_children_household_18to24]} df = pd.DataFrame(data) df['Unsheltered'] = df['Unsheltered'].astype(int) return df def helperFunction_Gender(): female = total_number_of_female() male = total_number_of_male() transgender = total_number_of_transgender() genderNonConforming = total_number_of_gender_non_conforming() data = {'Gender (youth parents only)':['Female (youth parents only)', 'Male (youth parents only)', 'Transgender (youth parents only)', 'Gender Non-Conforming (youth parents only)']\ , 'Unsheltered': [female,male,transgender,genderNonConforming]} df = pd.DataFrame(data) df['Unsheltered'] = df['Unsheltered'].astype(int) return df def helperFunction_Ethnicity(): non_Latino = total_number_of_ethnicity_nonlatino() Latino = total_number_of_ethnicity_latino() data = {'Ethnicity (youth parents only)':['Non-Hispanic/Non-Latino (youth parents only)', 'Hispanic/Latino (youth parents only)']\ , 'Unsheltered': [non_Latino, Latino]} df = pd.DataFrame(data) df['Unsheltered'] = df['Unsheltered'].astype(int) return df def helperFunction_Race(): white = total_number_of_race_white() black = total_number_of_race_African() asian = total_number_of_race_Asian() americanIndian = total_number_of_race_AmericanIndian() nativeHawaiian = total_number_of_race_NativeHawiian() multiple = total_number_of_race_Multiple() data = {'Race (youth parents only)':['White (youth parents only)', 'Black or African-American (youth parents only)', 'Asian (youth parents only)', 'American Indian or Alaska Native (youth parents only)','Native Hawaiian or Other Pacific Islander (youth parents only)','Multiple Races (youth parents only)']\ , 'Unsheltered': [white, black, asian, americanIndian, nativeHawaiian, multiple]} df = pd.DataFrame(data) df['Unsheltered'] = df['Unsheltered'].astype(int) return df def helperFunction_ChronicallyHomeless(): total_num_chronicallyHomeless = total_number_person_chronically_homeless() data = {'Chronically Homeless':['Total number of households (Chronically Homeless)']\ , 'Unsheltered': [total_num_chronicallyHomeless]} df = pd.DataFrame(data) df['Unsheltered'] = df['Unsheltered'].astype(int) return df ##* HelperFunction Combine Tables for CSV File def data_Table(): df0 = helperFunction_HouseHolds_Info() df1 = helperFunction_Gender().rename(columns={"Gender (youth parents only)": "Parenting Youth Households"}) df2 = helperFunction_Ethnicity().rename(columns={"Ethnicity (youth parents only)": "Parenting Youth Households"}) df3 = helperFunction_Race().rename(columns={"Race (youth parents only)": "Parenting Youth Households"}) df4 = helperFunction_ChronicallyHomeless().rename(columns={"Chronically Homeless": "Parenting Youth Households"}) result = df0.append([df1,df2, df3,df4]).reset_index(drop=True) return result ##* Helper Function that returns total number of households def helperFunction_Total_num_Households(): total_unaccompanied_Youth = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] != 'Child'))\ ,['ParentGlobalID','Relationship To HoH','Age As Of Today']]\ .drop_duplicates(subset='ParentGlobalID') total_Adults = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] > 24))\ ,['ParentGlobalID']]\ .drop_duplicates(subset='ParentGlobalID') total_children_relationship = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] < 18) & (df['Relationship To HoH'] == 'Child'))\ ,['ParentGlobalID']]\ .drop_duplicates(subset='ParentGlobalID') # #set_diff_df = pd.concat([total_Adults, total_children, total_children]).drop_duplicates(keep=False) set_diff_df = total_unaccompanied_Youth.merge(total_Adults, indicator=True, how="left", on='ParentGlobalID')[lambda x: x._merge=='left_only'].drop('_merge',1).drop_duplicates() households_list = pd.merge(set_diff_df, total_children_relationship, how='inner').drop_duplicates(subset='ParentGlobalID') return households_list ##* Total number of households def total_number_of_households(): households_list = helperFunction_Total_num_Households().shape[0] return households_list ##* Total number of persons def total_number_of_persons(): households_list = helperFunction_Total_num_Households() total_persons = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] <= 24))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() # total_persons = in_df['ParentGlobalID'].isin(households_list['ParentGlobalID']).sum() return total_persons ##* Total Parenting Youth (youth parents only) def total_number_of_parents(): households_list = helperFunction_Total_num_Households() total_parents = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_parents #* Total Children in Parenting Youth Households def total_children_in_Youth_Households(): households_list = helperFunction_Total_num_Households() total_children = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] < 18) & (df['Relationship To HoH'] == 'Child'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_children #* Number of parenting youth under age 18 def total_parenting_youth_under18(): households_list = helperFunction_Total_num_Households() total_parenting_under18 = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] < 18) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_parenting_under18 #* Children in households with parenting youth under age 18 def total_children_in_Under18_Households(): households_list = helperFunction_Total_num_Households() under_18 = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] < 18) & (df['Relationship To HoH'] == 'Self'))\ ,['ParentGlobalID']]\ .drop_duplicates(subset='ParentGlobalID') parents_under18 = pd.merge(under_18, households_list, how='inner').drop_duplicates(subset='ParentGlobalID') total_children = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] < 18) & (df['Relationship To HoH'] == 'Child'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(parents_under18['ParentGlobalID']).sum() return total_children #* Number of parenting youth age 18 to 24 def total_parenting_youth_18to24(): households_list = helperFunction_Total_num_Households() total_parents_18to24 = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & ((df['Age As Of Today'] >= 18) & (df['Age As Of Today'] <= 24)) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_parents_18to24 #* Children in households with parenting youth age 18 to 24 def total_children_in_18to24_Households(): households_list = helperFunction_Total_num_Households() total_18to24 = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & ((df['Age As Of Today'] >= 18) & (df['Age As Of Today'] <= 24)) & (df['Relationship To HoH'] == 'Self'))\ ,['ParentGlobalID']]\ .drop_duplicates(subset='ParentGlobalID') parents_18to24 = pd.merge(total_18to24, households_list, how='inner').drop_duplicates(subset='ParentGlobalID') total_children = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Age As Of Today'] < 18) & (df['Relationship To HoH'] == 'Child'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(parents_18to24['ParentGlobalID']).sum() return total_children ##* Total number of female def total_number_of_female(): households_list = helperFunction_Total_num_Households() total_female = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Gender'] == 'Female') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_female ##* Total number of male def total_number_of_male(): households_list = helperFunction_Total_num_Households() total_male = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Gender'] == 'Male') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_male ##* Total number of transgender def total_number_of_transgender(): households_list = helperFunction_Total_num_Households() total_transgender = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & ((df['Gender'] == 'MTF') | (df['Gender'] == 'FTM'))& (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_transgender ##* Total number of GenderConforming def total_number_of_gender_non_conforming(): households_list = helperFunction_Total_num_Households() total_gender_non_conforming = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Gender'] == 'GenderNonConforming') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_gender_non_conforming ##* Total number of Known Gender def total_number_of_gender_known(): households_list = helperFunction_Total_num_Households() total_gender_Known = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') &(df['Gender'] != 'DoesntKnow') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_gender_Known ##* Total number of non latinos/hispanics def total_number_of_ethnicity_nonlatino(): households_list = helperFunction_Total_num_Households() total_number_non_LatHisp = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Ethnicity'] == 'No') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_non_LatHisp ##* Total number of latinos/hispanics def total_number_of_ethnicity_latino(): households_list = helperFunction_Total_num_Households() total_number_LatHisp = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Ethnicity'] == 'Yes') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_LatHisp ##* Total number of Ethnicity Known def total_number_of_ethnicity_Known(): households_list = helperFunction_Total_num_Households() total_number_LatHisp = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Ethnicity'] != 'DoesntKnow') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_LatHisp ##* Total number of White def total_number_of_race_white(): households_list = helperFunction_Total_num_Households() total_number_white = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] == 'White') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_white ##* Total number of African def total_number_of_race_African(): households_list = helperFunction_Total_num_Households() total_number_black = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] == 'Black') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_black ##* Total number of Asian def total_number_of_race_Asian(): households_list = helperFunction_Total_num_Households() total_number_asian = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] == 'Asian') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_asian ##* Total number Native Hawaiian or Other Pacific Islander def total_number_of_race_NativeHawiian(): households_list = helperFunction_Total_num_Households() total_number_NativeHawaiian = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] == 'NativeHawaiian') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_NativeHawaiian ##* Total number American Indian def total_number_of_race_AmericanIndian(): households_list = helperFunction_Total_num_Households() total_number_AmericanIndian = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] == 'AmericanIndian') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_AmericanIndian ##* Total number Multiple Race def total_number_of_race_Multiple(): households_list = helperFunction_Total_num_Households() total_number_multiple = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] == 'Multiple') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_multiple ##* Total number Race Known def total_number_of_race_known(): households_list = helperFunction_Total_num_Households() total_number_of_race_known = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Race'] != 'DoesntKnow') & (df['Age As Of Today'] <= 24) & (df['Relationship To HoH'] == 'Self'))\ , ['ParentGlobalID']]['ParentGlobalID']\ .isin(households_list['ParentGlobalID']).sum() return total_number_of_race_known ## TODO Create some test cases #* Total number of households (Chronically Homeless) def total_number_of_ChronicallyHomeless(): households_list = helperFunction_Total_num_Households() total_number_of_ChronicallyHomeless = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Chronically Homeless Status'] == 1))\ , ['ParentGlobalID']] total_chronic_households = pd.merge(households_list, total_number_of_ChronicallyHomeless, how='inner').drop_duplicates(subset='ParentGlobalID') return total_chronic_households.shape[0] #* Total number of persons(Chronically Homeless) def total_number_person_chronically_homeless(): households_list = helperFunction_Total_num_Households() total_number_of_ChronicallyHomeless = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & (df['Chronically Homeless Status'] == 1))\ , ['ParentGlobalID']] total_chronic_households = pd.merge(households_list, total_number_of_ChronicallyHomeless, how='inner').drop_duplicates(subset='ParentGlobalID') total_persons = in_df.loc[lambda df:\ ((df['Household Survey Type'] == 'Interview') & ((df['Age As Of Today'] < 18) | (df['Age As Of Today'] >= 18)))\ | ((df['Household Survey Type'] == 'Observation') & ((df['Age Observed'] == 'Under18') | (df['Age Observed'] == 'Under24') | (df['Age Observed'] == 'Over25'))) , ['ParentGlobalID']]['ParentGlobalID']\ .isin(total_chronic_households['ParentGlobalID']).sum() return total_persons root= tk.Tk() root.title('Menu') canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'seashell3', relief = 'raised') canvas1.pack() saveAsButton_CSV = tk.Button(text='Export CSV', command=exportCSV, bg='red', fg='black', font=('helvetica', 15, 'bold')) loadAsButton_CSV = tk.Button(text='Import CSV', command=importCSV, bg='red', fg='black', font=('helvetica', 15, 'bold')) cancelButton = tk.Button(text='Cancel',command=root.destroy ,bg='red', fg='black', font=('helvetica', 15, 'bold')) canvas1.create_window(75, 150, window=loadAsButton_CSV) canvas1.create_window(225, 150, window=saveAsButton_CSV) canvas1.create_window(150, 225, window=cancelButton) root.mainloop()
a22bd52dd74ff4aa38685125774dc7b9fe25c3f7
mayk93/All---Unorganized
/Old/FunnzyIntervalSorting.py
2,144
3.640625
4
import random ''' This code needs bug fixing. ''' class Interval: def __init__(self,left,right): self.left=left self.right=right def __str__(self): return "< Start: "+str(self.left)+" End: "+str(self.right)+" >" def Intersects(interval,otherInterval): return interval.left <= otherInterval.right and otherInterval.left <= interval.right def Before(interval,otherInterval): return interval.right < otherInterval.left def After(interval,otherInterval): return interval.left > otherInterval.right #Initially, start = 0 and end = len(A) def Partition(A,start,end): randomIndex = random.randint(start,end-1) #We don't want to choose the length A[randomIndex],A[end-1]=A[end-1],A[randomIndex] intersection = A[end-1] for (index,element) in enumerate(A[:end-1]): index += start if(Intersects(intersection,element)): if(element.left > intersection.left): intersection.left = element.left if(element.right < intersection.right): intersection.right = element.right pivotLeft = start for (index,element) in enumerate(A[:end-1]): index += start if(Before(element,A[pivotLeft])): A[index],A[pivotLeft] = A[pivotLeft],A[index] pivotLeft += 1 A[end-1],A[pivotLeft] = A[pivotLeft],A[end-1] pivotRight = pivotLeft+1 index = end-1 while(pivotRight <= index): index += start if(Intersects(element,intersection)): A[pivotRight],A[index] = A[index],A[pivotRight] pivotRight += 1 else: index -= 1 return Interval(pivotLeft,pivotRight) def IntervalSort(A,start,end): if start < end-1: pivot = Partition(A,start,end) IntervalSort(A,start,pivot.left) IntervalSort(A,pivot.right,end) def Display(A): return [str(element) for element in A] #A = [Interval(abs(random.randint(0,5)),abs(random.randint(6,10))) for i in range(0,3)] A = [Interval(2,8),Interval(3,9),Interval(2,6)] print("Before: "+str(Display(A))) IntervalSort(A,0,len(A)) print("After: "+str(Display(A)))
94b8b227b5553da3eaba932a5687ef2c5aa1c76b
MiyaJ/py-study
/basic/demo_list.py
1,326
4.15625
4
# author : Caixiaowei-zy # date : 2020/12/18 14:55 # 列表 # 1. 列表申明 list1 = [1, 2, 'hello', 'python', '天天', 'study', 3, 99] list2 = list(list1) print(list1) print(list2) size = len(list1) print('list1 的大小为:', size) list_0 = list1[0] print('list1 索引0 的元素为:', list_0) list1.append('小哥哥') print(list1) list1.append('小姐姐') list1.insert(0, '小姐姐') print(list1) index = list1.index('小哥哥') print(index) # 切片 list3 = [00, 10, 20, 30, 40, 50, 60, 70, 60, 50, 50] print('原列表:', list3) print('原列表:', list3[1:]) print('切片后列表:', list3[1:6:1]) print('切片后列表:', list3[1:6:2]) print('步长 -1', list3[::-1]) print('步长 -1', list3[6:1:-1]) # 遍历 for i in list3: print('索引为:', list3.index(i), '元素值:', i) # list3 中50 出现的次数 print('50出现的次数:', list3.count(50)) # 增加序列 list3.extend([1, 2, 3]) print(list3) # 指定位置插入元素 list3.insert(0, '很忙啊') print(list3) # 移除指定位置的元素, 默认index=-1, 最后一个元素 list3.pop(0) print(list3) # 反向列表元素 list3.reverse() print(list3) # 排序 list3.sort() print('排序:',list3) # 复制 copy = list3.copy() print('复制:', copy) # 列表生成时 list4 = [2*i for i in range(1, 6)] print(list4)
bb8daf1b6257cd6b2efca5b66c84b6011a91a4f1
JavaRod/SP_Python220B_2019
/students/brian_minsk/lesson10/assignment/csv_files/csv_data_duplicator.py
1,341
3.578125
4
import csv import os def read_data(csv_file_name): """ Read each each row into a dict and return a list of all the dicts. """ with open(csv_file_name, newline='', encoding='utf-8-sig') as csv_file: reader = csv.DictReader(csv_file) return [row for row in reader] def get_fields(csv_file_name): with open(csv_file_name, newline='', encoding='utf-8-sig') as csv_file: reader = csv.DictReader(csv_file) for row in reader: return reader.fieldnames def create_new_file_name(csv_file_name, num_dups): root_ext = os.path.splitext(csv_file_name) return root_ext[0] + str(num_dups) + root_ext[1] def write_new_file(data, csv_file_name, field_names, num_dups): with open(file=csv_file_name, mode='w', newline='', encoding='utf-8-sig') as csv_file: writer = csv.DictWriter(csv_file, field_names) writer.writeheader() for _ in range(num_dups): writer.writerows(data) if __name__ == "__main__": file_names = ['customers.csv', 'product.csv', 'rentals.csv'] num_dups = 10000 for file_name in file_names: data = read_data(file_name) field_names = get_fields(file_name) new_file_name = create_new_file_name(file_name, num_dups) write_new_file(data, new_file_name, field_names, num_dups)
8f1a79140e76324ed9524d62b9339810aa09c067
JoaoErick/aula-python
/aula006.py
1,500
3.828125
4
# conjunto = {1, 2, 3, 4} # print(conjunto) # # conjunto = {1, 2, 3, 4, 4} #Não existem elementos duplicados # print(conjunto) # # conjunto = {1, 2, 3, 4, 2} # conjunto.add(5) # print(conjunto) # conjunto = {1, 2, 3, 4, 2} # conjunto.discard(2) # print(conjunto) # conjunto = {1, 2, 3, 4, 5} # conjunto2 = {5, 6, 7, 8} # conjunto_uniao = conjunto.union(conjunto2) # print('União: {}'.format(conjunto_uniao)) # conjunto_intersecao = conjunto.intersection(conjunto2) # print('Interseção: {}'.format(conjunto_intersecao)) # conjunto_diferenca1 = conjunto.difference(conjunto2) # conjunto_diferenca2 = conjunto2.difference(conjunto) # print('Diferença entre 1 e 2: {}'.format(conjunto_diferenca1)) # print('Diferença entre 2 e 1: {}'.format(conjunto_diferenca2)) # conjunto_diff_simetrica = conjunto.symmetric_difference(conjunto2) # print('Diferença simétrica: {}'.format(conjunto_diff_simetrica)) #O que tem de diferente nos dois conjuntos conjunto_a = {1, 2, 3} conjunto_b = {1, 2, 3, 4, 5} conjunto_subset = conjunto_a.issubset(conjunto_b) #Verifia se um conjunto é subconjunto do outro. print('A é subconjunto de B? {}'.format(conjunto_subset)) conjunto_superset = conjunto_b.issuperset(conjunto_a) #Verifica se um conjunto é superconjunto do outro. print('B é superconjunto de A? {}'.format(conjunto_superset)) lista = ['cachorro', 'cachorro', 'gato', 'gato', 'elefante'] print(lista) conjunto_animais = set(lista) print(conjunto_animais) lista = list(conjunto_animais) print(lista)
79c9a5c7ff158e257659097711e0ab7c1033d9ab
gbt1988/PythonToWork
/project/5.6.1displayInventory.py
1,844
3.765625
4
def displayInventory(inventory): print('Inventory:') item_total = 0 for k,v in inventory.items(): print(str(v) + ' ' + k) item_total += v print('Total number of items + str(item_total)')#循环内,循环完打印 def addToInventory(inventory,addedItems): count={} for a in addedItems: count.setdefault(a,0) count[a] += 1 print(count) for k,v in count.items(): if k in inventory: inventory[k]=inventory[k] + count[k] else: inventory.setdefault(k,count[k]) #inventory[k]=count[k]这两个写法都行 return inventory inv = {'gold coin':42,'rope':1} dragonLoot=['gold coin','dagger','gold coin','gold coin','ruby'] inv = addToInventory(inv,dragonLoot) #displayInventory(inv) print(inv) #或者以下: #stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} #def displayInventory(inventory): # print("Inventory:") # item_total = 0 # for k, v in inventory.items(): # print(str(v) + ' ' + k) # item_total += v # print("Total number of items: " + str(item_total)) # displayInventory(stuff) #def addToInventory(inventory, addedItems): # for i in addedItems: # if i in inventory: i 既可以是字典 b 的键,也可以是字典 a 的键,都可以用 in 查询。 # inventory[i] += 1 可以直接按照字典 b 中的键名,找到字典 a 中的同名键,直接更改键值。 # else: 这里是按照列表中的元素名,查看是否同时是字典的键名。 # inventory[i] = 1 # return inventory #inv = {'gold coin': 42, 'rope': 1} #dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] #inv = addToInventory(inv, dragonLoot) #displayInventory(inv)
67993ba0812d04ddebf78dde67a37a07821cdf76
mtourj/Intro-Python-II
/src/player.py
1,410
3.65625
4
# Write a class to hold player information, e.g. what room they are in # currently. class Player: def __init__(self, current_room): self.current_room = current_room self.inventory = [] def travel(self, direction): '''Move player in a direction toward a room. Returns True on success, False on failure''' target_room = getattr(self.current_room, f'{direction}_to') if target_room: self.current_room = target_room return True else: return False def addItemToInventory(self, item): '''Add item to player's inventory by instance''' item.on_take() self.inventory.append(item) def removeItemFromInventory(self, item_name): '''Remove an item from player's inventory by name''' target_item = None # Find item in inventory for item in self.inventory: if(item.name.lower() == item_name.lower()): target_item = item break if(target_item): item.on_drop() self.inventory.remove(item) return target_item def hasItem(self, item_name): '''Checks if this player has a specific item by name Returns True if it exists, False if it does not''' return item_name.lower() in [item.name.lower() for item in self.inventory]
9437f85c20151d6ef7aa0f264c882c8802822dd4
gontse00/quant_finance
/frame/market_enviroment.py
2,837
3.828125
4
### Market Enviroments """ Market enviroments is just a name for a collection of other data and python objects. This abstraction simplifies a number of operations and also allows for a consistant modeling of recuring aspects. A market enviroment consists of three dicts to store the following types of data and python objects. 1) constants: these can be model params or option maturity date. 2) Lists: These are sequences of objects in general, like a list object of objects modelling (risky) securities 3) Curves: These are objects for discounting, for example, like an instance of a short_rate class. """ """ This is a storage class, for practical applications, market data and other data as well as Python Objects are first collected, then a market_enviroment object is instantiated and filled with the relevent data objects. this is then delivered in a sigle step to other classes that need the data and objects in the respective market_enviroment objects. A major advantage of this object orientaed modeling aproach is, for example, that instances of the short_rate class can live in multiple market enviroments. Once the instanceis updated, for example, when a new costant short rate is set, all the instances of the market_enviroment class containing that particular instance of the discounting class will be updated automtically. """ class market_enviroment(object): """class to model a market enviroment relevent for valuation. Attributes ========== name : string (name of market enviroment) pricing_date : datetime object (date of market enviroment) Methods ======= add_constant : adds constant (e.g model param) get_constant : gets a constant add_list : adds a list (e.g underlyngs, dates etc) get_list : gets a list add_curve : add a market curve (e.g yield curve) get_curve : get a market curve add_enviroment : ads and overwrites whole market enviroments with constatns, lists and curves. """ def __init__(self, name, pricing_date): self.name = name self.pricing_date = pricing_date self.constants = {} self.lists = {} self.curves = {} def add_constant(self, key, constant): self.constants[key] = constant def get_constant(self, key): return self.constants[key] def add_list(self, key, list_object): self.lists[key] = list_object def get_list(self, key): return self.lists[key] def add_curve(self, key, curve): self.curves[key] = curve def get_curve(self, key): return self.curves[key] def add_enviroment(self, env): for key in env.constants: self.constants[key] = env.constants[key] for key in env.lists: self.lists[key] = env.lists[key] for key in env.curves: self.curves[key] = env.curves[key]
8138d75dd5ed8c476fe00fdc230a17923a20e429
lusineduryan/ACA_Python
/Basics/Homeworks/Homework_6/Exercise_4_binary exponent.py
196
3.6875
4
def bin_exp(x, n): res = 1 power = 2 ** n while power >= 2: power = power / 2 x = x * x return x def bin_exp_2(x, n): return (x ** n) ** 2 print(bin_exp(2,3))
dd68af568652bc274dcf99a3cc14480c686ef1f9
daniel-reich/turbo-robot
/quMt6typruySiNSAJ_4.py
1,498
4.0625
4
""" An out-shuffle, also known as an out Faro shuffle or a perfect shuffle, is a controlled method for shuffling playing cards. It is performed by splitting the deck into two equal halves and interleaving them together perfectly, with the condition that the top card of the deck remains in place. Using a list to represent a deck of cards, an out-shuffle looks like: [1, 2, 3, 4, 5, 6, 7, 8] ➞ [1, 5, 2, 6, 3, 7, 4, 8] # Card 1 remains in the first position. If we repeat the process, the deck eventually returns to original order: Shuffle 1: [1, 2, 3, 4, 5, 6, 7, 8] ➞ [1, 5, 2, 6, 3, 7, 4, 8] Shuffle 2: [1, 5, 2, 6, 3, 7, 4, 8] ➞ [1, 3, 5, 7, 2, 4, 6, 8] Shuffle 3: [1, 3, 5, 7, 2, 4, 6, 8] ➞ [1, 2, 3, 4, 5, 6, 7, 8] # Back where we started. Write a function `shuffle_count` that takes a positive even integer `num` representing the number of the cards in a deck, and returns the number of out- shuffles required to return the deck to its original order. ### Examples shuffle_count(8) ➞ 3 shuffle_count(14) ➞ 12 shuffle_count(52) ➞ 8 ### Notes The number of cards is always greater than zero. Thus, the smallest possible deck size is 2. """ def shuffle_count(n): c = 0 lst = [x for x in range(1, n+1)] lst1 = [a for a in lst] while True: k = [] c += 1 for a, b in zip(lst[:(n//2)+1], lst[(n//2):]): k.append(a) k.append(b) if k == lst1: return c lst = [a for a in k]
a582ab8d81a7672b7375352a230faf846f499479
bignamehyp/interview
/python/leetcode/BinaryTreeZigzagLevelOrderTraversal.py
882
3.796875
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def zigzagLevelOrder(self, root): if root is None: return [] solns = [] nodeList = [root] level = 0 while len(nodeList) > 0: nodeList2 = [] soln = [] for node in nodeList: if node.left: nodeList2.append(node.left) if node.right: nodeList2.append(node.right) soln.append(node.val) if level % 2 == 1: soln.reverse() level += 1 solns.append(soln) nodeList = nodeList2 return solns
745a32da9c3f8ebaf02d4ddd70655c13d1e791fe
RubyBerumen/1roISC
/POO/Sesion23.2_EjemploEncapsulamiento/src/Ejemplo_Encapsulamiento.py
687
3.5
4
''' Created on 28 may. 2020 @author: Ruby ''' class Auto: '''clase para crear objetos de tipo auto''' def __init__(self, marca="ND", precio=0.0): self.marca=marca #para simular el encapsulamiento se aade guioes bajos a los self.__precio=precio #getters y setter def getPrecio(self): return self.__precio def detPrecio(self,precio): self.__precio = precio def __str__(self): return f"Auto \nMarca: {self.marca}\nPrecio: {self.__precio}" #==========================Pruebas=============================== a1 = Auto ("1",1.0) print(a1) print(a1.marca) print(a1.getPrecio())
ecc9180df7c8d4544fe7326ec28e84dab6790d21
astraknots/ncis
/src/pattern/checker/patternChecker.py
7,994
3.578125
4
#!/usr/bin/python import getopt import logging import sys import re import json SEPARATORS = [',', '.'] REPEAT_START = ['(', '[', '*'] REPEAT_END = [')', ']', '*'] REPEAT_WORDS = {'ONCE': 1, 'TWICE': 2} OPERATION_CNT = {'K': 1, 'P': 1, 'SM': 0, 'YO': 1, '2TOG': 1} def get_rep_end_for_start(rep_start_str): if rep_start_str in REPEAT_START: idx = REPEAT_START.index(rep_start_str) return REPEAT_END[idx] def determine_rep_reps(rep_patt_instr_str): '''Determine the number of times to execute a repeat from a patt instru. i.e. 2 times or Twice or x 2''' print(rep_patt_instr_str) rep_words = rep_patt_instr_str.split(' ') for rep_word in rep_words: if len(rep_word) > 0: if rep_word.isnumeric(): return int(rep_word) else: rep_word_u = rep_word.upper() if rep_word_u in REPEAT_WORDS: return REPEAT_WORDS[rep_word_u] return 1 def parse_patt_str(patt_str, skip_repeat=False): instrs = [] single = '' # Loop over each char in the instr str for idx in range(0, len(patt_str)): char = patt_str[idx] # if we have the beginning of a repeat character if not skip_repeat and char in REPEAT_START: # get the rest of the str after that char rem_patt_str = patt_str[idx + 1:] # find the index of the end of repeat char in remaining str rep_end_idx = rem_patt_str.find(get_rep_end_for_start(char), 1) # parse the instructions for repeat - makes a recursive call that will skip this section, thus skip_repeat = True rep_instrs = parse_patt_str(rem_patt_str[0:rep_end_idx], True) # get index of the end of repeat end_rep_instru_idx = rem_patt_str.find(SEPARATORS[0], rep_end_idx) # capture the remaining patt str to parse remain_patt_str = '' # determine how many times this should repeat if end_rep_instru_idx == -1: # we've just hit end of str rep_reps = determine_rep_reps(rem_patt_str[rep_end_idx + 1:]) else: rep_reps = determine_rep_reps(rem_patt_str[rep_end_idx + 1:end_rep_instru_idx]) remain_patt_str = rem_patt_str[end_rep_instru_idx + 1:] # Add the instrs repeated out as individual instructions added = 0 while (added < rep_reps): instrs.extend(rep_instrs) added += 1 # recursively call this on the rem_patt_str after this repeat, and extend the result if len(remain_patt_str) > 0: instrs.extend(parse_patt_str(remain_patt_str)) break elif char in SEPARATORS: # when we hit a separator (i.e. ,) we've gathered a whole instruction, add to array instrs.append(single.strip()) single = '' continue else: # gather another character of an instruction single += char # This captures the last fully gathered instruction, once we've run out of separators that indicate the end if len(single.strip()) > 0: instrs.append(single.strip()) print(instrs) # debug return instrs def get_num_from_str(a_str): # get the numbers of the instr match_str = '[0-9]$' a_cnt_search = re.search(match_str, a_str) # print("A patt has cnt:", a_cnt_search) a_cnt_list = re.findall(match_str, a_str) # print("A cnt:", a_cnt_list) if a_cnt_list and len(a_cnt_list) > 0: st_cnt = 0 for a_cnt in a_cnt_list: st_cnt += int(a_cnt) return st_cnt return 0 def count_instr_sts(instr): cnt = 0 if instr in ['SM', 'PM', 'RM']: cnt += 0 elif instr in ['YO']: cnt += 1 elif instr in ['SSK']: cnt += 1 else: cnt += get_num_from_str(instr) print(f"{instr} has {cnt} st{'s' if cnt > 1 else ''}") return cnt def count_sts(patt_instr_list, specials=None): '''Count the number of sts this list of instrs involves - gives the count AFTER executing the sts''' if specials is None: specials = [] total_cnt = 0 for patt_instr in patt_instr_list: match = False if len(specials) > 0: for special in specials: if patt_instr == special["stitch-name"]: cnt = special["stitch-count"] total_cnt += cnt print(f"{patt_instr} has {cnt} st{'s' if cnt > 1 else ''}") match = True if not match: total_cnt += count_instr_sts(patt_instr.upper()) return total_cnt ''' st_cnt = 0 print(patt_str) # split the patt str by comma patt_pie = patt_str.split(',') print(patt_pie) for a_patt in patt_pie: print("-----A patt: ", a_patt) # try to count, or see if it is longer if "TWICE" in a_patt: print(a_patt, " Contains repeat Twice") elif "TIMES" in a_patt: print(a_patt, " Contains repeat Times") else: # see if part of a rep if '(' in a_patt: print(a_patt, " Begins rep") elif ')' in a_patt: print(a_patt, " Ends rep") # get the numbers of the instr match_str = '[0-9]$' a_cnt_search = re.search(match_str, a_patt) print("A patt has cnt:", a_cnt_search) a_cnt_list = re.findall(match_str, a_patt) print("A cnt:", a_cnt_list) if a_cnt_list and len(a_cnt_list) > 0: for a_cnt in a_cnt_list: print("..adding ", a_cnt, " to ", st_cnt) st_cnt += int(a_cnt) return st_cnt ''' def parse_special_patt_instrs(filename): '''Expected format for special pattern instru: { "stitch-name": <str stitch-name> i.e. "LC", "instr": <str normal separated list of knit instructions> i.e. "sl 1 st to cable needle and hold in front, k2, k1 from cable needle", "stitch-count": <int number of sts included in this special stitch> i.e. 3 (optional) "separator": <str separator> i.e. ',' } TOdo: For patterns? inc row instrs -- see/leverage patternUtil ''' specials = [] # list of dictionaries of json read in # Read in the file raw_data = "" with open(filename) as f: for line in f: raw_data += line if '}' in line: # then we've reached the end of this, parse and store # parse from json format into python dict data = json.loads(raw_data) specials.append(data) raw_data = "" for item in specials: print(item) #print(item, "=", data[item]) # print(json.dumps(data)) return specials def check_pattern(argv): filename = '' patt_str = '' try: opts, args = getopt.getopt(argv, "hp:f:b:", ["patt=", "file="]) except getopt.GetoptError: print('patternChecker.py -p <pattern-str> -f <pattern-file>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('patternChecker.py -p <pattern-str> -f <pattern-file>') sys.exit() elif opt in ("-f", "--file"): filename = arg elif opt in ("-p", "--patt"): patt_str = arg.upper() elif opt in "-b": patt_str = '' if filename == '': logging.info("No filename of pattern given") specials = [] else: logging.info("Filename of pattern given:" + filename) specials = parse_special_patt_instrs(filename) if patt_str == '': logging.info("No pattern string given") return parsed_instr = parse_patt_str(patt_str) st_cnt = count_sts(parsed_instr, specials) print("Found a total stitch count of:", st_cnt) if __name__ == "__main__": check_pattern(sys.argv[1:])
945b659e16d8f4d6a073e61a9a8178325f8d5349
4ndrewJ/CP1404_Practicals
/prac_05/hex_colours.py
685
4.15625
4
""" CP1404/CP5632 Practical Hex codes for colours in a dictionary """ COLOUR_NAME_TO_HEX = {'aliceblue': '#f0f8ff', 'blueviolet': '#8a2be2', 'cadetblue': '#5f9ea0', 'chocolate': '#d2691e', 'coral': '#ff7f50', 'darkgreen': '#006400', 'darkorange': '#ff8c00', 'darkorchid': '#9932cc', 'darkslategray': '#2f4f4f', 'firebrick': '#b22222'} colour_name = input("Enter colour name: ").lower() while colour_name != "": if colour_name in COLOUR_NAME_TO_HEX: print(f'Hex Code: {COLOUR_NAME_TO_HEX[colour_name]}') else: print("Invalid colour name") colour_name = input("Enter colour name: ").lower()
9b6d55c3cb3b0735dfdfbf109d57f8be65b0f3db
gagangaur/guvi
/player/set6/8.py
200
3.625
4
def countOccurance(s,k): print(s) count = 0 for i in s: if i==k: count+=1 return count sentense = input() word = input() print(countOccurance(sentense,word)) #abcc
e0b00d123c2e52493347796fc0c383c2b01f61ed
ArtemDavletov/EPAM_python_course
/homework2/hw4.py
669
3.9375
4
""" Write a function that accepts another function as an argument. Then it should return such a function, so the every call to initial one should be cached. def func(a, b): return (a ** b) ** 2 cache_func = cache(func) some = 100, 200 val_1 = cache_func(*some) val_2 = cache_func(*some) assert val_1 is val_2 """ from typing import Callable def cache(func: Callable) -> Callable: cacher = dict() def wrap(*args, **kwargs): kwags_values = tuple(kwargs.values()) if (args, *kwags_values) not in cacher: cacher[(args, *kwags_values)] = func(*args, **kwargs) return cacher[(args, *kwags_values)] return wrap
54dc370daa23f09a1701bba42c337e2c830ed796
AnoopKumarJangir/Python_Course
/Day 1/heartrate_cal.py
438
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 7 22:41:36 2019 @author: Anoop K. Jangir """ #Assume my age 21 my_age = 21 print (my_age) #Calculate maximum heart rate max_hr = 220 - my_age print (max_hr) #calculate target heart rate low_hr = max_hr * 0.70 print (low_hr) high_hr = max_hr * 0.85 print (high_hr) #calculate heart rate bites per minute print ("Heart rate is" + str(low_hr) + " to " + str(high_hr) + " beates per minute.")
080a7e6d3dc586c298a91effe3a34ecdfde98f96
signalwolf/Algorithm
/sort/merge_sort.py
3,153
3.765625
4
# coding=utf-8 from random import randint def quick_sort(array, start, end): def partition(): base = array[start] left, right = start + 1, end while left <= right: while left <= right and array[left] <= base: left += 1 while right >= left and array[right] > base: right -= 1 # if right < left: # done = True if left <= right: array[left], array[right] = array[right], array[left] array[start], array[right] = array[right], array[start] return right # print array, start, end if start < end: pivot = start #randint(start, end) array[pivot], array[start] = array[start], array[pivot] mid = partition() quick_sort(array, start, mid - 1) quick_sort(array, mid + 1, end) def merge_sort(array, start, end): if start >= end: return [] if start == end - 1: return [array[start]] mid = start + (end - start) / 2 left = merge_sort(array, start, mid) right = merge_sort(array, mid, end) res = [] i, j = 0, 0 while i < len(left) and j < len(right): if left[i] >= right[j]: res.append(right[j]) j += 1 else: res.append(left[i]) i += 1 if i == len(left): res += right[j:] if j == len(right): res += left[i:] return res # 我觉得这个是selection sort,每次遍历我都在寻找第一小,第二小的number def selection_sort(array): res = array[::] for i in xrange(len(res)): for j in xrange(i + 1, len(res)): if res[i] > res[j]: res[i], res[j] = res[j], res[i] return res # 这个不知道是什么sort def temp_sort(array): res = [None] * len(array) for i in xrange(len(array)): index = 0 for j in xrange(len(array)): if array[j] < array[i]: index += 1 while res[index] != None: index += 1 res[index] = array[i] # print res return res # Bubble sort就是通过不断的交换使得最小的或者最大的到list的最后 def bubble_sort(array): n = len(array) for i in xrange(n): for j in xrange(0, n - i - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array # def quick_sort_with_random (array): def main(): tried = 0 while tried < 10: array = arr_generator(1000, 0, 100) # print array # array = [1, 2] copy = array[:] merge = merge_sort(copy, 0, len(copy)) #print merge == sorted(array) copy = array[:] quick_sort(copy, 0, len(copy) - 1) # print copy print copy == sorted(copy) copy = array[:] bubble = bubble_sort(copy) # print bubble # print sorted(array) #print bubble == sorted(array) tried += 1 def arr_generator(n, start, end): res = [] for i in xrange(n): res.append(randint(start, end)) return res if __name__ == '__main__': main()