text
stringlengths
37
1.41M
def word_count(str): counts = dict() word = str,split('') for word in words: if word in counts: counts[word] =+ 1 else: return count word_count('the quick brown fox jumps over the lazy dog.')
#Level1 def lesser_of_two_evens(a, b): if a % 2 == 0 and b % 2 == 0: if a > b: print('both numbers are even and lesser is' + str(b)) else : print('both numbers are even and lesser is' + str(a)) else: if a > b: print('both numbers are odd and' + str(a) + ' is greater') else : print('both numbers are odd and' + str(b) + ' is greater') #could have used min and max functions lesser_of_two_evens(10, 20) def animal_crackers(str): mylist = str.split() word1 = mylist[0] word2 = mylist[1] letter1 = word1[0] letter2 = word2[0] print(letter1 == letter2) animal_crackers('lying plama') def makes_twenty(num1, num2): if num1 + num2 == 20: return True elif num1 == 20 or num2 == 20: return True else: return False print(makes_twenty(2 , 1)) def old_macdonald(str): if len(str) >= 4: print(str[0:3].capitalize() + str[3:].capitalize()) else: print(str.capitalize()) old_macdonald('mac') def yoda(str): mylist = str.split(' ') print(' '.join(mylist[::-1])) yoda('i am late') #This is a good example how slicing may work to reverse def almost_there(num): return num >=90 and num <=110 or num >=190 and num <=210 print(almost_there(90)) #Level2 #range is a very important function to be used in for loop def has_33(nums): for num in range(0,len(nums)-1): if nums[num] == 3 and nums[num+1] == 3: print('true') else: print('false') has_33([1,3,3,4]) def paper_doll(str): str3 = '' for char in str: str3 += (char * 3) print(str3) paper_doll('Ankur') def blackjack(num1, num2, num3): sum = num1 + num2 + num3 if num1 == 11 or num2 == 11 or num3 ==11: sum = sum - 10 if sum <= 21 : print(sum) else: print('BUST!') blackjack(9, 9, 11) #concept of flag needs to be used here def summer_69(arr): flag = 'false'; sum = 0; for num in arr: if num == 6: flag = 'true'; elif num == 9: flag = 'false' if flag == 'false': if num == 9: sum = sum + num -9; else: sum = sum + num; print('sum is {f}' .format(f=sum)); summer_69([2, 1, 6, 9, 11]) def spy_game(list): count0 = 0 spyFlag='false'; for num in list: if num == 0: count0= count0 + 1; if num == 7 and count0 ==2: spyFlag='true'; if spyFlag =='true': print('spy number') else: print('NO!') spy_game([1, 0,0,0,7,2,0,4,5,0]) map()
__author__ = 'Tamby Kaghdo' #My solution to the Kata: Excel's COUNTIF, SUMIF and AVERAGEIF functions def to_num(s): try: return int(s) except ValueError: return float(s) def count_if(values,criteria): ops = [">","<","<=",">=","<>"] counter = 0 condition_part = "" value_part = None if type(criteria) is str: if len(criteria) >= 3 and (criteria[1] == "=" or criteria[1] == ">"): condition_part = criteria[0] + criteria[1] value_part = to_num(criteria[2:]) elif criteria[0] in ops: condition_part = criteria[0] value_part = to_num(criteria[1:]) elif criteria not in ops: for i in values: if i == criteria: counter += 1 if condition_part == ">=": for i in values: if i >= value_part: counter += 1 elif condition_part == "<=": for i in values: if i <= value_part: counter += 1 elif condition_part == "<>": for i in values: if i != value_part: counter += 1 elif condition_part == ">": for i in values: if i > value_part: counter += 1 elif condition_part == "<": for i in values: if i < value_part: counter += 1 elif type(criteria) is int or type(criteria) is float: for i in values: if i == criteria: counter += 1 return counter def sum_if(values,criteria): sum = 0 if type(criteria) is str: if criteria[1] == "=" or criteria[1] == ">": condition_part = criteria[0] + criteria[1] value_part = to_num(criteria[2:]) else: condition_part = criteria[0] value_part = to_num(criteria[1:]) if condition_part == ">=": for i in values: if i >= value_part: sum += i elif condition_part == "<=": for i in values: if i <= value_part: sum += i elif condition_part == ">": for i in values: if i > value_part: sum += i elif condition_part == "<": for i in values: if i < value_part: sum += i elif condition_part == "<>": for i in values: if i != value_part: sum += i elif type(criteria) is int or type(criteria) is float: for i in values: if i == criteria: sum += i return sum def average_if(values,criteria): sum = sum_if(values,criteria) num = 0 if type(criteria) is str: if criteria[1] == "=" or criteria[1] == ">": condition_part = criteria[0] + criteria[1] value_part = to_num(criteria[2:]) else: condition_part = criteria[0] value_part = to_num(criteria[1:]) if condition_part == ">=": for i in values: if i >= value_part: num += 1 if condition_part == "<=": for i in values: if i <= value_part: num += 1 if condition_part == ">": for i in values: if i > value_part: num += 1 if condition_part == "<": for i in values: if i < value_part: num += 1 if condition_part == "<>": for i in values: if i <> value_part: num += 1 elif type(criteria) is int or type(criteria) is float: for i in values: if i == criteria: num += 1 return float(sum) / float(num) def main(): print(sum_if([1,3,5,3,0,-1,-5],'<>1')) pass if __name__ == '__main__': main()
## 2. Condensing class size ## class_size = data["class_size"] #only high school class_size = class_size[class_size["GRADE "] == "09-12"] #only GEN ED class_size = class_size[class_size["PROGRAM TYPE"] == "GEN ED"] print(class_size.head(5)) ## 3. Computing average class sizes ## import numpy class_size = class_size.groupby("DBN").agg(numpy.mean) class_size.reset_index(inplace=True) data["class_size"] = class_size print(data["class_size"].head(5)) ## 4. Condensing demographics ## data["demographics"] = data["demographics"][data["demographics"]["schoolyear"] == 20112012] print(data["demographics"].head(5)) ## 5. Condensing graduation ## data["graduation"] = data["graduation"][data["graduation"]["Cohort"] == "2006"] data["graduation"] = data["graduation"][data["graduation"]["Demographic"] == "Total Cohort"] print(data["graduation"].head(5)) ## 6. Converting AP test scores ## cols = ['AP Test Takers ', 'Total Exams Taken', 'Number of Exams with scores 3 4 or 5'] for c in cols: data["ap_2010"][c] = pd.to_numeric(data["ap_2010"][c],errors="coerce") print(data["ap_2010"].head(5)) ## 8. Performing the left joins ## combined = data["sat_results"] combined = combined.merge(data["ap_2010"], how="left", on="DBN") combined = combined.merge(data["graduation"], how="left", on="DBN") print(combined.head(5)) print(combined.shape) ## 9. Performing the inner joins ## combined = combined.merge(data["class_size"], how="inner", on="DBN") combined = combined.merge(data["demographics"], how="inner", on="DBN") combined = combined.merge(data["survey"], how="inner", on="DBN") combined = combined.merge(data["hs_directory"], how="inner", on="DBN") print(combined.head(5)) print(combined.shape) ## 10. Filling in missing values ## means = combined.mean() combined = combined.fillna(means) combined = combined.fillna(0) print(combined.head(5)) ## 11. Adding a school district column ## def first_2(s): return s[0:2] combined["school_dist"] = combined["DBN"].apply(first_2) print(combined["school_dist"].head(5))
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def multiple_sum_finder(max): y = 0 for x in range(0,max): if x % 3 == 0: y += x elif x % 5 == 0: y += x return y print multiple_sum_finder(1000)
# O(N) Time | O(N) Space def caesarCipherEncryptor(string, key): newLetters = [] newKey = key % 26 for letter in string: newLetters.append(getLetter(letter, newKey)) return "".join(newLetters) def getLetter(letter, key): newLetterCode = ord(letter) + key return chr(newLetterCode) if newLetterCode <= 122 else chr(96 + newLetterCode % 122) # O(N) Time | O(N) Space def caesarCipherEncryptor(string, key): newLetters = [] newKey = key % 26 alphabets = list("abcdefghijklmnopqrstuvwxyz") for letter in string: newLetters.append(getLetter(letter, newKey, alphabets)) return "".join(newLetters) def getLetter(letter, key, alphabets): newLetterCode = alphabets.index(letter) + key return alphabets[newLetterCode] if newLetterCode <= 25 else alphabets[-1 + newLetterCode % 25]
totalseconds = int(input('Input the number of seconds:')) days = totalseconds//86400 hours = (totalseconds%86400)//3600 minutes = (totalseconds%3600)//60 seconds = totalseconds%60 print(days,':',hours,':',minutes,':',seconds,sep='')
class Node: data = None next = None def __init__(self, data): self.data = data def append(self, data): node = self while node.next is not None: node = node.next node.next = Node(data) class Stack: top = None def push(self, item): node = Node(item) node.next = self.top self.top = node def pop(self): if self.top is not None: node = self.top self.top = self.top.next return node return None def print_stack(self): nodes = ['TOP'] node = self.top while node is not None: nodes.append(node.data) node = node.next nodes.append('BOTTOM') print nodes def peek(self): return self.top.data class StackWithMins(Stack): mins = Stack() def push(self, item): node = Node(item) node.next = self.top self.top = node if self.mins.top is not None: if self.mins.top.data > item: self.mins.push(item) else: self.mins.push(item) def pop(self): if self.top is not None: if self.peek() == self.mins.peek(): self.mins.pop() node = self.top self.top = self.top.next return node return None def min(self): return self.mins.peek() stack = StackWithMins() stack.push(9) stack.push(5) stack.push(7) stack.push(4) stack.push(3) stack.push(6) stack.push(5) stack.push(2) stack.push(1) stack.print_stack() stack.mins.print_stack() stack.pop() stack.pop() print stack.min() stack.print_stack()
from base import Node, print_nodes def find_nth_to_last(root, nth): if root is None or nth < 0: return None p2 = root for x in xrange(0, nth): p2 = p2.next if p2 is None: return None p1 = root while p2.next is not None: p1 = p1.next p2 = p2.next return p1 root = Node(0) root.append_to_tail(1) root.append_to_tail(2) root.append_to_tail(3) root.append_to_tail(4) root.append_to_tail(5) root.append_to_tail(6) root.append_to_tail(7) root.append_to_tail(8) root.append_to_tail(9) print_nodes(root) nth = 2 node = find_nth_to_last(root, nth) print "%s to last: %s" % (nth, node.data)
def rotate90(matrix, n): for layer in xrange(0, n / 2): first = layer last = n - 1 - layer for i in xrange(first, last): offset = i - first top = matrix[first][i] matrix[first][i] = matrix[last - offset][first] matrix[last - offset][first] = matrix[last][last - offset] matrix[last][last - offset] = matrix[i][last] matrix[i][last] = top return matrix def print_matrix(matrix): for x in matrix: print x matrix = [ ['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9'], ['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['K', 'L', 'M', 'N', 'O'] ] n = 5 print_matrix(matrix) print print_matrix(rotate90(matrix, n))
class Node: left = None right = None value = None def __init__(self, value): self.value = value class Tree: root = None def insert_new(self, node, value): if node.value > value: if node.left: return self.insert_new(node.left, value) else: node.left = Node(value) return True if node.value < value: if node.right: return self.insert_new(node.right, value) else: node.right = Node(value) return True def insert(self, value): if not self.root: # Tree is empty self.root = Node(value) else: self.insert_new(self.root, value) def insert_from_array(tree, array): if len(array) > 1: middle = int(round(len(array) / 2)) tree.insert(array[middle]) insert_from_array(tree, array[0:middle]) insert_from_array(tree, array[middle + 1:]) elif array: tree.insert(array[0]) return if __name__ == '__main__': bst = Tree() array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] insert_from_array(bst, array) print bst.root.value # 5 print bst.root.left.value # 2 print bst.root.right.value # 8 print bst.root.left.left.value # 1 print bst.root.left.right.value # 4 print bst.root.right.left.value # 7 print bst.root.right.right.value # 9 print bst.root.left.left.left.value # 0 print bst.root.left.right.left.value # 3 print bst.root.right.left.left.value # 6
# Playing Around with what i learned on day 1 # When doing day 1 I thought back on when I was learning alittle about f strings & And playing with lists # Played around with it abit here in my creativity. # Storing characters into a list[] & Some words into a string. Southpark_Characters = "Stan", "Cartmen", "Kenny", "Kyle" some_words = "How can you think that!\nI don't understand how you can say that\nSee these guys right here\n" # Getting the user input. greeting_input = input("Hello there! What's You Favorite T.V show? ") # Printing with a f string. # print(f"{greeting_input}!!\n{some_words} {Southpark_Characters}") # Changing the variable Southpark_Characters. Southpark_Characters = "SOUTHPARK!" # Printing out the changed variable. print(input("Okey ill give you one more chance. What your favorite T.V show? ")) print(f"You got to be kidding me this is the best show is!\n{Southpark_Characters}") # How it was done in the video adding variables # print("Welcome to the Band Name Generator.") # street = input("What's name of the city you grew up in?\n") # pet = input("What's your pet's name?\n") # print("Your band name could be " + street + " " + pet)
print("Hello World!") print("Hello('World')") print("Hello " + "\nWorld") # Debug Exercise print("Day 1 - String Manipulation") print("String Concatention is done with the '+' sign.") print("e.g print('Hello World!')") print("New lines can be added with a backslash n.") # Input Function Exercise. name = input("What is your name?") print(len(name))
"""Useful things to do with dates""" import datetime def date_from_string(string, format_string=None): """Runs through a few common string formats for datetimes, and attempts to coerce them into a datetime. Alternatively, format_string can provide either a single string to attempt or an iterable of strings to attempt.""" if isinstance(format_string, str): return datetime.datetime.strptime(string, format_string).date() elif format_string is None: format_string = [ "%Y-%m-%d", "%m-%d-%Y", "%m/%d/%Y", "%d/%m/%Y", ] for format in format_string: try: return datetime.datetime.strptime(string, format).date() except ValueError: continue raise ValueError("Could not produce date from string: {}".format(string)) def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0): """given a datetime.date, gives back a datetime.datetime""" # don't mess with datetimes if isinstance(plain_date, datetime.datetime): return plain_date return datetime.datetime( plain_date.year, plain_date.month, plain_date.day, hours, minutes, seconds, ms, ) class TimePeriod(object): def __init__(self, earliest, latest): if not isinstance(earliest, datetime.date) and earliest is not None: raise TypeError("Earliest must be a date or None") if not isinstance(latest, datetime.date) and latest is not None: raise TypeError("Latest must be a date or None") # convert dates to datetimes, for to have better resolution if earliest is not None: earliest = to_datetime(earliest) if latest is not None: latest = to_datetime(latest, 23, 59, 59) if earliest is not None and latest is not None and earliest >= latest: raise ValueError("Earliest must be earlier than latest") self._earliest = earliest self._latest = latest def __contains__(self, key): if isinstance(key, datetime.date): key = to_datetime(key) if self._latest is None: upper_bounded = True else: upper_bounded = key <= self._latest if self._earliest is None: lower_bounded = True else: lower_bounded = self._earliest <= key return upper_bounded and lower_bounded elif isinstance(key, TimePeriod): if self._latest is None: upper_bounded = True elif key._latest is None: upper_bounded = False else: upper_bounded = self._latest >= key._latest if self._earliest is None: lower_bounded = True elif key._earliest is None: lower_bounded = False else: lower_bounded = self._earliest <= key._earliest return upper_bounded and lower_bounded def contains(self, other): return other in self def overlaps(self, other): """does another datetime overlap with this one? this is a symmetric property. TP1 |------------| -------------------------------------------------> time TP2 |--------------| TP1.overlaps(TP2) == TP2.overlaps(TP1) == True args: other - a TimePeriod """ return self._latest in other or self._earliest in other def __eq__(self, other): return (self._earliest == other._earliest) and (self._latest == other._latest) def __repr__(self): return "<{}: {}-{}>".format( self.__class__.__name__, self._earliest, self._latest, ) @classmethod def get_containing_period(cls, *periods): """Given a bunch of TimePeriods, return a TimePeriod that most closely contains them.""" if any(not isinstance(period, TimePeriod) for period in periods): raise TypeError("periods must all be TimePeriods: {}".format(periods)) latest = datetime.datetime.min earliest = datetime.datetime.max for period in periods: # the best we can do to conain None is None! if period._latest is None: latest = None elif latest is not None and period._latest > latest: latest = period._latest if period._earliest is None: earliest = None elif earliest is not None and period._earliest < earliest: earliest = period._earliest return TimePeriod(earliest, latest) class DiscontinuousTimePeriod(object): """A bunch of TimePeriods""" def __init__(self, *periods): if any(not isinstance(period, TimePeriod) for period in periods): raise TypeError("periods must all be TimePeriods: {}".format(periods)) periods = set(periods) no_overlaps_periods = [] for period in periods: for other_period in periods: if id(other_period) == id(period): continue # periods that overlap should be combined if period.overlaps(other_period): period = TimePeriod.get_containing_period(period, other_period) no_overlaps_periods.append(period) no_equals_periods = [] reference = set(no_overlaps_periods) for period in no_overlaps_periods: # clean out duplicated periods if any(other_period == period and other_period is not period for other_period in reference): reference.remove(period) else: no_equals_periods.append(period) no_contains_periods = [] for period in no_equals_periods: # don't need to keep periods that are wholly contained skip = False for other_period in no_equals_periods: if id(other_period) == id(period): continue if period in other_period: skip = True if not skip: no_contains_periods.append(period) self._periods = no_contains_periods def __contains__(self, other): if isinstance(other, (datetime.date, TimePeriod)): for period in self._periods: if other in period: return True def days_ago(days, give_datetime=True): delta = datetime.timedelta(days=days) dt = datetime.datetime.now() - delta if give_datetime: return dt else: return dt.date() def days_ahead(days, give_datetime=True): delta = datetime.timedelta(days=days) dt = datetime.datetime.now() + delta if give_datetime: return dt else: return dt.date()
#Haemi Lee #Version 2 #Fall 2018 #Holds Turtle Interpreter class import turtle import random import sys class TurtleInterpreter: def __init__(self, dx = 800, dy = 800): turtle.setup(width = dx, height = dy ) turtle.tracer(False) def drawString(self, dstring, distance, angle): """ Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command.""" stack = [] colorstack = [] for c in dstring: if c == 'F': turtle.forward(distance) elif c == 'L': turtle.pendown() turtle.begin_fill() for i in range(2): turtle.forward(distance) turtle.left(60) turtle.forward(distance)f turtle.left(120) turtle.end_fill() turtle.penup() elif c == 'B': turtle.pendown() turtle.begin_fill() turtle.circle(distance*0.25) turtle.end_fill() turtle.penup() elif c == "-": turtle.right(angle) elif c == "+": turtle.left(angle) elif c == '[': stack.append(turtle.position()) stack.append(turtle.heading()) elif c == ']': turtle.penup() turtle.setheading(stack.pop()) turtle.goto(stack.pop()) turtle.pendown() elif c == '<': #push the current turtle color onto a color stack. colorstack.append( turtle.color()[0] ) elif c == '>': #pop the current turtle color off the color stack and set the turtle's color to that value. turtle.color(colorstack.pop()) elif c == 'g': #green turtle.color(0.15, 0.5, 0.2) elif c == 'y': #yellow turtle.color(0.8, 0.8, 0.3) elif c == 'r': #red turtle.color(0.7, 0.2, 0.3) elif c == 'b': #brown turtle.color(0.46, 0.18, 0.05) elif c == 'p': #pink turtle.color(0.85, 0.35, 0.6) elif c == 'v': #violet turtle.color(0.75, 0.34, 0.85) turtle.update() def hold(self): '''Holds the screen open until user clicks or presses 'q' key''' turtle.hideturtle() turtle.update() turtle.onkey(turtle.bye, 'q') turtle.listen() turtle.exitonclick() def place(self, xpos, ypos, angle=None): '''pick up the pen, place the turtle at location (xpos, ypos), orient the turtle if the angle argument is not None, and then put down the pen''' turtle.penup() turtle.goto(xpos, ypos) turtle.setheading(angle) turtle.pendown() def orient(self, angle): '''use the setheading function to set turtle's heading to the given angle''' turtle.setheading(angle) def goto(self, xpos, ypos): '''pick up the turtle, send the turtle to (xpos, ypos), and then put the pen down''' turtle.penup() turtle.goto(xpos, ypos) turtle.pendown() def color(self, c): '''call turtle.color() with the argument c to set the turtle's color''' turtle.color(c) def width(self, w): '''call turtle.width() with the argument w to set the turtle's width''' turtle.width(w)
# import sqlite3 # from_conn = sqlite3.connect("words.db") # to_conn = sqlite3.connect("db.sqlite3") # from_cur = from_conn.cursor() # to_cur = to_conn.cursor() # print(from_conn.execute("select name from sqlite_master where type='table';").fetchall()) # words > 'dictionary_words # print(to_conn.execute("select name from sqlite_master where type='table';").fetchall()) # from_words = from_cur.execute("select id, qom, dfs, syn, var, see from words").fetchall() # from_words = [list(l).insert(0, None) for l in from_words] # to_cur.executemany("insert into dictionary_word values (?, ?, ?, ?, ?, ?)", from_words) # to_conn.commit() # to_cur.close() # to_conn.close() # from_cur.close() # from_conn.close() # print(from_words, len(from_words))
import pandas as pd from datetime import date import psycopg2 import config def populate_user_table_from_csv(csv_file): conn = psycopg2.connect( host=config.live_config.host, database=config.live_config.database, user=config.live_config.user, password=config.live_config.password) conn.autocommit = True cur = conn.cursor() # csv_file = 'test_list.csv' df = pd.read_csv(csv_file) today = date.today().isoformat() for index, row in df.iterrows(): print(row['user_id']) print(row['follower_count']) print('date_updated: ' + str(today) + "\n") query = 'INSERT INTO users (twitter_id, follower_count, updated_last) VALUES (%s,%s,%s)' cur.execute(query, (row['user_id'], row['follower_count'], today)) # query = 'SELECT * FROM users;' # cur.execute(query) # res = cur.fetchall() # print(res) # close out connections to the db cur.close() conn.close() return if __name__ == "__main__": csv = input(('CSV File: ')) populate_user_table_from_csv(csv)
class Pessoa: def __init__(self, nome, idade): self.nome = nome self.idade = idade class PessoaFisica(Pessoa): def __init__(self, nome, idade, cpf): Pessoa.__init__(self,nome,idade) self.cpf = cpf def __repr__(self): return f'{self.nome} tem {self.idade} ano(s), está registrado no cpf {self.cpf}' renatinho = PessoaFisica('Renato', 41, '364.158.364-74') print(renatinho)
from keras import layers from keras import models '''have 32 filters using a 5×5 window for the convolutional layer and a 2×2 window for the pooling We will use the ReLU activation function. In this case, we are configuring a convolutional neural network to process an input tensor of size (28, 28, 1),which is the size of the MNIST images (the third parameter is the color channel which in our case is depth 1) ''' model = models.Sequential() model.add(layers.Conv2D(32,(5,5),activation='relu',input_shape=(28,28,1))) model.add(layers.MaxPooling2D((2, 2))) #The number of parameters of the conv2D layer corresponds to the weight matrix W of 5×5 # and a b bias for each of the filters is 832 parameters (32 × (25 + 1)). #No paramaters for MaxPooling model.add(layers.Conv2D(64, (5, 5), activation='relu')) #layer 2 added of 64 filters model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) #4*4*64=1024 model.add(layers.Dense(10, activation='softmax')) model.summary() #Training from keras.datasets import mnist from keras.utils import to_categorical (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_images = train_images.reshape((60000, 28, 28, 1)) test_images = test_images.reshape((10000, 28, 28, 1)) train_images = train_images.astype('float32') / 255 test_images = test_images.astype('float32') / 255 train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(train_images, train_labels, batch_size=100, epochs=5, verbose=1) test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc)
## """A dict of dict will have connected nodes details in dict with weight """ g = { "n1" : {"n2": 5, "n3": 6}, "n2" : { "n1": 2 , "n4": 9 }, "n3" : {"n1" : 6, "n4" : 3}, "n4" : {"n1" : 3, "n2" : 5, "n3" : 8} } if __name__ == '__main__': print(repr(g))
class LinkedListNode(object): def __init__(self,index, data): self.index = index self.data = data self.next = None class AdjNode(LinkedListNode): pass # A class to represent a graph. A graph # is the list of the adjacency lists. # Size of the array will be the no. of the # vertices "V" ##considring graph as dictionary of linked list class Graph: def __init__(self): self.vertices = {} # Function to add an edge in an undirected graph def __contains__(self, item): return item in self.vertices.keys() def __iter__(self): return iter(self.vertices.keys()) def add_edge(self, src, dest, weight): # Adding the node to the source node node = AdjNode(dest, weight) if src not in self.vertices: self.vertices[src] = None node.next = self.vertices[src] self.vertices[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src, weight) if dest not in self.vertices: self.vertices[dest] = None node.next = self.vertices[dest] self.vertices[dest] = node # Function to print the graph def print_graph(self): print(self.vertices) for v in graph: print("Adjacency list of vertex {}\n head".format(v), end="") temp = self.vertices[v] while temp: print(" -> {} ({})".format(temp.index, temp.data), end="") temp = temp.next print(" \n") if __name__ == '__main__': V = 5 graph = Graph() graph.add_edge(0, 4,5) graph.add_edge(0, 1,3) graph.add_edge(1, 2,7) graph.add_edge(1, 3,2) graph.add_edge(1, 4,8) graph.add_edge(2, 3,9) graph.add_edge(3, 4,1) graph.print_graph()
class Fraction(object) : def __init__(self,num,den): self.num = num self.den = abs(den) def show(self): print(str(self.num) + "/" + str(self.den) ) def __str__(self): return(str(self.num) + "/" + str(self.den)) def __add__(self,other_fraction): new_num = (self.num * other_fraction.den) + (self.den * other_fraction.num) new_den = self.den * other_fraction.den gcd_of_num_den = gcd(new_num,new_den) return Fraction(new_num//gcd_of_num_den,new_den//gcd_of_num_den) def __sub__(self,other_fraction): new_num = (self.num * other_fraction.den) - (self.den * other_fraction.num) new_den = self.den * other_fraction.den gcd_of_num_den = gcd(new_num,new_den) return Fraction(new_num//gcd_of_num_den,new_den//gcd_of_num_den) def gcd(m,n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n if __name__ == '__main__' : f1 = Fraction(3,7) f2 = Fraction(4,5) print str(f1) print str(f2) f3 = f1 + f2 print str(f3) f4 = f1 -f2 print str(f4)
class Node(object): def __init__(self,id): self.connected_to = {} self.id = id def add_neighbour(self,nbr, weight): self.connected_to[nbr] = weight ###Considering graph as dicitionary class Graph(object): def __init__(self): self.vertices = {} self.number_of_nodes = 0 def add_node(self,key): self.number_of_nodes += 1 node = Node(key) self.vertices[key] = node return node def get_node(self,key): if key in self.vertices : return self.vertices[key] raise ValueError def __contains__(self, item): return item in self.vertices def add_edge(self,src,dst,cost): if src not in self.vertices : node = self.add_node(src) if dst not in self.vertices: node = self.add_node(dst) self.vertices[src].add_neighbour(self.vertices[dst],cost) self.vertices[dst].add_neighbour(self.vertices[src],cost) def get_nodes(self): return self.vertices.keys() def __iter__(self): return iter(self.vertices.values()) if __name__ == '__main__': g = Graph() for i in range(6): g.add_node(str(i)) g.add_edge("1","2",10)
#--------Abstract classes ------- class Shape2DInterface: def draw(self): pass class Shape3DInterface: def build(self): pass #-------- Concrete classes ------- class Circle(Shape2DInterface): def draw(self): print("Circle.draw") class Square(Shape2DInterface): def draw(self): print("Square.draw") class Sphere(Shape3DInterface): def build(self): print("Sphere.build") class Qube(Shape3DInterface): def build(self): print("Qube.build") ##----- Abstract factory Interface class ShapeFactoryInterface: def get_shape(self,sides): pass ## Factory concrete class class Shape2DFactory(ShapeFactoryInterface): def get_shape(self, sides): if sides == 1: return Circle() if side == 4: return Square() assert 0, "bad argument side == " + sides class Shapre3DFactory(ShapeFactoryInterface): def get_shape(self,sides): if sides == 1 : return Sphere() if sides == 12: return Qube() assert 0, "bad argument side == " + sides if __name__ == '__main__': shape_2d = Shape2DFactory() c = shape_2d.get_shape(1) c.draw() shape_3d = Shapre3DFactory() q = shape_3d.get_shape(12) q.build()
''' list 타입을 선언하고 list에 엘리먼트 추가, 삭제 ''' ''' num_list = [10, 20, 30, 40, 50, 60] print(type(num_list),num_list) print(num_list[0], num_list[0:3], num_list[3:]) for idx, num in enumerate(num_list): print(idx, num) str_list = ['python', 'java', 'kotlin', 'C++', 'Scalar'] str_list[1] = 'java script' print(str_list[1], str_list[2:4]) str_list.append('Cobol') ''' num_list = [60, 10, 30, 70, 80,] num_list2 = [1, 2, 3, 4, 5] #리스트의 메모리 저장 방식 print(num_list, num_list2) num_list2 = num_list print(num_list, num_list2) num_list.sort() print(num_list, num_list2) a=list('python') print (a) my_list2 = 'hello, python'.split(',') # str -> list print(my_list2)
def fah_convert(value): fehren = (9 * value) / 5 + 32 return fehren celcius = float(input("변환하고 싶은 섭씨온도를 입력해주세요 : ")) fehren = fah_convert(celcius) print("섭씨온도 :",celcius) print("화씨온도 :",round(fehren,2))
# trzeba zainstalowac matplotlib # https://matplotlib.org/users/installing.html # easy # python -m pip install -U pip # python -m pip install -U matplotlib import matplotlib.pyplot as plt def next_vertex(x, y): h = (x**2 + y**2)**0.5 return (x - y / h, y + x / h) plt.axes().set_aspect(1) plt.axis('off') # base of the first triangle plt.plot([0, 1], [0, 0]) N = 17 x_old, y_old = 1, 0 for n in range(1, N): x_new, y_new = next_vertex(x_old, y_old) # draw short side plt.plot([x_old, x_new], [y_old, y_new]) # draw hypotenuse plt.plot([0, x_new], [0, y_new]) x_old, y_old = x_new, y_new # w katalogu z ktorego uruchamiasz zrobic nowy plik PNG z wynikiem plt.show()
lista = [] liczba = int(input("Podaj liczbe elementow: ")) for x in range(0, liczba, 1): lista.append(int(input())) print("Twoje liczby to :", lista) print("--------------------") print("Najwieksza to: ", max(lista))
print('Witaj! To jest moj program *yey*, zapraszam.') #brakowalo ponizej nawiasu na koncu #p=int(input('podaj liczbe powtorzen ') p=int(input('podaj liczbe powtorzen ')) ilosc = 0 while p > 0: p -= 1 ilosc += 1 print('|-|')
import math print(3 + 2) print(3 -2) print(3/2) print(3%2) a = 10 a = a+a print(a) z = 0.1+0.2-0.3 print(math.floor(z))
import time def countdown(t): seconds = t * 60 while seconds: mins,secs = divmod(seconds,60) timer = f"{mins:02d}:{secs:02d}" print (timer,end = '\r') time.sleep(1) seconds-=1 print ("time up bye bye") t = input ("enter time in minutes ") countdown(int(t))
from socket import * serverName = "localhost" serverPort = 5006 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName, serverPort)) def main(): user_main_menu() choice = make_choice_in_menu() if choice == 0: clientSocket.send(str(choice).encode()) print("You left the server") clientSocket.close() exit(0) else: clientSocket.send(str(choice).encode()) def user_main_menu(): print("\n" "====UNIVERSITY TEST SERVER====\n" "1 - Networks test\n" "2 - Russian test\n" "3 - Math test\n" "0 - Exit\n") def make_choice_in_menu(): while True: choice = input('Make a choice: ') try: if 0 <= int(choice) <= 3: return int(choice) else: print('Error. Your choice was out of range. Try again.\n') except ValueError: print('Error. You did not type number. Try again.') msg = "" while msg == "": msg = input('Please enter your name for authentication: ') if msg != "": clientSocket.send(msg.encode()) else: print('Error. You did not type your name. Try again.') while True: main() counter = 0 for i in range(6): message = "" modifiedMessage = clientSocket.recv(1024) print('This is your question:', modifiedMessage.decode("utf-8")) while message == "": message = input('Your answer:') if message.upper() in ["A", "B", "C", "D"]: clientSocket.send(message.encode()) else: print('Error. Your choice was out of range. Try again.\n') message = "" counter += 1 if message == "exit": clientSocket.close() exit(0) else: print("Your answer was sent!") result_msg = clientSocket.recv(1024) print(result_msg.decode())
''' 单元测试unittest ''' import unittest # 必须继承TestCase类 class Test01(unittest.TestCase): @classmethod # 注解 def setUpClass(self): print('*******这是setUpClass方法*******') @classmethod def tearDownClass(self): print('*******这是tearDownClass方法*******') # 继承自父类TestCase的方法,名字不能乱写 # setUp方法会自动在每一个测试用例前执行 def setUp(self): print('*******这是setUp方法*******') # tearDown方法会自动在每一个测试用例后执行 def tearDown(self): print('*******这是tearDown方法*******') # 自定义测试用例 # 自定义用例方法名必须以test***开头 # 按照ASCII码表中的字符顺序为优先级别来执行 def test2(self): print('*******这是test2方法-测试用例*******') def testabc(self): print('*******abc方法*******') def testAbc(self): print('*******Abc方法*******') def test1(self): print('*******这是test1方法-测试用例*******') if __name__ == "__main__": # Test01().test1() unittest.main()
import collections import pdb class TrieNode(): def __init__(self): self.children = collections.defaultdict(TrieNode) self.word_count = 0 class Solution(object): def build_trie(self, words): self.root = TrieNode() for word in words: node = self.root for w in word: node = node.children[w] node.word_count +=1 def word_count(self, word): node = self.root for w in word: node = node.children.get(w) wc = node.word_count node.word_count = 0 return wc def topKFrequent(self, words, k): """ :type words: List[str] :type k: int :rtype: List[str] """ self.build_trie(words) freq_word_list = [] for word in words: wc = self.word_count(word) if wc > 0: len_freq_word_list = len(freq_word_list) if len_freq_word_list > 0: for fw_index in range(min(len_freq_word_list,k)): if wc > freq_word_list[fw_index][0]: freq_word_list.insert(fw_index, (wc, word)) break elif wc == freq_word_list[fw_index][0]: if word < freq_word_list[fw_index][1]: freq_word_list.insert(fw_index, (wc, word)) break if (fw_index == min(len_freq_word_list, k) - 1 and len_freq_word_list < k): freq_word_list.append((wc, word)) else: freq_word_list.append((wc, word)) return [fw[1] for fw in freq_word_list[:k]] words = ["a","aa","aaa"] # ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"] K = 2 print Solution().topKFrequent(words, K)
__author__ = 'ChiYuan' # # Given a list of numbers, L, find a number, x, that # minimizes the sum of the absolute value of the difference # between each element in L and x: SUM_{i=0}^{n-1} |L[i] - x| # # Your code should run in Theta(n) time # from random import randint def minimize_absolute(L): global cl global cr global ll global fl ll = len(L) if ll ==1: return L[0] i = randint(0,ll-1) fl = (ll-1)//2 cl = 0#left of the partition cr = 0#right of the partition return partition(L,L[i]) # print ('x is %d'%x) # your code here def partition(L,x): global cl global cr global ll global fl lefs = [] rigs = [] for i in L: if i<x: lefs.append(i) elif i>x: rigs.append(i) lfl = len(lefs) cl = cl + lfl rgl = len(rigs) cr = cr + rgl print (lefs,rigs,cl,cr,fl) if cl==fl or cr==fl: print ("find it") print (x) return x elif cl > fl: if len(lefs) == 1: return lefs[0] else: #print (lfl) xt = randint(0,lfl-1) cl = cl - lfl cr += 1 return partition(lefs,lefs[xt]) elif cl < fl: if len(rigs) == 1: return rigs[0] else: #print (rgl) xt = randint(0,rgl-1) cr = cr - rgl cl +=1 return partition(rigs,rigs[xt]) L=[1,5,3,4,6,11] print (len(L)) print (minimize_absolute(L))
""" 286. Walls and Gates https://leetcode.com/problems/walls-and-gates/ You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. Example: Given the 2D grid: INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF After running your function, the 2D grid should be: 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 """ class Solution(object): def wallsAndGates(self, rooms): """ :type rooms: List[List[int]] :rtype: None Do not return anything, modify rooms in-place instead. """ rows = len(rooms) if rows == 0: return cols = len(rooms[0]) if cols == 0: return cur_bfs = [] for row_index in range(rows): for col_index in range(cols): if rooms[row_index][col_index] == 0: cur_bfs.append([row_index,col_index]) while len(cur_bfs) > 0: next_bfs = [] for node in cur_bfs: row_index, col_index = node[0], node[1] val = rooms[row_index][col_index] if row_index > 0: if rooms[row_index - 1][col_index] > val + 1: next_bfs.append([row_index - 1, col_index]) rooms[row_index - 1][col_index] = val + 1 if row_index < rows - 1: if rooms[row_index + 1][col_index] > val + 1: next_bfs.append([row_index + 1, col_index]) rooms[row_index + 1][col_index] = val + 1 if col_index > 0: if rooms[row_index][col_index - 1] > val + 1: next_bfs.append([row_index, col_index - 1]) rooms[row_index][col_index - 1] = val + 1 if col_index < cols - 1: if rooms[row_index][col_index + 1] > val + 1: next_bfs.append([row_index, col_index + 1]) rooms[row_index][col_index + 1] = val + 1 cur_bfs = next_bfs return
""" 443. String Compression DescriptionHintsSubmissionsDiscussSolution Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space? Example 1: Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". Example 2: Input: ["a"] Output: Return 1, and the first 1 characters of the input array should be: ["a"] Explanation: Nothing is replaced. Example 3: Input: ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". Notice each digit has it's own entry in the array. Note: All characters have an ASCII value in [35, 126]. 1 <= len(chars) <= 1000. """ class Solution(object): def compress(self, chars): """ :type chars: List[str] :rtype: int """ tot_len = 0 len_char = 0 index_char = 0 len_chars = len(chars) while index_char < len_chars: if index_char == 0: len_char += 1 index_char += 1 tot_len += 1 elif chars[index_char] == chars[index_char - 1]: len_char += 1 del chars[index_char] elif chars[index_char] != chars[index_char - 1]: if len_char > 1: chars = chars[:index_char] + list(str(len_char)) + chars[index_char:] index_char = index_char + len(str(len_char)) + 1 tot_len += len(str(len_char)) else: index_char += 1 len_char = 1 tot_len += 1 len_chars = len(chars) if len_char > 1: chars = chars + list(str(len_char)) tot_len += len(str(len_char)) print chars return tot_len class Solution2(object): def compress(self, chars): """ :type chars: List[str] :rtype: int """ if not chars: return 0 elif len(chars) == 1: return 1 cn = 1 res = '' for i in range(1, len(chars)): if chars[i] == chars[i-1]: cn += 1 else: res += chars[i-1] if cn == 1 else chars[i-1] + str(cn) cn = 1 if i == len(chars) - 1: res += chars[i] if cn == 1 else chars[i] + str(cn) chars[:len(res)] = list(res) #chars = list(res) + chars[len(res): len(chars)] print(res) print(chars) #print(len(res)) return len(res) print Solution().compress(["a","a","a","a","b","b","b","b","b","b","b","c","c"])
""" 207. Course Schedule https://leetcode.com/problems/course-schedule/ There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. Constraints: The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. You may assume that there are no duplicate edges in the input prerequisites. 1 <= numCourses <= 10^5 """ class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ list_courses = [0]*numCourses num_prerequisites = len(prerequisites) if num_prerequisites == 0: return True graph = {} for p_index, prereq in enumerate(prerequisites): if prereq[1] not in graph: graph[prereq[1]] = [prereq[0]] else: graph[prereq[1]].append(prereq[0]) for i in range(numCourses): if i in graph and list_courses[i] ==0: dfs = [i] path = [] seen = {} while len(dfs) > 0 : node = dfs[-1] # if node in seen and seen[node]: # return False # path.append(node) # if list_courses[node] == 1: break if (node not in seen or not seen[node]) and node in graph: for next_node in graph[node]: if next_node in seen and seen[next_node]: return False dfs.append(next_node) seen[node] = True else: ab_node = dfs.pop() seen[ab_node] = False list_courses[ab_node] == 1 return True from collections import defaultdict class ClassNode(object): def __init__(self): self.children = [] self.num_parents = 0 class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ # build graph num_edge = 0 graph = defaultdict(ClassNode) for pre in prerequisites: child, parent = pre[0], pre[1] graph[pre[1]].children.append(child) graph[pre[0]].num_parents += 1 num_edge += 1 # topological sort no_dependent_nodes = [] for node in graph: if graph[node].num_parents == 0: no_dependent_nodes.append(node) while len(no_dependent_nodes) > 0: node = no_dependent_nodes.pop() if len(graph[node].children) > 0: for child in graph[node].children: graph[child].num_parents -=1 if graph[child].num_parents ==0: no_dependent_nodes.append(child) num_edge -= 1 if num_edge > 0: return False return True solution = Solution() print(solution.canFinish(3, [[1,0],[2,1]]))
# Given a linked list, swap every two adjacent nodes and return its head. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head N1 = head.next N2 = head N2.next = self.swapPairs(N1.next) N1.next = N2 return N1
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? """ class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n==0:return 0 node_range = range(1,n+1) self.dict_num_tree = {} return self.find_bst(node_range) def find_bst(self,node_val_list): if not node_val_list: return 1 if len(node_val_list) == 1: return 1 len_node_val_list = len(node_val_list) if len_node_val_list in self.dict_num_tree: return self.dict_num_tree[len_node_val_list] tot_subtree = 0 for node_val in node_val_list: left_list = [node_val_temp for node_val_temp in node_val_list if node_val_temp<node_val] len_left_list = len(left_list) right_list = [node_val_temp for node_val_temp in node_val_list if node_val_temp>node_val] len_right_list = len(right_list) if len_left_list in self.dict_num_tree: num_left_subtree = self.dict_num_tree[len_left_list] else: num_left_subtree = self.find_bst(left_list) self.dict_num_tree[len_left_list] = num_left_subtree if len(right_list) in self.dict_num_tree: num_right_subtree = self.dict_num_tree[len(right_list)] else: num_right_subtree = self.find_bst(right_list) self.dict_num_tree[len_right_list] = num_right_subtree tot_subtree += num_left_subtree * num_right_subtree self.dict_num_tree[len(node_val_list)] = tot_subtree return tot_subtree Solution1 = Solution() print Solution1.numTrees(3)
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ first_zero_pos = -1 last_zero_pos = -1 for i in range(len(nums)): if nums[i] ==0 and first_zero_pos == -1: first_zero_pos = i last_zero_pos = i # elif nums[i] ==0 and i < first_zero_pos: # first_zero_pos = i elif nums[i] !=0 and first_zero_pos!=-1: nums[first_zero_pos], nums[i] = nums[i], nums[first_zero_pos] first_zero_pos = first_zero_pos + 1 last_zero_pos = i return nums Solution1=Solution() print(Solution1.moveZeroes([1,0, 1]))
import math class Point(object): """Point class stores and X,Y pair in meters""" def __init__(self, x = 0, y = 0): self.x = x self.y = y #returns the pythagorean distance between two points def distTo(self, other): return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2) #returns the global bearing of the other point def angleTo(self, other): return math.atan2(other.y - self.y, other.x - self.x) def __repr__(self): return str((self.x, self.y)) #returns the difference between two angles def angleDiff(x, y): return normalizeAngle(x-y) #math.atan2(math.sin(x-y), math.cos(x-y)) def normalizeAngle(angle): """normalize an angle to the range -pi - pi""" if angle > math.pi: angle -= 2 * math.pi elif angle < -math.pi: angle += 2 * math.pi return angle
def adadaval(n): k = 1 count = 0 while k <= n: if n % k == 0: count += 1 k += 1 if count == 2: return True else: return False n = int(input('enter a number:')) k = 1 while k <= n: if adadaval(k): print(k) k += 2
def area(r): return r * r def environment(r): return 4* r r = int(input("megdar zele morabe ra vared knid:")) print("masahat:", + area(r)) print("mohit:", +environment(r))
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] # for i in range(len(list1)): # for j in range(len(list2)): # list1[i]==list2[j] list3 = zip(list1,list2) list4=list(list3) list4.sort(key = lambda x: x[1]) print(list4)
# -*- coding: UTF-8 -*- # 获取今天、昨天和明天的日期 # 引入datetime模块 def testdatetime(): from datetime import datetime # 计算今天的时间 today = datetime.date.today() # 计算昨天的时间 yesterday = today - datetime.timedelta(days=1) # 计算明天的时间 tomorrow = today + datetime.timedelta(days=1) # 打印这三个时间 print(yesterday, today, tomorrow) # trailtime=datetime.strptime('', '%Y-%m-%d %H:%M:%S') trailfiletimeStr = '2015-04-15 12:00:05' trailfiletime = datetime.datetime.strptime(trailfiletimeStr, '%Y-%m-%d %H:%M:%S') print(type(trailfiletime)) if trailfiletime <= (datetime.datetime.now() - datetime.timedelta(days=1)): print('一天前更新的') print(trailfiletime) i = 0 while i <= 3: print (i) i = i + 1 # timenow = datetime.datetime.now() # timedelay = timenow + datetime.timedelta(seconds=3) # time.sleep(2) # if datetime.datetime.now() >= timedelay : # print ('时间已过,可以干活') # else: # print ('频率太高!') def testtime(): import time timestr = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) print (timestr) constr = '* 12 * *' # 分 时 日 月 timenow = time.strftime('%M %H %d %m %Y', time.localtime(time.time())).split(sep=' ') i = 0 for con in constr.split(sep=' '): if con != '*': timenow[i] = con print (con) i += 1 print (timenow) time1 = '' i = 0 for con in timenow: time1 = time1 + timenow[i] + ' ' i += 1 print (time1) print (time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(time1.rstrip(), '%M %H %d %m %Y'))) if time.localtime(time.time()) > time.strptime(time1.rstrip(), '%M %H %d %m %Y'): print ('吉时已到!') timestr def testdatetime2(schedulestr): from datetime import datetime # 将时间拆分成元组,并用定时器中配置替换相对应的时间 scheduletuple = datetime.today().strftime("%M %H %d %m %Y").split(sep=' ') i = 0 delay = 0 delaydict = {0:3600,1:86400,2:1036800,3:1036800} for element in schedulestr.split(sep=' '): if element != '*': scheduletuple[i] = element if delay == 0 : delay = delaydict[i] i += 1 print (scheduletuple) # 把元组组合成字符串,并转换为时间 scheduletime = '' i = 0 for element in scheduletuple: scheduletime = scheduletime + scheduletuple[i] + ' ' i += 1 # 判断是否是良辰吉日 if datetime.now() >= datetime.strptime(scheduletime.rstrip(), '%M %H %d %m %Y'): print ('吉时已到!出发!') else: print ('等待!') #返回系统需要延时的时间 return delay def testdatetime3(): from datetime import datetime yearno = 2013 print (datetime.today().replace(year=yearno)) if __name__ == '__main__': print (testdatetime2('* 12 * *')) print (testdatetime2('2 12 * 7')) print (testdatetime2('1 * * 7'))
#citire date de la tastatura1 produs_dorit = str(input("Care este produsul pentru care verificati stocul? ")) bonuri = int(input("Cate cititi?: ")) #definire matrice date = {} date["bonuri"] = {} date["produse_bon"] = {} date["stoc"] = {} for bon in range(bonuri): bon += 1 date["bonuri"][bon] = {} produse = int(input("Cate produse doriti sa adaugati pe bonul "+str(bon)+": ")) for produs in range(produse): produs += 1 nume = str(input("Ce nume are produsul cu numarul "+str(produs) + ": ")) valoare = int(input("Ce valoare are produsul cu numarul "+str(produs) + ": ")) date["bonuri"][bon][produs] = { "nume": nume, "valoare": valoare } for bon in date["bonuri"].keys(): date["produse_bon"][bon] = [] for produs in date["bonuri"][bon].keys(): date["produse_bon"][bon].append(date["bonuri"][bon][produs]["nume"]) for bon in date["produse_bon"].keys(): if produs_dorit in date["produse_bon"][bon]: print("Produsul " + produs_dorit + " a fost gasit pe bonul cu numarul " + str(bon) + ".") total_bon = 0 for produs in date["bonuri"][bon]: produs_curent = date["bonuri"][bon][produs] total_bon += produs_curent["valoare"] print("Valoarea totala a produselor de pe bonul cu numarul " + str(bon) + " care include si produsul" + produs_dorit + " este de " + str(total_bon) + ".")
# PYTHON: Reverse-sort the lines from standard input # execute:python rosetta.py < testcase.list> testcase.out import sys # bring in s standard library lines = sys.__stdin__.readlines() # read every line from stdin into an array # 假设输入的就是有向无环图 # lines.sort(reverse = True) # 新建一个数组,每一个元素都是不同的 # 再建一个字典,key为每个不同的行,value为在上述数组里头的标号 index = 0 dic = {} li = [] for line in lines: if line not in dic: dic[line] = index index = index + 1 li.append(line) # graph stand for the list of the list of each node # create a list of empty list print("***************************\n") for one_line in lines: print(one_line), # the ending comma means "don't print another newline"
import random bienvenida = input( '\n- Hola, a continuacion tenes que adivinar el nro entre uno y cien que piense yo. \nPresiona ENTER para comenzar..') nro = random.randint(1, 2) intentos = 0 nroIngresado = int(input('- ingresa el numero \n\t')) while nroIngresado != nro: intentos += 1 print('- ya llevas', intentos, 'intentos\n') if nroIngresado > nro: nroIngresado = int(input('- elegite un numero mas bajo:\n\t ')) else: nroIngresado = int(input('- elegite un numero mas alto:\n\t ')) print( '\n- exelente, adivinaste el numero, era ', nro, '\n- te ha tomado ', intentos, 'intentos adivinarlo') input('\nENTER para terminar..')
# 使用点语法获取json数据 from collections import abc class Solution(object): def __init__(self, mapping): self._data = dict(mapping) def __getattr__(self, name): if hasattr(self._data, name): return getattr(self._data, name) else: return Solution.build(self._data[name]) @classmethod def build(cls, obj): if isinstance(obj, abc.Mapping): return cls(obj) elif isinstance(obj, abc.MutableSequence): return [cls.build(item) for item in obj] else: return obj s = Solution({'a': {'b': 1}}) print(s.__dict__, s.a.b)
import pandas as pd import plotly.express as px df = pd.read_csv('./csv files/data.csv') #fig = px.line(df, x='Year', y='Per capita income', color='Country', title='Per Capita Income') #fig = px.bar(df, x='Country', y='InternetUsers') fig = px.scatter(df, x='Population', y='Per capita') fig.show()
''' an attempt to randomly generate text ''' from tkinter import * from random import randint, sample, choice class RandomCharsGen: def __init__(self): self.root = Tk() w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight() self.root.overrideredirect(1) # go in full screen mode self.root.geometry("%dx%d+0+0"%(w,h)) self.root.title('Random Characters Generator') self.root.attributes('-alpha',0.99) # set of characters to choose from self.chars = 'abcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()-_+={[}]|\\:;,.<>?/' self.fontsChoices = ['Arial', 'Times', 'Comics', 'Sans','Symbol','Courier'] self.canvas = Canvas(self.root, width=w, height=h, background='black') #self.canvas.create_text(w/2, h/2, text="Dhiraj", font=('Arial',16), fill='red') self.canvas.pack() # quit the program after any keypress or motion of mouse self.root.bind('<Any-KeyPress>', quit) self.root.bind('<Motion>', quit) self.create_random_text() self.root.mainloop() def create_random_text(self): r = lambda:randint(0,255) # random number between 0 and 255 to define colors self.color = '#%02x%02x%02x' % (r(), r(), r()) # define random colors self.color1 = '#%02x%02x%02x' % (r(), r(), r()) self.color2 = '#%02x%02x%02x' % (r(), r(), r()) self.xpos = randint(0, self.root.winfo_screenwidth()-10) self.ypos = randint(0, self.root.winfo_screenheight()-10) #self.itm1 = self.canvas.create_text(self.xpos, self.ypos, # text=sample(self.chars,6), font=('Arial',randint(16,24)), fill=self.color) self.itm1 = self.canvas.create_text(self.root.winfo_screenwidth()/2, self.root.winfo_screenheight()/2, text=sample(self.chars,randint(3,len(self.chars)/2)), font=(choice(self.fontsChoices),randint(16,34), 'bold'), fill=self.color) self.itm2 = self.canvas.create_text(self.root.winfo_screenwidth()/2, self.root.winfo_screenheight()/2 - 60, text=sample(self.chars,randint(3,len(self.chars)/2)), font=(choice(self.fontsChoices),randint(16,34), 'bold'), fill=self.color1) self.itm3 = self.canvas.create_text(self.root.winfo_screenwidth()/2, self.root.winfo_screenheight()/2 + 60, text=sample(self.chars,randint(3,len(self.chars)/2)), font=(choice(self.fontsChoices),randint(16,34), 'bold'), fill=self.color2) self.canvas.after(800, self.deleteOld) # repeatedly call deleteOld method aftr 300 milliseconds self.canvas.after(800, self.create_random_text) def deleteOld(self): # use this function to overwrite on previously created items/texts. self.canvas.delete(self.itm1, self.itm2, self.itm3) def quit(self, event): self.root.destroy() # start the screensaver if __name__ == '__main__': scv = RandomCharsGen()
from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s " % (from_file, to_file) #in_file = open(from_file) # method 1, file.read(name of file) #in_data = file.read(in_file) # method 2, var_name = in_file(type file).read() #in_data = in_file.read() # method 3, var_name = open(name of file).read() # don't close the file. in_data = open(from_file).read() print "The input file is %d bytes long " % len(in_data) print "Does the output file exist? %r" % exists(to_file) # print "Ready, hit RETURN to continue, CTRL-C to abort." # raw_input() out_file = open(to_file, 'w').write(in_data) # out_file.write(in_data) print "Done." # don't close the file. # in case of method 3 #out_file.close() #in_file.close()
class Component: #union find, dfs """ 323. Number of Connected Components in an Undirected Graph https://www.lintcode.com/problem/graph-valid-tree/description Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] Output: 2 0 3 | | 1 --- 2 4 Example 2: Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]] Output: 1 0 4 | | 1 --- 2 --- 3 Note: You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. """ def countComponents(self, n: int, a: List[List[int]]) -> int: g, q, s, ans = defaultdict(list), deque(), set(), 0 for u, v in a: g[u].append(v) g[v].append(u) for e in range(n): if e in s: continue ans += 1 q.append(e) while q: u = q.popleft() if u in s: continue s.add(u) if len(s) == n: return ans q.extend(g[u]) return ans """ 433. Number of Islands https://www.lintcode.com/problem/number-of-islands/description Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent. Find the number of islands Example Input: [ [1,1,0,0,0], [0,1,0,0,1], [0,0,0,1,1], [0,0,0,0,0], [0,0,0,0,1] ] """ def numIslands(self, grid): n, m = len(grid), len(grid[0]) if len(grid) > 0 else 0 queue, seen = collections.deque(), [[False] * m for _ in range(n)] count = 0 for r in range(n) : for c in range(m) : if grid[r][c] != 1 or seen[r][c]: continue count += 1 self.bfs(grid, seen, queue, r, c, n, m) return count def bfs(self, grid, seen, queue, r, c, n, m) : queue.append((r, c)) seen[r][c] = True while queue: r, c = queue.popleft() for d_r, d_c in [(0, 1), (1, 0), (0, -1), (-1, 0)]: n_r, n_c = r + d_r, c + d_c if 0 <= n_r < n and 0 <= n_c < m and grid[n_r][n_c] == 1 and not seen[n_r][n_c]: queue.append((n_r, n_c)) seen[n_r][n_c] = True """ 477. Surrounded Regions https://www.lintcode.com/problem/surrounded-regions/description Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O''s into 'X''s in that surrounded region. Example Input: X X X X X O O X X X O X X O X X Output: X X X X X X X X X X X X X O X X Input: X X X X X O O X X O O X X O X X Output: X X X X X O O X X O O X X O X X #其他解法union-find """ def surroundedRegions(self, b): n, m, q = len(b), len(b[0]) if b else 0, deque() #把边界一起加到queue,标记所有连通块 for x in range(n): if b[x][0] == 'O': q.append((x, 0)) if b[x][m - 1] == 'O': q.append((x, m - 1)) for y in range(m): if b[0][y] == 'O': q.append((0, y)) if b[n - 1][y] == 'O': q.append((n - 1, y)) while q: x, y = q.popleft() b[x][y] = 'Z' for dx, dy in ((0, - 1), (-1, 0), (0, 1), (1, 0)): nx, ny = dx + x, dy + y if 0 <= nx < n and 0 <= ny < m and b[nx][ny] == 'O': q.append((nx, ny)) for i in range(n): for j in range(m): b[i][j] = 'O' if b[i][j] == 'Z' else 'X' """ 431. Connected Component in Undirected Graph https://www.lintcode.com/problem/connected-component-in-undirected-graph/description Find connected component in undirected graph Each node in the graph contains a label and a list of its neighbors. (A connected component of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.) You need return a list of label set. Input: {1,2,4#2,1,4#3,5#4,1,2#5,3} Output: [[1,2,4],[3,5]] Explanation: 1------2 3 \ | | \ | | \ | | \ | | 4 5 #其他解法:union_find """ def connectedSet(self, nodes): q, s, rslt = collections.deque(), set(), [] #把n一个个放到queue,记录每一个连通块 for n in nodes: if n in s: continue q.append(n) s.add(n) rslt.append([]) while q: nxt = q.popleft() rslt[-1].append(nxt.label) for nghbr in nxt.neighbors: if nghbr in s: continue q.append(nghbr) s.add(nghbr) rslt[-1].sort() return rslt """ 432. Find the Weak Connected Component in the Directed Graph https://www.lintcode.com/problem/find-the-weak-connected-component-in-the-directed-graph/description Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a weak connected component of a directed graph is a maximum subgraph in which any two vertices are connected by direct edge path.) Input: {1,2,4#2,4#3,5#4#5#6,5} Output: [[1,2,4],[3,5,6]] Explanation: 1----->2 3-->5 \ | ^ \ | | \ | 6 \ v ->4 #其他解法: union-find """ def connectedSet2(self, nodes): g = {} #把n一个个放到queue,记录每一个连通块 for n in nodes: g[n] = g.get(n, []) for nei in n.neighbors: g[nei] = g.get(nei, []) #反向也要链接,避免重复计算 g[nei].append(n) g[n].append(nei) ans, q, s = [], collections.deque(), set() for n in nodes: if n in s: continue q.append(n) s.add(n) ans.append([]) while q: nxt = q.popleft() ans[-1].append(nxt.label) for nei in g[nxt]: if nei not in s: q.append(nei) s.add(nei) ans[-1].sort() return ans """ 1718. Minimize Malware Spread https://www.lintcode.com/problem/minimize-malware-spread/description In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1. Some nodes initial are initially infected by malware. Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops. We will remove one node from the initial list. Return the node that if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index. Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread. Example 1: Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1] Output: 0 Example 2: Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2] Output: 0 Example 3: Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2] Output: 1 """ def minMalwareSpread(self, g, a): q, sn, s, init, ans, max_sz = deque(), set(), set(), set(a), min(a), 0 for n in sorted(a): if n in s: continue q.append(n) sn.add(n) while q: u = q.popleft() for v in range(len(g[u])): if g[u][v] == 0 or v in sn: continue q.append(v) sn.add(v) if len(sn & init) == 1 and len(sn) > max_sz: ans, max_sz = n, len(sn) s |= sn sn.clear() return ans """ 680. Split String https://www.lintcode.com/problem/split-string/description Give a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. Output all possible results. # Input: "123" Output: [["1","2","3"],["12","3"],["1","23"]] # Input: "12345" Output: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]] """ def splitString(self, s): ans = [] self.dfs(s, ans, [], 0) return ans def dfs(self, s, ans, u, i): if i == len(s): ans.append(u[:]) for j in range(i, min(i + 2, len(s))): u.append(s[i : j + 1]) self.dfs(s, ans, u, j + 1) u.pop()
#dfs需要深度参数,深度参数可以隐藏在其他参数里,ex: len """ 17. Subsets https://www.lintcode.com/problem/subsets/my-submissions Given a set of distinct integers, return all possible subsets. """ def subsets(self, a): ans = [] self.dfs(sorted(a), [], ans, 0) return ans def dfs(self, a, p, ans, i): if i == len(a): ans.append(list(p)) return p.append(a[i]) self.dfs(a, p, ans, i + 1) p.pop() self.dfs(a, p, ans, i + 1) """ 10. String Permutation II https://www.lintcode.com/problem/string-permutation-ii/description Given a string, find all permutations of it without duplicates. Input: "aabb" Output: ["aabb", "abab", "baba", "bbaa", "abba", "baab"] """ def stringPermutation2(self, s): ans = [] self.dfs(sorted(s), set(), '', ans) # str可以sort,方便判断同一层选过的相同字母 return ans #seen可以看作subset那题深度i def dfs(self, s, seen, p, ans): if len(p) == len(s): ans.append(p) return for j in range(len(s)): # j已经被当前排列(隐形深度i)选过 或者 j - 1和j一样,但是j - 1没有被选过深度i选过(代表剪枝) if j in seen or (j > 0 and s[j - 1] == s[j] and j - 1 not in seen): continue seen.add(j) self.dfs(s, seen, p + s[j], ans)#和subset不同:深度可以选s[j]之前的数字,只要之前层没有选过就可以 seen.remove(j) """ 15. Permutations https://www.lintcode.com/problem/permutations/description Given a list of numbers, return all possible permutations. """ def permute(self, a): ans = [] self.dfs(sorted(a), ans, [], 0) return ans def dfs(self, a, ans, p, s): if s + 1 == 1 << len(a): ans.append(p[:]) return for j in range(len(a)): if s & 1 << j: continue p.append(a[j]) self.dfs(a, ans, p, s | 1 << j) p.pop() """ 16. Permutations II https://www.lintcode.com/problem/permutations-ii/description Given a list of numbers with duplicate number in it. Find all unique permutations. """ def permuteUnique(self, a): ans = [] self.dfs(sorted(a), ans, [], set()) return ans def dfs(self, a, ans, p, s): if len(s) == len(a): ans.append(p[:]) for j in range(len(a)): if j in s or j > 0 and a[j - 1] == a[j] and j - 1 not in s: continue s.add(j) p.append(a[j]) self.dfs(a, ans, p, s) p.pop() s.remove(j) """ 33. N-Queens https://www.lintcode.com/problem/n-queens/description The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other(Any two queens can't be in the same row, column, diagonal line). Given an integer n, return all distinct solutions to the n-queens puzzle. 考点:same row, column, diagonal line剪枝实现 """ def solveNQueens(self, n): ans = [] self.dfs(n, ans, []) return ans def dfs(self, n, ans, b): i = len(b) if i == n: ans.append([''.join(['Q' if j == c else '.' for c in range(n)]) for j in b]) return for j in range(n): if any([pj == j or pi - pj == i - j or pi + pj == i + j for pi, pj in enumerate(b)]): continue b.append(j) self.dfs(n, ans, b) b.pop() """ 34. N-Queens II https://www.lintcode.com/problem/n-queens-ii/description Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. Have you met this question in a real interview? Example 1: Input: n=1 Output: 1 Explanation: 1: 1 Example 2: Input: n=4 Output: 2 Explanation: """ def totalNQueens(self, n): return self.dfs([0] * n, 0) def dfs(self, b, i): if i == len(b): return 1 ans = 0 for j in range(len(b)): vld = True for r, c in enumerate(b[:i]): if c == j or r - c == i - j or r + c == i + j: vld = False break if not vld: continue b[i] = j ans += self.dfs(b, i + 1) b[i] = 0 return ans """ 425. Letter Combinations of a Phone Number https://www.lintcode.com/problem/letter-combinations-of-a-phone-number/description """ def letterCombinations(self, dgts): ans, kb = [], {'1': '', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} if len(dgts) > 0: self.dfs(dgts, kb, ans, '', 0) return ans def dfs(self, dgts, kb, ans, p, i): if i == len(dgts): ans.append(p) return for c in kb[dgts[i]]: self.dfs(dgts, kb, ans, p + c, i + 1) """ 426. Restore IP Addresses https://www.lintcode.com/problem/restore-ip-addresses/description Given a string containing only digits, restore it by returning all possible valid IP address combinations. (Your task is to add three dots to this string to make it a valid IP address. Return all possible IP address.) Example 1: Input: "25525511135" Output: ["255.255.11.135", "255.255.111.35"] Explanation: ["255.255.111.35", "255.255.11.135"] will be accepted as well. Example 2: Input: "1116512311" Output: ["11.165.123.11","111.65.123.11"] """ def restoreIpAddresses(self, s: str) -> List[str]: ans = [] self.dfs(s, ans, [], 0) return ans def dfs(self, s, ans, p, i): if len(p) == 4: if i == len(s): ans.append(''.join(p)) return for j in range(i, min(i + 3, len(s))): e = s[i : j + 1] if int(e) > 255: break p.append(e + ('.' if j != len(s) - 1 else '')) self.dfs(s, ans, p, j + 1) p.pop() if int(e) == 0: break """ 1288. Reconstruct Itinerary https://www.lintcode.com/problem/reconstruct-itinerary/description Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Example 1: Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]. Example 2: Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]. Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order """ def findItinerary(self, t): g, e = defaultdict(list), defaultdict(lambda: Counter()) for u, v in t: g[u].append(v) e[u][v] += 1 for a in g.values(): a.sort() return self.dfs(g, len(t) + 1, ['JFK'], e) def dfs(self, g, n, p, e): if len(p) == n: return p u = p[-1] for v in g[u]: if not e[u][v]: continue e[u][v] -= 1 p.append(v) if self.dfs(g, n, p, e): return p e[u][v] += 1 p.pop() return None """ 836. Partition to K Equal Sum Subsets https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ https://www.lintcode.com/problem/partition-to-k-equal-sum-subsets/description Given an array of integers nums and a positive integer k, find whether it's possible to divide this array intok non-empty subsets whose sums are all equal. Example 1 Input: nums = [4, 3, 2, 3, 5, 2, 1] and k = 4 Output: True Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2, 3), (2, 3) with equal sums. Example 2 Input: nums = [1, 3, 2, 3, 5, 3, 1] and k = 3 Output: True Explanation: It's possible to divide it into 3 subsets (1, 2, 3), (1, 5), (3, 3) with equal sums. Notice 1 <= k <= len(nums) <= 16. 0 < nums[i] < 10000 """ def canPartitionKSubsets(self, a: List[int], k: int) -> bool: s = sum(a) return s % k == 0 and self.dfs({}, sorted(a), s // k, 0, 0) def dfs(self, f, a, t, msk, s): if msk in f: return f[msk] if s > t: return False if s == t: s = 0 if msk + 1 == 1 << len(a): return True f[msk] = False for i in range(len(a)): if msk & 1 << i or i > 0 and a[i - 1] == a[i] and not msk & 1 << i - 1: continue if self.dfs(f, a, t, msk | 1 << i, s + a[i]): f[msk] = True break return f[msk] """ 842. Split Array into Fibonacci Sequence Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list F of non-negative integers such that: 0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type); F.length >= 3; and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2. Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from S, or return [] if it cannot be done. Example 1: Input: "123456579" Output: [123,456,579] Example 2: Input: "11235813" Output: [1,1,2,3,5,8,13] Example 3: Input: "112358130" Output: [] Explanation: The task is impossible. Example 4: Input: "0123" Output: [] Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid. Example 5: Input: "1101111" Output: [110, 1, 111] Explanation: The output [11, 0, 11, 11] would also be accepted. """ def splitIntoFibonacci(self, s: str) -> List[int]: return self.dfs(s, [], 0) def dfs(self, s, p, i): if i == len(s) and len(p) >= 3: return p for j in range(i, len(s)): e = int(s[i: j + 1]) if len(p) < 2 or p[-2] + p[-1] == e and e <= 2 ** 31 - 1: p.append(e) if self.dfs(s, p, j + 1): return p p.pop() if e == 0: break """ 1032. Letter Case Permutation https://www.lintcode.com/problem/letter-case-permutation/description Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Example 1: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] """ def letterCasePermutation(self, s): ans = [] self.dfs(s, ans, '', 0) return ans def dfs(self, s, ans, p, i): if i == len(s): ans.append(p) return if s[i].isalpha(): self.dfs(s, ans, p + s[i].upper(), i + 1) self.dfs(s, ans, p + s[i].lower(), i + 1) else: self.dfs(s, ans, p + s[i], i + 1) """ 680. Split String https://www.lintcode.com/problem/split-string/description Give a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. Output all possible results. # Input: "123" Output: [["1","2","3"],["12","3"],["1","23"]] # Input: "12345" Output: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]] """ def splitString(self, s): ans = [] self.dfs(s, ans, [], 0) return ans def dfs(self, s, ans, p, i): if i == len(s): ans.append(u[:]) for j in range(i, min(i + 2, len(s))): p.append(s[i : j + 1]) self.dfs(s, ans, p, j + 1) p.pop() """ 136. Palindrome Partitioning https://www.lintcode.com/problem/palindrome-partitioning/description Given a string s. Partition s such that every substring in the partition is a palindrome. Return all possible palindrome partitioning of s. Input: "a" Output: [["a"]] Explanation: Only 1 char in the string, only 1 way to split it (itself). Input: "aab"Output: [["aa", "b"], ["a", "a", "b"]] Explanation: There are 2 ways to split "aab". 1. Split "aab" into "aa" and "b", both palindrome. 2. Split "aab" into "a", "a", and "b", all palindrome. NoticeDifferent partitionings can be in any order. Each substring must be a continuous segment of s. """ def partition(self, s: str) -> List[List[str]]: ans, f = [], [[i >= j for j in range(len(s))] for i in range(len(s))] for l in range(2, len(s) + 1): for i in range(len(s) - l + 1): j = i + l - 1 f[i][j] = f[i + 1][j - 1] and s[i] == s[j] self.dfs(f, s, ans, [], 0) return ans def dfs(self, f, s, ans, p, i): if i == len(s): ans.append(p[:]) return for j in range(i, len(s)): if not f[i][j]: continue p.append(s[i : j + 1]) self.dfs(f, s, ans, p, j + 1) p.pop() """ 653. Expression Add Operators https://www.lintcode.com/problem/expression-add-operators/description Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Example 1: Input: "123" 6 Output: ["1*2*3","1+2+3"] Example 2: Input: "232" 8 Output: ["2*3+2", "2+3*2"] Example 3: Input: "105" 5 Output: ["1*0+5","10-5"] Example 4: Input: "00" 0 Output: ["0+0", "0-0", "0*0"] Example 5: Input: "3456237490", 9191 Output: [] """ def addOperators(self, a, t): ans = [] self.dfs(a, t, ans, '', 0, 0) return ans def dfs(self, a, t, ans, s, p, i): if i == len(a): if t == 0: ans.append(s) return for j in range(i, len(a)): e = a[i : j + 1] d = int(a[i : j + 1]) if i == 0: self.dfs(a, t - d, ans, e, d, j + 1) else: self.dfs(a, t - d, ans, s + '+' + e, d, j + 1) self.dfs(a, t + d, ans, s + '-' + e, -d, j + 1) self.dfs(a, t + p - p * d, ans, s + '*' + e, p * d, j + 1) if a[i] == '0': break """ 427. Generate Parentheses https://www.lintcode.com/problem/generate-parentheses/description Given n, and there are n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. """ @highlight def generateParenthesis(self, n): ans = [] self.dfs(ans, '', n, n) return ans def dfs(self, ans, u, l_lft, r_lft): if l_lft == r_lft == 0: ans.append(u) return if l_lft > 0: self.dfs(ans, u + '(', l_lft - 1, r_lft) if l_lft < r_lft: self.dfs(ans, u + ')', l_lft, r_lft - 1)
""" 41. First Missing Positive https://leetcode.com/problems/first-missing-positive/ Given an unsorted integer array nums, find the smallest missing positive integer. Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space.? Example 1: Input: nums = [1,2,0] Output: 3 Example 2: Input: nums = [3,4,-1,1] Output: 2 Example 3: Input: nums = [7,8,9,11,12] Output: 1 Constraints: 0 <= nums.length <= 300 -231 <= nums[i] <= 231 - 1 """ def firstMissingPositive(self, a: List[int]) -> int: n = len(a) for i in range(len(a)): if a[i] <= 0 or a[i] > len(a): a[i] = n + 1 for e in a: if abs(e) == n + 1: continue i = abs(e) - 1 if a[i] > 0: a[i] = -a[i] for i in range(len(a)): if a[i] > 0: return i + 1 return len(a) + 1 """ ★428. Pow(x, n) https://www.lintcode.com/problem/powx-n/description Implement pow(x, n). (n is an integer.) Input: x = 9.88023, n = 3 Output: 964.498 Input: x = 8.84372, n = -5 Output: 0.000 """ def myPow(self, x: float, n: int) -> float: return self.dvcq(x, n) if n >= 0 else 1 / self.dvcq(x, -n) def dvcq(self, x, n): if n == 1: return x if n == 0: return 1 tmp = self.dvcq(x, n // 2) return tmp * tmp * (x if n & 1 else 1) def myPow(self, x, n): if n < 0: x, n = 1 / x, -n ans, tmp = 1, x while n > 0: if n & 1: ans *= tmp tmp, n = tmp * tmp, n // 2 #x^n = x^(n/2) * x^(n/2) return ans """ 140. Fast Power https://www.lintcode.com/problem/fast-power/description Calculate the an % b where a, b and n are all 32bit non-negative integers. Example For 231 % 3 = 2 For 1001000 % 1000 = 0 """ def fastPower(self, a, b, n): if n == 0: return 1 p = self.fastPower(a, b, n // 2) p = (p * p) % b if n % 2 == 1: return (p * a) % b if n % 2 == 0: return p def fastPower(self, a, b, n): ans = 1 while n > 0: if n % 2 == 1: ans = (ans * a) % b a = a * a % b n = n // 2 return ans % b """ 845. Greatest Common Divisor https://www.lintcode.com/problem/greatest-common-divisor/description Given two numbers, number a and number b. Find the greatest common divisor of the given two numbers. """ def gcd(self, a, b): while b != 0: a, b = b, a % b return a def gcd(self, a, b): return a if b == 0 else self.gcd(b, a % b) """ 414. Divide Two Integers ★★ https://www.lintcode.com/problem/divide-two-integers/description Divide two integers without using multiplication, division and mod operator. If it will overflow(exceeding 32-bit signed integer representation range), return 2147483647 The integer division should truncate toward zero. #思路:倍增被除数和计数器直到超过被除数, 减去被除数reset被除数 计数器 然后继续 100 18 2 0 100 36 4 0 100 72 8 0 28 9 1 8 28 18 2 8 10 9 1 10 1 9 1 11 """ def divide(self, dvdnd: int, dvsr: int) -> int: a, b, neg, cnt, ans = abs(dvdnd), abs(dvsr), bool(dvdnd < 0) ^ bool(dvsr < 0), 1, 0 while a >= b: if a >= b << 1: b, cnt = b << 1, cnt << 1 else: a, b, cnt, ans = a - b, abs(dvsr), 1, ans + cnt return min(-ans if neg else ans, (1 << 31) - 1) """ 196. Missing Number https://www.lintcode.com/problem/missing-number/description Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array. """ def findMissing(self, a): n = len(a) return n * (n + 1) // 2 - sum(a) """ Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." Example: Input: citations = [3,0,6,1,5] Output: 3 Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, her h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. """ """ 238. Product of Array Except Self https://leetcode.com/problems/product-of-array-except-self/ Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. Note: Please solve it without division and in O(n). Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) """ def productExceptSelf(self, a: List[int]) -> List[int]: ans = [0] * len(a) p = 1 for i in range(len(a)): ans[i] += p p *= a[i] p = 1 for i in range(len(a) - 1, -1, -1): ans[i] *= p p *= a[i] return ans """ 168. Excel Sheet Column Title Easy 1549 283 Add to List Share Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 701 Output: "ZY" """ def convertToTitle(self, n: int) -> str: ans = [] while n > 0: n, d = (n-1) // 26, (n-1) % 26 ans.append(chr(ord('A') + d)) return ''.join(ans[::-1]) # 0 -> A # 25 -> Z # 26 -> AA # 0 + 1 -> A + 1 # 25 + 1 -> Z + 1 # 26 + 1-> AA + 1 # 1 -> A # 26 -> Z # 27 -> AA # n = (A+1) * 26^2 + (B+1) * 26^1 + (Z+1) * 26^0 # n = (A+1) * 26^2 + (B+1) * 26^1 + (Z+1) # n - 1 = (A+1) * 26^2 + (B+1) * 26^1 + Z
class array: """ 686. Repeated String Match Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1. Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc". Example 1: Input: a = "abcd", b = "cdabcdab" Output: 3 Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it. Example 2: Input: a = "a", b = "aa" Output: 2 Example 3: Input: a = "a", b = "a" Output: 1 Example 4: Input: a = "abc", b = "wxyz" Output: -1 """ def repeatedStringMatch(self, a: str, b: str) -> int: for f in range(1, len(b) // len(a) + 3): if (a * f).find(b) != -1: return f return -1 """ 6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR". Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" """ def convert(self, s: str, nr: int) -> str: z, i, d = [[] for _ in range(nr)], 0, 1 for c in s: z[i].append(c) if nr == 1: continue if i == nr - 1: d = -1 elif i == 0: d = 1 i += d return ''.join([''.join(e) for e in z]) 224. Basic Calculator """ 524. Longest Word in Dictionary through Deleting https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. Input: s = "abpcplea", d = ["ale","apple","monkey","plea"] Output: "apple" Input: s = "abpcplea", d = ["a","b","c"] Output: "a" """ def findLongestWord(self, s: str, d: List[str]) -> str: d = sorted(d, key = lambda e : (-len(e), e)) for e in d: i = 0 for c in s: if c == e[i]: i += 1 if i == len(e): return e return '' """ 1249. Minimum Remove to Make Valid Parentheses https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "a)b(c)d" Output: "ab(c)d" Example 3: Input: s = "))((" Output: "" Explanation: An empty string is also valid. Example 4: Input: s = "(a(b(c)d)" Output: "a(b(c)d)" """ def minRemoveToMakeValid(self, s: str) -> str: l, mtchd, a, ans = 0, 0, [], [] for i, c in enumerate(s): if c == '(': l += 1 elif c == ')': if not l - mtchd: continue mtchd += 1 a.append(c) for i, c in enumerate(a): if c == '(': if not mtchd: continue mtchd -= 1 ans.append(c) return ''.join(ans)
""" 128. Longest Consecutive Sequence https://leetcode.com/problems/longest-consecutive-sequence/ Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. Follow up: Could you implement the O(n) solution? Example 1: Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. Example 2: Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9 """ def longestConsecutive(self, a: List[int]) -> int: s, ans = set(a), 0 for e in a: if e - 1 in s: continue v, cnt = e, 0 while v in s: cnt += 1 ans = max(ans, cnt) v += 1 return ans def longestConsecutive(self, a: List[int]) -> int: ans, f, cnt = 1 if a else 0, {}, {e: 1 for e in a} for e in a: if e - 1 not in cnt: continue ra, rb = self.fnd(f, e - 1), self.fnd(f, e) if ra != rb: f[rb] = ra cnt[ra] += cnt[rb] ans = max(ans, cnt[ra]) return ans def fnd(self, f, n): if n not in f: f[n] = n if f[n] == n: return n f[n] = self.fnd(f, f[n]) return f[n] """ 594. Longest Harmonious Subsequence https://leetcode.com/problems/longest-harmonious-subsequence/ We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: nums = [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. Example 2: Input: nums = [1,2,3,4] Output: 2 Example 3: Input: nums = [1,1,1,1] Output: 0 """ def findLHS(self, a: List[int]) -> int: d, ans = {}, 0 for e in a: d[e] = d.get(e, 0) + 1 ans = max(ans, (d[e] + d[e + 1]) if e + 1 in d else 0, (d[e] + d[e - 1]) if e - 1 in d else 0) return ans """ 554. Brick Wall https://leetcode.com/problems/brick-wall/ There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right. If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Example:Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] """ def leastBricks(self, aa: List[List[int]]) -> int: d = collections.Counter() for a in aa: p = 0 for i in range(len(a) - 1): p += a[i] d[p] += 1 return len(aa) - (max(d.values()) if d else 0) """ 560. Subarray Sum Equals K https://leetcode.com/problems/subarray-sum-equals-k/ Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 """ def subarraySum(self, a: List[int], k: int) -> int: p, d, ans = 0, collections.Counter([0]), 0 for e in a: p += e ans += d[p - k] d[p] += 1 return ans """ 523. Continuous Subarray Sum https://leetcode.com/problems/continuous-subarray-sum/ Example 1: Input: [23, 2, 4, 6, 7], k=6 Output: True Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6. Example 2: Input: [23, 2, 6, 4, 7], k=6 Output: True Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42. """ d, p = {0: 0}, 0 for i, e in enumerate(a): p = (p + e) % k if k != 0 else p + e if p in d and i + 1 - d[p] > 1: return True d[p] = d.get(p, i + 1) return False """ 525. Contiguous Array https://leetcode.com/problems/contiguous-array/ Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. """ def findMaxLength(self, a: List[int]) -> int: diff, d, ans = 0, {0: 0}, 0 for i, e in enumerate(a): diff += 1 if e == 1 else -1 if diff in d: ans = max(ans, i + 1 - d[diff]) else: d[diff] = i + 1 return ans """ 581. Shortest Unsorted Continuous Subarray https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length. Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Example 2: Input: nums = [1,2,3,4] Output: 0 Example 3: Input: nums = [1] Output: 0 """ def findUnsortedSubarray(self, a: List[int]) -> int: s, l, r = [], len(a) - 1, 0 for i in range(len(a)): while s and a[s[-1]] > a[i]: l = min(l, s.pop()) s.append(i) s.clear() for i in range(len(a) - 1, -1, -1): while s and a[s[-1]] < a[i]: r = max(r, s.pop()) s.append(i) return r - l + 1 if l < r else 0 """ 565. Array Nesting https://leetcode.com/problems/array-nesting/ A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S. Example 1: Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} #其他解法 """ def arrayNesting(self, a: List[int]) -> int: s, cnt, ans = set(), 0, 0 for i in range(len(a)): cnt = 0 while a[i] not in s: s.add(a[i]) i = a[i] cnt = cnt + 1 ans = max(ans, cnt) return ans
class Heterodromous: """ 56. Two Sum https://www.lintcode.com/problem/two-sum/description Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are zero-based. """ def twoSum(self, a, t): d = {} for i in range(len(a)): if a[i] in d: return [i, d[a[i]]] if i < d[a[i]] else [d[a[i]], i] else: d[t - a[i]] = i return [-1, -1] def twoSum(self, a, t): a = [(e, i) for i, e in enumerate(a)] l, r = 0, len(a) - 1 a.sort() while l < r: sum = a[l][0] + a[r][0] if sum == t: return sorted([a[l][1], a[r][1]]) if sum < t: l += 1 else: r -= 1 return None """ 57. 3Sum https://www.lintcode.com/problem/3sum/description Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. """ def threeSum(self, a): a, n, rslt = sorted(a), len(a), [] for i in range(n): if i > 0 and a[i - 1] == a[i]: #i剪枝 continue l, r = i + 1, n - 1 while l < r: sum = a[l] + a[r] if sum < -a[i] or l > i + 1 and a[l - 1] == a[l]: #l 剪枝 l += 1 elif sum > -a[i] or r < n - 1 and a[r] == a[r + 1]: # r剪枝 r -= 1 else: rslt, l, r = rslt + [[a[i], a[l], a[r]]], l + 1, r - 1 return rslt """ 58. 4Sum https://www.lintcode.com/problem/4sum/description Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Input:[1,0,-1,0,-2,2],0 Output: [[-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2]] """ def fourSum(self, a, t): a, n, ans = sorted(a), len(a), [] for i in range(n - 3): if i > 0 and a[i - 1] == a[i]: #i剪枝 continue for j in range(i + 1, n - 2): if j > i + 1 and a[j - 1] == a[j]: #j剪枝 continue s, l, r = a[i] + a[j], j + 1, n - 1 while l < r: t_s = s + a[l] + a[r] if t_s < t or l > j + 1 and a[l - 1] == a[l]: #l剪枝 l += 1 elif t_s > t or r < n - 1 and a[r] == a[r + 1]:#r剪枝 r -= 1 else: ans.append([a[i], a[j], a[l], a[r]]) l, r = l + 1, r - 1 return ans """ 59. 3Sum Closest https://www.lintcode.com/problem/3sum-closest/description Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. Input:[2,7,11,15],3 Output:20 Explanation: 2+7+11=20 Input:[-1,2,1,-4],1 Output:2 Explanation: -1+2+1=2 Challenge O(n^2) time, O(1) extra space Notice You may assume that each input would have exactly one solution. """ def threeSumClosest(self, a, t): a.sort() ans, n, min_diff = sys.maxsize, len(a), sys.maxsize for i in range(n): if i > 0 and a[i - 1] == a[i]: continue l, r = i + 1, len(a) - 1 while l < r: s = a[i] + a[l] + a[r] diff = abs(s - t) if diff < min_diff: ans, min_diff = s, diff if s < t or l > i + 1 and a[l - 1] == a[l]: l += 1 elif s > t or r < n - 1 and a[r] == a[r + 1]: r -= 1 else: return ans return ans """ 363. Trapping Rain Water https://www.lintcode.com/problem/trapping-rain-water/description Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. Input: [0,1,0] Output: 0 Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Challenge: O(n) time and O(1) memory O(n) time and O(n) memory is also acceptable. """ def trap(self, a: List[int]) -> int: l, r, ans = 0, len(a) - 1, 0 max_l, max_r = 0, a[-1] if a else 0 while l < r: if a[l] < a[r]: max_l = max(max_l, a[l]) ans += max_l - a[l] l += 1 else: max_r = max(max_r, a[r]) ans += max_r - a[r] r -= 1 return ans """ 382. Triangle Count Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find? Given array S = [3,4,6,7], return 3. They are: [3,4,6] [3,6,7] [4,6,7] Given array S = [4,4,4,4], return 4. They are: [4(1),4(2),4(3)] [4(1),4(2),4(4)] [4(1),4(3),4(4)] [4(2),4(3),4(4)] """ def triangleNumber(self, a: List[int]) -> int: cnt, a = 0, sorted(a) for t in range(len(a) - 1, 1, -1): l, r = 0, t - 1 while l < r: if a[l] + a[r] > a[t]: cnt, r = cnt + r - l, r - 1 else: l += 1 return cnt """ 415. Valid Palindrome http://www.lintcode.com/problem/valid-palindrome-ii/ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Input: "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" Input: "race a car" Output: false Explanation: "raceacar" Challenge O(n) time without extra memory. Notice Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. """ def isPalindrome(self, s): l, r = 0, len(s) - 1 while l < r: if not s[l].isalnum(): l += 1 continue if not s[r].isalnum(): r -= 1 continue if s[l].lower() != s[r].lower(): return False l, r = l + 1, r - 1 return True """ 443. Two Sum - Greater than target https://www.lintcode.com/problem/two-sum-greater-than-target/description Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number. Please return the number of pairs """ def twoSum2(self, a, t): l, r = 0, len(a) - 1 a.sort() cnt = 0 while l < r: if a[l] + a[r] > t: cnt += r - l # 大于t,代表当前l,l + 1...2..到r 符合条件 r -= 1 else: l += 1 return cnt """ 533. Two Sum - Closest to target https://www.lintcode.com/problem/two-sum-closest-to-target/description Given an array nums of n integers, find two integers in nums such that the sum is closest to a given number, target. Return the absolute value of difference between the sum of the two integers and the target. """ def twoSumClosest(self, a, t): l, r, min_diff = 0, len(a) - 1, sys.maxsize a.sort() while l < r: s = a[l] + a[r] min_diff = min(min_diff, abs(s - t)) if s < t: l += 1 elif s > t: r -= 1 else: break return min_diff """ 587. Two Sum - Unique pairs https://www.lintcode.com/problem/two-sum-unique-pairs/description Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target number. Please return the number of pairs. Example Input: nums = [1,1,2,45,46,46], target = 47 Output: 2 Explanation: 1 + 46 = 47 2 + 45 = 47 """ def twoSum6(self, nums, target): nums = sorted(nums) left, right = 0, len(nums) - 1 result = 0 while left < right: sum = nums[left] + nums[right] if sum < target: left +=1 elif sum > target: right -= 1 else: result += 1 left += 1 right -= 1 while left < right and nums[left- 1] == nums[left]: left += 1 while left < right and nums[right] == nums[right + 1]: right -= 1 return result """ 608. Two Sum II - Input array is sorted https://www.lintcode.com/problem/two-sum-ii-input-array-is-sorted/description Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. """ def twoSum(self, a, t): l, r = 0, len(a) - 1 while l < r: sum = a[l] + a[r] if sum == t: return [l + 1, r + 1] elif sum < t: l += 1 else: r -= 1 return None """ 609. Two Sum - Less than or equal to target https://www.lintcode.com/problem/two-sum-less-than-or-equal-to-target/description Given an array of integers, find how many pairs in the array such that their sum is less than or equal to a specific target number. Please return the number of pairs. """ def twoSum5(self, nums, target): nums.sort() left, right = 0, len(nums) - 1 count = 0 while left < right: if nums[left] + nums[right] <= target: count += (right - left) left += 1 else: right -= 1 return count """ 891. Valid Palindrome II https://www.lintcode.com/problem/valid-palindrome-ii/description Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. # Input: s = "aba" Output: true Explanation: Originally a palindrome. # Input: s = "abca" Output: true Explanation: Delete 'b' or 'c'. # Input: s = "abc" Output: false Explanation: Deleting any letter can not make it a palindrome. Notice: The string will only contain lowercase characters. The maximum length of the string is 50000. """ def validPalindrome(self, s): l, r = 0, len(s) - 1 while l < r: if s[l] != s[r]: break l, r = l + 1, r - 1 return self.isPlndrm(s, l + 1, r) or self.isPlndrm(s, l, r - 1) def isPlndrm(self, s, l, r): while l < r: if s[l] != s[r]: return False l, r = l + 1, r - 1 return True """ 894. Pancake Sorting https://www.lintcode.com/problem/pancake-sorting/description Given an unsorted array, sort the given array. You are allowed to do only following operation on array. flip(arr, i): Reverse array from 0 to i Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons possible, the goal is to sort the sequence in as few reversals as possible. Input: array = [6,11,10,12,7,23,20] Output:[6,7,10,11,12,20,23] Explanation:flip(array, 5) flip(array, 6) flip(array, 0) flip(array, 5) flip(array, 1) flip(array, 4) flip(array, 1) flip(array, 3) flip(array, 1) flip(array, 2) Input: array = [4, 2, 3] Output: [2, 3, 4] Explanation: flip(array, 2) flip(array, 1) Notice: You only call flip function. Don't allow to use any sort function or other sort methods. #l每次找[l, r]之间最大值, 翻转到0, 翻转到r, r递减 """ def pancakeSort(self, a): for r in range(len(a) - 1, 0, -1): # 执行n-1次,因为最后剩一个最小的在第一个,不用处理。 max_l = 0 for l in range(r + 1): if a[l] > a[max_l]: max_l = l if max_l != 0: FlipTool.flip(a, max_l) #翻转到0 FlipTool.flip(a, r) #反转到r """ 200. Longest Palindromic Substring https://www.lintcode.com/problem/longest-palindromic-substring/description Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 其他解法:dp """ def longestPalindrome(self, s): lngst = '' for m in range(len(s)): lngst = max([lngst, self.plndrm(s, m, m), self.plndrm(s, m, m + 1)], key=len) return lngst def plndrm(self, s, l, r): lngth = 0 while l >= 0 and r < len(s): if s[l] != s[r]: break lngth, l, r = lngth + 1, l - 1, r + 1 return s[l + 1 : r] """ 11. Container With Most Water https://leetcode.com/problems/container-with-most-water/ Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Notice that you may not slant the container. Example 1: Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example 2: Input: height = [1,1] Output: 1 Example 3: Input: height = [4,3,2,1,4] Output: 16 Example 4: Input: height = [1,2,1] Output: 2 """ def maxArea(self, a: List[int]) -> int: l, r, ans = 0, len(a) - 1, 0 #移动较大边, 下次面积肯定比这次下, 因为面积取决于较小边, while l < r: ans = max(ans, (r - l) * min(a[l], a[r])) if a[l] < a[r]: l += 1 else: r -= 1 return ans """ 881. Boats to Save People https://leetcode.com/problems/boats-to-save-people/ The i-th person has weight people[i], and each boat can carry a maximum weight of limit. Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.) Example 1: Input: people = [1,2], limit = 3 Output: 1 Explanation: 1 boat (1, 2) Example 2: Input: people = [3,2,2,1], limit = 3 Output: 3 Explanation: 3 boats (1, 2), (2) and (3) Example 3: Input: people = [3,5,3,4], limit = 5 Output: 4 Explanation: 4 boats (3), (3), (4), (5) """ def numRescueBoats(self, a: List[int], t: int) -> int: a.sort() l, r = 0, len(a) - 1 cnt = 0 while l < r: if a[l] + a[r] <= t: l += 1 cnt, r = cnt + 1, r - 1 return cnt + 1 if l == r else cnt """ 977. Squares of a Sorted Array https://leetcode.com/problems/squares-of-a-sorted-array/ Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] """ def sortedSquares(self, a: List[int]) -> List[int]: l, r = 0, len(a) - 1 ans, i = [0] * len(a), len(a) - 1 while l <= r: if abs(a[l]) > abs(a[r]): ans[i] = a[l] ** 2 l += 1 else: ans[i] = a[r] ** 2 r -= 1 i -= 1 return ans
# 1 kilometer is equal to 0.62137 miles. #Miles = kilometer * 0.62137 #Kilometer = Miles / 0.62137 km=float(input('Enter the kilometers?:')) print("To miles it is :", (km*0.62137))
l = int(input()) r = int(input()) list=[] for i in range(l,r+1): for j in range(i,r+1): x=i^j list.append(x) print(max(list))
# Enter your code here. Read input from STDIN. Print output to STDOUT np=input().split() n=int(np[0]) p=int(np[1]) l1=[] for i in range(p): l=list(map(float,input().split())) l1.append(l) for i in zip(*l1): a=sum(i)/len(i) print(a)
def spiral_alphabet_print(m,n,a): k=0 l=0 while(k<m and l<n): for i in range(l,n): print(a[k][i],end=" ") k+=1 for i in range(k,m): print(a[i][n-1],end=" ") n-=1 if(k<m): for i in range(n - 1, (l - 1), -1): print(a[m - 1][i], end=" ") m-=1 if(l<n): for i in range(m-1,(k-1),-1): print(a[i][l], end=" ") l+=1 a = [['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p','q', 'r']] R = 3 C = 6 spiral_alphabet_print(R, C, a)
num1 = input('Enter first number:') num2 = input('Enter second number:') print("sum is :",int(num1)+int(num2)) print("multiplication is :",int(num1)*int(num2)) print("division is :",float(num1)/float(num2)) print("mod is :",float(num1)%float(num2))
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: count=0 if len(flowerbed)==1 and flowerbed[0]==0: return 1 else: if flowerbed[0]==0 and flowerbed[1]==0: flowerbed[0]=1 count+=1 if flowerbed[-1]==0 and flowerbed[-2]==0: flowerbed[-1]=1 count+=1 for i in range(1,len(flowerbed)-2): if flowerbed[i]==0 and flowerbed[i-1]==0 and flowerbed[i+1]==0: flowerbed[i]=1 count+=1 return (count>=n)
def minion_game(string): string=string.upper() v=0 c=0 for i in range(len(string)): if(string[i]in"AEIOU"): v+=(len(string)-i) else: c+=(len(string)-i) if(v>c): print("Kevin",v) elif(v<c): print("Stuart",c) else: print("Draw")
if __name__ == '__main__': n = int(input()) l=[] for _ in range(n): abc=input().split() a=abc[0] if(a=='insert'): b=int(abc[1]) c=int(abc[2]) l.insert(b,c) elif(a=='print'): print(l) elif(a=='remove'): b=int(abc[1]) l.remove(b) elif(a=='append'): b=int(abc[1]) l.append(b) elif(a=='sort'): l.sort() elif(a=='pop'): l.pop() elif(a=='reverse'): l.reverse() else: pass
mobil = { "brand" : "Ford", "tahun" : 2012 } mobil["warna"] = "merah" print(len(mobil)) print(mobil) print(mobil["brand"])
from graphics import * #opens up the text file text_file = open("data.txt") #reads the data text file dataRead = text_file.read() #splits up the data file and transfers it into a list dataList = dataRead.split("\n") #closes the file text_file.close() # Creates a window, 'ModuleData', to the size allocated window = GraphWin("ModuleData", 880, 400) window.setBackground(color_rgb(0,0,0)) # Create and draw a circle #number1--------------------------------green ball1 = Circle(Point(20,350), 9) ball1.setFill(color_rgb(43,228,61)) ball1.draw(window) #number2 ball2 = Circle(Point(50,350), 9) ball2.setFill(color_rgb(21,233,42)) ball2.draw(window) #number3 ball3 = Circle(Point(80,350), 9) ball3.setFill(color_rgb(38,236,58)) ball3.draw(window) #number4 ball4 = Circle(Point(110,350), 9) ball4.setFill(color_rgb(73,236,90)) ball4.draw(window) #number5 ball5 = Circle(Point(140,350), 9) ball5.setFill(color_rgb(92,233,106)) ball5.draw(window) #number6 ball6 = Circle(Point(170,350), 9) ball6.setFill(color_rgb(75,185,86)) ball6.draw(window) #number7 ball7 = Circle(Point(200,350), 9) ball7.setFill(color_rgb(111,175,117)) ball7.draw(window) #number8 ball8 = Circle(Point(230,350), 9) ball8.setFill(color_rgb(152,185,155)) ball8.draw(window) #number9--------------------------------orange ball9 = Circle(Point(260,350), 9) ball9.setFill(color_rgb(185,177,152)) ball9.draw(window) #number10 ball10 = Circle(Point(290,350), 9) ball10.setFill(color_rgb(196,177,116)) ball10.draw(window) #number11 ball11 = Circle(Point(320,350), 9) ball11.setFill(color_rgb(198,170,78)) ball11.draw(window) #number12 ball12 = Circle(Point(350,350), 9) ball12.setFill(color_rgb(216,176,43)) ball12.draw(window) #number13 ball13 = Circle(Point(380,350), 9) ball13.setFill(color_rgb(226,178,21)) ball13.draw(window) #number14 ball14 = Circle(Point(410,350), 9) ball14.setFill(color_rgb(239,185,9)) ball14.draw(window) #number15 ball15 = Circle(Point(440,350), 9) ball15.setFill(color_rgb(255,196,0)) ball15.draw(window) #number16 ball16 = Circle(Point(470,350), 9) ball16.setFill(color_rgb(255,219,95)) ball16.draw(window) #number17 ball17 = Circle(Point(500,350), 9) ball17.setFill(color_rgb(255,228,135)) ball17.draw(window) #number18 ball18 = Circle(Point(530,350), 9) ball18.setFill(color_rgb(255,208,135)) ball18.draw(window) #number19--------------------------------red ball19 = Circle(Point(560,350), 9) ball19.setFill(color_rgb(255,171,135)) ball19.draw(window) #number20 ball20 = Circle(Point(590,350), 9) ball20.setFill(color_rgb(240,138,93)) ball20.draw(window) #number21 ball21 = Circle(Point(620,350), 9) ball21.setFill(color_rgb(230,115,65)) ball21.draw(window) #number22 ball22 = Circle(Point(650,350), 9) ball22.setFill(color_rgb(222,92,37)) ball22.draw(window) #number23 ball23 = Circle(Point(680,350), 9) ball23.setFill(color_rgb(210,80,25)) ball23.draw(window) #number24 ball24 = Circle(Point(710,350), 9) ball24.setFill(color_rgb(210,56,25)) ball24.draw(window) #number25 ball25 = Circle(Point(740,350), 9) ball25.setFill(color_rgb(220,46,11)) ball25.draw(window) #number26 ball26 = Circle(Point(770,350), 9) ball26.setFill(color_rgb(233,41,3)) ball26.draw(window) #number27 ball27 = Circle(Point(800,350), 9) ball27.setFill(color_rgb(246,43,3)) ball27.draw(window) #number28 ball28 = Circle(Point(830,350), 9) ball28.setFill(color_rgb(255,62,23)) ball28.draw(window) #number29 ball29 = Circle(Point(860,350), 9) ball29.setFill(color_rgb(255,43,0)) ball29.draw(window) # Text Title text = Text(Point(425,40),"ModuleDATa") text.setSize(30) #text.setStyle('italic') text.setTextColor(color_rgb(255,255,255)) text.draw(window) # Text underneath the coloured circles text = Text(Point(426,380), "Click for Scores") text.setSize(20) text.setTextColor(color_rgb(255,255,255)) text.setStyle('bold') text.draw(window) # Text - marks ---> left and right = first number --- up and down = second number. #----------------------------------------green mark = Text(Point(30,100), "80") mark.setSize(36) mark.setTextColor(color_rgb(0,228,23)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(90,160), "79") mark.setSize(36) mark.setTextColor(color_rgb(0,228,23)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(60,220), "76") mark.setSize(36) mark.setTextColor(color_rgb(0,228,23)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(140,290), "74") mark.setSize(36) mark.setTextColor(color_rgb(0,228,23)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(180,90), "72") mark.setSize(36) mark.setTextColor(color_rgb(0,228,23)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(200,155), "62") mark.setSize(36) mark.setTextColor(color_rgb(0,228,23)) mark.setStyle("italic") mark.draw(window) #----------------------------------------orange mark = Text(Point(230,260), "59") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(250,90), "59") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(270,170), "59") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(300,270), "59") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(330,190), "59") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(350,90), "57") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(370,260), "57") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(400,90), "57") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(430,140), "55") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(460,270), "54") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(480,80), "54") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(500,200), "52") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") #mark.draw(window) mark = Text(Point(530,280), "52") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) mark = Text(Point(570,200), "52") mark.setSize(36) mark.setTextColor(color_rgb(255,196,0)) mark.setStyle("italic") mark.draw(window) #-----------------------------------------red mark = Text(Point(630,90), "49") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(640,290), "49") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(670,250), "48") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(710,270), "47") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(700,160), "44") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(770,130), "44") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(800,200), "44") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(830,260), "43") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) mark = Text(Point(840,150), "42") mark.setSize(36) mark.setTextColor("red") mark.setStyle("italic") mark.draw(window) # Wait until the mouse is clicked before closing the window window.getMouse()
mytuple= ('A','B','C','D','E') print(mytuple[3]) print(mytuple[1:3]) print(mytuple[-3:-1]) Coming=('A','B','C') Notcoming=('D','E','F') Changes=list(Coming) Changes.append('D') Changes.append('E') print(Changes) Coming=tuple(Changes) print(Coming) Changes=list(Coming) Changes.remove('C') Changes.remove('B') print(Changes) Coming=tuple(Changes) print(Coming) invitationcard=''' -------------------------------------------- Coming -------------------------------------------- 1.{} 2.{} 3.{} '''.format(mytuple[0],mytuple[3],mytuple[4]) print(invitationcard) invitationcard=''' -------------------------------------------- Not Coming -------------------------------------------- 1.{} 2.{} 3.{} '''.format(mytuple[1],mytuple[2],mytuple[3]) print(invitationcard)
# -*- coding: utf-8 -*- """Task solution: https://www.codewars.com/kata/first-variation-on-caesar-cipher """ import math RUNNERS = 5 NUMBERS_OF_LETTERS_IN_THE_ALPHABET = 26 def fib(num): """ Finds n-th element from a Fibonacci sequence. :param num: int : sequence number. :return: int : n-th element from a Fibonacci sequence. """ first, second = 0, 1 for _ in range(2, num - 1): first, second = second, first + second return second def fib_product(product): """ Finds two consistent Fibonacci numbers, being given their possible product. In case it is - returns a list with [fib(n), fib(n+1), True], otherwise [fib(n), fib(n+1), False]. :param product: int : product of two numbers. :return: list : list with first two elements from Fibonacci sequence and a boolean. """ current_value, num = 0, 0 fib1 = fib2 = 0 while current_value < product: num += 1 fib1 = fib(num) fib2 = fib(num + 1) current_value = fib1 * fib2 if current_value == product: return [fib1, fib2, True] return [fib1, fib2, False] def chunk_string(text: str, parts: int) -> list: """divide by message length between the five runners. :text : str : chipher text :parts : int : shows how many parts you need to split the text :returns : list : returns list with length which equal RUNNERS """ res = [text[i:i + len(text) // parts + 1] for i in range(0, len(text), len(text) // parts + 1)] return res def moving_shift(plain_text: str, shift: int) -> list: """Search for some intermediate results. :plain_text : str : input text which need to encrypt :shift : int : number of places up or down the alphabet :returns : list : returns list with length which equal RUNNERSs """ chipher_text = '' for letter in plain_text: if letter.isalpha(): shift_letter = ord(letter) + shift if shift_letter > ord('z'): shift_letter -= NUMBERS_OF_LETTERS_IN_THE_ALPHABET chipher_text += chr(shift_letter) else: chipher_text += letter return chunk_string(chipher_text, RUNNERS) def stick_together(chunks_chipher_text: list) -> str: """ Converts the list to string :chunks_chipher_text : list : encrypted tex is divided into RUNNERS elements :returns: str : returns full chipher text """ chipher_text = '' chipher_text = ''.join(chunks_chipher_text) return chipher_text def demoving_shift(chunks_chipher_text: list, shift: int) -> str: """ Decrypt chipher text :chunks_chipher_text : list : results of work moving_shift :shift : int : number of places up or down the alphabet :returns : str : returns plain text """ chipher_text = stick_together(chunks_chipher_text) plain_text = "" for letter in chipher_text: if letter.isalpha(): shift_letter = ord(letter) - shift if shift_letter > ord('z'): shift_letter += NUMBERS_OF_LETTERS_IN_THE_ALPHABET plain_text += chr(shift_letter) else: plain_text += letter return plain_text def artificial_rain(garden): """ counts longest descending subsequence :param garden: list : your garden :return: int : Best spot for artificial rain """ result_arr = [1] length = len(garden) for i in range(1, length): result = 1 for j in range(i, length): if garden[j] >= garden[j-1]: result += 1 else: break for k in range(i+result-1, length): if garden[k] <= garden[k-1]: result += 1 else: break result_arr.append(result) return max(result_arr) def zeros(num): """ Calculate the number of trailing zeros in a factorial of a given number and return number. :param num: int : Input number. :return: int : Number of the zeros """ i = 5 num_of_zeros = 0 while num >= i: num_of_zeros += num // i i *= 5 return num_of_zeros def gap_in_primes(gap, start, end): """Find a first pair of two successive prime numbers spaced with a defined gap-size. :param gap: int : Size of the gap between two primes. :param start: int : Gives the start number of the search (inclusive). :param end: int : Gives the end number of the search (inclusive). :return: list: The pair of two successive primes between start and end. :return: None: When there is no two successive prime numbers between start and end. """ primes = [] for possible_prime in range(start, end + 1): is_prime = True for num in range(2, int(possible_prime ** 0.5) + 1): if possible_prime % num == 0: is_prime = False break if is_prime: primes.append(possible_prime) i = 0 while i < len(primes) - 1: if primes[i + 1] - primes[i] == gap: return [primes[i], primes[i + 1]] i += 1 return None def solve(limit): """ Calculates x out of sequence 'x + 2x**2 + 3x**3 + .. + nx**n' :param limit: float : The limit of the sequence. :return: float : argument of the sequence. """ discriminant = math.pow((1 + 2 * limit), 2) - 4 * limit * limit argument = (- (1 + 2 * limit) + math.sqrt(discriminant)) / (-2 * limit) return argument def smallest(number): """ Find the smallest number doing only one permutation. :param number: int : number. :return: tuple : [the smallest number we got, the index of the digit we took, the index where we insert digit]. """ min_num, from_i, to_i = number, 0, 0 number = str(number) for i in enumerate(number): num1 = number[:i[0]] + number[i[0] + 1:] for j in range(len(num1) + 1): num = int(num1[:j] + number[i[0]] + num1[j:]) if num < min_num: min_num, from_i, to_i = num, i[0], j return [min_num, from_i, to_i] def prime_factors(number): """ Finds prime factors of the number. :param number: int : The initial number. :return: str : String with factors. """ fact = [] i = 2 result = '' while i <= number: if number % i == 0: fact.append(i) number //= i else: i += 1 if number > 1: fact.append(number) k = 0 while k < len(fact): num = fact.count(fact[k]) if num > 1: result += '(' + str(fact[k]) + '**' + str(num) + ')' else: result += '(' + str(fact[k]) + ')' k += num return result
print("""This is a puzzle favored by Einstein. You will be asked to enter a three digit number, where the hundred's digit differs from the one's digit by at least two. The procedure will always yield 1089 """) ABC = input("Give me a number: ") C = int(ABC) % 10 B = int((int(ABC) / 10) % 10) A = int((int(ABC) / 10 ** 2) % 10) CBA = int("{}{}{}".format(C, B, A)) if (CBA > int(ABC)): XYZ = (CBA) - int(ABC) else: XYZ = int(ABC) - (CBA) Z = int(XYZ) % 10 Y = int((int(XYZ) / 10) % 10) X = int((int(XYZ) / 10 ** 2) % 10) ZYX = int("{}{}{}".format(Z, Y, X)) Total = XYZ + ZYX print("For the number: {} the reverse number is: {}".format(ABC,CBA)) print("The difference between {} and {} is {}".format(ABC, CBA, XYZ)) print("The reverse difference is: ",ZYX) print("The sum of {} and {} is: {}".format(XYZ, ZYX, Total))
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Wiki.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets import bs4 as bs import urllib.request import re from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, sent_tokenize import heapq class Ui_WikiWindow(object): # Getting the data def get_data(self, url_input): try: source = urllib.request.urlopen(url_input).read() ''' ' lxml' = ' html.parser' They are used for reading html code serves as the basis for parsing text files formatted in HTML ''' soup = bs.BeautifulSoup(source, 'lxml') # Loop for finding p tags in html code which we're gonna sum up text = "" for paragraph in soup.findAll('p'): # the .text() method convert the paragraph from html to txt text += paragraph.text # Here we're getting the header tag H1 of the page, Then printing it in the plainText title = soup.find('h1') self.summary_plainTextEdit.appendPlainText(title.text + ":") self.summary_plainTextEdit.appendPlainText("------------------------------") # Calling the method summarize with text and num of words you want per sentence and number of sentence self.summarize(text) except: self.statusbar.showMessage("Check your internet connection or the URL you've entered") # https://en.wikipedia.org/wiki/Artificial_intelligence # Pre-processing the text def summarize(self, text): # The 1st copy of the text to remove all but the ( '.', ',') to recognize the sentences text = re.sub(r"\[[0-9]*\]", " ", text) text = re.sub(r"\s+", " ", text) # The 2nd copy of the text to remove all to recognize the words # symbols LIKE '! @ # $ % ^ & * ( ) = / - + . | : ; " | \ } { ] [ , < > . ? \ ' ' clean_text = text.lower() clean_text = re.sub(r"\W", " ", clean_text) clean_text = re.sub(r"\d", " ", clean_text) clean_text = re.sub(r"\s+", " ", clean_text) sentences = sent_tokenize(text) # Gettin' the stop words stop_words = set(stopwords.words("english")) # Dictionary for counting the word word2count = {} for word in word_tokenize(clean_text): if word not in stop_words: if word not in word2count.keys(): word2count[word] = 1 else: word2count[word] += 1 for key in word2count.keys(): word2count[key] = word2count[key] / max(word2count.values()) sent2score = {} for sentence in sentences: for word in word_tokenize(sentence.lower()): if word in word2count.keys(): if sentence not in sent2score.keys(): sent2score[sentence] = word2count[word] else: sent2score[sentence] += word2count[word] # Determine the number of sentence and the num of words per each try: best_sentences = heapq.nlargest(int(self.sentences_num.text()), sent2score, key=sent2score.get) except: best_sentences = heapq.nlargest(int(len(sent2score.keys()) / 2), sent2score, key=sent2score.get) # Show the sentences in the plainText for sentence in best_sentences: self.summary_plainTextEdit.appendPlainText(sentence + "\n") self.summary_plainTextEdit.setStatusTip( "Summarized " + str(int(len(sent2score.keys()))) + " sentences into " + str( int(len(best_sentences))) + " sentences") def setupUi(self, WikiWindow): WikiWindow.setObjectName("WikiWindow") WikiWindow.setWindowModality(QtCore.Qt.NonModal) WikiWindow.resize(594, 438) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(WikiWindow.sizePolicy().hasHeightForWidth()) WikiWindow.setSizePolicy(sizePolicy) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/wikipedia-logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) WikiWindow.setWindowIcon(icon) self.centralwidget = QtWidgets.QWidget(WikiWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.start_btn = QtWidgets.QPushButton(self.centralwidget) self.start_btn.setMaximumSize(QtCore.QSize(80, 70)) self.start_btn.setObjectName("start_btn") self.start_btn.setStatusTip("Start...") self.start_btn.clicked.connect(self.start) self.gridLayout.addWidget(self.start_btn, 1, 6, 1, 1) self.input_lineEdit = QtWidgets.QLineEdit(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.input_lineEdit.sizePolicy().hasHeightForWidth()) self.input_lineEdit.setSizePolicy(sizePolicy) self.input_lineEdit.setMinimumSize(QtCore.QSize(450, 0)) self.input_lineEdit.setMaximumSize(QtCore.QSize(1024, 70)) self.input_lineEdit.setClearButtonEnabled(True) self.input_lineEdit.setObjectName("input_lineEdit") self.gridLayout.addWidget(self.input_lineEdit, 1, 0, 1, 6) self.summary_label = QtWidgets.QLabel(self.centralwidget) self.summary_label.setObjectName("summary_label") self.gridLayout.addWidget(self.summary_label, 4, 0, 1, 1) self.url_label = QtWidgets.QLabel(self.centralwidget) self.url_label.setMaximumSize(QtCore.QSize(70, 70)) self.url_label.setObjectName("url_label") self.gridLayout.addWidget(self.url_label, 0, 0, 1, 1) self.sentences_label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sentences_label.sizePolicy().hasHeightForWidth()) self.sentences_label.setSizePolicy(sizePolicy) self.sentences_label.setMinimumSize(QtCore.QSize(70, 0)) self.sentences_label.setMaximumSize(QtCore.QSize(150, 70)) self.sentences_label.setObjectName("sentences_label") self.gridLayout.addWidget(self.sentences_label, 2, 0, 1, 1) self.sentences_num = QtWidgets.QLineEdit(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sentences_num.sizePolicy().hasHeightForWidth()) self.sentences_num.setSizePolicy(sizePolicy) self.sentences_num.setMaximumSize(QtCore.QSize(40, 70)) self.sentences_num.setObjectName("sentences_num") self.gridLayout.addWidget(self.sentences_num, 2, 1, 1, 1) self.summary_plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget) self.summary_plainTextEdit.setObjectName("summary_plainTextEdit") self.gridLayout.addWidget(self.summary_plainTextEdit, 5, 0, 1, 7) WikiWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(WikiWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 594, 21)) self.menubar.setObjectName("menubar") WikiWindow.setMenuBar(self.menubar) file_menu = self.menubar.addMenu("File") edit_menu = self.menubar.addMenu("Edit") save_file = QtWidgets.QAction("Save As...", WikiWindow) save_file.setShortcut("Ctrl+S") save_file.setStatusTip('Save file...') save_file.triggered.connect(self.saveFile) quit_action = QtWidgets.QAction("Exit", WikiWindow) quit_action.setShortcut("Esc") quit_action.setStatusTip('Quit WikiWindow') quit_action.triggered.connect(WikiWindow.close) file_menu.addAction(save_file) file_menu.addAction(quit_action) clear_action = QtWidgets.QAction("Clear all", WikiWindow) clear_action.setShortcut("Ctrl+D") # delete whats in the plaintext clear_action.setStatusTip('Empty all fields ') clear_action.triggered.connect(lambda: self.summary_plainTextEdit.clear()) clear_action.triggered.connect(lambda: self.input_lineEdit.clear()) edit_menu.addAction(clear_action) self.statusbar = QtWidgets.QStatusBar(WikiWindow) self.statusbar.setObjectName("statusbar") WikiWindow.setStatusBar(self.statusbar) self.retranslateUi(WikiWindow) QtCore.QMetaObject.connectSlotsByName(WikiWindow) def retranslateUi(self, WikiWindow): _translate = QtCore.QCoreApplication.translate WikiWindow.setWindowTitle(_translate("WikiWindow", "Summarize from Wiki")) self.sentences_label.setText(_translate("WikiWindow", "Number of Sentences :")) self.start_btn.setText(_translate("WikiWindow", "Summarize")) self.summary_label.setText(_translate("WikiWindow", "Summary :")) self.url_label.setText(_translate("WikiWindow", "Enter Url :")) def start(self): self.summary_plainTextEdit.clear() self.get_data(self.input_lineEdit.text()) def saveFile(self): try: name = QtWidgets.QFileDialog.getSaveFileName(None, 'Save File')[0] file = open(name, 'w') text = self.summary_plainTextEdit.toPlainText() file.write(text) file.close() except: self.statusbar.showMessage("Canceled") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) WikiWindow = QtWidgets.QMainWindow() ui = Ui_WikiWindow() ui.setupUi(WikiWindow) WikiWindow.show() sys.exit(app.exec_())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ make_trade_list.py Creates a list of trades and writes them to disk The file can be read by the risk_normalization program Created on Tue Sep 15 19:06:42 2020 @author: howard bandy """ import matplotlib.pyplot as plt import numpy as np mean_gain = 0.001 std_dev_gain = 0.003 number_trades = 1000 def make_trade_list( number_trades=number_trades, mean_gain = mean_gain, std_dev_gain = std_dev_gain): trades = np.random.normal(mean_gain, std_dev_gain, number_trades) return (trades) trades = make_trade_list(number_trades,mean_gain,std_dev_gain) # print (trades) file_name = 'generated_normal_trades.csv' f = open(file_name, 'w') s = f'Trades drawn from Normal distribution with mean: {mean_gain:0.3f}' s = s + f' and stdev: {std_dev_gain:0.3f}\n' f.write(s) for i in range(number_trades): s = str(trades[i]) + '\n' f.write(s) f.close() sorted_trades = np.sort(trades) y_pos = np.arange(len(trades)) plt.bar(y_pos,sorted_trades) plt.show() ## End ##
from pydrummer.models.sound import Sound class Mix(object): """A Mix is a single multi-sound pattern created by combing Sequences. A Mix is used for rhythm playback. TODO: Look into merging steps into one big wave file where notes can continue to play until they finish instead of cutting every sound off at each step """ def __init__(self, steps): self.steps = steps self.sounds = [Sound()] * steps self.pattern = [0] * steps def merge(self, sequence): """ Merge notes from the given sequence into the mix If the pattern in the given sequence has a note with the value of zero we do nothing and move on to the next note. If the note is one we merge it into the mix. We either merge the note into an existing note by mixing the two sounds together or we copy it into an empty slot in our pattern. """ for i in range(self.steps): if sequence.pattern[i] == 0: # nothing to copy or mix continue if self.pattern[i] == 0: # copy note self.pattern[i] = 1 self.sounds[i] = Sound(sequence.sound.name, sequence.sound.file_path) self.sounds[i].name = sequence.sound.name else: # mix notes together self.sounds[i].mix(sequence.sound) self.sounds[i].name = 'mix' def get_sounds(self): return self.sounds
import re pattern = r"abc" string = "abc" match_object = re.match(pattern, string) print(match_object) # <re.Match object; span=(0, 3), match='abc'> match - показывает вхождение шаблона внутрь строки. # span - показывает с какой по какую позицию содержится вхождение шаблона в строку string = "babcde" # None pattern = "a[abc]c" # в квадратных скобках перечисляются символы, которые подходят под шаблон на этой позиции # при запросе match подойдут строки "aac", "abc", "acc" и т.д. string = "abc, aac, acc" first = re.search(pattern, string) print(first) # <re.Match object; span=(0, 3), match='abc'> находит первое вхождение строки, подходящей под шаблон all_inclusions = re.findall(pattern, string) print(all_inclusions) # ['abc', 'aac', 'acc'] # findall находит все подстроки, подходящие под шаблон fixed_typos = re.sub(pattern, "abc", string) print(fixed_typos) # abc, abc, abc исправляет все вхождения шаблона согласно аргументу
f = open("text.txt", "r") # x = f.read() # чтение всего файла целиком # x = f.read(10) # чтение первых 10 символов(?) # print(repr(x)) # ''''First\nSecond\nThird', repr - это однозначное (недвусмысленное) представление объекта # в виде строки, такой, чтобы возможно было бы из этого представления сделать такой же объект''' # x = x.splitlines() # ['First', 'Second', 'Third'] # x = f.readline() # считывание одной строки # x = x.rstrip() # убираем символы справа # x = f.readline().rstrip() # объединяем строки for line in f: # '''итерация по файлу object, эффективен по памяти. если после него запустить read(), # он вернет пустую строку так как все уже считано''' line = line.rstrip() print(repr(line)) x = f.read() print(repr(x)) f.close()
"Задача: отсортировать имена по длине" x = [("Guido", 'Van', "Rossum"), ("Haskell", "Curry"), ("John", "Backus")] def length(name): return len("".join(name)) # разрезаем имена по пробелу, склеиваем и выводим длину x.sort(key=length) # сортируем по длине, используя функции key и length print(x) "Сокращаем код с помощью lambda" x.sort(key=lambda name: len("".join(name))) print(x)
import csv with open("example.csv") as f: reader = csv.reader(f) for row in f: print(row) # Если в файле у значения дробная часть отделена от целой не точкой а запятой, мы можем выделить значение кавычками # student,good,90,"90,2",100 # Также если элемент записан в две строки, мы можем выделить его кавычками # Можно явно указать символ в качестве разделителя. Пример: разделитель - табуляция. Указываем формат файла tsv и задаем # для ридера дополнительный параметр: delimiter="\t" with open("example.tsv") as f: reader = csv.reader(f, delimiter="\t") for row in f: print(row) # Чтобы записать файл в csv формате используется writer students = [["student", "best", 100, 100, 100, "Excellent score"], ["student", "good", 90, 90.2, 100, "Good score, but could do better"]] with open("example.csv", "a") as f: # параметр "а" указывает, мы дописываем в конец файла writer = csv.writer(f) for student in students: writer.writerow(student) # Вместо цикла for мы можем использовать метод writerows, который позволяет передавать список списков with open("example.csv", "a") as f: writer = csv.writer(f) writer.writerows(students) # Мы можем уточнять некоторое поведение, которое нам требуется при записи. Например, нам необходимо поместить все # элементы в кавычки. Для этого передаем специальный аргумент quoting with open("example.csv", "a") as f: writer = csv.writer(f, quoting=csv.QUOTE_ALL) writer.writerows(students) # используя константу QUOTE_ALL, мы заключаем в кавычки все элементы
import torch import torch.nn as nn from torch.autograd import Function class ReLU(Function): def forward(ctx, x): # 在forward中,需要定义MyReLU这个运算的forward计算过程 # 同时可以保存任何在后向传播中需要使用的变量值 ctx.save_for_backward(x) # 将输入保存起来,在backward时使用 output = input_.clamp(min=0) # relu就是截断负数,让所有负数等于0 return output def backward(ctx, grad_output): # 根据BP算法的推导(链式法则),dloss / dx = (dloss / doutput) * (doutput / dx) # dloss / doutput 就是输入的参数 grad_output # 因此只需求relu的导数,在乘以grad_output x, = ctx.saved_tensors grad_input = grad_output.clone() grad_input[x < 0] = 0 # 上诉计算的结果就是左式。即ReLU在反向传播中可以看做一个通道选择函数,所有未达到阈值(激活值<0)的单元的梯度都为0 return grad_input from torch.autograd import Variable input_ = Variable(torch.randn(1)) output_ = ReLU.apply(input_) # 这个relu对象,就是output_.creator,即这个relu对象将output与input连接起来,形成一个计算图 # print(relu) print(input_) print(output_)
from abc import ABC, abstractmethod class InventoryException( Exception): status = '' message = '' def __init__(self, statusORcopy, message =None): if message==None: self.status = statusORcopy.status self.message =statusORcopy.message else: self.status = statusORcopy self.message =message class storage(ABC): @abstractmethod def __init__(self): pass #return a dictionary of succesfully updated item and quantity @abstractmethod def update(self, dict): pass #return None @abstractmethod def remove(self, key): pass #return an integer @abstractmethod def get(self, key): pass #return the whole storage as a dictionary @abstractmethod def getAll(self): pass #return a dictionary of values and #quantity matching the boundary search @abstractmethod def boundSearch(self, upperBound_str, lowerBound_str): pass @staticmethod def boundToInt(bound_str): bound_int = None if isinstance(bound_str, int): bound_int = bound_str elif bound_str != None: try: bound_int = int(bound_str) except: raise InventoryException('400 Bad Request', 'Invalid Boundary input,\ must be whole numbers') return bound_int @abstractmethod def save(self): pass
#E: Un número #S: Averiguar la sumatoria de un número #R: Número debe ser entero positivo def sumatoria(ini,fin): if isinstance(ini,int) and isinstance(fin,int)and ini>=0 and fin>=0: if fin==0: return ini else: return ini+sumatoriaaux(ini,fin,0) else: return "Error" def sumatoriaaux(ini,fin,cont): if cont==fin: return 0 else: nuevo=inicio+1 return nuevo+sumatoriaaux(nuevo,fin,cont+1)
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 23:01:47 2020 @author: feng """ from mergesort import mergeSort def Count_Inversions(arr): while len(arr) > 2: l = Count_Inversions(arr[:len(arr)//2]) r = Count_Inversions(arr[len(arr)//2:]) m = Count_Split(arr[:len(arr)//2],arr[len(arr)//2:]) return l + r + m return bool(arr[1:] and arr[0] > arr[1]) def Count_Split(arr1,arr2): arr1 = mergeSort(arr1) arr2 = mergeSort(arr2) i = j = n = 0 while i < len(arr1) and j < len(arr2): if arr1[i] > arr2[j]: n += len(arr1) - i j += 1 else: i += 1 return n if __name__ == "__main__": with open("IntegerArray.txt","r") as file: l = [int(i.strip()) for i in file.readlines()] print ("Total inversions are {}".format( Count_Inversions(l)))
#!/usr/bin/python3 def main(): """ docstring Here's an explanation. """ # Comment out # Care about indent print("Hello, world!") x = 'text' print(x) y = 100 print(y) print(x,y) print(x + ' ', end='') print(y) z = 'mojiretu' print(x + z) print(x + ' ' + z) print(x + str(y)) # pass do nothing pass if __name__ == "__main__": main() #Comment out
people = {1:{'name':'john','age':'28','sex':'male'},2:{'name':'Marie','age':'24','sex':'female'}} for p_id,p_info in people.items(): print("\nperson ID:",p_id) for key in p_info: print(key + ':',p_info[key])
a = int(input("Enter a five digit number: ")) print(a) rev=0 while(a!=0): i=a%10; rev=(rev*10)+i a=a//10; print(rev)
class Contact: def __init__(self,name,number,email): self.name=name self.number=number self.email=email def __str__(self): return (self.name,self.number,self.email) def main(): my_contact=Contact('viral','6895412','[email protected]') print(my_contact.__str__()) main()
# Dictionary fruit = { 'orange': 'a sweet, ornage citrus fruit', 'apple': 'good for maing cider', 'lemon': 'a sour, yellow citrus fruit', 'grape': 'a small, sweet fruit growing in bushes' } # print(fruit) # print(fruit['lemon']) # # fruit['pear'] = 'an odd shaped apple' # print(fruit) # # fruit['pear'] = 'good with tequila' # print(fruit) # # del fruit['lemon'] #del fruit will delete the entire fruit dictionary. # print(fruit) #clear the dictionary #fruit.clear() # print(fruit) # validate a key before using it. # # while True: # dict_key = input('Enter a fruit: ') # if dict_key == 'quit': # break # if dict_key in fruit: # description = fruit.get(dict_key) # print(description) # else: # print("We don't have a {}".format(dict_key)) for snack in fruit: print(snack) # Default key value on get # while True: # dict_key = input('Enter a fruit: ') # if dict_key == 'quit': # break # description = fruit.get(dict_key, "We don't have a " + dict_key) # # print(description) # ordered_keys = list(fruit.keys()) # ordered_keys.sort() # for f in ordered_keys: # print(f + ' - ' + fruit[f]) # # for val in fruit.values(): # print(val) # fruit_keys = fruit.keys() # print(fruit_keys) # # fruit['tomato'] = 'not a slice' # print(fruit_keys) # print(fruit.items()) # # convert dict to a tuple of tuples # f_tuple = tuple(fruit.items()) # print(f_tuple) # # for snack in f_tuple: # item, description = snack # print(item + " is " + description) # # print(dict(f_tuple)) veg = { 'cabbage': 'every childs favorite', 'sprouts': 'mmmm, lovely', 'spinach': 'can i have some more fruit, please' } print(veg) veg.update(fruit) print(veg) print(fruit.update(veg)) print(fruit) nice_and_nasty = fruit.copy() nice_and_nasty.update(veg) print(nice_and_nasty) print(veg) print(fruit)
text = ("А роза упала на лапу Азора") text = text.split(' ') print("Enter your n. " "Or print 0 if you don't want to continue") n=1 while n!=0: n = int(input()) if n not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]: print("Change value") else: n = int(n) n= int(n) result = [] for word in text: if (len(word) == n): result.append(word.lower().replace("а","")) else: result.append(word) print(' '.join(result)) result.clear()
import sqlite3 conn = sqlite3.connect('database.db') print("database created") c = conn.cursor() def create(c): sql_create = """ DROP TABLE IF EXISTS users; CREATE TABLE users ( id integer unique primary key autoincrement, name text ); """ c.executescript(sql_create) print("Table Created") def insert(c): sql_insert = """INSERT INTO users (id, name) VALUES (1, 'ahmad'), (2, 'anika'), (3, 'rakin'), (4, 'Istiak'); """ c.executescript(sql_insert) print("Inserted") def select(c): c = conn.cursor() c.execute("SELECT * FROM users") rows = c.fetchall() for row in rows: print(row) print("showed database") def update(c, query): sql = ''' UPDATE users SET name = ? WHERE id = ?''' cur = conn.cursor() cur.execute(sql, query) def delete(c, query): sql = ''' DELETE FROM users where id=? ''' cur = conn.cursor() cur.execute(sql, (query,)) create(c) insert(c) select(c) update(c, ("istiak", 2)) select(c) #delete(c, 2) #select(c) conn.commit() conn.close()
class SymbolTable: def __init__(self): self.symbol_table = [] self.symbol_table.append(dict()) self.scope = 0 def __str__(self): return "{0}".format(self.symbol_table) def add_object(self, key, new_obj): self.symbol_table[self.scope] self.symbol_table[self.scope][key] = dict() self.symbol_table[self.scope][key]["val"] = new_obj self.symbol_table[self.scope][key]["type"] = type(new_obj) # print(self.symbol_table) def get_object_val(self, key): scope = self.scope while scope > 0 and not key in self.symbol_table[scope]: scope -= 1 if scope == -1: print("Undefined name '%s'" % key) return 0 try: return self.symbol_table[scope][key]["val"] except LookupError: print("Undefined name '%s'" % key) return 0 def increase_scope(self): self.scope += 1 self.symbol_table.append(dict()) # print("increase: {0}".format(self.symbol_table)) def decrease_scope(self): self.scope -= 1 self.symbol_table.pop() # print("decrease: {0}".format(self.symbol_table)) def delete_scoped_variables(self, scope): while self.scope > scope: self.decrease_scope() symbol_table = SymbolTable() class Node(object): def execute(self): raise NotImplementedError("Subclass must implement abstract method") class Suite(Node): """suite : stmt | stmt suite """ def __init__(self, stmt, suite=None): self.stmt = stmt self.suite = suite def execute(self): self.stmt.execute() if self.suite: self.suite.execute() class Stmt(Node): """stmt : exprStmt | declar | call SEMCOL | selectionStmt | iterationStmt | returnStmt SEMCOL | inputStmt SEMCOL | outputStmt SEMCOL | commentLine """ def __init__(self, stmt): self.stmt = stmt def execute(self): self.stmt.execute() class Declar(Node): """declar : varDeclar SEMCOL | funcDeclar | objDeclar """ def __init__(self, declar): self.declar = declar def execute(self): return self.declar.execute() class VarDeclar(Node): """varDeclar : NAME ASSIGN STRING | NAME ASSIGN exprStmt | NAME ASSIGN inputStmt """ def __init__(self, name, assign, val): self.name = name self.assign = assign self.val = val def execute(self): if str(self.val)[0] == "'" or str(self.val)[0] == '"': symbol_table.add_object(str(self.name), self.val) return self.val else: value = self.val.execute() symbol_table.add_object(str(self.name), value) return value class FuncDeclar(Node): """funcDeclar : DEF NAME LPARENT RPARENT COL suite | DEF NAME LPARENT params RPARENT COL suite """ pass class Params(Node): """params : paramsList """ pass class Params_list(Node): """paramsList : NAME COMA paramsList | NAME """ pass class ObjDeclaration(Node): """objDeclar : CLASS NAME COL suite """ pass class Call(Node): """call : NAME | NAME POINT call | NAME LPARENT RPARENT | NAME LPARENT params RPARENT | call POINT call """ def __init__(self, name=None): self.name = name def execute(self): if self.name: return symbol_table.get_object_val(str(self.name)) class ExprStmt(Node): """exprStmt : simpleExpr """ def __init__(self, simpleExpr): self.simpleExpr = simpleExpr def execute(self): return self.simpleExpr.execute() class SelectionStmt(Node): """selectionStmt : IF simpleExpr COL suite | IF simpleExpr COL suite ELSE COL suite """ def __init__(self, simpleExpr, suite1, suite2=None): self.simpleExpr = simpleExpr self.suite1 = suite1 self.suite2 = suite2 def execute(self): symbol_table.increase_scope() if self.simpleExpr.execute(): self.suite1.execute() elif self.suite2: self.suite2.execute() class IterationStmt(Node): """iterationStmt : WHILE simpleExpr COL suite """ def __init__(self, simpleExpr, suite): self.simpleExpr = simpleExpr self.suite = suite def execute(self): symbol_table.increase_scope() while self.simpleExpr.execute(): self.suite.execute() class Return(Node): """returnStmt : RETURN | RETURN simpleExpr """ pass class SimpleExpr(Node): """simpleExpr : simpleExpr OR andExpr | andExpr """ def __init__(self, simpleExpr=None, orToken=None, andExpr=None): self.simpleExpr = simpleExpr self.orToken = orToken self.andExpr = andExpr def execute(self): if self.orToken: return self.simpleExpr.execute() or self.andExpr.execute() else: return self.andExpr.execute() class AndExpr(Node): """andExpr : andExpr AND unaryRelExpr | unaryRelExpr """ def __init__(self, andExpr=None, andToken=None, unaryRelExpr=None): self.andExpr = andExpr self.andToken = andToken self.unaryRelExpr = unaryRelExpr def execute(self): if self.andToken: return self.andExpr.execute() and self.unaryRelExpr.execute() else: return self.unaryRelExpr.execute() class UnaryRelExpr(Node): """unaryRelExpr : NOT unaryRelExpr | relExpr """ def __init__(self, notToken=None, unaryRelExpr=None, relExpr=None): self.notToken = notToken self.unaryRelExpr = unaryRelExpr self.relExpr = relExpr def execute(self): if self.notToken: return not self.unaryRelExpr.execute() else: return self.relExpr.execute() class RelExpr(Node): """relExpr : sumExpr relop sumExpr | sumExpr """ def __init__(self, sumExpr1=None, relop=None, sumExpr2=None): self.sumExpr1 = sumExpr1 self.relop = relop self.sumExpr2 = sumExpr2 def execute(self): if self.relop: if self.relop.execute() == '<=': return self.sumExpr1.execute() <= self.sumExpr2.execute() elif self.relop.execute() == '<': return self.sumExpr1.execute() < self.sumExpr2.execute() elif self.relop.execute() == '>=': return self.sumExpr1.execute() >= self.sumExpr2.execute() elif self.relop.execute() == '>': return self.sumExpr1.execute() > self.sumExpr2.execute() elif self.relop.execute() == '==': return self.sumExpr1.execute() == self.sumExpr2.execute() elif self.relop.execute() == '!=': return self.sumExpr1.execute() != self.sumExpr2.execute() else: return self.sumExpr1.execute() class Relop(Node): """relop : LTE | LT | GTE | GT | EQ | NEQ """ def __init__(self, token): self.token = token def execute(self): return self.token class SumExpr(Node): """sumExpr : sumExpr sumop term | term """ def __init__(self, sumExpr=None, sumop=None, term=None): self.sumExpr = sumExpr self.sumop = sumop self.term = term def execute(self): if self.sumop: if self.sumop.execute() == '+': return self.sumExpr.execute() + self.term.execute() elif self.sumop.execute() == '-': return self.sumExpr.execute() - self.term.execute() else: return self.term.execute() class Sumop(Node): """sumop : SUM | SUBST """ def __init__(self, token): self.token = token def execute(self): return self.token class Term(Node): """term : term mulop opElement | opElement """ def __init__(self, term=None, mulop=None, opElement=None): self.term = term self.mulop = mulop self.opElement = opElement def execute(self): if self.mulop: if self.mulop.execute() == '*': return self.term.execute() * self.opElement.execute() elif self.mulop.execute() == '/': return self.term.execute() / self.opElement.execute() else: return self.opElement.execute() class OpElement(Node): """opElement : call | NUMBER """ def __init__(self, opElement): self.opElement = opElement def execute(self): if str(self.opElement).isdigit(): return self.opElement else: return self.opElement.execute() class Mulop(Node): """mulop : PROD | DIV """ def __init__(self, token): self.token = token def execute(self): return self.token class InputStmt(Node): """inputStmt : INPUT LPARENT RPARENT """ def __init__(self): self.type = 'INPUT' def execute(self): return input() class OutputStmt(Node): """outputStmt : PRINT LPARENT STRING RPARENT | PRINT LPARENT NAME RPARENT """ def __init__(self, printElement): self.printElement = printElement def execute(self): if (self.printElement[0] == '"' or self.printElement[0] == "'"): print(self.printElement) else: print(symbol_table.get_object_val(str(self.printElement))) class CommentLine(Node): """commentLine : LINE_COMMENT """ def __init__(self): self.type = 'COMMENT' def execute(self): return
"""Spectrum Effect for BlyncLight """ from typing import List, Tuple import math def Spectrum( steps: int = 64, frequency: Tuple[float, float, float] = None, phase: Tuple[int, int, int] = None, center: int = 128, width: int = 127, ) -> Tuple[float, float, float]: """Generator function that returns 'steps' (red, blue, green) tuples. steps: optional integer, default=64 frequency: optional 3-tuple for rbg frequency, default=(.3,.3,.3) phase: optional 3-tuple for rbg phase, default=(0,2,4) center: optional integer, default=128 width: optional integer, default=127 Returns (r, b, g) where each member is a value between 0 and 255. """ rf, bf, gf = frequency or (0.3, 0.3, 0.3) phase = phase or (0, 2, 4) for i in range(steps): r = int((math.sin(rf * i + phase[0]) * width) + center) b = int((math.sin(bf * i + phase[2]) * width) + center) g = int((math.sin(gf * i + phase[1]) * width) + center) yield (r, b, g)
# https://www.hackerrank.com/challenges/the-power-sum/problem def powerSum(X, N, candidate): candidateRes = pow(candidate, N) if candidateRes < X: return powerSum(X, N, candidate+1) + powerSum(X - candidateRes, N, candidate+1) if candidateRes==X: return 1 return 0 if __name__ == '__main__': print(powerSum(100,2,1))
# https://projecteuler.net/problem=12 from math import sqrt def countFactors(n): count = 0 for x in range(1, int(sqrt(n))): if n % x == 0: count += 1 if x*x != n: count += 1 return count def largestTriangleNumber(minFactorCount): t, lastInt, tCount = 1, 1, 1 while(tCount<minFactorCount): lastInt += 1 t = t + lastInt tCount = countFactors(t) return t if __name__ == '__main__': print(largestTriangleNumber(5),"\n") print(largestTriangleNumber(500),"\n")
# https://projecteuler.net/problem=9 def pyth(sum): for a in range(1,int(sum/(pow(2,0.5)+1))): b = (0.5*pow(sum,2) - sum*a)/(sum - a) if isInt(b): c = sum - a - b return a * b * c raise Exception("Doesn't exist") def isInt(n): return n==int(n) if __name__ == '__main__': print(pyth(1000), "\n")
#problem: Given an unsorted integer array, find the smallest missing positive integer. #shoudl run in O(n) #questions: #negatives? #what happens if theyre all the same number #no other data types? #what shoul it return in a list of all negatives #default return value #assumptions: def firstMissingPositive(nums): nums = sorted(nums) #sort numbers in ascending order smallest = 1 #the curretn smallest missing positive #loop through the list for x in range(len(nums)): #check if the current number is a positive if nums[x] > 0: #check to see if its smaller than or equal to the current smallest positive if nums[x]<=smallest: #skips duplicates if len(nums)>1 and nums[x] == nums[x-1] and x!=0: continue smallest+=1 #if so the increase the current missing positive return smallest print(firstMissingPositive([1,1])) #var table: #nums | [1,2,0], [0,1,2] #smallest | 1, 2 #x | 0, 1 #nums[x] | 0, 1
""" Choose any website(s) that you would like to scrape and write a script to get the html and save it to a file (<filename>.html). """ import requests as r wiki_korea_url = 'https://en.wikipedia.org/wiki/Korea' headers = {'user-agent': 'Jeong Kim ([email protected])'} response = r.get(wiki_korea_url, headers=headers) path = '/Users/jeong-ugim/Documents/BYU/\ 2018 Winter Semester/DIGHT 360/DIGHT 360/\ project_3/wiki_korea.html' file = open(path, "w", encoding='utf8') print(response.text) file.write(response.text) file.close()
from raspi_lora import LoRa, ModemConfig # This is our callback function that runs when a message is received def on_recv(payload): print("From:", payload.header_from) print("Received:", payload.message) print("RSSI: {}; SNR: {}".format(payload.rssi, payload.snr)) # Use chip select 0. GPIO pin 17 will be used for interrupts # The address of this device will be set to 2 lora = LoRa(1, 19, 2, modem_config=ModemConfig.Bw125Cr45Sf128, tx_power=123, acks=True) lora.on_recv = on_recv lora.set_mode_rx() # Send a message to a recipient device with address 10 # Retry sending the message twice if we don't get an acknowledgment from the recipient message = "Hello there!" status = lora.send_to_wait(message, 10, retries=2) if status is True: print("Message sent!") else: print("No acknowledgment from recipient") # And remember to call this as your program exits... lora.close()
class Function_Calc: def modular(self, value_1, value_2): # divisible function if value_2 == 0: return False elif value_1 % value_2 == 0: # if the value_1 can be divided by the value_2 with no remainder, then return True return True else: return False def triangle(self, height, base): # area of a triangle function return (height * base) / 2 def percentage(self, value_1, value_2): # area of a triangle function return (value_1 / value_2) * 100 def inches(self, value_1): return value_1 * 2.54 # multiplies the value by the length of an inch in centimeters
# Выводим на экран букву, которая находится в середине этой строки. # Если эта центральная буква равна первой букве в строке, то создать # и вывести часть строки между первым и последним символами исходной строки str_line = input('Введите строку: ') middle_str = int(len(str_line) / 2) center_letter = str_line[middle_str] print(center_letter) if center_letter == str_line[0]: print(str_line[::])