text
stringlengths
37
1.41M
def is_even(number): """ Checks if an integer number is even. >>> is_even(0) True >>> is_even(2) True >>> is_even(3) False It works with very long numbers: >>> is_even(100000000000000000000000000000) True And also with negatives: >>> is_even(-100000000000000000...
''' Given a string, str, and a character, char, your function countChar should count the number of char characters in the string str. We have written a helper function countChar_ for you, but it only works for substring str[1:]. This means that you have to do processing for str[0] character while the rest of the answer...
''' 水平面上有 N 座大楼,每座大楼都是矩阵的形状 可以用一个三元组表示 (start, end, height) 分别代表其在x轴上的起点,终点和高度。 大楼之间从远处看可能会重叠,求出 N 座大楼的外轮廓线。 外轮廓线的表示方法为若干三元组,每个三元组包含三个数字 (start, end, height), 代表这段轮廓的起始位置,终止位置和高度。 ''' from heapq import heappop, heappush class Solution: """ @param buildings: A list of lists of inte...
''' 给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组和的差的绝对值|SUM(A) - SUM(B)|最大。 返回这个最大的差值。 子数组最少包含一个数 ''' class Solution: """ @param nums: A list of integers @return: An integer indicate the value of maximum difference between two substrings """ def maxDiffSubArrays(self, nums): # write your ...
#automatic backward elimination '''we reduce number of variables not because we will get a better model, but because we can get a model with the same performance and fewer variables. Our advantages are the following: 1) We get rid of variables which have negligible predictive power, and learn what variables have actu...
def fizz_buzz(m): if m % 3 == 0 and m % 5 == 0: return "FizzBuzz" elif m % 5 == 0: return "Buzz" elif m % 3 == 0: return "Fizz" else: return m
A=[3,5,7] B=[1,8] C=[] counter=0 while len(A)>0 and len(B)>0: if A[0] <= B[0]: C[counter]=A[0] A=A[1:] counter=counter+1 else: C[counter]=B[0] B=B[1:] counter=counter+1 print(C)
r = int(input("Masukan Jari-jari : ")) pi = 22/7 luas = pi*(r*r) keliling = 2*pi*r print ("Luas Lingkaran = ",luas ,"cm") print ("Keliling Lingkaran = ",keliling ,"cm") print ("Luas Lingkaran = ",format(luas,'.2f' )) print ("Keliling Lingkaran = ",format(keliling,'.2f' ))
''' @Description: 一些常用的和推荐使用的语法 以及 一些工具的使用 @version: @Company: Lifegen @Author: CornC.fcx @Date: 2019-08-19 10:11:53 @LastEditors: CornC.fcx @LastEditTime: 2019-08-19 10:47:18 ''' # 使用生成式语法生成列表、集合和字典 # 字典 prices = { 'A' : 190, 'B' : 180, 'C' : 110, 'D' : 50, 'E' : 70, 'F' : 120 } # 价格大于 100 的...
''' @Description: 画出不同的三角形 @version: 1.0 @Company: Lifegen @Author: CornC.fcx @Date: 2019-05-20 14:19:37 @LastEditors: CornC.fcx @LastEditTime: 2019-05-21 11:53:12 ''' ''' * ** *** **** ***** * ** *** **** ***** * *** ***** ******* ********* ''' ''' row = int(input('Input Row Count :...
''' @Description: 计算给定半径的圆的周长和面积 @version: 1.0 @Company: Lifegen @Author: CornC.fcx @Date: 2019-05-17 15:29:53 @LastEditors: CornC.fcx @LastEditTime: 2019-05-17 15:36:52 ''' ''' Perimeter = 4 * pi * radius Area = pi * Square(radius) ''' import math raduis = float(input('Input Radius : ')) perimeter = 4 * math.pi * ra...
# Created by : Sidney Kang # Created on : 20 Nov. 2017 # Created for : ICS3UR # Daily Assignment - Unit5-05 # This program from numpy import random numbers = [] numbers.append([]) numbers.append([]) def calculate_average(numbers): average = float((sum(numbers[0]) + sum(numbers[1])) / (len(numbers[0]) + len...
import turtle as t t.penup() t.goto(-200,50) t.pendown() t.color("yellow") t.bgcolor("black") t.speed("fastest") def star(turtle,size): if size <=10: return else: turtle.begin_fill() for i in range(5): turtle.forward(size) star(turtle, size / 3) turt...
import turtle turtle.speed(0) turtle.hideturtle() turtle.setup(800,600) turtle.title('शिवलिंग Design BY- geek_programmer101') turtle.speed(0) turtle.up() turtle.hideturtle() def my_goto(x, y): turtle.pencolor("orange") turtle.penup() turtle.goto(x, y) turtle.pendown() def round_rec...
import turtle as t t.speed(0) def curve1(): t.begin_fill() t.fillcolor("red") t.right(50) t.forward(100) t.right(150) for i in range(30): t.forward(2) t.right(1) t.end_fill() def curve2(): t.begin_fill() t.fillcolor("red") for i in range(20): t.right(1)...
from controller import * from main import * from tkinter import * from tkinter import filedialog import os # main structure of the program class Application: def __init__(self, master): self.master = master self.directory = "" # heading self.heading = Label(master, text="File Mana...
#shamelessly stolen from https://pythonspot.com/en/building-an-irc-bot/ # these import statements include stuff from the "standard library" for python, just in particular socket lets us open connections import socket import sys # this is defining a class which is a thing, this is going to be used in a different file...
#importing packages from tkinter import * import tkinter.messagebox #function to enter the task in the Listbox def entertask(): #A new window to pop up to take input input_text="" def add(): input_text=entry_task.get(1.0, "end-1c") if input_text=="": tkinter.messageb...
# 条件循环判断肥胖程度 height = 1.75 weight = 80.5 bmi = weight / height ** 2 if bmi < 18.5: print("过轻") elif 18.5 < bmi < 25: print("正常") elif 25.0 < bmi < 28: print("过重") elif 28.0 < bmi < 32: print("肥胖") elif bmi > 32: print("严重肥胖") # 自己生成数字 a = list(range(5)) print(a) # 计算0-100的和 sum1 = 0 for x in range(...
##17.2: Write a method to shuffle a deck of cards. It must be a perfect shuffle with each shuffle having equal chance of happening import random def shuffle_deck(deck): c = 0 while c < len(deck): random_card = random.randrange(0, len(deck)) temp = deck[c] deck[c] = deck[random_card] deck[random_card] = temp...
""" 有时候需要在页面中进行的操作很多,那么可以使用鼠标行为链类Action来完成。比如,最简单的要将鼠标移动到某个元素上执行点击事件 """ from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time driver = webdriver.Chrome() driver.get("https://www.baidu.com") inputTag = driver.find_element_by_id("kw") submitTag = driver.find_element...
import ast def input_meal(name): f1 = open(name, 'r') myd = ast.literal_eval(f1.read()) return myd def input_operate(): dict_1 = open("operating_hour.txt", 'r') dict_list = [] o_h = {} # for the dictionary for words in dict_1: # first we append to the list and remove the new l...
"""Model for subscription in the database.""" from .movement_user_relation import MovementUserRelation class Subscription(MovementUserRelation): """ Subscription class for the subscription of a user to a movement. This class represents a table in the SQL database which holds rows of subscriptions. Al...
def removeMissing(filename): """Takes a file that contains missing scans and removes those rows, while providing the subject name and reason for removal.""" loaded_file = pd.read_csv(filename) cleaned_list = [] missing_counter = 0 for row in loaded_file.index: if loaded_file[3][row] == "": ...
enter =range(10) print(enter) enter =range(1, 11) print(enter) enter =range(0, 30, 5) print(enter) enter =range(0, -10, -1) print(enter) print(range(10)) for i in range(10,0,-1): print(i)
lists = ['Srini', 'Kiran', 'AIA', 'Scope', 'coke'] print (lists) print (lists[0]) print (lists[1:3]) print (lists[2:]) print(lists[2]) #tinylist *2) #print (lists + tinylist) lists[3]='coco' print(lists[2+1]) e=enumerate(lists) print(e.next) #print(enumerate(lists))
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 08:57:07 2020 @author: user """ # This program calculates different geometrical characteristics of a polygon shape. print("This program calculates different geometrical characteristics of a polygon shape") # Request number of point from user n=int (input("Ente...
from turtle import Screen, Turtle import numpy as np turtle = Turtle(visible=False) # hide the cursor completely turtle.speed(0) def draw_graph(num_rows, num_columns, space_from_edge=10): columns = num_columns + 1 rows = num_rows + 1 screen = Screen() width, height = screen.window_width(), screen.wi...
import numpy as np import matplotlib.pyplot as plt def Polynomial(t, X,Y): A=Y B=Y n=len(A) C = [] for j in range(1,n): A = list(B) C.append(B[j-1]) for i in range(j,n): B[i]=(A[i]-A[i-1])/(X[i]-X[i-j]) C.append(B[n-1]) S=0 ...
# x = 1. # x = int(x) # print(type(x)) # y = 4.3 # y = int(y) # print(type(y), y) # # z = 23 # z = int(z) #if u hash this out, you will get error(datatype) # print(type(z), z + 1) # a = 1234 # a = str(a) # a += 5 # a = int(a) # print(a + 10) #use the datatype names to convert between datatypes # int(), str(), float()...
#operator overloading class Point: # constructor def __init__(self, x=0,y=0): self.x = x self.y = y #we overloaded the __str__ operator #to String #overrides the original function which prints the address #we provide our own string that we want to see printed def __str__(s...
6. Write a Python program to convert a tuple to a string. Code: tup = ('A','l','v','a','s') str = ''.join(tup) print(str)
''' Date: 2022-09-15 08:38:56 LastEditors: r7000p LastEditTime: 2022-09-15 18:19:23 FilePath: \Daily\daily-python\09\findKthLargest.py ''' def quickSort(nums, reverse=False): quickSortHelper(nums, 0, len(nums), reverse) def quickSortHelper(nums, left, right, reverse=False): if right <= left: return ...
''' Date: 2022-09-06 10:31:39 LastEditors: r7000p LastEditTime: 2022-09-06 12:14:51 FilePath: \Daily\daily-python\09\moveZeros.py ''' class Solution: def moveZeroes(self, nums): """ Do not return anything, modify nums in-place instead. """ # i, j = 0, 0 # n = len(nums) ...
''' Date: 2022-08-27 20:38:30 LastEditors: r7000p LastEditTime: 2022-08-28 20:20:39 FilePath: \Daily\daily-python\08\generate.py ''' # 杨辉三角 class Solution: def generate(self, numRows): rows = [] if numRows == 1: rows = [[1]] elif numRows == 2: rows = [[1], [1, 1]] ...
''' Date: 2022-09-11 12:14:28 LastEditors: r7000p LastEditTime: 2022-09-21 21:21:11 FilePath: \Daily\daily-python\09\removeDuplicates2.py ''' class Solution: def removeDuplicates(self, nums, n): _nums = [] numsSet = [] for num in nums: if num not in numsSet: nums...
f=open("aylikmasraf.txt", "w+") gelir= int(input("Aylik geliriniz ne kadardir?")) mutfak= int(input("Aylik mutfak masrafiniz ne kadardir?")) egitim= int(input("Aylik egitim masrafiniz ne kadardir?")) giyim= int(input("Aylik giyim masrafiniz ne kadardir?")) ulasim= int(input("Aylik ulasim masrafiniz ne kadardir?"))...
# -*- coding: utf-8 -*- """ Created on Sun Sep 12 19:55:49 2021 @author: Kajol Shutra Dhar """ #%% """ Problem 2_5: """ import random def problem2_5(): """ Simulates rolling a die 10 times.""" # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. ...
""" OOP Assignment CSIS 250 2018 - 10 - 30 Author: Robert Schult """ class Poem: _number_of_poems = 0 def __init__(self, author = "", title = ""): self.author = author self.title = title self.text = [""] self.isHaiku = False Poem._number_of_poems += 1 def __str__(s...
import re # Class to display and format the data class Tweet: def __init__(self, data): self.data = data # Creates a link to the user's twitter page def user_link(self): return f"http://twitter.com/{self.data['username']}" # string formatting #return "http://twitter.com/{}".format...
def percentage(marks_obtained,max_marks): ''' Objective: To find a percentage by user input marks obtatained and maximum marks Input Parrameter: marks_obtained->contain marks obtained by user max_marks->contain maximum marks Return : percentage ''' #Approach : percent...
def areaOfRectangle(length,breadth): ''' Objective: To print a area of rectangle using input Input Parrameter: length->length of rectangle breadth->breadth of rectangle Result : Area of rectangle ''' #Approach : area=length * breadth area = length*breadth retur...
## 2. Enumerate ## ships = ["Andrea Doria", "Titanic", "Lusitania"] cars = ["Ford Edsel", "Ford Pinto", "Yugo"] for i,ship in enumerate(ships): print(ship) print(cars[i]) ## 3. Adding columns ## things = [["apple", "monkey"], ["orange", "dog"], ["banana", "cat"]] trees = ["cedar", "maple", "fig"] for i,thi...
## 2. Levels of abstraction ## import matplotlib.pyplot as plt %matplotlib inline # 2 simple lists of values month = [1,1,2,2,4,5,5,7,8,10,10,11,12,12] temperature = [32,15,40,35,50,55,52,80,85,60,57,45,35,105] plt.scatter(month, temperature) plt.show() ## 5. Axes ## import numpy as np month = [1,1,2,2,4,5,5,7,8,10...
''' # imutable x=10 print (id(x)) x=100 print (id(x)) # mutable list1=[1,2,3,4,5,6,7] print (id(list1)) # reassign list1[3]=12 print (id(list1)) # dictionary mydic = dict( name="Rajiv",age=22,salary=1000.35 ) print (mydic) #datatype print (type(mydic)) # get value by key print (mydic["...
### * Description # Script to get unique fasta sequences from a list of input sequences. # # Output is the unique sequences in a fasta format, using a hash of the # sequence as the sequence name. # # In addition to the Python documentation, useful information can be found here # for how to use stdin as the input strea...
""" Compute an optimum assignment of tasks: EPI 17.1 """ def assign_tasks(tasks): tasks.sort() scheduled_tasks = [] low, high = 0, len(tasks) - 1 while low < high: scheduled_tasks.append((tasks[low], tasks[high])) low += 1 high -= 1 return scheduled_tasks print(assign_ta...
""" Magic Index: an index where A[index] == index Find a magic index in a sorted array Example 1: Input: 2,3,7,10,12,20 Output: None Example 2: Input: 0,1,2,5,7,8 Output: 0 or 1 or 2 Example 3: Input: -2,-1,0,3,7,8 Output: 3 """ from io import StringIO import unittest def find_magic_index(stdin): nums = [] ...
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def check_palindrome(l): lower, upper = 0, len(l) - 1 while lower < upper: if l[lower] != l[upper]: return False lower += 1 upper -= 1 return Tru...
""" Delete duplicates from sorted array: EPI 5.5 """ def delete_duplicates(A): write_idx = 1 for i in range(1, len(A)): if A[i] != A[i-1]: A[write_idx] = A[i] write_idx += 1 return write_idx A = [1, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 7, 8] delete_duplicates(A) print(A)
""" Stack with Max API: EPI 8.1 """ class Stack(object): def __init__(self): self.stack = [] self.max_stack = [] def push(self, val): self.stack.append(val) if len(self.max_stack) == 0 or self.max_stack[-1] < val: self.max_stack.append(val) else: ...
""" Check for cyclicity: EPI 7.3 """ class Node(object): def __init__(self, value): self.value = value self.next = None def get_cycle_len(node_in_cycle): anchor = node_in_cycle step = 1 while True: node_in_cycle = node_in_cycle.next if node_in_cycle == anchor: ...
import heapq def merge_sorted_arrays(arrays): final_list = [] # This is to keep track of where we at in each array_and_string last_index = [0] * len(arrays) # Initialize the min heap with the first element from each array_and_string min_heap = [(a[0], array_index) for array_index, a in enumerate...
""" Advancing through an array: EPI 5.4 """ def can_advance_through_array(A): furthest_idx = 0 for i in range(len(A)): if A[i] == 0 and furthest_idx <= i: return False else: furthest_idx = max(furthest_idx, A[i] + i) return True print(can_advance_through_array([1...
#age = raw_input("how old?") #age = int(age) my_age = 29 for age in range(19,39): print "age is "+str(age) if age == my_age: print "same age" elif age > my_age: print "you're old" else: print 'young'
##Dictionaries is a collection of key-value pairs ## in order to return a value in a dictionary it must be referenced using the key #dictionaryName = {key1:value1, key2:value2, key3:value3} steakPrices = {"sirloin":18.99, "t-bone":27.99, "ribeye":29.99} print(steakPrices) #prints {'sirloin': 18.99, 't-bone': 27.99, 'ri...
##functions #syntax ; def functionName(): # blockOfCode def holaMundo(): print("Hola Mundo!") #syntax to call out a function holaMundo() #prints Hola Mundo! ## lets compute the area of a rectangle #area = length * width lengthOne = 8 widthOne = 3 areaOne = lengthOne * widthOne print(areaOne) #prints 2...
from datetime import datetime class Account: def __init__(self, first_name, last_name, phone_number): self.first_name = first_name self.last_name = last_name self.phone_number = phone_number self.balance = 0 self.deposits = [] self.withdrawals = [] s...
#defining function and passing one arguement def is_even(number): #if number is even if (number % 2 == 0): #then, it's true return True else: #anything else, it's false return False #defining second function with one arguement def is_odd(number): # if number is NOT true...
#asking for input user_input = input("Please enter a word: ") #create a function that prints tally of user input def print_letter(charachters): for charachters in range(0, len(user_input)):
from pet import Pet, CuddlyPet, DayOldPotatoChildUnderCouch, humanFoodLeftOnTable, Bones from menu import Menu from toy import Toy # Begin with no pets. pets = [] main_menu = [ "Adopt a Pet", "Play with Pet", "Feed Pet", "View status of pets", "Do nothing", "Eat Treat" ] adoption_menu = [ ...
## Validate Subsequence # What is a subsequence? A subsequence is an array (set of numbers) that aren't # necessarily adjacent in the array but are in the same order as the original sequence. ##Examples: Array - [1,2,3,4,5] Subsequence- [2,3,4] #This is a subsequence because even though it doesn't contain all the num...
from machine import Pin bit1 = Pin(25, Pin.OUT) bit2 = Pin(33, Pin.OUT) bit3 = Pin(15, Pin.OUT) bit4 = Pin(21, Pin.OUT) bit5 = Pin(14, Pin.OUT) bit6 = Pin(32, Pin.OUT) bit7 = Pin(27, Pin.OUT) bit8 = Pin(12, Pin.OUT) bit = [bit1, bit2, bit3, bit4, bit5, bit6, bit7, bit8] #****************** funtions ***************** ...
""" USBAPI - a simple API for driving the USB attached iBuddy USAGE To use this you need to add pywinusb to your Python installation - https://pypi.python.org/pypi/pywinusb/ Then you can drive this from the Python console as follows: >>> import usbapi as usb >>> devices = usb.usbapi().getDevices() That gets you an...
__author__ = 'joseph' from collections import defaultdict names = ['rachel', 'robert', 'randy', 'joseph', 'meghan', 'meryl', 'andrew', 'thomas', 'eric', 'matt', 'melissa', 'benjamin'] colors = ['red', 'green', 'green', 'blue', 'green', 'red', 'orange', 'green', 'red', 'yellow', 'orange'] d = {'a': 1, 'b': 2, 'c': 1, '...
# encoding: UTF-8 # Autor: Humberto Serra Mendieta # Calcula el IMC y checa que tan sano estas def calcularIMC(peso,estatura): imc=peso/(estatura*estatura) return imc def determinarSaludPersona(imc): if imc<18.5: salud="Bajo peso" elif imc>=18.5 and imc<=25: salud="Peso normal" el...
#Knuth Morriss Prat string searching algorithm class KMPStrinSearch: # @param haystack : string # @param needle : string # @return an integer #Using KMP algorithm def preprocessTable(self, needle): needle_ls = list(needle) table= [] table.append(-1) i = 1 le...
from abc import ABC, abstractmethod import time class Requester(ABC): @abstractmethod def request(self): pass class RealRequest(Requester): def request(self): print("Connecting to server") class Proxy(Requester): def __init__(self, login_to_server): self._login_to_server = ...
""" Calculator """ from tkinter import * def iCalc(source, side): storeObj = Frame(source, borderwidth=4, bd=4, bg="white") storeObj.pack(side=side, expand=YES, fill=BOTH) return storeObj def button(source, side, text, command=None): storeObj = Button(source, text=text, command=command) storeObj....
from numpy import random from numpy import shape import sys import time MAX = sys.maxint """ Creates a specified number of matrices with a specificed dimensions Fills in matrices with random values from numpy.random.random() Computes the chain multiplication according to questions """ def dynamic_chain(dimensions)...
""" Simplistic hashing function for turning a string into a number. By storing the number instead of the string, we can check that a given password matches the expected one, without storing the plain text password. Make sure no one besides me gets access to this source code! Hashed password: 81445731 """ def simple_...
""" Author: swetha@udel.edu Date: 2/18/2021 Description: CISC 320 Lesson 03: Using GradeScope Takes a filename from stdin, loads it into an int array, and sums only the positive values """ def summation(lines: [int]) -> int: """ Sums sequence of numbers while skipping negative numbers and stops upon ...
# -*- coding: utf-8 -*- """ Created on Thu Apr 2 15:10:13 2020 @author: Nathan """ from py2048_classes import Board, Tile from functools import reduce import time import math import random def main(): # allmoves = ['UP','LEFT','DOWN','RIGHT'] board = Board() board.add_random_tiles(2) ...
import sqlite3 connection=sqlite3.connect('data.db') cursor=connection.cursor() create_table="CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,username text,password text)" cursor.execute(create_table) create_item="CREATE TABLE IF NOT EXISTS itemdb (name text,price real)" cursor.execute(create_item) connec...
""" Now we want to access the ticker endpoint, where we can only access 100 results at a time (Check the parameters on the website) We'll be using it in an array format so that we can loop through the data with ease Ticker data is LIVE price data so essentially we'll be looking at the current value of these currencie...
#%% import numpy as np a = np.arange(0,11,1) # Contains a sequence of integers between 0 and 10. print ("a =",a) print ("The first element a[0] is",a[0]) print ("The last element a[-1] is",a[-1]) print ("The 5th number, at index 4 is",a[4]) print ("The second to the last: ",a[1:-1]) #index test
# # 打印树 # import math # # # # def print_tree(array: list, unit_width=2): # length = len(array) # depth = math.ceil(math.log2(length)) # index = 1 # # space = ' ' * unit_width # for i in range(depth-1, -1, -1): # pre = 2 ** i - 1 # print(pre * space, end='') # of...
""" The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as one 1 or 11. 11 is read off as two 1s or 21. 21 is read off as one 2, then one 1 or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as...
def sqrt(num): """ Find the Square Root on integer without using internal sqrt :param num: integer :return: floor(sqrt(num)) """ if num < 2: return num result = 0 start, end = 1, num // 2 while start <= end: mid = (start + end) // 2 sqr = mid ** 2 # ...
class Queue(object): def __init__(self): self.queue = [] def is_empty(self): return self.queue == [] def enqueue(self, n): self.queue.append(n) def dequeue(self): data = self.queue[0] del self.queue[0] return data def peek(self): return sel...
from threading import Condition class BlockingQueue: def __init__(self, max_size: int): self.__cond = Condition() self.__q = [] self.__max_size = max_size self.__curr_size = 0 def enqueue(self, item): self.__cond.acquire() while self.__curr_size == self.__max_s...
""" Check if two binary trees are identical or not | Iterative & Recursive """ # Data structure to store a Binary Tree node class Node: def __init__(self, key=None, left=None, right=None): self.key = key self.left = left self.right = right def isIdentical(x, y): if x is None and y is N...
from interviewbit.courses.programming.linked_list.base import ListNode, Node class Solution: # @param A : head node of linked list # @return the head node in the linked list def solve(self, A: Node): if not A: return A prev = Node(None) prev.next = A one = None...
class Node(object): def __init__(self, data): self.data = data self.next_node = None def __repr__(self): return "<Node {}>".format(self.data) class LinkedList(object): def __init__(self): self._size = 0 self._head = None def _verify_in_range(self, index): ...
""" Pascal's Triangle 1 11 121 1331 14641 Question: Find the value in given row and column First solution: brute force Second solution: Dynamic programming alternative def pascal(r, c): print(f"row: {r}, col: {c}") if r == 0 or r == 1 or c == 0: return 1 return pascal(r-1, c-1) + pascal(r-1, c...
""" O(n) """ from ds.linkedList.linkedlist import LinkedList def find_middle_node_linkedlist(l): node = l.get_first() single = double = node while single.next_node is not None and double.next_node is not None: single = single.next_node double = double.next_node.next_node if doubl...
n=input() a="abcdefghijklmnopqrstuvwxyz" if n in a: print("Alphabet") else: print("No")
import cv2 """ 图像灰度级指图像中的色度分量亮度的最大值与最小值之差的级别。 """ # 生成灰度图像 def create_gray_img(): img = cv2.imread('klcc_a.png') #cv2.imshow('原图像', img) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('灰度图像', img_gray) cv2.imwrite('klcc_a_gray.png',img_gray) pass def main(): img = cv2....
# 图像的可视化、基本属性的获取、部分内容分的修改以及可视化 # 0.导入必要的模块 import imageio import matplotlib.pyplot as plt # 1.原始图像的读取 pic = imageio.imread('demo_2.jpg') # 2. 原始图像基本属性的可视化 print('1--Type of the image : ' , type(pic)) print('2--Shape of the image : {}'.format(pic.shape)) print('3--Image Hight = {}'.format(pic.shape[0])) print('4--Im...
class ExecutionTime: """ This class is used as a decorator. Frames here means that, the methods decorates with ExecutionTime decorator will be executed after the number of frames passed is equal zero. This is used like a timer! """ def __init__(self, frames): self.frames = frames self.framesCo...
g=lambda x,y: 3*x+4*y-24 f=lambda x,y: 4*x+3*y-25 x=1; while(True): for y in range(x): if f(x,y)==0 and g(x,y)==0: print("x=%d, y=%d, f=%d, g=%d" %(x,y,f(x,y),g(x,y))) print(x,y) break else: print("x=%d, y=%d, f=%d, g=%d" %(x,y,f(x,y),g(x,y))...
a = input('請輸入身分證號:') if len(a) != 10: print('錯誤') exit() b = a[0] #切出a的第1位 if not(b.isupper() or b.islower()): #'A'<=b<='Z' print('第一位輸入錯誤') exit() print('正確')
#!/usr/bin/env python3 # Oct 7 2014 # Prints the mod2 version of Pascal's triangle a.k.a. Sierpinski's triangle. # Accepts multiple command line args in bash-- eg: "python3 pascal.py 5 10 20" import sys def printPascal(n): row = [1] printRow(row, n) for x in range(n-1): row = getNewRow(row) printRow(row, n) ...
a=int(input("enter the value:")) x=a**2 if (a%2) == 0: print("power of 2") else: print("not a power of 2")
n=int(input("enter the value:")) print(n+1)
score=float(input("Enter score: ")) if score>= 98 and score<=100: print("EXCELLENT!!!") elif score>=94 and score<=97: print("Very good, bro!") elif score>=89 and score<=93: print("Good...I guess.") elif score>=85 and score<=88: print("Meh...ok?") else: print("You have to find a new family ...
import pandas as pd import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText #Read Data File from syatem.... data = pd.read_excel("C:/Users/inparp00/Desktop/dataFile.xlsx") print(type(data)) #print(data.get("email")) listOfEmails = list(data.get("email")) listOFNames = l...
def sort_priority(values, group): def helper(x): print x if x in group: return (0, x) return (1,x) values.sort(key=helper) numbers = [8, 3, 1, 2, 5, 4, 7, 6] group = {2, 3, 5, 7} sort_priority(numbers, group) print(numbers)
import numpy as np import sys # LU factorization algorithm # 1. Want to solve Ax = b ( A is a matrix, x and b are vectors. This is how you represent a system of # linear equations using matrix and vectors ) # 2. Find lower triangular matrix L and upper triangular matrix U such that A = LU (this is LU factorization) # ...
print("hello python") # 100 미만 정수를 차례대로 i에 입력하기 for i in range(100): if i % 7 ==0: print(i) # round() 함수 사용법 round((50+45+33+39+29+30) / 6 , 1) # for 문과 리스트로 2단 출력하기 number = [1,2,3,4,5,6,7,8,9] for item in number: print(2*item) # range() 함수 사용법 for item in range(10): print(item) #...