text
stringlengths
37
1.41M
''' 我们创建一个 job, 分别用 threading 和 一般的方式执行这段程序并且创建一个 list 来存放我们要处理的数据. 在 Normal 的时候, 我们这个 list 扩展4倍; 在 threading 的时候, 我们建立4个线程, 并对运行时间进行对比. ''' import threading, copy, time from queue import Queue def job(l, q): res = sum(l) q.put(res) def multithreading(l): q = Queue() threads = [] fo...
''' 557. Reverse Words in a String III [Easy] Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each wo...
''' 10. Regular Expression Matching [Hard] Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). N...
''' 最简易版的聊天室服务端,仅用一个线程来收消息。只支持建立一个TCP socket连接。 [注意]: 1.socket连接的正常关闭(即双方都close)需要双方发送'exit'消息。 2.如果客户端主动断开,则服务端的收消息线程rec因为收到了'exit'消息所以跳出循环,终止线程, 但是主函数会因继续尝试给客户端发送消息而报错,因此主函数必须设置一个try/except捕捉exception; 但是客户端的收消息rec仍继续等待从已经断开了的socket收消息,则会报错,所以也必须设置try/except来避免bug。 同时因为服务端主函数的input()阻塞,所以服务端也该应该发出'exit'来正确...
#服务端 from socket import * import select server = socket(AF_INET, SOCK_STREAM) server.bind(('127.0.0.1',8093)) server.listen(5) # 设置为非阻塞 server.setblocking(False) # 初始化将服务端socket对象加入监听列表,后面还要动态添加一些conn连接对象,当accept的时候socket就有感应,当recv的时候conn就有动静 rlist=[server,] rdata = {} #存放客户端发送过来的消息 wlist=[] #等待写对象 wd...
''' [Pool] 如果要启动大量的子进程,可以用进程池的方式批量创建子进程: ''' from multiprocessing import Pool,cpu_count import os,time,random def task(name): print('result is %s' %(name**2)) return name**2 def long_time_task(name): print('Run task %s (%s)' % (name, os.getpid())) start = time.time() time.sleep(ran...
''' 509. Fibonacci Number [Easy] The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1. Given N, calculate F(N). Examp...
''' 69. Sqrt(x) (Easy) Method 1: Binary Search: O(lgn) ''' class Solution: def mySqrt(self, x: int) -> int: if x == 0: return 0 left, right = 1, x while left <= right: mid = left + (right - left) // 2 if mid == x // mid: return ...
import time import queue import threading def worker(i): while True: item = q.get() if item is None: print("线程%s发现了一个None,可以休息了^-^" % i) break # do_work(item)做具体的工作 time.sleep(0.5) print("线程%s将任务<%s>完成了!" % (i, item)) # 做完后发出任务完...
''' 92. Reverse Linked List II [Medium] Reverse a linked list from position m to n. 反转从位置 m 到 n 的链表。 Do it in one-pass. 请使用一趟扫描完成反转。 Note: 1 ≤ m ≤ n ≤ length of list. Example: Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL [Method 1]: 迭代 + dummy node + 多指针: 记住要反转部分的前一个节点 begin,要反转部分...
def largest_twice(nums): largest = second = 0 for i in range(len(nums)): if largest < nums[i]: second, largest = largest, nums[i] index = i elif second < nums[i]: second = nums[i] return index if largest >= second * 2 else -1 nums = [1, 2,...
''' 169. Majority Element [Easy] Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,...
''' 【动态规划】 0-1 背包问题 0/1 Knapsack Problem 完全背包问题 Unbounded Knapsack Problem 最小路径和(详细可看 Minimum Path Sum) 编程实现莱文斯坦最短编辑距离 编程实现查找两个字符串的最长公共子序列 编程实现一个数据序列的最长递增子序列 Note: 递归不是动态规划,不能混淆,二者有相通的地方:递归是自顶向下,动归是自底向上。 动归是递归综合备忘录算法以后的反向思维形式。 动态规划算法通常基于一个递推公式及一个或多个初始状态。 当前子问题的解将由上一次子问题的解推出。 使用动态规划来解题只需要多项式时间复杂度,...
''' 74. Search a 2D Matrix [Medium] Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: ...
''' 226. Invert Binary Tree [Easy] Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the ...
''' 剑指offer22. 链表中倒数第k个节点 输入一个链表,输出该链表中倒数第k个节点。 为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。 例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。 这个链表的倒数第3个节点是值为4的节点。 示例: 给定一个链表: 1->2->3->4->5, 和 k = 2. 返回链表 4->5. [Method 1]: 双指针一次遍历 当不允许求链表长度时,可以用一个fast指针先走k-1步,再用一个slow指针指向head, 使得两个指针之间相差k-1个节点,再同时让两个指针一起一步步地走,当fast走到最后一个...
''' 448. Find All Numbers Disappeared in an Array [Easy] Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You ...
''' 激活生成器主要有两个方法: 1. 使用next(generator),即不给生成器传任何参数, 如果生成器的yield语句为 received_value = yield some_value,则received_value为None; 2. 使用generator.send(None): send括号里是传给生成器的参数, 如果生成器的yield语句只是 yield some_value, 那么send括号里则只能为None; 如果语句为 received_value = yield some_value, 则send括号里的参数会被发送给生成器后 存在received_value这个变量里。 ''...
''' 9. Palindrome Number Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not...
''' 98. Validate Binary Search Tree [Medium] Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than th...
import unittest class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.push_stack = [] self.pop_stack = [] self.size = 0 def push(self, x): """ Push element x to the back of queue. :ty...
''' 【递归】 通过LeetCode上【70. 爬楼梯】学习(建议) ''' ''' 70. Climbing Stairs You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input...
class Tree: def __init__(self, label, branches=[]): self.label = label for branch in branches: assert isinstance(branch, Tree) self.branches = list(branches) def __repr__(self): if self.branches: branch_str = ', ' + ...
''' 136. Single Number Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2...
''' 75. Sort Colors [Medium] Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You ar...
''' 230. Kth Smallest Element in a BST [Medium] Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Example 1: Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1 Examp...
pwinicial = input('senha inicial \n') senha = '' for letra in pwinicial: if letra in 'Ss': senha = senha + '$' elif letra in 'Ii': senha = senha + '!' elif letra in 'Pp': senha = senha + '>' elif letra in 'Qq': senha = senha + '<' elif letra in 'Ee': senha = senha + '&' elif letra in 'Aa': senha...
class DivisorDigits: def howMany(self, number): numDigits = len(str(number)) count = 0 for digit in range(0, numDigits): if int(str(number)[digit])!=0 and number%int(str(number)[digit])==0: count += 1 return count a = 52527 x = DivisorDigits print(x.how...
# -*- coding: utf-8 -*- """ Created on Mon Jul 13 21:29:15 2015 @author: Wasit """ from turtle import * def leaf(size): init_pos=pos() init_head=heading() forward(size*0.5) left(30) for i in range(3): forward(size*0.5) right(120) setpos(init_pos) setheading(init_head) d...
# -*- coding: utf-8 -*- """ Created on Thu Sep 10 17:33:33 2015 @author: Wasit """ class Rect: def __init__(self, x,y,w,h): self.x=x self.y=y self.w=w self.h=h def __str__(self): return "x:%d y:%d w:%d h:%d"%(self.x,self.y,self.w,self.h) if __name__ ==...
""" Rain simulation Simulates rain drops on a surface by animating the scale and opacity of 50 scatter points. Author: Nicolas P. Rougier """ import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Create new Figure and an Axes which fills it. fig = plt.figure(figsize=(7...
from itertools import zip_longest def grouper(iterable, n, fillvalue=None): """Collect data into fixed-length chunks or blocks >>> tuple(map(''.join, grouper('ABCDEFG', 3, 'x'))) ('ABC', 'DEF', 'Gxx') >>> tuple(grouper('ABC', 2)) (('A', 'B'), ('C', None)) """ args = [iter(iterable)] * ...
# toh.py # to be completed for the CSE 512 midterm, Winter 2016 # # STUDENT NAME: Yazhuo Liu 004194007 # *** MIDTERM *** # COMPLETE THIS MODULE BY REPLACING EACH OCCURRENCE OF 'pass' WITH THE # PYTHON CODE THAT WILL IMPLEMENT THE DESCRIBED FUNCTIONALITY. # TEST by loading and RUN-ing file astar_s...
import turtle turtle.goto(0,0) DOWN = 1 LEFT = 2 RIGHT = 3 UP = 0 direction = None def up(): global direction direction = UP print("you pressed the up key.") on_move(10,20) def down(): global direction direction = DOWN print("you pressed the down key.") on_move(10,20) def left(): g...
class Node: def __init__(self, key): self.key = key self.next = None class LL: def __init__(self, key): head = Node(key) self.head = head def push(self, key): node = Node(key) node.next = self.head self.head = node def printList(self): n...
class Node: def __init__(self, key): self.key = key self.left = None self.right = None def height(r): height = 0 s = r while s: height += 1 s = s.left return height def printVS(r, level): if not r: return if 1 == level: print r.key elif l...
#!/usr/bin/env python # -*- coding: UTF-8 -*- def supported_scales(): print("F - Fahrenheit") print("K - Kelvin") print("F - Celsius") print("RE - Réamour") print("RA - Rankine") print("N - Newton") print("D - Delisle") print("RO - Rømer") def get_fahrenheit(t, e): if e.upper() == ...
# lab02# sal = int(input("What is your salary? (Please enter value between 0 and 100) \n")) kid1 = input("Do you have children? Y/N \n") kid = kid1.upper() if (30 <= sal < 50) and (kid == 'N'): print("Your Tax is 40") elif (30 <= sal < 50) and (kid == 'Y'): print("Your Tax is 35") elif (50 <= sal < ...
import streamlit as st import numpy as np import pandas as pd from PIL import Image st.title("Streamlit 超入門") st.write("Display Image") img = Image.open("img/untitled2.jpg") st.image(img, caption="flower", use_column_width=True) #st.write("DataFrame") #df = pd.DataFrame( # np.random.rand(100,2)/[50,50] + [35.69,...
# /usr/bin/env python # -*- coding:utf-8 -*- ''' L = ['A','B','C'] for name in L: print('hello '+ name) while True: print (123) #continue break print (456) li = [11,22,33] for k,v in enumerate(li, 1): print(k,v) ''' # 一、元素分类 # # 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个...
class analyzer(): def __init__(self, cname, target_grade, grade_details, db): self.cname = cname self.target_grade = target_grade self.comment_format = "|{0:^60}|" self.total_mark, self.total_weight = db.sum_weight(cname) self.total_lost_marks = self.total_weight - self.total...
import pygame from .env import * # class HightWay(): # def __init__(self): # # lanes is collection of lane and lane is a rect with white color # self.lanes = [] # pass # # def draw(self,screen): # # TODO screen blit way here # pass # # def update(self,car): # ...
from argparse import ArgumentParser def get_parser_from_dict(parser_config: dict): """ Generate `argparse.ArgumentParser` from `parser_config` @param parser_config A dictionary carries parameters for creating `ArgumentParser`. The key "()" specifies parameters for constructor of `ArgumentParser...
# Square Gradient generator by RaddedMC # Did this instead of sleeping or doing uni homework -- have fun :D # pip install Pillow numpy from PIL import Image, ImageDraw import numpy ## USER-CONTROLLED VARIABLES ## startColor = (234,80,255) # Color #1 endColor = (255,255,0) # Color #2 resolution = (1920,1080) # Image r...
#%% [markdown] # # Train your first neural network: basic classification # In this notebook you will make a program that recognize hand written letters. # But this is not a image recognition app, at least not a typical one. # The letter data is in form of trace. A trace registered by digital tablet, the time and x, ...
"""The N-pieces puzzle""" # Further changes - mkings checking, noard array, changing board size, other pieces, etc. class NPieces: """Generate all solutions for N-pieces puzzle for specified piece and board size""" def __init__(self, size, piece): # Store the puzzle (problem) size and the number of v...
hour= float(input("Enter the hours: ")) minutes= float(input("Enter the minutes: ")) seconds= float(input("Enter the seconds: ")) if 0<hour>23: print("Your time is invalid") if 0<minutes>59: print("Your time is invalid") if 0<seconds>59: print("Your time is invalid") elif (hour,minutes,seconds): print("Your...
a = eval(input('Enter the start point N: \n')) b =eval(input('Enter the start point M: \n')) a += 1 for i in range(a,b): y = True if(str(i) == str(i)[::-1]): if(i>2): for a in range(2,i): if(i%a==0): y = False break if y: print(i)
string = input("Input new string: ") string = str(string) reverse = string[::-1] if(reverse == string): print("It is a palindrome") else: print("It is not a palindrome")
a = int(input("Unesi broj: ")) if (a % 2 == 0): print("Broj je paran") else: print("Broj je neparan")
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import numpy as np import matplotlib.pyplot as plt print("\TALLER #3 - Graficando funciones...sen(x), cos(x), tan(X) y transformadas.") # 0. Preliminares def to_rad(c): return(c*math.pi/180) def to_deg(r): return(r*180/math.pi) def factorial(n): ...
N = int(raw_input()) num = [int(i) for i in raw_input().split()] if N != len(num): print 'Not matching' print sorted(list(set(num)))[-2]
def Mean(arr,l): s = sum(arr) mean = s/(l*1.0) return "{0:0.1f}".format(mean) def Median(arr, l): arr.sort() if l%2 == 0: median = (arr[l/2]+arr[(l/2)-1]) / 2.0 else: median = arr[l/2] return "{0:0.1f}".format(median) def Mode(arr): d = {} mode = 0 ...
def quartile(arr): l = len(arr) if l%2 == 0: q = (arr[(l/2)-1]+arr[l/2]) / 2 else: q = arr[l/2] return q if __name__ == '__main__': n = int(raw_input()) X = [int(i) for i in raw_input().strip().split()] X.sort() if n%2 == 0: low = (n/2) - 1 ...
# import math # import random # import sys class Player: def __init__(self, letter): self.letter = letter def get_move(self, game): pass # super() function will create a class that will inherit all the methods and properties from another class: # The isinstance() function returns True if the ...
import sys words = 'I used splitlines on the list and then assigned the proper listing to a new variable' # print(words.splitlines()) # splitlines can only be used on a string and in this case you cannot paste a vertical list # of words like I did above because a string cannot extend to multiple lines without the \ c...
import requests from requests import ConnectionError from urllib3.exceptions import ResponseError class XkcdAPIUnavailable(Exception): pass def get_comics_count(): url_comics = "https://xkcd.com/info.0.json" try: response = requests.get(url_comics) if not response.ok: raise R...
from insert import ajouter_plante , consulter,supprimer,rechercher print( "que souhaitez vous faire") print("C = CONSULTER ") print("A = AJOUTER ") print("S= SUPPRIMER ") print("R=RECHERCHER") choix=input("que choisissez-vous ") if choix.upper()== "A": id = 10 nom = input("nom de la nouvelle plante") i...
>>> # объявление функции def draw_triangle(fill, base): l = [i for i in range(1,base//2+2,)] l.extend([i for i in range(base//2, 0, -1)]) for elem in l: print(fill * elem) # считываем данные fill = input() base = int(input()) # вызываем функцию draw_triangle(fill, base)
# - Import random # - Engine # - Play function # - Map # - next_scene function # - opening_scene function # - Scenes # - Intro/entry scene(broom closet) # - Enter # - Room and game description # - Action input from user # - Exit leads to hallway # - Hallway #...
#Recall last exercise that you wrote a function, word_lengths, #which took in a string and returned a dictionary where each #word of the string was mapped to an integer value of how #long it was. # #This time, write a new function called length_words so that #the returned dictionary maps an integer, the length of...
#Copy your Burrito class from the last exercise. Now, add #a method called "get_cost" to the Burrito class. It should #accept zero arguments (except for "self", of course) and #it will return a float. Here's how the cost should be #computed: # # - The base cost of a burrito is $5.00 # - If the burrito's meat is ...
#Write a function called get_grade that will read a #given .cs1301 file and return the student's grade. #To do this, we would recommend you first pass the #filename to your previously-written reader() function, #then use the list that it returns to do your #calculations. You may assume the file is well-formed. # ...
#Write a function called "reader" that reads in a ".cs1301" #file described in the previous problem. The function should #return a list of tuples representing the lines in the file like so: # #[(line_1_number, line_1_assignment_name, line_1_grade, line_1_total, line_1_weight), #(line_2_number, line_2_assignment...
key1=[1,2,3] str1=['a','b','c'] print (key1) print (key1*2) print (key1*3) key2 = key1 + str1 print (key2) del key1[2] print (key1) key1[1]='aab' print (key1) print() print("列表查找") str2=[13,2,23,5] print (str2.index(5)) print() print("列表插入") key1.insert(1,'a1') print (key1) print() print("列表追加") key1.append('ccc') ...
import math N = int(raw_input("Enter N:")) R_i = raw_input("Enter R's seperated by a space: ") M = int(raw_input("Enter M: ")) coor_list = [] if M > 1: for i in range(M): coordinate = raw_input("Enter coordinates: ") coor_list.append(coordinate) else: coordinate = raw_input("Enter coordinates: ") ...
""" 两个数组的交集,考虑顺序问题所以先sort了一下,如果不sort则蜕变为最长公共子串问题 """ num1 = [4, 4, 8] num2 = [4, 2, 5, 4, 13] print("Input two list :") print(num1) print(num2) small = 0 big = 0 common = [] num1.sort() num2.sort() for i in num2: if small < len(num1): if num1[small] == num2[big]: common.append(...
import os from Rule import * # This function creates a new rule, asking the user to enter different information about the rule. # Each information entered by the user is stored in a dictionary. Before sending this new rule into our database, # we check if there are rules with the same id entered, or having a higher i...
# Now, we don't just want our computer to be able to do preset calculations - # we want it to respond to different situations; otherwise we might as well # do the maths using just a calculator! # We can do this using inputs. print("Type your name:") name = input() print("Your name is " + name + ". I hope that isn't...
from nltk.stem import SnowballStemmer from collections import defaultdict def decompound(word, vocabulary): '''Decompounds a word. This function tries to split a given word up into combinations of different words from a given vocabulary. Example: - decompound('toothbrush', ['tooth', 'brush']) => [['tooth...
# 1. import Flask from flask import Flask, jsonify app = Flask(__name__) @app.route("/") def trip(): print("All available routes") r return( f"<br/>" f"/api/v1.0/precipitation<br/>" f"<br/>" f"/api/v1.0/stations<br/>" f"<br/>" f"/api/v1.0/tobs<br/>" f"<b...
import pygame from .Pieces import * from .constants import * class newBoard: def __init__(self, Width, Height, Rows, Cols, Square, Win): self.Width = Width self.Height = Height self.Square = Square self.GameBoard = self.Width//2 self.Win = Win self.Rows = Rows ...
asignaturas = ["Matemáticas", "Física", "Química", "Historia", "Lengua"] notas = [] for asignatura in asignaturas: nota = input("¿Qué nota has sacado en " + asignatura + "?") notas.append(nota) for i in range(len(asignaturas)): print("En " + asignaturas[i] + " has sacado " + notas[i])
class Telefono(): def __init__(self,marca,color,precio): self.marca = marca self.color = color self.precio = precio self.encendido=False def encender(self): self.encendido=True def estado(self): if(self.encendido): return "El tele...
import turtle import random import lsystem """ Randomizes the lsystem and sets the turtle position args: snap(turtle) return: fn (text file) """ def randLsystem(snap): fn = "Rules" + str(random.randint(2,3)) + ".txt" if(fn == "Rules3.txt"): snap.setpos(-325,325) else: snap.setpo...
#字典的数据类型 a={} print(type(a)) a["one"]="this is number 1" a["two"]="this is number 2" print(a) print(a['one']) a["one"]="this is number 1,yeal" print(a) b={'one':'this is apple','two':'this is banana'} print(b['one']) #用dict初始化字典 inventory=dict([('a',123),('b',456),('c',789)]) print(inventory) inventory['a']+=1 pr...
class Node(object): def __init__(self,data,next=None): self.data = data self.next = next class linkOne(object): def __init__(self): self.head = None self.tail = None self.count = 0 def isEmpty(self): return self.count==0 def size(self): return self...
#!/usr/bin/python3 # -*- encoding: utf-8 -*- class Lnode: def __init__(self, elem, next_=None): ##初始化链表,并结点的next赋None self.elem = elem self.next = next_ llist1 = Lnode(1) ##头结点 p = llist1 for i in range(2, 11): p.next = Lnode(i) ##创建新的结点 p = p.next p = llist1 ###p重新指向表头 遍历所有的结点输出...
# Course: CS261 - Data Structures # Student Name: Nick Askam # Assignment: 6 # Description: Undirected Graph implementation, to add, track, remove edges and vertices. Also, tell if there's a cycle # , valid path, and count the connected import heapq class UndirectedGraph: """ Class to implement...
import re import json from src.logger import logger from src.utils import Util class AnaHelper(): @staticmethod def is_condition_match(left_operand, operator, right_operand): match = 0 if operator != "IsNull": if left_operand is None or right_operand is None: retu...
def levi_civita(dtype=float): """ Build the 3-D Levi--Civita matrix :param dtype: data type of the matrix :return: Levi--Civita matrix :rtype: ndarray(3, 3, 3) """ from numpy import zeros e_tensor = zeros([3, 3, 3], dtype=dtype) for i in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]: e...
''' Name: Rohit Nachaloor Date: 04/05/2019 Mastery Project Period: 1 Cowart ''' import mysql.connector as SQL def final(): #establishes connection to database dbGrade = SQL.connect( host='localhost', user='root', passwd='123456', database='grades' ) mycursor = dbGrade....
# coding: utf-8 # # Handwritten Number Recognition with TFLearn and MNIST # # In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. # # This kind of neural network is used in a variety of real-world applications including: recognizing phone numbers and sorting postal mail by...
# simple class to house code for median filter import math class filter: def __init__(self, reserved): self.data = [None] * reserved self.sorted = [] self.reserved = reserved # adding a value def add(self, value): if len(self.data) == self.reserved: self.data....
tags = ['python', 'development', 'tutorials', 'code'] tag_range = tags[1:2] print(tag_range) # => development tag_range = tags[1:3] print(tag_range) # => development, tutorials tag_range = tags[1:] print(tag_range) # => development, tutorials, code tag_range = tags[:3] print(tag_range) # => python, development, t...
post = ('Python Basics', 'Intro guide to Python', 'Some python content') tags = ['python', 'coding', 'tutorial'] post += (tags,) # remember that the comma indicates this is intended to be a tuple # => This will add the list tags to the end of the tuple post print(post) # => ('Python Basics', 'Intro guide to Pytho...
def weird_string_converter(input_text): x = 0 result = "" while x < len(input_text): if x % 2 == 0: result += input_text[x].upper() else: result += input_text[x].lower() x += 1 return result if __name__ == "__main__": print(weird_string_converter("Moi...
def nb_year(p0, percent, aug, p): """In a small town, the population is p0 at the beginning of a year. The population regularly increases by X percent per year and moreover Z new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p inhabit...
def camelcase(input_text): """Camel Case text generator. All words must have their first letter capitalized without spaces. """ words = input_text.split() result = "" for word in words: result += f'{word[0].upper()}{word[1:]}' return result if __name__ == "__main__": print(cam...
def setalarm(employed, vacation): """Function that determines whether alram is needed or not. The function should return true if you are employed and not on vacation (because these are the circumstances under which you need to set an alarm). It should return false otherwise. """ if employed == True and...
def change(order, money): """Bob's Coffee Shop order and change automat. Returns client ordered coffee when given exact amount of money, if not, asks to return the next day. """ menu = { "Americano" : 2.20, "Latte" : 2.30, "Flat white" : 2.40, "Filter" : 3.50 } i...
import re def checkbook_calc(filename: str): """Checkbook cleaner and summarizer. Cleans unnecessary characters and provides beautiful summary. """ with open(filename, "r", encoding="utf-8") as f: checkbook_data = f.read() checkbook_data = checkbook_data.split("\n") balance = float(ch...
def points(e): return e['points'] def name(e): return e['name'] def position_ranking(): contestants = [ { 'name': "John", 'points': 100, }, { 'name': "Bob", 'points': 130, }, { 'name': "Mary", 'points': 120, }, { 'name': "Kate", 'points': 120, } ] contestant...
def phone_number_hider(number): number = list(number) for x in range(5, 12): if number[x].isnumeric(): number[x] = "X" number = "".join(number) return number if __name__ == "__main__": print(phone_number_hider("201-680-0202"))
from card import Card import random class Deck(): def __init__(self): self.values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] self.suites = ['Hearts', 'Clubs', 'Diamonds', 'Spades'] self.cards = [] def construct_deck(self): for value in self.values: ...
email = raw_input("Enter your email text here:\n") if email.find('emergency') == 0: print "Do you want to make this email urgent?" elif email.find('joke') == 0: print "Do you want to set this email as non-urgent?" else: print "Mail sent, without special instructions"
import random class Item(object): def __init__(self, n, v, w): self.name = n self.value = v self.weight = w def getName(self): return self.name def getValue(self): return self.value def getWeight(self): return self.weight def __str__(self): ...
import sympy import math from sympy import Symbol, solve, sin, Limit, S, oo theta = Symbol('theta') # math.sin(theta) """ There's an error here. Can't get mathematical sinus. Because theta isn't a mathematical magnitude. Burada hata var. Matematiksel sinüs alamıyor. Çünkü theta matematiksel bir büyüklük değil. """ ...
print('Лабораторная работа №12') print() print('Название программы : Текст') print('Назначение программы : Работа с текстом') print() print() print() text = [' Приветствую каждого читателя. Сегодня я с радостью ', ' расскажу Вам прекрасный рецепт лабораторной ', ' работы по программиро...
#1 print all integers from 0 to 150 for x in range (151): print(x) #2 Multiples of Five - Print all the multiples of 5 from 5 to 1,000 for m in range (5, 1001, 1): if (m % 5 == 0): print(m) #3 Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print ...