text
stringlengths
37
1.41M
""" Solution for Algorithms #412: Fizz Buzz - Time Complexity: O(N) - Space Complexity: O(N) Runtime: 52 ms, faster than 90.93% of Python3 online submissions for Fizz Buzz. Memory Usage: 14.1 MB, less than 78.99% of Python3 online submissions for Fizz Buzz. """ class Solution: def fizzBuzz(self, n: int)...
""" Set + Filter solution for Algorithms #301: Remove Invalid Parentheses - Space Complexity: O(N) - Time Complexity: O(2^N) Runtime: 284 ms, faster than 26.67% of Python3 online submissions for Remove Invalid Parentheses. Memory Usage: 14 MB, less than 13.95% of Python3 online submissions for Remove Invalid Parenthe...
""" Solution for Algorithms #20: Valid Parentheses Runtime: 36 ms, faster than 87.97% of Python3 online submissions for Valid Parentheses. Memory Usage: 13.2 MB, less than 5.22% of Python3 online submissions for Valid Parentheses. """ class Solution: def isValid(self, s: str) -> bool: paren_stack =...
class Solution: def reverse(self, x: int) -> int: x_str = str(x) reversed_x_str = x_str[::-1] if reversed_x_str[-1] == '-': reversed_x = -1 * int(reversed_x_str[:-1]) else: reversed_x = int(reversed_x_str) if reversed_x < - (2 ** 31) or reversed_x > ...
""" Solution for July LeetCoding Challenges Week 4 Day 5: Add Digits """ class Solution: """ Repeat until the number is less than 10. Space : O(1) ------------ Nothing taking up space other than a few variables. Time : ? ----------- Difficult to determine. Runtime: 24 ms / 97.30% ...
""" Solution for August LeetCoding Challenges Week 3 Day 5: Numbers With Same Consecutive Differences """ from collections import deque class Solution: """ Use BFS to append digits one by one. Space : O(2^N) ------------ At any time, the BFS queue only holds sequences that are either length L or ...
""" Solution for Algorithms #238: Product of Array Except Self. - N: Length of `nums` - Space Complexity: O(1) - Excluding the output array - Time Complexity: O(N) Runtime: 92 ms, faster than 98.49% of Python3 online submissions for Product of Array Except Self. Memory Usage: 20.8 MB, less than 11.10% of Python3 on...
""" Dynamic programming solution for Algorithms #139 (Word Break). - N: len(s) - Space Complexity: O(N) - Time Complexity: O(N^3) - Substring operation: O(N) Runtime: 32 ms, faster than 99.04% of Python3 online submissions for Word Break. Memory Usage: 12.9 MB, less than 99.29% of Python3 online submissions for Wor...
""" DoubleLinkedList + Dict Solution for Algorithms #146: LRU Cache - GET Time Complexity: O(1) - PUT Time Complexity: O(1) Runtime: 148 ms, faster than 36.82% of Python3 online submissions for LRU Cache. Memory Usage: 22 MB, less than 33.26% of Python3 online submissions for LRU Cache. """ class DoubleLinkedListNode...
""" Solution for Algorithms #19: Remove Nth Node From End of List Double-pass. Runtime: 40 ms, faster than 92.06% of Python3 online submissions for Remove Nth Node From End of List. Memory Usage: 13.2 MB, less than 5.60% of Python3 online submissions for Remove Nth Node From End of List. """ # Definition for singly-l...
""" Non-string-sorting solution for Algorithms #49: Group Anagrams. - N: Number of strings - K: Maximum length of strings - Space Complexity: O(NK) - Time Complexity: O(NK) - Generate key: O(K) Runtime: 128 ms, faster than 41.78% of Python3 online submissions for Group Anagrams. Memory Usage: 17.7 MB, less than 17....
def turn(direction): """turns to the next wall""" if direction == "left": wall += 1 elif direction == "right": wall -= 1 else: invalid() if wall == 1: front() elif wall == 2: left() elif wall == 3: back() elif wall == 4: right() ...
#!/usr/bin/env python3 number=23 guess=int(input('Enter number:')) if guess==number: print('You WIN') print('Not priz') elif guess<number: print('Number>guess') else: print('number<guess') print('End GAME')
#!/usr/bin/env python3 def printMax(x, y): '''Print max from two number. Each may be INT.''' x=int(x) y=int(y) if x>y: print(x, 'max') else: print(y, 'max') printMax (3, 5) print (printMax.__doc__) help(printMax)
#!/usr/bin/env python3 age=26 name='Serhii' print('Age {0} -- {1} year.'.format(name, age)) print('Why {0} play this Python?'.format(name))
'''Python Programe to print fibonacci numbers from 1 to n "Buzz" when F(n) is divisible by 3. "Fizz" when F(n) is divisible by 5. "FizzBuzz" when F(n) is divisible by 15. "BuzzFizz" when F(n) is prime. the value F(n) otherwise. Author: Nisarg Pandya (nisargypandya@gmail.com) ''' #Get two numbers from...
#!/usr/bin/python import math r1 = {'milk': 100, 'flour': 4, 'sugar': 10, 'butter': 5} r2 = {'milk': 100, 'butter': 50, 'cheese': 10} r3 = {'milk': 2, 'sugar': 40, 'butter': 20} l1 = {'milk': 1288, 'flour': 9, 'sugar': 95} l2 = dict([('milk', 198), ('butter', 50), ('cheese', 10), ]) l3 = {'milk': 5, 'sugar': 120, 'b...
# Written: 01/31/2015 from fractions import Fraction from numbers import Number class Matrix(): """ Defines a Matrix Ryan Forsyth 2015 """ # Redefining Built-in Functions def __init__(self, values): """ Constructor for a matrix object. Pass in argument...
# -*- coding: utf-8 -*- name = str(raw_input('What\'s your name? ')) print('Hello, ' + name + '!!')
##print("What is your name?") ##name = input() ##print("Hello " + name + "!") ## ##print("How many states are in the USA?") ##answer = input() ##if answer == "50": ## print("Correct!") ##else: ## print("WRONG!!!!!") ## ##print("How old are you?") ##age = input() ##if age == "18": ## print("You are an adult now...
#!/usr/bin/python3 """Test this host's Internet connection. Returns 0 if Internet is reachable""" import requests def test_web(url): """Return True if a HTTP GET request of the URL returns a 200 code.""" r = requests.get(url) return r.status_code == requests.codes.OK def test_ping(host): """Return Tr...
import sys numeralValues = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } def numeralToDecimal(numeral): total = 0 lastValue = 0 for symbol in reversed(numeral): currentValue = numeralValues[symbol] if lastValue > currentValue: ...
def my_min(*args): result = args[0] for num in args: if num < result: result = num return result print(my_min(4, 3, 2, 1))
import pandas as pd import numpy as np import plotly.express as px class DrawManager(): def __init__(self): pass def create_fig(self,df,df_attribute = []): if df_attribute == []: df_melt = df.melt(id_vars=["Datum", "Tid (UTC)"], value_vars=df.columns[2]) #supposed the first column ...
# PPHA 30535 # Spring 2021 # Homework 1 # Zachary Obstfeld # ZacharyObstfeld # Due date: Sunday April 11th before midnight # Write your answers in the space between the questions, and commit/push only this file to your repo. # Note that there can be a difference between giving a "minimally" right answer, and a really...
''' Finding the longest common prefix ''' def LCP(arr): if arr is None: return "" pre = arr[0] for i in range(1, len(arr)): while arr[i].find(pre) != 0: pre = pre[0: len(pre) - 1] if len(pre) == 0 : return "" return pre def findDuplicate(nums): ...
''' Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycl...
# Course Schedule # A collection of courses at a University has prerequisite courses that must be taken first. Given an # array of course pairs [a, B] where A is the prerequisite of B, determine a valid sequence of courses # a student can take to complete all the courses # Parameters # Input: courses [[String]] # Out...
def generatePascalTriangle(numRows): if numRows == 0: return [] S =[[1]] if numRows == 1: return S for i in range(1, numRows): temp = [1] for j in range(1, i): print(temp) val = S[i - 1][j - 1] + S[i - 1][j] temp.append(val) te...
class HashTable: '''Hashtable implementation with python list using linear probing. Attributes: -_size: number of key-value entries in hashtable. -_slots: size allocated for key-value entries. Default value is 11 (integer). -_keys: list for key entries. -_va...
class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def findMid(start, end, nums): if start <= end: mid = (start + end) // 2 root = TreeNode(nums[mid]) root.left =...
''' CTCI Q8.3: Finding the magic index in a sorted array ''' def magicIndex(arr): ''' Arr has no dupes. Time: O(n) ''' return getIndex(arr, 0, len(arr) - 1) def getIndex(arr, start, end): if end < start: return -1 mid = (start + end) // 2 if arr[mid] == mid: return mid ...
def narcissistic(value): sum = 0 power = len(str(value)) for i in str(value): sum += int(i)**power if sum == value: return True else: return False
def to_weird_case(string): string_list = string.split(" ") weird_case = "" for word in string_list: for i in range(0,len(word)): if i%2 == 0: weird_case += word[i].upper() else: weird_case += word[i].lower() weird_case += " " return weird_case[:-1]
def ackermann(m, n): print('A({},{})'.format(m, n)) if m == 0: return n + 1 if n == 0: return ackermann(m - 1, 1) n2 = ackermann(m, n - 1) return ackermann(m - 1, n2) print(ackermann(2,2))
# This python file creates classes and methods to perform operations on vectors import math class Vectors: def __init__(self, coordinates): """ Initializing a vector with coordinates :param coordinates: represent the coordinates of the vector """ try: if not coo...
#!python3 from prefixtreenode import PrefixTreeNode class PrefixTree: """PrefixTree: A multi-way prefix tree that stores strings with efficient methods to insert a string into the tree, check if it contains a matching string, and retrieve all strings that start with a given prefix string. ...
#Matthew Beer #28/09/2014 #Revision exercise 4 - Selection num1 = int(input("Please enter a number ")) num2 = int(input("Please enter asecond number ")) if num1 > num2: print("The biggest number is {0}.".format(num1)) else: print("The biggest number is {0}.".format(num2))
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import matplotlib.pyplot as plt print('-'*10 + "Welcome to Data Vault" + '-'*10) print("\nThis is the original data") df=pd.read_csv("Data_Vault_Final1.csv") df # In[45]: # targetting only products # print("The below data only shows PRODUCTS colu...
import gspread from google.oauth2.service_account import Credentials SCOPE = [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive" ] CREDS = Credentials.from_service_account_file('livehealthy_creds.json') SCOPED_CREDS = ...
import numpy as np import matplotlib.pyplot as plt import csv def estimate_coef(x,y): n=np.size(x) mean_x=np.mean(x) mean_y=np.mean(y) mean_xy=np.mean(x*y) mean_xx=np.mean(x*x) #ss_xy=np.sum(y*x-n*mean_x*mean_y) #ss_xx=np.sum(x*x-n*mean_x*mean_x) ss_xy=mean_x*mean_y-mean_xy ss_xx=m...
import numpy as np import pandas as pd from sklearn import linear_model df =pd.read_csv('E:\\Programming\\Python\\Machine Learning\\Linear regression\\Datasets\\housepricing.csv') # Read file reg = linear_model.LinearRegression() # Linear regression model reg.fit(df[['area','bedrooms','age']],df.price) # De...
from enum import Enum from typing import List, NamedTuple class SongInfo(NamedTuple): '''Represents a minimal tuple of the necessary song info.''' level: int name: str difficulty: int class NoteDirection(str, Enum): '''Enum of possible `FFRNote` direction values''' LEFT = 'L' DOWN = 'D' ...
# Cian Doyle # G00335783 # Graph Theory def followes(state): """Return set of states that can be reached from state following e arrows.""" # Create a new set with state as it's only member states = set() states.add(state) # Check if state has arrows labelled e from it. if state.label is...
# The sum of the squares of the first ten natural numbers is, # 1**2 + 2**2 + ... + 10**2 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)**2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 3...
# -*- coding: utf-8 -*- import itertools import operator import statistics def join_list(l, separator=u", ", last_separator=u" и "): if len(l) == 0: return "" if len(l) == 1: return l[0] return separator.join(l[:-1]) + last_separator + l[-1] def tweet_with_list(tweet_variant_wo_list, ...
# Simple input parser based on ConfigParser # Only additions are echoing. # ConfigParser follows format of common INI files with substitutions. import configparser class InputParser(configparser.SafeConfigParser): def __init__(self): # super(InputParser, self).__init__(self) configparser.SafeConfi...
#prints print "mary had a little lamb" #prints print "its fleece was white as %s." % 'red' #prints print "and everywhere that she went" #prints the letter a 10 times print "a" * 10 #prints the word test 10 times print "test" * 10 #variables end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "e" ...
""" THE NUMPY ARRAY OJECT: """ import numpy as np # The numpy array object """ Numpy Library is the data structures for representing multidimentional arrays of homogenious data Homogeneous referes to all the elements in the array having the same data type In addition to data stored in the array it contains the m...
# -*- coding: utf-8 -*- """ Created on Sun Feb 14 21:34:33 2021 @author: ASUS """ #plotting basic #import pyplot from matplotlib import matplotlib.pyplot as plt x_day =[1,2,3,4,5] y_price1 =[9,9.5,10.1,10,12] y_price2 =[11,12,10.5,11.5,12.5] #define chart element plt.title("stock movement") plt.xlabel("week days") plt...
#集合set 无序,唯一性 #定义集合 ss=set() l=[1,23,4,45,65,77] s1=set(l) #print(s)# {65, 1, 4, 45, 77, 23} s2={1,3,2} s3={1,2,4} #交集 '''print(s2.intersection(s3))#{1, 2} print(s2&s3) #{1, 2}''' #并集 '''print(s2.union(s3))#{1, 2, 3, 4} print(s2|s3) #{1, 2, 3, 4}''' #差集 '''print(s2-s3) #{3} print(s3-s2) #{4} print(s2.difference(s3))#{...
########类型转换 a=int(5.9) # 直接取整,不会四舍五入 float(1) #1.0 bool(-5)#True bool(5)#True bool(0)#False bool(None)#False b="hello" print(list(b)) #['h', 'e', 'l', 'l', 'o'] tuple(b) # ('h', 'e', 'l', 'l', 'o') ####################333 ####运算符 ### b**2=b*b b**3=b*b*b ### in 、 not in 、is \is not
# -*- coding: utf-8 -*- #!/usr/bin/python import sys import twitter from settings import * print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nestablish the twitter object') # see "Authentication" section below for tokens and keys api = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token_key=O...
""" No.1 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solutio...
#IMPUT cateto_uno=float(input("ingrese cateto uno:")) cateto_dos=float(input("ingrese cateto dos:")) #PROCESSING hipotenusa=(cateto_uno**2+cateto_dos**2)**(1/2) #VERIFICADOR triangulo_grande=(hipotenusa>100) #OUTPUT print("##########################################") print("#### calcular la hipotenusa ####...
masa=float(input("ingrese masa:")) longitud=float(input("ingrese longitud:")) tiempo=float(input("ingrese tiempo:")) presion=masa/(longitud*tiempo**2) print("####################################") print("#### calcular presion ########") print("####################################") print("#### longitud =", long...
longitud=float(input("ingrese longitud:")) tiempo=float(input("ingrese tiempo:")) aceleracion=longitud/tiempo**2 print("#################################") print("#### calcular aceleracion ###") print("#################################") print("#### tiempo:",tiempo," ###") print("#### aceleracion:",...
#Input numero1=float(input("Ingresar el numero1:")) numero2=float(input("Ingresar el numero2:")) #Processing raiz=(numero1/numero2)**(1/2) #Verificador raiz_correcta=(raiz>=5) #Ouput print("###########################################################") print("# Algoritmo para hallar la raiz cuadrada de una division ...
#INPUT trabajador=input("ingrese nombre de trabajador:") pago_por_horas_extras=float(input("ingrese el pago por horas extras:")) horas_extras_trabajadas=float(input("ingrese horas extras trabajadas:")) #PROCESSING pago_total_de_horas_extras_trabajadas=pago_por_horas_extras*horas_extras_trabajadas #VERIFICADORES pago_...
""" Con JavaScript function MyFirstFunction() { console.log("Hola Mundo"); } console.log("Hola Mundo 2"); MyFirstFunction() """ # Para Python def MyFirstFunction(): print("Hola Mundo") print("Hola Mundo") print("Hola Mundo") print("Hola Mundo 2") MyFirstFunction() ''' va...
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] for row in a: for elem in row: print(elem, end=' ') print()
def stupid_sort(data): i, size = 1, len(data) while i < size: if data[i - 1] > data[i]: data[i - 1], data[i] = data[i], data[i - 1] i = 1 else: i += 1 return data
Capitals = {'Russia': 'Moscow', 'Ukraine': 'Kiev', 'USA': 'Washington'} Capitals = dict(Russia = 'Moscow', Ukraine = 'Kiev', USA = 'Washington') Capitals = dict([("Russia", "Moscow"), ("Ukraine", "Kiev"), ("USA", "Washington")]) Capitals = dict(zip(["Russia", "Ukraine", "USA"], ["Moscow", "Kiev", "Washington"])) print(...
def encryption (plainText,key): cipherText = [] # 1. Generate Key Matrix keyMatrix = generateKeyMatrix(key) # 2. Encrypt According to Rules of playfair cipher i = 0 while i < len(plainText): # 2.1 calculate two grouped characters indexes from keyMatrix n1 = indexLocator(plainTex...
"""1. Дан зашифрованный русский текст. Каждая буква заменяется на следующую за ней (буква я заменяется на а). Получить новый текст, содержащий расшифровку данного текста. letters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'""" a = "теперь моя пора я не люблю весны" def f (x): letters = 'абвгдеёжзийклмнопрстуфхцчшщ...
import socket def connection(message): print('Begin') # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening #208.103.44.151 is the router address that will forward 10000 # to the computer running the s...
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): def test_max_interger(self): """Test output of max_interger() """ self.assertAlmostEqual(max_integer([1, 2, 5, 4, 7]), 7) ...
#!/usr/bin/python3 """ This is he module Text indetation """ def text_indentation(text): """ print a text with 2 new lines after each of these characters """ if type(text) is not str: raise TypeError('text must be a string') else: replace_dot1 = text.replace('. ', '.') ...
#!/usr/bin/python3 """ Module Write to a file """ def write_file(filename="", text=""): """ function that writes a string to a text file Return: number od characters written """ with open(filename, mode='w', encoding='utf-8') as myfile: myfile.write(text) return myfile.tell()
#!/usr/bin/python3 """ this is Module Append to a file""" def append_write(filename="", text=""): """Function that appends s tring at the end of a text file Return: the number of character added """ with open(filename, mode='a', encoding='utf-8') as myfile: return myfile.write(text)
#!/usr/bin/python3 """ Module Student to Json with filter """ class Student: """ class that defines a student """ def __init__(self, first_name, last_name, age): """ Constructor Args: first_name (str): first name of a student last_name (str):last name of student ...
#!/usr/bin/python3 def uniq_add(my_list=[]): # obtenemos los elementos de la lista sin repetir uniq_idx = list(set(my_list)) # sumamos esos unicos elementos result = sum(uniq_idx) return result
#coding:utf-8 import dns.resolver domain = input('请输入域名地址') # 请输入域名地址www.baidu.com #1. A 记录,将主机转换为IP地址 A = dns.resolver.query(domain,'A') for i in A.response.answer: for j in i.items: if j.rdtype == 1: print(j.address) print(A) print(i) print(i.items) print(j) print(j.rdtype) print(j.addre...
""" LCHS Python Walkthrough Aug 2021 """ from beach import Beach from forest import Forest from person import Person class Game: """ The game! """ def __init__(self): """ Construct the game with default person """ self.player = Person() def se...
#! /usr/bin/python """ Module for handling the conversion of character sequences (strings or file-like object, including text files, all referred hereafter as 'stream') into python objects, by implementing some custom functions for parsing streams into (arrays or scalar) of floats, ints, booleans, or more generall...
#!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): # start with empty list of unpaired socks (we haven't started looking through them yet!) unpairedSocks = [] pairs = 0 # for each sock, if we've ...
""" File này dùng để chứa đối tượng là khách hàng """ class Customer: """ Dữ liệu của khách hàng gồm có Tên, địa chỉ (tương ứng với điểm trên đồ thị) và loại hàng mà người này đặt""" def __init__(self, name, address, merchan): self.name = name # tên khách hàng self.address = addre...
import re # The common advice about email validation is don't: # send a confirmation code to the email given and look # if the email sender return an error def valid_email(email): regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' if(re.search(regex, email)): return True, None return False...
import sys import pandas as pd import numpy as np """ The code is theoretically inspired from the following references: Artificial Intelligence: A Modern Approach, 3rd Edition. (From pages 697-707) https://en.wikipedia.org/wiki/Decision_tree Throughout the comments, the said book shall be referred to as AI:AMA """ ...
#!/usr/bin/python -tt # Script by - Rishab Saraf # Github profile: rishabsaraf93 import re import sys def breakdate(date): """ breakdate takes a date as an argument in the format '1 Jan 2010' and returns a tuple of size 3 The tuple contains three integer values (day,month,year) """ match = re.search(r'(\d+)...
notas = [] res = "si" while res=="si": no=int(input("ingrese nota: ")) notas.append(no) res=input("desea continuar si/no: ") nota = open("notasguardadas.txt","w") for no in notas : nota.write(str(notas) nota.write("\n") nota.close()
import numpy as np #for Numerical function import matplotlib #for ploting graph import matplotlib.pyplot as plt from matplotlib import style import pandas as pd #for different data frame xs=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] ys=[10,12,20,22,21,25,30,21,32,34,35,30,50,45,55,60,6...
# Learn how to get the current hour of your computer import datetime now = datetime.datetime.now() print (now.year, now.month, now.day, now.hour, now.minute, now.second)
# Write a function that extracts the even items in a given integer list, named get_even_list, # takes 1 parameter: l, where l is the given integer list ([1, 4, 5, -1, 10] for example), # returns a new list contains only even numbers ([4, 10] if the given list is [1,4,5,-1,10]) newl = [] def get_even_list(l): fo...
x = int(input("x = ")) op = input("Operation(+, -, *, /): ") y = int(input("y = ")) print("* " * 20) res = 0 if op == "+": res = x + y elif op == "-": res = x - y elif op == "*": res = x * y elif op == "/": res = x / y else: print("Buzz") break # nên rút print ra ngoài print("{0} {1} {2} = ...
import numpy as np import cv2 #numpy.ones reshapes the array--width600,height 800 rect=np.ones((600,800,3),dtype=np.uint8)*255 #bgr--red color below one #10 is the thickness cv2.rectangle(rect,(0,int(600/2)),(int(800/2),599),(0,0,255),10) cv2.imshow("image",rect) cv2.waitKey() cv2.destroyAllWindows() #b...
#!/usr/bin/env python # -*- coding: utf-8 -*- '格式转化工具' __author__='haipenge' class FormatUtil(object): #驼峰命名格式转下划线命名格式 def camel_to_underline(self,camel_format): underline_format='' if isinstance(camel_format, str): for _s_ in camel_format: underline_format += _s_ if _s_.islower() else '_'+_s_.lower() ...
#Dispalys the tic tac toe board def display_board(board): print('\n'*100) print(board[7]+' | '+board[8]+'|'+board[9]) print('-----------') print(board[4]+' | '+board[5]+'|'+board[6]) print('-----------') print(board[1]+' | '+board[2]+'|'+board[3]) #Takes in the players input to ask if X o...
from art import logo, stages from allwords import word_list import random lives=6 chosenWord= random.choice(word_list) print(logo) #Generar la lista en blanco print(chosenWord) list=[] for i in range(len(chosenWord)): list += "_" end_of_game=False while not end_of_game: userGuess=input('Guess...
''' Author : Nikhil Gabhane Date : Sept 20, 2016 ''' class encryption(object): def __init__(self): self.letters = "acdegilmnoprstuw" def reverse_hash(self,hash_code): res = [] if hash_code == 7: return "It's an Empty String" if hash_code <259: return "Invalid hash code" try: tmp = hash_code % 37 ...
# __dict__ class DictDemo(object): def __init__(self): self.name = "li" self.age = 18 def __setattr__(self, key, value): print("__setattr__ is running") super().__setattr__(key, value) def __delattr__(self, item): print("__delattr__ is running ") if item ==...
class MyClass(object): pass def study(): pass def __init__(self, name): self.name = name def hello(self): print(f'My name is{self.name}') # 所有累都是type创建的对象 # 'Student'类名 ‘(object,)继承的对象’,后面字典内为类中的属性 Student = type('Student', (object,), { '__init__': __init__, 'say': hello }) if __name__ ...
""" This is the Language gramatic. The first block determine how sentences are built. The second block determines what each token on a sentece is. SENTENCES: S = [Expressao]+ Expressao = (declaracao | operacao | forloop | print | ifbloco ) fimDeExpressao declaracao = (declaradorVariavel|null) variavel (operadorDeclar...
"""IP Validation check. Fundamental checks for: 1. Whether or not a cidr is listed within the cidr field. 2. Cidr blocks larger than a /13 3. Leading zero's within network ip address. 4. Checks for a valid Network Address. """ import os import ipaddress import re import logging def out_log(loggs, lo...
import random def roll_at_max_M_times(numbers, M): value = 0 for _ in range(M): value = random.choice(numbers) if random.random() <= (1.0 / M): break return value def roll_experiment(n, M, numbers): sum_win_amount = 0 for _ in range(n): ...
class FormattingException(Exception): pass def format_int(input_string): try: result = int(input_string) except ValueError: raise FormattingException("Couldn't parse as int.") return result def format_positive_int(input_string): result = format_int(input_string) if result >=...
#-*- coding: utf-8 -*- ''' # =========================================================== # from Python » Documentation » The Python Standard Library » 25. Development Tools » import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(),'FOO') def test_isupper...
#-*- coding: utf-8 -*- # 两个对象 共享参数(非继承) class Lxf1(object): session = 200 def __init__(self): self.__x = r'This is "class lxf1 -- def __init__" ' def lxf1_print(self): lxf = 100 lxf1 = 200 return lxf #,lxf1 class Lxf2(object): def __init__(self): self.lxf1 = Lxf1() def print_anying(self): print sel...
class Node: def __init__(self, key): self.left = None self.right = None self.data = key def inorder(temp): if not temp: return # LVR inorder(temp.left) print(temp.data) inorder(temp.right) def mirror(rootnode): if not rootnode: return q = [] ...
# Python lab assignment 3 # AuthorL: Sunny Kriplani # Student ID: 119220438 # This program prints the possible match of two persons from a marriage # record data import re f1 = open("mary_roche.txt") f2 = open("nicholas.txt") mary = f1.read() nicho = f2.read() mary_l = re.split("Marriage of ", mary) ...