text
stringlengths
37
1.41M
# EXERCÍCIO Nº 03- LISTA 06 - STRINGS print('\n Nome na Vertical') print('#################\n') nome=input('Insira o seu nome: ').upper() for letra in nome: print('o',letra)
# EXERCÍCIO Nº 15- LISTA 04 - LISTAS print('\nNotas e cálculos') print('################\n') lista=[] nota=0 while nota!=-1: nota=float(input('Insira uma nota (número inteiro): ')) if nota !=-1: lista.append(nota) qtde=len(lista) soma=sum(lista) média=soma/qtde a=0 acima_da_média=0 a...
#EXERCÍCIO Nº 25 - LISTA 02 - ESTRUTURA DE DECISÃO print('Perguntas sobre um crime') print('########################') a=input('Você telefonou para a vítima? (S/N): ') b=input('Você esteve no local do crime? (S/N): ') c=input('Você mora perto da vítima? (S/N): ') d=input('Você devia para a vítima? (S/N): ') e=...
# EXERCÍCIO Nº 21- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nNúmero Primo') print('############\n') lista=[2,3,5,7,11,13,17] a=0 número_inteiro=0 while número_inteiro>=0: número_inteiro =float(input('Insira um número inteiro >0: ')) while número_inteiro!=int(número_inteiro): print('O número de...
#EXERCÍCIO Nº 12 - LISTA 02 - ESTRUTURA DE DECISÃO print('Folha de pagamento') print('##################') valor_hora=float(input('Insira o valor da hora trabalhada: R$ ')) horas_trabalhada=float(input('Insira a quantidade de horas trabalhadas no mês: ')) salário_bruto=valor_hora*horas_trabalhada #Tabela do I...
#EXERCÍCIO Nº 01 - LISTA 02 - ESTRUTURA DE DECISÃO print('Maior número de dois') print('####################') número1=float(input("Insira um número: ")) número2=float(input("Insira um número: ")) if número1>número2: print('O número: ',número1,' é maior que: ',número2) elif número1==número2: pri...
# EXERCÍCIO Nº 35- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nNúmeros Primos') print('##############\n') intervalo=0 while intervalo<=0: intervalo =float(input('\nInsira um número inteiro e >0: ')) while (intervalo) != int(intervalo) or intervalo<=0: print('O número deve ser inteiro e maior que...
#EXERCÍCIO Nº 10 - LISTA 02 - ESTRUTURA DE DECISÃO print('Bom dia, Boa tarde e Boa noite') print('##############################') turno=input("Qual turno você estuda? (M/V/N): ") if 'MVN'.find(turno.upper())>=0: if turno.upper()=='M': print('Bom dia!') elif turno.upper()=='V': print...
# EXERCÍCIO Nº 14- LISTA 05 - LISTAS print('\n Quadrado Mágico') print('################\n') import numpy import random matriz = [[1, 2, 3], # i(linha) [4, 5, 6], [7, 8, 9]] resultado=False def quadradoMagico(): global resultado sl = numpy.sum(matriz, axis=1) sc = numpy.su...
# EXERCÍCIO Nº 34- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nNúmeros Primos') print('##############\n') n=0 while n<=0: n =float(input('Insira um número inteiro e >0: ')) while (n) != int(n) or n<=0: print('O número deve ser inteiro e maior que zero') n = float(input('Insira um número...
# EXERCÍCIO Nº 32- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nFatorial de um número inteiro') print('#############################\n') n=0 while n<=0: n =float(input('Insira um número inteiro >0: ')) while (n) != int(n) or n<=0: print('O número deve ser inteiro e maior que zero') n = f...
número01=input('número: ') número02=input('número: ') soma=int(número01)+int(número02) print('A soma dos números é: '+str(soma))
row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") number = list(str(position)) if int(number[1]) == 3: if int(number[0]) == 1: row3[0] = "X" elif int(number[0]) =...
# 1078.Bigram分词 # 给出第一个词first和第二个词second,考虑在某些文本text中可能以"first second third"形式出现的情况,其中second紧随first出现,third紧随second出现。 # 对于每种这样的情况,将第三个词"third"添加到答案中,并返回答案。 # 示例1: # 输入:text = "alice is a good girl she is a good student", first = "a", second = "good" # 输出:["girl", "student"] # 示例2: # 输入:text = "we will we will rock y...
# 977. 有序数组的平方 # 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 # 示例 1: # 输入:[-4,-1,0,3,10] # 输出:[0,1,9,16,100] # 示例 2: # 输入:[-7,-3,2,3,11] # 输出:[4,9,9,49,121] class Solution: def sortedSquares(self, A): return sorted([i**2 for i in A ]) sol = Solution() print(sol.sortedSquares([-4,-1,0,3,10]))
# 160.相交链表 # 编写一个程序,找到两个单链表相交的起始节点。 # 注意: # 如果两个链表没有交点,返回null. # 在返回结果后,两个链表仍须保持原有的结构。 # 可假定整个链表结构中没有循环。 # 程序尽量满足O(n)时间复杂度,且仅用O(1)内存。 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # 方法1:遍历法(超时) de...
#1046. 最后一块石头的重量 #有一堆石头,每块石头的重量都是正整数。 #每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: #如果 x == y,那么两块石头都会被完全粉碎; #如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。 #最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。 #提示: #1 <= stones.length <= 30 #1 <= stones[i] <= 1000 import heapq class Solution: # ...
# 429. N叉树的层序遍历 # 给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。 # 例如,给定一个 3叉树 : # 1 # / | \ # 3 2 4 # / \ # 5 6 # 返回其层序遍历: # [ # [1], # [3,2,4], # [5,6] # ] # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children ...
#35. 搜索插入位置 # # 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 # # 你可以假设数组中无重复元素。 # # 示例 1: # # 输入: [1,3,5,6], 5 # 输出: 2 # 示例 2: # # 输入: [1,3,5,6], 2 # 输出: 1 # 示例 3: # # 输入: [1,3,5,6], 7 # 输出: 4 # 示例 4: # # 输入: [1,3,5,6], 0 # 输出: 0 def searchInsert(nums,target) -> int: if target<=nums[0]: ret...
# 1122.数组的相对排序 # 给你两个数组,arr1和arr2, # arr2中的元素各不相同 # arr2中的每个元素都出现在arr1中 # 对arr1中的元素进行排序,使arr1中项的相对顺序和arr2中的相对顺序相同。 # 未在arr2中出现过的元素需要按照升序放在arr1的末尾。 # 示例: # 输入:arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], arr2 = [2, 1, 4, 3, 9, 6] # 输出:[2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19] # 提示: # arr1.length, arr2.length <= 1000 # 0 <= ar...
# 54. 螺旋矩阵 # 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 # 示例 1: # 输入: # [ # [ 1, 2, 3 ], # [ 4, 5, 6 ], # [ 7, 8, 9 ] # ] # 输出: [1,2,3,6,9,8,7,4,5] # 示例 2: # 输入: # [ # [1, 2, 3, 4], # [5, 6, 7, 8], # [9,10,11,12] # ] # 输出: [1,2,3,4,8,12,11,10,9,5,6,7] class Solution: def spiralOrder(self, mat...
# 206. 反转链表 # 反转一个单链表。 # 示例: # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->NULL # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 我的做法:使用了一个堆栈用来存储链表中的每个节点 def reverseList(self, head: ListNode) -> ListNode: ...
# 1089.复写零 # 给你一个长度固定的整数数组arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。 # 注意:请不要在超过该数组长度的位置写入元素。 # 要求:请对输入的数组就地进行上述修改,不要从函数返回任何东西。 # 示例1: # 输入:[1, 0, 2, 3, 0, 4, 5, 0] # 输出:null # 解释:调用函数后,输入的数组将被修改为:[1, 0, 0, 2, 3, 0, 0, 4] # 示例2: # 输入:[1, 2, 3] # 输出:null # 解释:调用函数后,输入的数组将被修改为:[1, 2, 3] # 提示: # 1 <= arr.length <= 10000 # ...
# 970.强整数 # 给定两个正整数x和y,如果某一整数等于x ^ i + y ^ j,其中整数i >= 0且j >= 0,那么我们认为该整数是一个强整数。 # 返回值小于或等于bound的所有强整数组成的列表。 # 你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。 # 示例1: # 输入:x = 2, y = 3, bound = 10 # 输出:[2, 3, 4, 5, 7, 9, 10] # 解释: # 2 = 2 ^ 0 + 3 ^ 0 # 3 = 2 ^ 1 + 3 ^ 0 # 4 = 2 ^ 0 + 3 ^ 1 # 5 = 2 ^ 1 + 3 ^ 1 # 7 = 2...
# Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. def func_var3(x): x = str(x) y = x[::-1] return y #100 loops, best of 5: 404 nsec per loop - Трехзначное число #100 loops, best of 5: 423 nsec per ...
#1. Пользователь вводит данные о количестве предприятий, их наименования и прибыль за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия.. Программа должна определить среднюю прибыль (за год для всех предприятий) и вывести наименования предприятий, чья прибыль выше среднего и отдельно вывести наименования пред...
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random size = 10 max_item = 10 array = [random.randint(0, max_item) for i in range(size)] min_el = max_item max_el = 0 max_index = 0 min_index = 0 for index, value in enumerate(array): if value > max_el: ma...
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. x = int(input("Введите число ")) n = x count = 0 z = 0 while n > 0: n = n // 10 count += 1 while count > 0: a = x % 10 y = a * 10 ** (count -...
# 백준, 2941번 크로아티아 알파벳 word = input() alpha = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="] for c_a in alpha : if c_a in word : word = word.replace(c_a, "A") print(len(word))
# Task # The provided code stub reads two integers, a and b, from STDIN. # Add logic to print two lines. The first line should contain the result of integer division, a // b. # The second line should contain the result of float division, a / b. # No rounding or formatting is necessary. # Input format: # The first li...
import pygame from time import sleep import socket, struct pygame.init() #Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Initialize the joysticks pygame.joystick.init() # -------- Main Program Loop ------...
#!/usr/bin/python3 import numpy as np import sympy as sym from sympy.physics.mechanics import dynamicsymbols class BaseSymbols: def __init__(self, name, identifier, is_coords=False): """The base object for this whole package to function. It defines the sympy symbols that are used in the modelling...
#!/usr/bin/python3 class DOF: def __init__(self, idx, free=True, const_value=0): """A Degree of Freedom is nothing other than a body coordinate that is able to move. Thus, to define a DOF, we need to simply supply the free index (idx). By default, if it is free, there is no consta...
"""金典排序之冒泡法""" def bubble_sort(alist): for j in range(len(alist) - 1,0,-1): # j 表示每次遍历需要比较的次数,是逐渐减小的 for i in range(j): if alist[i] > alist[i+1]: alist[i],alist[i+1] = alist[i+1],alist[i] li = [32,23,22,33,34,45,65,39] bubble_sort(li) print(li)
# squares = [i **0.5 for i in range(1,11)] # print(squares) # a = [ i for i in range(1,1000001)] # print(max(a)) # print(min(a)) # print(sum(a)) # # # a = [i for i in range(1,20,2)] # print(a) # # a = [i*3 for i in range(1,10)] # # print(a) # # # b = [i**3 for i in range(1,11)] # #if len(b)<=2: # print("The first three...
import math mylist = [] answers = [] def answer(area): curArea = area; i = 0 while curArea > 0: getSqrt(curArea) curArea = curArea - mylist[i]; i = i+1; answers = list(mylist) del mylist[:] return answers; def getSqrt(area): floorRoot = int(math.sqrt(area)) my...
#!/usr/bin/python3 """ Script to export data in the CSV format """ import csv import requests from sys import argv def export_to_csv(employee_id): """ Retrieves the ToDo list for an employee in CSV """ url = 'https://jsonplaceholder.typicode.com/' user_request = '{}users/{}'.format(url, employee_id) e...
# Jacob Wahl # 3/2/21 # # Problem 2.6 - Implement a function to check if a linked list is a # palindrome. # from Linked_List import Linked_List, Node def is_palindrome_helper(llist: Linked_List): fowards, backwards = is_palindrome(llist.head, '', '') print(fowards, backwards) return True...
# Jacob Wahl # 4/6/21 # # Problem 8.3 - A magic index in an array A[0 ... n-1] is defined to be an # index such that A[i] = i. Given a sorted array of distinct, # write a method to find a magic index, if one exists, in array # A. # FOLLOW UP: What if the values ar...
# Jacob Wahl # 2/4/21 # Problem 1.7 - Given an image represnted by an NxN matrix, where each pixel in the image is 4 bytes, # write a method to rotate the image by 90 degrees. Can you do this in place? # Using ints instead of 4 bytes because the method should be the same in essence # Assuming clockwise ...
# Petit exercice utilisant la bibliothèque graphique tkinter from tkinter import * from random import randrange # --- définition des fonctions gestionnaires d'événements : --- def drawline(): "Tracé d'une ligne dans le canevas can1" global x1, y1, x2, y2, coul can1.create_line(x1,y1,x2,y2,width=2,fil...
class Personne: "Classe personne" def __init__(self, nom, prenom): self._nom = nom self._prenom = prenom def __str__(self): return 'Mon prenom est {} et mon nom est {}'.format(self._prenom, self._nom) class Espion(Personne): "Espion" def __init__(self, nom, p...
liste = [1,6,9,4,5,7] plusFort = 0 for nb in liste: if nb>plusFort: plusFort = nb print("Le plus fort de la liste est {}".format(plusFort))
from abc import ABC, abstractmethod class Forme(ABC): @abstractmethod def aire(self): pass @abstractmethod def perimetre(self): pass class carre(Forme): def __init__(self, largeur,longueur): self._largeur = largeur self._longueur = longueur def a...
figure = input() area = 0 import math if figure == "square": a = float(input()) area = a * a elif figure == "rectangle": a = float(input()) b = float(input()) area = a * b elif figure == "circle": r = float(input()) area = math.pi * r * r elif figure == "triangle": ...
n = int(input()) odd_sum = 0 odd_min = 1000000000000 odd_max = -1000000000000 even_sum = 0 even_min = 10000000000000 even_max = -10000000000000 for i in range(0, n): num = float(input()) if i % 2 == 0: odd_sum += num if num >= odd_max: odd_max = num if num ...
n = int(input()) max_number = 0 sum = 0 for i in range (0, n): num = int(input()) sum += num if num >= max_number: max_number = num if max_number == sum - max_number: print("Yes") print("Sum = " + str(max_number)) else: print("No") print("Diff = " + str(abs(max_numbe...
# name = input("Enter your name") # print(type(name), name) # num9 = int(name) # print(type(num), num) thisDicto = { "name": "Praneet", "marks": 80 } print(thisDicto["marks"])
## How to create a Set # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) ## How to Update Set # initialize my_set my_set = {1,3} print(my_set) # if you uncomment line 9, # you will get an error # TypeError: 'set' object does not support inde...
#should return list of data from a text file def populate_data_from_file(data, file): try: for x in file: data.append(x.rstrip()) return data except TypeError: print({f'Cannnot use .append() or rstrip() if {file} is not a file with text'}) #splits a string into a list, th...
#!/usr/bin/env python from Tkinter import * class Graph(Canvas): def __init__(self, parent= None, **kw): Canvas.__init__(self,parent, kw) # self.create_rectangle(10,10,30,30,fill="green") self.rangex=(0,10) self.rangey=(0,10) self.xtics=10 self.ytics=10 self.xlabel="x" self.ylabel="y" self.startx =...
import random import curses import time import numpy as np import tty import sys import termios # TODO: also have a Food class which is basically just a coordinates and a type (less than, greater than) # We can then have a Screen class which has Food (composition), it has statements and it has a Zoo. FOOD_TYPE = cu...
#!/usr/bin/python # # trie.py, # A trie. (Not optimised for character space.) # # Chris Roeder, 2010-02-01, Python 2.6 import node substringsFilename = "substrings.txt" wordsFilename = "top100k.txt" #wordsFilename = "top10k.txt" #wordsFilename = "top1k.txt" #wordsFilename = "top100.txt" #wordsFilename = "top20.txt" ...
#!/usr/bin/python3 def search(arr, n, x): for i in range(0, n): if arr[i] == x: return i return -1
# #Kevin Nguyen #Basic program for Python that outputs the binary representation of a value. 1 Byte = 8 Bits. Truncating could be improved. # #How to run (linux): # 1.) open command line and cd into directory folder of where this code is # 2.) type in "python PythonGetBytes.py" #import statements import sys; ...
#IMPORTING THE LIBRARIES import numpy as np import matplotlib.pyplot as plt import pandas as pd #IMPORTING THE DATASET dataset = pd.read_csv('Position_Salaries.csv') X=dataset.iloc[:, 1:-1].values y=dataset.iloc[:, -1].values #TRAINING LINEAR REGRESSION ON WHOLE DATASET from sklearn.linear_model import LinearRegres...
import random N = int(input('Введите количество чисел в массиве: ')) array = [random.randint(-N, N) for _ in range(N)] if array[0] < array[1]: min_idx_1 = 1 min_idx_2 = 0 else: min_idx_1 = 0 min_idx_2 = 1 print(array) for i in range (2, N): if array[i] < array[min_idx_1]: spam = min_idx_...
# 1. Определение количества различных подстрок с использованием хеш-функции. # Требуется вернуть количество различных подстрок в этой строке. import hashlib def substring_count(input_string): input_string = str(input_string).lower() length = len(input_string) hash_set = set() for i in range(lengt...
# https://stackabuse.com/k-means-clustering-with-scikit-learn/ # https://towardsdatascience.com/understanding-k-means-clustering-in-machine-learning-6a6e67336aa1 # https://scikit-learn.org/stable/modules/clustering.html#clustering-performance-evaluation import pandas as pd import numpy as np import matplotli...
def divide(dividend, divisor): if divisor == 0: raise ZeroDivisionError("Divisor cannot be. ") return dividend / divisor def calculate(*values, operator): return operator(*values)
''' This is a simple straight heads-up poker game. The player and computer are each dealt a 5 card hand, with no drawing. The algorithm uses card counting, combinatorics, probability, Bayes theorem, logistic regression, and heuristics. The computer cannot 'see' the player's cards except if they are revealed at the...
import random a = int(input('faca sua escolha\n' '[1] pedra\n' '[2] papel\n' '[3] tesoura\n''')) lista = int(random.randint(1, 3)) #papel = 2 / pedra = 3 / tesoura = 1 PC = lista if a == 1 and PC == 1: print('Voce Venceu Pedra bate tesoura') elif a == 2 and PC == ...
import math import csv class Point: def __init__(self, x, y): self.x = float(x) self.y = float(y) def __repr__(self): return "({},{})".format(self.x,self.y) def getx(self): return self.x def gety(self): return self.y def distance(self,pt): "a dist...
def TotalScore(dice): # Sum of the score of the number of dice rolled from random import randint totalanswer=0 for z in range(0, dice) : totalanswer=totalanswer+randint(1,6) return(totalanswer) def Percent(part,whole): #The INTEGER percentage of which part (less than 100%) is of...
def Percent(part,whole): #The INTEGER percentage of which part is of whole if whole< part or part==0 or whole==0 : print ("Please enter correct values!!") whole =int(input ("Firstly the whole number : ")) part = int(input ("Then the part number to be calculated: ")) Perc...
def CommonTwo (string1, string2): #Uses the items from two strings and check them newstring="" if string1=="": return(string2) if string2=="": return(string1) for z in string1: for x in string2: if z==x : newstring+=z return (n...
contacts = {'Jason': '555-0123', 'Carl': '555-0987'} contacts['Tony'] = '555-0570' print (contacts) print ('Number of contacts', (len(contacts)))
#!/bin/python def soma(num1 ,num2): return num1+num2 #o return serve para retornar um valor e atribuir para uma outra variável x = soma(4, 5) print (x)
dict={} dict["id"]='101','102','104' dict["grade"]='A','C','E' dict["name"]='vishal','rohit','kapil' dict["section"]='D','E','F' print("enter the choice ") print("1.enter the key to see its value 2.display the whole dictionary") ch=int(input()) if(ch==1): print("enter the key") val=input() print("value is {}".forma...
PI = 3.141592 raio = float(input("Digite o raio: ")) circunferencia = 2 * PI * raio a_circulo = PI * raio ** 2 a_esfera = 4 * PI * raio ** 2 vol_esfera = 4 / 3 * PI * raio ** 3 print("Circunferência: %5.6f " % (circunferencia)) print("Área do círculo: %5.6f" % (a_circulo)) print("Área da esfera: %5.6f" % (a_esf...
from keras.utils import to_categorical import numpy as np #first define a dictionary of letters mapped to integer LETTERS="ABCDEFGHIJKLMNOPQRSTUWXYZV*" letter_to_int={} for i,letter in enumerate(LETTERS): letter_to_int[letter]=i #print(letter_to_int) char_to_int=dict((c,i) for i,c in enumerate(LETTERS)) int_to_...
# Line towards your cursor with infinite length # Right Click or Left Click to change position # By: Ali import pygame # --- constants --- BLACK = (0, 0, 0) GREEN = (0, 255, 0) DISPLAY_WIDTH = 800 DISPLAY_HEIGHT = 600 # --- functions --- def calculate(player_x, player_y, mouse_x, mouse_y): dx...
#is power of 2 def is_power_of_two(x): return x&(x-1)==0 #最大公约数 def gcd(a,b): # O(logmax(a,b)) if b==0: return a return gcd(b,a%b) # 求x,y 使得 ax+by=gcd(a,b) d=gcd(a,b) def extgcd(a,b,d): if b==0: return d/a,1 x,y=extgcd(b,a%b) return y,x-int(a/b)*y #最大公约数 def gcd(a,b): # O(logmax(a,b)...
#!/usr/bin/env python #from sys.stdout import write import sys import StringIO class Board: BLANK = ' ' BORDER_HOR = '-------------\n' BORDER_VER = '|' WIDTH = 9 HEIGHT = 9 def __init__(self, board=[]): self.board = board if not board: B = self.BLANK se...
""" Compute mean square displacement date: 06/21/2017 """ import numpy from numpy import ndarray def msd(x: ndarray) -> ndarray: """Assume each row is for one atom""" N = x.shape[0] def aux(gap: int) -> float: return numpy.average( numpy.sum( numpy.square(x[gap:N, :] -...
import sys import pygame from random import randint #setting the dimensions of screen,bricks,paddle,and the ball Screen_size = 800, 600 Brick_width =65 Brick_height = 20 Paddle_width = 200 Paddle_height = 20 Ball_diameter = 25 Ball_radius = int(Ball_diameter / 2) PADDLEX = Screen_size[0] - Paddle_width BA...
def INT(): return int(input()) def MAP(): return map(int, input().split()) X = INT() year = 0 cash = 100 while cash < X: year += 1 cash = int(cash * 1.01) print(year)
import math H = int(input()) if H == 1: print(1) exit() n = int(math.log2(H)) #print(n) print(2**(n+1)-1)
class Solution: """ Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. Time: 93% (28ms) O(nlogn) """ def heightChecker(self, hei...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import heapq class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: """ Construct a maximum binary tree from a...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return level_q = [] waiting_q = [] ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def construct_tree(left, right): nonlocal...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: self.strings = [] self.char_map = {} alph = "abcdefghijklmnopq...
class Solution: """ Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. Time: 77%-94% (72ms - 80ms) """ def sortArrayByParity(self, A: List[int]) -> List[int]: evens = [] odds = [] fo...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rightSideView(self, root: TreeNode) -> List[int]: # Definition for a binary tree node. # class TreeNode: # def __init__(s...
def make_pizza(size,*args): """Summarize the pizza we are about to make""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for arg in args: print(f"+ {arg}")
# Store information about a person in a dictionary, first name, last name, age and city. Then # print call it's key and print the value inside it. person = { 'first_name': 'Bianca', 'last_name': 'Pal', 'age': 21, 'city': 'Lleida' } print(person['first_name']) print(person['last_name']) print(person['age']) ...
# PASSING ARGUMENTS # Positional arguments # When you call a function, Python must match each argument in the function call with a # parameter in the function definition. The simplest way to do this is based on the order # of the arguments provided. Values matched up this way are called positional arguments. def de...
#"Gabriel Garcia Marquez, part of poem" print("If for a moment God would forget that I am a rag doll and give me a scrap of life, possibly I would not say everything that I think, but I would definitely think everything that I say.") print("I would value things not for how much they are worth but rather for what th...
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: print(f"Adding {requested_topping}.") print("\nFinished making your pizza\n") # An if statement in the loop could handle the possibility that there isn't # any element left for requested_topping in r...
guests = ['Guaynaa', 'Katy Perry', 'Orlando Bloom', 'Maluma', 'Miley Cyrus'] for guest in range(0,5): print(f"Would you want to come to dinner with me {guests[guest]}") print('\n') not_arriving = guests.pop() new_guest = guests.append('Fuego') for guest in range(0,5): print(f"Would you want to come to dinner wi...
# Hacer un programa que sume con un bucle los cuadrados de los números del 1 al n # pidiendo al usuario el valor de n. Después de hacerlo, comprobar que coincide con: # (n(n + 1)(2n + 1))/6 # Se puede imprimir el resultado de esta ecuación y después el resultado de nuestra # suma. numero = int(input("Introduce un nu...
# + plus # - minus # / devide # * times # ** exponentiation # % modulo # < less than # > greater than print ("What is the answer to life, the universe, and everything?", int((40 + 30 - 7) * 2 / 3)) print ("Is it true that 5 * 2 > 3 * 4?") print (5 * 2 > 3 * 4) print("What is 5 * 2?", 5 * 2) print("What is 3 * 4?",...
# Write a function that accepts a list of items a person wants on a sandwich. The function # should have one parameter that collects as many items as the function call, provides, and # it should print a summary of the sandwich that's being ordered. Call the function three # times, using a different number of arguments...
# TUPLE # A Tuple is a inmutable list # It looks like a list except you use parenthesis instead of squared brackets. Once you define a tuple, you can access individual elements by using each item's index, just as you would for a list dimensions = (200, 50) print(dimensions[0]) print(dimensions[1]) # If you try to cha...
name = "ada lovelace" # this method changes each word to title case, where each word begins with a capital letter. print(name.title()) # this method changes a string to uppercase print(name.upper()) # this method changes a string to lowercase print(name.lower())
import os os.system('clear') total_amount = float(input("How much is the total amount? ").strip('$')) tip_15 = total_amount*0.15 tip_18 = total_amount*0.18 tip_20 = total_amount*0.20 print (f"A 15% tip would be an amount of ${tip_15:.2f}") print (f"A 18% tip would be an amount of ${tip_18:.2f}") print (f"A 20% tip ...
# Pedir al usuario una cantidad en euros (real) y componer esa cantidad mediante # la mínima variedad de billetes y monedas. Para ello pasar primero la cantidad dada # en euros a céntimos: def centimos(euros): cents = int(euros) cents = (round(cents*100)) factor_conversion = { 'C500': [50000] , 'C200':...
# Repetir el programa anterior pero para dibujar cualquier polígono de lado 50. Para ello # declaramos una variable nlados=6 (por ejemplo) antes y después repetimos (for) el dibujo del # lado, y giramos el ánguloExt = 360/nlados, o sea, right(360/nlados). import turtle s = turtle.getscreen() for i in range(1,6): tu...
import random def removeTheVowelsImp(inputString): vowels = ["a", "i", "e", "o", "u"] theConsonants = "".join([x for x in inputString if x not in vowels]) return theConsonants test = removeTheVowelsImp("This is a Test String") print(test) print(" ") vowels = ["a", "i", "e", "o", "u"] weekDays = ["Monday...