text
stringlengths
37
1.41M
cin = map(int, input().split(' ')) seq = list(cin) print('NO') for xi in range(1, len(seq)): if seq[xi] in seq[:xi]: print('YES') else: print('NO')
# -*- coding: utf-8 -*- #初始位置 (0, 0) 处有一个机器人。给出它的一系列动作 #判断这个机器人的移动路线是否形成一个圆圈, #换言之就是判断它是否会移回到原来的位置。 #移动顺序由一个字符串表示。每一个动作都是由一个字符来表示的。 #机器人有效的动作有 R(右),L(左),U(上)和 D(下)。 #输出应为 true 或 false,表示机器人移动路线是否成圈。 def judgeCircle(moves): start = [0, 0] end = [0, 0] for step in moves: if step == 'L': ...
for i in range(5): print(i); names = ["name1","name2","name3"] for j in names: print(j)
# Inputs test_list = [1, 2, 4, 5, 6] test_num = 7 class BinarySearch: """ new class to complete challenge """ def __init__(self, test_list, test_num): self.counter = 0 self.test_list = test_list self.test_num = test_num self.answer = 0 def binary_search(self): ...
from node import Node from bst import BST as tree def fizz_the_buzz(Node): """ Function that replaces node values with appropriate string """ if (Node.val % 15 == 0): Node.val = 'fizzbuzz' return Node if (Node.val % 5 == 0): Node.val = 'buzz' return Node if (Node...
from bst import BST as tree def find_max_value(tree): """ Returns max value from a tree """ tree.in_order(set_root_value) return tree.root.val def set_root_value(tree, node): """ Sets root value to greatest value in tree """ if tree.root.val is None: raise AttributeError ...
from node import Node class LinkedList: """ Doc strings are gud """ def __init__(self, iter=[]): self.head = None self._size = 0 self._current = self.head for item in reversed(iter): self.insert(item) def __repr__(self): """ assumes hea...
size=int(input()) arr=list(map(int, input.split(' '))) incorrect_list=list() for i in range(size): if i+1 == arr[i]: continue else: if arr[i] not in incorrect_list: incorrect_list.append(arr[i]) print(len(incorrect_list)-1)
def isPrime2(n): if n==2 or n==3: return True if n%2==0 or n<2: return False for i in range(3,int(n**0.5)+1,2): # only odd numbers if n%i==0: return False return True res=list() num1, num2 = map(int, input().split(' ')) for i in range(num1, num2+1): if isPrime2(i) and isP...
def driver_code(arr, stri, start, stop): if start<=stop: mid = (start+stop)//2 arr.append(stri[mid]) driver_code(arr, stri, start, mid-1) driver_code(arr, stri, mid+1, stop) test=int(input()) for _ in range(test): size=int(input()) arr=list() stri = list(input()) ...
# Find the difference between a function defined inside a class and a function outside a class class Person: def __init__(self, name, age): self.name = name self.age = age def makeHerOlder(self): self.age = self.age + 1 def makeHerOlderFromOutSide(argument: Person): argument.age =...
n =int(input("Enter Name")) i=1 while i<=n: print(i) i=i+1 else: print("end of for loop")
def min_item_index(arr): min_item = arr[0] min_index = 0 for i in range(len(arr)): if arr[i] < min_item: min_item = arr[i] min_index = i return min_index def selection_sort(arr): sorted_arr = list() for i in range(len(arr)): min_index = min_item_index(arr) sorted_arr.append(arr.pop(min_index)) retur...
from tkinter import * window=Tk() # button btn=Button(window, text="This is Button widget", fg='blue') btn.place(x=80, y=100) #label lbl=Label(window, text="This is Label widget", fg='red', font=("Helvetica", 16)) lbl.place(x=60, y=50) # text entry field txtfld=Entry(window, text="This is Entry Widget", bd=5) txtfld...
# Chapter06-02 # 병행성(Concurrency) # 이터레이터, 제네레이터 # Iterator, Generator # 파이썬 반복 가능한 타입 # for, collections, text file, List, Dict, Set, Tuple, unpacking, *args # Generator Ex1 def generator_ex1(): print('Start') yield 'A Point.' print('continue') yield 'B Point.' print('End') temp ...
""" Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below example. https://leetcode.com/problems/diagonal-traverse/ Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] """ def findDiagonalOrder(matrix): """ ...
def criticalConnections(n, connections): """ :param n: int :param connections: List[List[int]] :return: List[List[int]] """ result = [] l = [] for i in range(len(connections)): for j in range(0, 2): l.append(connections[i][j]) for j in range(len(l)): if ...
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. https://leetcode.com/problems/pascals-triangle/ Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ def ...
from numpy import math from factor import * # Find the prime factorization of a number def prime_factor(): number = input("Number: ") factors = factor(number) prime_factors = [] for number in factors: # test for primality test = factor(number) if len(test) == 2: p...
import requests import random def download(key): image_url = 'https://source.unsplash.com/1600x900/?'+key response = requests.get(image_url).content random_num = random.randint(0,99999) random_num = str(random_num) image_name = random_num + '.jpg' with open('downloads/'+image_name,...
import random import sys from string import ascii_lowercase print("H A N G M A N") def menu(): while True: user_choice = input('Type "play" to play the game, "exit" to quit: ') if user_choice == "exit": sys.exit() elif user_choice == "play": break ...
# Haolin Wu, 15/1/2020 # LeetCode palindrome-number https://leetcode.com/problems/palindrome-number/ class Solution: def isPalindrome(self, x: int) -> bool: # Logic is based on string comparisons, keeps the comparison on both sides as strings # to account for negative numbers. Theoretically conver...
# Haolin Wu, 19/1/20 # LeetCode pascals-triangle https://leetcode.com/problems/pascals-triangle/ class Solution: # Sum Previous takes a list and returns the expected 'next row' of pascal's triangle from it def sum_previous(self, nums): next_row = [] i = 0 while i < len(nums): if i == 0: next_row.appen...
import Deck class CardTree(object): def __init__(self, data): self.left = None self.right = None self.data = data self.rightParent = None self.leftParent = None def insert_left(self, data): if self.left is None: self.left = CardTree(data) self.left.rightParent = self else: self.left.inse...
import turtle t = turtle.Turtle() turtle.title("Pythagora's Tree") steps = 5 side = 100 t.speed(10000000000) t.hideturtle() def calc_hypotenuse(l: float): return (pow(l * 0.5, 2) + pow(l * 0.5, 2)) ** 0.5 def draw_polygon(lato, steps): ipotenusa = calc_hypotenuse(lato) for x in range(0, 5): if...
from comb_sort import comb_sort from patience_sort import patience_sort from barier_sort import barier_sort from random import randint from time import perf_counter_ns def random_list_gen(a): return [randint(0, 1000) for x in range(a)] def increasing_list_gen(a): return [i for i in range(a)] def decreasing_l...
# http://stackoverflow.com/questions/31997436/python-classes-and-for-loop-error/31997843#31997843 #python 3 class Chess: def __init__ (self): self.board = self.create_board () def create_board (self): board_x = [] for x in range (8): board_y = [] for y in range ...
list1 = [4, 5, 7, 65, 4, 9, 10] list2 = [] for i in list1: list2.append(i ** 2) print(list2)
######################################################### # Author: Tracy Ficor BIFS617 # # Homework Assign 4 # ######################################################### print("-------------Question 1--------------------") import re # create a functi...
# Main file for RemindMe Application # Users will run this, and input their data # and store it in DB # # After, we will use sender to schedule reminders # # \Author: Conner S. Bean # circa October 2017 import sqlite3, datetime # Current date formatting curr = str(datetime.datetime.now().year) curr += '-' + str(da...
class Records: """ This class stores the record of all the data read from a file """ def __init__(self) -> None: """ This is the default constructor of record class """ self.pkt = None self.max_temperature = None self.mean_temperature = None self....
""" Entradas inversion-->int-->dato1 salidas incremento-->int-->di total-->int-->total """ #entrada dato1=int(input("digite su inversio: ")) #caja negra di=(dato1*0.2) total=di+dato1 #salidas print("su incremento mensual es: " +str(total))
""" Entradas Chelines-->int-->CA Dracmas-->int-->DG Pesetas-->int-->P salidas CA-->int-->P DG-->int-->FrancoFrances P-->int-->Dolares P-->int-->LirasItalianas """ #entrada CA=int(input("Ingrese la cantidad de Chelines Austriacos a cambiar: ")) DG=int(input("Ingrese la cantidad de Dracmas Griegos a cambiar: ")) P=int(in...
def sep_input_label(paired_txt): '''Separate input and label sentences from paired txt''' input_words = [ ] label_words = [ ] input_len = [ ] label_len = [ ] for i in range( len(paired_txt) ): input_txt, label_txt = paired_txt[i][0], paired_txt[i][1] input_words_cur = in...
#! encoding: UTF-8 #! /usr/bin/python import math Cero=0.00001 def f(x): return math.sin(x) def biseccion(a,b,tol): c=float((a+b)/2.0) while f(c) != Cero and abs(b-a) > tol: if f(a) * f(c) < Cero: b = c; else: a = c; c = (a+b)/2.0 return c print 'Calcular la raz de sen de x' a...
#Given four strings A, B, C, D, write a program to check if D is an interleaving of A, B #and C. D is said to be an interleaving of A, B and C, if it contains all characters of A, B, C and the order of all #characters in individual strings can be changed. import itertools x=[] z=dict() y=['A','B','C'] #list...
x = input("Wprowadź tekst: ") if len(x)<4: print("Nie ma możliwości utworzenia nowego tekstu, za mało liter.") else: x = x[:2]+x[len(x)-2:len(x)] print(x)
def usun(x): lista = [] for i in x: if i not in lista: lista.append(i) return lista lista = [1,1,2,5,5,8,9,9,9,9] print(usun(lista))
from sys import argv from numpy import average, var, std if len(argv)<2: print('Nie podano żadnych argumentów!') elif len(argv) == 2: try: file = open(argv[1], 'r', encoding='utf-8') except: print('Błąd otwarcia pliku!') else: values = [] for i in file.readlines(): valu...
# import pandas as pd # # Create some Pandas dataframes from some data. # df1 = pd.DataFrame({'Data': [11, 12, 13, 14]}) # df2 = pd.DataFrame({'Data': [21, 22, 23, 24]}) # df3 = pd.DataFrame({'Data': [31, 32, 33, 34]}) # # Create a Pandas Excel writer using XlsxWriter as the engine. # writer = pd.ExcelWrite...
#! /usr/bin/env python # -*- coding: utf-8 -*- # a = 3 # print(1 < a < 5) #True # print(bool(12)) # True # print(bool(-4)) # True # print(bool(0)) # False # print(bool(-0)) # False # # Logic operators # x, y = True, False # print(x and y) # False # print(x or y) # True # print(not y) # True # print(not x) # False ...
import numpy as np import matplotlib.pyplot as plt from scipy import signal from matplotlib.animation import FuncAnimation from matplotlib.colors import LinearSegmentedColormap class ForestFireModel: """ This class implements the Forest-fire model as outlined in Drossel and Schwabl's 1992 paper "Self-organiz...
# copy a list to a new one list = [ 1,2,3,4,5 ] newList = list list.reverse() # using = the newList will also be reversed print( list ) print( newList ) # using copy you create an independent list anotherList = list.copy() list.reverse() print( list ) print( anotherList )
import random main_list = [] # Length of list can be anywhere between 10 digits to 20 length_main_list = random.randint(10,20) # Get numbers randomly from 1 to 100 and add to the main_list # Now main_list created and can be play araound while len(main_list) <= length_main_list: main_list.append(random.randint(1,...
import random comp_num = random.randint(1,9) print (comp_num) user_num = 0 attempt = 0 while user_num != comp_num or gameon == 'n': user_num = int(input("Enter your number: ")) attempt +=1 if (user_num <1 and user_num>9): print ("not valid number") break elif (user_num == comp_num): ...
palavra = input("Informe uma palavra: ").title() if palavra.endswith('o'): print(f"{palavra}s") else: print(f"Essa conjunção de Palavra '{palavra}' não é terminada la letra O!")
"""Examples of using lists in a simple 'game'.""" from random import randint rolls: list[int] = list() while len(rolls) == 0 or rolls[len(rolls) - 1 ] != 1: rolls.append(randint(1, 6)) print(rolls) # Remove an item form the list by its inded ("pop") rolls.pop(len(rolls) - 1) print(rolls) # Sum the valus of ...
"""Repeating a beat in a loop.""" __author__ = "730320843" user_beat = input("What beat do you want to repeat? ") user_amount = int(input("How many times do you want to repeat it? ")) counter = 0 x = user_beat if user_amount <= 0: print("No beat...") else: user_beat2 = "" while counter < user_amount: ...
number = int(input().strip()) for i in range(number): if number <= 1 or (i > 1 and number % i == 0): print('This number is not prime') break else: print('This number is prime')
amount = int(input().strip()) def plural_print(count: int, noun: str) -> None: plural = noun if count > 1 and noun not in ['sheep']: plural += 's' print(count, plural) chicken = 23 goat = 678 pig = 1296 cow = 3848 sheep = 6769 if amount < chicken: print('None') elif chicken <= amount < goa...
# 2D table o currencies # For each currency on x, we have a price on y # Starting with amount of money A, is it possible to make trades and get more than A? # Mock currency table, with X, Y, Z # Mock values: X = 12, Y = 6, Z = 3 currency_exchange_rates = [ [1.0, 2.0, 4.0], # X line [0.5, 1.0, 2.0], # Y li...
str1 = input('enter your 1st string : ') str2 = input('enter your 2nd string : ') print(len(str1),len(str2)) print(str1 + str2) print(str1.upper(),str2.upper()) print(str1.lower(),str2.lower())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Programme principale du jeux de pendu en mode console Ce programme n'as pas de fonctions mais exécute toutes celle indiqués au début Dans un premier temps on choisie parmis des actions Puis : - On lance le jeux - On met à jour la liste des mots - On quitte ...
import argparse import sys import dnssplitter def parse_args(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("dns_names", type=str, nargs='+', help="Domain name(s) to break down into parts") args = parser.parse_args()...
#!/usr/bin/env python3 #-*- coding = utf-8 -*- #如何为元组中的每一个元素命名,提高可读性 #方案2 from collections import namedtuple Student = namedtuple("student",['name','age','sex','email']) s = Student('Jim',16,'male','jimeeee@gmail.com') print(s) print(s.name,s.age) print(isinstance(s,tuple))
class IntTuple(tuple): def __new__(cls,iterable): #IntTupule会传入到cls中,其它参数与__init__方法一致 g = (x for x in iterable if isinstance(x,int) and x > 0) return super().__new__(cls, g) def __int__(self,iterable): #before super().__int__(iterable) #after t = IntTuple([1,-1,'abc',6,['x','y'],3]) print(t)
# -*- coding: utf-8 -*- from collections import Iterable # 杨辉三角 def triangles(n): list = [1] while n>0: yield list list = [1]+[x+y for x,y in zip(list[:],list[1:])]+[1] n -=1 return for x in triangles(6): print(x) # test = [1] # t = zip(test[:],test[1:]) # x = [1, 2, 3] # y = [4, 5, 6, 7] # xy = zip(x, y) # ...
from random import randint from collections import deque import pickle import os target = randint(0,100) if os.path.exists('history.txt'): #使用load()将数据从文件中序列化读出 d = pickle.load(open('history.txt','rb')) #print('exit') else: d = deque([],5) #print('not exit') def guess(num): if num == target: print('well do...
# coding=utf-8 # 后缀表达式转中缀表达式 from Stack import Stack l = '6 5 2 3 + 8 * + 3 + *' l = l.split() s = Stack() result = '' t = 0 for i in l: if i.isdigit(): s.push(i) else: t = t + 1 if t == 1: tem1 = s.pop() tem2 = s.pop() print tem2,tem1 else: tem2 = s.pop() if i == '+' or i == '-': if t == 1...
# -*- coding=utf-8 -*- lis = [53,661,664,-66,-634] print(sorted(lis)) # key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序 print(sorted(lis, key = abs)) name = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(name, key=str.lower)) # 反向排序 print(sorted(name, key=str.lower, reverse=True)) L = [('Bob', 75), ('Adam', 92), ('Bart', ...
import random def game(count): car = 0 while count > 0: prizes = ['goat', 'goat', 'car'] random.shuffle(prizes) index = random.randrange(3) choice = random.choice(prizes) if choice == 'car': car += 1 count -= 1 return car def game_change_door(c...
############# #List of all street names in Iceland the postcode for the street and place (municipiality). Combines two datasets from the Iceland Post Authorities ############## import scraperwiki,re from BeautifulSoup import BeautifulSoup #This is a list of postcodes and their place (i.e: 101 = Reykjavik) html = scr...
# 6. В программе генерируется случайное целое число от 0 до 100. # Пользователь должен его отгадать не более чем за 10 попыток. # После каждой неудачной попытки должно сообщаться, # больше или меньше введенное пользователем число, чем то, что загадано. # Если за 10 попыток число не отгадано, вывести ответ. from random ...
# 2. Закодируйте любую строку по алгоритму Хаффмана. import heapq from collections import Counter, namedtuple # узед class Node (namedtuple('Node', ['left', 'right'])): # обход узла def walk(self, code, acc): self.left.walk(code, acc + '0') self.right.walk(code, acc + '1') # лист class Leaf ...
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random def main(): lst = [random.randint(-20, 33) for _ in range(0, 10)] print(lst) local_max = {'idx': 0, 'value': lst[0]} local_min = {'idx': 0, 'value': lst[0]} for i, item in enumerate(lst): ...
# 5. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. from string import ascii_letters def main(): letter_idx = int(input('Введите номер буквы ')) - 1 alphabet = ascii_letters[:26] result = alphabet[letter_idx] print(f'Под номером {letter_idx + 1} расположена буква {result}')
# 5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. # Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке. def main(): row = '' for i in range(32, 128): # чтобы отделить один элемент от другого задаем обрамляем...
from datetime import datetime now = datetime.now() print now # a = raw_input("You shall pass,but give me your name! ") # print "This is a wonder, my name is also %s" % (a) # def clinic(): # print "You've just entered the clinic!" # print "Do you take the door on the left or the right?" # answer = raw_in...
from sys import argv script, input_file = argv #input: current file #read all of current file def print_all(f): print(f.read()) #start from the top again def rewind(f): f.seek(0) #read just a line def print_line(line_count, f): #linecouent: num of the line print(line_count, f.readline()) #ope...
s=raw_input('Inserte una cadena: ') ch='.' new='' cont=0 for i in s[::-1]: if cont!=0 and cont%3==0: new=new+ch new=new+i cont=cont+1 print new[::-1]
# Escriba un programa que convierta de centímetros a pulgadas. Una pulgada es igual a 2.54 centímetros. # Guardamos los centimetros centimetros = input("Introduce la centimetros a convertir: ") # Definimos funcion para hacer la conversion def convertir(): resultado= centimetros*2.54 retu...
''' 13.Desarrollar un programa que permita cargar 5 nombres de personas y sus edades respectivas. Luego de realizar la carga por teclado de todos los datos imprimir los nombres de las personas mayores de edad (mayores o iguales a 18 años) . (Se deberá crear dos lista una para el nombre y otro para la edad) ''' list...
''' 6. Un número primo es un número natural que sólo es divisible por 1 y por sí mismo. Escriba un programa que reciba como entrada un número natural, e indique si es primo o compuesto. Los números que tienen más de un divisor se llaman números compuestos. El número 1 no es ni primo ni compuesto ''' numero = int(raw_...
# Cn = C * (1 + x/100) ^ n #Donde C es el capital inicial, x es la tasa de interés y n es el número de años a calcular. Hallar cuanto vale Cn. El resultado vendra dado con dos decimales #el exponente se pone ** en python # Guardamos los datos del usuario capital_inicial = float(raw_input("Cantidad de euros: ")) tasa...
''' 14. Desarrollar una aplicación que nos permita crear un diccionario ingles/castellano. La clave es la palabra en ingles y el valor es la palabra en castellano. Se irán pidiendo por teclado la palabra en ingles y castellano hasta que digamos que no queremos continuar. en caso de que exista la palabra en ingles se i...
#!/usr/bin/python3 import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from tkinter import * nombres = ["Navegador 1","Navegador 2","Navegador 3","Navegador 4","Navegador 5"] valores = [] def mostrarGrafica(): # Añaadimos cinco elementos a ambas listas preguntando # al usuario valor...
''' 11.Crear y cargar una lista con 5 enteros. Implementar un algoritmo que identifique el mayor valor de la lista. E imprime la lista entera ''' listaEnteros = [] mayor = 0 for i in range(0,5): enteros = raw_input("introduzca enteros : ") listaEnteros.append(enteros) for i in listaEnteros: ...
''' 10. Un número primo es un número natural que sólo es divisible por 1 y por sí mismo. Escriba un programa que reciba como entrada un número natural, e indique si es primo o compuesto. Los números que tienen más de un divisor se llaman números compuestos. El número 1 no es ni primo ni compuesto. ''' nDias = int (ra...
''' 12.Crear y cargar una lista con 5 enteros por teclado. Implementar un algoritmo que identifique el menor valor de la lista y la posición donde se encuentra. ''' listaEnteros = [] mayor = 0 for i in range(0,5): enteros = raw_input("introduzca enteros : ") listaEnteros.append(enteros) for i in lis...
''' 5.Un viajero desea saber cuánto tiempo tomó un viaje que realizó. Él tiene la duración en minutos de cada uno de los tramos del viaje. Desarrolle un programa que permita ingresar los tiempos de viaje de los tramos y entregue como resultado el tiempo total de viaje en formato horas:minutos. El programa deja de pedi...
''' Crea una función que reciba 2 números, devuelve el mayor e imprímelo. ''' def esmayor(numero1,numero2): if numero1 == numero2: return "el número1",numero1," es igual que", numero2 else: if numero1>numero2: return "el número1",numero1," es mayor que", numero2 else : ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 6. Realizar una calculadora aritmética con funciones. Crear el siguiente menú 1.Suma 2.Resta 3.Multiplica 4.División 5.Salir ''' def suma(): numero1 = int(input("introduzca numero 1: \n")) numero2 = int(input("introduzca numero 2: \n")) print (numero1 +...
''' 8.Introducir cadenas hasta que el usuario no desea insertar más en una lista. Para cada cadena se imprimiera el siguiente mensaje dependiendo de su longitud . Si la longitud es menor de 5 pondrá el nombre de la cadena y que es menor que 5 y en caso contrario pondrá que es mayor que 5 y la cadena Juan menor que 5...
# Hallar el área y el perímetro de una circunferencia. El radio se pedirá por teclado. La solución tendrá dos decimales from math import pi # Defining Funtions def circle_perimeter(radio): """ formula: perimetro = 2 * pi * radio """ radio = float(radio)# We convert the input in floating perimeter = 2 * pi * r...
import random import time from copy import deepcopy import matplotlib.pyplot as plt def bubble_sort(needSortList): for i in range(len(needSortList) - 1): #设置一个标志以确认列表是否已经完成排序 isSorted = True for j in range(len(needSortList) - 1 - i): if needSortList[j] > needSortList[j + 1]: ...
import os class Nodo(): def __init__(self,dato): self.dato=dato self.sig=None def getDato(self): return self.dato class ListaSimple(): def __init__(self): self.first=None self.last=None def isEmpty(self): if self.first==None: return True else: return False def inser...
x = str(raw_input()) def printt(a): r = "" if a ==0: print "0" else: while a>0: i = a%2 a = a/2 r = str(i) + r print r while( x!= "#"): N = int(x, 2) ans = 17*N printt(ans) ...
#Central_With_statistics Module 2 Project import statistics total = 0 values = 0 from typing import Counter values = range(101) for counter in range(101): print(counter, end=' ') total = total + counter print(f'The sum of numbers = {total}') print(f'The counter is {counter}') #print('The values a...
#!--coding:utf-8--!# import os from Crypto.Cipher import AES from random import randint #加密前的填充 def pad(PT,block_zise): PT_length = len(PT) pad_num = block_zise - ( PT_length % block_zise ) pad_alpha = chr(pad_num) PT_pad = PT + pad_alpha * pad_num return PT_pad #按块AES加密 def encrypt_block(key, pl...
#!--coding:utf-8--!# #pad_alpha = chr(pad_num) #pad_num = 块长度 - 明文 % 宽长度 def padding(PT,block_zise): PT_length = len(PT) pad_num = block_zise - ( PT_length % block_zise ) pad_alpha = chr(pad_num) PT_pad = PT + pad_alpha * pad_num return PT_pad def check_padding(Padded_PT): test = Padded_PT...
#Trying out python unittest, no real tests yet #Stephanie Simpler #9-28-2019 import unittest class TestEventTotals(unittest.TestCase): def set_up(self): #self.widget = Widget('The widget') print("This method will be run for every test.") def test_totals(self): #self.assertTrue(output) print("Test") def...
def countstring(string, n): return string * n if string.isalpha() else "Not a string"
""" 1.两数之和 https://www.geekxh.com/1.0.%E6%95%B0%E7%BB%84%E7%B3%BB%E5%88%97/007.html#_01%E3%80%81%E9%A2%98%E7%9B%AE%E5%88%86%E6%9E%90 """ def force_two_sum(nums: list, target: int) -> list: """ Force method :param nums: :param target: :return: """ for i in range(0, len(nums)): for j...
def removeDuplicates(array): """ :type nums1: String :rtype: int slow and fast runnner fucking stupid!!!!!! """ i = 0 if len(array) == 0: return 0 for j in range(1, len(array)): if array[j] != array[i]: i +=1 array[i] = array[j] return i +...
class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): walker = self a = "" while walker: a = a + str(walker.val) + '->' walker = walker.next return a.strip('->') def common_elements(string, lst, l...
class Solution:    def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:        result = []        l = min(len(arr1), len(arr2), len(arr3))        if l==len(arr1):            L1 = arr1            L2 = arr2            L3 = arr3        elif l==len(arr2):            L1 = ar...
#!python class CircularBuffer(object): def __init__(self, iterable=None): """Initialize circular buffer and enqueue iterables""" self.list = list() self.front = 0 if iterable: for i in iterable: self.enqueue(i) def __repr__(self): ""...
class Node: def __init__(self,key): self.left = None self.right = None self.val = key root = Node(10) root.left = Node(20) root.left.left = Node(30) root.left.right = Node(100) root.right = Node(80) root.right.left = Node(201) def level(root): q = [] if root: q.append(root...
''' Notes:: python 3 has // operator which gives floor of the division. Example : 9/2 will give 4.5 and 9//2 will give 4 as value. python 2 behaves equally for / and // operator Both 9/2 and 9//2 gives 4 ''' def create_array(size=10, max=50): from random import randint return [randint(0,max) for _ in rang...
numero1 = 2 numero2 = 3 resultado = 0 resultado = numero1 + numero2 print("El resultado de la operacion es:",resultado) resultado +=numero1 # resultado = resultado + 2 print("El resultado de la operacion es:",resultado) resultado *=numero2 # resultado = resultado * 3 print("El resultado de la operacion es:",resultad...