text
stringlengths
37
1.41M
# Standard library imports. import optparse import shlex def magic_fwrite(interpreter, parameter_s=''): """ Write the string representation of a variable out to a file. %fwrite myvar myfile.txt Usually, simply str(myvar) will be the string that gets written out. Unicode strings will be encoded to a byte string (as UTF-8 by default) first. """ varname, filename = shlex.split(parameter_s) value = interpreter.pull(varname) # Special case unicode strings. # fixme: allow the caller to specify an encoding. if isinstance(value, unicode): stringrep = value.encode('utf-8') else: stringrep = str(value) # Write the string out to a file. # fixme: Allow the user to change the mode. f = open(filename, 'wb') f.write(stringrep) f.close()
"""A queue that works on a ticketing system. Classes: TicktedQueue -- A FIFO queue with a ticketing system """ #***************************************************************************** # Copyright (C) 2005 Brian Granger, <[email protected]> # Fernando Perez. <[email protected]> # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** import Queue class TicketedQueue(object): """A FIFO queue with a ticketing system to provide asynchronous operations. """ def __init__(self): self.q = Queue.Queue() self.line = {} self.tickets = [] self.next_ticket = 0 self.next_to_call = 0 def get_ticket(self): t = self.next_ticket self.tickets.append(t) self.next_ticket += 1 return t def del_ticket(self, ticket): if ticket in self.tickets: self.line[ticket] = 'SKIPTICKET' self._load_queue() else: raise Exception def put(self, item, ticket=None): if ticket == None: ticket = self.get_ticket() if ticket in self.tickets: self.line[ticket] = item # See if there are any that can be placed in the queue self._load_queue() else: raise Exception def _load_queue(self): next = self.line.get(self.next_to_call) while next: if not next == 'SKIPTICKET': self.q.put(next,block=True,timeout=None) del self.line[self.next_to_call] del self.tickets[self.tickets.index(self.next_to_call)] self.next_to_call += 1 next = self.line.get(self.next_to_call) def get(self,block=True,timeout=None): return self.q.get(block,timeout) def qsize(self): return self.q.qsize() def empty(self): return self.q.empty() def full(self): return self.q.full()
def fib(num): arr = [0,1] for x in range(2,num+1): arr.append(arr[x-1]+arr[x-2]) return arr if __name__ == "__main__": print(fib(int(input("Put any num bigger than 1: "))))
import matplotlib.pyplot as plt import numpy as np from matplotlib.font_manager import FontProperties as FP from ..postprocessors.units import get_unit_converter def plot_convergence(dataframe, units=None, final_error=None, ax=None): """Plot the forward and backward convergence. The input could be the result from :func:`~alchemlyb.convergence.forward_backward_convergence` or :func:`~alchemlyb.convergence.fwdrev_cumavg_Rc`. The input should be a :class:`pandas.DataFrame` which has column `Forward`, `Backward` and :attr:`pandas.DataFrame.attrs` should compile with :ref:`note-on-units`. The errorbar will be plotted if column `Forward_Error` and `Backward_Error` is present. `Forward`: A column of free energy estimate from the first X% of data, where optional `Forward_Error` column is the corresponding error. `Backward`: A column of free energy estimate from the last X% of data., where optional `Backward_Error` column is the corresponding error. `final_error` is the error of the final value and is shown as the error band around the final value. It can be provided in case an estimate is available that is more appropriate than the default, which is the error of the last value in `Backward`. Parameters ---------- dataframe : Dataframe Output Dataframe has column `Forward`, `Backward` or optionally `Forward_Error`, `Backward_Error` see :ref:`plot_convergence <plot_convergence>`. units : str The unit of the estimate. The default is `None`, which is to use the unit in the input. Setting this will change the output unit. final_error : float The error of the final value in ``units``. If not given, takes the last error in `backward_error`. ax : matplotlib.axes.Axes Matplotlib axes object where the plot will be drawn on. If ``ax=None``, a new axes will be generated. Returns ------- matplotlib.axes.Axes An axes with the forward and backward convergence drawn. Note ---- The code is taken and modified from `Alchemical Analysis <https://github.com/MobleyLab/alchemical-analysis>`_. .. versionchanged:: 1.0.0 Keyword arg final_error for plotting a horizontal error bar. The array input has been deprecated. The units default to `None` which uses the units in the input. .. versionchanged:: 0.6.0 data now takes in dataframe .. versionadded:: 0.4.0 """ if units is not None: dataframe = get_unit_converter(units)(dataframe) forward = dataframe["Forward"].to_numpy() if "Forward_Error" in dataframe: forward_error = dataframe["Forward_Error"].to_numpy() else: forward_error = np.zeros(len(forward)) backward = dataframe["Backward"].to_numpy() if "Backward_Error" in dataframe: backward_error = dataframe["Backward_Error"].to_numpy() else: backward_error = np.zeros(len(backward)) if ax is None: # pragma: no cover fig, ax = plt.subplots(figsize=(8, 6)) plt.setp(ax.spines["bottom"], color="#D2B9D3", lw=3, zorder=-2) plt.setp(ax.spines["left"], color="#D2B9D3", lw=3, zorder=-2) for dire in ["top", "right"]: ax.spines[dire].set_color("none") ax.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("left") f_ts = np.linspace(0, 1, len(forward) + 1)[1:] r_ts = np.linspace(0, 1, len(backward) + 1)[1:] if final_error is None: final_error = backward_error[-1] if np.isfinite(backward[-1]) and np.isfinite(final_error): line0 = ax.fill_between( [0, 1], backward[-1] - final_error, backward[-1] + final_error, color="#D2B9D3", zorder=1, ) line1 = ax.errorbar( f_ts, forward, yerr=forward_error, color="#736AFF", lw=3, zorder=2, marker="o", mfc="w", mew=2.5, mec="#736AFF", ms=12, ) line2 = ax.errorbar( r_ts, backward, yerr=backward_error, color="#C11B17", lw=3, zorder=3, marker="o", mfc="w", mew=2.5, mec="#C11B17", ms=12, ) xticks_spacing = len(r_ts) // 10 or 1 xticks = r_ts[::xticks_spacing] plt.xticks(xticks, [f"{i:.2f}" for i in xticks], fontsize=10) plt.yticks(fontsize=10) ax.legend( (line1[0], line2[0]), ("Forward", "Reverse"), loc=9, prop=FP(size=18), frameon=False, ) ax.set_xlabel(r"Fraction of the simulation time", fontsize=16, color="#151B54") ax.set_ylabel(r"$\Delta G$ ({})".format(units), fontsize=16, color="#151B54") plt.tick_params(axis="x", color="#D2B9D3") plt.tick_params(axis="y", color="#D2B9D3") return ax
import sys import pandas as pd SPLITTER = "!!!" ''' Read the questions from the given filename :param: (str) filename: the given filename ''' def readQuestions(filename): try: # Reading the file with open(f'../questions_from_books/{filename}', 'r') as readFile: txt = str(readFile.read()).strip() questions = [question.replace('\n', ' ').strip() for question in txt.split(SPLITTER)] return questions except Exception as e: raise return [] ''' Read the programming questions from csv file :param: (str) filename: the given csv file ''' def readProgrammingQuestions(filename): try: # Loading df = pd.read_csv(f'../algo_questions/{filename}', header = None) if len(df.columns) > 4: df.drop(df.columns[4], axis = 1, inplace = True) df.columns = ["title", "level", "body", "labels"] questions = list(map(lambda res: {'title': res[1]['title'], 'body': res[1]['body'], 'level': res[1]['level'], 'labels': res[1]['labels'].split(',') }, df.iterrows())) return questions except Exception as e: raise return []
import nltk MAX_TITLE_LENGTH = 50 ''' Generating title from a given text :param: (str) text: the given text :return: (str) title: generated title ''' def generateTitleFromText(text): # Splitting into the sentences sentences = nltk.sent_tokenize(text) # TODO: Later it can be updated into more advanced form title = sentences[0] if len(sentences) > 0 else "..." # Limiting if len(title) > MAX_TITLE_LENGTH: title = title[:MAX_TITLE_LENGTH] title += "..." return title
## This solution provides the longest length achievable as well as subsequence itself ## Example--- list = [5,7,4,-3,9,1,10,4,5,8,9,3] ## LIS is -3,1,4,5,8,9 ## maximum LIS length is 6 list = [5,7,4,-3,9,1,10,4,5,8,9,3] length = [] nums = [] def LIS(list): for i in range (0,len(list)): ## Length of one item is one length.append(1) nums.append([list[i]]) for x in range (0,i): ## If list item that comes before item list[i] is less than list[i], than you know you can append list[i] to end (if length would be longer than current LIS for item i) if list[x] < list[i] and length[i] < 1 + length[x]: length.pop(i) length.append(1 + length[x]) nums.pop(i) nums.append(nums[x] + [list[i]]) maxVal = 1 maxIndex = 0 for i in range(0,len(length)): if length[i] > maxVal: maxVal = length[i] maxIndex = i print 'Length of the Longest Increasing Subsequence is ',maxVal print 'LIS is ',nums[maxIndex] return maxVal LIS(list)
# Expressão Lógica num = float(input("Digite um número: ")) exp = 1 <= num or num >=10 print(exp)
#Operações com numeros inteiros num = 0 i = 1 cont_par = 0 cont_impar = 0 somapar = 0 somarimpar = 0 for i in range(10): num = int(input("Digite um número inteiro:")) resto = num % 2 if resto == 0: cont_par = cont_par+1 somapar = somapar+num else: cont_impar = cont_impar+1 somarimpar = somarimpar+num med = somarimpar/cont_impar medarred = round(med, 2) print(" O número de inteiros pares é:", cont_par) print(" O número de inteiros ímpares é:", cont_impar) print("Soma dos números pares é", somapar) print("Soma dos números impares é", somarimpar) print("A média dos números ímpares é", medarred)
def main(): import sys import random import time from faker import Faker import names import gender_guesser.detector as gender fake = Faker() print("\n>>Created by SOD<<") userdefined_file_name=input("\nEnter your desired file name \t") file_txt=userdefined_file_name + ".txt" firstname_txt=userdefined_file_name +'Firstname' ".txt" middlename_txt=userdefined_file_name +'MiddleName' ".txt" lastname_txt=userdefined_file_name +'Lastname' ".txt" fullname_txt=userdefined_file_name+ 'Fullname' ".txt" firstname_lastname_txt=userdefined_file_name +'Firstname_Lastname' ".txt" firstname_middlename_lastname_txt=userdefined_file_name +'Firstname_MiddleName_Lastname' ".txt" title_txt=userdefined_file_name +'Title' ".txt" old_stdout = sys.stdout gender_detector = gender.Detector() def process_completed_time(): #sys.stdout.close() sys.stdout = old_stdout print("\n Generation is completed at " +time.ctime() +" \n Have a look at your file :) ") #time.sleep(150) file_generate_decision=input("\nDo you want to generate another file\nReply with Y or N\t") if(file_generate_decision=='Y' or file_generate_decision=='y'): main() else: exit(0) def wordsinglecount(): string= input("\nEnter Some sample name for Data Generation: \n Eg: Sanjay \n (or) \n Manoj Tiwari \n (or) \n Mary Elizabeth Smith \t") word = 1 for i in string: if(i==' '): word=word+1 if(word==3): title_decision=input("\nDo you want to include Title at the beginning? \n Eg: Ms. Mary Elizabeth Smith \n Reply with Y or N \t") if(title_decision=='Y' or title_decision== 'y'): firstname_middlename_lastname_title_single_file() elif(title_decision=='N' or title_decision=='n'): firstname_middlename_lastname_single_file() else: print("Sorry you haven't selected any options:( \n So going back<<<") wordsinglecount() elif(word==2): title_decision=input("\nDo you want to include Title at the beginning? \n Eg: Mr. Manoj Tiwari \n Reply with Y or N \t") if(title_decision=='Y' or title_decision== 'y'): firstname_lastname_title_single_file() elif(title_decision=='N' or title_decision=='n'): firstname_lastname_single_file() else: print("Sorry you haven't selected any options:( \n So going back<<<") wordsinglecount() elif(word==1): title_decision=input("\nDo you want to include Title at the beginning? \n Eg: Mr. Anush\n Reply with Y or N \t") if(title_decision=='Y' or title_decision== 'y'): firstname_title_single_file() elif(title_decision=='N' or title_decision=='n'): firstname_single_file() else: print("Sorry you haven't selected any options:( \n So going back<<<") wordsinglecount() firstname_title_single_file() def wordsplitcount(): string= input("\nEnter Some sample name for Data Generation: \n Eg: Sanjay \n (or) \n Manoj Tiwari \n (or) \n Mary Elizabeth Smith \t") word = 1 for i in string: if(i==' '): word=word+1 if(word==3): firstname_middlename_lastname_split_files() elif(word==2): firstname_lastname_split_files() elif(word==1): firstname_split_files() def firstname_title_single_file(): try: firstname_textfile_creation=open(firstname_txt,"w") userdefined_count=int(input("\n Enter the Number of Names (First Name) you want to generate\n in a single file \n Sample Output:Mr. Sanjay \t")) print("\n Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=firstname_textfile_creation a= names.get_first_name() gen=(gender_detector.get_gender(a)) print('Mr.'+" "+a if (gen=='male' or gen=='mostly_male') else 'Miss.'+" "+a) firstname_textfile_creation.close() finally: process_completed_time() def firstname_single_file(): try: firstname_textfile_creation=open(firstname_txt,"w") userdefined_count=int(input("\n Enter the Number of Names (First Name) you want to generate\n in a single file \n Sample Output: Sanjay \t")) print("\n Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=firstname_textfile_creation a= names.get_first_name() print(a) firstname_textfile_creation.close() finally: process_completed_time() def firstname_lastname_title_single_file(): try: firstname_lastname_textfile_creation=open(firstname_lastname_txt,"w") userdefined_count=int(input("\n Enter the Number of Names (First Name / Last Name) you want to generate\n in a single file \n Sample Output:Mr. Manoj Tiwari \t")) print("\n Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=firstname_lastname_textfile_creation a= names.get_first_name() b= names.get_last_name() gen=(gender_detector.get_gender(a)) print('Mr.'+" "+a+" "+b if (gen=='male' or gen=='mostly_male') else 'Miss.'+" "+a+" "+b) firstname_lastname_textfile_creation.close() finally: process_completed_time() def firstname_middlename_lastname_single_file(): try: firstname_middlename_lastname_textfile_creation=open(firstname_middlename_lastname_txt,"w") userdefined_count=int(input("\nEnter the Number of Names (First Name / Middle Name / Last Name) \n you want to generate in single file \n Sample Output: Ms. Mary Elizabeth Smith \t")) print("\nYour process is started at "+time.ctime()) female_list=['Miss.','Mrs.'] for _ in range(userdefined_count): sys.stdout=firstname_middlename_lastname_textfile_creation a= names.get_first_name() b= names.get_last_name() gen=(gender_detector.get_gender(a)) print(a+" "+fake.first_name_male()+" "+b if (gen=='male' or gen=='mostly_male') else a+" "+fake.first_name_female()+" "+b) firstname_middlename_lastname_textfile_creation.close() finally: process_completed_time() def firstname_middlename_lastname_title_single_file(): try: firstname_middlename_lastname_textfile_creation=open(firstname_middlename_lastname_txt,"w") userdefined_count=int(input("\nEnter the Number of Names (First Name / Middle Name / Last Name) \n you want to generate in single file \n Sample Output: Ms. Mary Elizabeth Smith \t")) print("\nYour process is started at "+time.ctime()) female_list=['Miss.','Mrs.'] for _ in range(userdefined_count): sys.stdout=firstname_middlename_lastname_textfile_creation a= names.get_first_name() b= names.get_last_name() gen=(gender_detector.get_gender(a)) print("Mr. "+a+" "+fake.first_name_male()+" "+b if (gen=='male' or gen=='mostly_male') else fake.random_element(female_list)+a+" "+fake.first_name_female()+" "+b) firstname_middlename_lastname_textfile_creation.close() finally: process_completed_time() def firstname_lastname_single_file(): try: firstname_lastname_textfile_creation=open(firstname_lastname_txt,"w") userdefined_count=int(input("\n Enter the Number of Names (First Name / Last Name) you want to generate\n in a single file \n Sample Output:Manoj Tiwari \t")) print("\n Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=firstname_lastname_textfile_creation a= names.get_first_name() b= names.get_last_name() print(a+" "+b) firstname_lastname_textfile_creation.close() finally: process_completed_time() def firstname_lastname_split_files(): try: choice_m=(input("What do you want to generate names in Lowercase or UpperCase, Reply with your choice(Number) \n 1.Lower \n 2.Upper\n")) if choice_m=='1': firstname_textfile_creation=open(firstname_txt,"w") lastname_textfile_creation=open(lastname_txt,"w") title_textfile_creation=open(title_txt,"w") userdefined_count=int(input("\n ETA 1L data: 20 min including title \n Enter the Number of Names (First Name / Last Name) you want to generate \n Sample Output:Mr. Manoj Tiwari \t")) print("\nYour process is started at "+time.ctime()) female_list=['Miss.','Mrs.'] for _ in range(userdefined_count): sys.stdout=firstname_textfile_creation a= names.get_first_name() b= names.get_last_name() print(a) sys.stdout=title_textfile_creation gen=(gender_detector.get_gender(a)) if gen=='male' or gen=='mostly_male': print('Mr.') else: print(fake.random_element(female_list)) sys.stdout=lastname_textfile_creation print(b) firstname_textfile_creation.close() title_textfile_creation.close() lastname_textfile_creation.close() if choice_m=='2': firstname_textfile_creation=open(firstname_txt,"w") lastname_textfile_creation=open(lastname_txt,"w") title_textfile_creation=open(title_txt,"w") userdefined_count=int(input("\nETA 1L data: 20 min including title \n Enter the Number of Names (First Name / Last Name) you want to generate \n Sample Output:Mr. MANOJ TIWARI \t")) print("\nYour process is started at "+time.ctime()) female_list=['Miss.','Mrs.'] for _ in range(userdefined_count): sys.stdout=firstname_textfile_creation a= names.get_first_name() b= names.get_last_name() print(a.upper()) sys.stdout=title_textfile_creation gen=(gender_detector.get_gender(a)) if gen=='male' or gen=='mostly_male': print('Mr.') else: print(fake.random_element(female_list)) sys.stdout=lastname_textfile_creation print(b.upper()) firstname_textfile_creation.close() title_textfile_creation.close() lastname_textfile_creation.close() finally: process_completed_time() def firstname_middlename_lastname_split_files(): try: firstname_textfile_creation=open(firstname_txt,"w") middlename_textfile_creation=open(middlename_txt,"w") lastname_textfile_creation=open(lastname_txt,"w") fullname_textfile_creation=open(fullname_txt,"w") title_textfile_creation=open(title_txt,"w") userdefined_count=int(input("\nEnter the Number of Names (First Name / Middle Name / Last Name) you want to generate \n Sample Output: Ms. Mary Elizabeth Smith \t")) print("\nYour process is started at "+time.ctime()) female_list=['Miss.','Mrs.'] for _ in range(userdefined_count): sys.stdout=firstname_textfile_creation a= names.get_first_name() b= names.get_last_name() c=fake.first_name_male() d=fake.first_name_female() print(a) sys.stdout=title_textfile_creation gen=(gender_detector.get_gender(a)) if gen=='male' or gen=='mostly_male': print('Mr.') else: print(fake.random_element(female_list)) sys.stdout=lastname_textfile_creation print(b) sys.stdout=middlename_textfile_creation if gen=='male' or gen=='mostly_male': print(c) else: print(d) sys.stdout=fullname_textfile_creation #print("Mr. "+a+" "+fake.first_name_male()+" "+b if (gen=='male' or gen=='mostly_male') else "Ms. "+a+" "+fake.first_name_female()+" "+b) print(a+' '+c+' '+b if (gen=='male' or gen=='mostly_male') else a+" "+d+" "+b) firstname_textfile_creation.close() title_textfile_creation.close() lastname_textfile_creation.close() fullname_textfile_creation.close() middlename_textfile_creation.close() finally: process_completed_time() def firstname_split_files(): try: firstname_textfile_creation=open(firstname_txt,"w") title_textfile_creation=open(title_txt,"w") userdefined_count=int(input("Enter the Number of Names (First Name) you want to generate \n Sample Output: Mr. Sanjay \t")) print("Your process is started at "+time.ctime()) female_list=['Miss.','Mrs.'] for _ in range(userdefined_count): sys.stdout=firstname_textfile_creation a= names.get_first_name() print(a) sys.stdout=title_textfile_creation gen=(gender_detector.get_gender(a)) if gen=='male' or gen=='mostly_male': print('Mr.') else: print(fake.random_element(female_list)) firstname_textfile_creation.close() title_textfile_creation.close() finally: process_completed_time() choice_m=(input("What do you want to generate, Reply with your choice(Number) \n 1.Address \n 2.Phone Number \n 3.Company Names \n 4.Credit Card Number \n 5.Email ID's \n 6.Job Titles \n 7.Name \n 8.Range \n 9. Random Number \t")) if choice_m=='1': if choice_m=='1': choice_m=(input("\n Do you want to generate \n 1.Address Line 1 \n 2.Address Line 2 \n 3.Address Line 3 \n 4.City \n 5.Postcode \n 6.Full UK address \n 7.Full Address")) if choice_m=='1': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Address Line 1 you want to generate \t")) print("Your process is started at "+time.ctime()) building_suffix=['Tower','Building','Hall',' '] for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.building_number()+","+fake.city()+" "+fake.random_element(building_suffix)) textfile_creation.close() finally: process_completed_time() elif choice_m=='2': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Address Line 2 you want to generate \t")) print("Your process is started at "+time.ctime()) street_suffix=[' Street',' '] for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.street_name()+fake.random_element(street_suffix)) textfile_creation.close() finally: process_completed_time() elif choice_m=='3': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Address Line 3 you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.state()) textfile_creation.close() finally: process_completed_time() elif choice_m=='4': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of City you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.city()) textfile_creation.close() finally: process_completed_time() elif choice_m=='5': try: textfile_creation=open(file_txt,"w") print("\n ETA for 1Lakh Data Generation is 4 Seconds") userdefined_count=int(input("Enter the Number of Post code you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.random_uppercase_letter()+fake.random_uppercase_letter()+str (fake.random_number(digits=3,fix_len=True))+' '+str (fake.random_number(digits=1,fix_len=True))+fake.random_uppercase_letter()+fake.random_uppercase_letter()) textfile_creation.close() finally: process_completed_time() elif choice_m=='6': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of address you want to generate \t")) print("Your process is started at "+time.ctime()) postalcode_list=['SY3','G41','G51','G31','G21','B44','SW1A','EC2M','N1','EC1A','EC4Y','EH12','EC2N','B70','B33','AB10','WC1A','B23','B65','B34','SW15','AB41','E8','AB21','E20','B71','B20','B68','B32','N14','N6','B42','AB56','AB25','E7','AB43','B46','B31','B69','B43','B62','B94','B66','B35','B79','W2','AB45','AB38','AB55','PO4 9BY','NE9 6HX','EX34 8LH','SM4 5RF','SE4 2BH','GL51 3ND','PR1 8JB','TW11 9BQ','GL7 2DG','TS15 9XE','PO21 3AE','SM1 4PL','GL53 9EQ','L21 2PA','GU28 0DS','WS14 0QH','YO31 1HZ','NN14 6EP','SY6 6DU','TN7 4AE','SW1A 1AA','SY3 7FA','BN1 2NW','CF24 3DG','BA1 2FJ','W1T 1JY','EH10 4BF','B3 2EW','SW1A 1BA','WIS 2HX','SWIA OAA','SW1E 5DU','SE1 2AA'] building_suffix=['Tower','Building','Hall',' '] for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.building_number()+","+fake.city()+" "+fake.random_element(building_suffix)+","+fake.street_name()+" Street"+", London"+", "+fake.random_element(postalcode_list)) textfile_creation.close() finally: process_completed_time() elif choice_m=='7': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of address you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.address()) textfile_creation.close() finally: process_completed_time() elif choice_m=='2': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Phone numbers you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print("0"+str(fake.random_number(digits=3,fix_len=True))+str(fake.random_number(digits=3,fix_len=True))+str(fake.random_number(digits=4,fix_len=True))) textfile_creation.close() finally: process_completed_time() elif choice_m=='3': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Company names you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.company()) textfile_creation.close() finally: process_completed_time() elif choice_m=='4': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Credit Numbers you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print((fake.credit_card_number()+fake.credit_card_number())[0:16]) textfile_creation.close() finally: process_completed_time() elif choice_m=='5': choice_m=(input("What do you want to generate, Reply with your choice(Number) \n 1.Username+Company E-Mail ID \n 2.Username+Personal E-Mail ID \n 3.E-mail ID Domains Alone \n 4.Custom Email Domain (Recommended for Large Data Creation)\n")) if choice_m=='1': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Username+Company E-Mail ID you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.company_email()) textfile_creation.close() finally: process_completed_time() elif choice_m=='2': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Username+Personal E-Mail ID you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.free_email()) textfile_creation.close() finally: process_completed_time() elif choice_m=='3': try: f=open(file_txt,"w") userdefined_count=int(input("Enter the Number of E-mail ID Domains you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=f print('@'+fake.domain_name()) f.close() finally: process_completed_time() elif choice_m=='4': try: f=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Customised E-mail ID you want to generate \t")) random_len=int(input("Enter how many digits of Random Number you need after the name \n Eg: If you enter '2' \n Output:[email protected] \t")) custom_domain=input("Enter custom domain with @(symbol) \n Eg: @yahoo.com \n Output:[email protected] \t") print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=f print(fake.first_name()+fake.last_name()+str(fake.random_number(digits=random_len,fix_len=True))+custom_domain) f.close() finally: process_completed_time() elif choice_m=='6': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Job Titles you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(fake.job()) textfile_creation.close() finally: process_completed_time() elif choice_m=='7': choice=input("Do you need splitup in files?? \n Eg: (if Yes) then your output will be in this format \nFirstName.txt, MiddleName.txt, LastName.txt, Title \n Reply with Y or N \t") if(choice=='y' or choice=='Y'): wordsplitcount() else: wordsinglecount() elif choice_m=='8': r1=int(input("Enter the start value \t")) r2=int(input("Enter the end value \t")) r3=r2-r1 print("Total count =", r3) choice=input("Do you want to include any number at the starting, reply with Y/N \t") if choice=='Y'or choice=='y': try: textfile_creation=open(file_txt,"w") front=input("Enter the number you want to insert in the front \t") for a in range(r1,r2): sys.stdout=textfile_creation print(front,a,sep="") textfile_creation.close() finally: process_completed_time() if choice=='N'or choice=='n': try: textfile_creation=open(file_txt,"w") for a in range(r1,r2): sys.stdout=textfile_creation print(a,end="\n") textfile_creation.close() finally: process_completed_time() elif choice_m=='9': try: textfile_creation=open(file_txt,"w") userdefined_count=int(input("Enter the Number of Random numbers you want to generate \t")) strnlngth_count=int(input("Enter the String length you want to generate \t")) print("Your process is started at "+time.ctime()) for _ in range(userdefined_count): sys.stdout=textfile_creation print(str(fake.random_number(digits=strnlngth_count,fix_len=True))) textfile_creation.close() finally: process_completed_time() else: print("Sorry you haven't selected any options:( \nSo going back <<") main() main()
import sqlite3 creation_table_str = """ CREATE TABLE IF NOT EXISTS TEMPERATURE ( id INTEGER PRIMARY KEY AUTOINCREMENT, sensor_id TEXT, temperature REAL, datetime TEXT, location TEXT ); """ check_if_table = """ SELECT count(name) FROM sqlite_master WHERE type='table' AND name=?; """ insertion_sample_data = """ INSERT INTO TEMPERATURE VALUES (null, ?, ?, ?, ?); """ if __name__ == "__main__": conn = sqlite3.connect('database_sql.db') cur = conn.cursor() cur.execute(check_if_table, ("TEMPERATURE",)) if cur.fetchone()[0] == 1: print('TEMPERATURE table already exists.') else: cur.execute(creation_table_str) conn.commit() print("TEMPERATURE table created successfully.") data_samples = [ ('t1', 32.4, '2019-10-01 08:18:00', '1st Floor, 4th Engineering Building, KoreaTech'), ('t2', 34.9, '2019-10-01 08:20:00', '3st Floor, 2th Engineering Building, KoreaTech') ] cur.executemany(insertion_sample_data, data_samples) conn.commit() conn.close()
import unittest from errors import InvalidInvoiceError, MaximumNumberOfInvoicesReached from invoice import Invoice from invoice_stats import InvoiceStats class TestInvoiceStats(unittest.TestCase): def test_add_invoice_ok(self): """ It should add an invoice to the `InvoiceStats` storage. """ valid_invoice = Invoice(10_000, 0) invoice_stats = InvoiceStats() invoice_stats.add_invoice(valid_invoice) self.assertListEqual(invoice_stats._invoices, [valid_invoice]) def test_add_invoice_float_raise_invalid_invoice_error(self): """ Invoice's dollars amount is not an integer. It should raise a `InvalidInvoiceError` error. """ float_invoice = Invoice(1.1, 0) invoice_stats = InvoiceStats() with self.assertRaises(InvalidInvoiceError) as context: invoice_stats.add_invoice(float_invoice) self.assertEqual(context.exception.code, 1) def test_add_invoice_negative_raise_invalid_invoice_error(self): """ Invoice's dollars amount is negative. It should raise a `InvalidInvoiceError` error. """ negative_invoice = Invoice(-1, 0) invoice_stats = InvoiceStats() with self.assertRaises(InvalidInvoiceError) as context: invoice_stats.add_invoice(negative_invoice) self.assertEqual(context.exception.code, 2) def test_add_invoice_too_large_raise_invalid_invoice_error(self): """ Invoice's amount is greater than maximum allowed value. It should raise a `InvalidInvoiceError` error. """ too_large_invoice = Invoice(200_000_000, 1) invoice_stats = InvoiceStats() with self.assertRaises(InvalidInvoiceError) as context: invoice_stats.add_invoice(too_large_invoice) self.assertEqual(context.exception.code, 3) def test_add_invoice_raise_maximum_number_of_invoices_reached(self): """ We shrink the `_MAX_INVOICES` value to 0 It should raise a `MaximumNumberOfInvoicesReached` error. """ invoice = Invoice(10_000, 0) invoice_stats = InvoiceStats() invoice_stats._MAX_INVOICES = 0 with self.assertRaises(MaximumNumberOfInvoicesReached) as context: invoice_stats.add_invoice(invoice) self.assertEqual(context.exception.code, 4) def test_add_invoices_ok(self): """ It should add each invoice to the `InvoiceStats` storage. """ invoices = [ Invoice(1000, 1), Invoice(10_000, 2), Invoice(100_000, 10) ] invoice_stats = InvoiceStats() invoice_stats.add_invoices(invoices) self.assertListEqual(invoice_stats._invoices, invoices) def test_get_median_rounded_down(self): """ It should compute the median of the added invoices. Half a cent should round down. Here, the raw median is 5.115, so `get_median` should return 5.11. """ invoices = [ Invoice(1, 23), Invoice(3, 45), Invoice(6, 78), Invoice(7, 89) ] invoice_stats = InvoiceStats() invoice_stats.add_invoices(invoices) median = invoice_stats.get_median() self.assertEqual(median, 5.11) def test_get_mean_rounded_down(self): """ It should compute the mean of the added invoices. Half a cent should round down. Here, the raw mean is 4.835, so `get_mean` should return 4.83. """ invoices = invoices = [ Invoice(1, 23), Invoice(3, 45), Invoice(6, 78), Invoice(7, 88) ] invoice_stats = InvoiceStats() invoice_stats.add_invoices(invoices) mean = invoice_stats.get_mean() self.assertEqual(mean, 4.83) def test_get_median_not_rounded(self): """ It should compute the median of the added invoices. Here, the raw median is 4.56, so `get_median` should return 4.56. """ invoices = [ Invoice(1, 23), Invoice(3, 45), Invoice(4, 56), Invoice(6, 78), Invoice(7, 89) ] invoice_stats = InvoiceStats() invoice_stats.add_invoices(invoices) median = invoice_stats.get_median() self.assertEqual(median, 4.56) def test_get_mean_rounded_up(self): """ It should compute the mean of the added invoices. Here, the raw mean is 4.8375, so `get_mean` should return 4.84. """ invoices = [ Invoice(1, 23), Invoice(3, 45), Invoice(6, 78), Invoice(7, 89) ] invoice_stats = InvoiceStats() invoice_stats.add_invoices(invoices) mean = invoice_stats.get_mean() self.assertEqual(mean, 4.84)
import random import os import json def read_settings(filename): if os.path.isfile(filename): file = open(filename, 'r') line = file.readline() file.close() if line: return line.split(';') return False def save_settings(filename, user): file = open(filename, 'w') file.write(";".join(user)) file.close() def settings(): """This function ask user about number of numbers that should be picked and max value.""" nick = input("Provide nick: ") filename = nick + '.ini' user = read_settings(filename) confirmation = None if user: print(f'Your settings:\nNumbers: {user[1]}\n Max: {user[2]}\n Tries: {user[3]}') confirmation = input('Do you want to change (y/n)? ') if not user or confirmation.lower() == 'y': while True: try: numbers_size = int(input('Define number of random numbers: ')) range_max = int(input('Define max value: ')) if numbers_size > range_max: raise ValueError try_number = int(input("How many tries: ")) break except ValueError: print('Invalida data!') continue user = [nick, str(numbers_size), str(range_max), str(try_number)] save_settings(filename, user) return user[0:1] + [int(x) for x in user[1:4]] def get_randoms(size, range_max): """This function generate list of unique random numbers""" numbers = [] i = 0 while i < size: number = random.randint(1, range_max) if numbers.count(number) == 0: numbers.append(number) i = i + 1 return numbers def get_answers (size, range_max): """Function gets user's answers""" print(f'Define {size} from {range_max} numbers') answers = set() while len(answers) < size: try: answer = int(input(f'Define {len(answers) + 1}. number')) except ValueError: print('Invalid data!') continue if 0 < answer <= range_max and answers not in answers: answers.add(answer) return answers def results (randoms, answers): hits = set(randoms) & answers if hits: print(f'\nYou\'ve hit {len(hits)} numbers:', ", ".join(map(str, hits))) else: print('You\'ve missed') return len(hits) def read_json(filename): data = [] if os.path.isfile(filename): with open(filename, 'r') as file: data = json.load(file) return data def write_json(filename, data): with open(filename, 'w') as file: json.dump(data, file)
import numpy as np import random import matplotlib.pyplot as plt n = int(input('Motion number: ')) x, y = 0, 0 history = [(x, y)] for i in range(0, n): rad = float(random.randint(0, 360)) * np.pi / 180 x = x + np.cos(rad) y = y + np.sin(rad) history.append((x, y)) print(history) xs = list(map(lambda point: point[0], history)) ys = list(map(lambda point: point[1], history)) plt.plot(xs, ys, 'o:', color='green', linewidth=2, alpha=0.5, label='history') plt.plot([xs[0], xs[-1]], [ys[0], ys[-1]], color='blue', linewidth=2, alpha=1, label='diff') plt.legend(loc="upper left") plt.xlabel('X') plt.ylabel('Y') plt.title('Brownian motion') plt.grid(True) plt.show()
""" Sort a list in ascending order Return a new sorted list - 3 steps: # Divide: Find midpoint of the list and divide into sublists # Conquer: Recursively sort the sublists created in previous step # Combine: Merge the sorted sublists created in previous step Takes O(n log n) time """ # example 1 (Imran Ahmed) def mergeSort(list): if len(list) > 1: mid = len(list) // 2 # splits list into half left = list[:mid] right = list[mid:] # recursively reprats until length of each list is 1 mergeSort(left) mergeSort(right) a = 0 b = 0 c = 0 while a < len(left) and b < len(right): if left[a] < right[b]: list[c] = left[a] a = a + 1 else: list[c] = right[b] b = b + 1 c = c + 1 while a < len(left): list[c] = left[a] a = a + 1 c = c + 1 while b < len(right): list[c] = right[b] b = b + 1 c = c + 1 return list lst = mergeSort([45, 21, 89, 35, 12, 90, 123, 345, 25]) print(lst)
# example 1 ''' A / \ B C / \ \ D E ---> F ''' graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [], } visited = set() # sets don't allow repeated elements def dfs(visited, graph, node): if node not in visited: print(node) visited.add(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) # recursion return visited l = dfs(visited, graph, 'A') print(l) # Time complexity: O(V+E) # Space complexit: O(V) # example 2 ''' A / \ B C / \ / \ D E F G / \ / \ / \ H I J K L M ''' default_dict = { 'A': ['B', 'C'], 'B': ['A','D', 'E'], 'C': ['A','F', 'G'], 'D': ['B', 'H', 'I'], 'E': ['B', 'J', 'K'], 'F': ['C', 'L', 'M'], 'G': ['C'], 'H': ['D'], 'I': ['D'], 'J': ['E'], 'K': ['E'], 'L': ['F'], 'M': ['F'], } # def dfs(adj)
class Edge(object): def __init__(self, source, target, data = None): self._source, self._target, self.data = source, target, data def __repr__(self): return "Edge<%s <-> %s>" % (repr(self.source), repr(self.target)) @property def source(self): return self._source @property def target(self): return self._target class Graph(object): def __init__(self, multi = False, directed = False, key_func = None, neighbors_func = None): self.nodes = {} self._is_directed = directed self._is_multi = multi self.neighbors_func = neighbors_func self.key_func = key_func or (lambda x: x) @property def is_directed(self): return self._is_directed @property def is_multi(self): return self._is_multi def get_edge(self, source, target): return self.nodes.get(self.key_func(source), {}).get(self.key_func(target), None) def add_nodes(self, *nodes): return [self.add_node(node) for node in nodes] def add_node(self, node): """ Adds or update a node (any hashable) in the graph. """ if node not in self.nodes: self.nodes[self.key_func(node)] = {} return self.nodes[self.key_func(node)] def neighbors(self, node): """Return the neighbors of a node.""" if self.neighbors_func: return self.neighbors_func(node) else: return self.nodes.get(self.key_func(node), {}) def iter_neighbors(self, node, reverse = False): """ Return an iterator of neighbors (along with any edge data) for a particular node. Override this method for custom node storage and inspection strategies. """ neighbors = self.neighbors(node) if type(neighbors) is dict: if reverse: return reversed(self.neighbors(node).items()) else: return self.neighbors(node).iteritems() else: if reverse: return reversed(neighbors) else: return neighbors def add_raw_edge(self, edge): self.add_nodes(edge.source,edge.target) source,target = edge.source,edge.target source_key = self.key_func(source) target_key = self.key_func(target) self.nodes[source_key][target_key] = edge if not self.is_directed and source_key != target_key: self.nodes[target_key][source_key] = edge return edge def add_edge(self, source, target): return self.add_raw_edge(Edge(source, target)) def add_edges(self, *edges): return [self.add_edge(*e) for e in edges]
def is_matched(e): l = len(e); if l%2 == 1: return False #l = l/2 #e = list(e) a = [] b = ['{', '(', '['] val = ['}', ')', ']'] for i in range(l): #print 'hi' #print a, e[i] if e[i] in b: a.append(e[i]) elif e[i] in val: #print a ind = val.index(e[i]) #print a[-1], e[ind] if a and a[-1] == b[ind]: a.pop() #print 'pop a',a else: #print '2nd exit' return False else: return False #print a if a: #print '3 exit', a return False else: return True t = int(raw_input().strip()) for a0 in xrange(t): expression = raw_input().strip() if is_matched(expression) == True: print "YES" else: print "NO" #print '='*50
# -*- coding: utf-8 -*- """ Created on Sun Apr 14 11:42:00 2019 @author: pacew """ # A bubble sort app import numpy as np import random def bubblesort(array): lenght = len(array) - 1 for i in range(lenght): for j in range(lenght): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array x = int(input("how long shout the array be? \n")) randnums = np.random.randint(1, 101, x) print("the array of numbers to sort is:") print(randnums) array = randnums print("sorted array by bubble sort method:") print(bubblesort(array))
#!/usr/bin/env python #codiing=utf-8 import random import time,threading ''' 线程从threading.Thread继承创建线程 ,重写__init__和run()方法 ''' class MyThread(threading.Thread): def __init__(self,name,urls): threading.Thread.__init__(self,name=name) self.urls =urls def run(self): print('Current %s is running....'%threading.current_thread().name) for url in self.urls: print('%s ----------->>>%s'%(threading.current_thread().name,url)) time.sleep(random.random()) print('%s ended....'%threading.current_thread().name) if __name__=='__main__': print('%s us runing....'%threading.current_thread().name) t1=MyThread('Thread_1',['url_'+str(i) for i in range(10)]) t2=MyThread('Thread_2',['url_'+str(i) for i in range(11,20)]) t1.start() t2.start() t1.join() t2.join() print('%s ended.'%threading.current_thread().name)
#! /usr/bin/env python """ Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) Example 1: [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]] Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. Example 2: [[0,0,0,0,0,0,0,0]] Given the above grid, return 0. Note: The length of each dimension in the given grid does not exceed 50. """ class Solution: # def maxAreaOfIsland(self, grid): # """ # :type grid: List[List[int]] # :rtype: int # """ # # seen = set() # def area(r, c): # if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) and (r, c) not in seen and grid[r][c]): # return 0 # seen.add((r, c)) # return (1 + area(r + 1, c) + area( r - 1, c) + area(r, c - 1) + area(r, c + 1)) # # return max(area(r, c) for r in range(len(grid)) for c in range(len(grid[0]))) def maxAreaOfIsland(self, grid): seen = set() maoi = 0 for r0, row in enumerate(grid): for c0, val in enumerate(row): if val and (r0, c0) not in seen: aoi = 0 stack = [(r0, c0)] seen.add((r0, c0)) while stack: r, c = stack.pop() aoi += 1 for nr, nc in ((r -1 , c), (r + 1, c), (r, c - 1), (r, c + 1)): if (0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] and (nr, nc) not in seen): stack.append((nr, nc)) seen.add((nr, nc)) maoi = max(maoi, aoi) return maoi if __name__ == "__main__": s = Solution() print(s.maxAreaOfIsland( [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]))
""" Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. Example 1: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun". Example 2: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["KFC", "Shogun", "Burger King"] Output: ["Shogun"] Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1). Note: The length of both lists will be in the range of [1, 1000]. The length of strings in both lists will be in the range of [1, 30]. The index is starting from 0 to the list length minus 1. No duplicates in both lists. """ class Solution: def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ commrest = set(list1) & set(list2) matchmap = {rest:i for i, rest in enumerate(list1) if rest in commrest} mindist = float("Inf") for i, rest in enumerate(list2): if rest in matchmap: matchmap[rest] = matchmap[rest] + i if matchmap[rest] < mindist: mindist = matchmap[rest] return [rest for rest in matchmap if matchmap[rest]==mindist] if __name__ == "__main__": s = Solution() print(s.findRestaurant(["Shogun","Tapioca Express","Burger King","KFC"], ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]))
""" Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. """ class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ psnums = sorted([i for i in nums if i >0]) if psnums == []: return 1 for i,v in enumerate(psnums): if v != i + 1: return i + 1 return psnums[-1]+1 if __name__ == "__main__": s = Solution() print(s.firstMissingPositive([1,2,0 ]))
""" Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2. """ class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minstack = [] def push(self, x): """ :type x: int :rtype: void """ self.stack.append(x) self.minstack.append(min(x, self.minstack[-1]) if self.minstack else x) def pop(self): """ :rtype: void """ self.stack.pop() self.minstack.pop() def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ return self.minstack[-1] if __name__ == "__main__": m = MinStack() m.push(-2) m.push(0) m.push(-3) print(m.getMin()) print(m.pop()) print(m.top()) print(m.getMin())
""" This file defines the class Device, which is basically the type of anything that attempts to connect to our network """ class Device: def __init__(self, macAddress, name): self.macAddress = macAddress self.name = name def __str__(self): return "<%s, %s>" % (self.macAddress, self.name) # Make it not print weird def __repr__(self): return "<%s, %s>" % (self.macAddress, self.name) # Also the printing thing
# ICS483 Group Project # Authors: Kekeli D Akouete, Vang Uni A # Implementing encryption in an application from tkinter import filedialog from tkinter import * from tkinter import messagebox import os from MyCipher import MyCipher # Callbacks to entry fields def key_callback(event): ivEntry.focus_set() def file_callback(event): keyEntry.focus_set() def iv_callback(event): outputText.focus_set() # Clear the input fields def clear_callback(): filename.set("") keyString.set("") ivTf.set("") outputResult.set("") fileEntry.focus_set() # Save function to write to a file def saveAs(): # Save your work to a file fname = filedialog.asksaveasfilename() if fname != '': writefile(outputResult.get(), fname) # Save keys function def saveKey(): if keyString.get() != '' or ivTf.get() != '': # Save your keys to a file fname = filedialog.asksaveasfilename() if fname: # Saving your key and IV to a file of your choice keys = "Key={} \nIV={}".format(keyString.get(), ivTf.get()) writefile(keys, fname) # Display the help menu for instruction def showhelp(): # Instruction on how to use the application messagebox.showinfo(title="About", message=readfile("help.txt")) # Prompt to browse a file directory def openfile(): if keyString.get() != '' or ivTf.get() != '': answer = messagebox.askyesno("Save Work", "Do you want to save your work?") if answer: saveAs() else: # Clear the variables values filename.set("") keyString.set("") ivTf.set("") outputResult.set("") openfile() else: # open the dialog widget myFile = filedialog.askopenfilename() if myFile: filename.set(myFile) keyEntry.focus_set() else: fileEntry.focus_set() # Definition of the read method which takes a file def readfile(file): if os.path.exists(file): with open(file, "r") as fd: file_content = fd.read() return file_content else: return "File not found" # Definition of the write method def writefile(context, file): if type(context) == bytes: context.decode() with open(file, "w") as fd: fd.write(context) fd.seek(0) # Action to perform when user click generate key def generate_key_callback(): mykey = cipher.keygen() keyString.set(mykey) # Action to perform when user click encrypt button def encrypt_callback(): if filename.get() == '': # Request the input file messagebox.showinfo(title="Error", message="Please Select a Valid File Path!") fileEntry.focus_set() elif keyString.get() == "" or len(keyString.get()) < 16: # Validate the key and key length messagebox.showinfo(title="Error", message="Please Enter a valid Key!") keyEntry.focus_set() elif len(readfile(filename.get())) == 14: # Validate the input file path messagebox.showinfo(title="Error", message="File Not Found!") fileEntry.focus_set() else: # Encryption process plaintext = readfile(filename.get()) c = cipher.encryptAES_128(plaintext, keyString.get()) ivTf.set(c[0]) outputResult.set(c[1]) # Action to perform when user click decrypt button def decrypt_callback(): if filename.get() == '': messagebox.showinfo(title="Error", message="Please Select an Input first!") fileEntry.focus_set() elif outputResult.get() != '': plnText = cipher.decryptAES_128(keyString.get(), ivTf.get(), outputResult.get()) if plnText != "Wrong key or IV provided": outputResult.set(plnText) else: messagebox.showinfo(title="Error", message=plnText) keyEntry.focus_set() else: plnText = cipher.decryptAES_128(keyString.get(), ivTf.get(), readfile(filename.get())) if plnText == "Wrong key or IV provided": messagebox.showinfo(title="Error", message=plnText) keyEntry.focus_set() else: outputResult.set(plnText) # Custom window class definition class Window(Frame): def __init__(self, master=None): super().__init__() self.master = master menu = Menu(self.master) self.master.config(menu=menu) # Menu bar items fileMenu = Menu(menu) menu.add_cascade(label="File", menu=fileMenu) fileMenu.add_command(label="Open", command=openfile) fileMenu.add_command(label="Save As", command=saveAs) fileMenu.add_command(label="Save Keys", command=saveKey) fileMenu.add_command(label="Exit", command=quitApp) actionMenu = Menu(menu) menu.add_cascade(label="Action", menu=actionMenu) actionMenu.add_command(label="Decrypt", command=decrypt_callback) actionMenu.add_command(label="Encrypt", command=encrypt_callback) actionMenu.add_command(label="Generate key", command=generate_key_callback) helpMenu = Menu(menu) menu.add_cascade(label="Help", menu=helpMenu) helpMenu.add_command(label="About", command=showhelp) # Exit method definition def quitApp(): if messagebox.askokcancel("Confirm Exit", "Do you really wish to quit?"): root.destroy() root = Tk() cipher = MyCipher() crypto_app = Window(root) crypto_app.master.title("Cryptographer1.0") root.geometry("650x350") crypto_app.master.maxsize(750, 530) crypto_app.master.protocol("WM_DELETE_WINDOW", quitApp) # File entry input widget definition frame1 = Frame() frame1.pack(fill=X) fileLabel = Label(frame1, text="Input File:", width=9) fileLabel.pack(side=LEFT, padx=5, pady=5) filename = StringVar() fileEntry = Entry(frame1, textvariable=filename) fileEntry.bind("<Return>", file_callback) fileEntry.pack(fill=X, padx=5, expand=True) # Key entry input widget definition frame2 = Frame() frame2.pack(fill=X) keyLabel = Label(frame2, text="Key:", width=9) keyLabel.pack(side=LEFT, padx=5, pady=5) keyString = StringVar() keyEntry = Entry(frame2, textvariable=keyString) keyEntry.bind("<Return>", key_callback) keyEntry.pack(fill=X, padx=5, expand=True) # IV entry input widget definition frame3 = Frame() frame3.pack(fill=X) ivLabel = Label(frame3, text="IV:", width=9) ivLabel.pack(side=LEFT, padx=5, pady=5) ivTf = StringVar() ivEntry = Entry(frame3, textvariable=ivTf) ivEntry.bind("<Return>", iv_callback) ivEntry.pack(fill=X, padx=5, expand=True) # Output widget definition frame4 = Frame() frame4.pack(fill=X) outputLabel = Label(frame4, text="Output:", width=9) outputLabel.pack(side=LEFT, padx=5, pady=5) outputResult = StringVar() outputText = Label(frame4, textvariable=outputResult) outputText.pack(fill=X, padx=5, pady=5, expand=True) # Buttons widget definition frame5 = Frame(relief=RAISED, borderwidth=0) frame5.pack(fill=BOTH, expand=True) clearButton = Button(frame5, text="Clear", command=clear_callback) clearButton.pack(side=RIGHT, padx=5) decryptButton = Button(frame5, text="Decrypt", command=decrypt_callback) decryptButton.pack(side=RIGHT, padx=5, pady=5) encryptButton = Button(frame5, text="Encrypt", command=encrypt_callback) encryptButton.pack(side=RIGHT, padx=5) # the application footer note status = Label(root, text="Cryptographer_1.0 \u00AE All rights reserved", justify=CENTER) status.pack(side=BOTTOM, padx=5, pady=5, anchor=S) crypto_app.mainloop() ######################### Test codes ############################## # print("Key: " + keyString.get() + "\n", "IV: " + ivTf.get()) # print("Content: " + readfile(filename.get())) # keyTf = bytearray() # print("Content: " + plnText) # keyTf.extend(mykey) # keyString.set(mykey.hex().upper()) # print("IV: " + c[0] + "\n", "Cipher Text: " + c[1])
a = input() if (int(a[0])+int(a[1])+int(a[2])) == (int(a[3])+int(a[4])+int(a[5])): print("молодец") else: print("НЕмолодец")
# Microsoft # Print the nodes in a binary tree level-wise. For example, the following should # print 1, 2, 3, 4, 5. # 1 # / \ # 2 3 # / \ # 4 5 # Tree Traversal # Pseudocode: # create class Node function class Node: def__init__(self, data): self.left = None self.right = None self.data = data def in_order(root): if root: in_order(root.left) print(root.val) in_order(root.right) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. EXCELLENT!\n")
import time import sys def Phone(phone_option): try: if phone_option == 1: s = ''' 1. Do you answer the phone in hopes of confronting the root cause of everything happening? 2. Do you send the caller to voicemail and try to reach "911"?''' for character in s: sys.stdout.write(character) sys.stdout.flush() time.sleep(.1) phone_choice = int(input('''\n--> ''')) if phone_choice == 1: print() print() time.sleep(2) print('You press answer on the small led screen, raise the phone to your ear,') time.sleep(2) print("and say hello. You listen intently waiting for something on the other") time.sleep(2) print("side to say something.... ") time.sleep(2) print("You hear nothing on the other end and decide to hang up and try to make a") time.sleep(2) print('call.... And everything goes black... time to restart the game... you lose...') time.sleep(2) print() print() return True elif phone_choice == 2: print() print() time.sleep(2) print("You swipe the caller to voicemail. The room starts to vibrate and then stops.") time.sleep(2) print('You focus back on your phone and dial "911". An operator answers, Yet as you') time.sleep(2) print('try to reply, no sound comes from your mouth.... And everything goes black...') time.sleep(2) print('time to restart the game... you lose...') time.sleep(2) print() print() return True except ValueError: print(''' I can see why you're stuck here... I don't even know you... but this is pathetic..... Press 1 or 2 chair warmer!!! ''') print() print()
# A string is considered to be valid if all characters of the string appear the same number of times. # It is also valid if he can remove just 1 character at any 1 index in the string, and the remaining characters # will occur the same number of times. Given a string , determine if it is valid. # If so, return YES, otherwise return NO. def is_valid(s): data_by_freq = dict() freq_of_data = dict() for c in s: freq_of_data[c] = freq_of_data.get(c, 0) + 1 for c, freq in freq_of_data.items(): if freq not in data_by_freq: data_by_freq[freq] = [c] else: data_by_freq[freq].append(c) print(data_by_freq) if len(data_by_freq) == 1: return 'YES' elif len(data_by_freq) == 2: len_1 = len(list(data_by_freq.values())[0]) len_2 = len(list(data_by_freq.values())[1]) freq_1 = list(data_by_freq.keys())[0] freq_2 = list(data_by_freq.keys())[1] if len_1 == 1 and (freq_1 - freq_2 == 1 or freq_1 == 1): return 'YES' elif len_2 == 1 and (freq_2 - freq_1 == 1 or freq_2 == 1): return 'YES' else: return 'NO' else: return 'NO' if __name__ == '__main__': # s = 'ibfdgaeadiaefgbhbdghhhbgdfgeiccbiehhfcggchgghadhdhagfbahhddgghbdehidbibaeaagaeeigffcebfbaieggabcfbiiedcabfihchdfabifahcbhagccbdfifhghcadfiadeeaheeddddiecaicbgigccageicehfdhdgafaddhffadigfhhcaedcedecafeacbdacgfgfeeibgaiffdehigebhhehiaahfidibccdcdagifgaihacihadecgifihbebffebdfbchbgigeccahgihbcbcaggebaaafgfedbfgagfediddghdgbgehhhifhgcedechahidcbchebheihaadbbbiaiccededchdagfhccfdefigfibifabeiaccghcegfbcghaefifbachebaacbhbfgfddeceababbacgffbagidebeadfihaefefegbghgddbbgddeehgfbhafbccidebgehifafgbghafacgfdccgifdcbbbidfifhdaibgigebigaedeaaiadegfefbhacgddhchgcbgcaeaieiegiffchbgbebgbehbbfcebciiagacaiechdigbgbghefcahgbhfibhedaeeiffebdiabcifgccdefabccdghehfibfiifdaicfedagahhdcbhbicdgibgcedieihcichadgchgbdcdagaihebbabhibcihicadgadfcihdheefbhffiageddhgahaidfdhhdbgciiaciegchiiebfbcbhaeagccfhbfhaddagnfieihghfbaggiffbbfbecgaiiidccdceadbbdfgigibgcgchafccdchgifdeieicbaididhfcfdedbhaadedfageigfdehgcdaecaebebebfcieaecfagfdieaefdiedbcadchabhebgehiidfcgahcdhcdhgchhiiheffiifeegcfdgbdeffhgeghdfhbfbifgidcafbfcd' # s = 'aaaabbcc' # s = 'abcdefghhgfedecba' s = 'aaaaabc' result = is_valid(s) print(result + '\n')
n = int(input()) cnt = 0 for i in range (n): cnt = cnt + int(int(input()) == 0) print(cnt)
import random rucksack = ['Water flask', 'Cheese', 'Gold coins', 'Handkercheif', 'Tinderbox', 'Scrolls', 'Dagger','Rope','Nuts','Pipe','Tobacco','Wine skin', 'Herbs','Axe'] ##function to sort inventory, printout and print number of items def rucksackupdate(): rucksack.sort() print(rucksack) print (str(len(rucksack)), "items in rucksack") ##function to remove item from list by a random indexnumber def thief(inventory): itemremoved = inventory.pop(random.randint(0,len(inventory)-1)) print ("A thief has stolen your", itemremoved) rucksackupdate() treasurechest = ['Gems', 'Necklace'] rucksack = rucksack + treasurechest rucksackupdate() ## 5 items stolen thief(rucksack) thief(rucksack) thief(rucksack) thief(rucksack) thief(rucksack) rucksackupdate()
##I wanted to simplify entering it so i print a menu and get them choose coorrsponing number print ("Choose your type of Pokemon") print ("For Fire press 1") print ("For Water press 2") print ("For Grass press 3") print ("For Electric press 4") type = int(input("Make your selection:")) letter = str(input("Whats the first letter of your Pokemons name:")) ##to make it easier for variations in case I'm turning all string to capital letter = letter.capitalize() if type == 1 and letter == "C": print("You chose Fire, your pokemon is called Charmander") elif type == 1 and letter == "M": print("You chose Fire, your pokemon is called Moltres") elif type == 2 and letter == "S": print("You chose Water, your pokemon is called Squirtle") elif type == 2 and letter == "T": print("You chose Water, your pokemon is called Tentacool") elif type == 3 and letter == "B": print("You chose Grass, your pokemon is called Bulbassaur") elif type == 3 and letter == "O": print("You chose Grass, your pokemon is called Oddish") elif type == 4 and letter == "P": print("You chose Electric, your pokemon is called Pikachu ") elif type == 4 and letter == "V": print("You chose Electric, your pokemon is called Voltorb") else: print("Sorry I can't guess")
##asking questions to get data creditScore = int(input("Please enter creditscore 1 -10:")) addressTerm = int(input("How many months at current address")) income = int(input("What is the income level (£)")) loanRequest = int(input("Borrowing amount requested (£)")) ##this is a variable that would go to true if loan approved Loan = False ##scenario 0 outright decline, realised after no need for this, ##if creditScore == 0 and addressTerm == 0: ## Loan = False ##scenario 1 on worksheet if loanRequest > income and loanRequest < (2 * income): if addressTerm >= 60 and creditScore >= 5: Loan = True ##scenario 2 on worksheet elif loanRequest < income: if addressTerm > 12 and addressTerm < 60: if creditScore >= 7 and creditScore <= 10: Loan = True ##scenario 3 elif addressTerm >= 60: if creditScore >= 2 and creditScore <= 5: Loan = True ##scenario 3 elif loanrequest < 0.2 * income: if creditScore == 1 and addressTerm > 12: Loan = True ##this part will print the data out print("You have a credit score of: " + str(creditScore)) print("Your time at the current address is " + str(addressTerm) + " months") print("Your income is £" +str(income)) print("You have requested a loan of £" +str(loanRequest)) ## this bit will look at id the loan approved variable is true orfalse and print message if Loan == True: print ("Your loan has been approved") else: print("Your loan application has been declined")
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- # 2018-05-23 # Personal Tax Calculator import sys # 导入系统模块 print(sys.argv) # 打印命令参数 # 异常处理:用户输入的参数必须为单个、正确的薪水!参数的数量不正确、输入小于或等于0、无法转换成整数,都需要打印参数错误提示。 try: len(sys.argv) == 2 # 参数的个数必须为2(包括参数名词在内) salary = int(sys.argv[1]) # 薪水等于传入的第一个参数 assert salary > 0 # 输入薪水必须大于0 except ValueError: print('数据类型错误') exit() except AssertionError: print('输入薪水必须>0') exit() # 定义所需的变量 tax_point = 3500 # 个税起征点 tax_salary = int(salary) - tax_point # 应纳税所得额公式,社会保险暂不考虑 # 按照公式计算个税 if tax_salary <= 0: print(format(0, ".2f")) elif 0 <= tax_salary <= 1500: tax = format((tax_salary * 0.03 - 0), ".2f") print(tax) elif 1500 < tax_salary <= 4500: tax = format((tax_salary * 0.10 - 105), ".2f") print(tax) elif 4500 < tax_salary <= 9000: tax = format((tax_salary * 0.20 - 555), ".2f") print(tax) elif 9000 < tax_salary <= 35000: tax = format((tax_salary * 0.25 - 1005), ".2f") print(tax) elif 35000 < tax_salary <= 55000: tax = format((tax_salary * 0.30 - 2755), ".2f") print(tax) elif 55000 < tax_salary <= 80000: tax = format((tax_salary * 0.35 - 5505), ".2f") print(tax) elif tax_salary > 80000: tax = format((tax_salary * 0.45 - 13505), ".2f") print(tax)
km = int(input('Qual a velocidade de seu carro? em km/h: ')) if km >= 80: print('Você ultrapassou a velocidade de 80 km/h e foi multado.') acd = km - 80 mult = (acd * 7) print('O valor da multa é R$ {} reais.'.format(mult))
cont = soma = maior = menor = 0 resp = 'S' while resp in 'Ss': num = int(input('Digite um valor: ')) soma += num cont += 1 if cont == 1: maior = menor = num else: if num > maior: maior = num if num < menor: menor = num resp = str(input('Quer continuar [S/N]: ')).upper() media = soma / cont print('a media dos {} valores digitados é {}'.format(cont, media)) print('O maior numero é {} e o menor numero é {}.'.format(maior, menor))
total = 0 num = int(input('Digite um numero: ')) for c in range(1, num +1): if num % c == 0:# vai ser testado se é divisivel de 1 até a num digitado. total += 1 #soma a quantidade de vezes que foi dividido com resposta 0 if total == 2: # apenas quando dividido 2 vezes é considerado um numero primo print('É um número primo') else: print('Não é um número primo!')
print('¨*¨' * 10) print(f' BANCO NOEMI ') print('¨*¨' * 10) while True: valor = int(input('\nDigite o valor que quer sacar: ')) notas50 = valor // 50 rest = valor - notas50 * 50 notas20 = rest // 20 rest2 = rest - notas20 * 20 notas10 = rest2 // 10 rest3 = rest2 - notas10 * 10 notas1 = rest3 // 1 print(f'Total {notas50} cédulas de R$ 50,00 reais') print(f'Total {notas20} cédulas de R$ 20,00 reais') print(f'Total {notas10} cédulas de R$ 10,00 reais') print(f'Total {notas1} cédulas de R$ 1,00 real') print('¨*¨' * 10) opcao = input('\nDeseja fazer um novo saque? [S/N]: ') if opcao in 'Nn': break print('Volte sempre!')
#Condição if e else n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) m = (n1 +n2)/2 print('Sua média final é {:.1f}.'.format(m)) if m >= 6: print('Você foi aprovado, parabéns!') else: print('Você foi reprovado, estude para a recuperação.') #Maneira simplificada print('Parabens' if m >= 6 else'Reprovado')
print('Você sabe quais são so números pares entre 1 e 50 ?Veja abaixo: ') for c in range(1+1, 50, 2): print(c, end=' ') print('Esses são os números pares.')
#Reajuste salarial sal = float(input('Digite o seu sálario: R$ ')) new = sal * 1.15 print('O seu salário de R${:.2f} reais, com o reajuste de 15% passa a ser de R$ {:.2f} reais.'.format(sal, new))
#Calculo da hipotesuna from math import hypot cat_op = float(input('Digite o comprimento do cateto oposto: ')) cat_adj = float(input('Digite o comprimento do cateto adjacente: ')) hip = hypot(cat_op, cat_adj) print('A sua hipotenusa é de {:.2f}'.format(hip)) #Forma mais simples de fazer sem importar bibliotecas co = float(input('Digite o comprimento do cateto oposto: ')) ca = float(input('Digite o comprimento do cateto adjacente: ')) hy = (co ** 2 + ca ** 2) ** (1/2) print('A sua hipotenusa é de {:.2f}'.format(hy))
soma = 0 idademaior = 0 nomemaisve = '' qntmulheres = 0 for c in range(1, 4 +1 ): nome = str(input('Digite o nome da {}º pessoa: '.format(c))).strip() idade = int(input('Digite a idade da {}º pessoa: '.format(c))) sexo = str(input('Qual o sexo biológico da {}º pessoa [M/F]: '.format(c))).strip().upper() soma += idade if c == 1 and sexo in 'M': idademaior = idade nomemaisve = nome if sexo in 'M' and idade > idademaior: idademaior = idade nomemaisve = nome if sexo in 'F' and idade < 20: qntmulheres += 1 media = soma / 4 print('A média da idade das pessoas é {} anos'.format(media)) print('A idade do homem mais velho é {} e se chama {}.'.format(idademaior, nomemaisve)) print('No grupo existem {} mulher(es) com menos de 20 anos.'.format(qntmulheres))
#Analisador de textos nome = str(input('Escreva seu nome completo: ')).strip() print(nome.upper()) print(nome.lower()) nome = (nome.split()) Nc = (''.join(nome)) print('O seu nome completo tem {} letras.'.format(len(Nc))) #print('Seu nome completo tem {} letras'.format(len(nome) - nome.count(' '))) subtraindo os espaços contidos no nome print('E o seu primeiro nome tem {} letras.'.format(len(nome[0])))
# Devolução de numero inteiro por biblioteca ou de forma simples from math import floor num = float(input('Digite um numero: ')) inteiro = floor(num) print('O número {} tem a parte inteira {}. '. format(num, inteiro)) #Outro metodo import math num = float(input('Digite um numero: ')) print('O número {} tem a parte inteira {}. '. format(num,math.trunc(num))) # trunc corta a parte real, deixando só a inteira #Outra formar mais simples num = float(input('Digite um numero: ')) print('O número {} tem a parte inteira {}. '. format(num,int(num)))
#!/bin/python3 """ list: 是python 内置的一种数据类型。list是一种有序集合,可以随时添加或删除其中元素。 """ # 定义一个空list list1 = [] print(list1) classmates = ['Michael', 'Bob', 'Jim'] print(classmates) # 获取list元素个数 print(len(classmates)) print("classmates[0] is %s" % classmates[0]) print("classmates[1] is %s" % classmates[1]) print("classmates[2] is %s" % classmates[2]) # print("classmates[3] is %s" % classmates[3]) print("classmates[-1] is %s" % classmates[-1]) print("classmates[-2] is %s" % classmates[-2]) print("classmates[-3] is %s" % classmates[-3]) # print("classmates[-4] is %s" % classmates[-4]) # 追回 classmates.append("Adam") print("classmates.appen('Adam') is ", classmates) # 把元素插到指定位置 classmates.insert(2, "Rolly") print(classmates) # 删除list最后一个元素 lastEle = classmates.pop() print(classmates) print(lastEle) # 删除list指定元素 specialEle = classmates.pop(1) print(classmates) print(specialEle) # 替换list某个元素 classmates[0] = "JJ" print(classmates) # list里的元素可以是不同的数据类型,当然也可以是list l1 = ["Rolly", 23, True, [100, 98, 99]] print(l1)
#!/bin/python3 """ 列表生成式:List Comprehensions """ import os # 求 1-10 的平方 # 循环迭代方式 L = [] for i in range(1, 11): L.append(i * i) print(L) # 列表生成式 [print(x * x, end=" ") for x in range(1, 11)] print() # 想获取平方数为偶数的结果 [print(x * x, end=" ") for x in range(1, 11) if x % 2 == 0] # 使用两层循环 [print(m + n ) for m in 'ABC' for n in 'ZXY'] # 使用列表生成式列出当前目录的文件和目录 [print(d) for d in os.listdir('.')] # 循环字典 d = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'} for k, v in d.items(): print(k, v) [print(k, v) for k, v in d.items()]
""" Class for background image """ import pygame class Background: """ Background for Mario Kart 2D game! """ def __init__(self, path: str, x_cor, y_cor) -> None: """ Initializes a background. """ self.img = pygame.image.load(path) self.x_cor, self.y_cor = x_cor, y_cor self.speed = 0 self.travelled = 0 def move_background(self, x, y): """ Move background to (x, y). """ old_x, old_y = self.x_cor, self.y_cor self.x_cor, self.y_cor = x, y if old_y <= self.y_cor: self.travelled += self.y_cor - old_y
# import nltk import numpy as np import matplotlib.pyplot as plt import operator import math # function to read a giveb file and return a sorted list of words and their frequencies def read_file(filename): word_dict = {} fp = open(filename, 'rb') print('Reading ' + filename) # count the frequencies of each unique word in the document for sent in fp: for word in sent.split(): if word not in word_dict: # create an entry for the word encountered for the first time in the document word_dict[word] = 1 else: # increase word count on each occurrence word_dict[word] += 1 print('Dictionary formed! Words: ' +str(len(word_dict))) return sorted(word_dict.items(), key=operator.itemgetter(1), reverse=True) if __name__ == '__main__': file1 = 'ACCEnglish.txt' file2 = 'ACCGerman.txt' file3 = 'ACCFrench.txt' # call function for creating word dictionaries of the text documents dict_english = read_file(file1) dict_french = read_file(file2) dict_german = read_file(file3) # arange the plot points in log scale x1 = [math.log(x+1) for x in np.arange(len(dict_english))] y1 = [math.log(x) for i, x in dict_english] x2 = [math.log(x+1) for x in np.arange(len(dict_french))] y2 = [math.log(x) for i, x in dict_french] x3 = [math.log(x+1) for x in np.arange(len(dict_german))] y3 = [math.log(x) for i, x in dict_german] # create plot handles for English, French and German text english, = plt.plot(x1, y1, 'r-', label="English") french, = plt.plot(x2, y2, 'b-', label="French") german, = plt.plot(x3, y3, 'g-', label="German") plt.xlabel('Log Word Rank') plt.ylabel('Log Frequencies') plt.legend(handles= [english, french, german]) #save the plot in png format plt.savefig('Zipf.png') plt.show()
def get_guests(): guests = [] name = "something" while True: name = raw_input("Who's coming? ") if name == "": break guests.append(name) return guests def say(what, guests): for x in guests: # print "Hi, {0}".format(x) print what + ", " + x def inflate_balloons(): print "The baloons are inflated." def start_music(): print "'I Want It That Way' is playing." def cheer(number_of_times): for j in range(number_of_times): print "whoop de doo." def party(): guests = get_guests() say("Hello", guests) inflate_balloons() start_music() cheer(8) say("Goodbye", guests) party()
# 스레드를 생성해서 1초마다 "Thread is running!" 문자열을 출력한다 # # 작성자: 강민석 # 작성날짜: 2017년 3월 19일 (version 1.0) import time import threading class ThreadClass(threading.Thread): def run(self): while True: print("Thread is running!") time.sleep(1) workThread = ThreadClass() workThread.start()
# 정수 입력 확인 프로그램 # 입력받은 값이 정수인지를 계산해주는 프로그램 # # 입력: 임의의 숫자 - 정수만 허용 # 출력: 입력받은 숫자 # # 1. 정수를 입력받을 때까지 계속 입력받음 # 2. 가장 앞에 '+'혹은 '-'기호가 있어도 정수로 취급 # 3. 입력받은 값이 정수일 경우 입력받은 값을 출력하고 종료 # # 작성자: 강민석 # 작성날짜: 2017년 3월 23일 (version 1.0) def is_number(str) : result=False try : float(str) result=2 int(str) result=1 except : pass return result def get_int_signed(message): temp = input(message) while not (is_number(temp) == 1): temp = input(message) return int(temp) print(get_int_signed("정수를 입력하시오\n"))
#what is faster list or tuple? #Tuples are allocated in the single block and are immutable and does not require extra storage #Lists are allocated in double block, one is of fixed length and storage and other is of variable length and storage tuple1 = (1,2,3,4,5) print(tuple1) list1 = [1,2,3,4,5] print(list1) list1.append(6) print(list1)
#This is used to write the contents to the file try: f = open("E:/Python_Latest_Besant_Technologies/write_example4.txt",'w') f.write('hello everyone !') except IOError: print('can\'t find the file or read') else: print('Written the contents to the file') try: f = open("E:/Python_Latest_Besant_Technologies/write_example4.txt",'r') print(f.read()) finally: f.close()
#Constructors are of two types #Creating Multiple Objects class Employee: def __init__(self,name,age): self.name=name self.age=age def display(self): print("name %s ange age %d"%(self.name,self.age)) emp1=Employee("John",101) emp2=Employee("David",102) emp3=Employee("Krithika",900) emp1.display() emp2.display() emp3.display() #Non Parameterized Constructor class Student: def __init__(self): print("This is non parameterised constructor") s=Student() #Count the number of Objects creation class Student: count = 0 def __init__(self): Student.count=Student.count+1 s1=Student() s2=Student() s3=Student() s4=Student() s5=Student() s6=Student() print("The number of objects created is %d",Student.count) #Parameterized Constructor class Student: def __init__(self,name): print("This is the parameterized constructor") self.name=name def show(self): print("Hello",self.name) student=Student("John") student.show()
#How we remove values from the array from array import array a = array('i', [1,2,3,4,5]) print(a) a.remove(3) print(a)
#Printing the Class Name class Myclass: x=5 print(Myclass) class Myclass: x=5 obj1=Myclass() print(obj1.x) #Usage of the init constructor class Person: def __init__(self,name,age): self.name=name self.age=age def myfunction(self): print(self.name) print(self.age) p1=Person("sudarshan",29) p1.myfunction() #We need not necessarily use only self key and we can also use other keys class Person: def __init__(obj,name,age): obj.name=name obj.age=age def myfunction(abc): print(abc.name) print(abc.age) p1=Person("sudarshan",29) p1.myfunction() #Modify the object properties class Person: def __init__(self,name,age): self.name=name self.age=age def myfunc(self): print('name is'+self.name+' age is: '+str(self.age)) p1=Person("Govindarajan",58) p1.myfunc() p1.age=60 p1.myfunc()
#-*- coding:utf-8 -*- #求两个三位数乘积的最大的回文数 def palindrome(n): temp=str(n) l=len(temp) for i in range(0,l/2): if temp[i] != temp[l-1-i]: # 不能写成if true else false的形式, return False #因为return一出现就意味着整个函数的 else: #结束,当然循环也只会执行一次 pass return True def largestPalindrome(): for i in range(999,0,-1): for j in range(i,0,-1): if palindrome(i*j): print i,'*',j,'=',i*j else: pass if '__name__'=='__main__': largestPalindrome()
from math import sqrt def isPrime(x): if x==1: return 0 if x==2: return 1 if x>2: for i in range(2,int(sqrt(x))+2): if x%i==0: return 0 elif i ==int(sqrt(x)+1): return 1 def main(): s=0 for i in range(1,1000001): if isPrime(i): s=s+i #print s print s main()
import csv def set_menu(x): with open('menu.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') item=[None]*20 price=[None]*20 i=0 for row in readCSV: item[i] = row[1] price[i] = row[2] i=i+1 return item[x],price[x] def menu_len(): with open('menu.csv') as csvfile: readCSV = csv.reader(csvfile,delimiter=',') i=0 for row in readCSV: i=i+1 return i #ch=int(input("Enter item index : ")) #menu(ch) #print(menu_len())
# Find who wins the tournament # Input array is of the form:[ [homeTeam,awayTeam] ] # results=[0,0,1] where 0 means home team lost and vice versa # Print who wins that tournament def tournamentWinner(competitions, results): # Write your code here. winner = "" tourny_score = {winner: 0} for i, arr in enumerate(competitions): if results[i] == 0: winner = arr[1] if winner in tourny_score: tourny_score[winner] += 3 else: tourny_score[winner] = 3 else: winner = arr[0] if winner in tourny_score: tourny_score[winner] += 3 else: tourny_score[winner] = 3 return max(tourny_score,key=tourny_score.get)
## Dimensionality Reduction **PCA** import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('Wine.csv') x = data.iloc[:,0:13].values y = data.iloc[:,13] **Splitting the dataset** from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0) **Feature Scaling** from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_test = sc.transform(x_test) **Applying PCA to dataset** from sklearn.decomposition import PCA pca = PCA(n_components=None) x_train = pca.fit_transform(x_train) x_test = pca.transform(x_test) explained_variance = pca.explained_variance_ratio_ #to explain percentage of variance, usually choose the ones that explain more variance explained_variance **Reapply pca with 2 components, the ones that explain more variance** pca = PCA(n_components=2) x_train = pca.fit_transform(x_train) x_test = pca.transform(x_test) explained_variance = pca.explained_variance_ratio_ explained_variance **Fitting Logistic Regression to training set with dimensions reduced** from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state=0) classifier.fit(x_train,y_train) y_pred = classifier.predict(x_test) **Metrics** from sklearn.metrics import confusion_matrix confusion_matrix(y_test,y_pred) **Visualizing the Training set results** plt.figure(figsize=(10,5)) from matplotlib.colors import ListedColormap x_set, y_set = x_train, y_train x1, x2 = np.meshgrid(np.arange(start = x_set[:, 0].min()-1, stop = x_set[:,0].max()+1, step = 0.01), np.arange(start = x_set[:, 1].min()-1, stop = x_set[:,1].max()+1, step = 0.01)) plt.contourf(x1,x2, classifier.predict(np.array([x1.ravel(),x2.ravel()]).T).reshape(x1.shape), alpha=0.5,cmap = ListedColormap(('red','green','blue'))) plt.xlim(x1.min(), x1.max()) plt.ylim(x2.min(),x2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set==j,0], x_set[y_set==j, 1], c = ListedColormap(('red','green','blue'))(i), label=j) plt.legend() plt.show() **Visualizing test results** plt.figure(figsize=(10,5)) from matplotlib.colors import ListedColormap x_set, y_set = x_test, y_test x1, x2 = np.meshgrid(np.arange(start = x_set[:, 0].min()-1, stop = x_set[:,0].max()+1, step = 0.01), np.arange(start = x_set[:, 1].min()-1, stop = x_set[:,1].max()+1, step = 0.01)) plt.contourf(x1,x2, classifier.predict(np.array([x1.ravel(),x2.ravel()]).T).reshape(x1.shape), alpha=0.25,cmap = ListedColormap(('red','green','blue'))) plt.xlim(x1.min(), x1.max()) plt.ylim(x2.min(),x2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(x_set[y_set==j,0], x_set[y_set==j, 1], c = ListedColormap(('red','green','blue'))(i), label=j) plt.legend() ## PCA Analysis with a different dataset ## The Data Let's work with the cancer data set again since it had so many features. from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() cancer.keys() print(cancer['DESCR']) df = pd.DataFrame(cancer['data'],columns=cancer['feature_names']) #(['DESCR', 'data', 'feature_names', 'target_names', 'target']) df.head() from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(df) scaled_data = scaler.transform(df) from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(scaled_data) Now we can transform this data to its first 2 principal components. x_pca = pca.transform(scaled_data) scaled_data.shape x_pca.shape Great! We've reduced 30 dimensions to just 2! Let's plot these two dimensions out! plt.figure(figsize=(8,6)) plt.scatter(x_pca[:,0],x_pca[:,1],c=cancer['target'],cmap='plasma') plt.xlabel('First principal component') plt.ylabel('Second Principal Component') pca.components_ In this numpy matrix array, each row represents a principal component, and each column relates back to the original features. we can visualize this relationship with a heatmap: df_comp = pd.DataFrame(pca.components_,columns=cancer['feature_names']) plt.figure(figsize=(12,6)) sns.heatmap(df_comp,cmap='plasma',)
import random count = 0 heads = 0 tails = 0 while count < 100 : count += 1 rand = random.randint(1,2) if rand == 1 : heads += 1 else: tails += 1 print("Heads = " + str(heads)) print("Tails = " + str(tails))
#Бутолин Александр ИУ7-12 # Для ф-ции Х составить программу вычесления Y # 0 при x<=-1 # 1 при -1<=x<0 # -1 при 0<=x<2 # 1 при x<=2 try: x=float(input('Введите значение X: ')) if x<-1: y=0 if -1<=x<0: y=1 if 0<=x<2: y=-1 if x>2: y=1 print(y) except ValueError: print('Неправильно значение')
from math import * c1=float(input('Введите начальное значение функции: ')) c2=float(input('Введите конечное значение функции: ')) h=float(input('Введите шаг: ')) n=c1 min=9999999999999 max=-999999999999 while round(n,7)<=c2: s=n*n*n+n-1 if s<min: min=s if s>max: max=s n+=h print() print('График функции S') print(' {:3.3f}'.format(min),end='') print('',' '*50,'{:3.3f}'.format(max)) print(' ','-'*59,end='') print('+') while round(c1,7)<=c2: s=c1*c1*c1+c1-1 o=int(round((0-min)/(max-min)*59+1,0)) zv=int(round((s-min)/(max-min)*59+1,0)) r0=(' '*o)+'|' rz=(' '*zv)+'*' if min >0: print('{:4.3f} {}'.format(c1,rz)) else: if zv<o: o=o-zv-1 r0=((' '*o) + '|') if c1<0: print('{:10.3f} {}{}'.format(c1,rz,r0)) else: print('{:10.3f} {}{}'.format(c1,rz,r0)) elif zv>o: zv=zv-o-1 rz=((' '*(zv) + '*')) if c1<0: print('{:10.3f} {}{}'.format(c1,r0,rz)) else: print('{:10.3f} {}{}'.format(c1,r0,rz)) else: print('{:10.3f} {}'.format(c1,rz)) c1+=h
# Бутолин Александр ИУ7-12 # Посчитать сумму ряда from math import * try: x=float(input('Ведите значение X: ')) if abs(x)>1: print('Неправильное значение X') else: e=float(input('Введите значение эпсилон: ')) n=int(input('Введите начальное значение для вывода: ')) if n<=0: print('Неправильное начальное значение: ') else: h=int(input('Введите шаг вывода результатов: ')) if h<=0: print('Неправильное значение шага вывода результатов: ') else: max=int(input('Максимальн итераций: ')) if max<=0: print('Неправильное значение итерации: ') else: z=1 sum=x t=x k=2 print(' k\t t\t sum') if n==1: print(' 1','\t',x,'\t ',x) while abs(t)>e: t=t*(-(x**2)*(z)/(z+2)) sum+=t if ((k==n) or (k>n and (k-n)%h==0)) and k<max: print('{:3d}'.format(k),'{:10.5f}'.format(t),' {:7f}'.format(sum)) k+=1 z+=2 if k>=max : print('Ряд не сошелся ') else: print('При X = ',x,'C точностью = ',e,'Cумма ряда = {:7f}\n'.format(sum),'Число просуммированных членов = ',k-1) except ValueError: print('Неправильное значение')
#Бутолин Александр ИУ7-12 #Метод парабол для заданного количества разбиений from math import * try: def f(y): return y*y a,b=map(float,input('Введите интервал для подсчёта интеграла: ').split()) n=int(input('Введите количество разбиений n: ')) if n%2==0: h=(b-a)/n s1=s2=0 for i in range (n): if i!=0 and i!=n: if i%2!= 0: x=a+i*h s1+=f(x) else: x=a+i*h s2+=f(x) sum1=h/3*(4*s1+2*s2+f(a)+ f(b)) print('Значение интеграла для',n,'разбиений =',sum1) else: print('Количество разбиений должно быть кратно двум') except ValueError: print('Введено неправильное значение')
# Largest Number formed from an Array # http://practice.geeksforgeeks.org/problems/largest-number-formed-from-an-array/0 import functools def comparator(x, y): xy = x + y yx = y + x return int(xy) - int(yx) if __name__ == "__main__": # num_cases = int(1) num_cases = int(input()) results = [] for _ in range(num_cases): num_input = int(input()) # num_input = 65 # string_input = "3 30 15 15151 15153 1515152" # string_input = "891 885 814 442 128 180 785 538 871 562 582 166 803 733 333 855 760 848 378 463 11 820 151 378 942 837 721 300 113 760 957 391 153 49 15 45 919 151 102 296 822 732 502 246 962 58 511 929 806 174 138 670 97 504 422 676 519 301 490 263 55 264 644 890 251" # string_input = "598 649 705 551 151 977 413 555 798 505 382 749 66 379 700 210 130 554 484 448 608 774 323 306 177 54 225 631 367 401 445 371 286 17 899 156 134 558 577 179 267 358 712 879 615 820 738 134 592 721 763 634 198 32 589 590 874 878 305 359 201 255 961 916 948" string_input = input() splitted = string_input.split(" ") # sortedList = sorted(splitted[:num_input], key=functools.cmp_to_key(comparator), reverse=True) # print(sortedList) results.append(functools.reduce(lambda x, y: x+y, sortedList)) for result in results: print(result)
import pandas as pd structure_number = "Structure Number" parent_index = "_parent_index" def reviser(xl_file_name): df = pd.read_excel(xl_file_name, index_col=0) df = df[df.groupby(structure_number)[parent_index].transform('max') == df[parent_index]] df.to_excel("Revised " + xl_file_name) print("Revised excel file is created.") if __name__ == '__main__': while True: excel_file_name = input("Enter excel file name : ") reviser(excel_file_name) # reviser('Structure List TG.xlsx')
def anagrams(word): result = [] length = len(word) anagram = '' if length <= 1: result.append(word) return result else: for char in anagrams(word[1:]) : for element in range (length): anagram = char[:element]+ word[0:1]+ char[element:] #accounts for doubles if anagram not in result: result.append(anagram) return result
# Leetcode # 121 : Best Time to Buy and Sell Stock class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 leng = len(prices) profit = 0 min_price = prices[0] for i in range(1,leng): profit = max(profit, prices[i] - min_price) min_price = min(min_price, prices[i]) return profit # ====================================================================================== # LeetCode # 70 : Climbing Stairs class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ if n <= 2 and n >= 0: return n f = 1 s = 2 c = 0 for _ in range(2, n): c = f + s f, s = s, c return c class Solution: def climbStairs(self, n: int) -> int: """ :type n: int :rtype: int """ if n <= 2 and n >= 0: return n arr = [1,2] for i in range(2, n): arr.append(arr[i-1] + arr[i-2]) return arr[n-1] # ====================================================================================== # LeetCode # 448 : Find All Numbers Disappeared in an Array class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for i in range(len(nums)): # index = abs(nums[i]) - 1 nums[abs(nums[i]) - 1] = - abs(nums[abs(nums[i]) - 1]) return [i+1 for i in range(len(nums)) if nums[i] > 0] # ====================================================================================== # LeetCode # 287 : Find the Duplicate Number class Solution: def findDuplicate(self, nums: List[int]) -> int: if len(nums) == 0: return 0 s = 1 e = len(nums)-1 while s + 1 <= e: count = 0 m = (s + e)//2 for num in nums: if num <= m: count += 1 if count <= m: s = m + 1 else: e = m return e # ====================================================================================== # 이것이 코딩 테스트다 그리디 # 02 : 큰 수의 법칙 n, m, k = map(int, input().split()) data = list(map(int, input().split())) data.sort() first = data[n-1] second = data[n-2] count = int(m / (k + 1)) * k count += m % (k + 1) result = 0 result += (count) * first result += (m - count) * second print(result) # ====================================================================================== # 이것이 코딩 테스트다 그리디 # 03 : 숫자 카드 게임 # min() 함수 n, m = map(int, input().split()) result = 0 for i in range(n): data = list(map(int, input().split())) min_val = min(data) result = max(result, min_val) print(result) # 2중 for문 n, m = map(int, input().split()) result = 0 for i in range(n): data = list(map(int, input().split())) min_val = 10001 for a in data: min_val = min(min_val, a) result = max(result, min_val) print(result) # ====================================================================================== # LeetCode # 1071 : Greatest Common Divisor of Strings class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: if len(str1) == len(str2) and str1 == str2: return str1 elif len(str1) < len(str2): str1, str2 = str2, str1 return self.gcdOfStrings(str1, str2) elif str1[: len(str2)] == str2: return self.gcdOfStrings(str1[len(str2):], str2) else: return '' # ====================================================================================== # 이것이 코딩 테스트다 그리디 # 04 : 1이 될때까지 # 풀이 1 n, k = map(int, input().split()) result = 0 while n >= k: while n % k != 0: n -= 1 result += 1 n //= k result += 1 while n > 1: n -= 1 result += 1 print(result) # 풀이 2: 나누어떨어지는 수가 될 때까지 1을 뺴는 법 # n이 k 이상이면 k로 나누는 것이 1을 빼는 것보다 빠르다 n, k = map(int, input().split()) result = 0 while True: target = (n // k) * k result += (n - target) n = target if n < k: break result += 1 n //= k result += (n - 1) print(result) """ n = 25 k = 3 result = 0 target = 24 result = 1 n = 24 result = 2 n = 8 target = 6 result = 4 n = 6 result = 5 n = 2 target = 2 result = 5 n = 2 result = 6 ----------------------- result = 6 """ # ====================================================================================== # 이것이 코딩 테스트다 구현 # 01 : 상하좌우 n = int(input()) x, y = 1, 1 plans = input().split() dx = [0, 0, -1, -1] dy = [-1, 1, 0, 0] move_types = ['L', 'R', 'U', 'D'] for plan in plans: for i in range(len(move_types)): if plan == move_types[i]: nx = x + dx[i] ny = y + dy[i] if nx < 1 or ny < 1 or nx > n or ny > n: # 공간을 벗어나는 경우 무시한다 continue x, y = nx, ny print(x, y)
import numpy import math # This function implements an infinite series formula for e, 1/n! def calculate_e(terms): array = numpy.arange(terms) # Create a numpy array automatically filled with the terms e = 0 for term in array: e += 1/math.factorial(term) return e num_terms = 20 for num in range(num_terms): estimate = calculate_e(num) error = math.e - estimate # Using the math.e constant print("Terms: {} \t\t Estimate: {} \t\t Error: {}".format(num, estimate, error))
import string def check_string(file_name, string_to_search): with open(file_name, 'r') as read_obj: for line in read_obj: if string_to_search in line: return True return False def score_word(file_name, string_to_search): """Search for the given string in file and return lines containing that string, along with line numbers""" line_number = 0 list_of_results = [] with open(file_name, 'r') as read_obj: # Read all lines in the file one by one for line in read_obj: # For each line, check if line contains the string line_number += 1 words = line.split(" ") for word in words: if word.upper().lower() == string_to_search: list_of_results.append((line_number, line.rstrip())) # Return list of tuples containing line numbers and lines where string is found return list_of_results def average_core(file_name): with open(file_name,'r') as read_obj: text = read_obj.read() words = text.split() #normalize all and strip all punctuation table = str.maketrans("","",string.punctuation) stripped = [w.translate(table) for w in words] assemble = " ".join(stripped) assemble = assemble.lower() print(assemble) def main(): print("What would you like to do ?") print("1: Get score of a word?") print("2: Get the average score of words in a file ") print("3: Find the highest / lowest scoring words in a file") print("4: Sort the words into positive.txt and negative.txt") print("5: Exit the program") word = input("enter a word to get score's word ?") if check_string('training.txt', word): print('Yes, word found in file') else: print('Word not found in file') matched_lines = score_word('training.txt', word) s =0 score = 0 for elem in matched_lines: s += int(elem[1][0]) score = round(s/(len(matched_lines)), 2) print("score: ", score) if score > 2: print(word," is positive") else: print(word," is negative") #function2: #normalize and strip punctuation # normalize = average_core('training.txt') # print(normalize) if __name__ == '__main__': main()
def main(): string = input('Enter a string for the program to capitalize sentences: ') result = capitalize(string) print(result) # The capitalize method return a opy of the string # with the first character of each sentence capitalized. def capitalize(string): result = '' new_sentence = True result_word = '' words = string.split() for item in words: if new_sentence: result_word = item[0].upper() + item[1:] else: result_word = item result += result_word + ' ' if item[-1] == '.' or item[-1] == '?' or item[-1] == '!': new_sentence = True else: new_sentence = False return result main()
#!/usr/bin/env python3 import csv from datetime import date import datetime from datetime import timedelta import pandas as pd from yahoofinancials import YahooFinancials """ Obtain yahoo stock prices and email to nominated email addresses Program takes stocks as an input and returns prices. Some light analysis done then results sent to a CSV file. Selected elements taken and inserted into email and sent to selected email accounts. Paramaters: Nil. """ currencies = ['EURUSD=X', 'JPY=X', 'GBPUSD=X', 'AUDUSD=X', 'INRUSD=X'] # The difference is AUDUSD=X or AUD=X # Setup dates so they can be used later, has to be a weekday or when market is open def price_range_setup(): today = date.today() is_weekday = today.weekday() if is_weekday >= 0 and is_weekday <= 4: yesterday = today - timedelta(days=1) yesterday, today = str(yesterday), str(today) return yesterday, today else: print("Today is a weekend, no data is available") quit() def write_to_csv(filename, func): with open(filename, "a") as archive: wr = csv.writer(archive) for value in func: wr.writerow(value) def get_stock_prices(): #yesterday, today = price_range_setup() for currency in currencies: raw_data = YahooFinancials(currency) # raw_data = raw_data.get_historical_price_data(today, today, "daily") // remember has to be a weekday! raw_data = raw_data.get_historical_price_data("2020-04-15", "2020-04-15", "daily") df = pd.DataFrame(raw_data[currency]['prices']) adjclose, close, date, high, low, opening, volume = df['adjclose'], df['close'], df['date'], \ df['high'], df['low'], df['open'], df['volume'] yield currency, adjclose, close, date, high, low, opening, volume # Iterate through elements and calculate whatever metrics you require def calculate_metrics(): for value in get_stock_prices(): currency, adjclose, close, unix_date, high, low, opening, volume = (value[0]), (value[1][0]), (value[2][0]), (value[3][0]), \ (value[4][0]), (value[5][0]), (value[6][0]), (value[7][0]) unix_timestamp = datetime.datetime.fromtimestamp(unix_date) adj_timestamp = unix_timestamp.strftime('%H:%M:%S %d-%m-%Y') intra_day_movement = low - high daily_difference = opening - close line = currency, adj_timestamp, opening, close, high, low, intra_day_movement, daily_difference yield line write_to_csv("output.csv", calculate_metrics())
def printPascal(testVariable) : # Base Case if testVariable == 0: return [1] else: line = [1] # Recursive Case previousLine = printPascal(testVariable - 1) for i in range(len(previousLine) - 1): line.append(previousLine[i] + previousLine[i+1]) line += [1] return line testVariable = 5 print(printPascal(testVariable))
## O(N*lgN + M*LgM) Time | O(1) Space def smallestDifference(arrayOne, arrayTwo): # Ask you interviewer if it's okay to sort the array in place. # Sometimes, you can't hamper the data. arrayOne.sort() arrayTwo.sort() idxOne = 0 idxTwo = 0 smallest = float("inf") current = float("inf") smallestPair = [] while(idxOne < len(arrayOne) and idxTwo < len(arrayTwo)): firstNum = arrayOne[idxOne] secondNum = arrayTwo[idxTwo] if firstNum < secondNum: current = secondNum - firstNum idxOne += 1 elif secondNum < firstNum: current = firstNum - secondNum idxTwo += 1 else: return [firstNum, secondNum] if smallest > current: smallest = current smallestPair = [firstNum, secondNum] return smallestPair # Leetcode - Not available # Easy
#import modules import os import csv #set path for file pypoll_csv = os.path.join('.','election_data.csv') #set initial values and list votes = 0 dict = {} #open the csv to read with open (pypoll_csv, newline='') as csvfile: #specify delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') #read the header row first csv_header = next(csvreader) #create dictionary from file with unique candidates names as keys. for row in csvreader: #The total number of votes cast votes += 1 #counts votes for each candidate as values #keeps a total vote count by counting up 1 for each row if row[2] in dict.keys(): dict[row[2]] += 1 else: dict[row[2]] = 1 #create empty list for candidates and their votes count candidates = [] cand_votes = [] #take dictionary keys and values and adds them to the lists for key, value in dict.items(): candidates.append(key) cand_votes.append(value) #create percent list percent = [] for i in cand_votes: percent.append(round(i/votes*100, 3)) #group candidates, cand_votes and percent into tuples group = list(zip(candidates, cand_votes, percent)) #create winner list winner_list= [] for candidate in group: if max(cand_votes) == candidate[1]: winner_list.append(candidate[0]) # makes winner_list a str with the first entry winner = winner_list[0] print("Election Results") print("-------------------------") #The total number of votes cast print(f"Total Votes: {votes}") print("-------------------------") #A complete list of candidates who received votes #The percentage of votes each candidate won #The total number of votes each candidate won for j in range(len(candidates)): print(candidates[j],": ",percent[j],"% (",cand_votes[j],")") print("-------------------------") #The winner of the election based on popular vote. print("Winner: ",winner) print("-------------------------") #create text file in this path text_file = os.path.join("Election Results.txt") #write this in text with open("Election Results.txt", "w") as text_file: print("Election Results", file = text_file) print("-------------------------", file = text_file) print(f"Total Votes: {votes}", file = text_file) print("-------------------------", file = text_file) for j in range(len(candidates)): print(candidates[j],": ",percent[j],"% (",cand_votes[j],")", file = text_file) print("-------------------------", file = text_file) print("Winner: ",winner, file = text_file) print("-------------------------", file = text_file)
num = int (input("Enter Number to find its prime or not: ")) for i in range(2, num): if(num%i) == 0: print("Its not a prime number") break else: print("Its a prime number") break
#!/usr/bin/env python3 ''' Functions used for loading and finding files for brain analysis. Authors: Sydney C. Weiser Date: 2017-07-28 ''' import os import re import sys import time from subprocess import call import yaml from typing import List def find_files(folder_path: str, match_string: str, subdirectories: bool = False, suffix: bool = False, regex: bool = False, verbose: bool = True) -> List[str]: ''' Finds files in folder_path that match a match_string, either at the end of the path if suffix=True, or anywhere if suffix=False. Searches subdirectories if subdirectories = True Arguments: folder_path: The folder to search for files in. match_string: The match string to search for. subdirectories: Whether to search subdirectories. suffix: The suffix to search for. regex: Whether to use regex to search for the match string. verbose: Whether to produce verbose output. Returns: results: A list of file paths. ''' assert os.path.isdir(folder_path), 'Folder input was not a valid directory' files = [] if subdirectories: result = os.walk(folder_path) for i, f in enumerate(result): print(i) root, folder, file_list = f for file in file_list: print(file) files.append(os.path.join(root, file)) else: for file in os.listdir(folder_path): files.append(os.path.join(folder_path, file)) if verbose: print("all files found in folder '{0}':".format(folder_path)) results = [] for filepath in files: file = os.path.basename(filepath) if os.path.isfile(filepath): if verbose: print('\t', file) if regex: # search using regular expressions if re.match(match_string, file): results.append(filepath) else: # search using string functions if suffix: if file.endswith(match_string): results.append(filepath) else: if file.find(match_string) >= 0: results.append(filepath) if verbose: print('matching files found in folder:') [print('\t', os.path.basename(file)) for file in results] return results def movie_sorter(pathlist: List[str], matchstr: str = None, verbose: bool = True) -> dict: ''' Takes list of paths, sorts into experiments, and orders files by extension number. Returns dict of experiments with associated files. Arguments: pathlist: A list of paths, generally produced by find_files. Returns: experiments: A dict, containing top level entries representing unique results of the matchstring search, each containing a list of tif files which matched that experiment. ''' n_files = len(pathlist) exp_list = [] fnum_list = [] # Only match movie files that have a specific file format. if matchstr is None: matchstr = r'(\d{6}_\d{2})(?:[@-](\d{4}))?\.tif' for i, file in enumerate(pathlist): name = os.path.basename(file) match = re.match(matchstr, name) if match is not None: exp, fnum = re.match(matchstr, name).groups() exp_list.append(exp) fnum_list.append(fnum) experiments = {} for exp in set(exp_list): indices = [i for i, exp_i in enumerate(exp_list) if exp == exp_i] if len(indices) == 1: experiments[exp] = [pathlist[indices[0]]] else: fnum_set = [fnum_list[i] for i in indices] # Sort file number extensions by order, get new indices. for n, fnum in enumerate(fnum_set): if fnum is None: fnum_set[n] = 0 else: fnum_set[n] = int(fnum) _, indices_sorted = zip(*sorted(zip(fnum_set, indices))) experiments[exp] = [pathlist[i] for i in indices_sorted] if verbose: print('\nExperiments\n-----------------------') for exp in experiments: print(exp + ':') [print('\t', fname) for fname in experiments[exp]] return experiments def experiment_sorter(folder_path: str, experimentstr: str = None, verbose: bool = True) -> dict: ''' Finds all files associated with an experiment in a particular folder, organizes them by filetype: movie files, processed files, metadata files. Arguments: folder_path: A path specifying which folder to search for experiment files within. experimentstr: The matchstring to search for relevant paths with. verbose: Whether to produce verbose output. Returns: experiment_files: A dictionary containing all the types of relevant files found for the given experiment specified by experimentstr. ''' assert os.path.isdir(folder_path), 'Folder input was not a valid directory' # Determine whether experimentstr matches the expected format. if experimentstr is not None: if re.match(r'^\d{6}_\d{2}-\d{2}$', experimentstr) is not None: print('matching multiple experiments') match = re.match(r'^(\d{6})_(\d{2})-(\d{2})$', experimentstr) groups = match.groups() experimentlist = [groups[0]+'_{:02d}'.format(i) \ for i in range(int(groups[1]), int(groups[2])+1)] else: assert re.match(r'^\d{6}_\d{2}$', experimentstr) is not None, \ 'experimentstr input was not a valid YYMMDD_EE experiment name' experimentlist = [experimentstr] else: experimentlist = [r'\d{6}_\d{2}'] files = os.listdir(folder_path) if verbose: print("all matching found in folder '{0}':".format(folder_path)) movies = [] meta = [] ica = [] processed = [] roi = [] dfof = [] body = [] oflow = [] videodata = [] for experimentstr in experimentlist: movies_unsorted = [] moviestr = experimentstr + r'(?:[@-](\d{4}))?\.tif' metastr = experimentstr + r'_meta\.yaml' icastr = experimentstr + r'_(.*)(ica|pca)\.hdf5' processedstr = experimentstr + r'_(ica|pca)(.+)\.hdf5' roistr = experimentstr + r'_roiset\.zip' dfofstr = experimentstr + r'_(\d+x)_dfof\.mp4' bodystr = experimentstr + r'_c(\d)-body_cam\.mp4' oflowstr = experimentstr + r'_(\w+)OpticFlow\.hdf5' ###### videodatastr = experimentstr + r'_videodata\.hdf5' for file in files: filepath = os.path.join(folder_path, file) if verbose: if re.match(experimentstr, file): print('\t', file) if re.match(moviestr, file, re.IGNORECASE): movies_unsorted.append(filepath) elif re.match(metastr, file, re.IGNORECASE): meta.append(filepath) elif re.match(icastr, file, re.IGNORECASE): ica.append(filepath) elif re.match(processedstr, file, re.IGNORECASE): processed.append(filepath) elif re.match(roistr, file, re.IGNORECASE): roi.append(filepath) elif re.match(dfofstr, file, re.IGNORECASE): dfof.append(filepath) elif re.match(bodystr, file, re.IGNORECASE): body.append(filepath) elif re.match(oflowstr, file, re.IGNORECASE): oflow.append(filepath) elif re.match(videodatastr, file, re.IGNORECASE): videodata.append(filepath) movies.extend( movie_sorter(movies_unsorted, verbose=False)[experimentstr]) experiment_files = { 'movies': movies, 'meta': meta, 'processed': processed, 'ica': ica, 'roi': roi, 'dfof': dfof, 'body': body, 'oflow': oflow, 'videodata': videodata } if verbose: print('Matches:') for key in experiment_files: if len(experiment_files[key]) > 0: print('\t' + key + ':') [ print('\t\t' + os.path.basename(item)) for item in experiment_files[key] ] return experiment_files def sort_experiments(files: List[str], experiment_format_string: str = None, verbose: bool = True) -> dict: ''' Given a list of files, sort them into relevant experiments. Arguments: files: A list of files to search for a given experiment format string. experiment_format_string: the experiment match string. Returns: experiments_found: A dictionary containing the unique experiments found by the format string. ''' if verbose: print('\nSorting Keys\n-----------------------') if experiment_format_string is not None: assert re.match(r'\d{6}_\d{2}', experiment_format_string) is not None, \ 'experiment_format_string input was not a valid YYMMDD_EE experiment name' else: experiment_format_string = r'(\d{6}_\d{2})' experiments_found = {} for i, file in enumerate(files): match = re.match(experiment_format_string, os.path.basename(file)) if match is not None: exp = match.groups()[0] if exp not in experiments_found.keys(): experiments_found[exp] = [file] else: experiments_found[exp].append(file) if verbose: for expname in experiments_found: print(expname) [print('\t', key) for key in experiments_found[expname]] return experiments_found def get_exp_span_string(experiments: List[str]) -> str: ''' Creates a formatted string based on the experiments found in the experiments list. Args: experiments: A list of experiments found. e.g. 120244_12, 120244_13, 120244_12. Returns: experiment_span_string: A string representing the experiment name and experiment span. e.g. 120244_12-14. ''' if len(experiments) == 1: experiment_span_string = [ get_basename(experiment) for experiment in experiments ] return experiment_span_string[0] else: experimentstr = r'(\d{6})_(\d{2})' explist = {} for exp in experiments: match = re.match(experimentstr, exp) if match is not None: date = match.groups()[0] if date not in explist: explist[date] = [] explist[date].append(match.groups()[1]) # In-place sort experiment numbers. [explist[date].sort() for date in explist] experiment_span_list = [ date + '_' + '-'.join(explist[date]) for date in explist ] experiment_span_string = '_'.join(experiment_span_list) return experiment_span_string def get_basename(path: str): ''' Get the experiment basename, stripping any extensions or tiff file fount extensions. Arguments: path: The unformatted filepath. e.g.: ./example/directory/[email protected] Returns: name: The formatted name. e.g.: filename, from the example above. ''' name = os.path.basename(path) name = re.sub(r'(\.)(\w){3,4}$', '', name) # remove extension name = re.sub(r'([@-])(\d){4}', '', name) # remove @0001 from path return name def read_yaml(path: str) -> dict: ''' Loads nested dictionaries from .yaml formated files. Arguments: path: the path to read yaml data from. Returns: yaml_contents: The contents of the yaml file. ''' yaml_contents = dict() with open(path, 'r') as data: try: yaml_contents = yaml.load(data) except yaml.YAMLError as exc: print(exc) return yaml_contents
def read_input(): res = [] with open("input.txt") as inf: for line in inf: res.append(line.strip()) return res def get_num(name): if name in dict_num: res = dict_num[name] else: res = len(dict_num) dict_num[name] = res return res def Dijkstra(N, S, matrix): valid = [True]*N weight = [1000000]*N weight[S] = 0 for i in range(N): min_weight = 1000001 ID_min_weight = -1 for i in range(N): if valid[i] and weight[i] < min_weight: min_weight = weight[i] ID_min_weight = i for i in range(N): if weight[ID_min_weight] + matrix[ID_min_weight][i] < weight[i]: weight[i] = weight[ID_min_weight] + matrix[ID_min_weight][i] valid[ID_min_weight] = False return weight indata = read_input() map_size = len(indata) + 1 space_map = [[1000000 for j in range(map_size)] for i in range(map_size)] dict_num = {"COM": 0} for planet in indata: temp = planet.split(sep=")") num_a = get_num(temp[0]) num_b = get_num(temp[1]) space_map[num_a][num_b] = 1 space_map[num_b][num_a] = 1 test = Dijkstra(map_size, dict_num["YOU"], space_map) print(test[dict_num["SAN"]] - 2)
def fibonacci(n): b = [] for i in range(n+1): if i == 0: b.append(0) elif i == 1: b.append(1) else: b.append(b[i - 1] + b[i - 2]) # fibonacci(n - 1) + fibonacci(n - 2) return b a = int(raw_input(">>> ")) print fibonacci(a)
#!/usr/bin/env python # coding: utf-8 # In[1]: # 17 list comprehension problems in python fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange'] numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9] # In[2]: # Example for loop solution to add 1 to each number in the list numbers_plus_one = [] for number in numbers: numbers_plus_one.append(number + 1) # Example of using a list comprehension to create a list of the numbers plus one. numbers_plus_one = [number + 1 for number in numbers] # Example code that creates a list of all of the list of strings in fruits and uppercases every string output = [] for fruit in fruits: output.append(fruit.upper()) # In[3]: # Exercise 1 - rewrite the above example code using list comprehension syntax. Make a variable named uppercased_fruits to hold the output of the list comprehension. Output should be ['MANGO', 'KIWI', etc...] uppercased_fruits= [x.upper() for x in fruits] uppercased_fruits # In[5]: # Exercise 2 - create a variable named capitalized_fruits and use list comprehension syntax to produce output like ['Mango', 'Kiwi', 'Strawberry', etc...] capitalized_fruits= [fruits.title() for fruits in fruits] capitalized_fruits # In[8]: def count_vowels(string): vowels = "AaEeIiOoUu" final = [each for each in string if each in vowels] return(len(final)) # In[10]: # Exercise 3 - Use a list comprehension to make a variable named fruits_with_more_than_two_vowels. Hint: You'll need a way to check if something is a vowel. fruits_with_more_than_two_vowels= [x for x in fruits if count_vowels(x) > 2] fruits_with_more_than_two_vowels # In[13]: # Exercise 4 - make a variable named fruits_with_only_two_vowels. The result should be ['mango', 'kiwi', 'strawberry'] fruits_with_only_two_vowels = [x for x in fruits if count_vowels(x) == 2] fruits_with_only_two_vowels # In[16]: # Exercise 5 - make a list that contains each fruit with more than 5 characters more_than_five= [x for x in fruits if len(fruits) > 5] more_than_five # In[19]: # Exercise 6 - make a list that contains each fruit with exactly 5 characters exactly_five= [fruits for fruits in fruits if len(fruits) == 5] exactly_five # In[20]: # Exercise 7 - Make a list that contains fruits that have less than 5 characters less_than_five= [fruits for fruits in fruits if len(fruits) < 5] less_than_five # In[21]: # Exercise 8 - Make a list containing the number of characters in each fruit. Output would be [5, 4, 10, etc... ] length_of_fruit_characters= [len(fruits) for fruits in fruits] length_of_fruit_characters # In[22]: # Exercise 9 - Make a variable named fruits_with_letter_a that contains a list of only the fruits that contain the letter "a" letter = "a" fruits_with_letter_a= [fruits for fruits in fruits if letter in fruits] fruits_with_letter_a # In[23]: # Exercise 10 - Make a variable named even_numbers that holds only the even numbers even_numbers = [num for num in numbers if num % 2 == 0] even_numbers # In[24]: # Exercise 11 - Make a variable named odd_numbers that holds only the odd numbers odd_numbers= [num for num in numbers if num % 2 ==1] odd_numbers # In[25]: # Exercise 12 - Make a variable named positive_numbers that holds only the positive numbers positive_numbers = [num for num in numbers if num > 0] positive_numbers # In[26]: # Exercise 13 - Make a variable named negative_numbers that holds only the negative numbers negative_numbers = [num for num in numbers if num < 0] negative_numbers # In[27]: # Exercise 14 - use a list comprehension w/ a conditional in order to produce a list of numbers with 2 or more numerals two_or_more =[num for num in numbers if num > 9 or num < -9] two_or_more # In[29]: # Exercise 15 - Make a variable named numbers_squared that contains the numbers list with each element squared. Output is [4, 9, 16, etc...] numbers_squared=[number ** 2 for number in numbers] numbers_squared # In[30]: # Exercise 16 - Make a variable named odd_negative_numbers that contains only the numbers that are both odd and negative. odd_negative_numbers = [num for num in numbers if num % 2 ==1 and num < 0] odd_negative_numbers # In[31]: # Exercise 17 - Make a variable named numbers_plus_5. In it, return a list containing each number plus five. numbers_plus_five= [num +5 for num in numbers] numbers_plus_five # In[32]: # BONUS Make a variable named "primes" that is a list containing the prime numbers in the numbers list. *Hint* you may want to make or find a helper function that determines if a given number is prime or not. def prime_number (num): for i in range (2, num): if (num % i) == 0: return False else: return True primes = [number for number in numbers if prime_number (number) == True] primes
# Search for identical data in two dictionaries dict1 = { 'a' : 'dog', 'b' : 'cat', 'c' : 'guinea pig' } dict2 = { 'a' : 'giraffe', 'd' : 'leopard', 'c' : 'guinea pig' } # searching for the same keys k = dict1.keys() & dict2.keys() print(k) # searching for the same pairs of keys&values i = dict1.items() & dict2.items() print(i) # searching for keys not included in dict2 k = dict1.keys() - dict2.keys() print(k)
# The code in week 2 lectur e3 of the MITx 6.00.1x to find the cube root # of a given number does not work due to syntax and symantic errors. # Here is how I fixed it. :) x = int(raw_input("Enter an integer: ")) for ans in range(0, abs(x)+1): if ans**3 ==abs(x): if x < 0: ans = -ans print('Cube root of ' + str(x) + ' is: '+ str(ans)) break if abs(ans) == (abs(x)): print(str(x) + ' is not a perfect cube') continue
def search(mid): conv = 0 max_len = len(board)-1 # mid 만큼 휴개소 갯수 탐색 for i in range(max_len): conv += (board[i+1] - board[i]-1)//mid return conv n, m, l = map(int, input().split()) board = list(map(int, input().split())) left, right = 0, l board += [left, right] board.sort() while left <= right: mid = (left+right) // 2 if search(mid) > m: left = mid + 1 else: right = mid - 1 print(left)
# -*- coding: utf-8 -*- #!/usr/bin/python ################################################ ####### THE CHEATSHEET OF LETTER CODES: ######## # ś (si) = \xc5\x9b #ą = \xc4\x85 # ź (zi) #ć (ci) = \xc4\x87 #dź (dzi) =\xc5\xba ################################################ ####### THE FUNCTION KASHUBY: ################## def kashuby(x): #the word is turned into an array a = list(x) # BELOW : control print; to be enabled when a check is needed # print a l = len(a) #this checks whether a certain element of the array doesn't belong to the alphabet. #if it's so, it increments z. z = 0 for i in range(0,l): if(a[i].isalpha()==False): z += 1 #if z>0, there are special signs so we need to have each letter after a space. #this ensures that the strange signs don't get messed up as they would with list(x) if(z>0): x = raw_input("Proszę podaj słowo raz jeszcze, po każdym znaku umieszczając spację: \n") a = x.split(" ") #BELOW: a control print of the special array # print a l = len(a) #a standard, brute force and sloppy way of exchanging one-letter Pols into Kashs for i in range(0,l): if(a[i]=="ś"): a[i] = "s" elif(a[i]=="\xc4\x87"): a[i] = "c" elif(a[i]=="\xc5\xba"): a[i] = "z" #BELOW: a control print # print "the length is %d" % (l) #a standard, brute force and sloppy way of exchanging two-letter Pols into Kashs #the for loop must be therefore restricted for i in range(0,l-1): if(a[i]+a[i+1]=="si"): a[i+1] = "" elif(a[i]+a[i+1]=="ci"): a[i+1] = "" elif(a[i]+a[i+1]=="zi"): a[i+1] = "" elif((a[i]+a[i+1]=="ro") | (a[i]+a[i+1]=="ró")): a[i] = "a" a[i+1] = "r" print "".join(a) ################################################ ####### MAIN FUNCTION: ######################## x = raw_input("Daj mi słowo: ") kashuby(x)
## num = [5,9,13,18,23] num1 = [9,5,18,13,23] #num #num1 print(num) print(num1) ##### Indexes of a list ##### ### ### ### 0 1 2 3 4 ### ### 5 9 13 18 23 ### ### -5 -4 -3 -2 -1 ### ### ### ############################# print(num[2]) print(num1[2]) print(num[0]) print(num[-1]) print(num[-5]) print(num[2:]) ### String Lists ### names = ['venkata', 'harish', 'tallam'] print(names) ### String & Number Lists #### dob = ['venkata', '13', 'harish', '05', 'tallam', '1987'] print(dob) ## lets print lists of lists print(num, names) ## Other in-built operations num.append(55) ## 55 appends to the existing list print(num) num.insert(5,10) ## inserts 10 at index 5 print(num) num.remove(23) ## removes number 23 print(num) num.pop(4) ## removes basis on index print(num) num.pop() ## removes basis on LIFO (push,pop tech as per data structures) print(num) del num[3:] ## removes from 3rd index print(num) num.extend([2,3,1,6,32]) ##adds these number from last index print(num) ## IN-BUILD FUNCTIONS ## print(min(num)) print(max(num)) print(sum(num)) num.sort() ## sorts in order print(num)
# Recursion - Calling a function itself import sys # By default, the recursive function can be executed only 1000 times print(sys.getrecursionlimit()) # This will give recursion limit print(sys.setrecursionlimit(2000)) # Using this, we can overwrite recursion limit print(sys.getrecursionlimit()) # Checking the recursion limit after overwriting it # Example for understanding i = 0 def greet(): global i i += 1 print("Hello", i) greet() # Enable below just to understand the recursion # greet() # Example - 1 # Factorial using recursion def fac(n): if n == 0: return 1 return n * fac(n-1) x = 5 result = fac(x) print(result)
# Example 1 def search(list, n): i = 0 while i < len(list): if list[i] == n: return True i = i + 1 return False # This is list list = [2, 5, 9, 13, 18] # This is what we need to search n = 20 if search(list, n): print("Found the number") else: print("Number not found")
# Functions - Functions are objects in Python # defining a function def greet(): # simple function print("Hello") print("Good Morning") def add(x, y): # argument based function z = x + y print(z) def add1(x, y): # argument based function with return z = x + y return z def add_sub(x, y): # argument based function with multiple return statements z = x + y s = x - y return z, s # calling a function greet() add(2, 3) result = add1(5, 4) print(result) result1, result2 = add_sub(5, 4) print(result1, result2)
a = 5 b = 0 # Example 1 try: print(a/b) except Exception: print("A number cannot be divided by zero") # Example 2 try: print(a/b) except Exception as e: print("A number cannot be divided by zero:", e) # Example 3 a = 5 b = 2 try: print(a/b) k = int(input("Enter the value: ")) except Exception as e: print("A number cannot be divided by zero:", e) # Example 4 a = 5 b = 2 try: print(a/b) k = int(input("Enter the value: ")) except ZeroDivisionError as e: print("A number cannot be divided by zero:", e) except ValueError as e: print("Invalid input", e) except Exception as e: print("Something went wrong:", e) # Example 5 a = 5 b = 2 try: print("Resource Open") print(a/b) k = int(input("Enter the value: ")) except ZeroDivisionError as e: print("A number cannot be divided by zero:", e) except ValueError as e: print("Invalid input", e) except Exception as e: print("Something went wrong:", e) finally: print("Resource closed")
""" The main purpose of having modules is to split the code into multiple files or multiple blocks depends upon the need instead of maintaining in a single file which eventually leads to confusion """ def add_new(a, b): return a + b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): return a / b
import os # Open a file #fo = open(r"D:\Installations\python-workspace\files_learn\foo.txt", "r+") os.remove("foo.txt") os.remove("oof.txt") fo = open("foo.txt", "w+") fo.write("Amazing.. \nZing Zing\n") str = fo.read(10) print ("Read string is:", str) # Check current position position = fo.tell() print ("Current file position : ", position) # Reposition pointer at the beginning once again position = fo.seek(0, 0) str = fo.read(10) print ("Again read String is : ", str) fo.close() os.rename("foo.txt","oof.txt")
file = open('mydata.txt', 'r') file1 = open('newfile.txt', 'w') # writes data to the file (ensure the file is created) file1.write("Something ") file1.write("good gonna happen. ") # a - indicates append to existing file file1 = open('newfile.txt', 'a') file1.write("Good for every one")
n = int(input("Ingresa un numero: ")) acc = 1 i = 1 while i <= n: acc = acc*i i += 1 print("El factorial es: " + str(acc)) # Alternative: recursion
##Dado un monto en soles, conviértelo a dólares y a euros. monto = input('Ingresa un monto \n') monto = float(monto) monto_dol = monto*3.30 monto_eur = monto*3.88 print("El monto ingresado en dolares es: "+str(monto_dol) +" \n") print("El monto ingresado en euros es: "+str(monto_eur))
n = int(input("Ingresa el primer numero: ")) m = int(input("Ingresa el segundo numero: ")) while n <= m: if n%2 == 0: print(n) n += 1
monto = input("Ingresa el monto: ") cambio_dolares = 3.2 cambio_euros = 4.7 a_dolares = cambio_dolares * float(monto) a_euros = cambio_euros * float(monto) print("Tu monto en dolares es: {0}".format(a_dolares)) print("Tu monto en euros es: {0}".format(a_euros))