text
stringlengths
37
1.41M
__author__ = 'mingluma' import os class Splitter(object): def __init__(self, path, worker_num): self.path = path self.worker_num = worker_num def split(self): """ Split files into splits, each split has multiple chunks. :return: An array of split information, i.e., (f...
# -*- coding:utf-8 -*- """ 代码主要作用: """ class Condition(object): def __init__(self, rank): self._rank = rank def __ge__(self, other): """Used for comparisons.""" return self._rank >= other._rank def __str__(self): if self._rank == 1: return "critical" ...
# -*- coding:utf-8 from ExampleCode.chapter4.node import Node from ExampleCode.arrays import Array from abstractset import AbstractSet class HashSet(AbstractCollection, AbstractSet): """A hashing implementation of a set.""" DEFAULT_CAPACITY = 3 def __init__(self, sourceCollection=None, capacity=None):...
# -*- coding:utf-8 -*- """ File: countfib.py Prints the number of calls of a recursive Fibonacci function with problem sizes that double. """ from ExampleCode.chapter1.counter import Counter def fib(n, counter): """Count the number of calls of the Fibonacci function.""" counter.increment() if n < 3...
# -*- coding:utf-8 -*- """ 代码主要作用: """ class ArrayListIterator(object): """Represents the list iterator for an array list.""" def __init__(self, backingStore): """Set the initial state of the list iterator.""" self._backingStore = backingStore self._modCount = backingStore.getModCoun...
# -*- coding:utf-8 -*- """ 代码主要作用: """ from hashtable import HashTable class Profiler(object): """Represents a profiler for hash tables.""" def __init__(self): self._table = None self._collisions = 0 self._probeCount = 0 def test(self, table, data): """Inserts the data ...
# -*- coding:utf-8 -*- def main(): iteration_time = int(input("input a iteration time: ")) flag = -1 div4_result = 0 denominator = 1 while iteration_time > 0: div4_result -= 1 / denominator * flag iteration_time -= 1 flag *= -1 denominator += 2 print('the resu...
# -*- coding:utf-8 -*- from project_09 import Book, Patron class Library: book_list = [] reader_list = [] # def __init__(cls): # cls.book_list = [] # cls.reader_list = [] @classmethod def add_book(cls, title, author, reader=None): """添加一本书""" book = Book(title, ...
import matplotlib.pyplot as plt x_values = list(range(1, 1001)) y_values = [x**2 for x in x_values] # s表示点大小 # edgecolor表示轮廓颜色 # c表示点颜色 # p1t.scatter(x_values, y_values, s=40, edgecolor='none', c='red') # cmap设置颜色映射,数据从小到大,则颜色由浅变深 # 这里要设置点颜色c=y_values plt.scatter(x_values, y_values, s=40, edgecolor='none', c=y_valu...
""" 输入学生考试成绩计算平均分 """ def main(): number = int(input("请输入学生人数:")) names = [None] * number scores = [None] * number for index in range(len(names)): names[index] = input("请输入第【%d】个学生的姓名:" % (index + 1)) scores[index] = float(input("请输入第【%d】个学生的成绩:" % (index + 1))) total...
import math radius = float(input('请输入圆的半径:')) peremeter = 2 * math.pi * radius area = math.pi * radius * radius print('圆的半径长%.2f,周长%.2f,面积%.2f' %(radius, peremeter, area))
name = input('請輸入名字: ') #遇到input 程式會等到使用者輸入才結束 print('嗨', name) #問完問題想要把回答儲存 取變數 把右邊的輸入東西存進name #先印出嗨這個單獨的字串 再印出name這個變數 這裡是印出兩個東西 一個字串和一個變數
class BinaryTree(): def __init__(self, val): self.value = val self.left = None self.right = None self.parent = None def set_left(self,node): self.left = node self.left.parent = self def set_right(self,node): self.right = node self.right.paren...
# craps.py # # This program simulates the dice game craps. The user starts with $100 and is allowed to bet on the roll of two # six-sided dice: # # - A roll of 7 or 11 on the opening throw results in a win # - A roll of 2, 3, or 12 on the opening throw results in a loss # - A roll of anything else means the user has...
''' #acceptint user input x=int(input("Enter the value of x")) print(x) y=5 print(y) #multiplication a = 10 b = 20 c = a * b print(c) #mnemonic multiplication hrs=10 rate=5 pay=hrs*rate print(pay) #assignment operator g=0.5 print(g) g=3.9*g*(1-g) print ("This is new value of g :",g) #numeric expression xx=56 yy=25...
import math def loc_angle(c, a, b): numerator = math.pow(c, 2) - math.pow(a, 2) - math.pow(b, 2) denominator = -2*a*b frac = numerator / denominator result = math.acos(frac) return math.degrees(result) print(loc_angle(5, 4, 3))
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Intervals # @return a list of Interval def merge(self, intervals): i=0 #moveahead=0 while(i+1...
# To find where the target element should be inserted in the sorted list. #lightest class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l = 0 r = len(nums) - 1 while l<=r: m = l + int((r-l) / 2) if nums[m] < target: l ...
class Solution: # @param A : list of list of integers # @return a list of list of integers def diagonal(self, A): m=len(A) n=len(A[0]) listy=[] for i in range(m+n-1): ni=[] for j in range(i+1): if(j...
#using heapq class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: # graph g = defaultdict(lambda:[]) #heapq q= ["JFK":["ATL","SFO"]] for u,v in tickets: # to maintain sort heap heapq.heappush(g[u],v) ans = [] def go(s): # check if any airport need to travel f...
from stack_and_queue.node import Node class Queue: def __init__(self): self.front=None self.rear=None def enqueue(self, value): node=Node(value) if not self.rear: self.front=node self.rear=node else: self.rear.next=node ...
from typing import List, Optional, Union, Dict import numpy as np import pandas as pd from feature_engine.base_transformers import BaseNumericalTransformer from feature_engine.variable_manipulation import _check_input_parameter_variables class CyclicalTransformer(BaseNumericalTransformer): """ The CyclicalTr...
def validate_brackets(string): stack = [] for char in string: # If its opening bracket, so push it in the stack if char == '{' or char == '(' or char == '[': stack.append(char) # Else if its closing bracket then check if the stack is empty then return false or # Po...
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next class Queue: def __init__(self, node=None): self.front = node self.rear = node def enqueue(self, value): node = Node(value) if self.front is None: self.f...
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; ...
# The arithmetic sequence, 1487, 4817, 8147, in which each of the # terms increases by 3330, is unusual in two ways: # (i) each of the three terms are prime, and, # (ii) each of the 4-digit numbers are permutations # of one another. # # There are no arithmetic sequences made up of three 1-, 2-, # or 3-...
''' It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20...
def divisors(num): try: if num<0: raise ValueError("Tiene que ser numero positivo") divisors = [] for i in range(1,num + 1): if num % i == 0: divisors.append(i) return divisors except ValueError as ve: print(ve) return Fa...
#Convert Decimal number to Binary Number dec_n=int(input("Enter number")) bin_n=0 k=1 while dec_n!=0: r=int(dec_n%2) bin_n=bin_n+(r*k) dec_n=dec_n/2 k=k*10 print(bin_n) '''output: Enter number10 1010'''
print ( "mengubah Huruf Kecil menjadi Kapital") print( "silahkan masukan huruf yang ingin diubah") a=input () #perintah input() untuk memasukkan string print("menjadi =", a.upper()) print("========================")
kısakenar = input("kısa kenarı giriniz") uzunkenar = input("uzun kenarı giriniz") cevre = (int(kısakenar) + int(uzunkenar)) alan = int(kısakenar) * int(uzunkenar) print("\nDikdörtgenin Çevresi : {0}".format(cevre)) print("\nDikdörtgenin Alanı : {0}".format(alan))
#!/usr/bin/python __author__ = 'Mayank' # Although normally set in a setter method, instance attribute values can be set anywhere # Encapsulation in python is a voluntary restriction # Python does not implement data hiding, as does java class MyClass(object): def set_val(self, val): self.val = ...
#!/usr/bin/python __author__ = 'Mayank' class MyInteger(object): def set_val(self, val): try: val = int(val) except ValueError: return self.val = val def get_val(self): return self.val def increment_val(self): self.val = sel...
#!/usr/bin/python __author__ = 'Mayank' import random class Animal(object): def __init__(self, name): self.name = name class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) self.breed = random.choice(['Lebrador', 'German Shepherd', 'Bulldog', 'Go...
# coding=utf-8 while 1 : words = input("谁是这个世界上最美的女生?") if words == "林嘉婷" : print("真聪明~") while 1: answer = input("你喜欢她吗?") if answer== "喜欢": print("她说她也喜欢你哦~") break else: print("我再问你一遍!") continu...
''' Class for drawing a Circuit in matplotlib or other output matplotlib output is generated by the PlotQCircuit library: https://github.com/rpmuller/PlotQCircuit Multi-bit gates will be displayed on the last bit with the others drawn as control bits. Example: ``` from circuit import QuantumCircuit from gate...
from help import insertion_sort, test_k def quicksort(arr, k = 0, start = 0, end = None): if end is None: end = len(arr) - 1 if end <= start: return if len(arr) <= k: insertion_sort(arr) return div_ind = (start + end) // 2 divider = arr[div_ind] i...
import random class HashTable: def __init__(self, M, C=None): if M == 0: raise Exception("M must be greater than 0") self.M = M self.C = C or 0.61 self.values = [None] * M @staticmethod def h1(number, M, C): return int(M * ((C * number)...
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' import numpy as np from log_api import log class Solution(): def solve(self, A): return np.poly1d(A) * np.poly1d(np.array([2.0, 0.0, -1.0, 1.0])) ''' 在Numpy中,多项式函数的系数可以用一维数组表示,例如对于f(x)=2x^3-x+1可表示为f=np.array([2.0,0.0,-1.0,...
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' from scipy.stats import chi2 from log_api import log class Solution(): def solve(self): data = ((154, 132), (180, 126), (104, 131)) total_x = (286, 306, 235) total_y = (438, 389) total = 827 c...
import random def pickDices(): diceList = ['d4','d6','d6', 'd8','d8','d8','d8','d10','d10','d12','d20','d20','d20'] firstThreeDices = random.sample(diceList, 3) print("First three dices are: ", firstThreeDices) for dice in firstThreeDices: diceList.remove(dice) print("Remaining Dice...
import csv import copy """ This is a very useful class for Chris, and others who might work with CSV data often. The key data structure to know about is that each row is naturally stored as a dictionary where column names are keys as opposed to a list. Here are the assumptions made: If a row has missing elements, ...
from room1 import Room from player1 import Player # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons."), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Gra...
answer = input("Would you like to play? (yes/no) ") if answer.lower().strip() == "yes": answer = input("you reach a crossroads, would you like to go left or right").lower().strip() if answer == "left": answer = input("you encounter a monster, would you like to run or attack.") if an...
''' Joseph Erwin Internship Game Project ''' from hero import Hero from os import path, chdir def selectHero(heroList, prompt): # Ask the user to provide input based on the prompt heroNum = int(input(prompt)) # Return the hero at the input index return heroList[heroNum] def heroCombat(heroes): ...
SIZE = 100 Q = [0] * SIZE front, rear = -1, -1 def isFull(): if rear == len(Q): return True else: return False def isEmpty(): if front == rear: return True else: return False def enQueue(item): global rear rear += 1 Q[rear] = item def de...
answer = [] oneBlock_dy = [1, -1, 0, 0] oneBlock_dx = [0, 0, 1, -1] diagonal_dy = [1, 1, -1, -1] diagonal_dx = [1, -1, 1, -1] def check_oneBlock(place, y, x): for i in range(4): if place[y][x] == 'P': Y = y + oneBlock_dy[i] X = x + oneBlock_dx[i] if 0 <= Y < 5 and 0 ...
words = input() def my_strrev(words): long = int(len(words) // 2) re_words = list(words) for i in range(long): re_words[i], re_words[-i-1] = words[-i-1], words[i] return ''.join(re_words) print(my_strrev(words)) #-------------------------------- s = "Reverse this strings" s = s[:...
str1 = "abc 1, 2 ABC" print(str1) str1 = str1.replace("1, 2", "one, two") print(str1)
# 비트마스크 ############################################## # 공집합 zero = 0 print(bin(zero)) # '0b0' ############################################## # 꽉 찬 집합 ( 20 bit ) full = (1 << 20) - 1 print(bin(full)) # '0b11111111111111111111' # '0b100000000000000000000'(21bit) 에서 1을 뺀 2진수 20bit 전체가 1인 2진수 ######################...
from generallibrary.functions import Operators import time from datetime import datetime import pytz from dateutil import parser from dateutil.tz import gettz import timeit class Timer: """ Callable class to easily time things and print. """ def __init__(self, start_time=None): """ Returns a started...
import sys if sys.argv[1] == "-": linia = raw_input() znak = "" while linia != znak: if linia.find(sys.argv[2])>-1: print (linia) linia = raw_input() linia = "" else: with open(sys.argv[1],"r") as plik: if linia.find(sys.argv[2])>-1: print ...
""" This class is responsible for the lecturer announcements feature so students can see the latest announcements from LiC """ from database.DataBaseManager import DataBaseManager class AnnouncementsGetter: def __init__(self, database_manager=DataBaseManager()): """Instantiate with a database inst...
""" This file contains the Authenticator class which is responsible for checking if a credential entered is correct or not and also give authority level to the user logging in. """ from database.DataBaseManager import DataBaseManager from conf.Logger import Logger """ Logger setup """ logger = Logger(...
""" Algorytm 18 1) Stwórz listę 'f' wypełnioną 1 i listę 'F' wypełnioną 2 (1...n). 2) Zdefiniuj zmienną boolowską 'koniec' i przypisz jej False. 3) Dopóki 'koniec' nie jest True, to wypisuj tablicę 'f'. 4) Przypisz 'j' wartośc 'n', jeśli f[j] jest równe F[j] to zmniejszaj 'j' o 1. 5) Gdy wartość 'j' jest większa od 1 t...
# Find the best response to any tic-tac-toe board configuration. # taking a memoized approach. # This could be used as a starting point for a full game with the ability # to play tic-tac-toe against an intelligent computer. # It also serves as an example for how to find brute-force solutions for # more complex g...
numeros = [0] * 6 # Ler os valores for i in range(6): numeros[i] = int(input('Valor: ')) # Verificar se são distintos distintos = True for i in range(6): # Verificar se o números da vez (i) é igual algum valor que # está após ele (j) na coleção. for j in range(i + 1, 6): # Se forem iguais, pod...
''' Para ler 4 números. Calcule e informe a soma dos números lidos! ''' soma = 0 qtde_pos = 0 qtde = int(input('Quantidade de iterações: ')) for i in range(qtde): num = int(input('Informe o {} valor: '.format(i + 1))) soma = soma + num if (num > 0): qtde_pos += 1 # soma += num print(so...
while(True): abriu_i = False abriu_b = False try: texto = input() texto_out = '' for s in texto: if (s == '_'): if (not abriu_i): texto_out += '<i>' abriu_i = True else: texto_out...
lista1 = [1,2,3,4] lista2 = [5,6,7,8] lista3 = lista1 + lista2 lista4 = lista3[4:len(lista3)] print(lista1, len(lista1)) print(lista2, len(lista2)) print(lista3, len(lista3)) print(lista4, len(lista4))
# Converter em maiúsculo # minúsculo: [97 - 122] palavra = input('Palavra: ') nova_palavra = '' for i in range(len(palavra)): #if (ord(palavra[i]) >= 97) and (ord(palavra[i]) <= 122): if (palavra[i] >= 'a') and (palavra[i] <= 'z'): nova_palavra += chr(ord(palavra[i]) - 32) else: nova_palav...
numeros = [0] * 10 # Ler os 10 valores for i in range(10): numeros[i] = int(input('Número: ')) # Exibir os números ímpares digitados for i in range(10): if (numeros[i] % 2 == 1): print(numeros[i])
# select only one element from each list, apply square data = [[1, 2, 3, 4], [5, 6, 7, 8], [8, 9, 10]] def getCartezianProduct(N): # storing 1st row elements as lists in product product = [[x] for x in N[0]] rest_rows = N[1:] for i in range(0, len(rest_rows)): # tmp will store cartezian product...
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 10:11:43 2020 @author: DAVID CAIZALUISA """ import numpy as np from random import randint print("Ingrese la cantidad de filas que desea: ") fis=int(input()) print("Ingrese la cantidad de columnas que desea: ") colu=int(input()) print("\n"*0) matr...
#Question 1 list=[] n=int(input("Enter how much integers you want in list\n")) print("Enter elements") for i in range(n): a=int(input()) list.append(a) print(list) #Question 2 list2=['google','apple','facebook','microsoft','tesla'] list.extend(list2) print(list) #Question 3 list3=[1,1,2,3,4,3,4,5,3,2,3,3] pri...
class FormattedWord: def __init__(self, word, capitalize=False) -> None: self.word = word self.capitalize = capitalize class Sentence(list): def __init__(self, plain_text): for word in plain_text.split(' '): self.append(FormattedWord(word)) def __str__(self) -> str: ...
from copy import deepcopy class Address: def __init__(self, street, suite, city) -> None: self.street = street self.suite = suite self.city = city def __str__(self) -> str: return f'{self.street}, Suite #{self.suite}, {self.city}' class Employee: def __init__(self, name,...
#Create board, an array of arrays board=[['BR','BKn','BB','BQ','BK','BB','BKn','BR'],['BP','BP','BP','BP','BP','BP','BP','BP'],['','','','','','','',''],['','','','','','','',''],['','','','','','','',''],['','','','','','','',''],['WP','WP','WP','WP','WP','WP','WP','WP'],['WR','WKn','WB','WQ','WK','WB','WKn','WR']] r...
def conversacion(mensaje): print('Hola') print('Como estás') print(mensaje) print('Adios') opcion = int(input('Elige una opcion: (1, 2, 3): ')) if opcion == 1: conversacion('Elegiste la opcion 1') elif opcion == 2: conversacion('Elegiste la opcion 2') elif opcion == 3: conversacion('Elegist...
import datetime # imports the datetime fields needed for the game print('---------------------------------') print(' BIRTHDAY APP') # gives name of the game print('---------------------------------') print() year= int(input('what year were you born in [YYYY]:')) # asking for year of birth month = int(input(...
print('-------------------------------------') print(' SEARCHING APP ') print('-------------------------------------') # imports all required libraries import os import time arb=None # main function def main(): filename = None while filename is None: # asks for the name and directory of...
""" Example of Decision Tree Algorithms usage. This Example uses the Play tennis Dataset from Kaggle: https://www.kaggle.com/datasets/fredericobreno/play-tennis """ import pandas as pd from mlkit.classification.decision_tree import DecisionTree def example_tennis_categorical(): target = 'target' df = pd.read_csv('...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 5 14:02:34 2017 @author: janusboandersen """ #inputfile = "dna.txt" #f = open(inputfile, "r") #seq = f.read() inputfile = "dna.txt" def read_seq(inputfile, cds_start=0, cds_stop=0, mod_crop=1): """ Reads and returns the input sequence w...
# Maxwell Lin 46268364 class gamestate: def __init__(self,list_2d,turn): self._board = list_2d self._turn = turn def print_board(self): for rows in self._board: row = [] for cols in rows: row.append(cols) print(' '.join(...
# -*- coding: utf-8 -*- ''' 字符串连续出现的字符压缩成一个字符并在后面加上该字符的次数 eg: s = 'aaabdd' output: r = 'a3b1d2' ''' s = 'aaabddd' r = [] last = s[0] count = 1 for e in s[1:]: if last != e: r.append(last) r.append(str(count)) last = e count =...
# -*- coding: utf-8 -*- ''' 请实现一个算法,翻转一个给定的字符串. eg: "This is nowcoder!" output: !redocwon si sihT ''' def reversestr(s): low = 0 high = len(s) - 1 s2 = [e for e in s] while low < high: s2[low], s2[high] = s2[high], s2[low] low += 1 ...
# -*- coding: utf-8 -*- ''' 题目描述 输入一组勾股数a,b,c(a≠b≠c),用分数格式输出其较小锐角的正弦值。(要求约分。) 输入格式 一行,包含三个数,即勾股数a,b,c(无大小顺序)。 输出格式 一行,包含一个数,即较小锐角的正弦值 ''' nums_str = input().split() nums = [int(e) for e in nums_str] # 做排序的操作 nums.sort() a, _, c = nums def gcd(a, b): if b == 0: return a ...
# -*- coding: utf-8 -*- ''' 题目描述 Given two integers A and B, A modulo B is the remainder when dividing A by B. For example, the numbers 7, 14, 27 and 38 become 1, 2, 0 and 2, modulo 3. Write a program that accepts 10 numbers as input and outputs the number of distinct numbers in the input, if the numbers are...
# -*- coding: utf-8 -*- from collections import namedtuple # 二叉树的创建 ''' 补空法,是指如果左子树或右子树为空时,则用特殊字符补空,如'#'.然后先按照先序遍历 的顺序,得到先序遍历序列,根据该序列递归创建二叉树 ''' class Node: def __init__(self, val): self.val = val self.left = self.right = None def __str__(self): return...
# -*- coding: utf-8 -*- # 切蛋糕递归算法 def sum2(arr, index): if index == len(arr): return 0 return arr[index] + sum2(arr, index + 1) a = list(range(101)) print('a is', sum2(a, 0)) # 翻转字符串 a = 'abcd' r = [] def revse(s, index): if index == -1: return # pri...
# -*- coding: utf-8 -*- import threading from threading import Lock import time from queue import Queue from typing import Callable def printFirst(): print('first') def printSecond(): print('second') def printThird(): print('third') class Foo: def __init__(self): se...
# -*- coding: utf-8 -*- ''' 判断一个字符串是否为 回文字符串。 ''' s = 'abccba' reverse_s = ''.join(reversed(s)) print('s is', s) print('reverse of s is', reverse_s) res = s == reverse_s print('res is', res)
# -*- coding: utf-8 -*- # 通过python的list来进行顺序存储的逻辑 # 而且我们通过索引1的位置开始存储 # 如上所示0代表我们不存储任何值 # 小顶堆的下沉的操作 def sink(nums, k, n): while k * 2 <= n: m = le = k * 2 # 替换到下一个节点 ri = le + 1 if ri <= n and nums[ri] > nums[le]: m += 1 if nums[k] < nums[...
# -*- coding: utf-8 -*- ''' 编写某个方法,返回集合的所有的子集 给定 ''' import copy # 递归模式 def getsubsetscore(s, index): if index == len(s): return [set()] # # if index == len(s) - 1: # return [set(), {s[index]}] c = s[index] old_set = getsubsetscore(s, index + 1) ...
# -*- coding: utf-8 -*- # 算法思路,所需要找的最小值一定是在无序的那段区间之中 a = list(range(4, 20)) a = a + [0, 1, 2, 3] # a = [5, 6, 1, 2, 3] print('a is', a) def findMin(nums, low, high): # if low == high: # return nums[low] if low + 1 == high: return min(nums[low], nums[high]) mid = ...
# -*- coding: utf-8 -*- a = list(range(10 ** 3, -1, -1)) print('希尔排序前 a is ', a) interval = len(a) // 2 while interval > 0: i = 0 while i < interval: for j in range(i + interval, len(a), interval): ii = j tmp = a[j] # 边界条件确实需要斟酌!!! whi...
# -*- coding: utf-8 -*- # def pow0(a: int, n: int) -> int: # if n == 0: # return 1 # # return a * pow0(a, n - 1) # # r = pow0(2, 3) # print('r is ', r) ''' 高效的模式的确很高效的策略 ''' def pow2(a: int, n: int) -> int: if n == 0: return 1 res = a ex = 1 whi...
# -*- coding: utf-8 -*- nums = list(range(9, -1, -1)) print('nums is ', nums) # 分区的逻辑的确很重要的特性!!! def partition(nums, low, high) -> int: ''' 一遍单向扫描法,定主元的情况 该分区算法的逻辑是把第一个当做最大值来进行考虑,然后从中把最大的值放入到 临界的那个位置中去 :param nums: :param low: :param high: :return: 返回的值...
# -*- coding: utf-8 -*- k = 5 glo_d = { 'k': k, 'heap': [0] * k, 'size': 0, } print('heap is', glo_d['heap']) # 目前我们使用数组来代表堆的使用 def minHeap(nums): for i in range(len(nums) // 2 - 1, -1, -1): minheapfixdown(nums, i, len(nums)) def minheapfixdown(nums, i, n): # 找到左...
"""Contains the TrieNode class, that represents a node of the Prefix Trie. Use list_completions to retrieve the list of completions of a given word. """ __all__ = ['TrieNode', 'list_completions'] class TrieNode(object): """Node of the Trie. Contains value and children nodes""" def __init__(self): se...
import shutil columns = shutil.get_terminal_size().columns def Merge(array, copy, low, mid, high): k,i = low,low j = mid+1 while i<=mid and j<=high: if array[i]<=array[j]: copy[k] = array[i] i += 1 k += 1 else: copy[k]=array[j] j +...
class Stack: def __init__(self): self._data = [] def push(self, e): self._data.append(e) def pop(self): return self._data.pop() def len(self): return len(self._data) def is_empty(self): return not self._data def top(self): if self.is_empty(): ...
import numpy as np from copy import deepcopy ''' Experiment 5: - A population of input excitatory neurons. - A population of output excitatory neurons. - A single, very strong, IIN. We're trying to understand the connection between the inhibitory threshold size and the number of winners (among output neurons), where ...
#1 - Define a dictionary call story1, it should have the following keys: # 'start', 'middle' and 'end' story1 = { "start": "Villain destroying earth", "middle": "Hero fights with villain", "end": "Hero saves earth from the villain" } #2 - Print the entire dictionary print(story1) #3 - Print the ty...
# EJERCICIO 12 # Participante: # Jose Luis Hernandez Meza # Import of modules import argparse import time import os import DetectEs # Start argparse parser = argparse.ArgumentParser( description = "Cesar Encryption Tool" ) # We add the required arguments parser.add_argument( "-mode", ...
import random # Define the players and their bets players = { 'Lou': 100, 'David': 200, 'Dan': 500 } # Calculate the total amount of money collected total_money = sum(players.values()) # Calculate the value of each square square_value = total_money / 100 # Create an empty 10x10 grid to store the assigne...
# Rename the key size to amount for any dictionary of the same style recipe = { 'ingredients': [ {'id': 1, 'ingredient': 'flour', 'size': 200, 'measurement': 'mg'}, {'id': 2, 'ingredient': 'eggs', 'size': 2, 'measurement': 'egg'}, {'id': 3, 'ingredient': 'milk', 'size': 3, 'measurement': 'm...
def solution(nums): answer = 0 if len(set(nums)) > len(nums)//2: answer = len(nums)//2 else: answer = len(set(nums)) return answer print(solution([3,1,2,3])) print(solution([3,3,3,2,2,4])) print(solution([3,3,3,2,2,2]))
# -*- coding: utf-8 -*- # class for places class Ort: def __init__(self, name, beschreibung): self.name = name self.beschreibung = beschreibung self.nach = {} richtungen = ("norden", "süden", "osten", "westen", "oben", "unten") bar = Ort( "Die Bar", "Du nichtnütziges Stück Schafscheiße ...
""" The approach to this problem is to maintain a dp array, which stores T or F based on if the wordDict contains the sub-string till the current index, if so we can consider the sub-string till the current index and at any given point if the other part of the main string i.e is the remaing part which has not been sto...