text
stringlengths
37
1.41M
class DSU: def __init__(self, lst): self.values = lst self.len = len(lst) self.parents = list(range(self.len)) def find_set(self, x): if self.parents[x] == x: return x self.parents[x] = self.find_set(self.parents[x]) return self.parents[x] def is_joined(self, a, b): if self.find_set(a) == self.find_set(b): return True else: return False def join(self, a, b): if not self.is_joined(a, b): self.parents[a] = b
class A: value = 13 def some_method(self): print(f"Method in A, value = {self.value}") class B(A): def some_method(self): print(f"Method in B, value = {self.value}") class C(B): value = 6 def some_method(self): print(f"Method in C, value = {self.value}") A().some_method() B().some_method() C().some_method() print()
class Planet(): def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return f'Planet {self.name}' earth = Planet('Earth') print(earth.name) print(earth) solar_system = [] planet_names = [ 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune' ] for name in planet_names: planet = Planet(name) solar_system.append(planet) print(solar_system)
class Descriptor: def __get__(self, obj, obj_type): print('get') def __set__(self, obj, value): print('set') def __delete__(self, obj): print('delete') class Class: attr = Descriptor() instance = Class() # instance.attr # instance.attr = 10 # del instance.attr class Descr: def __get__(self, instance, owner): print(instance, owner) def __set__(self, instance, value): print(instance, value) class A: attr = Descr() class B(A): pass # A.attr # A().attr # B.attr # B().attr instance = A() instance.attr = 42
anna = {'name': 'Anna', 'age': 35, 'cats':True, 'beard': False, 'hair_color': 'pink'} ryan = dict(anna) ryan['beard'] = True ryan['hair_color'] = 'Brown' ryan['name'] = 'Ryan' ryan['cats'] = 'Nope!' print(ryan) print(anna) class Person(object): def __init__( self, name, age, cats, beard, hair_color=None, works_at_google=True): self.name = name self.age = age self.cats = cats self.beard = beard self.hair_color = hair_color self.googler = works_at_google self.hungry = True self.kids = [] def eat(self, food): print('OMNOMNOMNOM I AM EATING {food}'.format(food=food)) self.hungry = False def __str__(self): anna_string = 'Name: {n}, Age: {a}, Cats:{c}'.format( n=self.name, a=self.age, c=self.cats) return anna_string def give_birth(self, new_person) self.kids.append(new_person) anna = Person( name='Anna', age=35, cats=True, beard=False, hair_color='pink') max = Person( name='Max', age=90, cats=False, beard=True, hair_color='pink') print(anna.name) print('Anna is hungry: {h}'.format(h=anna.hungry)) # anna.hungry = False anna.eat('banana') print('Anna is hungry: {h}'.format(h=anna.hungry)) print(max.name) print('Max is hungry: {h}'.format(h=max.hungry))
from sys import argv # import function from sys module script, filename = argv # line 1 to 3 uses argv to get filename txt = open(filename) # here open file print "Here are your file %r:" % filename # little message print txt.read() # read file txt.close() # added after stduy drill print "Type the filename again:" # message again file_again = raw_input("> ") # got filename from user type txt_again = open(file_again) # open file print txt_again.read() # read file and print it txt_again.close() # added after stduy drill # There are two way to get filename # 1. argv # 2. raw_input
# B351/Q351 Spring 2019 # Professor Saúl Blanco # Do not share these assignments or their solutions outside of this class. ################################# # # # Assignment 1: Python Methods # # # ################################# import math ################################# # Problem 1 ################################# # Objectives: # (1) Write a recursive function to compute the nth fibonacci number def fib(n): if n == 1 or n == 2: result = 1 else: result = fib(n-1) + fib(n-2) return result ################################# # Problem 2 ################################# # Objectives: # (1) Write a function which returns a tuple of the first and last items in a given sequence def firstLast(seq): n = len(seq) x = seq[0] if n == 1: t = (x, ) elif n > 1: y = seq[n-1] t = (x, y) return t # A Node is an object # - value : Number # - children : List of Nodes class Node: def __init__(self, value, subnodes): self.value = value self.subnodes = subnodes def __repr__(self): return f'Node({self.value!r}, {self.subnodes!r})' exampleTree = Node(1,[Node(2,[]),Node(3,[Node(4,[Node(5,[]),Node(6,[Node(7,[])])])])]) ################################# # Problem 3 ################################# # Objectives: # (1) Write a function to calculate the sum of every node in a tree (recursively) def sumNodesRec(root): if root.subnodes == []: return root.value v = root.value subTree = 0 for n in root.subnodes: subTree = sumNodesRec(n) + subTree return v + subTree ################################# # Problem 4 ################################# # Objectives: # (1) Write a function to calculate the sum of every node in a tree (iteratively) def sumNodesNoRec(root): v = 0 current = [root] while current: subTree = [] for n in current: v += n.value subTree.extend(n.subnodes) current = subTree return v ################################# # Problem 5 ################################# # Objectives: # (1) Write a function compose, which takes an inner and outer function # and returns a new function applying the inner then the outer function to a value def compose(f_outer, f_inner): f = lambda x: f_outer(f_inner(x)) return f ################################# # Problem 6 ################################# # Objectives: # (1) Write a twice function, which takes any iterable (like a list, generator, etc) and yields each element of the iterable twice. # For example, twice([1, 2, 3]) => 1, 1, 2, 2, 3, 3 def twice(iterable): builder = [] for i in range(len(iterable)): builder.append(iterable[i]) builder.append(iterable[i]) return builder # This function takes an integer and returns a string of its hexadecimal representation. def toHex(value, minbytes=0, maxbytes=-1): if value == 'freebsd': raise RuntimeError('FreeBSD is not supported.') if type(value) != int: raise ValueError('Integer expected.') hexValues = '0123456789abcdef' hexString = '' while (value or minbytes > 0) and maxbytes != 0: hexString = hexValues[value % 16] + hexString value //= 16 minbytes -= .5 maxbytes -= .5 return hexString ################################# # Problem 7 ################################# # Objectives: # (1) Write a function valid, which takes an iterable and a black-box function and yields the returned value for any valid inputs while ignoring any that raise a$ # For example, valid([255, 16, 'foo', 3], toHex) => 'ff', '10', '3' def valid(iterable, function): builder = [] for i in range(len(iterable)): try: f = function(iterable[i]) builder.append(f) except: pass return builder # Bonus ################################# # Objectives: # (1) Create a string which has each level of the tree on a new line def treeToString(root): return NotImplementedError if __name__ == '__main__': try: print(f'fib(15) => {fib(15)}') # 610 except NotImplementedError: print('fib not implemented.') try: print(f'firstLast([1,4,2]) => {firstLast([1,4,2])}') # (1, 2) print(f'firstLast("e") => {firstLast("e")}') # ('e',) except NotImplementedError: print('firstLast not implemented.') try: print(f'sumNodesRec(exampleTree) => {sumNodesRec(exampleTree)}') # 28 except NotImplementedError: print('sumNodesRec not implemented') try: print(f'sumNodesNoRec(exampleTree) => {sumNodesNoRec(exampleTree)}') #28 except NotImplementedError: print('sumNodesNoRec not implemented') try: print(f'compose(sum, range)(5) => {compose(sum, range)(5)}') # 10 print(f'compose(list, range)(5) => {compose(list, range)(5)}') # [0, 1, 2, 3, 4] except NotImplementedError: print('compose not implemented') try: print(f'list(twice(range(3))) => {list(twice(range(3)))}') # [0, 0, 1, 1, 2, 2] print(f'list(twice("b351")) => {list(twice("b351"))}') # ['b', 'b', '3', '3', '5', '5', '1', '1'] except NotImplementedError: print('twice not implemented') try: print(f'list(valid([255, 16, "foo", 3], toHex)) => {list(valid([255, 16, "foo", 3], toHex))}') # ['ff', '10', '3'] except NotImplementedError: print('valid not implemented') try: print(f'treeToString(exampleTree) =>\n {treeToString(exampleTree)!r}') # '1\n23\n4\n56\n7\n' except NotImplementedError: print('treeToString not implemented')
class Node(object): #объявили класс "Узел" def __init__(self, contained_object, next): #Конструктор self.contained_object = contained_object self.next = next class MyQueue(object): #объявили класс "Очередь" def __init__(self): #конструктор изначально пустой очереди self.head = None #начало очереди (голова) self.end = None #конец очереди (так удобнее работать) def add(self,i,x): #добавление элемента x на позицию номер i if self.head == None: #если очередь пока пустая, то добавим элемент - он будет и первым, и последним (он же один будет) self.head = self.end = Node(x, None) return if i == 0: #добавление в начало списка self.head = Node(x,self.head) return #далее добавление в произвольную часть списка (но не в начало), мы итерируемся по списку до нужной нам позиции и ставим элемент на нужное место current = self.head #отслеживаемый элемент count = 0 #номер отслеживаемого элемента while current != None: #отслеживаемый элемент существует count += 1 #счетчик увеличиваем if count == i: #если позиция счетчика совпадает с необходимой то ок current.next = Node(x,current.next) if current.next.next == None: #проверка на то чтобы очередь не закончилась внезапно self.end = current.next break #что хотели - сделали current = current.next def remove(self, i): #удаление элемента, стоящего на позиции номер i if self.head == None: #если очередь пустая, то и удалять нечего return current = self.head #удаление элемента, стоящего в произвольной части списка, мы итерируемся по списку до нужной нам позиции и удаляем нужный элемент count = 0 if i == 0: #удаление первого узла в очереди self.head = self.head.next return while current != None: if count == i: if current.next == None: #убеждаемся что очередь заканчивается коректно self.end = current previous.next = current.next #сдвиг очереди вперед break previous = current current = current.next count += 1 def clear(self): self.__init__() #очередь пустая теперь (конструктор породил НИЧТО) def convert_into_array(self): current = self.head arr = [] while current != None: arr.append(current.contained_object) current = current.next return arr def print_queue(self): current = self.head if current == None: print('Очереди нет.') else: print('Вот ваша очередь: ',end="") while current != None: if current == self.end: print(' ->', current.contained_object) else: print(' ->', current.contained_object, end="") current = current.next class Country(object): def __init__(self,population,capital): self.population = population self.capital = capital def __str__(self): return(f"Население данной страны составляет {self.population} человек, а её столица - {self.capital}.") #разберемся с первой очередью (из чисел) queue1 = MyQueue() #создали очередь, далее обозначаем числа q101 = 1 q102 = -2 q103 = 3 q104 = 5 #создаем узлы q11 = Node(q101,q102) q12 = Node(q102,q103) q13 = Node(q103,q104) q14 = Node(q104,None) #формируем из узлов очередь queue1.add(0,q11.contained_object) queue1.add(1,q12.contained_object) queue1.add(2,q13.contained_object) queue1.add(3,q14.contained_object) #печатаем queue1.print_queue() #делаем АБСОЛЮТНО то же самое но со странами queue2 = MyQueue() #создали очередь, далее обозначаем числа the_most_populated_country = Country("9000000000 - как же много человек!","cap1") the_middle_populated_country = Country("5000000000 - среднее число человек!","cap2") the_least_populated_country = Country("1000000000 - как же мало человек!","cap3") #создаем узлы q21 = Node(the_most_populated_country.population,the_middle_populated_country.population) q22 = Node(the_middle_populated_country.population,the_least_populated_country.population) q23 = Node(the_least_populated_country.population,None) #формируем из узлов очередь queue1.add(0,q21.contained_object) queue1.add(1,q22.contained_object) queue1.add(2,q23.contained_object) #печатаем queue1.print_queue()
""" Abstracts the process of converting the output from the requests into more workable json objects """ class OutputHandler(object): def __init__(self): import json self.json = json """ Turns a object into the string form of a json and returns it as a beautified json @param data dict """ def outputToJson(self, data): data = data.text data = self.json.loads(data) return self.json.dumps(data, sort_keys=True, indent=4) def dictToJson(self, data): return self.json.dumps(data, sort_keys=True, indent=4) """ To make the requests to the jira plataform and return their raw output @param user string - the user name to sign into the jira platform @param password string - the api key or password for the authentication """ class Requester(): def __init__(self, user, password): import requests import json self.json = json self.requests = requests self.user = user self.password = password # json header for the requests self.jsonContentType = {'Content-type': 'application/json'} """ Sends a generic get requests with the option to append values @param url string - url to make the requests to @param payload dict - contains the values to be sent """ def getRequest(self, url, payload = None): return self.requests.get(url, auth=(self.user, self.password), params=payload) """ Sends a generic post request with a json object as its request body @param url string - url to make the requests to @param payload dict - contains the values to be sent """ def postRequestWithJsonBody(self, url, payload = None): # Converts the payload to josn payload = self.json.dumps(payload) return self.requests.post(url, auth=(self.user, self.password), data=payload, headers=self.jsonContentType) """ Wrapper for the different jira endpoints that will be used as well as container for the interaction logic """ class Jira(object): def __init__(self, Requester): import configparser from os.path import expanduser # Parsing data from the config file homePath = expanduser("~") configFilePath = "%s%s%s" % (homePath, "/", ".config.ini") config = configparser.ConfigParser() config.read(configFilePath) # Intantiates the requester class self.requester = Requester(config['auth']['userName'], config['auth']['apikey']) # Forms the base url to which all the api calls will be made self.jiraUrl = "%s%s" % (config['url']['baseurl'], config['url']['apiparturl']) # Url to query the boards available to the user self.boardListingUrl = "%s%s" % (self.jiraUrl, config['boardListing']['urlpart']) # Required to form the url with parms for issues by board self.issuesByBoard1 = config['issuesByBoard']['urlpart1'] self.issuesByBoard2 = config['issuesByBoard']['urlpart2'] # Url to query the metadata for the issues self.metadataForIssuesUrl = "%s%s" % (self.jiraUrl, config['metadataForIssues']['urlpart']) # Url to create a new issue self.createNewIssueUrl = "%s%s" % (self.jiraUrl ,config['sendIssue']['urlpart']) def listBoards(self, payload): return self.requester.getRequest(self.boardListingUrl, payload) def issuesByBoardId(self, boardId, payload = None): url = "%s%s%s%s" % (self.jiraUrl, self.issuesByBoard1, boardId, self.issuesByBoard2) return self.requester.getRequest(url, payload) def metadataForIssues(self): return self.requester.getRequest(self.metadataForIssuesUrl) # Creates a issue and if the user data was sent asigns it to them def sendNewIssue(self, projectId, summary, description, issuetype, userName, email): # Creates a dictionary with the sent data to submit a new issue body = {} body['fields'] = {} body['fields']['summary'] = summary body['fields']['description'] = description body['fields']['project'] = {} body['fields']['project']['id'] = projectId body['fields']['issuetype'] = {} body['fields']['issuetype']['id'] = issuetype if userName is not None and email is not None: body['fields']['assignee'] = {} body['fields']['assignee']['name'] = userName body['fields']['assignee']['key'] = userName body['fields']['assignee']['emailAddress'] = email return self.requester.postRequestWithJsonBody(self.createNewIssueUrl, body) """ The application logic The classes above will be used here to serve the requests made to the script """ import argparse parser = argparse.ArgumentParser() requiredNamed = parser.add_argument_group('Required named arguments') requiredNamed.add_argument('-a', '--action', type=str, help='The desired type of action to interact with jira', required=True) parser.add_argument('--name', type=str, help='Name of the board', default=None) parser.add_argument('--maxResults', type=str, help='Maximun amount of board to return, by default 50', default=None) parser.add_argument('--boardId', type=str, help='The id of the board') parser.add_argument('--startAt', type=int, help='The desired start point of the sequence', default=None) parser.add_argument('--projectId', type=int, help='The id of the project', default=None) parser.add_argument('--summary', type=str, help='A summary of the issue', default=None) parser.add_argument('--description', type=str, help='A description of the issue', default=None) parser.add_argument('--issuetype', type=int, help='The id of the issue, can be taken from the issue metadata', default=None) parser.add_argument('--userName', type=str, help='Username of the user being handled', default=None) parser.add_argument('--email', type=str, help='Email of the user being handled', default=None) args = parser.parse_args() jira = Jira(Requester) outputHandler = OutputHandler() """ This methods interact directly with the classes and are called depending on the action argument sent by the user """ def listBoards(payload): output = jira.listBoards(payload) return outputHandler.outputToJson(output) def issuesByBoard(): output = jira.issuesByBoardId(args.boardId, payload) return outputHandler.outputToJson(output) def metadataForIssues(): output = jira.metadataForIssues() return outputHandler.outputToJson(output) def createIssue(projectId, summary, description, issuetype, userName, email): output = jira.sendNewIssue(projectId, summary, description, issuetype, userName, email) return outputHandler.outputToJson(output) #return output """ This section determines what's the desired action to perform by the user and processes the aeguments taken from the scrip calling according to the action """ # Listing boards if args.action == "listBoards": payload = {} if args.name is not None: payload['name'] = args.name if args.maxResults is not None: payload['maxResults'] = args.maxResults print listBoards(payload) # Listing issues by board elif args.action == "issuesByBoard": payload = {} if args.startAt is not None: payload['startAt'] = args.startAt if args.maxResults is not None: payload['maxResults'] = args.maxResults print issuesByBoard() # Lists the met available adata for the issues elif args.action == "metadataForIssues": print metadataForIssues() # Creating a new issue elif args.action == "createIssue": print createIssue(args.projectId, args.summary, args.description, args.issuetype, args.userName, args.email) # If the action is not mapped else: print "Invalid action"
# Code your solution here string = input("Enter a string") print(string.swapcase())
marks = input('User Grade') if marks >=35 print("Passing grade") else: print("Failing Grade")
''' Look at the main function for testing the queue ''' class queue: def __init__(self): self.inStack = [] self.outStack = [] def enqueue(self, x): self.inStack.append(x) def dequeue(self): if len(self.inStack) == 0 and len(self.outStack) == 0: raise Exception('Queue is empty') if len(self.outStack) == 0: while len(self.inStack) > 0: self.outStack.append(self.inStack.pop()) return self.outStack.pop() def front(self): if len(self.inStack) == 0 and len(self.outStack) == 0: raise Exception('Queue is empty') if len(self.outStack) == 0: while len(self.inStack) > 0: self.outStack.append(self.inStack.pop()) return self.outStack[len(self.outStack)-1] def main(): q = queue() q.enqueue(5) q.enqueue(4) q.enqueue(3) q.enqueue(2) q.enqueue(1) print(q.front()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) q.enqueue(23) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) if __name__ == '__main__': main()
f = open("zedd.txt") for line in f: line = line.rstrip() if not "is" in line: continue print(line)
import sqlite3 class User: def __init__(self, _id, username, password): self.id=_id self.username=username self.password=password @classmethod def find_by_username(cls, username): connect = sqlite3.connect('data.db') cursor = connect.cursor() query="select userid, username, password from users where username=?" result = cursor.execute(query, (username,)) row = result.fetchone() if row: user = cls(row[0], row[1], row[2]) else: user = None connect.close() return user @classmethod def insert_user(cls, username, email, password, publickey, privatekey): connect = sqlite3.connect('data.db') cursor = connect.cursor() query = "INSERT INTO users (username, email, password, public_key, private_key) VALUES (?, ?, ?, ?, ?)" cursor.execute(query, (username,email,password, publickey, privatekey)) connect.commit() connect.close() @classmethod def find_by_id(cls, userid): connect = sqlite3.connect('data.db') cursor = connect.cursor() query = "select userid, username, password from users where userid=?" result = cursor.execute(query, (userid,)) row = result.fetchone() if row: user = cls(row[0], row[1], row[2]) else: user = None connect.close() return user @classmethod def return_all_users(cls): connect = sqlite3.connect('data.db') cursor = connect.cursor() query = "select userid, username from users" result = cursor.execute(query) row = result.fetchall() lst=[] if row: for i in row: lst.append([i[0], i[1]]) else: lst = None connect.close() return lst @classmethod def return_pub_pri_keys(cls,userid): userid=int(userid) connect = sqlite3.connect('data.db') cursor = connect.cursor() query = "select public_key, private_key from users where userid=?" result = cursor.execute(query, (userid,)) row = result.fetchone() lst=[] if row: lst.append(row[0]) lst.append(row[1]) else: lst=None connect.close() return lst class Message: def __init__(self, content, userid, recipient_id): self.content=content self.userid=userid self.recipient_id=recipient_id @classmethod def find_by_userids(cls, userid, recipient_id): userid = int(userid) recipient_id = int(recipient_id) connect = sqlite3.connect('data.db') cursor = connect.cursor() query = "select userid, content, time_stamp from message where (userid=? and recipientid=?) or (userid=? and recipientid=?) order by time_stamp desc" result = cursor.execute(query, (userid, recipient_id, recipient_id, userid)) row = result.fetchmany(30) lst = [] if row: for i in row: lst.append(i) else: lst=None connect.close() return lst @classmethod def insert_message(cls, userid, recipient_id, content): userid = int(userid) recipient_id=int(recipient_id) connect = sqlite3.connect('data.db') cursor = connect.cursor() query = "INSERT INTO message (userid, recipientid, content) VALUES (?, ?, ?)" cursor.execute(query, (userid, recipient_id, content)) connect.commit() connect.close()
# -*- coding: utf-8 -*- def write_to_pickle(filename, list_of_sentences): import cPickle as pickle f = open("%s.pickle"%filename, "wb") pickle.dump(list_of_sentences, f) f.close() print "The data was saved to %s.pickle. The file contains %d lines."%(filename, len(list_of_sentences)) def write_to_csv(filename, list_of_sentences): import csv with open("%s.csv"%filename, 'wb') as f: wr = csv.writer(f, delimiter=',') for row in list_of_sentences: wr.writerow([row[0], row[1], row[2], row[3]]) print "The data was saved to %s.csv. The file contains %d lines."%(filename, len(list_of_sentences))
# Crie um programa que leia quanto dinheiro uma pessoa tem na # carteira e mostre quantos Dolares ela pode comprar. print('--== Desafio 010 ==--') n = float(input('Digite o valor em reais: ')) r = n / 3.27 print('É possivel comprar ${:.4f}'.format(r))
# Faça uma programa que leia o nome de um pessoa e mostre uma # mensagem de boas-vendas. print('--== Desafio 002 ==--') nome = input('Qual seu nome ? ') print('Olá ',nome,', Prazer em Conhece-lo!')
# Faça um programa que leia o nome completo de uma pessoa. mostrando # o primeiro e o ultimo nome separadamente. print('--== Desafio 027 ==--') nome = str(input('Digite seu nome completo: ')).strip().split() print('Seu primeiro nome é {}\nSeu ultimo nome é {}'.format(nome[0], nome[len(nome)-1]))
import numpy as np import sys try: escagno = int(input("¿Cuántos escaños se reparten? ")) numPartidos = int(input("¿Cuántos partidos se presentan a las elecciones? ")) except ValueError: print("No es un número") sys.exit(-1) listaPartidos = [] for _ in range(0, numPartidos): partido = dict() print("Introduzca el partido") partido["nombre"] = input("Introduzca el nombre del partido: ") partido["votos"] = int(input("Introduzca el número de votos: ")) partido["escagno"] = 0 listaPartidos.append(partido) print("\n") matrix = np.zeros(shape=(numPartidos, escagno)) for i in range(0, numPartidos): for j in range(0, escagno): matrix[i][j] = listaPartidos[i]["votos"] / (j+1) escagnosrepartidos = 0 while escagnosrepartidos < escagno: location = np.where(matrix == np.max(matrix)) matrix[location[0][0]][location[1][0]] = -1 listaPartidos[location[0][0]]["escagno"] += 1 escagnosrepartidos += 1 for i in range(0, numPartidos): print(listaPartidos[i]["nombre"], " con ", listaPartidos[i]["votos"], " votos ha conseguido ", listaPartidos[i]["escagno"], " escaño/escaños.")
import numpy as np import sys try: rows = int(input("Introduzca el número de filas: ")) cols = int(input("Introduzca el número de columnas: ")) except ValueError: print("No es un número") sys.exit(-1) matrix = np.random.rand(rows, cols) print("Los valores de la matriz son") print(matrix) print("El máximo valor de la matriz es ", np.max(matrix)) print("El mínimo valor de la matriz es ", np.min(matrix)) opcion = 0 while True: print("1. Ángulos formados entre dos filas") print("2. Ángulos formados entre dos columas") try: opcion = int(input("Eliga una de las opciones: ")) except ValueError: print("No es un número") sys.exit(-1) if opcion in [1, 2]: break else: print("Opción Incorrecta\n") if opcion is 1: try: row1 = int(input("Introduzca la primera fila: ")) row2 = int(input("Introduzca la segunda fila: ")) except ValueError: print("No es un número") sys.exit(-1) if row1 not in range(0, rows) or row2 not in range(0, rows): print("Una de las filas no existe") sys.exit(-1) rowdata1 = matrix[row1, :] rowdata2 = matrix[row2, :] dotproduct = np.dot(rowdata1, rowdata2) mod1 = np.sqrt(np.dot(rowdata1, rowdata1)) mod2 = np.sqrt(np.dot(rowdata2, rowdata2)) angle = np.arccos(dotproduct/(mod1*mod2)) print("El ángulo entre los dos vectores en grados es ", np.degrees(angle)) else: try: col1 = int(input("Introduzca la primera columna: ")) col2 = int(input("Introduzca la segunda columna: ")) except ValueError: print("No es un número") sys.exit(-1) if col1 not in range(0, cols) or col2 not in range(0, cols): print("Una de las columnas no existe") sys.exit(-1) coldata1 = matrix[:, col1] coldata2 = matrix[:, col2] dotproduct = np.dot(coldata1, coldata2) mod1 = np.sqrt(np.dot(coldata1, coldata1)) mod2 = np.sqrt(np.dot(coldata2, coldata2)) angle = np.arccos(dotproduct/(mod1*mod2)) print("El ángulo entre los dos vectores en grados es ", np.degrees(angle))
# # El formato del fichero será el siguiente: # En la primera línea, separado por un espacio # se pondrá el número de filas y columnas # Cada fila del fichero será una fila de la matriz # Cada elemento estará separado por un espacio # import numpy as np import sys if len(sys.argv) != 2: print("Se ha llamado mal al programa") sys.exit(-1) try: f = open(sys.argv[1], 'rt') except IOError: print("No se puede leer el fichero") sys.exit(-1) lines = f.read().splitlines() shape = lines[0].split(' ') shape = [int(i) for i in shape] matrix = np.zeros(shape=(shape[0], shape[1])) for i in range(0, len(lines)-1): lines[i+1] = lines[i+1].split(' ') lines[i+1] = [int(j) for j in lines[i+1]] matrix[i, :] = np.array(lines[i+1]) print("La matriz es:") print(matrix) if np.linalg.det(matrix) == 0: print("La matriz no es invertible") else: print("La inversa de la matriz es:") inversa = np.linalg.inv(matrix) print(inversa) #La matriz original multiplicada por su inversa tiene #que dar la matriz identidad print("Si la inversa se ha calculado correctamente") print("La proxima matriz es la identidad de orden ", shape[0]) print(np.matmul(matrix, inversa).round(0))
import time def iinput(showstring,default): ttemp = input(showstring) if ttemp == "": return default else: return ttemp def fastdivision(value): A = ((value + D) * mult) >> N return A def getsizeof(value): sizeof = 0 while value: value >>= 1 sizeof += 1 return sizeof def show_opener(): print(" ") print(" ") print(" ") print(" |--------------------------- G A N Z Z A H L D I V I S I O N M I T A V R - M I K R O C O N T R O L L E R N ------------------------------|") print(" | |") print(" | Einfache Mikrocontroller ohne Hardwareunterstützung für Division benötigen sehr viel Rechenzeit zur Ausführung einer Ganzzahldivision. |") print(" | ATmega MCUs besitzen im Gegensatz zu ATtiny MCUs eine Hardwareunterstützung für Multiplikation. |") print(" | Dieses Script hilft bei der Umwandlung einer Ganzzahldivision in eine inverse Multiplikation mit anschließender Rechtsschiebeoperation, |") print(" | die von allen MCUs einfach und schnell ausgeführt werden kann. |") print(" | |") print(" | |") print(" | aus A = B // C mache A = ((B + D) * (1<<N)//C) >> N |") print(" | |") print(" | Da Ganzzahldivisionen immer abrunden erhöht man bei Bedarf für bessere Annäherung an eine Festkommadivision den Dividenten |") print(" | zusätzlich um die Hälfte des Divisors: |") print(" | |") print(" | B = B + (C >> 1) |") print(" | 25mmHg 24.09.2016 |") print(" |----------------------------------------------------------------------------------------------------------------------------------------------|") print(" ") print(" ") def show_inputdialog(): global Bmax global Bmin global C global Dmax global Dmin global Smax global Emax global Fmax global Nmax print(" ") Bmax = int(iinput(" größte Zahl, die geteilt werden soll (Dividend): ", 511)) print(" Bmax = ", Bmax) Bmin = int(iinput(" optional kleinste Zahl, die geteilt werden soll (Dividend): ", 0)) print(" Bmin = ", Bmin) C = int(iinput(" Zahl durch die geteilt werden soll (Divisor): ", 60)) print(" C = ", C) Dmax = int(iinput(" optional maximaler Korrekturwert (Summand): ", C // 2 + 1)) print(" Dmax = ", Dmax) Dmin = int(iinput(" optional minimaler Korrekturwert (Summand): ", -Dmax)) print(" Dmin = ", Dmin) Smax = int(iinput(" optional maximale Streuung des Multiplikators: ", 1)) print(" Smax = ", Smax) print(" Smin = ", -Smax) Emax = int(iinput(" optional maximale Größe der Abweichung für Anzeige (Error): ", 1)) print(" Emax = ", Emax) Fmax = int(iinput(" optional maximale Anzahl der Abweichungen über Bmax bis Bmin: ", 22)) print(" Fmax = ", Fmax) Nmax = int(iinput(" (größtmögliche) Bitschiebeweite (1<<N): ", 32)) print(" Nmax = ", Nmax) print(" ") def show_table(): print(" ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- ") print(" ALLE ANZAHL MULTIPLIKATOR FEHLERHAFTE ") print(" OK? FEHLER ((1<<N)//C)+j N D sizeof() ERGEBNISSE bei B = ") print(" ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- ") def getabsdelta(value): A01 = value // C A1 = fastdivision(value) return abs(A1-A01) def show_solution(): print(" %2s %2i %#12x %2i %3i %2iBit %s " % (ok,errcnt,mult,N,D,maxbits,str(falselist))) show_opener() while input(" Neue Berechnung starten? ") == "ja": show_inputdialog() oldtime = time.clock() for i in range(Nmax,0,-1): N = i Nold = 0 for j in range(Smax,-(Smax+1),-1): mult = ((1<<N)//C)+j if mult < 2: break for k in range(Dmax,Dmin-1,-1): D = k ready2print = True falselist = [] errcnt = 0 ok = "JA " maxbits = getsizeof((Bmax + D) * mult) for l in range(Bmax, Bmin -1, -1): B = l absdelta = getabsdelta(B) if absdelta > Emax: ready2print = False break elif absdelta != 0: ok = "---" falselist.append(B) errcnt = len(falselist) if errcnt > Fmax: ready2print = False break if ready2print == True: if Nold != N: Nold = N show_table() show_solution() print(" ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- ") calctime = time.clock() - oldtime print(" Rechenzeit = %6fs" % (calctime)) print(" ") print(" ") print(" >>> ENDE <<<") time.sleep(3)
class Node: def __init__(self,data,next): self.data=data self.next=next ''' def printlist(sourceList): printnode=sourceList if sourceList==None: print('printnode-None') else: while printnode.next != None: print('printnode',printnode.data,end=" ") printnode=printnode.next print('printnode',printnode.data)''' def findtail(sourceList): tmpnode=sourceList while tmpnode.next != None: tmpnode=tmpnode.next return tmpnode.data def merge(leftHalf, rightHalf): global cnt if findtail(leftHalf) > findtail(rightHalf): cnt+=1 fake_head = Node(None,None) curr = fake_head while leftHalf and rightHalf: if leftHalf.data < rightHalf.data: curr.next = leftHalf leftHalf = leftHalf.next else: curr.next = rightHalf rightHalf = rightHalf.next curr = curr.next if leftHalf == None: curr.next = rightHalf elif rightHalf == None: curr.next = leftHalf return fake_head.next def countlist(sourceList): count=1 tmpnode=sourceList while tmpnode.next != None: tmpnode=tmpnode.next count+=1 return count def split(sourceList): if sourceList == None or sourceList.next == None: leftHalf = sourceList rightHalf = None return leftHalf, rightHalf else: numofdata=countlist(sourceList) count=0 midPointer = sourceList while count != numofdata//2-1: midPointer=midPointer.next count += 1 leftHalf = sourceList rightHalf = midPointer.next midPointer.next = None return leftHalf, rightHalf def merge_sort(m): if m==None or m.next==None: return m left,right= split(m) left=merge_sort(left) right=merge_sort(right) return merge(left,right) def findmiddle(sourceList,N): tmpnode=sourceList length=0 while length != N//2: tmpnode=tmpnode.next length+=1 return tmpnode.data T=int(input()) for test_case in range(1,T+1): N=int(input()) todolist=list(map(int,input().split())) for i in range(N): if i==0: Head=Node(todolist[0],None) tmpnode=Head else: tmpnode.next=Node(todolist[i],None) tmpnode=tmpnode.next cnt=0 resultnode=merge_sort(Head) result=findmiddle(resultnode,N) print("#{} {} {}".format(test_case,result,cnt))
# 7. Write a program which accept one number and display below pattern. # Input : 5 # Output : 1 2 3 4 5 # 1 2 3 4 5 # 1 2 3 4 5 # 1 2 3 4 5 # 1 2 3 4 5 # def fun(num): for i in range(1,num+1): for j in range(1,num+1): print(i ,end=" ") print("\r") print("Enter row"); num=int(input()); fun(num) # Output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Assignment/Assignment2 # $ python Assignment2_7.py # Enter row # 5 # 1 1 1 1 1 # 2 2 2 2 2 # 3 3 3 3 3 # 4 4 4 4 4 # 5 5 5 5 5
# 8 Write a program which accept one number and display below pattern. # Input : 5 # Output : 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 def fun(num): for i in range(1,num+1): for j in range(1,i+1): print(j,end=" ") print("\r") print("Enter Num-:"); num=int(input()); fun(num) # output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Assignment/Assignment2 # $ python Assignment2_8.py # Enter Num-: # 5 # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5
# 1.Write a program which contains one function named as Fun(). That function should display # “Hello from Fun” on console. def fun(): print("Hello from Fun"); fun() # Output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1 # $ python fun.py # Hello from Fun
# 3. Write a program which contains one class named as Numbers. # Arithmetic class contains one instance variables as Value. # Inside init method initialise that instance variables to the value which is accepted from user. # There are four instance methods inside class as ChkPrime(), ChkPerfect(), SumFactors(), # Factors(). # ChkPrime() method will returns true if number is prime otherwise return false. # ChkPerfect() method will returns true if number is perfect otherwise return false. # Factors() method will display all factors of instance variable. # SumFactors() method will return addition of all factors. Use this method in any another method # as a helper method if required. # After designing the above class call all instance methods by creating multiple objects. class Numbers: def __init__(self,value): self.value=value def ChkPrime(self): if self.value > 1: for i in range(2,self.value): if (self.value % i) == 0: print(self.value,"is not a prime number") break else: print(self.value,"is a prime number") else: print(self.value,"is not a prime number") def ChkPerfect(self): Sum = 0 for i in range(1, self.value): if(self.value % i == 0): Sum = Sum + i if (Sum == self.value): print(self.value," is a Perfect Number") else: print(self.value,"is not a Perfect Number") # def SumFactors(self): # def Factors(self): obj1=Numbers(6) obj1.ChkPrime(); obj1.ChkPerfect(); obj1=Numbers(9) obj1.ChkPrime(); obj1.ChkPerfect(); # output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Assignment/Assignment7 # $ python Assignment7_3.py # 6 is not a prime number # 6 is a Perfect Number # 9 is not a prime number # 9 is not a Perfect Number
# 1.Design python application which creates two thread named as even and odd. Even # thread will display first 10 even numbers and odd thread will display first 10 odd # numbers. import threading def even(no): for i in range(1,no): if(i%2==0): print("Even",i); def Odd(no): for i in range(1,no): if(i%2!=0): print("Odd",i); if __name__ == "__main__": t1 = threading.Thread(target=even, args=(10,)); t2 = threading.Thread(target=Odd, args=(10,)); t1.start() t2.start() # output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Assignment/Assignment8 # $ python Assignment8_1.py # Even 2 # Even 4 # Even 6 # Even 8 # Odd 1 # Odd 3 # Odd 5 # Odd 7 # Odd 9
# 6.Write a program which accept number from user and check whether that number is positive or # negative or zero. # Input : 11 Output : Positive Number # Input : -8 Output : Negative Number # Input : 0 Output : Zero print("Enter num"); num=int(input()) if num > 0: print ("Positive Number"); elif num == 0: print("Zero"); else : print ("Negative Number"); # Output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1 # $ python positivenum.py # Enter num # 5 # Positive Number # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1 # $ python positivenum.py # Enter num # -5 # Negative Number # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1 # $ python positivenum.py # Enter num # 0 # Zero
# 2.Write a program which contains one lambda function which accepts two parameters and return # its multiplication. # Input : 4 3 Output : 12 # Input : 6 3 Output : 18 fptr=lambda no1,no2:no1*no2; no1=int(input("Enter Fist number-:")); no2=int(input("Enter Second number-:")); ans=fptr(no1,no2); print("Two number multiplication =:",ans); # Output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Assignment/Assignment4 # $ python Assignment4_2.py # Enter Fist number-:4 # Enter Second number-:3 # Two number multiplication =: 12
# Write a program which display first 10 even numbers on screen. # Output : 2 4 6 8 10 12 14 16 18 20 def fun(num): for i in range(2,num*2+2,2): print(" ",i); num=int(input()) fun(num) # Output-: # zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1 # $ python even_num.py # 10 # 2 # 4 # 6 # 8 # 10 # 12 # 14 # 16 # 18 # 20
#!/usr/bin/env python #some eg of mathematical functions import math; x=int(input('enter any no. to calculate factorial: ')); fact = math.factorial(x); print('factorial of given no. : ',fact); # print('pi value: ', math.pi)
# author: h.serimer 03.2021 https://github.com/eproje/uPy_Course # Board: Lolin32 Lite # simple touch # There are ten capacitive touch-enabled pins that can be used on the ESP32: 0, 2, 4, 12, 13 14, 15, 27, 32, 33. # Trying to assign to any other pins will result in a ValueError. # REF: https://docs.micropython.org/en/latest/esp32/quickref.html from machine import TouchPad, Pin from time import sleep touch_pin1 = TouchPad(Pin(12)) touch_pin2 = TouchPad(Pin(14)) while True: touch_value1 = touch_pin1.read() touch_value2 = touch_pin2.read() print(touch_value1,"-",touch_value2) sleep(0.5)
import time import machine from machine import Pin Led1=Pin(22, Pin.OUT) Led2=Pin(23, Pin.OUT) def YakSondur(pinNo,sure,tekrar): for i in range (tekrar * 2 ):# kitap sayfa 73 pinNo.value(1 - pinNo.value()) # toogle değerin tersini alır time.sleep(sure) try: #program çalışırken yapılacak işler while (True): YakSondur(Led1,0.05,3) YakSondur(Led2,0.05,3) except KeyboardInterrupt: #program durdurulduğunda yapılacak işler Led1.value(0) Led2.value(0)
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################### # File name : p.py # Create date : 2018-07-23 08:49 # Modified date : 2018-07-23 13:04 # Author : DARREN # Describe : not set # Email : lzygzh@126.com ##################################### # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Print(self,root): if not root: return [] levels,result,leftToRight = [root],[],True while levels: curValues,nextLevel = [],[] for node in levels: curValues.append(node.val) if node.left: nextLevel.append(node.left) if node.right: nextLevel.append(node.right) if not leftToRight: curValues.reverse() if curValues: result.append(curValues) levels = nextLevel leftToRight = not leftToRight return result
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################### # File name : p.py # Create date : 2018-07-23 08:49 # Modified date : 2018-07-23 13:04 # Author : DARREN # Describe : not set # Email : lzygzh@126.com ##################################### class Solution: def __init__(self): self.adict = {} self.alist = [] def FirstAppearingOnce(self): while len(self.alist) > 0 and self.adict[self.alist[0]] == 2: self.alist.pop(0) if len(self.alist) == 0: return "#" else: return self.alist[0] def Insert(self,char): if char not in self.adict.keys(): self.adict[char] = 1 self.alist.append(char) elif self.adict[char]: self.adict[char] = 2
x= 8 # if x < 2: # print('samll') # elif x < 10: # print('medium') # else : # print('large') #======================================= sh = input('enter your working hours: ') sr = input('enter rate: ') fh = float(sh) fr = float(sr) #. print(sh, sr) if fh > 40 : print('Overtime') reg = fr * fh otp = (fh - 40)*(fr * 1.5) print(reg,otp) xp = reg + otp else: print('Regular') xp = fh * fr print('pay: :', xp)
import math def CountSplitInversion(left_array, right_array): left_len = len(left_array) right_len = len(right_array) array = [] i = 0 j = 0 count = 0 for k in range(left_len + right_len): if i == left_len: array += right_array[j:right_len] break if j == right_len: array += left_array[i:left_len] break if left_array[i] < right_array[j]: array.append(left_array[i]) i += 1 elif left_array[i] > right_array[j]: array.append(right_array[j]) j += 1 count += left_len - i #print array, count return array, count def CountInversion(array): n = len(array) middle = int(math.floor(n/2)) #print middle, n if(n==1): return array, 0 left_array, left_count = CountInversion(array[0:middle]) right_array, right_count = CountInversion(array[middle:n]) final_array, split_count = CountSplitInversion(left_array, right_array) return final_array, left_count + right_count + split_count
# -*- encoding: utf-8 -*- __metaclass__ = type class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print "Aaaah..." self.hungry = False else: print "No, thanks!" class SongBird(Bird): def __init__(self): super(SongBird, self).__init__() self.sound = "Squawk!" def sing(self): print self.sound print "--------Bird---------" bird = Bird() bird.eat() bird.eat() print "------Song Bird------" sbird = SongBird() sbird.sing() sbird.eat() sbird.eat()
# -*- encoding: utf-8 -*- def init(data): data['first'] = {} data['middle'] = {} data['last'] = {} def lookup(data, label, name): """look for full names in dicitionary""" return data[label].get(name) def store(data, full_name): """ store people\'s full names hello world """ names = full_name.split() if len(names) == 2: names.insert(1, '') labels = ['first', 'middle', 'last'] for label, name in zip(labels, names): people = lookup(data, label, name) if people: data[label][name].append(full_name) else: data[label][name] = [full_name] def store2(data, *full_names): """ :param data: dictionary stored all full names :param full_names: people's full names :return: """ for fullname in full_names: names = fullname.split() if len(names) == 2: names.insert(1, '') labels = ['first', 'middle', 'last'] for label, name in zip(labels, names): people = lookup(data, label, name) if people: data[label][name].append(fullname) else: data[label][name] = [fullname] MyNames = {} init(MyNames) store(MyNames, 'Wu Zhenyu Yu') store(MyNames, 'Magus Lie Hetland') store(MyNames, 'Mr. Gumby') store2(MyNames, 'Zhang Fei', 'Tylor Swift') print lookup(MyNames, 'middle', 'Zhenyu') print lookup(MyNames, 'middle', '') print store.__doc__ print store2.__doc__
# Author @dan # facebook : /whodanyalahmed # twitter : /whodanyalahmed # instagram : @whodanyalahmed # linkedin : /in/whodanyalahmed import math while True: print("\n\t\tVector") print("\t\t------\n") print("1 - Dot (.) Product") print("2 - Length") print("3 - Unit Vector") print("4 - Vector Addition") print("5 - Scalar Multiple") print("E - Exit") op = input("Enter the option: ") if(op == "1"): try: val = eval(input("Enter number of values: ")) ul = [] vl = [] result = [] for i in range(val): u = eval(input("Enter u"+str(i+1)+": ")) ul.append(u) for i in range(val): v = eval(input("Enter v"+str(i+1)+": ")) vl.append(v) mul = ul[i] * vl[i] result.append(mul) final = [] c = 0 for r in result: c = c + r final.append(c) print("u = ", ul) print("v = ", vl) print("( "+str(ul)+" * "+str(vl) + " ) = ", result) print("( "+str(ul)+" * "+str(vl) + " ) = ", final) except SyntaxError as e: print("You had SyntaxError") elif (op == "2"): try: val = eval(input("Enter number of values: ")) ul = [] result = [] for i in range(val): u = eval(input("Enter u"+str(i+1)+": ")) ul.append(u) mul = ul[i] * ul[i] result.append(mul) print("The of u is: ", ul) print("The square of u is : ", result) ans = 0 for i in result: ans = ans + i print("The final under root ans is: ", ans) print("||u|| : ", math.sqrt(ans)) except SyntaxError as e: print("You had SyntaxError") elif(op == "3"): try: val = eval(input("Enter number of values: ")) ul = [] result = [] for i in range(val): u = eval(input("Enter u"+str(i+1)+": ")) ul.append(u) mul = ul[i] * ul[i] result.append(mul) print("The of u is: ", ul) print("The square of u is : ", result) ans = 0 for i in result: ans = ans + i print("||u|| : \u221A or", ans) print("||u|| : ", math.sqrt(ans)) for i in ul: print(" ( "+str(i) + " / " + "\u221A" + str(ans) + " )", end="") except SyntaxError as e: print("You had SyntaxError") elif(op == "4"): try: val = eval(input("Enter number of values: ")) ul = [] vl = [] result = [] for i in range(val): u = eval(input("Enter u"+str(i+1)+": ")) ul.append(u) for i in range(val): v = eval(input("Enter v"+str(i+1)+": ")) vl.append(v) sum = ul[i]+vl[i] result.append(sum) print("The sum of u : " + str(ul) + " and v : " + str(vl) + " is : " + str(result)) except SyntaxError as e: print("You had SyntaxError") elif(op == "5"): try: s = eval(input("Enter any scalar value: ")) val = eval(input("Enter number of values: ")) ul = [] result = [] for i in range(val): u = eval(input("Enter u"+str(i+1)+": ")) ul.append(u) mul = ul[i]*s result.append(mul) print("The sum of u : " + str(ul) + " and s : " + str(s) + " is : " + str(result)) except SyntaxError as e: print("You had SyntaxError") elif(op == "e" or op == "E"): break else: print("Enter valid option/Try again")
import time import threading import random from multiThreading.error import ThreadSafeQueueException class ThreadSafeQueue(object): """ 创建一个线程安全的队列类 """ def __init__(self, max_size=0): self.queue = [] self.max_size = max_size self.lock = threading.Lock() self.condition = threading.Condition() # 获取队列的长度 def size(self): self.lock.acquire() size = len(self.queue) self.lock.release() return size # 向队列中放入元素 def put(self, item): if self.max_size != 0 and self.size() > self.max_size: return ThreadSafeQueueException() self.lock.acquire() self.queue.append(item) self.lock.release() # 假设队列为0,线程阻塞,则队列能通知线程进行处理 self.condition.acquire() self.condition.notify() self.condition.release() # 批量放入元素 def batch_put(self, item_list): if not isinstance(item_list, list): item_list = list(item_list) for item in item_list: self.put(item) # 从队列中取出元素,默认是头部元素 def pop(self, block=False, timeout=None): if self.size() == 0: # 如果需要阻塞等待, 则需要通知线程 if block: self.condition.acquire() self.condition.wait(timeout=timeout) self.condition.release() else: return None self.lock.acquire() item = None if len(self.queue) > 0: item = self.queue.pop() self.lock.release() return item # 获取队列中的元素 def get(self, index): self.lock.acquire() item = self.queue[index] self.lock.release() return item if __name__ == '__main__': queue = ThreadSafeQueue(max_size=100) def producer(): while True: i = random.randint(1, 999) queue.put(i) print("put ", i, "into the queue") time.sleep(2) def consumer(): while True: item = queue.pop(block=True, timeout=2) print("get item from queue: ", item) time.sleep(1) thread1 = threading.Thread(target=producer) thread2 = threading.Thread(target=consumer) thread1.start() thread2.start() thread1.join() thread2.join()
#Rosalind_countdna #Objective: Count each nucleotide in a given sequence '''DNA strand is composed of 4 different nucleotides A,C,G,T. This task will perform how to count nucleotides in a sequence using python''' import os os.chdir('/home/vu/Downloads') #move to a desired directory f = open('rosalind_dna (1).txt', 'r').read()[:-1] #[-1] for rm \n d = {} for i in f: if i not in d: d[i] = 1 else: d[i] = d[i] + 1 for items in d: print items, d[items] ''' Result A 230 C 220 T 242 G 252 '''
from datetime import datetime # Current date time in local system date = datetime.now().date() date = str(date) print("Todays Date:",date) enterDate = input("Enter date in format shown above ({0}):".format(date)) if(enterDate == ""): enterDate = date fileName = str("presentPeople"+enterDate+".txt") # try: # fd=open(fileName, "r") # except FileNotFoundError: # print("No One Present On This Date") with open(fileName) as f: content = f.readlines() content = [x.strip() for x in content] presenties = content[0].split() presenties = [x.lower() for x in presenties] print('\n'"Presenties on ",enterDate,":"'\n\n',presenties,'\n') val = 'y' while(val == 'y' or val == 'Y'): name = input("Enter name to check: ").lower() if name in presenties: print("Present"'\n') else: print("Absent"'\n') val = input("Want to check for someone else? (Y/n)") #METHOD 2 # count =0 # for i in presenties: # if i == name: # count = count+1 # print('present') # if count == 0: # print("absent")
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None @staticmethod def inorder(node): if node is None: return TreeNode.inorder(node.left) print(node.val) TreeNode.inorder(node.right) class Solution: # @param {integer[]} nums # @return {TreeNode} def sortedArrayToBST(self, nums): return self.buildTree(nums, 0, len(nums)-1) def buildTree(self, nums, left, right): if left > right: return None mid = left + (right - left)/2 left = self.buildTree(nums, left, mid-1) root = TreeNode(nums[mid]) root.left = left root.right = self.buildTree(nums, mid+1, right) return root root = Solution().sortedArrayToBST([3, 5, 8]) TreeNode.inorder(root)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def inorder(self, root, sum): if root is None: return self.stack.append(root.val) self.inorder(root.left, sum + root.val) if root.left is None and root.right is None: if sum + root.val == self.aim: self.paths.append(self.stack[:]) self.inorder(root.right, sum + root.val) self.stack.pop() def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ self.paths = [] self.stack = [] self.aim = sum self.inorder(root, 0) return self.paths def main(): root = TreeNode(5) n1 = TreeNode(4) n2 = TreeNode(8) n3 = TreeNode(11) n4 = TreeNode(13) n5 = TreeNode(4) n6 = TreeNode(7) n7 = TreeNode(2) n8 = TreeNode(5) n9 = TreeNode(1) # root.left = n1 # root.right = n2 n1.left = n3 n2.left = n4 n2.right = n5 n3.left = n6 n3.right = n7 n5.left = n8 n5.right = n9 s = Solution() print s.pathSum(root, 5) if __name__ == '__main__': main()
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if __name__ == '__main__': sudoku = [['53..7....'], ['6..195...'], ['.98....6.'], ['8...6...3'], ['4..8.3..1'], ['7...2...6'], ['.6....28.'], ['...419..5'], ['....8..79']] Solution().solveSudoku(sudoku) import pprint pprint.pprint(sudoku)
class Solution: # @param {string[]} tokens # @return {integer} def evalRPN(self, tokens): if not tokens: return 0 stack = [] for t in tokens: try: val = int(t) stack.append(val) except ValueError: if t == '+': adder = stack.pop() added = stack.pop() stack.append(added + adder) elif t == '-': substracter = stack.pop() substracted = stack.pop() stack.append(substracted - substracter) elif t == '*': multiplier = stack.pop() multiplied = stack.pop() stack.append(multiplied * multiplier) elif t == '/': divider = stack.pop() divided = stack.pop() if divider == 0: raise ValueError('divider can not be zero') # because python division is floor division # 1/-10 = -1 actually we need 1/-10 = 0 stack.append(int(float(divided) / divider)) return stack[0] def main(): tokens = ["4", "13", "5", "/", "+"] print(Solution().evalRPN(tokens)) if __name__ == '__main__': main()
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ self.k = k self.result = root.val self.running = True self.visit(root) return self.result def visit(self, root): if root is None or not self.running: return self.visit(root.left) self.k -= 1 if self.k == 0: self.result = root.val self.running = False self.visit(root.right) def main(): root = TreeNode(8) n1 = TreeNode(1) n3 = TreeNode(3) n4 = TreeNode(4) n6 = TreeNode(6) n7 = TreeNode(7) n10 = TreeNode(10) n13 = TreeNode(13) n14 = TreeNode(14) n14.left = n13 n10.right = n14 root.right = n10 n6.left = n4 n6.right = n7 n3.left = n1 n3.right = n6 root.left = n3 print(Solution().kthSmallest(root, 2)) if __name__ == "__main__": main()
# coding: utf-8 # Tools to study different variations of the the somma cube # ---------------------------------- # --------------------------------- # In[1]: import matplotlib.pyplot as plt import matplotlib.patches as patches # Rotation, shifting and transposition of 2D--shapes # ---------------------------------------------------------------- # In[2]: def shift_fX(x): shift_order_fX = [8, 0, 1, 2, 3, 4, 5, 6, 7] return [x[i] for i in shift_order_fX] def shift_bX(x): shift_order_bX = [1, 2, 3, 4, 5, 6, 7, 8, 0] return [x[i] for i in shift_order_bX] def shift_fY(x): shift_order_fY = [6, 7, 8, 0, 1, 2, 3, 4, 5] return [x[i] for i in shift_order_fY] def shift_bY(x): shift_order_bY = [3, 4, 5, 6, 7, 8, 0, 1, 2] return [x[i] for i in shift_order_bY] def transposition(x): transpose_order = [0,3,6,1,4,7,2,5,8] return [x[i] for i in transpose_order] # In[3]: def turn(x): turn_order = [6,3,0,7,4,1,8,5,2] return [x[i] for i in turn_order] # Graphical representation of 2D shapes # ------------------------------------------------ # In[4]: def build_shape(x): dx = 1/3 pos_2d ={ 0:(0,0), 1:(dx,0), 2:(2*dx,0), 3:(0,dx), 4:(dx,dx), 5:(2*dx,dx), 6:(0,2*dx), 7:(dx,2*dx), 8:(2*dx,2*dx)} pieces = [] frame = patches.Rectangle( (0.0, 0.0),1, 1, fill=False, edgecolor="red",linewidth=2) pieces.append(frame) for i in range(9): if x[i]==1: p = patches.Rectangle(pos_2d[i], dx,dx, fill=True) pieces.append(p) return pieces # In[5]: def show_shape(x): ax1=plt.subplot(111,aspect='equal') shape = build_shape(x) for p in shape: ax1.add_patch(p) plt.axis('off') plt.show() # Spatial rotation and shifting of 3D--shapes # ---------------------------------------------------- # In[6]: def shift3D_fX(x): return shift_fX(x[0:9]) + shift_fX(x[9:18])+ shift_fX(x[18:27]) def shift3D_bX(x): return shift_bX(x[0:9]) + shift_bX(x[9:18])+ shift_bX(x[18:27]) def shift3D_fY(x): return shift_fY(x[0:9]) + shift_fY(x[9:18])+ shift_fY(x[18:27]) def shift3D_bY(x): return shift_bY(x[0:9]) + shift_bY(x[9:18])+ shift_bY(x[18:27]) def shift3D_fZ(x): return x[18:27] + x[0:9] + x[9:18] def shift3D_bZ(x): return x[9:18] + x[18:27] + x[0:9] # In[7]: def turn3D_Z(x): return turn(x[0:9])+ turn(x[9:18])+ turn(x[18:27]) def turn3D_Y(x): turn_order_Y = [18, 9, 0, 21, 12, 3, 24, 15, 6, 19, 10, 1, 22, 13, 4, 25, 16, 7, 20, 11, 2, 23, 14, 5, 26, 17, 8] return [x[i] for i in turn_order_Y] def turn3D_X(x): turn_order_X = [18, 19, 20, 9, 10, 11, 0, 1, 2, 21, 22, 23, 12, 13, 14, 3, 4, 5, 24, 25, 26, 15, 16, 17, 6, 7, 8] return [x[i] for i in turn_order_X] # Graphical representation of the horizontal sections of the cube # --------------------------------------------------------------- # In[8]: def show3D_shape(x): ax1 = plt.subplot(131,aspect='equal') shape = build_shape(x[:9]) for p in shape: ax1.add_patch(p) plt.axis('off') #################### ax2=plt.subplot(132,aspect='equal') shape = build_shape(x[9:18]) for p in shape: ax2.add_patch(p) plt.axis('off') ########################## ax3=plt.subplot(133,aspect='equal') shape = build_shape(x[18:]) for p in shape: ax3.add_patch(p) plt.axis('off') ################### plt.show() # Some shapes mading up the Soma cube and several of its variations: black devil and red devil # ------------------------------------------------------------------ # Soma # ----- # In[9]: AA = [1,1,0,1,0,0,0,0,0, 0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomA = (1,1,1) BB = [1,1,0,0,1,0,0,0,0, 1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomB = (1,1,1) LL = [1,1,1,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomL = (0,1,2) PP = [1,1,0,1,0,0,0,0,0, 1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomP = (1,1,1) TT = [1,1,1,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomT = (0,1,2) VV = [1,1,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomV = (1,1,2) ZZ = [1,1,0,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomZ = (0,1,2) # Black devil # ------------- # The black devil is made up of six polycubes: AA, BB, LL, TTB, GAB, ZZB, three of which are share with the Soma cube. Therefore it suffies to describe GAB, TTB and ZZB only. # In[10]: GAB = [1,1,1,1,0,0,0,0,0, 0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomGAB = (0,1,1) TTB = [1,1,1,0,1,0,0,0,0, 0,0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomTTB = (0,1,1) ZZB = [1,1,0,0,1,0,0,0,0, 0,0,0,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomZZB = (0,1,1) # Red devil # ----------- # The Red devil cube is made up of six polycubes: AA, AA, LL, GAR, TTI, ZZR # In[11]: GAR = [1,1,1,0,0,1,0,0,0, 0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomGAR = (0,1,1) TTR = [1,1,1,0,0,1,0,0,0, 0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomTTR = (0,1,1) ZZR = [1,1,0,0,0,0,0,0,0, 0,1,0,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomZZR = (0,1,1) # Diabolical Cube # The diabolical cube is made up of six polycubes: b, c, d, e, h, g. # In[12]: b = [1,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomb = (1,2,2) c = [1,1,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomc = (1,1,2) d = [1,1,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomd = (1,1,2) e = [1,1,1,1,0,1,0,0,0, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedome = (0,1,2) h = [1,1,1,0,1,1,0,0,1, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomh = (0,0,2) g = [1,1,1,0,1,1,0,1,1, 0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0] #freedomg = (0,0,2)
import numpy as np def forward_euler_step(deriv, t, u, dt): return u + dt * deriv(t, u) def forward_euler(deriv, init, time_min, time_max, numSteps): ''' Solves a differential equation using Euler's method from time_min to time_max, using a step of time_step deriv: callable; the derivative init: numpy 1D array; initial condition time_min: float; Minimum time time_max: float; Maximum time numSteps: int; number of stes ''' dim = init.shape[0] # checks for 1D array assert(init.shape == (dim,)) # initialize times times = np.linspace(time_min, time_max, numSteps+1)[1:] time_step = float(time_max - time_min) / (numSteps - 1) ys = np.zeros((numSteps+1, dim)) ys[0] = init for (ind, t) in enumerate(times): time_ind = ind + 1 curr = ys[time_ind-1] ys[time_ind] = forward_euler_step(deriv, t, curr, time_step) return ys if __name__ == "__main__": lam = 1. def deriv(t, u): return lam * u nsteps = 200 init = np.array([1.]) res = forward_euler(deriv, init, 0, 1, nsteps)[:,0] print res print len(res) exact = np.exp(np.linspace(0,1,nsteps+1)) print exact - res
"""nota1 = int(input("ingrese la primera nota: ")) nota2 = int(input("ingrese la segunda nota: ")) nota3 = int(input("ingrese la tercera nota: ")) prom=(nota1+nota2+nota3)/3 if prom>=7: print("promocionado") elif prom>=4: print("regular") else: print("reprobado") x=1 suma=0 while x<=10: valor=int(input("ingrese un valor: ")) suma= suma + valor x=x+1 prom=suma/10 print("la suma de los 10 valores: ") print(suma) print("el promedio es: ") print(prom) """ #contenido 5 cantidad=0 x=1 n=int(input("cuantas piezas cargara?:")) while x<=n: medida=float(input("ingrese la medida:")) if medida>=1.2 and medida<=1.3: cantidad=cantidad+1 x=x+1 print("cantidad de piezas aptas: ") print(cantidad)
lista = [] for k in range(10): lista.append(input("agregue valor a la lista: ")) print("los elementos de la lista son:"+str(lista)) valor=int(input("introduce el valor a modificar pon el indice:")) nuevo=input("ingresa el nuevo valor:") lista[valor]= nuevo print("los elementos de la lista son:" +str(lista)) valor=int(input("inserta el indice donde se inserta el nuevo valor:")) nuevo=input("inserta el nuevo valor:") lista.insert(valor,nuevo) print("los elementos de la lista son:" +str(lista)) nuevo=input("introduce el valor a aliminar:") lista.remove(nuevo) print("los elementos de la lista son:" +str(lista)) nuevo=input("inserta el valor que quieres buscar") resultado=(nuevo in lista) if (resultado): print("existe este elemento y su indice es:" +str(lista.index(nuevo))) else: print("no existe este elemento")
class TvProgram: def __init__(self, name, year): self._name = name.title() self.year = year self._likes = 0 def __str__(self): return f'Name: {self._name} - Year: {self.year} - Likes: {self._likes}' @property def likes(self): return self._likes @property def name(self): return self._name def like(self): self._likes += 1 @name.setter def name(self, new_name): self._name = new_name class Movie(TvProgram): def __init__(self, name, year, length): super().__init__(name, year) self.length = length def __str__(self): return f'Name: {self._name} - Year: {self.year} - Length: {self.length} min - Likes: {self._likes}' class TvShow(TvProgram): def __init__(self, name, year, seasons): super().__init__(name, year) self.seasons = seasons def __str__(self): return f'Name: {self._name} - Year: {self.year} - Seasons: {self.seasons} - Likes: {self._likes}' class Playlist(): def __init__(self, name, tv_programs): self.name = name self.tv_programs = tv_programs def __iter__(self): return self.tv_programs.__iter__() def __len__(self): return len(self.tv_programs) avengers = Movie('avengers - guerra infinita', 2018, 160) atlanta = TvShow('atlanta', 2018, 2) avengers.like() avengers.like() avengers.like() atlanta.like() atlanta.like() playlist = Playlist('minha playlist', [atlanta, avengers]) for programa in playlist: print(programa)
#! /usr/bin/env python import Card import HandEvaluation as he class Hand: """ A Hand of Poker cards """ def __init__(self, handId): self.cardNumbers = [] self.handId= handId self.suitCountDict = {Card.Card.HEARTS : 0, Card.Card.DIAMONDS : 0, Card.Card.SPADES : 0, Card.Card.CLUBS : 0} self.faceCountDict = {} def accept(self, cardNumber): self.cardNumbers.append(cardNumber) cardSuit = cardNumber / 13 cardNumericRank = cardNumber % 13; self.suitCountDict[cardSuit] += 1 if self.faceCountDict.has_key(cardNumericRank): self.faceCountDict[cardNumericRank] += 1 else: self.faceCountDict[cardNumericRank] = 1 def removeLast(self): cardNumber = self.cardNumbers[-1] self.cardNumbers = self.cardNumbers[:-1] cardSuit = cardNumber / 13 cardNumericRank = cardNumber % 13; self.suitCountDict[cardSuit] -= 1 if self.faceCountDict[cardNumericRank] == 1: self.faceCountDict.pop(cardNumericRank, None) else: self.faceCountDict[cardNumericRank] -= 1 def __repr__(self): return str(self.cardNumbers) def __sortCards(self): #self.sortedCards = sorted(self.cardNumbers) self.sortedCards = self.cardNumbers # Returns a list of tuples(Card.SUIT, n) def __suitCount(self): # Sort the suits in descending order of counts(the most counts first) sortedKeys = sorted(self.suitCountDict, key=self.suitCountDict.__getitem__, reverse=True) self.suitCountOrdered = [(k, self.suitCountDict[k]) for k in sortedKeys] return self.suitCountOrdered # Returns a list of tuples(Card.numericRank, n) def __faceCardCount(self): # Sort the face values in descending order of counts(the most counts first) sortedKeys = sorted(self.faceCountDict, key=self.faceCountDict.__getitem__, reverse=True) self.faceCountOrdered = [(k, self.faceCountDict[k]) for k in sortedKeys] return self.faceCountOrdered def __isPair(self): vPair1, countPair1 = self.faceCountOrdered[0] return countPair1 == 2 def __isTwoPairs(self): vPair1, countPair1 = self.faceCountOrdered[0] vPair2, countPair2 = self.faceCountOrdered[1] return countPair1 == 2 and countPair2 == 2 def __isThreeOfKind(self): v, count = self.faceCountOrdered[0] return count == 3 def __findLongestStraight(self, values): prev = values[0] n = 1 nMax = n for v in values: if v == prev+1: n += 1 if n>nMax: nMax = n else: n = 1 prev = v return nMax def __isStraight(self): unrepeatedCardsSet = set([k%13 for k in self.cardNumbers]) unrepeatedCards = list(unrepeatedCardsSet) unrepeatedCards.sort() if unrepeatedCards[0]==0: # Add King + 1, so it can detect 10,J,Q,K,A unrepeatedCards.append(13) longestStraight = self.__findLongestStraight(unrepeatedCards) return longestStraight >= 5 def __isFullHouse(self): v3, count3 = self.faceCountOrdered[0] v2, count2 = self.faceCountOrdered[1] return count3 == 3 and count2 >= 2 def __isFourOfKind(self): v, count = self.faceCountOrdered[0] return count == 4 # It doesn't consider Royal Flush (as it was evaluated already) def __isStraightFlushFromThisCard(self, suit, lCards): previousCard = lCards[0] % 13 count = 1 for card in lCards[1:]: cardSuit = card/13 if cardSuit != suit: return False cardNumericRank = card % 13 if cardNumericRank == previousCard+1: count += 1 if count==5: return True else: count = 1 previousCard = cardNumericRank return False def __islStraightFlush(self, suit): # The hand has no repeats, its not a royal flush, and has at least 5 of same suit cardsInRoyalFlush = 0; for idx, card in enumerate(self.sortedCards): cardSuit = card/13 if cardSuit == suit: return self.__isStraightFlushFromThisCard(suit, self.sortedCards[idx:]) return False def __isRoyalFlush(self, suit): # The hand has no repeats, so count how many are in T, J, Q, K, A range for suit cardsInRoyalFlush = 0; for card in self.sortedCards: cardSuit = card/13 if cardSuit == suit: cardSymbolicRank = card%13 if cardSymbolicRank in [0, 9, 10, 11, 12]: cardsInRoyalFlush += 1 return cardsInRoyalFlush == 5 def evaluate(self): if len(self.cardNumbers) != 7: return None self.__sortCards() self.__suitCount() suit, count = self.suitCountOrdered[0] # Only bother with RoyalFlush and Straight Flush if possible if count >= 5: if self.__isRoyalFlush(suit): return he.HandEvaluation.ROYAL_FLUSH, self.suitCountOrdered elif self.__islStraightFlush(suit): return he.HandEvaluation.STRAIGHT_FLUSH, self.suitCountOrdered self.__faceCardCount() if self.__isFourOfKind(): return he.HandEvaluation.FOUR_OF_A_KIND, self.faceCountOrdered if self.__isFullHouse(): return he.HandEvaluation.FULL_HOUSE, self.faceCountOrdered if count >= 5: return he.HandEvaluation.FLUSH, self.suitCountOrdered if self.__isStraight(): return he.HandEvaluation.STRAIGHT, self.faceCountOrdered if self.__isThreeOfKind(): return he.HandEvaluation.THREE_OF_A_KIND, self.faceCountOrdered if self.__isTwoPairs(): return he.HandEvaluation.TWO_PAIR, self.faceCountOrdered if self.__isPair(): return he.HandEvaluation.PAIR, self.faceCountOrdered return he.HandEvaluation.HIGH_CARD, self.suitCountOrdered if __name__ == '__main__': h = Hand(0) """ h.accept(1) h.accept(13+2) h.accept(3) h.accept(13+3) h.accept(5) h.accept(4) h.accept(13*1+4) h.evaluate() """ """ d = 0 h.accept(13*d+2) h.accept(15) h.accept(13*d+5) h.accept(13*d+4) h.accept(13*d+1) h.accept(32) h.accept(13*d+3) rank, hv = h.evaluate() print len(hv), 4 suit, count = hv[0] print suit, d print count, 5 print rank, he.HandEvaluation.STRAIGHT_FLUSH """ d = 3 h.accept(13*d+2) h.accept(15) h.accept(13*d+1) h.accept(13*d+4) h.accept(22) h.accept(13*d+0) h.accept(13*d+3) rank, hv = h.evaluate() print len(hv), 4 suit, count = hv[0] print suit, d print count, 5 print rank, he.HandEvaluation.STRAIGHT_FLUSH
#! /usr/bin/env python import random import Card class Deck: """ A Deck of Poker cards""" _DECK = range(0, 52) def __init__(self, size): #self.numericCardValues = range(0, 52) #random.shuffle(self.numericCardValues) self.numericCardValues = random.sample(self._DECK, size) self.nCardsDealt = 0 def dealCard(self): numericCardValue = self.numericCardValues[self.nCardsDealt] c = Card.Card(numericCardValue) self.nCardsDealt += 1; return c if __name__ == '__main__': d = Deck() c = d.dealCard() print c.symbolicRank(), c.suit()
import random minimum = int(raw_input("Lowest number in range: ")) maximum = int(raw_input("Highest number in range: ")) number = random.randint(minimum, maximum) statement = "Guess a number between " + str(minimum) + " and " + str(maximum) + ": " guess = int(raw_input(statement)) tries = 0 while guess != number: if guess > maximum or guess < minimum: print "Number out of range" elif guess < number: print "Too low" elif guess > number: print "Too high" guess = int(raw_input(statement)) tries += 1 print "Correct number!" print "Number of tries: ", tries + 1
import streamlit as st import gspread as gsp import pandas as pd from df2gspread import df2gspread as d2g from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials # Authorising the code with the client key credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json') gc = gsp.authorize(credentials) st.title("Preliminary List Automation") st.write("Refer to the side bar on the left") st.sidebar.title("Points to remember") st.sidebar.write("1. Don't forget to change the edit access before pasting the link") st.sidebar.write("2. Giving the same name to a sheet will modify an existing sheet for a given workbook") # Give the user options to choose from the list of courses final_select = st.selectbox("All Courses",["CS","MIS","BA","DS","MEM"]) # Give the user input fields for # GPA # GRE # WORK-EX gpa = st.number_input("Enter student GPA") gre = st.number_input("Entet student GRE score") work = st.number_input("Enter the work experience in years") link_to_user_sheet = st.text_input("Please paste the URL of the students Google Sheet only") name_of_sheet = st.text_input("Enter the name you wish to give this sheet") # Code to strip the sheet_ID sheet_Id = link_to_user_sheet.split('/')[5] if link_to_user_sheet != '' else link_to_user_sheet submit = st.button("Submit") # Computer Science if submit: if final_select == "CS": st.text("You choose Computer Science") gpa_weight = 0.75 gre_weight = 0.15 work_weight = 0.1 score = (gpa_weight * gpa) + (gre_weight * gre) + (work_weight * work) if score >= 55: st.text("The student is excellent!") df = pd.read_csv('./computer_science/Computer_Science_Masters_List - EXCELLENT_PROFILE.csv', index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 53) and (score < 55): st.text("The student is good!") df = pd.read_csv('./computer_science/Computer_Science_Masters_List - GOOD_PROFILE.csv', index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 50) and (score < 53): st.text("The student is average") df = pd.read_csv('./computer_science/Computer_Science_Masters_List - AVERAGE_PROFILE.csv', index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) else: st.text("You know what to do!") df = pd.read_csv('./computer_science/Computer_Science_Masters_List - POOR_PROFILE.csv', index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # Mangagement Information Systems and Software Engineering if final_select == "MIS": st.text("You choose Management Information Systems and Software Engineering") gpa_weight = 0.6 gre_weight = 0.15 work_weight = 0.25 score = (gpa_weight * gpa) + (gre_weight * gre) + (work_weight * work) if score >= 55: st.text("The student is excellent!") df = pd.read_csv('./information_systems/MIS - MIS-Excellent.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 52) and (score < 55): st.text("The student is good!") df = pd.read_csv('./information_systems/MIS - MIS-Good.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 49) and (score < 51): st.text("The student is average") df = pd.read_csv('./information_systems/MIS - MIS-Average.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) else: st.text("You know what to do!") df = pd.read_csv('./information_systems/MIS - MIS-Poor.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # Business Analytics if final_select == "BA": st.text("You choose Business Analytics") gpa_weight = 0.6 gre_weight = 0.15 work_weight = 0.25 score = (gpa_weight * gpa) + (gre_weight * gre) + (work_weight * work) if score >= 55: st.text("The student is excellent!") df = pd.read_csv('./business_analytics/Business Analytics - BA-Excellent.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 52) and (score < 55): st.text("The student is good!") df = pd.read_csv('./business_analytics/Business Analytics - BA-Good.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 49) and (score < 51): st.text("The student is average") df = pd.read_csv('./business_analytics/Business Analytics - BA-Average.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) else: st.text("You know what to do!") df = pd.read_csv('./business_analytics/Business Analytics - BA-Poor.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # Data Science if final_select == "DS": st.text("You choose Data Science") gpa_weight = 0.6 gre_weight = 0.25 work_weight = 0.15 score = (gpa_weight * gpa) + (gre_weight * gre) + (work_weight * work) if score >= 86: st.text("The student is excellent!") df = pd.read_csv('./data_science/Data_Science - DS-Excellent.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 84) and (score < 86): st.text("The student is good!") df = pd.read_csv('./data_science/Data_Science - DS-Good.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 79) and (score < 84): st.text("The student is average") df = pd.read_csv('./data_science/Data_Science - DS-Average.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) else: st.text("You know what to do!") df = pd.read_csv('./data_science/Data_Science - DS-Poor.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # Engineering Management if final_select == "MEM": st.text("You choose Engineerig Management") gpa_weight = 0.75 gre_weight = 0.10 work_weight = 0.15 score = (gpa_weight * gpa) + (gre_weight * gre) + (work_weight * work) if score >= 39: st.text("The student is excellent!") df = pd.read_csv('./engineering_management/Engineering Management - MEM-Excellent.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 38) and (score < 39): st.text("The student is good!") df = pd.read_csv('./engineering_management/Engineering Management - MEM-Good.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) elif (score >= 35) and (score < 38): st.text("The student is average") df = pd.read_csv('./engineering_management/Engineering Management - MEM-Average.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) else: st.text("You know what to do!") df = pd.read_csv('./engineering_management/Engineering Management - MEM-Poor.csv',index_col=False) d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # Industrial Engineering # if final_select == "IE": # st.text("You choose Industrial Engineering") # gpa_weight = 0.75 # gre_weight = 0.10 # work_weight = 0.15 # score = (gpa_weight * gpa) + (gre_weight * gre) + (work_weight * work) # if score >= 39: # st.text("The student is excellent!") # df = pd.read_csv('./industrial_engineering/') # d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # elif (score >= 38) and (score < 39): # st.text("The student is good!") # df = pd.read_csv('./industrial_engineering/') # d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # elif (score >= 35) and (score < 38): # st.text("The student is average") # df = pd.read_csv('./industrial_engineering/') # d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet) # else: # st.text("You know what to do!") # df = pd.read_csv('./industrial_engineering/') # d2g.upload(df, gfile=sheet_Id, col_names=True, credentials=credentials, wks_name=name_of_sheet)
from collections import namedtuple Datapoint = namedtuple('Datapoint', ['attributes', 'label']) def attributes(dataset): ''' Return an iterator of the attributes in the dataset. ''' for p in dataset: yield p.attributes def labels(dataset): ''' Return an iterator of the labels in the dataset. ''' for p in dataset: yield p.label def attributes_and_labels(dataset): ''' Return an iterator of the attributes and labels in the dataset. ''' for a, l in zip(attributes(dataset), labels(dataset)): yield a, l def single_attribute(dataset, index): ''' Return an iterator of the attribute fixed. ''' if(index >= len(dataset[0].attributes) or index < 0): print(index) raise Exception('Attribute selected does not exists') for datapoint in dataset: yield datapoint.attributes[index] def datapoints_and_labels(dataset): ''' Return an iterator of the datapoints and labels in the dataset. ''' for p, l in zip(dataset, labels(dataset)): yield p, l def read_dataset(filename, id_column=None, label_column=-1, cast_functions=None): ''' Return a dataset (list of Datapoints) based on the given CSV file. The first row must be of headers and will be used to figure the number of columns. label is the column number for the labels and ident is the column number of the identifier, which will be ignored. cast_functions is a list of functions used to cast each row. For example, if cast_functions == [None, int, float, str, lambda x: 0 if x == 'a' else 1] then id_column must be 0, the second column will be cast to integers, the third to floats and the fourth to strings. The last will be 0 if the value is 'a' and 1 otherwise. This can be used to cast labels which are not numeric. All float attributes will be normalized. ''' with open(filename) as csv: header = csv.readline().strip().split(',') num_columns = len(header) maxs = [float('-inf')]*num_columns mins = [float('+inf')]*num_columns label_column = label_column%num_columns rows = [] for row in csv: row = row.strip().split(',') for i, c in enumerate(row): if i != id_column: row[i] = cast_functions[i](c) if type(row[i]) == float: maxs[i] = max(maxs[i], row[i]) mins[i] = min(mins[i], row[i]) rows.append(row) dataset = [] for row in rows: label = row[label_column] attributes = [] for i, c in enumerate(row): if i == label_column or i == id_column: continue if type(row[i]) == float and maxs[i] != mins[i]: row[i] = (c - mins[i])/(maxs[i] - mins[i]) attributes.append(row[i]) dataset.append(Datapoint(attributes, label)) return dataset
from tkinter import * import math class calc: def getandreplace(self): self.expression = self.e.get() self.newtext = self.expression.replace('/', '/') self.newtext = self.newtext.replace('x', '*') def equals(self): self.getandreplace() try: self.value = eval(self.newtext) except SyntaxError or NameError: self.e.delete(0, END) self.e.insert(0, 'Invalid Input') else: self.e.delete(0, END) self.e.insert(0, self.value) def sqaureroot(self): self.getandreplace() try: self.value = eval(self.newtext) except SyntaxError or NameError: self.e.delete(0, END) self.e.insert(0, 'Invalid Input') else: self.sqrtval = math.sqrt(self.value) self.e.delete(0, END) self.e.insert(0,self.sqtrval) def sqaurer(self): self.getandreplace() try: self.value = eval(self.newtext) except SyntaxError or NameError: self.e.delete(0, END) self.e.insert(0, 'Invalid Input') else: self.sqval = math.pow(self.value, 2) self.e.delete(0, END) self.e.insert(0, self.sqval) def clear1(self): self.txt = self.e.get()[:-1] self.e.delete(0, END) self.e.insert(0, self.txt) def clearall(self): self.e.delete(0, END) def action(self, argi): self.e.insert(END,argi) def __init__(self,master): master.title('Calculator') master.geometry() self.e = Entry(master) self.e.grid(row=0, column = 0, columnspan = 6, pady=3) self.e.focus_set() #creating Buttons Button(master,text = "=",width = 11,height=3,fg="black",bg="light grey",command = lambda:self.equals()).grid(row=4,column=4,columnspan=2) Button(master,text = "AC",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.clearall()).grid(row=1,column=4) Button(master,text = "C",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.clear1()).grid(row=1,column=5) Button(master,text = "+",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('+')).grid(row=4,column=3) Button(master,text = "x",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('x')).grid(row=2,column=3) Button(master,text = "-",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('-')).grid(row=3,column=3) Button(master,text = "%",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('%')).grid(row=4,column=2) Button(master,text = "/",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('/')).grid(row=1,column=3) Button(master,text = "7",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('7')).grid(row=1,column=0) Button(master,text = "8",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('8')).grid(row=1,column=1) Button(master,text = "9",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('9')).grid(row=1,column=2) Button(master,text = "4",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('4')).grid(row=2,column=0) Button(master,text = "5",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('5')).grid(row=2,column=1) Button(master,text = "6",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('6')).grid(row=2,column=2) Button(master,text = "1",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('1')).grid(row=3,column=0) Button(master,text = "2",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('2')).grid(row=3,column=1) Button(master,text = "3",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('3')).grid(row=3,column=2) Button(master,text = "0",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('0')).grid(row=4,column=0) Button(master,text = ".",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('.')).grid(row=4,column=1) Button(master,text = "(",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('(')).grid(row=2,column=4) Button(master,text = "(",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action(')')).grid(row=2,column=5) Button(master,text = "?",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.sqaureroot('?')).grid(row=3,column=4) Button(master,text = "^",width = 5,height=3,fg="black",bg="light grey",command = lambda:self.action('^')).grid(row=3,column=5) #driver code root = Tk() obj = calc(root) root.mainloop()
import cv2 import numpy as np # This file is about intensity transformation in a image. # I will use three functions for that, negative to show a negative imagem, # e logarithmic and exponential to increase or decrease the constrast. img = cv2.imread("pout.tif", 0) #img = cv2.imread("negative.jpeg") #Colorful Image cv2.imshow("Image", img) #cv2.waitKey(0) def negative(r, L): return L - 1 - r def logarithmic(r, c): return c*np.log(1+r) def exponential(r, c, gama): return c*r**gama def transformation(image): lines, cols = image.shape #get the quantity of lines and columns of the image #s = np.zeros((lines, cols), dtype=np.int) #Create a matrix of zeros in the same dimension of the passed image by parameter -> FAIL s = image L = 256 - 1 c = 1 gama = 0.8 for i, row in enumerate(image): for j, col in enumerate(row): r = image[i][j] s[i][j] = negative(r, L) #s[i][j] = logarithmic(r, c) #s[i][j] = exponential(r, c, gama) #lambda is a reserved word in python return s def colorfulTransformation(image): lines, cols, colors = image.shape #get the quantity of lines, columns and colors of the image #s = np.zeros((lines, cols, colors), dtype=np.int) #Create a matrix of zeros in the same dimension of the passed image by parameter -> FAIL s = image L = 65536 #16 bits image c = 1 gama = 0.7 for i, row in enumerate(image): for j, col in enumerate(row): for k, cor in enumerate(col): r = image[i][j][k] s[i][j][k] = negative(r, L) #s[i][j][k] = logarithmic(r, c) #s[i][j][k] = exponential(r, c, gama) #lambda is a reserved word in python return s img2 = transformation(img) cv2.imshow("Transformed Image", img) cv2.waitKey(0) print img
def number_in_range(low, high, number): if(low < number and high > number): return True else: return False number1= 1 number10 = 10 number_in_the_range = 4 number_out_range = -5 number_too_high = 100 isnumberinrange = number_in_range(number1, number10, number_in_the_range) print(isnumberinrange) number_in_range(number1, number10, number_out_range) number_in_range(number1, number10, number_too_high)
''' Problem 1 ''' people = int(input("How many people are attending to the campfire?")) if (people == 1): print("Just you then?") if (people == 2): print("Bring marshmellows, please") if (people >= 3): print("More than 3 is a crowd") if(people >= 7): print("Party") if (people < 0): print("Which dimension have you entered?") ''' Problem 2 ''' speed_limit5 = 55 speed_limit15 = 65 speed = int(input(">")) speed_limit = 50 license_loss= 50 * 2 bdaycop = str(input("Is it your birthday?")) bday = "Yes" if(speed < speed_limit): print("No ticket") if(bdaycop == bday): print("Happy birthday to you, happy birthday dear David, Happy birthday to you") speed = speed - 5 if(speed > speed_limit and speed < speed_limit5): if(bdaycop == bday): speed = speed - 5 print("warning") if(speed > speed_limit5 and speed < speed_limit15): if(bdaycop == bday): speed = speed - 5 print("Small Ticket") if(speed > speed_limit15 and speed < license_loss): if(bdaycop == bday): speed = speed - 5 print("Big ticket") if(speed > license_loss): if(bdaycop == bday): speed = speed - 5 print("Immediate license loss")
print("Give me a number") number = input(">") factors_list =[] for x in range(1, int(number) + 1): if (int(number) % x == 0): factors_list.append(x) print(number,"has",len(factors_list),"factors, ","which are", factors_list)
""" problem 1 """ x = 5 y = 5.9 z = True w = "62" """ problem 2 """ a = float(input("please enter a number for a")) A_t = ((3**1 / 2) /4) * a A_s = a**2 b = .25 c = 5**(1/2) d = 5 * (5 + 2 * c) A_p = b * (d**(1/2)) * (a**2) print(" The area of the pentagon is " + str(A_p)) print(" The area of the triangle is " + str(A_t)) print(" The area of the square is " + str(A_s))
import math top = 20 def is_prime(x): if x == 2: return True if x % 2 == 0: return False for y in xrange(3, int(math.sqrt(x)) + 1, 2): if x % y == 0: return False return True def power_trip(x): if x * x > top: return x y = 2 while x ** y <= top: y += 1 return (x ** (y - 1)) def main(x): n = 1 for y in xrange(2, x + 1): if is_prime(y): n = n * power_trip(y) return n print main(top)
## 没有必须要求掌握,难度较大,如果是刚开始学习Python的同学,可以先跳过,一个月以后再回来看 ##1.理解闭包函数定义 ##2.理解闭包函数的调用 ##3.变量在不同函数中的作用域 # 闭包函数 # 函数定义 name = "鲸鱼" def func1(): print("我是func1") print(name) # 在函数func1 内在定义一个函数 def func2(): name = "虾米" print("我是func2") print(name) # 返回"肚子"里面的函数对象 return func2 # 不加括号叫做函数对象 # func1 # 加了括号叫做函数调用 # func1的调用,其实== func2 func22 = func1() ## fun22是 return的func2 的函数对象' func22()
import random as r import math class Map: def __init__(self, width, height, min_size = 10, max_size = 40, generate = True): if(min_size>max_size): raise OverflowError("Map minimum size cannot be greater than maximum size") self.width = width self.height = height self.rooms = [] self.min_size = min_size self.min_room_width = math.ceil(math.sqrt(min_size)) self.min_room_height = math.ceil(math.sqrt(min_size)) self.max_size = max_size self.max_room_width = math.ceil(math.sqrt(max_size)) self.max_room_height = math.ceil(math.sqrt(max_size)) self.room_map_str = "" self.wall_map = [] if(generate): self.generate(Point(0,0),Point(self.width,0),Point(0,self.height),Point(self.width,self.height)) self.generate_wall_map(); self.generate_room_map_str(); ''' Creates an array of characters that define the walls of the map ''' def generate_wall_map(self): #Create a blank width x height array y=0 while(y<=self.height): x=0; arry = [] while(x<=self.width): arry.append(".") x+=1 self.wall_map.append(arry) y+=1 #print(len(self.wall_map)) for room in self.rooms: p1x = room.p1.x p2x = room.p2.x p3x = room.p3.x p4x = room.p4.x p1y = room.p1.y p2y = room.p2.y p3y = room.p3.y p4y = room.p4.y #print(str(room)); #draw upper wall i=p1x while(i<=p2x): self.wall_map[i][p1y]="#" i+=1 #draw bottom wall i=p3x while(i<=p4x): self.wall_map[i][p3y]="#" i+=1 #draw right wall i=p1y while(i<=p3y): self.wall_map[p1x][i]="#" i+=1 #draw right wall i=p2y while(i<=p4y): self.wall_map[p2x][i]="#" i+=1 ''' Creates a string of characters that can be displayed using the print command ''' def generate_room_map_str(self): string = "" y=0 while(y<self.height+1): x=0; while(x<self.width+1): string+=" " string+=self.wall_map[x][y] x+=1 string+="\n" y+=1 self.room_map_str = string return string ''' Recursively creates a set of rooms defined by the min and max parameters defined in the Map object ''' def generate(self,p1,p2,p3,p4): room = Room(p1,p2,p3,p4) if(room.width<=self.min_room_width): vertical = 0 elif(room.height<=self.min_room_height): vertical = 1 else: vertical = r.randint(0,1) if(room.size<=self.max_size): self.rooms.append(room) return if(vertical): if(p1.x+self.min_room_width<p2.x-self.min_room_width): rand = r.randint(p1.x+self.min_room_width,p2.x-self.min_room_width) v1 = Point(rand,p1.y) v2 = Point(rand,p3.y) self.generate(p1,v1,p3,v2) self.generate(v1,p2,v2,p4) else: self.rooms.append(room) else: if(p1.y+self.min_room_height<p3.y-self.min_room_height): rand = r.randint(p1.y+self.min_room_height,p3.y-self.min_room_height) h1 = Point(p1.x,rand) h2 = Point(p2.x,rand) self.generate(p1,p2,h1,h2) self.generate(h1,h2,p3,p4) else: self.rooms.append(room) class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return"("+str(self.x)+", "+str(self.y)+")" class Room: def __init__(self,p1,p2,p3,p4): self.p1 = p1 self.p2 = p2 self.p3 = p3 self.p4 = p4 self.width = p2.x-p1.x self.height = p3.y-p1.y self.size = self.width*self.height def self_string(self): string = "" y=0 while(y<self.height): x=0; while(x<self.width): #Print Top Wall if(x==0 or x==self.width-1 or y==0 or y==self.height-1): string+="#" else: string+=" " x+=1 string+="\n" y+=1 return string def __str__(self): return str(self.p1)+" "+str(self.p2)+" "+str(self.p3)+" "+str(self.p4) from os import system, name while(True): map = Map(30, 30, 40, 50) print(map.room_map_str) input("Press enter to generate a new room\n") system('clear')
# crypto.py # -------------- # COMP1405A - Fall2020 ## Student: Queenie Li ## ID: 101185786 def encrypt(message, shift, alphabet): result = "" for x in range(0,len(message)): for y in range(0,len(alphabet)): if message[x] == alphabet[y]: shift_position = y + shift if (shift_position) > len(alphabet) - 1: result = result + alphabet[shift_position - len(alphabet)] break else: result = result + alphabet[shift_position] break y = y + 1 x = x + 1 print(result) def passwordIsValid(passwd): #length > 5 if len(passwd) < 5: return False #2 digits numbers = '0123456789' for i in range(len(passwd)): if passwd[i] in numbers: break elif i == len(passwd) - 1: return False #special char special_characters = '!@#$%^_' for i in range(len(passwd)): if passwd[i] in special_characters: break elif i == len(passwd) - 1: return False #upper and lower upper_lower_found = False for i in range(len(passwd)): if passwd[i].isupper() == True: for h in range(len(passwd)): if passwd[h].islower() == True: upper_lower_found = True if upper_lower_found == False: return False #start alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' if passwd[0] !='_': if passwd[0] not in alphabet: return False return True
nums = [1, 2, 3, 4, 5] words = ['one', 'two', 'three', 'four', 'five'] d = dict(zip(nums, words)) print(d) print(type(d)) d1 = {} for i, val in enumerate(nums): d1[val] = words[i] print(d1) print(type(d1)) def listtodict(list1, list2): return dict(max(vars(__builtins__).items())[1](list1, list2)) d3 = listtodict(nums, words) print(d3) print(type(d3))
from collections import deque class Stack: def __init__(self): self.stack=deque() def push(self,data): self.stack.append(data) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] def empty(self): return len(self.stack)==0 def size(self): return len(self.stack) def display(self): print(self.stack) s=Stack() print(s.empty()) s.push(5) s.push(4) s.push(3) s.push(2) s.push(1) print(s.display()) s.pop() s.pop() print(s.display()) print(s.peek())
class Multiples: global numberOfMultiples global multiplier global multiplicand def MultiplesInARange(self, multiplier, numberOfMultiples): multiplicand=1 multipleslist = list() while(multiplicand<numberOfMultiples): product=multiplier*multiplicand multipleslist.append(product+1) multiplicand+1 return product def IsDefinedMultiplier(self, number): self.multiplier=number def ValidNumberOfMultiples(self, number): self.numberOfMultiples=number def MultiplesRange(self): multiplicand=1 a =[] while(multiplicand <= self.numberOfMultiples): a.append(self.multiplier*multiplicand) multiplicand=multiplicand+1 return a def MultiplesUnderAMax(self, maxnum): multiplicand=1 product=0 b=[] while(product<maxnum): product=self.multiplier*multiplicand b.append(product) multiplicand=multiplicand+1 return b
from tkinter import * def click(event): text = event.widget.cget("text") print(text) if text == "=": if scvalue.get().isdigit(): value = int(scvalue.get()) else: try: value = eval(screen.get()) except EXCEPTION as e: print(e) value = "ERROR" scvalue.set(value) screen.update() elif text == "C": scvalue.set("") screen.update() else: scvalue.set(scvalue.get() + text) screen.update() root = Tk() root.geometry("644x900") root.title("Calculator by Atul") scvalue = StringVar() scvalue.set(" ") screen = Entry(root, text=scvalue, font="lucida 40 bold") screen.pack(fill="x", ipadx=8 , pady=4, padx=10) f = Frame(root, bg="grey") b = Button(f, text="9", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="8", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="7", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) f.pack() f = Frame(root, bg="grey") b = Button(f, text="6", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="5", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="4", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) f.pack() f = Frame(root, bg="grey") b = Button(f, text="3", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="2", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="1", padx=15, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) f.pack() f = Frame(root, bg="grey") b = Button(f, text="0", padx=16, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="-", padx=20, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="*", padx=18, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) f.pack() f = Frame(root, bg="grey") b = Button(f, text="/", padx=23, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="+", padx=14, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="=", padx=13, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) f.pack() f = Frame(root, bg="grey") f.pack() b = Button(f, text="%", padx=9, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text="C", padx=11, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) b = Button(f, text=".", padx=21, pady=4, font="lucida 35 bold") b.pack(side=LEFT, padx=10, pady=5) b.bind("<Button-1>", click) root.mainloop()
# coding: utf-8 # タプルを用いて公約数を求めるプログラム # 順序型と多重代入の利用 def findDivisors (n1, n2): """n1とn2を正のint型とする。 n1とn2のすべての公約数からなるタプルを返す""" divisors = () for i in range(1, min(n1, n2) + 1): if n1 % i == 0 and n2 % i == 0: divisors = divisors + (i,) return divisors def findExtremeDivisors(n1, n2): """n1とn2を正のint型とする。 n1とn2の 最小の公約数 > 1 と 最大公約数 からなるタプルを返す""" divisors = () minVal, maxVal = None, None for i in range(2, min(n1, n2) + 1): if n1 % i == 0 and n2 % i == 0: if minVal == None or i < minVal: minVal = i if maxVal == None or i > maxVal: maxVal = i return (minVal, maxVal) def main(): divisors = findDivisors(100, 200) print divisors total = 0 for d in divisors: total += d print total minDivisor, maxDivisor = findExtremeDivisors(100,200) print minDivisor print maxDivisor if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # *幾何分布* # 幾何分布は指数分布を離散化したものである # それは最初の成功までの必要な独立試行の回数を表す import random import pylab def successfulStarts(eventProb, numTrials): """eventProb : 一回の試行で成功する確率を表す浮動小数点数 numTrials : 正の整数 各実験において,成功するまでに必要な試行の回数を出力する""" triesBeforeSuccess = [] for t in range(numTrials): consecFailures = 0 while random.random() > eventProb: consecFailures += 1 triesBeforeSuccess.append(consecFailures) return triesBeforeSuccess random.seed(0) probOfSuccess = 0.5 numTrials = 5000 distribution = successfulStarts(probOfSuccess, numTrials) pylab.hist(distribution, bins = 14) pylab.xlabel('Tries Before Success ') pylab.ylabel('Number of Occurrences Out of ' + str(numTrials)) pylab.title('Probability of Starting Each Try' + str(probOfSuccess)) pylab.show()
# coding: utf-8 # 様々なソート ## 選択ソート ## 計算量O(n^2) インプレースなので外部記憶は定数サイズ def selSort(L): """Lを、>を用いて比較できる要素からなるリストとする Lを、昇順にソートする""" suffixStart = 0 while suffixStart != len(L): #サフィックスの各要素を見る for i in range(suffixStart, len(L)): if L[i] < L[suffixStart]: #要素を入れ替える L[suffixStart], L[i] = L[i], L[suffixStart] suffixStart += 1 ## マージソート ## 計算量O(nlogn) リストのコピーを利用するため空間計算量がO(len(L)) def merge(left, right, compare): """leftとrightをソート済みのリストとし、 compareを要素間の順序を定義する関数とする (left + right)と同じ要素からなり、 compareに従いソートされた新たなリストを返す""" result = [] i, j = 0, 0 while i < len(left) and j < len(right): if compare(left[i], right[j]): result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 while (i < len(left)): result.append(left[i]) i += 1 while (j < len(right)): result.append(right[j]) j += 1 #print result return result import operator def mergeSort(L, compare = operator.lt): """Lをリストとし、 compareをLの要素間の順序を定義する関数とする Lと同じ要素からなり、ソートされた新たなリストを返す""" if len(L) < 2: return L[:] else: middle = len(L)//2 left = mergeSort(L[:middle], compare) right = mergeSort(L[middle:], compare) return merge(left, right, compare)
def withdraw_money(current_balance, amount): if (current_balance >= amount): current_balance = current_balance - amount else: print("Insufficnet funds") return current_balance def add2 (number): output = number + 2 return output answer = add2(3) print("The answer is: ", answer) ##balance = withdraw_money(10, 200) ##print("Current Balance: ", balance)
''' Source Name: label.py Author: Brandon McLellan Last Modified: August 7th, 2012 Last Modified By: Brandon McLellan Description: Revision History: Revision 3: - Added easy way of mass-updating options. Revision 2: - Overhauled label options Revision 1: - Brought label class in from previous assignment. ''' import pygame ''' Label Class Provides a easy, uniform way to place text in my game. ''' class Label(pygame.sprite.Sprite): Left = 0 Center = 1 Right = 2 def __init__(self, x, y, text): pygame.sprite.Sprite.__init__(self) # Basic label options self.x = x self.y = y self.color = (255,255,255) self.text = text # Font options self.fontSize = 12 self.fontName = "Tahoma" self.bold = False self.underlined = False self.italic = False self.align = Label.Left #Allows for easy mass-option changes. def options(self, **kwargs): for key in kwargs: self.__dict__[key] = kwargs[key] def update(self): #Setup font with proper values for rendering font = pygame.font.SysFont(self.fontName, self.fontSize) font.set_underline(self.underlined) font.set_bold(self.bold) font.set_italic(self.italic) #Render text self.image = font.render(str(self.text), True, self.color) self.rect = self.image.get_rect() # Determine label position based on alignment if self.align == Label.Left: self.rect.x = self.x self.rect.y = self.y elif self.align == Label.Center: self.rect.centerx = self.x self.rect.centery = self.y elif self.align == Label.Right: self.rect.right = self.x self.rect.y = self.y
#22/123 L = ['michael','sarah','tracy','bob','jack'] print(L) print([L[0],L[1],L[2]]) r = [] n = 3 for i in range(n): r.append(L[i]) print(r) print(L[0:3]) print(L[:3]) print(L[1:3]) print(L[-2:]) print(L[-2:-1]) L = list(range(100)) print(L) print(L[:10]) print(L[-10:]) print(L[10:20]) print(L[:10:2]) print(L[::5]) print(L[:]) print((0,1,2,3,4,5)[:3]) print('ABCDEFG'[::2]) print('ABCDEFG'[:3])
#23/123 d = {'a':1,'b':2,'c':3} for key in d: print(key) for value in d.values(): print(value) for k,v in d.items(): print(k,v) for ch in 'ABC': print(ch) from collections import Iterable print(isinstance('abc',Iterable)) print(isinstance([1,2,3],Iterable)) print(isinstance(123,Iterable)) for i, value in enumerate(['a','b','c']): print(i,value) for x,y in [(1,1),(2,4),(3,9)]: print(x,y)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} x # @return {ListNode} def partition(self, head, x): if not head or not head.next: return head l,r = ListNode(0),ListNode(0) result,rstart = ListNode(0),ListNode(0) result.next = l rstart.next = r while head: if head.val<x: l.next = head l = l.next else: r.next = head r = r.next head = head.next l.next = rstart.next.next r.next = None return result.next.next
class Solution: # @param {integer} dividend # @param {integer} divisor # @return {integer}' def divide(self, dividend, divisor): if dividend == -1*math.pow(2,31) and divisor==-1: return int(math.pow(2,31)-1) result = 0 flag = -1 rem = abs(dividend) tmp = abs(divisor) if rem == dividend and tmp==divisor: flag = 1 elif rem!=dividend and tmp!=divisor: flag = 1 while rem>=tmp: c = tmp count = 1 while c<=rem: rem-=c result+=count c = c+c count = count+count return result*flag
class Solution: # @param {string} s # @return {integer} def lengthOfLastWord(self, s): if len(s)==0: return 0 result = "" for i in range(len(s)): if s[-1-i]!=" ": result+=s[-1-i] elif len(result)!=0: break return len(result)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param two ListNodes # @return the intersected ListNode def getIntersectionNode(self, headA, headB): if headA is None or headB is None: return None count = 0 result = None p1,p2 = headA,headB while p1!=None and p2!=None: if p1 is p2: result = p1 break p1 = p1.next p2 = p2.next if p1 is None and count==0: p1 = headB count+=1 if p2 is None: p2 = headA return result
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): if not head: return False s,f = ListNode(0),head s.next = head while f and f.next: f = f.next.next s = s.next if f is s: return True return False
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ import heapq class Solution: """ @param lists: a list of ListNode @return: The head of one sorted list. """ def mergeKLists(self, lists): # write your code here helper = [] length = len(lists) if not length: return None for i in range(length): if lists[i]: helper.append((lists[i].val, lists[i])) heapq.heapify(helper) result = ListNode(0) cur = result while helper: tmp = heapq.heappop(helper) cur.next = ListNode(tmp[0]) cur = cur.next if tmp[1].next: heapq.heappush(helper, (tmp[1].next.val, tmp[1].next)) return result.next
import sqlite3 from sqlite3 import Error import datetime from math import pi, acos, cos, sin #! ***** MENU ***** def menu(): linha(40) print('--- MENU ---') linha(40) print('1- Criar db') print('2- Criar tabelas') print('3- Insere dados') print('4- Atualizar dados') print('5- Selecionar dados') print('6- Apagar dados') linha(40) print('0- sair do programa') linha(40) opcao = int(input('Opção -> ')) linha(40) return opcao def linha(tam=120): print('-' * tam) #! ***** MENU 1 ***** def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) print(f'SQLite v{sqlite3.version}') return conn except Error as e: print(e) return conn #! ***** MENU 2 ***** def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def main_create(db_file): sql_create_projects_table = """CREATE TABLE IF NOT EXISTS projects ( id integer PRIMARY KEY, data_hora datetime NOT NULL, latitude float NOT NULL, longitude float NOT NULL, accuracy int NOT NULL, info bool NOT NULL, distancia float NOT NULL, tempo time NOT NULL );""" sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks ( project_id integer NOT NULL, data_hora datetime NOT NULL, type text NOT NULL, confidence int NOT NULL, FOREIGN KEY (project_id) REFERENCES projects (id) );""" # create a database connection conn = create_connection(db_file) # create tables if conn is not None: # create projects table create_table(conn, sql_create_projects_table) # create tasks table create_table(conn, sql_create_tasks_table) else: print("Error! cannot create the database connection.") return conn #! ***** MENU 3 ***** def create_project(conn, project): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO projects(data_hora,latitude,longitude,accuracy,info,distancia,tempo) VALUES(?,?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, project) return cur.lastrowid def create_task(conn, task): """ Create a new task :param conn: :param task: :return: """ sql = ''' INSERT INTO tasks(project_id,data_hora,type,confidence) VALUES(?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, task) return cur.lastrowid def distancia(la1, la2, lo1, lo2): """ #* Fórmula: #* Diâmetro da terra = 6378.137 Km #* coordenadas (latitude e longitude) em radianos #* distancia = d_terra * acos(cos(lat1) * cos(lat2) * cos(long2 - long1) + sin(lat1) * sin(lat2)) #* acos(-1 <= x <= 1) // erro: 1.0000000000000002 #* distancia = x Km """ def radianos(coordenada): return coordenada * pi / 180 d_terra = 6378.137 la1 = radianos(la1) la2 = radianos(la2) lo1 = radianos(lo1) lo2 = radianos(lo2) _ = cos(la1) * cos(la2) * cos(lo2 - lo1) + sin(la1) * sin(la2) if _ == 1.0000000000000002: _ = 1.0 _ = acos(_) dist = d_terra * _ dist = round(dist, 3) return dist def tempo_convert(t): t = str(t) return datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S') def main_insert(db_file, json_data): # create a database connection conn = create_connection(db_file) with conn: count = 1 for local in json_data['locations']: state1 = state2 = True try: _ = local['timestampMs'] except: state1 = False else: _ = int(_[0:10]) timestampMs = datetime.datetime.utcfromtimestamp(_) try: _ = local['latitudeE7'] except: state1 = False else: latitudeE7 = float(_ / 10000000) try: _ = local['longitudeE7'] except: state1 = False else: longitudeE7 = float(_ / 10000000) try: _ = local['accuracy'] except: state1 = False else: accuracy = int(_) try: _ = local['activity'] except: state2 = False else: _ts = _[0]['timestampMs'] _ts = int(_ts[0:10]) tsMs = datetime.datetime.utcfromtimestamp(_ts) _ = _[0]['activity'] tipo = _[0]['type'] confidence = int(_[0]['confidence']) if state1: if count == 1: lat1 = lat2 = latitudeE7 lon1 = lon2 = longitudeE7 dist_atual = dist_ant = 0 tempo_atual = tempo_convert(timestampMs) tempo_ant = tempo_atual tempo = str(tempo_atual - tempo_ant) else: lat1 = lat2 lon1 = lon2 lat2 = latitudeE7 lon2 = longitudeE7 dist_ant = dist_atual tempo_atual = tempo_convert(timestampMs) tempo = str(tempo_atual - tempo_ant) tempo_ant = tempo_atual dist_atual = distancia(lat1, lat2, lon1, lon2) count += 1 project = (timestampMs, latitudeE7, longitudeE7, accuracy, state2, dist_atual, tempo) project_id = create_project(conn, project) if state2: task = (project_id, tsMs, tipo, confidence) create_task(conn, task) return conn #! ***** MENU 4 ***** def update_task(conn, task): """ update priority, begin_date, and end date of a task :param conn: :param task: :return: project id """ sql = ''' UPDATE tasks SET priority = ? , begin_date = ? , end_date = ? WHERE id = ?''' cur = conn.cursor() cur.execute(sql, task) conn.commit() def main_update(db_file): # create a database connection conn = create_connection(db_file) with conn: update_task(conn, (2, '2015-01-04', '2015-01-06', 2)) return conn #! ***** MENU 5 ***** def select_all_tasks(conn): """ Query all rows in the tasks table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT * FROM tasks") rows = cur.fetchall() for row in rows: print(row) def select_task_by_priority(conn, priority): """ Query tasks by priority :param conn: the Connection object :param priority: :return: """ cur = conn.cursor() cur.execute("SELECT * FROM tasks WHERE confidence=?", (priority,)) rows = cur.fetchall() for row in rows: print(row) def main_select(db_file): # create a database connection conn = create_connection(db_file) with conn: print("1. Query task by priority:") select_task_by_priority(conn, 100) print("2. Query all tasks") select_all_tasks(conn) return conn #! ***** MENU 6 ***** def delete_task(conn, id): """ Delete a task by task id :param conn: Connection to the SQLite database :param id: id of the task :return: """ sql = 'DELETE FROM tasks WHERE id=?' cur = conn.cursor() cur.execute(sql, (id,)) conn.commit() def delete_all_tasks(conn): """ Delete all rows in the tasks table :param conn: Connection to the SQLite database :return: """ sql = 'DELETE FROM tasks' cur = conn.cursor() cur.execute(sql) conn.commit() def main_delete(db_file): # create a database connection conn = create_connection(db_file) with conn: delete_task(conn, 2); # delete_all_tasks(conn); return conn
class Player: def __init__(self, name, symbol): self.name = name self.symbol = symbol class Game: MAX_STEPS = 9 DEFAULT_SYMBOL = "_" def __init__(self): self.player_1 = Player("Игрок 1", "X") self.player_2 = Player("Игрок 2", "O") self.current_step = 0 self.current_player = None self.cells = None self.finish_results = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] def start(self): print("\n") print("_________________________________НОВАЯ_ИГРА_________________________________________") print("\n") self.cells = [] self.current_player = self.player_1 for i in range(3): self.cells.append([]) for j in range(3): self.cells[i].append(self.DEFAULT_SYMBOL) # Game loop for i in range(self.MAX_STEPS): self.show_game_state() is_input_correct = False while not is_input_correct: print(self.current_player.name, "(" + self.current_player.symbol + "),", "введите номер строки и столбца: ") try: data = input() except KeyboardInterrupt: print("Данные не получены. Игра окончена") exit(0) is_input_correct = self.check_input_data_correct(data) if not is_input_correct: print("Неправильный ввод!") self.show_game_state() column = int(data[0]) row = int(data[1]) self.cells[column][row] = self.current_player.symbol if self.check_game_finish(): self.show_game_result("Игра закончена. Победил игрок: " + self.current_player.name) self.start() else: self.change_player() self.show_game_result("Игра закончена. Ничья!") self.start() def check_input_data_correct(self, data): if len(data) != 2: return False try: column = int(data[0]) row = int(data[1]) except ValueError: return False if column > 2 or row > 2 or column < 0 or row < 0: return False if self.cells[column][row] != self.DEFAULT_SYMBOL: return False return True def change_player(self): if self.current_player == self.player_1: self.current_player = self.player_2 else: self.current_player = self.player_1 def show_game_state(self): for i in range(len(self.cells)): print("| ", end="") for j in range(len(self.cells[i])): symbol = self.cells[i][j] print(symbol, end=" | ") print("\n") def show_game_result(self, message): self.show_game_state() print("========================================================================") print("************************************************************************") print(message) print("************************************************************************") print("========================================================================\n") def check_game_finish(self): symbol = self.current_player.symbol cells_inline = [] for cols in self.cells: for cell in cols: cells_inline.append(cell) for result in self.finish_results: if cells_inline[result[0]] == symbol and cells_inline[result[1]] == symbol and cells_inline[result[2]] == symbol: return True return False if __name__ == '__main__': game = Game() game.start()
#!/usr/bin/python3 ''' module containing the recurse function ''' import requests def recurse(subreddit, hot_list=[]): ''' function that recursively finds a list of all hot topics of a subreddit Attributes: subreddit - subreddit to find hot topics of hot_list - list to store topics in Returns: list of hot topics or None if subreddit not found ''' url = "https://www.reddit.com/r/{}/hot.json".format(subreddit) headers = {'User-Agent': "macintosh:schoolproject (by /u/HolbertonSchool)"} r = requests.get(url, headers=headers, allow_redirects=False) if r.status_code == 200: recurse_helper(subreddit, hot_list) return hot_list else: return None def recurse_helper(subreddit, hot_list, after=""): ''' Helper function to do recursion after data is valid Attributes: subreddit - subreddit to query hot_list - list to store topic titles after - where to start url query count - how many titles have already been returned Returns: hot_list populated with titles ''' url = "https://www.reddit.com/r/{}/hot.json?limit=100&after={}".format( subreddit, after, count) headers = {'User-Agent': "macintosh:schoolproject (by /u/HolbertonSchool)"} r = requests.get(url, headers=headers, allow_redirects=False) new_after = r.json()['data']['after'] if new_after is not None: recurse_helper(subreddit, hot_list, new_after) for i in r.json()['data']['children']: hot_list.append(i['data']['title'])
import abc import hashlib from typing import Tuple MINIMAL_LENGTH_OF_SECURITY_STRING = 3 class PasswordRepository(abc.ABC): def __init__(self, username_hash_salt: str): PasswordRepository.verify_security_string_length(username_hash_salt, MINIMAL_LENGTH_OF_SECURITY_STRING, "Username salt") self.username_hash_salt = username_hash_salt @abc.abstractmethod def _save_password(self, username: str, password: str) -> None: pass @abc.abstractmethod def _load_password(self, username: str) -> str: pass def save_password(self, username: str, password: str) -> None: PasswordRepository.verify_security_string_length(username, MINIMAL_LENGTH_OF_SECURITY_STRING, "Username") PasswordRepository.verify_security_string_length(password, MINIMAL_LENGTH_OF_SECURITY_STRING, "Password") hashed_username = PasswordRepository._hash_with_salt(hashable=username, salt=self.username_hash_salt) hashed_password = PasswordRepository._hash_with_salt(hashable=password, salt=hashed_username) self._save_password(hashed_username, hashed_password) def validate_password(self, username: str, password: str) -> Tuple[bool, str]: hashed_username = PasswordRepository._hash_with_salt(hashable=username, salt=self.username_hash_salt) hashed_password = self._load_password(hashed_username) if hashed_password: if hashed_password == self._hash_with_salt(password, hashed_username): return True, "Match" else: return False, "No match" else: return False, "Not found" @staticmethod def _hash_with_salt(hashable: str, salt: str) -> str: return hashlib.sha256(salt.encode() + hashable.encode()).hexdigest() @classmethod def verify_security_string_length(cls, string, minimal_length, field_name): if not string or len(string)<minimal_length: raise ValueError(f"{field_name} must be of at least {minimal_length} characters")
class Cat: def eat(self): print("%s is eating"%self.name) def drink(self): print("it is drinking") tom = Cat() tom.name="TOM" tom.eat() print(tom) addr=id(tom) print("十进制is %d\n" %addr) lazy_cat=Cat() lazy_cat.name="大懒猫" lazy_cat.eat()
while i<(len(lst)): if type(lst[i]) ==type([]): round_list(lst[i],decimals) elif type(lst[i]) == [type(0.0),type([])]: i+=1 else: list1[i]=round(list1[i],decimals) i+=1
import numpy as np def get_mean(num_1, num_2): """Функция возвращает медианное число типа int из двух заданных""" mean = int(np.mean(range(num_1, num_2 + 1))) # поиск медианного числа return mean # возвращает медианное число def game_core_v3(number): """Угадывает путем называния медианного числа среди ряда возможных""" count = 1 # счетчик попыток min_num = 1 # минимальное число в ряде возможных чисел max_num = 100 # максимальное число в ряде возможных чисел predict = get_mean(min_num, max_num) # предполагаемое число while number != predict: # цикл пока не угадали число count += 1 # +1 к счетчику попыток if number > predict: # если загаданное число больше предполагаемого min_num = predict + 1 # меняет минимальное число ряда возможных elif number < predict: # если загаданное число меньше предполагаемого max_num = predict - 1 # меняет максимальное число ряда возможных predict = get_mean(min_num, max_num) # вычисляет предполагаемое число return count # возвращает кол-во попыток def score_game(game_core): """Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число""" count_ls = [] # список с количеством попыток, за которые удалось угадать число np.random.seed(1) # фиксирует RANDOM SEED, чтобы ваш эксперимент был воспроизводим! random_array = np.random.randint(1, 101, size=1000) # список из 1000 чисел от 1 до 100 for number in random_array: # цикл для каждого числа из списка count_ls.append(game_core(number)) # запускает игру и добавляет к списку попыток за сколько удалось угадать score = int(round(np.mean(count_ls))) # определение среднего числа попыток print(f"Ваш алгоритм угадывает число в среднем за {score} попыток") # вывод на экран среднего количества попыток return score # возвращает среднее количество попыток score_game(game_core_v3)
def file_reader(): arr = [] file = open("file .txt", "r") # File called data.txt must be in the same directory as the number_of_times.py # Read each line from the file for line in file: list = line.split() # Read each word from a line for word in list: arr.append(word) # Add each word to the array return arr; def welcome_user(): print('Welcome To Number Of Times') element = input("Enter Number or Word:") return element; def number_of_times(element, arr): count = 0 # Check items in arr that are equal to element for word in arr: if word == element: count = count + 1 # Print results as a statement print(element, 'appears ', count, 'times in the file') arr = file_reader() element = welcome_user() number_of_times(element, arr)
# Python3 has 5 built-in sequence types: # > string # > list # > tuple # > range # > bytes and bytearray # What is a sequence? # An ordered set of items # "Hello world" # ["PC", "Speakers", "Keyboard", "Mouse"] # Because a sequence is ordered, we can use indexing to access individual items in the sequence # Almost everything you can do with a string can be done with the other sequence types # However, not all sequence types can be multiplied or concatenated. For example, a range can't be concatenated. string1 = "he's " string2 = "probably " string3 = "pining " string4 = "for the " string5 = "fjords" print(string1 + string2 + string3 + string4 + string5) print("Hello " * 5) print("Hello " * (5 + 4)) print("Hello " * 5 + "4") today = "friday" print("day" in today) print("fri" in today) print("thur" in today)
def fibonacci(n: int) -> int: """ Return `n`th Fibonacci number for a positive value of `n`. The value of the number at position n in the Fibonacci equence is determined by: F[n] = F[n - 1] + F[n - 2] where: F[0] = 0 and F[1] = 1 """ prev = 0 current = 1 if 0 <= n <= 1: return n count = 1 while count < n: next = current + prev prev = current current = next count += 1 return current print(", ".join(str(fibonacci(i)) for i in range(1, 11))) print(fibonacci(6))
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head p=head.next pre=None while head: a=head b=a.next if b: head=b.next if pre: pre.next=b b.next=a else: b.next=a a.next=None pre=a else: head=b if pre: pre.next=a return p
class Solution(object): def isPalindrome(self, x): if x < 0 or (x%10 == 0 and x > 0): return False rev = 0 carry = -1 num = x temp = [] while num is not 0: temp.append(num % 10) carry += 1 num = num // 10 while carry > -1: print(temp, carry) rev += temp.pop(0) * 10 ** carry carry -= 1 print(rev) if x == rev: return True else: return False if __name__ == "__main__": solve = Solution() print(solve.isPalindrome(123)) print(solve.isPalindrome(-121)) print(solve.isPalindrome(10))
import urllib.request, json with urllib.request.urlopen("https://canlidoviz.com/borsa.jsonld") as url: data = json.loads(url.read()) a = data["mainEntity"]["itemListElement"] for i in a: b = i["currentExchangeRate"] print("{} = {}".format(i["currency"],b["price"]))
n = int(input("Enter Integer : ")) a = 0 for val in range(0,(n+1)) : a += (val/((val+1))) print(a)