text
stringlengths
37
1.41M
#the code for ultrasonic sensor is adapted from "https://gist.github.com/eyllanesc/f8464b57e091777a5aef48fdd9ea9067" import RPi.GPIO as GPIO import time from datetime import datetime # from datetime import date class ProjectTwo(object): "the class for the project to meausre the distance and based on teh distance meaured it stores the date" def __init__(self): GPIO.setwarnings(False) self.TRIG = 18 #defining the pins self.ECHO = 24 #defining the pins GPIO.setmode(GPIO.BCM) GPIO.setup(self.TRIG, GPIO.OUT) GPIO.setup(self.ECHO, GPIO.IN) self.distance = 0 self.myfile = open("indreswaranl.csv", "a+") #to create a csv file #self.myfile.write("Date" + ","+"Time"+","+"\n")# to name the rows def find_distance(self): isRunning = True GPIO.output(self.TRIG, False) time.sleep(.8) GPIO.output(self.TRIG, True) time.sleep(0.00001) GPIO.output(self.TRIG, False) while GPIO.input(self.ECHO) == 0: pulse_start = time.time() #measuring the time while GPIO.input(self.ECHO) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start #time taken for the echo to reach self.distance = pulse_duration * 17150 #changing the time to distance self.distance = round(self.distance, 2) #rounding of the decimal to two decimal #print (self.distance) #return self.distance def write_file(self): #for creating a file and storing data #due to the location where we placed the pi, the sound waves always reach the wall which is 97cm away from the pi and considering the door can #not be opened neyod a certain distnce we wanted to filter the data below 89cm if self.distance < 89: #for our project, we want to store the data only when the distance meaured by the #sensor is less than 89cm so that we know people entered the restroom. #we are using 5cm here self.myfile.write (str(date.today())+ "," + str(datetime.time(datetime.now())) + "," + "\n")# save the data in the file created above in two columns self.myfile.close() def main(): while True: dist = ProjectTwo() dist.find_distance() dist.write_file() GPIO.cleanup() main()
import pandas as pd import numpy as np df = pd.read_csv('carbonemissiondata.csv') list_of_lists = df.values.tolist() my_formatted_list = [[np.round(float(i), 3) for i in nested] for nested in list_of_lists] print(my_formatted_list)
#! /usr/bin/env python3 import argparse import os import re import sys from datetime import datetime from datetime import datetime import os def input_to_python(date_input): return date_input.replace('YYYY', '%Y').replace('YY', '%y').replace('MM', '%m').replace('DD', '%d') def input_to_regex(date_input): return re.compile(date_input.replace('YYYY', r'\d{4}').replace('YY', r'\d{2}').replace('MM', r'\d{2}').replace('DD', r'\d{2}')) def convert_date_format(filename, old_format, new_format): """ Converts the date format in a filename from old_format to new_format. Args: filename (str): The filename to be converted. old_format (str): The current date format in the filename. new_format (str): The desired date format in the filename. Returns: str: The new filename with the date format converted. """ old_regex = input_to_regex(old_format) match = re.match(old_regex, filename) if match: date_str = match.group(0) try: date_obj = datetime.strptime(date_str, input_to_python(old_format)) if date_str != datetime.strftime(date_obj, input_to_python(old_format)): raise ValueError('Date format does not match input format.') except ValueError: print(f"Error: {old_regex} does not match the format {input_to_python(old_format)}. Skipping file {filename}.") # print(f"Error: {old_regex};{date_str};{input_to_python(old_format)};{date_obj};{filename}.") return filename new_date_str = datetime.strftime(date_obj, input_to_python(new_format)) new_filename = filename.replace(date_str, new_date_str, 1) return new_filename return filename def get_renamings(directory_path, old_format, new_format): renamings = {} for filename in os.listdir(directory_path): new_filename = convert_date_format(filename, old_format, new_format) if new_filename != filename: renamings[filename] = new_filename return renamings def apply_renamings(directory_path, renamings): """ Applies the renamings to the files in the specified directory. Args: directory_path (str): The path to the directory containing the files to be renamed. renamings (dict): A dictionary of renamings to be made, mapping old filenames to new filenames. Returns: None """ for old_filename, new_filename in renamings.items(): old_path = os.path.join(directory_path, old_filename) new_path = os.path.join(directory_path, new_filename) os.rename(old_path, new_path) def rename_files_in_directory(directory_path, old_format, new_format, ask_for_consent = True): """ Renames all files in a directory whose filename starts with the expected date pattern. Args: directory_path (str): The path to the directory containing the files to be renamed. old_format (str): The current date format in the filename. new_format (str): The desired date format in the filename. ask_for_consent (bool): If False, skips user input prompt and renames files directly Returns: None """ print("Renaming matching files in directory: " + directory_path) renamings = get_renamings(directory_path, old_format, new_format) if not renamings: print("No files to rename.") return print("Renaming the following files:") for old_filename, new_filename in renamings.items(): print(f"{old_filename} -> {new_filename}") if ask_for_consent: confirmation = input("Do you want to proceed with the renaming? (Y/N) ").strip().lower() if confirmation != 'y': print("Renaming aborted.") return apply_renamings(directory_path, renamings) print("Renaming complete.") if __name__ == '__main__': parser = argparse.ArgumentParser(description='Rename files with date format in filename.') parser.add_argument('old_format', metavar='old_format', type=str, help='the current date format in the filename') parser.add_argument('new_format', metavar='new_format', type=str, help='the desired date format in the filename') args = parser.parse_args() directory_path = os.path.abspath(os.path.curdir) old_format = args.old_format new_format = args.new_format rename_files_in_directory(directory_path, old_format, new_format)
import simple_draw as sd def rainbow(point, radius, step): rainbow_colors = (sd.COLOR_RED, sd.COLOR_ORANGE, sd.COLOR_YELLOW, sd.COLOR_GREEN, sd.COLOR_CYAN, sd.COLOR_BLUE, sd.COLOR_PURPLE) for i in rainbow_colors: radius += step sd.circle(center_position=point, radius=radius, width=10, color=i)
# -*- coding: utf-8 -*- # Вывести на консоль жителей комнат (модули room_1 и room_2) # Формат: В комнате room_1 живут: ... from room_1 import folks as room1 from room_2 import folks as room2 print('В комнате room_1 живут: ', ' , '.join(room1)) print('В комнате room_2 живут: ', ' , '.join(room2))
a = input("input:") print(a) print("a""b""c") print("a"+"b"+"c") print("a","b","c") #콤마는 띄어쓰기 for i in range(1,11): print(i,end=' ')
def sumall(*args): sum = 0 for i in args: sum += i return sum result = sumall(3,4,5,6,7) print(result) result = sumall(1,2,3) print(result) def summul(choice, *args): if choice == "sum": result = 0 for i in args: result += i elif choice == "mul": result = 1 for i in args: result *= i else: result = 0 return result result = summul('sum',1,2,3,4,5,6,7) print(result) result = summul('sum',1,2,3) print(result) result = summul('mul',1,2,3) print(result) result = summul('mul',1,2,3,4,5) print(result) def sumandmul(a,b): return a+b,a*b result = sumandmul(3,4) #결과를 여러개 돌려줄수도 있다. => 튜플로 값이 묶인다. print(result) num1, num2 = sumandmul(5,6) #따로 따로 받고 싶으면 이렇게 받으면 된다. print(num1, num2) def ret2summul(a,b): return a+b return a*b result = ret2summul(3,4) print(result) # a+b만 리턴된다. a*b는 실행되지 않는다.
from enum import Enum class Color(Enum): red = 1 green = 2 blue = 3 Color2 = Enum('Color2','red green blue') print(Color.blue.name) print(Color.blue.value)
""" Created on Sat Nov 24 19:45:24 2018 @author: chetanbommu """ ## Importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt ## Importing dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values ## Splitting dataset into training and testing set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) ## Feature Scaling => Some algorithms doesn't need feature scaling, since algorithm itself does feature scaling for us """ from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.fit_transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train) """ ## Fitting Simple Linear Regresion to the training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() ## No Compulsory Parameters regressor.fit(X_train, y_train) ## Predicting the test set results y_pred = regressor.predict(X_test) ## Visualising the Training set results plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title("Salary vs Experience (Train set)") plt.xlabel("Experience in years") plt.ylabel("Salary in $") plt.show() ## Visualising the Test set results plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title("Salary vs Experience (Test set)") plt.xlabel("Experience in years") plt.ylabel("Salary in $") plt.show()
class first(): def __init__(self): self.__a = 100 def getters(self): print("val of a",self.__a) def setters(self,val): self.__a = val f = first() f.getters() print("Now changed outside the class") f.__a = -100 f.getters() print("Now changing inside the class") f.setters(-100) f.getters()
from collections import defaultdict import re import unicodedata import inflect class Preprocessor(object): ''' A class containing methods for preprocessing a sentence. ''' def remove_non_ascii(self, words): """Remove non-ASCII characters from list of tokenized words""" new_words = [] for word in words: new_word = unicodedata.normalize('NFKD', word).encode( 'ascii', 'ignore').decode('utf-8', 'ignore') new_words.append(new_word) return new_words def to_lowercase(self, words): """Convert all characters to lowercase from list of tokenized words""" new_words = [] for word in words: new_word = word.lower() new_words.append(new_word) return new_words def remove_punctuation(self, words): """Remove punctuation from list of tokenized words""" new_words = [] for word in words: new_word = re.sub(r'[^\w\s]', '', word) if new_word != '': new_words.append(new_word) return new_words def split_punctuation(self, words): new_words = [] for word in words: if word[-1] == '.' or word[-1] == '?' or word[-1] == '!': punc = word[-1] word = word[:-1] new_words.append(word) new_words.append(punc) else: new_words.append(word) return new_words def replace_numbers(self, words): """Replace all interger occurrences in list of tokenized words with textual representation""" p = inflect.engine() new_words = [] for word in words: if word.isdigit(): new_word = p.number_to_words(word) new_words.append(new_word) else: new_words.append(word) return new_words def add_eos(self, words): '''Appends <eos> at the end of a sentence''' words_copy = words.copy() words_copy.append('<eos>') return words_copy def add_sos(self, words): '''Prepends <sos> at the beginning of a sentence''' words_copy = words.copy() words_copy.insert(0, '<sos>') return words_copy def preprocess_sentence(self, sentence, eos=False, sos=False): '''Performs preprocessing on sentence''' sentence_array = sentence.split(' ') sentence_array = self.to_lowercase(sentence_array) sentence_array = self.remove_punctuation(sentence_array) sentence_array = self.split_punctuation(sentence_array) sentence_array = self.replace_numbers(sentence_array) if eos: sentence_array = self.add_eos(sentence_array) if sos: sentence_array = self.add_sos(sentence_array) sentence = ' '.join(sentence_array) return sentence class Language(object): ''' A class that contains methods to contain the vocabulary of a language and convert written sentences into a format that can be read by a machine learning algorithm ''' def __init__(self, name): ''' Arguments: name: the name of the language ''' self.name = name self.word2idx = {'<sos>': 0, '<eos>': 1, '<unk>': 2, '<pad>': 3} self.idx2word = {0: '<sos>', 1: '<eos>', 2: '<unk>', 3: '<pad>'} self.word_counter = 4 self.word_frequency = defaultdict(int) def sentence_to_idx(self, sentence): ''' Converts sentence in language of interest into index form. Arguments: sentence: a sentence in the language of interest Returns: indices: the sentence transformed into indices ''' indices = [] for word in sentence.split(' '): try: idx = self.word2idx[word] except(KeyError): idx = self.word2idx['<unk>'] indices.append(idx) return indices def idx_to_sentence(self, indices): ''' Converts sentence in index form back into a language of interest. Arguments: indices: a sentence in index form Returns: sentence: the sentence in language of interest ''' sentence = [] for index in indices: word = self.idx2word[index] sentence.append(word) return sentence def index_words(self): ''' Assigns a unique index to each word in the vocabulary of the top n words. ''' for word in self.top_words: if word not in self.word2idx.keys(): self.word2idx[word] = self.word_counter self.idx2word[self.word_counter] = word self.word_counter += 1 def count_words(self, sentence): ''' For each word in a sentence, adds to a counter for the frequency of that word. Arguments: sentence: a sentence in language of interest ''' for word in sentence.split(' '): self.count_word(word) def count_word(self, word): ''' Adds to a counter counting the frequency of a specific word. Arguments: word: a word in a language of interest ''' self.word_frequency[word] += 1 def top_n_words(self, n): ''' Calculates a list of the top n words in the language of interest sorted by frequency. Arguments: n: the number of top words to consider. Returns: sorted_words: a sorted list of top n words ''' sorted_freq_words = list( sorted(self.word_frequency.items(), key=lambda kv: kv[1], reverse=True))[:n] sorted_words = list(map(lambda x: x[0], sorted_freq_words)) self.top_words = sorted_words return sorted_words def vocab_size(self): ''' Returns the vocabulary size of your language of interest. ''' return len(list(self.word2idx.keys()))
# #!/usr/bin/python # # -*- coding: utf-8 -*- # from time import time, sleep # def deco(func): # def wrapper(): # start_time = time() # print "start time = %s" %start_time # func() # # sleep(1) # print "end time = %s, %s runs %s seconds." %(time(), func, time() - start_time) # return wrapper # def deco2(func): # def wrapper(a, b): # start_time = time() # print "start time = %s" %start_time # x = func(a, b) # # sleep(1) # print "end time = %s, %s runs %s seconds." %(time(), func, time() - start_time) # return x # return wrapper # def deco3(args): # def deco(func): # def wrapper(a, b): # print "before %s called [%s]." % (func.__name__, args) # func(a, b) # # sleep(1) # print "after %s called [%s]." % (func.__name__, args) # return wrapper # return deco # @deco # def test(): # print "This is a test message." # @deco2 # def test2(a, b): # print "test2 mesg : {0} + {1} = {2}.".format(a, b, a + b) # return a + b # @deco2 # @deco3("module") # def test3(a, b): # print "test3 mesg : {0} * {1} = {2}.".format(a, b, a * b) # return a * b # def main(): # # test() # # test2(1,2) # # test2(2,3) # # test3(2,5) # test3(3,5) # if __name__ == '__main__': # main() def dec1(func): print "inner dec1" def one(): print "before {} called".format(func.__name__) func() print "after {} called".format(func.__name__) return func print "still in dec1" return one def dec2(func): print "inner dec2" def two(): print "inner dec2.two" print "before {} called".format(func.__name__) func() print "after {} called".format(func.__name__) return func print "still in dec2" return two @dec1 @dec2 def test(): print "inner test" # 执行test() test() ''' 多重装饰器进行装饰函数时,自下而上执行。 但是下层的装饰器的装饰体并不执行,而是直接把该函数返回给上层装饰器,当做上层装饰器的函数参数。 依次类推,直到最上层装饰器开始执行装饰体,再一层一层向下执行,直到内层装饰体执行完毕,被装饰的函数体也执行完毕, 依次返回给上层装饰器继续执行上层装饰器剩下的部分。 ''' print("===============================") def wrapClass(cls): print "inside wrapClass" def inner(a): print 'class name: %s' %cls.__name__ return cls(a) print "after inner" return inner @wrapClass class Foo(): def __init__(self, a): self.a = a print "init Foo" def fun(self): print 'self.a = %s' %self.a m = Foo('xiemanR') m.fun() print "=========================" def deco(func): print("before myfunc() called.") func() print(" after myfunc() called.") return func # deco = deco(myfunc) @deco def myfunc(): print(" myfunc() called.") myfunc() myfunc() print "==================" def foo(): class Foo(object): """docstring for ClassName""" def __init__(self): print "inner class" def bar(self): print "bar" print "end Foo class" a = Foo() a.bar() print "a = %s,type Foo: %s"%(a.__class__.__name__,type(a)) print "end foo" print "==============================" def dec(func): a = 100 def wrapper(*args, **kwargs): print "auth1" # func() return func(*args, **kwargs) return wrapper # print "auth2" # return func @dec def foo1(a,b,c): print a+b+c print "inner foo1" b = foo1(1,2,3) print b foo1(2,3,4) print "=======================" def foo2(x,y): return x+y print map(foo2,[1,2,3,4], [1,1,1,1]) # print map(foo2, [1,2,3,4], ['a','b','c']) from functools import reduce print reduce(lambda x,y: x+y, [1,2,3,4,5], 100) def str2int(s): seq = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return reduce(lambda x,y: 10*x + y, map(lambda x: seq[x], s)) print str2int('12345') print int('123456') def normalize(name): return name.capitalize() # return map(lambda name: name[:1].upper()+name[1:].lower(), name) L = ['adam', 'LISA', 'barT'] # print normalize(L) print list(map(normalize, L)) def prod(L): return reduce(lambda x,y: x*y, L) print '3 * 5 * 7 * 9 =%s'%prod([3, 5, 7, 9]) def str2float(s): seq = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} # 小数点之前 if "." in s: s1 = s.split('.')[0] # 小数点之后 s2 = s.split('.')[1] return reduce(lambda x,y: 10.0*x+y, map(lambda z: seq[z], s1+s2))/(10**(len(s2))) else: return reduce(lambda x,y: 10.0*x+y, map(lambda z: seq[z], s)) print str2float('12345678') def is_palindrome(n): return str(n) == str(n)[::-1] print filter(is_palindrome, range(1, 200)) dict1 = {"a1":"a11", "a2":"a22"} dict2 = {"c1":"c11", "d2":"d22"} # dict1.update(dict2) # print dict1 d3 = {} d3.update(dict1) d3.update(dict2) print d3
from player import Player from gesture import Gesture import random class Computer(Player): def __init__(self): super().__init__() def pvp(self): print("Choose a gesture!") print(Gesture().gestures) self.choice_1 = int(input("Player One Enter Choice: ")) while self.choice_1 != 0 and self.choice_1 != 1 and self.choice_1 != 2 and self.choice_1 != 3 and self.choice_1 != 4: print("Invalid input please try again") self.choice_1 = int(input("Player 1 chose: ")) self.choice_2 = get_random_number(0, 4) print("") print(f"Player 1 chooses {Gesture().gestures[self.choice_1]}") print(f"Computer chooses {Gesture().gestures[self.choice_2]}") print("") return self.choice_1, self.choice_2 def random_number(min_value, max_value): return random.randint(min_value, max_value) def get_random_number(num_1, num_2): random_int = random_number(num_1, num_2) return random_int
from tkinter import * # from NLP_FINAL import XYZ insertSentencesWindow = Tk() insertSentencesWindow.title("Welcome to project number 18") insertSentencesWindow.geometry('450x400') # State numberOfEnteredSentences = 0 S1 = [] S2 = [] # Insert sentences layout string variables instructionsLabelStringVariable = StringVar() instructionsLabelStringVariable.set("Enter first sentence") #resultLabelStringVariable = StringVar() sentenceInputEntryStringVariable = StringVar() # This variable will contain what ever the user has typed into the input field #result = StringVar() # Public functions def getSentences(): global S1, S2 return [S1, S2] # Callbacks def submitCallback(): # This function will get called when user presses the global numberOfEnteredSentences, S1, S2 numberOfEnteredSentences = numberOfEnteredSentences + 1 enteredSentence = sentenceInputEntryStringVariable.get() if numberOfEnteredSentences == 1: S1 = enteredSentence #submitButton = Button(insertSentencesWindow, text= "Process") elif numberOfEnteredSentences == 2: S2 = enteredSentence sentenceInputEntryStringVariable.set("") # Clear the input field instructionsLabelStringVariable.set("Enter second sentence") # Update instructions if numberOfEnteredSentences == 2: # Line below is mock functionality: we should query the api here and then update the result resultLabelStringVariable #result.set("test: ") #resultLabelStringVariable.set("blaablaa") insertSentencesWindow.destroy() # removeInsertSentencesLayout() # displayResultsLayout() # Insert sentences layout elements instructionLabel = Label(insertSentencesWindow, textvariable=instructionsLabelStringVariable, font=("Arial Bold", 20)) sentenceInputEntry = Entry(insertSentencesWindow, textvariable=sentenceInputEntryStringVariable) #resultLabel2 = Label(insertSentencesWindow, textvariable=result) #resultLabel = Label(insertSentencesWindow, textvariable=resultLabelStringVariable) submitButton = Button(insertSentencesWindow, text= "submit", width='10', height = '20', command=submitCallback, fg='red') def displayInsertSentencesLayout(): instructionLabel.grid(column=3, row=0) #instructionLabel.pack() sentenceInputEntry.grid(column=3, row=1) sentenceInputEntry.focus() #sentenceInputEntry.pack() #resultLabel2.pack() #resultLabel2.grid(column=2, row=0) #resultLabel.grid(column=3, row=0) #resultLabel.pack() submitButton.grid(column=3, row=3) #submitButton.pack() insertSentencesWindow.mainloop() # def removeInsertSentencesLayout(): # instructionLabel.grid_forget() # sentenceInputEntry.grid_forget() # #resultLabel2.grid_forget() # #resultLabel.grid_forget() # submitButton.grid_forget() def displayResultsLayout(firstSentence, secondSentence, jaccardResult, ExjaccardResult, wordNetResult, wikiSimilarity): # Update labels # resultsFirstSentenceStringVariable.set(S1) # resultsSecondSentenceStringVariable.set(S2) # set variables here############ # Setup window resultsWindow = Tk() resultsWindow.title("Welcome to project number 18") resultsWindow.geometry('1000x1000') # Layout elements Label(resultsWindow, text="Sentence 1", font=("Arial Bold", 20)).grid(row=0, column=0) Label(resultsWindow, text="Sentence 2", font=("Arial Bold", 20)).grid(row=0, column=1) Label(resultsWindow, text=firstSentence).grid(row=1, column=0) Label(resultsWindow, text=secondSentence).grid(row=1, column=1) # Label(resultsWindow, text="Snippets", font=("Arial Bold", 20)).grid(row=2, column=0) # Label(resultsWindow, text=firstSnippet).grid(row=3, column=0) # Label(resultsWindow, text=secondSnippet).grid(row=3, column=1) Label(resultsWindow, text="Jaccard similarity", font=("Arial Bold", 20)).grid(row=2, column=0) Label(resultsWindow, text=jaccardResult).grid(row=3, column=0) Label(resultsWindow, text="Expand Jaccard similarity", font=("Arial Bold", 20)).grid(row=4, column=0) Label(resultsWindow, text=ExjaccardResult).grid(row=5, column=0) Label(resultsWindow, text="WordNet similarity", font=("Arial Bold", 20)).grid(row=6, column=0) Label(resultsWindow, text=wordNetResult).grid(row=7, column=0) Label(resultsWindow, text="Wiki similarity", font=("Arial Bold", 20)).grid(row=8, column=0) Label(resultsWindow, text=wikiSimilarity).grid(row=9, column=0) resultsWindow.mainloop()
import matplotlib.pyplot as plt import numpy as np def generate_city_populations(num_cities, population_range): # Generate city populations following Zipf's Law ranks = np.arange(1, num_cities + 1) populations = np.round(population_range[0] / (ranks ** 0.8)) return populations def calculate_concentration_index(city_populations, num_selected_cities): # Calculate the concentration index based on the population distribution sorted_populations = np.sort(city_populations)[::-1] selected_populations = sorted_populations[:num_selected_cities] total_population = np.sum(sorted_populations) selected_population = np.sum(selected_populations) concentration_index = selected_population / total_population return concentration_index def plot_population_distribution(city_populations): # Plot the population distribution ranks = np.arange(1, len(city_populations) + 1) plt.scatter(ranks, city_populations, color='blue') plt.xlabel('Rank') plt.ylabel('Population') plt.title('Population Distribution of Cities') plt.show() # Parameters num_cities = 1000 population_range = (100000, 10000000) num_selected_cities = 10 # Generate city populations based on Zipf's Law city_populations = generate_city_populations(num_cities, population_range) # Plot the population distribution plot_population_distribution(city_populations) # Calculate the concentration index concentration_index = calculate_concentration_index(city_populations, num_selected_cities) print(f"Concentration Index: {concentration_index}")
import networkx as nx import matplotlib.pyplot as plt # Number of nodes in the initial network m0 = 5 # Number of edges to attach from a new node to existing nodes m = 2 # Create an empty graph ba_network = nx.Graph() # Add the initial nodes to the graph ba_network.add_nodes_from(range(m0)) # Iterate to add new nodes with preferential attachment for i in range(m0, 50): # Select m nodes from the existing network to which the new node will connect selected_nodes = list(ba_network.nodes()) new_edges = [] # Perform preferential attachment by connecting the new node to existing nodes while len(new_edges) < m: selected_node = nx.utils.random.choice(selected_nodes) if not ba_network.has_edge(i, selected_node): new_edges.append((i, selected_node)) # Add the new edges to the graph ba_network.add_edges_from(new_edges) # Print the degree of each node in the generated Barabási–Albert network print("Node\tDegree") for node, degree in ba_network.degree(): print(node, "\t", degree) # Draw the network graph nx.draw(ba_network, with_labels=True, node_size=200, alpha=0.8) plt.title("Barabási–Albert Network") plt.show()
''' A python implementation of the Earthmover distance metric. ''' import math from collections import Counter from collections import defaultdict from ortools.linear_solver import pywraplp def euclidean_distance(x, y): return math.sqrt(sum((a - b)**2 for (a, b) in zip(x, y))) def earthmover_distance(p1, p2): ''' Output the Earthmover distance between the two given points. Arguments: - p1: an iterable of hashable iterables of numbers (i.e., list of tuples) - p2: an iterable of hashable iterables of numbers (i.e., list of tuples) ''' dist1 = {x: count / len(p1) for (x, count) in Counter(p1).items()} dist2 = {x: count / len(p2) for (x, count) in Counter(p2).items()} solver = pywraplp.Solver('earthmover_distance', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING) variables = dict() # for each pile in dist1, the constraint that says all the dirt must leave this pile dirt_leaving_constraints = defaultdict(lambda: 0) # for each hole in dist2, the constraint that says this hole must be filled dirt_filling_constraints = defaultdict(lambda: 0) # the objective objective = solver.Objective() objective.SetMinimization() for (x, dirt_at_x) in dist1.items(): for (y, capacity_of_y) in dist2.items(): amount_to_move_x_y = solver.NumVar(0, solver.infinity(), 'z_{%s, %s}' % (x, y)) variables[(x, y)] = amount_to_move_x_y dirt_leaving_constraints[x] += amount_to_move_x_y dirt_filling_constraints[y] += amount_to_move_x_y objective.SetCoefficient(amount_to_move_x_y, euclidean_distance(x, y)) for x, linear_combination in dirt_leaving_constraints.items(): solver.Add(linear_combination == dist1[x]) for y, linear_combination in dirt_filling_constraints.items(): solver.Add(linear_combination == dist2[y]) status = solver.Solve() if status not in [solver.OPTIMAL, solver.FEASIBLE]: raise Exception('Unable to find feasible solution') for ((x, y), variable) in variables.items(): if variable.solution_value() != 0: cost = euclidean_distance(x, y) * variable.solution_value() print("move {} dirt from {} to {} for a cost of {}".format( variable.solution_value(), x, y, cost)) return objective.Value() if __name__ == "__main__": p1 = [ (0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), ] p2 = [ (0, 0), (0, 2), (0, -2), (2, 0), (-2, 0), ] print(earthmover_distance(p1, p2))
from collections import deque, namedtuple Vertex = namedtuple('Vertex', ['name', 'incoming', 'outgoing']) def build_doubly_linked_graph(graph): """ Given a graph with only outgoing edges, build a graph with incoming and outgoing edges. The returned graph will be a dictionary mapping vertex to a Vertex namedtuple with sets of incoming and outgoing vertices. """ g = {v:Vertex(name=v, incoming=set(), outgoing=set(o)) for v, o in graph.items()} for v in g.values(): for w in v.outgoing: if w in g: g[w].incoming.add(v.name) else: g[w] = Vertex(name=w, incoming={v}, outgoing=set()) return g def kahn_top_sort(graph): """ Given an acyclic directed graph (format described below), returns a dictionary mapping vertex to sequence such that sorting by the sequence component will result in a topological sort of the input graph. Output is undefined if input is a not a valid DAG. The graph parameter is expected to be a dictionary mapping each vertex to a list of vertices indicating outgoing edges. For example if vertex v has outgoing edges to u and w we have graph[v] = [u, w]. """ g = build_doubly_linked_graph(graph) # sequence[v] < sequence[w] implies v should be before w in the topological # sort. q = deque(v.name for v in g.values() if not v.incoming) sequence = {v: 0 for v in q} while q: v = q.popleft() for w in g[v].outgoing: g[w].incoming.remove(v) if not g[w].incoming: sequence[w] = sequence[v] + 1 q.append(w) return sequence #And the accompanied unit test: import unittest class KahnTopSortTest(unittest.TestCase): def test_single_vertex(self): graph = { 0: [], } self.assertEqual(kahn_top_sort(graph), { 0: 0, }) def test_total_order_2(self): graph = { 0: [1], 1: [], } self.assertEqual(kahn_top_sort(graph), { 0: 0, 1: 1, }) def test_total_order_3(self): graph = { 0: [1], 1: [2], 2: [], } self.assertEqual(kahn_top_sort(graph), { 0: 0, 1: 1, 2: 2, }) def test_two_independent_total_orders(self): # 0 -> 1 -> 2 # 3 -> 4 -> 5 graph = { 0: [1], 1: [2], 2: [], 3: [4], 4: [5], 5: [], } self.assertEqual(kahn_top_sort(graph), { 0: 0, 3: 0, 1: 1, 4: 1, 2: 2, 5: 2, }) def test_simple_dag_1(self): # 0 -> 1 -> 2 # \ / # 3 graph = { 0: [1, 3], 1: [2], 2: [], 3: [1], } self.assertEqual(kahn_top_sort(graph), { 0: 0, 3: 1, 1: 2, 2: 3, })
from collections import namedtuple, defaultdict from Queue import PriorityQueue Edge = namedtuple('Edge', ['target', 'weight']) def dijkstra(graph, source, target): """ Given a directed graph (format described below), and source and target vertices, returns a shortest path as a list of vertices going from source to target, along with the distance of the shortest path, or None if no such path exists. Returned path will not include the source vertex in it. Assumes non-negative weights. The graph parameter is expected to be a dictionary mapping each vertex to a list of Edge named tuples indicating the vertex's outgoing edges. For example if vertex v has outgoing edges to u and w with weights 10 and 20 respectively, we have graph[v] = [Edge(u, 10), Edge(w, 20)]. """ q = PriorityQueue() q.put((0, source)) # previous_vertex[v] holds the immediate vertex before v in the shortest # path from source to v. This dictionary also acts as our "visited" set # since we set previous_vertex[v] as soon as the vertex enters our queue. previous_vertex = {source: source} # Arguably not the best way to represent infinity but it works for the sake # of learning the algorithm. shortest_distance = defaultdict(lambda: float('inf')) shortest_distance[source] = 0 while not q.empty(): (distance, v) = q.get() if v == target: return (distance, _construct_path(previous_vertex, source, target)) for edge in graph[v]: alt_distance = edge.weight + distance if alt_distance < shortest_distance[edge.target]: shortest_distance[edge.target] = alt_distance q.put((alt_distance, edge.target)) previous_vertex[edge.target] = v return None def _construct_path(previous_vertex, source, target): if source == target: return [] return _construct_path(previous_vertex, source, previous_vertex[target]) + [target] import unittest class DijkstraTest(unittest.TestCase): def test_single_vertex(self): graph = {0: []} self.assertEqual(dijkstra(graph, 0, 0), (0, [])) def test_two_vertices_no_path(self): graph = { 0: [], 1: [], } self.assertEqual(dijkstra(graph, 0, 1), None) def test_two_vertices_with_path(self): graph = { 0: [Edge(target=1, weight=10)], 1: [], } self.assertEqual(dijkstra(graph, 0, 1), (10, [1])) def test_cycle_3(self): graph = { 0: [Edge(target=1, weight=10), Edge(target=2, weight=30)], 1: [Edge(target=0, weight=10), Edge(target=2, weight=10)], 2: [Edge(target=0, weight=30), Edge(target=1, weight=30)], } self.assertEqual(dijkstra(graph, 0, 2), (20, [1, 2])) def test_clrs_example(self): graph = { 's': [ Edge(target='t', weight=3), Edge(target='y', weight=5), ], 't': [ Edge(target='x', weight=6), Edge(target='y', weight=2), ], 'y': [ Edge(target='t', weight=1), Edge(target='z', weight=6), ], 'x': [ Edge(target='z', weight=2), ], 'z': [ Edge(target='x', weight=7), Edge(target='s', weight=3), ], } distance, path = dijkstra(graph, 's', 'z') self.assertEqual(distance, 11) self.assertIn(path, [ ['y', 'z'], ['t', 'y', 'x', 'z'], ]) distance, path = dijkstra(graph, 's', 'x') self.assertEqual(distance, 9) self.assertIn(path, [ ['t', 'x'], ['y', 'x'], ])
from collections import namedtuple from union_find import DisjointSet # Putting weight as the first element means Edges will sort by weight first, # then source and target (lexicographically). Edge = namedtuple('Edge', ['weight', 'source', 'target']) def kruskal_mst(n, edges): """ Given a positive integer n (number of vertices) and a collection of Edge namedtuple objects representing the undirected edges of a graph, returns a list of edges forming a minimal spanning tree of the graph. Assumes the vertices are numbers in the range 0 to n - 1. Also assumes input is a valid connected undirected graph and that for two vertices v and w only one of (v, w) or (w, v) is an edge in the input. Output is undefined if these assumptions are not satisfied. """ d = DisjointSet(n) mst_tree = [] for edge in sorted(edges): if d.find(edge.source) != d.find(edge.target): mst_tree.append(edge) if len(mst_tree) == n - 1: break d.union(edge.source, edge.target) return mst_tree import unittest class KruskalMSPTest(unittest.TestCase): def test_single_vertex_graph(self): self.assertEqual(kruskal_mst(1, []), []) def test_single_edge_graph(self): edges = [Edge(source=0, target=1, weight=10)] self.assertEqual(kruskal_mst(2, edges), edges) def test_cycle_5(self): edges = [ Edge(source=0, target=1, weight=50), Edge(source=1, target=2, weight=30), Edge(source=2, target=3, weight=60), Edge(source=3, target=4, weight=20), Edge(source=4, target=0, weight=10), ] # Everything except the heaviest edge. Output sorted by weight. self.assertEqual(kruskal_mst(5, edges), [ Edge(source=4, target=0, weight=10), Edge(source=3, target=4, weight=20), Edge(source=1, target=2, weight=30), Edge(source=0, target=1, weight=50), ]) def test_complete_graph_4(self): edges = [ Edge(source=0, target=1, weight=10), Edge(source=0, target=2, weight=30), Edge(source=0, target=3, weight=40), Edge(source=1, target=2, weight=20), Edge(source=1, target=3, weight=50), Edge(source=2, target=3, weight=60), ] self.assertEqual(kruskal_mst(4, edges), [ Edge(source=0, target=1, weight=10), Edge(source=1, target=2, weight=20), Edge(source=0, target=3, weight=40), ])
#!/usr/bin/python3 # -*- coding: utf-8 -*- age = input() if int(age) >= 18: pass else: print('Child')
#!/usr/bin/python3 # -*- coding: utf-8 -*- # At range [1, 11) print([x for x in range(1, 11)]) print([x * x for x in range(1, 11)]) print([x * x for x in range(1, 11) if x % 2 == 1]) print([m + n for m in 'ABC' for n in 'XYZ']) import os print([d for d in os.listdir('.')]) L = ['Hello', 'World', 'IBM', 'Apple'] print([s.lower() for s in L])
#ques1 skrillex=['EDM','LEGEND','DUBSTEP','LEVEL'] print(skrillex) #ques2 Avicii=['google','apple','facebook','microsoft','tesla'] print(skrillex+Avicii) #ques3 number=[1,1,1,2,3,4] print(number.count(1)) #ques4 numbers=[1,2,3,6,5,4,7] numbers.sort() print(numbers) #ques5 list6=[] list1=[1,2,5,6,7] list2=[8,7,9,4] list6=list1+list2 list6.sort() print(list6) #ques6 list=[1,2,3,4,5,6,7,8,9] even=0; odd=0; for i in list: if i%2==0: even=even+1; else: odd=odd+1; print("no. of even",even) print("no.of odd",odd) #ques9 str1='i am skrillex' a=str1.upper() print(a) #ques10 txt='1234' print(txt.isnumeric()) #ques11 text='hello world' a=text.replace('hello world','hello') print(a)
slowo = str(input('Podaj slowo:')) print(slowo + ' ?? ' + slowo[::-1]) if slowo == slowo[::-1]: print('Palindrom') else: print('Gowno, a nie palindrom')
name = input ('Podaj swoje imie:') age = int ( input ('Podaj swoj wiek:') ) kopia = int (input('Podaj liczbe calkowita:')) for number in range(1,kopia+1): print('{}. Witaj {}, będziesz miał 100 lat w {} roku.'.format(number,name,2019+100-age))
s = """We encourage everyone to contribute to Python. If you still have questions after reviewing the material in this guide, then the Python Mentors group is available to help guide new contributors through the process.""".replace("," ,"").replace(".","")\ .replace("\n","").upper() words = s.split(" ") frequency = {} for word in words: count = frequency.get(word, 0) frequency[word] = count + 1 frequency_list = frequency.keys() for word in frequency_list: print(word, frequency[word])
# Notes for MidTerm THE SOFTWARE DEVELOPMENT PROCESS # 1. Analyze the Problem # Do we understand the exact problem to be solved? # 2. Determine the Specifications: # What are the inputs, outputs, and how they relate to one another? # Here we list each input, each output, and how they relate to each other # 3. Create a Design # This is the pseudocode of your program # Here we write an algorithm line by line in general English # 4. Implement the Design # Write it in Python # Here we convert the pseudocode to actual code # 5. Test/Debug the Program # 6. Maintain the Program # If you follow these steps, coding should be easier # If you skip them, it will become more challenging # 1. Analysis – the temperature is given in Celsius, but the user wants it expressed in degrees Fahrenheit. # 2. Specification- # Input – temperature in Celsius # Output – temperature in Fahrenheit # Output = 9/5 * (input) + 32 # 3. Pseudocode: # Input the temperature in degrees Celsius (call it celsius) # Calculate fahrenheit as (9/5)*celsius+32 # Output fahrenheit # 4. Now we need to implement the design in Python! # 5. And don’t forget to test and debug FUNCTIONS #PASSING PARAMETERS #convert.py def main(): Fahrenheit = eval(input("What is the Fahrenheit temperature?")) Celsius = (Fahrenheit-32) * 5 / 9 print("The temperature is", Celsius ,"degrees Celsius") main() #OR # RETURNING VALUES def main(): celsius = eval(input("What is the Celsius temperature? ")) print("The temperature is", temperature(celsius), "degrees Fahrenheit.") def temperature(C): F = (9/5) * C + 32 return F main() # Notice how the variable celsius is passed to temperature() # C in temperature() then equals celsius # F is returned exactly where temperature(celsius) has been called. # Remember! Functions should be defined before they are run! # main() cannot be placed before def main() SENTINEL LOOP WITH PRIMING READ # average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xStr = input("Enter a number (<Enter> to quit) >> ") while xStr != "": x = float(xStr) sum = sum + x count = count + 1 xStr = input("Enter a number (<Enter> to quit) >> ") print("\nThe average of the numbers is", sum / count) main() #This is an interactive loop because the user is providing input at each loop # It utilizes a sentinel “”. As long as the input entered is NOT “”, the loop continues # xStr = input("Enter a number (<Enter> to quit) >> ")is the priming read SEEDING THE LOOP AND INPUT VALIDATION # Another option is seeding the loop. # In this case an invalid value is given to begin the loop # Rather than an input() prior to the loop with the priming read # An example of this is the following # number = -1# start with an illegal value while number <= 0: # to get into the loop # number = float(input("Enter a positive number: ")) # The loop will not start until a positive number is provided # We can use this for input validation # The loop does not start until a proper input is provided # We could use this to ensure numbers are entered, words etc. FOR LOOPS WITH RANGE (): # average1.py # A program to average a set of numbers # Illustrates counted loop with accumulator def main(): n = int(input("How many numbers do you have? ")) sum = 0.0 for i in range(n): x = float(input("Enter a number >> ")) sum = sum + x print("\nThe average of the numbers is", sum / n) main() #This is a definite/counted loop because it will run through the precise number of items in the list. # In this case range(n) tells it to cycle n times from 0 to n-1 FOR LOOPS WITH A LIST []: # average1_altered.py # A program to average a set of numbers # Illustrates counted loop with accumulator def main(): sum = 0.0 count = 0 for i in [1, 2, 3, 4, 5]: sum = sum + i count = count + 1 print("\nThe average of the numbers is", sum / count) # This is a definite/counted loop because it will run through the precise number of items in the list. # In this case 5 items. # Note: It can cycle through numbers, strings of text, etc. # Whatever is in the list between commas is considered 1 item ACCUMULATOR # In both examples an accumulator was used # It was sum and count # We build up or “accumulate” a final valuE # piece by piece. # It is NOT just used for addition # We CAN have multiple accumulators in a single program IF-ELIF-ELSE STATEMENT # quadratic4.py import math def main(): print("This program finds the real solutions to a quadratic\n") a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: ")) discrim = b * b - 4 * a * c if discrim < 0: print("\nThe equation has no real roots!") elif discrim == 0: root = -b / (2 * a) print("\nThere is a double root at", root) else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2 ) main() #This version checks for errors when doing math: # quadratic5.py # A program that demonstrates exception handling import math def main(): print ("This program finds the real solutions to a quadratic\n") try: a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: ")) discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2) except ValueError: print("\nNo real roots") main() IF-ELIF-ELSE AND EXCEPTION HANDLING #A simple decision will have an # if # A two-way decision # if-else # A multi-way decision # if-elif-else, wherein all conditions that are not first or last are elif # Exception handling always uses try-except # The body is under the try condition # The exceptions are under the except conditions # You can have multiple exceptions, one for each error # Writing a general except with nothing else, will cover all exceptions not previously listed # In both sets of statements, the program will only move to the next statement, if the first is NOT True. # It will never arrive at ELSE if the condition with IF is true THE LIST DATA TYPE # >>> myList = [1, "Spam ", 4, "U"] # >>> myList[0] # 1 # >>> myList[0:2] [1, 'Spam '] >>> myList[-1] 'U' # >>> myList[2:] [4, 'U'] # Remember that we can refer to parts of a list too # Each item is the next number in the string. # An item can be a character, a number, a long string, etc. # Note this is different than a string STRING FORMATTING # >>> "Hello {0} {1}, you may have won ${2}." .format("Mr.", "Smith", 10000) # 'Hello Mr. Smith, you may have won $10000.' # >>> 'This int, {0:5}, was placed in a field of width 5'.format(7) # 'This int, 7, was placed in a field of width 5' # >>> 'This int, {0:10}, was placed in a field of width 10'.format(10) # 'This int, 10, was placed in a field of width 10' # >>> 'This float, {0:10.5}, has width 10 and precision 5.'.format(3.1415926) # 'This float, 3.1416, has width 10 and precision 5.' # >>> 'This float, {0:10.5f}, is fixed at 5 decimal places.'.format(3.1415926) # 'This float, 3.14159, is fixed at 5 decimal places.' # >>> "Compare {0}, {0:0.10}, and {0:0.10f}".format(3.14) # 'Compare 3.14, 3.14, and 3.1400000000' #Note: without the f, # the precision is based on the number of digits listed, with the f, the precise decimal is determined # If you are interested in more thorough types of formatting, you can explore on your own. STRING: HELLO BOB (8 DIGITS INCLUDING THE SPACE) # 012345678 # >>> greet = "Hello Bob" # >>> greet[0] 'H' # >>> greet[0:3] 'Hel' # >>> greet[5:9] ' Bob' # >>> greet[:5] 'Hello' # >>> greet[5:] ' Bob' # >>> greet[-3] 'B' PYTHON VS MATHEMATICS ---- MEANING < < Less than <= ≤ Less than or equal to == = Equal to >= ≥ Greater than or equal to > > Greater than != ≠ Not equal to
import networkx as nx import matplotlib.pyplot as plt import random #Distribution graph for Erdos_Renyi model. def distribution_graph(g): print(nx.degree(g)) all_node_degree = list(dict((nx.degree(g))).values()) unique_degree = list(set(all_node_degree)) unique_degree.sort() nodes_with_degree = [] for i in unique_degree: nodes_with_degree.append(all_node_degree.count(i)) plt.plot(unique_degree, nodes_with_degree) plt.xlabel("Degrees") plt.ylabel("No. of nodes") plt.title("Degree distribution") plt.show() # 1. Take N number of nodes from user. print("Enter number of nodes") N = int(input()) # 2. Take P probability value for edges. print("Enter value of probability of every node") P = float(input()) # 3. Create a empty graph. g = nx.Graph() # 4. Add nodes to it. g.add_nodes_from(range(1, N + 1)) # 5. Add edges to the graph randomly. for i in g.nodes(): for j in g.nodes(): if (i < j): # 6. Take random number R. R = random.random() # 7. Check if R<P add the edge to the graph else ignore. if (R < P): g.add_edge(i, j) pos=nx.circular_layout(g) nx.draw(g,pos,with_labels=1) plt.show() distribution_graph(g)
import json import os def read_json(f): if isinstance(f, str): # If it refers to a filename, need to open and use ``json.load`` if os.path.exists(f): with open(f, 'r', encoding='utf-8') as f: return json.load(f) # Support for filename input which lacks the `.json` extension if not f.lower().endswith('.json') and os.path.exists(f + '.json'): return JSON(f + '.json') # Assume `str` input is raw JSON return json.loads(f) # Assume `f` refers to a file-like object return json.load(f)
prime_list = [2] def check_prime(n): for x in prime_list: if n % x == 0: return False return True n, m = map(int, input().split()) for i in range(3, m+1): if check_prime(i): prime_list.append(i) if i > n: print(i)
from datetime import datetime from typing import Callable """ Annotated experiments on decorators. Beware: using with no arguments, as in @dec a decorator that expects arguments, as in @dec(args), breaks your code. The correct syntax if you want to pass no arguments to such a decorator is @dec(). practical use of decorators can be, for example, for timing, logging, error check, type check... See example1() for an implementation of chained decorators with or without arguments. See example2() for a practical example of a function call log implemented via decorators. """ def example1(): """Three chained decorators: * format result into a string (no arguments) * execute n times (one argument) * add documentation (one argument with default) """ def doc_dec(doc='no document'): def doc_dec(f): # wrapper 1: arguments from enclosing dec, receives function def doc_dec_wrapper(*args, **kwargs): # wrapper 2: receives function args return f(*args, **kwargs) doc_dec_wrapper.__doc__ = doc return doc_dec_wrapper return doc_dec def outer_dec(n): # used with arguments: receives arguments def outer_dec(f): # wrapper 1: arguments from enclosing dec, receives function def outer_dec_wrapper(*args, **kwargs): # wrapper 2: receives function args result = [] for _ in range(n): result.append(f(*args, **kwargs)) return 'outer_dec ' + str(result) return outer_dec_wrapper return outer_dec def inner_dec(f): # used with no arguments, receives the function def inner_wrapper(*args, **kwargs): return 'inner_dec: "' + str(f(*args, **kwargs) + '"') return inner_wrapper @doc_dec('My function documentation') @outer_dec(2) @inner_dec def my_f(n): return(f'my_f = {n}') print(f'Docstring for my_f: {my_f.__doc__}') print(my_f(42)) def example2(): def log_decorator(logfilename='functions.log'): def open_file_and_run(f: Callable): logfile = open(logfilename,'a') def log_execution(*args, **kwargs): time_start = datetime.now() try: exception = False result = f(*args, **kwargs) except Exception as exc: exception = True result = exc finally: time_end = datetime.now() logfile.write( f'''\n{str(time_start)} function call: {f.__module__}.{f.__name__} args: {args} kwargs: {kwargs} end time: {str(time_end)} elapsed: {str(time_end - time_start)} ''') if exception: logfile.write( f'''\tRAISED EXCEPTION \tof type {type(result)} \targs: {repr(result.args)} ''') else: logfile.write(f'function returned: {type(result)}, value: {repr(result)}\n') if exception: raise result return result return log_execution return open_file_and_run @log_decorator() def target_fn(): return 42 @log_decorator() def target_fn_except(a, b): return a / b print(target_fn()) print(target_fn_except(1,1)) print(target_fn_except(1,0)) example1() example2()
# Assignment 7 # By: Joshua Rifkin import argparse import random from itertools import cycle class Dice(object): def __init__(self): self.sides = 6 def rollDie(self): return random.randint(1, 6) class Player(object): def __init__(self, name): self.playerScore = 0 self.playerName = name def addScore(self, score): self.playerScore += score def getScore(self): return self.playerScore def getPlayer(self): return self.playerName class Game(object): def __init__(self, players): self.numPlayers = players self.players = [] self.playerCycle = cycle(self.players) self.turnScore = 0 self.currPlayer = None def newTurn(self): return next(self.playerCycle) def play(self, numPlayers): die = Dice() for i in range(numPlayers): player = Player("player " + str(i + 1)) self.players.append(player) self.currPlayer = self.newTurn() print(self.currPlayer.getPlayer() + "'s turn.") while (self.currPlayer.getScore() + self.turnScore) < 100: move = input("\nWhat would you like to do?\n \'r\' = roll\n \'h\' = hold\n") if move == 'r': turn = die.rollDie() if turn == 1: print(self.currPlayer.getPlayer() + " rolled a 1! End of your turn.") self.turnScore = 0 self.currPlayer = self.newTurn() print("\n" + self.currPlayer.getPlayer() + "'s turn.") else: print("You rolled a " + str(turn)) self.turnScore += turn print("Total round score = " + str(self.turnScore)) print(self.currPlayer.getPlayer() + "'s total score is: " + str((self.currPlayer.getScore() + self.turnScore))) elif move == 'h': self.currPlayer.addScore(self.turnScore) self.turnScore = 0 print("End of " + self.currPlayer.getPlayer() + "'s turn.") self.currPlayer = self.newTurn() print(self.currPlayer.getPlayer() + "'s turn.") elif move == 'quit': quit() else: print("Please enter a valid move option.") print(self.currPlayer + " wins! Your score was " + str((self.currPlayer.getScore + self.turnScore))) quit() def main(): parser = argparse.ArgumentParser(description="How many people want to play the game of pig?") parser.add_argument('-n', '--numPlayers', type=int, help='How many people are playing the game?') args = parser.parse_args() print("Welcome to Pig!") # Seed placed for sake of simplification of testing for Professor random.seed(0) if args.numPlayers <= 1: print("You need at least 2 players to play Pig!") else: game = Game(args.numPlayers) game.play(args.numPlayers) if __name__ == '__main__': main()
#Un comentario solo para decir lo mal que está escrito esto def abrirarchivo(): archivo=input('Archivo: ') while True: try: arch=open(archivo) break except: print('El archivo no existe') archivo=input('Archivo: ') return arch def probararchivo(arch): a=1 cuenta=0 for linea in arch: if a%7==1 and linea != '\n': a=a+1 elif a%7==2 and linea.startswith('A. '): a=a+1 elif a%7==3 and linea.startswith('B. '): a=a+1 elif a%7==4 and linea.startswith('C. '): a=a+1 elif a%7==5 and linea.startswith('D. '): a=a+1 elif a%7==6 and linea.startswith('ANSWER:'): a=a+1 elif a%7==0 and linea.startswith('\n'): a=a+1 else: print('Hay un error en el archivo. Comprueba la línea', a) return False return True def listacontenido(arch): import re preguntas=list() respuestaA=list() respuestaB=list() respuestaC=list() respuestaD=list() solucion=list() bloque=list() i=0 for linea in arch: if re.findall('^A\.\s\S+',linea): respuestaA=respuestaA+re.findall('^A\.\s(.+$)',linea) elif re.findall('^B\.\s\S+',linea): respuestaB=respuestaB+re.findall('^B\.\s(.+$)',linea) elif re.findall('^C\.\s\S+',linea): respuestaC=respuestaC+re.findall('^C\.\s(.+$)',linea) elif re.findall('^D\.\s\S+',linea): respuestaD=respuestaD+re.findall('^D\.\s(.+$)',linea) elif re.findall('^ANSWER:\S',linea): solucion=solucion+re.findall('^ANSWER:(\S)',linea) elif linea != '\n': preguntas.append(linea.strip()) for i in range(0,len(preguntas)): if solucion[i]=='A': respuestaA[i]=(respuestaA[i], 1) respuestaB[i]=(respuestaB[i], 0) respuestaC[i]=(respuestaC[i], 0) respuestaD[i]=(respuestaD[i], 0) elif solucion[i]=='B': respuestaA[i]=(respuestaA[i], 0) respuestaB[i]=(respuestaB[i], 1) respuestaC[i]=(respuestaC[i], 0) respuestaD[i]=(respuestaD[i], 0) elif solucion[i]=='C': respuestaA[i]=(respuestaA[i], 0) respuestaB[i]=(respuestaB[i], 0) respuestaC[i]=(respuestaC[i], 1) respuestaD[i]=(respuestaD[i], 0) elif solucion[i]=='D': respuestaA[i]=(respuestaA[i], 0) respuestaB[i]=(respuestaB[i], 0) respuestaC[i]=(respuestaC[i], 0) respuestaD[i]=(respuestaD[i], 1) bloque.append((preguntas[i], respuestaA[i], respuestaB[i], respuestaC[i], respuestaD[i])) return bloque def numpreguntas(bloque): print('Hay %d preguntas en el archivo' % len(bloque)) num=input('Cantidad de preguntas deseadas: ') while True: try: num=int(num) if num>0 and num<=len(bloque): print('\n') return num else: print('Entrada no válida') num=input('Cantidad de preguntas deseadas: ') continue except: print('Entrada no válida') num=input('Cantidad de preguntas deseadas: ') def cuestionario(bloque, num): import random cuenta=num aciertos=0 while cuenta>0: aleat=random.randint(0, len(bloque)-1) lista=list(bloque[aleat]) print(lista.pop(0)) aleat2=random.randint(0,3) if lista[aleat2][1]==1: solucion='A' print('A.',lista[aleat2][0]) del(lista[aleat2]) aleat3=random.randint(0,2) if lista[aleat3][1]==1: solucion='B' print('B.',lista[aleat3][0]) del(lista[aleat3]) aleat4=random.randint(0,1) if lista[aleat4][1]==1: solucion='C' print('C.',lista[aleat4][0]) del(lista[aleat4]) if lista[0][1]==1: solucion='D' print('D.',lista[0][0]) del(lista[0]) resp=input('Tu respuesta: ') resp=resp.upper() if resp == solucion: print('Bien!\n') aciertos=aciertos+1 else: print('Mal\n') cuenta=cuenta-1 del bloque[aleat] return aciertos archivo=abrirarchivo() cosa=listacontenido(archivo) numero=numpreguntas(cosa) aciertos=cuestionario(cosa,numero) print('Has acertado', aciertos, 'de',numero,'preguntas.')
# -*- coding: utf-8 -*- # # Voici un petit exemple de fonction # def maFonction( x, y ): """ maFonction(x,y) calcule 2*x + 3*y^2 """ # On calcule d'abord 2 x z1 = 2*x # Puis 3 y au carré z2 = 3*y^2 # Puis on additionne les deux résultat = z1 + z2 # Et on renvoie le résultat return( résultat ) # NB : les noms z1, z2 et résultats sont oubliés après appel de la fonction
reponse = 3 proposition = int(input("Donne-moi un nombre entre 1 et 10 : ")) if proposition == reponse: # si 1 print("Bravo, tu as trouvé !") elif proposition < reponse: # sinon si 1 print("Trop petit... Recommence") else: # sinon print("Trop grand... Recommence")
# # Ce petit programme calcule la somme des n premiers entiers # n est le nombre d'entiers qu'on veut additionner # n = 5 sauven = n # s va contenir la somme s = 0 # Boucle de calcul while n > 0: print("J'en suis à n = ", n) # accumuler n dans s s = s + n print("S vaut maintenant: ",s) # Décrémenter n n = n - 1 # À la fin, on affiche la valeur de s print( "La somme des ", sauven, " premiers entiers est: ", s )
from math import sqrt # ==> math.sqrt calcule la racine carrée def ecart_type(maliste): moy = sum(maliste) / len(maliste) i = 0 somme = 0 # commence à 0 while i < len(maliste): somme = somme + (maliste[i] - moy)**2 i = i + 1 return sqrt(somme / len(maliste)) maliste = [1, 2, 3, 4, 5, 6] son_stddev = ecart_type(maliste) # ~= 1.7078... print("L'écart-type des éléments de ma liste est", son_stddev)
import string def duplicate_count(text): return len([x for x in set(text.lower()) if text.lower().count(x) > 1]) def sort_array(source_array): odds = iter(sorted(el for el in source_array if el % 2)) return [next(odds) if el % 2 else el for el in source_array] def rot13(message): alphabet = list(string.ascii_lowercase) * 2 + list(string.ascii_uppercase) * 2 return "".join([alphabet[alphabet.index(x) + 13] for x in list(message)]) def iq_test(numbers): odd_or_even = ["o" if int(x) % 2 != 0 else "e" for x in numbers.split(' ')] return odd_or_even.index("o") + 1 if odd_or_even.count("o") == 1 else odd_or_even.index("e") + 1 def find_uniq(arr): return set(arr)[0] if arr.count(set(arr)[0]) == 1 else set(arr)[1] def countBits(n): return list(format(n, "b")).count(1) print(list(format(10, "b")).count("1"))
while True: try: num1 = int(input("Enter a number: ")) op = str(input("Enter an operation: ")) num2 = int(input("Enter a number: ")) except ValueError: continue break if op == "+": print("Result: {}".format(num1 + num2)) if op == "-": print("Result: {}".format(num1 - num2)) if op == "*": print("Result: {}".format(num1 * num2)) if op == "/": print("Result: {}".format(num1 / num2)) else: SystemExit
print("Enter 6 integer(3 coordinates x,y), use only numbers(-100 - 100)!") while True: try: ax = int(input("Enter a=>x[value]: ")) ay = int(input("Enter a=>y[value]: ")) bx = int(input("Enter b=>x[value]: ")) by = int(input("Enter b=>y[value]: ")) cx = int(input("Enter c=>x[value]: ")) cy = int(input("Enter c=>y[value]: ")) except ValueError: print("Please use only numbers!") continue if ax < -100 or ay < -100 or bx < -100 or by < -100 or cx < -100 or cy < -100 \ or ax > 100 or ay > 100 or bx > 100 or by > 100 or cx > 100 or cy > 100: # min(ax, ay, bx, by) < -100 print("One of your numbers was out of range!") continue break def area(): import math A = math.sqrt(((bx - ax)**2) + ((by - ay)**2)) B = math.sqrt(((bx - cx)**2) + ((by - cy)**2)) C = math.sqrt(((cx - ax)**2) + ((cy - ay)**2)) S = 0.5 * (A + B + C) Area = math.sqrt(S * (S - A) * (S - B) * (S - C)) print("Area of the triangle:", round(Area, 1)) area()
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(16, GPIO.OUT) GPIO.setup(11, GPIO.IN) GPIO.setup(13, GPIO.IN) p = GPIO.PWM(16, 50) p.start(0) dc = 5 p.ChangeDutyCycle(dc) try: while 1: inputValue1 = GPIO.input(11) inputValue2 = GPIO.input(13) if inputValue1 == False and dc < 8: dc += 1 p.ChangeDutyCycle(dc) print("Button pressed 1", dc) elif inputValue2 == False and dc > 3: dc -= 1 p.ChangeDutyCycle(dc) print("Button pressed 2", dc) time.sleep(0.5) except KeyboardInterrupt: pass p.stop() GPIO.cleanup()
def callback(MoistureSensor1): #if GPIO.input(MoistureSensor1): if GPIO.gpio_function(15) == GPIO.HIGH: print("MoistureSensor on") GPIO.output(Pump1, GPIO.HIGH) GPIO.output(Pump2, GPIO.HIGH) time.sleep(0.25) else: print("MoistureSensor off") GPIO.output(Pump1, GPIO.LOW) GPIO.output(Pump2, GPIO.LOW) time.sleep(0.25) def main(): pump_and_moisture = input("Switch pump and moisture sensor on? ") if pump_and_moisture == "yes": callback() else: print("nope") # Runs main() function first! if __name__ == "__main__": import RPi.GPIO as GPIO import time GPIO.setwarnings(False) # Set our GPIO numbering to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin that we have our digital output from our sensor connected to MoistureSensor1 = 15 Pump1 = 3 Pump2 = 2 # Set the GPIO pin to an input # Kosteusmittari GPIO.setup(MoistureSensor1, GPIO.IN) # Pumput saadetty output:ina GPIO.setup(Pump1, GPIO.OUT) GPIO.setup(Pump2, GPIO.OUT) # This line tells our script to keep an eye on our gpio pin and let us know when the pin goes HIGH or LOW GPIO.add_event_detect(MoistureSensor1, GPIO.BOTH, bouncetime=300) # This line asigns a function to the GPIO pin so that when the above line tells us there is a change on the pin, run this function GPIO.add_event_callback(MoistureSensor1, callback) # This is an infinte loop to keep our script running while True: time.sleep(1) main()
# Import OS for Traversing Directories import os # Import Numpy for Mathematical Functions import numpy as np # Function to Obtain a List of Files def getFileList(directory): fileList = [] fileSize = 0 folderCount = 0 # For Loop to Cycle Through Directories for root, dirs, files in os.walk(directory): folderCount += len(dirs) for file in files: f = os.path.join(root, file) fileSize = fileSize + os.path.getsize(f) fileList.append(f) # Print to Check Data has been located correctly print('################################################') print('############ Traversing Directories ############\n') print("Total Size is {0} bytes".format(fileSize)) print('Number of Files = %i') % (len(fileList)) print('Total Number of Folders = %i') % (folderCount) print('################################################\n') return fileList # Location of File file_loc = '/home/dan/Desktop/IMN432-CW01/meta/' files = getFileList(file_loc) numFiles = len(files) # Import Module from xml.dom import minidom from xml.dom.minidom import parseString import re table = [] for direc in np.arange(0, numFiles): # Read and Convert XML to String file = open(files[direc], 'r') data = file.read() file.close() # Ebook Number Retrieval ebook = parseString(data) ebook = ebook.getElementsByTagName('pgterms:ebook')[0].toxml() ebook = ebook.replace( '<pgterms:ebook>', '').replace( '</pgterms:ebook>', '') ebook = ebook[:ebook.find('>\n')] ebook = str(re.split('/', re.split('=', ebook)[1])[1]).replace('"', '') # Read XML into an Object xmldoc = minidom.parse(files[direc]) # Navigate onto the Tree to Find the Ebook No. pgterms_ebook = xmldoc.getElementsByTagName('pgterms:ebook')[0] # Navigate to the Subjects Tree subjects = pgterms_ebook.getElementsByTagName('dcterms:subject') # Print the Subjects values for lines in subjects: values = lines.getElementsByTagName('rdf:value')[0].firstChild.data table.append([ebook, str(values)]) f = open('Ebook_Subject.txt', 'w') for i in np.arange(0, len(table)): f.write("%s\n" % table[i]) f.close()
a = int(input("number:")) r1 = int("%s" % a) r2 = int("%s%s" % (a, a)) r3 = int("%s%s%s" % (a, a, a)) r4 = int("%s%s%s%s" % (a, a, a, a)) print(r1 + r2 - r3 * r4)
# authors - Dawei Ju and Bo Liu import random global deck global discard class myStatic: hand_status = hand_status = [False] * 10 status_check = False deck = range(1,61) discard = [] def shuffle(): '''This function shuffles the deck or the discard pile\ 1.initial game: shuffle the deck\ 2.There is no card in deck. ''' global deck global discard if len(deck) == 60: #Initial game shuffle deck random.shuffle(deck) if len(deck) == 0: #There is no cards in deck. shuffle the discard's cards deck = list(discard) random.shuffle(deck) def check_racko(rack): '''Given a rack, determine if Racko has been achieved.''' for i in range(0, 9): if rack[i] < rack [i+1]: return False return True def deal_card(): '''get the top card from the deck''' print "The top card from the deck is: " print deck[len(deck) + 1] deck.pop() def deal_initial_hands(): ''' Start the game off by dealing two hands of 10 cards each. Returns two lists.''' hand1 = [] hand2 = [] for i in range(0,10): hand1.append(deck.pop()) hand2.append(deck.pop()) return hand1, hand2 def does_user_begin(): ''' simulate a coin toss by using the random library.If it is head,\ return Ture, and user first. If it is tail, return False, and computer first''' head_or_tail = random.randint(1, 2) if head_or_tail == 1: return True else: return False def print_top_to_bottom(rack): '''Given a rack print it out from top to bottom.''' for i in range(0,10): print rack[i] print def add_card_to_discard(card): '''Add the card to the top of the discard pile.''' discard.append(card) def find_and_replace(newCard, cardToBeReplaced, hand): '''find the cardToBeReplaced (represented by a number) in the hand and replace it with newCard.''' if cardToBeReplaced not in hand: return False else: #switch the new card and cardToBeReplaced replace_index = hand.index(cardToBeReplaced) hand[replace_index] = newCard discard.append(cardToBeReplaced) return True def user_play(user_hand): '''user’s strategy''' #check and make sure there are still some cards in the deck #else reshuffle the discard and restart. if len(deck) == 0: #shuffle cards shuffle() #reveal one card to begin the discard pile add_card_to_discard(deck.pop()) print 'Your current cards:' print_top_to_bottom(user_hand) print 'The current top card of the discard pile is', discard[-1] choice = raw_input ('Do you want this card? (y/n) \n') if choice == 'y' or choice == 'Y': card = discard.pop() #ask the user for the number of the card they want to kick out cardToBeReplaced = input('Please input the number you want to kick out.') #modify the user’s hand and the discard pile while not find_and_replace(card, cardToBeReplaced, user_hand): print 'The number you input is not in your hand. Please input again!' cardToBeReplaced = input('Please input the number you want to kick out.') #print the user’s hand print 'Your current cards:' print_top_to_bottom(user_hand) else: card = deck.pop() print 'The card you get from the deck is ' + str(card) #ask the user if they want this secondChoice = raw_input('do you want to keep it? (y/n) \n') if secondChoice == 'y' or choice == 'Y': #ask the user for the number of the card they want to kick out cardToBeReplaced = input('Please input the number you want to kick out.') #modify the user’s hand and the discard pile while not find_and_replace(card, cardToBeReplaced, user_hand): print 'The number you input is not in your hand. Please input again!' cardToBeReplaced = input('Please input the number you want to kick out.') #print the user’s hand print 'Your current cards:' print_top_to_bottom(user_hand) else: add_card_to_discard(card) print 'Your current cards:' print_top_to_bottom(user_hand) print 'You have finished your play!' print return user_hand def computer_play(computer_hand): '''computer's strategy''' #check and make sure there are still some cards in the deck #else reshuffle the discard and restart. if len(deck) == 0: #shuffle cards shuffle() #reveal one card to begin the discard pile add_card_to_discard(deck.pop()) #determine the status for each slot #ranges of each slot are 60-53, 54-49, 48-43, 42-35, 36-31, 32-23, 24-17, 18-13, 12-7, 6-0 if not myStatic.status_check: myStatic.status_check = True for i in range(0,10): #modify the computer’s hand and the discard pile if computer_hand[i] <= 6 * (10 - i) and computer_hand[i] > 6 * (9 - i): myStatic.hand_status[i] = True for i in range(0,9): #modify the computer’s hand and the discard pile if myStatic.hand_status[i] and not myStatic.hand_status[i+1] and computer_hand[i+1] > 6 * (9 - i) and computer_hand[i+1] < computer_hand[i]: myStatic.hand_status[i+1] = True for i in range(9,0,-1): #modify the computer’s hand and the discard pile if myStatic.hand_status[i] and not myStatic.hand_status[i-1] and computer_hand[i-1] <= 6 * (10 - i) and computer_hand[i-1] > computer_hand[i]: myStatic.hand_status[i-1] = True index = 0 #determine the slot card belongs to if discard[-1] % 6 == 0: index = 9 - (discard[-1] / 6 -1 ) else: index = 9 - (discard[-1] / 6) if not myStatic.hand_status[index]: #modify the computer’s hand and the discard pile computer_hand[index], discard[-1] = discard[-1], computer_hand[index] myStatic.hand_status[index] = True elif computer_hand[index] > discard[-1] and (index+1) < 10 and not myStatic.hand_status[index+1]: #modify the computer’s hand and the discard pile computer_hand[index+1], discard[-1] = discard[-1], computer_hand[index+1] myStatic.hand_status[index+1] = True elif computer_hand[index] < discard[-1] and (index-1) >= 0 and not myStatic.hand_status[index-1]: #modify the computer’s hand and the discard pile computer_hand[index-1], discard[-1] = discard[-1], computer_hand[index-1] myStatic.hand_status[index-1] = True else: #pop card from deck card = deck.pop() #computer will use this card and calculate the index of hand for this card if card % 6 == 0: index = 9 - (card / 6 -1) else: index = 9 - (card / 6) if not myStatic.hand_status[index]: #modify the computer’s hand and the discard pile computer_hand[index], card = card, computer_hand[index] myStatic.hand_status[index] = True elif computer_hand[index] > card and (index+1) < 10 and not myStatic.hand_status[index+1]: #modify the computer’s hand and the discard pile computer_hand[index+1], card = card, computer_hand[index+1] myStatic.hand_status[index+1] = True elif computer_hand[index] < card and (index-1) >= 0 and not myStatic.hand_status[index-1]: #modify the computer’s hand and the discard pile computer_hand[index-1], card = card, computer_hand[index-1] myStatic.hand_status[index-1] = True else: pass #add the replaced card to discard list add_card_to_discard(card) print 'Computer has finished his play!' print return computer_hand def main(): '''main function''' computer_racko = False user_racko = False print 'Game Start!' print #shuffle cards shuffle() #determine whether the user goes first userStarts = does_user_begin() #deal two hands of 10 cards each if userStarts: #user first print 'Heads! You first!' print (user_hand, computer_hand) = deal_initial_hands() else: #computer first print 'Tails! Computer first!' print (computer_hand, user_hand) = deal_initial_hands() #reveal one card to begin the discard pile add_card_to_discard(deck.pop()) #check racko user_racko = check_racko(user_hand) computer_racko = check_racko(computer_hand) while True: if userStarts: #user first user_hand = user_play(user_hand) #check racko if check_racko(user_hand): user_racko = True break computer_hand = computer_play(computer_hand) #check racko if check_racko(computer_hand): computer_racko = True break else: #computer first computer_hand = computer_play(computer_hand) #check racko if check_racko(computer_hand): computer_racko = True break user_hand = user_play(user_hand) #check racko if check_racko(user_hand): user_racko = True break if computer_racko: print "Computer's current cards:" print_top_to_bottom(computer_hand) print 'Computer Win!' if user_racko: print 'You Win!' print print 'Game Over!' if __name__ == '__main__': main()
def readFile(): '''read the text file 'resume.txt' into list''' my_lines = [] f = open('resume.txt','rU') line = f.readline() while line: my_lines.append(line) line = f.readline() f.close() return my_lines def detectName(my_lines): '''extract the name from file lines''' name = [] if my_lines[0].lstrip().rstrip() != '': char = my_lines[0].lstrip().rstrip()[0] if char not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': raise ValueError, "first line should be name with proper capitalization" name.append(my_lines[0]) else : raise ValueError, "first line should be name with proper capitalization" return name def detectEmail(my_lines): '''extract the email from file lines''' email = [] for line in my_lines: if '@' in line: email_line = line.lstrip().rstrip() + '\n' if email_line[-5:-1] == '.com' or email_line[-5:-1] == '.edu': index = email_line.find('@') index += 1 if email_line[index] in 'abcdefghijklmnopqrstuvwxyz': email.append(email_line) break return email def detectCourses(my_lines): '''extract courses from file lines''' courses = [] for line in my_lines: if 'Courses' in line: courses_line = line.lstrip()[7:] index = 0 while courses_line[index] not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' and courses_line[index]!='\n': index += 1 if courses_line[index]!='\n': courses.append(courses_line[index:]) break return courses def detectProjects(my_lines): '''extract projects from file lines''' projects = [] for line in my_lines: if 'Projects' in line: index = my_lines.index(line) index += 1 while my_lines[index].lstrip().rstrip()[0:10] != '----------': if my_lines[index].lstrip().rstrip() != '': projects.append(my_lines[index]) index += 1 break return projects def detectEducation(my_lines): '''extract education from file lines''' education = [] for line in my_lines: if (('Master' in line) or ('Bachelor' in line) or ('Doctor' in line)) and (('University' in line) or ('university' in line)): education.append(line) return education def modifyHTMl(file_name): '''modifies the HTML file''' f = open(file_name, 'r+') lines = f.readlines() f.seek(0) f.truncate() del lines[-1] del lines[-1] line = '<div id="page-wrap">\n' lines.append(line) f.writelines(lines) f.close() def surround_block(tag, text): '''surrounds text with HTML tags''' lines = [] line = '<' + tag + '>' + '\n' lines.append(line) lines.extend(text) line = '</' + tag + '>' + '\n' lines.append(line) return lines def write_intro_section(file_name, name, email): '''write intro section of the resume''' f = open(file_name, 'a') if name != []: text = surround_block('h1', name) if email != []: text.extend(surround_block('p', ['Email: ' + email[0]])) f.writelines(surround_block('div', text)) f.close() def write_education_section(file_name, education): '''write education section of the resume''' if education != []: f = open(file_name, 'a') text = surround_block('h2', ['Education\n']) edu = [] for degree in education: edu.extend(surround_block('li', degree)) text.extend(surround_block('ul', edu)) f.writelines(surround_block('div', text)) f.close() def write_project_section(file_name, projects): '''write projects section of the resume''' if projects != []: f = open(file_name, 'a') text = surround_block('h2', ['Projects\n']) pro = [] for project in projects: pro.extend(surround_block('li', surround_block('p', project))) text.extend(surround_block('ul', pro)) f.writelines(surround_block('div', text)) f.close() def write_course_section(file_name, courses): '''write courses section of the resume''' if courses != []: f = open(file_name, 'a') text = surround_block('h3', ['Courses\n']) text.extend(surround_block('span', courses)) f.writelines(surround_block('div', text)) f.close() def write_end(file_name): '''write the end part''' f = open(file_name, 'a') lines = ['</div>\n', '</body>\n', '</html>\n'] f.writelines(lines) f.close() def main(): "use this commands that are commented out for the recitation" my_lines = readFile() name = detectName(my_lines) email = detectEmail(my_lines) courses = detectCourses(my_lines) projects = detectProjects(my_lines) education = detectEducation(my_lines) file_name = 'resume.html' modifyHTMl(file_name) write_intro_section(file_name, name, email) write_education_section(file_name, education) write_project_section(file_name, projects) write_course_section(file_name, courses) write_end(file_name) if __name__=='__main__': main()
# s=map(lambda x:x*2 ,[1,2,34,5]) # for i in s: # print(i) from functools import reduce # var=filter(lambda x:x%2==0,[2,4,8,9]) # for y in var: # print(y) # var1=reduce(lambda x,y:x*y,[1,2,3,5]) print(var1)
e=1 try: 1/0 except ZeroDivisionError as e: print('error:{}'.format(e)) # print(e) #运行上面代码,执行结果 NameError: name 'e' is not defined # 官方文档说明: # except E as N: # foo # 就等于 # except E as N: # try: # foo # finally: # del N # 因为上面例子的e最后被delete,所以会抛NameError import datetime print(datetime.datetime.now())
""" 12. 아래 두 함수를 정의한다. ① 여러 개의 숫자를 매개변수로 받아서, 해당 숫자 중에 가장 큰 값을 반환하는 max. 어떤 개수의 숫자가 매개변수로 넘어와도 작동해야 한다. ② 여러 개의 숫자를 매개변수로 받아서, 해당 숫자 중에 가장 작은 값을 반환하는 min. 어떤 개수의 숫자가 매개변수로 넘어와도 작동해야 한다. max(6, 8, 9, -10, 4), min(6, 8, 9, -10, 4)를 호출하여 출력 <출력 예> 최대값: 9 최소값: -10 """ def max(*a) : max_num = a[0] for i in a : if max_num < i : max_num = i return max_num def min(*b) : min_num = b[0] for j in b : if min_num > j : min_num = j return min_num print("최대값:", max(6, 8, 9, -10, 4)) print("최소값:", min(6, 8, 9, -10, 4))
""" 9. 매개변수로 넘어온 자연수가 소수인지 여부를 판별하여, 소수이면 True, 아니면 False를 반환하는 함수 is_prime을 정의하라. 2,3,5,7,11,13 등 1과 자기자신이외의 약수가 없는 자연수를 소수라 한다. """ def is_prime(a) : # 매개변수 값을 a에 저장 count = 0 # 약수를 담을 변수 count 초기화 for i in range(1, a+1) : # 1~a까지 반복 if a % i == 0 : # a 나누기 i 의 나머지가 0이라면 count += 1 # i가 a의 약수이기 때문에 count ++ if count == 2 : # 소수는 count가 2 return True # True 반환 else : # 아니면 return False # False 반환 a = int(input("숫자 입력: ")) # 숫자 입력 print(is_prime(a)) # 인수 전달
""" 챕터: Day 6 주제:class 상속/계승 문제: shape,circlerectangle class define 작성자: 김기범 작성일:2018.11.01 """ """ 1.Define shape class, method로 area(), perimeter()를 가지고 있다. A.area()는 면적, perimeter()는 둘레를 반환한다. 하지만,shape class는 0을 반환 B.__str__()를 정의한다. "도형"을 반환 2.Shape를 계승하는, Circle,Rectangle,Triangle을 정의한다,__init__(),area(),perimeter(),__str__()를 정의한다. Triangle의 __init__는 세변(첫번째 변은 밑변)과 높이를 매개변수로 받는다. A. Circle class에는 getRadius() method를 정의(반지름), 클래스변수PI=3.1415정의 B. Triangle,Rectangle class에는 getHeight() method를 정의(높이) C. Triangle,Rectangle class에는 getWidth() method를 정의(밑변) D. Triangle,Rectangle class에는 변의 길이를 list형태로 반환하는 getSides()method를 정의한다(변들을 반환한다.) """ class Shape: #개념적으로 되는 정의(특별한 개념은 없지만 크게 하나로 묶어내는 개념) abstract class def area(self): return 0 def perimeter(self): return 0 def __str__(self): return "도형" class Circle(Shape): PI = 3.1415 def __init__(self,r): self.raidus = r def area(self): return ((self.raidus**2)*PI) def perimeter(self): return (self.raidus*2*PI) def getRadius(self): return self.raidus def __str__(self): return "Circle" class Rectangle(Shape): def __init__(self,x,y): self.height = x self.width = y def getHeight(self): return self.height def getWidth(self): return self.width def area(self): return self.height * self.width def perimeter(self): return (self.height + self.width)*2 """ 실행부 1. s 변수는 도형이다. 2. 반지름이 5인 원을 정의하여 c변수에 저장한다. 3. 가로,세로가 5,10인 직사각형을 정의하여 r에 저장한다. 4. 세변이 3(밑변),4,5이고 높이가 4인 삼각형을 정의하여 t에 저장한다. 5. c의 면적과 둘레를 출력한다. 6. r의 면적과 둘레를 출력한다. 7. t의 면적과 둘레를 출력한다. 8. t의 변들을 리스트로 받아 출력한다. 9. 리스트 l을 정의하여, s,c,r,t을 요소로 추가한다. 10. l의 각 요소에 대해, 해당요소를 출력하고, 면적과 둘레를 계산하여 출력한다.(for문 이용) * for문 안에서 테스트: getRadius() method를 수행한다.(오류발생) """ s = Circle(5) print(s.area())
""" 챕터: Day 6 주제: class 문제: 숫자를 하나씩 발생시키는 Counter 클래스 정의 작성자: 김기범 작성일: 2018.10.18. """ # Counter 클래스 정의, instance는 아직 생성되지 않음 class Counter : def __init__(self, start = 0): """ 특별한 메소드이다. instance를 생성할 때 초기화하는 메소드, instance를 생성할 때 자동 호출됨 :param start: """ self.count = start def reset(self): """ 카운터를 초기화하는 메소드 self: method가 수행되는 instance 자신을 의미 :return: """ self.count = 0 # count는 instance variable(member) def increment(self): """ 카운터를 하나 증가시킴 :return: """ self.count += 1 # count를 1 증가 def get(self): """ count 값을 반환 :return: """ return self.count # 실행 코드 시작 # class Counter의 instance를 생성해서 변수 a의 저장 a = Counter() # Counter는 클래스 이름, ()가 있어야 한다, __init(self)__가 호출됨, 디폴트값 0 # class Counter의 instance를 생성해서 변수 b의 저장, 매개변수를 포함하는 __init함수가 호출됨 b = Counter(10) a.reset() # 변수에 "."을 이용하여 메소드 호출, a가 self 매개변수값이 되어 넘어감 a.increment() a.increment() a.increment() print("a = %d" %a.get()) print("b = %d" %b.get())
""" 챕터: Day 4 주제: 반복문(for 문) 문제: while 문을 이용하여 100에서 1까지 2의 배수를 크기가 작아지는 순서로 출력하시오 작성자: 김기범 작성일: 2018.09.20. """ x = 100 # x를 초기화 while x > 0 : # x가 0보다 크면 print(x) # x를 출력 x -= 2 # x = x - 2
""" 챕터: Day 5 주제: 재귀함수(recursion) 자기 자신을 호출하는 함수 문제: A. 팩토리얼 계산 함수 fact를 재귀함수로 정의하여, fact(5)를 호출한 결과를 출력하라. 작성자: 김기범 작성일: 2018.10.11. """ def fact(a) : # 재귀함수 fact 정의 if a == 1 : # a가 1이면 return 1 # 1 반환 else : return a * fact(a-1) # 재귀함수 print(fact(5)) # 매개변수 5로 호출
""" 챕터: Day 6 주제: exception 문제: 사용자로부터 숫자를 입력받아, 1부터 해당 숫자까지의 합을 구하라. 만약 숫자가 아닌 값이 입력되면, "숫자를 입력하세요"라는 문장을 출력한 후 다시 입력을 받는다 작성자: 김기범 작성일: 2018.11.27. """ # exception을 사용하여 프로그래밍 sum = 0 # 합을 저장할 변수 정의 while True: # 숫자를 입력할 때까지 반복 try: # 숫자값이 입력되는지 검사를 위해 try 사용 n = int(input("숫자 입력: ")) # int로 변환되는 과정에서 ValueError 발생시 except로 이동 for i in range(1, n+1): # 오류 발생되지 않을 경우 합 구하기 sum += i break # 합을 구했으므로 반복문 종료 except ValueError: # 숫자가 입력되지 않은 Exception 잡기 print("숫자를 입력하세요") print(n, "까지의 합: ", sum) # 결과 출력
""" 챕터: Day 6 주제: class 문제: 좌표를 표현하는 클래스 Coordinate를 정의한다. 1. __init__는 x, y 좌표를 받아서 self의 x, y에 배정 2. 거리를 구하는 distance 메소드를 정의한다. self와 다른 좌표 other를 매개 변수로 받는다. 거리는 ( x좌표 사이의 차의 제곱(**2로 계산)과 y좌표 사이 차의 제곱의 합)의 제곱근이다. 제곱근(**0.5로 계산) 작성자: 김기범 작성일: 2018.10.18. """ # 클래스 정의 class Coordinate : def __init__(self, x = 0, y = 0): # instance를 정의하면서 자동으로 좌표 받기 """ Python에서는 __init__함수를 한 클래스 당 하나만 정의할 수 있음 """ self.x = x # 매개변수 x는 좌표 x 값 self.y = y # 매개변수 y는 좌표 y 값 def distance(self, other): """ 두 좌표의 거리를 계산하여 반환 :param other: 다른 좌표 :return: self와 other와의 거리를 반환 """ r = ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5 # 거리 구하기 공식, 제곱근(**0.5) return r # 거리를 반환 # 실행 코드 시작 """ 실행코드 부분 (3, 4) 좌표의 점 c를 정의 원점 origin 정의 (3. 4)와 원점과의 거리를 출력 """ c = Coordinate(3, 4) # (3, 4) 좌표의 점 c를 정의 origin = Coordinate() # 원점 origin 정의 c1 = Coordinate(10, 9) # 새로운 좌표 c1 정의 print("거리: %.2f" %c.distance(origin)) # 원점과의 거리 출력하기, 소수점 둘째 자리까지 출력, c가 self이고 origin이 other print("거리: %.2f" %c1.distance(c)) # c1과 c의 거리 구하기, c1이 self, c가 other # 클래스 이름과 함께 메소드 호출 가능, 이 때는 self에 해당되는 매개변수를 보내야 한다 print("거리: %.2f" %Coordinate.distance(c1, origin))
""" 챕터: Day 4 주제: 반복문(for 문) 문제: 사용자가 입력한 영문자를 아래와 같이 출력 예) BINGO INGO NGO GO O 작성자: 김기범 작성일: 2018.09.27. """ S = input() # 문자열 입력받기 #1 for i in range(0, len(S)) : # 0부터 문자열 끝 앞 번호까지 반복문 print(" " * i, end = "") # 줄 길이만큼 앞에 여백 늘리기 print(S[i:]) # i부터 끝까지 출력하기 #2 for i in range(0, len(S)) : # 문자열 길이만큼 반복 o = '' # o를 초기화 for j in range(0, i) : # i만큼 공백 붙이기 o = o + ' ' for k in range(i, len(S)) : # 공백이 있는 o에 문자 붙이기 o = o + S[k] print(o)
# This is a demo task. # Write a function: # def solution(A) # that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. # For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. # Given A = [1, 2, 3], the function should return 4. # Given A = [−1, −3], the function should return 1. # Write an efficient algorithm for the following assumptions: # N is an integer within the range [1..100,000]; # each element of array A is an integer within the range [−1,000,000..1,000,000]. a = [1, 3, 6, 4, 1, -2, -4, 2] n = 6 smallest_possible = 1 new_list = [i for i in a if i > 0] new_list.sort() print(new_list, 'new') if len(new_list) == 0 or new_list[0] != 1: print(1, 'first if statement') else: #while loop - compare each number in list to the number before it current = 0 for i in range(len(new_list)): if (new_list[i] - 1) != current and new_list[i] != current: print(new_list[i] - 1, 'if statement return ') else: current = new_list[i]
print ("\n\nWelcome!") # Print single line print """ \nThis program creates text file if you type in some informations. It won't take too long... Enjoy! """ # Print multiple lines response = raw_input("*** To continue, press ENTER. ***") # Make variable called response with line of texts if response == "": # If variable eqauls nothing, run the codes below filename = raw_input("\nFirst, set a Filename:") # Make variable called filename with line of texts print""" -------------------------------------------------------- Informations you typed in will be saved in the text file with a filename you just set right before. -------------------------------------------------------- Now you will type in informations of three people you want... """ # Print multiple lines with open (filename + ".txt", "w") as f: # Open file with name that user set, and write per1 = raw_input("First person's name:") # Make variable called per1 with line of texts f.write(per1 + "\n") # Type in per1 with newline inside the text file birth1 = raw_input("First person's birthday:") # Make variable called birth1 with line of texts f.write(birth1 + "\n") # Type in birth1 with newline inside the text file pnum1 = raw_input("First person's phonenumber:") # Make variable called pnum1 with line of texts f.write(pnum1 + "\n\n\n") # Type in pnum1 with multiple newlines inside the text file per2 = raw_input("Second person's name:") # Make variable called per2 with line of texts f.write(per2 + "\n") # Type in per2 with newline inside the text file birth2 = raw_input("Second person's birthday:") # Make variable called birth2 with line of texts f.write(birth2 + "\n") # Type in birth2 with newline inside the text file pnum2 = raw_input("Second person's phonenumber:") # Make variable called pnum2 with line of texts f.write(pnum2 + "\n\n\n") # Type in pnum2 with multiple newlines inside the text file per3 = raw_input("Third person's name:" ) # Make variable called per3 with line of texts f.write(per3 + "\n") # Type in per3 with newline inside the text file birth3 = raw_input("Third person's birthday:") # Make variable called birth3 with line of texts f.write(birth3 + "\n") # Type in birth3 with newline inside the text file pnum3 = raw_input("Third person's phonenumber:") # Make variable called pnum3 with line of texts f.write(pnum3 + "\n\n\n") # Type in pnum3 with multiple newlines inside the text file print ("Thank you. Check the file if it's all saved.") # Print single line f.close() # Save and close the file
# UNIDAD 6: ECUACIONES DIFERENCIALES ORDINARIAS import time import numpy as np import sympy as sym import matplotlib.pyplot as plt from sympy import sin, cos t, y = sym.symbols("t y") # Método de Euler def euler(ODE, t0, y0, tf, h): """ Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), dos reales t0 & y0 que representan las condiciones iniciales y(t0) = y0, un real tf que es el límite superior del intervalo de análisis, y un real h que representa el incremento de t. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ f = sym.lambdify([t, y], ODE) pasos = [(t0, y0)] tk, yk = pasos[-1] while (tk < tf): yk += f(tk, yk) * h tk += h pasos.append((tk, yk)) return pasos # Método de Serie de Taylor def taylor(ODE, t0, y0, tf, h): """ Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), dos reales t0 & y0 que representan las condiciones iniciales y(t0) = y0, un real tf que es el límite superior del intervalo de análisis, y un real h que representa el incremento de t. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ f = sym.lambdify([t, y], ODE) pasos = [(t0, y0)] tk, yk = pasos[-1] ypp = sym.diff(ODE, t) + sym.diff(ODE, y)*ODE fpp = sym.lambdify([t, y], ypp) while (tk < tf): yk += f(tk, yk)*h + (fpp(tk, yk)/2)*(h**2) tk += h pasos.append((tk, yk)) return pasos # Método de Runge-Kutta (orden 2) def runge_kutta_2(ODE, t0, y0, tf, h): """ Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), dos reales t0 & y0 que representan las condiciones iniciales y(t0) = y0, un real tf que es el límite superior del intervalo de análisis, y un real h que representa el incremento de t. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ f = sym.lambdify([t, y], ODE) pasos = [(t0, y0)] tk, yk = pasos[-1] while (tk < tf): k1 = f(tk, yk) * h k2 = f(tk + h, yk + k1) * h yk += (1/2) * (k1 + k2) tk += h pasos.append((tk, yk)) return pasos # Método de Runge-Kutta (orden 4) def runge_kutta_4(ODE, t0, y0, tf, h): """ Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), dos reales t0 & y0 que representan las condiciones iniciales y(t0) = y0, un real tf que es el límite superior del intervalo de análisis, y un real h que representa el incremento de t. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ f = sym.lambdify([t, y], ODE) pasos = [(t0, y0)] tk, yk = pasos[-1] while (tk < tf): k1 = f(tk, yk) * h k2 = f(tk + h/2, yk + k1/2) * h k3 = f(tk + h/2, yk + k2/2) * h k4 = f(tk + h, yk + k3) * h yk += (1/6) * (k1 + 2*k2 + 2*k3 + k4) tk += h pasos.append((tk, yk)) return pasos # Método Multipaso (2 pasos) def multipaso_2(ODE, t0, y0, tf, h): """ Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), dos reales t0 & y0 que representan las condiciones iniciales y(t0) = y0, un real tf que es el límite superior del intervalo de análisis, y un real h que representa el incremento de t. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ f = sym.lambdify([t, y], ODE) t1, y1 = runge_kutta_4(ODE, t0, y0, t0+h, h)[1] pasos = [(t0, y0), (t1, y1)] tk, yk = pasos[-1] while (tk < tf): ypk_1 = f(pasos[-2][0], pasos[-2][1]) yk += (1/2) * (3*f(tk, yk) - ypk_1) * h tk += h pasos.append((tk, yk)) return pasos # Método Multipaso (4 pasos) def multipaso_4(ODE, t0, y0, tf, h): """ Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), dos reales t0 & y0 que representan las condiciones iniciales y(t0) = y0, un real tf que es el límite superior del intervalo de análisis, y un real h que representa el incremento de t. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ f = sym.lambdify([t, y], ODE) pasos = [(t0, y0)] + runge_kutta_4(ODE, t0, y0, t0 + 3*h, h)[1:4] tk, yk = pasos[-1] while (tk < tf): ypk_1 = f(pasos[-2][0], pasos[-2][1]) ypk_2 = f(pasos[-3][0], pasos[-3][1]) ypk_3 = f(pasos[-4][0], pasos[-4][1]) yk += (1/24) * (55*f(tk, yk) - 59*ypk_1 + 37*ypk_2 - 9*ypk_3) * h tk += h pasos.append((tk, yk)) return pasos # Resolución de Ecuaciones de Orden Superior (Con el Método de Euler) def ODEs_superior(ODE, t0, y0s, tf, h, n): """ Entrada: una Ecuación Diferencial Ordinaria ODE de orden n, un real t0 y una lista de reales y0s que representan las condiciones iniciales de cada orden, un real tf que es el límite superior del intervalo de análisis, un real h que representa el incremento de t, y un entero n que es el orden de la ODE. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para t0 <= tk <= tf. """ pasos = [(t0, y0s[0])] tk, yk = t0, list (y0s) while (tk < tf): f = sym.lambdify([t, y], ODE) for i in range(n - 1, -1, -1): yk[i] += f(tk, yk[i]) * h f = sym.lambdify([t, y], yk[i]) tk += h pasos.append((tk, yk[0])) return pasos # Método de Diferencias Finitas def diferencias_finitas(ODE, t0, y0, tf, yf, n): """ Entrada: una Ecuación Diferencial Ordinaria ODE de orden 2, cuatro reales t0, y0, tf, yf que representan las condiciones de frontera y(t0) = y0 & y(tf) = yf, y un entero n que indica la cantidad de puntos que describen la solución, incluyendo los puntos inicial y final. Salida: los puntos (tk, yk) que corresponden a la solución de la ODE, para 0 <= k <= n. """ ti = np.linspace(t0, tf, n) f = sym.lambdify(t, ODE) h = (tf - t0) / (n - 1) A = [[0 for _ in range(n - 2)] for _ in range(n - 2)] b = [f(ti[i]) * (h**2) for i in range(1, n - 1)] for i in range(1, n - 1): j = i - 1 A[j][j] = -2 if (i == 1): b[j] -= y0 if (i == n - 2): b[j] -= yf if (i > 1): A[j][j - 1] = 1 if (i < n - 2): A[j][j + 1] = 1 yi = [y0] + list (np.linalg.solve(A, b)) + [yf] pasos = [(ti[i], yi[i]) for i in range(n)] return pasos # Método de Elementos Finitos (Colocación) def elementos_finitos(ODE, t0, y0, tf, yf, n): """ Entrada: una Ecuación Diferencial Ordinaria ODE de orden 2, cuatro reales t0, y0, tf, yf que representan las condiciones de frontera y(t0) = y0 & y(tf) = yf, y un entero n que indica la cantidad de puntos que describen la solución, incluyendo los puntos inicial y final. Salida: la función polinomio que corresponden a la solución de la ODE. """ ti = np.linspace(t0, tf, n) f = sym.lambdify(t, ODE) A, b = [], [] for i in range(n): if (i == 0): A.append([t0**j for j in range(n)]) b.append(y0) elif (i == n - 1): A.append([tf**j for j in range(n)]) b.append(yf) else: A.append([j*(j - 1)*ti[i]**(j - 2) if j > 1 else 0 for j in range(n)]) b.append(f(ti[i])) x = np.linalg.solve(A, b) polinomio = sum([x[i] * (t**i) for i in range(n)]) return polinomio
dob= list(map(int,input().split(":"))) todays=list(map(int,input().split(":"))) dob.reverse() todays.reverse() if dob[0]<todays[0]: if dob[1]< todays[1]: print(str(todays[0]-dob[0])+" Years",end=" ") print(str(todays[1]-dob[1])+" Months",end=" ") print(str((30-dob[2])+todays[2])+" Days",end=" ") elif dob[1]>todays[1]: print(str(todays[0]-dob[0]-1)+" Years",end=" ") print(str(12-todays[1])+" Months",end=" ") print(str(365-((30-todays[2])+dob[2])) + " Days", end=" ") else: print(str(todays[0]-dob[0])+" Years",end=" ") print("0 Months",end=" ") print(str(abs(todays[2]-dob[2]))+"Days") elif dob[0]==todays[0]: print("same year born")
from Player import Player class Traitor(Player): starting_ability_charge = 0 def __init__(self, name): """player role will be protected since it is good information to keep secret each traitor will start with full ability charge, and a defined role as Traitor""" super().__init__() self.name = name self._role = "Traitor" self.current_ability_charge = Traitor.starting_ability_charge @classmethod def _set_ability_charge(cls, value): """Used to set starting ability charge to another value for possible different game modes""" cls.starting_ability_charge = value def use_ability(self, player): """Traitor ability poisons other players. Watch out! If a traitor poisons a traitor, it will instantly kill them!""" if self.current_ability_charge == 100: if player._role == "Survivor": self.current_ability_charge = 0 player.current_hp -= 100 player.current_hunger += 25 print(f"{self.name} poisoned {player.name}") else: self.current_ability_charge = 0 player.current_hp = 0 print(f"{self.name} killed {player.name}!") def die(self): print(f"{self.name} the {self._role} has perished! Good Riddance.")
N=int(input("Tamano de la lista: ")) A=[int(input("Inserte un numero: ")) for x in range(N)] for x in range(1,N): i=x-1 j=A[x] while i>=0 and j<A[i]: A[i+1]=A[i] i=i-1 A[i+1]=j print (A)
Name='Joel' weight=80 str="this is string example.....wow!!" str2="THIS IS STRING EXAPLE" print "My name is %s and weight is %d kg!" % (Name,weight) print"------------------------------------------" print"str.capitalize() : ", str.capitalize() #this works of make the first word in mayuscula print"---------------------------------------" print str2.lower() print"-------------------------------------------" suffix="wow!!" print str.endswith(suffix) print str.endswith(suffix,20) # this works compare an word if is in the string print"-------------------------------------------" print str.replace("is","was") print str.replace("is","was",3)
A=257 B=257 if( A is B): print"is true" else: print "is false" print "---------------------" if not (A is B): print"is false" else: print "is true"
import sys import time MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.20, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } profit = 0 resources = { "water": 300, "milk": 200, "coffee": 100, } # animation = ["10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"] def animatron(): animation = ["[■□□□□□□□□□]", "[■■□□□□□□□□]", "[■■■□□□□□□□]", "[■■■■□□□□□□]", "[■■■■■□□□□□]", "[■■■■■■□□□□]", "[■■■■■■■□□□]", "[■■■■■■■■□□]", "[■■■■■■■■■□]", "[■■■■■■■■■■]"] for i in range(len(animation)): time.sleep(0.2) sys.stdout.write("\r" + animation[i % len(animation)]) sys.stdout.flush() print("\n") def sufficient_resources(order_ingredients): """True if order can be made, False if insufficient ingredients""" for i in order_ingredients: if order_ingredients[i] >= resources[i]: print(f'Sorry, not enough {i} ☹️') return False return True def process_coins(): """Returns total calculated from coins inserted""" print('Please insert coins 🪙') total = int(input('How many 1€ coins?\n')) * 1 total += int(input('How many 0,50€ coins?\n')) * 0.5 total += int(input('How many 0,20€ coins?\n')) * 0.2 total += int(input('How many 0,10€ coins?\n')) * 0.1 return total def transaction_successful(received, drink_cost): """Return True when payment accepted. False if insufficient""" if received >= drink_cost: change = round(received - drink_cost, 2) print(f'Here\'s your change: {change}€') global profit profit += drink_cost return True else: print('Sorry, not enough money. Coins refunded 🥲') return False def make_coffee(name, order_ingredients): """Deduct ingredients from resources""" for item in order_ingredients: resources[item] -= order_ingredients[item] print(f'Here\'s your {name} ☕️. Enjoy!\n') is_on = True while is_on: order = input('Hi there!😊 \n Espresso(1,20€) | Latte(2,50€) | Cappuccino(3€)\n What would you like?\n') if order == 'off': print('Goodbye now!') is_on = False elif order == 'report': print('Here\'s the latest report:') print(f"Water: {resources['water']}ml") print(f"Milk: {resources['milk']}ml") print(f"Coffee: {resources['coffee']}gr") print(f"Money: €{profit}") elif order not in MENU.keys(): print('Sorry, we don\'t serve hipsters! Bye now 👋 ') is_on = False else: drink = MENU[order] if sufficient_resources(drink['ingredients']): payment = process_coins() if transaction_successful(payment, drink['cost']): print('Coming right up!') animatron() make_coffee(order, drink['ingredients'])
five = 5 ten = 10 print("five is " + ("bigger" if five > ten else "smaller") + " than ten") print("ten is " + ("bigger" if ten > five else "smaller") + " than five")
# def f1(): # x=100 # print(x) # x=+1 # f1() tuple = (1,2,3) tuple.append((4,5)) print(len(tuple))
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ 性能优化示例-循环 @module performance_optimizing_circle @file performance_optimizing_circle.py """ import datetime DOT_RANGE_NUM = 10000000 DOT_WORDS = [ 'test', 'for', 'circle', 'performance', 'optimizing', 'dot' ] def dot_in_circle(): _str = '' for _i in range(DOT_RANGE_NUM): _str = DOT_WORDS[_i % len(DOT_WORDS)].upper() return _str def dot_out_circle(): _str = '' _upper = str.upper for _i in range(DOT_RANGE_NUM): _str = _upper(DOT_WORDS[_i % len(DOT_WORDS)]) return _str def var_out_circle(): _str = '' _upper = str.upper _len = len(DOT_WORDS) for _i in range(DOT_RANGE_NUM): _str = _upper(DOT_WORDS[_i % _len]) return _str if __name__ == '__main__': # 循环内有"."操作 _start = datetime.datetime.now() dot_in_circle() _end = datetime.datetime.now() print('dot_in_circle time: %s' % str((_end - _start).total_seconds())) # 循环内无"."操作 _start = datetime.datetime.now() dot_out_circle() _end = datetime.datetime.now() print('dot_out_circle time: %s' % str((_end - _start).total_seconds())) # 变量计算移出循环 _start = datetime.datetime.now() var_out_circle() _end = datetime.datetime.now() print('var_out_circle time: %s' % str((_end - _start).total_seconds()))
import numpy as np """ Implementation of a Markov chain using states (which can be numbers, strings or even functions)""" class Chain: """Object representing a stochastic markov chain""" def __init__(self, states, transitions): """ Initialize a markov chain with a list of states and list of list of transitions""" assert(len(states) == len(transitions)), \ "number of states and transitions do not match" self._states = states markov_chain = list(zip(states, transitions)) efficient_chain = {} for m in markov_chain: efficient_chain[m[0]] = m[1] self._transitions = efficient_chain def get_states(self): """ Getter function for the states of a markov chain""" return self._states def get_transitions(self): """ Setter function for the (states,transitions) pairs of the markov chain""" return self._transitions def pick_random(self, next_states): """ Given a list of transition functions (probabilities) choose a random next_state and return its index""" random_num = np.random.rand() previous = 0 for i in range(len(next_states)): if random_num <= previous + next_states[i]: return i previous += next_states[i] # Error case return None def step(self, start_state): """ Computes one step along the markov chain""" dist = self._transitions[start_state] index = self.pick_random(dist) return self._states[index] def n_orbit(self, start_state, n=10): """ Returns a numpy array of a list of states""" res = [start_state] next_state = self.step(start_state) for i in range(n): res.append(next_state) next_state = self.step(next_state) return np.array(res) def __repr__(self): return str(self.get_transitions())
if __name__ == '__main__': s = input() isalnum = False isalpha = False isdigit = False islower = False isupper = False for i in s: if i.isalnum(): isalnum = True if i.isalpha(): isalpha = True if i.isdigit(): isdigit = True if i.islower(): islower = True if i.isupper(): isupper = True print(isalnum) print(isalpha) print(isdigit) print(islower) print(isupper) #https://www.hackerrank.com/challenges/string-validators/leaderboard
"""Defines operation functions that can be put on the board""" from model.board.board import Board from model.board.modifiers.resource import Resource def copy_board(dest, src, rect=None, pos=None): """Copies tiles from src board to destinations. If rect is given than a rect, starting from the x,, y corner from the src will be copied to dest at it's topleft corner. If pos is also specified than the copied rect will start at dest at the given position.""" if rect: x, y, width, height = rect if not pos: pos = (0, 0) # default top left for i in range(width): for j in range(height): dest[i + pos[0], j + pos[1]] = src[i + x, j + y] else: min_width = min(src.width, dest.width) min_height = min(src.height, dest.height) for i in range(min_width): for j in range(min_height): dest[i, j] = src[i, j] def increase_width(board): new_board = Board(board.width + 1, board.height) copy_board(new_board, board) return new_board def decrease_width(board): new_board = Board(board.width - 1, board.height) copy_board(new_board, board) return new_board def increase_height(board): new_board = Board(board.width, board.height + 1) copy_board(new_board, board) return new_board def decrease_height(board): new_board = Board(board.width, board.height - 1) copy_board(new_board, board) return new_board def add_resource(board, x, y, category, amount): if board[x, y].has_modifier(Resource): mod = board[x, y].get_modifier(Resource) if mod.category == category: mod.amount += amount return board[x, y].add_modifier(Resource(category, amount)) def remove_resource(board, x, y, category, amount): if board[x, y].has_modifier(Resource): mod = board[x, y].get_modifier(Resource) if mod.category == category: mod.amount -= amount if mod.amount <= 0: board[x, y].remove_modifier(mod) def set_pathable(board, x, y, pathable): board[x, y].pathable = pathable def set_elevation(board, x, y, new_height): board[x, y].elevation = new_height def add_spawn(board, position): board.start_locations.add(position) def remove_spawn(board, position): board.start_locations.remove(position)
''' Time complexity : O(M \times N)O(M×N) where MM is the number of rows and NN is the number of columns. Space complexity : worst case O(M \times N)O(M×N) in case that the grid map is filled with lands where DFS goes by M \times NM×N deep ''' class Solution: def numIslands(self, grid): if not grid: return 0 count = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == '1': self.dfs(grid, row, col) count += 1 return count def dfs(self, grid, row, col): #base case, if not 1, then its not an island if row<0 or col<0 or row>=len(grid) or col>=len(grid[0]) or grid[row][col] != '1': return #update grid with islands we have visited already to not recount grid[row][col] = '#' self.dfs(grid, row+1, col) self.dfs(grid, row-1, col) self.dfs(grid, row, col+1) self.dfs(grid, row, col-1)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root): def collect(node, depth): if node: if depth == len(view): view.append(node.val) collect(node.right, depth+1) collect(node.left, depth+1) view = [] collect(root, 0) return view
class Solution: def jump(self, nums: List[int]) -> int: jump = 0 currJumpEnd = 0 farthest = 0 for index in range(len(nums)-1): farthest = max(farthest, index+nums[index]) #if we've reached the end of currJump and need another jump if index == currJumpEnd: jump+=1 currJumpEnd = farthest return jump
class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 #two pointer approach left = 0 right = len(height) - 1 answer = 0 #when water is greater at one end, left or right, we only need to subtract it from that direction leftMax = height[left] rightMax = height[right] while left < right: #calculate left side if leftMax < rightMax: left+=1 leftMax = max(leftMax,height[left] ) answer += leftMax - height[left] #add in right side so its all in one pass else: right -=1 rightMax = max(rightMax, height[right]) answer += rightMax - height[right] return answer
class Solution: def evalRPN(self, tokens): stack = [] for token in tokens: if token not in "+-/*": stack.append(int(token)) continue number_2 = stack.pop() number_1 = stack.pop() result = 0 if token == "+": result = number_1 + number_2 elif token == "-": result = number_1 - number_2 elif token == "*": result = number_1 * number_2 else: result = int(number_1 / number_2) stack.append(result) return stack.pop()
class Solution: def scheduleCourse(self, courses: List[List[int]]) -> int: #sorts the course according to the 2nd index of all elements in the list courses.sort(key = lambda x:x[1]) #print(courses) #to visualize the code after sorting it maxHeap = [] # to store the negative values of the courses of index to understand more watch the image attached you will get more clarification # to count the courses and to add the total Sum cnt,totSum = 0,0 #traverse the loop upto length of the courses for i in range(len(courses)): #push the negative value of the courses[i][0] into maxHeap heappush(maxHeap,-1*courses[i][0]) #calculate the total number of courses to total Sum and increment the count by 1 totSum += courses[i][0] cnt += 1 #print(maxHeap) #Just to see the elements present in max heap #if total sum exceeds before the loop ends then heap comes into action to find the exact count if totSum > courses[i][1]: #Now negative value in the heap gets poped out and added to the total Sum and the count is decremented by 1. totSum += heappop(maxHeap) cnt -= 1 return cnt
class Solution: def maximumSwap(self, num: int) -> int: #idea: from right to left, have a max at hand, each smaller one is a candidate to swith # 98368: 8 -> 6 -> 3 digits = list(str(num)) max_digit = (-1, -1) #val, index candidate = (-1, -1) # candidate pair of indexes for i in range(len(digits)-1, -1, -1): if int(digits[i]) > max_digit[0]: max_digit = (int(digits[i]), i) elif int(digits[i]) < max_digit[0]: #smaller one found, but this can be replaced with a even smaller one candidate = (i, max_digit[1]) digits[candidate[0]], digits[candidate[1]] = digits[candidate[1]], digits[candidate[0]] return int(''.join(digits))
print('wordcount and frequency') # with open we are reading text.txt file that in our Homework3 folder 'r' open file for reading. with open('text.txt', 'r') as f: f_cotents = f.read() #splitting words word_list=(f_cotents.split()) #checking if this worked print(word_list) #init dictionary ### make empty dictionary d = {} for word in word_list: if word not in d: d[word]=1 else: d[word]+=1 #d[word]=d.get(word, 0) + 1 #empty wordfreq word_freq = [] for key, value in d.items(): word_freq.append((value, key)) #Sorting from high number to the lowest. word_freq.sort(reverse=True) print(word_freq)
a = input('one') b = input('two') m = int(a) n = int(b) def gcd(m, n): if n == 0: print(m) else: print(gcd(n, m%n)) print(gcd(m, n))
def checkrange(name, value, l, u): if not (l <= value <= u): raise ValueError(f'{name} be {l}...{u}') class Datetime: def __init__(self, year, month, day, hour, minute): self._year(year) self.set_month(month) self.set_day(day) self.set_hour(hour) self.smin(minute) def _year(self, year): if type(year) != int: raise TypeError('year must be int') self._year = year def set_month(self, month): checkrange('month', month, 1, 12) self._month = month def set_day(self, day): if self._month in {1,3,5,7,8,10,12}:checkrange('',day,1,31) elif self._month in {4,6,9,11}: checkrange('',day,1,30) elif self._month == 2 and leap(self._year):#leap()還沒定義 checkrange('',day,1,29) else:checkrange('',day,1,28) self._day = day def set_hour(self, hour): checkrange('', hour, 1, 24) self._hour = hour def smin(self, minute): checkrange('', minute, 0, 60) self.min = minute class Datetime2: def checkandset(self, name, value, l, u): if type(name) != str: raise TypeError('name wromg') if not (l <= value <= u): raise ValueError(f'{name} must be {l}...{u}') self.__dict__['_'+ name] = value def __init__(self, year, month, day, hour, minute): self.set_year(year) self.set_month(month) self.set_day(day) self.set_hour(hour) self.smin(minute) def set_year(self, year): if type(year) != int: raise TypeError('year must be int') self._year = year def set_month(self, month): self.checkandset('month', month, 1, 12) def set_day(self, day): if self._month in {1,3,5,7,8,10,12}: self.checkandset('day',day,1,31) elif self._month in {4,6,9,11}: self.checkandset('day',day,1,30) elif self._month == 2 and leap(self._year): self.checkandset('day',day,1,29) else:self.checkandset('day',day,1,28) def set_hour(self, hour): self.checkandset('h', hour, 1, 24) def smin(self, minute): self.checkandset('m', minute, 0, 60) class Datetime3:#most completed year_from = -5000# year_to = +4000# def checkandset(self, name, value, l, u): if type(name) != str: raise TypeError('name wromg') if not (l <= value <= u): raise ValueError(f'{name} must be {l}...{u}') self.__dict__['_'+ name] = value def __init__(self, year, month, day, hour, minute): self.set_year(year) self.set_month(month) self.set_day(day) self.set_hour(hour) self.smin(minute) @classmethod#如果不加@classmethod,改year_from、to 要用Datetime3.year_from、to = 9000(ex)\ #加了後,可用yearrange去改year_from、to def yearrange(sel,l,u):#sel should be chamged with "cls", but i think it doesn't matter sel.year_from, sel.year_to = l, u def set_year(self, year):# self.checkandset('year', year, self.year_from, self.year_to) def get_month(self): return self.month# def set_month(self, month): if not (1 <= month <= 12): raise ValueError(f'month must be 1 ... 12') self.__dict__['month'] = month _month = property(lambda self: self.get_month(), lambda self, v: self.set_month(v)) #def get_month(self):#原本(上面的版本為a._month可做修改,此原版為a.month可作修改,即a.month = 8可這樣改) #return self.month#續上,可用dt.__dict__去看 #def set_month(self, month): #self.checkandset('month', month, 1, 12) #month = property(lambda self: slef.get._month(), lambda self, v: self.set_month(v)) def set_day(self, day): if self.month in {1,3,5,7,8,10,12}:#原版為self._month self.checkandset('day',day,1,31) elif self.month in {4,6,9,11}:#原版為self._month self.checkandset('day',day,1,30) elif self.month == 2 and self.leap(self._year):#,#is use self.leap not cls.leap self.checkandset('day',day,1,29)#原版為self._month else:self.checkandset('day',day,1,28) def set_hour(self, hour): self.checkandset('h', hour, 1, 24) def smin(self, minute): self.checkandset('m', minute, 0, 60) @staticmethod def leap(year): if (year % 400 == 0): return True else: if(year % 4 != 0): return False else: if (year % 100 == 0): return False else: return True
#!/usr/bin/env python3 a = input('what') x = int(a) if x > 0: print('ghh') else: print('kjj')
def stackinterpreter(): l = [] while True: line = input('command') words = line.split() if len(words) == 0: pass elif words[0] == 'show': print(l) elif words[0] == 'push': l.extend(words[1:]) elif words[0] == 'pop': print(l.pop()) elif words[0] == 'quit': break else: print('unknown commmand')
"""Write a program which takes 4 inputs, where each input consists of 2 numbers in the format x,y. You are required to print a two dimensional array having x rows and y columns for each input. The elements of the arrays should be whole numbers starting from 1 and incrementing by 1. Example Suppose the following 4 inputs are given to the program: 2,2 2,3 3,3 3,4 Then, the output of the program should be: [[1, 2], [3, 4]] [[1, 2, 3], [4, 5, 6]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] Note: You should assume that input to the program is from console input (raw_input) """ import numpy as np print('Enter The First Dimension:') D1 = input().split(",") print('Enter The Second Dimension:') D2 = input().split(",") print('Enter The Thrid Dimension:') D3 = input().split(",") print('Enter The Fourth Dimension:') D4 = input().split(",") num = 1 M1 = np.zeros((int(D1[0]),int(D1[1]))) for row in range (0,int(D1[0])): for col in range(0,int(D1[1])): M1[row][col] = num num += 1 print(M1) num = 1 M2 = np.zeros((int(D2[0]),int(D2[1]))) for row in range (0,int(D2[0])): for col in range(0,int(D2[1])): M2[row][col] = num num += 1 print(M2) num = 1 M3 = np.zeros((int(D3[0]),int(D3[1]))) for row in range (0,int(D3[0])): for col in range(0,int(D3[1])): M3[row][col] = num num += 1 print(M3) num = 1 M4 = np.zeros((int(D4[0]),int(D4[1]))) for row in range (0,int(D4[0])): for col in range(0,int(D4[1])): M4[row][col] = num num += 1 print(M4)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ node = head if not node or not node.next: return None ctr = 1 result = head while node.next: if ctr > n: result = result.next node = node.next ctr = ctr + 1 if ctr == n: head = head.next else: result.next = result.next.next return head
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ results = [] def findCombination(start, target, result, results): if target == 0: results.append(result) for i in range(start, len(candidates)): if target < candidates[i]: return findCombination(i, target - candidates[i], result + [candidates[i]], results) candidates.sort() findCombination(0, target, [], results) return results if __name__ == '__main__': assert Solution().combinationSum([2, 3], 7) == [[2, 2, 3]] assert Solution().combinationSum([2, 3, 5], 7) == [[2, 2, 3], [2, 5]] assert Solution().combinationSum([2, 3, 6, 7], 7) == [[2, 2, 3], [7]]
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } if digits == '': return [] def combine(x, y): r = [] for i in x: for j in mapping[y]: r.append(i + j) return r return reduce(combine, list(str(digits)), ['']) if __name__ == "__main__": assert Solution().letterCombinations("") == [] assert Solution().letterCombinations("2") == ["a","b","c"] assert Solution().letterCombinations("23") == [ "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf" ]
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ results = [] def findCombination(start, target, result, results): if target == 0: results.append(result) for i in range(start, len(candidates)): if target < candidates[i]: return if not (i > start and candidates[i] == candidates[i-1]): findCombination(i + 1, target - candidates[i], result + [candidates[i]], results) candidates.sort() findCombination(0, target, [], results) return results if __name__ == '__main__': assert Solution().combinationSum2([2, 3], 7) == [] assert Solution().combinationSum2([2, 3, 5], 7) == [[2, 5]] assert Solution().combinationSum2([2, 2, 3, 6, 7], 7) == [[2, 2, 3], [7]] assert Solution().combinationSum2([3, 1, 3, 5, 1, 1], 8) == \ [[1, 1, 1, 5], [1, 1, 3, 3], [3, 5]] assert Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8) == \ [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
def binarySearch(values, k): top = len(values)-1 bottom = 0 values.sort() print(values) found = False while(found != True): mid = (top+bottom) // 2 if(values[mid] == k): print(str(k) + " found at index: " + str(top)) found = True return True elif(values[mid] < k): bottom = mid + 1 elif(values[mid] > k): top = mid - 1 else: return "Not found" values = [1,2,3,4,5,6,7] binarySearch(values, 3)
from sys import argv from random import randint from math import gcd, log from prime import factorize DEFAULT_S = 10 def p1_pollard(n, primes, s): base = primes[:s] a = randint(2, n - 2) d = gcd(a, n) if d >= 2: return d for i in range(s): power = int(log(n) / log(base[i])) a = (a * pow(a, pow(base[i], power), n)) % n d = gcd(a - 1, n) return d if 1 < d < n else -1 def main(): n = int(argv[1]) with open('p.txt') as f: primes = list(map(int, f.read().split('\n'))) s = DEFAULT_S if len(argv) < 3 else int(argv[2]) factors = factorize(n, p1_pollard, primes, s) print('\n'.join(map(str, factors.items()))) if __name__ == '__main__': main()
#Víctor Hugo Flores Pineda 155990 #Rebeca Baños García 157655 #Python 3 import numpy as np import matplotlib.pyplot as plt import huffman as hf #1 x = np.random.randint(1,6,20) print("Cadena aleatoria de numeros: ") print(x) print("\n") #2 xB = np.zeros(20) for i in range(0,20): xB[i] = np.binary_repr(x[i],3) print("Representación binaria de la cadena original:") print(xB) longT = 0 for i in range(0,20): longT = longT + len(str(xB[i])) -2 print("Longitud total de cadena bianria: " + str(longT)) longP = longT/20 print("Longitud pormedio por simbolo: " + str(longP)) print("\n") #4 #Seis bits #4 def prob(vec): p = np.zeros(5) for i in range(0,20): if vec[i] == 1: p[0] = p[0] + 1 elif vec[i] == 2: p[1] = p[1] +1 elif vec[i] == 3: p[2] = p[2] +1 elif vec[i] == 4: p[3] = p[3] + 1 else: p[4] = p[4] +1 for i in range(0,5): p[i] = p[i]/20 return p probabilidad = prob(x) print("probabilidad de aparición de cada simbolo: ") print(probabilidad) print("\n") #5 huffVec = ([('1',probabilidad[0]*20), ('2',probabilidad[1]*20), ('3',probabilidad[2]*20), ('4',probabilidad[3]*20),('5',probabilidad[4]*20)]) xH = hf.codebook(huffVec) print("Codigo Huffman: ") print(xH) longT = len(xH['1']) + len(xH['2']) + len(xH['3']) + len(xH['4']) + len(xH['5']) longP = longT/5 print("Longitud pormedio por simbolo: " + str(longP)) print("\n") #6 cadH = ["" for x in range(len(x))] longT = 0 for i in range(0,len(x)): if(x[i] == 1): cadH[i] = xH['1'] elif (x[i] == 2): cadH[i] = xH['2'] elif (x[i] == 3): cadH[i] = xH['3'] elif (x[i] == 4): cadH[i] = xH['4'] elif (x[i] == 5): cadH[i] = xH['5'] longT = longT + len(cadH[i]) print("Cadena aleatoria original en representación Huffman:") print(cadH) print("Longitud total de cadena Huffman: " + str(longT)) #8 cadDec = np.zeros(len(cadH)) for i in range(0,len(cadH)): if(cadH[i] == xH['1']): cadDec[i] = 1 elif (cadH[i] == xH['2']): cadDec[i] = 2 elif (cadH[i] == xH['3']): cadDec[i] = 3 elif (cadH[i] == xH['4']): cadDec[i] = 4 elif (cadH[i] == xH['5']): cadDec[i] = 5 print("Cadena decodificada") print(cadDec)
List=['p','y','t','h','o','n','f','o','r','g','a','m','e','s'] sliced_List = List[3:8] sliced_List = List[::-1] print(sliced_List) x={"apple","banana","cherey"} y={"google","microsoft","facebook"} z=x.isdisjoint(y) print(z) x={'a','b','c'} y={"f","e","d","c","b","a"} z=x.issuperset(y) print(z) x={"f","e","d","c","b","a"} y={"a","b","c"} z=x.symmetric_difference(y) print(z) x={"apple","banana","cherey"} y={"google","microsoft","facebook"} x.symmetric_difference_update(y) print(x) x={"apple","banana","cherey"} y={"google","microsoft","facebook"} z=x.union(y) print(z) x={"apple","banana","cherey"} y={"google","microsoft","facebook"} x.update(y) print(x)
import os from tkinter import * from PIL import ImageTk, Image root = Tk() #adding a title root.title("Image-Viewer") #adding a favicon/icon root.iconbitmap("3-Basics_2\\favicon.ico") # #adding an image # my_img = ImageTk.PhotoImage(Image.open("3-Basics_2\\images\\picture.png")) # #creating a label for the image # my_label = Label(root, image=my_img) # my_label.grid(row=0, column=0, columnspan=3) #scanning the image folder and putting it in list #list the directories inside image folder images = os.listdir("3-Basics_2\\images") image_list = [i for i in images] #variable for position in relative to image_list position = 0 #function for buttons def forward(): global my_label global my_img global image_list global position my_label.grid_forget() if position == len(image_list) - 1: position = 0 else: position = position + 1 my_img = ImageTk.PhotoImage( Image.open("3-Basics_2\\images\\" + image_list[position])) my_label = Label(root, image=my_img) my_label.grid(row=0, column=0, columnspan=3) def backword(): global my_label global my_img global image_list global position my_label.grid_forget() if position == 0: position = len(image_list) - 1 else: position = position - 1 my_img = ImageTk.PhotoImage( Image.open("3-Basics_2\\images\\" + image_list[position])) my_label = Label(root, image=my_img) my_label.grid(row=0, column=0, columnspan=3) def refresh(): global my_img global image_list images = os.listdir("3-Basics_2\\images") image_list = [i for i in images] #adding an image my_img = ImageTk.PhotoImage( Image.open("3-Basics_2\\images\\" + image_list[position])) #creating a label for the image my_label = Label(root, image=my_img) my_label.grid(row=0, column=0, columnspan=3) #creating the buttons forward_button = Button(root, text=">>", fg="#2E86C1", bg="#2C3E50", command=forward) back_button = Button(root, text="<<", fg="#2E86C1", bg="#2C3E50", command=backword) refresh_button = Button(root, text="Refresh Images", fg="#2E86C1", bg="#2C3E50", command=refresh) #grid-ing the buttons forward_button.grid(row=1, column=2) back_button.grid(row=1, column=0) refresh_button.grid(row = 1, column= 1) #running the main loop root.mainloop()
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import json #讀取 json 的程式 def jsonTextread(path, target): with open(path,encoding="utf-8") as f: inputtext = json.load(f)[target] return inputtext #將字串轉為「句子」列表的程式 def text2Sentence(inputSTR): sentence_LIST = [] start = 0 k = 0 length_STR = len(inputSTR) while k < length_STR: for i in [".","…"]: while inputSTR[k]==i: inputSTR=inputSTR[:k]+inputSTR[k+1:] length_STR=len(inputSTR) k = k+1 for i in range(0,length_STR): number = 0 if (inputSTR[i]==","): for j in range(0,10): if((inputSTR[i-1]==str(j))|(inputSTR[i+1]==str(j))): number = number+1 print("ya") if (number == 2): pass print("NO!") else: sentence_LIST.append(inputSTR[start:i]) start = i+1 print("Ya") for j in ["、",",","。"]: if (inputSTR[i]==j): sentence_LIST.append(inputSTR[start:i]) start = i+1 break return sentence_LIST if __name__== "__main__": #設定要讀取的 news.json 路徑 path_STR = "./example/news.json" #將 news.json 利用 [讀取 json] 的程式打開 inputSTR = jsonTextread(path_STR,"text") #將讀出來的內容字串傳給 [將字串轉為「句子」 列表」]的程式,存為 newsLIST news_LIST = text2Sentence(inputSTR) #設定要讀取的 test.json 路徑 path_TEXT = "./example/test.json" #將 test.json 的 sentenceLIST 內容讀出,存為 testLIST test_LIST = jsonTextread(path_TEXT,"sentence") #測試是否達到作業需求 print(news_LIST) print(test_LIST) if news_LIST == test_LIST: print("作業過關!") else: print("作業不過關,請回到上面修改或是貼文求助!")
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import json #讀取 json 的程式 def jsonReader(jsonFILE): with open(jsonFILE, encoding="utf-8") as f: jsonContent = f.read() txt = json.loads(jsonContent) try: return txt["text"] except: return txt["sentence"] #將字串轉為「句子」列表的程式 def sentence2LIST(inputSTR): inputSTR = inputSTR.replace("…", "") inputSTR = inputSTR.replace("...", "") for item in ("「", ",", "、", "」", "。", "\"", ","): inputSTR = inputSTR.replace(item, "<mark>") # print(inputSTR) while "2<mark>718" in inputSTR: inputSTR = inputSTR.replace("2<mark>718", "2,718") inputSTR = inputSTR.split("<mark>") return inputSTR if __name__== "__main__": #設定要讀取的 news.json 路徑 newsjsonPath = "./example/news.json" #將 news.json 利用 [讀取 json] 的程式打開 jsonDICT = jsonReader(newsjsonPath) #將讀出來的內容字串傳給 [將字串轉為「句子」 列表」]的程式,存為 newsLIST newsLIST = sentence2LIST(jsonDICT) newsLIST.remove(newsLIST[-1]) #設定要讀取的 test.json 路徑 testPath = "./example/test.json" #將 test.json 的 sentenceLIST 內容讀出,存為 testLIS testjsonDICT = jsonReader(testPath) testLIST = testjsonDICT #print(newsLIST) #print(testLIST) #測試是否達到作業需求 if newsLIST == testLIST: print("作業過關!") else: print("作業不過關,請回到上面修改或是貼文求助!")
# search.py # --------------- # Licensing Information: You are free to use or extend this projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to the University of Illinois at Urbana-Champaign # # Created by Michael Abir (abir2@illinois.edu) on 08/28/2018 """ This is the main entry point for MP1. You should only modify code within this file -- the unrevised staff files will be used for all other files and classes when code is run, so be careful to not modify anything else. """ # Search should return the path and the number of states explored. # The path should be a list of tuples in the form (row, col) that correspond # to the positions of the path taken by your search algorithm. # Number of states explored should be a number. # maze is a Maze object based on the maze from the file specified by input filename # searchMethod is the search method specified by --method flag (bfs,dfs,greedy,astar) def search(maze, searchMethod): return { "bfs": bfs, "dfs": dfs, "greedy": greedy, "astar": astar, }.get(searchMethod)(maze) def bfs(maze): # TODO: Write your code here # return path, num_states_explored start_point=maze.getStart() row,col=maze.getDimensions() visited=[] previous=[] for i in range(row): visited.append([]) previous.append([]) for j in range(col): visited[i].append(False) previous[i].append((0,0)) objectives=maze.getObjectives() obj_size=len(objectives) found=False visited[start_point[0]][start_point[1]]=True previous[start_point[0]][start_point[1]]=(start_point[0],start_point[1]) reverse_path=[] path=[] q=[] q.append(start_point) num_states_explored=0 while found==False: current_point=q[0] q.remove(current_point) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] for j in range(obj_size): if neighbor[0]==objectives[j][0] and neighbor[1]==objectives[j][1]: previous[neighbor[0]][neighbor[1]]=(corx,cory) it=neighbor path.append(it) while it!=start_point: it=previous[it[0]][it[1]] reverse_path.append(it) print(it) for i in range(len(reverse_path)): path.append(reverse_path[len(reverse_path)-1-i]) return path, num_states_explored if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True previous[neighbor[0]][neighbor[1]]=(corx,cory) q.append(neighbor) num_states_explored+=1 return [], 0 def dfs(maze): # TODO: Write your code here # return path, num_states_explored start_point=maze.getStart() row,col=maze.getDimensions() visited=[] previous=[] for i in range(row): visited.append([]) previous.append([]) for j in range(col): visited[i].append(False) previous[i].append((0,0)) objectives=maze.getObjectives() obj_size=len(objectives) found=False visited[start_point[0]][start_point[1]]=True previous[start_point[0]][start_point[1]]=(start_point[0],start_point[1]) reverse_path=[] path=[] q=[] q.append(start_point) num_states_explored=0 while found==False: current_point=q[len(q)-1] q.remove(current_point) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] for j in range(obj_size): if neighbor[0]==objectives[j][0] and neighbor[1]==objectives[j][1]: previous[neighbor[0]][neighbor[1]]=(corx,cory) it=neighbor path.append(it) while it!=start_point: it=previous[it[0]][it[1]] reverse_path.append(it) print(it) for i in range(len(reverse_path)): path.append(reverse_path[len(reverse_path)-1-i]) return path, num_states_explored if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True previous[neighbor[0]][neighbor[1]]=(corx,cory) q.append(neighbor) num_states_explored+=1 return [], 0 def greedy(maze): # TODO: Write your code here # return path, num_states_explored start_point=maze.getStart() row,col=maze.getDimensions() visited=[] correct_path=[] examined=[] for i in range(row): visited.append([]) examined.append([]) for j in range(col): visited[i].append(False) examined[i].append(False) objectives=maze.getObjectives() obj_size=len(objectives) objective=objectives[0] visited[start_point[0]][start_point[1]]=True examined[start_point[0]][start_point[1]]=True current_point=start_point path=[] q=[] q.append(start_point) num_states_explored=0 while len(q)!=0: distance=1000 closest_idx=0 print(current_point[0],current_point[1]) for i in range(len(q)): new_distance=abs(q[i][0]-objective[0])+abs(q[i][1]-objective[1]) if new_distance<distance: closest_idx=i distance=new_distance print(i) current_point=q[closest_idx] q.remove(current_point) corx=current_point[0] cory=current_point[1] if current_point==objective: print('666') examined[corx][cory]=True break else: neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True q.append(neighbor) examined[corx][cory]=True for i in range(row): for j in range(col): print(i,j,examined[i][j]) end_point=objective path.append(end_point) current_point=end_point num_states_explored+=1 while current_point!=start_point: corx=current_point[0] cory=current_point[1] print(corx,cory) neighbors=maze.getNeighbors(corx,cory) if len(neighbors)==1 and examined[neighbors[0][0]][neighbors[0][1]]==False: print('first') path.remove(current_point) current_point=path[len(path)-1] elif len(neighbors)==2 and examined[corx][cory]==False: print('second') path.remove(current_point) current_point=path[len(path)-1] else: print('thrid') examined[corx][cory]=False has_examined=False for i in range(len(neighbors)): neighbor=neighbors[i] print(i) if examined[neighbor[0]][neighbor[1]]==True: path.append(neighbor) current_point=neighbor num_states_explored+=1 has_examined=True break if has_examined==False: path.remove(current_point) current_point=path[len(path)-1] print('no examined') for i in range(len(path)): correct_path.append(path[len(path)-1-i]) return path, num_states_explored def astar(maze): # TODO: Write your code here # return path, num_states_explored start_point=maze.getStart() row,col=maze.getDimensions() visited=[] previous=[] successorg=[] successorf=[] successorh=[] for i in range(row): visited.append([]) successorg.append([]) successorf.append([]) successorh.append([]) for j in range(col): visited[i].append(False) successorg[i].append(-1) successorf[i].append(-1) successorh[i].append(-1) objectives=maze.getObjectives() obj_size=len(objectives) found=False visited[start_point[0]][start_point[1]]=True successorg[start_point[0]][start_point[1]]=0 path=[] q=[] q.append(start_point) num_states_explored=0 while len(q)!=0: current_point=q[0] q.remove(current_point) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True successorg[neighbor[0]][neighbor[1]]=successorg[corx][cory]+1 q.append(neighbor) else: if successorg[neighbor[0]][neighbor[1]]>successorg[corx][cory]+1: successorg[neighbor[0]][neighbor[1]]=successorg[corx][cory]+1 q=[] for i in range(row): for j in range(col): visited[i][j]=False if obj_size==1: end_point=objectives[0] q.append(end_point) successorf[end_point[0]][end_point[1]]=0 visited[end_point[0]][end_point[1]]=True while len(q)!=0: current_point=q[0] q.remove(current_point) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True successorh[neighbor[0]][neighbor[1]]=successorh[corx][cory]+1 q.append(neighbor) else: if successorh[neighbor[0]][neighbor[1]]>successorh[corx][cory]+1: successorh[neighbor[0]][neighbor[1]]=successorh[corx][cory]+1 for i in range(row): for j in range(col): visited[i][j]=False successorf[i][j]=successorg[i][j]+successorh[i][j] path=[] num_states_explored=0 current_point=start_point visited[current_point[0]][current_point[1]]=True visited[1][1]=True path.append(start_point) while found==False: corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) neighborf=100000 neighbor_idx=5 for i in range(len(neighbors)): neighbor=neighbors[i] if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True if neighbor==objectives[0]: path.append(neighbor) num_states_explored+=1 print('ass') return path,num_states_explored if successorf[neighbor[0]][neighbor[1]]<neighborf: neighborf=successorf[neighbor[0]][neighbor[1]] neighbor_idx=i elif successorf[neighbor[0]][neighbor[1]]==neighborf: if successorh[neighbor[0]][neighbor[1]]<successorh[corx][cory]: neighbor_idx=i path.append(neighbors[neighbor_idx]) current_point=neighbors[neighbor_idx] num_states_explored+=1 return [], 0 def astar_multiple(maze): # TODO: Write your code here # return path, num_states_explored start_point=maze.getStart() row,col=maze.getDimensions() objectives=maze.getObjectives() points=objectives distance=[] visited=[] previous=[] successorf=[] successorg=pre_astar(maze,objectives) for m in range(row): successorf.append([]) distance.append([]) for n in range(col): successorf[m].append([]) distance[m].append([]) for i in range(row): successorf[m][n].append([]) distance[m][n].append([]) visited.append([]) for j in range(col): distance[m][n][i].append(-1) successorf[m][n][i].append(-1) visited[i].append(-1) distance_points=[] distance_points.append(start_point) for i in range(len(objectives)): distance_points.append(objectives[i]) for i in range(len(distance_points)): for j in range(len(distance_points)): if i!=j: distance[distance_points[i][0]][distance_points[i][1]][distance_points[j][0]][distance_points[j][1]]=bfs_astar(maze,distance_points[i],distance_points[j]) current_point=start_point simple_path=[] simple_path.append(start_point) while len(points)!=0: closest_point,idx=closest(maze,current_point,points,distance) current_point=closest_point points.remove(closest_point) simple_path.append(current_point) for i in range(len(simple_path)): print('pathpoint',simple_path[i]) print('done') for i in range(row): for j in range(col): visited[i][j]=False path=[] num_states_explored=0 current_point=start_point current_start=start_point current_goal=simple_path[1] goal_idx=1 visited[current_point[0]][current_point[1]]=True visited_goal=[] visited_goal.append(start_point) path.append(start_point) get_to_new_goal=False while current_start!=simple_path[len(simple_path)-1]: if get_to_new_goal==True: #print('current_start',current_start) #print('current_goal',current_goal) get_to_new_goal=False for i in range(row): for j in range(col): visited[i][j]=False #for i in range(len(visited_goal)): #visited[visited_goal[i][0]][visited_goal[i][1]]=True #print(visited_goal[i]) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) neighborf=100000 neighbor_idx=0 #print('current',current_point) for i in range(len(neighbors)): neighbor=neighbors[i] #print(neighbor,visited[neighbor[0]][neighbor[1]]) #print(current_point) #print(successorg[current_start[0]][current_start[1]][neighbor[0]][neighbor[1]]) if visited[neighbor[0]][neighbor[1]]==False: #print('ttttt',current_start) visited[neighbor[0]][neighbor[1]]=True if neighbor==current_goal: visited_goal.append(neighbor) #path.append(neighbor) current_start=neighbor neighbor_idx=i get_to_new_goal=True if (goal_idx+1)==len(simple_path): for i in range(len(path)): print('path',path[i]) path.append(current_goal) return path,num_states_explored else: goal_idx+=1 current_goal=simple_path[goal_idx] break if successorg[current_start[0]][current_start[1]][neighbor[0]][neighbor[1]]+successorg[current_goal[0]][current_goal[1]][neighbor[0]][neighbor[1]]<neighborf: neighborf=successorg[current_start[0]][current_start[1]][neighbor[0]][neighbor[1]]+successorg[current_goal[0]][current_goal[1]][neighbor[0]][neighbor[1]] neighbor_idx=i #print('second',current_start) elif successorg[current_start[0]][current_start[1]][neighbor[0]][neighbor[1]]+successorg[current_goal[0]][current_goal[1]][neighbor[0]][neighbor[1]]==neighborf: #print('third',current_start) if successorg[current_goal[0]][current_goal[1]][neighbor[0]][neighbor[1]]<successorg[current_goal[0]][current_goal[1]][neighbors[neighbor_idx][0]][neighbors[neighbor_idx][1]]: neighbor_idx=i path.append(neighbors[neighbor_idx]) current_point=neighbors[neighbor_idx] return [], 0 def smallest_successorf(maze,start,objectives,successorg): smallest_f=100000 smallest_idx=0 for i in range(len(objectives)): successorf=successorg[start[0]][start[1]][objectives[i][0]][objectives[i][1]]+successorg[objectives[i][0]][objectives[i][1]][start[0]][start[1]] if successorf<smallest_f: smallest_f=successorf smallest_idx=i return objectives[smallest_idx],smallest_idx def closest(maze,start,objectives,distance): smallest_distance=100000 smallest_idx=0 for i in range(len(objectives)): if distance[start[0]][start[1]][objectives[i][0]][objectives[i][1]]<smallest_distance: smallest_distance=distance[start[0]][start[1]][objectives[i][0]][objectives[i][1]] smallest_idx=i return objectives[smallest_idx],smallest_idx def bfs_astar(maze,start_point,end_point): # TODO: Write your code here # return path, num_states_explored row,col=maze.getDimensions() visited=[] previous=[] for i in range(row): visited.append([]) previous.append([]) for j in range(col): visited[i].append(False) previous[i].append((0,0)) found=False visited[start_point[0]][start_point[1]]=True previous[start_point[0]][start_point[1]]=(start_point[0],start_point[1]) reverse_path=[] path=[] q=[] q.append(start_point) num_states_explored=0 while len(q)!=0: current_point=q[0] q.remove(current_point) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] if neighbor[0]==end_point[0] and neighbor[1]==end_point[1]: previous[neighbor[0]][neighbor[1]]=(corx,cory) it=neighbor path.append(it) while it!=start_point: it=previous[it[0]][it[1]] reverse_path.append(it) #print(it) for i in range(len(reverse_path)): path.append(reverse_path[len(reverse_path)-1-i]) return len(path) if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True previous[neighbor[0]][neighbor[1]]=(corx,cory) q.append(neighbor) num_states_explored+=1 return [], 0 def pre_astar(maze,objectives): # TODO: Write your code here # return path, num_states_explored start_point=maze.getStart() row,col=maze.getDimensions() points=[] points.append(start_point) for i in range(len(objectives)): points.append(objectives[i]) visited=[] successorg=[] for m in range(row): successorg.append([]) for n in range(col): successorg[m].append([]) for i in range(row): successorg[m][n].append([]) for j in range(col): successorg[m][n][i].append(-1) for i in range(row): visited.append([]) for j in range(col): visited[i].append(False) for p in range(len(points)): for k in range(row): for j in range(col): visited[k][j]=False visited[points[p][0]][points[p][1]]=True successorg[points[p][0]][points[p][1]][points[p][0]][points[p][1]]=0 q=[] q.append(points[p]) num_states_explored=0 while len(q)!=0: current_point=q[0] q.remove(current_point) corx=current_point[0] cory=current_point[1] neighbors=maze.getNeighbors(corx,cory) for i in range(len(neighbors)): neighbor=neighbors[i] if visited[neighbor[0]][neighbor[1]]==False: visited[neighbor[0]][neighbor[1]]=True successorg[points[p][0]][points[p][1]][neighbor[0]][neighbor[1]]=successorg[points[p][0]][points[p][1]][corx][cory]+1 q.append(neighbor) else: if successorg[points[p][0]][points[p][1]][neighbor[0]][neighbor[1]]>successorg[points[p][0]][points[p][1]][corx][cory]+1: successorg[points[p][0]][points[p][1]][neighbor[0]][neighbor[1]]=successorg[points[p][0]][points[p][1]][corx][cory]+1 return successorg
# tips_07.py # coding:utf-8 ''' time.clock(): 获取毫秒信息 ''' import time start = time.clock() for i in range(10000): print i end = time.clock() print start, end print 'different is %6.3f' % (end - start)
# test_interview_10.py # coding: utf-8 ''' 十道题 1. 讲下list和tuple的区别 2. 讲下类方法和静态方法的区别 3. list的切片用法 4. 强制转换 5. 编程实现十进制转换为八进制 6. copy和deepcopy的区别 7. lamda的使用 8. with的使用 9. <.*>和<.*?>匹配的区别 10. Set如何使用? ''' seq = [1,2,3,4] def compare(a1,a2): if a1==a2: print 'correct' else: print 'wrong' compare(seq[:2],[1,2]) # 不包含右边所在的2, 只包含0,1 compare(seq[-2:],[3, 4]) compare(seq[10:],[]) #没有元素的list,不是None compare(seq[::-1],[4,3,2,1]) compare(seq[:],[1,2,3,4]) print id(seq[:])==id(seq) # False, 也就是说seq[:]和seq不是一个instance # id()函数不多见 ''' Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. ''' ''' 强制转换: · int(x) 将x转换为一个整数 · float(x) 将x转换到一个浮点数 · str(x) 将对象 x 转换为字符串 · tuple(s) 将序列 s 转换为一个元组 · list(s) 将序列 s 转换为一个列表 · set(s) 将序列 s 转换为一个集合 int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 complex(real [,imag ]) 创建一个复数 str(x ) 将对象 x 转换为字符串 repr(x ) 将对象 x 转换为表达式字符串 eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象 tuple(s ) 将序列 s 转换为一个元组 list(s ) 将序列 s 转换为一个列表 chr(x ) 将一个整数转换为一个字符 unichr(x ) 将一个整数转换为Unicode字符 ord(x ) 将一个字符转换为它的整数值 hex(x ) 将一个整数转换为一个十六进制字符串 oct(x ) 将一个整数转换为一个八进制字符串 ''' ''' 用算法实现十进制到八进制的转换 提示: 难点在于:多项式的表达 1. 先找到最高阶层的系数 2. 然后用循环法找到次高,。。。。0阶层的系数 3. 将系数放在list 4. 将系数list转换为str,返回str 5. 幂的表达,a**b ''' s = 100 def my_oct(x): xi_list = [] n=0 # t 是最高幂 while True: if x / 8**n < 8: break n += 1 xi_list.append(x/(8**n)) temp = x for i in range(n,0,-1): temp = temp- xi_list[-1]* 8**i result = temp/(8**(i-1)) xi_list.append(result) value = '0' for item in xi_list: value += str(item) return value print my_oct(10000), type(my_oct(10000)) print oct(10000), type(oct(10000)) ''' 类方法和静态方法 什么情况下使用静态方法- 普通函数 Python使用静态方法类似函数工具使用,一般尽量少用静态方法 1)静态方法无需传入self参数,类成员方法需传入代表本类的cls参数; 2)从第1条,静态方法是无法访问实例变量的,而类成员方法也同样无法访问实例变量,但可以访问类变量; 3)静态方法有点像函数工具库的作用,而类成员方法则更接近类似Java面向对象概念中的静态方法。 ''' import math print math.sqrt(10) # 静态方法 ''' copy 和 deepcopy的区别 copy嵌套数组时,copy只copy第一层,第二层是共享的。 deepcopy是完全在内存中区分开 ''' import copy list1 = [[1,2],[3,4],[5,6],[7,8]] list2 = copy.copy(list1) print id(list1[0]) print id(list2[0]) # 指向的元素1的地址一致,说明两者指向同一个元素如果我去修改list1的元素0,那么list2也会改变 #下面看list内指向Obj的情况 list3 = copy.deepcopy(list1) print id(list3[0]) # 指向的元素1地址变化了,这说明list3完全是一个新的数组 class Dog: def __init__(self,name): self.name = name def __repr__(self): return self.name oudy = Dog('oudy') candy = Dog('candy') tom = Dog('tom') dog_list1 = [oudy,candy,tom] dog_list2 = copy.copy(dog_list1) dog_list3 = copy.deepcopy(dog_list1) print dog_list1[0], dog_list2[0] oudy.name = 'oudy_new' dog_list1[0]=oudy print dog_list1[0], dog_list2[0] # 看到没,只修改了dog_list1 0元素的名字,导致dog_list2 0元素的名字也发生了变化 print dog_list1[0], dog_list3[0] # 此时,dog_list3 0元素的名字不变。。因为它指向单独的存储空间 ''' lambda的用法 lambda用来编写简单的函数,而def用来处理更强大的任务。 一般来讲:lambda就适合编写一行的函数 简单来说,编程中提到的 lambda 表达式,通常是在需要一个函数, 但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数 尤其如果这个函数只会使用一次的话。而且第一种写法实际上更易读, 因为那个映射到列表上的函数具体是要做什么,非常一目了然。 如果你仔细观察自己的代码,会发现这种场景其实很常见: 你在某处就真的只需要一个能做一件事情的函数而已,连它叫什么名字都无关紧要。 Lambda 表达式就可以用来做这件事。 这样的写法时,你会发现自己如果能将「遍历列表, 给遇到的每个元素都做某种运算」的过程从一个循环里抽象出来成为一个函数 map, 然后用 lambda 表达式将这种运算作为参数传给 map 的话,考虑事情的思维层级会高出一些来, 需要顾及的细节也少了一点。 这种能够接受一个函数作为参数的函数叫做「高阶函数」(higher-order function) ''' f = lambda x,y,z : x+y+z print f(1,2,3) print map(lambda x: x*x ,[y for y in range(10)]) # 此时lambda函数为乘方函数 ''' with语句, 上下文管理 with最多的 就是打开文件,和实现__enter__和__exit__ 个人理解with常用在try-except-finally,需要在finally对资源进行释放类型的模型 使用with语法可以使用上下文管理器,实现上下文协议__enter__和__exit__,在__exit__中队资源进行释放 此时打开某个文件,不需要记住关闭文件(释放资源) ''' with open(r'somefileName') as somefile: for line in somefile: print line
# factory_mode.py # coding:utf-8 ''' 工厂方法模式去掉了简单工厂模式中工厂方法的静态属性,使得它可以被子类继承。对于python来说,就是工厂类被具体工厂继承。这样在简单工厂模式里集中在工厂方法上的压力可以由工厂方法模式里不同的工厂子类来分担。也就是工厂外面再封装一层。 1) 抽象工厂角色: 这是工厂方法模式的核心,它与应用程序无关。是具体工厂角色必须实现的接口或者必须继承的父类。 2) 具体工厂角色:它含有和具体业务逻辑有关的代码。由应用程序调用以创建对应的具体产品的对象。 3) 抽象产品角色:它是具体产品继承的父类或者是实现的接口。在python中抽象产品一般为父类。 4) 具体产品角色:具体工厂角色所创建的对象就是此角色的实例。由一个具体类实现。 ''' class car: '''interface as Product''' def drive(self): pass class BMW(car): '''Concrete Product''' def __init__(self,carname): self.__name=carname def drive(self): print "Drive the BMW as "+self.__name class Benz(car): '''Concrete Product''' def __init__(self,carname): self.__name=carname def drive(self): print "Drive the Benz as "+self.__name class driver: '''Factory also called Creator''' def driverCar(self): return car() class BMWdriver(driver): '''Concrete Creator''' def driverCar(self): return BMW("BMW") class Benzdriver(driver): '''Concrete Creator''' def driverCar(self): return Benz("Benz") if __name__ == "__main__": driver=BMWdriver() car=driver.driverCar() car.drive() driver=Benzdriver() car=driver.driverCar() car.drive()