text
stringlengths
37
1.41M
def falsi(x0, x1): x2 = x0 - ((x1-x0)/(f(x1)-f(x0))*f(x0)) return x2 def f(x): result = x*x - 2*x - 8 return result #x0 = eval(input("input x0: ")) #x1 = eval(input("input x1: ")) #print(falsi(x0, x1))
def is_password_strong(password): symbols = ["!","@","#","$","%","^","&","*","(",")",'_','-','=','+','|','\\','/','?','.','>',',','<',';',':'] letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u''v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','...
"""Planet.py: To draw a picture to imitate how planets run around the sun using turtle. __author__="Liyuhao" __pkuid__="1800011761" __email__="1800011761@pku.edu.cn" """ import turtle import math m = turtle.Screen() sun = turtle.Turtle() sun.hideturtle() sun.up() sun.goto(100, 0) sun.dot(50, "red") alexa = turtle.Turt...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if head is None: return False fast = head.next while fast: if fast == h...
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: n @return: The new head of reversed linked list. """ def reverse(self, head): prev = None while head : ...
#!/usr/bin/env python3 class Solution: """ @param: source: source string to be scanned. @param: target: target string containing the sequence of characters to match @return: a index to the first occurrence of target in source, or -1 if target is not part of source. """ def strStr(self, source,...
#fibonacci series import sys n=int(input()) list = [0,1] for i in range(2,n): list.append(list[i-1]+list[i-2]) print(list)
#!/usr/bin/python # -*- coding: utf-8 -*- filename = input("File: ") def openFile(fn): f = open(fn,'r',encoding="utf8") d = f.read() f.close() return d def saveFile(fn,d): f = open(fn,'w',encoding="utf8") f.write(d) f.close() content = openFile(filename) content = content.replace(" ", " ").replace("\r ", "...
import math # импротируем модуль math x = 3.265 # целое число, ближайшее целое снизу, ближайшее целое сверху print(math.trunc(x), math.floor(x), math.ceil(x)) print(math.pi) # константа пи print(math.e) # число Эйлера y = math.sin(math.pi / 4) # math.sin – синус print(round(y, 2)) y = 1 / math.sqrt(2) # math....
import numpy as py import pandas as pd import matplotlib.pyplot as plt #reading the file datasets = pd.read_csv('Salary.csv') #dividing dataset into x and y X=datasets.iloc[:,:-1].values Y=datasets.iloc[:,1].values print(X) print(Y) #splitiing dataset into test and train from sklearn.cross_valida...
# get user email address email= input("Enter your email address: ").strip() #slice out user name username= email[0:email.index('@')] #slice out domain name #garimagr@gmail.com ind=email.index('@')+1 domainname= email[ind:] #format message message= "The user name is {} and the domain name is {}" output=message.form...
""" Created on Thu Jun 24 12:44:36 2021 @author: Yousif Alyousif """ import tkinter as tk import sqlite3 from tkinter import ttk #con = sqlite3.connect('FinanceManager.db') #cur = con.cursor() #cur.execute("""CREATE TABLE finances ( # item blob, # expense blob, # qty blo...
def writeBackward1(string): if string == "": return string else: return string[len(string)-1]+writeBackward(string[0:len(string)-1]) def writeBackward2(s): if s== "": return s else: return writeBackward2(s[1:]) + s[0] s = raw_input() print writeBackward2(s)
import random import math # initialize global variables used in your code here num_range = 100 num_guesses = int(math.ceil(math.log(num_range,2))) secret_number = random.randint(0, 100) # helper function to start and restart the game def new_game(): print "New game. Range is from 0 to",num_range print "Number...
high = 100 #high end of guess - cut as needed low = 0 # low end of guess - cut as needed numGuesses = 0 print 'Please think of a number between 0 and 100!' while True: guess = (high + low)/2 print "Is your secret number " + str(guess) + "?" user = raw_input ("Enter 'h' to indicate the guess is too high. E...
from math import ceil, sqrt import numpy as NP # Get the prime divisors of a number. # This function come from http://codereview.stackexchange.com/questions/19509/functional-prime-factor-generator def factor(n): if n <= 1: return [] prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n) resul...
# -*- coding: utf-8 -*- #Author: Aristotle Ducay #Date: 09/16/2020 #File: Cars.py #List objects for car makes, models and years years = [2001, 1989, 2019, 1999] makes = ["Honda", "Toyota", "Mercedes", "Nissan"] models = ["Accord", "Camry", "C63AMG", "Skyline"] #indexing values for years and makes list ye...
#!/usr/bin/env python def load_dict(dict_path): """ Read a dictionary located at the path provided. Add each of the words in the dictionary to a set that can then be used to provide spelling suggestions. Returns a dict with all words in the dictionary. """ words = {} # add each line to ...
from abc import ABC, abstractmethod class A(ABC): @abstractmethod def show(self): pass class B(A): def show(self): print('show method') b1 = B() b1.show()
""" Creational: - Factory Method: 3 Component => 1.Creator, 2.Product, 3.Client """ # Factory Method allows us to create a super_class that is responsible \ # for creating an object and allow the sub_class to be able to change the \ # type of object being made from abc import ABC, abstractmeth...
""" 77.Remove duplicates elements of the list withoud using built in keywords and temporary list. """ l=[1,2,3,4,3,5,6,3,7,4,5] print "actual list:",l def remove_duplicates(lst): lst.sort() i = len(lst) - 1 while i > 0: if lst[i] == lst[i - 1]: lst.pop(i) i -= 1 return lst ...
""" 72. create a user defined datatype, and provide functionalities of addition substraction and multiplication. Create three instances(obj1,obj2,obj3) and print an output of obj1+obj2+obj3, obj1-obj2-obj3, obj1*obj2*obj3 """ class userdeffun: def __init__(self,x=0,y=0): self.x=x self.y=y def __...
""" 80.WAP to remove perticular element from a given list for all occurancers """ s=[1,2,3,4,3,2] print "main list:",s m=[1,2] print "sublist:",m for i in s: for i in s: if i in m: del s[s.index(i)] print "after removing elements in sublist:",s
""" 52. keys=['k1','k2'], values = ['v1','v2'] form a dictionary """ keys=['k1','k2'] values=['v1','v2'] d={} j=0 for i in keys: d[i]=values[j] j=+1 print d
#!/usr/bin/env python2 """Text Widget/Automatic scrolling This example demonstrates how to use the gravity of `GtkTextMarks` to keep a text view scrolled to the bottom while appending text. """ import pygtk pygtk.require('2.0') import gobject import gtk class AutomaticScrollingDemo(gtk.Window): def __init__(self...
#!/usr/bin/env python2 '''Buttons/Button 3 Toggle Buttons Toggle buttons are derived from normal buttons and are very similar, except they will always be in one of two states, alternated by a click. They may be depressed, and when you click again, they will pop back up. Click again, and they will pop back down. Toggl...
#!/usr/bin/env python2 """Dialogs/D0 The Dialog widget is a window with a few things pre-packed into it for you. It creates a window, and then packs a VBox into the top, which contains a separator and then an HBox called the "action_area". Constructor is `gtk.Dialog` It can be used for pop-up messages to the user an...
#!/usr/bin/env python2 '''Tree View/Model Tree 0 Basic Treeview connected to TreeStore. The TreeView widget displays lists and trees displaying multiple columns. It replaces the previous set of List, CList, Tree and CTree widgets with a much more powerful and flexible set of objects that use the Model-View-Controller...
nums = [1,2,3,4,5,6] #NORMAL METHOD USING FUNCTIOS: # def square(n): # return(n*n) #USING LAMBDA FUNCTION: print(list(map(lambda n: n*n ,nums))) x = lambda a, b : a * b print(x(5, 6))
names = ['raju','rani','pinky','sunny','baby'] for name in names: print(name) #Slicing using for loop56 for name in names[1:3]: print(name) for name in names: if (name == 'pinky'): print(f'{name}-Good girl') # break else: print(name) #WHILE LOOPS: age = ...
# String Functions # ******************* prem = "what are" print(prem.replace("what","how")) print(":".join(["apple","mango","banana"])) print(prem.upper()) print(prem.lower()) print(prem.startswith("What")) print(prem.isnumeric())
my_tuple = (1, 2, 3) print(my_tuple[1]) my_other_tuple = (4,5,6) my_tuple += my_other_tuple x, y , z = my_tuple
##in fisierul 'ad.txt' se gasesc datele de intrare ##fisierul este de forma: ##stare_initiala Stari_finale ##cuvant cuvant cuvant...... ##litera starea_din_care_pleaca starea_in_care_ajunge ##... ##litera starea_din_care_pleaca starea_in_care_ajunge def parcurgere(lista, sir): ok = True point = 0 #...
def num_to_words(n): # supports up to 1000 if n == 1000: return "one thousand" if n >= 100: if n % 100 == 0: return f"{num_to_words(n // 100)} hundred" return f"{num_to_words(n // 100)} hundred and {num_to_words(n % 100)}" if n >= 20: if n % 10 == 0: ...
""" 47. Permutations II: Runtime: 40 ms, faster than 92.96% Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Example 1: Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] Example 2: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3...
""" 在控制台中录入一个成绩,判断等级(优秀、良好、及格、不及格) """ def print_grade_level(grade_input): """ 根据输入的成绩评判等级 :param grade_input: int 成绩 :return: 返回出对应的等级 """ if int(grade_input)>100 or int(grade_input)<0: return "成绩有误" if int(grade_input) >= 90: return"成绩优秀!" if 75 <= int(grade_input): r...
#边界情况left与右的初始位置要与刚开始的时候相对应 #查找目标值 def get_target(nums, target): left, right = 0, len(nums)#left为序列的开头,right为序列的末尾索引+1 while left < right: mid = left + (right - left) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 #下一轮迭代,left与righ...
# -*- coding: utf-8 -*- import re import time import sys class Union(object): def __init__(self, n): # set count self.time_counter = 0 self.ini_time = time.time() self.count = n # all numbers. when initialed, every number make a tree self.id = list(xrange(n)) d...
from typing import List, TypeVar T = TypeVar('T', int, float, str) def minimum(array: List[T]) -> int: min_el = array[0] for i in range(1, len(array)): if min_el > array[i]: min_el = array[i] return min_el
from typing import TypeVar, List T = TypeVar('T', int, str, float) def linear_search(array: List[T], key: T) -> int: for i in range(len(array)): if array[i] == key: return i return -1
# -*- coding: utf-8 -*- """ Created on Thu Dec 27 19:19:45 2018 @author: Lucy """ ''' __str__ ''' class Student(object): def __init__(self,name): self.name=name def __str__(self): return 'Student object (name:%s)' % self.name __repr__=__str__ ''' 怎么才能打印得好看呢...
# -*- coding:utf-8 -*- from collections import deque #双端队列 dequeQueue = deque(['Eric','John','Smith']) print(dequeQueue) dequeQueue.append('Tom') #在右侧插入新元素 dequeQueue.appendleft('Terry') #在左侧插入新元素 print(dequeQueue) dequeQueue.rotate(2) #循环右移2次 print(dequeQueue) while len(dequeQueue) > 0 : print(dequeQueu...
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ d = dict() for i in nums: if d.get(i): return True else: d[i]= 1 return False t = [1,2,3,1] s =...
""" Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may ...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: return self.visitNode(root) def visitNode(self...
''' Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd...
''' Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets. ''' from collections import Counter class Soluti...
# -*- coding:utf-8 -*- # 最大公约与最小公倍 # def max_yue(number1:int, number2:int): if number1 < number2: temp = number1 number1 = number2 number2 = temp m=number1; n=number2; while( m%n !=0): r = m % n m = n n = r print("最大公约数:{}".format(n)) pr...
country = input("What is your country? ").capitalize() tax = 0 if country == "Canada": province = input("What is your province? ").capitalize() if province in ("Alberta", "Nunavut", "Yukon"): tax = 0.05 elif province == "Ontario": tax = 0.13 else: tax = .15 print("Your pro...
#this is straight up code from I believe CodeCademy.com from node import Node def type(name, content, endDate): table = name + ' ' + content.ljust(20) + endDate return table class LinkedList: def __init__(self, name, content, endDate=None, next_node=None): self.head_node = Node(name, content, endDate, nex...
''' an automated bruteforce attack on a shift cipher @author: Willi Schoenborn ''' from LetterFrequency import LetterFrequency from string import upper import sys def main(): if len(sys.argv) is 1: filename = '../resources/hinter-den-wortbergen.txt' else: filename = sys.argv[1] t...
# Archivo: pinta_parabola.py # Autor: Javier Garcia Algarra # Fecha: 24 de diciembre de 2017 # Descripción: Dibujamos una circunferencia import matplotlib.pyplot as plt import math # importamos la librería matemática que sabe hacer raíces cuadradas # Funcion para crear una lista ...
x=int(input("enter 1st value:")) y=int(input("enter 2nd value:")) z=int(input("enter 3rd value:")) def fun(x,y,z): if(x>y): if(x>z): print(x," is greatest") else: print(z," is greatest") elif(y>z): print(y," is greatest") else: print...
class Solution: def sortArray(self, nums): """ :type nums:List[int] :rtype: List[int] """ if len(nums) <= 1: return nums mid_point = int(len(nums) / 2) left, right = self.sortArray( nums[:mid_point]), self.sortArray(nums[mid_point:]) ...
class Solution: def reverse(self, x: int) -> int: value = str(x) new_str = '' num = 0 if x == 0: return 0 elif x < 0: if value.__contains__('0'): value = value.strip('0') value = value[1:] for i in range(len(va...
import random from random import randint import os import os.path flag1=True flag2=True flag3=True flag4=True flag5=True flag6=True class player: player_name = "Bot" player_nprizes =2 player_money = 100.0 player_prize="book,pen" def set_player_details(self,name, nprizes, money,prize): self...
def logicaFibonacci (op): numUno = 0 numDos = 1 numSop = 0 detener = True print(numUno) print(numDos) while detener: numSop = numUno + numDos print(numSop) numUno = numDos numDos = numSop if ( op <= numSop ): detener = False def validarVal...
arr=[1,2,3,0] def Min(arr): cont=arr[0] for i in arr: if i<cont: cont=i print('минимум в массиве =',cont) Min(arr) def Arif(arr): sum=0 count=len(arr) for i in arr: sum+=i sr=sum/count print('среднее арифметическое в массиве =',sr) Arif(arr) string='hello, world' def Swap(string): c=len(string)-1 arr...
# initialization pentagonal = [] n = 1 res = [] tested = [] while n < 10: # reasonable number pentagonal.append(n*(3*n-1)/2) for e in pentagonal: for p in pentagonal: if [e,p] in tested: continue if (e+p) in pentagonal: if (e-p) or (p...
import random def isPrime(number): for x in range (2,int(number**0.5+1)): if (number % x == 0): return False return True def factorial(tralala): total = 1 while tralala > 0: total *= tralala tralala -= 1 return total def counts(options): ...
def digit_addition(n): pos = 0 total = 0 n = str(n) while pos < len(n): digit = int(n[pos]) total += digit pos += 1 return total n = 100 product = 1 while n > 0: product = product * n n += -1 print digit_addition(product)
#n46 def prime(i): if i%2==0: return False for j in range(3,int(i**0.5)+1,2): if i%j==0: return False return True def goldbach(m): global primes for n in primes: if (((m-n)/2)**0.5).is_integer(): return False return True x = 3 primes = [] #composites = [] while True: if prime(x): primes.append(x) el...
# initialization n = 0 count = 0 irrational = 0 while float(len(str(irrational))) < 15: n += 1 count += 1 irrational += n*(-10**(count-int(len(str(n)))+1) if float(len(str(irrational))) > 10.0 : a = int(str(irrational)[12]) print a
def digiNext(n): next = 0 for digitpos in range(0, int(len(str(n)))): #taken from 30.py next += int((str(n))[digitpos]) return next largest = 0 for a in range(1, 100): for b in range(1, 100): test = a**b result = digiNext(test) if result >= largest: ...
def selection_sort(a): for i in range(0, len(a)-1): min_idx = i for j in range(i+1, len(a)): if a[j] < a[min_idx]: min_idx = j a[i], a[min_idx] = a[min_idx], a[i] #python은 그냥 된다 swap ls = [1,5,8,3,5,7,3] selection_sort(ls) print(ls)
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import datetime __DATE__ = 2016 / 10 / 10 __author__ = "ban" __email__ = "bcan@shou.edu.cn" __version__ = "1.0" # start_time=np.array(Ptime(time[0],'mjulian').Format('mpl'))+TimeZone/24.0 # ptime_obs=Ptime(ptime_obs.Format('mjulian')-8.0/24.0,'mjulian')...
name=input('请输入您的姓名:') hoppy=input('请输入您的爱好:') print('您输入的姓名为:'+name+',您的爱好为:'+hoppy) print('您输入的姓名为:',name,',您的爱好为:',hoppy) print('您输入的姓名为:%s,您的爱好为:%s'%(name,hoppy)) print('您输入的姓名为:%s'%name) print('您的爱好为:%s'%hoppy)
# for循环 # 计算1~10内所有数字的相加之和 sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum += x print('相加之和为:%s' % sum)
score=int(input('请输入您的python成绩:')) print(score>60) print(score>=60) print(score<60) print(score<=60) print(score==100) print(score!=0)
import random name_list = ['Alise', 'Bob', 'Cindy'] num = len(name_list) stu_info = [] stu_info_2 = [] # 方法1:stu_info包含num个小列表,对应每个人的姓名和年龄 for i in range(num): age = random.randint(0, 51) stu_i = [name_list[i], age] stu_info.append(stu_i) print("方法1:") for i in stu_info: print(i) # 方法2:stu_info包含姓...
# 方法一: for i in range(1, 11): for j in range(1, i): print('*', end = '') print('*') print('-' * 20) # 方法二: for i in range(1, 11): a = '' for j in range(1, i+1): a += "*" print(a)
# Python中的函数的用法 # 函数,又叫方法,表示一个功能 # print('') input() # str(1) int('') # append('') insert(2, '') pop() # items() pop() get() # random.randint() # range() # 输出3遍Hello # 输出5遍World # 输出4遍Hello # 输出5遍World # 输出3遍Hello # 输出3遍World a = for i in range(3): print('Hello') b = for i in range(5): print('Wor...
#Grater number between two numbers a=30 b=20 c=25 if b<c<a: print('c the graeter number ') else: print('c is not a grater number')
#!/usr/bin/env python3 # https://adventofcode.com/2020/day/7 import os import sys from collections import defaultdict with open(os.path.join(sys.path[0], "input.txt"), "r") as file: lines = [line.rstrip("\n") for line in file] d = defaultdict(list) d2 = defaultdict(list) for line in lines: color1 = " ".joi...
#!/usr/bin/env python3 # https://adventofcode.com/2020/day/21 import os import sys import regex with open(os.path.join(sys.path[0], "input.txt"), "r") as file: lines = [line.rstrip("\n") for line in file] def parse_foods(data): candidates = {} ingredients = [] for line in data: match = rege...
#!/usr/bin/env python # coding: utf-8 # In[ ]: ##assumption lets consider the index position as role number of student. ## we will create the three list as math,chem,phy. ## score will be out of 100 # # In[1]: math = [] phy = [] chem = [] listof_rollno_reappering_std = [] listof_rollno_failur...
import os def usr_str(): print("Input a string that has multiple words.") print("Example: My name is Kyle") return input("--> ") def reverse_order(usr_str): usr_str = usr_str.split(" ") rev = usr_str[::-1] joined = " ".join(rev) return joined def main(): play = True while play == True: usr_str_s =...
from bs4 import BeautifulSoup import sys import os import requests from ast import literal_eval def get_links(url): r = requests.get(url) contents = r.content soup = BeautifulSoup(contents) links = set() with open("links_methods.txt", "a") as file: for link in soup.findAll('a'): ...
# Python_Page_Spider_Web_Crawler_Tutorial # from https://www.youtube.com/watch?v=SFas42HBtMg&list=PLa1r6wjZwq-Bc6FFb9roP7AZgzDzIeI8D&index=3 # Spider algorithm. # You need to EXECUTE the file in Shell, e.g. execfile("nytimes/scrape.py") # First open cmd. Then cd C:\Users\Joh\Documents\Python Scripts\Web Crawler Proje...
def insertion_sort(arr): for i in range(1, len(arr)): t = arr[i] j = i - 1 while (j >= 0 and t < arr[j]): arr[j + 1] = arr[j] alg_count[0] += 1 j = j - 1 arr[j + 1] = t alg_count[1] += 1 import timeit a = timeit.default_timer() ...
# -*- coding: utf-8 -*- ''' Control Flow ''' def main(): # Variable x = 21 # if, elif and else Statement if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative" # For loop words = ['cat', 'window', 'defenestrate'] for w ...
# -*- coding: utf-8 -*- ''' Set It is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set object also support mathematical operations like union, intersection, difference, and symmetric difference. Curly braces or the set() functi...
# -*- coding: utf-8 -*- ''' Assignment Operators ''' def main(): # Integers a = 21 b = 10 c = 0 # Assignment Operators c = a + b print "Value of c is ", c c += a print "Value of c is ", c c *= a print "Value of c is ", c c /= a print "Value of c is ", c c = 2 ...
"""text feature extraction. feature: word presence captured by bag of words." 1. filter stopwords. 2. include significant bigrams using chi_sq score function. """ import nltk from nltk.corpus import stopwords from nltk.collocations import BigramCollocationFinder from nltk.metrics import BigramAssocMeasures def bag_of_...
# 1 a = int(input()) b = int(input()) c = int(input()) print(a + b + c) # Tkinter2 b = int(input()) h = int(input()) print(b * h / 2) # 3 n = int(input()) k = int(input()) print(k // n) print(k % n) # 4 # делением на 60 узнаем количество часов для n минут. # делением с остатком на 24 узнаем количество часов с начала...
def Sort(num):#升序 MergeSort(num,0,len(num)-1) def Merge(num,left,mid,right): tmp = [] i = left j = mid+1 while i<=mid and j<=right: if num[i]>num[j]: tmp.append(num[j]) j+=1 else: tmp.append(num[i]) i+=1 while i<=mid: tmp.ap...
def sort_by_ratio(item): return item[1] def Knapsack(w,v,c): ratio = [] r = [0 for i in range(len(w))] for i in range(len(w)): ratio.append((i,v[i]/w[i])) # 比重越大,越值得放入背包 ratio.sort(key=sort_by_ratio,reverse=True) print("根据价值与重量比值降序排列",ratio) tmp_c = c total = 0 for i in rang...
def put_pivot(num,left,right): pivot = num[left] i = left j = right while i<j: while num[j]>=pivot and i<j: j-=1 num[i]=num[j] while num[i]<=pivot and i<j: i+=1 num[j]=num[i] num[i] = pivot return i def divide_conquer(num,left,right):# 对...
def binsearch(num,left,right,target): if left>right: # 边界限制 return mid = (left+right)//2 if num[mid] == target: return mid if num[mid]>target: r = binsearch(num,left,mid-1,target) else: r = binsearch(num,mid+1,right,target) return r if r else -1 # 可能找不到 r = binse...
from collections import defaultdict def simple_cycles(G): # Yield every elementary cycle in python G exactly once def unblock(thisnode, blocked, B): # to get unique values stack = set([thisnode]) # while stack is not empty while stack: # get top element of stack ...
import matplotlib.pyplot as plt n = int(input("Enter generation number\n")) def func(p, w11, w12, w22): a = [p] b = [0] c = [(1-p)**2] d = [2*p*(1-p)] for i in range(1, n): p += p*(1-p)*(p*(w11-w12)-(1-p)*(w22-w12))/(p**2*w11+2*p*(1-p)*w12+(1-p)**2*w22) a.append(p) b.append(i) plt.plot(b, a) plt.xlabel('N...
class Student: def __init__(self,first_name,second_name,age,): self.first_name = first_name self.second_name = second_name self.age = age def full_name(self): name = self.first_name + self.second_name return name def year_of_birth(self): return 2019 - self.age def initials(self): ...
class Multionationale: def __init__(self,nom,pays): self.__nom = nom self.__pays = pays self.__filiale = [] def AjouterFiliale(self,filiale): self.__filiale.append(filiale) def Afficher(self): print(f"- La multinationale {self.__nom} est composée de {len(self.__fili...
""" MoveZeroes to the end """ def moveZeros(nums): if len(nums) == 1: return nums slow = 0 fast = 0 while fast < len(nums): if nums[fast] != 0: nums[fast], nums[slow] = nums[slow], nums[fast] if nums[slow] != 0: slow += 1 fast += 1 ret...
# # Binary trees are already defined with this interface: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None def inorderRec(node, lst): if node.left: inorderRec(node.left, lst) if node is not None: lst.append(node.value) if no...
def search(self, nums, target): def rotate_idx(l,r,nums): if nums[l]<nums[r]: return 0 while l<=r: mid = l+(r-l)//2 if nums[mid]>nums[mid+1]: return mid+1 else: if nums[mid]>=nums[l]: l = mid+1 ...
def permute(nums): res = [] path = [] used = [False] * len(nums) dfs(nums, res, path, used) return res def dfs(nums, res, path, used): if len(path) == len(nums): res.append(path[:]) return for i in range(len(nums)): if not used[i]: used[i] = True ...
""" Find the duplicate number: using 3 methods 1) brute force using sort 2) set 3) cycle detection algo -tortoise and hare """ def findDuplicate(nums): # brute force and sort # Time: O(nlogn) and space: o(1) nums.sort() prev = nums[0] for i in range(1, len(nums)): if nums[i] == prev: ...
class Node(object): def __init__(self, value): self.data = value self.next = None class LinkedList(object): def __init__(self): self.head = None self.tail = None def AddDigit(self, val): node = Node(val) if self.head is None: self.head = node ...
# def reverseWords(s): # s = s.split() # return " ".join(reversed(s)) # using deque and two pointer from collections import deque def reverseWords(s): if len(s) < 1: return "" left = 0 right = len(s) - 1 while left <= right and s[left] == " ": left += 1 while left <= right...