text
stringlengths
37
1.41M
# Srijana Shrestha # 1918305 word = input() for x in word: word = word.replace('i', '1') word = word.replace('m', 'M') word = word.replace('a', '@') word = word.replace('s', '$') word = word.replace('o', '.') print(word+'q*s')
import math def main(): # Escribe tu código abajo de esta línea pass a = int(input("Da el valor de a:")) b = int(input("Da el valor de b:")) c = int(input("Da el valor de c:")) if ((b**2)-4*a*c) < 0: print ("Raices Complejas") elif a == 0 and b == 0: print ("No tiene solucion") elif a == 0 and b != 0:...
def firstrun(): return "success" def computecirclearea(radius): return radius * radius * 3.14159 def firstandlast(inputlist): return inputlist[0], inputlist[len(inputlist) - 1] def timedates(date1, date2): # date input formate MMDDYYYY daydiff = 0 if date1[2] == date2[2]: if date1[...
from PIL import Image, ImageTk import tkinter as tk width = 600 size = 300 def show_entry_fields(): print("hello") root = tk.Tk() root.title('EuroTrip 2019 Photo Labeller') root.geometry("900x400") root.resizable(0,0) img = Image.open("lim.jpg") img = img.resize((width,size)) tkimage = ImageTk.PhotoImage(...
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Code starts here data=np.genfromtxt(path,delimiter=",",skip_header=1) census = np.concatenate((data,new_record),axis=0) # ...
import unittest from leetcode.problems.lc0083_remove_duplicates_from_sorted_list import LC0083_Remove_Duplicates_from_Sorted_List from leetcode.common.listnode import ListNode class LC0083_Remove_Duplicates_from_Sorted_List_Tests(unittest.TestCase): def test_LC0083_Remove_Duplicates_from_Sorted_List_00(se...
import unittest from leetcode.problems.lc0015_three_sum import LC0015_Three_Sum class LC0015_Three_Sum_Tests(unittest.TestCase): def test_LC0015_Three_Sum_01(self): lc = LC0015_Three_Sum() nums = [-1, 0, 1, 2, -1, -4] actual = lc.threeSum(nums) expected = [ ...
import unittest from leetcode.common.treenode import TreeNode from leetcode.problems.lc0101_symmetric_tree import LC0101_Symmetric_Tree class LC0101_Symmetric_Tree_Tests(unittest.TestCase): def test_LC0101_Symmetric_Tree_00(self): lc = LC0101_Symmetric_Tree() root = TreeNode(1) ...
import unittest from leetcode.problems.lc0031_next_permutation import LC0031_Next_Permutation class LC0031_Next_Permutation_Tests(unittest.TestCase): def test_LC0031_Next_Permutation_01(self): lc = LC0031_Next_Permutation() nums = [1, 2, 3] lc.nextPermutation(nums) expec...
#! /usr/bin/python a = 10 b = input(); c = a+b; #print('Sum of two number = {0}'.format(c)); print c
#! /usr/bin/python dict ={}; dict['one'] = "This is one"; dict[2] = "This is two"; tinydict ={'Name':'John',"code":6363,'Dep':"Sale"}; print dict['one']; print dict[2]; print tinydict; print tinydict.keys(); print tinydict.values();
sum_odd=0 sum_even=0 total=0 # sum of 1st 100 even integers for number in range(2,101, 2): sum_even += number print(f"Sum of 1st 100 even numbers is :{sum_even}") # sum of 1st odd integers for number in range(1,101,2): sum_odd += number print(f"Sum of 1st 100 odd numbers is:{sum_odd}") # sum of 1st 100 integer...
import os import art def sum1(n1,n2): return n1+n2 def substract(n1,n2): if n1>n2: return n1-n2 else: n2-n1 def multiply(n1,n2): return n1*n2 def divide(n1,n2): if n2==0: return "invalid can not be divided by 0" else: return n1/n2 operator={ "+":sum1, "-":...
import random from art import logo import os import time def Black_jack(): start_game=input("Do you want to play a game of Blackjack? Type 'yes' or 'no'").lower() user_score=0 dealer_score=0 user_deck=list() dealer_deck=list() counter=1 while start_game=="yes": print(logo) ...
from art_High_Low import logo,vs from game_data import data import random import os score=0 game_over=True a_dic={ 'name': "sarthak", 'follower_count': 0, 'description': 'xyxy ', 'country': 'India ' } b_dic={ 'name': "sarthak", 'follower_count': 0, 'description': 'xyxy ', 'country': ...
#!/usr/bin/env python # coding: utf-8 # In[5]: class Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, items): self.items.insert(0,items) def dequeue(self): return self.items.pop() def size(self): re...
import numpy as np from Particle3D import Particle3D def Find_potential_energy(particle1, particle2): """ Method to return the gravitational potential energy between two objects Potential energy is given by Ep = -Gm1m2/r :param particle1: Particle3D instance :param partcile2: Particle 3D insatn...
#!/usr/bin/env python # coding: utf-8 # In[2]: # importing important libraries import os import sys import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import pandas as pd import seaborn as sns from matplotlib.pyplot import figure, show # In[3]: #reading the cs...
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): for item in sorted(a_dictionary): print("{}: {}".format(item, a_dictionary[item]))
#!/usr/bin/python3 """ module urllib """ import requests import sys """" script that fetches an url """ if __name__ == "__main__": if len(sys.argv) == 2: response = requests.post('http://0.0.0.0:5000/search_user', data={'q': sys.argv[1]}).json() if resp...
#!/usr/bin/python3 import numpy as np """ Matrix multiplication Attributes: m_a(matrix): first matrix m_b(matrix): second matrix Return result(matrix) """ def lazy_matrix_mul(m_a, m_b): """ Multiply two matrix m_a * m_b """ if not isinstance(m_a, list): raise TypeError("m_a must ...
#!/usr/bin/python3 """ matrix_divided: divide all elements of a matrix Attributes: matrix(list): list of int, div(int): number used to divide Return: new matrix """ def matrix_divided(matrix, div): """ function: divide list of integer """ mustbeint = "matrix must be a matrix (list of lis...
class DQueue: def __init__(self): self.dequeue = [] def isEmpty(self): return self.dequeue == [] def addBegin(self, item): self.dequeue.insert(0,item) def addEnd(self, item): self.dequeue.append(item) def remBegin(self): self.dequeue.pop(0) def remEn...
#!/usr/bin/env python # coding: utf-8 # In[33]: def cal_kg(): """ kg를 파운드(lb)로 변환해주는 함수 """ kg = float(input("kg? >>>")) lb = float(2.20462 * kg) print(lb, "lb") # In[35]: def cal_lb(): """ 파운드(lb)를 kg으로 변환해주는 함수 """ lb = float(input("lb? >>>")) kg = float(0.453592 * lb) print(kg, "kg")...
""" Problem 1. Maximim Index - level medium Given an array A of positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] <= A[j]. EX1 34 8 10 3 2 80 30 33 1 A[1] = 8 A[7] = 33 therefore the answer is 7-1 = 6 Look at other numbers. A[0]= 34 that is the max so no bueno. A[2] =...
''' joaquim coleciona filmes no computador, mas quer gravar alguns em cd, precisar organizar sua lista por ordem alfabetica e gravar os cinco primeiros. (mae, vida, nos, eli, vidro, resgate, close, o poço, fragmentado, parasita). ''' import time filmes = ['mae', 'vida', 'nos', 'eli', 'vidro', 'resgate', ...
# coding: utf-8 # In[47]: def tuple_sort(): inp1=["PHP","Exercises","Backend"] '''counting the length of each input''' len_inp1=[len(inp1[0]),len(inp1[1]),len(inp1[2])] '''converting into tuple''' new_inp1=list(zip(len_inp1,inp1)) '''sorting using first key''' new_inp1.sort(key=lambda ne...
#!/usr/bin/env python ##################################################################################################### # Code Developed by Raja Chellappan # Student ID: 200716420 # Queen Mary University of London # Square Size Generator is used to create a random value using Python.random.uniform() function # f...
import numpy as np import matplotlib.pyplot as pl import csv import math import pandas as pd # Linear Regression Model class LinearRegression: def __init__(self): self.W = None def predict(self,X): y_predict = X.dot(self.W) return y_predict def L1Cost(self, X, y_target,reg): ...
import math def ln(): x=int(input("Value?")) ln=math.log(x) print(ln)
import math def sec(): x=int(input("Angle in Radian or Degree?Press 1 for radian,press 2 for degree")) if x==1: a=float(input("Enter Angle in Radian")) b=1/math.cos(a) print(b) elif x==2: a = float(input("Enter Angle in Degree")) ...
num2 = input('Please enter a length: ') print('User has entered', num2) num3 = input('Please enter a breath: ') print('User has entered', num3) if num2==num3: print("its is a square") else: print("its is a rectangle")
if __name__ == '__main__': N = int(raw_input()) a = []; while N > 0: s = raw_input().split(' ') if s[0] == "insert": (i,v) = (int(s[1]),int(s[2])) a.insert(i,v) elif s[0] == "remove": v = int(s[1]) if a.count(v): a.remov...
from geometry import Vector, normalize_angle from math import atan2, pi from bzrc import Command """A controller for a single tank. This used to be in the agent, but I wanted to clean up the agent code a tad so I made its own class""" class TankController(object): def __init__(self, tank): self.prev_speed_error =...
# Fri, 3 Sep 2021 # Task 13 # Reading and writing csv file import csv def viewData(): with open("D:\\College\\SEM 5\\Implant Training\\Git\\AI-ML-Inplant-Training\\Temp.csv", "rt") as f: for lines in csv.reader(f): print(lines) def addData(): with open("D:\\College\\SEM 5\\Implant...
# Mon, 23 Aug 2021 # Task 8.1 # Take input from user and find out sum and average of 0 to that number. i =0 sum = 0 n = int(input("\nEnter number : ")) while i <= n : sum+= i i += 1 print("------------------------------------------") print(f"\nSum of numbers from 0 to {n} = {sum} ") print(f" ...
#!/usr/bin/env python # coding: utf-8 # In[1]: A=8 B=30 print("Operator Relasional") print("-------------------") print("A= 8 dan B= 30") print("1. A == B bernilai ",A == B) print("2. A != B bernilai ",A != B) print("3. A > B bernilai ",A > B) print("4. A < B bernilai ",A < B) print("5. A >= B bernilai ",A >= B) pri...
from math import sqrt from aocframework import AoCFramework class Day(AoCFramework): test_cases = () def go(self): raw = self.raw_puzzle_input raw_split = self.linesplitted class Point(): x=0 y=0 vel_x=0 vel_y=0 def __init__...
#=================== #==collections #=================== #-----defaultdict from collections import defaultdict ice_cream = defaultdict(lambda: 'Vanilla') ice_cream['Sarah'] = 'Chunky Monkey' print(ice_cream['Sarah']) # Chunky Monkey print(ice_cream['Joe']) # Vanilla #===================== #==json file #===============...
# TODO Aula 04: https://www.youtube.com/watch?v=3ohzBxoFHAY&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc&index=5 class Employee: percent = 1.04 def __init__(self, name, lastname, sal): self.name = name self.lastname = lastname self.sal = sal self.email = '{}.{}@prop.com'.format(name...
import math import unittest def calcCircumfrence(r): return r*2*math.pi class TestMyCode(unittest.TestCase): def test_circumfrence(self): actual = calcCircumfrence(5) self.assertEqual(actual, 31.41592653589793) def test_calcCircumfrenceZero(self): actual = calcCircumfrence(0) ...
first_num = int (input ("first num >")) second_num = int (input ("second num >")) for number in range(first_num,second_num + 1): found_prime = True for i in range(2, number-1): if number % i == 0 : print ( number , "is not a prime number") found_prime = False bre...
P = list(map(int,input().split())) Q = list(map(int,input().split())) XEntre = True if (Q[0] >= P[0] and Q[0]<=P[2]) or ((Q[2] >= P[0] and Q[2]<=P[2])) else False YEntre = True if (Q[1] >= P[1] and Q[1]<=P[3]) or ((Q[3] >= P[1] and Q[3]<=P[3])) else False XEntre = XEntre or (True if (P[0] >= Q[0] and P[0]<=Q[2]) or ((P...
R1 = list(map(int,input().split())) R2 = list(map(int,input().split())) A1 = R1[0]*R1[1] A2 = R2[0]*R2[1] if A1>A2: R = "Primeiro" elif A1 == A2: R = "Empate" else: R = "Segundo" print(R)
#http://marathoncode.blogspot.com/2012/03/numeros-primos-iii.html #https://tiagomadeira.com/2007/06/crivo-de-eratostenes/ def crivo_erastostenes(N,crivo): crivo[1]=True for i in range(1,N+1): if not crivo[i]: j = 2 while i*j<=N: crivo[i*j] = True ...
V = [] #V[0] = Quantidade de posições #V[1] = Posição do Disco Voador #V[2] = Posição do Avião for i in range(3): V.append(int(input())) if V[0] == V[1]: Resp = V[2] elif V[0] == V[2]: Resp = V[1] else: Resp = V[0] print(Resp)
# 函数input()让用户可以输入一些信息,等待python存储后方便使用 message = input("Tell me something , and I will repeat it to you : ") print(message) # 在提示用户输入的是否可以提示用户输入的数据类型 name = input("Please enter your name : ") print("Hello ! " + name) # 用 += 创建多行字符串 prompt = "If you tell us who you are ,we can personalize the message you see ." prompt...
cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) # for语句的格式问题,注意缩进 # 条件测试 # python 是个根据条件测试的值为true还是false来决定是否执行if后面的语句 # python在考虑值是否相等时,会检查大小写,如何检查是否相等时不用考虑大小写得使用lower() ,upper()和title()方法 # 用"=="来询问是否相等,用"!="来询问是否不相等,如果回答...
import os from multiprocessing import Pool, Manager def copy_file(q, file_name, old_file_name, new_file_name): # print("copying from %s to %s: %s" % (old_file_name, new_file_name, file_name)) old_f = open(old_file_name + '/' + file_name, 'rb') content = old_f.read() old_f.close() new_f = open(new_...
#Opcion 1 para pedir un dato desde teclado en consola print("Ingresa un dato: ") n = input() #Las opciones de mostrar el dato obtenido desde teclado print("El dato ingresado fue: " + n) print("El dato ingresado fue:", n) print(f"El dato ingresado fue: {n}") #Opcion 2 para pedir un dato desde teclado en consola nombre...
#LAS TUPLAS PUEDEN SER USADAS PARA CUANDO NO QUIERA QUE SE MODIFIQUE ALGUN DATO ESPECIFICADO DESDE LA CREACION DEL MISMO ejemplo = ([40, 2], "Cincuenta", 23, "Doce") print(ejemplo[0]) ejemplo2 = ("solo un dato en la tupla",) #Si solo se quiere un elemento dentro de la tupla se debe poner una coma al final ...
def sumar(a, b): return a + b def restar(a, b): return a - b def multiplicar(a, b): return a * b; num1 = input("Num1: ") num2 = input("Num2: ") print("Opciones\n1.- Sumar\n2.- Restar\n3.- Multiplicar") operaciones = {'1': sumar, '2': restar, '3': multiplicar} seleccion = input('Escoge una: ') try:...
#EN JAVA SERIA indexOf() cadena = "Alvarado" #PIDE SI ES QUE SE ENCUENTRA ESA LETRA PARA DEVOLVER TRUE print('A' in cadena)#Devuelve un true o un false si esta letra se encuentra o no dentro de la anterior cadena #PIDE QUE ESTA LETRA NO SE ENCUENTRA PARA DEVOLVER TRUE print('o' not in cadena) #OPERADORES DE IDENTID...
from auxiliares import Auxiliares class TablaLL(Auxiliares): """Clase para la creacion y despliegue de la tabla LL(1) utilizando los metodos contenidos en la clase padre Auxiliares""" def __init__(self, archivo): """Se recibe el nombre del archivo y se pasa a la clase padres""" super(Tabla...
# 예외 (exception) -> 통상적으로 에러 # 예외 발생 -> 프로그램이 비정상적으로 처리됨 # 예외 처리 -> 발생된 예외를 처리하는 것이 아니고 정상종료 하도록 유도 # 예외 처리 방법 # 예외클래스(계층구조)를 제공해서 처리, (파이썬 문서(python.org) 에서 hierarchy 볼 수 있음 (library reference)) # try ~ except 문장 # finally 문 # 1. 예외 발생 n1 = 10 n2 = n1/5 #n2 = ...
# while n = 1 while n < 6 : print("hello") n += 1 print("end") print("#"+"-"*20+"#") # while 중첩 n = 1 while n < 4 : m = 1 while m < 3: print(str(n) + " " + str(m)) m += 1 n += 1 print("end") print("#"+"-"*20+"#")
def add_comp(num): if num <= 3: return 0 else: comp_num_sum = 0 for n in range(3, num+1): for m in range(2, n): if (n % m) == 0: comp_num_sum += n break return comp_num_sum list_to_test = [2, 3, 4, 5, ...
def piramide_for(): lenght = int(input('Hoe groot? ')) for i in range(lenght+1): print('*' * i) for i in range(lenght): print('*' * (lenght-i)) def piramide_while(): lenght = int(input('Hoe groot? ')) count = 1 while count < lenght: print('*' * count) count += 1...
def fibonaci(index): if index == 0: return 1 elif index == 1: return 1 else: return fibonaci(index-1) + fibonaci(index-2) print(fibonaci(40))
#!/usr/bin/env python #coding: utf-8 '''------------------------------------------------------------------------ > File Name: insertion_sort.py > Author: Hat_Cloud > Mail: jijianfeng529@gmail.com > Created Time: 2014-11-20 14:23 ------------------------------------------------------------------------'...
""" Displays an image pyramid """ from skimage import data from skimage.util import img_as_ubyte from skimage.color import rgb2gray from skimage.transform import pyramid_gaussian import napari import numpy as np # create pyramid from astronaut image astronaut = data.astronaut() base = np.tile(astronaut, (3, 3, 1)) p...
from gates import NAND, NOR, OR, AND, XOR, NOT # function to take input def take_input(): # take input as string, and split it on basis of white spaces return input('Enter two numbers: (Enter with empty string to exit)').split() # validate if there are 2 and only 2 elements entered def validate_count(nums):...
import re # 验证手机号是否正确 phone_pat = re.compile(r'^1[3-9]\d{9}$') name_pat = re.compile(r'^Simle[A-Z]{6}$') class Student(): def __init__(self): self.list1 = [] def menu(self): while True: user = int(input("北京格林豪泰酒店\n1.登记保存\n2.退出\n输入:")) if user == 1: ...
from rgfunc import * def printEmp(employees): n = 1 for name in employees: print n, ": ", name.fullname() n +=1 br() def new_emp(Employee,employees): br() print "Enter New Employees Details" employee = Employee(raw_input("Enter new employee's frist name: ")) employee.lastname = raw_input("Enter new emplo...
class Superhero(object): def __init__(self, name): self.powers = set() self.name = name self.gender = "" self.super_friends = set() self.evil_enemies = set() self.sidekicks = set() self.weaknesses = set() self.lair = "" self.biological_parents = tuple() de...
import numpy as np # Write a function that takes as input a list of numbers, and returns # the list of values given by the softmax function. def softmax(L): expL = np.exp(L) sum_expL = sum(expL) result = [] for i in expL: result.append(i * 1.0/sum_expL) print(result) return result ...
# -*- coding:UTF-8 -*- #! /usr/bin/python3 # 赋值运算符 a = 1 print("初值:",a) a += 3 print("加3:",a) a -= 9 print("减9:",a) a *= 8 print("乘8:",a) a /= 2 print("除2:",a) a //= 3 print("整除3:",a) a **= 4 print("4次方:",a) a %= 2 print("余2:",a)
# -*- coding:UTF-8 -*- #! /usr/bin/python3 list_a = list(range(5,10)) it = iter(list_a) print(next(it)) print(next(it)) for a in it: print(a,end=' ') del it import sys list_b = range(4) it = iter(list_b) while 1: try: print(next(it)) except StopIteration: sys.exit()
# -*- coding:UTF-8 -*- #! /usr/bin/python3 def dprint(str): print(str) # return def fun_1(x): x += 1 return x def fun_2(x): x = [x,[123,12,1]] print('函数内a:', x) return x def fun_3(x): x.append([1,2,3,4]) print('函数内a:',x) return b dprint("1") # return 存在与否尚无影响...
""" T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subTree of T1. A tree T2 is a subtree of T1 if there exists a node n in T1 such that the substree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical...
""" There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false """ def is...
""" Given two strings, write a method to decide if one is a permutation of the other. """ def ispermutation(a, b): i = 0 j = 0 for c in a: i += ord(c) for c in b: j += ord(c) return i == j and len(a) == len(b) if __name__ == '__main__': print("Is Permutation: aab, baa {0}".format(ispermutati...
def findMax(arr): do_pick = [0]*len(arr) do_not_pick = [0]*len(arr) do_pick[0] = arr[0] #do_pick = 2 for i in range(1, len(arr)): do_pick[i] = do_not_pick[i-1] + arr[i] do_not_pick[i] = max(do_not_pick[i-1], do_pick[i-1]) return do_pick[-1] if __name__ == '__main__': arr = [3,2,3,2] prin...
""" Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words EXAMPLE Input: Tact Coa Output True (permutat...
import RPi.GPIO as GPIO import time ''' This is the initialization for GPIO stuff ''' GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) ''' This is the setup for every motor on the robot ''' GPIO.setup(17, GPIO.OUT) motor_1 = GPIO.PWM(17, 50) motor_1.start(3) ''' This is the code for the robot ''' while True: d...
import nltk # 使用nltk工具对以下句子的词性标注 text = nltk.word_tokenize('the lawyer questioned the witness about the revolver') str = nltk.pos_tag(text) print("Answer 1 : ") print(str) print("\n------------------------------------------------\n") print("Answer 2 : ") # 测试答案 grammar = nltk.CFG.fromstring(""" S -> NP VP VP -> VBD NP...
def dict_to_arr(x): import numpy as np if isinstance(next(iter(x)), tuple): n = max([i for (i, j) in x.keys()]) + 1 m = max([j for (i, j) in x.keys()]) + 1 y = np.zeros((n, m), dtype=int) for i in range(n): for j in range(m): y[i, j] = x.get((i...
class Solution: def findMin(self, nums: List[int]) -> int: return self.binarySearch(nums, 0, len(nums) - 1) def binarySearch(self, nums, a, b): if nums[a] <= nums[b]: return nums[a] mid = (a + b) // 2 if a < mid < b and nums[mid] < nums[mid - 1]...
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ sign = 1 if x < 0: sign = -1 x = abs(x) rev = int(str(x)[::-1]) if rev > 2**31 - 1 or rev*sign < -2**31: return 0 ...
class Solution: def toLowerCase(self, string): """ :type str: str :rtype: str """ ret = [] for c in string: cascii = ord(c) ret.append(chr(cascii + 32) if 65 <= cascii <= 95 else c) return ''.join(ret) # Python Easy Way # cla...
for x in list(range(0,100)): output = "" if(x % 3 == 0): output += 'Fizz' if(x % 5 == 0): output += 'Buzz' if(output == ""): output += str(x) print(output)
def merge(A,B): (C,m,n) = ([], len(A), len(B)) (i,j) = (0,0) while i+j < m+n: if i == m: C.append(B[j]) j = j + 1 elif j == n: C.append(A[i]) i = i + 1 elif A[i] <= B[j]: C.append(A[i]) i = i + 1 elif A[i] > B[j]: C.append(B[j]) j = j + 1 return(C) def mergesort(A,left,right): prin...
""" A command-line controlled coffee maker. """ import sys import load_recipes as rec """ Implement the coffee maker's commands. Interact with the user via stdin and print to stdout. Requirements: - use functions - use __main__ code block - access and modify dicts and/or lists - use at least once som...
class introduce: def __init__(self, name, sex, height, weight): self.name = name self.sex = sex self.height = height self.weight = weight def info(self): print(f'이름:{self.name}') print(f'성별:{self.sex}') print(f'키:{self.height}') print(f'몸무게:{self....
# Given a string,write a function to check if it is a permutation of a palindrome # Example : # tact coa # Output : true(permutations : 'taco cat','atco cta' etc) class PalindromePerm: def palindromePerm(self,str): # Join string together # str1 = str.replace(" ","") str1 = "".join(str.split()) print(str1) ...
# Deep copy print('Exemplo de DEEP COPY') lista = [ 1, 2, 3 ] nova = lista.copy() nova.append(4) print(lista) print(nova) # COPY print('Exemplo de COPY') lista2 = [ 3, 2, 1 ] nova2 = lista2 nova2.append(0) print(lista2) print(nova2)
import pygame grid = [[0 for x in range(3)] for y in range(3)] #Esta sentencia crea las 3 tuplas for row in grid: print(row) print("\n") grid[0][2]="X" grid[0][0]="X" grid[0][1]="X" for item in grid: print(item) print("\n") grid2 = [["X" for x in range(3)] for y in range(3)] #Esta...
import requests from bs4 import BeautifulSoup import csv # sets up for scrape scrape_soup = requests.get('https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population') info = BeautifulSoup(scrape_soup.text, 'html.parser') #Finds the table containing all the information about Amecican cities table_info = ...
#Autor: Jose Heinz Moller Santos #Descripción: Este programa es para calcular el IMC de las personas. #calcular IMC: def calcularElIMC(peso,estatura): indiceMasa=peso/(estatura**2) return indiceMasa def main(): peso=float(input("Introduzca su peso en kg:")) estatura=float(input("Introduzca su estatura en metros:"...
number = int(input("пожалуйста,введите целое число число\n")) max = 0 while number > 0: box = number%10 number = number//10 if max < box: max = box print(f'наибольшая цифра в числе - {max}')
class counter: c = 0 def __init__(self,n): int self.c = n cc = counter(2) : counter print cc.c
"""============================================================================= Ex3: Hypothesis testing Câu 3: P-test và T-test Cho 2 bộ dữ liệu phụ thuộc nhau như sau: np.random.seed(11) before = stats.norm.rvs(scale=30, loc=250, size=100) after = before + stats.norm.r...
# -*- coding: utf-8 -*- """============================================================================= Ex5: SPARSE MATRIX Câu 3: a) Tạo ma trận thưa thớt ngẫu nhiên S(5,5) với mật độ density = 0.25 b) Chuyển S thành full matrix A c) Tạo ma trận thưa thớt ngẫu nhiên S1(5,5) với mật độ densi...
vowels = 'aeiou' vowels += vowels.upper() print(vowels) for _ in range(5): string = input('Enter a string: ') for v in vowels: string = string.replace(v, '') print(string)
# range object iteration total = 0 for i in range(0, 100): print(i) total += i print('total:', total) # list object iteration fruits = ['apple', 'banana', 'grapes', 'orange'] for f in fruits: print(f) # double variable iteration fruits = ['apple', 'banana', 'grapes', 'orange'] for index, fruit in enumer...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Brennan # # Created: 09/09/2015 # Copyright: (c) Brennan 2015 # Licence: <your licence> #------------------------------------------------------------------------------- def b...
#------------------------------------------------------------------------------- # Name: Virtual Pet # Purpose: # # Author: Brennan # # Created: 08/09/2015 # Copyright: (c) Brennan 2015 # Licence: <your licence> #------------------------------------------------------------------------------- clas...
#------------------------------------------------------------------------------- # Name: Blackjack # Purpose: # # Author: cnys # # Created: 09/09/2015 # Copyright: (c) cnys 2015 # Licence: <your licence> #------------------------------------------------------------------------------- from Deck imp...
print("SUMA DE IMPARES EN UN RANGO DADO") def rango1(): #funcion para el rango si en caso el usuario elije solo uno d1 = int(input("Inicio de rango: ")) d2 = int(input("Fin de rango: ")) a = 0 for i in range(d1,d2+1): if i%2 != 0: #este if verifica si el numero en i en el rango, es par o impar, osea di...
# *** 5 || 15 dono se divisiable hai ya nahi *** # num=int(input("enter a number")) # if num%5==0 and num%15==0: # print("number is divisible by 5 and 15") # else: # print(" number is not divisible by 5 and 15")