text
stringlengths
37
1.41M
""" Triangulates 2D image points to create 3D object/world points. """ import cv2 import numpy as np def from_ip(ip, E=None, F=None): """ Calculates the distance from cam center to each point in IP. """ l_cam_mat = [np.eye(3, 3), np.zeros(1, 3)] if E: rx, ry, rz, _ = cv2.triangulatePoints(l_cam_mat, E, ip[0], ip[1]) elif F: rx, ry, rz, _ = cv2.triangulatePoints(l_cam_mat, F, ip[0], ip[1]) else: raise Exception("Need either E or F to triangulate distance.") return [rx, ry, rz] def main(): pass if __name__ == '__main__': main()
# for loop understands the lists paranoid_android = 'Marvin, the paranoid android' letters = list(paranoid_android) # for loop automatically detects the lists and works accordingly for alph in letters: print(alph) #for loop also detects the slices of the lists for alph in letters[:6]: print('\t',alph) print() for alph in letters[-7:]: print('\t'*2,alph) print() for alph in letters[12:20]: print('\t'*3,alph)
# sets don't allow duplicates, order is not guaranteed vowels = {'a','a','e','e','i','o','u','u'} # duplicates will be removed {'a', 'i', 'e', 'u', 'o'} print(vowels) # set from string vowels1 = set('aeeeeeeeiou') print(vowels1) # set operations word = 'hello' vowels2 = set('aeiou') # union {'e', 'l', 'o', 'h', 'i', 'a', 'u'} u = vowels2.union(set(word)) print(u) # difference {'a', 'u', 'i'} d = vowels2.difference(set(word)) print(d) # intersection {'o', 'e'} i = vowels2.intersection(set(word)) print(i)
class Bill: period_str: str bill_nbr: int customer_nickname: str customer_name: str customer_address: str customer_zip_place: str nbr_of_eggs: int price_per_egg: float = 0.6 def __init__(self, period_str: str, bill_nbr: int, customer_nickname: str, information_path: str, nbr_of_eggs: int): self.period_str = period_str self.bill_nbr = bill_nbr self.customer_nickname = customer_nickname self.get_postal_information(information_path, customer_nickname) self.nbr_of_eggs = nbr_of_eggs def get_postal_information(self, information_path: str, customer_name: str): information_path = information_path if information_path[-1] == "/" else information_path + "/" with open(information_path + customer_name + ".txt", 'r', encoding='utf-8') as f: self.customer_name = f.readline() self.customer_address = f.readline() self.customer_zip_place = f.readline() def get_bill_nbr_string(self) -> str: return str(self.bill_nbr).zfill(3)
# -*- coding: utf-8 -*- """ Created on Wed Sep 9 11:06:30 2020 @author: zorian Time to scramble some words? """ # user sees : ysk # goal: unscramble the word to sky words_to_scramble = ['man', 'woman', 'person', 'camera', 'television'] #import random from numpy import random #randomly choose a word from list word_choice = random.choice(words_to_scramble) #turn word into list of charecters char_list = list(word_choice) #1 scramble list of charecters random.shuffle(char_list) #2 join back as a string scrambled_word = ''.join(char_list) #print out the char list scrambled print(char_list) #3 give user a chance to guess guess = input(f'What does {char_list} mean?') #4 if user is correct tell them, if not let them guess again if guess == word_choice: print('Nice job') else: print('Wow you suck!') ################################### #scramble list random.shuffle(words_to_scramble) # display scrambled list words_to_scramble
class Person(object): def __init__(self, first_name, last_name, *args, **kwargs): self.first = first_name self.last = last_name def __str__(self): return "{} {}".format(self.first, self.last) def eat(self, food): print('eating ' + food) class Student(Person): def __init__(self, first_name, last_name, netid): print(super().__init__) super().__init__(first_name, last_name, netid) self.netid = netid; def __str__(self): return "{} {}, {}".format(self.first, self.last, self.netid) def study(self): print("study") class Teacher(Person): def __init__(self, first_name, last_name, *args, **kwargs): super().__init__(first_name, last_name, *args, **kwargs) def __str__(self): return "Professor {}".format(self.last) def teach(self): print("teaching") # multiple inheritance is fine! class GradStudent(Student, Teacher): def __init__(self, first_name, last_name, netid): print(super()) super().__init__(first_name, last_name, netid) print(GradStudent.mro()) g = GradStudent('Joe', 'Versoza', 'jjv222') g.teach() g.study()
""" composition ---- has a --> part of a whole relationship one object owns / contains --> another object MultipleChoiceQuestion Quiz --> has many MultipleChoiceQuestions Survey --> has many MultipleChoiceQuestions Code reuse FTW!!!! self.attribute_name = other_object ducktyping ----- * regardless of type, if object responds to method * that means that method can be invoked * (this isn't the case in all languages, like Java for example) polymoriphism ----- * objects of different types behaving the same way * in Python, ducktyping is (one) mechanism for polymorphism ^^^ """ """ class Duck: def quack(): print('quack') class NotADuck: def quack(): print('meow') d = Duck() n = NotADuck() type(d) == type(n) # False # but they can both quack sometimes it's good practice to explicitly inherit from object """ class Person(object): def __init__(self, first_name, last_name): self.first = first_name self.last = last_name def __str__(self): return "{} {}".format(self.first, self.last) def eat(self, food): print('eating ' + food) class Student(Person): def __init__(self, first_name, last_name, netid): print(super().__init__) super().__init__(first_name, last_name) self.netid = netid; def __str__(self): return "{} {}, {}".format(self.first, self.last, self.netid) def study(self): print("study") class Teacher(Person): def __init__(self, first_name, last_name, netid): super().__init__(first_name, last_name) def __str__(self): return "Professor {}".format(self.last) def teach(self): print("teaching") # multiple inheritance is fine! class GradStudent(Student, Teacher): def __init__(self, first_name, last_name, netid): print(super()) super().__init__(first_name, last_name, netid) print(GradStudent.mro()) g = GradStudent('Joe', 'Versoza', 'jjv222') g.teach() g.study() """ TODO: multiple inheritance and constructors p = Person('Joe', 'Versoza') s = Student('Joe', 'Versoza', 'jjv22') t = Teacher('Joe', 'Versoza', 'jjv22') print(p) print(s) print(t) p.eat("pineapple") s.eat("papaya") """ """ inheritance vs composition when??? it depends on the relationship you want has a --> part of whole --> composition is a --> one object can be considered as another --> inheritance favor composition over inheritance both ways to reuse code sometimes you can use either... """ class Door: def __init__(self): self.status = "closed" def open(self): self.status = "open" def close(self): self.status = "closed" def is_open(self): # true or false return self.status == "open" """ class LockableDoor(Door): def __init__(self, locked): super().__init__() self.locked = locked def open(self): if not self.locked: super().open() else: print("it's locked!") d1 = Door() d1.open() print(d1.is_open()) d2 = LockableDoor(True) d2.open() print(d2.is_open()) """ class LockableDoor(): def __init__(self, locked): self.locked = locked self.door = Door() def open(self): if not self.locked: self.door.open() else: print("It's locked") def is_open(self): return self.door.is_open() d2 = LockableDoor(True) d2.open() print(d2.is_open())
""" web_server.py ===== This file is both a web server and a web application in one. We'll consider a web server as a long running program that handles client connections, accepts requests and sends back responses. The web application is some program that works on the request and constructs a response. The server and the app work together to field requests and send back responses. We'll be creating a web site that's role-playing game themed (sooo nerdy). It'll respond to the following URLs: localhost:5000/creatures --> list out a bunch of creatures localhost:5000/ --> link to creatures and dice localhost:5000/dice --> generates a random number from 1 through 6 """ import socket # WEB APPLICATION import random class Request: """Represents an HTTP request. Parses a request and creates properties on this request instance. For example... if the request is: GET /dice HTTP/1.1 User-Agent: my suuuuper cool browser Accepts: text/html # req is an instance of Request: req.path --> "/dice" req.method --> "/GET" req.http_version --> "HTTP/1.1" This request object ignores the headers. """ def __init__(self, request_text): self.parse_request(request_text) def parse_request(self, request_text): """Extract path, method and http version from string version of HTTP request. Save in instance variables. """ # grab the first line (split by carriage return \r and newline \n - # http specs mention that \r\n represents newlines) request_parts = request_text.split('\r\n') parts = request_parts[0].split(' ') self.method, self.path, self.http_version = parts print(self.method, self.path, self.http_version) # routes contains mappings of paths to functions # for example, the path /dice would map to a function called dice: # {'/dice': dice} # that function will be called to generate a response routes = {} def route(path): """decorator (with parameter) for used to map a path to a function """ def decorator(old_f): # add path and function to routes dictionary routes[path] = old_f # just give back the old function unmodified return old_f return decorator @route('/') def home(req): html = 'The homepage! ' html += 'Check out <a href="/creatures">creatures</a> ' html += 'or <a href="/dice">dice</a>.' return html @route('/creatures') def creatures(req): return 'Creatures: <ul><li>Griffin</li><li>Zombie</li></ul>' @route('/dice') def dice(req): return "Dice Roll: {}".format(random.randint(1, 6)) # WEB SERVER HOST, PORT = '', 5000 QUEUE = 5 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(QUEUE) print('starting server on port', PORT) while True: client, address = s.accept() # we're using a fixed size here, but some strategies for getting "all" # of the data sent by the client include: # 1. fixed size (obvs) # 2. server and client agree on delimiter character so server knows when # all data is received # 3. client sends the number of bytes the server should expect and server # continues to recv until size data = client.recv(4096) if data: data_text = data.decode('utf-8') request_text = data_text req = Request(request_text) # get the function that handles the path of the incoming request handle_route = routes.get(req.path, None) if handle_route: # if the path exists, then our response will be the result # of using calling that function response_body = handle_route(req) # notice that the body comes after a blank line (2 \r\n's) res = 'HTTP/1.1 200 OK\r\nContent-Type:text/html\r\n\r\n{}'.format(response_body) else: # if the key doesn't exist, that means we don't have that # path! give back a 404 res = 'HTTP/1.1 404 Page not found\r\n\r\n<strong>404 - page not found</strong>' client.send(bytes(res, 'utf-8')) client.close()
""" The purpose of this code is to show how to work with plant.id API. You'll find API documentation at https://plant.id/api """ import base64 import requests from time import sleep secret_access_key = "-- ask for one at [email protected] --" class SendForIdentificationError(Exception): def __init__(self, m): self.message = m def __str__(self): return self.message def send_for_identification(file_names): files_encoded = [] for file_name in file_names: with open(file_name, "rb") as file: files_encoded.append(base64.b64encode(file.read()).decode("ascii")) params = { "latitude": 49.194161, "longitude": 16.603017, "week": 23, "images": files_encoded, "key": secret_access_key, "parameters": ["crops_fast"] } # see the docs for more optional attributes # for example "custom_id" allows you to work with your custom identifiers headers = { "Content-Type": "application/json" } response = requests.post("https://plant.id/api/identify", json=params, headers=headers) if response.status_code != 200: raise SendForIdentificationError(response.text) # this reference allows you to gather the identification result # (once it is ready) return response.json().get("id") def get_suggestions(request_id): params = { "key": secret_access_key, "ids": [request_id] } headers = { "Content-Type": "application/json" } # To keep it simple, we are pooling the API waiting for the server # to finish the identification. # The better way would be to utilize "callback_url" parameter in /identify # call to tell our server to call your"s server endpoint once # the identification is done. while True: print("Waiting for suggestions...") sleep(5) resp = requests.post("https://plant.id/api/check_identifications", json=params, headers=headers).json() if resp[0]["suggestions"]: return resp[0]["suggestions"] # more photos of the same plant increase the accuracy request_id = send_for_identification(["photo1.jpg", "photo2.jpg"]) # just listing the suggested plant names here (without the certainty values) for suggestion in get_suggestions(request_id): print(suggestion["plant"]["name"])
#!/usr/bin/env python """ info about project here """ __author__ = "Johannes Coolen" __email__ = "[email protected]" __status__ = "development" def plus(x, y): try: print(x + y) except Exception as e: print(e) main() def min(x, y): try: print(x - y) except Exception as e: print(e) main() def maal(x, y): try: print(x * y) except Exception as e: print(e) main() def delen(x, y): try: print(x / y) except Exception as e: print(e) main() def main(): try: getal1 = int(input("geef een natuurlijk getal")) getal2 = int(input("nu nog een alstublieft")) operator = input("wil je optellen(+) aftrekken(-) delen(/) of vermenigvuldigen(*)") if operator == '+': plus(getal1, getal2) elif operator == '-': min(getal1, getal2) elif operator == '*': maal(getal1, getal2) elif operator == '/': delen(getal1, getal2) else: raise Exception("ik vroeg +,-,*,/, aub") main() except Exception as e: print(e) main() if __name__ == '__main__': # code to execute if called from command-line main()
import json import csv import io filepath = input("Enter Path to your Json File: ") csv_filepath = input("Enter Name of your Csv File:") csv_filepath_format = csv_filepath + '.csv' json_file = io.open(filepath, 'r+', encoding="utf-8") csv_file = io.open(csv_filepath_format, 'w+', encoding="utf-8") json_parsed = json.loads(json_file.read()) csvwriter = csv.writer(csv_file) for emp in json_parsed: csvwriter.writerow(emp.values()) csv_file.close()
class TV: modelo: "" cor: "" fabricante: "" tamanho = 0 estado_tv = "Desligada" canal_atual = 0 volume_atual = 0 def mudarCanal(self, valor): self.canal_atual = valor def aumentarVolume(self, valor): self.volume_atual = valor def printTV(self): print("O modelo da televisão é", self.modelo) print("A cor da televisão é", self.cor) print("O fabricante da televisão é", self.fabricante) print("A televisão é de", self.tamanho, "polegadas") print("A televisão esta", self.estado_tv) if (self.estado_tv == "Ligada"): print("No canal", self.canal_atual, "com o volume no", self.volume_atual)
usuarios = {} usuarios_media = {} menor_media = 0 nome_menor_media = '' maior_media = 0 nome_maior_media = '' while (len(usuarios)) != 4: nome = input('Digite seu nome: ') foto1 = int(input('Digite a quantidade de curtdas da primeira foto: ')) foto2 = int(input('Digite a quantidade de curtdas da segunda foto: ')) foto3 = int(input('Digite a quantidade de curtdas da terceira foto: ')) media = (foto1 + foto2 + foto3) / 3 usuarios[nome] = (foto1, foto2, foto3) usuarios_media[nome] = media if menor_media == 0: nome_menor_media = nome menor_media = media if media < menor_media: nome_menor_media = nome menor_media = media if media > maior_media: nome_maior_media = nome maior_media = media for nome in usuarios_media: print(nome, ':', usuarios_media[nome]) print(nome_maior_media, 'teve o maior número de curtidas') print(nome_menor_media,'teve o menor número de curtidas')
import sys class ExtendedList(list): @property def reversed(self): return list(reversed(self)) @property def first(self): return self[0] @first.setter def first(self, value): self[0] = value @property def last(self): return self[len(self) - 1] @last.setter def last(self, value): self[len(self) - 1] = value @property def size(self): return len(self) @size.setter def size(self, value): if value > len(self): for i in range(0, value - len(self), 1): self.append(None) elif value < len(self): for i in range(0, len(self) - value, 1): self.pop() F = first R = reversed L = last S = size exec(sys.stdin.read())
#Latihan #Akses List list_a = [10, 20, 30, 40, 50] print(list_a) print(list_a[2]) print(list_a[1:4]) print(list_a[-1]) #Ubah Element List list_a[3] = 45 print(list_a[3]) list_a[3:4] = 48, 55 print(list_a[3:5]) #Tambah ELement List list_b = list_a[0:2] print(list_b) list_b.append(25) print(list_b) list_b.extend([35, 45, 55]) print(list_b) list_c = list_a + list_b print(list_c)
message = "Hello Python world!" print(message) message = "Hello Python Crash Course world" print(message) # print('I told my friend, "Python is my favorite language"') print("The language 'Python' is named after Monty Python, not the snake") print("One of Pyhon's strength is its diverse and supportive comunity") # name = "ada lovelace" print(name.title()) # name = "Ada Lovelace" print(name.upper()) print(name.lower()) # first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name print(full_name) print("Hello, " + full_name.title() + "!") # print("Python") print("\tPython") # print("Languages:\n\tPython\n\tC\n\tJavaScript") # favorit_language = 'python ' favorit_language favorit_language.rstrip() favorit_language # favorit_language = ' python ' favorit_language.rstrip() favorit_language.lstrip() favorit_language.strip() # 2 + 3 3 - 2 2 * 3 3 / 2 3 ** 2 3 ** 3 10 ** 6 2 + 3 * 4 (2 + 3) * 4 # 0.1 + 0.1 0.2 + 0.2 2 * 0.1 2 * 0.2 0.2 + 0.1 3 * 0.1 # age = 23 message = "Happy " + str(age) + "rd Birthday" print(message) # # Say hello to everyone print("Hello Python people!") # import this
"""This module provides functionality for using the DataFrame widget like for example custom styling""" from typing import Dict import pandas as pd from bokeh.models.widgets.tables import NumberFormatter INT_DTYPE = "int64" INT_FORMAT = "0,0" INT_ALIGN = "right" FLOAT_DTYPE = "float64" FLOAT_FORMAT = "0,0.00" FLOAT_ALIGN = "right" def get_default_formatters( data: pd.DataFrame, int_format: str = INT_FORMAT, int_align: str = INT_ALIGN, float_format: str = FLOAT_FORMAT, float_align: str = FLOAT_ALIGN, ) -> Dict: """A dictionary of columns and formats for the the `DataFrame` Panel widget. #### Example Use Case ```python formatters = get_default_formatters(data) dataframe_widget = pn.widgets.DataFrame(data, formatters=formatters)) ``` ### Notes - if the index is 1-dimensional and the name is None we rename to 'index' in order to be able to format the index. - For the complete formattings specification see [numbrojs](http://numbrojs.com/format.html) Args: data (pd.DataFrame): A DataFrame of data int_format (str, optional): The int format string. Defaults to INT_FORMAT. int_align (str, optional): [description]. Defaults to INT_ALIGN. float_format (str, optional): [description]. Defaults to FLOAT_FORMAT. float_align (str, optional): [description]. Defaults to FLOAT_ALIGN. Returns: Dict[str,str] -- A dictionary of default formats for the columns """ formatters = {} for column in data.columns: if data[column].dtype == INT_DTYPE: formatters[column] = NumberFormatter(format=int_format, text_align=int_align,) elif data[column].dtype == FLOAT_DTYPE: formatters[column] = NumberFormatter(format=float_format, text_align=float_align,) # Hack: Without a proper name we cannot format the index if len(data.index.names) == 1 and not data.index.name: data.index.name = "index" for (index, name,) in enumerate(data.index.names): if name: dtype = data.index.get_level_values(index).dtype if dtype == INT_DTYPE: formatters[name] = NumberFormatter(format=int_format, text_align=int_align,) elif dtype == FLOAT_DTYPE: formatters[name] = NumberFormatter(format=float_format, text_align=float_align,) return formatters
class SLLNode: def __init__(self,data): self.data = data self.next = None def __repr__(self): return "SLLNode object: data={}".format(self.data) def get_data(self): """"Return the self.data attribue""" return self.data def set_data(self,new_data): """"Replace the existing value of the self.data attribute with the new_data parameter""" self.data = new_data def get_next(self): """"Return the self.next attribute""" return self.next def set_next(self, new_next): """"Replace the existing value of the self.data attribute with the new_next parameter""" self.next = new_next class SLL: def __init__(self): self.head = None def __repr__(self): return "SSL object: head={}".format(self.head) def is_empty(self): """"Returns True if Linked List is empty. Otherwise returns, False.""" return self.head == None #self.head == None def add_front(self,new_data): """Add a node whose data is a new_data argument to the front of the linked list""" temp = SLLNode(new_data) temp.set_next(self.head) self.head = temp def size(self): """Traverses the Linked List and returns an integer value representhing the number of nodes in the Linked List""" size = 0 if self.head == None: return 0 current = self.head while current is not None: #while there are more still nodes left to count size = size + 1 current = current.get_next() return size def search(self,data): """Traverses the linked list and returns true if the data searched is present in one of the nodes. Otherwise, returns false. The time complexity is O(n). """ if self.head == None: return "Linked List is empty. No nodes to search." current = self.head while current is not None: if current.get_data() == data: return True else: current = current.get_next() return False def remove(self,data): """Removes the first occurence of the node that contains the self.data variable. Returns nothing. The time complexity is O(n) """ if self.head == None: return "Linked list is empty. No nodes to remove." current = self.head previous = None found = False while not found: if current.get_data() == data: found = True else: if current.get_next() == None: return "A node with that data value is not present." else: previous = current current = current.get_next() if previous is None: self.head = current.get_next() else: previous.set_next(current.get_next())
# -*- coding: utf-8 -*- """ Created on Sun Feb 7 15:08:35 2021 @author: kalya """ user1 = input("Player 1,Enter your choice rock/paper/scissor: ") user2 = input("Player2,Enter your choice rock/paper/scissor:") def rock_paper_scissor(player_1, player_2): a_list = ["rock","paper","scissor"] while player_1 not in a_list or player_2 not in a_list : print("Invalid input!") player_1 = input("player1, Enter rock/paper/scissor:") player_2 = input("player2, Enter rock/paper/scissor:") while player_1 == player_2 : print("Nobody wins:") player_1 = input("player1, Enter rock/paper/scissor:") player_2 = input("player2, Enter rock/paper/scissor:") if player_1 == "rock" and player_2 == "scissor": print("Player_1 wins! Do you want play again?") if player_1 == "rock" and player_2 == "paper": print("player_2 wins!") if player_1 == "scissor" and player_2 == "paper" : print("player1 wins!") rock_paper_scissor(user1, user2)
import string def test(): """Here code reads,breaks the file(whitespace) and convertingwords to lowercase""" fin = open("file.txt","r") pun_char = string.punctuation for i in fin: i = i.strip().replace(" ","\n") for char in pun_char: i = i.replace(char,"") i = i.lower() print(i) test()
class Test: """this class shows time""" time=Test() time.hour=9 time.minute=35 time.second=25 def print_time(t): print('the time is:','%.2d:%.2d:%.2d'%(t.hour,t.minute,t.second)) print_time(time)
# 使用字典 ab = {'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]' , 'Spammer' : '[email protected]'} print("Larry's address is %s" % ab['Larry']) # 使用索引操作符可以增加一个新的键值对 ab['Gundo'] = '[email protected]' print('now the new dictionary is :', ab) del ab['Spammer'] for name,address in ab.items(): print('Contact %s at %s' % (name,address)) if 'Swaroop' in ab: # 注意这个if语句块和上面for...in语句块没关系,即这个没包含在上面的缩进语句里: print("\nSwaroop's address is %s" % ab['Swaroop'])
def double(x): return 2 * x x = double(2) for x in range(10): for y in range(10): print(x, y)
import datetime import operator import os EMPTY_LIST_MESSAGE = "\nNothing to do yet, add some items to the list.\n" ITEM = "item" DEPT = "department" grocery_list = [] run_date = datetime.datetime.today() class GroceryItem: def __init__(self, item, department): self.item = item self.department = department def __eq__(self, other): return self.item == other.item and self.department == other.department def __ne__(self, other): return self.item != other.item or self.department != other.department def __gt__(self, other): return (self.department, self.item) > (other.department, other.item) def __lt__(self, other): return (self.department, self.item) < (other.department, other.item) def __ge__(self, other): return (self.department, self.item) > (other.department, other.item) or ( self.item == other.item and self.department == other.department) def __le__(self, other): return (self.department, self.item) < (other.department, other.item) or ( self.item == other.item and self.department == other.department) def get_item(self): return self.item def get_department(self): return self.department def clear_screen(): os.system("cls" if os.name == "nt" else "clear") def print_menu(): clear_screen() print("-" * 80) print("Let's make a Grocery List! :)\n" "Keep entering new items to pick up at the store or:\n" "\tS Show the grocery list by department\n" "\tA to Show the grocery list alphabetically by item names\n" "\tW to Write the list to a file, (always by department)\n" "\tH or Help will show this menu again\n" "\tQ or Quit will end the program") print("-" * 80) def print_list(first_key, second_key=None): clear_screen() if len(grocery_list) > 0: if second_key: grocery_list.sort(key=operator.attrgetter(first_key, second_key)) else: grocery_list.sort(key=operator.attrgetter(first_key)) print("-" * 80) print( f"Grocery List for {run_date:%B %d, %Y}:" ) print("-" * 80) for index, grocery_item in enumerate(grocery_list, start=1): print(f"\n{index}) {grocery_item.item} in {grocery_item.department}") print("-" * 80) print("\n") else: print(EMPTY_LIST_MESSAGE) def write_to_file(): if len(grocery_list) > 0: grocery_list.sort(key=operator.attrgetter(DEPT, ITEM)) file_name = f"grocery_list_{run_date:%Y-%m-%d}.txt" with open(file_name, "w+") as grocery_file: grocery_file.write("-" * 80 + "\n") grocery_file.write(f"Grocery List for {run_date:%B %d, %Y}:\n") grocery_file.write("-" * 80 + "\n") current_dept = None for grocery_item in grocery_list: if grocery_item.department != current_dept: current_dept = grocery_item.department if not current_dept: current_dept = "No Department Specified" grocery_file.write(f"\n{current_dept.title()}\n") grocery_file.write("-" * 40 + "\n") grocery_file.write(f"{grocery_item.item} [ ]\n") else: print(EMPTY_LIST_MESSAGE) def add_to_list(new_item): if len(new_item) > 0: new_depart = input("What department is that in?: ") new_depart = new_depart.lower() grocery_list.append( GroceryItem(item=new_item, department=new_depart) ) else: print("You forgot to enter a new item for the list, try again.") if __name__ == "__main__": print_menu() keep_running = True while keep_running: next_item = input("Enter an item for the list (or s|a|w|h|q): ") next_item = next_item.lower() if next_item in ["q", "quit"]: keep_running = False elif next_item in ["h", "help"]: print_menu() elif next_item == "a": print_list(first_key=ITEM) elif next_item == "s": print_list(first_key=DEPT, second_key=ITEM) elif next_item == "w": write_to_file() else: add_to_list(new_item=next_item)
import sys # part one: create the length-to-words dictionary contents = open("sonnets.txt").read() words = contents.split() by_length = {} for item in words: if len(item) not in by_length: by_length[len(item)] = [] by_length[len(item)].append(item) #part two: read in standard input and perform the replacements for line in sys.stdin: line = line.strip() words = line.split() print ' '.join([random.choice(by_length[len(w)]) for w in words]) print by_length
# # Worksheet #4 # # This worksheet is also a Python program. Your task is to read the # task descriptions below and then write one or more Python statements to # carry out the tasks. There's a Python "print" statement before each # task that will display the expected output for that task; you can use # this to ensure that your statements are correct. # # In this worksheet, some of the tasks will throw an error that causes # the program to stop running, and skip the remaining tasks. Because of # this, you'll have to complete the tasks in the given order! print "\n------" print "Task 1: Making a web request" print 'DONE Expected output: {"ping": "ok"}' # Task 1: There is a web API (which I made specifically for this worksheet!) # available at the following URL: # http://blooming-shelf-7827.herokuapp.com # Modify the value of the variable "url" below so that it makes a request to # the "/ping" path of this web API. import urllib url = "http://blooming-shelf-7827.herokuapp.com/ping" # <-- modify this response = urllib.urlopen(url).read() print response #------------------------------------------------------------------------ print "\n------" print "Task 2: Parsing JSON" print "DONE Expected output: <type 'dict'>" # Task 2: The web API also supports a path called "/kittens", which returns # a list of kittens in JSON format. Add a function call to the line below # so that the variable "data" is a Python dictionary containing the data from # the response. (I've taken the liberty of importing the Python library that # contains the function you'll want to use.) import json url = "http://blooming-shelf-7827.herokuapp.com/kittens" response = urllib.urlopen(url).read() data = json.loads(response) # <-- add a function call here! print type(data) #------------------------------------------------------------------------ print "\n------" print "Task 3: Manipulating URLs, part one" print 'DONE Expected output: ["results"]' # Task 3: You may have noticed that the previous response actually returned # an error! That's because this particular API requires that you supply an # API key. The API key must be supplied as a parameter on the query string. # Modify the variable "url" below so that it has a query string with one # parameter, "api_key", whose value is "abc123". url = "http://blooming-shelf-7827.herokuapp.com/kittens?api_key=abc123" # <-- modify this response = urllib.urlopen(url).read() # uncomment the following line if you want to see what the response looks like #print response data = json.loads(response) print data.keys() #------------------------------------------------------------------------ print "\n------" print "Task 4: Working with web API data" print "DONE Expected output: 3" # Task 4: A request to "/kittens" (with the appropriate API key) returns a # list of kittens. Modify the expression following "print" below so that the # number of kittens in the response is displayed. (Use the value of "url" # from the previous task.) response = urllib.urlopen(url).read() # uncomment the following line if you want to see what the response looks like print response data = json.loads(response) print len (data['results']) # <-- modify this! #------------------------------------------------------------------------ print "\n------" print "Task 5: Working with embedded data structures" print "DONE IN OH Expected output:" #print " McFluff the Crime Kitten" #print " Scratch" #print " Her Majesty Queen Esmerelda Poopbutt" # Task 5: Use the variable "data" from the previous task. Modify the two # expressions indicated below so that the names of each of the kittens are # displayed. (Take a good look at the data structure returned from the # response. What kind of data structure is it? What other kinds of data # structures does it contain?) kitten_list = data['results'] # <-- modify this! Hint: the value for a key in "data" #print kitten_list for kitten in kitten_list: print kitten['name'] # <-- when printing we have to remind it to look into the temporary variable kitten #------------------------------------------------------------------------ print "\n------" print "Task 6: Manipulating URLs, part two" print "DONE Expected output:" #print " McFluff the Crime Kitten" #print " Her Majesty Queen Esmerelda Poopbutt" #print " Scratch" # Task 6: This API also allows you to specify a sort order for the kittens # returned in the data. To take advantage of this functionality, include a key # in the query string, "sort", whose value is the data field that you want to # sort by (e.g., "name", "weeks_old", "weight_kg", etc.). Modify the dictionary # inside the call to urllib.urlencode below so that the for loop prints the # names of the kittens in (ascending) order by weight. (Hint: don't forget # to include your API key!) base_url = "http://blooming-shelf-7827.herokuapp.com/kittens?" params = urllib.urlencode({'api_key':'abc123','sort':'weight_kg'}) # <-- modify this dictionary url = base_url + params #print url response = urllib.urlopen(url).read() data = json.loads(response) ordered_kittens = data['results'] for kitten in ordered_kittens: print kitten['name'] #It keps on giving me the kittens in the order they are in results. I am not #using params because if I do it, it only prints the last parameter in the new #dictonary (weight_kg:2.0 in this case) #How am I writing params wrong? #Should I be retriving the kittens from response? or should I tell params to get #the parameters from 'results' How? #*I'm using the same key three times, that is why it gives me the last one, How #to let it know it has to differenciate them? #------------------------------------------------------------------------ print "\n------" print "Task 7: Working with embedded data structures, part two" print "DONE Expected output:" #print " salmon" #print " duck" #print " chicken" # Task 7: Use the variable "url" from the previous task. The value for each # kitten's "favorite_foods" key is a list of strings. Change the indicated # expression below so that the code prints out the first favorite food for # each kitten. response = urllib.urlopen(url).read() data = json.loads(response) for kitten in ordered_kittens: print kitten['favorite_foods'][0] # -- modify this expression! #I've tried kitten['favorite_foods'[0]] # kitten['favorite_foods':[0]] # kitten['favorite_foods':0] # kitten['favorite_foods:0'] # kitten['favorite_foods:0'] # kitten"'favorite_foods':[0]" # kitten('favorite_foods':[0]) # ('favorite_foods':[0]) # I need to access the kitten list and in it get favorite foods and in it get #the first item HOW TO WRITE IT?! # kitten, 'favorite_foods'[0] # step 1: get the first item...[0] #step 2: ...from the value associated with the key 'favorite_foods'... # ['favorite_foods'][0] #step 3: ...in the dictionary kitten. # kitten['favorite_foods'][0] #------------------------------------------------------------------------ print "\n------" print "Task 8: Working with embedded data structures, part three (advanced!)" print "Expected output: 7.3" # Task 8: Write a list comprehension in the indicated space that returns a # list of the values for the "weight_kg" field in each kitten record. # The resulting expression will bring out the sum of their weights. (Use the # value of "url" from the previous task.) response = urllib.urlopen(url).read() data = json.loads(response) product = [kitten for weight_kg in ordered_kittens] # <-- change [] to a list comprehension print sum(product)
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ This file defines the most important class DimQuant, which is a child of BaseDimQuant. The difference with respect to BaseDimQuant is the ability to initialize a DimQuant instance using a string representation of a dimensional quantity. In BaseDimQuant the user has to provide two arguments: a numerical value, and a Dimensional instance. In DimQuant the instanciation is simplified. """ from . import Dimensional as D from . import BaseDimQuant from . import Translator class DimQuant(BaseDimQuant): """Class for working with dimensional quantities. Args: args (string): the usual way to instanciate an object of this class is by means of a string such as '1 kg/m2', or '2 m.s'. *args (optional): alternatively to the string representation of the quantity this class accepts the same arguments as BaseDimQuant. .. seealso:: The legal dimensional identifiers for the string representation can be found in :py:meth: `dimensionalquantity.Translator`""" _T = Translator() def __init__(self, *args, **kwargs): if len(args)==1 and isinstance(args[0], str): dq_string = args[0] _q, _d = dq_string.split(' ') _DQ = self._T.translate(_d) self.numeric = _DQ.numeric * float(_q) self.dimensions = _DQ.dimensions else: super(DimQuant, self).__init__(*args, **kwargs) def __repr__(self): """Example: >>> q = DimQuant('1 m/s') >>> print(q) DimQuant(1, Dimensional({'L':1, 't':-1})""" return 'DimQuant({}, {})'.format(self.numeric,self.dimensions) def __str__(self): """Example: >>> q = DimQuant('1 m/s') >>> str(q) '1 m.s-1' Though, the exact result depends on the registered translator. .. seealso:: :py:meth: `dimensionalquantity.BasicTranslator` :py:meth: `dimensionalquantity.Translator` """ unit_string = self._T.reverse_unit_lookup(self.dimensions) return ' '.join([str(self.numeric), unit_string]) @classmethod def register_translator(cls, translator): """Thanks to the registered translator we can convert a string representation (like '1 m/s') into a `DimQuant`, and also a `DimQuant` into a string; which is more human readable. This is a classmethod, which means all DimQuant instances share the same translator. Typically, this method is called at the beginning of a script; right after registering the corresponding look-up-tables (LUTs) needed for the translator. Without explicitly registering a translator, a default instance of `Translator` is used. Args: translator (Translator): an instance capable to interpret the string representations used in a particular script. .. seealso:: :py:meth: `dimensionalquantity.BasicTranslator` :py:meth: `dimensionalquantity.Translator` """ cls._T = translator
# happy2.py # Happy Birthday using value returning functions def happy(): return "Happy birthday to you!\n" def verseFor(person): lyrics = happy()*2 + "Happy birthday, dear " + person + ".\n" + happy() return lyrics def main(): for person in ["Fred", "Lucy", "Elmer"]: print(verseFor(person)) main()
## program to extract Strings between HTML import re test_str = '<b>Reddy Prasad</b> is <b>Best</b>. I love <b>Technology Enabler Machine Learning Algorithm</b> <b>Reading CS</b> from it.<b>Machine Learing Researcher</b>' print("The original string is : " + str(test_str)) tag = "b" # brack tag in html # regex to extract required strings reg_str = "<" + tag + ">(.*?)</" + tag + ">" res = re.findall(reg_str, test_str) # printing result print("The Strings extracted : " + str(res))
""" Python does not have the private keyword, unlike some other object oriented languages, but encapsulation can be done. Instead, it relies on the convention: a class variable that should not directly be accessed should be prefixed with an underscore. """ class Robot(object): def __init__(self): self.a = 123 self._b = 123 self.__c = 123 obj = Robot() print(obj.a) print(obj._b) print(obj.__c) """ **A single underscore:** Private variable, it should not be accessed directly. But nothing stops you from doing that (except convention). **A double underscore:** Private variable, harder to access but still possible. **Both are still accessible:** Python has private variables by convention. """ class Robot(object): def __init__(self): self.__version = 22 def getVersion(self): print(self.__version) def setVersion(self, version): self.__version = version obj = Robot() obj.getVersion() obj.setVersion(23) obj.getVersion() print(obj.__version)
for row in range(6): for col in range(4): if col==1 and row>0 or row==3 and col<3 or col==2 and row==0 or col==3 and row==1: print('*', end = ' ') else: print(' ', end = ' ') print()
for row in range(4): for col in range(4): if col%3==0 and row<3 or row==3 and col>0: print('*', end = ' ') else: print(' ', end = ' ') print()
i=1 j=3 for row in range(5): for col in range(5): if(row==0)or(row==4): print('*',end='') elif (row==i and col==j): print('*', end='') i+=1 j-=1 else: print(end=' ') print()
for row in range(8): for col in range(5): if ((col==0 or col==4) and (row>0 and row<6)) or ((row==0 or row==6)and (col>0 and col<4))or (row==5 and col==1)or (row==7 and col==3): print("*",end="") else: print(end=" ") print()
for row in range(7): for col in range(5): if col==0 or (col==4 and (row==1 or row==2)) or ((row==0 or row==3) and (col>0 and col<4)): print("*",end="") else: print(end=" ") print()
# printfile.py # Prints a file to the screen. def main(): fname = input("Enter filename: ") infile = open(fname,"r") data = infile.read() print(data) main()
# Shape of reverse left angle triangle using fucntions def for_reverse_left_angle_triangle(): """ *'s printed in the shape of Reverse Left Angle Triangle """ for row in range(9): for col in range(9): if col >= row: print('*',end=' ') else: print(' ',end=' ') print() def while_reverse_left_angle_triangle(): """ *'s printed in the shape of Reverse Left Angle Triangle """ row =0 while row<9: col =0 while col <9: if col >= row: print('*',end=' ') else: print(' ',end=' ') col+=1 print() row += 1
for row in range(6): for col in range(4): if col==2 and row!=1 and row!=5 or row==5 and col==1 or col==0 and row==4 or col==1 and row==2: print('*', end = ' ') else: print(' ', end = ' ') print()
for row in range(7): for col in range(5): if row%3==0 and col>0 and col<4 or col==0 and row in (1,4,5) or col==4 and row>0 : print('*', end = ' ') else: print(' ', end = ' ') print()
# text2numbers.py # A program to convert a textual message into a sequence of # numbers, utilizing the underlying Unicode encoding. def main(): print("This program converts a textual message into a sequence") print("of numbers representing the Unicode encoding of the message.\n") # Get the message to encode message = input("Please enter the message to encode: ") print("\nHere are the Unicode codes:") # Loop through the message and print out the Unicode values for ch in message: print(ord(ch), end=" ") print() # End line of output main()
a = raw_input("Enter a word No spaces please:") if a[::-1] == a and len(a)>0: print "yes" else: print "no"
n = int(raw_input("enter:")) z =[] Mlist =[] for x in range(0,n): a = raw_input("enter a:").split(" ") for y in a: z.append(y) a = raw_input("enter a:").split(" ") for y in a: z.append(y) a = raw_input("enter a:").split(" ") for y in a: z.append(y) Mlist = sorted(z) print Mlist
"""Base classes and helper functions for data handling (dataset, dataloader).""" import abc from typing import Iterator from typing import List from typing import Optional from typing import Union import numpy as np class Dataset(abc.ABC): """ An abstract class representing an `iterable dataset <https://pytorch.org/docs/stable/data.html#iterable-style-datasets>`_. Your iterable datasets should be inherited from this class. """ @abc.abstractmethod def __iter__(self): raise NotImplementedError class IndexedDataset(Dataset): """ A class representing a `map-style dataset <https://pytorch.org/docs/stable/data.html#map-style-datasets>`_. Your map-style datasets should be inherited from this class. """ @abc.abstractmethod def __getitem__(self, item): raise NotImplementedError @abc.abstractmethod def __len__(self): raise NotImplementedError def __iter__(self): self.current_index = -1 return self def __next__(self): self.current_index += 1 if self.current_index >= len(self): raise StopIteration return self[self.current_index] class DataLoader: """ Interface b/w model and task, implements restrictions (e.g. max batch size) for models. Args: dataset: Dataset from which to load the data. max_batch_size: How many samples allowed per batch to load. """ def __init__(self, dataset: Dataset, max_batch_size: Optional[int]): self._dataset = dataset self.__max_batch_size = max_batch_size @property def max_batch_size(self): """Maximum allowed batch size that the dataloader will satisfy for request through the :py:func:`iterate` function.""" return self.__max_batch_size def iterate(self, batch_size) -> Iterator[List[np.ndarray]]: """Iterate through the dataloader and return batches of data. Args: batch_size: Maximum batch size the function that requests the data can handle. Yields: The dataset split up in batches. """ if self.max_batch_size is not None: batch_size = min(batch_size, self.max_batch_size) batch = [] ds_iter = iter(self._dataset) while (item := next(ds_iter, None)) is not None: batch.append(item) if len(batch) == batch_size: yield batch batch = [] if len(batch) != 0: yield batch def shuffle_data( *, data: Union[List[np.ndarray], np.ndarray], seed: int ) -> Union[List[np.ndarray], np.ndarray]: """Randomly shuffles without replacement an :py:class:`numpy.ndarray`/list of :py:class:`numpy.ndarray` objects with a fixed random seed. Args: data: Data to shuffle. seed: Random seed. """ undo_list = False if not isinstance(data, List): undo_list = True data = [ data, ] assert np.all( [len(data[0]) == len(it) for it in data] ), "All data arrays must have the same length" rng = np.random.default_rng(seed=seed) rnd_indxs = rng.choice(len(data[0]), size=len(data[0]), replace=False) data = [it[rnd_indxs] for it in data] if undo_list: data = data[0] return data
def reverter(entrada): return print(entrada[::-1]) ent = str(input('Digite um numero ou texto: ')) reverter(ent)
lista = [] def numero(): for i in range(5): numeros = int(input('Digite o %d° número: ' % (i + 1))) lista.append(numeros) maior = max(lista) return print(f'O maior número é: {maior}') numero()
def salrio(hora, hMes): salario = hora * hMes ir = salario * 0.11 inss = salario * 0.08 sind = salario * 0.05 sLiquido = salario - ir - inss- sind return salario, ir, inss, sind, sLiquido h = float(input('Qual o seu salário hora: ')) m = float(input('Quantas horas trabalhou neste mês: ')) print('Sua folha de pagamento é: {}'.format(salrio(h, m)))
class No: """ Estruturação da arvore, para cada nó dou um dado, e tendo um filho esquerdo um filho direito e um pai """ def __init__(self, dado): self.dado = dado self.filhoesq = None self.filhodir = None self.pai = None def getDado(self): return self.dado def setDado(self, novo): self.dado = novo def getFilhoesq(self): return self.filhoesq def setFilhoesq(self, filho): self.filhoesq = filho def getFilhodir(self): return self.filhodir def setFilhodir(self, filho): self.filhodir = filho def getPai(self): return self.pai def setPai(self, pai): self.pai = pai def __str__(self): return str("No:" + str(self.getDado())) class Arvore(No): def __init__(self): self.raiz = None def getRaiz(self): return self.raiz def setRaiz(self, nova): self.raiz = nova def buscar(self, x, d): if x is None or x.getDado() is d: return x if d < x.getDado(): return self.buscar(x.getFilhoesq(), d) else: return self.buscar(x.getFilhodir(), d) def minimo(self, x): while x.getFilhoesq() is not None: x = x.getFilhoesq() return x def maximo(self, x): while x.getFilhodir() is not None: x = x.getFilhodir return x def sucessor(self, x): if x.getFilhodir() is not None: return self.minimo(x.getFilhodir()) y = x.getPai() while y is not None and x is y.getFilhodir(): x = y y = y.getPai() return y def predecessor(self, x): if x.getFilhoesq() is not None: return self.maximo(x.getFilhoesq()) y = x.getPai() while y is not None and x is y.getFilhoesq(): x = y y = y.getPai() return y def inserir(self, z): y = None x = self.getRaiz() while x is not None: y = x if z.getDado() < x.getDado(): x = x.getFilhoesq() else: x = x.getFilhodir() z.setPai(y) if y is None: self.setRaiz(z) else: if z.getDado() < y.getDado(): y.setFilhoesq(z) else: y.setFilhodir(z) def remover(self, x): if x.getFilhoesq() is None or x.Filhodir() is None: y = x else: y = self.sucessor(x) if y.getFilhoesq() is not None: z = y.getFilhoesq() else: z = y.getFilhodir() if z is not None: z.setPai(y.getPai()) if y.getPai() is None: self.setRaiz(z) else: if y is y.getPai().getFilhoesq(): y.getPai().setFilhoesq(z) else: y.getPai().setFilhodir(z) if y is not x: x.setDado(y.getDado)
import datetime #classes-------------------------------- class Employee: def __init__(self,name,age,salary,employment_year, **kwargs): self.name = name.capitalize() self.age = age self.salary = int(salary) self.employment_year = int(employment_year) for key, value in kwargs.items(): setattr(self, key, value) def get_working_years(self): return int(datetime.datetime.today().year) - self.employment_year def __str__(self): return "name: {}, age: {}, salary: {}, working years: {}".format(self.name, self.age, self.salary, self.get_working_years()) #---------------------------- class Manager (Employee): def __init__(self, name,age,salary,employment_year, bonus_percentage, **kwargs): super().__init__(name, age,salary, employment_year, **kwargs) self.bonus_percentage = float(bonus_percentage) def get_bonus(self): return self.bonus_percentage * self.salary def __str__(self): return super().__str__() + ", bonus: {}".format(self.get_bonus()) #MAIN - - - - - - - - - - - - - - - - - - - def print_list(list): for item in list: print(item) print("") employees = [] managers = [] print("Welcome to HR Pro 2019") while True: print("""Choose an action to do: 1. show employees 2. show managers 3. add an employee 4. add a manager 5. exit""") choice = int(input("What would you like to do? ")) if choice == 1: print("Employees: ") print_list(employees) elif choice == 2: print("Managers: ") print_list(managers) elif choice == 3: employee_name = input("Enter name: ") employee_age = input("Enter age: ") employee_salary = input("Enter salary: ") employee_date = input("Enter employment date: ") employees.append(Employee(employee_name, employee_age, employee_salary, employee_date)) print("Employee added succesfully\n") elif choice == 4: employee_name = input("Enter name: ") employee_age = input("Enter age: ") employee_salary = input("Enter salary: ") employee_date = input("Enter employment date: ") manager_bonus = input("Enter manager bonus percentage: ") managers.append(Manager(employee_name, employee_age, employee_salary, employee_date, manager_bonus)) print("Manager added succesfully\n") elif choice == 5: break else: print("Error invalid choice")
from collections import namedtuple # added in Python 2.6 # immutable Person = namedtuple('Person',['person_id','name','gender']) if __name__ == '__main__': person_n1 = Person(100,'Guido','M') print(person_n1) # nice __repr__ method print(person_n1.name) # access by name person_id,name,gender = person_n1 #unpack print(person_id,name,gender)
#the format of each algorithm will be a list of integers def swap(a, i, j): tmp = a[i] a[i] = a[j] a[j] = tmp #end swap def bubble(arg): end = len(arg) - 1 while end > 0: high = arg[0] highpos = 0 for i in range(end): if high < arg[i]: high = arg[i] highpos = i swap(arg, end, highpos) end -= 1 return arg #end bubble def merge(L, R): s = [] a, b = 0, 0 while a < len(L) and b < len(R): if L[a] < R[b]: s.append(L[a]) a += 1 else: s.append(R[b]) b += 1 for i in range(a, len(L)): s.append(L[i]) for i in range(b, len(R)): s.append(R[i]) return s #end merge def merge_recurse(arg): #print(arg) halfs = [] halfs.append(arg[:len(arg)//2]) halfs.append(arg[len(arg)//2:]) #print(halfs) for i in range(len(halfs)): if len(halfs[i]) > 1: halfs[i] = merge_recurse(halfs[i]) srtd = merge(halfs[0], halfs[1]) #print(srtd) arg.clear() arg.extend(srtd) return arg #end merge_recurse def merge_iter(arg): cnt = len(arg) #print(arg) current_size = 1 while current_size < cnt - 1: left = 0 while left < cnt - 1: mid = left + current_size - 1 a = (2 * current_size) + left - 1 b = cnt - 1 right = (a, b)[a > b] #wtf is this syntax, its one unreadable line that replaces an if else l = [] r = [] #print(left, mid, right, current_size) for i in range(left, mid + 1): if i < cnt: l.append(arg[i]) for i in range(mid + 1, right + 1): r.append(arg[i]) m = merge(l, r) for i in range(len(m)): arg[left + i] = m[i] left = left + (current_size * 2) current_size = current_size * 2 #print(arg) return arg #end merge_iter #for some reason, this is much slower than the recursive method def quick_iter(arg): chunks = [arg.copy()] is_sorted = False while not is_sorted: #for repeat in range(3): is_sorted = True for c in range(len(chunks)): if len(chunks[c]) > 1: is_sorted = False chunk = chunks[c] smol = [] bigg = [] pivot = chunk[0] for i in range(1, len(chunk)): if chunk[i] < pivot: smol.append(chunk[i]) else: bigg.append(chunk[i]) pre = chunks[:c] post = chunks[c+1:] current = [] if len(smol) > 0: current.append(smol) current.append([pivot]) if len(bigg) > 0: current.append(bigg) chunks = pre + current + post #print(chunks) #break arg.clear() for i in range(len(chunks)): arg.append(chunks[i][0]) return arg #end quick_iter def quick_recurse(arg): pivot = arg[0] less = [] more = [] for i in range(1, len(arg)): if arg[i] < pivot: less.append(arg[i]) else: more.append(arg[i]) if len(less) > 1: less = quick_recurse(less) if len(more) > 1: more = quick_recurse(more) less.append(pivot) arg.clear() arg.extend(less + more) return arg #end quick_recurse def selection(arg): cnt = len(arg) start = 0 while start < cnt: low = arg[start] lowpos = start for i in range(start, cnt): if arg[i] < low: lowpos = i low = arg[lowpos] swap(arg, start, lowpos) start += 1 print(arg) return arg #end selection def insertion(arg): cnt = len(arg) for i in range(1, cnt): #print(arg, cnt, i) if arg[i] <= arg[i-1]: popped = arg.pop(i) for j in range(i-1, -1, -1): #print(arg, popped, arg[j]) if popped > arg[j]: arg.insert(j+1, popped) break if j == 0: arg.insert(j, popped) return arg #end insertion def shell(arg): cnt = len(arg) sec = cnt // 2 while sec >= 1: #print("sec: ", sec) pos = 0 while pos < cnt: for i in range(pos,pos+sec): if i+sec < cnt: #print(arg[i], arg[i+sec]) if arg[i] > arg[i+sec]: swap(arg, i, i+sec) else: break pos += sec sec -= 1 #sec //= 2 #insertion(arg) #end shell def gravity(arg): cnt = len(arg) beads = [] for i in range(cnt): for j in range(arg[i]): if len(beads) > j: beads[j] += 1 else: beads.append(1) #print (beads) fallen = [] empty = False while not empty: current = 0 empty = True for i in range(len(beads)): if beads[i] > 0: empty = False beads[i] -= 1 current += 1 else: break if current > 0: fallen.append(current) arg.clear() arg.extend(list(reversed(fallen))) return arg #end gravity
from collections import Counter my_list = [1, 1, 1, 1, 2, 2, 2, 4, 4, 6, 6, 8] print(Counter(my_list)) print(Counter('Python')) # Counter the number of words in this sentence! my_str = "How many times does each word show up in this sentence with a word" print(Counter(my_str.split())) # Returns most common items (most repeated) - sorter tuples print(Counter(my_str.split()).most_common()) # Returns two most common words print(Counter(my_str.split()).most_common(2))
def add(num1, num2): try: result = num1 + num2 # Specific error except TypeError: print('Type error occurred!') except OSError: print('An OS error occurred!') except: print('Other exception occurred!') else: print('Add went well!') finally: print('I always run!') add('2', 3)
def new_decorator(original_func): def wrap_func(): print('Some extra code, before the original function') original_func() print('Some extra code, after the original function') return wrap_func def fun_needs_decorator(): print('I want to be decorated!') # This is what actually happens behind the sense of decorator decorator_func = new_decorator(fun_needs_decorator) decorator_func() # You do not need what we have done above, you can use decorator to run decorator and it saves you a lot of time! @new_decorator def fun_needs_decorator2(): print('I want to be decorated2!') fun_needs_decorator2()
def add(num1, num2): try: result = num1 + num2 # Generic error except: print('Something went wrong!') else: print('Add went well!') print(result) add(1, 2)
# Given a non-empty array N, of non-negative integers. The degree of this array is defined as # the maximum frequency of any one of it's elements. Your task is to find the smallest possible # length of a (contiguous) subarray of N, that has the same degree as N. For example, in the array # [1 2 2 3 1], integer 2 occurs maximum of twice. Hence the degree is 2. # Input # Test case input contains 2 lines. First line contains an integer T, representing the number of # elements in the array. The second line contains the array N, list of T integers each separated # by space. # Output # Print the length of the smallest contiguous subarray of input array N, that has the same degree as N. # Code evaluation is based on your output, please follow the sample format and do NOT print anything else. # Sample Input # 5 # 1 2 2 3 1 # Sample Output # 2 def size(array): left, right, count = {}, {}, {} for k, v in enumerate(array): if v not in left.keys(): left[v] = k right[v] = k count[v] = count.get(v, 0) + 1 degree = max(count.values()) size = len(array) for i in count: if count[i] == degree: size = right[i] - left[i] + 1 return size def get_array(string): return list(map(lambda x: int(x), string.split('\n')[1].split(' '))) print(size(get_array('5\n1 2 2 3 1')))
age = 24 print("My age is " + str(age) + " years") print("My age is {0} years".format(age)) print( """ January: {2} February: {0} April: {1}""".format(28,30,31) ) print("My age is %d years" % age) #old for i in range(1, 12): print("No. {0:2} squared is {1:4} and cubed is {2:4}".format(i, i ** 2, i ** 3)) for i in range(1, 12): print("No. {0:2} squared is {1:<4} and cubed is {2:<4}".format(i, i ** 2, i ** 3)) # left formatted print("Pi is aproximately {0:12.50}".format(22 / 7))
# ages={} # print(type(ages)) # ages["himanshu"]=45 # ages[71]="tkr" # print(ages) # print(ages.keys()) # print(ages.values()) hg='himanshu' k=[print(i) for i in hg if i not in "aeiou"] print(k)
def firstLast(u): return u[0] == 6 or u[-1] == 6 #function to create a new list in ascending order def ascending(list, new_list): min_n = list[0] while len(list) != 0: min_n = list[0] for i in range(len(list)): if list[i] <= min_n: min_n = list[i] new_list.append(min_n) list.remove(min_n) return new_list #unlucky 13: sum up all numbers in list except for 13 and number preceding 13 def sum13(nums): sum = 0 for i in range(len(nums)): sum += nums[i] for i in range(len(nums)): if nums[i] == 13 and i == len(nums) - 1: sum -= 13 elif nums[i] == 13: sum -= 13 if nums[i+1] != 13: sum -= nums[i+1] return sum def sum13(nums): sum = 0 for i in range(0, nums.count(13)): if nums.count(13): after = nums.index(13) nums.remove(13) if after < len(nums): nums.pop(after) #pop removes and returns last object or (obj) index from the list for i in nums: sum += i return sum #Sum up all the numbers except every 6 to the next 7 def sum67(nums): sum = 0 add = 'yes' for i in range(len(nums)): if add == 'yes': if nums[i] == 6: add = 'no' else: sum += nums[i] else: if nums[i] == 7: add = 'yes' return sum def main(): list = [1,2,3,4,5,6] a = firstLast(list) print (a) new_list = [] list = [9,8,7,6,5,4] b = ascending(list, new_list) print (b) main()
# File: GuessingGame.py # Description: Create a program that will "guess" a number that the user chooses between 1 and 100 (using binary search) # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 4/11/2016 # Date Last Modified: 4/11/2016 def main(): #Initialize the boundaries of the guess lo = 1 hi = 100 #Print the introduction and header print ("Guessing Game") print() print ("Think of a number between 1 and 100 inclusive.\nAnd I will guess what it is in 7 tries or less.") print() #Prompt the user to enter if he/she is ready or not choice = input("Are you ready? (y/n): ") #Keep prompting if user is not entering y or n while choice != 'y' and choice != 'n': choice = input("Are you ready? (y/n): ") if choice == 'n': print ("Bye") return #Initialize the counter variable; this variable will not exceed 6 (for a total of 7 tries) counter = 0 #Initialize the first "guess" by the program; should be middle of lo and hi mid = (lo + hi) // 2 while counter < 7: #Print the guess, ask for user input if right or wrong print ("\nGuess %d: The number you thought was %d" %(counter + 1, mid)) response = input("Enter 1 if my guess was high, -1 if low, and 0 if correct: ") print() #Keep prompting user if he/she is not entering 0, 1, or -1 while response != '0' and response != '1' and response != '-1': print ("\nGuess %d: The number you thought was %d" %(counter + 1, mid)) response = input("Enter 1 if my guess was high, -1 if low, and 0 if correct: ") print() #If 0, break out of the program, else, reset mid accordingly if response == '0': print("\nThank you for playing the Guessing Game.") return elif response == '1': hi = mid mid = (lo + mid) // 2 elif response == '-1': lo = mid mid = (hi + mid + 1) // 2 #Increment counter counter += 1 #If out of loop, that means the user guessed a number out of range or incorrect entry print ("Either you guessed a number out of range or you had an incorrect entry.") main()
# File: PalindromicSum.py # Description: Given a range of numbers, figure out which one has the longest cycle until it becomes a palindromic number # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 2/19/2016 # Date Last Modified: 2/19/2016 #Create the reverse number function def rev_num(n): rev_n = 0 while (n > 0): rev_n = rev_n * 10 + (n % 10) n = n // 10 return rev_n #Create the is_palindromic function def is_palindromic(n): return (n == rev_num(n)) def main(): #Ask the user to enter a starting and ending number start = eval(input("Enter starting number of the range: ")) end = eval(input("\nEnter ending number of the range: ")) #Check for positivity and that start < end while ((start > end) or (start < 0 or end < 0)): start = eval(input("\nEnter starting number of the range: ")) end = eval(input("\nEnter ending number of the range: ")) #Initialize max_counter and max_number max_counter = 0 max_number = 0 #While loop to iterate over the range of start and end while (start <= end): #Set n to start and reset counter to 0 n = start counter = 0 #Iterate until the number IS palindromic while (not(is_palindromic(n))): n = n + rev_num(n) counter += 1 #Update max_counter and max_number if (counter >= max_counter): max_counter = counter max_number = start #Go to the next value start += 1 #Print output print ("\nThe number", str(max_number), "has the longest cycle length of", str(max_counter) + ".") main()
# File: Goldbach.py # Description: Given a range of even numbers greater than or equal to 4, print out all the unique sum combinations of prime numbers # Student Name: Jonathan Zhang # Student UT EID: jz5246 # Course Name: CS 303E # Unique Number: 50860 # Date Created: 2/25/2016 # Date Last Modified: 2/25/2016 #Define the is_prime function def is_prime (n): if (n == 1): return False limit = int(n ** 0.5) + 1 divisor = 2 while (divisor < limit): if (n % divisor == 0): return False divisor += 1 return True #Define main function def main(): #Initialize start and end for the range start = eval(input("Enter the lower limit: ")) end = eval(input("Enter the upper limit: ")) #While loop to check number conditions while (start >= end or (start % 2 != 0 or end % 2 != 0) or start < 4): start = eval(input("Enter the lower limit: ")) end = eval(input("Enter the upper limit: ")) #Initialize the counter counter = start #Outer while loop to that iterates over the given range while (counter <= end): #Initialize n and answer n = 2 answer = '' #Note to self: always put variables that you need to update towards the top of the while loop so that it will reset after each iteration #Inner while loop to determine all possible prime sum combinations excluding repititions while (n <= counter // 2): if (is_prime(counter - n) and is_prime(n)): #Format the answer answer += " = " + str(n) + " + "+ str(counter - n) n += 1 #Final format answer and print it out answer = str(counter) + answer print(answer) #Go to the next number in the range counter += 2 #Call main main()
# File: htmlChecker.py # Description: Create a program that will check if an html file has matching tags throughout # Student's Name: Jonathan Zhang # Student's UT EID: jz5246 # Course Name: CS 313E # Unique Number: 50940 # # Date Created: 9/30/2016 # Date Last Modified: 9/30/2016 #Implement the stack class class Stack (object): def __init__(self): self.items = [ ] def isEmpty (self): return self.items == [ ] def push (self, item): self.items.append (item) def pop (self): return self.items.pop () def peek (self): return self.items [len(self.items)-1] def size (self): return len(self.items) def getTag(index, line): returnTag = '' while line[index] != ">": if line[index] == ' ': break returnTag += line[index] index += 1 return returnTag def main(): infile = open("htmlfile.txt", "r") #Hold every single tag tagsList = [] #Get rid of duplicates from tagsList VALIDTAGS = [] counter = 0 #Create an instance of stack tagStack = Stack() #Create an exception tags list EXCEPTIONS = ['meta', 'br', 'hr'] #Read each line, then go through each line to extract all tags for line in infile: line = line.strip() if line == "": continue #Iterate through the line and extract tags, appending them to tagsList for i in range(len(line)): if line[i] == "<": tagsList.append(getTag(i+1, line)) #Iterate through tagsList to create validTags for tag in tagsList: #Check for exceptions if tag in EXCEPTIONS: print ("Tag " + str(tag) + " does not need a match: stack is still ", end = '') print (tagStack.items) #Add tag to VALIDTAGS if tag not in VALIDTAGS: VALIDTAGS.append(tag) print ("This is a new tag. Adding to VALIDTAGS") continue #Push start tags onto the stack and print output if tag[0] != "/": tagStack.push(tag) print ("Tag " + str(tag) + " pushed: stack is now ", end = '') print (tagStack.items) #Check to make sure end tags match with top of stack elif tag[0] == "/": #If it's a match if tag[1:] == tagStack.peek(): tagStack.pop() print ("Tag " + str(tag) + " matches top of stack: stack is now ", end = '') print (tagStack.items) #If not a match else: print ("Error. Tag is " + str(tag) + " but top of stack is " + str(tagStack.peek())) #break #Add tag to VALIDTAGS if tag not in VALIDTAGS: VALIDTAGS.append(tag) print ("This is a new tag. Adding to VALIDTAGS") #Ending output if tagStack.isEmpty(): print ("Processing complete. No mismatches found") if tagStack.isEmpty() == False: print ("Processing complete. Unmatched tags remain on stack: ", end = '') print (tagStack.items) print ("\nHere's the list of valid tags: ", end = '') VALIDTAGS.sort() print (VALIDTAGS) EXCEPTIONS.sort() print ("\nHere's the list of exceptions: ", end = '') print (EXCEPTIONS) main()
#Time complexity O(n) and space complexity O(1) class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: l=len(nums) # creating product array with same size as nums p=[0]*l p[0]=1 #Traversing from left and finding product for i in range(1,l): p[i]=p[i-1]*nums[i-1] # Creating right pointer and traversing from right r=1 for i in range(l-1,-1,-1): # p array carries the product p[i]=p[i]*r # incrementing right pointer by multiply it with right elements r=r*nums[i] return p
#!/usr/bin/env python # Credit to: # # http://www.improbable.com/news/2012/Optimal-seating-chart.pdf # https://github.com/perrygeo/python-simulated-annealing from __future__ import division import math import random from .anneal import Annealer #### Plans and Tables #### # A Plan is a list of Tables. # A Table is a list of integers representing people def empty(table): return all(p == -1 for p in table) ### People who are coming, and information about connections MAX_CONNECTION = 100 CONSERVE_TABLE_COEFFICIENT = 50 class PlanningHelper(object): def __init__(self, names, connections): self.NAMES = names self.CONNECTIONS = connections def plan_to_people(self, plan): plan = [[ dict(name=self.NAMES[p], friends=sum(1 if self.CONNECTIONS[p][k] > 0 else 0 for k in table if k != p and k != -1) ) for p in table if p != -1] for table in plan] # Now sort. Assuming sensibly ordered input names, the best is to re-use # that sorting. sort_person_key = lambda p: self.NAMES.index(p['name']) # Just sort tables alphabetically by the first person sort_table_key = lambda t: t[0]['name'] for t in plan: t.sort(key=sort_person_key) plan.sort(key=sort_table_key) return plan class AnnealHelper(object): def __init__(self, names, connections, table_size, table_count): self.NAMES = names self.CONNECTIONS = connections for row in connections: for col in row: assert col <= MAX_CONNECTION self.TABLE_SIZE = table_size self.PEOPLE_COUNT = len(names) self.TABLE_COUNT = table_count # Just need a value that is big enough to keep energy always positive self.MAX_ENERGY = MAX_CONNECTION * self.TABLE_COUNT * self.PEOPLE_COUNT**2 def get_initial_plan(self): people = list(range(0, self.PEOPLE_COUNT)) random.shuffle(people) # We need extra items, to represent spare places. This allows us the # flexibility to have different sized tables. To avoid fruitless # searches, we put them at the end *after* shuffling, and group such # that we get empty tables at the end. total_places = self.TABLE_SIZE * self.TABLE_COUNT # We use -1 as sentinel indicating an empty place, so that it has the # same type as the rest of the data, rather than None, giving us large # speeds up with a JIT (e.g. PyPy). people.extend([-1] * (total_places - len(people))) s = self.TABLE_SIZE c = self.TABLE_COUNT return [people[i*s:(i+1)*s] for i in range(c)] def move(self, plan): # This modifies the plan in place. # Swap two people on two tables t1 = plan.pop(random.randrange(0, len(plan))) t2 = plan.pop(random.randrange(0, len(plan))) p1 = t1.pop(random.randrange(0, len(t1))) p2 = t2.pop(random.randrange(0, len(t2))) t1.append(p2) t2.append(p1) plan.append(t1) plan.append(t2) if p1 == -1 and p2 == -1: # We just swapped two empty seats. Try again: self.move(plan) def seated_together(self, plan, table_num, j, k): t = plan[table_num] return int(j in t and k in t) def energy(self, plan): val = sum( self.CONNECTIONS[j][k] * self.seated_together(plan, table_num, j, k) for table_num in range(0, self.TABLE_COUNT) for j in range(0, self.PEOPLE_COUNT - 1) for k in range(j, self.PEOPLE_COUNT) ) # Better score if fewer tables used (for more friendliness even with # strangers). If table_size and table_count are chosen better this # isn't necessary. val += len([t for t in plan if empty(t)]) * CONSERVE_TABLE_COEFFICIENT * self.PEOPLE_COUNT # Negative, because annealing module finds minimum return self.MAX_ENERGY - val def solve( names, connections, table_size, table_count, annealing_time=6, exploration_steps=100, ): """ Given a list of names, and a square matrix (list of list) defining connection strengths, the table size, and the maximum number of tables available, attempt to find a seating arrangement. Returns a PlanningHelper structure, which has some useful methods like 'plan_to_people', and a plan, which is a list of tables, where each table is a list of people (represented by integers which are indexes into the names list). """ anneal_helper = AnnealHelper(names, connections, table_size, table_count) planning_helper = PlanningHelper(names, connections) state = anneal_helper.get_initial_plan() annealer = Annealer(anneal_helper.energy, anneal_helper.move) schedule = annealer.auto(state, seconds=annealing_time, steps=exploration_steps) state, e = annealer.anneal(state, schedule['tmax'], schedule['tmin'], schedule['steps'], updates=6) # Remove empty tables: state = [t for t in state if not empty(t)] return planning_helper, state
import datetime import math import numbers import re import sys PY3 = sys.version_info[0] == 3 if PY3: string_types = str else: string_types = basestring def luhn(s): """ Calculates the Luhn checksum of a string of digits :param s: :type s: str :return: """ sum = 0 for i in range(0, len(s)): v = int(s[i]) v *= 2 - (i % 2) if v > 9: v -= 9 sum += v return int(math.ceil(float(sum)/10) * 10 - float(sum)) def _test_date(year, month, day): """ Test if the input parameters are a valid date or not """ for x in ['19', '20']: newy = x.__str__() + year.__str__() newy = int(newy) try: date = datetime.date(newy, month, day) if not (date.year != newy or date.month != month or date.day != day): return True except ValueError: continue return False def _get_parts(ssn): """ Get different parts of a Swedish social security number :param ssn: A Swedish social security number to format :type ssn: str|int :rtype: dict :return: Returns a dictionary of the different parts of a Swedish SSN. The dict keys are: 'century', 'year', 'month', 'day', 'sep', 'num', 'check' """ reg = r"^(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\-|\+]{0,1})?(\d{3})(\d{0,1})$" match = re.match(reg, str(ssn)) if not match: raise ValueError( 'Could not parse "{}" as a valid Swedish SSN.'.format(ssn)) century = match.group(1) year = match.group(2) month = match.group(3) day = match.group(4) sep = match.group(5) num = match.group(6) check = match.group(7) if sep == '': if not century: sep = '-' elif datetime.datetime.now().year - int(century + year) < 100: sep = '-' else: sep = '+' if not century: base_year = datetime.datetime.now().year if sep == '+': base_year = base_year - 100 full_year = base_year - ((base_year - int(year)) % 100) century = str(int(full_year / 100)) return { 'century': century, 'year': year, 'month': month, 'day': day, 'sep': sep, 'num': num, 'check': check } def valid(s, include_coordination_number=True): """ Validate a Swedish social security number :param s: A Swedish social security number to validate :param include_coordination_number: Set to False in order to exclude coordination number (Samordningsnummer) from validation :type s: str|int :type include_coordination_number: bool :rtype: bool :return: """ if isinstance(s, string_types) is False and isinstance(s, numbers.Integral) is False: return False try: parts = _get_parts(s) except ValueError: return False year = parts['year'] month = parts['month'] day = parts['day'] num = parts['num'] check = parts['check'] if len(check) == 0: return False is_valid = luhn(year + month + day + num) == int(check) if is_valid and _test_date(year, int(month), int(day)): return True if not include_coordination_number: return False return is_valid and _test_date(year, int(month), int(day) - 60) def format(ssn, long_format=False): """ Format a Swedish social security number as one of the official formats, A long format or a short format. This function raises a ValueError if the input number could not be parsed as a valid Swedish social security number :param ssn: A Swedish social security number to format :param long_format: Defaults to False and formats a social security number as YYMMDD-XXXX. If set to True the format will be YYYYMMDDXXXX. :type ssn: str|int :type long_format: bool :rtype: str :return: """ if not valid(ssn): raise ValueError( 'The social security number "{}" is not valid ' 'and cannot be formatted.'.format(ssn) ) if long_format: ssn_format = '{century}{year}{month}{day}{num}{check}' else: ssn_format = '{year}{month}{day}{sep}{num}{check}' parts = _get_parts(ssn) return ssn_format.format(**parts)
# # Compute the top ten most frequently occurring hashtags in the twitter data. # import sys import json from collections import Counter def main(): tweet_file = open(sys.argv[1]) # Load the tweets lines = tweet_file.readlines() results = {} # a list of tweets as dictionaries for i in range(len(lines)): pyresponse = json.loads(lines[i]) results[i] = pyresponse # Create a dictionary of hashtags and their counts dictionary = {} for i in range(len(results)): # for each tweet in the file entities = {} if(results[i].has_key("entities")): entities = results[i]["entities"] hashtags = [] if(entities.has_key("hashtags")): hashtags = entities["hashtags"] for j in range(len(hashtags)): hashtag = hashtags[j]["text"] if(dictionary.has_key(hashtag)): # Already in dictionary, increment count dictionary[hashtag] += 1 else: # New entry in dictionary dictionary[hashtag] = 1 # Sort dictionary and print top 10 hashtags and their values sorted_dictionary = Counter(dictionary) for hashtag, count in sorted_dictionary.most_common(10): encoded_hashtag = hashtag.encode('utf-8') print '%s: %i' % (encoded_hashtag, count) if __name__ == '__main__': main()
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = Node(root) def insert(self): # consider the balancing act # think about powers of 2 pass def delete(self): # consider the balancing act pass def height_balance(self): pass def in_order_traversal(node: Node): # left, root, right # most used if node: in_order_traversal(node.left) print(node.value, end=" -> ") in_order_traversal(node.right) def pre_order_traversal(node: Node): # root, left, right # most used if node: print(node.value, end=" -> ") in_order_traversal(node.left) in_order_traversal(node.right) def post_order_traversal(node: Node): # left, right, root if node: in_order_traversal(node.left) in_order_traversal(node.right) print(node.value, end=" -> ") # Main driver code if __name__ == "__main__": some_b_tree = BinaryTree(10) some_b_tree.root.left = Node(20) some_b_tree.root.right = Node(30) some_b_tree.root.right.right = Node(60) some_b_tree.root.left.left = Node(40) some_b_tree.root.left.left.left = Node(50) print("In-order traversal results: ", end="") in_order_traversal(some_b_tree.root) print() print("Preorder traversal results: ", end ="") pre_order_traversal(some_b_tree.root) print() print("Post-order traversal results: ", end ="") post_order_traversal(some_b_tree.root) print() """r In-order traversal results: 50 -> 40 -> 20 -> 10 -> 30 -> 60 -> Preorder traversal results: 10 -> 50 -> 40 -> 20 -> 30 -> 60 -> Post-order traversal results: 50 -> 40 -> 20 -> 30 -> 60 -> 10 -> """
# -*- coding: utf-8 -*- """ Created on Sat Apr 10 10:24:22 2021 @author: Sofii """ import random from collections import Counter def tirada_conv(): #Tiro los 5 dados por primera vez tirada1= Counter([random.randint(1,6) for i in range(5)]) #Veo cual es el maximo de veces que se repite algún dado rep_dado1 = max((tirada1).values()) #Hago una lista con los dados que se repiten el maximo de veces dados_max1 = [dado for dado in tirada1 if tirada1[dado] == rep_dado1] #De la lista anterior me quedo con el primero de la lista, sería la versión #en la cuál cuando salen todos los dados distintos me quedo con 1 dados_max1 = dados_max1[0] # print(f'Me quedo con el {dados_max1} y tengo {rep_dado1}') if rep_dado1 == 5: #Si es generala servida devolve un 6 y no sigas con el programa return 6 tirada2= Counter([random.randint(1,6) for i in range((5-rep_dado1))]) # print(tirada2) #Hago la segunda tirada solo con los dados que no me quedé rep_dado2 = max((tirada2).values()) # print("max=", rep_dado2) #Veo cual es el máximo de veces que se repite algún dado en la segunda tirada if rep_dado2 == 5: #Si es generala devolve un 5 return rep_dado2 if rep_dado2 <= rep_dado1: #Si el numero de dados repetidos en la segunda tirada es menor que en # la primera, me quedo con los dados de la primera Ej: Primer tirada me #quedaron 2 dados con el numero 4, y en la segunda me salieron 2 o 1 #dado/s con el número 3, me quedo los del numero 4 for dado in tirada2: if dado == dados_max1: #print(dado) #print(rep_dado1) rep_dado1+=1 #Para cada dado en la segunda tirada, si el dado es del mismo #tipo que el que estaba guardando, sumo uno a la cantidad de #dados que guardo # print(f'Ahora tengo {rep_dado1} del numero {dados_max1}') tirada3= Counter([random.randint(1,6) for i in range((5-rep_dado1))]) #Hago la tercer tirada # print(tirada3) for dado in tirada3: if dado == dados_max1: #print(dado) #print(rep_dado1) rep_dado1+=1 #Para cada dado en la tercer tirada, si el dado es del mismo #tipo que el que estaba guardando, sumo uno a la cantidad de #dados que guardo #print(f'Ahora tengo {rep_dado1} del numero {dados_max1}') return rep_dado1 # Me devuelve el numero maximo de dados del mismo numero # que junte en las tres tiradas else: #Si el numero de dados repetidos en la segunda tirada es mayor que en # la primera, me quedo con los dados de la segunda Ej: Primer tirada me #quedaron 2 dados con el numero 4, y en la segunda me salieron 3 dados #con el número 3, me quedo los del numero 3 dados_max1 = [dado for dado in tirada2 if tirada2[dado] == rep_dado2] dados_max1 = dados_max1[0] #print(f'Cambio los dados y me quedo con {dados_max1} y tengo {rep_dado2}') tirada3= Counter([random.randint(1,6) for i in range((5-rep_dado2))]) for dado in tirada3: if dado == dados_max1: #print(dado) #print(rep_dado1) rep_dado2+=1 # print(f'Ahora tengo {rep_dado2} del numero {dados_max1}') return rep_dado2 # Me devuelve el numero maximo de dados del mismo numero # que junte en las tres tiradas, en el caso de quedarme # con los dados de la segunda tirada tirada_conv() def es_generala(tirada): if tirada == 5: return "generala" elif tirada == 6: return "generala servida" else: return "Mala suerte" print(es_generala(tirada_conv())) N = 100000 Gc = sum([1 for i in range(N) if es_generala(tirada_conv()) == "generala"]) Gs= sum([1 for i in range(N) if es_generala(tirada_conv()) == "generala servida"]) G = Gc+Gs probc= Gc/N probs = Gs/N prob = G/N print(f'Hice {N} tiradas convencionales, de las cuales {G} saqué generala, y {Gs} fueron servidas.') print(f'Podemos estimar la probabilidad de sacar generala mediante uno o mas tiros como: {prob:.6f}.') print(f'Podemos estimar la probabilidad de sacar generala servida como: {probs:.6f}.') #Para probar si tiro todos los dados de nuevo # if len(dados_max1)= 5 # tirada2 = Counter([random.randint(1,6) for i in range(5)])
# HackerRank SHerlock and anagrams # find number of anagramic substrings in each string #anagramic -> which are built of exactly same letters (order of letters isnt important) # i. e. kkkk has 10 pairs # k,k,k,k -> six pairs (combinations of 2 letters in diferent positions) # kk,kk -> 2 pairs # kkk,kkk -> 2 pairs import logging logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO) def CountPairs(s): logging.info(f'Counting pairs of anagrams in string {s}') count=dict() # find all substring and add them to count for i in range(1,len(s)): logging.info(f'Creating {i} letters anagrams:') for j in range(0,len(s)-i+1): ss=''.join(sorted(s[j:j+i])) if ss in count: count[ss]+=1 else: count[ss]=1 logging.info(f'{ss} added to {count}') # sum of numbers of combinations for each substring return sum(sum(range(a)) for a in count.values()) if __name__ == '__main__': e1='kkkk' e2='ifailuhkqq' print(CountPairs(e1)) print(CountPairs(e2))
# example of quicksort implemetation in python usin Hoares partition import logging logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO) def partition(arr,l,h,comp): logging.info(f'current pivot {arr[0]}') pivot=arr[l] i=l+1 j=h while i<=j: # repeat process while pointers i and j dont 'pass by' each other while i<=h and comp(pivot,arr[i]): i+=1 # while pointer i dont reach last index and comp return True while j>l and not comp(pivot,arr[j]): j-=1 # while pointer j dont reach starting point of i and comp return False if i<=j: # at this point we found elements arr[i] and arr[j] that are on reversed sides arr[i],arr[j]=arr[j],arr[i] # swap these elements i+=1 j-=1 logging.info(f'Moving pivot from {l}. to {j}. index') arr[l],arr[j]=arr[j],arr[l] return j def _sort(arr,l,h,comp): # perform recursive divide and conquer tactic using logging.info(f'Performin partition on {arr[l:h+1]}') if l<h: j=partition(arr,l,h,comp) _sort(arr,j+1,h,comp) _sort(arr,l,j-1,comp) def quicksort(arr,comp): h=len(arr)-1 _sort(arr,0,h,comp) asc=lambda p,e: True if p>e else False #e<p desc=lambda p,e: True if p<e else False #e>p if __name__ == '__main__': arr=[5,7,9,3,2,4,6,8,10,21,33,31,23,30] arr2=[7,5,6,3,2] arr3=[8,4,3,5] quicksort(arr,asc) print(arr) quicksort(arr,desc) print(arr) quicksort(arr2,asc) print(arr2) quicksort(arr3,asc) print(arr3)
#python module which provides heapsort with #adjustable comparator function #it relies on max-heap sorting principle #so elements with higher priority are in higher #indexes in sorted iterable from singleton import singleton_decorator @singleton_decorator class parent_child(object): #object that stores comparator function def __init__(self,comp=lambda p,c: True if (p>=c) else False): #by default max-heap comparator fnc self.comp = comp def compare(self,parent,child): return self.comp(parent,child) #function that compares elements at #parent-child indexes def determine_son(self,parentI,lastI,arr): #function that returns index of son #with higher priority childI=None if parentI*2+1<=lastI: childI=parentI*2+1 if childI+1<=lastI and self.compare(arr[childI+1],arr[childI]): childI+=1 return childI ParentChild=parent_child() def heapsort(arr): endI=len(arr)-1 startI=(endI-1)//2 #heapifying arr from first #parent index to the root while startI>=0: heapify(startI,endI,arr) startI-=1 #swaping element from root(index 0) with element #on last index, lowering last index by 1 #and then restoring heap order from index 0 #to the last index while endI>0: arr[0],arr[endI]=arr[endI],arr[0] endI-=1 heapify(0,endI,arr) def heapify(first,last,arr): #restoring heap order of 'branch' #from first to last given indexes parentI=first heapRestored=False while not heapRestored: maxSonI=ParentChild.determine_son(parentI,last,arr) if not maxSonI or ParentChild.compare(arr[parentI],arr[maxSonI]): heapRestored=True else: arr[parentI],arr[maxSonI]=arr[maxSonI],arr[parentI] parentI=maxSonI if __name__ == '__main__': a=[5, 7, 9, 1, 3,6,2,7,5,1,1,2,3,4,5,6,7,8,9,10] b=[2,3,10,11,25,4,5,6,7,8] heapsort(a) heapsort(b) print(a) print(b)
#!/usr/bin/env python3 #import modules import os import sys import shutil import re #store the directory where the files to be renamed are located directory = sys.argv[1] #make a list of the files to be renamed article_list = os.listdir(directory) #create a new directory to save the renamed files new_directory = directory + r"\Renamed" os.mkdir(new_directory) #copy each file in the new directory changing the name n = 0 for article in article_list: name = re.search(r"(.*) ([0-9]*) - (.*)",article) new_article = name[2] + " " + name[1] + " - " + name[3] shutil.copyfile(directory + "\\" + article, new_directory + "\\" + new_article) n += 1 print("{} files renamed succesfully!".format(n)) x = input("Press any key to exit...")
#!/usr/bin/python # -*- coding: UTF-8 -*- # 题目:统计 1 到 100 之和。 tmp = 0 for i in range(1,101): tmp += i print 'The sum is %d' % tmp
#!/usr/bin/env python # -*- coding: utf-8 -*- # 题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同, # 十位与千位相同。 # ___________________________________________________________________ # 程序分析:同29例 # ___________________________________________________________________ # 程序源代码: # main( ) # { # long ge,shi,qian,wan,x; # scanf(“%ld”,&x); # wan=x/10000; # qian=x%10000/1000; # shi=x%100/10; # ge=x%10; # if (ge==wan&&shi==qian)/*个位等于万位并且十位等于千位*/ # printf(“this number is a huiwen\n”); # else # printf(“this number is not a huiwen\n”); # } def main(): x = int(raw_input()) wan = int(x/10000) qian = int(x%10000/1000) shi = int(x%100/10) ge = int(x%10) if ge == wan and shi == qian: print("this number is a huiwen\n") else: print("this number is not a huiwen\n") main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # 题目:一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2 # +3.编程找出1000以内的所有完数。 # ___________________________________________________________________ # 程序源代码: # void main() # { # int a=0,i; # for(i=1;i<1000;i++) # int j,a=0; # for(j=1;j<i;j++) # if((i%j)==0) # a+=j; # if(i==a) # printf("%d是完数\n",a); # return(0); # } def main(): for j in range(2,1000): a = 0 for i in range(1,j): if j%i==0: a+=i if j==a: print("%d is a wanshu"%j) main()
import pygame BLACK = (0,0,0) WHITE = (255,255,255) GREY = (200,200,200) class TextButton(): def __init__(self,size,position,colour=WHITE,rollover_colour=GREY,text="",text_size=14,text_colour=BLACK,font="Arial",action=None): """ size: tuple, (width,height) position: tuple, (x,y of the top left corner of the button) colour: tuple, (R,G,B), defaults to white text: string, defaults to empty string text_size: int, defaults to 14 text_colour: tuple, (R,G,B), defaults to black font: string, defaults to Arial action: function, defaults to None (image with roll-over effect) """ self.width = size[0] self.height = size[1] self.x = position[0] self.y = position[1] self.colour = colour self.rollover_colour = rollover_colour self.text = text #defaults to an empty string self.text_size = text_size self.text_colour = text_colour self.font = font self.action = action #the function to run when the button is clicked def exist(self,screen): """Display the button and make it operational.""" button_location = (self.x,self.y,self.width,self.height) # Get the mouse position for button shading effects mouse_position = pygame.mouse.get_pos() # Stores the left click in click[0] click = pygame.mouse.get_pressed() # Set the text to be displayed on the button font = pygame.font.SysFont(self.font,self.text_size) text_surface = font.render(self.text, True, self.text_colour) text_rect = text_surface.get_rect() text_rect.center = ((self.x + self.width/2),(self.y + self.height/2)) if (self.x < mouse_position[0] < (self.x + self.width)) and (self.y < mouse_position[1] < (self.y + self.height)): # Cursor is hovering over the button pygame.draw.rect(screen,self.rollover_colour,button_location,border_radius=(self.height//2)) screen.blit(text_surface, text_rect) # If the mouse is clicked, execute the function if (click[0] == 1) and (self.action != None): self.action() else: # Cursor is not hovering over the button pygame.draw.rect(screen,self.colour,button_location,border_radius=(self.height//2)) screen.blit(text_surface, text_rect) class ImageButton(): def __init__(self,size,position,image,text="",text_size=14,text_colour=BLACK,font="Arial",action=None,offset=None,last_element=False): """ size: tuple, (width,height) position: tuple, (x,y of the top left corner of the button) image: loaded PyGame image text: string, defaults to empty string text_size: int, defaults to 14 text_colour: tuple, defaults to black font: string, defaults to Arial action: function, defaults to None (image with roll-over effect) offset: int, defaults to None (not a line of images with a set overlap) last_element: bool, defaults to False (not the last element in the line of images, not used if offset is None) """ self.width = size[0] self.height = size[1] self.x = position[0] self.y = position[1] self.image = image self.text = text #defaults to an empty string self.text_size = text_size self.text_colour = text_colour self.font = font self.action = action #the function to run when the button is clicked self.offset = offset self.last_element = last_element def exist(self,screen): """Display the button and make it operational.""" button_location = (self.x,self.y,self.width,self.height) # Get the mouse position for button shading effects mouse_position = pygame.mouse.get_pos() # Stores the left click in click[0] click = pygame.mouse.get_pressed() # Set the text to be displayed on the button font = pygame.font.SysFont(self.font,self.text_size) text_surface = font.render(self.text, True, self.text_colour) text_rect = text_surface.get_rect() text_rect.center = ((self.x + self.width/2),(self.y + self.height/2)) if (self.x < mouse_position[0] < (self.x + self.width)) and (self.y < mouse_position[1] < (self.y + self.height)): # Scale and display the image self.image = pygame.transform.scale(self.image,(self.width,self.height)) #failsafe if image is not pre-scaled, might be redundant in some cases screen.blit(self.image,(self.x,self.y)) # Display a black box around the selected card (logic necessary for image lines with a set offset) if (self.offset is not None) and not self.last_element and (self.x < mouse_position[0] < (self.x + self.offset)) and (self.y < mouse_position[1] < (self.y + self.height)): #it is an image line, it is not the last element in the line pygame.draw.rect(screen, BLACK, (self.x,self.y,self.width,self.height), width=5) # If the mouse is clicked, execute the function if (click[0] == 1) and (self.action != None): self.action() elif (self.offset is not None) and self.last_element and (self.x < mouse_position[0] < (self.x + self.width)) and (self.y < mouse_position[1] < (self.y + self.height)): #it is an image line, it is the last element in the line pygame.draw.rect(screen, BLACK, (self.x,self.y,self.width,self.height), width=5) # If the mouse is clicked, execute the function if (click[0] == 1) and (self.action != None): self.action() elif self.offset is None: # it is not an image line pygame.draw.rect(screen, BLACK, (self.x,self.y,self.width,self.height), width=5) # If the mouse is clicked, execute the function if (click[0] == 1) and (self.action != None): self.action() # Display the text over the button, if applicable screen.blit(text_surface, text_rect) else: # Cursor is not hovering over the button self.image = pygame.transform.scale(self.image,(self.width,self.height)) screen.blit(self.image,(self.x,self.y)) screen.blit(text_surface, text_rect)
# # Programming Assignment 2 # # Problem 2 (15 Points) # # For Dictionary ADT implemented with open hash tables the average number of probes # required to make either a deletion or an insertion is O(1+a). # Find best numerical constants for deletion and insertion. # class Dictionary: 'Dictionary ADT implemented using an open hash table' def __init__(self, buckets): self.table = [[]] * buckets def __getitem__(self, key): i = self._getHash(key) while len(self.table[i]) > 0: if self.table[i][0] == key: return self.table[i][1] else: i += 1 raise IndexError, 'Key not found' def _getHash(self, x): return ord(x[0]) % len(self.table) def insert(self, key, value): i = self._getHash(key) count = 0 while len(self.table[i]) > 0: if count > len(self.table): raise IndexError, 'Hash table is full' i = i+1 if i < (len(self.table) - 1) else 0 count += 1 self.table[i] = [key, value] def delete(self, key): i = self._getHash(key) while len(self.table[i]) > 0: if self.table[i][0] == key: self.table[i] = [] return True else: i += 1 raise IndexError, 'Key not found' if __name__ == '__main__': d = Dictionary(256) # Insert data print 'Inserting values' d.insert('Key', 'Value') d.insert('Other', 'Other value') print '\nThe value of \'Key\' is :', d['Key'] # Delete data print '\nDeleting \'Key\' from dictionary' d.delete('Key') try: print 'The value of \'Key\' is :', d['Key'] except: print 'Unable to find node; deletion successful.' # Explain best case print '\nThe best case for insertion/deletion of a node is one probe. In the above example with ' + \ 'only one value in the dictionary, it only has to probe one value at the location returned ' + \ 'by the hash function'
#!/usr/bin/env python from array import * from list_array import * def makeTrie(): allWords = [] f = open("AliceInWonderland.txt","r"); lines = f.readlines(); for i in lines: thisline = i.split(" "); for j in thisline: if j!="": allWords.append(j.strip()) x=ListArray() for word in allWords: for letter in word: if (word!=""): x.insert(letter,x.end()) x.insert("$",x.end()) count=0 counter=0 while(x.retrieve(counter)!=None): if x.retrieve(counter)=="$": count=count+1 counter=counter+1 return count print "The purpose of this program is to create a trie of all the words appearing in AliceInWonderland.txt, and to find the size of that trie." print "The program does this by creating an array list containing all the words that are in Alice in Wonderland." print "It then iterates through each word, and adds the corresponding letters in order to the list_array implementation. The letters following each letter are stored in a list. At the end of each word, a '$' character is added to indicate the end of a unique word. The method then counts the number of occurences of the '$' character, and returns that number as the size of the trie." print "The size of the trie of AliceInWonderland.txt is:",makeTrie(),"."
#!/usr/bin/python3 """Module and function must be documented""" def island_perimeter(grid): """returns perimeter""" if len(grid) == 0 or grid is None: return 0 height = len(grid) lenght = len(grid[0]) perimeter = 0 for lists in grid: for items in lists: if type(items) is not int: return for y in range(height): for x in range(lenght): if grid[y][x] == 0: continue if y == 0 or grid[y - 1][x] == 0: perimeter += 1 if y == height - 1 or grid[y + 1][x] == 0: perimeter += 1 if x == 0 or grid[y][x - 1] == 0: perimeter += 1 if x == lenght - 1 or grid[y][x + 1] == 0: perimeter += 1 return perimeter
print('''Day3 List \n \n ''') example = [1, 2, 3] print(example) xample1 = ['cat', 'bat', 'rat', 'elephant'] print(example1) example2 = ['hello', 3.4452, True, None, 42] print(example2) spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[0]) print(spam[1]) print(spam[2]) print(spam[3]) print('Hello ' + spam[0]) print(f"The {spam[1]} ate the {spam[0]}") print(spam[20000]) print(spam[int(1.0)]) spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] print(spam[0]) print(spam[0][0]) print(spam[1][4]) print(spam[-1]) print(spam[-3]) print(f"The {spam[-1]} is afraid of the {spam[-3]}.") print(spam[0:4]) rint(spam[1:3]) print(spam[0:-1]) print(spam[:2]) print(spam[1:]) print(spam[:]) spam = ['cat', 'dog', 'mouse'] print(len(spam)) spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aakash' print(spam) spam[2] = spam[1] print(spam) spam[-1] = 12345 print(spam) mix = [1, 2, 3] + ['a', 'b', 'c'] print(mix) mix2 = ['X', 'Y', 'Z'] * 3 print(mix2) spam = [1, 2, 3] spam = spam + ['A', 'B', 'C'] print(spam) del spam[2] print(spam) del spam[2] print(spam) catName1 = input('Enter the name of cat 1:\n') catName2 = input('Enter the name of cat 2:\n') catName3 = input('Enter the name of cat 3:\n') catName4 = input('Enter the name of cat 4:\n') catName5 = input('Enter the name of cat 5:\n') catName6 = input('Enter the name of cat 6:\n') print('The cats names are: 'f'{catName1} {catName2} {catName3} {catName4} {catName5} {catName6} ') carNames = [] while True: name = input(f"Enter the name of cat {str(len(carNames) + 1)} (or enter nothing to stop.); ") if name == '': break carNames = carNames + [name] print('The cat name are; ') for name in carNames: print(' ' + name)
#! ============================================================================== #! NEW SECTION - Lab 1 #! ============================================================================== english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"] french = ["bonjour", "chat", "chien", "oui", "demain", "hier", "difficile", "facile", "mauvais", "non", "mardi", "janvier"] if(len(english) % 2 == 0 and len(french) % 2 == 0): print("They are both even") else: print("Lists are not both even") #! next =========================== > english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"] #! next =========================== > english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"] french = ["bonjour", "chat", "chien", "oui", "demain", "hier", "difficile", "facile", "mauvais", "non", "mardi", "janvier"] # Creating the Dictionary english_and_french = {} # They are both same length so can run loop for length of either one for counter in range(len(english)): english_and_french[english[counter]] = french[counter] print(english_and_french) #! next =========================== > english_french = {k: v for k, v in english_and_french.items() if(len(v) > 4)} print(english_french) #! next =========================== > print(english_french) #! next =========================== > def translate(dictionary, word_to_translate, default_word): if(word_to_translate in dictionary.keys()): print("Word found, translating...") print(dictionary[word_to_translate]) print("Completed") return dictionary[word_to_translate] else: print("Not found") return default_word # End of the function response = translate(english_french, "dog", "Not in the dictionary") print("Response is: ", response) #! next =========================== > english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"] #! next =========================== > english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"] french = ["bonjour", "chat", "chien", "oui", "demain", "hier", "difficile", "facile", "mauvais", "non", "mardi", "janvier"] if(len(english) % 2 == 0 and len(french) % 2 == 0): print("They are both even") else: print("Lists are not both even") #! next =========================== > english = ["hello", "cat", "dog", "yes", "tomorrow", "yesterday", "difficult", "easy", "bad", "no", "tuesday", "january"] french = ["bonjour", "chat", "chien", "oui", "demain", "hier", "difficile", "facile", "mauvais", "non", "mardi", "janvier"] # Creating the Dictionary english_and_french = {} # They are both same length so can run loop for length of either one for counter in range(len(english)): english_and_french[english[counter]] = french[counter] print(english_and_french) #! next =========================== > def translate(dictionary, word_to_translate, default_word): if(word_to_translate in dictionary.keys()): print("Word found, translating...") print(dictionary[word_to_translate]) print("Completed") return dictionary[word_to_translate] else: print("Not found") return default_word # End of the function response = translate(english_french, "dog", "Not in the dictionary") print("Response is: ", response) #! ============================================================================== #! NEW SECTION - Lab 2 #! ============================================================================== # Setting global variable for practice # How to get 2 decimal places: "{:1.2f}".format(x) total = 0; # Function which takes in csv file path and sums up each row def getTotal(file_path): try: f = open(file_path, "r") lines = f.readlines() f.close() except IOError: print("Unable to read from file", file_path) # file path is correct lineCounter = 1 for line in lines: # Using global variable in this scope global total # line is the whole line #parts is a list of strings, need to convert each parts = line.split(",") line = line.strip() parts = (list(map(float, parts))) total += sum(parts) response = '''\ This is a {lineCounter} Here is a {total} '''.format(lineCounter=lineCounter, total="{:1.2f}".format(total)) print(response) lineCounter += 1 total = 0 # end of for loop return total print(getTotal("scores.csv")) #! next =========================== > def reverse_numbers(input_file_path, output_file_path): try: fin = open(input_file_path, "r") fout = open(output_file_path, "w") lineCounter = 1 for line in fin.readlines(): fout.write("Line Number ") fout.write(str(lineCounter)) fout.write("\n") parts = line.split(",") parts = (list(map(float, parts))) # Returns None, but acts on the original list parts parts.reverse() # parts is now in reverse order fout.write(str(parts)) fout.write("\n") lineCounter += 1 # Close connections fin.close() fout.close() except IOError: print("Unable to read from files given", input_file_path, " ", output_file_path) # end of function reverse_numbers("scores.csv", "reverse_numbers.csv") #! ============================================================================== #! NEW SECTION #! ==============================================================================
#!/usr/bin/python __author__ = 'pythonspot.com' l = [ "Drake", "Derp", "Derek", "Dominique" ] print(l) # prints all elements print(l[0]) # print first element print(l[1]) # prints second element
# A program that plots 3 different lines on one line plot. # Each line has similar x values however they have a different equation to solve for y value of each line. # Author: Ryan Cox # Importing numpy and matplotlib. import numpy as np import matplotlib.pyplot as plt minRange = 0 # Defining the minimum parametre maxRange = 4 # Defining the maximum parametre fx = np.arange(minRange,maxRange) # creating an array for the x value of f(x) line. Values are the range within the range parametres set above. fy = np.array([]) # creating empty array for y value of f(x) line. hx = np.arange(minRange,maxRange) hy = np.array([]) gx = np.arange(minRange, maxRange) gy = np.array([]) for x in fx: # loop the value of fx ie. the range of x values. y = x # y is equal to x. fy = np.append(fy,y) # Append y to the fy array. for x in hx: # loop the value of hx ie. the range of x values. y = x**2 # y is equal to x^2. hy = np.append(hy,y) # append y to the hy array. for x in gx: # loop the value of gx ie. the range of x values. y = x**3 # y is equal to x^3. gy = np.append(gy,y) # append y to the gy array. # plotting f(x), h(x), and g(x). plt.plot(fx,fy, color='aqua', lw='2', label = 'f(x)') # ploting the f(x) line with adjusted color and line width. Name this line 'f(x)' plt.plot(hx,hy, color ='darkgreen',lw='4', label = 'h(x)') # similar adjustments made to h(x) line plt.plot(gx,gy, color='hotpink', ls = '--', lw='2', label = 'g(x)') # ls is linestyle i.e. broken line. plt.legend() # adding a legend to the plot. plt.title("Different Lines", fontsize=18, weight = "bold") # Adding title to the plot with the font size and in bold font. plt.xlabel("x Axis", fontsize=12) # labeling the x Axis with fontsize 12. plt.ylabel("y Axis", fontsize=12) # labeling the y Axis with fontsize 12. plt.show() # running the plot to show as an image.
import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, MaxAbsScaler, MinMaxScaler def stats(raw_data): """Computes statistics useful for reverse scaling of predictions. :param raw_data: pandas.DataFrame - original DataFrame :return: pandas.DataFrame - DataFrame of coefficients used for reverse scaling """ stats_df = raw_data.describe().transpose() stats_df = stats_df[["min", "max", "mean", "std"]] stats_df["maxabs"] = pd.concat([stats_df["min"].abs(), stats_df["max"].abs()], axis=1).max(axis=1) stats_df["std"] = np.std(raw_data) return stats_df def scale_standard(raw_data): """Wrapper for Scikit-learn StandardScaler : scales raw data and returns stats_df for later rescaling. :param raw_data: pandas.DataFrame - original DataFrame to scale :return: tuple of pandas.DataFrames - (data_scaled, stats_df) """ stats_df = stats(raw_data) data_scaled = raw_data.copy() data_scaled.iloc[:, :] = StandardScaler().fit_transform(data_scaled) return data_scaled, stats_df def scale_maxabs(raw_data): """Wrapper for Scikit-learn MaxAbsScaler : scales raw data and returns stats_df for later rescaling. :param raw_data: pandas.DataFrame - original DataFrame to scale :return: tuple of pandas.DataFrames - (data_scaled, stats_df) """ stats_df = stats(raw_data) data_scaled = raw_data.copy() data_scaled.iloc[:, :] = MaxAbsScaler().fit_transform(data_scaled) return data_scaled, stats_df def scale_minmax(raw_data): """Wrapper for Scikit-learn MinMaxScaler : scales raw data and returns stats_df for later rescaling. :param raw_data: pandas.DataFrame - original DataFrame to scale :return: tuple of pandas.DataFrames - (data_scaled, stats_df) """ stats_df = stats(raw_data) data_scaled = raw_data.copy() data_scaled.iloc[:, :] = MinMaxScaler().fit_transform(data_scaled) return data_scaled, stats_df def scaling(raw_data, method): """Scales the raw dataframe using the specified scaling method. :param raw_data: pandas.DataFrame - original DataFrame :param method: String in ["", "standard", "maxabs", "minmax"] - Scaling to be applied to the data :return: tuple of two pandas.DataFrames - (scaled data, stats useful for later reverse scaling) """ method_dict = {"standard": scale_standard, "maxabs": scale_maxabs, "minmax": scale_minmax} if method == "": scaled, stats_df = raw_data, stats(raw_data) else: scaled, stats_df = method_dict[method](raw_data) return scaled, stats_df def reverse_standard(data_scaled, interest_vars, stats_df): """Reverse the Standard scaling of a 2D numpy array (the predicted values) given the place of the predicted features in the original data and the stats DataFrame. :param data_scaled: numpy.ndarray (2D) - data to transform back to the original scale. :param interest_vars: list of ints - indices of the features to predict (indices in the input matrix) Example : 321 features as inputs, we predicted the features corresponding to the columns 1, 6 and 315: interest_vars is then [1, 6, 315] :param stats_df: pandas.DataFrame - DataFrame of coefficients used to reverse scaling (obtained from scale_standard) :return: numpy.ndarray (2D) - data transformed back to the original scale. """ data_unscaled = np.copy(data_scaled) k = 0 for i in interest_vars: coefs_1 = stats_df["mean"].iloc[i] coefs_2 = stats_df["std"].iloc[i] if len(data_unscaled.shape) > 1: data_unscaled[:, k] = coefs_1 + coefs_2 * data_unscaled[:, k] else: data_unscaled = coefs_1 + coefs_2 * data_unscaled k = k + 1 return data_unscaled def reverse_maxabs(data_scaled, interest_vars, stats_df): """Reverse the MaxAbs scaling of a 2D numpy array (the predicted values) given the place of the predicted features in the original data and the stats DataFrame. :param data_scaled: numpy.ndarray (2D) - data to transform back to the original scale. :param interest_vars: list of ints - indices of the features to predict (indices in the input matrix) Example : 321 features as inputs, we predicted the features corresponding to the columns 1, 6 and 315: interest_vars is then [1, 6, 315] :param stats_df: pandas.DataFrame - DataFrame of coefficients used to reverse scaling (obtained from scale_maxabs) :return: numpy.ndarray (2D) - data transformed back to the original scale. """ data_unscaled = np.copy(data_scaled) k = 0 for i in interest_vars: coefs = stats_df["maxabs"].iloc[i] if len(data_unscaled.shape) > 1: data_unscaled[:, k] = coefs * data_unscaled[:, k] else: data_unscaled = coefs * data_unscaled k = k + 1 return data_unscaled def reverse_minmax(data_scaled, interest_vars, stats_df): """Reverse the MinMax scaling of a 2D numpy array (the predicted values) given the place of the predicted features in the original data and the stats DataFrame. :param data_scaled: numpy.ndarray (2D) - data to transform back to the original scale. :param interest_vars: list of ints - indices of the features to predict (indices in the input matrix) Example : 321 features as inputs, we predicted the features corresponding to the columns 1, 6 and 315: interest_vars is then [1, 6, 315] :param stats_df: pandas.DataFrame - DataFrame of coefficients used to reverse scaling (obtained from scale_minmax) :return: numpy.ndarray (2D) - data transformed back to the original scale. """ data_unscaled = np.copy(data_scaled) k = 0 for i in interest_vars: coefs_1 = stats_df["min"].iloc[i] coefs_2 = stats_df["max"].iloc[i] if len(data_unscaled.shape) > 1: data_unscaled[:, k] = coefs_1 + (coefs_2 - coefs_1) * data_unscaled[:, k] else: data_unscaled = coefs_1 + (coefs_2 - coefs_1) * data_unscaled k = k + 1 return data_unscaled def reverse_scaling(data_scaled, interest_vars, stats_df, method): method_dict = {"standard": reverse_standard, "maxabs": reverse_maxabs, "minmax": reverse_minmax} return method_dict[method](data_scaled, interest_vars, stats_df) def inputs_targets_split(data, input_cols, target_cols, samples_length=168, pred_delay=24, pred_length=1): """Selects input and target features from data. :param data: pandas.DataFrame - loaded data, possibly scaled already. :param input_cols: list - names of the columns used as input variables. [] means "all columns". :param target_cols: list - names of the columns used as target variables. [] means "all columns". :param samples_length: int - time window size (timesteps) for the RNN. Default = 168 :param pred_delay: int - prediction horizon. We predict values at t+pred_delay. Default = 24 :param pred_length: int - number of predicted timesteps, starting at t+pred_delay. Default = 1 :return: Tuple of two pandas.DataFrames - - the first is the DataFrame of input features - the second is the DataFrame of output features """ inputs = data if len(input_cols) == 0 else data[input_cols] targets = data if len(target_cols) == 0 else data[target_cols] inp_end = len(data) - (pred_delay + pred_length) + 1 tar_start = samples_length + pred_delay + pred_length - 2 inputs = inputs.iloc[:inp_end] targets = targets.iloc[tar_start:].reset_index(drop=True) return inputs, targets def train_val_split(targets, train_ratio=0.6, val_ratio=0.2): """Returns range limits for Train / Validation / Test sets :param targets: pandas.DataFrame - target columns (obtained after scaling and inputs_targets_split) :param train_ratio: float in ]0, 1[ - Proportion of rows to use as training set. Default = 0.6 :param val_ratio: float in ]0, 1[ - Proportion of rows to use as validation set. Default = 0.2 :param pred_delay: int - prediction horizon > 0. We predict values at t+pred_delay. Default = 24 :param pred_length: int - number of predicted timesteps, starting at t+pred_delay. Default = 1 :return: tuple of 3 int-tuples - (train_start, train_end), (val_start, val_end), (test_start, test_end) """ train_start = 0 train_end = round(train_ratio * len(targets)) val_start = train_end val_end = val_start + round(val_ratio * len(targets)) test_start = val_end test_end = len(targets) return (train_start, train_end), (val_start, val_end), (test_start, test_end) def colnames_to_colindices(interest_cols, original_df): """Returns a list containing the indices (in the original DataFrame) of the target columns. :param interest_cols: list - list of target columns names :param original_df: pandas.DataFrame - initial DataFrame with its original column names :return: list of ints - indices of the target columns in the original DataFrame. """ names = list(original_df.columns) indices = [names.index(col) for col in interest_cols] return indices def sample_gen_rnn(scaled_inputs, scaled_targets, limits=None, samples_length=168, sampling_step=1, batch_size=24): """Batch generator for RNN architectures. :param scaled_inputs: pandas.DataFrame - inputs obtained from inputs_targets_split() :param scaled_targets: pandas.DataFrame - targets obtained from inputs_targets_split() :param limits: int tuple - (start_row, end_row) : start and end rows, one of train_val_split() results :param samples_length: int - time window size (timesteps) for the RNN. Default = 168 :param sampling_step: int - step of the sliding time window. Default = 1 (no position skipped) :param batch_size: int - batch size for mini-batch gradient descent. Default = 24 :yield: tuple - (input_batch, target_batch) """ if limits is None: limits = (0, len(scaled_targets)) inp_row = limits[0] tar_row = limits[0] inp_batch = [] tar_batch = [] while inp_row < limits[1]: inp = scaled_inputs.iloc[inp_row:inp_row + samples_length].values inp_batch.append(inp) tar = scaled_targets.iloc[tar_row].values tar_batch.append(tar) if len(inp_batch) == batch_size or (inp_row + sampling_step) >= limits[1]: yield np.array(inp_batch), np.array(tar_batch) inp_batch = [] tar_batch = [] inp_row += sampling_step tar_row += sampling_step if inp_row >= limits[1]: inp_row = limits[0] tar_row = limits[0] def yield_inputs_only(generator): while True: x, y = next(generator) yield x def compute_generator_steps(idx, sampling_step, batch_size): """Computes the number of steps for Keras.models.fit_generator. :param idx: int tuple - (start_row, end_row) : start and end rows; one of train_val_split() results :param sampling_step: int - step of the sliding time window. :param batch_size: int - batch size for mini-batch gradient descent. :return: int - number of samples yielded by the generator in one epoch """ nb_indices = idx[1] - idx[0] nb_indiv_samples = nb_indices // sampling_step + min(nb_indices % sampling_step, 1) nb_batches = nb_indiv_samples // batch_size + min(nb_indiv_samples % batch_size, 1) return nb_batches def prepare_data_generators(raw_data, input_cols, target_cols, scaling_method="", samples_length=168, pred_delay=24, pred_length=1, sampling_step=1, batch_size=24, train_ratio=0.6, val_ratio=0.2): """Global data preparation method. Scales data and prepares generators respectively for train, validation and test. :param raw_data: pandas.DataFrame - original DataFrame :param input_cols: list - names of the columns used as input variables. [] means "all columns". :param target_cols: list - names of the columns used as target variables. [] means "all columns". :param scaling_method: String in ["", "standard", "maxabs", "minmax"] - Scaling to be applied to the data :param samples_length: int - time window size (timesteps) for the RNN. Default = 168 :param pred_delay: int - prediction horizon. We predict values at t+pred_delay. Default = 24 :param pred_length: int - number of predicted timesteps, starting at t+pred_delay. Default = 1 :param sampling_step: int - step of the sliding time window. :param batch_size: int - batch size for mini-batch gradient descent. :param train_ratio: float in ]0, 1[ - Proportion of rows to use as training set. Default = 0.6 :param val_ratio: float in ]0, 1[ - Proportion of rows to use as validation set. Default = 0.2 :return: dictionary of (generators, nb steps for each generator), stats useful for reverse scaling """ scaled, stats_df = scaling(raw_data, scaling_method) inputs, targets = inputs_targets_split(scaled, input_cols, target_cols, samples_length, pred_delay, pred_length) train_idx, val_idx, test_idx = train_val_split(targets, train_ratio, val_ratio) train_gen = sample_gen_rnn(inputs, targets, train_idx, samples_length, sampling_step, batch_size) train_gen_steps = compute_generator_steps(train_idx, sampling_step, batch_size) val_gen = sample_gen_rnn(inputs, targets, val_idx, samples_length, sampling_step, batch_size) val_gen_steps = compute_generator_steps(val_idx, sampling_step, batch_size) test_gen = sample_gen_rnn(inputs, targets, test_idx, samples_length, sampling_step, batch_size) test_gen_steps = compute_generator_steps(test_idx, sampling_step, batch_size) generators_dict = {"train": (train_gen, train_gen_steps), "val": (val_gen, val_gen_steps), "test": (test_gen, test_gen_steps)} return generators_dict, stats_df
def list_recursion(number): numbers = [] if number > 0: numbers.append(number) return numbers + list_recursion(number - 1) else: return [] print(list_recursion(5)) list_recursion(5) [5] + list_recursion(4) [5] + ([4] + list_recursion(3)) [5] + ([4] + ([3] + list_recursion(2))) [5] + ([4] + ([3] + ([2] + list_recursion(1)))) [5] + ([4] + ([3] + ([2] + ([1] + list_recursion(0))))) [5] + ([4] + ([3] + ([2] + ([1] + [])))) [5] + ([4] + ([3] + ([2] + ([1])))) [5] + ([4] + ([3] + ([2, 1]))) [5] + ([4] + ([3, 2, 1])) [5] + ([4, 3, 2, 1]) [5, 4, 3, 2, 1]
import argparse import cProfile, pstats, sys import logging from typing import List logging.basicConfig() logging.root.setLevel(logging.DEBUG) """ leetcode 877. stone game https://leetcode.com/problems/stone-game/ https://github.com/labuladong/fucking-algorithm/blob/master/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E7%B3%BB%E5%88%97/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E4%B9%8B%E5%8D%9A%E5%BC%88%E9%97%AE%E9%A2%98.md my understanding https://docs.google.com/spreadsheets/d/1_ND0CsEl4EoC92WEZDQ2lWtw0Wyy7D2rU3RttFALYO4/edit#gid=1593371985 """ class Solution(object): def stoneGame(self, piles: List[int]) -> bool: dp = [[(0,0) for x in piles] for x in piles] # initialize with one pile only for i in range(0, len(piles)): dp[i][i] = (piles[i], 0) for i in range(1, len(piles)): # i=1 means 2 piles, i=2 means 3 piles x = 0 # start index y = x + i # end index while y < len(piles): # left = piles[x] + dp[x+1][y][1] right = piles[y] + dp[x][y-1][1] if left > right: dp[x][y] = (left, dp[x+1][y][0]) else: dp[x][y] = (right, dp[x][y-1][0]) x += 1 y += 1 result = dp[0][len(piles)-1] return result[0] > result[1] if __name__ == "__main__": parser = argparse.ArgumentParser() # arguments ref: https://stackoverflow.com/questions/15301147/python-argparse-default-value-or-specified-value parser.add_argument("--piles", help="piles", nargs='?', type=str, const="5,3,4,5", default="5,3,4,5") args = parser.parse_args() piles = [int(x) for x in args.piles.split(",")] solution = Solution() result = solution.stoneGame(piles) print("result for piles {} is {}".format(piles, result))
""" YZ_IMPORT try to understand python compiler! """ import os import re def main(): """ MAIN tests module ex.1 >>> path = './file01.txt' >>> tree = Tree(path) >>> print(tree) >>> print(tree.is_valid(path)) def('a') call('a') { call('a') def('b') } call('a') True """ # ex.1 path = './file01.txt' tree = Tree(path) print(tree) print(tree.is_valid()) class Tree(object): """ TREE makes a tree from a file with given path. """ def __init__(self, path): """ PARAM path as str: path of file """ self.root = Tree.make_tree(path) @staticmethod def make_tree(path): """ MAKE_TREE makes a tree from a file with given path. """ (filename, _) = os.path.splitext(os.path.basename(path)) root = Node(filename) for line in open(path): line = str.strip(line) if line == '{': root.childs.append(Node(name='', parent=root)) root = root.childs[-1] elif line == '}': root = root.parent elif str.startswith(line, 'import'): root = Tree.make_tree(Tree.get_text_of_node_name(line)) else: root.childs.append(Node(name=line, parent=root)) return root def __str__(self): root = self.root res = [] Tree.recursive_str(root, res, '') return '\n'.join(res) @staticmethod def recursive_str(root, res, tab): """ RECURSIVE_STR makes string representaion of the tree determined by given 'root' PARAM root as Node: root of tree PARAM res as [str]: result PARAM tab as str: specifies the indentation """ for node in root.childs: if len(node.childs) == 0: res.append(tab + node.name) else: res.append(tab + '{') Tree.recursive_str(node, res, tab + '\t') res.append(tab + '}') def is_valid(self): """ IS_VALID check that a module with given 'path' is valid or not. """ return all(\ self.is_valid_call_node(call_node) \ for call_node in self.get_call_nodes(self.root) \ ) def get_call_nodes(self, root): """ GET_CALL_NODES returns all call nodes """ if str.startswith(root.name, 'call'): yield root for node in root.childs: yield from self.get_call_nodes(node) def get_def_nodes(self, root): """ GET_DEF_NODES returns all def nodes of a node """ if root is None: return for node in root.childs: if str.startswith(node.name, 'def'): yield node yield from self.get_def_nodes(root.parent) def is_valid_call_node(self, call_node): """ IS_VALID_CALL_NODE returns true if there is an 'def' node in """ call_text = Tree.get_text_of_node_name(call_node.name) return any(\ Tree.get_text_of_node_name(def_node.name) == call_text \ for def_node in self.get_def_nodes(call_node.parent) \ ) @staticmethod def get_text_of_node_name(name): """ GET_TEXT_OF_NODE_NAME returns text of 'call(text)' or 'def(text)' """ pattern = r'(?:call|def|import)\((.+)\)' match = re.search(pattern, name) return match.group(1) class Node(object): """ NODE implements node of tree """ def __init__(self, name, parent=None): self.name = name self.parent = parent self.childs = [] if __name__ == '__main__': main()
import sqlite3 class UserModel: #class for initiating a user, finding the user and retrieving it (sign in) def __init__(self, _id, username, password): #id because id is a python keyword, but self.id is okay self.id = _id self.username = username self.password = password @classmethod #the next code is a method of the class User, so we use cls instead of self, User def find_by_username(cls, username): #a function to find user by his username connection = sqlite3.connect('data.db') #connecting to the data.db database cursor = connection.cursor() query = "SELECT * FROM users WHERE username=?" #selecting all data with the same username we provided result = cursor.execute(query, (username,)) #putting the data of the selected user in result variable row = result.fetchone() #if this user was found it will be fetched in row if row: user = cls(*row) #retrieve data in the 3 columns in this user else: user = None connection.close() return user @classmethod #the next code is a method of the class User, so we use cls instead of self, User def find_by_id(cls, _id): #a function to find user by his id connection = sqlite3.connect('data.db') #connecting to the data.db database cursor = connection.cursor() query = "SELECT * FROM users WHERE id=?" #selecting all data with the same id we provided result = cursor.execute(query, (_id,)) #putting the data of the selected user in result variable, the, format is because we want to indicate a tuple containing only id for the user row = result.fetchone() #if this user was found it will be fetched in row if row: user = cls(*row) #retrieve data in the 3 columns in this user else: user = None connection.close() return user
import math def circumference(r): """Calculate the surface of a circle of radius r This does not compute the surface though :D""" return 2*math.pi*r def area(r): """ Function calculating area of circle of radius r """ return math.pi*r**2 def area_triangle(base, height): """ Calculate the area of a triangle. param "base": width of the triangle base param "height": height of the trianble """ return base*height/2 def circumference_triangle(a, b, c): """ Calculate the circumference of a triangle. param a: one side of the triangle param b: other side of the triangle param c: third side of the triangle return: circumference of the triangle """ return a + b + c print("Hello world")
import sys def get_score(array): ans = 0 for k in array: if k%2 == 0: ans+=2 else: ans+=1 return ans def get_numbers(array): vowels = ( 'a', 'e', 'i', 'o', 'u', 'y' ) counts = [] temp = 0 for i in range(len(array)): for j in range(len(array[i])): if array[i][j] in vowels: temp+=1 counts.append(temp) temp = 0 return counts def main(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') input() words = tuple(input().split()) numbers = get_numbers(words) print(get_score(numbers)) if __name__ == '__main__': main()
def percentage(arr, n): x=sum(arr) y=n*100 return "%.12f" %(x*100/y) def main(): n=int(input()) d=list(map(int,input().split())) print(percentage(d,n)) if __name__ == '__main__': main()
def math(number_x, number_y): s='' for i in range(len(number_x)): if int(number_x[i])+int(number_y[i])==2: s+='0' elif int(number_x[i])+int(number_y[i])==1: s+='1' else: s+='0' return s def main(): x=input() y=input() print(math(x,y)) if __name__ == '__main__': main()
import sys def get_lowest(bird_dict, ans): lowest_birds = [] for bird in bird_dict: if bird_dict[bird] == ans: lowest_birds.append(bird) return min(lowest_birds) def get_count(arr): counts = {} ans = 0 for birds in arr: counts[birds] = counts.get(birds, 0) + 1 if counts[birds] > ans: ans = counts[birds] return counts, ans def main(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') input() birds = tuple(map(int, input().split())) bird_dictionary, x = get_count(birds) print(get_lowest(bird_dictionary, x)) if __name__ == '__main__': main()
n=int(input("enter number of terms required")) n1=0 n2=1 c=0 if n<0: print("enter positive integers") elif n==1: print("0") else : print("the series is:") while c<n: print(n1) temp=n1+n2 n1=n2 n2=temp c+=1
i= int(input("enter a number")) num=(i+(10*i+i)+(110*i+i)) print(num)
#函数 #print() #a = 2.23232323 #print(round(a,3)) #2.23 ''' 函数内部执行了return , 后面的代码不会执行 import sys sys.setrecursionlimit(29) def add(x, y): print(x + y) result = x-y return result a = add(2,3) print(a) ''' ''' 提高阅读性,接收函数结果方式,用名称代替damage[0]使接受的参数简单明了 def damage(skill1, skill2): damage1 = skill1+skill2 damage2 = skill1*skill2 #return {'s':damage1,'f':damage2} return damage1,damage2 skill1_damages1, skill1_damages2 = damage(2,3) print(skill1_damages1) print(skill1_damages2) print(type(skill1_damages2)) ''' ''' #序列解包 a = 1, 2, 3 print(type(a)) c,d,e = a print(c) print(type(c)) '''
# 문제4 # 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에 # 출력해보세요. 1부터 99까지만 실행하세요. for i in range(1, 100): if (str(i).find('3') != -1 or str(i).find('6') != -1 or str(i).find('9') != -1): print(i, '짝')
#!/bin/python3 # https://www.hackerrank.com/challenges/2d-array/problem import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): hgSum = -63 for x in range (len(arr) - 2): for y in range(len(arr) -2): num = arr[x][y] + arr[x][y + 1] + arr[x][y + 2] + arr[x + 1][y + 1] + arr[x + 2][y] + arr[x + 2][y + 1] + arr[x + 2][y + 2] if num > hgSum: hgSum = num return hgSum if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) result = hourglassSum(arr) fptr.write(str(result) + '\n') fptr.close()
from itertools import islice def evolution(island): ''' Infinite generator for evolution of some population. This generator yields population: population - tuple together containing tuples/individuals population_0 = create() population_1 = evolve(population_0, info_0) . . population_k = evolve(population_k-1, info_k-1) . . Since population is a tuple/an immutable type, a population cannot be influenced by outside functions. Population can be used only to gather statistics If no immigration and emmigration is used this island evolution becomes a classical genetic algorithm. ''' population = island.create_population() while True: for _ in range(island.migration_interval if island.migrate else 1): yield population # Immigration - Outside individuals are inhabiting an island if island.assimilate: population = island.assimilate(population) # Evolution - Each island population is evolved into the next generation population = island.evolve(population) # Emmigration - Sends individuals (clones) from one population onto voyage if island.migrate: island.migrate(population) def finite_evolution(num_iterations, island): ''' Same as evolution, except stopped after num_iterations ''' return islice(evolution(island), num_iterations) def stagnation_evolution(max_stagnation, island): ''' Same as evolution, except stopped after max_stagnation ''' infinite_evolution = evolution(island) population = next(infinite_evolution) best = min(population) stagnation = 0 while stagnation < max_stagnation: stagnation += 1 yield population population = next(infinite_evolution) current_best = min(population) if current_best < best: stagnation = 0 best = current_best
import random import functools as fcn def get_number_permutation_generator(start, end): ''' Closure around elements (start, start + 1, ..., end - 1) ''' return get_random_permutation_generator(range(start, end)) def get_random_permutation_generator(elements): ''' Generates closure around elements = (x_0, x_1, x_2, ..., x_n-1). This closure returns random permutation of this elements, e.g. (x_0, x_n-1, x_3, ..., x_2, x_n - 1) ''' generator_elements = list(elements) return fcn.partial(__random_permutation_generator, generator_elements) def __random_permutation_generator(generator_elements): ''' Closure which returns permutation of generator_elements ''' random.shuffle(generator_elements) return tuple(generator_elements) def unit(num_elements): ''' generates unit permutation, (0, 1, 2, ..., n - 1) ''' return tuple(range(num_elements))