text
stringlengths
37
1.41M
Artist = 'Soundgarden' SoloArtist = 'False' StillActive = "Unknown" YearFormed = 1984 MusicansBand = True print(MusicansBand) if Artist == "Soundgarden": #if the Artist name is 'Soundgarden' then print the following True output.. MusicansBand = "Soundgarden is a Quartet Grunge band formed in 1984" ...
""" 将一张图片均匀向下移动,向右移动,每移动一次,切割出一个固定面积的图片 算法思想:我们知道图片实际上是有一个二维数组组成的,所以先控制横坐标不变,纵坐标截取,一直到纵坐标的边界,然后向右移动横坐标,重复上一步操作 """ # python实现图片切割技术 from PIL import Image # id标识图片 vx,vy为切成的图片大小 def cut(CUT_PATH, BLOCK_W, BLOCK_H,BLOAK_PATH): cut_image = CUT_PATH print(cut_image) cut_image_name = cut_image.split('/')[-1].sp...
import pandas as pd import datetime as dt from bs4 import BeautifulSoup import requests class ScraperBBC(object): def __init__(self): pass def scrape_site(self, url, element, attribute, news_page=True): """ Function to scrape BBC website using BeautifulSoup. It takes the following arg...
import math #print("Hello, world!") #name=input("What's your name? ") #print("your name is "+name) area=TriangoloArea(76,4) print (str(area)) area=TriangoloArea(89,5) print (str(area)) perimetro=TriangoloPer(57,14,29) print (str(perimetro)) #base=input("Give me the base of a triangle ") #height=input("Give m...
import os #print ('I want to find the area of a square. Give me the length of one of the sides.') #side=input('Enter length of the side...') #print ( 'The area is...',int(side)*int(side)) print ('I want to find the area of a triangle. Give me the length of the base and height.') base=input('Enter length of the base.....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # modulo_letra.py # # Copyright 2021 # Autor: Guilherme Silveira Mendes # ############################ # Código fonte em Python 3 ############################ #Todas funções abaixo fazem e retornam os padrões pedidos def opc_a(caracter): #declaracao de variavel ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # APNP7.py # # Copyright 2021 # Autor: Guilherme Silveira Mendes # ############################ # Código fonte em Python 3 ############################ #Import modularizado from produtos import * import json #Função Principal def main(): nome_entrada = input() ...
"""Capturing tweets which are sent from a location that is approximately the area that is Kingston Upon Hull""" from twython import TwythonStreamer import time import json import vaderSentiment from datetime import datetime, timedelta import plotly as py import plotly.graph_objs as go from pprint import pprint from va...
def contar_maiuscular_minusculas(texto): info = { "maiusculas": 0, "minusculas": 0 } for letra in texto: if letra.isupper(): # info['maiusculas'] = info['maiusculas'] + 1 info['maiusculas'] += 1 elif letra.islower(): info['minusculas'] += 1 ...
def intervalo(numero, inicio_intervalo, fim_intervalo): return numero >= inicio_intervalo and numero <= fim_intervalo if __name__ == '__main__': numero = int(input("Informe o número: ")) inicio_intervalo = int(input("Informe o início do intervalo: ")) fim_intervalo = int(input("Informe o fim do inter...
""" Exercício 02 Criar uma função que calcule o IMC de uma pessoa e retorne o valor. A fórmula de cálculo é a seguinte: imc = peso / (altura * altura) peso deve ser descrito em Kgs (ex. 85.5) altura deve ser descrita em metros (ex. 1.76) """ def ex02(peso, altura): return peso / (altura * altura) if _...
def match_brackets(input_str): stack = [] open_br = ['[', '{', '('] close_br = [']', '}', ')'] close_dict = { ']':'[', '}':'{', ')':'('} for s in input_str: if s in open_br: stack.append(s) elif s in close_br: print("found c...
# http://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_24_-_Convert_A_to_B_using_dictionary.jsp # Problem: Given a dictionary of words and two words A and B, find the minimum path required to convert A to B. # Only one character can be changed at a time while going from A to B and every word thus formed ...
#Divide two integers without using multiplication, division and mod operator. # #If it is overflow, return MAX_INT # class Solution(object): def divide_till_remainder_more_than_divisor(self, dividend, divisor): count = 1 if dividend - divisor >= divisor: while divisor < dividend: ...
l = [2, 4, 3, 1, 7, 6, 9, 8] print(l) d = {} for item in l: d[item] = 1 print(d) for i in range(1, len(l)): potential = [] potential.append(d[l[i]]) for j in range(0, i): print("Now comparing {} {}".format(l[j],l[i])) if l[j] < l[i]: potential.append(int(d[l[i]])+int(d[l[j]...
#! /usr/bin/python #Easy Given a list of two integers or set of two integers, print all two number subsets from this list of integers #Hard- Print all subsets from a given set of two integers. try: a=[1,2,3,4] b=[5,6,7,8] c=[(x,y) for x in a for y in b] print( c) except ValueError: print( "Value Error") def pri...
list=[10,15,16,14,17,13,11,19] pos_buy_price = list[0] neg_buy_price = list[0] neg_sell_price = -1 pos_sell_price = -1 temp_buy_price = pos_buy_price temp_sell_price = -1 max_loss=0 max_profit=0 temp_max_profit=0 for val in list[1:]: #Check if the price is falling down if(val <= neg_buy_price): if(neg_sell_price ...
s = 'john' m = 10 # print(dir(s)) s = s.upper() l = [1,2,3,4,5] # print(dir(l)) # print(help(l.append)) l.append(100) # print(l) l = [2, 1, 4, 79, 3, 100, 50] l.sort(reverse=True) # print(l) d = {'Italy': 'Rome', 'Germany': 'Berlin', 'Spain': 'Madrid'} # print(d) # print(dir(d)) # print(help(d.keys)) # print(d.k...
from typing import Dict, Tuple, List def print_list(item_list: List[any]): for one_item in item_list: print(one_item)
import time import math """ Prompts you to say numbers. Start this, and then hit "Record" in Audacity. http://www.audacityteam.org/download/ When you start Audacity, look in the bottom-left and set the Project Rate (Hz) to 8000. It takes about 30 minutes to record a full dataset. Tips: - Turn off your screen save...
animais = [] while(True): tipo = input() peso = float(input()) local = input() animais.append({'tipo':tipo, 'peso': peso, 'local': local}) s = input() if(s.upper() == 'PARAR'): break tigres, macacos, cobras = 0, 0, 0 peso_tigres = 0 for animal in animais: if(animal['tipo'].upper(...
''' Carros de João e Maria ''' char = input() max_ano = 0 max_velocidade = 0 vmedia = 0 count = 0 if(char == 's' or char == 'S'): while(char == 's' or char == 'S'): ano = int(input()) if(ano > max_ano): max_ano = ano velocidade = float(input()) if(velocidade > max_...
#Gerador #Gerador sera um objeto da classe dos geradores def g1(): yield 1 yield 2 yield 3 yield 4 def g2(): i = 0 #Loop infinito while True: yield i i = i + 2 def g3(seed): x = [] for n in seed: x.append(int(n)) i = 0 print x while True: ...
tal = input('skriv ett heltal?:') tal2 = input('skriv ett till heltal: ') x = int(tal) i = int(tal2) y = x t = i print(y + t)
import string text = 'heh' if text.lower()[0] == text.lower()[-1]: print('yes' ) else: print('jag dum')
import math import random as r inside = total = 0 while True: x = r.random() y = r.random() dist = math.sqrt(x*x+y*y) if dist < 1: inside += 1 total += 1 pi = 4.0 * inside / total print(pi)
def reverse(value): str = "" for i in value: str = i + str return str
def run_program(program): executed = set() ip = 0 acc = 0 while True: if ip == len(program): return (True, acc) elif ip > len(program) or ip in executed: return (False, acc) instr = program[ip].split() executed.add(ip) if instr[0] == 'no...
from PIL import Image import numpy as np #importando as bibliotecas utilizadas # tranformando a imagem para RGB, para certificar-se de que os pixels sejam apresentados neste formato im = Image.open('Syngenta.bmp').convert('RGB') # Criando um array de numeros (RGB) da imagem utilizando o numpy na = np.arra...
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2020 tamalone1 A collection of conversion factors for the units supported in the Vessel class. """ US = {'pressure': {'name': 'psi', 'factor': 0.006895}, 'length': {'name': 'in', 'factor': 25.4}} SI = {'pressure': {'name...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data N_NODES_HIDDEN_LAYER_1 = N_NODES_HIDDEN_LAYER_2 = N_NODES_HIDDEN_LAYER_3 = 500 N_CLASSES = 10 BATCH_SIZE = 100 N_PIXELS = 784 def get_layer(shape_w, shape_b): return {'weights': tf.Variable(tf.random_normal(shape_w)), ...
# grid.py """ Simple script to explore use of grid positioning in tkinter gui interface """ from tkinter import * root = Tk() # Creating a label with tkinter my_label1 = Label(root, text="This is the first label") my_label2 = Label(root, text="This is the second label") my_label3 = Label(root, text="This is the third...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.rightNode = None def connectNodes(root): if root is not None: q = [root, None] while q: cur_node = q.pop(0) if cur_node: cur_node.rightNode = q[0] if cur_node....
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def isSymmetric(root1, root2): if root1 is None and root2 is None: return True if root1 is not None and root2 is not None: return root1.data == root2.data and isSymmetric(root1.left, root2.right)...
# Input: # 2 # geeksforgeeks # forgeeksgeeks # allergy # allergic # Output: # YES # NO t = int(input()) for _ in range(t): str1 = input() str2 = input() len1 = len(str1) len2 = len(str2) if len1 != len2: print("NO") continue str1Map = {} for i in range(len1): if ...
import socket def main(): s = socket.socket() print("Socket created successfully") port = 12345 # Binding s.bind(('', port)) print("Socket binded to the port %s" %(port)) s.listen(5) print("Server is listening on the port %s" %(port)) while True: c, addr = s.accept()...
def cond(): a=int(input()) b=int(input()) c=int(input()) if a>b and a>c: print("a is larger") else print("a is smaller") if b>a and b>c: print("b is larger") else print("b is smaller") if c>b and c>a: print("c is larger") else: print("c is sm...
def cond(): a=5 b=3 if a==b: print("a is equal to b") else: print("a is not equal to b") cond()
# To search a binary search tree class Node: def __init__(self, data): self.data=data self.left=None self.right=None def search(root,key): if root is None or root.data==key return root elif root.data< key: return search(root.right, key) else: return se...
''' Created on Feb 10, 2019 @author: ITAUser ALGORTHM 1) Make a .json text file that will store our assignments 2) Import our .json file into our code 3) Create user input for finding assignments 4) Find the users assignments in our data -If the users input is in our data -The users input isn't in our data '...
class Solution: def frequencySort(self, s: str) -> str: freq = collections.defaultdict(int) for c in s: freq[c] += 1 res = '' freq = sorted(freq.items(), key=lambda x: -x[-1]) for c, q in freq: res += c*q ...
numeros=[1,8,6,3,9,1,100,45,25] cantidad = input ('que numeros') cantidad = int(cantidad) for numero in numeros: if numero >= cantidad: print (numero)
""" This module represents the Marketplace. Computer Systems Architecture Course Assignment 1 March 2021 """ from threading import Lock, currentThread class Marketplace: """ Class that represents the Marketplace. It's the central part of the implementation. The producers and consumers use its methods con...
x = input('Enter x:') y = input('Enter y:') z = input('Enter z:') x2 = input('Enter x:') y2 = input('Enter y:') z2 = input('Enter z:') x3 = (y*z2)-(z*y2) y3 = (x*z2)-(z*x2) z3 = (x*y2)-(y*x2) i = 'i' j = 'j' k = 'k' print x3,i print y3,j print z3,k
class EmptyStack(Exception): """ Stack is empty. """ pass class ListStack(): """ Use Python's list datastructure to implement a Stack Data Structure """ def __init__(self): """ Creates a Stack with a list backend """ self._data = [] def push(self, element): ""...
# 1. #五角数 # def getPentagona1Number(n): # if n % 10 == 0: # print(n) # def start(): # for n in range(1,101): # num = n*(3*n-1)/2 # print(num,end=" ") # getPentagona1Number(n) # start() # 2. #求一个整数各位数字和 # def sumDigits(n): # sum = 0 # for...
# CI2692 - Laboratorio de Algoritmos y Estrcuturas 2 # Laboratorio 2 - Merge Sort # Sorts.py # Autor: Luis Pino (15-11138) y Félix Arnos (15-10088) # Descripcion: Implementacion de los algoritmos InsertionSort y MergeSort # Librerias global arreglo import sys # Funciones def InsertionSort(A:list,P:int,R:int): for j ...
# from tkinter import * # window = Tk() # window .title("DATA") # window .mainloop() import tkinter window = tkinter.Tk() window.title("GUI") # creating the 'Canvas' area of width and height 500px canvas = tkinter.Canvas(window, width = 500, height = 500) canvas.pack() # 'create_line' is used to create a line. P...
# decimalnumber = int(input("enter a first biinary number ")) # reminder =0 # result = None # while(decimalnumber > 0): # reminder = decimalnumber %2 # result= decimalnumber //2 # print(result) # break # num = int(input("entere a binary number")) # # print(bin(num)) # num = int(input("Enter a...
#List creation numbers = [] number_input = '' print() print('Enter a list of numbers, type 0 when finished.') #Adding to the list while number_input != 0: number_input = int(input('Enter Number: ')) if number_input != 0: numbers.append(number_input) print() #Finds the sum sum = 0 for ...
'''Take user input for farenheit and convert to celcius''' print() print('This program will convert Farenheit to Celcius for you automatically!') print() fahr_num = float(input('What is the temperature in Farenheit? : ')) cels_num = (fahr_num - 32) * 5 / 9 print(f'The temperature is {cels_num} degrees.')
print('BRIDGEKEEPER: Stop! Who would cross the Bridge of Death must answer me these questions three, ere the other side he see.') print('LANCELOT(you): Ask me the questions, bridgekeeper. I am not afraid.') N = input('BRIDGEKEEPER: What is your name? - ') print('LANCELOT(you): My name is ' + N + ' of Camelot') Q = ...
#User input print('MULTIPLICATION TABLE') user_num = int(input('How many columns and rows do you want in your multiplication table? : ')) num_lines = user_num + 1 #Multiplication and output for row_num in range(1, num_lines): for col_num in range(1, num_lines): mult_num = row_num * col_num ...
import sys import re keymap = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', } def read_content(filename='ngrams-10k.txt'): with open(filename, 'r') as f: return f.read().strip().replace(',', ' ') def ask_for_numbers()...
#!/usr/bin/env python import calendar from datetime import timedelta, datetime from time import strptime, mktime def timeconverter2seconds(timestring): """ converts time from string with date in expected format to seconds since epoch """ # timestring = "2011-11-02 15:28:01" time_format1 = "%...
from math import factorial # Перестановки с повт def permutationsRep(n): return n**n def permutations(n): return factorial(n) def combinations(n, k): return int(factorial(n)/(factorial(n-k)*factorial(k))) # Cочетания с повт def combinationsRep(n, k): return int(factorial(n + k - 1) / (factorial(n - 1) * factori...
#Get info from file with open("input.txt", "r") as file: input_lines = [line.strip() for line in file] #Go through each line, break apart line to get relevant data, then check conditions, counting valid passwords validCounter = 0 for line in input_lines: #Break apart line halves = line.split(": ") password = halv...
#Class Assignment 2 #Nelson Koomson #3/11/21 for i in range(10): print("Hello World")
#Hello World #Nelson Koomson #2/18/21 #A program that prints Hello World 100 times using for loop for number in range(100): print("Hello World")
x1 = int(input('Please enter X coordinate of 1st rectangle: ')) y1 = int(input('Please enter Y coordinate of 1st rectangle: ')) width1 = int(input('Please enter width of 1st rectangle: ')) height1 = int(input('Please enter height of 1st rectangle: ')) x2 = int(input('Please enter X coordinate of 2nd rectangle: ')...
import random class NameGenerator: """This class represents a name generator. This is a python conversion of the generator found in `<http://forum.codecall.net/topic/49665-java-random-name-generator/>`_ all credits to the creator. This class generates random names from syllables, and provides a simp...
def happyBirthday (nazwa): print ("Happy Birthday to you!") print ("Happy Birthday to you!") print ("Happy Birthday, dear "+ nazwa + ".") print ("Happy Birthday to you!") def main(): imiesol = input ('Podaj imie:') happyBirthday (imiesol) main()
def isValid(s): """ :type s: str :rtype: bool """ parentheses = {')':'(',']':'[','}':'{'} stack = list() valid = True index = 0 while index < len(s) and valid: token = s[index] if token in [parentheses[k] for k in parentheses]: stack.append(token) ...
from collections import Counter def high_card(hand): """ This function will return the value of highest valued card in the given hand Example: ['5', '6', 'A', 'J'] => 14('A') """ highest = 0 for i in hand: if i > highest: highest = i return highest def number_of...
from typing import List class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: """ >>> s = Solution() >>> s.peakIndexInMountainArray([0, 10, 5, 2]) 1 >>> s.peakIndexInMountainArray([3, 4, 5, 1]) 2 """ begin, end = 0, len(arr) ...
# the function here is to build a parse tree w.r.t # a given dictionary def helper(s,wordDict,out): if len(s) == 0: return for i in range(len(s)+1): prefix = s[0:i] if prefix in wordDict: out.append(prefix) helper(s[i:],wordDict,out) def wordBreak...
from collections import Counter import heapq class TreeNode: def __init__(self,key,val,isJoin=False): self.key = key self.val = val self.isJoin = isJoin self.left = None self.right = None def __lt__(self,others): return self.val < others.val def huffmanCode(stri...
def countBitSet(n): count = 0 while(n): n =n&(n-1) count += 1 return count for i in [2**i for i in range(10)]: # print(i) print(countBitSet(i)) print("---------------------") for i in [3**i for i in range(10)]: # print(i) print(countBitSet(i))
def first_word(text: str) -> str: from itertools import takewhile, dropwhile # Return the 1st word return ''.join( # Remove everything else after a space or punctuation takewhile( lambda c: c not in ',. ', # Remove spaces and punctuation from the beginning ...
def easy_unpack(elements: tuple) -> tuple: """ returns a tuple with 3 elements - first, third and second to the last """ # your code here return elements[0], elements[2], elements[-2] ''' Chekio Mission Link: https://py.checkio.org/en/mission/easy-unpack/ Chekio Solution Link: https://py.check...
def group_equal(els): from itertools import groupby # Return a list of consecutive groups return [ # Make each consecutive groups into a list list(g) for k, g in groupby(els) ] ''' Chekio Mission Link: https://py.checkio.org/en/mission/group-equal-consecutive/ Chekio Solution L...
# name = input("Enter your name: ") # print("Hello there, {}!".format(name.title())) # num = int(input("Enter an integer")) # print("hello" * num) # result = eval(input("Enter an expression: ")) # print(result) # get and process input for a list of names names = input("Enter names separated by commas: ").title().spl...
''' Miranda Clay INST364 Final Project ''' ''' This simulation will walk the user through 5 different cybersecurity scenarios, each which varying costs for consequences ''' import random #random library will leave the outcomes up to chance print(" _ _ _ ...
def max_profit(prices): max_profit = prices[1] - prices[0] min_price = prices[0] for i in range(1, len(prices)): if (prices[i] - min_price > max_profit): max_profit = prices[i] - min_price if (prices[i] < min_price): min_price = prices[i] return max(max_profit...
print("I will now count my chickens:") # Prints normal print("hens",25 + 30 / 6) print("roosters", 100-25*3%4) # Calculates math print("Now I will count the eggs:") # Prints print(3+2+1-5+4%2-1/4+6) # # calculates without showing anything but answer print("Is it true that 3 + 2 < 5 - 7?") # Displays ur calculations pr...
# 3- Faça um Programa que peça o raio de um círculo, calcule e mostre sua área. import math raio = float(input("Digite o raio do circulo:")) result = math.pi * (raio ** 2) print(f"A area do circulo é: {result} e arredondado com duas casas decimais: {round(result, 2)}")
import functools as f import random as r def money(arr): return f.reduce( lambda agg, x: [min(agg[0], x), max(0, max(x - agg[0], agg[1]))], arr, [float('inf'), float('-inf')] ) while(True): l = [r.randint(0, 12) for _ in range(r.randint(2, 7))] x = money(l) print(l) pri...
first_number = int(input("Enter first number:")) second_number = int(input("Enter second number:")) operation = input("Enter arithmetic operation") if operation == "+" : result = first_number + second_number print("Result: " + str(result)) if operation == "-" : result = first_number - second_number pr...
## get user inputs def userInput(): loop = True counter = 0 list = [] while (loop == True): var = raw_input("Please enter something: ") if var != "-1": print "you entered", var list.append(int(var)) elif(var == "-1"): loop = False return l...
from sys import argv # returns the sum of the numbers on the diagonal # from the bottom left to the top right def sumDiagBotLftTopRgt(n): i=1 d=4 s=1 cnt=1 while cnt<n: for t in range(2): i+=d cnt+=1 s+=i d+=4 return s # returns the sum of te...
from sys import argv from primeUtil import getPrimesUpTo # returns the nth prime number def getAnswer(n): cnt=1 getPrimes = getPrimesUpTo(float('inf')) while cnt<n: cnt+=1 next(getPrimes) return next(getPrimes) if __name__=="__main__": print(getAnswer(int(argv[1])))
from sys import argv from primeUtil import factorCardByPrime # returns the smallest positive number that is evenly divisible # by all of the numbers from 1 to n def getAnswer(n): cards = {} for i in range(2,n+1): c = factorCardByPrime(i) for prime in c: if prime not in cards or c[pr...
# 참고한 링크: https://ratsgo.github.io/data%20structure&algorithm/2017/10/03/mergesort/ n = int(input()) list = [] for _ in range(n): list.append(int(input())) def merge_sort(list): if (len(list) == 1): return list else: middle = len(list)//2 left...
# -*- codin: utf-8 -*- import sqlite3 nome = str(input("Digite seu nome: ")) altura = float(input('Digite sua Altura substituindo a VIRGULA por PONTO: ')) peso = float(input('Digite seu Peso: ')) altX2 = (altura*altura) imc = (peso/altX2) conexao = sqlite3.connect("IMC.db") cursor = conexao.cursor() cu...
import keras from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential, load_model from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout import cv2 batch_size = 128 epochs = 5 # loading the dataset (X_train,y_train),(X_test,y_test) = mnist.load_data() img_r...
number = 2**1000 strNum = str(number) total = 0 for x in strNum: total += int(x) print(total)
def factorial(num): retVal = 1 for x in range(num): retVal *= (x + 1) return retVal stringNum = str(factorial(100)) counter = 0 for x in stringNum: counter += int(x) print(counter)
#!/usr/bin/python from time import time import gmpy2 from math import sqrt def isqrt(n): x = n y = (x + n // x) // 2 while y < x: x = y y = (x + n // x) // 2 return x def Read(data): fileName="PrimeNumbers.txt" file=open(fileName,"r") x=file.read(data) file.close r...
#!/usr/bin/env python # coding: utf-8 # In[ ]: Introduction to while loops # In[1]: current_num = 1 while current_num<=5: print(current_num) current_num+=1 # In[ ]: Letting the user choose when to quit: # In[2]: prompt = "\n Tell me something and I will repeat it back to you" prompt+= "\n Enter '...
def greet(name): #return "Hi %s " % user_input.title() return f"Hi {user_input.title()}" #.title() make the first letter uppercase user_input = input("What is your name?") print(greet(user_input))
monday_temperatures = [9.1, 8.8, 7.5] monday_temperatures.append(5.7) print(monday_temperatures) #find the index of an item monday_temperatures = [9.1, 8.8, 7.5] monday_temperatures.index(8.8) #find the value asigned to the index monday_temperatures = [9.1, 8.8, 7.5] monday_temperatures.__getitem__(1) print(monday_te...
//Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions. class Solution: def reverseOnlyLetters(self, S: str) -> str: start = 0 S = list(S) end = len(S)-1 a = range(33, 123, 1) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module for expanding contractions in english text. """ import os from core.path import Path __author__ = "Yannick Couzinié" # standard library imports import itertools import operator import yaml # third party library imports import nltk # local imports import core....
#!/usr/bin/python #using crypt module to decrypt an encrypted file (cipher) import hashlib from Crypto.Cipher import AES password = "foobar" key = hashlib.sha256(password).digest() mode = AES.MODE_CBC encryptor = AES.new(key,mode) text = 'some data that I want to encrypt' ciphertext = encryptor.encrypt(text) #prin...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # TEXT AREA explaining what the program is doing, any copyrights, licenses, etc # Copyright 2017 MyLittleCompany # Licensed under the ... License, Version X.X # # This program shows GPIO PWM usage,duty cycle change from 0% to 100% and reverse it, # used to glow up/dim d...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # TEXT AREA # Programmet skal bestå av to funksjoner: # Første funksjon skal # kalkulere fahrenheit grader fra oppgitt celsius område, kalt calc_fahrenheit() # der celsiusområdet er fra -10 til +10 grader celsius (begge tall inklusive) # # Andre funksjon skal # kalkuler...
import random def dice(quantity, sides = 6): """Rolls dice and shows each and total.""" rolls = [] for x in range(quantity): rolls.append(random.randint(1, sides)) total = 0 for y in range(len(rolls)): print('Roll %s is %s'%(y+1,rolls[y])) total += rolls[y] print('Total ...
import math """ Readable number """ def friendly_number(number, base=1000, decimals=0, suffix='', powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']): power = math.floor(math.log(abs(number), base)) if abs(number) > 0 else 0 power = min(power, len(powers) - 1) number /= ...
#! /usr/bin/env/python3 from math import ceil as roundup import time import random # ----------------------------------------------------------------- # This module is the main module for the entire application. # 29007778 - Wahyu Agung Sugimartanto (wsug0001@student.monash.edu) # -------------------------------------...
import numpy as np from layers import * from layer_utils import * class TwoLayerNet(object): """ A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of d, a hidden dimension of h, and perform classification over C c...