text
stringlengths
37
1.41M
# Understanding of Data Pre-processing for given dataset 1 using Spyder (Python) import numpy as np import pandas as pd dataset= pd.read_csv('dataset1.csv') dataset.shape dataset.info() X=dataset.iloc[:,:-1].values X Y=dataset.iloc[:,-1].values Y # 2. Replace Missing values by below imputation...
a, b, c = map(int, raw_input().split()) def any_odd(x, y, z): if x % 2 or y % 2 or z % 2: return True else: return False def exchange(a, b, c): new_a = b // 2 + c // 2 new_b = a // 2 + c // 2 new_c = a // 2 + b // 2 return new_a, new_b, new_c if a == b == c and (a + b + c) % ...
#!/usr/bin/env python # coding: utf-8 # In[1]: # Importing libraries to be used. import turtle import time import random delay = 0.1 # Delay variable which will be used for the delay of the screen. score = 0 # Storing current score of your game. high_score = 0 # Storing high score of your game. win = turtle...
''' Filename: Negascout.py Description: Responsible for finding an optimal move based on its evaluation function. @author: Hristo Asenov ''' import Evaluation import MoveGenerator import string import Common import bisect class Negascout(object): ## # Constructor Negascout def __init__(self, board, colo...
x = int(input()) y = int(input()) a = int(input()) b = int(input()) if ((x + y) % 2 == 0) and ((a + b) % 2 == 0): print("YES") elif ((x + y) % 2 != 0) and ((a + b) % 2 != 0): print("YES") else: print("NO")
# # @lc app=leetcode.cn id=329 lang=python3 # # [329] 矩阵中的最长递增路径 # # https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/description/ # # algorithms # Hard (40.91%) # Likes: 193 # Dislikes: 0 # Total Accepted: 14.6K # Total Submissions: 35.6K # Testcase Example: '[[9,9,4],[6,6,8],[2,1,1]]' # # 给...
# # @lc app=leetcode.cn id=1021 lang=python3 # # [1021] 删除最外层的括号 # # https://leetcode-cn.com/problems/remove-outermost-parentheses/description/ # # algorithms # Easy (76.90%) # Likes: 117 # Dislikes: 0 # Total Accepted: 30.2K # Total Submissions: 39.1K # Testcase Example: '"(()())(())"' # # 有效括号字符串为空 ("")、"(" + ...
# # @lc app=leetcode.cn id=152 lang=python3 # # [152] 乘积最大子数组 # # https://leetcode-cn.com/problems/maximum-product-subarray/description/ # # algorithms # Medium (39.69%) # Likes: 621 # Dislikes: 0 # Total Accepted: 74.4K # Total Submissions: 187.4K # Testcase Example: '[2,3,-2,4]' # # 给你一个整数数组 nums ,请你找出数组中乘积最大的...
# # @lc app=leetcode.cn id=143 lang=python3 # # [143] 重排链表 # # https://leetcode-cn.com/problems/reorder-list/description/ # # algorithms # Medium (55.97%) # Likes: 234 # Dislikes: 0 # Total Accepted: 26.9K # Total Submissions: 48.1K # Testcase Example: '[1,2,3,4]' # # 给定一个单链表 L:L0→L1→…→Ln-1→Ln , # 将其重新排列后变为: L0→...
# # @lc app=leetcode.cn id=187 lang=python3 # # [187] 重复的DNA序列 # # https://leetcode-cn.com/problems/repeated-dna-sequences/description/ # # algorithms # Medium (44.51%) # Likes: 102 # Dislikes: 0 # Total Accepted: 19K # Total Submissions: 42.5K # Testcase Example: '"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"' # # 所有 DNA ...
# # @lc app=leetcode.cn id=6 lang=python3 # # [6] Z 字形变换 # # https://leetcode-cn.com/problems/zigzag-conversion/description/ # # algorithms # Medium (48.05%) # Likes: 703 # Dislikes: 0 # Total Accepted: 137.1K # Total Submissions: 285.4K # Testcase Example: '"PAYPALISHIRING"\n3' # # 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 ...
# # @lc app=leetcode.cn id=224 lang=python3 # # [224] 基本计算器 # # https://leetcode-cn.com/problems/basic-calculator/description/ # # algorithms # Hard (38.02%) # Likes: 205 # Dislikes: 0 # Total Accepted: 14.8K # Total Submissions: 39K # Testcase Example: '"1 + 1"' # # 实现一个基本的计算器来计算一个简单的字符串表达式的值。 # # 字符串表达式可以包含左括号...
# # @lc app=leetcode.cn id=912 lang=python3 # # [912] 排序数组 # # @lc code=start class Solution: def sortArray(self, nums: List[int]) -> List[int]: import random def quick_sort(arr, l, r): if l < r: q = partition2(arr, l, r) quick_sort(arr, l, q - 1) ...
# # @lc app=leetcode.cn id=884 lang=python3 # # [884] 两句话中的不常见单词 # # https://leetcode-cn.com/problems/uncommon-words-from-two-sentences/description/ # # algorithms # Easy (62.25%) # Likes: 62 # Dislikes: 0 # Total Accepted: 10.9K # Total Submissions: 17.5K # Testcase Example: '"this apple is sweet"\n"this apple ...
# # @lc app=leetcode.cn id=164 lang=python3 # # [164] 最大间距 # # https://leetcode-cn.com/problems/maximum-gap/description/ # # algorithms # Hard (55.14%) # Likes: 168 # Dislikes: 0 # Total Accepted: 15.8K # Total Submissions: 28.7K # Testcase Example: '[3,6,9,1]' # # 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 # # 如果数组元素个数小于...
# # @lc app=leetcode.cn id=66 lang=python3 # # [66] 加一 # # https://leetcode-cn.com/problems/plus-one/description/ # # algorithms # Easy (44.34%) # Likes: 485 # Dislikes: 0 # Total Accepted: 164.1K # Total Submissions: 370K # Testcase Example: '[1,2,3]' # # 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 # # 最高位数字存放在数组的首位, 数组中...
# # @lc app=leetcode.cn id=599 lang=python3 # # [599] 两个列表的最小索引总和 # # https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/description/ # # algorithms # Easy (50.84%) # Likes: 73 # Dislikes: 0 # Total Accepted: 15.2K # Total Submissions: 29.7K # Testcase Example: '["Shogun","Tapioca Express","Burger K...
# # @lc app=leetcode.cn id=139 lang=python3 # # [139] 单词拆分 # # https://leetcode-cn.com/problems/word-break/description/ # # algorithms # Medium (44.84%) # Likes: 461 # Dislikes: 0 # Total Accepted: 56.9K # Total Submissions: 127K # Testcase Example: '"leetcode"\n["leet","code"]' # # 给定一个非空字符串 s 和一个包含非空单词列表的字典 wo...
# # @lc app=leetcode.cn id=583 lang=python3 # # [583] 两个字符串的删除操作 # # https://leetcode-cn.com/problems/delete-operation-for-two-strings/description/ # # algorithms # Medium (49.27%) # Likes: 118 # Dislikes: 0 # Total Accepted: 8K # Total Submissions: 16.2K # Testcase Example: '"sea"\n"eat"' # # 给定两个单词 word1 和 wor...
# # @lc app=leetcode.cn id=493 lang=python3 # # [493] 翻转对 # # https://leetcode-cn.com/problems/reverse-pairs/description/ # # algorithms # Hard (25.94%) # Likes: 99 # Dislikes: 0 # Total Accepted: 4.9K # Total Submissions: 19K # Testcase Example: '[1,3,2,3,1]' # # 给定一个数组 nums ,如果 i < j 且 nums[i] > 2*nums[j] 我们就将...
# # @lc app=leetcode.cn id=1221 lang=python3 # # [1221] 分割平衡字符串 # # https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/description/ # # algorithms # Easy (78.34%) # Likes: 53 # Dislikes: 0 # Total Accepted: 19.4K # Total Submissions: 24.7K # Testcase Example: '"RLRRLLRLRL"' # # 在一个「平衡字符串」中,'L' 和...
# # @lc app=leetcode.cn id=142 lang=python3 # # [142] 环形链表 II # # https://leetcode-cn.com/problems/linked-list-cycle-ii/description/ # # algorithms # Medium (49.71%) # Likes: 449 # Dislikes: 0 # Total Accepted: 69.2K # Total Submissions: 139K # Testcase Example: '[3,2,0,-4]\n1' # # 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,...
# # @lc app=leetcode.cn id=14 lang=python3 # # [14] 最长公共前缀 # # https://leetcode-cn.com/problems/longest-common-prefix/description/ # # algorithms # Easy (38.24%) # Likes: 1094 # Dislikes: 0 # Total Accepted: 288.5K # Total Submissions: 754.2K # Testcase Example: '["flower","flow","flight"]' # # 编写一个函数来查找字符串数组中的最...
# # @lc app=leetcode.cn id=86 lang=python3 # # [86] 分隔链表 # # https://leetcode-cn.com/problems/partition-list/description/ # # algorithms # Medium (58.13%) # Likes: 214 # Dislikes: 0 # Total Accepted: 39.3K # Total Submissions: 67.6K # Testcase Example: '[1,4,3,2,5,2]\n3' # # 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在...
# # @lc app=leetcode.cn id=559 lang=python3 # # [559] N叉树的最大深度 # # https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/description/ # # algorithms # Easy (69.61%) # Likes: 93 # Dislikes: 0 # Total Accepted: 25.9K # Total Submissions: 37.2K # Testcase Example: '[1,null,3,2,4,null,5,6]' # # 给定一个 N 叉树,找到其最...
# # @lc app=leetcode.cn id=70 lang=python3 # # [70] 爬楼梯 # # https://leetcode-cn.com/problems/climbing-stairs/description/ # # algorithms # Easy (49.73%) # Likes: 1076 # Dislikes: 0 # Total Accepted: 222.6K # Total Submissions: 447.6K # Testcase Example: '2' # # 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # # 每次你可以爬 1 或 2 个台阶。你有多少种不...
# # @lc app=leetcode.cn id=121 lang=python3 # # [121] 买卖股票的最佳时机 # # https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/ # # algorithms # Easy (54.19%) # Likes: 1011 # Dislikes: 0 # Total Accepted: 219.5K # Total Submissions: 405.1K # Testcase Example: '[7,1,5,3,6,4]' # # 给定一个数组,它的第 i 个元...
# # @lc app=leetcode.cn id=216 lang=python3 # # [216] 组合总和 III # # https://leetcode-cn.com/problems/combination-sum-iii/description/ # # algorithms # Medium (71.26%) # Likes: 123 # Dislikes: 0 # Total Accepted: 22.3K # Total Submissions: 31.3K # Testcase Example: '3\n7' # # 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的...
# # @lc app=leetcode.cn id=719 lang=python3 # # [719] 找出第 k 小的距离对 # # https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/description/ # # algorithms # Hard (32.99%) # Likes: 99 # Dislikes: 0 # Total Accepted: 4.3K # Total Submissions: 12.8K # Testcase Example: '[1,3,1]\n1' # # 给定一个整数数组,返回所有数对之间的第 ...
import matplotlib.pyplot as plt import numpy as np def simple_process(): cnt = 2 primes = [] x = [] y = [] while True: flag = True for i in range(2, cnt): if cnt % i == 0: flag = False break if flag is True: primes.app...
import functools nums = [1, 2, 1, 3, 2, 5] ret = functools.reduce(lambda x, y: x ^ y, nums) div = 1 while div & ret == 0: div <<= 1 a, b = 0, 0 for n in nums: if n & div: a ^= n else: b ^= n print([a, b])
class Apartamento: def __init__(self): self.id = int() self.numero = str() self.torre = None self.vaga = int() self.proximo = None def cadastrar(self, valor): self.id = int(input("Digite o id do apartamento: ")) self.numero = str(input("Digite o...
import tkinter as tk from tkinter import ttk window = tk.Tk() window.title("My Window") window.geometry("600x600+0+0") namelabel = ttk.Label(window, text="Miss P", foreground="red", font=("Helvetica", 58)) namelabel.pack() whatisnamelabel = ttk.Label(window, text="Hello, what is your name?") whatisnamelabel.pack() ...
import tkinter as tk from tkinter import ttk window = tk.Tk() window.title("My Window") window.geometry("600x600+0+0") namelabel = ttk.Label(window, text="Miss P", foreground="red", font=("Helvetica", 58)) namelabel.pack() #In order to show the image in our program, we first need to know where to find it #THE IMAGE ...
import sqlite3 # initialize database def create_db(db_name): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS DENTALINFO (dentist_id integer PRIMARY KEY AUTOINCREMENT, dentist_name text NOT NULL, location text ...
#!python from sorting_iterative import is_sorted, bubble_sort, selection_sort, insertion_sort from timeit import default_timer as timer def random_ints(count=20, min=1, max=50): """Return a list of `count` integers sampled uniformly at random from given range [`min`...`max`] with replacement (duplicates are ...
""" Three columns CSV to JSON converter """ import csv def isLast(itr): old = next(itr) for new in itr: yield False, old old = new yield True, old with open('misc-data/seventytwo-names.csv', 'r', encoding='utf-8') as cf: in_data = csv.reader(cf, delimiter=',') # num_rows = sum(1 fo...
import time #Some Functions and Exercice with while loop def tcheck_pass (): while input("password : ") != "sidali" : print("wrong !Try again !") print("Correct ,Comme on in ;) ") tcheck_pass() #fonction print from 1 to 10 n=1 while n<=10 : print(n) time.sleep(1) #This ligne make python pau...
# # This implements the ability to compose and pipe functions so that they can # short circuit the pipe/composition with a value to return class ReturnValue(Exception): """ This is used to short circuit the valuation and return ret """ def __init__(self, ret): self.ret = ret def runPipe(m,...
# Most callback-based frameworks, such as NodeJS and Tornado, handle events # using callback functions. For example if you want to download a webpage # you would do: # # downloadWebpage(url, function (contents) { /* handle page downloaded */ }) # # In Twisted, downloadWebpage would return a Deferred to which you would...
import random team1 = input("Enter The First Team: ") team2 = input("Enter The Second Team: ") team_name = False #Checking if Team 1 or Team 2 Input equals to Csk if team1.upper() == 'CSK' or team2.upper() == 'CSK': if(team1.upper() == 'CSK'): squad_of_team_1 = ['MS Dhoni(c)(wk)', 'Faf Du Plesis', ...
# Basic calculator in python 3.6 # Made in Turkey # By akerem16 # [EN] First we will get number of operations. We will run the code block according to what action will be taken. # [TR] ilk önce işlem numarasını almamız gerekiyor. Hangi işlem yapılacaksa ona göre kod bloğu çalıştıracağız. operationnumber = str(input(""...
def max_num (num1, num2, num3): #find the largest number in these 3 max=num1 if num1>=num2: if num1>=num3: max=num1 else: max=num3 elif num2>=num3: max=num2 else: max=num3 return max print (max_num(5, 3, 7)) def is_equal (str1, str2): #compar...
friends=["Bob", "John", "Jim", "gg"] first_friend=friends[0] print(first_friend) print(friends) print(friends[-1]) #negative index just overflow print(friends[1:3]) #print from index 1 to (3-1)print(friends[1:]) #print from index 1 to the end friends [1]="fuck" #modify the element in list index 1 to "fuck"
def checkDouble(x): for i in range(5): if str(x)[i] == str(x)[i+1] and str(x).count(str(x)[i]) <= 2: return True return False def checkIncreasing(x): sort = "".join(sorted(str(x))) if str(x) == sort: return True return False lowerLimit = 254032 upperLimit =...
#Pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais #ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 p/dia e R$ 0,15 por km rodado dias = int(input('Por quantos dias o carro foi alugado? ')) km = int(input('Quantos km rodados? ')) pagar = (dias*60)...
#Leia a altura e a largura de uma parede em metros, calcule a sua area e a quntidade # necessária de tinta para pinta-la, sabendo que cada l pinta 2m² altura = float(input('Digite a altura da parede em metros: ')) largura = float(input('Digite a largura da parece em metros: ')) mquadrado = altura * largura tinta = mqua...
n = input('Digite algo: ') print('Qual o tipo primitivo?', type(n)) print('É numérico?',n.isnumeric()) print('É alfanumérico? ',n.isalnum()) print('É alfa',n.isalpha()) print('É ascii',n.isascii()) print('É decimal', n.isdecimal()) print('É digit', n.isdigit()) print('É identifier', n.isidentifier()) print('É tudo minú...
'''Leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a media atingida: media abaixo de 5.0 REPROVADO media entre 5 e 6.9 RECUPERAÇÃO media 7 ou superior APROVADO''' n1 = float(input('Digite a primeira nota do aluno: ')) n2 = float(input('Digite a segunda nota do aluno: ')) ...
# holds all of the data in array values import os import sys import my_data from my_data import symptoms_names from my_data import symptoms_numbers from my_data import disease_match_to_symptom from my_data import symptom_match_to_disease # save these from the user entering them # should match with 392680, 8031, ...
*** Problem Statement # Given ‘N’ ropes with different lengths, we need to connect these ropes into one big rope with minimum cost. The cost of connecting two ropes is equal to the sum of their lengths. Example 1: Input: [1, 3, 11, 5] Output: 33 Explanation: First connect 1+3(=4), then 4+5(=9), and then 9+11(=20). So...
*** Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {l, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {l0, 5, 40} B[] = {5...
# Задание 3 # Функция принимает три числа a, b, c. Функция должна определить, существует ли треугольник с такими сторонами. # Если треугольник существует, вернёт True, иначе False. a=int(input()) b=int(input()) c=int(input()) def triangle (a,b,c): if a+b>c and b+c>a and a+c>b: print('True') else: ...
def task(): print('\n<<< Виконання завдання >>>') # Получаем строку и сразу разбираем её по словам в массив (список) через split() # Строка "привет всем и пока" в split сделает список: ['привет', 'всем', 'и', 'пока'] text = input('Введіть щось: ').split() # Перебираем каждое слово: # Создаём тип...
# Autor: Salamandra #Url del ejercicio: http://www.pythondiario.com/2013/05/ejercicios-en-python-parte-1.html # Definir una función generar_n_caracteres() que tome un entero n y devuelva el caracter multiplicado por n. Por ejemplo: generar_n_caracteres(5, "x") debería devolver "xxxxx". def generar_n_caracteres(caracte...
#sum program sum = 10 def calculate(): sum = 30 sum = sum + 20 currentSum = 200 totalSum = sum + currentSum print(totalSum) calculate(); print (sum)
# def info_person(): # person = {"name": "Jorge", "age": "31", "country": "Mexico", "programingLang": "Python"} # print "My name is ", person["name"] # print "My age is ", person["age"] # print "My country of birth is ", person["country"] # print "My favorite language is ", person["programingLang"] ...
def showStd(): students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] for data in students: print data["fi...
import csv import sys def count_for_chf(): with open('/Users/Shia/Documents/Capstone/FeatExtraction/data/brfss/extracted.csv', 'rb') as csv_file: reader = csv.DictReader(csv_file) count = [0, 0, 0, 0] # 0-40, 40-60, 60-80, 80+ for row in reader: if row['VETERAN3'] == '1': age = float(row['_AGE80']) ...
class SequenceIterator(): def __init__(self, sequence: object): self._sequence = sequence self._iterator = iter(self._sequence._contents) def __next__(self): while True: elem = next(self._iterator) if self._sequence._filter(elem): return ele...
from sys import argv from math import sqrt from typing import List from time import sleep class Sudoku: def __init__(self, sudoku: List[List[int]]): ''' :param sudoku: int[n][n] :attr N: n * n ''' self.board = sudoku self.N = len(self.board[0]) self.n = int(sqrt(self.N)) self.sep = "\n" + ("+ " + ("- ...
import math class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return str((self.x, self.y)) def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __ne__(self, other): return not self.__eq__(other...
'''#1 import math a, b, c = eval(raw_input("Enter a, b, c:")) n = b*b-4*a*c if (n>0): r1 =( -b + math.sqrt(b*b-4*a*c))/2*a r2 =( -b - math.sqrt(b*b-4*a*c))/2*a print(r1 , r2) elif (n==0): r1 =( -b + math.sqrt(b*b-4*a*c))/2*a r2 =( -b - math.sqrt(b*b-4*a*c))/2*a r1 = r2 print(r1) if (n<0) : ...
""" 날짜 : 2020/06/24 이름 : 이성진 내용 : 내장함수 교재 p231 """ # abs() : 절대값 r1 = abs(-5) r2 = abs(5) print('r1 :', r1) print('r2 :', r2) # all() : 리스트에서 0이 포함됐는지 검사하는 함수 r3 = all([1,2,3,4,5]) r4 = all([1,2,3,4,0]) print('r3 :', r3) print('r4 :', r4) # any() : 리스트에서 하나라도 True 값이 있으면 전체 True, 모두 False 이면 전체 False r5 ...
import sys import re import argparse import random import time # !/usr/bin/env python pwins = 0 cwins = 0 play = True pchoice = None draw = 0 def main(): print("Welcome to Rock Paper Scissors") parser = argparse.ArgumentParser(description='asdfasdfasdfas') parser.add_argument('--selection', '-s', help=...
""" Tic Tac Toe Player """ import math import copy from copy import deepcopy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): ""...
import tkinter as tk from tkinter.constants import END # screen window = tk.Tk() window.title("Calculator") window.iconbitmap("calculator.ico") # place to type in enter = tk.Entry(window, width = 45, borderwidth = 10) enter.grid(row = 0, column = 0, columnspan = 3) # print number in thing function def b...
''' Items held by players or found in rooms. Part of the text adventure game''' class Item(): ''' Items held by players or found in rooms. Base class for specialized item types.''' def __init__(self, name, description): self.name = name self.description = description def on_take(self...
from src.model.CollisionSide import CollisionSide def detect_collision_from_inside(collider, container): """ Detects if the `collider` has collided with the `container` from the inside :param collider: the collider :param container: the container :return: The side of the container where the collis...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # method 1: # hashmap # time complexity: O(m+n) # space complexity: O(m) or O(n) class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: ...
import unittest from typing import List """ 思路: 当 p 循环时, min_price 为 p 之前的最小值 将移动的 p 选定为最大值 在每一次循环中, p-min_price 为在 p 点卖时的最大收益 再取所有 p-min_price 里的最大值 """ class Solution1: def maxProfit(self, prices: List[int]) -> int: min_price = float("inf") max_profit = 0 for p in prices: min...
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes class Solution: def countPrimes(self, n: int) -> int: if n <= 2: return 0 isPrime = [True] * n isPrime[0] = isPrime[1] = False for i in range(2,n): if i * i >= n: break if isPrim...
def longest(s1, s2): s3 = s1 + s2 s3 = set(s3) s3 = list(s3) s3.sort() return "". join(s3)
import random def getList(dict): list = [] for key in dict.keys(): list.append(key) return list def initBackpack(): backpack = list() f = open("25.txt") # считываю грузоподъемность и вместимость firstline = f.readline() weight = firstline[0:firstline.index(...
#!/usr/local/bin python3 # encoding=utf-8 import os from PIL import Image # 图片最大减少的像素值 SQUARE_FIT_SIZE = 800 LOGO_FILE_NAME = 'catlogo.png' logo_im = Image.open(LOGO_FILE_NAME) logo_width, logo_height = logo_im.size print('logo image size:%s,%s' %(logo_width, logo_height)) os.makedirs('img_with_logo', exist_ok=True...
texto = "curso de Python 3" txt1 = texto.capitalize() # Curso de python 3 txt2 = texto.swapcase() # CURSO DE pYTHON 3 txt3 = texto.upper() # CURSO DE PYTHON 3 txt4 = texto.lower() # curso de python 3 txt5 = texto.title() # Curso De Python 3 texto = "curso de Python 3, Python básico" txt6 = texto.replace("Python", "Ja...
from tkinter import * import sqlite3,sys def connection(): try: conn=sqlite3.connect("student.db") except: print("cannot connect to the database") return conn def verifier(): a=b=c=d=e=f=0 if not student_name.get(): t1.insert(END,"<>Student name is required<>\n") ...
import random from games.cards.Card import Card TYPES_CARD = ["Diamond", "Spade", "Heart", "Club"] ACE_FACES = {"Jack": 11, "Queen": 12, "King": 13, "ACE": 14} class DeckOfCards: def __init__(self): # init the deck with all cards self.deck = self.__build_deck() def __shuffle(self): #...
''' 2- Sílaba 'pe' Se pide desarrollar un programa en Python que permita cargar por teclado un texto completo en una variable de tipo cadena de caracteres. Se supone que el usuario cargará un punto para indicar el final del texto, y que cada palabra de ese texto está separada de las demás por un espacio en blanco. El ...
''' 4. Punto en el plano Se pide realizar un programa que ingresando el valor x e y de un punto determine a que cuadrante pertenece en el sistemas de coordenadas. ''' x = float(input("\nIngrese el valor de 'x': ")) y = float(input("Ingrese el valor de 'y': ")) print() if x > 0 and y > 0: print(f"El punto corres...
''' 7. Tirada de moneda Programar una tirada de una moneda (opciones: cara o cruz) aleatoriamente. Permitir que un jugador apueste a cara o cruz y luego informar si acertó o no con su apuesta. ''' import random print(">>> TIRADA DE MONEDA <<<\n") print("Digite '1' si apuesta 'CARA'\n" "Digite '2' si apuesta 'C...
''' 23- Cálculo presupuestario En un hospital existen 3 áreas de servicios: Urgencias, Pediatría y Traumatología. El presupuesto anual del hospital se reparte de la siguiente manera: Urgencias 50%, Pediatría 35% y Traumatología 15% Cargar por teclado el monto del presupuesto total del hospital, y calcular y mostrar el...
class Solution: def search(self, nums, target): n = len(nums) if (n == 0): return False end = n - 1 start = 0 while (start <= end): mid = (start + end)//2 if (nums[mid] == target): return True if (not self.isB...
# """ # This is ArrayReader's API interface. # You should not implement it, or speculate about its implementation # """ #class ArrayReader(object): # def get(self, index): # """ # :type index: int # :rtype int # """ #binary_search in array of unknown length class Solution(object): d...
class Solution(object): ''' find shortest sub-array with degree same as original array. Degree =maximum frequency of any character/number ''' def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ countmap = {} left = {} # m...
#NOTE there is NO equivalent of TreeMap (sorted keys dictionary) in Python #There is collections.OrderedDict which stores keys in the order which elements were added to the dict #>>> a = OrderedDict() # >>> a[4] = 1 # >>> a # OrderedDict([(4, 1)]) # >>> a[6] = 2 # >>> print(a.keys()) # [4, 6] # >>> print(a.values()) cl...
''' There are several other data structures, like balanced trees and hash tables, which give us the possibility to binary_search for a word in a dataset of strings. Then why do we need trie? Although hash table has O(1) time complexity for looking for a key, it is not efficient in the following operations : 1. Findi...
class Trie: def __init__(self): self.key = None self.chars = [None]*26 def insert(trie, word): #max depth is 26 cur = trie for w in word: key = ord(w) - ord('a') #each level is for english alphabets in order a = 0 to z=25 if cur.chars[key] is None: cur.chars[k...
class RandomizedSet: def __init__(self): self.indexmap = {} #map of value to index (keys are sets element) key -> index of list self.elements = [] #list of elements All set keys are added here too """ Initialize your data structure here. """ def insert(self, va...
class Solution(object): def search(self, nums, target): start = 0 end = len(nums)-1 while start <= end: #have to check until start==end mid = (start + end)//2 if nums[mid] == target: return mid elif target < nums[mid]: end =...
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 10:15:01 2020 @author: kevin """ import gauss as gs import auxclass as aux import sys print("\n-------------Calculadora de Sistemas de Ecuaciones MxN-------------\nIngresa el numero de Ecuaciones: ") m = int(input())#Ecuaciones print("Ingresa el numero de ...
from collections import Iterator from copy import deepcopy class LinkedListIterator(Iterator): def __init__(self, linked_list): self.list = linked_list def __next__(self): if self.list is END: raise StopIteration t = self.list.head self.list = self.list.tail ...
def _reachable_tiles(self, convoy, path, reachable): if self.is_fleet: return _reachable_tiles() def _reachable_tiles_base(self, convoy, path, reachable): """ Compute all the reachable tiles for a given unit. This take into account all the adjacent land tiles and all the land tiles accessible...
import matplotlib.pyplot as plt import numpy as np def exhaustive_search(a, b, inc): ran = np.arange(a, b, inc) # print(ran) y = func(ran.__array__()) # print(y) plt.plot(ran, y) i: int for i in range(1, len(y) - 1): if (y[i - 1] > y[i] and y[i + 1] > y[i]) or (y[i] > y[i - 1] and ...
class Song(object): def __init__(self, rowId, title, artist): self.rowId = rowId self.title = title self.artist = artist def __str__(self): return "({0}, {1} - {2})".format(self.rowId, self.artist, self.title)
import sqlite3 def create_database(db_path): connection = sqlite3.connect(db_path) cursor = connection.cursor() create_person_table = '{}{}{}{}{}{}{}'.format( 'CREATE TABLE IF NOT EXISTS', ' person(id INTEGER PRIMARY KEY,', ' first_nam...
# Getting Started with Raspberry Pi Ch 4 Example 6 import pygame from pygame.locals import * import RPi.GPIO as GPIO import time def setup_leds(): GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.OUT) GPIO.setup(24, GPIO.OUT) GPIO.setup(25, GPIO.OUT) def output_to_led(value,leds): #simple 3 LED case ...
#!/usrs/bin/env python3 ''' Task : write a script to take a list as a parameter from a user and return its reversed version as a result. Example: [2, 3, 4, 5] if pass then result will be [5, 4, 3, 2] ''' #1Solution, Let's write a function def reverse_items_list(items_list): __reversed_items_list = [] __or...
''' Problem: Given a 32-bit signed integer, reverse digits of an integer. Example: Input: 123 Output: 321 Solution: (Slow) -Convert to string, reverse and convert to int ''' class Solution: def reverse(self, x: int) -> int: if (x < 0): s = str(-x) n...
''' validation for email ''' import re def check_valid_email(email): if (re.match("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$", email) != None): return email return "colud you please provide correct email " email = "abc@gmail.com" output = check_valid_email(email...