text
stringlengths
37
1.41M
# This works was inspire by the worked example "Counting email in databases" which we get the email from a txt file. # Then I want to retrieve the email in the url format and # I successfully get the email from "http://www.py4inf.com/code/mbox-short.txt" # However, I find it cannot read from "https://www.py4e.com/code3/mbox.txt." # The reason could be this web page is secure. # Result: mbox-short.txt(successed) # mbox.txt(fail) import sqlite3 import urllib.request, urllib.parse, urllib.error import ssl from bs4 import BeautifulSoup ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE conn = sqlite3.connect('emaildb.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS Counts') cur.execute('CREATE TABLE Counts (email TEXT, count INTEGER)') #Create a table in SQL that the name is 'Counts' and has email and count in row. #Get the content in Url and split the content by line url = input('enter the url') if (len(url)<1): url = 'http://www.py4inf.com/code/mbox-short.txt' html = urllib.request.urlopen(url, context=ctx).read() html = BeautifulSoup(html, "html.parser") data = str(html).splitlines() # We first create a list to store email that we get from url emails = [] for line in data: if not line.startswith('From'): continue line = line.split() if len(line) > 5: emails.append(line[1]) for email in emails: cur.execute('SELECT count FROM Counts WHERE email = ? ', (email,)) #Find the table named 'Counts" in SQL and selct 'count' cell that corresponds to certain email row = cur.fetchone() if row is None: cur.execute('''INSERT INTO COUNTS (email, count) VALUES (?, 1)''', (email,)) else: cur.execute('UPDATE Counts SET count = count + 1 WHERE email = ?', (email,)) conn.commit() # Upgrade the change in the server sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10' for row in cur.execute(sqlstr): print(str(row[0]),row[1]) cur.close()
total = 0 for num in range (1, 1000): if (num % 3 == 0) or (num % 5 == 0): total += num print(total)
import csv import sys def unique_csv(connections, column): connections_list = [] with open(connections, 'r', newline='') as connections_file: reader = csv.reader(connections_file, delimiter=',') for row in reader: if row[column] not in connections_list: connections_list.append(row[column]) return connections_list def filter_csv(connections, edges, output): connections_list = unique_csv(connections, 0) with open(edges, 'r', newline='') as edges_file, open(output, 'w', newline='') as output_file: reader = csv.DictReader(edges_file, delimiter=',') # ['Source', 'Target'] writer = csv.writer(output_file) writer.writerow(reader.fieldnames) for row in reader: if row['Source'] in connections_list and row['Target'] in connections_list: writer.writerow(row.values()) if __name__ == "__main__": if len(sys.argv) == 1: print(f'''Filters an edges csv to only users in the connections csv. Connections csv MUST have both a "Source" and "Target" column. Usage: {sys.argv[0]} <connections csv> <edges csv> <output csv>''') exit() filter_csv(sys.argv[1], sys.argv[2], sys.argv[3])
from random import randint """ SUDOKU (SOLUTION) BOARD GENERATION 1. Sudoku board is built row by row with recursion 2. For every cell, its row, square and col possible values are checked 3. If no solution can be found, the row is re-built via recursion 4. If the row is re-built too many times, break out of the recursion and re-build the row before. 5. Continue until every row is built. There is some RNG involved for every iteration as the row-generating algorithm is not aware what extra constraints are added when it inserts a randomly chosen value in. The extra constraints may make the sdku unsolvable from the get-go, hence the need to move back a row. """ __recursionCounter = 0 __timesCalled = 0 # Returns the row/col limits for the cell's square def getSquareLimits(rowIndex, colIndex): rowLimits, colLimits = [], [] if colIndex < 3: colLimits = [0,3] elif colIndex < 6: colLimits = [3,6] else: colLimits = [6,9] if rowIndex < 3: rowLimits = [0,rowIndex+1] elif rowIndex < 6: rowLimits = [3,rowIndex+1] else: rowLimits = [6,rowIndex+1] # rowIndex+1 is set as the endlimit, saving computation time for the unfilled '0' rows return (rowLimits, colLimits) # Main logic for sifting through usable data # Aim here is to minimise memory usage def getAvailValues(rowIndex, colIndex, grid): # For debugging and analysis purposes global __timesCalled __timesCalled +=1 # Mapping of number of values that appear vmap = [0 for x in range(10)] sqLim = getSquareLimits(rowIndex, colIndex) # Fn has disappointing time complexity (10+colIndex+rowIndex+9) # Logs occurences in row for i in range(colIndex+1): vmap[grid[rowIndex][i]] +=1 # Log occurences in col for i in range(rowIndex+1): vmap[grid[i][colIndex]] +=1 # Log occurences in the cell's square for ri in range(sqLim[0][0], sqLim[0][1]): for ci in range(sqLim[1][0], sqLim[1][1]): vmap[grid[ri][ci]] +=1 unused = [] for i in range(1,10): if vmap[i] == 0: unused.append(i) return unused # Generate the sudoku board row in accordance with sdku rules def generateRow(rowIndex, sudokuGrid): global __recursionCounter # Break recursion to backtrack and rebuild the previous row # Arbitrary number chosen if(__recursionCounter>9): return for i in range(9): pool = getAvailValues(rowIndex, i, sudokuGrid) # Recursion managed by the global counter field if len(pool)==0: # No solution. Re-build row __recursionCounter +=1 # print("Inner Backtrack") sudokuGrid[rowIndex] = [0 for x in range(9)] generateRow(rowIndex, sudokuGrid) return else: rdi = randint(0,8) if rdi >= len(pool): rdi = rdi%len(pool) sudokuGrid[rowIndex][i] = pool[rdi] # print("Row Built!") # Driver function to generate rows and manage recurion errors def generateSudoku(): global __timesCalled __timesCalled = 0 grid = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0] ] i = 0 while i<9: global __recursionCounter if __recursionCounter > 9: # print("Backtracked") __recursionCounter = 0 i-=1 generateRow(i,grid) else: generateRow(i,grid) i+=1 return grid def getCalls(): global __timesCalled return __timesCalled # Debug def sudoku_debug(): sudo = generateSudoku() for row in sudo: print(row) print(__timesCalled)
from matplotlib import * from Funcoes import * import time def newton(ai, nit): # Trata divisão por 0 if fd(ai) == 0: return p = ai - (f(ai) / fd(ai)) # Teste de parada if (mod(p - ai) < dx) or (mod(p - ai) / mod(p) < dx) or (mod(f(p)) < dx): print("Raiz:", p) print("Iteracoes:", nit) return # Se não para, chama a recursão else: newton(p, nit + 1) newton(1.5, 0)
import math num = int(input("How many species in this gas mixture? ")) x = [0] * num M = [0] * num mu = [0] * num for i in range(0, num): x[i] = float(input("Enter the Molar Fraction: ")) M[i] = float(input("Enter the Molecular Weight: ")) mu[i] = float(input("Enter the mu value: ")) def calculate(x, M, mu): w, h = num, num phi = [[0 for x in range(w)] for y in range(h)] xphi = [[0 for x in range(w)] for y in range(h)] denominator = [0] * num numerator = [0] * num viscosity = [0] * num for i in range(0, num): for c in range(0, num): phi[i][c] = get_phi(mu[i], mu[c], M[i], M[c]) for a in range(0, num): for b in range(0, num): xphi[a][b] = x[b] * phi[a][b] for i in range(0, num): denominator[i] = sum(xphi[i]) for i in range(0, num): numerator[i] = x[i] * mu[i] for i in range(0, num): viscosity[i] = numerator[i] / denominator[i] print("\n") print("Viscosity [g/cm s]: " + str(round(sum(viscosity), 13))) def get_phi(mui, muj, mi, mj): if mui == muj: return 1 phi = ( (1 / math.sqrt(8)) * ((1 + (mi / mj)) ** (-0.5)) * (1 + ((mui / muj) ** 0.5) * ((mj / mi) ** 0.25)) ** 2 ) return phi calculate(x, M, mu) """ x = [0.5226, 0.3048, 0.0659, 0.0900] M = [2.01588, 28.01, 28.0134, 36.46] mu = [0.027469092, 0.060326492, 0.059615963, 434.55] 0.0001464707550, 0.0002028770331, 0.0001746432201 """
import sys, time MOVE_COSTS = [1, 1, 10, 10, 100, 100, 1000, 1000] AMPHIPOD_INDEX_TO_TYPE = [ "A", "A", "B", "B", "C", "C", "D", "D", ] def solve(): board = [list(l) for l in open("day-23-part-one-input.txt").read().splitlines()[1:-1]] amphipods = get_amphipods_from_board(board) cost = find_solution(amphipods, sys.maxsize) print("Part one = " + str(cost)) def get_amphipods_from_board(board): amphipods = [(-1, -1) for _ in range(0, 8)] ai = 0 bi = 2 ci = 4 di = 6 for y, line in enumerate(board): for x, c in enumerate(line): if c == "A": amphipods[ai] = (x, y) ai += 1 if c == "B": amphipods[bi] = (x, y) bi += 1 if c == "C": amphipods[ci] = (x, y) ci += 1 if c == "D": amphipods[di] = (x, y) di += 1 assert (ai == 2) assert (bi == 4) assert (ci == 6) assert (di == 8) return amphipods def find_solution(amphipods, current_best): possible_boards_data = generate_all_new_possible_boards(amphipods, 0) start = time.perf_counter() previous_states = {} i = 0 while len(possible_boards_data) > 0: possible_board, cost = possible_boards_data.pop() hash = get_board_hash(possible_board) if hash in previous_states: previous_cost = previous_states[hash] if cost >= previous_cost: continue previous_states[hash] = cost if cost >= current_best: continue if board_completed_state(possible_board): current_best = cost continue a = generate_all_new_possible_boards(possible_board, cost) possible_boards_data.extend(a) if i % 10_000 == 0 and i > 0: elapsed = time.perf_counter() - start iter_sec = elapsed / (i / 10_000) print("{:.2f}".format(iter_sec) + "s per 10k iterations. " + str(len(previous_states)) + " previous states. Best = " + str(current_best)) i += 1 return current_best def get_board_hash(amphipods): r = 0 for i in range(0, 8): r += amphipods[i][0] << (i * 4) return r def generate_all_new_possible_boards(amphipods, cost): possible_boards_data = [] for i in range(0, len(amphipods)): new_possible_boards = generate_possible_boards(amphipods, i, cost) possible_boards_data.extend(new_possible_boards) return possible_boards_data def board_completed_state(amphipods): for i, a in enumerate(amphipods): if a[0] != 2 + (int(i / 2) * 2): return False return True def generate_possible_boards(amphipods, amphipod_index, cost): output = [] valid_tiles = get_valid_tiles(amphipods, amphipod_index) for tile_pos in valid_tiles.keys(): new_cost = cost + valid_tiles[tile_pos] new_amphipods = amphipods.copy() new_amphipods[amphipod_index] = tile_pos output.append((new_amphipods, new_cost)) return output def get_valid_tiles(amphipods, amphipod_index): valid_tiles = {} open_set = {} closed_set = set() open_set[amphipods[amphipod_index]] = 0 move_cost = MOVE_COSTS[amphipod_index] current_pos = amphipods[amphipod_index] amphipod_type = AMPHIPOD_INDEX_TO_TYPE[amphipod_index] while len(open_set) > 0: test_pos = next(iter(open_set)) new_cost = open_set[test_pos] + move_cost open_set.pop(test_pos) if test_pos[1] == 0: if test_pos[0] > 0: new_pos = (test_pos[0] - 1, test_pos[1]) try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles) if test_pos[0] < 10: new_pos = (test_pos[0] + 1, test_pos[1]) try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles) if test_pos[0] == 2 or test_pos[0] == 4 or test_pos[0] == 6 or test_pos[0] == 8: new_pos = (test_pos[0], test_pos[1] + 1) try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles) elif test_pos[1] == 1: new_pos = (test_pos[0], test_pos[1] + 1) try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles) new_pos = (test_pos[0], test_pos[1] - 1) try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles) else: new_pos = (test_pos[0], test_pos[1] - 1) try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles) return valid_tiles def try_add_neighbour(amphipods, amphipod_type, current_pos, new_pos, new_cost, open_set, closed_set, valid_tiles): if new_pos not in open_set and \ new_pos not in closed_set and \ is_empty_tile(amphipods, new_pos): open_set[new_pos] = new_cost closed_set.add(new_pos) # prevent moving out of locked in correct place in a room if amphipod_type == "A" and current_pos[0] == 2: if current_pos[1] == 2: return if amphipod_type == get_amphipod_type_from_position(amphipods, (current_pos[0], 2)): return if amphipod_type == "B" and current_pos[0] == 4: if current_pos[1] == 2: return if amphipod_type == get_amphipod_type_from_position(amphipods, (current_pos[0], 2)): return if amphipod_type == "C" and current_pos[0] == 6: if current_pos[1] == 2: return if amphipod_type == get_amphipod_type_from_position(amphipods, (current_pos[0], 2)): return if amphipod_type == "D" and current_pos[0] == 8: if current_pos[1] == 2: return if amphipod_type == get_amphipod_type_from_position(amphipods, (current_pos[0], 2)): return if new_pos[1] == 0: # block positions directly outside of side rooms if new_pos[0] == 2 or new_pos[0] == 4 or new_pos[0] == 6 or new_pos[0] == 8: return # prevent moving from hallway to hallway if current_pos[1] == 0 and new_pos[1] == 0: return else: # prevent moving from room to incorrect room if amphipod_type == "A" and new_pos[0] != 2: return if amphipod_type == "B" and new_pos[0] != 4: return if amphipod_type == "C" and new_pos[0] != 6: return if amphipod_type == "D" and new_pos[0] != 8: return # prevent moving into room with other type of amphipod inside if new_pos[1] == 1 and \ get_amphipod_type_from_position(amphipods, (new_pos[0], new_pos[1] + 1)) != amphipod_type: return valid_tiles[new_pos] = new_cost def is_empty_tile(amphipods, pos): for a in amphipods: if a == pos: return False return True def get_amphipod_type_from_position(amphipods, pos): for i, a in enumerate(amphipods): if a == pos: return AMPHIPOD_INDEX_TO_TYPE[i] return None def get_amphipod_index_from_position(amphipods, pos): for i, a in enumerate(amphipods): if a == pos: return i return None solve()
def solve(): print("Part one fuel = " + str(sum(partOne()))) print("Part two fuel = " + str(partTwo())) def partOne(): lines = open("day-1-input.txt").readlines() fuel_masses = [] for line in lines: fuel_masses.append(fuelEqn(int(line))) return fuel_masses def partTwo(): fuel_masses = partOne() adjusted_fuel = 0 for fuel in fuel_masses: while fuel > 0: adjusted_fuel += fuel fuel = fuelEqn(fuel) return adjusted_fuel def fuelEqn(fuel): return (int((int(fuel) / 3)) - 2) solve()
class Str(): def __init__(self,name,expected_type): self.name = name self.expected_type = expected_type # 限制name传入类型 def __get__(self, instance, owner): '''获取''' print("get-->",instance, owner) # 防止类访问name属性 if instance is None: return self return instance.__dict__[self.name] def __set__(self, instance, value): '''控制/设置传入的值''' print("set-->",instance,value) if not isinstance(value,self.expected_type): # if传入的类型不是限制的类型则会报错 raise TypeError("兄弟, 你是来捣乱的吧!") instance.__dict__[self.name] = value def __delete__(self, instance): print("del-->", instance) instance.__dict__.pop(self.name) class Int(): def __get__(self, instance, owner): print("int 调用...") def __set__(self, instance, value): print("int 配置...") def __delete__(self, instance): print("int 删除...") class People(): name = Str('name',str) # name被Str代理 # age = Int() # age被Int代理 def __init__(self,name,age,salary): self.name = name self.age = age self.salary = salary if __name__ == '__main__': # p1 = People('alex',18,100) # p1.name # # 赋值 # print(p1.__dict__) # p1.name = 'egonlin' # print(p1.__dict__) # # # 删除name # del p1.name # print(p1.__dict__) # 用类操作属性name # People.name # 报错, 类去操作属性时, 会将None传给instance # print(People.name)# 来自<__main__.Str object at 0x00000000021184E0> # p1 = People(666,18,100) # 报错 p1 = People('alex',18,100) # p1.__dict__['name'] print(p1.__dict__['name'])
Question:1 What is python?? Ans: Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development (server-side), software development, mathematics, system scripting. What can Python do? Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. Why Python? Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. Python can be treated in a procedural way, an object-orientated way or a functional way. Good to know The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular. In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files. Python Syntax compared to other programming languages Python was designed for readability, and has some similarities to the English language with influence from mathematics. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. How to install the python in your pc: 1.Click Python Download. 2.Click the Windows link (two lines below the Download Python 3.7.4 button). The following page will appear in your browser 3.Click on the Download Windows x86-64 executable installer link under the top-left Stable Releases. The following pop-up window titled Opening python-3.74-amd64.exe will appear. Click the Save File button. The file named python-3.7.4-amd64.exe should start downloading into your standard download folder. This file is about 30 Mb so it might take a while to download fully if you are on a slow internet connection (it took me about 10 seconds over a cable modem). The file should appear as 4.Move this file to a more permanent location, so that you can install Python (and reinstall it easily later, if necessary). 5.Feel free to explore this webpage further; if you want to just continue the installation, you can terminate the tab browsing this webpage. 6.Installing Double-click the icon labeling the file python-3.7.4-amd64.exe. A Python 3.7.4 (64-bit) Setup pop-up window will appear. Ensure that the Install launcher for all users (recommended) and the Add Python 3.7 to PATH checkboxes at the bottom are checked. If the Python Installer finds an earlier version of Python installed on your computer, the Install Now message may instead appear as Upgrade Now (and the checkboxes will not appear). Highlight the Install Now (or Upgrade Now) message, and then click it. When run, a User Account Control pop-up window may appear on your screen. I could not capture its image, but it asks, Do you want to allow this app to make changes to your device. Click the Yes button. A new Python 3.7.4 (64-bit) Setup pop-up window will appear with a Setup Progress message and a progress bar. During installation, it will show the various components it is installing and move the progress bar towards completion. Soon, a new Python 3.7.4 (64-bit) Setup pop-up window will appear with a Setup was successfuly message. Click the Close button. Python should now be installed. Verifying To try to verify installation, Navigate to the directory C:\Users\Pattis\AppData\Local\Programs\Python\Python37 (or to whatever directory Python was installed: see the pop-up window for Installing step 3). Double-click the icon/file python.exe. The following pop-up window will appear. A pop-up window with the title C:\Users\Pattis\AppData\Local\Programs\Python\Python37\python.exe appears, and inside the window; on the first line is the text Python 3.7.4 ... (notice that it should also say 64 bit). Inside the window, at the bottom left, is the prompt >>>: type exit() to this prompt and press enter to terminate Python. You should keep the file python-3.7.4.exe somewhere on your computer in case you need to reinstall Python (not likely necessary). You may now follow the instructions to download and install Java (you should have already installed Java, but if you haven't, it is OK to do so now, so long as you install both Python and Java before you install Eclipse), and then follows the instruction to download and install the Eclipse IDE. Note: you need to download/install Java even if you are using Eclipse only for Python) Start the Installing instructions directly below. Question:2 What is code Environment? and thier types. Ans: Python… the most popular and favorite programming language in the world for programmers of all age groups. If you are a beginner this language is strongly recommended to learn first. Well, In programming, we all know the importance of code editor and IDEs to write our program and to execute it but choosing the best code editor or IDE is always a confusing question. Understand that the best code editor or IDE depends on so many things such as programming language, project type, project size, OS support and considering a lot of other features. If we talk about Python so this language is also not an exception. We are going to discuss the code editor or IDEs for Python to use in 2020. This information is going to be based on the opinion given by experienced developers, public web data, some previous surveys like Python Developers Survey 2018 Results / Editors and IDEs and the most important person Guido van Rossum (Python Creator). Firstly understand that IDE and code editor both are different things. Text/Code Editor: Code editors are the lightweight tool that allows you to write and edit the code with some features such as syntax highlighting and code formatting. It provided fewer features than IDE. Integrated Development Environment (IDE): IDEs are full-fledged environment which provide all the essential tools needed for software development. It just doesn’t handle the code (for example, write, edit, syntax highlighting and auto-completion) but also provides other features such as debugging, execution, testing, and code formatting that helps programmers. Let’s start with some overview of the best code editor based on certain terms… What is Your Level? Beginner — IDLE (or Online Python Editors) is perfect choice for the first steps in python language. PyCharm is also good but takes the help of some experienced person while using this. Intermediate — PyCharm, Sublime, Atom, Vs Code. Advanced — PyCharm, Vim, Emacs, Sublime, Atom, Vs Code. What’s Your End Goal? Web development — PyCharm Professional, VS Code Data Science — Spyder, Jupyter Notebook, PyCharm Professional Scripting — Sublime, Atom, PyCharm Community, Eclipse + PyDev QA — Sublime, Atom, PyCharm Community, Jupyter Notebook What is Your Environment/OS? Linux, macOS — PyCharm, Sublime, Atom, Vim, Jupyter Windows — Sublime, VS Code, Eclipse + PyDev, PyCharm Multiple/mixed OS — PyCharm, Sublime, Atom Which Hardware Do You Have? Bad — IDLE, Atom, Sublime, Online Editor Good — PyCharm, VS Code, Eclipse + PyDev Note: We have considered limited terms but it also depends on budget, git integration, teamwork, previous programming knowledge. List of Best Python IDE 1. PyCharm In industries most of the professional developers use PyCharm and it has been considered the best IDE for python developers. It was developed by the Czech company JetBrains and it’s a cross-platform IDE. It gives daily tips to improve your knowledge of how you can use it more efficiently which is a very good feature. It comes in two versions community version and a professional version where community version is free but the professional version is paid. Below are some other features of this IDE. It is considered as an intelligent code editor, fast and safe refactoring, and smart code. Features for debugging, profiling, remote development, testing the code, auto code completion, quick fixing, error detection and tools of the database. Support for Popular web technologies, web frameworks, scientific libraries and version control. 2. Spyder Spyder is another good open-source and cross-platform IDE written in Python. It is also called Scientific Python Development IDE and it is the most lightweight IDE for Python. It is mainly used by data scientists who can integrate with Matplotlib, SciPy, NumPy, Pandas, Cython, IPython, SymPy, and other open-source software. It comes with the Anaconda package manager distribution and it has some good advanced features such as edit, debug, and data exploration. Below are some other features of this IDE. Auto code completion and syntax highlighting. Ability to search and edit the variables from the graphical user interface itself. Static code analysis It is very efficient in tracing each step of the script execution by a powerful debugger. 3. Eclipse PyDev Eclipse is one of the most popular IDE among developers which is written in Java but you can install Pydev plugin in eclipse and use it for Python as well. The primary focus of this IDE is the analysis of code, debugging in the graphical pattern, refactoring of python code, etc. Eclipse PyDev is stable and provides good performance for most of the python project life cycle. Below are some other features of this IDE. Pydev supports Django integration, Unittest integration, PyLint integration Code folding and code completion with auto import Good syntax high lighting and remote debugger Interactive console Allows you to create a Google App Engine (GAE) Python project 4. IDLE IDLE is a cross-platform open-source IDE that comes by default with Python so you don’t need to worry about the installation or setup. IDLE is written in Python and this IDE is suitable for beginner level developers who want to practice on python development. IDLE is lightweight and simple to use so you can build simple projects such as web browser game automation, basic web scraping applications, and office automation. This IDE is not good for larger projects so move to some advance IDEs after learning the basics from IDLE. Python shell with syntax highlighting Call stack’s clear visibility Multi-window code editor that allows features like smart indentation, autocomplete, etc It has an interactive interpreter with colorizing of input, output, and error messages. Program animation or stepping. 5. Wing Wing IDE is created by Wingware and it is faster, stable and extremely lightweight cross-platform Python IDE. It comes in three editions: Wing Pro (Free Trial): A full-featured commercial version, for professional programmers. Wing Personal (Paid): Free version that omits some features, for students and hobbyists. Wing 101 (Paid): A very simplified free version, for beginners in programming. This IDE comes with a strong debugger and smart editor that makes the interactive Python development speed, accurate and fun to perform. Some of its main features are given below… Automatic multi-process, child process, remote debug process and refactoring, etc. Test-driven development with various frameworks like the unittest, pytest, nose, doctest, and Django testing. It also has auto code completion in which the error is displayed in a feasible manner and line editing is also possible. Remote development support. List of Best Python Code Editor 1. Emacs Emacs was created in 1976 by Richard Stallman. It is free and fully customizable software available on all platforms. Emacs uses a form of the powerful Lisp programming language for customization, and various customization scripts exist for Python development. Syntax highlighting to differentiate document elements such as keywords and comments. Automatic indentation such as spaces, newlines, and brackets for consistent formatting in a file. 24-bit color encoded support for the terminals supporting it. Guido van Rossum (Python creator) accepted Emacs his favourite text editor in one of his tweet in 2016 Emacs of course!. We also took his recent opinion about his favorite text editor and Emacs is still his favorite one. Reply-to-Anu-Upadhyay-By-Guido-van-Rossum In the book “The Art of UNIX Programming” Emacs is undoubtedly the most powerful programmer’s editor in existence. It’s a big, feature-laden program with a great deal of flexibility and customizability. 2. Visual Studio Code Visual Studio Code (VS Code) is a free and open-source code editor created by Microsoft that can be used for Python development. You can add the extension to create a Python development environment. It provides support for debugging, embedded Git control, syntax highlighting, IntelliSense code completion, snippets, and code refactoring. Some of it’s best features are given below. Thousands of plugins/extensions available through the VS Code Marketplace. Powerful debugger by which the user can debug code from the editor itself. Easily customizable. Multi-platform, multi-language support, multi-split window feature and vertical orientation. 3. Sublime Text: Written by a Google engineer sublime text is a cross-platform IDE developed in C++ and Python. It has basic built-in support for Python. Sublime text is fast and you can customize this editor as per your need to create a full-fledged Python development environment. You can install packages such as debugging, auto-completion, code linting, etc. There are also various packages for scientific development, Django, Flask and so on. Some of its best features are given below… Goto anything for opening files with few clicks and can navigate to words or symbols. Python-based plugin API. Syntax highlighting and allows simultaneous editing (multiple selections) Command Palette implementation that accepts text input from users. High performance, block selection and simultaneous editing (multiple selections). 4. Atom Atom is an open-source cross-platform IDE built using web technologies. It is based on a framework built by GitHub named Electron. Atom is highly customizable and provides Python language support installing the extension when Atom is running. Some of the good packages for Python development are atom-python-run, Python Black, python-indent, atom-python-test, autocomplete-python, Python Tools, linter-flake8, python-debugger, etc. Below are some nice features of the Atom. Enables support for third-party packages Lightweight, smart auto-completion, multi-language support with good syntax highlighting Multiple panes and themes Allows installation and management of packages 5. Vim Vim is an open-source, cross-platform text editor. It is pre-installed in macOS and UNIX systems but for Windows, you need to download it. This text editor can be used as a command-line interface as well as a standalone application. Vim is extremely popular in geeks communities and by adding extensions or modifying its configuration file you can easily adapt it for development in Python. There are big lists of plugins, features, and versions of Vim. Some of its good features are listed below… Very stable and lightweight. Plugins are available for syntax highlighting, code completion, debugging, refactoring, etc It has a powerful integration, search and replace functionality. It is very persistent and also have a multilevel undo tree. Honorable Mentions We have mentioned all the IDEs and text editor for Python development but there is one popular web application or tool which is mainly used for data science projects and i.e. Jupyter Notebook. Let’s see the introduction and some of its features… Jupyter Notebook: Jupyter Notebook is a web-based interactive development environment; It’s well known in the data science community for analyzing, sharing and presenting the information. It is easy to use, open-source software that allows you to create and share live code, visualizations, etc. Some of its good features are given below… Support for Numerical simulation, data cleaning machine learning data visualization, and statistical modeling. Markdown and HTML integration. Integrated data science libraries (matplotlib, NumPy, Pandas). It offers you to see and edit your code to create powerful presentations. You can also convert your complete work into PDF and HTML files, or you can just export it as a .py file. Starting and stoping servers, opening folders and files.
from math import floor def fuel_required(mass): return floor(mass/3) - 2 def get_input_string(): with open('day1input.txt') as f: return f.read() def part1(): input_list = [int(x) for x in get_input_string().splitlines()] total = 0 for m in input_list: total += fuel_required(m) return total def fuel_required_including_fuel(mass): total_fuel = 0 fuel = fuel_required(mass) while fuel >= 0: total_fuel += fuel fuel = fuel_required(fuel) return total_fuel def part2(): input_list = [int(x) for x in get_input_string().splitlines()] total = 0 for m in input_list: total += fuel_required_including_fuel(m) return total print(part1()) print(part2())
import csv from random import choice def gen_num_phrase(): dice = list(map(str, list(range(1, 7)))) num_phrase = [] for _ in range(5): num_phrase.append(choice(dice)) return ''.join(num_phrase) #importing diceware dictionary reader = csv.reader(open('11_diceware.csv')) #crearing dictionary d = dict() for r in reader: d[r[0]]=r[1] n = int(input('Enter number of words to be used in the passphrase: ')) #generatiing phrase phrase = [] for _ in range(n): phrase.append(d[gen_num_phrase()]) print('Your passphrase: ') print(' '.join(phrase))
from random import choice from collections import defaultdict as dd n = int(input('Enter number of sides of the dice:')) l = list(range(1, n+1)) s = int(input('Enter the number of simulations to be used:')) d = dd(int) for _ in range(s): c = choice(l) d[c]+=1 for k in d.keys(): d[k]=round(d[k]*100/s, 3) print('The results of the simulation are:') print('face probability') for k in range(1, n+1): print(f'{k} {d[k]}%')
#Program to print couln name #Print the total number of rows and columns in a sheet import pandas as PD file_path="D:\\Pythonpractice\\Book1.xlsx" a=PD.read_excel(file_path,sheet_name='Sheet1') print('Column names ',a.columns)
import os import pathlib def home_is_where_this_file_is(): """Changes the working directory to wherever this file is located.""" current_working_directory = pathlib.Path.cwd() file_home_directory = pathlib.PurePath(__file__).parent if current_working_directory == file_home_directory: return else: os.chdir (file_home_directory)
# LIBRARIES AND MODULES # # for access to the filesystem and for some useful functions on pathnames from pathlib import Path # and for an additional useful function for changing directories from os import chdir ## Print the current working directory and home directory on screen so I can confirm them visually. print(f"Current directory: {Path.cwd()}") print(f"Home directory: {Path.home()}") chdir('..') print(f"New current directory: {Path.cwd()}") # make a shortcut variable for the current working directory path path = Path.cwd() # declare some more variables and set them to the expected paths of the UI, Logic, and Data folders. # We'll use these variables as quick ways to interact with files and folders outside our current working directory. uiDirectory = path / 'UI' logicDirectory = path / 'Logic' dataDirectory = path / 'Data' # Print the directory paths on screen so I can confirm them visually. print(uiDirectory) print(logicDirectory) print(dataDirectory) ################# # x = 1 # y = 2 # if x == y: # print("Got it.") # elif x != y: # print("Error. I can't find the Data folder.") # else: # print("An impossible error occured.") # TUTORIALS # I got this from here: https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f # also: http://zetcode.com/python/pathlib/
""" 给定一个已按照 非递减顺序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。 函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。 你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。   示例 1: 输入:numbers = [2,7,11,15], target = 9 输出:[1,2] 解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 示例 2: 输入:numbers = [2,3,4], target = 6 输出:[1,3] 示例 3: 输入:numbers = [-1,0], target = -1 输出:[1,2]   提示: 2 <= numbers.length <= 3 * 104 -1000 <= numbers[i] <= 1000 numbers 按 非递减顺序 排列 -1000 <= target <= 1000 仅存在一个有效答案 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。""" """ class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: index = [] for i in range(0,len(numbers)-1,1): for j in range(i+1,len(numbers),1): if numbers[i] == target - numbers[j]: index.append(i+1) index.append(j+1) return index """ class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: for i in range(len(numbers)): low,high = i+1,len(numbers)-1 while low <= high: mid = (low + high) // 2 if numbers[mid] == target - numbers[i]: return[i+1,mid+1] elif numbers[mid] < target - numbers[i]: low = mid + 1 else: high = mid -1 return [-1,-1]
''' A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. The student decides on an encryption scheme that involves two large strings. The encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Determine this number. Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings. Example a = 'cde' b='dcf, Delete from and from so that the remaining strings are and which are anagrams. This takes character deletions. ''' import math import os import random import re import sys from collections import Counter #Complete the makeAnagram function below. def makeAnagram(a, b): count = 0 for item in a: if item not in b: count +=1 for item in b: if item not in a: count +=1 if count == (len(a) + len(b)): return "Anagram cannot be made" else: return count dict1=(Counter("crxzwscanmligyxyvym")) dict2=(Counter("jxwtrhvujlmrpdoqbisbwhmgpmeoke")) print(dict1.values()) print(dict2.values()) print(("jxwtrhvujlmrpdoqbisbwhmgpmeoke","crxzwscanmligyxyvym")) dict1.subtract(dict2) print(sum(abs(i) for i in dict1.values())) if __name__ == '__main__': pass #fptr = open(os.environ['OUTPUT_PATH'], 'w') #a = input() #b = input() #res = makeAnagram(a, b) #print(res) #fptr.write(str(res) + '\n') #fptr.close()
""" Given two strings, write a method to decide if one is a permutation of the other. """ # str_1= "google" # str_2 = "ooggle" str_1= "bad" str_2 = "dab" from itertools import permutations permword = [] def allPermutations(str, str_2): # Get all permutations of string 'ABC' permList = permutations(str) for perm in list(permList): permstr = (''.join(perm)) permword.append(permstr) if str_2 in permword: return "Is a permutation" else: return "Is not a permutation" if __name__ == "__main__": str = 'ABC' ans = allPermutations(str_1, str_2) print(ans)
input_str = "LucidProgramming" def countlen(word): if word == "": return 0 else: return 1+ countlen(word[1:]) print(countlen(input_str))
def find_next_empty(puzzle): #finds empty cell in puzzle #return tuple row, col for r in range(9): for c in range(9): if puzzle[r][c] == -1: return r, c return None, None # if all cells are filled def is_valid(puzzle, guess, row, col): #checks if input is valid then returns true otherwise it returns false row_vals = puzzle[row] if guess in row_vals: return False col_vals = [] col_vals = [puzzle[i][col] for i in range(9)] if guess in col_vals: return False #Find which 3x3 box to run through row_start = (row // 3) * 3 col_start = (col // 3) * 3 for r in range(row_start, row_start + 3): for c in range(col_start, col_start + 3): if puzzle[r][c] == guess: return False return True def solve_sudoku(puzzle): #solve sudoku using backtracking #step1: Choose a cell in the puzzle to make a guess row, col = find_next_empty(puzzle) #step1.1: validation check if all cells are filled if row is None: return True #step2: if a cell is empty input a value in range 1-9 for guess in range(1,10): #step2.1: check if guess is valid if is_valid(puzzle, guess, row, col): #place guess at the cell puzzle[row][col] = guess #step4: recursive call function if solve_sudoku(puzzle): return True #step5: if puzzle is not solved or guess doesnt solve puzzle then backtrack and try new number puzzle[row][col] = -1 #step6: if none of the above work then puzzle is unsolvable return False if __name__ == '__main__': example_board = [ [8, 9, -1, -1, 5, -1, -1, -1, -1], [-1, -1, -1, 2, -1, -1, -1, -1, 5], [-1, -1, -1, 7, 1, 9, -1, 8, -1], [-1, 5, -1, -1, 6, 8, -1, -1, -1], [2, -1, 6, -1, -1, 3, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, 4], [5, -1, -1, -1, -1, -1, -1, -1, -1], [6, 7, -1, 1, -1, 5, -1, 4, -1], [1, -1, 9, -1, -1, -1, 2, -1, -1] ] print(solve_sudoku(example_board)) print(example_board)
#迭代器切片 def count(n): while True: yield n n+=1 c=count(0) #c无法通过下标切片,通过itertools在迭代器或者生成器上做切片 import itertools for x in itertools.islice(c,10,20): print(x) #消耗性!
#大型数组运算 import numpy as np ax=np.array([1,2,3,4]) ay=np.array([5,6,7,8]) print(ax*2) print(ax+10) print(ax+ay) print(ax*ay) #该模块还提供通用函数 print(np.sqrt(ax)) print(np.cos(ax)) #构造超大数组 grid=np.zeros(shape=(10000,10000),dtype=int) print(grid) #同样所有操作都会作用到每个元素 print(grid+10) #numpy扩展了列表的索引功能 a=np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(a) #选择某行 print(a[1]) #选择某列 print(a[:,2]) #选择子矩阵 print(a[1:3, 1:3]) #按行加 print(a+[100,101,102,103]) #条件操作 print(np.where(a<10,a,10))
#跳过可迭代对象的开始部分 with open('somefile.txt') as f: lines =(line for line in f if not line.startswith('#')) for line in lines: print(line,end='') #知道获取的元素的形式 from itertools import dropwhile with open('somefile.txt') as f: for line in dropwhile(lambda line:line.startswith('#'),f): print(line,end='') #明确知道所要获取的元素的索引 from itertools import islice items = ['a','b','c',1,3,4,5] for x in islice(items,3,None): print(x)
#序列上索引值迭代 #迭代一个序列的同时跟踪一个正在被处理的元素索引 my_list=['a','b','c'] for idx,val in enumerate(my_list): print(idx,val) #传递开始参数 for idx,val in enumerate(my_list,1): print(idx,val) from collections import defaultdict word_summary=defaultdict(list) with open('somefile.txt') as f: lines=f.readline() print(lines) for idx,line in enumerate(lines): words=[w.strip().lower() for w in line.split()] for word in words: word_summary[word].append(idx) print(word_summary)
#字节字符串的字符串操作 import re #支持正则表达式,正则表达式本身必须是字节串 data=b'a a' #print(re.split('\s',data))报错 print(re.split(b'\s',data)) #注意 #1、字节字符串的索引操作返回的是整数而非字符 #2、字节字符串的输出需要先解码为文本字符串,否则无法支持格式化操作 print(data.decode('ascii'))
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 def conectar(): con = sqlite3.connect('usuarios.db') con.row_factory = sqlite3.Row return con def existe(nombre): con = conectar() c = con.cursor() query = "SELECT * FROM usuarios WHERE user='" + nombre + "'" resultado = c.execute(query) usuarios = resultado.fetchall() con.close() #print usuarios return usuarios def crear(nombre, contrasenia): con = conectar() c = con.cursor() query = "INSERT INTO Usuarios(user, pass) VALUES ('"+ nombre +"', '" + contrasenia + "')" c.execute(query) con.commit() con.close() print "agregado"
import csv from schoolByCondition import * def subjectDict(): from collections import defaultdict data = defaultdict(list) with open('Data/subjects-offered.csv', 'rb') as data_file: reader = csv.DictReader(data_file) for row in reader: data[row['School_Name']].append(row['Subject_Desc']) return data class SubjectsOffered: def getDict(self): return self.__dict def filterMultiSubs(self, filtered, result=None): """ Filter the dictionary recursively for multiple subjects :param filtered: Subjects to filter by :param result: The schools that matches the critrea of all the filters :return: a dictionary of schools mapped to their subject """ if result is None: result = self.__dict if len(filtered) == 0: return result else: result2 = {} for i in result: for x in result[i]: if filtered[0].upper() == x[self.__headers[1]].upper() and i not in result2: result2.update({i: result.get(i)}) return self.filterMultiSubs(filtered[1:], result2) def getUniqueSubjectList(self): """ Returns a list of unique subjects, generates it the first time the function is called. :return: A list of unique subjects """ if self.__subList is not []: return self.genUniqueSubjectList() else: return self.__subList def genUniqueSubjectList(self): """ Generates a list of unique subjects :return: a list of unique subjects """ for rows in self.__dict.values(): for cols in rows: if not cols.get(self.__headers[1]) in self.__subList: self.__subList.append(cols.get(self.__headers[1])) return self.__subList def getSubjectsBySchoolName(self, school_name): subjects = [] for i in self.__dict.keys(): if i.upper() == school_name.upper(): for x in self.__dict[i]: subjects.append(x[self.__headers[1]]) return subjects def getSchoolsBySubjectDesc(self, subject_name): _subj_name = subject_name.upper() school_arr = [] for i in self.__dict: for x in self.__dict[i]: if _subj_name in x[self.__headers[1]].upper(): school_arr.append(i) return school_arr def getSubjectsByLevel(self, level): # gets all schools under specified level x = schoolstuff(level, 'mainlevel_code') schools_arr = [] for y in range(len(x)): schools_arr.append(x[y][0]) # stores all subjects (non-duplicated) subjects_arr = [] for item in schools_arr: subjects_temp = self.getSubjectsBySchoolName(item) for i in subjects_temp: if i not in subjects_arr: subjects_arr.append(i) return subjects_arr # split into dict def createDict(self): x = genDict(self.__raw) self.__dict = x[1] self.__headers = x[0] def __init__(self): self.__subList = [] self.__raw = openCSV("Data/subjects-offered.csv") self.__dict = None self.__headers = None self.createDict()
#%% import csv from collections import Counter #%% def leer_arbol(nombre_archivo): types = [float, float, int, int, int, int, int, str, str, str, str, str, str, str, str, float, float] with open(nombre_archivo, 'rt', encoding="utf8") as f: filas = csv.reader(f) headers = next(filas) #Salta los datos de cabecera datos = [{name: func(val) for name, func, val in zip(headers, types, row)} for row in filas] return datos #%% def alturas(arboleda,tipo_arbol): alt = [(float(arbol["altura_tot"]),float(arbol["diametro"])) for arbol in arboleda if arbol["nombre_com"] == tipo_arbol] return alt # %% def medidas_de_especies(especies,arboleda): salida = {especie: alturas(arboleda,especie) for especie in especies} return salida # %%
# Agustin Avila # tinto.avila@gmail.com # 17/8/21 import csv # Funcion que devuelve los datos del camion como una lista de diccionarios def costo_camion(nombre_archivo): datos = [] with open(nombre_archivo, 'rt') as f: rows = csv.reader(f) headers = next(rows) #Salta los datos de cabecera for row in rows: lote = {'nombre': row[0], 'cajones': int(row[1]), 'precio': float(row[2])} datos.append(lote) return datos # Funcion que devuelve los datos de los precios como un diccionario def leer_precios(nombre_archivo): datos = {} with open(nombre_archivo, 'rt') as f: rows = csv.reader(f) headers = next(rows) #Salta los datos de cabecera for row in rows: try: datos[row[0]] = row[1] except: pass # Podria levantar alguna alerta, en este caso no hace nada return datos # Nombres de archivos para abrir: nombre_archivo_camion = '../Data/camion.csv' nombre_archivo_precios = '../Data/precios.csv' # Variables que almacenan los datos cargados de cada archivo: camion = costo_camion(nombre_archivo_camion) precios = leer_precios(nombre_archivo_precios) costo_camion = 0 # Inicializa las variables en cero ganancia_venta = 0 for item in camion: costo_camion += item['cajones']*item['precio'] #Calcula el costo del item if item['nombre'] in precios: # Si la fruta está en el diccionario de precios, calcula la ganancia ganancia_venta += item['cajones']*float(precios[item['nombre']]) #Calcula la ganancia del item # Imprime por pantalla el resultado print("El costo del camion es de",costo_camion) print("El ingreso por la venta es de",ganancia_venta) saldo_neto = ganancia_venta - costo_camion print(f'El saldo final es de {saldo_neto:10.2f}') if saldo_neto<0: print("Hubo pérdida!") elif saldo_neto == 0: print("Ni se ganó ni se perdió") else: print("Hubo ganancia!")
main_list = [10, 12, 13, 43, 20, 15, 27, 18, 29, 42] # Simple squaring of all elements of main_list def list_comprehension_squared(list): # For rebasing practice # Check if list is not empty if list: # Quadruple all numbers temp_list = [x**4 for x in list] func = lambda x: x + 10 return map(func, temp_list) print(list(list_comprehension_squared(main_list))) # Return even numbers only def list_comprehension_even_numbers(list): # For rebasing practice # Check if list is not empty if list: # Floor divide by 3 and then add 15 to all numbers temp_list = [ (x//3) + 15 for x in list] add_10_func = lambda x: x + 10 return map(add_10_func, temp_list) return "List does not exists!" print(list(list_comprehension_even_numbers(main_list))) def yet_another_func(list): sorted_list = sorted(list) greater_than_25 = lambda x: x > 25 return filter(greater_than_25, sorted_list) print(list(yet_another_func(main_list)))
#!/usr/bin/env python3 # File encryption only (micro-arch). # This test implements file encryption encryption and decryption. # Files are encrypted with one round of encryption with the same algorithm as the secret message cipher. # Further work on this function would implement encryption rounds with key permutation. # Test 006 is the final script. import binascii import numpy as np import os.path from tkinter import * from tkinter.filedialog import askopenfilename # open file, read as hex, grab first 64-bits, split into 32-bit, convert to base 16, create matrix. def open_file_handler(): global file_type, filename, file_to_hex, f64_matrix root = Tk() root.withdraw() # File to be encrypted filename = askopenfilename() # filename = 'test.png' file_type = os.path.splitext(filename)[1] # Open file and read as binary with open(filename, 'rb') as f: content = f.read() file_to_hex = binascii.hexlify(content) # Convert entire file to hexadecimal # Show user file hex file conversion print("\n[START] Converted file to hexadecimal.") # Decode byte string # Get first 64 bits of file first_64_bits = file_to_hex[:16] # Grab first 16 characters (8 characters = 4 bytes) # Show user first 64-bits of file print("\n[STEP 1] Collected first 64-bits of file : ", first_64_bits.decode("utf-8")) # Split 64-bit segment into two 32-bit segments print("\n[STEP 2] Splitting 64-bits into two 32-bit segments...") split_64 = first_64_bits.decode("utf-8") splits = 8 two_bytes = [split_64[i:i + splits] for i in range(0, len(split_64), splits)] print("\n[STEP 3] Split complete : ", two_bytes) # Convert hex to base16 for simple arithmetic bytes_b16 = [int(x, 16) for x in two_bytes] print("\n[STEP 4] Converted hex to base 16 : ", bytes_b16) # Create matrix of two bytes (32-bit) f64_matrix = np.matrix(bytes_b16) print("\n[STEP 5] Inserted base 16 values into matrix: ", f64_matrix) # Generate key matrix def key_gen_f(): global k # Generate Key Matrix k = np.random.randint(2, 10, f64_matrix.shape, dtype=np.int) print("\n[STEP 6] Generated key matrix : ", k) print("\nReady to start encryption!") # Encryption function def run_file_encryption(): global encrypted, encrypted_file, encrypted_hex_a, encrypted_hex_b # encrypt print("\n[STEP 7] Encrypting base16 values with key...") encrypted = np.multiply(k, f64_matrix) print("\n[STEP 8] Encrypted base16 values: ", encrypted) base16_list = np.array(encrypted)[0].tolist() # Convert matrix to array then list for base16 conversion. # Convert base16 back to hex print("\n[STEP 9] Converting encrypted base16 values to hexadecimal...") encrypted_hex_a, encrypted_hex_b = [hex(x)[2:].zfill(9) for x in base16_list] print("\n[STEP 10] New, encrypted 32-bit hexadecimal value : ", encrypted_hex_a, encrypted_hex_b) removed = file_to_hex[16:] # remove first 16 (64-bits) characters appended = [encrypted_hex_a + encrypted_hex_b + removed.decode("utf-8")] appended_to_string = appended appended_string = ''.join(str(e) for e in appended_to_string) # Add encrypted bits to file print("\n[STEP 11] Added encrypted segments to file : ") print("\n[STEP 12] Saving encrypted file...") # Save file as encryptedFile + file type with open('encryptedFile' + file_type, 'wb') as encrypted_file: encrypted_file.write(binascii.a2b_hex(appended_string.strip())) encrypted_file.close() # Decryption function def run_file_decryption(): print("\nReady to start decryption!") # Decrypt print("\n[STEP 13] Decrypting file...") decrypt_segments = np.floor_divide(encrypted, k) print("[STEP 14] Decrypted initial 64-bits from hex", decrypt_segments) decrypted_base16_list = np.array(decrypt_segments)[0].tolist() # Convert to list. # Convert base16 back to hex decrypted_hex_a, decrypted_hex_b = [hex(x)[2:].zfill(8) for x in decrypted_base16_list] # split list into two variables print("\n[STEP 15] Converted encrypted base16 values to original hexadecimal : ", decrypted_hex_a, decrypted_hex_b) removed_encrypted = file_to_hex[16:] # Remove encrypted bits from file append_decrypted = [decrypted_hex_a + decrypted_hex_b + removed_encrypted.decode("utf-8")] decrypted_to_string = append_decrypted decrypted_string = ''.join(str(e) for e in decrypted_to_string) # Add decrypted bits back to file print("[STEP 16] Added decrypted segments back to file.") print("[FINISHED] Saving decrypted file...") # Pythonic byte conversion decrypted_data = decrypted_string decrypted_data = decrypted_data.upper() decrypted_data = decrypted_data.strip() decrypted_data = decrypted_data.replace(' ', '') decrypted_data = decrypted_data.replace('\n', '') decrypted_data = binascii.a2b_hex(decrypted_data) # Save file (thanks to the byte conversion ;)) with open('decryptedFile' + file_type, 'wb') as image_file: image_file.write(decrypted_data) if __name__ == '__main__': open_file_handler() key_gen_f() run_file_encryption() run_file_decryption()
#!/usr/bin/env python3 # File encryption only (micro-arch). # This test implements file encryption encryption and decryption. # Files are encrypted with one round of encryption with the same algorithm as the secret message cipher. # Further work on this function would implement encryption rounds with key permutation. # Test 006 is the final script. import binascii import numpy as np import os.path from tkinter import * from tkinter.filedialog import askopenfilename def run_file_algorithm(): global file_to_hex, encrypted, encrypted_file, encrypted_hex_a, encrypted_hex_b, k, filename, file_type root = Tk() root.withdraw() # File to be encrypted filename = askopenfilename() # filename = 'test.png' file_type = os.path.splitext(filename)[1] # Open file and read as binary with open(filename, 'rb') as f: content = f.read() file_to_hex = binascii.hexlify(content) # Convert entire file to hexadecimal # Show user file hex file conversion print("\nConverted file to hexadecimal.", file_to_hex.decode("utf-8")) # Decode byte string # Get first 64 bits of file first_64_bits = file_to_hex[:16] # Show user first 64-bits of file print("\nCollected first 64-bits of file : ", first_64_bits.decode("utf-8")) # Split 64-bit segment into two 32-bit segments print("\nSplitting 64-bits into two 32-bit segments...") split_64 = first_64_bits.decode("utf-8") splits = 8 two_bytes = [split_64[i:i + splits] for i in range(0, len(split_64), splits)] print("\nSplit complete : ", two_bytes) # Convert hex to base16 for simple arithmetic bytes_b16 = [int(x, 16) for x in two_bytes] print("\nConverted hex to base 16 : ", bytes_b16) # Create matrix of two bytes (32-bit) f64_matrix = np.matrix(bytes_b16) print("\nInserted base 16 values into matrix: ", f64_matrix) # Generate Key Matrix k = np.random.randint(2, 10, f64_matrix.shape, dtype=np.int) print("\nGenerated key matrix : ", k) # encrypt print("\nEncrypting base16 values with key...") encrypted = np.multiply(k, f64_matrix) print("\nEncrypted base16 values: ", encrypted) base16_list = np.array(encrypted)[0].tolist() # Convert matrix to array then list for base16 conversion. # Convert base16 back to hex print("\nConverting encrypted base16 values to hexadecimal...") encrypted_hex_a, encrypted_hex_b = [hex(x)[2:].zfill(9) for x in base16_list] print("\nNew, encrypted 32-bit hexadecimal value : ", encrypted_hex_a, encrypted_hex_b) removed = file_to_hex[16:] appended = [encrypted_hex_a + encrypted_hex_b + removed.decode("utf-8")] appended_to_string = appended appended_string = ''.join(str(e) for e in appended_to_string) print("\nAdded encrypted segments to file : ", appended_string) print("\nSaving encrypted file...") with open('encryptedFile' + file_type, 'wb') as encrypted_file: encrypted_file.write(binascii.a2b_hex(appended_string.strip())) encrypted_file.close() def run_file_decryption(): # Decrypt print("\nDecrypting file...") decrypt_segments = np.floor_divide(encrypted, k) print("Decrypted initial 64-bits from hex", decrypt_segments) decrypted_base16_list = np.array(decrypt_segments)[0].tolist() # Convert to list. # Convert base16 back to hex decrypted_hex_a, decrypted_hex_b = [hex(x)[2:].zfill(8) for x in decrypted_base16_list] print("\nConverted encrypted base16 values to original hexadecimal : ", decrypted_hex_a, decrypted_hex_b) removed_encrypted = file_to_hex[16:] append_decrypted = [decrypted_hex_a + decrypted_hex_b + removed_encrypted.decode("utf-8")] decrypted_to_string = append_decrypted decrypted_string = ''.join(str(e) for e in decrypted_to_string) print("Added decrypted segments back to file : ", decrypted_string) print("Saving decrypted file...") decrypted_data = decrypted_string decrypted_data = decrypted_data.upper() decrypted_data = decrypted_data.strip() decrypted_data = decrypted_data.replace(' ', '') decrypted_data = decrypted_data.replace('\n', '') decrypted_data = binascii.a2b_hex(decrypted_data) with open('decryptedFile' + file_type, 'wb') as image_file: image_file.write(decrypted_data) if __name__ == '__main__': run_file_algorithm() run_file_decryption()
# Let's create reptile class to inherit Animal class from animal import Animal # importing Animal class class Reptile(Animal): # inherting from Animal class def __init__(self): super().__init__() # super is used to iherit everything from the parent class self.cold_blooded = True self.tetrapods = None self.heart_chamber = [3, 4] def seek_heat(self): return "it's chilly looking have fun in the sun!" def hunt(self): return "keep working hard to find food " def use_venom(self): return "If I have it I will use it " # Let's create an object of Reptile class smart_reptile = Reptile() # print(smart_reptile.breathe()) # breathe method is inherited from Animal class # print(smart_reptile.hunt()) # hunt() is available in Reptile class # print(smart_reptile.eat()) # print(smart_reptile.move()) # print(smart_reptile.hunt())
def loGtest(): user_key = {'kelvin@gmail.com': 5, 'blue': 1, 'red': 2, 'yellow': 3} passKey = {5: 'rt'} pkey=0 # this gives the set of keys and values that can be displayed for the administrator to see about login details d = user_key.keys() f = user_key.values() print(d) print(f) # this is the end the set containing keys and values which might not be used tempUse=0 uSerName = input('enter username ') for x in user_key: # we can add append list to store them in order # #we have to create that order for now we just want the highest if x == uSerName: ukey = user_key[x] # temporary value 'ukey' to hold key , variable will be used later to find the password # and comparison made for a match and the function can proceed pkey = passKey[ukey] # there should be a variable being passed from out put if this loop if it found the name worked and if it did not find anything tempUse = uSerName # we can exit the loop now that we have located the password location and stored it some where to be used later if tempUse==uSerName : print ('Username is found ') paSsword = input('enter password') if pkey == paSsword: print('congrats you gained entrance to the system ') print('proceed to login') # next function can be loaded elif pkey != paSsword: print('wrong password you will be directed back to enter Username allover again') loGtest() elif tempUse !=uSerName : print('enter the right username or email ') loGtest() # NB THE new updated addition will stay in the namespace during the function # or software is being run but has to be written onto a permanent file storage which will # pick it up and load during the next time the file has to be run # these dictionaries being printed now might be saved onto a file and loaded next time b4 the function # so the function can load values and infer from there #
#!/usr/bin/python print "My name is %s and weight is %d kg ! " %('Zara' ,21) para_str= """ this is to show thaat there will be no reason to saccept the the only fine line betweeen this ad tht is lonly a matter of time and this will bew inherently shown by the standards and the will be nothing more to it aas well aso shown by the the real reason for all of thei s abut i dipnt e bkbfuwebwh butshy theat """ print para_str
print ("Enter a number ") try: caseinterMed=int(input("please enter the number over here ")) reDnum=45 + caseinterMed print(reDnum) except ValueError : print("re enter the right data type which is a number ")
import webbrowser #Permite a exibição de docs web aos usuários import tkinter #Interface padrão do python para o kit de ferramentas TK from time import sleep root = tkinter.Tk( ) #Nome do sistema == root root.title('Abrir browser') root.geometry('300x200') #Tamanho do sistema def opensite(): site = str(input('Digite o site a ser aberto: ')).strip().lower() #Abrindo o site antes de clicar no botão. webbrowser.open(site) #if site != '': mysite = tkinter.Button(root, text=f'acessar', command=opensite).pack(pady=20) root.mainloop()
from Util import Util class Node: def __init__(self, key, children, is_leaf=True, value=None): """ Basic element of the Trie :param key: The key of the node :param children: List of children nodes :param is_leaf: Is current node leaf or not, default=False :param value: Value of the node """ self.key = key self.children = children self.is_leaf = is_leaf self.value = value def __str__(self): result = self.key if self.children: result += " -> [" for child in self.children: if child.key: result += str(child) result += ", " result = result[:-2] + "]" return result def __repr__(self): result = self.key if self.children: result += " -> [" for child in self.children: if child.key: result += str(child) result += ", " result = result[:-2] + "]" return result def add(self, word, value): """ Add a Node with the given as the prefix key and the value in the, if the word already exists the value is unioned with the existing word's value :param word: The word to add in :param value: The value to add for the Node :return: True if added successfully else None """ prefix = Util.get_prefix(self.key, word) """ if current node matches the prefix we already have that word """ if prefix == word: if self.value: self.value = self.value.union(value) else: self.value = value return True """ If current node is leaf and we need to add another leaf node, split the current node """ if self.is_leaf: if prefix: self.children.append(Node(self.key[len(prefix):], list(), value=self.value)) self.children.append(Node(word[len(prefix):], list(), value=value)) self.key = prefix self.is_leaf = False return True """ Check if word can be traced with current internal nodes """ if self.children: for child in self.children: if not prefix and Util.has_prefix(child.key, word): return child.add(word, value) if Util.has_prefix(child.key, word[len(prefix):]): return child.add(word[len(prefix):], value) """ Add new external nodes """ if not prefix: self.children.append(Node(word, list(), value=value)) elif prefix != self.key: new_node = Node(word[len(prefix):], list(), value=value) new_child_node = Node(self.key[len(prefix):], self.children, is_leaf=False) self.children = list() self.children.append(new_child_node) self.children.append(new_node) self.key = prefix else: self.children.append(Node(word[len(prefix):], list(), value=value)) self.is_leaf = False return True def search(self, word): """ Recursively search a word in the from this Node :param word: The word to search :return: The node where the word matches after tracing from the root else None """ prefix = Util.get_prefix(self.key, word) if prefix == word: return self if self.is_leaf: return None if self.children: for child in self.children: if not prefix and Util.has_prefix(child.key, word): return child.search(word) if Util.has_prefix(child.key, word[len(prefix):]): return child.search(word[len(prefix):]) Trie = Node("#", list(), is_leaf=False) # Inverted Index file
import string import numpy as np import math import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer def get_keywords(text): text.rstrip() """ Remove stop words and punctuation """ stop_words = stopwords.words('english') + list(string.punctuation) text = ' '.join([ word for word in text.split() if word.lower() not in stop_words ]) tokens = nltk.word_tokenize(text) return tokens
# -*- coding: utf-8 -*- from __future__ import print_function from random import randint try: input = raw_input except NameError: pass """ Coś tu nie gra! Gracz zgaduje kilka razy, ale widzi zawsze komunikat "pierwsza próba"... Dodaj do funkcji <<zgadnij>> argument "proba" i wypisuj poprawny komunikat z numerem próby zamiast "pierwsza próba". """ # liczba, którą zna komputer tajemnicza_liczba = randint(1, 100) def zgadnij(): proba = int(input("Zgadnij liczbę (pierwsza próba): ")) if proba == tajemnicza_liczba: print("Zwycięstwo!") for proba in range(10): zgadnij()
num = [1, 2, 3, 4, 5] num = iter(num) print(num) x = list(num) # 迭代器转换成列表 print(x) # ######################### 迭代器 ############################## # # 迭代器可以通过 next 进行遍历 # print(next(num)) # 1 # print(next(num)) # 2 # print(next(num)) # 3 # print(next(num)) # 4 # print(next(num)) # 5 # # print(next(num)) # 源列表只有五个元素,当要输入第六个是会报错 # # for 循环亦可以对迭代器进行遍历,输出前需要先把上面注释掉才可以 # print("=" * 80) # for i in num: # print(i) # 此方法也可以 # while True: # try: # print(next(num)) # except StopIteration: # break # ######################### 生成器本身也是迭代器 ############################## # 接下来我们创建生成器对象: # ge = (x for x in range(1)) # 这将创建一个生成器对象,类似于列表解析,将外层用括号括起来,同样可以调用next()方法取值。 # 1. 通过 yield 创建生成器对象 # 我们通过斐波拉契数列来定义一个函数说明yield,如果函数包含yield,则这个函数是一个生成器, # 当生成器对象每次调用next()时,遇到yield关键字会中断执行,当下一次调用next(),会从中断出开始执行。 def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n += 1 data = fib(10) for i in data: print(i)
#%% -1- import numpy as np import cv2 img = cv2.imread(r"C:\Users\OSMANMERTTOSUN\Desktop\barcode.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #%% -2- # OpenCV provides three types of gradient filters or High-pass filters, Sobel, Scharr and Laplacian. # If ksize = -1, a 3x3 Scharr filter is used which gives better results than 3x3 Sobel filter. gradX = cv2.Sobel(gray, ddepth = cv2.cv2.CV_32F , dx = 1, dy = 0,ksize = -1) gradY = cv2.Sobel(gray,ddepth = cv2.cv2.CV_32F, dx = 0, dy = 1, ksize= -1) #%% -3- #Substracting and converting the image back to grayscale after applying Sobel gradient = cv2.subtract(gradY, gradX) gradient = cv2.convertScaleAbs(gradient) #%% -4- #Smoothing out high frequency noise and thresholding the image blurred = cv2.blur(gradient, ksize = (8,8)) (_, thresh) = cv2.threshold(blurred, 210, 255, cv2.THRESH_BINARY) #cv2.imshow("img", thresh) #%% -5- #closing the gaps between the vertical bars of barcode kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20)) closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) #cv2.imshow("img", closed) #%% -6- #Erosion and Dilation processes #"Dilation adds pixels to the boundaries of objects in an image and erosion removes pixels on object boundaries" closed = cv2.erode(closed, None, iterations = 1) closed = cv2.dilate(closed, None, iterations = 10) #cv2.imshow("img", closed) #%% -7- #Finding largest contour area (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) c = sorted(cnts, key = cv2.contourArea, reverse = True) c = c[0] rect = cv2.minAreaRect(c) box = np.int0(cv2.boxPoints(rect)) cv2.drawContours(image, [box], -1, (0, 255,255), 3) #%% -8- cv2.imshow("img", image) cv2.waitKey(0)
import random while True: a = input('ask me something') answers = ['yes', 'no', 'maybe', 'shut up', 'go away', 'im sleeping', 'ok'] print(random.choice(answers))
#Alex Chen,CSC201 #Lab03,Part5 #Objective:Computing the total number of matching DNA fragments DNA1 = input("Enter the first DNA sequence:") DNA2 = input("Enter the second DNA sequence:") def dna_Match(DNA1,DNA2): count = 0 if len(DNA1) > len(DNA2): small = DNA2 big = DNA1 else: small = DNA1 big = DNA2 for i in range(len(small)): if small[i] == big[i]: count += 1 return count print(dna_Match(DNA1,DNA2)) input("Press enter to continue:") #Lab03,Part6 #Objective:Computing the length of the longest matching DNA fragments DNA1 = input("Enter the first DNA sequence:") DNA2 = input("Enter the second DNA sequence:") def dna_Length(DNA1,DNA2): count = 0 maxMatch = 0 if len(DNA1) > len(DNA2): small = DNA2 big = DNA1 else: small = DNA1 big = DNA2 for i in range(len(small)): if small[i] == big[i]: count += 1 else: count = 0 if count > maxMatch: maxMatch = count return maxMatch print(dna_Length(DNA1,DNA2)) input("Press enter to continue:") #Lab03,Part7 #Objective:Complete DNA search def validate(dna_Frag): valid = True for i in dna_Frag: if i not in Valid_DNA: valid = False break return valid def dna_Match(dna_Frag,gene): count = 0 if len(dna_Frag) > len(gene): small = gene big = dna_Frag else: small = dna_Frag big = gene for i in range(len(small)): if small[i] == big[i]: count += 1 return count def compare(matchList): gList = "" greatest = matchList[0] if matchList[1] > greatest: greatest = matchList[1] elif matchList[2] > greatest: greatest = matchList[2] elif matchList[3] > greatest: greatest = matchList[3] for i in range(len(matchList)): if matchList[i] == greatest: gList += ("Gene" + str(i + 1) + " ") return gList def len_Compare(lengthList): lList = "" greatest = lengthList[0] if lengthList[1] > greatest: greatest = lengthList[1] elif lengthList[2] > greatest: greatest = lengthList[2] elif lengthList[3] > greatest: greatest = lengthList[3] for i in range(len(lengthList)): if lengthList[i] == greatest: lList += ("Gene" + str(i + 1) + " ") return lList def dna_Length(dna_Frag,gene): count = 0 maxMatch = 0 if len(dna_Frag) > len(gene): small = gene big = dna_Frag else: small = dna_Frag big = gene for i in range(len(small)): if small[i] == big[i]: count += 1 else: count = 0 if count > maxMatch: maxMatch = count return maxMatch ################################################################################ #Main: Valid_DNA = "AGCT" gene1 = "ATTAGGTAA" gene2 = "ACTGATCAG" gene3 = "ATTCGGCTC" gene4 = "TAGCCGTTA" dna_Frag = input("Enter the DNA sequence:") isValid = validate(dna_Frag) while isValid == False: print("Invalid entry") dna_Frag = input("Renter the DNA sequence:") isValid = validate(dna_Frag) gene1match = dna_Match(dna_Frag, gene1) gene2match = dna_Match(dna_Frag, gene2) gene3match = dna_Match(dna_Frag, gene3) gene4match = dna_Match(dna_Frag, gene4) matchList = [gene1match, gene2match, gene3match, gene4match] gList = compare(matchList) print("The best matches are:",gList) gene1length = dna_Length(dna_Frag, gene1) gene2length = dna_Length(dna_Frag, gene2) gene3length = dna_Length(dna_Frag, gene3) gene4length = dna_Length(dna_Frag, gene4) lengthList = [gene1length, gene2length, gene3length, gene4length] lList = len_Compare(lengthList) print("The longest consecutive matches are:",lList)
# import pandas as pd import csv from difflib import SequenceMatcher file_name = 'data/faq.csv' NO_RESULT = "Ничего не найдено по вашему вопросу, вы можете задать вопрос по " \ "ссылке https://pk.mipt.ru/faq/" def compare(question): global Answer, Answer2, Answer3, Answer4, Answer5, Score, Score2, Score3, Score4, Score5, rawdata maxim = 0 x = 0 Answer, Answer2, Answer3, Answer4, Answer5 = '', '', '', '', '' Score, Score2, Score3, Score4, Score5 = 0, 0, 0, 0, 0 with open(file_name, newline='') as csvfile: df = csv.reader(csvfile, delimiter=';') # print(df[3]) for row in df: # print(i) # print(df[x-1:x]) # if row[2]: # s = SequenceMatcher(lambda x: x == " ", question, row[2]) # else: k = 0 ratio_mean = 0 for i in range(1, 4): if row[i]: s = SequenceMatcher(lambda x: x == " ", question, row[i]) ratio_mean += s.ratio() k += 1 ratio = ratio_mean / k if ratio > maxim: Answer5, Score5 = Answer4, Score4 Answer4, Score4 = Answer3, Score3 Answer3, Score3 = Answer2, Score2 Answer2, Score2 = Answer, Score Answer = row[1:] Score = ratio maxim = ratio rawdata = row x += 1 result = [Answer, Score, Answer2, Score2, Answer3, Score3, Answer4, Score4, Answer5, Score5, rawdata] print(result) if Score >= 0.22: quest = list() for i in range(3): print("results:", result[i * 2], result[i * 2 + 1]) if result[i * 2 + 1] >= 0.21: quest.append( [result[i * 2][1] if result[i * 2][1] else result[i * 2][0], result[i * 2][2]]) return quest return NO_RESULT if __name__ == "__main__": print(compare("Какая стипендия")) # print(Answer, Score, '\n', Answer2, Score2, '\n', Answer3, Score3, '\n', Answer4, Score4, '\n', Answer5, Score5, '\n', rawdata, '\n')
# -*- coding: utf-8 -*- """ Created on Wed Mar 20 23:32:40 2019 @author: Shyam Parmar """ import pandas as pd import numpy as np import random as rd from sklearn.decomposition import PCA from sklearn import preprocessing #Preprocessing for scaling data import matplotlib.pyplot as plt ######################### # # Data Generation Code # ######################### ## In this example, the data is in a data frame called data. ## Columns are individual samples (i.e. cells) ## Rows are measurements taken for all the samples (i.e. genes) ## Just for the sake of the example, we'll use made up data... genes = ['gene' + str(i) for i in range(1,101)] wt = ['wt' + str(i) for i in range(1,6)] ko = ['ko' + str(i) for i in range(1,6)] data = pd.DataFrame(columns=[*wt, *ko], index=genes)#The '*' unpacksthe wt and ko arrays so that the column #names are single arrays that look like [wt1, wt2,..wt6,ko1,ko2,..ko6]. Without the stars we'd create an array #of two arrays and that would'nt create 12 columns like we want.[[w1,w2..w6],[ko1,ko2..ko6]] #index=genes means gene names are used for the index which means they are the equivalent of row names. for gene in data.index: data.loc[gene,'wt1':'wt5'] = np.random.poisson(lam=rd.randrange(10,1000), size=5) data.loc[gene,'ko1':'ko5'] = np.random.poisson(lam=rd.randrange(10,1000), size=5) print(data.head()) print(data.shape) ######################### # # Perform PCA on the data # ######################### # First center and scale the data # After centering, the avg val for each gene will be 0 and after scaling the standard deviation for the # values of each gene will be 1 scaled_data = preprocessing.scale(data.T) #.T represents that we're passing transpose of our data. The scale #function expects the samples to be rows instead of columns #StandardScaler().fit_transform(data.T) - This is more commonly used than processing.scale(data.T) pca = PCA() # create a PCA object pca.fit(scaled_data) # do the math pca_data = pca.transform(scaled_data) # get PCA coordinates for scaled_data ######################### # # Draw a scree plot and a PCA plot # ######################### #The following code constructs the Scree plot per_var = np.round(pca.explained_variance_ratio_* 100, decimals=1) #Calculate %of variation that each PC accounts for labels = ['PC' + str(x) for x in range(1, len(per_var)+1)] # Labels for scree plot plt.bar(x=range(1,len(per_var)+1), height=per_var, tick_label=labels) plt.ylabel('Percentage of Explained Variance') plt.xlabel('Principal Component') plt.title('Scree Plot') plt.show() #the following code makes a fancy looking PCA plot using PC1 and PC2 pca_df = pd.DataFrame(pca_data, index=[*wt, *ko], columns=labels) #to draw PCA plot, we'll first put #thr new coordinates, created bt pca.transform(scaled.data), into a nice matrix where rows have sample lables #and columns have pc labels plt.scatter(pca_df.PC1, pca_df.PC2) plt.title('My PCA Graph') plt.xlabel('PC1 - {0}%'.format(per_var[0])) plt.ylabel('PC2 - {0}%'.format(per_var[1])) for sample in pca_df.index: #This loop adds sample names to the graph plt.annotate(sample, (pca_df.PC1.loc[sample], pca_df.PC2.loc[sample])) plt.show() ######################### # # Determine which genes had the biggest influence on PC1 # ######################### ## get the name of the top 10 measurements (genes) that contribute ## most to pc1. ## first, get the loading scores loading_scores = pd.Series(pca.components_[0], index=genes) ## now sort the loading scores based on their magnitude sorted_loading_scores = loading_scores.abs().sort_values(ascending=False) # get the names of the top 10 genes top_10_genes = sorted_loading_scores[0:10].index.values ## print the gene names and their scores (and +/- sign) print(loading_scores[top_10_genes])
a = int(input("Введите сколько км ")) b = int(input("Введите сколько км ")) d = 1 while a < b: a *= 1.1 d += 1 print(d)
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number <= 2: return number first,second,third = 1,2,0 for i in range(2,number): third = first + second first,second = second,third return third
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt def main(): m = 1000 # Number of trials for each size sample_sizes = np.array([10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000]) biased = np.zeros(len(sample_sizes)) unbiased = np.zeros(len(sample_sizes)) for i in range(len(sample_sizes)): n = sample_sizes[i] biased_trials = np.zeros(m) unbiased_trials = np.zeros(m) for j in range(m): r = np.random.rand(n) r = r - np.mean(r) r = r * r biased_trials[j] = np.sum(r) / float(n) unbiased_trials[j] = np.sum(r) / float(n-1) biased[i] = np.mean(biased_trials) unbiased[i] = np.mean(unbiased_trials) # plotting the results exact = 1./12 plt.plot(sample_sizes, np.array([exact] * len(sample_sizes))) plt.plot(sample_sizes, biased, label='biased') plt.plot(sample_sizes, unbiased, label='unbiased') plt.xscale('log') plt.legend(loc='lower right') plt.xlabel("sample size") plt.ylabel("estimated variance") plt.show() if __name__ == '__main__': main()
def answer(numbers): if (len(numbers) == 2): return 2 else: current=0 index=1 while(numbers[current]>=0): next = numbers[current] numbers[current] = (-1 * index) index+=1 current=next return (index-(numbers[current]*-1))
# 내부 함수로 구현 print("s : ") s = input() print("t : ") t = input() def fcmp(s, t): def numcmp(s, t): num1 = float(s) num2 = float(t) if num1 > num2: return 1 elif num1 < num2: return -1 else: return 0 def strcmp(s, t): str1 = s str2 = t if str1 > str2: return 1 elif str1 < str2: return -1 else: return 0 if s[0] == '-': for i in s: if i.isnumeric() or i == '.' or i == '-': cond = "NUM" else: cond = "STR" else: cond ="STR" if t[0] == '-': for i in t: if i.isnumeric() or i == '.' or i == '-': cond = "NUM" else: cond = "STR" else: cond = "STR" if cond == "NUM": return numcmp(s, t) elif cond == "STR": return strcmp(s, t) else: print("Error") exit() p = fcmp(s, t) print(p)
#Task_3 #========================================Метод словаря=================================== calend = { 'Зима':['12','1','2'], 'Весна':['3','4','5'], 'Лето':['6','7','8'], 'Осень':['9','10','11'] } while True: mnt = input('Введите номер месяца - ') if (int(mnt) < 1) | (int(mnt) > 12): print("Введите число 1-12") else: break for key, value in calend.items(): if mnt in value: print(key) #========================================Метод списка=================================== winter = ['12','1','2'] spring = ['3','4','5'] summer = ['6','7','8'] autumn = ['9','10','11'] print("=========Метод списка===========") while True: mnt = input('Введите номер месяца - ') if (int(mnt) < 1) | (int(mnt) > 12): print("Введите число 1-12") else: break if mnt in winter: print ('Зима') elif mnt in spring: print ('Весна') elif mnt in summer: print ('Лето') elif mnt in autumn: print ('Осень')
#Task_5 my_list = [7,5,3,3,2] j=0 print(my_list) while True: n = int(input("Введите число 1-9 \n")) if not((n<1) | (n>9)): break for i in my_list: if n < i: j+=1 my_list.insert(j,n) print(my_list)
import networkx as nx import matplotlib.pyplot as plt G=nx.DiGraph() G.add_node(0),G.add_node(1),G.add_node(2),G.add_node(3),G.add_node(4) G.add_edge(0, 1),G.add_edge(1, 2),G.add_edge(0, 2),G.add_edge(1, 4),G.add_edge(1, 3),G.add_edge(3, 2),G.add_edge(3,1),G.add_edge(4,3) nx.draw(G, with_labels=True, font_weight='bold') for cycle in nx.simple_cycles(G): print(cycle) plt.show()
# EP - Design de Software # Equipe: Pedro Cliquet do Amaral # Data: 18/10/2020 import random fichas = 100 while fichas > 0 : if fichas == 0 : break carta = random.randint(0,9) print('Fichas disponiveis {0} ' .format(fichas)) aposta = int(input('quanto quer apostar? ')) if aposta > fichas: print('Não possui toda essa quantia') if aposta == 0: break metodo = input('Como quer apostar?(mesa/jogador/empate) ') #DISTRIBUINDO CARTAS carta_1 = random.randint(0,9) carta_2 = random.randint(0,9) carta_3 = random.randint(0,9) carta_4 = random.randint(0,9) mesa = [carta_1,carta_2] jogador = [carta_3,carta_4] print('Mão da mesa:') print(mesa) mao_mesa = sum(mesa) print('Mão do jogador:') print(jogador) mao_jogador = sum(jogador) #MESA if mao_mesa <= 5: print('Mesa recebe mais uma carta') carta_3 = random.randint(0,9) mesa.append(carta_3) mao_mesa = sum(mesa) print(mesa) if mao_mesa > 10 : print('Soma da mão da mesa:') mao_mesa = mao_mesa - 10 print(mao_mesa) #JOGADOR if mao_jogador <= 5: print('Jogador recebe mais uma carta') carta_4 = random.randint(0,9) jogador.append(carta_4) mao_jogador = sum(jogador) print(jogador) print('Soma da mão do jogador:') print(mao_jogador) if mao_jogador >= 10 : mao_jogador = mao_jogador - 10 print('Soma da mao da jogador:') print(mao_jogador) #Comissão taxa_mesa = int(aposta*(1.01/100)) taxa_jogador = int(aposta*(1.29/100)) taxa_empate = int(aposta*(15.75/100)) #METODO #apostando na mesa if metodo == 'mesa': if mao_mesa == mao_jogador: fichas = fichas - aposta print('Você perdeu!') if mao_mesa > mao_jogador: fichas = int(fichas + aposta*(95/100)) - taxa_mesa print('Você ganhou!') elif mao_jogador > mao_mesa: fichas = fichas - aposta print('Você perdeu!') #apostando no jogador if metodo == 'jogador': if mao_mesa < mao_jogador: fichas = fichas + aposta - taxa_jogador print('Você ganhou!') elif mao_jogador < mao_mesa: fichas = fichas - aposta print('Você perdeu!') if mao_mesa == mao_jogador: fichas = fichas - aposta print('Você perdeu!') #apostando no empate if metodo == 'empate': if mao_jogador == mao_mesa: fichas = fichas + aposta*8 - taxa_empate print('Você ganhou!') else: fichas = fichas - aposta print('Você perdeu!')
# Daily Challenge : Build Up A String # Using the input function, ask the user for a string. The string must be 10 characters long. # If it’s less than 10 characters, print a message which states “string not long enough” # If it’s more than 10 characters, print a message which states “string too long” # Then, print the first and last characters of the given text # Construct the string character by character: Print the first character, then the second, then the third, until the full string is printed # Example: # The user enters “Hello Word” # Then, you have to construct the string character by character # H # He # Hel # … etc # Hello World # Swap some characters around then print the newly jumbled string (hint: look into the shuffle method) # Example: # Hlrolelwod askstring = ("Enter a string, It has to be at least 10 characters long : ") if len(askstring) > 10: print("string not long enough") elif len(askstring) < 10: print("string too long") else : print(askstring[0], askstring[-1]) for i in range(len(askstring)): print(askstring[0:i+1]) import random print("original string :", askstring) final_str = "".join(random.sample(askstring, len(askstring))) print("shuffled string is :", final_str)
# Exercise 1 xp : Convert Lists Into Dictionaries # Convert the two following lists, into dictionaries. # Hint: Use the zip method # keys = ['Ten', 'Twenty', 'Thirty'] # values = [10, 20, 30] # Expected output: # {'Ten': 10, 'Twenty': 20, 'Thirty': 30} # Solution : # def Convert_dict(a): # init = iter(keys) # res_dct = dict(zip(init, init)) # return res_dct # keys = ['Ten', 10, 'Twenty', 20, 'Thirty', 30] # print(Convert_dict(keys)) # Exercise 2 xp : Cinemax #2 # “Continuation of Exercise Cinemax of Week4Day2 XP” # A movie theater charges different ticket prices depending on a person’s age. # if a person is under the age of 3, the ticket is free # if they are between 3 and 12, the ticket is $10; # and if they are over age 12, the ticket is $15 . # Here is the object you will work with : family = {"rick": 43, 'beth': 13, 'morty': 5, 'summer': 8} # Using a for loop, the dictionary above, and the instructions, print out how much each family member will need to pay alongside their name # After the loop print out the family’s total cost for the movies # Bonus: let the user input the names and ages instead of using the provided family variable (Hint: ask the user for names and ages and add them into a family dictionary that is initially empty) # Solution : # family = {'rick': 43, 'beth': 13, 'morty': 5, 'summer': 8} # for name, age in family.items(): # if age > 3 and age < 12: # print(f"{name} has to pay 10$") # if age < 3: # print(f"{name} free ticket !") # elif age >= 12: # print(f"{name} has to pay 15$") # print("The whole family has to pay 50$ for the movie") #bonus # nameage = {} # total = 0 # while True: # askname = input("What is your name ?") # if askname == 'x': # break # askage = int(input("What is your age ?")) # nameage[askname] = askage # for askname, askage in nameage.items(): # if askage > 3 and askage < 12: # print(f"{askname} has to pay 10$") # total += 10 # if askage < 3: # print(f"{askname} free ticket !") # total += 0 # elif askage >= 12: # print(f"{askname} has to pay 15$") # total += 15 # Exercise 3 xp : Zara # Here is some information about a brand. # name: Zara # creation_date: 1975 # creator_name: Amancio Ortega Gaona # type_of_clothes: men, women, children, home # international_competitors: Gap, H&M, Benetton # number_stores: 7000 # major_color: France -> blue, Spain -> red, US -> pink, green # Create a dictionary called brand, and translate the information above into keys and values. # Change the number of stores to 2. # Print a sentence that explains who the clients of Zara are. # Add a key called country_creation with a value of Spain to brand # If the key international_competitors is in the dictionary, add the store Desigual. # Delete the information about the date of creation. # Print the last international competitor. # Print in a sentence, the major clothes’ colors in the US. # Print the amount of key value pairs (length of the dictionary). # Print only the keys of the dictionary. # Create another dictionary called more_on_zara with the following information: # creation_date: 1975 # number_stores: 10 000 # Use a method to add the information from the dictionary more_on_zara to the dictionary brand. # Print the value of the key number_stores. What just happened ? # Solution : # #1 # brand = { # "name": "Zara", # "creation_date": 1975, # "creator_name": "Amancio Ortega Gaona", # "type_of_clothes": ["men", "women", "children", "home"], # "international_competitors": ["Gap", "H&M", "Benetton"], # "number_stores": 7000, # "major_color": ["France: blue", "Spain: red", "US: pink, green"], # } # #2 # brand.update({"number_stores": 2}) # print(brand) # #3 # print(f"Zara's clients are {brand['type_of_clothes']}") # #4 # brand["country_creation"] = "Spain" # print(brand) # #5 # brand["international_competitors"].append("Desigual") # print(brand) # #6 # brand.pop("creation_date") # print(brand) # #7 # print(brand['international_competitors'][-1]) # #8 # print(f"The major clothes’ colors in the {brand['major_color'][-1]}") # #9 # print(len(brand)) #numbers of keys in the dictionary # #10 # for key in brand.items() : # print(key) #print only keys # for value in brand.items() : # print(value) #print only values # #11 # more_on_zara = { # "creation_date": 1975, # "number_stores": 10000, # } # brand = more_on_zara(creation_date=1975, # number_stores= 10000) # print(more_on_zara) # Exercise 4 xp : Disney Characters # Consider this list : # users = [ "Mickey", "Minnie", "Donald","Ariel","Pluto"] # Analyse these results : # #1/ print(disney_users_A) >> {"Mickey": 0, "Minnie": 1, "Donald": 2, "Ariel": 3, "Pluto": 4} # #2/ print(disney_users_B) >> {0: "Mickey",1: "Minnie", 2: "Donald", 3: "Ariel", 4: "Pluto"} # #3/ print(disney_users_C) >> {"Ariel": 0, "Donald": 1, "Mickey": 2, "Minnie": 3, "Pluto": 4} # Use a for loop to recreate the #1 result. Tip : don’t hardcode the numbers # Use a for loop to recreate the #2 result. Tip : don’t hardcode the numbers # Use a method to recreate the #3 result # Hint: The 3rd result is in the alphabetical order # Recreate the #1 result, only if: # The characters’ names contain the letter “i”. # The characters’ names start with the letter “m” or “p”. # Solution : # users = ["Mickey", "Minnie", "Donald","Ariel","Pluto"] # indices = list(range(len(users))) # disney_users_A = dict(zip(users, indices)) # print(disney_users_A) # disney_users_B = dict(zip(indices, users)) # print(disney_users_B) # disney_users_C = dict(zip(sorted(users), indices)) # print(disney_users_C) # mylist = [name for name in users if "i" in name] # disney_users_D = dict(zip(sorted(users), indices)) # print(disney_users_D) # disney_users_D = {key: value for (key, value) in disney_users_A.items() if "i" in key} # print(disney_users_D)
#Exercise 2 : Dogs # class Dog: # def __init__(self, name, height): # self.name = name # self.height = height # def bark(self, message): # print("{} {}".format(self.name, message)) # def jump(self): # print("{} jumps {}cm high".format(self.name, self.height*2)) # def dogsperson(self): # print("The dog's name is {} and his height is {}".format(self.name, self.height)) # h1 = Dog("Bobby", 133) # h1.bark("goes woof !") # h1.jump() # davids_dog = Dog("Rex", 50) # davids_dog.dogsperson() # sarahs_dog = Dog("Teacup", 20) # sarahs_dog.dogsperson() # def biggers(self): # if davids_dog.Dog.self.height > sarahs_dog.Dog.self.height : # print(f"{davids_dog.dogsperson()}, and he is the bigger") # else: # print(f"{sarahs_dog.dogsperson()}, and he is the bigger") #Exercise 3 : Who’s The Song Producer ? # class Song: # def __init__(self, lyrics): # self.lyrics = lyrics # lyrics = [] # def sing_me_a_song(self): # print(self.lyrics) # stairway = Song("There’s a lady who's sure\n all that glitters is gold\n and she’s buying a stairway to heaven") # stairway.sing_me_a_song() #Exercise 4 : Afternoon At The Zoo class Zoo: def __init__(self, zoo_name): self.zoo_name = zoo_name def add_animal(self, new_animal): self.new_animal = new_animal if new_one is not new_animal: new_animal += new_one animals = Zoo([]) name = Zoo("ZOOOOM")
# Exercise 1 xp : What Are You Learning ? # Write a function called display_message() that prints one sentence telling everyone what you are learning about in this chapter. # Call the function, and make sure the message displays correctly. # Solution : # def display_message(): # print("Today we learned function !") # display_message() # Exercise 2 xp : What’s Your Favorite Book ? # Write a function called favorite_book() that accepts one parameter, title. # The function should print a message, such as “One of my favorite books is Alice in Wonderland”. # Call the function, making sure to include a book title as an argument in the function call. # Solution : # def favorite_book(title='book title'): # print('One of my favorite books is Alice in Wonderland') # favorite_book(title='book title') # Exercise 3 xp : # Write a function that accepts one parameter (a number X) and returns the value of X+XX+XXX+XXXX. # Solution : # def digit_sum_from_letters(x): # a = int("%s" % x) # b = int("%s%s" % (x,x)) # c = int("%s%s%s" % (x,x,x)) # d = int("%s%s%s%s" % (x,x,x,x)) # return a+b+c+d # print(digit_sum_from_letters(9)) # Exercise 4 xp : Some Geography # Write a function called describe_city() that accepts the name of a city and its country. # The function should print a simple sentence, such as “Reykjavik is in Iceland”. # Give the parameter for the country a default value. # Call your function for three different cities, at least one of which is not in the default country. # Solution : # def describe_city(city, country="france"): # print(f"{city} is in {country}") # describe_city("Paris") # describe_city("Tel aviv", "Israel") # describe_city("Milan", "Italy") # Exercise 5 xp : Let’s Create Some Personalized Shirts ! # Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt. # The function should print a sentence summarizing the size of the shirt and the message printed on it. # Call the function once using positional arguments to make a shirt. # Call the function a second time using keyword arguments. # Modify the make_shirt() function so that shirts are large by default with a message that reads I love Python. # Make a large shirt and a medium shirt with the default message, and a shirt of any size with a different message. # Solution : # #1,2 # def make_shirt(size="large", printedtext="'I love Python'"): # print(f"The size is {size} and the message is {printedtext}") # #3 # make_shirt("medium", "'I'm the boss'") # #4 # make_shirt(size="large", printedtext="'You are the boss'") # #5 # make_shirt() # #6 # make_shirt() # make_shirt(size="medium") # make_shirt(size="small", printedtext="'Hi everyone'") # Exercise 6 xp : Magicians … # Make a list of magician’s names. # Pass the list to a function called show_magicians(), which prints the name of each magician in the list. # Write a function called make_great() that modifies the list of magicians by adding the phrase "the Great" to each magician’s name. # Call show_magicians() to see that the list has actually been modified. # Solution : # #1 # names = ["Harry Potter", "Ron Weasley", "Hermione Granger"] # #2 # def show_magicians(magicians): # for mag in magicians: # print(mag) # show_magicians(names) # #3 # def make_great(mag): # for mags in range(0, len(mag)): # mag[mags] = 'The great ' + mag[mags] # return mag # show_magicians(names) # new_names = make_great(names) # show_magicians(new_names) # Exercise 7 xp : When Will I Retire ? # The point of the exercise is to check is a person can retire depending on his age and his gender. # Note : Retirement age in Israel is 67 for men, and 62 for women (born after April, 1947). # Create a function get_age(year, month, day) # Hard-code the current year and month in your code (there are better ways of doing this, but for now it will be enough.) # After calculating the age of a person, the function should return it (the age is an integer). # Create a function can_retire(gender, date_of_birth). # It should call the get_age function (with what arguments?) in order to receive an age back. # Now it has all the information it needs in order to determine if the person with the given gender and date of birth is able to retire or not. # Calculate. You may need to do a little more hard-coding here. # Return True if the person can retire, and False if he/she can’t. # Some Hints # Ask for the user’s gender as “m” or “f”. # Ask for the user’s date of birth in the form “yyyy/mm/dd”, eg. “1993/09/21”. # Call can_retire to get a definite value for whether the person can or can’t retire. # Display a message to the user informing them whether they can retire or not. # As always, test your code to ensure it works. # Solution : from datetime import date local_dt = datetime.now() print(local_dt) datetime.now(year=2020, month=11, day=11) retiremindate = [date(1953, 1, 1), date(1958, 1, 1)] print(retiremindate[0].year) print(retiremindate[0].month) print(retiremindate[0].day) def get_age(year, month, day): for men and women in datetime: print(input(datetime)) if men >= local_dt.year - 67 and women >= local_dt.year - 62 : print("You can retire !") else: print("You have to wait..") get_age(year=1988, month=2, day=5) # def show_magicians(magicians): # for mag in magicians: # print(mag) # show_magicians(names) # #3 # def make_great(mag): # for mags in range(0, len(mag)): # mag[mags] = 'The great ' + mag[mags] # return mag # show_magicians(names) # new_names = make_great(names) # show_magicians(new_names)
import sys import unittest from unittest.mock import patch from fizzbuzz.app import run, fizz_buzz, convert_to_int class TestFizzBuzz(unittest.TestCase): def test_fizzbuzz_returns_correct_list(self): """ Test that fizzbuzz list has correct values for multiples """ fizzbuzz = fizz_buzz(1, 15) self.assertEqual(fizzbuzz[0], 1, "List did not start with the number 1") self.assertEqual( fizzbuzz[-1], "FizzBuzz", "Multiple of both 3 and 5 (15) did not print FizzBuzz", ) self.assertEqual(fizzbuzz[2], "Fizz", "Multiple of 3 (3) did not print Fizz") self.assertEqual(fizzbuzz[4], "Buzz", "Multiple of 5 (5) did not print Buzz") def test_convert_to_int_returns_defaults(self): """ Test that converting the numbers returns a [1, 100] if empty list is passed """ integer_list = convert_to_int([])[0] print(integer_list) self.assertEqual(integer_list[0], 1, "List did not start with the number 1") self.assertEqual(integer_list[1], 100, "List did not end with the number 100") def test_convert_to_int_returns_error_for_non_integers(self): """ Test that converting the numbers returns a [1, 100] if empty list is passed """ integer_list = convert_to_int(["something"]) self.assertEqual( integer_list[1], "Please enter integers only", "Convert to int did not return an error for non int value", ) def test_convert_to_int_returns_error_for_more_than_2_args(self): """ Test that more than 2 args will result in error """ integer_list = convert_to_int([1, 2, 3]) self.assertEqual( integer_list[1], "You cannot enter more than 2 arguments", "Convert to int did not return an error for more than 2 args", ) def test_convert_to_int_returns_error_for_zero_as_an_arg(self): """ Test that zero is not accepted as an arg """ integer_list = convert_to_int([1, 0]) self.assertEqual( integer_list[1], "When entering integers ensure they are greater than 0", "Convert int did not throw an error when zero was passed", ) def test_convert_to_int_returns_1_as_min_value_when_single_arg_is_provided(self): """ Test that 1 is returned as the min value if one argument is passed """ integer_list = convert_to_int([80])[0] self.assertEqual( integer_list[0], 1, "Convert to int did not return a minimum value when provided with a single argument", ) def test_run_function_accepts_args(self): """ Test that the run function runs and prints """ testargs = ["main.py", "1", "3"] with patch.object(sys, "argv", testargs): self.assertEqual( run(), "Success", "The run function did not go all the way through", ) def test_run_function_returns_errors_when_invalid_args_passed(self): """ Test that the run function runs and prints """ testargs = ["main.py", 1, 2, 3, 4] with patch.object(sys, "argv", testargs): with self.assertRaises(Exception): run() if __name__ == "__main__": unittest.main()
def main(): print('This tests if else statements and function') number_test = float(input('Please insert a number')) if number_tester(number_test): print('This number is five.') else: print('This number is not five.') def number_tester(number_test): if (number_test) == 5: status = True else: status = False return status main()
from integer import Integer first_number = int(input('Type a first integer number: ')) second_number = int(input('Type a second integer number: ')) print('1 - Add') print('2 - Subtract') print('3 - Multiply') print('4 - Divide') operation = int(input('Type a valid operation! please!: ')) if operation is 1: result = Integer(first_number) + Integer(second_number) print(result) elif operation is 2: result = Integer(first_number) - Integer(second_number) print(result) elif operation is 3: result = Integer(first_number) * Integer(second_number) print(result) elif operation is 4: result = Integer(first_number) / Integer(second_number) print(result) else: print('Onvalid choice!')
''' Esto es un adelanto en hackaton , comentario en bloque ''' nombre = 'Angel Diaz' edad = 15 esta_Trabajando = True # False dato = input ('Introducir un dato: ') print(dato) print(edad) if( edad >= 18 ): print('mayor') else: print('menor') def cuadrado(x): return x * x cuadrado_de_dos = cuadrado(2) print(cuadrado_de_dos) for valor in (1,2,3,4): print(valor)
import matplotlib.pyplot as pyplot x = [x * x for x in range(1, 100) if x % 2 == 0] x.append(100) y = [y * y for y in range(1, 100) if y % 2 != 0] pyplot.plot(x, y) pyplot.show()
# coding=utf-8 import functools def map_test(): """ map test """ # map 函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 i = (1, 2, 3, 4, 5, 6, 7, 8, 9, 19) map_process = map(lambda x: str(x) + ".", i) for i in map_process: print(i) def reduce_test(): """ reduce test """ # 再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...] # 上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算 i = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(functools.reduce(lambda x, y: x + y, i, 0)) def filter_test(): """ filter test """ print("filter test begin") i = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) for x in filter(lambda x: x % 2 == 0, i): print(x) def sort_test(): """ sort test """ print("sort test begin") i = (1, 6, 7, 8, 9, 10, 2, 3, 4, 5) new_list = sorted(i, key=abs, reverse=True) for x in new_list: print(x) if __name__ == '__main__': map_test() reduce_test() filter_test() sort_test()
from collections import deque """ 参数数组 """ de = deque([1, 2, 3]) print(de) """ 单个元素都可 """ de.append('a') de.append('b') print(de) de.appendleft('left') print(de)
# coding=utf-8 """ 解决闭包不优雅的方式""" def return_fun(): fs = [] def go(j): def fun(): return j * j return fun for temp in range(3): fs.append(go(temp)) return fs if __name__ == '__main__': result = return_fun() print(result) for x in result: print(x) print(x())
# coding=utf-8 def return_fun(): """ return a function :return: """ def add(x, y): """ return result of x plus y :param x: :param y: :return: """ return x + y return add if __name__ == '__main__': add = return_fun() print(add) print(add(1, 2)) # not the same function False print(return_fun() == return_fun())
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ rev = 0 while x: pop = x % 10 x /= 10 if rev > (2 ** 31 - 1) / 10 or (rev == (2 ** 31 - 1) / 10 and pop > 7): return 0 if rev < -2 ** 31 / 10 or (rev == -2 ** 31 / 10 and pop < -8): return 0 rev = rev * 10 + pop return rev
############################################################ # CIS 521: Homework 2 ############################################################ student_name = "Shubhankar Patankar" ############################################################ # Imports ############################################################ # Include your imports here, if any are used. import collections import math import random import copy ############################################################ # Section 1: N-Queens ############################################################ def num_placements_all(n): queens = n squares = n**2 # squares choose queens return int(math.factorial(squares)/(math.factorial(queens) * math.factorial(squares - queens))) def num_placements_one_per_row(n): queens = n # squares choose queens return (queens**queens) # def n_queens_valid(board): # # ROW CHECK # # is implemented by virtue of # # the fact that the i-th index cannot have # # two values # # COLUMN CHECK # if len(set(board)) != len(board): # # if condition checks for duplicate entries in board, # # if any value appear more than once, that implies that # # multiple queens share the same columns # return False # # DIAGONAL CHECK # n = max(board) # queens_exist = [] # for i, col in enumerate(board): # queens_exist.append((i, col)) # # diagonal elements going down # for queen in queens_exist: # curr_queen_row = queen[0] # curr_queen_col = queen[1] # diags_down = [] # within = True # within bounds of board # new_row = curr_queen_row # new_col = curr_queen_col # while within: # new_row += 1 # new_col += 1 # if (new_row > n) or (new_col > n): # within = False # else: # diags_down.append((new_row, new_col)) # if [queen_exists for queen_exists in diags_down if queen_exists in queens_exist]: # return False # a queen exists diagonally downwards from current queen # diags_up = [] # within = True # within bounds of board # new_row = curr_queen_row # new_col = curr_queen_col # while within: # new_row -= 1 # new_col += 1 # if (new_row > n) or (new_col > n): # within = False # else: # diags_up.append((new_row, new_col)) # if [queen_exists for queen_exists in diags_up if queen_exists in queens_exist]: # return False # a queen exists diagonally upwards from current queen # return True # if no fail condition was tripped def n_queens_valid(board): if len(set(board)) != len(board): return False for row_1, col_1 in enumerate(board): for row_2, col_2 in enumerate(board): if row_1 != row_2: if col_1 == col_2: # same queen in two columns return False if abs(row_1 - row_2) == abs(col_1 - col_2): return False return True def n_queens_helper(n, board): all_valid = set(range(n)) - set(board) count = len(all_valid) while count > 0: copy_board = board.copy() elem = all_valid.pop() count -= 1 copy_board.append(elem) if n_queens_valid(copy_board): yield elem def solve_n_queens(n, row, board, result): if row == n: yield board.copy() else: for col in range(n): board.append(col) if n_queens_valid(board): yield from solve_n_queens(n, row + 1, board, result) board.pop() def n_queens_solutions(n): board = [] result = [] row = 0 return solve_n_queens(n, row, board, result) ############################################################ # Section 2: Lights Out ############################################################ def create_puzzle(rows, cols): board = [[False]*cols for _ in range(rows)] puzzle = LightsOutPuzzle(board) return puzzle class LightsOutPuzzle(object): def __init__(self, board): # initialize 2-D board self.num_rows = len(board) self.num_cols = len(board[0]) self.board = board def get_board(self): return self.board def perform_move(self, row, col): board = self.board if row >= 0 and row < self.num_rows and col >= 0 and col < self.num_cols: board[row][col] = not board[row][col] row_above = row - 1 col_above = col if row_above >= 0: board[row_above][col_above] = not board[row_above][col_above] row_below = row + 1 col_below = col if row_below < self.num_rows: board[row_below][col_below] = not board[row_below][col_below] row_right = row col_right = col + 1 if col_right < self.num_cols: board[row_right][col_right] = not board[row_right][col_right] row_left = row col_left = col - 1 if col_left >= 0: board[row_left][col_left] = not board[row_left][col_left] self.board = board def scramble(self): new_self = self.copy() for row in range(new_self.num_rows): for col in range(new_self.num_cols): if random.random() < 0.5: new_self.perform_move(row, col) return new_self def is_solved(self): board = self.board need_falses = self.num_rows * self.num_cols count = 0 for row in range(self.num_rows): for col in range(self.num_cols): if not board[row][col]: count += 1 if count == need_falses: return True return False def copy(self): copy_puzzle = copy.deepcopy(self) return copy_puzzle def successors(self): for row in range(self.num_rows): for col in range(self.num_cols): move = (row,col) temp_puzzle = self.copy() temp_puzzle.perform_move(row, col) result_tuple = (move, temp_puzzle) yield result_tuple def find_solution(self): node = self parent = {} moves = () if node.is_solved(): return moves frontier = [node] explored = set() while True: if not frontier: # frontier empty return None node = frontier.pop(0) # remove from frontier explored.add(tuple(tuple(x) for x in node.board)) # add to explored for move, successor in node.successors(): candidate_child = tuple(tuple(x) for x in successor.board) if candidate_child in explored: continue if candidate_child in frontier: continue parent[tuple(tuple(x) for x in successor.board)] = (move) # this `move' links `parent'-`child' if successor.is_solved(): # use parent dictionary while successor.board != self.board: moves = (parent[tuple(tuple(x) for x in successor.board)],) + moves successor.perform_move(moves[0][0], moves[0][1]) return list(moves) frontier.append(successor) ############################################################ # Section 3: Linear Disk Movement ############################################################ def create_game(length, n): state = [-1]*length for i in range(n): state[i] = i game = Game(state) return game class Game(object): def __init__(self, state): self.num_disks = sum(elem is not -1 for elem in state) self.length = len(state) self.state = state def get_state(self): return self.state def perform_move(self, loc, jump): # jump could be -1, -2, +1, +2 state = self.state disk = state[loc] state[loc] = -1 state[loc + jump] = disk self.state = state def is_solved_identical(self): state = self.state n = self.num_disks check_list = state[-n:] if any(elem == -1 for elem in check_list): return False return True def is_solved_distinct(self): state = self.state n = self.num_disks length = self.length check_list = list(reversed(range(n))) while len(check_list) != length: check_list.insert(0,-1) if state == check_list: return True else: return False def copy(self): copy_game = copy.deepcopy(self) return copy_game def successors(self): jumps = [-2, -1, 1, 2] for i in range(self.length): for jump in jumps: temp_game = self.copy() if valid_move(i, jump, temp_game): temp_game.perform_move(i, jump) result_tuple = ((i, i + jump),temp_game) yield result_tuple def valid_move(i, jump, temp_game): num_disks = temp_game.num_disks length = temp_game.length state = temp_game.state if jump == -2: # ensure there is a disk to leap over middle = i + jump + 1 if middle not in range(length): return False if state[middle] == -1: return False if jump == 2: # ensure there is a disk to leap over middle = i + jump - 1 if middle not in range(length): return False if state[middle] == -1: return False to = i + jump if (to < 0) or (to >= length): return False if state[i] == -1: return False if state[to] != -1: return False return True def solve_identical_disks(length, n): g = create_game(length,n) node = g.copy() parent = {} moves = () if node.is_solved_identical(): return list(moves) frontier = collections.deque() frontier.append(node) explored = set() while True: if not frontier: # frontier empty return None node = frontier.popleft() # remove from frontier: BFS explored.add(tuple(node.state)) # add to explored for move, successor in node.successors(): if tuple(successor.state) in explored: continue if successor in frontier: continue parent[tuple(successor.state)] = (move) # this `move' links `parent'-`child' if successor.is_solved_identical(): # use parent dictionary while successor.state != g.state: moves = (parent[tuple(successor.state)],) + moves # going backwards, the parent's jump position becomes # child's position, and the jump for the child is the difference # between the parent's initial position and the child's current # position successor.perform_move(moves[0][1], moves[0][0] - moves[0][1]) return list(moves) frontier.append(successor) def solve_distinct_disks(length, n): g = create_game(length,n) node = g.copy() parent = {} moves = () if node.is_solved_identical(): return list(moves) frontier = collections.deque() frontier.append(node) explored = set() while True: if not frontier: # frontier empty return None node = frontier.popleft() # remove from frontier: BFS explored.add(tuple(node.state)) # add to explored for move, successor in node.successors(): if tuple(successor.state) in explored: continue if successor in frontier: continue parent[tuple(successor.state)] = (move) # this `move' links `parent'-`child' if successor.is_solved_distinct(): # use parent dictionary while successor.state != g.state: moves = (parent[tuple(successor.state)],) + moves # going backwards, the parent's jump position becomes # child's position, and the jump for the child is the difference # between the parent's initial position and the child's current # position successor.perform_move(moves[0][1], moves[0][0] - moves[0][1]) return list(moves) frontier.append(successor) ############################################################ # Section 4: Feedback ############################################################ feedback_question_1 = """ Approximately between 40 and 50 hours. """ feedback_question_2 = """ Translating the pseudocode for the search algorithms was tricky for me. Not having a strong background in data-structures made it harder to quickly understand what was meant by queues and stacks and popping, etc. """ feedback_question_3 = """ I enjoyed the programming rigor. I have had to learn a lot of Python very very quickly for this assignment, which is always a plus. I would have loved for this assignment to be shorter though, perhaps without the solve_distinct_disks() implementation. """
# Lab 1: Python program to check if rectangles overlap using object oriented paradigm # CS107, Haverford College # <replace with your name> # Creating a class rectangle # https://en.wikipedia.org/wiki/Rectangle # # This program is intended to find whether two rectangles overlap (or intersect) each other or not. # In the Euclidean space, a rectangle can be represented by two coordinates. Let the first co-ordinate is for the # top-left corner and the second co-ordinated is for the bottom-right corner of the rectangle. # A point in two dimensional Euclidean space can be represented by a pair say (x,y). # Thus, a sample representation of a rectangle can be given as class with two member objects of another class named Point class Point: def __init__(self, x, y): self.x = x self.y = y class Rectangle: # A recangle defined by two points bottom-left (bleft), and upper-right(uright) def __init__(self, bleft, uright): self.bleft = bleft self.uright = uright def doesIntersect(self, other): """ First draw and check for the conditions when two rectangles can or cannot overlap with each other Note down the ordinated and write test suit for the same as follows Then add your logic to find overlap >>> Rect1 = Rectangle(Point(0, 0), Point(3, 3)) >>> Rect2 = Rectangle(Point(1, 1), Point(4, 4)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point(1, 1), Point(3, 3)) >>> Rect2 = Rectangle(Point(4, 4), Point(5, 5)) >>> Rect1.doesIntersect(Rect2) False >>> Rect1 = Rectangle(Point(0, 0), Point(2, 2)) >>> Rect2 = Rectangle(Point(-1, -1), Point(1, 1)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point(0, 0), Point(2, 2)) >>> Rect2 = Rectangle(Point(1, 0), Point(3, 2)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point(-1, -2), Point(1, 2)) >>> Rect2 = Rectangle(Point(-2, -1), Point(2, 1)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point(0, 0), Point(3, 3)) >>> Rect2 = Rectangle(Point(1, 1), Point(2, 2)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point(0, 0), Point(1, 1)) >>> Rect2 = Rectangle(Point(2, 0), Point(3, 1)) >>> Rect1.doesIntersect(Rect2) False >>> Rect1 = Rectangle(Point(1, 1), Point(3, 3)) >>> Rect2 = Rectangle(Point(4, 4), Point(5, 5)) >>> Rect1.doesIntersect(Rect2) False >>> Rect1 = Rectangle(Point(0, 0), Point(2, 2)) >>> Rect2 = Rectangle(Point(1, 3), Point(3, 10)) >>> Rect1.doesIntersect(Rect2) False >>> Rect1 = Rectangle(Point(0, 0), Point(1, 1)) >>> Rect2 = Rectangle(Point(-1, 2), Point(2, 4)) >>> Rect1.doesIntersect(Rect2) False Bonus Test Cases Below >>> Rect2 = Rectangle(Point(-1, -2), Point(1, 2)) >>> Rect1 = Rectangle(Point(-2, -1), Point(2, 1)) >>> Rect1.doesIntersect(Rect2) True >>> Rect2 = Rectangle(Point(0, 0), Point(3, 3)) >>> Rect1 = Rectangle(Point(1, 1), Point(2, 2)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point(-1, -2), Point(1, 2)) >>> Rect2 = Rectangle(Point(-2, -5), Point(2, 1)) >>> Rect1.doesIntersect(Rect2) True >>> Rect1 = Rectangle(Point("Hello", 1), Point(3, 3)) >>> Rect2 = Rectangle(Point(4, 4), Point(5, 5)) >>> Rect1.doesIntersect(Rect2) Traceback (most recent call last): TypeError: Self bleft's x value should be either an integer or a float >>> Rect1 = Rectangle(Point(1, 1), Point(0, 0)) >>> Rect2 = Rectangle(Point(4, 4), Point(5, 5)) >>> Rect1.doesIntersect(Rect2) Traceback (most recent call last): ValueError: Self bleft is not below or left of uright -----Add your test cases here similar to the above test cases """ # <------- Add your logic for checking preconditions ----> if not (isinstance(self.bleft.x, float) or isinstance(self.bleft.x, int)): raise TypeError("Self bleft's x value should be either an integer or a float") if not (isinstance(self.bleft.y, float) or isinstance(self.bleft.y, int)): raise TypeError("Self bleft's y value should be either an integer or a float") if not (isinstance(self.uright.x, float) or isinstance(self.uright.x, int)): raise TypeError("Self uright's x value should be either an integer or a float") if not (isinstance(self.uright.y, float) or isinstance(self.uright.y, int)): raise TypeError("Self uright's y value should be either an integer or a float") if not (isinstance(other.bleft.x, float) or isinstance(other.bleft.x, int)): raise TypeError("Other bleft's x value should be either an integer or a float") if not (isinstance(other.bleft.y, float) or isinstance(other.bleft.y, int)): raise TypeError("Other bleft's y value should be either an integer or a float") if not (isinstance(other.uright.x, float) or isinstance(other.uright.x, int)): raise TypeError("Other uright's x value should be either an integer or a float") if not (isinstance(other.uright.y, float) or isinstance(other.uright.y, int)): raise TypeError("Other uright's y value should be either an integer or a float") if not (self.bleft.x < self.uright.x and self.bleft.y < self.uright.y): raise ValueError("Self bleft is not below or left of uright") if not (other.bleft.x < other.uright.x and other.bleft.y < other.uright.y): raise ValueError("Other bleft is not below or left of uright") # In this case, you will be testing the validity of the input points # The x and y parts of all the coordinates should be numbers (int or float) # The bottom-left point should be below to the upper-right point # If preconditions are not met, throw exceptions with appropriate message # To learn how to raise exceptions, I encourage you to refer to the file named UsefulCodeBase.py # UsefulCodeBase.py contains code that checks types, values and raises helpful exceptions # <------- Add your logic for overlap here ------> # Checks if a point in the "other" rectangle is located within the "self" rectangle, in the case the "other" rectangle is completely enclosed -- and vice versa if self.bleft.x <= other.bleft.x <= self.uright.x and self.uright.y >= other.bleft.y >= self.bleft.y: return True if other.bleft.x <= self.bleft.x <= other.uright.x and other.uright.y >= self.bleft.y >= other.bleft.y: return True # Checks if any of the self points are between the y coordinates of the other rectangle, then checks if the self.uright/bleft points are on opposite sides of one of other's vertical sides if ((other.uright.y >= self.uright.y >= other.bleft.y) or ( other.uright.y > self.bleft.y >= other.bleft.y)) and ( (self.uright.x >= other.uright.x >= self.bleft.x) or (self.uright.x >= other.bleft.x >= self.bleft.x)): return True # Same as above, except checks if the self points are between the x coordinates of the other rectangle, then verifies the points are on opposite sides of one of the other's horizontal sides if ((other.uright.x >= self.uright.x >= other.bleft.x) or ( other.uright.x > self.bleft.x >= other.bleft.x)) and ( (self.uright.y >= other.uright.y >= self.bleft.y) or (self.uright.y >= other.bleft.y >= self.bleft.y)): return True return False # Test for the post condition i.e. correctness of the output. def test_intersect(): # doctest use, as per http://docs.python.org/lib/module-doctest.html import doctest print("Trying out tests given at the beginning of this script") doctest.testmod() # Program execution starts here # I copied this from http://docs.python.org/lib/module-doctest.html if __name__ == "__main__": test_intersect()
#!/usr/bin/python3 ''' Q4.1 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. ''' from Graph import Graph from Queue import Queue #depth first search def dfs(graph, u, v, visited=None): if visited == None: visited = set() result = False for e in graph._outgoing[u]: if e in visited: continue visited.add(e) if e == v: return True result = dfs(graph, e, v, visited) #print({e._element for e in visited}) return result #breadth first search def bfs(graph, u, v): if u == v: return True visited = set() queue = Queue() queue.enqueue(u) while not queue.is_empty(): #print([i._element for i in queue._data if i is not None] ) for i in range(queue._size): u = queue.dequeue() visited.add(u) for e in graph._outgoing[u]: if e in visited: continue elif e == v: return True queue.enqueue(e) return False #--------TEST-------- def test(graph): G = {} for i in graph._outgoing.keys(): G[i._element] = {i2._element for i2 in graph._outgoing[i]} print(G) ''' Graph example 0->1->2->3->4->5 {0: {1}, 1: {2}, 2: {3, 4}, 3: set(), 4: set()} ''' #make new graph graph = Graph(True) V = {} E = {} for i in range(9): V[i] = graph.insert_vertex(i) for i in range(6): if i == 3: E[(i-1,i+1)] = graph.insert_edge(V[i-1],V[i+1]) elif i == 7: continue else: E[(i,i+1)] = graph.insert_edge(V[i],V[i+1]) #print("->".join([str(i._element) for i in graph.edges()])) E[(V[6],V[4])] = graph.insert_edge(V[6],V[4]) E[(V[8],V[1])] = graph.insert_edge(V[8],V[1]) E[(V[2],V[8])] = graph.insert_edge(V[2],V[8]) u = V[2] v = V[6] print("-------------") test(graph) print("Origin:", u) #print(dfs(graph, u, v)) print(bfs(graph, u, v)) print("Destination:", v)
#!/usr/bin/python3 """ Question 1.2 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. Note: permutation -> when all charas in str1 are present in str2; order does not matter; whitespace matters; confirm if str is ascii """ #------------------------------------------------ #O(nlogn) def permutation2(str1, str2): if len(str1) != len(str2): return False return sorted(str1) == sorted(str2) #------------------------------------------------ #O(n) def permutation(str1, str2): str1Dict, str2Dict = {}, {} if len(str1) != len(str2): return False for i in str1: if i in str1Dict.keys(): str1Dict[i] += 1 else: str1Dict[i] = 1 for i in str2: if i in str2Dict.keys(): str2Dict[i] += 1 else: str2Dict[i] = 1 if str1Dict == str2Dict: return True return False #------------------------------------------------ def permutation3(str1, str2): charaCount = [0 for i in range(128)] for i in str1: charaCount[ord(i)] += 1 for i in str2: charaCount[ord(i)] -= 1 if charaCount[ord(i)] < 0: return False return True #------------------------------------------------ #TEST str1 = 'wef34 f' str2 = 'wff e34' str3 = 'dcw4f' str4 = 'dcw5f' print(permutation(str1,str2), "True") print(permutation(str3,str4), "False") print(permutation2(str1,str2), "True") print(permutation2(str3,str4), "False") print(permutation3(str1,str2), "True") print(permutation3(str3,str4), "False")
#!/usr/bin/python3 ''' Q2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (7-> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295. Output:2 -> 1 -> 9. That is, 912. FOLLOW UP Suppose the digits are stored in forward order. Repeat the above problem. Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295. Output: 9 -> 1 -> 2. That is, 912. ''' from LinkedList import LinkedList #O(n) time def sum_lists_reverse(lla, llb): currA = lla.head currB = llb.head while(currA or currB): #add 0 if numbers are not even in length if not currA: lla.push(0) currA = lla.tail elif not currB: llb.push(0) currB = llb.tail #add digits currA.value += currB.value #add one to next digits place if > 9 if currA.value > 9: currA.value -= 10 if currA.next: currA.next.value += 1 else: lla.push(1) #continue to next digits currA, currB = currA.next, currB.next return lla #O(n) time def sum_lists_forward(lla, llb): if len(lla) > len(llb): diff = len(lla) - len(llb) for i in range(diff): llb.shift(0) elif len(lla) < len(llb): diff = len(llb) - len(lla) for i in range(diff): lla.shift(0) currA = lla.head currB = llb.head prevA = None while(currA or currB): currA.value += currB.value if currA.value > 9: currA.value -= 10 if prevA: prevA.value += 1 else: lla.shift(1) prevA = currA currA, currB = currA.next, currB.next return lla def sum_lists(lla, llb): lstA, lstB = [], [] for a in lla: lstA.append(a.value) for b in llb: lstB.append(b.value) numA = int("".join(map(str, lstA))) numB = int("".join(map(str, lstB))) sumForward = numA + numB lstA.reverse() lstB.reverse() numA = int("".join(map(str, lstA))) numB = int("".join(map(str, lstB))) sumReverse = numA + numB sumReverse = str(sumReverse)[::-1] return (sumForward, sumReverse) #TEST lla = LinkedList() llb = LinkedList() ''' #TEST - REVERSE lla.generate(5, 9, 9) llb.generate(3, 1, 9) print("reverse lists") print(lla) print(llb) print("reverse sum") print(sum_lists(lla, llb)[1]) print(sum_lists_reverse(lla, llb)) ''' #TEST - FORWARD lla.generate(5, 1, 9) llb.generate(3, 1, 9) print("forward lists") print(lla) print(llb) print("forward sum") print(sum_lists(lla, llb)[0]) print(sum_lists_forward(lla, llb))
########################################################## # Name: greedy_algorithms.py # Description: contains implementation of Prim's algorithm # Author: Medina Lamkin # Last Edited: 13/03/19 ########################################################## import math from graph import * # doesn't account for graphs that have unconnected areas; does it need to? # returns a minimum spanning tree and the minimun weight between the vertices def prims_algorithm(graph): min_spanning_graph = Graph() total_weight = 0.0 # get a starting key for key in graph.graph: first_vertex = key break # add the first key to the min_spanning_graph min_spanning_graph.add_new_key(first_vertex) add_vertex = True # find the lowest weight which connects to an adjacent node while add_vertex: #(len(min_spanning_graph.graph) <= len(graph.graph)) add_vertex = False #print("add_vertex: ", add_vertex) key1 = None # when set, this key should already be in the min_spanning_graph key2 = None # new key to add to the min spanning graph lowest_weight = math.inf #print("key1, key2: ", key1, key2) #print("lowest_weight", lowest_weight) for key in min_spanning_graph.graph: if key in graph.graph: for neighbour in graph.graph[key]: if neighbour[0] in min_spanning_graph.graph: #print("neighbour: ", neighbour) pass else: if neighbour[1] < lowest_weight: # (neighbor node, edge weight) lowest_weight = neighbour[1] key1 = key key2 = neighbour[0] add_vertex = True #print("lowest_weight", lowest_weight) #print("key1, key2: ", key1, key2) else: pass #if there is a neighboring vertex to the if add_vertex: min_spanning_graph.add_new_key(key2) min_spanning_graph.add_edge(key1, key2, lowest_weight) total_weight += lowest_weight #print(min_spanning_graph.graph) #print("add_vertex: ", add_vertex) return total_weight, min_spanning_graph
#!/usr/bin/env python #-*- coding: utf-8 -*- def palindrom(lancuch): lancuch=lancuch.lower().replace(" ", "").decode("utf-8") lancuch_odwrocony=lancuch[::-1] if lancuch_odwrocony==lancuch: return True else: return False print palindrom("Kobyła ma mały bok") print palindrom("Zakopane na pokaz") print palindrom("Cokolwiek")
# 现在,对于任一个英文的纯文本 txt 文件,请统计其中的单词总数 # 结果示例: # There are 687 words in words.txt. # 导入模块 import re import os def search(): # 设定查找规则 pattern = re.compile(r"[A-z]+") path = os.listdir(path="D:\\pythonwork\\小应用") while True: user_input = input("请输入您想查询的文件:") # 设置判断如果搜索的文件名在该目录下的话执行查找,否则告知文件不存在,并重新搜索 if user_input in path: # 打开文件 with open(f"{user_input}", encoding="utf-8") as f: result = pattern.findall(f.read()) num_word = len(result) print(f"There are {num_word} words in {f.name}") else: print("你搜索的文件不存在") continue search()
from typing import List, Dict, Union from .db_conn import DatabaseConnection """ Concerned with storing and retrieving books from a csv file Format of the csv file: name,author,read """ Book = Dict[str, Union[str, int]] def create_book_tables(): with DatabaseConnection() as connection: cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS books (name text primary key, author text, read integer)') def add_book(name: str, author: str): with DatabaseConnection() as connection: cursor = connection.cursor() cursor.execute('INSERT INTO books VALUES(?, ?, 0)', (name, author)) def get_all_books() -> List[Book]: with DatabaseConnection() as connection: cursor = connection.cursor() result = cursor.execute('SELECT * FROM books').fetchall() result = [{'name': row[0], 'author': row[1], 'read': row[2]} for row in result] print(result) return result def mark_book_as_read(name): with DatabaseConnection() as connection: cursor = connection.cursor() cursor.execute('UPDATE books SET read = ? WHERE name = ?', (1, name)) def delete_book(name): with DatabaseConnection() as connection: cursor = connection.cursor() cursor.execute('DELETE FROM books WHERE name = ?', (name,))
#!usr/bin/env python #coding=utf-8 import nwmath import unittest class addTest(unittest.TestCase): ''' Test the multiplyTest from the nwmath library ''' def test_add_integer(self): """ Test that subtracting integers returns the correct result """ result=nwmath.add(3, 4) self.assertEqual(result, 7) class divideTest(unittest.TestCase): ''' Test the multiplyTest from the nwmath library ''' def test_divide_integer(self): """ Test that subtracting integers returns the correct result """ result=nwmath.divide(64, 4) self.assertEqual(result, 16) class multiplyTest(unittest.TestCase): ''' Test the multiplyTest from the nwmath library ''' def test_multiply_integer(self): """ Test that subtracting integers returns the correct result """ result=nwmath.multiply(3, 4) self.assertEqual(result, 12) if __name__ =='__main__': unittest.main()
import datetime class numToWord: _dict20 = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'} _dictTens = { 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'} def __init__(self, n = None): self._number = n self._word = self.getword(n) def number(self, n = None): if n: self._number = n return self._number def word(self): return self._word def getword(self, n): if n < 0 or n >= 100: raise TypeError(f'Expected value between 0 and 99, got {n}.') if n >= 0 and n <= 19: w = self._dict20[n] elif n % 10 == 0: w = self._dictTens[n] else: a = (n // 10) * 10 b = n % 10 w = self._dictTens[a] + '-' + self._dict20[b] return w def __repr__(self): return f'{self.number()} - {self.word()}' class timeToWord: def __init__(self, t = None): if isinstance(t, datetime.time): self._time = t self._hour = t.hour self._minutes = t.minute else: raise TypeError(f'timeToWord expects a value of type datetime.time as an agrument, got {type(t)}.') self._tword = self.getWordFromTime(self._hour, self._minutes) def hourToWord(self, h): if h == 0: w = 'midnight' elif h == 12: w = 'noon' else: w = numToWord(h % 12).word() return w def minToWord(self, m): if m == 15: w = 'quarter' elif m == 30: w = 'half' else: w = numToWord(m).word() return w def getWordFromTime(self, hour, minutes): wHour = self.hourToWord(hour) nextHour = 0 if hour == 23 else hour + 1 wNextHour = self.hourToWord(nextHour) rMinutes = 60 - minutes wMinutes = self.minToWord(minutes) rMinutes = 60 - minutes wrMinutes = self.minToWord(rMinutes) if minutes == 0: wTime = wHour if (hour % 12) == 0 else wHour + " o'clock" elif minutes <= 30: wTime = wMinutes + ' past ' + wHour else: wTime = wrMinutes + ' till ' + wNextHour return wTime def __repr__(self): return self._tword def main(): x = 1 try: a = numToWord(x) print(a) b = a.number() c = a.word() print(b, c) except TypeError as e: print(f'Error: {e}') # test # for i in range(100): # print(f'{i}: {numToWord(i).word()}') now = datetime.datetime.now() try: tw = timeToWord(now.time()) print(tw) except TypeError as e: print(f'TypeError: {e}') # test time t1 = datetime.time(0,0) t2 = timeToWord(t1) print(t2) l = ((0, 0), (0, 1), (11, 0), (12, 0), (13, 0), (12, 29), (12, 30), (12, 31), (12, 15), (12, 30), (12, 45), (11, 59), (23, 15), (23, 59), (12, 59), (13, 59) ) tests = list() for i in l: tests.append(datetime.time(i[0], i[1])) for i in tests: print(f'{i} - {timeToWord(i)}') if __name__ == '__main__': main()
secret = 'swordfish' pw = '' count = 0 auth = False max_attempts = 5 while pw != secret: count += 1 if count > max_attempts: break pw = input(f'{count}: What is the secret word? ') else: auth = True print('Authorized.' if auth else 'Calling FBI...')
import sqlite3 def main(): print('Create DB connection') db = sqlite3.connect('My_DB-API.db') cur = db.cursor() cur.execute('DROP TABLE IF EXISTS my_table') cur.execute(""" CREATE TABLE my_table ( id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT ) """) cur.execute(""" INSERT INTO my_table (first_name, last_name) VALUES ('Ivan', 'Petrov'), ('Petr', 'Ivanov') """) db.commit() cur.execute(""" SELECT COUNT(*) FROM my_table """) res = cur.fetchone()[0] print(f'number of rows in my_table: {res}') print('\nContent of my_table:') for row in cur.execute('SELECT * FROM my_table'): print(row) db.close() if __name__ == '__main__': main()
def main(): x = [5] print(f'in main x is {x}') print(f'id x is {id(x)}') kitten(x) print(f'in main x is {x} after calling the function') print(f'id x is {id(x)}') def kitten(a): print(f'in function id a is {id(a)}') a[0] = 3 print(f'in function a is assigned to {a}') print(f'in function id a is {id(a)}') if __name__ == '__main__': main()
def main(): print("1. Create a list wich consists of elements of the other list which are multiplied by 2.") l1 = range(11) l2 = (i*2 for i in l1) print_list(l1) print_list(l2) print("\n2. Create a list which consists of elements of the other list that are not dividable by 3.") l3 = (i for i in l1 if i % 3 != 0) print_list(l1) print_list(l3) print("\n3. Create a list of tuples where one element is a figure and the other element is a squared of this figure.") l4 = [(i, i**2) for i in l1] print_list(l4) print("\n4. Create a list of pi values rounded to 0, 1, .., 10.") from math import pi l5 = [round(pi, i) for i in l1] print_list(l5) print("\n5. Create a dictionary: key is the digit, value is the squared digit.") d = {i: i**2 for i in l1} print(d) print("\n6. Create a set of letters which are in phrase 'superduper' and are not in string 'pd'") s = {i for i in 'superduper' if i not in 'pd'} print_list(s) def print_list(o): for i in o: print(i, end=' ') print() if __name__ == '__main__': main()
#!/usr/bin/python #word_count.py #python program to count the words in the line. class strcou: def method(self,str): self.str=str a=self.str.split() temp=[] for i in a: temp.append(i) if temp.count(i)>1: pass else: print i,a.count(i) z=strcou() z.method("""sandeep reddy chinna papanna svec tirupathi krishna puram""")
#!/usr/bin/python #head.py #python program to open the file, reading and printing. class head: def read1(self,file): self.f=file fd=open(self.f,'r') txt=fd.read() return txt class main(head): def method(self,nam,line): data=head.read1(self,nam) self.line=line s='' count=0 for i in data: if i!='\n': s=s+i else: print s s='' count+=1 if count==self.line: break a=main() a.method('reverse.txt',5)
""" Name : Word Count Author: Benjamin Wacha Email: bmwachajr Disc: A python app that counts the occurrence of a word in a string """ def words(string): dict = {} list = string.split() list.sort() for word in list: if word.isdigit(): word = int(word) if word in dict: dict[word] = dict[word] + 1 else: dict[word] = 1 return (dict)
__author__ = 'Renan Nominato' __version__ = '0.0.1' """" This script selects randomly words, and create multiple choice questions looking for the meaning. """ import pandas as pd import numpy as np import random as rn import os from gtts import gTTS import time questions = pd.read_csv("Planilha sem título - Vocab.csv") #dataframe with all tested words. #questions = questions[0:5][:] mistakes = [] mistakes = pd.DataFrame(mistakes) for i in range(0, len(questions)): questions = questions.sample(frac=1).reset_index(drop=True) #tts = gTTS("What is the meaning of " "{}" .format(questions.loc[0,'Word'])) #tts = gTTS ("{}".format (questions.loc[0, 'Word'])) #tts.save('hello.mp3') #os.system("mpg123 hello.mp3") print ("\n"*10) print('What is the meaning of ' '{} ?'.format(questions.loc[0,'Word'])) questions2 = questions[0:5][:] questions2 = questions2.sample(frac=1).reset_index(drop=True) if len(questions)> 0: print('0)' '{}'.format(questions2.loc[0,'Desc'])) if len (questions) > 1: print('1)' '{}'.format(questions2.loc[1,'Desc'])) if len (questions) > 2: print('2)' '{}'.format(questions2.loc[2,'Desc'])) if len (questions) > 3: print('3)' '{}'.format(questions2.loc[3,'Desc'])) if len (questions) > 4: print('4)' '{}'.format(questions2.loc[4,'Desc'])) print('') resp = int(input('Write your answer as the number in the choice:')) print('') if questions2.loc[resp,'Desc'] == questions.loc[0,'Desc']: print('You are right! ' '{}: {} - {}'.format(questions.loc[0,'Word'], questions.loc[0,'Desc'], questions.loc[0,'Tran'])) else: print('You are wrong. This word will be back on the mistakes list') mistakes = mistakes.append(questions.loc[0][:]) time.sleep(3) questions = questions.drop (questions.index[0]) #mistakes.to_csv("mistakes.csv") #clear = lambda: os.system('clear')
### delete function of BST #### class node: def __init__(self, value=None): self.value = value self.left_child = None self.right_child = None self.parent = None class binary_search_tree: def __init__(self): self.root = None def insert(self,value): if self.root == None: self.root = node(value) else: self._insert(value, self.root) def _insert(self, value, cur_node): if value < cur_node.value: if cur_node.left_child == None: cur_node.left_child = node(value) cur_node.left_child.parent = cur_node else: self._insert(value, cur_node.left_child) elif value>cur_node.value: if cur_node.right_child == None: cur_node.right_child = node(value) cur_node.right_child.parent = cur_node else: self._insert(value, cur_node.right_child) else: print('Value already in tree') def find(self,value): if self.root != None: return self._find(value,self.root) def _find(self, value, cur_node): if value == cur_node.value: return cur_node elif value < cur_node.value and cur_node.left_child != None: return self._find(value, cur_node.left_child) elif value > cur_node.value and cur_node.right_child != None: return self._find(value, cur_node.right_child) def delete_value(self,value): return self.delete_node(self.find(value)) def delete_node(self, node): def min_value_node(n): current =n while current.left_child: current = current.left_child return current def num_children(n): num_children = 0 if n.left_child: num_children += 1 if n.right_child: num_children += 1 return num_children node_parent = node.parent node_children = num_children(node) if node_children == 0: if node_parent.left_child == node: node_parent.left_child = None else: node_parent.right_child = None if node_children==1: if node.left_child: child = node.left_child else: child = node.right_child if node.parent.left_child == node: node_parent.left_child = child else: node_parent.right_child = child child.parent = node_parent if node_children == 2: successor = min_value_node(node.right_child) node.value = successor.value self.delete_node(successor) def print_tree(self): if self.root!=None: self._print_tree(self.root) def _print_tree(self, cur_node): if cur_node!=None: self._print_tree(cur_node.left_child) print(str(cur_node.value)) self._print_tree(cur_node.right_child) def height(self): if self.root != None: return self._height(self.root, 0) else: return 0 def _height(self, cur_node, cur_height): if cur_node== None: return cur_height left_height = self._height(cur_node.left_child, cur_height+1) right_height = self._height(cur_node.right_child, cur_height+1) return max(left_height, right_height) def search(self,value): if self.root != None: return self._search(value, self.root) else: return False def _search(self, value, cur_node): if value == cur_node.value: return True elif value < cur_node.value and cur_node.left_child != None: return self._search(value, cur_node.left_child) elif value > cur_node.value and cur_node.right_child != None: return self._search(value, cur_node.right_child) return False def fill_tree(tree, num_elems=100, max_int=1000): from random import randint for _ in range(num_elems): cur_elem = randint(0, max_int) tree.insert(cur_elem) return tree tree = binary_search_tree() #tree = fill_tree(tree) tree.insert(6) tree.insert(4) tree.insert(5) tree.insert(3) tree.insert(20) tree.insert(0) tree.print_tree() print(tree.root.value) print('Tree height ' + str(tree.height())) print(tree.search(3)) print(tree.search(30)) tree.print_tree() tree.delete_value(3) tree.print_tree()
from produto import produtos class estoque: def __init__(self): self.lista = [] self.total = 0.0 def cadastrar(self,produto, valor, tipo,quant_estoque): if len(self.lista) == 0: pro = produto(produto, valor, tipo, quant_estoque) self.lista.append(pro) print " " print '%s cadastrado com sucesso' % pro.getProduto() print " " print '%d %s(s) cadastrado(s) com sucesso' % (pro.getQuant(), pro.getProduto()) else: existe = False for i in range(len(self.lista)): if self.lista[i].getProduto() == produto: print '%s ja cadastrado no sistema'%produto existe = True break if existe == False: pro = produto(produto, valor, tipo, quant_estoque) self.lista.append(pro) print '%s cadastrado com sucesso' % pro.getProduto() print '%d %s(s) cadastrado(s) com sucesso' % (pro.getQuant(), pro.getProduto()) def vender(self,produto_vendido): total = 0 existe = False teste = False for i in range(len(self.lista)): if self.lista[i].getProduto() == produto_vendido: print '==> %s (%s). R$%.2f' % ( self.lista[i].getProduto(), self.lista[i].getTipo(), self.lista[i].getValor()) print " " quant_vendido = int(raw_input('Digite a quantidade que deseja vender: ')) estoque = self.lista[i].getQuant() teste = False if quant_vendido <= 0: print 'Valor invalido' teste = True continue elif estoque < quant_vendido: print 'Nao e possivel vender pois nao ha %s suficiente' % produto_vendido else: estoque -= quant_vendido self.lista[i].setQuant(estoque) total = quant_vendido * self.lista[i].getValor() print '==> Total arrecadado: R$%.2f ' % total existe = True break if existe == False and teste == False: print produto_vendido + ' nao cadastrado(a) no sistema.' return total def imprimir(self,total): for i in range(len(self.lista)): print ' %d) %s (%s). R$ %.2f' % ((i + 1), self.lista[i].getProduto(), self.lista[i].getTipo(), self.lista[i].getValor()) print ' Restante: %d' % self.lista[i].getQuant() print ' ' total += self.lista[i].getValor() * self.lista[i].getQuant() print ' Total arrecadado em vendas: R$%.2f ' % (total) print ''
import numpy as np import matplotlib.pyplot as plt n = 5 l = [0 for i in range(n)] nv=[0 for i in range(n)] for i in range(n): nv[i]=int(i+1) l[0] = 2**0.5 for i in range (1,n): l[i] = (2+ l[i-1]**0.5)**0.5 print((2+2**0.5)**0.5) print((2+(2+2**0.5)**0.5)**0.5) plt.plot(nv,l,".") plt.xlabel("n") plt.ylabel("$x_n$") plt.ylim(0,2) plt.show()
"""This module provides helper functionality with time.""" from datetime import timedelta DATE_FORMAT = "%Y.%m.%d" DATETIME_FORMAT = "%Y.%m.%d %H:%M:%S" def generate_days_period(start_date, end_date): """Yield days in provided date period.""" start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0) days_count = (end_date - start_date).days + 1 for n_days in range(days_count): yield start_date + timedelta(days=n_days)
""" David Rubio Vallejo Implements a CNN with an embedding layer consisting of the word vectors for the input words, a 2D convolutional layer with MaxPooling and Dropout, and an output layer mapping into a single neuron. A CNN model is typically represented as the four-tuple (N, C, H, W), where N = Batch size C = Channels (# of filters that the convolutional layer has) H = Length of the sentences ('H'eight of the feature-vector matrix, the # of rows) W = Length of each word-vector in a sentence ('W'idth of the feature-vector matrix, the # of columns) """ # coding: utf-8 import mxnet.gluon as gluon from mxnet.gluon import HybridBlock class CNNTextClassifier(HybridBlock): def __init__(self, emb_input_dim, emb_output_dim, num_classes=1, prefix=None, params=None): super(CNNTextClassifier, self).__init__(prefix=prefix, params=params) with self.name_scope(): # Embedding layer self.embedding = gluon.nn.Embedding(emb_input_dim, emb_output_dim) # 2D Convolutional layer self.conv1 = gluon.nn.Conv2D(channels=100, kernel_size=(3, emb_output_dim), activation='relu') # MaxPooling followed by dropout self.pool1 = gluon.nn.GlobalMaxPool2D() self.activation1 = gluon.nn.Dropout(0.2) # Output layer self.out = gluon.nn.Dense(num_classes) def hybrid_forward(self, F, data): # print('Data shape', data.shape) embedded = self.embedding(data) # print('Embedded shape',embedded.shape) x = self.conv1(embedded) x = self.pool1(x) x = self.activation1(x) x = self.out(x) return x
p1 = input().split(" ") x1 = float(p1[0]) y1 = float(p1[1]) p2 = input().split(" ") x2 = float(p2[0]) y2 = float(p2[1]) Distancia = ((x2-x1)** 2 + (y2-y1)** 2)**0.5 print (f'{Distancia:.5}')
# -*- coding: utf-8 -*- """ Created on Fri Jan 08 14:11:19 2016 @author: ashutoshsingh The file takes the turnstile data and runs a linear regression model on it. It also calculates the R-squared values and plots the graph of it """ import pandas as pd import numpy as np from ggplot import * from scipy import stats import matplotlib.pyplot as plt import statsmodels.api as sm import numpy as np import statsmodels.api as sm import pylab features = [ 'rain' , 'hour','weekday'] def linear_reg_using_ols(inputs,target): #we need an intercept so adding ones inputs = sm.add_constant(inputs) model = sm.OLS(target,inputs) result = model.fit() return result def r_square_result(data, predicted_values): data_mean = np.mean(data) ss_total = np.sum((data-predicted_values)**2) ss_reg = np.sum((data-data_mean)**2) r_squared = 1 - (ss_total/ss_reg) return r_squared #main function if __name__ == '__main__': #first read the files data = pd.read_csv('turnstile_weather_v2.csv') #generate a features list input_features = data[features] target = data['ENTRIESn_hourly'] #for dummy units dummy_vars = pd.get_dummies(data['UNIT']) input_features = input_features.join(dummy_vars) result = linear_reg_using_ols(input_features,target) #print result.summary() model = result.params print "Intercept : ", model[0] non_dummy_params = model[1:5] print non_dummy_params predictions = model[0] + np.dot(input_features.values, model[1:]) #print r_square_result(data['ENTRIESn_hourly'].values, predictions) print "R-Squared Value : ",result.rsquared #plot the residual curve residual_data = pd.DataFrame(data['ENTRIESn_hourly'].values - predictions, \ columns = ['residual']) plot = ggplot(residual_data, aes(x = 'residual')) + \ geom_histogram() + \ ggtitle('Residuals histogram') + \ xlab('Residuals') + \ ylab('Count') + \ xlim(-15000,15000) print plot ggsave('./plots/residual_curve.png',plot) #probability plot of the residuals sm.qqplot(residual_data['residual'].values, line='45') pylab.show()
#!/usr/bin/python n = input('Height (>4): ') if n < 2: print "WTF?! Your tree is too small ! I'll make it higher\n" n = 4 i = 1 while i <= n: print (n/3)*" " + (n-i)*' ' + (i-1)*'*_' + '*' i += 1 print "\nMerry Christmas!"
import json def registra_aluno(nome, ano_entrada, ano_nascimento, **misc): """Cria a entrada do registro de um aluno.""" registro = {'nome': nome, 'ano_entrada': ano_entrada, 'ano_nascimento': ano_nascimento} for key in misc: registro[key] = misc[key] return registro def escreve_registro(registro, arquivo): with open(arquivo, 'w') as f: json.dump(registro, f) registros = { 'alunos': [] } def adicionar_registro(nome, ano_entrada, ano_nascimento, registros, **misc): registros['alunos'].append(registra_aluno(nome, ano_entrada, ano_nascimento, **misc))
# How many distinct terms are there of the form a^b for 2\leq a,b\leq 100? # # Answer: 9183 import sets nums = sets.Set() for a in range (2,101): for b in range(2,101): nums.add(pow(a,b)) print len(nums)
# Find the largest palindrome made from the product of two 3-digit numbers. # # Answer: 906609 def is_pal(i): s = str(i) pal=True for j in range(1,len(s)/2+1): if(s[j-1] != s[-j]): pal=False break return pal pals = [] for i in range(100, 1000): for j in range(100,1000): if(is_pal(i*j)): pals.append(i*j) print max(pals)