text
stringlengths
37
1.41M
# Shows how numbers work in python # An integer a = 4 print(a) # A floating point number b = 4.3 print(b) # Round down a float print(int(4.3)) # A string c = "1000" # If you try to do math on it, weird stuff will # happen print(c * 5) # So, convert a string to a number print(int(c) * 5)
idade = int(input("Digite a sua idade: ")) if idade >=0 and idade <= 12: print("Criança") else: if idade >= 13 and idade <=17: print("Adolescente") else: print("Adulto") ## 2 m1 = float(input("Insira a primeira nota: ")) m2 = float(input("Insira a segunda nota: ")) m3 = float(input("Insira...
def swap_bits(num): even = num & 0xAAAAAAAA odd = num & 0x55555555 even >>=1 odd <<= 1 out = even|odd return out num = 56 output = swap_bits(num) print(output)
# -*- coding: utf-8 -*- """ Created on Thu Jul 23 13:18:24 2020 @author: Santiago Quinga """ import numpy as np from random import randint print("\nIngrese cuantas filas se requieren: ") filas=int(input()) print("\nIngrese cuantas columnas se requieren: ") columnas=int(input()) print("\n"*0) matrix=np.zeros([fila...
# -*- coding: utf-8 -*- """ Created on Thu Jul 2 17:49:57 2020 @author: Santiago Quinga """ def isYearLeap(year): # # Un año es bisiesto si cumple lo siguiente: # es divisible por 4 y no lo es por 100 ó si es divisible por 400. if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0): retur...
# -*- coding: utf-8 -*- """ Created on Fri Jun 19 12:25:39 2020 @author: Santiago Quinga """ Nombre=input("Ingresa tu nombre: ") Apellido=input("Ingresa tu Apellido: ") Ubicacion=input("Ingresea tu Ubicacion: ") Edad=input("Ingresa tu edad: ") space=" " print("\n " *1) print("Hola que tal un gusto en conocerte"+space...
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 11:13:36 2020 @author: Santiago Quinga """ import numpy as np matrix=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.int64) print(matrix) print("\n") print("La matriz Tiene: ",matrix.ndim, " dimensiones")
# AUTHOR: HAIDER ALI SIDDIQUEE # DATE : 2/15/2020 # TIME : 4:59:01 # ABOUT : IMPLEMENTATION OF GRADIENT DESCENT FOR SQUARES import sys import math import random datafile = sys.argv[1] f = open (datafile, 'r') data = [] i = 0 l = f.readline() ###################### ##### READ DATA ###### ###################### whil...
import re pattern1 = "^(?![-._])(?!.*[_.-]{2})[\w.-]{6,30}(?<![-._])$" pattern2 = "[A-Za-z0-9@#$%^&+=_+-]{8,}" def login_password(username=None, password=None): print("Administrator login Panel ") print("\t1.New user Entry\n" "\t2.Change Credentials\n" "\t3.Show all accounts") option...
target = '123' def rec(target, num): if len(target) == 1: print(num + target[0]) else: for letter in target: rec(target.replace(letter, ''), num+letter) to_print = '' rec(target, to_print)
# Helper class for doubly-linked list class Node: def __init__(self, key, val): self.next = None self.prev = None self.key = key self.val = val class LRUCache: def __init__(self, n): self.n = n self.count = 0 self.nodes = {} self.start = None self.end = None def get(self, key...
'''You have a list of timestamps. Each timestamp is a time when there was a glitch in the network. If 3 or more glitches happen within one second (duration), you need to print the timestamp of the first glitch in that window. input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9] The...
class Node(object): def __init__(self, data, next_node=None): self.data = data self.next = next_node def runner_techinque_recursive(pointer_1, pointer_2): if not pointer_1: return pointer_2.next pointer_1 = pointer_1.next if pointer_1 and pointer_1.next: pointer_2 = po...
#!/usr/bin/env python3 import sys import numbers import numpy as np def read_experiments(file_list): experiments = [] for fn in file_list: with open(fn) as f: data = f.read().rstrip('\n') exec('experiments.append(' + data + ')') return experiments def aggregate(exps, cond...
import pandas as pd import matplotlib.pyplot as plt import numpy as np import csv #First select file csv path with data (this replaces 'C:\Your data'), give each data column a name, you can add or remove columns as you wish: data = pd.read_csv(r'C:\Your data', header = 0, usecols = ['column 1', 'column 2', 'c...
# def fed(x): # return x*x # # r = map(fed,[1,2,3,4]) # for i in r: # print(i) # # from functools import reduce # def add(x, y): # return x + y # print(reduce(add,[1, 3, 5, 7, 9])) from day04.Student import Student ddd = Student('Bart Simpson', 59) ddd.print_score()
import csv from datetime import datetime import os import sqlite3 def create_tables(cursor): create_item_table = """ CREATE TABLE item ( name TEXT, CONSTRAINT unique_item_name UNIQUE (name) ) """ create_category_table = """ CREATE TABLE category ( name TEXT, ...
# importing os module import os # Function to rename multiple files def main(): def removeYear(): for filename in os.listdir("pdf"): print(filename[11:]) os.rename('pdf/' + filename, 'pdf/' + filename[11:]) def organizeLetters(): for filename in os.listdir("pdf"): ...
# time complexity space complexity # add() O(1) O(1) # remove() O(1) O(1) # contain() O(1) O(1) class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.hasset=[None]*1000...
""" Hacer un script que muestro todos los numeros, entre dos numeros ingresados por el usuario. """ numero_uno = int(input("Ingresa numero uno: ")) numero_dos = int(input("Ingrese numero dos: ")) if numero_uno < numero_dos: for numoro in range(numero_uno, (numero_dos + 1)): print(numero) else: ...
def inputconvert(): f = [] d = [] while True: t = input() if t: f.append(t) else: break for i in f: d.append(int(i)) return d c = [] a = inputconvert() b = inputconvert() for i in a: c.append(i) for i in b: c.append(...
def listToString(list): final_string = '' for i in range(len(list)): if i == len(list) - 1: final_string += list[i] elif i == len(list) - 2: final_string = final_string + list[i] + ' i ' else: final_string = final_string + list[i] + ', ' return fin...
# Exercise Objective: # Produce a data visualization output to determine the # market cap value of the PSE's only ETF in the market from matplotlib import pyplot as plt import numpy as np import pandas as pd import csv data_set = pd.read_csv("PSE DATA.csv", index_col=False) etf_coy = data_set.loc[0,"CO...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 16 13:57:22 2018 @author: nataliecedeno """ #%% #Exercise 1 shopping_list = {"Guitar":1000, "Pick_box":5, "Guitar_string":10 } shopping_cart = ["Guitar", "Guitar_string" ] def checkout(s...
week = 0 one = 25000.0 two = 25000.0 three = 25000.0 for x in range(0, 365): week += 1 if week == 6: print "------" elif week == 7: week = 0 else: one=one*1.01 two=two*1.02 three=three*1.03 print "%.0f" % one + " %.0f" % two + " %.0f" % three
import tensorflow as tf # A placeholder like a variable that won't actually receive its data until a later point. # In a placeholder you need to specify the data type, as well as the data type's precision in terms of the number of bits. a = tf.placeholder(tf.float32) b = 2*a # The placeholder doesn't hold a value. #...
from shapely.geometry import Polygon, Point import random def generator(poly, number_of_random_points): minx, miny, maxx, maxy = poly.bounds list_of_points = [] for i in range(number_of_random_points): while True: p = Point(random.uniform(minx, maxx), random.uniform(miny, maxy)) ...
from statistics import mean import numpy as np class LSR: def __init__(self): self.slope = 0 #This represents the slope of our regression self.intercept = 0 #This represents the intercept of our regression self.r_squared = 0 #This represents the r^2 squared of our regression def Model...
# set is like the dictionary created with {} but it has no key value pair empty_set={} print(type(empty_set)) empty_set=set() print(type(empty_set)) set1={"r","t","y","m"} print(set1) dic4={4:"prabh",5:"prabha",6:"kuruvi"} set2=set(dic4) print(set2) set3=set(dic4.values()) print(set3) print(len(set3)) prin...
# Project Euler - Problem 3 # Question: # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? # Solution: def high_factor(num): i = 2 factors = [] while num > 1: if num%i == 0: factors.append(i) num/=i i = i +1 return factors print(str(max(...
import math def numTrees(n): dp = [0] * (n + 1) dp[0] = 1 dp[1] = 1 for i in range(2, len(dp)): for j in range(0, i): """ for a tree with i nodes the total number of possible trees is the sum of the product of all possible subtrees ...
def longestPalidrome(s): dp = [[False] * len(s) for i in range(len(s))] for i in range(len(s)): for j in range(len(s)): if i >= j: dp[i][j] = True left, right = 0, 0 for k in range(2, len(s) + 1): #the length of substring for i in range(len(s) - k + 1): #start...
def maxSubarry(num): localMax = 0 localMin = 0 maxRes = 0 for i in range(len(num)): tempMax = localMax localMax = max(localMax * num[i], localMin * num[i], num[i]) localMin = min(tempMax * num[i], localMin * num[i], num[i]) maxRes = max(maxRes, localMax) return maxRe...
from customer_account import Customer_account class FileParser(): def read_customer_accounts(self, filename): customer_accounts = [] try: fo = open(filename, "r") # store the file contents as a list of strings lines = fo.readlines() fo.close() ...
class Person(): def __init__(self, name, field): self.name = name self.field = field self.action = None self.article = None def assignArticle(self, articleID): self.article = articleID def isPersonReal(self): ''' Determines whether a name is actually a human name Returns true...
def calculetor(): print("\n Welcome to Calc: This is developed by TechGuyShubham") operation = input("Choose your choice of Calculation\n + For Addition \n - For Subtraction \n * For Multipy \n ** For Power \n Enter Your choice:") num1 = int(input("Enter 1st Number :")) num2 = int(input("Enter your 2nd Number...
import numpy as np def calculate_pmi_rate(credit_score): pmi_rate = 0 if credit_score < 640: pmi_rate = 2.25 elif 639 < credit_score < 660: pmi_rate = 2.05 elif 659 < credit_score < 680: pmi_rate = 1.90 elif 679 < credit_score < 700: pmi_rate = 1.40 elif 699 <...
#Day 12 Rain Risk #Making an object for this challenge seemed appropriate as I expected pt2 to have multiple boats :) class Boat: #Boat has a position x/y, a current direction (in the form of an int) and possible directions def __init__(self, x, y, direction=0): self.x = x self.y = y s...
# Day 3: Toboggan Trajectory """ Takes a filepath (default = my path) and generates a 2D array of the environment ...# .#.. #... Becomes [[., ., ., #], [., #, ., .], [#, ., ., .]] """ def get_env(filepath="../assets/trees.txt"): env = [] with open(filepath, 'r') as f: lines = f.readlines() ...
# Read two integers from STDIN and print three lines where: # The first line contains the sum of the two numbers. # The second line contains the difference of the two numbers (first - second). # The third line contains the product of the two numbers. # Sample input a = 3 b = 2 # Sample output # 5 # 1 # 6 def arith...
import random import numpy as np import pandas as pd nations = pd.Series(['Italy', 'Spain', 'Greece', 'Germany']) def throwNeedles(numNeedles): inCircle = 0 for _ in range(1, numNeedles+1, 1): x = random.random() y = random.random() if (x**2 + y**2) ** 0.5 <= 1: # x**2 + y**2 = h...
import numpy as np import pandas as pd def df(): data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002, 2003], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]} frame = pd.DataFrame(data) print(pd.DataFrame(data, columns=['state','pop'])) # cr...
import re txt = "The rain in Spain" x = re.search("^The", txt) x = re.search("^The.*Spain$", txt) #Search the string to see if it starts with "The" and ends with "Spain": print (x) #findall - Returns a list of containing all matches #search - Returns a Match Object if there is a match anywhee in the string # sub Repl...
import json #Convert Python objects into JSON strings, and print the values: print(json.dumps({"name": "John", "age": 30})) print(json.dumps(["apple", "bananas"])) print(json.dumps(("apple", "bananas"))) print(json.dumps("hello")) print(json.dumps(42)) print(json.dumps(31.76)) print(json.dumps(True)) print(json.dumps...
def age_count(x): if int(x) > 1980 and int(x) < 2020: age = 2020 - int(x) return str(age) return 'Invalid' birth_year=input("Enter your birth year: ") print("Your age is " + age_count(birth_year))
print('Hello world') name = input('Enter your name:') age = int(input('Enter your age: ')) print('Welcome ' + name + ' your age is ' + str(age))
from enum import Enum class BookFormat(Enum): HARDCOVER = 1 PAPERBACK = 2 EBOOK = 3 KINDLE = 4 MAGAZINE = 5 JOURNAL = 6 class BookStatus(Enum): AVAILABLE = 1 LOANED = 2 RESERVED = 3 LOST = 4 class AccountStatus(Enum): ACTIVE = 1 SUSPENDED = 2 CLOSED = 3 CANCELLE...
################################################### # MC102 - Algoritmos e Programação de Computadores # Laboratório 12 - Filtros de Imagens # Nome: Bruno Morari # RA: 168107 ################################################### ''' Função que recebe uma imagem e imprime essa imagem no formato PGM ''' def imprime_image...
# -*- coding: utf-8 -*- from typing import NamedTuple, List if __name__ == '__main__': Item = NamedTuple( 'Item', [ ('id', int), ('name', str), ('amount', int), ] ) User = NamedTuple( 'User', [ ('id', int), ...
# -*- coding: utf-8 -*- def make_named_set(name, s): return {'name': name, 'set': s} if __name__ == '__main__': sets = [ make_named_set('set_a', set([1, 2, 3, 4])), make_named_set('set_b', set([1, 2, 3])), make_named_set('set_c', set([1, 2, 3, 4])), make_named_set('set_d', se...
# 計算 1 + 2 + 3 + ... + 100 count_sum = 0 for i in range(1,101): count_sum += i s = "1 + 2 + 3 + ... + 100=%d" % (count_sum) # 字串格式化,語法: "內容%d %d" % (int,int) print(s) print("\n\n\n") # 九九乘法表 for i in range(1,10): for j in range(1,10): print("%d x %d = %d" % (i,j,i*j)) print("\n\n\n") # 九九乘法表2 - 方形版 ...
#!/usr/bin/python # -*- coding: utf-8 -*- ###################################################################### # Simples Web Server em python! # Criado em 31/03/2019 # Criado por: Rafael Souza # # Passar os seguintes dados como variavel de ambiente: # # WEBSERVICE_PORT (INFORMAR PORTA TCP) # WEBSERVICE_NAME (...
# -*- coding: utf8 -*- """ Napisz program, który dla 10 kolejnych liczb naturalnych wyświetli sumę poprzedników. Oczekiwany wynik: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 """ for i in range(11): x = int((i*(1+i))/2) print (x) """ 0 + 1 = 1 1 + 2 = 3 3 + 3 = 6 6 + 4 = 10 ----------------------------- #inn...
# -*- coding: utf8 -*- """ Utwórz spis oglądanych seriali. Każdy serial powinen mieć przypisaną ocenę w skali od 1-10. Zapytaj użytkownika jaki serial chce obejrzeć. W odpowiedzi podaj jego ocenę. Zapytaj użytkownika o dodanie kolejnego serialu i jego oceny. Dodaj do swojego spisu. """ serial = { "Stranger Thing...
import itertools import unittest import string from hypothesis import given, reproduce_failure, strategies as st ########################################################################### # # Human-readable representation # # We'll use strings of alphabetical characters, with # capital letters being the inv...
# 1. Import a file with strings # 2. Let it read through the file and do per string the following: # 2.1. Break the string up in seperate characters. # 2.2. The index of the letter in the alphabet will be the power of 2. For example: a = 2^0, b = 2^1, e = 2^5. # 2.3. Calculate the sum of all c...
def backspaceCompare1(S, T): def func(S): s = [] for i in S: if i == '#': if len(s) > 0: s.pop() else: pass else: s.append(i) return s return func(S)==func(T) def backspaceCom...
class MinStack: def __init__(self): """ 同步栈 """ self.data=[]# 数据栈 self.list=[]# 辅助栈 def push(self, x: int): self.data.append(x) if len(self.list)==0 or x<=self.list[-1]: self.list.append(x) else: self.list.a...
# https://www.hackerrank.com/challenges/bomber-man/problem #output of 3,7,11... will be same -> 3x #output of 5,9,13... will be same -> 5x #output of 2,4,6... will be complete fill -> 2x #5x and {0} will be different but after blast both will be same #ie {6} will be same as {2} from copy import deepcopy r, c, n = map...
# https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem from collections import Counter counter=Counter(list(Counter(list(input())).values())) base=counter.most_common()[0][0] counter.pop(base) if(len(counter)==0): print('YES') exit(0) if(len(counter)==1): val=list(counter.keys())[0] ...
def repeatedString0(s, n): m=len(s) ans=0 for i in range(0,n): if(s[i%m]=='a'): ans+=1 return ans def repeatedString(s,n): num=n//len(s) extra=n%len(s) ans=0 for i in range(0,len(s)): if(s[i]=='a'): ans+=1 ans*=num fo...
# https://www.hackerrank.com/challenges/common-child/problem def commonChild(s1, s2): m, n = len(s1), len(s2) prev, cur = [0]*(n+1), [0]*(n+1) for i in range(1, m+1): for j in range(1, n+1): if s1[i-1] == s2[j-1]: cur[j] = 1 + prev[j-1] else: i...
# -*- coding: utf-8 -*- # A list of blanks to be passed in to the game function. blanks = ["___1___", "___2___", "___3___", "___4___", "___5___"] # Questions will be asked to fill in game_data = { 'Easy': { 'quiz': '''A ___1___ is one of the basic things a program works with, like a letter or a number.These ___...
# Assignment: Multiply # Create a function called 'multiply' that reads each value in the list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5. # # The function should multiply each value in the list by the second argument. For example, let's say: a = [2,4,10,16] def multiply(li...
# QUELLE dictionaryGermanToSpanish = { 'hallo': 'hola' } dictionaryGermanToEnglish = { 'hallo': 'hello' } dictionaryGermanToKorean = { 'hallo': '안녕하세요' } # CODE languageToDictionary = { 'english': dictionaryGermanToEnglish, 'spanish': dictionaryGermanToSpanish, 'korean': dictionaryGermanToKorean } whichLangu...
class Node(object): def __init__(self, name:str): self.child_nodes = list() self.name = name def append(self, child_node): self.child_nodes.append(child_node) def draw(self, depth:int = 0): # tree = self.name # for child in self.child_nodes: # tree+=...
# functions file import collections def sort_list(numbers): print("Sorted list from least to greatest: ", numbers.sort()) def sum_list(numbers): sum = 0 for number in numbers: sum = sum + number return sum print(f"The sum of the list is: {sum}") def product_list(numbers): produ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @author: Qiaoxueyuan @time: 2017/8/21 14:34 ''' import random, string def random_string(num=5): # str = ''.join(random.sample(string.ascii_letters + string.digits, num)) # return str str = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYy...
# Runtime: 1220 ms, faster than 50.44% of Python3 online submissions for Longest Palindromic Substring. # Memory Usage: 14.2 MB, less than 81.75% of Python3 online submissions for Longest Palindromic Substring. def is_palindrome(l, r, s): result = '' result_length = 0 # Ensure that the left and right point...
# Runtime: 56 ms, faster than 75.41% of Python3 online submissions for Palindrome Number. # Memory Usage: 14.4 MB, less than 13.65% of Python3 online submissions for Palindrome Number. def reverse_number(x): ''' simply reverse x and see if the the reversed value of x and original x match ''' x_orig = x...
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head): # Node to handle the case in case we just have one root node and the elements after that are all the same as the root node sentinel = Node(...
#!/usr/bin/env python '''slidepuzzle.py A sliding puzzle game by Nick Loadholtes No warranty provided with this code. Use at your own risk. version 1.3 ''' import random, cmath, curses, curses.wrapper, curses.ascii side = "|" newline = "\n" _topborder = "_" topb = "" newscreen = "\n...
opcao = "" total = 0 i = 0 while opcao != "0": print("(1) - Informar consumo de alimentos ingeridos") print("(0) - Encerrar o programa") opcao = input("\nDigite o número da opção desejada: ") if opcao == "1": x = "" qnt = int(input("Informe a quantidade de alimentos que você...
class Object(object): ''' Creates an object for simple key/value storage; enables access via object or dictionary syntax (i.e. obj.foo or obj['foo']). ''' def __init__(self, **kwargs): for arg in kwargs: setattr(self, arg, kwargs[arg]) def __getitem__(self, prop): '...
import numpy as np class GDOptimizer: """Basic gradient descent optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized """ def __init__(self, learning_rate): ...
#!/usr/bin/python """ 7th of October 2020 """ import numpy as np class DividedDifference(): def __init__(self): # default setting self.stg = { "length" : 5, "loc" : 0.0, "scale" : 20.0, "initial-decimal" : 0, ...
import numpy as np #Numpy array print("Numpy array") dizi=np.array((3,4)) print(dizi.shape) #arange methodu (normal range mothodunun numpy de kullanılışı) print("arange methodu") result=np.arange(0,10) print(result) #linspace methodu start,stop,kaç adet print("linspace methodu") result=np.linspace(0,20,500) print(...
from bs4 import BeautifulSoup import webbrowser import urllib2 # Get the product search query from user and parse the page source of the search result from flipkart website product = raw_input("Enter product name: ") product = product.replace(' ', '+') print "entering search" content1 = urllib2.urlopen('http://www.flip...
a = int(input("Please enter a number to start with: ")) b = int(input("Please enter a number to end with: ")) list_nums = list(range(a, b)) class Numbers(): def __init__(self): print("Numbers object created") def odd_nums(self): ''' If a number is odd, print odd ''' fo...
def recursive_binary_search(list, target): if len(list) == 0: return False else: list.sort() mid = (len(list)) // 2 if list[mid] == target: return True else: if list[mid] < target: return recursive_binary_search(list[mid+1:], target...
import random class Die(): def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def roll(self): result = self.num1 + self.num2 print(f"You have just rolled {self.num1} and {self.num2}") if result == 12: print(f"Double 6! You just rolled {res...
from matplotlib import pyplot as plt plt.style.use("ggplot") year_x = [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] # % of Python questions asked on Stack Overflow py_growth = [3.90, 4.20, 5.30, 6.00, 7.10, 8.20, 10.40, 12.00, 13.80] plt.plot(year_x, py_growth, color="b", marker="o", linewidth=3, labe...
import math lst = [1, 4, 5, 67, 2, 3, 5, 6, 1, 23, 4, 6, 7, 1, 2, 2, 234, 3, 32, 1, 12, 2, 2] # Mean - Add all up and divide by length def mean(lst): total = sum(lst) average = total / len(lst) return average # Median - Sort and find middle number def median(lst): lst.sort() length = len(lst) ...
def binary_search(list, target): first = 0 list.sort() last = len(list) - 1 while first <= last: mid = (first + last) // 2 if list[mid] == target: return mid elif list[mid] < target: first = mid + 1 elif list[mid] > target: last = mid -...
import time class Solution(object): def containsDuplicate(self, nums): list = {} for x in nums: if not (x in list): list.update({x:1}) else: return True return False def containsDuplicate2(self, nums): return len(nums) != len(set(nums)) j = Solution() x...
import heapq a = [4,2,1,3,5] heap = heapq.heapify(a) heapq.heappush(heap, 6) x = heapq.heappop(heap) heap[0] # get smallest item without pop # push item on the heap, then pop the smallest from the heap x = heapq.heappushpop(heap, 7) # pop the smallest from the heap, then push the new item x = heapq.heapreplace(heap...
""" This problem was asked by Amazon. There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 unique ways: 1, 1, 1,...
#1 - Actualiza los valores en diccionarios y listas: #Cambia el valor 10 en x a 15. Una vez que haya terminado, x ahora debería ser [[5,2,3], [15,8,9]]. #Cambia el apellido del primer alumno de 'Jordan' a 'Bryant' #En el directorio sports_directory, cambia 'Messi' a 'Andres' #Cambia el valor 20 en z a 30 x = [ [5,2,3]...
class BankAccount: def __init__(self, int_rate=0.01, balance=0): self.int_rate = int_rate self.balance = balance def deposit(self,amount): self.balance += amount return self def withdraw(self, amount): if self.balance >= amount: self.balance -= amount return self else: ...
#Oscar Miranda A01630791 #Julio Arath Rosales Oliden A01630738 #Se pide que se ingrese el año variable_1=float(input("Inserta el año, para checar si es un año bisiesto \n")) #se compara si el año es multiplo de cuatro, despues se usa un or de divisible entre o 400 y un not de divisible entre 100, como es #and ...
#Julio Arath Rosales Oliden #A01630738 def menor_ingresado(): print("Ingrese un numero, mientras no sea cero lo ingresara denuevo") numero = float(input("Ingrese un numero :\n")) menor_numero=numero while numero!=0: numero=float(input("Ingrese otro numero :)\n")) if numero<meno...
#Julio Rosales Oliden A01630738 #se dice lo que hace el programa print("Escribe un numero, se sumara hasta que escribas un numero negativo") num=0 dato_user=0 #si el dato ingresado por el usuario es mayor o igual que cero el programa correra la suma while dato_user>=0: dato_user=int(input("Escribe un nume...
def anagramas(palabra1,palabra2): if len(palabra1) == len(palabra2) and (palabra1 != palabra2): for letra in palabra1: if letra not in palabra2: return False return True else: return False def cambia_multplos(lista, n): for pos in range(l...
#Julio Arath Rosales Oliden #A01630738 #En la primera parte se pide la cantidad de alumnos en el grupo #Despues asignamos una varieble que cuente la calificacion grupal a 0 para hacer la sumatoria de esta estudiantes=int(input("Este programa calcula el promedio por estudiante y por grupo\nEscribe el numero de est...
#Julio Rosales Oliden #A01630738 numero=float(input("Inserta el numero \n")) digitos=1 numero=abs(numero) while 9<=numero or numero<=-9: numero=numero/10 digitos+=1 print("el numero tiene "+ str(digitos) + " digitos") #Aprendi a usar el abs (absoluto)
from tkinter import * import requests import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart root = Tk() root.title("Let's Convert Your Winnings !") # SETTING THE SIZE root.geometry("600x600") # THE USER CANT MAXIMIZE THE WINDOW root.resizable(height=False, width=False) #...
from random import shuffle import os ##################### #--- Create Deck ---# ##################### #Simple function making use of list comprehension to make a list of cards. #Ordered from aces to kings, but in separate suits. def create_deck(): deck = [] suits = ['H','S','C','D'] special = ['a','j','q...
import random import math import time ''' A helper function to print `n` cute ASCII rabbits. This is a little tricky because each rabbit needs 3 lines to print. ''' def print_rabbits( n ): max_rabbits_in_row = 6 # Feel free to change this number; # be forwarned, if it's too big, things # will look...
def func(a, n): memd={} # memd reverses the order of be and id memd[be][id] def mins(ids, be): if(memd.has_key(be)): if(memd[be].has_key(ids)): return memd[be][ids] else: memd[be]={} if(ids==1): # id-1 is shirt. It says the box befor...
nums = [37, 99, 48, 47, 40, 25, 99, 51] num_list = sorted(nums) # 二分插入前提:序列必须是有序的! def insert_int(orderlist, value): ret = orderlist[:] # 浅拷贝 low = 0 height = len(orderlist) while low < height: mid = (low + height) // 2 # 取中间值 if value > ret[mid]: low = mid + 1 else...