blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ccaf24653c74db54244d886057a9a25d5a7dbc2b
Python-Repository-Hub/Learn-Online-Learning
/Python-for-everyone/03_Web_Scraping/11_Regular_Expression/01_string_pattern.py
197
3.625
4
import re # To Use a Regular Expression hand = open('box-short.txt') for line in hand: line = line.rstrip() if re.search('From:', line) : print(line)
cb0497b2316bea804caf4a7773f7be8aeef39f80
MariaOkrema/bot
/Function.py
144
3.671875
4
price = 100 discount = 5 price_with_discount = price - price * discount/100 print (price_with_discount) a = 10 b = 5 c = a + b print (c)
2862e372f077efa63b712d50da6aa56089a30a1a
yangqu/TreasureHouse
/demo/pandas_read_csv.py
2,244
4.1875
4
# import the function pandas to format the dataset as a table called dataframe # 导入pandas包,起一个别名pd import pandas as pd # import the package os to read some folder to list files # 导入os包 import os def main(): # input dir ,if your files in this folder,the name will be listed,you can change it # input为输入路径,r代表字符串里边没有转义符号 input = r'D:\format' # in this case we use the for-loop function for file list # 使用OS包来读取输入的路径下的所有文件,file来引用读取到的文件,这是一个循环操作 for file in os.listdir(input): # if the file name end with txt # 如果文件以txt为结尾,那么继续运行 if file.endswith('txt'): # get the full path of the file # file为该文件的文件名,和input拼成全路径 io = input + '\\' + file # read csv file.It is not only the csv ,but also excel(pd.read_excel(io, sheet_name=0)) # the parameter io is the stream of the file content,error_bad_lines means skip the parsing error # 使用pandas的方法读取csv,并且用\t间隔 source = pd.read_csv(io, error_bad_lines=False, sep='\t') # extract the columns you want by the column name # 读取文件里的响应字段 source_extract = source[['tbb.locationid', 'push.stat', 'playlog.stat', 'heartbeat.stat']] # transform Null into 0 # 把null转化成0 source_extract.fillna(0, inplace=True) # print the dataframe # 打印 print(source_extract) # main function ,the python program entrance,it is the start of the dream # 函数入口,代表程序执行 # 所有的程序都是从上往下来执行,先是包的引入,然后遇到函数例如main(),先读进内存,但是不是运行,主程序看到if __name__ == '__main__',这个算是通用写法,主程序执行的入口,执行 # if中的部分,if中调用了main()函数,于是,运行main()函数里边的内容已经从上往下运行,运行到print截至,程序运行完毕 if __name__ == '__main__': main()
ffbf170e7ec54bb8c3cad5a1ca2c48eaa9017b21
wjdwls0630/2018-1-Web-Python-KHU
/Week6/Week 6.py
1,278
4.09375
4
#String method name="jungjin" print(name.capitalize()) print(str.capitalize(name)) print(name.upper()) print(str.upper(name)) print(len(name)) print(name.count("g")) #String methond find name="tomato" print(name.isalpha()) help(str.find) print(str.find(name,"o")) print(name.find('o')) print(name.find('o',str.find(name,"o")+1)) print(str.find(name,'o',str.find(name,"o")+1)) print(name.find("o",name.find('o',str.find(name,"o")+1)+1)) print(name.find('p')) print(name.count("e")) #Hangman game 1 name=input() character=input() print("="*30) print(str.center("Hangman Game",30)) print("="*30) print("Enter a long word:",end=" ") print("Enter a character:",end= " ") if character in name : print("{0} is in {1} ({2} times)".format(character, name, name.count(character))) else : print("{0} is not in {1}".format(character, name)) #List method 1 kingdoms=['Bacteria', 'Protozoa', 'Chromista', 'Plantae', 'Fungi', 'Animalia'] print(kingdoms[0]) print(kingdoms[len(kingdoms)-1]) print(kingdoms[0:3]) print(kingdoms[2:5]) print(kingdoms[4:]) print(kingdoms[0:0]) #List method 2 ids=[4353,2314,2956,3382,9362,3900] ids.remove(3382) print(ids) print(ids.index(9362)) ids.insert(4,4499) print(ids) ids.extend([5566,1830]) print(ids) ids.reverse() print(ids) ids.sort() print(ids)
33aa5694714a5ac67dc3c115ae5716d33b5c515e
MateuszMazurkiewicz/CodeTrain
/InterviewPro/2019.12.09/task.py
1,331
3.953125
4
''' Given a list of words, group the words that are anagrams of each other. (An anagram are words made up of the same letters). Example: Input: ['abc', 'bcd', 'cba', 'cbd', 'efg'] Output: [['abc', 'cba'], ['bcd', 'cbd'], ['efg']] Here's a starting point: ''' import collections def create_word_signature(word): signature = {} for letter in word: if letter not in signature: signature[letter] = 0 signature[letter] += 1 return signature def compare_signatures(s1, s2): if set(s1.keys()) != set(s2.keys()): return False for key in s1.keys(): if s1[key] != s2[key]: return False return True def groupAnagramWords(strs): signatures = [] for word in strs: signatures.append(create_word_signature(word)) res = [] for i in range(len(strs)): if not strs[i]: continue tmp = [] tmp.append(strs[i]) for j in range(i + 1, len(strs)): if not strs[j]: continue v = compare_signatures(signatures[i], signatures[j]) if v: tmp.append(strs[j]) strs[j] = None res.append(tmp) return res print(groupAnagramWords(['abc', 'bcd', 'cba', 'cbd', 'efg'])) # [['efg'], ['bcd', 'cbd'], ['abc', 'cba']]
d4c939b593196fa89158f180d6b8bfdaa0fd846a
gregseda/Python-Programming-Fundamentals
/Homework 7/re_order.py
619
3.578125
4
"""Homework 7 for CSE-41273""" # Greg Seda import sys def re_order(in_file, out_file): with open(in_file, 'r') as current_file: lines = current_file.read().split('\n') while '' in lines: lines.remove('') new_file = open(out_file, 'w') for line in lines: columns = line.split(',') columns[1], columns[0] = columns[0], columns[1] writer = str(",".join(columns)) + "\n" new_file.write(writer) new_file.close() if __name__ == "__main__": in_file = sys.argv[1] out_file = sys.argv[2] re_order(in_file, out_file)
7b25a160c8ff0ffa5cb57df42dc954d3ec842159
RunTheWave/Python
/main.py
484
3.734375
4
ask = input("Are you encrypting or decrypting? Enter 'e' or 'd'") string = input("Enter message!") alphabet = "abcdefghijklmnopqrstuvwxyz" newstring = "" key = int(input("Enter Key")) i = 0 while i < len(string): letter = string[i] whereisletter = alphabet.find(letter) if ask == 'e': newletter = alphabet[(whereisletter + key)%26] else: newletter = alphabet[(whereisletter - key)%26] newstring = newstring+newletter i+=1 print newstring
79dd75bf652f4452b71ae10f59e9cc264e15f8bd
TweetPete/ProjectIMU
/lib/GeoLib.py
836
3.859375
4
""" Geodetic Library """ from math import sqrt, sin, cos from MathLib import toValue, toVector def earthCurvature(a,f,lat): """ calculates radius of curvature in North and East takes ellipsoidal parameters as argument """ e = sqrt(f*(2-f)) Rn = a *((1-e**2)/(1-e**2*(sin(lat))**2)**(3/2)) Re = a/sqrt(1-e**2*(sin(lat))**2) return Rn, Re def ell2xyz(pos_obj): """ transformation of geographic coordinates to cartesian coordinates input is an EllipsoidPosition-object returns a 3x1 vector """ lat, lon, he = toValue(pos_obj.values) _, N = earthCurvature(pos_obj.a, pos_obj.f, lat) x = (N + he) * cos(lat)*cos(lon) y = (N + he) * cos(lat)*sin(lon) z = N * sin(lat)*(pos_obj.b**2/pos_obj.a**2) + he*sin(lat) return toVector(x,y,z)
ff489667025b3e9b9080debf15640ccc080f9349
matthewyoon/rangers59-homework
/projects/rental-property-roi-project/rental-property-roi-project.py
6,934
4.0625
4
""" ROI calculator Start with a general property class: (# Units, Income, Expenses, Cash Flow, Cash on Cash ROI) Include various methods for calculating income, expenses, cashflow, and a method to calculate ROI using the other calculated variables """ from IPython.display import clear_output class Rental_Property(): # Income # Expenses # Cash Flow # ROI # Print Statement of calculated attributes def __init__(self, num_units=1, income=0, expenses=0, annual_cashflow=0, total_investment=0, target_roi = 10.0, roi = 0, property_num = 1, roi_dict = {}): self.num_units = num_units self.income = income self.expenses = expenses self.annual_cashflow = annual_cashflow self.target_roi = target_roi self.total_investment = total_investment self.roi = roi self.property_num = property_num self.roi_dict = roi_dict #function to start the ROI calculator program def start(self): print("Welcome to the ROI calculator.") print("Please gather your paperwork. We will need some numbers in order to calculate the ROI on your future property.") self.target_roi = input("To begin, is there a target ROI that you would like to achieve? If not, the default will be 10%. ") if self.target_roi == "": self.target_roi = 10.0 else: self.target_roi = float(self.target_roi) self.program() def program(self): self.num_units = int(input("How many units are in the property? ")) self.calc_income() self.calc_expenses() self.calc_cashflow() self.calc_total() self.calc_roi() self.property_dict() clear_output() if self.target_roi > self.roi: print(f"The ROI for this property will be {self.roi}%. Compared to your target ROI of {self.target_roi}%, your expenses and investments for this property are too high.") else: print(f"The ROI for this property will be {self.roi}%. You should buy considering your target ROI is {self.target_roi}%.") print(self.roi_dict) end = input("Would you like to make any changes or calculate the ROI of a different property? (Y/N) ") if end.lower() == "y": self.repeat() else: print("Thank you for using our ROI investment program. Have a nice day!") def repeat(self): change = input("Would you like to change a previous property submitted? (Y/N) ") if change.lower() == "y": change_property = int(input("Please enter the property number that you would like to change? (See printed list above) ")) self.property_num = change_property self.target_roi = input("Target ROI? ") if self.target_roi == "": self.target_roi = 10.0 else: self.target_roi = float(self.target_roi) self.program() else: self.target_roi = input("Target ROI? ") if self.target_roi == "": self.target_roi = 10.0 else: self.target_roi = float(self.target_roi) self.program() # function to calculate the estimated income def calc_income(self): print("Next, we will need to calculate the estimated income from the prospective property.") rent_income = self.calc_rent() misc_income = int(input("Total of other miscellaneous incomes(ie. storage, laundry, etc). ")) total_income = rent_income + misc_income self.income = total_income print(f"Your total rental income is {self.income}.") def calc_rent(self): unit_dict = {} rent_income = [] while self.num_units > 0: unit_rent = int(input(f'For unit number {self.num_units}, what is the estimated rental income? ')) rent_income.append(unit_rent) unit_dict[f'Unit {self.num_units}'] = unit_rent self.num_units -= 1 return sum(rent_income) def calc_expenses(self): print("Thank you for your income information. Now we will need to calculate expenses.") tax = int(input("How much do you expect to pay in taxes? (This can be based on property cost, deductions, expenses, profit) ")) insurance = int(input("How much do you expect to pay for insurance? (Double check if insurance is included within your mortgage) ")) utilities = int(input("How much do you expect to pay in utilities? (input 0 if the tenant pays for utilities) ")) HOA = int(input("Is this property located in an area that requires HOA(Homeowner's Association) fees? If so how much are those fees? ")) Lawn_Snow = int(input("What is the expected cost of lawn maintenance/snow removal? (input 0 if tenant will maintain/clear) ")) vacancy = int(input("How much are you willing to set aside for any period of vacancies? (Typically 5% of rental income) ")) repairs = int(input("How much are you willing to set aside for any repairs that need to be done for the property? ")) capEx = int(input("How much are you willing to set aside for Capital Expenditures (Also typically about 5% of rental income) ")) property_management = self.prop_mg() mortgage = int(input("How much is your mortgage? ")) self.expenses = tax + insurance + utilities + HOA + Lawn_Snow + vacancy + repairs + capEx + property_management + mortgage print(f"The total expense amount of this rental property per month would be {self.expenses}.") def prop_mg(self): pm = (input("Will you be managing this property on your own? Y/N? ")) if pm.lower() == "n": return int(input("How much does property management cost? ")) else: return 0 def calc_cashflow(self): cash_flow = self.income - self.expenses self.annual_cashflow = cash_flow * 12 def calc_total(self): down = int(input("How much is the down payment on the property? ")) close = int(input("How much are the closing costs? (ie. appraisal/lawyer fees etc.) ")) rehab = int(input("How much money will need to be invested to cover any renovations or rehabiliation of the property? ")) misc = int(input("Are there any miscellaneous costs in regards to extra investments for the property? ")) self.total_investment = down + close + rehab + misc def calc_roi(self): roi = ((self.annual_cashflow/self.total_investment) * 100) self.roi = float(roi) self.roi = round(self.roi, 2) def property_dict(self): new_dict = {} new_dict[f'Property #{self.property_num}'] = f"ROI: {self.roi}" self.roi_dict.update(new_dict) self.property_num = self.property_num + 1 def run(): rent = Rental_Property() rent.start() run()
da2575d739bd1a8c1d25afbf775b8f68c03a0499
Larc-Asgard/LPTHW
/ex31/ex31.py
1,007
3.9375
4
print "You are in a room with two doors in front of you. Would you enter door #1 or door #2?" door = raw_input("> ") if door == "1": print "There is a bear eating a cheese cake. What would you do?" print "1. Take the cake.\n2. Scream at the bear." bear = raw_input("> ") if bear == "1": print "The bear cries!" elif bear == "2": print "The bear roars!" else: print "%s is not an option, the bear has eaten the cake, and you."% bear elif door == "2": print "You meet a cult priest who preaches you about the Old God" print "1. You run away." print "2. You punch him in the face." print "3. You channel your inner magical power to launch a fireball at him." insanity = raw_input("> ") if insanity == "1" or insanity == "2": print "The priest now treats you as the new Old God!" elif insanity == "3": print "Wow, I don't know you are a mage." else: print "The walls close in and you become a pile of meat."
da113b76c5a844a37c42c024104f5b312ed7df7a
cr646531/Blackjack
/card.py
197
3.5
4
''' Card class ''' class Card(): def __init__(self, rank, suit, value): self.rank = rank self.suit = suit self.value = value def __str__(self): return f'| {self.rank} of {self.suit} |'
b719f682bf3b49d3fe553dd55b0a264520e76ee5
yuuuhui/Basic-python-answers
/梁勇版_6.16.py
407
3.953125
4
year =int(input("Enter the year:")) def numberofDaysInAYear(): print("year \t number of days") for i in range(2010,2021): print(i,end ="\t\t") k = 365 if i % 4 == 0 and i % 100 != 0: k = 366 elif i % 400 == 0: k = 366 else: k = 365 print(k,end = "\n") numberofDaysInAYear()
754a6aa3c68f2941d6080f77b331d7736648ebac
mikeyball/classwork
/class/exception.py
337
3.765625
4
''' def main(): try: x=input("give me your age") print(x+5) except: print("Why you don't give me number") main() ''' def main(): newlist=[] try: x=input("give me your age") newlist.append(x) print(newlist[4]) except: print("Why you don't give me number") main()
12cdd52588da4ba7fe962e17fe51ddb8d4a03d7e
XrossFox/GuideScrapper
/GuideScrapper.py
3,574
3.5
4
import urllib.request from bs4 import BeautifulSoup import pdfkit import os from fileinput import filename from _codecs import decode import codecs import shutil ''' It recives an url Reads the source code of the page/s Parses the pages Outputs Temporal pages in temporal folder1 Gets all the pages, then fuse them into a single PDF Success TODO: Delete temporal folder before exit. TODO: To make it compatible with single paged, spaghetti guides. ''' def send_response(url,headers): req = urllib.request.Request(url, None, headers) print(url) #Seends request response = urllib.request.urlopen(req) #Reads page page = response.read() return page def get_page(url,max_page): #An array of pages pages_array = [] #Header, just in case, yes, i copy-pasted from Stack Overflow user_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3' headers = { 'User-Agent' : user_agent } #Requesting is done here, request main page and add its extra pages pages_array.append(send_response(url,headers)) for i in range(max_page): n = i + 1 print (str(i)+" : "+str(n)) if n >= max_page: break urltemp = url+"?page="+str(n) pages_array.append(send_response(urltemp,headers)) return pages_array def to_pdf(): #Here is where you turn the temporal pages into a single PDF. #Yes, it should be 2 different methods, but im a lil bit too lazy dir_array = [] for file in os.listdir("temp"): if file.endswith(".html"): print(os.path.join("temp", file)) dir_array.append(os.path.join("temp", file)) pdfkit.from_file(dir_array,'guide.pdf') def parse_content(page,number,size): #Yet, another method that should be 2 #Here, we parse the page array #This if, is for avoiding an unsorted PDF if(number < 10): filename = 'temp/page0'+str(number)+'.html' else: filename = 'temp/page'+str(number)+'.html' #Creates temp dir to store the htmls, if doesnt exist, it creates a new folder #It strips unneeded html tags, and outputs a temporal HTML os.makedirs(os.path.dirname(filename), exist_ok=True) soup = BeautifulSoup(page, 'html.parser') if size == 1: text = soup.find('pre',{"id":"faqtext"}) writo_to(filename,text) else: for script in soup.find_all('script'): script.extract() for a in soup.find_all('a'): a['href'] = '#' for div in soup.find_all('div',{'class':'body'}): div.extract() for div in soup.find_all('div',{'class':'head'}): div.extract() for div in soup.find_all('div',{'class':'header'}): div.extract() soup.find('div',{'class':'ftoc'}).extract() pod = soup.find_all('div', {'class':'pod'}) writo_to(filename,str(pod)) def writo_to(filename,text): file = codecs.open(filename, 'w','utf-8') out = str(text).encode('utf-8','strict') file.write(out.decode('utf-8')) #Replace URL and pages #If guide only has a single, spaghetti text page, set pages to 0 index = get_page("URL Goes Here", 0) array_of_html = [] for i in range(len(index)): array_of_html.append(parse_content(index[i],i,len(index))) to_pdf() print('Removing temo folder:') shutil.rmtree('temp') print('All done!') exit()
763c60155502ef80be56326982300dbde029bf52
noh-yj/algorithm
/Data_Structure/recursive_func.py
604
4.0625
4
# 재귀 함수: 자기 자신을 다시 호출하는 함수 # 특정 깊이에서 탈출하는게 중요 즉 종료 조건을 꼭 명시해야 함 # def recursive_function(): # print('재귀 함수를 호출합니다.') # recursive_function() # recursive_function() # def recursive_function(i): # if i == 100: # return # print(i, '재귀 함수를 호출합니다.') # recursive_function(i + 1) # print(i, '번째에서 종료') # recursive_function(1) # def factorial(n): # if n <= 1: # return 1 # return n*factorial(n-1) # print(factorial(5))
75be460138fa574c46b47fc9a6ba44ea6ce6439d
FabioDPires/Blackjack
/deck.py
575
3.703125
4
from card import Card import random class Deck: def __init__(self): self.cards = [] def fill_deck(self): for x in range(4): # values 0,1,2,3 of cards' suit for y in range(13): card = Card(y + 1, x); self.cards.append(card); random.shuffle(self.cards) def show_deck_card(self): for card in self.cards: print(f'|Suit: {card.suit} ,Value: {card.value} |') def draw_card(self): drawn_card = self.cards[0] self.cards.pop(0) return drawn_card
07db599dbaebab813b223f4719e478497ca429f6
chrisleewilliams/github-upload
/Exercises/Chapter3/exercise14.py
470
4.0625
4
# program to find the average of a list of numbers a user provides # Author: Chris Williams def main(): print("Hello, If you provide a list of numbers I can find the average of the numbers.") y = int(input("How many numbers will you be providing? ")) total = 0 num = 0 for i in range(y): num = float(input("Enter a number: ")) total = num + total avg = total / y print("The average of the numbers you provided is", avg) main()
dd9539a9604118a7e94ea087b7f7eeb886485745
ajeetsinghparmar/loan_approval_prediction
/predict_loan.py
963
3.546875
4
from loan_predict import model import numpy as np while True: a_name = input('Enter Your Name ') a_income = input('Enter Your Income ') c_income = input('Enter Your Coapplicant Income ') l_amount = input('Enter Loan Amount ') l_term = input('Enter term of loan ') c_hist = input('Enter credit history ') try: array =np.array([[a_income, c_income, l_amount, l_term, c_hist]]) array = array.astype(int) # array =np.array([[1500,1000,500,300,1]]) array.reshape(-1, 1) prediction = model.predict(array) # print(prediction) if prediction[0] == 1: print(f'Congratulations {a_name} You are eligible to take loan.') else: print(f'Sorry {a_name} You cannot take loan') except ValueError: print('Please Provide valid inputs') confirm = input('Do you want to check again (Write yes or no) ') if confirm.lower() == 'no': break
ab49fe4062eaaf4b6e2028a17b61a0985c88f185
Janik-ux/minecode
/rnaBeispielEventverarbeitung.py
551
3.609375
4
from tkinter import * def linksklick(event): event.widget.config(bg='green') def rechtsklick(event): event.widget.config(bg='blue') def doppelklick(event): event.widget.config(bg='white') liste=[(x,y) for x in range(10) for y in range(10)] fenster = Tk() for (i,j) in liste: l=Label(fenster, width=2, height=1, bg='white') l.grid(column=i, row=j) l.bind(sequence='<Button-1>', func=linksklick) l.bind(sequence='<Button-3>', func=rechtsklick) l.bind(sequence='<Double-Button-1>', func=doppelklick) fenster.mainloop()
7e9e3e6c2b79020326940756ada799834d26c26d
Lomaev2/python1
/python/Координатные четверти.py
155
3.703125
4
x1 =int(input()) y1 =int(input()) x2 =int(input()) y2 =int(input()) if (x1>0 and x2>0) and (y1>0 and y2>0): print('YES') else: print('NO')
3b048cab9b7e9e9ff344846fe96ebafcbb12fe3e
diegoserodio/Contests
/IEEExtreme 2018/commom_3_pair.py
500
3.765625
4
parity = False done = False a = 0 b = [] pairs = 0 def get_numbers(): global parity, done, a, b if parity == False: a = int(input()) parity = True else: b = list(input().split(' ')) parity = False done = True return a, b while True: index, numbers = get_numbers() if done == True: for i in range(index): for j in range(i + 1, index): soma = int(numbers[i])+int(numbers[j]) if soma % 3 == 0: pairs = pairs + 1 print(pairs) print("\n") pairs = 0 done = False
fd00a3aec92b4bbc146aeb3b4292ecd6644c461a
kapoor-rakshit/pyfiddle
/elementTree_XML_API.py
3,515
4.1875
4
# REFERENCE : https://docs.python.org/3.7/library/xml.etree.elementtree.html # The xml.etree.ElementTree (ET) module implements a simple and efficient API for parsing and creating XML data. # ET has two classes for this purpose - ElementTree represents the whole XML document as a tree, # and Element represents a single node in this tree. # READING XML FILE --------------------- # importing data by reading from a file import xml.etree.ElementTree as ET tree = ET.parse('testXML.xml') root = tree.getroot() # an Element has a tagNAME, dictionary of attributes, text content within tag print(root.tag) print(root.attrib) print(root.text) # children nodes over which we can iterate for i in root: print(i.tag, i.attrib, i.text) for j in i: print("<" + j.tag + ">", j.attrib, j.text) print("---------------------------------------") # Children are nested, and we can access specific child nodes by index also print(root[2][2].text) # Element.iter() : iterate recursively over all sub-tree of an element below it (its children, their children, and so on). # Element.findall() : finds only elements with a tag which are DIRECT children of the current element. # Element.find() : finds the first child with a particular tag. # Element.get() : accesses the element’s attribute specified. # 1 tags_list = root.iter("year") for t in tags_list: print(t.text) # 2 country_list = root.findall("country") for c in country_list: print(c.find("rank").text) print(c.get("capital")) print("-----------------") # MODIFYING EXISTING XML FILE ------------------------------- # Element.text : changing its text content # Element.set() : adding and modifying attributes # Element.remove() : remove it's child element, STRING not allowed, only Element object # Element.append() : adding new children # ElementTree.write() : build XML documents and write them to files # 1 # add one to each country’s rank, and add an updated attribute to the rank element for rank in root.iter('rank'): new_rank = int(rank.text) + 1 rank.text = str(new_rank) rank.set('updated', 'yes') tree.write('testXML.xml') # 2 # remove all countries with a rank higher than 50 for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('testXML.xml') # 3 # remove attribute of an element, using pop('key', defaultValue_to_return) as attrib is a dict() root[2][0].attrib.pop("updated", None) tree.write("testXML.xml") # CREATING NEW XML FILE ------------------------ # ELEMENT TREE tree = ET.ElementTree() # ELEMENT (tag) of TREE roottag = ET.Element("ROOT_TAG", {"version" : "1.0"}) # SUB-ELEMENT (child tag) childtag1 = ET.SubElement(roottag, "CHILD_TAG_1") # attribute values can be configured one at a time with set() # or all at once by passing a dictionary childtag1.set("key1", "val1") childtag1.set("key1", "val modified") # COMMENT appended comment = ET.Comment('comment generated for ETwork example') childtag1.append(comment) # MODIFY text of ELEMENT childtag1.text = "content of child tag 1" # dict passed for attrib values childtag2 = ET.SubElement(childtag1, "CHILD_TAG_2", {"key1" : "val1", "key2" : "val2"}) childtag2.text = "content of child tag 2" # SET root tag and write to a file tree._setroot(roottag) tree.write("chkxml.xml")
85c318a4d7e31966fb62fe7d7debe9f4199feb75
lucassilva-dev/codigo_Python
/ex075.py
439
4
4
n = (int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: '))) print(f'Você digitou os valores {n}') print(f'O valor 9 apareceu {n.count(9)} vezes') print(f'O valor 3 apareceu na {n.index(3)+1} posição') print(f'Os valores pares foram digitados foram ', end='') for numero in n: if n % 2 == 0: print(n, end=' ')
f2c9d012d840d3c68ec318863b9e2648f254eaec
4workspace/Python-calisma-notlari
/2_format.py
1,075
4.4375
4
""" Burada süslü parantez {} yerine format icine yazilan deger gelir süslü parantezin içine ilkine 0 diğerine 1 yazıldığında sıralı şekilde yerleştirilir ancak {} içine 1 ve 0 yazıldığında 2. yazı ilkinin yerine 1. yazı ise ikinciinin yerine yazılır """ name = "Ahmet" surname = "CETIN" age = 27 """ print("My name is {} {}".format(name, surname)) print("My name is {0} {1}".format(name, surname)) print("My name is {1} {0}".format(name, surname)) print("My name is {n} {s}".format(n=name, s=surname)) print("My name is {s} {n}".format(n=name, s=surname)) print("My name is {n} {s}".format(n=name, s=surname)) print("My name is {} {} and I'm {} years old".format(name, surname, age)) """ print(f"My name is {name} {surname} and I'm {age} years old") # bu da aynı görevi gören "f string" metodu result = 200/700 print("the result is {}".format(result)) print("the result is {r:1.3}".format(r=result)) # 1: virgulden onceki, 3 ise virgülden sonra kaç karakterlik yer ayrılacağını belirtir
c720aa5fbedb00ea2d6bd7cad5b29eff90f790e2
kalehub/tuntas-hacker-rank
/designer-pdf.py
714
3.78125
4
from string import ascii_lowercase def design_pdf_viewer(char_height, word): word = word.lower() list_of_words = list() # dictionary to know the alphabet ALPHABET = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=0)} numbers = [ALPHABET[w] for w in word if w in ALPHABET] for n in numbers: list_of_words.append(char_height[int(n)]) return max(list_of_words)*len(word) def main(): # result = design_pdf_viewer([1,3,1,3,1,4,1,3,2,5,5,5,5,1,1,5,5,1,5,2,5,5,5,5,5,5], "torn") result = design_pdf_viewer([1,3,1,3,1,4,1,3,2,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], "abc") print(f"Hasil: {result}") if __name__ == "__main__": main()
a8c62809d2c403679ad5a85cd5ed4f396594bfb3
Crypto-Dimo/textbook_ex
/checking_usernames.py
309
3.53125
4
current_users = ['cryptodimo', 'fedefio', 'dimix', 'jackking', 'minus'] new_users = ['ildimo', 'fedefio', 'karamella', 'dimix', 'Ada'] for user in new_users: if user in current_users: print("Username already in use, please try another one.") else: print("The username is available.")
09281756052bad7f673e84386792352f2843f4c7
drahmuty/Algorithm-Design-Manual
/03-10.py
1,438
3.71875
4
""" For best-fit scenario: - Each bucket is a node on the tree. - For each new item, find the maximum node that can hold the new item. This takes O(n log n) time worst case. - Add the new item to that node and update the total value of the node. - Rebalance the tree. - Return the total number of nodes as the final step. This takes O(n) time. For worst-fit scenario: - For each new item, find the minimum node that can hold the new item. This takes O(n log n) time worst case. - Add the new item to that node and update the total value of the node. - Rebalance the tree. - Return the total number of nodes as the final step. This takes O(n) time. """ def main(items, tree, total): for item in items: bestfit(item, tree, total) countnodes(tree) def bestfit(item, tree, total): target = total - item if tree.value == target: tree.value = tree.value + item elif tree.value < target: if tree.right is None: bestfit(item, tree, total-1) # taking a break. This isn't complete else: bestfit(item, tree.right, total) else: if tree.left is None: tree.left = Tree(item) else: bestfit(item, tree.left, total) def worstfit(item, tree, total): while tree.left is not None: tree = tree.left if tree.value + item <= total: tree.value = tree.value + item else: tree.left = Tree(item)
9480532b7f8fce2dd7ab84a359a70b186102ad4c
lixinxin2019/LaGou2Q
/homework002.py
3,385
3.859375
4
# 课后作业:自己写一个面向对象的例子 # 描述: # 创建一个类(Animal)【动物类】,类里有属性(名称,颜色,年龄,性别),类方法(会叫,会跑) import yaml class Animal: def __init__(self, name, color, age, gender): self.name = name self.color = color self.age = age self.gender = gender def shout(self): print(f"{self.name} 会叫") def run(self): print(f"{self.name} 会跑") # 创建子类【猫】,继承【动物类】, class Cat(Animal): # - 复写父类的__init__方法,继承父类的属性, # - 添加一个新的属性,毛发=短毛, def __init__(self, name, color, age, gender, hair="短毛"): self.name = name self.color = color self.age = age self.gender = gender self.hair = hair # - 添加一个新的方法, 会捉老鼠, def catch_mouse(self): print(f"{self.name} 会捉老鼠") # - 复写父类的‘【会叫】的方法,改成【喵喵叫】 def shout(self): print(f"{self.name} 会喵喵叫~") # 打印猫猫的信息 def info(self): print(f"猫猫的名字是:{self.name},颜色是:{self.color},年龄是:{self.age},性别是:{self.gender},毛发是:{self.hair},捉到了老鼠") # 创建子类【狗】,继承【动物类】, class Dog(Animal): # - 复写父类的__init__方法,继承父类的属性, # - 添加一个新的属性,毛发=长毛, def __init__(self, name, color, age, gender, hair="长毛"): self.name = name self.color = color self.age = age self.gender = gender self.hair = hair # - 添加一个新的方法, 会看家, def outstanding(self): print(f"{self.name} 会看家!") # - 复写父类的【会叫】的方法,改成【汪汪叫】 def shout(self): print(f"{self.name} 会汪汪叫!") # - 打印狗狗的信息 def info(self): print(f"狗狗的名字是:{self.name},颜色是:{self.color},年龄是:{self.age},性别是:{self.gender},毛发是:{self.hair}") if __name__ == '__main__': #调用data.yaml中的数据: with open("data.yaml") as f: datas = yaml.safe_load(f) print(datas) mycat = datas["mycat"] mydog = datas["mydog"] # 创建一个猫猫实例 #cat = Cat("小黑猫", "黑色", 1, "母猫") #创建一个猫猫实例,使用data.yaml中的数据管理实例的属性 cat = Cat(mycat["name"], mycat["color"], mycat["age"], mycat["gender"]) # - 调用捉老鼠的方法 cat.catch_mouse() # - 打印【猫猫的姓名,颜色,年龄,性别,毛发,捉到了老鼠】。 cat.info() #=========================================================== # 创建一个狗狗实例 #dog = Dog("阿黄", "黄色", 1, "母狗") # 创建一个狗狗实例,使用data.yaml中的数据管理实例的属性 dog = Dog(mydog["name"], mydog["color"], mydog["age"], mydog["gender"]) # - 调用【会看家】的方法 dog.outstanding() # - 打印【狗狗的姓名,颜色,年龄,性别,毛发】。 dog.info() # 4、使用 yaml 来管理实例的属性 # 5、提交代码到自己的github仓库, 贴到作业贴上
dee6b58bec5e18ada5417e80c7b156b177739b8a
cxs7650/Unit-1
/script.py
1,303
3.734375
4
import codecademylib from matplotlib import pyplot as plt unit_topics = ['Limits', 'Derivatives', 'Integrals', 'Diff Eq', 'Applications'] middle_school_a = [80, 85, 84, 83, 86] middle_school_b = [73, 78, 77, 82, 86] def create_x(t, w, n, d): return [t*x + w*n for x in range(d)] # Make your chart here school_a_x = [0.8, 2.8, 4.8, 6.8, 8.8] school_b_x = [1.6, 3.6, 5.6, 7.6, 9.6] n = 1 # This is our first dataset (out of 2) t = 2 # Number of datasets d = 5 # Number of sets of bars w = 0.8 # Width of each bar school_a_x = [t*x + w*n for x in range(d)] plt.bar(school_a_x, middle_school_a) #1 n = 2 # This is our second dataset (out of 2) t = 2 # Number of datasets d = 5 # Number of sets of bars w = 0.8 # Width of each bar school_b_x = [t*x + w*n for x in range(d)] #2 creating width & height plt.figure(figsize=(10, 8)) # Make your chart here#creating set of axes ax = plt.subplot()#3 plt.bar(school_a_x, middle_school_a )#4 plt.bar(school_b_x, middle_school_b) middle_x = [(a + b)/2.0 for a, b in zip(school_a_x, school_b_x)]#5 ax.set_xticks(middle_x)#6 ax.set_xticklabels(unit_topics)#7 plt.legend(['Middle School A', 'Middle School B'])#8 plt.title("Test Averages on Different Units")#9 plt.xlabel("Unit") plt.ylabel("Test Average") plt.show() plt.savefig('my_side_by_side.png')
dda59ff66d1ae110e39095a3c0fd596ecb10df82
PengJi/python-code
/pythonic/decorator/intro.py
1,159
4.0625
4
# -*- coding: utf-8 -*- """ 装饰器介绍 """ # 简单装饰器 def my_decorator(func): def wrapper(): print('wrapper of decorator') func() return wrapper # 第二种调用方式 def greet(): print('hello world') greet = my_decorator(greet) greet() # 第二种调用方式:更优雅的调用方式,使用@ @my_decorator def greet(): print('hello world') greet() # 带参数的装饰器 def my_decorator(func): def wrapper(message): print('wrapper of decorator') func(message) return wrapper @my_decorator def greet(message): print(message) greet('hello world') # 可传入任务参数的装饰器 def my_decorator(func): def wrapper(*args, **kwargs): print('wrapper of decorator') func(*args, **kwargs) return wrapper # 带有自定义参数的装饰器 def repeat(num): def my_decorator(func): def wrapper(*args, **kwargs): for i in range(num): print('wrapper of decorator') func(*args, **kwargs) return wrapper return my_decorator @repeat(4) def greet(message): print(message)
f9c1c83a0c19aa6c0dc923b9c8456ac52ed12443
bhculqui/Curso-python-bhculqui
/input.py
195
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 13 18:53:32 2019 @author: BLUEIT-PARTICIPANTE """ firstname = input("what is your first name?") a=input() print("Hello "+ firstname ,a+3)
91821332878f273d752c4a3da6fcebd623a72d0f
newpheeraphat/banana
/Algorithms/List/T_FindIndex.py
353
3.5
4
class Solution: def search(self, lst : list, item : int) -> int: try: result = lst.index(item) return result except: return -1 if __name__ == "__main__": p1 = Solution() print(p1.search([1, 2, 3, 4], 3)) print(p1.search([2, 4, 6, 8, 10], 8)) print(p1.search([1, 3, 5, 7, 9], 11))
f4e743e6e0c5d72c4638c8efb13dfa086158052d
blubbers122/Python-LeetCode-Problems
/Easy/Find_Numbers_with_Even_Number_of_Digits.py
250
3.53125
4
class Solution: def findNumbers(self, nums) -> int: evens = 0 for num in nums: if len(str(num)) % 2 == 0: evens += 1 return evens s = Solution() print(s.findNumbers(nums = [555,901,482,1771]))
cea5b206d17df68d37b427195388f5454412cd55
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_155/1880.py
1,091
3.765625
4
#!/usr/bin/python3 import sys from collections import namedtuple def case(line): max_shyness,syness_str = line.split(' ') shyness = dict(zip(range(int(max_shyness) + 1), (int(c) for c in syness_str))) return shyness def cases(lines): return (case(line) for line in lines if line) def main(filename): with open(filename, 'r') as input_file: lines = input_file.read().split('\n') number_of_cases = int(lines[0]) for i,case in zip(range(1,number_of_cases+1), cases(lines[1:])): #print("Case #{}: {}".format(i, case)) print("Case #{}: {}".format(i, solve(case))) def solve(case): """A simple greedy algorithm that determines the amount it takes to get to the next level""" number_of_people_applauding = case[0] number_of_extra_people_required = 0 for shyness_level in list(case.keys())[1:]: extra_friends = 1 if number_of_people_applauding < shyness_level else 0 number_of_extra_people_required += extra_friends number_of_people_applauding += extra_friends + case[shyness_level] return number_of_extra_people_required main("in.dat")
2312488fb0c9b07dbc94ef61d9363441ffafb0df
sharepusher/leetcode-lintcode
/math/double_factorial.py
652
3.65625
4
## Reference # https://www.lintcode.com/problem/double-factorial/description ## Easy - Recursion ## Description # Given a number n, return the double factorial of the number. # In mathematics, the product of all the integers from 1 up to some non-negative integer n that have the same parity (odd or even) # as n is called the double factorial. # We guarantee that the result does not exceed long. #n is a positive integer ## Example # Input: n = 5 # Output: 15 # Explanation: # 5!! = 5 * 3 * 1 = 15 ## Input: n = 6 # Output: 48 # Explanation: # 6!! = 6 * 4 * 2 = 48 ## Analysis # n!! = n * (n-2)!! # n!! = 1 if n = 0 or n = 1 ## Solution
0a65ab5a12172e052d8c73d2630d95c396280272
stsewd/ucuenca.py
/examples/mean.py
845
3.5
4
""" Script para calcular el promedio de todas las materias aprobadas de un estudiante. """ from statistics import mean from ucuenca import Ucuenca student_id = input('Cédula: ') uc = Ucuenca() for career in uc.careers(student_id): career_id = career['carrera_id'] career_plan = career['placar_id'] curriculum_id = career['malla_id'] notes = [ class_['nota_final'] for class_ in uc.curriculum_progress( student_id, career_id, curriculum_id, career_plan ) if class_['estado'] == 'APROBADO' ] msg = """ Carrera: {career} Materias aprobadas: {num} Suma: {sum} Promedio: {mean} """.format( career=career['carrera'], num=len(notes), sum=sum(notes), mean=mean(notes) ) print(msg)
11974492da5e2e52d4d157539d942329d771a46d
Daisythebun/Module-4
/Main.py
4,179
4.375
4
#Movie Store where user can add, remove and delete and Edit movies. Use can also search the movie name. User can see the list of all movies as well. class Movies: global movieStore movieStore=["intersteller","the great gatsby","12 angry men","requiem for a dream","death note"] #Search movie def searchMovie(self, moviename): print("\nSearch Result:") for i in range(len(movieStore)): if(movieStore[i] == moviename): print(movieStore[i]+" is found in the store") break elif (i ==len(movieStore)-1 and movieStore[i] !=moviename): print("Movie Not found") break #Display movies list def movieList(self): print("List of Movies\n") print('\n'.join(movieStore)) #Add movie to the list def addMovie(self, moviename): for i in range(len(movieStore)): if(i == len(movieStore)-1 and movieStore[i] !=moviename): movieStore.append(moviename) print("\n"+moviename+" is added to the Store") print("UPDATED MOVIES LIST:\n") print('\n'.join(movieStore)) break elif(movieStore[i] == moviename): print("Movie is already in the Store") break #delete movie from the list def deleteMovie(self, moviename): for i in range(len(movieStore)): if(i == len(movieStore)-1 and movieStore[i] !=moviename): print("Movie is not in the Store") break elif(movieStore[i] == moviename): movieStore.remove(moviename) print("\n"+moviename+" is removed from the movie list") print("UPDATED MOVIES LIST:\n") print('\n'.join(movieStore)) break #Update movie from the list def updateMovie(self, moviename,updatedname): for i in range(len(movieStore)): if(i == len(movieStore)-1 and movieStore[i] !=moviename): print("Movie is not in the Store") break elif(movieStore[i] == moviename): print("\n"+moviename+" is changeed to "+updatedname) movieStore[i] = updatedname print("UPDATED MOVIES LIST:\n") print('\n'.join(movieStore)) break def main(): loginpin = 3040 attempt = 3 print("\t\t******************** WELCOME TO THE MOVIES STORE ********************") print("\n\nYOU ARE ALLOWED ONLY 3 LOGIN ATTEMPT, IF YOU ARE FAILED THE PROGRAM WILL BE TERMINATED: \n\n") print("ENTER LOGIN PIN: ") for i in range(attempt): pin = int(input()) if(pin == loginpin): movies = Movies() while(True): print("\nWELCOME TO THE MOVIE STORE\n1. MOVIE LIST\n2. SEARCH A MOVIE\n3. ADD MOVIE\n4.DELETE MOVIE\n5.UPDATE MOVIE\n6.EXIT\n") user = int(input()) if(user == 1): print("\nMOVIES LIST:\n") movies.movieList() elif(user == 2): print("ENTER MOVIE NAME: ") name = input() movies.searchMovie(name) elif(user == 3 ): name = input("ADD MOVIE TO THE STORE:\n") movies.addMovie(name) elif(user == 4): name = input("DELETE MOVIE FROM THE STORE:\n") movies.deleteMovie(name) elif(user == 5): movies.movieList() name = input("\nENTER THE MOVIE NAME YOU WANT TO CHANGE:\n") updated = input("ENTER THE UPDATED MOVIE NAME:\n") movies.updateMovie(name,updated) elif(user == 6): exit() elif(user<1 or user>6): print("invalid input!! Please enter the integer from 1-5 ") break else: atempt = attempt - 1 print("Incorrect pin."+str(attempt)+" is left!") main()
eefde76eeff5520289088010e92bee9d7df1cc77
mygithello/python_test
/pythonbase/09python的函数.py
5,356
4.375
4
print(""" --------1----------------------定义一个函数------------------------------------- 你可以定义一个由自己想要功能的函数,以下是简单的规则: 函数的特点: 1.函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。 2.任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。 3.函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。 4.函数内容以冒号起始,并且缩进。 5.return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。 """) print(""" 常用函数使用: """) # def functionname( parameters ): # "函数_文档字符串" # function_suite # return [expression] def printme( str ): "打印传入的字符串到标准显示设备上" print(str) return print("--------------2-----------调用函数-------------------------") printme("my printme test!") print(""" --------------3------------在 python 中,类型属于对象,变量是没有类型的:------------------------- a=[1,2,3] a="Runoob" 以上代码中,[1,2,3] 是 List 类型,"Runoob" 是 String 类型,而变量 a 是没有类型,她仅仅是一个对象的引用(一个指针),可以是 List 类型对象,也可以指向 String 类型对象。 """) print("""--------------------------------值传递还是引用传递---即---传不可变对象和传可变对象---------- 可更改(mutable)与不可更改(immutable)对象 在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象 """) #!/usr/bin/python # -*- coding: UTF-8 -*- print("----------------不可变传递--------") def ChangeInt( a ): #当接受到参数,是接受到一个值,用一个方法内飞引用指向这个值,此处是对个这个方法内的引用的值赋值 a = 10 b = 2 ChangeInt(b) print(b) # 结果是 2 print("------------------可变对象传递实例------") #!/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 def changeme( mylist ):#此列接收的参数是个引用,当做修改时,直接是对引用对应的值进行了修改 "修改传入的列表" mylist.append([1,2,3,4]); print("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10,20,30]; changeme( mylist ); print("函数外取值: ", mylist) print("----参数1---调用参数必须和声明的参数一样----也就是小括号里面声明的参数-") print("----参数2---键字参数允许函数调用时参数的顺序与声明时不一致----也就是才调用的时候指明参数名和参数值-") print("--------------------默认参数----方法形参内定义参数名和默认值,如果没有接收到该参数,方法就使用事先定义的默认值------------------") #!/usr/bin/python # -*- coding: UTF-8 -*- #可写函数说明 def printinfo( name, age = 35 ): "打印任何传入的字符串" print("Name: ", name); print("Age ", age); return; #调用printinfo函数 printinfo( age=50, name="miki" ); printinfo( name="miki" ); print(""" ---------------不定长参数----能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数------------ """) #!/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 def printinfo( arg1, *vartuple ): "打印任何传入的参数" print("输出: ") print(arg1) for var in vartuple: print(var) return; # 调用printinfo 函数 printinfo( 10 ); printinfo( 70, 60, 50 ); print("---------------------匿名函数------------") #!/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 print("---lambda 语法只包含一个语句------lambda [arg1 [,arg2,.....argn]]:expression") sum = lambda arg1, arg2: arg1 + arg2; # 调用sum函数 print("相加后的值为 : ", sum( 10, 20 )) print("相加后的值为 : ", sum( 20, 20 )) print("----------------------------------------------------") #!/usr/bin/python # -*- coding: UTF-8 -*- print("-------------------return 语句接受返回值--------") # 可写函数说明 def sum( arg1, arg2 ): # 返回2个参数的和." total = arg1 + arg2 print("函数内 : ", total) return total; # 调用sum函数 total = sum( 10, 20 ); print("函数外: "+str(total)) print("---------变量的作用域---局部变量和全局变量--------") #!/usr/bin/python # -*- coding: UTF-8 -*- total = 0; # 这是一个全局变量 # 可写函数说明 def sum( arg1, arg2 ): #返回2个参数的和." total = arg1 + arg2; # total在这里是局部变量. print("函数内是局部变量 : ", total) return total; #调用sum函数 sum( 10, 20 ); print("函数外是全局变量 : ", total) print("python 的数据类型转换函数:str(),int(),float(),list()") print(float(3.43)) print(type(float(3.43))) a='list()函数的使用,把数据转换成列表类型' print(list(a)) print(type(list(a)))
1a280541ce0d5321c12bd5823fa6579b384213c0
veltzer/pytimer
/pytimer/pytimer.py
599
3.515625
4
import time class Timer: def __init__(self, do_print=True, do_title=None): self.start_time = None self.end_time = None self.print = do_print self.title = do_title def __enter__(self): self.start_time = time.time() def __exit__(self, itype, value, traceback): self.end_time = time.time() diff = self.end_time - self.start_time if self.print: if self.title: print(f"time taken for [{self.title}]: {diff:.6f} seconds") else: print(f"time taken: {diff:.6f} seconds")
def6a6e3228434919e8f5dc9f88f13215696988d
juancq/character-evolver
/app/vertex_shader/pygene/gamete.py
1,699
3.90625
4
""" Implements gametes, which are the result of splitting an organism's genome in two, and are used in the organism's sexual reproduction In our model, I don't use any concept of a chromosome. In biology, during a cell's interphase, there are no chromosomes as such - the genetic material is scattered chaotically throughout the cell nucleus. Chromosomes (from my limited knowledge of biologi) are mostly just a device used in cell division. Since division of cells in this model isn't constrained by the physical structure of the cell, we shouldn't need a construct of chromosomes. Gametes support the python '+' operator for sexual reproduction. Adding two gametes together produces a whole new Organism. """ from xmlio import PGXmlMixin class Gamete(PGXmlMixin): """ Contains a set of genes. Two gametes can be added together to form a new organism """ def __init__(self, orgclass, **genes): """ Creates a new gamete from a set of genes """ self.orgclass = orgclass self.genes = dict(genes) def __getitem__(self, name): """ Fetch a single gene by name """ return self.genes[name] def __add__(self, other): """ Combines this gamete with another gamete to form an organism """ return self.conceive(other) def conceive(self, other): """ Returns a whole new Organism class from the combination of this gamete with another """ if not isinstance(other, Gamete): raise Exception("Trying to mate a gamete with a non-gamete") return self.orgclass(self, other)
1b5544ff00f086b08e3d0f9e2e76e276118aa17d
kumarravindra/leetworld
/ltc_python_topics/com/lc/easy/Add_String.py
649
3.796875
4
''' https://leetcode.com/problems/add-strings/ ord function : https://www.geeksforgeeks.org/ord-function-python/ ''' def add_String(str1, str2): numlist1 = list(str1) numlist2 = list(str2) carry = 0 res = [] while len(numlist1) > 0 or len(numlist2) > 0: n1 = ord(numlist1.pop()) - ord('0') if len(numlist1) > 0 else 0 n2 = ord(numlist2.pop()) - ord('0') if len(numlist2) > 0 else 0 temp = n1 + n2 + carry res.append(temp % 10) carry = temp // 10 if carry: res.append(carry) return ''.join([str(i) for i in res])[::-1] word1 = "540" word2 = "290" print(add_String(word1,word2))
41fc8e627d7b82698c4bef8988c99407d8ae8ea0
RickArora/Algo-practice
/dynamic-programming/rodCutting.py
1,150
3.875
4
# Given a rod length n inches an an array that contain prices of all pieces of size smaller then n. # Determine the maximum value obtainable by cutting up the rod and selling the pieces import sys INT_MIN = -sys.maxsize-1 #min is initialized to negative numbers def cutRod(price, n): # defining cut rod with 2 parameters price and n which is the length of the rod val = [0 for x in range(n+1)] # initializes an array for 0 to n elements val[0] = 0 # trivial statement since all values in the array val were set to 0 anyways #bottom-up manner for i in range(1, n+1): # iterates from 1 to n+1 in the value i max_val = INT_MIN # min possible value assigned to max_val for j in range(i): # iterates from 0 to i max_val = max(max_val, price[j] + val[i-j-1]) #assigns max val the maximum value from the current max val and the price[j] + a precomputed value in val val[i] = max_val # assigns val[i] another entry cached in our memo array print(val[i]) return val[n] # returns the last entry, i.e the highest val #main price = [2,10,15,16,21] size = len(price) print("Max value is " + str(cutRod(price, size)))
cdf2b987524a798de728fa89676187ff95398d3d
302wanger/Python-record
/Learn-code-note/Python/Head-First-Python/Chapter-1/version-1.py
1,502
4.21875
4
# -*- coding: utf-8 -*- # 这个是第一章的列表的知识 # 向列表中添加新的元素 # 这是老的列表 movies = ["The Holy Grail","The Life of Brain","The Meaning of Life"] print(movies) # 方法1 # 添加新元素 movies.insert(1,1975) # 将1975添加到第2个位置 movies.insert(3,1976) # 将1976添加到第4个位置 movies.insert(5,1983) # 将1983添加到第6个位置 print(movies) # 方法2 # 直接在列表中进行更新 movies = [ "The Holy Grail",1975, "The Life of Brain",1976, "The Meaning of Life",1983 ] print(movies) # 方法1和方法2在元素不多的情况下都可以使用。 # 迭代的学习 fav_movies = ["The Holy Grail", "The Life of Brain"] print(fav_movies[0]) # 在屏幕上显示各项列表的值 print(fav_movies[1]) # 该迭代列表中的数据了 # 使用for循环进行列表的迭代,适用于任意大小的列表 for each_filck in fav_movies: print(each_filck) # 同时可以用while循环进行同样的迭代 count = 0 while count < len(movies): print(movies[count]) count = count + 1 # 在列表中存储列表 movies = [ "The Holy Grail",1975, "The Life of Brain",1976, ["Michal Palin","John Cleese",1789] ] print(movies[4][1]) # 嵌套在某个列表中的列表,而该列表本身又嵌套在另一个列表中。 # 通过for循环来迭代新的movies列表 for each_item in movies: print(each_item) # 迭代结果显示最后一行没有迭代元素,而是迭代出了一个列表,这是不对的。
4740471cc305cf94af154a869aa5215b5aa92b59
QPromise/DataStructure-UsingPython
/3.链表/CH03_02.py
2,801
3.75
4
import sys class employee: def __init__(self): self.num=0 self.salary=0 self.name='' self.next=None def findnode(head,num): ptr=head while ptr!=None: if ptr.num==num: return ptr ptr=ptr.next return ptr def insertnode(head,ptr,num,salary,name): InsertNode=employee() if not InsertNode: return None InsertNode.num=num InsertNode.salary=salary InsertNode.name=name InsertNode.next=None if ptr==None: #插入第一个节点 InsertNode.next=head return InsertNode else: if ptr.next==None: #插入最后一个节点 ptr.next=InsertNode else: #插入中间节点 InsertNode.next=ptr.next ptr.next=InsertNode return head position=0 data=[[1001,32367],[1002,24388],[1003,27556],[1007,31299], \ [1012,42660],[1014,25676],[1018,44145],[1043,52182], \ [1031,32769],[1037,21100],[1041,32196],[1046,25776]] namedata=['Allen','Scott','Marry','John','Mark','Ricky', \ 'Lisa','Jasica','Hanson','Amy','Bob','Jack'] print('员工编号 薪水 员工编号 薪水 员工编号 薪水 员工编号 薪水') print('-------------------------------------------------------') for i in range(3): for j in range(4): print('[%4d] $%5d ' %(data[j*3+i][0],data[j*3+i][1]),end='') print() print('------------------------------------------------------\n') head=employee() #建立链表的头部 head.next=None if not head: print('Error!! 内存分配失败!!\n') sys.exit(1) head.num=data[0][0] head.name=namedata[0] head.salary=data[0][1] head.next=None ptr=head for i in range(1,12): #建立链表 newnode=employee() newnode.next=None newnode.num=data[i][0] newnode.name=namedata[i] newnode.salary=data[i][1] newnode.next=None ptr.next=newnode ptr=ptr.next while(True): print('请输入要插入其后的员工编号,如输入的编号不在此链表中,') position=int(input('新输入的员工节点将视为此链表的链表头部,要结束插入过程,请输入-1:')) if position ==-1: break else: ptr=findnode(head,position) new_num=int(input('请输入新插入的员工编号:')) new_salary=int(input('请输入新插入的员工薪水:')) new_name=input('请输入新插入的员工姓名: ') head=insertnode(head,ptr,new_num,new_salary,new_name) print() ptr=head print('\t员工编号 姓名\t薪水') print('\t==============================') while ptr!=None: print('\t[%2d]\t[ %-7s]\t[%3d]' %(ptr.num,ptr.name,ptr.salary)) ptr=ptr.next
7dd6dca92ac3db2b95fa6afc5f4ff609e31b00c4
rickmur/pyCrashCourse
/foods.py
290
4.03125
4
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") for mf in my_foods: print (mf.title()) print("\nMy friend's favorite foods are:") for ff in friend_foods: print ff
25e124489b378f87d1a903a1c8f4edad7b001c3f
TheNeuralBit/aoc2017
/10/sol1.py
792
3.5
4
def tie_knots(l, lengths): idx = 0 skip = 0 for length in lengths: knot(l, length, idx) idx = (idx + length + skip) % len(l) skip += 1 return l def knot(l, length, idx): halflen = int(length/2) lindices = (i % len(l) for i in range(idx, idx+halflen)) rindices = (i % len(l) for i in range(idx+length - 1, idx+length-1-halflen, -1)) for left, right in zip(lindices, rindices): tmp = l[right] l[right] = l[left] l[left] = tmp return l assert knot([0, 1, 2, 3, 4], 3, 1) == [0, 3, 2, 1, 4] assert knot([0, 1, 2, 3, 4], 4, 3) == [4, 3, 2, 1, 0] with open('input', 'r') as fp: lengths = map(int, fp.readline().strip().split(',')) l = list(range(256)) tie_knots(l, lengths) print(l[0]*l[1])
36ca99728c21ecdae5457e5a601a0225a46e77b7
AnkitaJainPatwa/python-assignment1
/Testapp/Complex number.py
310
4.15625
4
#Addition of two numbers print("For Addition of two complex numbers :",(4+3j)+(7+9j)) #Subtration of two numbers print("For Subtraction of two complex numbers :",(4+3j)-(7+9j)) # print("For Multiplication of two complex numbers :",(4+3j)*(7+9j)) # print("For Division of two complex numbers :",(4+3j)/(7+9j))
5a335fe149db393ad44e9eddac468479d9eace84
charliegriffin/GraduateUnschool
/SWE001/crackingTheCodingInterviewPython/sortingAndSearching/mergeSort.py
1,090
4.125
4
import numpy as np # merge sort for integers def mergeSort(list): '''sorts the input list using merge sort''' if len(list) <= 1: return list mid = len(list)//2 left = mergeSort(list[:mid]) # slice 1st half right = mergeSort(list[mid:]) # slice 2nd half return merge(left, right) def merge(left,right): '''takes two sorted lists and returns a single sorted list by comparing the elements one at a time''' if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:],right) return [right[0]] + merge(left, right[1:]) def mergeSortTest(): randList = [np.random.randint(0,100) for i in xrange(10)] print '\nunsorted',randList,'\nsorted',mergeSort(randList) randList = [np.random.randint(0,100) for i in xrange(100)] print '\nunsorted',randList,'\nsorted',mergeSort(randList) mergeSortTest() ''' hitting max recursion depth at 1000 makes this seem much less useful than I originally thought. Maybe I'm missing something'''
46aa0c9c5a77af6ee5c1fcb54681f6fff1e14b44
riziry/MeLearningHelloWorld
/Py/branch_apple.py
1,133
3.984375
4
# Python 2 print('====Branch Apple====') inp = input("How much money do you have? ") money = int(inp) print("money = " + str(money) + " dollars") Aprice = 2 print('Apple Price = ' + str(Aprice) + " dollars") print("=============================================") while inp != "exit": if money > 0: inp = input("How much apple do you want to buy? ") count = int(inp) totalPrice = Aprice * count if money > totalPrice: print("You've bought " + str(count) + " apples for " + str(count * Aprice) + " dollars") print("You've " + str(money - totalPrice) + " dollars left") inp = money - totalPrice elif money == totalPrice: print(("You've bought " + str(count) + " apples")) print("You're money is now empty") inp = money - totalPrice else: print("Not enough money") inp = 0 money = int(inp) print(money) print("=============================================") else: print(type(inp)) inp = input("do you want to recharge money? ") print(inp) if inp == "yes": inp = str(input("How much do you want to recharge? ")) money = int(inp) elif inp == "no": inp = "exit"
0091a7b3c6e2da9149b2837272cc85f03663f509
pnd-tech-club/Python-Exercises
/ex42.py
831
3.6875
4
# is-a class Animal(object): pass # is-a class Dog(Animal): def __init__(self, name): # has-a self.name = name # is-a class Cat(Animal): def __init__(self, name): # has-a self.name = name # is-a class Person(object): def __init__(self, name): # has-a self.name = name # has-a self.pet = None # is-a class Employee(Person): def __init__(self, name, salary): # has-a super(Employee, self).__init__(name) # has-a self.salary = salary # is-a class Fish(object): pass # is-a class Salmon(Fish): pass # is-a class Halibut(Fish): pass # is-a rover = Dog("Rover") # is-a jane = Cat("Jane") # is-a mary = Person("Mary") # is-a mary.pet = jane # is-a frank = Employee("Frank", 120000) # is-a frank.pet = rover # has-a flipper = Fish() # ??? crouse = Salmon() # ??? harry = Halibut()
2502a3448805b66ca11b78806d74dea95cdb13ed
ba-java-instructor-zhukov-82/ma-python-module-six-build-in-system-modules
/labs/work_6_6/solution_6_6.py
729
3.5625
4
#! coding: utf-8 import time # import time module import datetime # import datetime module time.clock() # Set clock start print(time.ctime()) # print current time in format 'Tue May 24 14:09:17 2016’ print(time.localtime().tm_year) # Current time year print(time.localtime().tm_yday) # Current year day print(time.strftime("%d %m. %Y %H:M",time.gmtime())) print(datetime.datetime.strptime("19 Sep. 2012 10:15", "%d %b. %Y %H:%M")) time_1 = datetime.datetime.now() + datetime.timedelta(days = -1) # Create datetime tuple with current day minus one day now = datetime.datetime.now() print('Time delta', (now - time_1).days) # Check the difference with time delta print("Script execution time: %f4.2" % time.clock())
1691ad9cbfa4d50cafe1b3572af37cc05535e6e9
yashaswini87/Latest_Projects
/Bayes Classifier/tagger.py
7,726
3.796875
4
import collections from collections import defaultdict import nltk import pdb def document_features(document, tagger_output): """ This function takes a document and a tagger_output=[(word,tag)] (see functions below), and tells you which words were present as 'words' (as opposed to 'tags') in tagger_output. Parameters ---------- document: string, your document tagger_output: list of tuples of the form [(word, tag)] Returns ------- features : dictionary of tuples ('has(word)': Boolean) Notes ----- Use the nltk.word_tokenize() to break up your text into words """ words = [word for (word,tag) in docTag(document)] # break up text into words s = {word for (word,tag) in tagger_output} # select word from the list of tuples bool_list =[(expression in words) for expression in s] # True if words are present as word in tagger_output features = dict(zip(s,bool_list)) # form a dictionary of tuples return features def usefulDocumentFeatures(doc, dict): tagged_tokens = docTag(doc) words = [] for tup in tagged_tokens: new_word = tup[0] try: if dict[new_word]: words.append(new_word) except KeyError: pass return words def checkFeatures(document, feature_words): """ This function takes a document and a list of feautures, i.e. words you have identitifed as features, and returns a dictionary telling you which words are in the document Parameters ---------- document: list of strings (words in the text you are analyzing) features: list of strings (words in your feature list) Returns ------- features: dictionary keys are Sting (the words) values are Boolean (True if word in feature_words) """ bool_list = [x in document for x in feature_words] # list of booleans to see presence of features features = dict(zip(feature_words,bool_list)) # form a dictionary return features def onlyAlpha(document): """ Takes a list of strings in your document and gets rid of everything that is not alpha, i.e. returns only words Parameters ---------- document: list of strings Returns ------- words: list of strings """ words=[] for w in document: if w.isalpha(): words.append(w) return words def getTopWords(word_list, percent): """ Takes a word list and returns the top percent of freq. of occurence. I.e. if percent = 0.3, then return the top 30% of word_list. Parameters ---------- word_list: list of words percent: float in [0,1] Returns ------- top_words: list Notes ----- Make sure this returns only alpha character strings, i.e. just words. Also, consider using the nltk.FreqDist() """ ###get rid of non alphas in case you have any word_list = onlyAlpha(word_list) topwords=[] ## using nltk.FreqDist() to find the Frequency of words fdist = nltk.FreqDist(word.lower() for word in word_list) popular_words=sorted(fdist, key = fdist.get, reverse = True) topwords=popular_words[:(int(percent*len(popular_words))+1)] return topwords def posTagger(documents, pos_type=None, dummy_filter=False): """ Takes a list of strings, i.e. your documents, and tags all the words in the string using the nltk.pos_tag(). In addition if pos_type is not None the function will return only tuples (word, tag) tuples where tag is of type pos_type. For example, if pos_type = 'NN' we will get back all words tagged with "NN" "NNP" "NNS" etc Parameters ---------- documents: list of strings pos_type: string Returns ------- tagged_words: list of tuples (word, pos) Notes ----- You need to turn each string in your documents list into a list of words and you want to return a list of unique (word, tag) tuples. Use the nltk.word_tokenize() to break up your text into words but MAKE SURE you return only alpha characters words """ tagged_words = [] # Initialize empty list for document in documents: tokenized_doc = nltk.word_tokenize(document) # Tokenize the document taggedTokens = nltk.pos_tag(tokenized_doc) # Tag the tokens first taggedTokens=[(a,b) for (a,b) in taggedTokens if a.isalpha()] #return only alpha character strings in the already tokened list # Now, filter the tokens that don't fit pos_type # And convert to list of lists for bigramtagger maxLen = len(taggedTokens) if dummy_filter: toAdd = [taggedTokens[i][0] for i in range(0,maxLen) if taggedTokens[i][1] not in ['CC','RP','PRP','PRP$','TO','IN','LS','DT']] #toAdd=set(toAdd) ##[list(x) for x in taggedTokens if x[1] == pos_type] elif pos_type is None: toAdd = [taggedTokens[i] for i in range(0,maxLen)] #toAdd=set(toAdd) else: toAdd = [taggedTokens[i] for i in range(0,maxLen) if taggedTokens[i][1][:2]==pos_type[:2]] tagged_words += (toAdd) # Add to list tagged_words=list(set(tagged_words)) return tagged_words def bigramTagger(train_data, docs_to_tag, base_tagger=posTagger, pos_type=None): """ Takes a list of strings, i.e. your documents, trains a bigram tagger using the base_tagger for a first pass, then tags all the words in the documents. In addition if pos_type is not None the function will return only those (word, tag) tuples where tag is of type pos_type. For example, if pos_type = 'NN' we will get back all words tagged with "NN" "NNP" "NNS" etc Parameters ---------- train_data: list of tuples (word, tag), for trainging the tagger docs_to_tag: list of strings, the documents you want to extract tags from pos_type: string Returns ------- tagged_words: list of tuples (word, pos) Notes ----- You need to turn each string in your documents list into a list of words and you want to return a list of unique (word, tag) tuples. Use the nltk.word_tokenize() to break up your text into words but MAKE SURE you return only alpha characters words. Also, note that nltk.bigramTagger() is touchy and doesn't like [(word,tag)] - you need to make this a list of lists, i.e. [[(word,tag)]] """ ourTagger = nltk.BigramTagger(train_data, model=base_tagger) tagged_words = [] # Initialize empty list for document in docs_to_tag: taggedTokens = docTag(document) # Now, filter the tokens that don't fit pos_type # And convert to list of lists for bigramtagger if pos_type is None: toAdd = [taggedTokens[i] for i in range(0,len(taggedTokens))] #toAdd=set(toAdd) else: toAdd = [taggedTokens[i] for i in range(0,len(taggedTokens)) if taggedTokens[i][1][:2]==pos_type[:2]] #toAdd=set(toAdd) ##[list(x) for x in taggedTokens if x[1] == pos_type] tagged_words += toAdd # Add to list tagged_words=set(tagged_words) return tagged_words def docTag(document): """ Takes a document and only returns the ONLY word tokens using onlyAlpha. Parameters: ---------- doc: the document of interest Returns ------- wordList: a list of word tokens. """ tokenized_doc = nltk.word_tokenize(document) taggedTokens = nltk.pos_tag(tokenized_doc) return taggedTokens
860586f6d9d1e52314836911eabab03f9485941e
itsolutionscorp/AutoStyle-Clustering
/assignments/python/61a_hw4/code/18.py
201
3.640625
4
def num_common_letters(goal_word, guess): total = 0 count = 0 while count < len(goal_word): if goal_word[count] in guess: total += 1 count += 1 return total
f263101c785af554f4d88991e0347ca89ddd03aa
SergeantMini/SmartTry
/algo.py
73
3.53125
4
print("Hello man") var x: Int var x = 4 var y:Int var y = 3 print (x*y)
26b38bb7f86f2141d29ade240fb3570d35375480
ziul123/truth-table-generator
/truth-table.py
7,501
3.984375
4
"""Print the truth table of a user input expression. Fixed values for propositions can be set by comma separated <proposition>=<value> pairs. Symbols ------- propositions: any letter followed by any combination of letters, numbers and underscores (except "v" or "tmp") not: the symbol "¬" and: the symbol "^" or: the symbol "v" conditional: the symbol "->" biconditional: the symbol "<->" exit: enter "exit" to exit Usage ----- Binary operations must always be nested in parentheses. For example, "(p v q v r)" must be written as either "((p v q) v r)" or "(p v (q v r))". There must always be a space between the symbol of the operation and each of the operands. Examples -------- ¬p (p v q) ¬(p -> q) (p ^ ¬q), p=True (¬p <-> q), p=True, q=False """ ###BNF### # <expr> ::= <prop>|<neg>|<op> # <prop> ::= "p"|"q"|"r" # <neg> ::= "¬"<prop>|"¬"<op> # <op> ::= "("<expr><sym><expr>")" # <sym> ::= " v "|" ^ "|" -> "|" <-> " ###Tree### class Expr: """ Generic expression class. Methods ------- eval(env): Evaluates the expression. """ def eval(self,env): """ Evaluates the expression. Paremeters ---------- env : dict truth values of the propositions. """ pass class BinOp(Expr): """ Generic binary operation class. Attributes ---------- l : Expr the left operand. r : Expr the right operand. symbol : str the symbol of the operation. """ def __init__(self,l,r): self.l = l self.r = r self.symbol = None def __str__(self): return "(" + str(self.l) + f" {self.symbol} " + str(self.r) + ")" class UnOp(Expr): """ Generic unary operation class. Attributes ---------- r : Expr the operand. """ def __init__(self,r): self.r = r class Prop(Expr): """ Proposition class. Attributes ---------- name : str name of the proposition. """ def __init__(self,name): self.name = name def __str__(self): return self.name def eval(self,env): return env[self.name] class Not(UnOp): """ Not operation. Attributes ---------- r : Expr the operand. """ def __init__(self,r): super().__init__(r) self.symbol = "¬" def __str__(self): return self.symbol + str(self.r) def eval(self,env): return not self.r.eval(env) class Conj(BinOp): """ Conjunction operation. Attributes ---------- l : Expr the left operand. r : Expr the right operand. symbol : str symbol for conjunction: '^'. """ def __init__(self,l,r,symbol = "^"): super().__init__(l,r) self.symbol = symbol def eval(self,env): return self.l.eval(env) and self.r.eval(env) class Disj(BinOp): """ Disjunction operation. Attributes ---------- l : Expr the left operand. r : Expr the right operand. symbol : str symbol for disjunction: 'v'. """ def __init__(self,l,r,symbol = "v"): super().__init__(l,r) self.symbol = symbol def eval(self,env): return self.l.eval(env) or self.r.eval(env) class Cond(BinOp): """ Conditional operation. Attributes ---------- l : Expr the left operand. r : Expr the right operand. symbol : str symbol for conditional: '->'. """ def __init__(self,l,r,symbol="->"): super().__init__(l,r) self.symbol = symbol def eval(self,env): return (lambda x,y:False if x and not y else True)(self.l.eval(env),self.r.eval(env)) class Bicond(BinOp): """ Biconditional operation. Attributes ---------- l : Expr the left operand. r : Expr the right operand. symbol : str symbol for biconditional: '<->'. """ def __init__(self,l,r,symbol="<->"): super().__init__(l,r) self.symbol = symbol def eval(self,env): return self.l.eval(env) == self.r.eval(env) ###Parser### import re prop = re.compile(r"\(?[a-uw-zA-Z][a-uw-zA-Z_0-9]*\)?") neg = re.compile(r"[ \(]*¬[a-uw-zA-Z\(][a-uw-zA-Z_0-9]*\)?") disj = re.compile(r" v ") conj = re.compile(r" \^ ") cond = re.compile(r" -> ") bicond = re.compile(r" <-> ") tmpre = re.compile(r"\(?tmp\)?") biops = [(disj,Disj),(conj,Conj),(cond,Cond),(bicond,Bicond)] def paren(str1): """Identify the most nested pair of parenthesis.""" tmp = '' for i in range(str1.find(')'),-1,-1): if str1[i] == '(': tmp += str1[i] break tmp += str1[i] return tmp[::-1] def tmp_replace(main,tree): """Replace a tmp node for tree in main .""" try: if type(main.r) is Prop: if main.r.name == "tmp": main.r = tree return True except: pass try: if type(main.r) is Not: if main.r.r.name == "tmp": main.r.r = tree return True elif main.r.l.name == "tmp": main.r.l = tree return True except: pass try: if type(main.l) is Not: if main.l.r.name == "tmp": main.l.r = tree return True elif main.l.l.name == "tmp": main.l.l = tree return True except: pass try: if type(main.l) is Prop: if main.l.name == "tmp": main.l = tree return True except: pass try: if type(main.r.l) is Not: if main.r.l.r.name == "tmp": main.r.l.r = tree return True except: pass return False def simple(exp): """Parse a single operation enclosed in parentheses.""" if not exp or not re.search(prop,exp): raise Exception elif re.fullmatch(tmpre,exp): return Prop("tmp") elif re.fullmatch(prop,exp): tmp = re.findall(r"[a-uw-zA-Z][a-uw-zA-Z_0-9]*",exp)[0] return Prop(tmp) elif re.fullmatch(neg,exp): tmp = exp.split("¬")[1] return Not(simple(tmp)) else: for x in biops: if re.search(x[0],exp): tmp = re.split(x[0],exp) return x[1](simple(tmp[0]),simple(tmp[1])) def parse(exp,stack=[]): """Parse an entire expression.""" if stack: tree = stack.pop() else: tree = None if paren(exp) == exp: if tree: tmp = simple(exp) tmp_replace(tmp,tree) return tmp else: return simple(exp) elif re.fullmatch(r"¬tmp",exp): tmp = simple(exp) tmp.r = tree return tmp elif re.fullmatch(prop,exp) or re.fullmatch(neg,exp): return simple(exp) else: tmp = simple(paren(exp)) if tree: flag = tmp_replace(tmp,tree) if not flag: stack.append(tree) stack.append(tmp) exp = exp.replace(paren(exp),'tmp') result = parse(exp,stack=stack) if re.search(r"tmp", str(result)): tmp_replace(result,stack.pop()) return result ###Truth tables### from itertools import product def table(expr,assume={}): """ Prints the truth table of expression expr. Parameters ---------- expr : Expr expression to be evaluated. assume : dict dictionary of prop:value pairs to be assumed (optional). """ props = list(set(re.findall(r"[a-uw-zA-Z][a-uw-zA-Z_0-9]*",str(expr)))) if assume: for x in assume: try: props.remove(x) except ValueError: print("Proposition not in expression.") return combs = product([False,True],repeat=len(props)) final = [list(zip(props, x)) for x in combs] if assume: for x in final: for y,z in assume.items(): x.append((y,z)) for x in assume: props.append(x) dicts = [dict(x) for x in final] print(("{:^5} "*len(props)).format(*props),expr,sep='\t') for x in dicts: print(("{:^5} "*len(props)).format(*map(str,x.values())),expr.eval(x),sep='\t') return if __name__ == '__main__': import sys try: if sys.argv[1] == '-h' or sys.argv[1] == '--help': print(__doc__) except: while True: expr,*values = input(">> ").split(',') if expr == "exit": break try: if values: tmp = [(x.split('=')[0][1:],x.split('=')[1]=="True") for x in values] values = dict(tmp) e1 = parse(expr) table(e1,values) except: print("Bad expression.")
03f30c6e3de602c031e1a0a497d9d8d4424dd802
BentGunnarsson/LL_Hangman
/hangman_sll.py
1,714
3.8125
4
class Node: def __init__(self, data=None, nexd=None, found = False): self.data = data self.next = nexd if data == " ": self.found = True # Not gonna have the players guessing for spaces else: self.found = found class LinkedList: def __init__(self): self.head = None self.tail = None def push_back(self, data): new_node = Node(data) if self.head == None: self.head = new_node else: self.tail.next = new_node self.tail = new_node def find(self, char): '''Checks for a character in the word. Returns True if it is found and False if not. Also toggles self.found''' curr = self.head ret_val = False while curr != None: if curr.data == char: curr.found = True ret_val = True curr = curr.next if ret_val: return True else: return False def check_win_con(self): '''Checks for win conditions, that is if all characters have been found.''' curr = self.head while curr != None: if curr.found == False: return False curr = curr.next return True def __str__(self): '''Prints the word but only found characters are displayed. The others appear as dashes.''' return_str = "" node = self.head while node != None: if node.found: return_str += str(node.data) node = node.next else: return_str += "-" node = node.next return return_str
8728f270c5f1ef36da673ab0763f4493f8834290
K4cp3rski/Programowanie-I-R
/Ćwiczenia 23.03/zad4.py
407
3.53125
4
import time start = time.process_time() lista = [1, 2, 3] def numDiff(lista): dl = len(lista) rozne = [] for i in range(dl): if lista[i] not in rozne: rozne.append(lista[i]) else: continue return len(rozne) print("Liczba różnych elementów w liście to:", numDiff(lista)) duration = time.process_time() - start print("{0:02f}s".format(duration))
7a8ce5d1299ba726a2de9773531fff57f8ebca01
kerryhuang1/tree-visualizer
/draw.py
4,190
3.953125
4
from trees import * width, height = 1280, 640 radius = 16 h_offset = 16 v_offset = -64 window = GraphWin("Tree Visualizer", width, height, autoflush=False) window.setCoords(0, 0, width, height) def visualize(tree, animate=False): ''' Provide the full visualization of the tree and its __repr__. Can highlight both the circular nodes and their corresponding __repr__()'s by clicking. ''' def draw_tree(t): ''' Draw the circle for the current node and its label in the center of the circle. If the current node is not the root node, draw a line connecting the top of the current node to the root node, ensuring the line does not cross into either circle. ''' t.circle.draw(window) t.text.draw(window) if t.parent: distance = ((t.parent.x - t.x)**2 + (t.parent.y-t.y)**2 ) ** 0.5 parent_dx = (t.parent.x - t.x) / distance * radius parent_dy = (t.parent.y - t.y) / distance * radius Line(Point(t.x, t.y + radius), Point(t.parent.x - parent_dx, t.parent.y - parent_dy)).draw(window) for b in t.branches: draw_tree(b) def draw_repr(t, h=0.95*height, max_ppr=0.75*width, space=7): ''' Draw t.__repr__() onto the window, making sure no overlap occurs. Return a dictionary mapping each character's index within t.__repr__() to its corresponding Text object (useful for coloring the Text object later). ''' strindex_to_textobj = {} def draw_text(text, color="black", size=14, font="courier"): text.setSize(size) text.setFace(font) text.setFill(color) text.draw(window) draw_text(Text(Point((width - max_ppr)/2 - 24, h), 't = ')) def draw_baserepr(string): ''' Draw the string onto the window by creating and drawing a Text object for each character inside. Each character has 'space' number of pixels between. The string is separated into rows beginning at height 'h' and each of width 'max_ppr'. ''' px_start, px_end = (width - max_ppr)/2, (width + max_ppr)/2 y = h i = 0 while i < len(string): text = Text(Point(px_start, y), string[i]) draw_text(text) strindex_to_textobj[i] = text px_start += space i += 1 if px_start > px_end: px_start = (width - max_ppr)/ 2 y -= 16 if y - t.y <= 16: raise WinsizeError("Repr overlaps with Tree") draw_baserepr(tree.__repr__()) return strindex_to_textobj def fill_loop(t): ''' Loop that allows user to click the nodes on the visual tree, highlighting subtrees and their corresponding text within the __repr__ green. ''' def search_tree(st, point): ''' Detect if the point is within st.circle's radius, returning st if it is. ''' if (st.x - 16 <= point.getX() <= st.x + 16) and (st.y - 16 <= point.getY() <= st.y + 16): return st for b in st.branches: if search_tree(b, point) is not None: return search_tree(b, point) def fill_tree(st, color): ''' Fill st and all of its children's circles to be color. ''' st.circle.setFill(color) for b in st.branches: fill_tree(b, color) def find_highlight_index(st): ''' Find the index inside of t.__repr__() where st's __repr__ occurs, accounting for duplicates by using st.repr_occurrence. ''' substring = st.__repr__() copy = t.__repr__() occurrence = 0 while True: if substring in copy: if occurrence == st.repr_occurrence: return copy.index(substring) else: copy = copy.replace(substring, ' '*len(substring), 1) occurrence += 1 d = draw_repr(tree) if animate: window.autoflush = True draw_tree(tree) window.autoflush = False while not window.isClosed(): click_pt = window.getMouse() fill_this = search_tree(t, click_pt) #highlight both the circles and the text if fill_this is not None: fill_tree(fill_this, 'green') repr_index = find_highlight_index(fill_this) for index in d.keys(): if index in range(repr_index, repr_index + len(fill_this.__repr__())): d[index].setFill('green') window.getMouse() #second click resets circles to white and text to black fill_tree(t, 'white') for index in d.keys(): d[index].setFill('black') fill_loop(tree)
83ca0c73bf480918b254810c2c929adbef91ef56
coin-or/pulp
/pulp/sparse.py
3,360
3.703125
4
# Sparse : Python basic dictionary sparse matrix # Copyright (c) 2007, Stuart Mitchell (s.mitchell@auckland.ac.nz) # $Id: sparse.py 1704 2007-12-20 21:56:14Z smit023 $ # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ sparse this module provides basic pure python sparse matrix implementation notably this allows the sparse matrix to be output in various formats """ class Matrix(dict): """This is a dictionary based sparse matrix class""" def __init__(self, rows, cols): """initialises the class by creating a matrix that will have the given rows and columns """ self.rows = rows self.cols = cols self.rowdict = {row: {} for row in rows} self.coldict = {col: {} for col in cols} def add(self, row, col, item, colcheck=False, rowcheck=False): if not (rowcheck and row not in self.rows): if not (colcheck and col not in self.cols): dict.__setitem__(self, (row, col), item) self.rowdict[row][col] = item self.coldict[col][row] = item else: print(self.cols) raise RuntimeError(f"col {col} is not in the matrix columns") else: raise RuntimeError(f"row {row} is not in the matrix rows") def addcol(self, col, rowitems): """adds a column""" if col in self.cols: for row, item in rowitems.items(): self.add(row, col, item, colcheck=False) else: raise RuntimeError("col is not in the matrix columns") def get(self, k, d=0): return dict.get(self, k, d) def col_based_arrays(self): numEls = len(self) elemBase = [] startsBase = [] indBase = [] lenBase = [] for i, col in enumerate(self.cols): startsBase.append(len(elemBase)) elemBase.extend(list(self.coldict[col].values())) indBase.extend(list(self.coldict[col].keys())) lenBase.append(len(elemBase) - startsBase[-1]) startsBase.append(len(elemBase)) return numEls, startsBase, lenBase, indBase, elemBase if __name__ == "__main__": """unit test""" rows = list(range(10)) cols = list(range(50, 60)) mat = Matrix(rows, cols) mat.add(1, 52, "item") mat.add(2, 54, "stuff") print(mat.col_based_arrays())
d0d6fbe5e7478f4547f4d88c7e17f4dc5dcf05a0
michaelssavage/Advanced_Algorithms
/Dynamic_Programming/greedy_ks.py
2,311
4.5
4
""" In this exercise, you will solve the KnapSack Problem using a greedy algorithm. The basic strategy is to just find the most valuable item per unit weight, place that in the knapsack and repeat the procedure until there is no room in the knapsack. Your method should return the total value of the items added. For example, if the amount was 10 and there were three items: item1 with value 20 and weight 5, item2 with value 300 and weight 11 and item 3 with value 4 and weight 2. Then the greedy algorithm will find the item with the largest value per unit weight that can fit in the knapsack. item2 has the largest value per unit weight (300 / 11) but it is too heavy to fit in the knapsack and so is not considered. The next most valuable item per unit weight is item 1 (20 / 5) and so we keep adding that until we have no more room. That is, we add two of item1 for total value of 40. There is no more items that can fit and so the greedy search terminates. However, the greedy algorithm will not always produce an optimal result. E.g. a knapsack with capacity 50 and two items: item1 has a value of 15 and a weight of 26 whereas item2 has a value of 10 and a weight of 25. The best result would be to use two of item2 for a total value of 20, but the greedy algorithm sees that the first item is most valuable and so adds that to the knapsack, leaving no room for anything else and ends up with a value of 15. """ def ks_greedy(initial_capacity, items): assert initial_capacity >= 0 total_value = 0 items.sort(key=getValue, reverse=True) itemsUsed = [0 for n in items] i = 0 for item in items: while initial_capacity >= item.weight: itemsUsed[i] = item.weight total_value += item.value initial_capacity -= item.weight i+=1 return total_value, itemsUsed def getValue(item): return item.value/item.weight def main(): capacity = 10 items = [Item(20, 5), Item(300, 11), Item(4, 2)] mostVal, itemUsed = ks_greedy(capacity, items) print("Weighted items used ---> ", itemUsed) print("The total value is -->", mostVal) class Item: def __init__(self, x, y): self.value = x self.weight = y if __name__ == "__main__": main()
cfc630c97205a1f767ecf4b7b09ab737137ee68b
Sameer2898/Data-Structure-And-Algorithims
/Placement Prepration/Stack/sort_a_stack.py
408
3.8125
4
def sorted(s): return s.sort(reverse = True) if __name__=='__main__': t = int(input('Enter the number of test cases:- ')) for i in range(t): n = int(input('Enter the size of the stack:- ')) arr = list(map(int, input('Enter the element of the stack:- ').strip().split())) sorted(arr) for e in range(len(arr)): print(arr.pop(0), end=" ") print()
5e8d0ebf14e9d7690a5b0028cb05a959f3cdfa54
reb33/-algorithms_2021
/Урок 5. Практическое задание/Урок 5. Коды примеров/OrderedDict_ex/task_7.py
729
4.15625
4
"""Класс collections.OrderedDict()""" import collections NEW_DICT = {'a': 1, 'b': 2, 'c': 3} # -> с версии 3.6 порядок сохранится print(NEW_DICT) # -> {'a': 1, 'b': 2, 'c': 3} # а в версии 3.5 и более ранних можно было получить и такой результат # {'b': 2, 'c': 3, 'a': 1} # и вообще любой, ведь порядок ключей не сохранялся # поэтому приходилось при необходимости обращаться к OrderedDict NEW_DICT = collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print(NEW_DICT['a']) # -> OrderedDict([('a', 1), ('b', 2), ('c', 3)]) # {} vs OrderedDict ?? # csv
f27817d68897edcdaa1f08dbc333ade4c3deaf8f
psemchyshyn/IMDB_research
/top_authors_visualisation.py
1,559
4.25
4
import matplotlib.pyplot as plt from literature_manag import * # Module for visualisation of data # A program asks user to enter the number n of authors and will create a bar with n authors, on whose works there was the biggest amount of films shot. films, books = read_file("literature.list") bokauth = book_author(books) #extracting movie and year data = amount_of_author_books(bokauth) def top_author_histogram(authors, amount_of_books): """ A function takes as input a list of ten authors, which has the biggest amount of their books released in film industry and a list of the number of that list. The function returns a histogram portraying those dependancies """ fug, ax = plt.subplots() ax.barh(authors, amount_of_books, align='center') ax.invert_yaxis() # labels read top-to-bottom ax.set_xlabel('Amount of books', labelpad=20) ax.set_ylabel('Authors') ax.set_title(f'Statistics of top {number} authors, whose books were used in kinomatography') plt.show() if __name__ == "__main__": while True: try: number = int(input("Enter the number of authors(no more than 30): ")) if 1 <= number <= 30: break else: raise Exception except: continue top_authors = top_ten_authors(data, number) authors = [x[0] for x in top_authors] amount_of_books = [y[1] for y in top_authors] top_author_histogram(authors, amount_of_books)
511c7717ebc22c118c481c73ffefc364ddc9a844
sumin3/holbertonschool-higher_level_programming
/0x0A-python-inheritance/2-is_same_class.py
352
3.984375
4
#!/usr/bin/python3 def is_same_class(obj, a_class): """function check if obj and a_class are exact the same object Args: obj: the object a_class: the class Return: returns True if the object is exactly an instance of the specified class ; otherwise False. """ return type(obj) is a_class
5644602b1da736494b3064dfb260465451a46828
marshallhumble/Coding_Challenges
/Code_Eval/Easy/SetIntersection/SetIntersection.py3
851
4.28125
4
#!/usr/bin/env python from sys import argv """ SET INTERSECTION CHALLENGE DESCRIPTION: You are given two sorted list of numbers (ascending order). The lists themselves are comma delimited and the two lists are semicolon delimited. Print out the intersection of these two sets. INPUT SAMPLE: File containing two lists of ascending order sorted integers, comma delimited, one per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 OUTPUT SAMPLE: Print out the ascending order sorted intersection of the two lists, one per line. Print empty new line in case the lists have no intersection. E.g. 4 8,9 SUBMIT SOLUTION """ with open(argv[1], 'r') as f: test_cases = f.read().strip().splitlines() for line in test_cases: set_a, set_b = line.split(';') print(','.join(sorted(set(set_a.split(',')) & set(set_b.split(',')))))
1cba4ee4d2c3abf618b980083b2fdd239c1c4cd3
DylanDelucenauag/cspp10
/unit5/ddelucena_ap_create.py
2,606
4.21875
4
#Mcdonalds Simulator #use lists #big mac = $4 #Quarter pounder with cheese = $3.79 #Hamburger = $2.49 #cheeseburger = $2.79 #mcchicken = $1.29 #mcwrap = $4 #filet o fish = $3.79 #mcrib = $3 def get_p1_order(): p1_order = input("Welcome to Mcdonalds, What would you like to order\nThis is our menu today:\n(1)Big Mac (2)Quarter Pounder with Cheese (3)Hamburger (4)Cheeseburger\n(5)McChicken (6)McWrap (7)Filet O Fish (8)McRib\n(9)Oreo McFlurry (10)M&M McFlurry\nChoose a number to order:") if p1_order == "1": return p1_order elif p1_order == "2": return p1_order elif p1_order == "3": return p1_order elif p1_order == "4": return p1_order elif p1_order == "5": return p1_order elif p1_order == "6": return p1_order elif p1_order == "7": return p1_order elif p1_order == "8": return p1_order elif p1_order == "9": print ("Sorry ice cream machine is broken today.") return get_p1_order() elif p1_order == "10": print ("Sorry ice cream machine is broken today.") return get_p1_order() else: get_p1_order() def get_food_name(shortname): if shortname == "1": return "Big Mac" elif shortname == "2": return "Quarter Pounder with Cheese" elif shortname == "3": return "Hamburger" elif shortname == "4": return "Cheeseburger" elif shortname == "5": return "McChicken" elif shortname == "6": return "McWrap" elif shortname == "7": return "Filet O Fish" elif shortname == "8": return "McRib" def order_list(p1_order): p1_order_list = [] p1_order_list = p1_order_list.append(p1_order) add_to_order = input("Anything else (yes or no): ") while True: if add_to_order == ("yes"): add_to_order = input("What would you like to order\nThis is our menu today:\n(1)Big Mac (2)Quarter Pounder with Cheese (3)Hamburger (4)Cheeseburger\n(5)McChicken (6)McWrap (7)Filet O Fish (8)McRib\n(9)Oreo McFlurry (10)M&M McFlurry\nChoose a number to orderOr to remove an item write it as a negative number:") p1_order_list.append(add_to_order) print (p1_order_list) return p1_order_list elif add_to_order == ("no"): break def McSim(): p1_order = get_p1_order() p1_order_list = order_list(p1_order) "1" == 4 "2" == 3.79 "3" == 2.49 "4" == 2.79 "5" == 1.29 "6" == 4 "7" == 3.79 "8" == 3 print (p1_order_list) McSim()
4383298ad04b3949e63975138421827956c10d07
CamilaTermine/programitas
/Python/Parte1/11-07-2021/ejercicio4.py
1,025
4.15625
4
cantAlumnos = int(input("ingrese cantidad de alumnos: ")); mensaje = ""; notaMenor = 0; notaMayor = 0; nombreAlumnoNotaMenor = ""; nombreAlumnoNotaMayor = ""; sumaNotas = 0; for i in range(0, cantAlumnos): nombreAlumno = input("ingrese el nombre del alumno: "); notaAlumno = int(input("ingrese la nota del alumno: ")); sumaNotas = sumaNotas + notaAlumno if i == 0: notaMenor = notaAlumno; nombreAlumnoNotaMenor = nombreAlumno; notaMayor = notaAlumno; nombreAlumnoNotaMayor = nombreAlumno; else: if notaAlumno < notaMenor: notaMenor = notaAlumno; nombreAlumnoNotaMenor = nombreAlumno; if notaAlumno > notaMayor: notaMayor = notaAlumno; nombreAlumnoNotaMayor = nombreAlumno; print(f"el alumno {nombreAlumnoNotaMenor} con la nota {notaMenor} fue la mas baja"); print(f"el alumno {nombreAlumnoNotaMayor} con la nota {notaMayor} fue la mas alta"); print(f"el promedio de notas fue de {sumaNotas/cantAlumnos}");
88cb615a3215780fa14173b59a0d3f411b5cf1b1
mliu/googlemapz
/algo.py
831
3.875
4
# Tests various algorithms for finding the ideal destination by some combination of distances in a selection of potential destinations. distances = [ [28,29,30], [35,35,45], [15,15,45], [7,7,60], [1,1,60], [7,7,90], [1,1,120], [1,60,60], [7,45,45], [20,20,20], ] def rankSum(distances): return sum(distances) def rankMagnitude(distances): total = 0 for d in distances: total += d**2 # no need to square root for ranking return total def rankMiddle(distances): total = 0 for d in distances: total += d**1.5 return total def rank(distances, algorithm): res = [] for ds in distances: t = algorithm(ds) res.append([ds, t]) res.sort(key = lambda x: x[1]) print(res) def main(): rank(distances, rankSum) rank(distances, rankMagnitude) rank(distances, rankMiddle) if __name__ == '__main__': main()
6a9c54ca0d4c3007d4f3121418cbc6b3a0824250
MihirVaidya94/Sorting-Algorithms
/quicksort.py
1,213
4.0625
4
#Function for swapping the two integers that are being compared def swap(x,y): temp = x x = y y = temp return (x,y) def quicksort(arr,l): if len(arr)%2 == 0: t = [arr[0], arr[len(arr)/2 - 1], arr[len(arr)-1]] t.sort() if t[1] == arr[0]: pivot = 0 elif t[1] == arr[len(arr)/2 - 1]: pivot = len(arr)/2 - 1 else: pivot = len(arr)-1 else: t = [arr[0], arr[len(arr)/2], arr[len(arr)-1]] t.sort() if t[1] == arr[0]: pivot = 0 elif t[1] == arr[len(arr)/2]: pivot = len(arr)/2 else: pivot = len(arr)-1 i = 0 m = 1 arr[0],arr[pivot] = swap(arr[0],arr[pivot]) for k in range(m,len(arr)): if arr[k] <= arr[0]: i = i+1 arr[i],arr[k] = swap(arr[i],arr[k]) arr[0],arr[i] = swap(arr[0],arr[i]) return arr,i+l,len(arr)-1 arr_file = open("C:\Users\dell pc\Desktop\QuickSort.txt", "r") num_list = map(int, arr_file.read().split()) pivots = [-1,len(num_list)] j = 0 count = 0 while pivots[j] < len(num_list): while len(num_list[pivots[j]+1:pivots[j+1]]) > 1: num_list[pivots[j]+1:pivots[j+1]],k,l = quicksort(num_list[pivots[j]+1:pivots[j+1]],pivots[j]+1) pivots = pivots[:j+1] + [k] + pivots[j+1:] count = count + l j = j+1 print num_list print count
27e14bd0416f92289684d4da3961c3e87036d05d
globlo/CyberSecurityHW1
/HW1.py
3,829
3.515625
4
import sys import traceback import Crypto.Cipher # BEGIN SOLUTION # please import only standard modules and make sure that your code compiles and runs without unhandled exceptions from Crypto.Cipher import AES # END SOLUTION def problem_1(): with open("cipher1.bin", "rb") as cipher_file: # rb means "read only in binary" cipher_text = cipher_file.read() # byte #print(cipher_text) # BEGIN SOLUTION iv=bytearray(16) key = bytearray([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) aes = AES.new(key, AES.MODE_CBC, iv) plain_text = aes.decrypt(cipher_text) # END SOLUTION with open("plain1.txt", "wb") as plain_file: # wb means writing in binary mode plain_file.write(plain_text) def problem_2(): with open("cipher2.bin", "rb") as cipher_file: cipher_text = cipher_file.read() # BEGIN SOLUTION iv=bytearray(16) rList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] key = bytearray(rList) ctext1 = cipher_text[:16] ctext2 = cipher_text[16:32] ctext3 = cipher_text[32:] # mtxt = ctext1+ctext2+ctext3 # mtxt = ctext1+ctext3+ctext2 # mtxt = ctext2+ctext1+ctext3 # mtxt = ctext2+ctext3+ctext1 # mtxt = ctext3+ctext1+ctext2 modified_cipher_text = ctext3+ctext2+ctext1 aes = AES.new(key, AES.MODE_CBC, iv) decd = aes.decrypt(modified_cipher_text) print("decd is ",decd) plain_text = decd # END SOLUTION with open("plain2.txt", "wb") as plain_file: plain_file.write(plain_text) def problem_3(): with open("cipher3.bmp", "rb") as cipher_file: cipher_bmp = cipher_file.read() with open("msg3.bmp", "rb") as message_file: other_bmp = message_file.read() # BEGIN SOLUTION header = other_bmp[:1000] modified_cipher_bmp = header + cipher_bmp[1000:] # END SOLUTION with open("cipher3_modified.bmp", "wb") as modified_cipher_file: modified_cipher_file.write(modified_cipher_bmp) def problem_4(): with open("plain4A.txt", "rb") as plain_file: plain_text_a = plain_file.read() with open("cipher4A.bin", "rb") as cipher_file: cipher_text_a = cipher_file.read() with open("cipher4B.bin", "rb") as cipher_file: cipher_text_b = cipher_file.read() # BEGIN SOLUTION # p1 xor c1 xor c2 = p2 plain_text_b = bytes([ a ^ b ^ c for (a,b,c) in zip(bytes(plain_text_a), bytes(cipher_text_a), bytes(cipher_text_b)) ]) print(plain_text_b) # END SOLUTION with open("plain4B.txt", "wb") as plain_file: plain_file.write(plain_text_b) def problem_5(): with open("cipher5.bin", "rb") as cipher_file: cipher_text = cipher_file.read() # BEGIN SOLUTION iv=bytearray(16) key = bytearray([0] * 16) for month in range(1,12): for day in range(1,31): for year in range(0,99): key = bytearray([month,day,year,0,0,0,0,0,0,0,0,0,0,0,0,0]) aes = AES.new(key, AES.MODE_CBC, iv) decd = aes.decrypt(cipher_text) count =0 for c in decd: if 0 <= c and c <= 128: count = count +1 if count == len(decd): print("Moriarty's birth - month : "+str(month)+", day : "+str(day)+", year : "+str(year)) print(decd) plain_text = decd # END SOLUTION with open("plain5.txt", "wb") as plain_file: plain_file.write(plain_text) def main(): try: problem_1() problem_2() problem_3() problem_4() problem_5() except Exception: print("Exception:") traceback.print_exc(file=sys.stdout) if __name__ == "__main__": main()
72197a6f7f0701734924fafde88e8f1bb4bf9fd0
erjan/coding_exercises
/minimum_cost_of_buying_candies_with_discount.py
1,059
4.0625
4
''' A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies. ''' class Solution: def minimumCost(self, cost: List[int]) -> int: nums = cost nums = sorted(nums, reverse=True) total_cost = 0 i = 0 while i < len(nums): if i == len(nums)-1: total_cost += nums[i] break #print(nums[i], nums[i+1]) total_cost += nums[i] + nums[i+1] i += 3 print(total_cost) return total_cost
4c26639e65c3adcd9032d8f0794bcbda3700240b
programhung/learn-python
/PythonCode/Number/updatefrancais2.py
1,141
3.9375
4
import random def play(min,max): print("Donc, le numero secret est entre "+str(min)+" et "+str(max)) print("Entrez le maximum de fois pour deviner") a=input() a=int(a) userchoice=2 counter=0 while userchoice!=1: if counter>=a: print("GAME OVER.") break counter=counter+1 x=random.randint(min,max) print("Est-ce que "+str(x)+ " est le numero secret? C'est vrai(1) ou faux(2)") userchoice=input() userchoice=int(userchoice) if userchoice==1: print("Oui! J'ai gagne. HA HA HA...") else: print("Le numero secret est grand(1) or petit(2) que "+str(x)) qwerty=input() qwerty=int(qwerty) if qwerty==1: min=x+1 else: max=x-1 print("Choisissez le niveau:") print("press 1.Debutant(0-100) 2.Semi-pro(0-1000) 3.Pro(0-10000) 4.Autre") choose=input() choose=int(choose) if choose==1: play(0,100) elif choose==2: play(0,1000) elif choose==3: play(0,10000) elif choose==4: print("Entrez le minimum numero:") min=input() min=int(min) print("Entrez le maximum numero:") max=input() max=int(max) play(min,max) else: print("ERROR")
204c3da8f86100df264acb4a0f03f5c75ca83cf6
Dragon-Boat/PythonNote
/PythonCode/Python入门/Set/访问set.py
878
3.921875
4
#coding=utf-8 #author: sloop ''' setʶСд֣Ľsetʹ 'adam' 'bart'ܷTrue ''' # s = set(['Adam', 'Lisa', 'Bart', 'Paul']) temp = set() for k in s: l = k.lower() temp.add(l) for k in temp: s.add(k) print 'adam' in s print 'bart' in s print s ''' set set洢򼯺ϣûͨʡ setеijԪʵϾжһԪǷsetС 磬洢˰ͬѧֵset >>> s = set(['Adam', 'Lisa', 'Bart', 'Paul']) ǿ in жϣ BartǸðͬѧ >>> 'Bart' in s True BillǸðͬѧ >>> 'Bill' in s False bartǸðͬѧ >>> 'bart' in s False СдҪ'Bart' 'bart'ΪͬԪء '''
ce859a4552935aa06ea2847d0353e6b9995fd57a
KaterinaMutafova/SoftUni
/Python Advanced/1. Stack_and_queues/SQ_lab_ex1_reverse.py
149
3.9375
4
text = list(input()) reverse_text = [] for ch in range(len(text)): reverse_text.append(text.pop()) print(''.join(reverse_text))
3f12bb16fe477a688e2eda8de7e15270b4414a39
ZhuoyiZou/python-challenge
/PyBank/main.py
1,721
3.671875
4
# Import module import csv import os import numpy as np # Select the csv file through directory pybank_data = os.path.join(".", "PyBank_Resources_budget_data.csv") column_1 = [] column_2 = [] total_amount = 0 # Read the csv file with open (pybank_data, newline = "") as csvfile: pybank_data_reader = csv.reader(csvfile, delimiter = ",") for row in pybank_data_reader: column_1.append(row[0]) column_2.append(row[1]) # Calculate the number of months. total_month = len(column_1) - 1 # Calculate the total net amount profit/loss total_net_amount = 0 for i in column_2[1:]: total_net_amount = total_net_amount + int(i) # Calculate the average changes converted_column_2 = [int(i) for i in column_2[1:]] changes = [] for i in range(len(converted_column_2)): changes.append(converted_column_2[i] - converted_column_2[i-1]) average_changes = round(np.mean(changes[1:]),2) # Find the greatest increase and greatesr decrease in profit greatest_increase = max(changes) greatest_decrease = min(changes) for i in range(len(changes)): if changes[i] == greatest_increase: increase_month = i + 1 elif changes[i] == greatest_decrease: decrease_month = i + 1 greatest_increase_month = column_1[increase_month] greatest_decrease_month = column_1[decrease_month] # Print the results print("Financial Analysis") print("-------------------------") print(f"Total Months: {total_month}") print(f"Total: ${total_net_amount}") print(f"Average Change: ${average_changes}") print(f"Greatest Increase in Profits: {greatest_increase_month} (${greatest_increase})") print(f"Greatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease})")
5484eaa2350116455179ffaadb17f01ab2cddb8a
saran1211/rev-num
/avg.py
148
3.96875
4
n=int(input('enter the no of elements')) l=[] for i in range(1,n+1): a=int(input('enter the elements')) l.append(a) avg=len(l)//2 print (avg)
5749847612f3b1904fc8ca679436be2ec3cd93b4
skhan75/CoderAid
/DataStructures/Graphs/number_of_islands.py
1,956
3.796875
4
class Graph: def __init__(self, r, c, g): self.row = r self.col = c self.graph = g # Function to check if a given cell (row, col) can be included in DFS def is_safe(self, i, j, visited): # row number is in range, column number # is in range and value is 1 # and not yet visited return (i >= 0 and i < self.row and j >= 0 and j < self.col and not visited[i][j] and self.graph[i][j]) def dfs(self, row, col, visited): # Following are th 8 possible movements (neighbors) around a given cell row_neighbors = [-1, -1, -1, 0, 0, 1, 1, 1] col_neighbors = [-1, 0, 1, -1, 1, -1, 0, 1] # Mark the current cell as visited visited[row][col] = True # Recur all connected 8 neighbors for i in range(8): current_nbr_row_idx = row + row_neighbors[i] current_nbr_col_idx = col + col_neighbors[i] if self.is_safe(current_nbr_row_idx, current_nbr_col_idx, visited): self.dfs(current_nbr_row_idx, current_nbr_col_idx, visited) def count_islands(self): visited = [[False for i in range(self.col)] for j in range(self.row)] if self.graph is None: return 0 count = 0 for i in range(self.row): for j in range(self.col): # If a cell value is 1 and is not yet visited, its our new found island if visited[i][j] == False and self.graph[i][j] == 1: self.dfs(i, j, visited) count += 1 return count if __name__ == "__main__": graph = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] row = len(graph) col = len(graph[0]) g = Graph(row, col, graph) print "Number of islands is:" print g.count_islands()
212daf118b37eca829d86e7502d407df2c8a9472
jeffrey0601/uda-project1
/Task2.py
2,491
3.578125
4
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信息: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". 提示: 建立一个字典,并以电话号码为键,通话总时长为值。 这有利于你编写一个以键值对为输入,并修改字典的函数。 如果键已经存在于字典内,为键所对应的值加上对应数值; 如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。 """ _phone_number_dicts = {} def sum_number_duration_time(num, time): """ 计算单个号码的通话时间并存储到'_phone_number_dicts'字典中 Args: num: string 电话号码 time: string 通话时间 """ global _phone_number_dicts if num in _phone_number_dicts: _phone_number_dicts[num] += int(time) else: _phone_number_dicts[num] = int(time) # 该函数可用内置max函数替代 # def longest_duration_time(): # """ # 计算最长通话时间并返回对应的字典键,如果出现多个最长记录取第一个 # """ # global _phone_number_dicts # longest_time = 0 # longest_time_key = None # for key in _phone_number_dicts: # if _phone_number_dicts[key] > longest_time: # longest_time = _phone_number_dicts[key] # longest_time_key = key # return longest_time_key # 遍历通话记录计算每个电话的通话时间 for call in calls: calling = call[0] receiving = call[1] duration_time = call[3] # 主叫通话时间 sum_number_duration_time(calling, duration_time) # 被叫通话时间 sum_number_duration_time(receiving, duration_time) # 获取最长通话时间对应的字典键与值 # longest_time_key = longest_duration_time() longest_time_key = max(_phone_number_dicts, key=_phone_number_dicts.get) longest_time = _phone_number_dicts[longest_time_key] print("{} spent the longest time, {} seconds, on the phone during September 2016.".format( longest_time_key, str(longest_time) ))
523d5a682363fa4b0ad6807d38a9d69bbee4e389
KantiMRX/calculator
/calc.py
496
4.1875
4
print("პროგრამა შექმნილა Kanti-ის მიერ, ისიამოვნეთ.") x = "symbols" x = float(input("შეიტანეთ x: ")) oper = input("აირჩიეთ ოპერაცია: +, -, /, * ...> ") y = float(input("აირჩიეთ y: ")) if oper == "+": print(x + y) elif oper == "-": print(x - y) elif oper == "/": print(x / y) elif oper == "*": print(x * y) else: print("შეცდომა")
0fdaa63ddaac440ed2def666f238e9dbac311538
ErnestoSiemba/Python-for-Everybody
/Chapter 7 Exercise 3.py
424
3.65625
4
fname=input('Enter file name to find # of "Subject" lines: ') if fname=='': fname='mbox.txt' if fname=='na na boo boo': print('NA NA BOO BOO TO YOU - You have been cock slapped') exit() try: hand=open(fname) except: print('File cannot be opened:', fname) exit() count=0 for line in hand: if line.startswith('Subject'): count=count+1 print('There were', count, 'subject lines in', fname)
6853646f8599664940f0096c2e55a9b7009eaeab
Guzinanda/Interview-Training-Microsoft
/01 Arrays/rotateArray.py
826
4.15625
4
''' Rotate an Array @ Problem Given an array of integers, and a 'k' number indicating the number of times the arrays must be rotated, totate that number to the right. @ Example Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] @ Template I want to move the last item of the list (index[-1]) in front of the list (index[0]) This will be repeated "k" times ''' def rotateArray(nums, k): while k > 0: last_item = nums.pop(-1) nums.insert(0, last_item) k -= 1 return nums # TEST ____________________________________________________________________________________ nums1 = [1,2,3,4,5,6,7] # [5,6,7,1,2,3,4] k1 = 3 nums2 = [-1,-100,3,99] # [3,99,-1,-100] k2 = 2 print(rotateArray(nums1, k1)) print(rotateArray(nums2, k2))
d83f9bdbc0231735e1538d9ac1dd9314e0aa6133
jonathalfc/exercicios_uri_python3
/1013_o_maior_13.py
333
4.03125
4
#coding: utf-8 def funcao_abs(valor1,valor2,valor3): valor1 = valor1 valor2 = valor2 valor3 = valor3 maior_ab = (a+b+abs(a-b))/2 maior_ab_c = (maior_ab+c+abs(maior_ab-c))/2 print('%d eh o maior'%maior_ab_c) valores = input("").split(" ") a = int(valores[0]) b = int(valores[1]) c = int(valores[2]) funcao_abs(a,b,c)
86e286b264daae5b06ca4eb995de4702c1eb8da2
40013395/Python
/assignment1.py
196
4.3125
4
#change the first character occurence in a string to "$", except the first character itself my_str = input("Enter the string: ") print((my_str.replace(my_str[0], "$")).replace("$", my_str[0], 1))
6bbf6972449c914b5268114595bff0705bd0732a
ivanstewart2001/projects
/Numbers/Exercise1.py
552
4.09375
4
""" Let's assume you are planning to use your Python skills to build a social networking service. You decide to host your application on servers running in the cloud. You pick a hosting provider that charges $0.51 per hour. You will launch your service using one server and want to know how much it will cost to operate per day and per month. """ print("How much does it cost to operate one server per day?") per_day = 0.51 * 24 print(per_day) print("How much does it cost to operate one server per month?") per_month = 0.51 * 24 * 30 print(per_month)
7da12768036bddd2e4870b67a88096c53d19dfeb
LuisGPMa/my-portfolio
/Coding-First-Contact_With_Python/Fahrenheit_to_Celsius.py
268
4.0625
4
celsius= float(input ("What's the temperature in Celsius? ")) fahreinheit= ((celsius*9)/5)+32 print (celsius,"º in celsius is the same temperature as", fahreinheit, "º in fahreinheit.") if fahreinheit>90: print("It's hot") else: print("It's not hot")
94d6783b96acb2c37fc463d586095bf4608a36af
mukund7296/Python-Brushup
/27 Class obeject.py
806
3.96875
4
'''Python Classes/Objects Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. Example :- Any table is like template and we use object to store data in row wise using object''' #Create a class named Person, use the __init__() function to assign values for name and age: class Person: #Class def __init__(self, name, age): #initiallizing attributes self.name = name #attribute self.age = age #attribute p1 = Person("John", 36) #object p1 and passing two values p1.name="arvind" print(p1.name) #print one attibute print(p1.age)
20b7b515b1481a0487fc0b447cf7f93bb7a8cba1
mingming733/LCGroup
/Sen/Unique_Paths.py
713
3.5
4
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m == 1 and n == 1: lst = [[1]] elif m == 1 and n > 1: lst = [[1 for i in range(n)]] elif m > 1 and n == 1: lst = [[1 for i in range(m)]] else: lst = [[0 for i in range(n)] for i in range(m)] for i in range(n): lst[0][i] = 1 for i in range(m): lst[i][0] = 1 for i in range(1, m): for j in range(1, n): lst[i][j] = lst[i - 1][j] + lst[i][j - 1] return lst[m - 1][n - 1] m = 3 n = 7 i = Solution() print i.uniquePaths(m, n)
ea0049c717885acb16b5536b74c9bc92937cde14
TomEdwardBell/PycharmProjects
/ALevel/ReversePolish/infix2reversepolish.py
1,019
3.59375
4
# Precedence rules # ( # + - ) # * / # ^ def infix2polish(str): items = str.split(' ') precedence = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3, } def calc_reverse(str): stack = [] for item in str.split(' '): try: float(item) stack.append(float(item)) except: if item == '+': o1, o2 = stack.pop(), stack.pop() stack.append(o2 + o1) if item == '-': o1, o2 = stack.pop(), stack.pop() stack.append(o2 - o1) if item == '*': o1, o2 = stack.pop(), stack.pop() stack.append(o2 * o1) if item == '/': o1, o2 = stack.pop(), stack.pop() stack.append(o2 / o1) if item == '^': o1, o2 = stack.pop(), stack.pop() stack.append(o2 ** o1) print(stack[0])
595c2dbeeba2c98d884fed7f8373d606768cbd6d
wolfgang-azevedo/python-tips
/tip15_enumerate/tip15_enumerate.py
468
4.09375
4
#!/usr/bin/env python3.8 # ######################################## # # Python Tips, by Wolfgang Azevedo # https://github.com/wolfgang-azevedo/python-tips # # Enumerate Built-in Function # 2020-03-13 # ######################################## # # routers = ['ROUTER01', 'ROUTER02', 'ROUTER03', 'ROUTER04', 'ROUTER02'] # With Enumerate built-in function you can enumerate an object # Com a função interna Enumerate, você pode enumerar objetos print(list(enumerate(routers)))
c28b1337b555209c42e7633be8e4f63080b55093
elrion018/CS_study
/beakjoon_PS/no10828_2.py
710
3.796875
4
def push(x): return stack.append(x) def pop(): if len(stack) == 0: return print(-1) else: return print(stack.pop()) def size(): return print(len(stack)) def empty(): if len(stack) == 0: return print(1) else: return print(0) def top(): if len(stack) == 0: return print(-1) else: return print(stack[-1]) # 입력 stack = [] N = int(input()) for _ in range(N): temp = list(input().split()) if temp[0] == 'push': push(int(temp[1])) elif temp[0] == 'top': top() elif temp[0] == 'size': size() elif temp[0] == 'empty': empty() elif temp[0] == 'pop': pop()
ac04a421b785675f44ee77ce2564c91fae4497fd
ii0/algorithms-6
/Sort/inset_sort.py
371
3.703125
4
""" author: buppter datetime: 2019/8/27 20:14 插入排序 时间复杂度: O(n*n) """ def inset_sort(alist): if not alist: return None for i in range(len(alist) - 1): for j in range(1 + i, 0, -1): if alist[j] < alist[j - 1]: alist[j], alist[j - 1] = alist[j - 1], alist[j] else: break
debf8a46598a7f428cdbd96b89e2959f419e43f8
sayalijo/my_prog_solution
/geeks_for_geeks/Arrays/searching/search_missing_element/search_missing_element.py
327
4.25
4
def missing_element(arr): x1 = 1 x2 = 1 n = len(arr) for i in range(n): x1 ^= arr[i] for i in range(n+2): x2 ^= i print(x1, x2) return x1^x2 arr = list(map(int, input("enter your array").split(" "))) result = missing_element(arr) print("Your missing element is array is", result)
164675b714842c342e0ef001352aa5bf49f30761
YaroslavaMykhailenko/Laboratory-1_Mykhailenko
/Task3.py
8,644
3.5
4
import random import math import pandas as pd import numpy as np import matplotlib.pyplot as plt from prettytable import PrettyTable from scipy.stats import chisquare from scipy.stats import shapiro import seaborn as sns n = 100 # Task 3 def pos_value(a): a = float(a) if a < 0: print("\nErorr, incorrect input") a = float(input("\nEnter correct value: ")) return a def gauss(): gauss_ = [] mu = float(input("Enter mu: ")) sigma = pos_value(input("Enter sigma: ")) for i in range(100): gauss_.append(float("{0:.5f}".format(random.gauss(mu, sigma)))) # Вывод графика plt.plot(gauss_[:100]) plt.show() print('Mathematical expectation and dispersion for gauss: ', round(np.mean(gauss_), 5), round(np.var(gauss_), 5)) def to_round(num): num = int(num + (0.5 if num > 0 else -0.5)) return num gauss_.sort() m = to_round(1 + 3.322 * math.log(100, 10)) r = gauss_[-1] - gauss_[0] h = r / m f_elem = gauss_[0] intervals = [] table = PrettyTable() frequency = 0 index = 1 # freq_sum = 0 dict_freq = {} table = PrettyTable() # Определение столбцов table.field_names = ['Index', 'Interval', 'Frequency hit', 'Relative frequency '] # Создание интервалов for i in range(m): intervals.append((round(f_elem, 4), round(f_elem + h, 4))) f_elem += h # Заполнение таблицы данными for interval in intervals: for num in gauss_: if interval[0] <= num < interval[1]: frequency += 1 table.add_row([index, interval, frequency, frequency / n]) dict_freq[interval] = frequency frequency = 0 index += 1 # Вывод таблицы print(table) # Вывод гистограммы pd.Series(dict_freq).plot.bar() plt.show() def weibull(): weibull_ = [] alpha = float(input("Enter alpha: ")) beta = float(input("Enter beta: ")) for i in range(100): weibull_.append(float("{0:.5f}".format(random.weibullvariate(alpha, beta)))) plt.plot(weibull_[:100]) plt.show() print('Mathematical expectation and dispersion for weibull: ', round(np.mean(weibull_), 5), round(np.var(weibull_), 5)) def to_round(num): num = int(num + (0.5 if num > 0 else -0.5)) return num weibull_.sort() m = to_round(1 + 3.322 * math.log(100, 10)) r = weibull_[-1] - weibull_[0] h = r / m f_elem = weibull_[0] intervals = [] table = PrettyTable() frequency = 0 index = 1 # freq_sum = 0 dict_freq = {} table = PrettyTable() # Определение столбцов table.field_names = ['Index', 'Interval', 'Frequency hit', 'Relative frequency '] # Создание интервалов for i in range(m): intervals.append((round(f_elem, 4), round(f_elem + h, 4))) f_elem += h # Заполнение таблицы данными for interval in intervals: for num in weibull_: if interval[0] <= num < interval[1]: frequency += 1 table.add_row([index, interval, frequency, frequency / n]) dict_freq[interval] = frequency frequency = 0 index += 1 # Вывод таблицы print(table) # Вывод гистограммы pd.Series(dict_freq).plot.bar() plt.show() def rayleigh(): mode = pos_value(input("Enter mode: ")) rayleigh_ = np.random.rayleigh(mode, 100) plt.plot(rayleigh_[0:5]) plt.show() print('Mathematical expectation and dispersion for reyleigh: ', round(np.mean(rayleigh_), 5), round(np.var(rayleigh_), 5)) def to_round(num): num = int(num + (0.5 if num > 0 else -0.5)) return num rayleigh_.sort() m = to_round(1 + 3.322 * math.log(100, 10)) r = rayleigh_[-1] - rayleigh_[0] h = r / m f_elem = rayleigh_[0] intervals = [] table = PrettyTable() frequency = 0 index = 1 # freq_sum = 0 dict_freq = {} table = PrettyTable() # Определение столбцов table.field_names = ['Index', 'Interval', 'Frequency hit', 'Relative frequency '] # Создание интервалов for i in range(m): intervals.append((round(f_elem, 4), round(f_elem + h, 4))) f_elem += h # Заполнение таблицы данными for interval in intervals: for num in rayleigh_: if interval[0] <= num < interval[1]: frequency += 1 table.add_row([index, interval, frequency, frequency / n]) dict_freq[interval] = frequency frequency = 0 index += 1 # Вывод таблицы print(table) # Вывод гистограммы pd.Series(dict_freq).plot.bar() plt.show() def lognormal(): lognormal_ = [] mulognormal = float(input("Enter mu for logNormal distribution: ")) sigmalognormal = pos_value(input("Enter sigma for logNormal distribution: ")) for i in range(100): lognormal_.append(float("{0:.5f}".format(random.lognormvariate(mulognormal, sigmalognormal)))) plt.plot(lognormal_[:100]) plt.show() print('Mathematical expectation and dispersion for logNormal: ', round(np.mean(lognormal_), 5), round(np.var(lognormal_), 5)) def to_round(num): num = int(num + (0.5 if num > 0 else -0.5)) return num lognormal_.sort() m = to_round(1 + 3.322 * math.log(100, 10)) r = lognormal_[-1] - lognormal_[0] h = r / m f_elem = lognormal_[0] intervals = [] table = PrettyTable() frequency = 0 index = 1 # freq_sum = 0 dict_freq = {} table = PrettyTable() # Определение столбцов table.field_names = ['Index', 'Interval', 'Frequency hit', 'Relative frequency '] # Создание интервалов for i in range(m): intervals.append((round(f_elem, 4), round(f_elem + h, 4))) f_elem += h # Заполнение таблицы данными for interval in intervals: for num in lognormal_: if interval[0] <= num < interval[1]: frequency += 1 table.add_row([index, interval, frequency, frequency / n]) dict_freq[interval] = frequency frequency = 0 index += 1 # Вывод таблицы print(table) # Вывод гистограммы pd.Series(dict_freq).plot.bar() plt.show() def cauchy(): cauchy_ = np.random.standard_cauchy(100) plt.plot(cauchy_[:100]) plt.show() print('Mathematical expectation and dispersion for cauchy: ', round(np.mean(cauchy_), 5), round(np.var(cauchy_), 5)) def to_round(num): num = int(num + (0.5 if num > 0 else -0.5)) return num cauchy_.sort() m = to_round(1 + 3.322 * math.log(100, 10)) r = cauchy_[-1] - cauchy_[0] h = r / m f_elem = cauchy_[0] intervals = [] table = PrettyTable() frequency = 0 index = 1 # freq_sum = 0 dict_freq = {} table = PrettyTable() # Определение столбцов table.field_names = ['Index', 'Interval', 'Frequency hit', 'Relative frequency '] # Создание интервалов for i in range(m): intervals.append((round(f_elem, 4), round(f_elem + h, 4))) f_elem += h # Заполнение таблицы данными for interval in intervals: for num in cauchy_: if interval[0] <= num < interval[1]: frequency += 1 table.add_row([index, interval, frequency, frequency / n]) dict_freq[interval] = frequency frequency = 0 index += 1 # Вывод таблицы print(table) # Вывод гистограммы pd.Series(dict_freq).plot.bar() plt.show() def start(): print("Choose the distribution:\n1 - Normal\n2 - Weibull\n3 - Rayleigh\n4 - LogNormal\n5 - Cauchy") number = int(input("")) if number == 1: gauss() again() elif number == 2: weibull() again() elif number == 3: rayleigh() again() elif number == 4: lognormal() again() elif number == 5: cauchy() again() else: print("Wrong number!") def again(): print("Would you like to try again?:\n1 - yes\n2 - no") choice = int(input("")) if choice == 1: start() elif choice == 2: return 0 start()
d959f4de2e8e948792b54dd7cd52cbe3a8db8c96
Christine1225/Leetcode_py3
/14.py
1,871
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 6 18:36:39 2018 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 @author: Abigail """ class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs : return "" shortest = len(strs) if shortest == 1 and strs[0] != "": return strs[0] shortest = len(strs[0]) shortest_index = 0 for index,short in enumerate (strs ): shortest_index,shortest =( index,len(short)) if len(short) < shortest else (shortest_index,shortest) if shortest == 0: return "" loop = True for index,ic in enumerate (strs[shortest_index]): for i in strs: if i == shortest_index: continue if i[index] != ic: loop = False break if not loop: break if loop: return strs[shortest_index] return strs[shortest_index][:index] ss = Solution() #test =["dog","racecar","car"] #print(ss.longestCommonPrefix(test)) #test =["flower","flow","flight"] #print(ss.longestCommonPrefix(test)) #test =[""] #print(ss.longestCommonPrefix(test)) test =["ca","a"] print(ss.longestCommonPrefix(test)) test =["a"] print(ss.longestCommonPrefix(test)) test =["aa","aa"] print(ss.longestCommonPrefix(test)) test =["a","ab","ac","ad"] print(ss.longestCommonPrefix(test))
755273ac19faf2740da588ca41c607846ca03797
netfj/Project_Stu02
/e100/e038.py
666
3.609375
4
#coding:utf-8 """ @info: 题目:求一个3*3矩阵 主 对角线元素之和。 @author:NetFj @software:PyCharm @file:e038.py @time:2018/11/5.22:08 """ import random # a = random.randint(-100,100) m=3 a = [[random.randint(0,10) for n in range(m)] for n in range(m)] for x in a: print(x) # 主对角线 s=0 h=len(a[0]) for n in range(h): s += a[n][n] print(s) print('-------------') # 两条对角线 s=0 h = len(a[0]) for n in range(0,h): print(a[n][n],a[n][h-n-1]) s += a[n][n] s += a[n][h-n-1] # 奇数时去掉中间的数 if not h%2==0: s0 = a[int((h-1)/2)][int((h-1)/2)] print('减去重复的中间数:',s0) s -= s0 print(s)
f9bf9633d75bf991e9bc17eb1dcc3c3ed672c2a1
donghL-dev/Info-Retrieval
/lecture-data/PythonBasics/003_list.py
577
3.59375
4
L=[] L=['a','b','c','d'] print(L) print(L[0]) print(L[-1]) print(len(L)) L.append('e') del L[0] s='-'.join(L) print(s) s='ZZZ ABC DEF GHI JKL' print(s) L=s.split() print(L) if 'ABC' in L: print('ABC is in L') else: print('ABC is not in L') for e in L: print(e) # end for print() for e in sorted(L): print(e) # end for print() for e in sorted(L,reverse=True): print(e) # end for print() for i in range(len(L)): print(i,L[i]) # end for print() for i in range(0,len(L),1): print(i,L[i]) # end for print() for i in range(len(L)-1,-1,-1): print(i,L[i]) # end for
e14413048f057f81da4b7e81513b365c10282aca
lpozo/pyadt
/pyadt/array.py
1,807
3.875
4
"""Array abstract data type.""" import ctypes from typing import Any, Generator, Optional class Array: """Array abstract data type based on ctypes.py_object. >>> a = Array(5) >>> a Array(size=5) >>> len(a) 5 >>> a[0] = 42 >>> a[0] 42 >>> print(a) Array(42, None, None, None, None) """ def __init__(self, size: int) -> None: self._size = size self._data = (ctypes.py_object * self._size)() self._type = None self.clear() def clear(self, value: Optional[Any] = None) -> None: """Clear the array by setting all its items to value. >>> a = Array(5) >>> for i in range(len(a)): ... a[i] = 0 >>> print(a) Array(0, 0, 0, 0, 0) >>> a.clear() >>> print(a) Array(None, None, None, None, None) """ for i in range(self._size): self._data[i] = value def __len__(self) -> int: return self._size def __contain__(self, value): return value in self._data def __getitem__(self, index: int) -> Any: try: return self._data[index] except IndexError: raise IndexError(f"Index out of range: {index}") from None def __setitem__(self, index: int, value: Any) -> None: try: self._data[index] = value except IndexError: raise IndexError(f"Index out of range: {index}") from None def __iter__(self) -> Generator[Any, None, None]: yield from self._data def __reversed__(self): yield from reversed(self._data) def __str__(self) -> str: return f"{self.__class__.__name__}{(*self._data,)}" def __repr__(self) -> str: return f"{self.__class__.__name__}(size={self._size})"
a0cb7b77dc819031743f0ce779cbbf11f07008f7
MIPLabCH/nigsp
/nigsp/operations/laplacian.py
10,863
3.625
4
#!/usr/bin/env python3 """ Operations for laplacian decomposition. Attributes ---------- LGR Logger """ import logging from copy import deepcopy import numpy as np LGR = logging.getLogger(__name__) def compute_laplacian(mtx, negval="absolute", selfloops=False): """ Compute Laplacian (L) matrix from a square matrix. mtx is supposed to be a connectivity matrix - its diagonal will be removed. L is obtained by subtracting the adjacency matrix from the degree matrix. Parameters ---------- mtx : numpy.ndarray A square matrix negval : "absolute", "remove", or "rescale" The intended behaviour to deal with negative values in matrix: - "absolute" will take absolute values of the matrix - "remove" will set all negative elements to 0 - "rescale" will rescale the matrix between 0 and 1. Default is "absolute". selfloops : "degree", bool, or numpy.ndarray Allow or remove self-loops in input matrix. A numpy array can be used to specify particular loops directly in the adjacency matrix. The degree matrix of the Adjacency matrix can also be used instead. In the last two cases, the degree matrix will be updated accordingly. Default is to remove self loops (False). Returns ------- numpy.ndarray The laplacian of mtx numpy.ndarray The degree matrix of mtx as a (mtx.ndim-1)D array, updated with selfloops in case. See Also -------- https://en.wikipedia.org/wiki/Laplacian_matrix Raises ------ NotImplementedError If negval is not "absolute", "remove", or "rescale" If selfloop """ mtx = deepcopy(mtx) if mtx.min() < 0: if negval == "absolute": mtx = abs(mtx) elif negval == "remove": mtx[mtx < 0] = 0 elif negval == "rescale": mtx = (mtx - mtx.min()) / mtx.max() else: raise NotImplementedError( f'Behaviour "{negval}" to deal with negative values is not supported' ) adjacency = deepcopy(mtx) if selfloops is False: adjacency[np.diag_indices(adjacency.shape[0])] = 0 elif selfloops is True: pass elif type(selfloops) is np.ndarray: if selfloops.ndim > 1: raise NotImplementedError( "Multidimensional arrays are not implemented to specify self-loops" ) if selfloops.shape[0] != mtx.shape[0]: raise ValueError( f"Array specified for self-loops has {selfloops.shape[0]} elements, " f"but specified matrix has {mtx.shape[0]} diagonal elements." ) adjacency[np.diag_indices(adjacency.shape[0])] = selfloops elif selfloops == "degree": adjacency[np.diag_indices(adjacency.shape[0])] = 0 adjacency[np.diag_indices(adjacency.shape[0])] = adjacency.sum(axis=1) else: raise NotImplementedError( f'Value "{selfloops}" for self-loops settings is not supported' ) degree = adjacency.sum(axis=1) # This is fixed to across columns degree_mat = np.zeros_like(mtx) degree_mat[np.diag_indices(degree_mat.shape[0])] = degree return degree_mat - adjacency, degree def normalisation(lapl, degree, norm="symmetric", fix_zeros=True): """ Normalise a Laplacian (L) matrix using either symmetric or random walk normalisation. Parameters ---------- lapl : numpy.ndarray A square matrix that is a Laplacian, or a stack of Laplacian matrices. degree : np.ndarray or None, optional An array, a diagonal matrix, or a stack of either. This will be used as the the degree matrix for the normalisation. It's assumed that degree.ndim == lapl.ndim or degree.ndim == lapl.ndim-1. norm : ["symmetric", "symm", "random walk", "rw", random walk inflow", "rwi", "random walk outflow", "rwo"], str, optional The type of normalisation to perform. Default to symmetric. - "symmetric": D^(-1/2) @ L @ ^(-1/2), a.k.a. symmetric laplacian noramlisation - "random walk", "random walk inflow": D^(-1) @ L, a.k.a. random walk It normalises the inflow, i.e. it is row-optimised (each row = 0). Normally used in e.g. consensus networks. - "random walk outflow": L @ D^(-1) It normalises the outflow, i.e. it is column-optimised (each column = 0). Normally used in e.g. physical distribution networks. fix_zeros : bool, optional Whether to change 0 elements in the degree matrix to 1 to avoid multiplying by 0. Default is to do so. Returns ------- numpy.ndarray The normalised laplacian Raises ------ NotImplementedError If `lapl.ndim` - `degree.ndim` > 1 If "norm" is not supported. ValueError If `d` in not a diagonal matrix or an array If `d` and `mtx` have different shapes. See Also -------- https://en.wikipedia.org/wiki/Laplacian_matrix """ deg = deepcopy(degree) if lapl.ndim - deg.ndim > 1: raise NotImplementedError( f"The provided degree matrix is {deg.ndim}D while the " f"provided laplacian matrix is {lapl.ndim}D." ) elif lapl.ndim == deg.ndim: if not (deg.diagonal() == deg.sum(axis=1)).all(): raise ValueError( "The provided degree matrix is not a diagonal matrix (or a stack of)." ) deg = deepcopy(deg.diagonal()) if deg.shape != lapl.shape[:-1]: raise ValueError( f"The provided degree matrix has shape {deg.shape} while the " f"provided matrix has shape {lapl.shape}." ) if fix_zeros: deg[deg == 0] = 1 d = np.zeros_like(lapl) if norm in ["symmetric", "symm"]: d[np.diag_indices(d.shape[0])] = deg ** (-1 / 2) return d @ lapl @ d elif norm in ["random walk", "rw", "random walk inflow", "rwi"]: d[np.diag_indices(d.shape[0])] = deg ** (-1) return d @ lapl elif norm in ["random walk outflow", "rwo"]: d[np.diag_indices(d.shape[0])] = deg ** (-1) return lapl @ d else: raise NotImplementedError(f'Normalisation type "{norm}" is not supported.') def symmetric_normalised_laplacian(mtx, d=None, fix_zeros=True): """ Compute symmetric normalised Laplacian (SNL) matrix. The SNL is obtained by pre- and post- multiplying mtx by the square root of the inverse of the diagonal and subtract the result from the identity matrix. Alternatively, it is possible to specify a different diagonal to do so. With zero-order nodes, the diagonals will contain 0s, returning a Laplacian with NaN elements. To avoid that, 0 elements in d will be changed to 1. Parameters ---------- mtx : numpy.ndarray A [structural] matrix d : np.ndarray or None, optional Either an array or a diagonal matrix. If specified, d will be used as the **normalisation factor** (not the degree matrix). fix_zeros : bool, optional Whether to change 0 elements in the degree matrix to 1 to avoid multiplying by 0 Returns ------- numpy.ndarray The symmetric normalised laplacian of mtx Raises ------ ValueError If `d` in not a diagonal matrix or an array If `d` and `mtx` have different shapes. Note ---- This is here mainly for tests and legacy code, but it would be better not to use it! See Also -------- https://en.wikipedia.org/wiki/Laplacian_matrix#Symmetrically_normalized_Laplacian_2 """ if d is not None: if d.ndim == 1: d = np.diag(d) elif not (np.diag(d) == d.sum(axis=-1)).all(): raise ValueError( "The provided matrix for symmetric normalisation " "is not a diagonal matrix." ) if d.shape != mtx.shape: raise ValueError( f"The provided diagonal has shape {d.shape} while the " f"provided matrix has shape {mtx.shape}." ) colsum = mtx.sum(axis=-1) identity_mat = np.zeros_like(colsum) identity_mat[colsum != 0] = 1 identity_mat = np.diag(identity_mat) if fix_zeros: colsum[colsum == 0] = 1 if d is None: d = np.diag(colsum ** (-1 / 2)) symm_norm = d @ mtx @ d return identity_mat - symm_norm # ## Fix Identity matrix by giving def decomposition(mtx): """ Run a eigenvector decomposition on input. Parameters ---------- mtx : numpy.ndarray The matrix to decompose Returns ------- numpy.ndarray The eigenvalues resulting from the decomposition numpy.ndarray The eigenvectors resulting from the decomposition """ eigenval, eigenvec = np.linalg.eig(mtx) idx = np.argsort(eigenval) eigenval = eigenval[idx] # #!# Check that eigenvec has the right index and not inverted eigenvec = eigenvec[:, idx] return eigenval, eigenvec def recomposition(eigenval, eigenvec): """ Recompose a matrix from its eigenvalues and eigenvectors. At the moment, it supports only 2D (not stacks). Parameters ---------- eigenval : numpy.ndarray Array of eigenvalues. The program detects if it's a diagonal matrix or not. eigenvec : numpy.ndarray Matrix of eigenvectors. Returns ------- numpy.ndarray The reconstructed matrix """ if eigenvec.ndim > 2: raise NotImplementedError( f"Given matrix dimensionality ({eigenvec.ndim}) is not supported." ) if eigenval.ndim == eigenvec.ndim - 1: eigenval = np.diag(eigenval) elif eigenval.ndim < eigenvec.ndim - 1: raise ValueError("Not enough dimensions in given eigenvalue matrix.") elif eigenval.ndim > eigenvec.ndim: raise ValueError("Too many dimensions in given eigenvalue matrix.") elif not (np.diag(eigenval) == eigenval.sum(axis=-1)).all(): raise ValueError("The provided eigenvalue matrix is not a diagonal matrix.") mtx = eigenvec @ eigenval @ eigenvec.T return mtx """ Copyright 2022, Stefano Moia. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """
bc1a314e19da0b9f0a4ca12ca1d3bc8e540baa8f
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/binary/905d373b04574f0d9a7c91efde4ca60f.py
286
3.796875
4
def parse_binary(bin): bin = list(bin) dec = 0 cur = 0 while bin: dig = bin.pop() if dig == '1': dec += 2**cur elif dig != '0': raise ValueError('Input string must contain only 0s and 1s.') cur += 1 return dec
2cb593e1006667e62a9b1aedac63edc480d69da1
annamalai0511/ATM-Banking-Interface
/Main.py
18,456
3.53125
4
#demo account login credential given below #Account Number : 0000 ------------ Password : demo # modules used from tkinter import * from tkinter import messagebox import sqlite3 import time import math, random,smtplib #global font ARIAL = ("arial",10,"bold") class Bank: # login page def __init__(self,root): root.geometry("550x550") self.conn = sqlite3.connect("atm_databse.db", timeout=100) self.login = False self.root = root self.header = Label(self.root,text="STATE BANK OF INDIA",bg="#50A8B0",fg="white",font=("arial",20,"bold")) self.header.pack(fill=X) self.frame = Frame(self.root,bg="#728B8E",width=550,height=550) # Login Page Form Components self.userlabel =Label(self.frame,text="ACCOUNT NUMBER",bg="#728B8E",fg="white",font=ARIAL) self.uentry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.plabel = Label(self.frame, text="PASSWORD",bg="#728B8E",fg="white",font=ARIAL) self.pentry = Entry(self.frame,bg="honeydew",show="*",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.fpbutton =Button(self.frame,text="Forgot Password",bg="#50A8B0",fg="white",font=ARIAL,command=self.otp) self.nubutton = Button(self.frame,text="New User",bg="#50A8B0",fg="white",font=ARIAL,command=self.new_user) self.log_button = Button(self.frame,text="LOGIN",bg="#50A8B0",fg="white",font=ARIAL,command=self.verify) self.q = Button(self.frame,text="Quit",bg="#50A8B0",fg="white",font=ARIAL,command = self.root.destroy) # placement of buttons,labels self.userlabel.place(x=145,y=100,width=200,height=20) self.uentry.place(x=153,y=130,width=200,height=20) self.plabel.place(x=125,y=160,width=200,height=20) self.pentry.place(x=153,y=190,width=200,height=20) self.log_button.place(x=220,y=240,width=55,height=25) self.fpbutton.place(x=50,y=300,width=150,height=25) self.nubutton.place(x=250,y=300,width=100,height=25) self.q.place(x=400,y=300,width=50,height=25) self.frame.pack() # forgot password : otp methoed to retrive password def otp(self): messagebox._show("Notice","get to the idle screen" ) self.acc_list = [] self.temp = self.conn.execute("select email from atm where acc_no = ? ",(int(self.uentry.get()),)) for i in self.temp: self.acc_list.append("{}".format(i[0])) import math, random,smtplib email=self.acc_list string = '0123456789' OTP = "" length = len(string) for i in range(6): OTP += string[math.floor(random.random() * length)] s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login("statebankofindia.in.com@gmail.com", "assveera") subject = "Your One Time Password (OTP) for BANKING on SBI is " body = "The requested otp is : " message = f'Subject :{subject}\n\n{body+OTP}' s.sendmail("statebankofindia.in.com@gmail.com", email, message) s.quit() otp = input("ENTER OTP : ") if otp == OTP: print("OTP is correct") self.acc=int(self.uentry.get()) passw=input("enter your password here : ") self.conn.execute("update atm set pass = ? where acc_no = ?",(passw,self.acc)) messagebox._show("Notice", "your password has been changed successfully") else: print("OTP is wrong :(") # new user registration def new_user(self): self.frame.destroy() self.header = Label(self.root,text="NEW USER APPLICATION",bg="#50A8B0",fg="white",font=("arial",20,"bold")) self.header.pack(fill=X) self.frame = Frame(self.root,bg="#728B8E",width=1000,height=1100) # Login Page Form Components self.name_label =Label(self.frame,text="NAME",bg="#728B8E",fg="white",font=ARIAL) self.name_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.accno_label = Label(self.frame, text="ACC_NO.",bg="#728B8E",fg="white",font=ARIAL) self.accno_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.acctype_label =Label(self.frame,text="ACC_TYPE",bg="#728B8E",fg="white",font=ARIAL) self.acctype_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.balance_label =Label(self.frame,text="BALANCE",bg="#728B8E",fg="white",font=ARIAL) self.balance_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.password_label =Label(self.frame,text="PASSWORD",bg="#728B8E",fg="white",font=ARIAL) self.password_entry = Entry(self.frame,bg="honeydew",show="*",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.email_label =Label(self.frame,text="EMAIL",bg="#728B8E",fg="white",font=ARIAL) self.email_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.phno_label =Label(self.frame,text="PHONE NO.",bg="#728B8E",fg="white",font=ARIAL) self.phno_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.done_button = Button(self.frame,text="Done",bg="#50A8B0",fg="white",font=ARIAL,command=self.insert) self.quit = Button(self.frame,text="Quit",bg="#50A8B0",fg="white",font=ARIAL,command = self.root.destroy) # placement of buttons,labels self.name_label.place(x=50,y=50,width=150,height=20) self.name_entry.place(x=250,y=50,width=150,height=20) self.accno_label.place(x=50,y=100,width=150,height=20) self.accno_entry.place(x=250,y=100,width=150,height=20) self.acctype_label.place(x=50,y=150,width=150,height=20) self.acctype_entry.place(x=250,y=150,width=150,height=20) self.balance_label.place(x=50,y=200,width=150,height=20) self.balance_entry.place(x=250,y=200,width=150,height=20) self.password_label.place(x=50,y=250,width=150,height=20) self.password_entry.place(x=250,y=250,width=150,height=20) self.email_label.place(x=50,y=300,width=150,height=20) self.email_entry.place(x=250,y=300,width=150,height=20) self.phno_label.place(x=50,y=350,width=150,height=20) self.phno_entry.place(x=250,y=350,width=150,height=20) self.done_button.place(x=123,y=400,width=50,height=20) self.quit.place(x=325,y=400,width=50,height=20) self.frame.pack() def insert(self): entries=(self.name_entry.get(),self.accno_entry.get(),self.acctype_entry.get(),self.balance_entry.get(),self.password_entry.get(),self.email_entry.get(),self.phno_entry.get()) self.conn.execute("insert into atm values(?,?,?,?,?,?,?)",entries) self.conn.commit() messagebox._show("Notice", "your account is been created ! please log in again") #Fetching Account data from database def database_fetch(self): self.acc_list = [] self.temp = self.conn.execute("select name,pass,acc_no,acc_type,bal,email,phno from atm where acc_no = ? ",(self.ac,)) for i in self.temp: self.acc_list.append("Name = {}".format(i[0])) self.acc_list.append("Password = {}".format(i[1])) self.acc_list.append("Account no = {}".format(i[2])) self.acc_list.append("Account type = {}".format(i[3])) self.ac = i[2] self.acc_list.append("Balance = {}".format(i[4])) self.acc_list.append("{}".format(i[5])) self.acc_list.append("Phone No. = {}".format(i[6])) return self.ac #verifying of authorised user def verify(self): ac = False self.temp = self.conn.execute("select name,pass,acc_no,acc_type,bal from atm where acc_no = ? ", (int(self.uentry.get()),)) for i in self.temp: self.ac = i[2] if i[2] == self.uentry.get(): ac = True elif i[1] == self.pentry.get(): ac = True m = "{} Login SucessFull".format(i[0]) self.database_fetch() messagebox._show("Login Info", m) self.frame.destroy() self.MainMenu() else: ac = True m = " Login UnSucessFull ! Wrong Password" messagebox._show("Login Info!", m) self.MainMenu() self.email() if not ac: m = " Wrong Acoount Number !" messagebox._show("Login Info!", m) #security alert ensured : send a mail about wrong login def email(self): import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import os.path self.database_fetch() email = 'statebankofindia.in.com@gmail.com' #login details password = 'assveera' send_to_email = self.acc_list[5] subject = 'Critical security alert' # The subject line message = ("Your Bank Account was just signed in from a new Windows device.\n" #message "You're getting this email to make sure it was you.\n" "If you didn't change it, you should check what happened.\n") #file location :: please change this location according to your computer file_location=r"C:\Users\surya\Desktop\Banking_Project-ATM-- MASTER\DATA\How to protect your bank cards from fraud.docx" msg = MIMEMultipart() msg['From'] = email msg['To'] = send_to_email msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) # Setup the attachment filename = os.path.basename(file_location) attachment = open(file_location, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) # Attach the attachment to the MIMEMultipart object msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, send_to_email, text) server.quit() #Main App Appears after logined ! def MainMenu(self): self.frame = Frame(self.root,bg="#728B8E",width=1300,height=600) root.geometry("1300x510") #button anf funtional commands self.detail = Button(self.frame,text="Account Details",bg="#50A8B0",fg="white",font=ARIAL,command=self.account_detail) self.enquiry = Button(self.frame, text="Balance Enquiry",bg="#50A8B0",fg="white",font=ARIAL,command= self.Balance) self.deposit = Button(self.frame, text="Deposit Money",bg="#50A8B0",fg="white",font=ARIAL,command=self.deposit_money) self.withdrawl = Button(self.frame, text="Withdrawl Money",bg="#50A8B0",fg="white",font=ARIAL,command=self.withdrawl_money) self.pinchange = Button(self.frame, text="Pin Change",bg="#50A8B0",fg="white",font=ARIAL,command=self.pinchange2) self.transfer = Button(self.frame, text="Transfer Fund",bg="#50A8B0",fg="white",font=ARIAL,command=self.transfer) self.q = Button(self.frame, text="Quit", bg="#50A8B0", fg="white", font=ARIAL, command=self.root.destroy) self.log = Button(self.frame, text="Logout",bg="#50A8B0",fg="white",font=ARIAL, command=self.logout) #placement of these buttons self.detail.place(x=100,y=50 ,width=200,height=50) self.withdrawl.place(x=100, y=200, width=200, height=50) self.transfer.place(x=100, y=350, width=200, height=50) self.enquiry.place(x=900, y=50, width=200, height=50) self.deposit.place(x=900, y=200, width=200, height=50) self.pinchange.place(x=900, y=350, width=200, height=50) self.q.place(x=350, y=350, width=200, height=50) self.log.place(x=650, y=350, width=200, height=50) self.frame.pack() #internal functions def logout(self): text="STATE BANK OF INDIA"+"\n"+"You Have Been Successfully Logged Out!"+"\n"+str(time.ctime()) self.label = Label(self.frame, text=text,font=ARIAL) self.label.place(x=400,y=150,width=400,height=100) self.frame.destroy() self.header.destroy() self.__init__(root) def account_detail(self): self.database_fetch() text = self.acc_list[0]+"\n"+self.acc_list[2]+"\n"+self.acc_list[3]+"\n"+self.acc_list[5]+"\n"+self.acc_list[6] self.label = Label(self.frame,text=text,font=ARIAL) self.label.place(x=400,y=150,width=400,height=100) self.ok = Button(self.frame,text="ok",bg="#50A8B0",fg="white",font=ARIAL,command = self.label.destroy) self.ok.place(x=575,y=300,width=50,height=25) def Balance(self): self.database_fetch() self.label = Label(self.frame, text=self.acc_list[4],font=ARIAL) self.label.place(x=400,y=150,width=400,height=100) self.ok = Button(self.frame,text="ok",bg="#50A8B0",fg="white",font=ARIAL,command = self.label.destroy) self.ok.place(x=575,y=300,width=50,height=25) def deposit_money(self): self.money_box = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.submitButton = Button(self.frame,text="Submit",bg="#50A8B0",fg="white",font=ARIAL) self.money_box.place(x=375,y=100,width=175,height=20) self.submitButton.place(x=575,y=200,width=55,height=20) self.submitButton.bind("<Button-1>",self.deposit_trans) def deposit_trans(self,flag): self.label = Label(self.frame, text="Transaction Completed !", font=ARIAL) self.label.place(x=400,y=150,width=400,height=100) self.conn.execute("update atm set bal = bal + ? where acc_no = ?",(self.money_box.get(),self.ac)) self.conn.commit() def withdrawl_money(self): self.money_box = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.submitButton = Button(self.frame,text="Submit",bg="#50A8B0",fg="white",font=ARIAL) self.money_box.place(x=650,y=100,width=175,height=20) self.submitButton.place(x=575,y=200,width=55,height=20) self.submitButton.bind("<Button-1>",self.withdrawl_trans) def withdrawl_trans(self,flag): self.label = Label(self.frame, text="Money Withdrawl !", font=ARIAL) self.label.place(x=400,y=150,width=400,height=100) self.conn.execute("update atm set bal = bal - ? where acc_no = ?",(self.money_box.get(),self.ac)) self.conn.commit() def pinchange2(self): self.label = Label(self.frame, text="Type Password Below !", font=ARIAL) self.label.place(x=400,y=150,width=400,height=100) self.passwd_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.passwd_entry.place(x=520,y=225,width=175,height=20) self.submit_Button = Button(self.frame,text="Submit",bg="#50A8B0",fg="white",font=ARIAL,command=self.fppinchange) self.submit_Button.place(x=570,y=270,width=55,height=20) passwd=str(self.passwd_entry.get()) self.conn.execute("update atm set pass = ? where acc_no = ?",(passwd,self.ac)) self.conn.commit() def fppinchange (self): self.conn.execute("update atm set pass = ? where acc_no = ?",(self.passwd_entry.get(),self.ac)) self.conn.commit() messagebox._show("Notice", "your password has been changed successfully") def transfer(self): self.tacc = Label(self.frame, text="account no. of the recipient", font=ARIAL) self.tacc_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.tamt = Label(self.frame, text="amt to be transferred", font=ARIAL) self.tamt_entry = Entry(self.frame,bg="honeydew",highlightcolor="#50A8B0",highlightthickness=2,highlightbackground="white") self.submit_Button = Button(self.frame,text="Submit",bg="#50A8B0",fg="white",font=ARIAL,command=self.transfer1) self.tacc.place(x=400,y=100,width=400,height=20) self.tacc_entry.place(x=535,y=150,width=150,height=20) self.tamt.place(x=400,y=200,width=400,height=20) self.tamt_entry.place(x=535,y=250,width=150,height=20) self.submit_Button.place(x=575,y=300,width=70,height=20) def transfer1(self): self.conn.execute("update atm set bal = bal - ? where acc_no = ?",(self.tamt_entry.get(),self.ac)) self.conn.commit() self.conn.execute("update atm set bal = bal + ? where acc_no = ?",(self.tamt_entry.get(),self.tacc_entry.get())) self.conn.commit() messagebox._show("Notice", "transferred successfully") root = Tk() root.title("Sign In") root.geometry("600x420") icon = PhotoImage(file="icon.png") root.tk.call("wm",'iconphoto',root._w,icon) obj = Bank(root) root.mainloop()