text
stringlengths
37
1.41M
from operator import sub, add, mul operators = { "-": sub, "+": add, "*": mul } class DynamicList: DEFAULT_INITIAL_CAPACITY = 10 MINIMAL_CAPACITY = 10 GROW_COEEFICIENT = 2 def __init__(self, initialCapacity = DEFAULT_INITIAL_CAPACITY): self.capacity = max(initialCapacity, self.MINIMAL_CAPACITY) self.storage = [None] * initialCapacity self.size = 0 def append(self, element): if self.size == self.capacity: self.__ensureCapacity(True) self.storage[self.size] = element self.size += 1 def pop(self): if self.size == 0: return None popped = self.storage[self.size - 1] self.size -= 1 if self.size <= self.capacity / 4: self.__ensureCapacity(False) return popped def peek(self): if self.size == 0: return None return self.storage[self.size - 1] def __ensureCapacity(self, isGrow): newCapacity = self.capacity * self.GROW_COEEFICIENT if isGrow \ else max(self.capacity // self.GROW_COEEFICIENT, self.MINIMAL_CAPACITY) self.capacity = newCapacity extendedList = [None] * self.capacity for index in range(self.size): extendedList[index] = self.storage[index] self.storage = extendedList class ProblemSolver: def solve(self): stack = DynamicList() for x in input().split(): if x in ["-", "+", "*"]: last = stack.pop() prev = stack.pop() stack.append(operators[x](prev, last)) else: stack.append(int(x)) print(stack.pop()) ProblemSolver().solve()
def find_max_substring_occurrence(input_string): if len(input_string) == 0: return 0 else: repeatLengthCandidate = 1 while repeatLengthCandidate < len(input_string): if len(input_string) % repeatLengthCandidate == 0: k = len(input_string) // repeatLengthCandidate if input_string[0:repeatLengthCandidate] * k == input_string: return k repeatLengthCandidate += 1 return 1
import re def sanitise_string(string: str) -> str: return re.sub(r"\_|[^\w']+", ',', string.lower()).strip(',') def sanitise_words(words: list) -> list: results = [] for w in words: word = re.sub(r"^['\']|['\']$", "", w) results.append(word) return results def count_words(sentence: str) -> dict: sanitised_string = sanitise_string(sentence) sanitised_words = sanitise_words(sanitised_string.split(',')) results = {} for w in sanitised_words: results.update([(w, sanitised_words.count(w))]) return results
def hello_again(**kwargs): return "I am {}, and am I'm {}".format(kwargs['name'], kwargs ['age']) print hello_again(name='Joe', age=20) print hello_again(age=20, name='Jane') other_people = [ {'name': 'Joe', 'age':98}, {'name': 'Jane', 'age':60}, {'name': 'Pauline', 'age':26} ] Pauline = {'name': 'Joe', 'age':98} print hello_again(**Pauline) for person in other_people: hello_again(**person)
def funky(a, b): if isinstance(a, (int,list,float)) and isinstance (b, (int,list,float)): return a + b elif isinstance(a, dict) and isinstance (b, dict): z = dict(a.items() + b.items()) return z elif type(a) ==str or type(b) ==str: return str(a) + str(b) else: return "NO CAN DO" print('h',7) print funky('g', 'h') print funky(5, 8) print funky(2.4, 2.3) print funky({1: ""}, {0: "g"}) print funky([2,3,4],[4,5,6])
def data_type(item): if type(item) == str: return(len(item)) elif type(item) == bool: return item elif type(item)== int: if item < 100: return "less than 100" elif item > 100: return "more than 100" else: return "equal to 100" elif type(item) == list: if len(item) < 3: return None return item[2] elif item == None: return 'no value'
""" neural nets will be masd up of layers. Each layer needs to pass its input forward and propagate gradients backward. for example, a neural net might look like: inputs -> Linear -> Tanh -> Linear -> output """ import os, sys from mynet import tensor sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from typing import Dict, Callable import numpy as np from mynet.tensor import Tensor class Layer: def __init__(self) -> None: self.params: Dict[str, Tensor] = {} self.grads: Dict[str, Tensor] = {} def forward(self, inputs: Tensor) -> Tensor: """ Produce the outputs corresponding to these inputs. """ raise NotImplementedError def backward(self, grad: Tensor) -> Tensor: """ Backpropagate this gradient through the layer. """ raise NotImplementedError class Linear(Layer): """ compute output = inputs @ w + b """ def __init__(self, input_size: int, output_size: int) -> None: # inputs will be (batch_size, input_size) # outputs will be (batch_size, output_size) super().__init__() self.params['w'] = np.random.randn(input_size, output_size) self.params['b'] = np.random.randn(output_size) def forward(self, inputs: Tensor) -> Tensor: """ outputs = inputs @ w + b """ self.inputs = inputs return inputs @ self.params['w'] + self.params['b'] def backward(self, grad: Tensor) -> Tensor: """ eltwise-MUL if y = f(x) and x = t * w + b then: dy/dt = f'(x) * w dy/dw = f'(x) * t dy/db = f'(x) Matmul if y = f(x) and x = t @ w + b then: dy/dt = f'(x) @ w.T dy/dw = t.T @ f'(x) dy/db = f'(x) """ self.grads['b'] = np.sum(grad, axis=0) # axis0: batch self.grads['w'] = self.inputs.T @ grad return grad @ self.params['w'].T ################################################################ F = Callable[[Tensor], Tensor] class Activation(Layer): """ An activation layer just applies a function elementwise to its inputs. """ def __init__(self, f: F, f_prime: F) -> None: super().__init__() self.f = f self.f_prime = f_prime def forward(self, inputs: Tensor) -> Tensor: self.inputs = inputs return self.f(inputs) def backward(self, grad:Tensor) -> Tensor: """ if y = f(x) and x = g(t) then: dy/dz = f'(x) * g'(t) """ return self.f_prime(self.inputs) * grad def tanh(x: Tensor) -> tensor: return np.tanh(x) def tanh_prime(x: Tensor) -> Tensor: y = tanh(x) return 1 - y**2 class Tanh(Activation): def __init__(self): super().__init__(tanh, tanh_prime)
import time def sumOfN(n): startTime = time.time() theSum = 0 for i in range(1, n+1 ): theSum = theSum + i endTime = time.time() return theSum, endTime - startTime print(time.time()) print(sumOfN(10)) for i in range(5): print("sum is %d required %10.5f seconds" % sumOfN(10000)) for i in range(5): print("sum is %d required %10.3f seconds" % sumOfN(1000000))
import time def sumOfN3(n): startTime = time.time() theSum = n * (n+1) / 2 endTime = time.time() return theSum, endTime - startTime print("the sum is %d reuqired %10.10f seconds" % sumOfN3(10000)) print("the sum is %d reuqired %10.10f seconds" % sumOfN3(1000000)) print("the sum is %d reuqired %10.10f seconds" % sumOfN3(100000000))
def print_max(x, y): """ Print the maximum of two numbers. 打印两个数值中的最大数 the two values must be integer. 这两个数都应该是整数 """ # 如果可能,将其转换至整数类型 x = int(x) y = int(y) if x > y: print(x, ' is the maximum') elif x < y: print(y, ' is the maximum') else: print('The two numbers are equal') print_max(3, 5) print(print_max.__doc__) help(print_max) __version__ = '123' a = 5 print(dir()) del a print(dir()) print(__file__)
import random import time a = ["stone", "paper", "scissor"] print("lets start the game \nThere will be 3 rounds \n") time.sleep(1) print("\t 3") time.sleep(1) print("\t 2") time.sleep(1) print("\t 1") time.sleep(0.5) print("\n\tlets go !!!!\n") # print(random.choice(a)) PlayerPoints = 0 CompPoints = 0 i = 1 while i <= 3: player = input("enter your move : ").strip() r = random.choice(a) print("computer : {}".format(r)) if player.lower() == r: print("tie") ###################################################################### elif player.lower() == "stone" and r == "scissor": PlayerPoints += 1 print("You win !!!") elif player.lower() == "stone" and r == "paper": CompPoints += 1 print("You lost") ####################################################################### elif player.lower() == "paper" and r == "stone": PlayerPoints += 1 print("You win !!!") elif player.lower() == "paper" and r == "scissor": CompPoints += 1 print("You lost !!!") ####################################################################### elif player.lower() == "scissor" and r == "stone": # CompPoints += 1 print("You lost !!!") CompPoints += 1 elif player.lower() == "scissor" and r == "paper": # PlayerPoints += 1 print("You win !!!") PlayerPoints += 1 i += 1 time.sleep(1) print("\nYour Points : {} \nComputer Points : {}".format(PlayerPoints, CompPoints)) if PlayerPoints == CompPoints: print("Its a tie") elif PlayerPoints > CompPoints: print("Congrats, You win this game !!!!!!!") elif PlayerPoints < CompPoints: print("You lost this game . Better Luck next time .")
#!/usr/bin/env python3 ''' booksdatasource.py Jeff Ondich, 18 September 2018 For use in some assignments at the beginning of Carleton's CS 257 Software Design class, Fall 2018. ''' import sys, csv, operator class BooksDataSource: ''' A BooksDataSource object provides access to data about books and authors. The particular form in which the books and authors are stored will depend on the context (i.e. on the particular assignment you're working on at the time). Most of this class's methods return Python lists, dictionaries, or strings representing books, authors, and related information. An author is represented as a dictionary with the keys 'id', 'last_name', 'first_name', 'birth_year', and 'death_year'. For example, Jane Austen would be represented like this (assuming her database-internal ID number is 72): {'id': 72, 'last_name': 'Austen', 'first_name': 'Jane', 'birth_year': 1775, 'death_year': 1817} For a living author, the death_year is represented in the author's Python dictionary as None. {'id': 77, 'last_name': 'Murakami', 'first_name': 'Haruki', 'birth_year': 1949, 'death_year': None} Note that this is a simple-minded representation of a person in several ways. For example, how do you represent the birth year of Sophocles? What is the last name of Gabriel García Márquez? Should we refer to the author of "Tom Sawyer" as Samuel Clemens or Mark Twain? Are Voltaire and Molière first names or last names? etc. A book is represented as a dictionary with the keys 'id', 'title', and 'publication_year'. For example, "Pride and Prejudice" (assuming an ID of 132) would look like this: {'id': 193, 'title': 'A Wild Sheep Chase', 'publication_year': 1982} ''' def __init__(self, books_filename, authors_filename, books_authors_link_filename): ''' Initializes this data source from the three specified CSV files, whose CSV fields are: books: ID,title,publication-year e.g. 6,Good Omens,1990 41,Middlemarch,1871 authors: ID,last-name,first-name,birth-year,death-year e.g. 5,Gaiman,Neil,1960,NULL 6,Pratchett,Terry,1948,2015 22,Eliot,George,1819,1880 link between books and authors: book_id,author_id e.g. 41,22 6,5 6,6 [that is, book 41 was written by author 22, while book 6 was written by both author 5 and author 6] Note that NULL is used to represent a non-existent (or rather, future and unknown) year in the cases of living authors. NOTE TO STUDENTS: I have not specified how you will store the books/authors data in a BooksDataSource object. That will be up to you, in Phase 3. ''' self.books_list = self.create_books_list(books_filename) self.authors_list = self.create_authors_list(authors_filename) self.books_authors = self.create_link_list(books_authors_link_filename) def create_books_list(self, books_filename): books_list = [] books_csv = csv.reader(open(books_filename)) for book in books_csv: book_dictionary = {'id': int(book[0]), 'title':book[1], 'publication-year': int(book[2])} books_list.append(book_dictionary) return books_list def create_authors_list(self, authors_filename): authors_list = [] authors_csv = csv.reader(open(authors_filename)) for author in authors_csv: if author[4] == "NULL": author_dictionary = {'id': int(author[0]), 'last-name': author[1], 'first-name': author[2], 'birth-year': int(author[3]), 'death-year': None} else: author_dictionary = {'id': int(author[0]), 'last-name': author[1], 'first-name': author[2], 'birth-year': int(author[3]), 'death-year': int(author[4])} authors_list.append(author_dictionary) return authors_list def create_link_list(self, books_authors_link_filename): books_authors = [] link_csv = csv.reader(open(books_authors_link_filename)) for link in link_csv: link_dictionary = {'book_id': int(link[0]), 'author_id': int(link[1])} books_authors.append(link_dictionary) return books_authors def book(self, book_id): ''' Returns the book with the specified ID. (See the BooksDataSource comment for a description of how a book is represented.) Raises ValueError if book_id is not a valid book ID. ''' if book_id != None and type(book_id) == int and book_id >= 0: for book in self.books_list: if book['id'] == book_id: return book else: raise ValueError exit() def books(self, *, author_id=None, search_text=None, start_year=None, end_year=None, sort_by='title'): ''' Returns a list of all the books in this data source matching all of the specified non-None criteria. author_id - only returns books by the specified author search_text - only returns books whose titles contain (case-insensitively) the search text start_year - only returns books published during or after this year end_year - only returns books published during or before this year Note that parameters with value None do not affect the list of books returned. Thus, for example, calling books() with no parameters will return JSON for a list of all the books in the data source. The list of books is sorted in an order depending on the sort_by parameter: 'year' -- sorts by publication_year, breaking ties with (case-insenstive) title default -- sorts by (case-insensitive) title, breaking ties with publication_year See the BooksDataSource comment for a description of how a book is represented. QUESTION: Should Python interfaces specify TypeError? Raises TypeError if author_id, start_year, or end_year is non-None but not an integer. Raises TypeError if search_text or sort_by is non-None, but not a string. QUESTION: How about ValueError? And if so, for which parameters? Raises ValueError if author_id is non-None but is not a valid author ID. ''' result_list = [] if author_id != None: result_list = self.books_with_author_id(author_id) if search_text != None: if len(result_list) == 0: result_list = self.books_with_search_text(search_text.lower(), self.books_list) else: result_list = self.books_with_search_text(search_text.lower(), result_list) if start_year != None: if len(result_list) == 0: result_list = self.books_with_start_year(start_year, self.books_list) else: result_list = self.books_with_start_year(start_year, result_list) if end_year != None: if len(result_list) == 0: result_list = self.books_with_end_year(end_year, self.books_list) else: result_list = self.books_with_end_year(end_year, result_list) if sort_by == 'year': result_list.sort(key = self._sort_first_year_then_title) else: result_list.sort(key = self._sort_first_title_then_year) return result_list def _sort_first_year_then_title(self, book): return (book['publication-year'], book['title']) def _sort_first_title_then_year(self, book): return (book['title'], book['publication-year']) def books_with_start_year(self, start_year, books_list): if type(start_year) != int: raise ValueError exit() else: book_list = [] for book in books_list: if book['publication-year'] - start_year >= 0: book_list.append(book) return book_list def books_with_end_year(self, end_year, books_list): if type(end_year) != int: raise ValueError exit() else: book_list = [] for book in books_list: if book['publication-year'] - end_year <= 0: book_list.append(book) return book_list def books_with_search_text(self, search_text, books_list): if type(search_text) == str: book_list = [] for book in books_list: if search_text.lower() in book.get('title').lower(): book_list.append(book) return book_list else: raise ValueError exit() def books_with_author_id(self, author_id): book_id_list = [] book_list = [] if type(author_id) == int and author_id >= 0: for link_dict in self.books_authors: if author_id == link_dict['author_id']: book_id_list.append(link_dict['book_id']) for book_id in book_id_list: book_list.append(self.book(book_id)) return book_list else: raise ValueError exit() def author(self, author_id): ''' Returns the author with the specified ID. (See the BooksDataSource comment for a description of how an author is represented.) Raises ValueError if author_id is not a valid author ID. ''' answer = [] for author in self.authors_list: if author['id'] == author_id: answer = author return author def authors(self, *, book_id=None, search_text=None, start_year=None, end_year=None, sort_by='birth_year'): ''' Returns a list of all the authors in this data source matching all of the specified non-None criteria. book_id - only returns authors of the specified book search_text - only returns authors whose first or last names contain (case-insensitively) the search text start_year - only returns authors who were alive during or after the specified year end_year - only returns authors who were alive during or before the specified year Note that parameters with value None do not affect the list of authors returned. Thus, for example, calling authors() with no parameters will return JSON for a list of all the authors in the data source. The list of authors is sorted in an order depending on the sort_by parameter: 'birth_year' - sorts by birth_year, breaking ties with (case-insenstive) last_name, then (case-insensitive) first_name any other value - sorts by (case-insensitive) last_name, breaking ties with (case-insensitive) first_name, then birth_year See the BooksDataSource comment for a description of how an author is represented. ''' result_list = [] if book_id != None: result_list = self.authors_with_book_id(book_id) if search_text != None: if len(result_list) == 0: result_list = self.authors_with_search_text(search_text.lower(), self.authors_list) else: result_list = self.authors_with_search_text(search_text.lower(), result_list) if start_year != None: if len(result_list) == 0: result_list = self.authors_with_start_year(start_year, self.authors_list) else: result_list = self.authors_with_start_year(start_year, result_list) if end_year != None: if len(result_list) == 0: result_list = self.authors_with_end_year(end_year, self.authors_list) else: result_list = self.authors_with_end_year(end_year, result_list) if sort_by == 'birth_year': result_list.sort(key = self._sort_by_birth_year) else: result_list.sort(key = self._sort_by_other) return result_list # TODO: IMPLEMENT CHECKS FOR TYPES def authors_with_book_id(self, book_id): if type(book_id) != int: raise ValueError exit() author_list = [] final_list = [] for pair in self.books_authors: if (pair['book_id'] == book_id) and (pair['author_id'] not in author_list): author_list.append(pair['author_id']) for author in author_list: final_list.append(self.authors_list[author]) return(final_list) def authors_with_search_text(self, search_text, result_list=None): author_list = [] for author in result_list: if author in author_list: pass elif search_text in author['last-name']: author_list.append(author) elif search_text in author['first-name']: author_list.append(author) return(author_list) def authors_with_start_year(self, start_year, result_list=None): if type(start_year) != int: raise ValueError exit() author_list = [] for author in result_list: if author in author_list: pass elif author['death-year'] is None: author_list.append(author) elif author['death-year'] >= start_year: author_list.append(author) return(author_list) def authors_with_end_year(self, end_year, result_list=None): if type(end_year) != int: raise ValueError exit() author_list = [] for author in result_list: if author in author_list: pass elif author['birth-year'] <= end_year: author_list.append(author) return(author_list) def _sort_by_birth_year(self, author): return (author['birth-year'], author['last-name'], author['first-name']) def _sort_by_other(self, author): return (author['last-name'], author['first-name'], author['birth-year']) # Note for my students: The following two methods provide no new functionality beyond # what the books(...) and authors(...) methods already provide. But they do represent a # category of methods known as "convenience methods". That is, they provide very simple # interfaces for a couple very common operations. # # A question for you: do you think it's worth creating and then maintaining these # particular convenience methods? Is books_for_author(17) better than books(author_id=17)? def books_for_author(self, author_id): ''' Returns a list of all the books written by the author with the specified author ID. See the BooksDataSource comment for a description of how an book is represented. ''' return self.books(author_id=author_id) def authors_for_book(self, book_id): ''' Returns a list of all the authors of the book with the specified book ID. See the BooksDataSource comment for a description of how an author is represented. ''' return self.authors(book_id=book_id) def main(): test = BooksDataSource("books.csv", "authors.csv", "books_authors.csv") print(test.authors(start_year=2018, end_year=2018)) if __name__ == '__main__': main()
''' var1 =0 #equality & inequality operators print(var1 != 0) var1 =1 print(var1 != 0) x = int(input("Enter the number you want to enter : ")) print(x<=100) # read two numbers IF ELSE STATEMENT .............. number1 = int(input("Enter the first number: ")) number2 = int(input("Enter the second number: ")) # choose the larger number if number1 > number2: larger_number = number1 else: larger_number = number2 # print the result print("The larger number is:", larger_number) x = int(input("ENter value in x")) IF ELIF ELSE STMT.................. y = int(input("ENter value in y")) z = int(input("ENter value in z")) if(x>y): print(x," is greater no.") elif(y>z): print(y," is greater no.") elif(x>z): print(x," is greater no.") else: print(z," is greater no.") x =input("Enter a plant name") if(x == "Spathiphyllum"): print(x+"is the best pllant ever!") else: print(x+"! Not pelargonium!") n1= int(input("ENter the firt number")) WHILE LOOP EG............. n2= int(input("ENter the last number")) while(n1<=n2): if(n1%2==0): print("Even = ",n1) else: print("Odd = ",n1) n1+=1 print("Thank You 💛️") import time FOR LOOP ....................... # Write a for loop that counts to five. # Body of the loop - print the loop iteration number and the word "Mississippi". # Body of the loop - use: time.sleep(1) # Write a print function with the final message. i=1 for i in range(6): print(i,"Mississipi \n") i+=1 print("Ready or not, here I come") # break - example print("The break instruction:") BREAK STMT....................................... for i in range(1, 6): if i == 3: break print("Inside the loop.", i) print("Outside the loop.") # continue - example print("\nThe continue instruction:") CONTINUE STMT............................. for i in range(1, 6): if i == 3: continue print("Inside the loop.", i) print("Outside the loop.") blocks = int(input("Enter number of blocks: ")) TO MEASURE HEIGHT OF THE BLOCK ............. for i in range(blocks + 1): for j in range(blocks + 1): height = j / 2 if height % 2 == 0: height = height / 2 print(f"The height of the pyramid: {height}") ''' x =int(input("Enter no")) while(x!=17): if(x%2==0): x = x + 2 print(x) else: x = 3 * x + 1 print(x) x+=1
def strangeListFunction(n): strangeList = [] for i in range(0, n): strangeList.insert(0, i) return strangeList print(strangeListFunction(5)) # O/p: [4, 3, 2, 1, 0]
nombre_archivo = raw_input("nombre del archivo? ") if nombre_archivo != "": archivo = open (nombre_archivo, "r") else: exit () total_linea = 0 total_char = 0 for linea in archivo: total_linea +=1 for caracter in linea: total_char += 1 print "total lineas", total_linea print "total caracteres", total_char
# -*- coding: utf-8 -*- """ Programming template for CS-E5740 Complex Networks problem 3.3 (PageRank) Written by Onerva Korhonen Created on Tue Sep 8 10:25:49 2015 @author: aokorhon """ from random import random import numpy as np import matplotlib.pyplot as plt import networkx as nx import timeit def page_rank(network: nx.DiGraph, d: float, n_steps: int) -> dict: """ Returns the PageRank value, calculated using a random walker, of each node in the network. The random walker teleports to a random node with probability 1-d and with probability d picks one of the neighbors of the current node. Parameters ----------- network : a networkx graph object d : damping factor of the simulation n_steps : number of steps of the random walker Returns -------- page_rank: dictionary of node PageRank values (fraction of time spent in each node) """ assert n_steps > 0 # Initialize PageRank of of each node to 0 pr, nodes = {}, network.nodes() for node in nodes: pr[node] = 0 # Pick a random starting point for the random walker curr_node = np.random.choice(nodes) # Random walker steps for i in range(n_steps): # Increase the PageRank of current node by 1 pr[curr_node] += 1 sucessors = network.successors(curr_node) # Pick the next node either randomly or from the neighbors if len(sucessors) == 0 or random() > d: curr_node = np.random.choice(nodes) else: curr_node = np.random.choice(sucessors) # Normalize PageRank by n_steps for (key, item) in pr.items(): pr[key] /= n_steps return pr def pagerank_poweriter(g: nx.DiGraph, d: float, iterations: int) -> dict: """ Uses the power iteration method to calculate PageRank value for each node in the network. Parameters ----------- g : a networkx graph object d : damping factor of the simulation n_iterations : number of iterations to perform Returns -------- pageRank : dict where keys are nodes and values are PageRank values :param iterations: """ # Create a PageRank dictionary and initialize the PageRank of each node to 1/n. pr, n = {}, len(g) for node in g: pr[node] = 1 / n nodes = g.nodes() for i in range(iterations): next_pr = {} for key in nodes: # Update each node's PageRank to (1-d)*1/n + d*sum(x_j(t-1)/k_j^out). next_pr[key] = ((1 - d) / n) + d * sum((pr[x] / g.out_degree(x)) for x in g.predecessors_iter(key)) pr = next_pr return pr def add_colorbar(cvalues, cmap='OrRd', cb_ax=None): """ Add a colorbar to the axes. Parameters ---------- cvalues : 1D array of floats """ import matplotlib as mpl eps = np.maximum(0.0000000001, np.min(cvalues) / 1000.) vmin = np.min(cvalues) - eps vmax = np.max(cvalues) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) scm = mpl.cm.ScalarMappable(norm, cmap) scm.set_array(cvalues) if cb_ax is None: plt.colorbar(scm) else: cb = mpl.colorbar.ColorbarBase(cb_ax, cmap=cmap, norm=norm, orientation='vertical') def visualize_network(network, node_positions, figure_path, cmap='OrRd', node_size=3000, node_colors=None, w_labels=True, title=""): """ Visualizes the given network using networkx.draw and saves it to the given path. Parameters ---------- network : a networkx graph object node_positions : a list positions of nodes, obtained by e.g. networkx.graphviz_layout figure_path : string cmap : colormap node_size : int node_colors : a list of node colors w_labels : should node labels be drawn or not, boolean title: title of the figure, string """ fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(111) if node_colors: pos = nx.spring_layout(network) nx.draw(network, pos, cmap=cmap, node_color=node_colors, with_labels=w_labels, node_size=node_size) add_colorbar(node_colors) ax.set_title(title) plt.tight_layout() else: pos = nx.spring_layout(network) nx.draw(network, pos, cmap=cmap, with_labels=True, node_size=node_size) ax.set_title(title) plt.tight_layout() if figure_path is not '': plt.savefig(figure_path, format='pdf', bbox_inches='tight') def investigate_d(network: nx.DiGraph, ds, colors, n_steps, d_figure_path): """ Calculates PageRank at different values of the damping factor d and visualizes and saves results for interpretation Parameters ---------- network : a NetworkX graph object ds : a list of d values colors : visualization color for PageRank at each d, must have same length as ds n_steps : int; number of steps taken in random walker algorithm d_figure_path : string """ fig = plt.figure(1000) ax = fig.add_subplot(111) # Hint: use zip to loop over ds and colors at once for (d, color) in zip(ds, colors): pageRank_pi = page_rank(network, d, n_steps) nodes = sorted(network.nodes()) node_colors = [pageRank_pi[node] for node in nodes] ax.plot(nodes, node_colors, color, label="$d=$" + str(d)) ax.set_xlabel(r'Node index') ax.set_ylabel(r'PageRank') ax.set_title(r'PageRank with different damping factors') ax.legend(loc=0) plt.tight_layout() plt.savefig(d_figure_path, format='pdf', bbox_inches='tight') def main(): network = nx.DiGraph(nx.read_edgelist('pagerank_network.edg', create_using=nx.DiGraph())) # Visualization of the model network network (note that spring_layout # is intended to be used with undirected networks): node_positions = nx.layout.spring_layout(network.to_undirected()) uncolored_figure_path = 'graphs/page_rank/uncolored_graph.pdf' visualize_network(network=network, node_positions=node_positions, figure_path=uncolored_figure_path, title='network') nodes = network.nodes() n_nodes = len(nodes) # PageRank with self-written function n_steps = 10000 d = .85 pageRank_rw = page_rank(network, d, n_steps) # # Visualization of PageRank on network: node_colors = [pageRank_rw[node] for node in nodes] colored_figure_path = 'graphs/page_rank/colored_graph.pdf' visualize_network(network=network, node_positions=node_positions, figure_path=colored_figure_path, node_colors=node_colors, title='PageRank random walker') # PageRank with networkx: pageRank_nx = nx.pagerank(network) # Comparison of results from own function and nx.pagerank match: compare_pr(n_nodes, nodes, pageRank_nx, pageRank_rw) # PageRank with power iteration n_iterations = 10 pageRank_pi = pagerank_poweriter(network, d, n_iterations) # Visualization of PageRank by power iteration on the network power_iteration_path = 'graphs/page_rank/power_iterations.pdf' node_colors = [pageRank_pi[node] for node in nodes] visualize_network(network, node_positions, power_iteration_path, node_colors=node_colors, title='PageRank power iteration') compare_pr(n_nodes, nodes, pageRank_nx, pageRank_pi) # Investigating the running time of the power iteration fuction running_time(network) def running_time(network: nx.DiGraph): num_tests = 3 n_nodes = 10 ** 4 k5net = nx.directed_configuration_model(n_nodes * [5], n_nodes * [5], create_using=nx.DiGraph()) # Print results: how many seconds were taken for the test network of 10**4 nodes, # how many hours would a 26*10**6 nodes network take? result = timeit.timeit(lambda: pagerank_poweriter(k5net, 0.85, 10), number=num_tests) print(result) # Investigating the running time of the random walker function n_steps = 1000 * n_nodes # each node gets visited on average 1000 times # Print results: how many seconds were taken for the test network of 10**4 nodes, # how many hours would a 26*10**6 nodes network take? result = timeit.timeit(lambda: page_rank(k5net, 0.85, n_steps), number=num_tests) print(result) # Investigating effects of d: ds = np.arange(0, 1.2, 0.2) colors = ['b', 'r', 'g', 'm', 'k', 'c'] d_figure_path = 'graphs/page_rank/d_effect.pdf' investigate_d(network, ds, colors, n_steps, d_figure_path) # Wikipedia network: network_wp = nx.DiGraph(nx.read_edgelist("wikipedia_network.edg", create_using=nx.DiGraph())) # nx.read_edgelist. page_rank_wp = nx.pagerank(network_wp) indegree_wp = network_wp.in_degree() outdegree_wp = network_wp.out_degree() if page_rank_wp is not {}: highest_pr = sorted(page_rank_wp, key=lambda k: page_rank_wp[k])[::-1][0:5] print('---Highest PageRank:---') for p in highest_pr: print(page_rank_wp[p], ":", p) if indegree_wp is not {}: highest_id = sorted(indegree_wp, key=lambda k: indegree_wp[k])[::-1][0:5] print('---Highest In-degree:---') for p in highest_id: print(indegree_wp[p], ":", p) if outdegree_wp is not {}: highest_od = sorted(outdegree_wp, key=lambda k: outdegree_wp[k])[::-1][0:5] print('---Highest Out-degree:---') for p in highest_od: print(outdegree_wp[p], ":", p) def compare_pr(n_nodes, nodes, pageRank_nx, pageRank_rw): pageRank_rw_array = np.zeros(n_nodes) pageRank_nx_array = np.zeros(n_nodes) for node in nodes: pageRank_rw_array[int(node)] = pageRank_rw[node] # ordering dictionary values to node order pageRank_nx_array[int(node)] = pageRank_nx[node] fig = plt.figure() ax = fig.add_subplot(111) check_figure_path = 'graphs/page_rank/check_sanity.pdf' # check visualization ax.plot(range(0, n_nodes), pageRank_rw_array, 'k+', label=r'power iteration') ax.plot(range(0, n_nodes), pageRank_nx_array, 'rx', label=r'networkx') ax.set_xlabel(r'Node index') ax.set_ylabel(r'PageRank') ax.set_title(r'PageRank with different methods') ax.legend(loc=0) plt.tight_layout() plt.savefig(check_figure_path, format='pdf', bbox_inches='tight') if __name__ == '__main__': main()
#!/usr/bin/env python import psycopg2 def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" try: return psycopg2.connect("dbname=news") except: print("Cannot conncet to DATABASE") def popart(): db = connect() cu = db.cursor() # Part 1 query_one = """SELECT viewsofarticlesmain.title, viewsofarticlesmain.views FROM viewsofarticlesmain ORDER BY viewsofarticlesmain.views DESC LIMIT 3; """ cu.execute(query_one) results_one = cu.fetchall() print "The most popular three articles of all time are: " for (t, v) in results_one: print("% s - %s views") % (t, v) # Part 2 query_two = """SELECT viewsofarticlesmain.name, SUM(viewsofarticlesmain. views) AS page_views FROM viewsofarticlesmain GROUP BY viewsofarticlesmain.name ORDER BY page_views DESC;""" cu.execute(query_two) results_two = cu.fetchall() print "\nThe most popular article authors of all time are: " for (n, pv) in results_two: print("%s - %s views") % (n, pv) # Part 3 query_three = """SELECT * FROM errorpercent WHERE errorpercent.percentage_error > 1 ORDER BY errorpercent.percentage_error DESC;""" cu.execute(query_three) results_three = cu.fetchall() print """\nDays On which there was more than 1% of errors: """ for (d, pe) in results_three: print("%s - %s%% errors") % (d, pe) db.close() if __name__ == "__main__": connect() popart()
import random when = ['10 years ago' , 'Last week' , 'Yesterday' , 'Two weeks a go'] who = ['a man' , 'a dog' , 'a girl', 'a raccoon' , 'a panda' ] name = ['Stevie', 'Rafa' , 'Jane', 'Abdul', 'Raj', 'Jane','Rhonda'] residence = ['Portland' , 'Toronto' , 'NYC' , 'Berlin'] went = ['Paris' , 'Delhi' , 'Sydney', 'Louisiana'] happened = ['ate pie' , 'went to a party' , 'went hiking', 'went shopping'] print(random.choice(when) + ', ' + random.choice(who) + ' that lived in ' + random.choice(residence) + ', went to ' + random.choice(went)+' and '+random.choice(happened))
import random roll_dice = input("Do you want to roll the dice? ") while roll_dice.lower() == 'yes' or roll_dice.lower() == 'y': n1 = random.randint(1,6) n2 = random.randint(1,6) print(f"Your numbers are {n1} & {n2}") roll_dice = input("Do you want to roll again? ")
class ATM(object): def __init__(self, cardnum, pin, bankname): self.cardnum=cardnum self.pin=pin self.banname=bankname self.amount=50000 def checkbalance(self): print("Your balance is", self.amount) def withdraw(self, amount): bal=self.amount-amount if bal<0: print("insufficient funds") else: self.amount=bal print("Your balance is ", self.amount) bank=input("Please enter your bank: ") cardnum=input("Please enter your card number: ") pin=input("Please enter your pin: ") newuser=ATM(cardnum, pin, bank) print("Choose your activity") print("1 balance inquiry") print("2 withdrawal") activity=input("Please enter your option: ") if activity==1: newuser.checkbalance() elif activity==2: amount=int(input("Please enter your amount: ")) newuser.withdraw(amount) else: print("Enter a valid option")
from person import * class PersonManager(object): """人员管理类""" def __init__(self): # 存储数据所用的列表 self.person_list = [] # 程序入口函数 def run(self): # 加载文件里面的人员数据 self.load_person() while True: # 显示功能菜单 self.show_menu() # 用户输入目标功能序号 menu_num = int(input("请输入需要的功能序号:")) # 根据用户输入的序号执行不同的功能 if menu_num == 1: # 添加人员 self.add_person() elif menu_num == 2: # 删除人员 self.del_person() elif menu_num == 3: # 修改人员 self.mod_person() elif menu_num == 4: # 查询人员 self.search_person() elif menu_num == 5: # 显示所有人员信息 self.show_person() elif menu_num == 6: # 保存人员信息 self.save_person() elif menu_num == 7: # 退出系统 break else: print("输入错误,请重新输入") # 系统功能函数 # 显示功能菜单 静态方法 @staticmethod def show_menu(): print("请选择如下功能:") print("1.添加人员") print("2.删除人员") print("3.修改人员信息") print("4.查询人员信息") print("5.显示所有人员信息") print("6.保存人员信息") print("7.退出系统") # 添加人员 def add_person(self): """添加人员信息""" # 输入人员信息 name = input("请输入姓名:") # 遍历人员列表,如果存在则报错,如果不存在则添加 for i in self.person_list: if i.name == name: print("人员已存在") break else: gender = input("请输入性别:") tel = input("请输入电话:") # 创建人员对象 person = Person(name, gender, tel) # 添加到人员列表 self.person_list.append(person) print(person) def del_person(self): """删除人员信息""" # 输入要删除的人员姓名 name = input("请输入要删除的人员姓名:") # 遍历人员列表,如果存在则删除,如果不存在则报错 for i in self.person_list: if i.name == name: self.person_list.remove(i) print("删除成功") break else: print("要删除的人员不存在") def mod_person(self): """修改人员信息""" # 输入要修改的人员姓名 name = input("请输入要修改的人员姓名:") # 遍历列表,如果要修改的人员存在则修改,否则报错 for i in self.person_list: if i.name == name: tel = input("请输入新手机号:") i.tel = tel print("修改成功") print(i) break else: print("要修改的人员不存在") def search_person(self): """查询人员信息""" # 请输入要查询的人员姓名 name = input("请输入要查询的人员姓名:") # 遍历列表,如果要查询的人员存在则显示,否则报错 for i in self.person_list: if i.name == name: print(i) break else: print("要查询的人员不存在") def show_person(self): """显示所有人员信息""" print("姓名\t性别\t手机号") for i in self.person_list: print(f"{i.name}\t{i.gender}\t{i.tel}") def save_person(self): """保存人员信息""" # 打开文件 f = open("person.data", "w") # 文件写入数据 # 人员对象转换成字典 new_list = [i.__dict__ for i in self.person_list] f.write(str(new_list)) # 关闭文件 f.close() print("保存成功") def load_person(self): """加载人员信息""" # 尝试以“r”模式打开数据文件,如果文件不存在,则提示用户;文件存在则读取数据 try: f = open("person.data", "r") except: f = open("person.data", "w") else: data = f.read() print(data) # 读取的文件是字符串,需要转换。【{}】转换【人员对象】 new_list = eval(data) self.person_list = [ Person(i["name"], i["gender"], i["tel"]) for i in new_list] finally: f.close()
#three2min.py a=eval(input("第1个整数:")) b=eval(input("第2个整数:")) c=eval(input("第3个整数:")) temp=0 #用于存放三个数的最小值 if (a>b): temp=b else: temp=a if(temp<c): print("最小数为:%d" %temp) else: print("最小数为:%d" %c)
# -*- coding: UTF-8 -*- # @Project -> File: python_training -> order_search # @Time: 2021/8/1 15:47 # @Author: Yu Yongsheng # @Description: # 顺序查找 def orderSearch(num_list, x): for i in range(len(num_list)): if num_list[i] == x: return i return -1 if __name__ == '__main__': num_list = [10, 20, 30, 40, 50, 60, 70, 75, 80, 90, 100] index = orderSearch(num_list, 65) print(index)
pizza = { "ctust":"thick", "toppings":["mushroom","extra cheese"] } print("You ordered a "+pizza["ctust"]+"- crust pizza" +"with the flowing toppings:") for topping in pizza["toppings"]: print("\t"+topping)
message1 = input("Tell me something,and I will repeat it back to you:") print(message1) promot = "\n Tell me something, and I will repeat it back to you:" promot = "\n Enter 'quit' to end the program." message = "" while message != "quit": message = input(promot) if message != "quit": print(message)
age = 88 if 2<age<=4: print("他正蹒跚学步") elif 4<age<=13: print("他是儿童") elif 13<age<=20: print("他是青少年") elif 20<age<=65: print("成年人") elif 65<age: print("老年人") fruits = ["strawberry","grapefruit","bananas"] if "strawberry" in fruits: print("You really like strawberry!") if "grapefruit" in fruits: print("You really like grapefruit!") if "bananas" in fruits: print("You really like bananas!")
squares =[] for value in range(1,11): square = value ** 2 squares.append(square) print(squares) # 另一种写法 for value in range(1,11): squares.append(value**2) print(squares) print(min(squares)) print(max(squares)) print(sum(squares))
# """ # if <Condition>: # statement # # """ # number_01 =1 # number_02 =2 # number_03 =4 # # # if number_01 < number_02: # # print('Number 02 is greater than Number01.') # # # # #if else # # # # if number_01 > number_02: # # print("Number 01 is greater than Number02.") # # else: # # print('Number 02 is greater than Number01.') # # #if elif else # # # if number_01 > number_02: # # print("Number 02 is greater than Number 01.") # # # # elif number_02 < number_03: # # print('Number 03 is greater than Number02.') # # # # else: # # print('Number 02 is greater than Number01.') # # # ## if # """ # if <Condition>: # statement # """ # number_01 =8 # number_02 =5 # number_03 =6 # # # if number_01 > number_02: # if number_01 > number_03: # print("Number 01 is max") # else: # if number_02 > number_03: # print("Number 02 is max") # else: # print("Number 03 is max") # # if number_01 < number_02 < number_03: # print("Number 03 is max") # # elif number_01 < number_02 and number_02 > number_03: # print("Number 02 is max") # # elif number_01 > number_02 and number_01 > number_03: # print("Number 01 is max") # # # #################################################################################################################### # # 2) Break abd continue # # #################################################################################################################### # # # """ # for i in range(): # print(i) # """ # # # for Loop # for i in range(0, 5): # print(i) # # # while loop # number = 0 # while number < 5: # print(number) # number += 1 # # #Do while loop (by default enter in loop) # number = 0 # while True: # if number > 5: # break # print(number) # number += 1 # # # #################################################################################################################### # # 4) Nested loop # # #################################################################################################################### # # for i in range(0, 5): # for j in range(0, i): # print(j, end="") # print('') # # # #################################################################################################################### # # 5) Control Looping # # #################################################################################################################### # # Do while loop (by default enters in loop) # # number = 0 # # while True: # # if number >5: # break # print(number) # number +=1 # # for i in range(0, 11, 2): # if i % 2 == 0: # print(i) # # # #################################################################################################################### # # Create Assignment using for or while loop # # for i in range(0, 5): # # for j in range(0, 5): # print("1", end=" ") # print('') # # # # # # number = 0 # # while True: # # if number > 5: # # break # # print(number) # # number += 1 # # for i in range(0, 11, 2): # if i % 2 == 0: # print(i) # # # # # # for i in range(0, 5): # # for j in range(0,5): # print(i%2,end='') # print('') # # # # # for i in range(0, 5): # # for j in range(0, 5): # print("1", end=" ") # print('') # # # # for i in range(0, 5): # # for j in range(0, 5): # print("*", end=" ") # print('') # # # # # # # # # num=int(input(5)) # # for i in range(1,number+1): # # for j in range(1,i+1): # # print("1", end="") # # print('') # # # # # # # # # # # for i in range(0, 5): # # # # for j in range(0, 5): # # print("*", end=" ") # # print('') # # # # # # # # # # # # for i in range(0, 5): # # # # for j in range(0, 5): # # print("1", end=" ") # # print('') # # # # print("###########") # # # for i in range(0,6): # for j in range(0, i+1): # print(2**(j+1), end=" ") # print(" ") # # # # # # # # # for i in range(0,5): # # for j in range(0, j+1): # # print (i%2, end=" ") # # print(" ") # # # # # # # for i in range(0,5): # # for j in range(0, j<5-1): # # i%2==0 # # print (j+1)%2 # # print(" ") # # # # ## # # # # # # # # print("###########") number = 0 for i in range(1,7): if(i%2 == 1): start = 1 end = 6 incremental = 1 number += 1 else: start = 5 end = 0 incremental = -1 for j in range(start,end,incremental): print("%02d"%(j*number),end=" ") print(" ")
class Fifteen: def __init__(self, verbose=0): self.count = 0 def lab(self,xlength,ylength): if xlength > 0 and ylength >0: self.lab (xlength - 1, ylength) self.lab (xlength, ylength -1) if xlength==0 or ylength==0: self.count = self.count + 1; print str(xlength) + ' ' + str(ylength) + ' ' + str(self.count) def getCount (self): return self.count fifteen = Fifteen (); fifteen.lab(20,20); print fifteen.count
def read_triangles_from_file (): triangles = [] with open('triangles.txt', 'r') as f: for line in f: triangle = line.rstrip('\n') triangles.append(triangle) return triangles def get_A(line): values = line.split(',') values = map(float, values) A = [] A.append([values[0], values[2], values[4]]) A.append([values[1], values[3], values[5]]) A.append([1,1,1]) return A def get_L_and_R (A): R = list(A) L = [[0,0,0], [0,0,0],[0,0,0]] for spalte in range(0,3): L[spalte][spalte] = 1 for zeile in range(spalte+1,3): quotient = float(R[zeile][spalte]/R[spalte][spalte]) L[zeile][spalte] = quotient for position in range (0,3): R[zeile][position] = R[zeile][position] - quotient * R[spalte][position] return L,R def get_results (L,R,b): y_1 = b[0] y_2 = b[1] - L[1][0] * y_1 y_3 = b[2] - L[2][0] * y_1 - L[2][1] * y_2 x_3 = y_3 / R[2][2] x_2 = (y_2 - R[1][2] * x_3) / R[1][1] x_1 = (y_1 - R[0][2] * x_3 - R[0][1] * x_2) / R[0][0] return x_1, x_2, x_3 triangles = read_triangles_from_file() count_inside = 0 for triangle in triangles: A = get_A (triangle) b = [0,0,1] L,R = get_L_and_R(A) x_1, x_2, x_3 = get_results(L,R,b) if x_1 > 0 and x_1<1: if x_2 > 0 and x_2 < 1: if x_3 > 0 and x_3 < 1: count_inside += 1 print count_inside
faculty=1 for i in range(100,1,-1): faculty= faculty * i; print faculty facultyStr=str(faculty) summe=0 for i in range (0,len(facultyStr)): summe = summe + int(facultyStr[i]) print summe
from argparse import ArgumentParser from subprocess import call as _call parser = ArgumentParser(description="Development scripts for OpenSlides") subparsers = parser.add_subparsers() def command(*args, **kwargs): """ Decorator to create a argparse command. The arguments to this decorator are used as arguments for the argparse command. """ class decorator: def __init__(self, func): self.parser = subparsers.add_parser(*args, **kwargs) self.parser.set_defaults(func=func) self.func = func def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) return decorator def argument(*args, **kwargs): """ Decorator to create arguments for argparse commands. The arguments to this decorator are used as arguments for the argparse argument. Does only work if the decorated function was decorated with the command-decorator before. """ def decorator(func): func.parser.add_argument(*args, **kwargs) def wrapper(*func_args, **func_kwargs): return func(*func_args, **func_kwargs) return wrapper return decorator def call(*args, **kwargs): """ Calls a command in a shell. """ return _call(shell=True, *args, **kwargs)
""" Inverse Burrows-Wheeler Transform Problem: Reconstruct a string from its Burrows-Wheeler transform. Input: A string Transform (with a single "$" symbol). Output: The string Text such that BWT(Text) = Transform. CODE CHALLENGE: Solve the Inverse Burrows-Wheeler Transform Problem. Sample Input: TTCCTAACG$A Sample Output: TACATCACGT$ https://github.com/ngaude/sandbox/blob/f009d5a50260ce26a69cd7b354f6d37b48937ee5/bioinformatics-002/bioinformatics_chapter8.py """ def ibwt(s): """ Inverse Burrows-Wheeler Transform Problem: Reconstruct a string from its Burrows-Wheeler transform. Input: A string Transform (with a single "$" symbol). Output: The string Text such that BWT(Text) = Transform. """ l = len(s) def char_rank(i): d[s[i]] = d.get(s[i],0) + 1 return d[s[i]] d = {} # produce a list tuple (char,rank) for the last column last_char_rank = [(s[i],char_rank(i),i) for i in range(l)] d = {} # produce the list tuple (char,rank) for the first column first_char_rank = sorted(last_char_rank) # for i in range(l): # r = str(first_char_rank[i])+('*'*(l-2))+str(last_char_rank[i]) # print r i = 0 decoded = '' for j in range(l): i = first_char_rank[i][2] decoded += first_char_rank[i][0] return decoded with open('11_Burrows_Wheeler_transform.txt') as infile: text = infile.read().strip() result = ibwt(text) print result result = str(result) with open('11_Burrows_Wheeler_transform_Answer.txt', "w") as f: f.write(result)
def layered_multiples(arr): print arr new_array = [] for x in arr: val_arr = [] for i in range(0,x): val_arr.append(1) new_array.append(val_arr) return new_array x = layered_multiples(multiply([2,4,5],3)) print x
#inventory using functions def order(): print("Each box price is Rs.3000/-") enter = int(input("Enter how many boxes you want to order: ")) return enter def bill(box): unit_cost = 3000 price = box * unit_cost return price def discount(offer): if offer >= 50000: user_discount= 0.5*offer new_price = offer - user_discount print("You are offered a discount of: "+str(user_discount)+" The new price of your order is :"+str(new_price)) elif offer >=25000: user_discount= 0.25*offer new_price = offer - user_discount print("You are offered a discount of: "+str(user_discount)+" The new price of your order is :"+str(new_price)) else: print("No Discount!") user_order = order() user_bill = bill(user_order) print("Your bill is :" + str(user_bill)) user_discount = discount(user_bill)
'''A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.''' #lambda arguments : expression x = lambda a: a*10 print(x(3)) y = lambda a,b : a * b print(y(3,4)) #The power of lambda is better shown when you use them as an anonymous function inside another function. def my_func(n): return lambda a: a*n #here n is 11 and a is 2 func = my_func(11) print(func(2))
###PROGRAM TO SEARCH IN A LIST### tem = input("Enter the item you want to find? ") mylist = [input() for num in range(5)] flag = False for x in range(len(mylist)): if mylist[x] == item: print("Item is found " + item + " at location: " + str(x+1)) flag = True break else: pass if flag == False: print("Item is not in the list")
# -*- coding: utf-8 -*- """ Created on Thu Feb 04 18:49:27 2016 @author: Geetha Yedida """ import turtle def draw_sphere(): sphere = turtle.Turtle() window = turtle.Screen() for i in range(36): sphere.circle(100) sphere.right(10) window.exitonclick() draw_sphere()
# if 문을 사용한다. money =1 if money : print("taxi") else : print("walk") a =10 if a : print("true") print("what we can do") print("yes we can") else : print("false") money = 2000 if(money > 3000) or a : print("money is much than 2000") else: print("money is less than 2000") if 1 in [1,2,3] : print("1 is in the List") else: print("1 is not in the List") if 1 not in [1,2,3]: print("1 is not in the List") else: print("1 is in the List") if 'a' in ('a','b','c'): print("a is in the tutle") else: print("a is not in the tutle") pocket = ['paper','handphone'] watch = 1 if 'money' in pocket : print("money is in pocket") else : if watch : print("watch is true") else : print("watch is not dlelelelel") treehit = 0 while treehit <10 : treehit +=1 print("tree is cutted %d" %treehit) if(treehit==10): print("tree is endndndnd") ''' coffee = 10 while 1: money = int(input("돈을 넣어 주세요: ")) if money == 300: print("커피를 줍니다.") coffee = coffee -1 elif money > 300: print("거스름돈 %d를 주고 커피를 줍니다." % (money -300)) coffee = coffee -1 else: print("돈을 다시 돌려주고 커피를 주지 않습니다.") print("남은 커피의 양은 %d개 입니다." % coffee) if not coffee: print("커피가 다 떨어졌습니다. 판매를 중지 합니다.") break ''' test_list = ['1','2','3'] for i in test_list : print(i) marks = [90, 25, 67, 45, 80] number = 0 for mark in marks : number = number +1 if mark >=60 : print("%d 학생은 합격입니다. " %number) else : print("%d 학생은 불합격입니다. " %number) # range 함수를 이용하여 내가 원하는 범위를 정할수 있다. sum =0 for i in range(1,11): sum += i print (sum) for i in range(1,10): for j in range(1,10): print(i*j , end=" ") print(" ") marks = [90, 25, 67, 45, 80] for number in range(len(marks)): if marks[number] < 60: continue print("%d번 학생 축하합니다. 합격입니다." % (number+1))
''' 🍏219. Contains Duplicate II Easy https://leetcode.com/problems/contains-duplicate-ii/description/ Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.   Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Example 3: Input: nums = [1,2,3,1,2,3], k = 2 Output: false Constraints: • 1 <= nums.length <= 105 • -109 <= nums[i] <= 109 • 0 <= k <= 105 ''' class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: d = dict() for i, x in enumerate(nums): if (x in d) and (i - d[x] <= k): return True d[x] = i return False
''' 🍏145. Binary Tree Postorder Traversal Easy https://leetcode.com/problems/binary-tree-postorder-traversal/ Given the root of a binary tree, return the postorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] Follow up: Recursive solution is trivial, could you do it iteratively? Constraints: • The number of the nodes in the tree is in the range [0, 100]. • -100 <= Node.val <= 100 ''' # python (non-recursion; iteratively) class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: res = [] if not root: return res stack = [root] postorder = [] while stack: node = stack.pop() postorder.append(node) if node.left: stack.append(node.left) if node.right: stack.append(node.right) while postorder: node = postorder.pop() res.append(node.val) return res # python key iteratively class Solution: # @param {TreeNode} root # @return {integer[]} def postorderTraversal(self, root): traversal, stack = [], [(root, False)] while stack: node, visited = stack.pop() if node: if visited: # add to result if visited traversal.append(node.val) else: # post-order stack.append((node, True)) stack.append((node.right, False)) stack.append((node.left, False)) return traversal # The 2nd uses modified preorder (right subtree first). Then reverse the result. class Solution: # @param {TreeNode} root # @return {integer[]} def postorderTraversal(self, root): traversal, stack = [], [root] while stack: node = stack.pop() if node: # pre-order, right first traversal.append(node.val) stack.append(node.left) stack.append(node.right) # reverse result return traversal[::-1]
''' 🍊🔐1569. 社交网络 中等 https://www.lintcode.com/problem/1569/ 每个人都有自己的网上好友。现在有n个人,给出m对好友关系,寻问任意一个人是否能直接或者间接的联系到所有网上的人。若能,返回yes,若不能,返回no。好友关系用a数组和b数组表示,代表a[i]和b[i]是一对好友。 样例1 样例2 输入: n=4, a=[1,1,1], b=[2,3,4] 输入: n=5, a=[1,2,4], b=[2,3,5] 输出: "yes" 输出: "no" 说明: Explanation: 1和2,3,4能直接联系 1,2,3能相互联系 2,3,4和1能直接联系,这3个人能通过1间接联系 4,5能相互联系 不过这两组人不能联系,比如,1无法联系4或者5 ''' # python class Solution: """ @param n: the person sum @param a: the array a @param b: the array b @return: yes or no """ class UnionFind: def __init__(self, n): self.parent = [i for i in range(n)] self.treeSize = [1 for _ in range(n)] self.count = n def union(self, a, b): a = self.find(a) b = self.find(b) if a == b: return if self.treeSize[a] < self.treeSize[b]: self.parent[a] = b self.treeSize[b] += self.treeSize[a] else: self.parent[b] = a self.treeSize[a] += self.treeSize[b] self.count -= 1 def find(self, x) -> int: while x != self.parent[x]: self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x def isConnect(self, a, b) -> bool: return self.find(a) == self.find(b) def socialNetwork(self, n, a, b): if n <= 0: return 'no' uf = self.UnionFind(n + 1) # 1-based arr, so+ one '0' for i, j in zip(a, b): uf.union(i, j) return 'yes' if uf.count == 2 else 'no' # 1-based, so 0->0 add 1;
''' 22. Generate Parentheses Medium https://leetcode.com/problems/generate-parentheses/ Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.  Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"]   Constraints: 1 <= n <= 8 ''' # python using n-1: 24 ms, faster than 99.09s class Solution: def generateParenthesis(self, n: int) -> List[str]: self.res = [] if n < 1: return self.res self.find(n, n, '') return self.res def find(self, l: int, r: int, cur: str): if l < 0: return if r == 0: self.res.append(cur) return if l > 0: self.find(l-1, r, cur + '(') if r > l: self.find(l, r-1, cur + ')')
''' 🍊153. Find Minimum in Rotated Sorted Array Medium https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: • [4,5,6,7,0,1,2] if it was rotated 4 times. • [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time.   Example 1: Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5] rotated 3 times. Example 2: Input: nums = [4,5,6,7,0,1,2] Output: 0 Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. Example 3: Input: nums = [11,13,15,17] Output: 11 Explanation: The original array was [11,13,15,17] and it was rotated 4 times.   Constraints: • n == nums.length • 1 <= n <= 5000 • -5000 <= nums[i] <= 5000 • All the integers of nums are unique. • nums is sorted and rotated between 1 and n times. ''' # python key # https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/158940/Beat-100%3A-Very-Simple-(Python)-Very-Detailed-Explanation class Solution: def findMin(self, nums: List[int]) -> int: if not nums or len(nums) == 1: return nums[0] if len(nums) == 1 else 0 n = len(nums) l, r = 0, n - 1 while l < r: m = l + ((r - l) >> 1) if nums[m] > nums[r]: l = m + 1 else: r = m # do NOT -1 return nums[l]
import numpy as np WHITE = -1 BLACK = +1 EMPTY = 0 PASS_MOVE = None class GameState(object): """State of a game of Go and some basic functions to interact with it """ def __init__(self, size=19): self.board = np.zeros((size, size)) self.board.fill(EMPTY) self.size = size self.turns_played = 0 self.current_player = BLACK self.ko = None self.history = [] self.num_black_prisoners = 0 self.num_white_prisoners = 0 def liberty_count(self, position): """Count liberty of a single position (maxium = 4). Keyword arguments: position -- a tuple of (x, y) x being the column index of the position we want to calculate the liberty y being the row index of the position we want to calculate the liberty Return: q -- A interger in [0, 4]. The count of liberty of the input single position """ return len(self.liberty_pos(position)) def liberty_pos(self, position): """Record the liberty position of a single position. Keyword arguments: position -- a tuple of (x, y) x being the column index of the position we want to calculate the liberty y being the row index of the position we want to calculate the liberty Return: pos -- Return a list of tuples consist of (x, y)s which are the liberty positions on the input single position. len(pos) <= 4 """ (x, y) = position pos=[] if x+1 < self.size and self.board[x+1][y] == EMPTY: pos.append((x+1, y)) if y+1 < self.size and self.board[x][y+1] == EMPTY: pos.append((x, y+1)) if x - 1 >= 0 and self.board[x-1][y] == EMPTY: pos.append((x-1, y)) if y - 1 >= 0 and self.board[x][y-1] == EMPTY: pos.append((x, y-1)) return pos def get_neighbor(self, position): """An auxiliary function for curr_liberties. This function looks around locally in 4 directions. That is, we just pick one position and look to see if there are same-color neighbors around it. Keyword arguments: position -- a tuple of (x, y) x being the column index of the position in consideration y being the row index of the posisiton in consideration Return: neighbor -- Return a list of tuples consist of (x, y)s which are the same-color neighbors of the input single position. len(neighbor_set) <= 4 """ (x, y) = position neighbor_set=[] if y+1 < self.size and self.board[x][y] == self.board[x][y+1]: neighbor_set.append((x,y+1)) if x+1 < self.size and self.board[x][y] == self.board[x+1][y]: neighbor_set.append((x+1,y)) if x-1 >= 0 and self.board[x][y] == self.board[x-1][y]: neighbor_set.append((x-1,y)) if y-1 >= 0 and self.board[x][y] == self.board[x][y-1]: neighbor_set.append((x,y-1)) return neighbor_set def visit_neighbor(self, position): """An auxiliary function for curr_liberties. This function perform the visiting process to identify a connected group of the same color Keyword arguments: position -- a tuple of (x, y) x being the column index of the starting position of the search y being the row index of the starting position of the search Return: neighbor_set -- Return a set of tuples consist of (x, y)s which are the same-color cluster which contains the input single position. len(neighbor_set) is size of the cluster, can be large. """ (x, y) = position # handle case where there is no piece at (x,y) if self.board[x][y] == EMPTY: return set() # A list for record the places we visited in the process # default to the starting position to handle the case where there are no neighbors (group size is 1) visited=[(x,y)] # A list for the the places we still want to visit to_visit=self.get_neighbor((x,y)) while len(to_visit)!=0: for n in to_visit: # append serve as the actual visit visited.append(n) # take off the places already visited from the wish list to_visit.remove(n) # With the cluster we have now, we look around even further for v in visited: # we try to look for same-color neighbors for each one which we already visited for n in self.get_neighbor(v): # we don't need to consider the places we already visited when we're looking if n not in visited: to_visit.append(n) neighbor_set=set(visited) return neighbor_set def update_current_liberties(self): """Calculate the liberty values of the whole board Keyword arguments: None. We just need the board itself. Return: A matrix self.size * self.size, with entries of the liberty number of each position on the board. Empty spaces have liberty 0. Instead of the single stone liberty, we consider the liberty of the group/cluster of the same color the position is in. """ curr_liberties = np.ones((self.size, self.size)) * (-1) for x in range(0, self.size): for y in range(0, self.size): if self.board[x][y] == EMPTY: continue # get the members in the cluster and then calculate their liberty positions lib_set = set() neighbors = self.visit_neighbor((x,y)) for n in neighbors: lib_set |= set(self.liberty_pos(n)) curr_liberties[x][y] = len(lib_set) return curr_liberties def copy(self): """get a copy of this Game state """ other = GameState(self.size) other.board = self.board.copy() other.turns_played = self.turns_played other.current_player = self.current_player other.ko = self.ko other.history = self.history other.num_black_prisoners = self.num_black_prisoners other.num_white_prisoners = self.num_white_prisoners return other def is_suicide(self, action): """return true if having current_player play at <action> would be suicide """ tmp = self.copy() tmp.board[action] = tmp.current_player zero_liberties = tmp.update_current_liberties() == 0 other_player = tmp.board == -tmp.current_player to_remove = np.logical_and(zero_liberties, other_player) tmp.board[to_remove] = EMPTY return tmp.update_current_liberties()[action] == 0 def is_legal(self, action): """determine if the given action (x,y tuple) is a legal move note: we only check ko, not superko at this point (TODO?) """ # passing move if action is PASS_MOVE: return True (x,y) = action empty = self.board[x][y] == EMPTY on_board = x >= 0 and y >= 0 and x < self.size and y < self.size suicide = self.is_suicide(action) ko = action == self.ko return on_board and (not suicide) and (not ko) and empty def is_eye(self, position, owner): """returns whether the position is empty and is surrounded by all stones of 'owner' """ (x,y) = position if self.board[x,y] != EMPTY: return False neighbors = [(x-1,y), (x+1,y), (x,y-1), (x,y+1)] for (nx,ny) in neighbors: if nx >= 0 and ny >= 0 and nx < self.size and ny < self.size: if self.board[nx,ny] != owner: return False return True def get_legal_moves(self): moves = [] for x in range(self.size): for y in range(self.size): if self.is_legal((x,y)): moves.append((x,y)) return moves def do_move(self, action): """Play current_player's color at (x,y) If it is a legal move, current_player switches to the other player If not, an IllegalMove exception is raised """ if self.is_legal(action): # reset ko self.ko = None if action is not PASS_MOVE: (x,y) = action self.board[x][y] = self.current_player # check liberties for captures liberties = self.update_current_liberties() zero_liberties = liberties == 0 other_player = self.board == -self.current_player captured_stones = np.logical_and(zero_liberties, other_player) capture_occurred = np.any(captured_stones) # note EMPTY spaces are -1 if capture_occurred: # clear pieces self.board[captured_stones] = EMPTY # count prisoners num_captured = np.sum(captured_stones) if self.current_player == BLACK: self.num_white_prisoners += num_captured else: self.num_black_prisoners += num_captured if num_captured == 1: xcoord,ycoord = np.where(captured_stones) # it is a ko iff were the opponent to play at xcoord,ycoord # it would recapture (x,y) only # (a bigger group containing xy may be captured - this is 'snapback') if len(self.visit_neighbor(action)) == 1 and self.update_current_liberties()[action] == 1: self.ko = (xcoord[0], ycoord[0]) # next turn self.current_player = -self.current_player self.turns_played += 1 self.history.append(action) else: raise IllegalMove(str(action)) def symmetries(self): """returns a list of 8 GameState objects: all reflections and rotations of the current board does not check for duplicates """ # we use numpy's built-in array symmetry routines for self.board. # but for all xy pairs (i.e. self.ko and self.history), we need to # know how to rotate a tuple (x,y) into (new_x, new_y) xy_symmetry_functions = { "noop": lambda (x,y): (x, y), "rot90": lambda (x,y): (y, self.size-x), "rot180": lambda (x,y): (self.size-x, self.size-y), "rot270": lambda (x,y): (self.size-y, x), "mirror-lr": lambda (x,y): (self.size-x, y), "mirror-ud": lambda (x,y): (x, self.size-y), "mirror-\\": lambda (x,y): (y, x), "mirror-/": lambda (x,y): (self.size-y, self.size-x) } def update_ko_history(copy, name): if copy.ko is not None: copy.ko = xy_symmetry_functions[name](copy.ko) copy.history = [xy_symmetry_functions[name](a) if a is not PASS_MOVE else PASS_MOVE for a in copy.history] copies = [self.copy() for i in range(8)] # copies[0] is the original. # rotate CCW 90 copies[1].board = np.rot90(self.board,1) update_ko_history(copies[1], "rot90") # rotate 180 copies[2].board = np.rot90(self.board,2) update_ko_history(copies[2], "rot180") # rotate CCW 270 copies[3].board = np.rot90(self.board,3) update_ko_history(copies[3], "rot270") # mirror left-right copies[4].board = np.fliplr(self.board) update_ko_history(copies[4], "mirror-lr") # mirror up-down copies[5].board = np.flipud(self.board) update_ko_history(copies[5], "mirror-ud") # mirror \ diagonal copies[6].board = np.transpose(self.board) update_ko_history(copies[6], "mirror-\\") # mirror / diagonal (equivalently: rotate 90 CCW then flip LR) copies[7].board = np.fliplr(copies[1].board) update_ko_history(copies[7], "mirror-/") return copies def from_sgf(self, sgf_string): raise NotImplementedError() def to_sgf(self, sgf_string): raise NotImplementedError() class IllegalMove(Exception): pass
import json #Класс хранит состояние игры в города, есть методы для того чтобы делать ходы class Game: def __init__(self): with open('cities.json', 'r', encoding='utf-8') as fin: self.cities = json.load(fin) self.used_cities = [] self.prev_city = 'Москва' self.player_turn = True def use_city(self, city): self.used_cities.append(city) self.cities.remove(city) self.prev_city = city def try_city(self, city): city = city.lower() prev_city = self.prev_city if prev_city[-1] in ['ь','ы','ъ']: prev_city = prev_city[:-1] if city[0] != prev_city[-1]: return f'Город должен начинаться на букву {self.prev_city[-1]}' elif city in self.used_cities: return f'Такой город уже был' elif city not in self.cities: return f'Такого города я не знаю' else: self.use_city(city) self.player_turn = not self.player_turn return city def bot_turn(self): prev_city = self.prev_city if prev_city[-1] in ['ь','ы','ъ']: prev_city = prev_city[:-1] for city in self.cities: if city[0] == prev_city[-1]: return self.try_city(city).capitalize() break return 'Я сдаюсь!'
def student_name(*names): for name in names: print(name) student_name("jayshri","vaishali","puja","saru") # def student_name(*names): # print(names) # student_name("jayshriuyi","baishu","hgijk","gyguij")
""" Recurrent Neural Network. A Recurrent Neural Network (LSTM) implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Links: [Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf) [MNIST Dataset](http://yann.lecun.com/exdb/mnist/). Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ """ from __future__ import print_function import tensorflow as tf from tensorflow.contrib import rnn ''' To classify images using a recurrent neural network, we consider every image row as a sequence of pixels. Because MNIST image shape is 28*28px, we will then handle 28 sequences of 28 steps for every sample. ''' # Training Parameters #learning_rate = 0.001 learning_rate = 0.01 training_steps = 1000 batch_size = 128 display_step = 200 # Network Parameters num_input = 28 # MNIST data input (img shape: 28*28) timesteps = 28 # timesteps num_hidden = 128 # hidden layer num of features num_classes = 10 # MNIST total classes (0-9 digits) ## Import MNIST data #from tensorflow.examples.tutorials.mnist import input_data #mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # Transforms a scalar string `example_proto` into a pair of a scalar string and # a scalar integer, representing an image and its label, respectively. def _parse_function(example_proto): features = {"image_raw": tf.FixedLenFeature([], tf.string, default_value=""), "label": tf.FixedLenFeature([], tf.int64, default_value=0)} parsed_features = tf.parse_single_example(example_proto, features) image = tf.decode_raw(parsed_features['image_raw'], tf.uint8) label = tf.cast(parsed_features['label'], tf.int32) return image, label #def read_and_decode(filename_queue): # reader = tf.TFRecordReader() # _, serialized_example = reader.read(filename_queue) # features = tf.parse_single_example( # serialized_example, # # Defaults are not specified since both keys are required. # features={ # 'image_raw': tf.FixedLenFeature([], tf.string), # 'label': tf.FixedLenFeature([], tf.int64), # 'height': tf.FixedLenFeature([], tf.int64), # 'width': tf.FixedLenFeature([], tf.int64), # 'depth': tf.FixedLenFeature([], tf.int64) # }) # image = tf.decode_raw(features['image_raw'], tf.uint8) # label = tf.cast(features['label'], tf.int32) # height = tf.cast(features['height'], tf.int32) # width = tf.cast(features['width'], tf.int32) # depth = tf.cast(features['depth'], tf.int32) # return image, label, height, width, depth # Creates a dataset that reads all of the examples from two files, and extracts # the image and label features. #training_filenames = ["/tmp/data/train.tfrecord"] #filenames = tf.placeholder(tf.string, shape=[None]) filenames = ["/tmp/data/train.tfrecord"] dataset = tf.contrib.data.TFRecordDataset(filenames) dataset = dataset.map(_parse_function) dataset = dataset.repeat() # Repeat the input indefinitely. dataset = dataset.batch(128) iterator = dataset.make_one_shot_iterator() # tf Graph input X = tf.placeholder("float", [None, timesteps, num_input]) Y = tf.placeholder("float", [None, num_classes]) # Define weights weights = { 'out': tf.Variable(tf.random_normal([num_hidden, num_classes])) } biases = { 'out': tf.Variable(tf.random_normal([num_classes])) } def RNN(x, weights, biases): # Prepare data shape to match `rnn` function requirements # Current data input shape: (batch_size, timesteps, n_input) # Required shape: 'timesteps' tensors list of shape (batch_size, n_input) # Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input) x = tf.unstack(x, timesteps, 1) # Define a lstm cell with tensorflow lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0) # Get lstm cell output outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32) # Linear activation, using rnn inner loop last output return tf.matmul(outputs[-1], weights['out']) + biases['out'] def model_function(Data, Label): logits = RNN(Data, weights, biases) prediction = tf.nn.softmax(logits) # Define loss and optimizer loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y)) return loss_op, prediction def GetNext(): batch_x, batch_y = iterator.get_next() batch_x = tf.reshape(batch_x,[batch_size, timesteps, num_input]) batch_y = tf.one_hot(batch_y, num_classes) batch_y = tf.reshape(batch_y, tf.stack([batch_size, num_classes])) batch_y.set_shape([batch_size, num_classes]) return batch_x, batch_y loss_op, prediction = model_function(X, Y) optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) # Evaluate model (with test logits, for dropout to be disabled) correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initialize the variables (i.e. assign their default value) init = tf.global_variables_initializer() # Add ops to save and restore all the variables. saver = tf.train.Saver() # Start training with tf.Session() as sess: ## Restore variables from disk. #saver.restore(sess, "/tmp/model.ckpt") #print("Model restored.") # Run the initializer sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for step in range(1, training_steps+1): ##Get Data From Demo Dataset from network #batch_x, batch_y = mnist.train.next_batch(batch_size) ## Reshape data to get 28 seq of 28 elements #batch_x = batch_x.reshape((batch_size, timesteps, num_input)) batch_x, batch_y = sess.run(GetNext()) # Run optimization op (backprop) sess.run(train_op, feed_dict={X: batch_x, Y: batch_y}) if step % display_step == 0 or step == 1: # Calculate batch loss and accuracy loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y}) print("Step " + str(step) + ", Minibatch Loss= " + \ "{:.4f}".format(loss) + ", Training Accuracy= " + \ "{:.3f}".format(acc)) coord.request_stop() coord.join(threads) print("Optimization Finished!") ## Save the variables to disk. #save_path = saver.save(sess, "/tmp/model.ckpt") #print("Model saved in file: %s" % save_path) ## Calculate accuracy for 128 mnist test images #test_len = 128 #test_data = testdata.images[:test_len].reshape((-1, timesteps, num_input)) #test_label = testdata.labels[:test_len] #print("Testing Accuracy:", \ # sess.run(accuracy, feed_dict={X: test_data, Y: test_label}))
from numpy import mean, std operaciones_lista=[-9,-45,0,7,45,-100,89] #Se crea la lista suma_numeros_positivos=0 suma_numero_negativos=0 for i in range(len(operaciones_lista)): #For que vaya desde i=0 hasta la cantidad de numero en la lista if operaciones_lista[i]>=0: #Solo si son mayor a 0 suma_numeros_positivos+=operaciones_lista[i] #Suma numeros positivos print("Suma numeros positivos:",suma_numeros_positivos) #Imprime numeros positivos for i in range(len(operaciones_lista)): #For que vaya desde i=0 hasta la cantidad de numero en la lista if operaciones_lista[i]<=0: #Solo si son menor a 0 suma_numero_negativos+=abs(operaciones_lista[i]) #Suma de numeros negativos print("Suma numeros negativos:",suma_numero_negativos) print(sorted(operaciones_lista)) #Con el metodo sorted se ordenan los numeros de forma ascendete o descendente #sorted(iterable, key=None, reverse=False)
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) # convert decimal to binary using bin() # use [2:] to remove the ob from start of output bin_output = bin(n)[2:] #print(bin_output) count = 0 total_count = 0 for i in bin_output: # convert to int as count wasn't recognising it. z = int(i) #print("i ----", z) if z is 1: count += 1 #print("1 count = ", count) # if current count is higher than previous counts then update total_count if count > total_count: total_count = count else: count = 0 #print("0 count = ", count) print(total_count)
8.5심사 so = {'go':90,'en':81,'ma':86,'si':80} 9.3 심사 so['en'] > 80 or so['ma'] > 85 or so['si'] >= 80 or so['go'] >= 90 10.5심사 su = int(input()) print(list(range(-10,11,su))) 11. 심사 ans1 = str(input()) ans2 = str(input()) for i in ans1: a = ans1.index(i) 12.심사 key = ['health', 'health_regen', 'mana' ,'mana_regen'] su = [575.6, 1.7 ,338.8, 1.63] dict(zip(key,su)) 13.심사 price = int(input()) cash = int(input()) print(price-cash)
from collections import defaultdict def group_anagrams(strings): anagrams = defaultdict(list) for string in strings: s_anagram = "".join(sorted(string)).replace(" ", "") anagrams[s_anagram].append(string) all_anagrams = [] for anagram_strings in anagrams.values(): all_anagrams += anagram_strings return all_anagrams strings = ["ma n", " tree", "ret e", "nam"] print(group_anagrams(strings))
def rotated_search(array, needle): if not array: return None mid = int(len(array) / 2) mid_val = array[mid] if mid_val == needle: return mid right_val = array[-1] if (needle > mid_val and not needle > right_val) or (needle < mid_val and needle < array[0]): return rotated_search(array[mid+1:], needle) + 1 + mid else: return rotated_search(array[:mid], needle) print(rotated_search([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 5))
num = int(input()) count = 0 for i in range(2,num): if num % i == 0: count = count + 1 if(count >= 1): print("no") else: print("yes")
ps=input() ps=ps.replace(" ","") ps=ps.lower() if(len(set(ps)))==26: print("yes") else: print("no")
a1=int(input()) if a1>1: for i in range(2,a1//2): if(a1%i)==0: print("yes") break else: print("no") else: print("yes")
nber1=str(input()) for i in range(0,len(nber1)): if nber1[i]!='0' and nber1[i]!='1': print("no") else: print("yes")
number=int(input()) l={1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",9:"Nine",10:"Ten"} print(l[number])
number=input() e=input().split(" ") f=len(e) for i in range(f): print(e[i],end=" ") print(i)
shi,sea=map(str,input().split()) if(len(shi) != len(sea)): print('no') xs=[shi.count(char1) for char1 in shi] ys=[sea.count(char1) for char1 in sea] if(xs==ys): print('yes') else: print('no')
num=input() count=0 for i in num: if (i.isnumeric())== True: count=count+1 print(count)
num=int(input()) a=input().split(' ') b= [int(j) for j in a] b.sort() for j in range (num): print(b[j],end=" ")
print([x*x for x in range(4)]) print([x*x*x for x in range(4) if x*x % 3 == 0]) print([x.lower() for x in "LOREM IPSUM DOLOR".split()]) print(sum([x*x*3 for x in range(4) if x*x % 3 == 0]))
import os import os.path def przegladanie(root, file_dictionary): file_list = os.listdir(root) dir_list = [] for item in file_list: if os.path.isfile(os.path.join(root, item)): full_name = os.path.join(root, item) file_size = os.path.getsize(full_name) if file_size in file_dictionary: file_dictionary[file_size].append(full_name) else: file_dictionary[file_size] = [full_name] print(full_name, file_size) if os.path.isdir(os.path.join(root, item)): dir_list.append(item) for dirname in dir_list: przegladanie(os.path.join(root, dirname), file_dictionary) file_dictionary_keys = list(file_dictionary.keys()) file_dictionary_keys.sort() file_dictionary_sorted = {} for key in file_dictionary_keys: file_dictionary_sorted[key] = file_dictionary[key] return file_dictionary_sorted def znajdz_pliki_o_tym_samym_rozmiarze(file_dictionary): for key in file_dictionary: if len(file_dictionary[key]) > 1: print("Pliki o tym samym rozmiarze to: ") print("Rozmiar: " + str(key)) for item in file_dictionary[key]: print(item)
class NotStringError(Exception): pass class NotIntError(Exception): pass class Wyrazenie: pass class Zmienna(Wyrazenie): def __init__(self, nazwa): if not isinstance(nazwa, str): raise NotStringError self.nazwa = nazwa def __str__(self): return self.nazwa def oblicz(self, stan): return stan[self.nazwa] class Stala(Wyrazenie): def __init__(self, wartosc): if not isinstance(wartosc, int): raise NotIntError self.wartosc = wartosc def __str__(self): return str(self.wartosc) def oblicz(self): return self.wartosc class Dodawanie(Wyrazenie): def __init__(self, lewy, prawy): self.lewy = lewy self.prawy = prawy def __str__(self): return str(self.lewy) + " + " + str(self.prawy) def oblicz(self, stan): if type(self.lewy) is Stala and type(self.prawy) is Stala: return self.lewy.oblicz() + self.prawy.oblicz() elif type(self.prawy) is Stala: return self.lewy.oblicz(stan) + self.prawy.oblicz() elif type(self.lewy) is Stala: return self.lewy.oblicz() + self.prawy.oblicz(stan) else: return self.lewy.oblicz(stan) + self.prawy.oblicz(stan) def uprosc(self): if (type(self.lewy) is Stala and type(self.prawy) is Stala) or \ (self.lewy.oblicz() == 0 or self.prawy.oblicz() == 0): return Stala(self.lewy.oblicz() + self.prawy.oblicz()) class Mnozenie(Wyrazenie): def __init__(self, lewy, prawy): self.lewy = lewy self.prawy = prawy def __str__(self): return str(self.lewy) + " * " + str(self.prawy) def oblicz(self, stan): if type(self.lewy) is Stala and type(self.prawy) is Stala: return self.lewy.oblicz() * self.prawy.oblicz() elif type(self.prawy) is Stala: return self.lewy.oblicz(stan) * self.prawy.oblicz() elif type(self.lewy) is Stala: return self.lewy.oblicz() * self.prawy.oblicz(stan) else: return self.lewy.oblicz(stan) * self.prawy.oblicz(stan) def uprosc(self): if (type(self.lewy) is Stala and type(self.prawy) is Stala) or \ (self.lewy.oblicz() == 1 or self.prawy.oblicz() == 1): return Stala(self.lewy.oblicz() * self.prawy.oblicz()) # aktualny_stan = {'x': 1, 'y': 3, 'z': 3} # # wyrazenie = Dodawanie(Dodawanie(Zmienna("x"), Zmienna("y")), Zmienna("z")) # print(wyrazenie) # print(wyrazenie.oblicz(aktualny_stan)) # # wyrazenie2 = Mnozenie(Mnozenie(Zmienna("x"), Zmienna("y")), Zmienna("z")) # print(wyrazenie2) # print(wyrazenie2.oblicz(aktualny_stan)) # # wyrazenie3 = Dodawanie(Dodawanie(Stala(2), Zmienna("y")), Zmienna("z")) # print(wyrazenie3) # print(wyrazenie3.oblicz(aktualny_stan)) # # wyrazenie4 = Mnozenie(Mnozenie(Stala(2), Zmienna("y")), Stala(2)) # print(wyrazenie4) # print(wyrazenie4.oblicz(aktualny_stan)) # # wyrazenie5 = Dodawanie(Stala(0), Stala(6)) # nowe = wyrazenie5.uprosc() # print("nowe = " + str(nowe)) # # wyrazenie6 = Mnozenie(Stala(1), Stala(6)) # nowe2 = wyrazenie6.uprosc() # print("nowe2 = " + str(nowe2)) # # wyrazenie7 = Dodawanie(nowe, nowe2) # print(wyrazenie7) # print(wyrazenie7.oblicz(aktualny_stan))
class CustomException(Exception): def __init__(self, msg): self.msg = msg class TryAddExistTriangleException(CustomException): pass class NotValidinstanceOfTriangleException(CustomException): pass class ValidationException(CustomException): pass class ListOfTriangles(list): """ Creates list of triangles with unique names """ def __init__(self): self.list = [] def append(self, instance): if instance.name not in (triangle.name for triangle in self.list): self.list.append(instance) else: raise TryAddExistTriangleException('You are trying to add triangle with existed name!') def __str__(self): output = '===== Triangles list:======\n' for index, triangle in enumerate(sorted(self.list)): output += f"{index+1}. [Triangle {triangle.name}]: {round(triangle.area)} cm\n" return output class Triangle(): """ Creates triangles with unique names. The sides of triangles must be possitive integer or float value. """ def __init__(self, name, side_1, side_2, side_3): self.side_1 = side_1 self.side_2 = side_2 self.side_3 = side_3 self.name = name self.validate_data() self.check_area() @property def area(self): """ Calculate by Heron's formula and return area """ p = (self.side_1 + self.side_2 + self.side_3)*.5 area = (p*(p - self.side_1)*(p - self.side_2)*(p - self.side_3))**.5 return area def check_area(self): """ Check if the area is complex number or area less or equal to null. """ if not isinstance(self.area, complex): if self.area <= 0: raise NotValidinstanceOfTriangleException('Negative area of triangle') else: raise NotValidinstanceOfTriangleException('Negative area of triangle') def validate_data(self): """ For attribute 'name' return string with the deleted whitespace at the begin and end of the string For sides attributes return integer or float and checks if the value greater than null """ for attr in self.__dict__: if attr == 'name': self.__dict__[attr] = self.__dict__[attr].strip() else: self.__dict__[attr] = validate_to_number(self.__dict__[attr]) if self.side_1 <=0 or self.side_2 <= 0 or self.side_3 <= 0: raise NotValidinstanceOfTriangleException('Negative side of triangle') def __lt__(self, other): if self.area < other.area: return True else: return False def __gt__(self, other): if self.area > other.area: return True else: return False def validate_to_number(value): value = value.strip() try: value = int(value) except ValueError: try: value = float(value) except ValueError: raise ValidationException("Not valid data in entering sides") else: return value else: return value def answer_choise(question): answer = input(f"{question} [y/n][Yes/No]").lower() if answer == 'n' or answer == 'no': return False elif answer == 'y' or answer == 'yes': return True else: print("We couldn't understand you") return answer_choise(question) def create_triangle_from_input(): try: name = input("Enter the name of triangle:") side_1 = input("Enter the first side of triangle:") side_2 = input("Enter the second side of triangle:") side_3 = input("Enter the third side of triangle:") return Triangle(name, side_1, side_2, side_3) except CustomException as e: print(e.msg) if answer_choise('Try again?'): return create_triangle_from_input() return def add_to_list(triangle, list_of_triangles): try: list_of_triangles.append(triangle) except CustomException as e: print(e.msg) if answer_choise('Do you want to change name?'): name = input("Enter the name of triangle:") triangle.name = name return add_to_list(triangle, list_of_triangles) def create_and_add(list_of_triangles): tr = create_triangle_from_input() if tr: add_to_list(tr, list_of_triangles) def main(): list_of_triangles = ListOfTriangles() want_to_add = True while want_to_add: create_and_add(list_of_triangles) want_to_add = answer_choise('Do you want to add triangle?') else: print(list_of_triangles) if __name__ == "__main__": main()
import sys # ---------------------------------------------- # Cartesian coordinate point # ---------------------------------------------- class Coordinate: def __init__(self, x, y): self.x = x self.y = y def printIt(self): sys.stdout.write("(" + str(self.x) + ", " + str(self.y) + ")")
def main(): print(is_even([5, 6, 7, 8])) def is_even(arr): return sum(arr) % 2 == 0 if __name__ == '__main__': main()
import pandas as pd import numpy as np # Adpated from https://machinelearningmastery.com/convert-time-series-supervised-learning-problem-python/ def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): n_vars = 1 if type(data) is list else data.shape[1] var_n= data.columns.tolist() df = pd.DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) names += [(var_n[j]+'(t-%d)' % ( i)) for j in range(n_vars)] # forecast sequence (t, t+1, ... t+n) for i in range(0, n_out): cols.append(df.shift(-i)) if i == 0: names += [(var_n[j]+'(t)') for j in range(n_vars)] else: names += [(var_n[j]+'(t+%d)' % (i)) for j in range(n_vars)] # put it all together agg = pd.concat(cols, axis=1) agg.columns = names # drop rows with NaN values if dropnan: agg.dropna(inplace=True) return agg def dataTimeSeries(timesteps,df,predictors,target,dropnan,out=2,dropVars=True): """ This function transforms a dataframe in a timeseries for surpervised learning. timesteps: Number of delays (i.e: timesteps =2 (t),(t-1),(t-2)); df: Dataframe; predictors: List of columns in dataframe as features for the ML algorithm; target: Target of the supervised learning; dropnan: Flag to drop the NaN values after transforming the out: Number of steps to forecast (i.e: out = 2 (t),(t+1)); dropVars= Leave only the Target of the last timestep on the resulting dataframe; """ series = series_to_supervised(df[predictors+[target]].copy(),timesteps,out,dropnan=dropnan) if dropnan==False: series.replace(pd.np.nan,0,inplace=True) # Dropping other variables: if dropVars: index = list(np.arange(series.shape[1]-2, series.shape[1]-len(predictors)-2, -1)) labels = [item for idx,item in enumerate(series.columns) if idx in index] print("Eliminando variáveis: {}".format(labels)) series.drop(labels,axis=1,inplace=True) return series
#/usr/bin/python import sys def main(argv): strand = str(argv[0]) aCount = 0 cCount = 0 gCount = 0 tCount = 0 #Parsing DNA strand for molecule in strand: if molecule == "A": aCount += 1 elif molecule == "C": cCount += 1 elif molecule == "G": gCount += 1 elif molecule == "T": tCount += 1 print aCount, cCount, gCount, tCount if __name__ == "__main__": main(sys.argv[1:])
# python3 /users/haoransong/Desktop/python/5qi.py import random def play_wuziqi(): first = 1 #1:player first 2:computer first board = make_board() x = [] for i in range(13): x.append([]) for i1 in range(13): x[-1].append(0) y = [] for i in range(13): y.append([]) for i1 in range(13): y[-1].append(0) z1 = [] for i in range(25): z1.append([]) if i <= 12: n = i+1 else: n = 25-i for i1 in range(n): z1[-1].append(0) # z2=z1[:] z2 = [] for i in range(25): z2.append([]) if i <= 12: n = i+1 else: n = 25-i for i1 in range(n): z2[-1].append(0) b = ['a','b','c','d','e','f','g','h','i','j','k','l','m'] bw = 0 while True: btn = bw%2+first%2 print('btn:',btn) print_board(board) if btn == 1: move = input('next?\n').lower() else: move = robot([x,y,z1,z2],bw%2+1,bw,b) print(move) if not move: move = input('nextwhite?\n').lower() xx = int(move[1:])-1 yy = b.index(move[0]) if board[xx][yy] != '.': print('Error:there has been placed') move = input('nextwhite?\n').lower() if move == 'aaa': break elif move == 'save': break if move[0] in b: if int(move[1:]) <= 13: pass else: print('Error:input type error') continue else: print('Error:input type error') continue if move[0] in b: xx = int(move[1:])-1 yy = b.index(move[0]) if board[xx][yy] != '.': print('Error:there has been placed') continue else: if xx+yy >= 12: z1[xx+yy][12-yy] = btn else: z1[xx+yy][yy] = btn if 12+xx-yy >= 12: z2[12+xx-yy][yy] = btn else: z2[12+xx-yy][xx] = btn x[xx][yy] = btn y[yy][xx] = btn if btn == first: board[xx][yy] = 'O' else: board[xx][yy] = 'X' # print('X'*50) # for line in x: # print(line) # print('X'*50) else: xx = int(move[:-1])-1 yy = b.index(move[-1]) if board[xx][yy] != '.': print('Error:there has been placed') continue else: x[xx][yy] = btn y[yy][xx] = btn z1[xx+yy][13-xx] = btn z2[12+xx-yy][xx] = btn board[xx][yy] = btn if if_win([x,y,z1,z2],btn): print_board(board) if btn == first: if first == 1: print('win') else: print('lose') else: if first == 1: print('lose') else: print('win') break bw += 1 def make_board(): board = [] for i in range(13): board.append([]) for i1 in range(13): board[-1].append('.') return board def print_board(a): print('\n',' ','A','','B','','C','','D','','E','','F','','G','','H','','I','','J','','K','','L','','M') x = 0 for i in a: x += 1 board = [] for i1 in i: board.append('%s' % i1) board = ' '.join(board) if x < 10: print(' ',x,'',board,'',x) else: print('',x,'',board,'',x) print(' ','A','','B','','C','','D','','E','','F','','G','','H','','I','','J','','K','','L','','M') def if_win(a,bw): if bw == 0: bw = 2 fi = 0 for i in a: for i1 in i: for i2 in i1: if i2 == bw: fi += 1 if fi == 5: return True else: fi = 0 def robot(a,bw,bw1,b): def locate(i,i1,s1,line,reverse=False): if reverse == True: if i <= 1: lo = '%s' % (12-line.find(s1)-s1.find('0')) else: if i >= 12: lo = '%s' % (26-i1-line.find(s1)-s1.find('0')) else: lo = '%s' % (i1-line.find(s1)-s1.find('0')) else: lo = '%s' % (line.find(s1)+s1.find('0')) if i == 0: move = b[int(lo)] + '%s' % ((int(i1))+1) # b[i1] + '%s' % (int(lo)+1) elif i == 1: move = b[i1] + '%s' % (int(lo)+1) elif i == 2: if i1 < 12: move = b[int(lo)] + '%s' %(i1-int(lo)+1) else: move = b[(12-int(lo))] + '%s' %(i1-11+int(lo)) elif i == 3: if i1 >= 12: move = b[int(lo)] + '%s' % (i1-11+int(lo)) else: move = b[(12-i1+int(lo))] + '%s' % (int(lo)+1) print('move:',move) print('i:',i,'i1:',i1,'s1:',s1,'line:',line,'lo:',lo,reverse) return move def robot_h(all_ma): all_ind = [] all_move = [] for li in range(len(a)): for i1 in range(len(a[li])): num = [] for i2 in a[li][i1]: num.append('%s' % i2) numr = num[:] numr.reverse() numr = ''.join(numr) num = ''.join(num) for s1 in all_ma: if s1 in num: return locate(li,i1,s1,num) elif s1 in numr: return locate(li,i1,s1,numr,True) # print('in',s1,li) # for t in range(len(s1)): # if o[t] == '0': # all_move.append(loc(num.index(s1)+t,li,i1)) # all_move.append(locate(li,i1,s1,num)) # if len(all_move) == 1: # return all_move[0] # return choose(all_move,a) if bw1 <= 1: if a[0][6][6] == 0: return('g7') else: move_all = ['f6','g6','h6','f7','h7','f8','g8','h8'] return(move_all[random.randint(0,7)]) all_ma0 = ['02222','22220','22022','20222','22202','01111','11110','11011','11101','10111'] all_ma1 = ['02220','22200','00222','22020','01110','10110','11010'] all_ma2 = ['22200','02220','20220','22020'] all_ma3 = ['11100','01110','02200','2020','10110','11010','01100','00111']#,'000110','011000','001100','010100','001010'] all_ma4 = ['20'] move = robot_h(all_ma0) print(0) if move: return move # if move.index(' ') == 1: # return '%s' % b[int(move[0])] + '%s' % (int(move[1:])+1) # else: # return '%s' % b[int(move[:2])] + '%s' % (int(move[3:])+1) def if_4zi(): line = '' for i in range(len(a)): #i:each board for i1 in range(len(a[i])): #i1:each board's line line = '' for s1 in a[i][i1]: line += '%s' % s1 for s in all_ma0: if s in line: move = locate(i,i1,s,line) # if_4zi() move = robot_h(all_ma1) print(1,move) if move: return move move = robot_h(all_ma2) print(2,move) if move: return move move = robot_h(all_ma3) print(3) if move: return move move = robot_h(all_ma4) print(4) if move: return move def loc(lo,i,i1): print(lo,i,i1) if i == 1: move = '%s' % i1 + ' ' + '%s' % (lo) print(move) return move elif i == 0: move = '%s' % lo + ' ' + '%s' % (i1) print(move) return move elif i == 2: if i1 < 12: move = '%s' % lo + ' ' + '%s' %(i1-lo) else: move = '%s' % (12-lo) + ' ' + '%s' %(i1-12+lo) print(move) return move elif i == 3: if i1 >= 12: move = '%s' % lo + ' ' + '%s' % (i1-12+lo) else: move = '%s' % (12-i1+lo) + ' ' +'%s' % (lo) print(move) return move def choose(all_move,a): grade_all = [] for i in all_move: if i.index(' ') == 1: x = a[0][int(i[0])] y = a[1][int(i[1:])] else: x = a[0][int(i[:2])] y = a[1][int(i[3:])] grade_all.append(x.count('2')-x.count('1')+y.count('2')-y.count('1')) ma = 0 for i in grade_all: if i > ma: ma = i co = grade_all.count(ma) print(grade_all,ma,co,all_move) if co == 1: return all_move[grade_all.index(ma)] else: ind = random.randint(1,co) ix = 0 i1 = -1 for i in grade_all: i1 += 1 if i == ma: ix += 1 if ix == ind: return all_move[i1] if __name__ == '__main__': play_wuziqi()
score = input("Enter Score: ") try : x=float(score) except: print ("Error,pleas enter a numeric input between 0.0 and 1.0") quit() if x < 0.6 : print ("F") elif x > 1 : print ("Error,pleas enter a numeric input between 0.0 and 1.0") elif x >= 0.6 : print ("D") elif x >=0.7 : print ("C") elif x >= 0.8 : print("B") elif x >= 0.9 : print ("A")
class Solution(object): def lexicalOrder(self, n): res = [] def print_numbers(k, n): for i in range (0, 10): if (k+i)<= n: res.append(k+i) print_numbers((k+i)*10, n) for k in range (1, 10): if k <= n: res.append(k) print_numbers(k*10, n) return res a = Solution() print a.lexicalOrder(50)
class Solution: def spiralOrder(self, matrix): def spiral(d,i,j): result.append(matrix[i][j]) temp[i][j] = matrix[i][j] if d == 'right': if j == n-1 or temp[i][j+1] != '.': d = 'down' i += 1 else: j += 1 elif d == 'down': if i == m-1 or temp[i+1][j] != '.': d = 'left' j -= 1 else: i += 1 elif d == 'left': if j == 0 or temp[i][j-1] != '.': d = 'up' i -= 1 else: j -= 1 elif d == 'up': if i == 0 or temp[i-1][j] != '.': d = 'right' j += 1 else: i -= 1 if len(result) < m*n: return spiral(d,i,j) result = [] if len(matrix) > 0: m = len(matrix) n = len(matrix[0]) temp = [['.' for x in range(n)] for x in range(m)] spiral('right',0,0) return result a = Solution() print a.spiralOrder([[1,2,3],[4,5,6],[7,8,9]])
class Solution: def canCompleteCircuit(self, gas, cost): if sum(gas) < sum(cost): return -1 else: tank = 0 i = 0 result = 0 while True: tank += gas[i]-cost[i] if i == len(gas)-1: return result i += 1 if tank < 0: tank = 0 result = i a = Solution() print a.canCompleteCircuit([0,1,0,3],[1,1,1,1])
class Solution: def mySqrt(self, x): low = 0 high = x if x < 2: return x while low < high-1: mid = (low+high)//2 if mid**2 == x: return mid elif mid**2 > x: high = mid else: low = mid return low a = Solution() print a.mySqrt(1)
class Solution: def findMin(self, nums): low = 0 high = len(nums)-1 if nums[0] < nums[-1]: return nums[0] while low < high-1: mid = (low+high)//2 if nums[mid] < nums[-1] or nums[mid] < nums[0]: high = mid elif nums[mid] > nums[-1] or nums[mid] > nums[0]: low = mid else: return min(nums[low:high+1]) return nums[high] a = Solution() print a.findMin([1])
class Bike: list_of_bikes = [] rate = 0 bill = 0 def __init__(self,stock,bikes_requested): self.stock = stock self.bikes_requested = bikes_requested def price_of_bikes(self,type_of_rate): if type_of_rate == "hourly": Bike.rate = 5 elif type_of_rate == "daily": Bike.rate = 20 elif type_of_rate == "weekly": Bike.rate = 60 return Bike.rate def get_bill(self): total = 0 for item in Bike.list_of_bikes: total += item Bike.bill = total return Bike.bill def discount(self,bill,family_members, rentals): if family_members >= 5 and rentals >=3 or rentals <= 5: Bike.bill = Bike.bill * 0.70 return Bike.bill def main(): num_family_members = int(input("How many members in your group are renting bikes?\nFamilies of 5 or greater, renting between 3 and 5 bikes get 30% off: ")) check_if_bike_available = True while check_if_bike_available: inputStock = int(input("How many bikes would you like?: ")) bike = Bike(25,inputStock) if inputStock > bike.stock: print("Sorry, we don't have that many bikes") print("The amount of available bikes is {}".format(bike.stock)) else: break amount_bikes = 1 i = 0 while i < inputStock: rate_of_bikes = input("For bike {}, enter either hourly,weekly, or monthly to choose what type of rental you want: ".format(amount_bikes)) how_long_customer_wants_bike = int(input("How long do you want bike {} for?: ".format(amount_bikes))) getBike = bike.price_of_bikes(rate_of_bikes) * how_long_customer_wants_bike Bike.list_of_bikes.append(getBike) amount_bikes += 1 i+=1 get_bikes_bill = bike.discount(bike.get_bill(),num_family_members,inputStock) print(Bike.list_of_bikes) print(get_bikes_bill) if __name__ == '__main__': main()
from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt import pandas as pd import numpy as np def create_data(): df = pd.read_excel("../dataset/GDP_original.xlsx") df = df.fillna(value=0) year_GDP = {"Year" : "million_dollars"} for row in range(2, 2+9): year_GDP[int(df.iloc[row][0])-1911] = df.iloc[row][1] # 指定orient='index'使用字典鍵作為行來創建DataFrame pd.DataFrame.from_dict(data=year_GDP, orient='index').to_excel('../dataset/GDP.xlsx', header=False) def draw_2D_graph(): plt.style.use('classic') gdp_data = pd.read_excel("../dataset/GDP.xlsx") crime_data = pd.read_excel("../dataset/犯罪事件.xlsx") ##GDP & crime plt.figure() fig, ax1 = plt.subplots() #標題 plt.suptitle('GDP vs crime') #X軸名稱 ax1.set_xlabel('Year') #直方圖及左側Y軸名稱 ax1.bar(crime_data.iloc[:,0], crime_data.iloc[:,1], color='steelblue', label='crime(left)') ax1.tick_params('y', colors='darkslategray') #相同x軸 ax2 = ax1.twinx() #折線圖及右側Y軸名稱 ax2.plot(gdp_data.iloc[:,0], gdp_data.iloc[:,1], color='maroon', label='GDP(right)') ax2.tick_params('y', colors='maroon') #圖例 ax1.legend(loc='upper left', shadow=True) ax2.legend(loc='upper center', shadow=True) plt.show() def draw_3D_graph(): df_GDP = pd.read_excel('../dataset/GDP.xlsx') df_Crime = pd.read_excel('../dataset/犯罪事件.xlsx') #設定key key_GDP = df_GDP.keys()[1] key_Crime = df_Crime.keys()[1] #資料集裡的最小值 min_GDP = min(df_GDP[key_GDP]) min_Crime = min(df_Crime[key_Crime]) #將資料以百分比的方式呈現 av_GDP = (max(df_GDP[key_GDP]) - min_GDP) / 100 av_Crime = (max(df_Crime[key_Crime]) - min_Crime) / 100 for i in range(9): df_GDP[key_GDP][i] = (df_GDP[key_GDP][i]-min_GDP)/av_GDP df_Crime[key_Crime][i] = (df_Crime[key_Crime][i]-min_Crime)/av_Crime #轉換成 ndarray df_GDP_np = df_GDP[key_GDP].to_numpy() df_Crime_np = df_Crime[key_Crime].to_numpy() data = np.array([df_GDP_np, df_Crime_np],dtype=int) # 保持間隔的命名 column_names = range(99,110,2) row_names = ['','','GDP','','','','Crime','',''] fig = plt.figure() # 三維的軸 ax = Axes3D(fig) # x, y軸的資料量 len_x, len_y = 9, 2 # 用描述資料大小 xpos = np.arange(0,len_x,1) ypos = np.arange(0,len_y,1) xpos, ypos = np.meshgrid(xpos, ypos) # 攤平資料,變成一維 xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(len_x * len_y) # 資料間隔 dx = 0.75 * np.ones_like(zpos) dy = dx.copy() dz = data.flatten() # 用顏色標示資料間的差異 colors = plt.cm.jet(data.flatten()/float(data.max())) ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color = colors, alpha = 0.4) # alpha為透明度 # x, y軸的標示 ax.w_xaxis.set_ticklabels(column_names) ax.w_yaxis.set_ticklabels(row_names) ax.set_xlabel('Year') ax.set_ylabel('Data') ax.set_zlabel('%') plt.show() #create_data() #draw_2D_graph() draw_3D_graph()
import random def create_matrix(columns:int, rows: int): """ Testea la funcion que crea una matriz: - Creando una matriz randomizada (utilizando seed) >>> random.seed(5) >>> columns = 5 >>> rows = 5 >>> create_matrix(columns, rows) [[5, 3, 3, 5, 1], [4, 2, 1, 2, 1], [3, 4, 2, 4, 5], [1, 5, 2, 1, 2], [4, 3, 2, 4, 2]] - Accediendo a una posicion de una matriz creada >>> random.seed(5) >>> matriz = create_matrix(columns, rows) >>> matriz[0][4] 1 - Accediendo a una posicion inexistente de una matriz creada >>> matriz = create_matrix(columns, rows) >>> matriz[3][6] Traceback (most recent call last): ... IndexError: list index out of range """ matrix = [[random.randint(1, 5) for x in range(columns)] for y in range(rows)] return matrix def find_sequence(matrix: list, sequence: int): """ Testea la funcion que halla una secuencia: - Buscando una secuencia de 4 en una matriz que no posee ninguna >>> columns = 5 >>> rows = 5 >>> sequence = 4 >>> random.seed(5) >>> find_sequence(create_matrix(columns, rows), sequence) -1 - Buscando una secuencia de 4 en una matriz que posee una horizontal >>> matriz_prueba_horizontal = [[5, 3, 1, 5, 1], [4, 2, 2, 2, 1], [3, 4, 3, 4, 5], [1, 5, 4, 1, 2], [4, 3, 2, 4, 2]] >>> find_sequence(matriz_prueba_horizontal, sequence) {'initial': [0, 2], 'final': [3, 2]} - Buscando una secuencia de 4 en una matriz que posee una horizontal >>> matriz_prueba_vertical = [[5, 3, 4, 5, 1], [4, 2, 1, 2, 1], [3, 4, 3, 4, 5], [1, 1, 2, 3, 4], [4, 3, 2, 4, 2]] >>> find_sequence(matriz_prueba_vertical, sequence) {'initial': [3, 1], 'final': [3, 4]} """ #esta solucion funciona solo cuando la cantidad de filas es la misma que de columnas for x in range(len(matrix)): y = 0 while (y <= len(matrix[x]) - sequence): found_vertical = 1 #cantidad de numeros consecutivos encontrados en la iteracion found_horizontal = 1 #buscando verticalmente aux_index = y while (found_vertical < sequence) and (matrix[x][aux_index] == matrix[x][aux_index + 1] - 1): aux_index += 1 found_vertical += 1 if(found_vertical == sequence): #si while corta por hallar 4 consecutivos return {"initial": [x, y], "final": [x, aux_index]} #buscando horizontalmente aux_index = y while (found_horizontal < sequence) and (matrix[aux_index][x] == matrix[aux_index + 1][x] - 1): aux_index += 1 found_horizontal += 1 if(found_horizontal == sequence): #si while corta por hallar 4 consecutivos return {"initial": [y, x], "final": [aux_index, x]} y += 1 return -1 if(__name__ == "__main__"): import doctest doctest.testmod(verbose=True)
# coding=utf-8 from collections import defaultdict import random from environment import * import matplotlib.pyplot as plt Q_PERIOD = 3 class Q_Agent(): def __init__(self, actions, epsilon=0, discount=1, alpha=0.8): self.actions = actions self.game = Game() self.Q = defaultdict(float) self.initial_epsilon = epsilon self.discount = discount self.alpha = alpha def select_action(self, state): # Exploration and Exploitation if random.random() < self.epsilon: return np.random.choice(self.game.action_space.n) qValues = [self.Q.get((state, action), 0) for action in self.actions] if qValues[0] < qValues[1]: return 1 elif qValues[0] > qValues[1]: return 0 else: return np.random.choice(self.game.action_space.n) def update_Q(self, state, action, reward, next_state): """Update the Q value based on Q-Learning""" next_Q = [self.Q.get((next_state, a), 0) for a in self.actions] best_value = max(next_Q) self.Q[(state, action)] = self.Q.get((state, action), 0) + self.alpha * \ (reward + self.discount * best_value - self.Q.get((state, action), 0)) def train(self, n_iters, n_iters_eval): """ Train the agent""" self.game.seed(random.randint(0, 100)) done = False max_scores = [0] avg_scores = [0] for i in range(n_iters): self.epsilon = self.initial_epsilon sars_list = [] for j in range(Q_PERIOD): score = 0 total_reward = 0 ob = self.game.reset() state = self.game.getGameState() while True: action = self.select_action(state) next_state, reward, done, _ = self.game.step(action) sars_list.append((state, action, reward, next_state)) state = next_state total_reward += reward if reward >= 1: score += 1 if done: break for (state, action, reward, next_state) in sars_list: self.update_Q(state, action, reward, next_state) if i % 250 == 0: print("Iter: ", i) # Evaluate the model after every 500 iterations if (i + 1) % 500 == 0: max_score, avg_score = self.evaluate(n_iter=n_iters_eval) max_scores.append(max_score) avg_scores.append(avg_score) draw_graph(max_scores, avg_scores, n_iters) self.game.close() def evaluate(self, n_iter): """evaluates the agent""" self.epsilon = 0 self.game.seed(0) max_score = 0 results = defaultdict(int) for i in range(n_iter): score = 0 total_reward = 0 ob = self.game.reset() state = self.game.getGameState() while True: action = self.select_action(state) state, reward, done, _ = self.game.step(action) total_reward += reward if reward >= 1: score += 1 if done: break results[score] += 1 if score > max_score: max_score = score self.game.close() avg_score = sum([k*v for (k, v) in results.items()]) / n_iter print("Max Score on Evaluation: ", max_score) print("Average Score on Evaluation: ", avg_score) return max_score, avg_score def draw_graph(max_scores, avg_scores, iter_num): x = np.arange(0, iter_num + 1, step=500) x_ticks = np.arange(0, iter_num + 1, step=2000) plt.plot(x, max_scores, color="red", label="Max Scores") plt.plot(x, avg_scores, color="darkviolet", linestyle="dashed", label="Average Scores") plt.legend(loc="upper left") plt.xticks(x_ticks) plt.xlabel('Number of Iterations') plt.ylabel('Scores') plt.title('Forward Q-Learning & No ϵ-Greedy') plt.savefig('figures/graph.png', bbox_inches='tight') plt.close() if __name__ == '__main__': agent = Q_Agent(actions=[0, 1]) agent.train(20000, 100)
#creando la lista vacia listaRegistro = [] clientes = 0 clientela = int(input("Clientes a ingresar: ")) costoTotal=0 while clientes < clientela: cliente = input("nombre del cliente: ") producto = input("nombre del producto: ") costo = float(input("costo($0.00): ")) #registro: {"cliente": cliente, "producto": producto, "costo": costo} registro = dict(cliente=cliente, producto=producto, costo=costo) #print(registro) #print(type(registro)) #agregar nuevo elemento a una lista listaRegistro.append(registro) #dejar de ocupar la variable registro #registro=none clientes += 1 for registro in listaRegistro: costoTotal+=registro.get("costo") print(registro) print("El costo total de los productos es de: "+ str(costoTotal))
########### This program to indicate whether a point is within a city's borders on a 2-dimensional grid (X and Y axes) or not ############## import csv from collections import defaultdict import numpy as np import os.path def ReadaingCitiesCoordinatesFromCSV(): columns = defaultdict(list) # get the list of cities from the csv file with open('cities.csv', 'r') as csvfile: reader = csv.DictReader(csvfile) # read rows into a dictionary format for row in reader: # read a row as {column1: value1, column2: value2,...} for (k, v) in row.items(): # go over each column name and value columns[k].append(v) # append the value into the appropriate list column_name = columns['Name'] column_TopLeft_X = list(map(int,columns['TopLeft_X'])) column_TopLeft_Y = list(map(int,columns['TopLeft_Y'])) column_BottomRight_X= list(map(int,columns['BottomRight_X'])) column_BottomRight_Y = list(map(int,columns['BottomRight_Y'])) return column_name, column_TopLeft_X ,column_TopLeft_Y,column_BottomRight_X, column_BottomRight_Y def ReadaingPointsCoordinatesFromCSV(): columns = defaultdict(list) # get the list of points from the csv file with open('points.csv', 'r') as csvfile: reader = csv.DictReader(csvfile) # read rows into a dictionary format for row in reader: # read a row as {column1: value1, column2: value2,...} for (k, v) in row.items(): # go over each column name and value columns[k].append(v) # append the value into the appropriate list column_ID = columns['ID'] column_X = list(map(int,columns['X'])) column_Y = list(map(int,columns['Y'])) return column_ID,column_X,column_Y #### concatenate the x coordinates list and y coordinates list in single list def Concatenate_X_Y_Coordinates(X,Y): #X = X coordinate , Y = Y coordinate concatenateList = (np.column_stack((X,Y))).tolist() return concatenateList #### sort the cities based on the closest one to the origin point def SortCities(FirstPointList,SecondPointList,NameList): # NameList : cities Names , FirstPointList : TopLeft Coordinates , SecondPointList : BottomRight Coordinates FirstPointList, SecondPointList , NameList = zip(*sorted(zip(FirstPointList,SecondPointList,NameList))) return FirstPointList,SecondPointList,NameList #### Check whether a given point inside a rectangle or not def CheckPointInsideRectangleOrNot(X_Point,Y_Point,X_TOPLEFT,X_BOTTOMRIGHT,Y_TOPLEFT,Y_BOTTOMRIGHT): #X_Point , Y_Point : coordinates of point #X_TOPLEFT,Y_TOPLEFT,X_BOTTOMRIGHT,Y_BOTTOMRIGHT : coordinates of city (Boundary of rectangle ) if ((X_TOPLEFT <= X_Point <= X_BOTTOMRIGHT) and (Y_TOPLEFT <= Y_Point <= Y_BOTTOMRIGHT )): Flag = True else: Flag = False return Flag def WritingOutputToCSV(id,x,y,city): file_exists = os.path.isfile("output_points.csv") with open("output_points.csv", "a", newline='', encoding='utf-8') as resultFile: # open input file for reading # writer = csv.writer(resultFile) writer = csv.DictWriter(resultFile, fieldnames=["ID","X","Y","CityName"]) if not file_exists: writer.writeheader() # file doesn't exist yet, write a header spamwriter = csv.writer(resultFile) spamwriter.writerow([id,x,y,city]) resultFile.close() ##### Reading Cities Coordinates from csv CityNameLists,TopLeft_XList,TopLeft_YList,BottomRight_XList,BottomRight_YList = ReadaingCitiesCoordinatesFromCSV() #### Reading Points Coordinates from csv PointID,Point_XList,Point_YList = ReadaingPointsCoordinatesFromCSV() #### creating TopLeft list consists of all points of cities on the TopLeft corner TopLeftLists = Concatenate_X_Y_Coordinates(TopLeft_XList,TopLeft_YList) #### creating Bottom Right list consists of all points of cities on the BottomRight corner BottomRightLists = Concatenate_X_Y_Coordinates(BottomRight_XList,BottomRight_YList) #### sorting the TopLeftList, BottomRightList and CityNameList TopLeftLists,BottomRightLists,CityNameLists = SortCities(TopLeftLists,BottomRightLists,CityNameLists) PointsLists = Concatenate_X_Y_Coordinates(Point_XList,Point_YList) #### iterate on all given points for point_list,ID in zip(PointsLists,PointID): #this list that will contain all cities that belongs to point ListOfCitiesContainingPoint = [] ### Read the coordinates (x,y) of given point Point_X = point_list[0] Point_Y = point_list[1] #### read the coordinates (x,y) of city for TopLeft_List,BottomRight_List,CityName in zip(TopLeftLists,BottomRightLists,CityNameLists): #Flag to check if the list that contains cities that belongs to point is empty or not FlagListOfCities = False X_Top = TopLeft_List[0] Y_Top = TopLeft_List[1] Y_Bottom = BottomRight_List[1] X_Bottom = BottomRight_List[0] #check if the city is within this rectangle or not CheckFlag = CheckPointInsideRectangleOrNot(Point_X,Point_Y,X_Top,X_Bottom,Y_Top,Y_Bottom) #check if the point in the current city if CheckFlag == True: #if the city contains the point append the city to the list ListOfCitiesContainingPoint.append(CityName) FlagListOfCities = True continue #check if the point in the next city or not if (CheckFlag == False) and (FlagListOfCities == True): break #check if the point don't belong to any city so append a "None " to the list if not(ListOfCitiesContainingPoint): ListOfCitiesContainingPoint.append("None") if len(ListOfCitiesContainingPoint) == 1: ListOfCitiesContainingPoint = ListOfCitiesContainingPoint[0] WritingOutputToCSV(ID,Point_X,Point_Y,ListOfCitiesContainingPoint)
#!/bin/python3 import math import os import random import re import sys # Complete the candies function below. def candies(n, arr): for e in range(len(arr)): if e==0: ans=1 peek=1 last=1 acc=0 else: if(arr[e]>arr[e-1]): last+=1 peek=last ans+=last acc=0 elif(arr[e]==arr[e-1]): peek=1 acc=0 last=1 ans+=1 else: last=1 acc+=1 if(acc==peek): peek+=1 ans+=1 ans+=acc return int(ans) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = [] for _ in range(n): arr_item = int(input()) arr.append(arr_item) result = candies(n, arr) fptr.write(str(result) + '\n') fptr.close()
def identificarcarta(x): if x=="T" or x=="J" or x=="Q" or x=="K" or x=="A": return 10 else: return int(x) t=1 casos=int(input()) while t<=casos: Y=0 buscador=26 x=input() x=x.split() card=identificarcarta(x[buscador][0]) Y+=card buscador-=10-card+1 card=identificarcarta(x[buscador][0]) Y+=card buscador-=10-card+1 card=identificarcarta(x[buscador][0]) Y+=card buscador-=10-card if Y>(buscador): Y=x[32] else: Y=x[Y-1] print ("Case "+str(t)+": "+Y) t+=1
import random chance = 1 max_chance = 10 rand_value = random.randint(1, 1000) while chance <= max_chance: try: print('Chance :', chance) user_value = int(input('enter the value :')) except ValueError as err: print('invalid input, retrying......\n') continue if user_value == rand_value: print('you won :) !!!!!!!!') break elif user_value < rand_value: print(user_value, ': lesser') else: print(user_value, ': greater') chance += 1 print() else: print('you lost :(............')
"""http request with proxies""" import requests def get_proxies(): proxies = dict( http='http://user:passwd@isas.danskenet.net:80', https='http://user:passwd@isas.danskenet.net:80', ) return proxies if __name__ == '__main__': url = 'http://google.com' response = requests.get(url) #proxies=get_proxies()) print(response.status_code) print() print(response.headers) print() print(response.content)
"""sort or reverse""" temp = [3.3, 2.2, 0.98, 0.12, 3.3, 2.2, 0.98, 0.12, 3.3, 2.2, 0.98, 'peter'] temp.reverse() # inplace edit print(temp)
import os import re def count_word(): """ 统计总字数 :return: """ dirname = '章节' filenames = os.listdir('章节') count = 0 for name in filenames[:]: with open(os.path.join(dirname, name), 'r', encoding='utf8') as f: words = re.findall('[\u4e00-\u9fa5]', f.read()) count += len(words) return count if __name__ == '__main__': print(count_word()) pass
# 반례를 생각하지 못했다 - 합친 카드 팩과 다른 것을 비교할때 다른 두개가 더 작을경우 # 그 두개 먼저 비교해야하는데 그 경우를 생각하지 못했다. # 시간복잡도가 너무 크게나와 우선순위 큐를 힙으로 구현하여 사용하기로 했다. import sys import heapq N = int(input()) data = [] for i in range(N): heapq.heappush(data, int(sys.stdin.readline())) result = 0 if len(data) == 1: # data 가 1개일 경우 비교할 필요 없음 print(0) else: while len(data) > 1: temp_1 = heapq.heappop(data) temp_2 = heapq.heappop(data) result += temp_1+temp_2 heapq.heappush(data, temp_1+temp_2) print(result)
def person_print(name, last_name, *others, age): formatted_data = 'Imię: {}, nazwisko: {}, wiek: {}'.format(name, last_name, age) others_str = ' ' for arg in others: others_str += arg + ' ' print(formatted_data + others_str) person_print('Jan', 'Kowal', 'pesel: 90122413426', age=33) # Wniosek: Funkcje z zadania można wywołać bez błędu bez wprowadzania w niej zmian.
# Input function lets you input a string into the variable string = input("Please enter a string: ") i = 0 stringrev = "" #print prints to the console print(string) stringlen = len(string) j = stringlen print(stringlen) #reverses the string into the stringrev for i in range(0, stringlen): stringrev += string[j - 1] j = j - 1 print(stringrev) #makes both lower case so that it can compare wothout case stringrev = stringrev.casefold() string = string.casefold() if(string == stringrev): print("Is a palindrome") else: print("Not a palindrome")
# print("你好,世界!") # day01 复习 # Python 简介 # python执行方式 # 交互式:在终端中输入指令,回车即可得到结果 # 文件式:将指令存放在.py的文件中,可以重复执行 # Python执行过程 # 编译:运行前,将源代码转换为机器码,例如:C语言 # 优势:运行速度快 # 劣势:开发效率低 # 解释:运行时,逐行翻译执行,例如JavaScript # 劣势:运行速度慢 # 优势:开发效率高 # 运行时 # 源代码 -“编译”- 字节码 -解释-》 机器码 # 第一次 class A: a=1 obj=A() obj.a=2 print(obj.a)
import math def findMaximum(arr, mid): # Caso chegue em um ponto no qual arr[mid] é maior que ambos os elementos adjacente if arr[mid] > arr[mid + 1] and arr[mid] > arr[mid - 1]: return arr[mid] # Se o arr[mid] é maior que o próximo elemento e menor que o elemento anterior if arr[mid] > arr[mid + 1] and arr[mid] < arr[mid - 1]: return findMaximum(arr, math.floor(mid/2)) else: # Se o arr[mid] é menor que o próximo elemento e maior que o elemento anterior. return findMaximum(arr, math.floor((mid+len(arr)/2)-1)) arr = [1, 3, 10, 20, 30, 50, 60] n = len(arr) print ("O ponto máximo p é: %d"% findMaximum(arr, math.floor(n/2)))
def trifeca(word): """ Checks whether word contains three consecutive double-letter pairs. word: string returns: bool """ double = 0 ind = 0 while ind < (len(word)-1): if word[ind] == word[ind+1]: double = double+1 ind = ind+2 else: ind = ind+1 double = 0 if double >= 3: return True return False
phone=input("请输入手机号") list=[151,186,153,139,156,187] try: int(phone) if(len(phone)==11): head=phone[:3] bool=False for i in list: if(int(head)==(i)): bool=True break if(bool): print("合格") else: print("不合格") else: print("不合格") except ValueError: print("不合格")
# my_list = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] # # my_list="hello" # print(len(my_list)) # print(my_list[0:-1]) # a = [1, 2, 3] # b = (5, 6, 7) # u, s, t = b # x, y, z = a # print(x) # print(y) # print(z) # print(u) # print(s) # print(t) # # a = [1,2,3] # del a[0] # print(a) # # b = 56 # del b # print(b) # a = [1, 5, 7, 0] # # a.sort() # # print(a) # # print(sorted(a)) # print(a) a = [item for item in range(20) if item % 2 == 0] print(a)
# 5.9 (Palindrome Tester) A string that’s spelled identically backward and forward, like # 'radar', is a palindrome. Write a function is_palindrome that takes a string and returns # True if it’s a palindrome and False otherwise. Use a stack (simulated with a list as we did # in Section 5.11) to help determine whether a string is a palindrome. Your function should # ignore case sensitivity (that is, 'a' and 'A' are the same), spaces and punctuation. client_word = input("Enter a word: ") new_client_word = client_word[::-1] if client_word == new_client_word: print("the word is a palindrome") else: print("the word is not a palindrome")
import os def main( argv ): """Main entry point for processing the file.""" if ( len(argv) > 1 ): text_filename = argv[1] if ( os.path.exists(text_filename) and os.path.isfile(text_filename) ): print("Opening file...") file_object = open(text_filename, 'r') lines = file_object.readlines() new_list = list(map(lambda x: x.strip('\n'),lines)) # print(new_list) comma_separated_string_list = list(map(lambda x: x.replace(' ', ','),new_list)) print(comma_separated_string_list) #final output should be comma separated with new line for each row for item in comma_separated_string_list: print(item) else: exit() else: print("Insufficient parameters!") exit() if __name__ == '__main__': import sys sys.exit(main( sys.argv ))
''' used to pass a keyworded, variable-length argument list A keyword argument is where you provide a name to the variable as you pass it into the function. One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. **kwargs differs from *args in that you will need to assign keywords to the arguments ''' def myFun(**kwargs): for key, value in kwargs.items(): print("%s == %s" % (key, value)) myFun(first='Geeks', mid='for', last='Geeks') #theres no positional order in which the items are output as in a list def print_values(**kwargs): for key, value in kwargs.items(): print("The value of {} is {}".format(key, value)) print_values(my_name="Sammy", your_name="Casey") #Using *args and **kwargs to call a function def myFun(arg1, arg2, arg3): print("arg1:", arg1) print("arg2:", arg2) print("arg3:", arg3) # Now we can use *args or **kwargs to # pass arguments to this function : args = ("Geeks", "for", "Geeks") myFun(*args) kwargs = {"arg1": "Geeks", "arg2": "for", "arg3": "Geeks"} myFun(**kwargs)