text
stringlengths
37
1.41M
# Faça um programa que pede para o usuário digitar uma palavra e cria uma nova string igual, porém com espaço entre cada letra, depois imprima a nova string: # Exemplo: se o usuário digitar "python" o programa deve imprimir "p y t h o n " import re # string de entrada string = input('Digite uma palavra:') # quebra ...
# Super Desafio! - Repita o exercício anterior usando recursão, ou seja, # uma função que chame ela mesma, lembrando que 3! = 3*2!, que 2! = 2*1!, que 1! = 1*0! e que 0! = 1. n = int(input('Digite um número para que seu fatorial seja calculado:\n')) def fatorial(n): if n < 2: return 1 else: r...
# Crie uma classe ControleRemoto cujo atributo é televisão # (isso é, recebe um objeto da classe do exercício 4). # Crie métodos para aumentar/diminuir volume, trocar o canal # e sintonizar um novo canal, que adiciona um novo canal à lista # de canais (somente se esse canal não estiver nessa lista). class Televiso...
# Faça uma função que sorteia 10 números aleatórios entre 0 e 100 e retorna o maior entre eles. from random import randint lista = [] count = 0 while count < 11: num = randint(0,100) lista.append(num) count += 1 def aleatorio(lista): maximo = max(lista) print(num) aleatorio(lista)
""" [Final Quiz] Date: 2021-08-23 Design at least 3 major features for a text editor Do a quick research on the Internet if you need some ideas or references Save your project as 'mytexteditor' Share your project to github Post your URL of your remote git repository to SLACK Due date: 2021-08-31 Hints: Self-study on fo...
""" Sandpile arithmetics. The Sandpile class is used to construct a sandpile grid. S is a virtual set that elements can be checked to be contained in. """ from itertools import zip_longest __all__ = ['Sandpile', 'S'] class Sandpile(object): """A sandpile grid""" TL = '┏' V = '┃' TR = '┓' BL = '┗...
"""Find the most frequent num(s) in nums. Return the set of nums that are the mode:: >>> mode([1]) == {1} True >>> mode([1, 2, 2, 2]) == {2} True If there is a tie, return all:: >>> mode([1, 1, 2, 2]) == {1, 2} True """ def mode(nums): """Find the most frequent num(s) in nums.""" ...
def natural_number(data): data=data[::-1] Sum=0 for i in range(len(data)): Sum+=int(data[i])*(2**i) return Sum def signed_integer(data): n=data[0] data=data[1::][::-1] Sum=0 for i in range(len(data)): Sum+=int(data[i])*(2**i) if n=="1": return Sum-128 ...
from functools import reduce left = 1 right = 22 def checker (count, num): for c in str(num): if (int(c) == 0 or (num % int(c) != 0)): return count count.append(num) return count s = reduce(checker, [i for i in range(left, right + 1)], []) print (s)
#Programa23: Dado el promedio obtenido en 5to de secundaria import os #Declaraciones alumno=" " prom=0.0 #Input vis os alumno=str(os.sys.argv[1]) prom=int(os.sys.argv[2]) #Processing #Si su promedio es mayor o igual a 17 (Ganó una beca) if(prom>=17): print(alumno,"SE GANO UNA BECA") #Si su promedio es menor a 17...
# Programa 11 import os #Declaracion nombre,edad=" ",0 #INPUT nombre=str(os.sys.argv[1]) edad=int(os.sys.argv[2]) #PROCESSING #Si el usuario es menor de edad no podra entrar al cine #mostrar "¡Hasta la proxima!" menor_edad=(edad < 18) if (edad < 18): print(nombre , "¡Hasta la proxima!") else: print(nombre,...
# Programa 17 import os #Declaracion nombre,cantidad="",0 #INPUT nombre=str(os.sys.argv[1]) cantidad=int(os.sys.argv[2]) #PROCESSING #Si la compra es mayor de 3 panetones #mostrar "¡Ganaste una tableta de chocolate!" premio=( cantidad > 3 ) if (cantidad > 3): print(nombre, "¡Ganaste una tableta de chocolate!"...
#Programa7:Dado un número import os #Declaración num=0 #Input vis os num=int(os.sys.argv[1]) #Processing #mostrar: El número es impar if (num%2 != 0): print("El número es impar") #fin_if
# Programa 03 import os #Declaracion alumno,nota=" ",0 #INPUT alumno=str(os.sys.argv[1]) nota=int(os.sys.argv[2]) #PROCESSING #Si la nota del alumno es mayor a 14 #mostrar "¡Estas aprobado!" aprobado=(nota >= 14) if (nota >= 14): print(alumno , "¡Estas aprobado!")
def Menu(): ##菜单主界面 print('*' * 22) print("* 查看毕业生列表输入: 1 *") print("* 添加毕业生信息输入: 2 *") print("* 修改毕业生信息输入: 3 *") print("* 删除毕业生信息输入: 4 *") print("* 退出系统请输入 0 *") print('*' * 22) def CheckIdisRight(StudentList, id): ##检查学号是否在列表中 for i in range(0, len(StudentList)): if ((id ...
arr = [1,12,2, 11, 13, 5, 6,18,4,9,-5,3,11] def insertionSort(arr): #从要排序的列表第二个元素开始比较 for i in range(1,len(arr)): j = i #从大到小比较,直到比较到第一个元素 while j > 0: if arr[j] < arr[j-1]: arr[j-1],arr[j] = arr[j],arr[j-1] j -= 1 return arr print(insertionSo...
#!/usr/bin/env python3 class Stack: def __init__(self): self.list = [] def isEmpty(self): return True if len(self.list) == 0 else False def size(self): return len(self.list) def pop(self): return self.list.pop() def push(self,data): self.list.append(data) ...
from Tkinter import * import random import math # Graphics Commands def random_color(): '''Returns a random color in the hexadecimal format.''' options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] options.extend(['a', 'b', 'c', 'd', 'e', 'f']) x = 0 color = '#' while (x < 6): color += random.choice(op...
# Définition des variables import os from random import randrange from math import ceil argent = 100 roulette = randrange(50) # Proposer à l'utilisateur de miser sur un numéro entre 0 et 49 (pairs = noir, impairs = rouge) # Si c'est gagné, le joueur gagne 3* sa mise # Sinon, on vérifie si la couleur est bonne...
class Cat: def __init__(self, name, preferred_food, meal_time): self.name = name self.preferred_food = preferred_food self.meal_time = meal_time def __str__(self): return "{}, {} and {}".format(self.name, self.preferred_food, self.meal_time) def eats_at(self): i...
import unittest class TestDemoExecution(unittest.TestCase): def test_demo_result_true(self): """ This is an example of how to write a boolean unit test Ex: 4==4 -> True """ some_function = lambda x : x==4 self.assertTrue(some_function(4)) def test_demo_results_equals(self): """ This is an example o...
#secondlargest def secondlargest(n,data): sh,fh=data[0],data[0] for i in data[1:]: if i>fh: sh=fh fh=i if i>sh and i<fh: sh=i return sh n=int(input()) data=list(map(int,input().split())) print(secondlargest(n,data)) '''...
#second largest element def secondlargest(n,data): sh,lh=data[0],data[0] for i in data[1:]: if data[i]>fh: sh=fh fh=data[i] if data[i]>sh and data[i]fh: sh=i return sh n=int(input()) data=list(map(int,input().split())) print(second...
''' def findmin(n,data): s,c=data[0],0 for i in data: if s==i: c+=1 if s>i: s=i c=1 ind=[s,c] for i in range(n): if s==data[i]: ind.append(i) return ind n=int(input()) data=list(map(int,input().split())) minva...
def linear_search(data,key): count=0 for i in range(0,len(data)): count+=1 if data[i]==key: print("Element found") return count else: print("Not found") return count def binary_search(data,key): l=0 h=len(data)-1 count=0 w...
from random import randint from flask import Flask, request app = Flask(__name__) rules = """ <h3>Rules: Pick one number and I will try to guess it in 10 tries.</h3> """ @app.route('/') def guess_number(): min_num, max_num = 1, 1000 answer = 0 tried = 1 form = """ <p> <form> ...
# -*- coding: utf-8 -*- ''' P3 Assignment Derek Nguyen Created: 2019-02-11 Modified: 2019-02-11 Due: 2019-02-11 ''' # %% codecell #P3 import numpy as np import scipy.integrate as integrate import matplotlib # used to create interactive plots in the Hydrogen package of the Atom IDE matplotlib.use('Qt5A...
# https://leetcode.com/problems/longest-palindromic-substring/ """ Longest Palindromic Substring Medium Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Example 3: Input: s =...
# https://leetcode.com/problems/two-sum/ """ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. ...
# https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/python """ The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) # should be 6: [4, -1, 2, 1] Easy case is when the list is made up of...
# https://www.codewars.com/kata/56882731514ec3ec3d000009/train/python """ Take a look at wiki description of Connect Four game: Wiki Connect Four The grid is 6 row by 7 columns, those being named from A to G. You will receive a list of strings showing the order of the pieces which dropped in columns: pieces_posit...
# https://www.codewars.com/kata/51fda2d95d6efda45e00004e/train/python """ Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar to the one Codewars uses. Business Rules: A user starts at rank -8 and can progress all the way to 8. There is no ...
import numpy as np class SequentialData(object): def __init__(self, data_size, num_classes, batch_size, num_steps): """Set the parameters for generating the data using a predefined rule """ self.batch_size = batch_size self.data_size = data_size self.num_classes = num_classe...
""" 用Spyder運行,命令行參數在 Run-Configuration per file-Command line options 設置 e.g. do.txt doc.txt """ import sys import os import re def get_file_name(c): res = [] prefix = input_filename.split(c)[0] dirPath = os.getcwd() # 獲取當前工作路徑 for root, dirs, files in os.walk(dirPath): for file in file...
a = int(input()) total = 1 for i in range(1,a+1): total *= i print(total)
# ------------- Machine Learning - Topic 2: Logistic Regression # You will need to complete the following functions # in this exercise: # sigmoid # costFunction # predict # plotData # plotDecisionBoundary ## Initialization import numpy as np from scipy.optimize import fmin, fmin_bfgs import os, sy...
import numpy as np from matplotlib import pyplot as plt def sigmoid(x): return 1.0 / (1.0 + np.exp(-x)) def main(): x = np.arange(-10, 10, 0.2) # -10-10的数组,间隔为0.2数值 # 非调库实现方法 y = [sigmoid(i) for i in x] plt.grid(True) plt.plot(x, y) plt.show() if __name__ == '__main__': main()
#print ("Input the number of characters in line: ") w = int(input("Input the number of characters in line: ")) my_string_list = ['Hello I am Phoebe!', 'I know you, you feed me.', 'You are Helen and Anton.'] def split_lines_into_words(line_list): new_words_list = [] for ...
s = 'betty bought a bit of butter but the butter was bitter' wordlist = s.split() wordfreq = [wordlist.count(w) for w in wordlist] # TODO: Sort the occurences in descending order (alphabetically in case of ties) d = dict(zip(wordlist,wordfreq)) aux = [(d[key],key) for key in d] from operator import itemgetter, attrgett...
def coin(N, K): if K > N and (K >= 1 and K <= 500): a = (N**2 - N)/2 if K == a: return 'Y' else: return 'N' else: return 'N' N = 0 K = 5 res = coin(N, K) print(res)
class Node: def __init__(self, obj, next): self.object=obj self.next=next class LinkedList: def __init__(self, obj=None, next=None): self.node = None def add(self, obj): if self.node == None: self.node = Node(obj,None) else: p=self.node.next ...
""" Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. For example,"egg" and "add" are isomorphic, "foo" and "bar" are not. """ def isIsomorphic(word1, word2): if len(word1) != len(word2): return False d={} for ...
import random def quickSort(s, e , _list): if s > e: return print("{!r}".format( _list), end = " ") pp = partition_origin(s, e, _list) print("{}: {} PP:{} {!r}".format(s, e ,pp, _list)) quickSort(s, pp - 1 , _list) quickSort(pp +1, e, _list) # This does not find right index for pivot...
import threading, time class BankAccount: def __init__(self): self.bal = 0 self.lock = threading.Lock() def deposit(self, amt): with self.lock: #DEADLOCK #self.lock.acquire() balance = self.bal time.sleep(2) self.bal = balance ...
""" Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. """ def binarySearch(nums, target): ...
def consecutive(num): count = 0 L = 1 while (L * (L + 1) < 2 * num): a = (num - (L * (L + 1)) / 2) / (L + 1) print("{} {}".format(a, int(a))) if (a - int(a) == 0.0): count += 1 L += 1 print(count) return count consecutive(15)
import time, timeit from datetime import timedelta # O(n) def fibonacci(n): init_1 = 1 init_2 = 1 if n < 3: return init_1 for i in range (2, n): temp = init_2 init_2 = init_1 + init_2 init_1 = temp return init_2 # O(2^n) def fibonacci_rec(n): if n == 1...
from queue import Queue ''' This is shortest path when its edges has same factor ''' class Graph: def __init__(self, n): self.g = {} self.n = n for i in range(1, n + 1): nodes = self.g.get(i, set()) self.g[i] = nodes def connect(self, s, e): self.g[s].ad...
class ExampleIterator: def __init__(self, sequence): self.index = 0 self.data=sorted(sequence, reverse=True) def __iter__(self): self.index = 0 return self def __next__(self): if self.index >= len(self.data): raise StopIteration() result = self.da...
from LinkedList import LinkedList def remove(ll, k): h1 = ll.head if h1 == None: return p = h1 pp = p.next f = h1 while f != None and k != 0: f = f.next k -= 1 if f == None: ll.head = ll.head.next return while f.next != None: f = f.next...
def maxSubArray(nums): n = len(nums) memo = [0] * n memo[0] = nums[0] submax = nums[0] for i in range(1, n): t_max = max(memo[i - 1] + nums[i], nums[i]) if t_max > submax: submax = t_max memo[i] = submax else: if t_max < 0: ...
from LinkedList import LinkedList """ def reverse(ll): h1 = ll.head if h1 == None or h1.next == None: return else: p = h1 pp = h1.next p.next = None while pp != None: next_pp = pp.next pp.next = p p = pp pp = next_pp ll.head = p """ ...
""" Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. """ ## This should be taken as a cautious aproach #Does this ha...
def numOf1_bits(num): n = 0 for i in range(32): bit = num & 0x01 << i if bit == 1: n+=1 print(n) inputs = [5,6,7,8] for input in inputs: numOf1_bits(input)
""" Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. Note: A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells ne...
#memory bound implimataion def remove_deuplicate(nums): single, i = 0, 1 while i < len(nums): if not isDuplicate(nums, single, nums[i]): single += 1 nums[single], nums[i] = nums[i], nums[single] i += 1 return nums, single def isDuplicate(nums, k, target): i = 0...
""" Insert a cha remove a cha replace a cha pale, Ple => true pales,pale => True pale, bale => True pale, bake => False write a function to check if they are one edit (or zero) away Note 1: Only one character difference Solution 1 ( Logical Error: because the order matters) : using dictionary. if there a...
def readchars(filename): with open(filename, mode='rt') as f: for four in f: print(four, end="") def readchars1(filename): with open(filename, mode='rt') as f: print(f.read()) def readchars2(filename): with open(filename, mode='rt') as f: lines = f.readlines() p...
#longest palindromic sequence # Complete the longestPalindrome function below. #https://www.youtube.com/watch?v=_nCsPn7_OgI def longestPalindrome(n, s): L = [[0 for x in range(n)] for x in range(n)] for i in range(n): L[i][i] = 1 for cl in range(2, n + 1): for i in range(n - cl + 1): ...
""" Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. """ def maxProduct(nums): _max = nums[0] _can = 1 for i in range(1, len(nums)): if _...
""" Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that only one letter can be changed at a time and each intermediate word must exist in the dictionary. For example, given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"] ...
""" if an element in an MxN matrix is 0, its entire row and column are set to 0 """ def MxN_zero_matrix(mxn): c_zeros, l_zeros = set(), set() for i in range(len(mxn)): for j in range(len(mxn[0])): if mxn[i][j] == 0: c_zeros.add(j) l_zeros.add(i) for i i...
def get_summ(one,two,delimiter='and'): return(str(one)+delimiter+str(two)) a= get_summ('Learn','python') print(a.upper())
########### Set up simple RSA-Environment: p = 11 # prime q = 13 # prime m = 42 # message ############################################################################### ########### Calculate simple RSA-Environment: N = p * q phi = (p-1) * (q-1) e = 23 # Coprime of phi -> ggt(e, phi) = 1 # TODO: "generate" by it...
import requests api_key = '177590d4ced1c92728f2563be3fa6f12' # function which makes a call to the API and returns the status code it receives. All data is hard coded so the return status # should always be 200 def api_test(): try: test_request = 'http://api.openweathermap.org/data/2.5/weather?q=san%20die...
Number1=int(input("The First Number is : ")) Number2=int(input("The Second Number is : ")) print(Number1,"+",Number2,"=",Number1+Number2) print(Number1,"-",Number2,"=",Number1-Number2) print(Number1,"*",Number2,"=",Number1*Number2) print(Number1,"/",Number2,"=",int(Number1/Number2))
""" Platform: CodeSignal You need to sum up a bunch of fractions that have different denominators. In order to do this, you need to find the least common denominator of all the fractions. As a professional programmer, you know that the least common denominator is in fact their LCM. For the given list of denominators, ...
''' Platform: CodeSignal Here's how permutation cipher works: the key to it consists of all the letters of the alphabet written up in some order. All occurrences of letter 'a' in the encrypted text are substituted with the first letter of the key, all occurrences of letter 'b' are replaced with the second letter from ...
""" Platform: CodeSignal You don't have time to investigate the problem, so you need to implement a function that will fix the given array for you. Given result, return an array of the same length, where the ith element is equal to the ith element of result with the last digit dropped. """ def fixResult(result): ...
import numpy ''' Platform: HackerRank You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array. ''' a=numpy.array(list(map(int,input().split()))) print(numpy.reshape(a,(3,3)))
#lass SortingRobot: # def __init__(self, l): # """ # SortingRobot takes a list and sorts it. # """ # self._list = l # self._item = None # self._position = 0 # self._light = "OFF" # self._time = 0 class SortingRobot: def __init__(self, l): """ Sort...
print("this is an if elif and else code") day=input("choose a day") if day=="monday": print("i do not have football today") elif day=="tuesday": print("i have football today") elif day=="wednesday": print("i do not have football today") elif day=="thursday": print("i do not have football today") elif day=="f...
import sqlite3 import csv # Open csv file readfile=open('20200318_account_snapshot.csv','r', newline='') readfile=csv.reader(readfile, delimiter=',') conn = sqlite3.connect('accounts.db') cur = conn.cursor() cur.execute('CREATE TABLE EOS (id INTEGER PRIMARY KEY AUTOINCREMENT, Account TEXT, Balance FLOAT)') conn.comm...
fname = input("Enter file name: ") try: fh = open(fname) except FileNotFoundError: print("File not found") quit() text = [] for line in fh: add_text = line.split() for word in add_text: # print("Add ", word, "?") # if word in text: # print("Nope, not adding: ", word) ...
import re name = input("Enter file:") # get file name from user if len(name) < 1: # give a default if no file is given name = "sample_text.txt" handle = open(name) sum = 0 for line in handle: line = line.rstrip() # print('line', line) x = re.findall('[0-9]+', line) # print('x:', x) for xs in ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Some documentation""" class Board: def __init__(self, w, h): self.width = w self.height = h self.grid = [[False] * w for i in range(h)] def __iter__(self): self.n = 0 return self def __next__(self): if sel...
#tuple tuple = ('Gerardo', 'Manrique', 19, 25, 'Nose') #print("Todos los elementos de lista:", lista) #print("Todos los elementos del tuple son:", tuple) lista = ['Armando', 'Ruelas', 18, 'Mexicana', 'Sinaloa', 'Los Mochis'] nombre = lista[0] apellido = lista[1] edad = str(lista[2]) nacionalidad = lista[3] estado = ...
#Variables space = "---------------------" string = "Hola soy un String" print(string) string = "Ahora soy otro valor" print(string) print(space) a, b, c = "Hola", "Soy", "Armando" print("El valor de las variables son:", a, b, c) del a, b, c #print("El valor actual de las variables son:", a, b, c) #conversion de var...
from re import compile, X class Robot(): """Simulate a robot moving on a 5x5 grid""" def __init__(self): self._x = 0 self._y = 0 self._f = None def init_place(self): """if the first command to the robot is a PLACE command""" if self._f == None: retu...
# -*- coding: utf-8 -*- """ Created on Mon Dec 2 16:31:45 2019 @author: Olli --- Day 1: The Tyranny of the Rocket Equation --- --- Part One --- Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his war...
# Make a function that takes a sequence (like a list, string, or tuple) and a number n and returns # the last n elements from the given sequence, as a list. # # Bonus 1 # # As a bonus, make your function return an empty list for negative values of n. # # Bonus 2 # # As a second bonus, make sure your function works with...
class Solution: def isValid(self, s: str) -> bool: # result = [] # dicts = {'(': ')', '{': '}', '[': ']'} # if len(s) == 0: # return True # else: # for paranthesis in s: # print(paranthesis) # try: # if dicts...
from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: i = 0 while i < len(nums): if nums[i] < target: i = i + 1 elif nums[i] == target: return i else: break r...
import math import os import random import re import sys from itertools import combinations # Complete the countTriplets function below. def countTriplets(arr, r): # SLOW SOLUTION #1 # for index, number in enumerate(arr): # for number in range(index, len(arr) - 1): # triplets.ap...
def is_pangram(sentence): s=set(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t","u","v","w","x","y","z"]) sentence=sentence.lower() for i in range(len(sentence)): if sentence[i] in s: s.remove(sentence[i]) return len(s)==0 ...
# Python Program to replace all occurences of 'a' with $ in a String name = input("Enter a name:") print("Your entered name is:",name) name = name.replace('a','$') print(name)
# # Project Euler Solution # Problem ID: 2 # # Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not exceed four...
#!/usr/bin/env python # coding: utf-8 # In[22]: import numpy as np import scipy as sp import scipy.stats import matplotlib.pyplot as plt text_file = open("/Users/rishika/Desktop/anomaly_detection.txt", "r+") lines = text_file.readlines() new_file=[] text_file.close() for item in lines: new_file.append(item.stri...
# Developer: Wellington # Data: 18/09/2021 # Description: Scrip developed to simulate a calculator by using methods and functions # it's a part of course Python Fundamentos at DSA # Create a calculator method def operations(parameter): # Here we have some simple function which will doing the math operat...
# -*- coding: utf8 -*- class MyClass: def __new__(cls, *args, **kwargs): print("inside MyClass.__new__()") return super(MyClass, cls).__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): print("inside MyClass.__init__()") def __call__(self, *args, **kwargs): ...
""" Single Responsibility Principle (Princípio da responsabilidade única) 'Uma classe deve ter apenas um motivo para mudar' Uma classe deve ter apenas um trabalho, Se uma classe tem mais de uma responsabilidade, vira acoplada. Uma mudança em uma responsabilidade resulta na modificação de outra responsabilidade. """ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @author:JaNG @email:136772@163.com ''' class Animal: def __init__(self,name): self.name = name hobbie = 'meat' @classmethod #类方法 只能通过 Animal.talk()不能访问实例变量 def talk(self): print('{} is talking ...'.format(self.hobbie)) @stati...
""" desc: Starter code for simple linear regression example using tf.data 线性拟合略显智障,我们在这里找到曲线拟合效果, Y = ax^2 + bx + c author: LongYinZ date: 2018.1.30 """ import os import time import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import utils from advanced_util import huber_loss os.e...
#Write the program to print vowels and consonant letters from "gnulinux" #Vowels variables Vowels=[ #defining empty lists vowles1 = [] conatants = [] #giving input string11 = "gnulinux" #sepearating constants from vowels for i in string11: if i in Vowels: vowles1.append(i) else: constants.append(i) #Printing resu...
def generate_powerset(input_set): ''' Enumerate all subsets of a given string input_set (list): an arbitrary list. Assume that it does not contain any duplicate elements. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of lists containing ...
import random import math import numpy as np import matplotlib.pyplot as plt def monte_method(N):#モンテカルロ法関数 point = 0 for i in range(N): x = random.random() y = random.random() if x*x+y*y < 1.0: point += 1 pi = 4.0 * point / N#円周率の近似値の計算 return pi count=0#i回目計算のためのカ...
# -*- coding: utf-8 -*- import Sort #Sort.testAlgorithms([10, 20, 30, 40, 50, 60]) test = [3,2,3,4,45,66,1,22,42] #Sort.Bubble(test) Sort.QuickSort(test, 0, len(test) - 1, rand = True) print(test)
class node: def __init__(self, data): self.data=data; def left_child(self,lc): assert lc.data<self.data self.left=lc def right_child(seld,rc): assert rc.data>self.data self.right=rc arr=eval(input("Enter BST data: ")) root=node(arr[0]) def add_node(n,e): if e<...
aa=input("Enter Your Name : ") print("Hello", aa, "Welcome to Ankur's Calculator Programme") a=int(input("Enter Your First Number : ")) b=int(input("Enter Your Secod Number : ")) c=int(input('''Press (1 for Addition) (2 for Subtraction) (3 for Multiplication) (4 for Division) For your preffered result\n''')) if...
"""This example shows how to create a scatter plot using the `shell` package. """ # Major library imports from numpy import linspace, random, pi # Enthought library imports from chaco.shell import plot, hold, title, show # Create some data x = linspace(-2*pi, 2*pi, 100) y1 = random.random(100) y2 = random.random(10...