text
stringlengths
37
1.41M
def editDistanceRec(str1, str2, m, n): if n == 0: return m if m == 0: return n if str1[m-1] == str2[n-1]: return editDistanceRec(str1, str2, m-1, n-1) return 1 + min(editDistanceRec(str1, str2, m-1, n), editDistanceRec(str1, str2, m, n-1), editDistanceRec(str1, str2,...
"""Housing functions""" import numpy as np import pandas as pd a = pd.DataFrame([1,2,3,np.NaN]) print(a)
# -*- coding: iso-8859-1 -*- """ Blatt 11: Yahtzee Thomas Hofmann, Yannic Boysen Version 1.0 (26.01.18, 18:41): # Diese Version kann ein komplettes Kniffel Spiel simulieren # Das Programm berlsst alle Entscheidungen dem Zufall. Version 2.0 (30.01.18, 19:29): # Das Programm trifft nun informierte Entscheidungen ""...
#welcome to chương trình phòng vệ toàn cầu. aliens= 2 password = "nguyenthao" print("Nhanh lên! Người ngoài hành tinh đang xâm chiếm đấy!") print("Bạn cần bật hệ thống phòng vệ toàn cầu lên ngay!") print("Hy vọng bạn biết mật khẩu, vì tương lai Trái Đất...") print() print("........................................
import random import sys from io import StringIO import unittest from Circle import Circle from DrawingProgram import DrawingProgram from Rectangle import Rectangle from Square import Square from Triangle import Triangle from ShapeFactory import ShapeFactory from DrawingProgramIterator import DrawingProgramIt...
# Authors: Brent van Dodewaard, Jop van Hest, Luitzen de Vries. # Heuristics programming project: Protein pow(d)er. # This file implements an random algorithm which randomly builds up the protein chain. import random from classes.amino import Amino from functions.GetLegalMoves import get_legal_moves from functions.Ge...
""" common Implement a number of functions which we will use repeatedly throughout the course. """ from matplotlib import rc, pyplot as plt import seaborn as sns import numpy as np from IPython.core.display import HTML def initialize_figures(): """ initialize_figures() Set the common...
def WER(X,Y): """ returns the lavenshtein distance between X and Y X and Y are 2 strings of arbitrary lengths, represented as arrays. """ # if any of the string is empty # return the length of the other if len(X)*len(Y) == 0: return max(len(X), len(Y)) # if zeroth elements are same, # no need to make chan...
# ===== Problem Statement ===== # Given the array nums, for each nums[i] find out # how many numbers in the array are smaller than it. # That is, for each nums[i] you have to count the number # of valid j's such that j != i and nums[j] < nums[i]. # # Return the answer in an array. class Solution: # Runtime: 280...
from typing import List # ===== Problem Statement ===== # You are given the array paths, where paths[i] = [cityAi, cityBi] # means there exists a direct path going from cityAi to cityBi. Return # the destination city, that is, the city without any path outgoing to # another city. It is guaranteed that the graph of pat...
from typing import List # ===== Problem Statement ===== # Given an array arr, replace every element in that array # with the greatest element among the elements to its right, # and replace the last element with -1. # After doing so, return the array. class Solution: # Runtime: 124 ms # Memory: 14.9 MB de...
# 'Write'- A basic text editor in python # made using tkinter import tkinter as tk from tkinter.filedialog import * # Setting up the window try: window=tk.Tk() window.minsize(800,500) window.title('Write') text=Text(window) text.pack(expand=True,fill=BOTH) # Defining Save,Open and New comm...
def c_to_f(cel): return int((cel * 1.8) +32) c_to_f(-10) print("Water freezing at {} C, {} F".format(0, c_to_f(0))) print("Coldest recorded temperatura is {} C, {} F".format(-79, c_to_f(-79))) print("Coldest temperatura possible {} C, {} F".format(-273, c_to_f(-273)))
#string = "This is a string with bunch of words" #print(string[8]) #print(len(string)) #for i in range(0, len(string)): # print(i) #for i in string: # print(i) # for i in range(0, len(string)): # for j in string: # print("This is index {} this is a char {}".format(i, string[i])) #string = "this samp...
numbers = [123, 54, 2, -1, 43, 22333, 1, 99, 883423] numbers_len = len(numbers) max_number = numbers[0] for i in range(1, numbers_len): if max_number < numbers[i]: max_number = numbers[i] print("This is the largest: {}".format(max_number)) numbers_len = len(numbers) min_number = numbers[0] for i in rang...
#Task1 #write a function which calculates factorial of a number #Functions has to accept a single argument, integer #Factorial formula #Factorial of n is #n! = 1 * 2 * 3 ... n def factorial(number): result = 1 for i in range(1, number+1): result = result * i print("Factorial of {} is {}".format(numbe...
print("Bien venido al mundo virtual, el menu:\n") while (True): print("""Acciones del menu principal 1.- Saludar 2.- Sumar dos numeros 3.- Salir""") respuesta = int(input("Por favor ingrese una opcio: ")) if respuesta == 1: print("Hola amigos desde Debian-Python") elif respuesta == 2: n...
import random import string def gen(LengthPassword): s = list(string.ascii_uppercase) + list(string.ascii_lowercase) + list(string.digits) + list(string.punctuation) random.shuffle(s) password = "".join(s[0:LengthPassword]) return password LenPass = int(input("Enter the Length of Passwor...
import networkx as nx from __helpers_general__ import print_res def centralities(graph, decrease_dictionary, no_of_nodes): """ Given a network x graph and information about the polarization finds the closeness, betweenness and Eigen centrality of the nodes that were connected and had the biggest and t...
# -*- coding: utf-8 -*- #!/usr/bin/python #批量将一个目录下的文件复制或移动到另一目录 #复制或移动的过程中,可以对文件进行重命名操作 #src_dir为源目录 dst_dir为目标目录 import os,shutil from random import randint root_path = os.getcwd() #获取当前根目录的路径 src_dir = r"E:\Examples_in_Python\Docs" dst_dir = r"E:\Examples_in_Python\Copytest" files = os.listdir(src_di...
""" phrase = input("Your phrase:") if len(phrase) < 1 : phrase = "Hello world" print(phrase) lst, lst_backwards = list(), list() for i in phrase: if i == " " : continue lst.append(i.lower()) ind = len(lst) - 1 # 10 - 1 while ind >= 0: lst_backwards.append(lst[ind]) ind -= 1 if lst == lst_bac...
import time,sys def typingPrint(text): for character in text: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) def typingInput(text): for character in text: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) value = input() return value game_still_going = Tru...
import math import matplotlib.pyplot as plt from .GeneralDistribution import Distribution class Binomial(Distribution): """ Binomail dist'n class for calculating and visualizing binomial dist'n. Attributes: mean (float) representing the mean value of the distribution stdev (float) r...
<<<<<<< HEAD banjang = input('반장의 이름을 입력하세요') print("우리반 반장 이름은", banjang) number1 = input("첫번째 문자를 입력하세요") number2 = input("두번째 문자를 입력하세요") print(number1+number2) number1 = int(input("첫번째 문자를 입력하세요")) number1 = int(input("두번째 문자를 입력하세요")) ======= banjang = input('반장의 이름을 입력하세요') print("우리반 반장 이름은", banjang) n...
N = list(input()) n = 0 for x in N: n += int(x) if n % 9 == 0: ans = "Yes" else: ans = "No" print(ans)
S = input() a = str(S.count('A')) b = str(S.count('B')) c = str(S.count('C')) d = str(S.count('D')) e = str(S.count('E')) f = str(S.count('F')) print(a+' '+b+' '+c+' '+d+' '+e+' '+f) #print(*[a,b,c,d,e,f])でいい ################## s=input() print(*[s.count(x) for x in 'ABCDEF'])
S = input() ans = "No" if len(S) % 2 == 0: if S == ("hi" * (len(S) // 2)): ans = "Yes" print(ans)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ self.data =...
""" Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not change their names. NTRIALS = 10 # Number of trials to run SCORE_CURRENT = 1.0 # Score for ...
import itertools # the letters a through f stand for the numbers 1-9 # d+b=c b+e=f the digits "abc" = the digits "ad" squared for x in itertools.permutations( range(1,10) ,6): if x[3] + x[1] == x[2] and x[1] + x[4] == x[5]: if pow(x[0] * 10 + x[3],2) == (x[0] * 100) + (x[1] * 10) + x[2]: print(list(...
#sectet nuber exercise secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input(f'{guess_count + 1} Guess: ')) guess_count += 1 if guess == secret_number: print('You won') break # so this else is tricky. if this else is after if then it will be pr...
#!/usr/bin/env python2.5 """ Problem 6 from Project Euler Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ n = 100 def sumsquares(n): total = 0 for i in range(1, n+1): total += i**2 return total def squaresum(n): to...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Problem 30 from Project Euler Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """ powlen = 5 fpl = [] def splitb10(x): """Split into a tuple of the ones, tens, hundreds, etc""" sl = () while x != 0: ...
#!/usr/bin/env python2.5 """ Problem 9 from Project Euler There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ from math import sqrt l = [] n = 1000 #Find all the Pythagorean triplets for i in range(1, n+1): for j in range(1, n+1): k = sqrt(i**2 + j**2) ...
# Create a UName and Pwd in the code. # Collect credentials from user as input # match to see if the credentials are correct s1 = "sdfsdf" s2 = "sdfsdf" if s1 == s2: print ("Strings are same ") else : print ("Strings are different ") u1 = "Hemant" u2 = "Scott" u3 = "Tim" p1 = "romeo1" p2 = "romeo2" p3 = ...
# Take a variable. # Put a day in it (Mon, Tue, Wed ... ) # Say if it is weekday or a weekend myDay = "Sun" """ if myDay == "Mon" : print ("Not a weekend") else : if myDay == "Tue" : print("Not a weekend") else myDay == "Wed" : print("Not a weekend") """ if myDay == "Tue" : print("Not ...
from datetime import datetime def get_userName(): n = raw_input("Whats your Name? ... ") return n def greet_user(name): print 'welcome {}'.format(name) def get_dob(): dob = raw_input("What's your date of birth in format m/d/y") #ask user to input data and return the date return dob def calcu...
class HeadSnakeLessThanTailSnake(Exception): def __init__(self, snake: "Snake") -> None: self.snake = snake def __str__(self) -> str: return f"{self.snake.head} less than {self.snake.tail}" class HeadSnakeEqualTailSnake(Exception): def __init__(self, snake: "Snake") -> None: se...
def bracket_matcher(input): # empty stack catch = [] # all the brackets brackets = {'[':']', '{':'}', '(':')'} # loop through input for i in input: # catch the keys and append to stack if i in brackets.keys(): catch.append(i) # look for other side of brackets if i...
import random print("\nLet's play Rock Paper Scissors!\n") win = 0 lose = 0 tie = 0 while True: n = random.randint(0, 2) print("Rock, Paper or Scissors?\n") RPS = input("") if RPS.upper() == "ROCK" and n == 0: tie += 1 print("\nYou played Rock, and the computer p...
# ISBN def isValidISBN(isbn): # Comprobamos la longitud del isbn if len(isbn) != 10: return False # Suma de los primeros 9 dígitos # Sumatoria de la multiplicación del valor de cada caracter en el isbn por # cada elemento de la "lista orden descendente del 10 al 1" _sum = sum([(int(isbn...
""" Program goals: 1. Get user input 2. Convert the input to input 3. Add input to list 4. Fill values from specific input positions """ #create functions that will perform those actions above import random myList = [] unique_list = [] def mainProgram(): print ("Hello! Let's work with some c...
"""Ejercicio 9: Crear un programa que pregunte al usuario 5 números enteros y devuelva una lista con ellos.""" lista_numeros = [] numero1 = int(input('1er número: ')) lista_numeros.append(numero1) numero2 = int(input('2do número: ')) lista_numeros.append(numero2) numero3 = int(input('3er número: ')) lista_numeros.a...
""" AVL trees Invariant: - lenght of left/right for every node differ at most +/- 1 Details: - each node attr is height - rotate avl on each operation (left rotate / right rotate) Implement: - delete - rotateLeft - rotateRight - rebalance """ from typing import Optional from dataclasses i...
class Car: #Define a class """My first Python class.""" def __init__(self,make,model,year): #Init method of the class, though it is not necessary but recommended if using OOP """Initialize attributes for a car.""" self.make = make #This and below attributes are initialized based on the paramete...
class CrclArea: """Class to calclate the area of a circle.""" def __init__(self, pi, radius): self.pi = pi self.radius = radius def crcl_area(self): area = self.pi * (self.radius)**2 return area pi = '' radi = 2 file = 'pi_digits.txt' with open(file) as fil...
#Inheritance Example showing passing a class instance as attributes #Super Class (or Parent class) class Car: #Define a class """My first Python class.""" def __init__(self,make,model,year): #Init method of the class, though it is not necessary but recommended if using OOP """Initialize attributes for...
#grocery = {"flour":10,"rice":10,"sugar":5,"pulse1":2,"pulse2":2,"pulse3":3} #print (grocery) #for key,val in grocery.items(): # if(key == "rice"): # print(val) #del grocery # ............... new program grocery = {} no_of_items = int(input("enter the number of items to be inserted\n")) ...
*** program for n= 5 to print pattern like #@@@@@ ### ##### ### @@@@@# *** n=5 m=n x=1 for i in range(n//2+1): print(" "*m,end='') #same as using for loop print("x"*x,end='') if(i==0):print("@"*n,end='') m-=1 x+=2 print("") m+=1 x-=2 for i in range(n//2): if(i==n//2-1):pr...
# the code below uses a static array where none value denotes that node has not child(left/right) ''' the binary tree for the array below will be 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 ''' arr = [1,2,3,4,5,6,7,None,None,8,9,N...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'pickingNumbers' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def pickingNumbers(a): # Write your code herere count = 1 newAr = {} temp...
# REVIEWING LOOPS #-----> GENERAL STUCTURE OF FOR LOOPS USING A COLLECTION: # for <temporary variable> in <collection>: # <action> # A for keyword indicates the start of a for loop. # A <temporary variable> that is used to represent the value of the element in the collection the loop is curre...
array = ['a', 'b', 'c', 'd', 'e'] print(array[::-1]) ##내일
import csv class Nation: def __init__(self, name, staticData): self.name = name self.data = {} for prop in staticData: self.data[prop] = staticData[prop] def addYearData(self, year, yearData): self.data[year] = yearData def getGDP(self, year, perCap = False):...
def Sort(d): sorted_values = list({k: int(v) for k, v in sorted(d.items(), key=lambda item: int(item[1]), reverse=True)}.values()) sorted_dict = {} while sorted_values: keys_with_same_value = [] value = sorted_values[0] for k in d.keys(): if int(d[k]) == value: ...
# CODE IS FROM https://www.digitalocean.com/community/tutorials/how-to-make-a-simple-calculator-program-in-python-3 # LICENSED Attribution-NonCommercial-ShareAlike # 4.0 International (CC BY NC-SA 4.0) # CODE IS NOT OWNED BY ME # Improved certain sections and added various other functions import math def mode(): mo...
class BST: def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): result = '' result += str(self.value) result += ' ' if self.left: result += str(self.left) if self.right: result += str(self.right) result += ' ' retu...
# Write a function that takes in an array of unique integers and returns its powerset. # The powerset P(X) of a set X is the set of all subsets of X. # For example, the powerset of [1,2] is [[], [1], [2], [1,2]]. # Note that the sets in the powerset do not need to be in any particular order. # O(2^n*n) TIME | O(2^n...
#2020/12/31 def solution(priorities, location): array1 = [c for c in range(len(priorities))] array2 = priorities.copy() i = 0 while True: if array2[i] < max(array2[i + 1:]): array1.append(array1.pop(i)) array2.append(array2.pop(i)) else: i += 1 ...
# input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not a pair was found def pair(hand): # first we build a list of the values of the cards in the hand, i.e. forget the suite list_of_values = [] for card in hand: valu...
#Jung Kim #CS-21 #Project #2 - Basic grade book def gradebook(): #creates the grade book as an empty list roster = [] return roster def add_student(roster): #a function to add students to the roster created in gradebook() user_confirm, confirm = confirming() #local confirm feature to increase efficiency ...
#Jung Kim #CS-21 Intro to programming #Coding lab 4 - flagging suspicious e-mails #It will output various information outlined in the lab instructions #The program has been generalized for any text files written in standard e-mail format def open_email(): #simple function to open e-mails textfile = input("") #...
# a=float(input('Side A:')) # b=float(input('Side B:')) # c=float(input('Side C:')) a,b,c = input('Please enter 3 sides: ').split() a=float(a) b=float(b) c=float(c) print(a,b,c) p = (a+b+c)/2 triang = (p*(p-a)*(p-b)*(p-c))**0.5 print(triang)
# # str =input('enter Stroka palindrom: ') # str1 = str.replace(' ','') # print(str1) # # mylist = list(str1) # print(mylist) # # mylist.reverse() # newstr = '' # for i in mylist: # newstr = newstr+i # # if str1==newstr: # print('URA !!!', str+' = '+newstr) # else: # print('Fig Vam....') entry = 'never odd...
import time def insertionSort(vetor): n = len(vetor) inicio = (time.time() * 1000) for i in range(2, n): atual = vetor[i] j = i - 1 while j>0 and vetor[j]>atual: #Move os elementos menores para o inicio do vetor vetor[j+1] = vetor[j] j = j - 1 v...
import time def mergeSort(vetor): if len(vetor) > 1: mid = len(vetor) // 2 # Encontrando o meio do vetor L = vetor[:mid] # Dividindo os elementos do vetor no meio R = vetor[mid:] mergeSort(L) # Ordenando a primeira metade mergeSort(R) # Ordenando a segunda metade ...
import re regexp = r'"(?:[^\\]| "' print re.findall(regexp,'"I say, \\"hello.\\""') == ['"I say, \\"hello.\\""'] print re.findall(regexp,'"\\"') != ['"\\"']
# input_shape(2,2)의 lstm from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout, BatchNormalization from sklearn.model_selection import train_test_split import numpy as np x = np.array(range(1,101)) y = np.array(range(1,101)) size = 8 def split_10(seq, size): aaa = [] ...
import openpyxl #carregando o arquivo book = openpyxl.load_workbook('planilhadecompras.xlsx') #slecionando uma página frutas_page = book['Frutas'] #imprimindo os dados de cada linha for rows in frutas_page.iter_rows(min_row=2, max_row=5): for cell in rows: print(cell.value)
# x = 1 # speed = 1 # y = 1 # def setup(): # size(1500, 1500) # background(255) # def draw(): # global x # global y # background(255) # fill(255) # rect(x,100,50,25) # fill(0) # x = x + 1 # while y != 100: # if y % 5 == 0: # rect(10,100...
import pickle # load the previous score if it exists try: with open('score.dat', 'rb') as file: score = pickle.load(file) except: score = 0 print ("High score: %d" % score) # your game code goes here score = 10 # save the score with open('score.dat', 'wb') as file: pickle.dump(sc...
from collections import namedtuple Point = namedtuple("Point", ["lat", "long"]) class Region(object): def __init__(self, firstPoint, *args): self._nw = firstPoint self._se = firstPoint map(self.include_point, args) def northmost(self): return self._n...
# Printing current date and time import datetime time = datetime.datetime.now() print("Current Date and Time", end=': ') print(time.strftime("%Y-%m-%d %H:%M:%S"))
proceeds = int(input("Введите значение выручки в рублях:")) costs = int(input("Введите значение издержек в рублях:")) if proceeds > costs: print("Вы отработали прибылью") profitability = proceeds / costs print(f"{profitability:.2f}") human = int(input("Введите количество сотрудников:")) print(f"{pr...
#creating employee class class Employee: print('Common base class for all employees') empCount = 0 #creating constructor def __init__(self, name, salary, age, bloodgroup): self.name = name self.salary = salary self.age = age self.bloodgroup = bloodgroup ...
def is_greater(x, y): if x > y: val = True return val else: return False assert not is_greater(4, 7) assert is_greater(8, 7)
import unittest from classes.room import Room from classes.guest import Guest from classes.song import Song class TestRoom(unittest.TestCase): def setUp(self): self.room = Room("Utahime", 100, "Karaoke Bar") self.guest_1 = Guest("Akira Nishikiyama", 200) self.guest_2 = Guest("Goro Maj...
""" from sys import argv script, filename = argv # use argv to get filename txt = open(filename) # opens filename print "Here's %r..." % filename print txt.read() # do the read command with no params """ print "Enter file to open:" # print "Type the filename again:" file_again = raw_input("> ") txt_again = ope...
#Assignment 5, Group Work: Creating XML Files #Brett Byron; Group 1 import csv, os, xml.etree.ElementTree as ET #Add class to xml file def add_xml_class(dept, abbr, num, name, credit, days, seats, building, room): root = ET.parse(source="classes.xml") elements = root.getiterator() class_list = elements[0]...
import brainteaser import random info = True def findout(): value1 = random.randint(1, 10) value2 = random.randint(1, 10) answer = input('What is {0} + {1}: '.format(value1, value2)) result = value1 + value2 if answer == result: print('Your answer is correct') else: print('You...
import random def dictionary_words(num): file = open("/usr/share/dict/words", "r") words_list = (file.read().split('\n')) #.read gives whole file, .split splits a string into a list # print(words_list) new_list = [] # for word in range(num): # new_list.append(random.choice(words_list)) ...
import time as t #import the time module #https://docs.python.org/3/library/time.html#time.time def bench(func): start_time = t.time() end_time = t.time() total_run_time = end_time - start_time return total_run_time #define functions # def test_function(): # sum = 0 # for i in range(100):...
class Node(object): def __init__(self, data, next_node=None, prev_node=None): ''' Initialize previous node for doubly linked list''' self.next_node = next_node self.prev_node = prev_node self.data = data def __repr__(self): ''' Return a string representation o...
import sample def markov(source): chain = {} current = None prev = None for word in source: current = word if not chain: chain[current] else: chain[prev] += current prev = current return chain if __name__ == '__main__': source =...
import urllib.request #Importing necessary libraries from urllib.parse import urlparse from bs4 import BeautifulSoup url= input( "Enter the Url : ") #Input the URL page = urllib.request.urlopen(url) ...
import math class Joint: ''' A joint. ''' def __init__(self, n, loc, pred=None, suc=None, weight=1, angle=0): ''' Initialized joint object. ''' self.ID = n self.location = loc self.pred = pred self.suc = suc self.weight = weight self.angle = angle def findnextpos(self, interval): ''' M...
# -*- coding: utf-8 -*- """ Created on Fri Nov 29 20:58:20 2019 @author: axelb """ import socket import random import string s = socket.socket() port = 3000 s.connect(('127.0.0.1',port)) print("Recieved :-") temp = "" while True: data = s.recv(1024).decode("utf-8") if(temp is not data):...
#oefening09, gokken #we raden een getal tussen 1 en 20 import random #we laten onze appliccatie een getal kiezen te_raden_getal = random.randint(1,20) print(te_raden_getal) succes = False aantal_pogingen = 0 #we gaan op zoek naar het getal while succes == False : aantal_pogingen +=1 gokje = int(input(f"Doe een...
def matmul(A): a={} for i in range(len(A)-1): for j in range(0,len(A)-i-1): if i==0: b=(j,j) a[b]=0 elif i==1: b=(j,j+1) a[b]=A[j]*A[j+1]*A[j+2] else: b=(j,j+i) ...
def main(): T = int(input()) for case in range(T): grade = list(map(int, input().split())) N = grade.pop(0) avg = sum(grade) / N cnt = 0 for i in grade: if i > avg: cnt+=1 persent = round((cnt/N)*100,3) pr...
import sys def main(): while True: string = sys.stdin.readline() if string[0] == '#': break stack = [] for i in range(len(string)): if string[i] == '<': idx = i elif string[i] == '>': tag = string[idx:...
#TODO def main(): N = int(input()) arr = [] arr_len =[] answer=[] for _ in range(N): k = list(input()) arr.append(k) arr_len.append(len(k)) print(arr) print(arr_len) for _ in range(N): idx = arr_len.index(min(arr_len)) ...
# Love Calculator class LoveCalculate: lover_name = "Hello" partner_name = "World" def __init__(self, lover_name, partner_name): self.lover_name = lover_name self.partner_name = partner_name @staticmethod def remove_space(sentence): return sentence.replace(" ", "").lower(...
# Object Oriented class Number: price = 1 def __init__(self, price): self.price = price def check_odd_even(self): if self.price % 2: return str(self.price) + " is Odd Number" else: return str(self.price) + " is Even Number" number = int(input("Enter a Nu...
# fibonacci series def fibonacci(x): sequence_list = [] current = 0 another = 1 for i in range(x): sequence_list.append(current) current = another if i > 0: another = sequence_list[i] + current else: another = 1 return sequence_list # pro...
#Emerging Technologies #Python Fundatmentals Problem Sheet #Ríona Greally - G00325504 #8.Write a function that merges two sorted lists into a new sorted list. [1,4,6],[2,3,5] → [1,2,3,4,5,6]. #creating 2 lists list1 = [3,4,9] list2 =[2,5,6] #using sorted function to merge and sort the lists print(sorted(list1 + list...
from simpleimage import SimpleImage DEFAULT_FILE = 'countries.jpg' def main(): print("\nHello! My name is Coffee Taster, and I will help you navigate through the world of coffee :)") print("It's grown in many countries, and its taste differs depending on the climate.") print("Tell me what coffee you like...
s = input("Enter your string : ") m = {i:s.count(i) for i in s} m_length = len(m) m_value = list(m.values()) m_max = max(m_value) m_new = [m_max - m_value[i] for i in range(m_length)] if(m_new.count(0)==m_length or m_new.count(1)==1): print("This is My String") else: print("This Is not my string"...
#CODE FOR Q1: def isStrDigit(x): #Check if a string is number of not for i in range(len(x)): if x[i]=='0' or x[i]=='1' or x[i]=='2' or x[i]=='3' or x[i]=='4' or x[i]=='5' or x[i]=='6' or x[i]=='7' or x[i]=='8' or x[i]=='9' : continue else: return False break...
""" convolutional neural network flow of the convolutional network for example, 256*256 RGB photo, the width and height are compressed into smaller size of arrays and the depth is increased during stride: the pixels for one step 2 key methods: ...