text
stringlengths
37
1.41M
# Bottle deposit small_bottle = 0.10 big_bottle = 0.25 small = int(input('how many less then 1 liter bottles do you want to return?\n')) big = int(input('how many more then 1 liter bottles do you want to return?\n')) refund = small * small_bottle + big * big_bottle print('your bottle refund is %.2f$' % re...
# Volume of a Cylinder import math radius = float(input('enter the radius of the cylinder: ')) height = float(input('enter the height of the cylinder: ')) volume = math.pi * radius**2 *height print('the volume of the cylinder is %.1f cubic cm' % volume)
# Median of Three Values # @param a the first value # @param b the second value # @param c the third value # @return the median of values a,b and c def median_of_three(a, b, c): if a > b > c or c > b > a: return b elif b > c > a or a > c > b: return c else: return a def main(): ...
import random def jogada(escolhaj,escolhapc): placarj = 0 placarc = 0 if escolhaj == "pedra" and escolhapc == "papel": print(nome,escolhaj,"X",escolhapc,"Computador") print("Você perdeu!") placarc = placarc + 1 return placarc elif escolhaj == ...
def reverse(sentence): answer = '' temp = '' for char in sentence: if char != ' ': temp += char else: answer = temp + ' ' + answer temp = '' answer = temp + ' ' + answer print(answer) sentence = 'This is a string to try' reverse(sentence)
from collections import Counter '''lista = [1, 1, 1, 2, 2, 3, 3, 3, 3, 1, 2, 3, 4, 5, 5, 4] resultado = Counter(lista) print(type(resultado)) print(resultado) # elemento: ocorrências ''' # print(Counter('André Lubawski')) texto = """ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem...
# os sets seguem as regras dos conjuntos matemáticos ''' con = set({1,1,1,2,14,23,0,4}) print(con) con2 = {1,1,2} print(con2) lista = [1, 1, 1, 2, 3] con3 = set(lista) print(con3) # obs: assim como nas outras coleções, posso usar vários tipos de dados num mesmo set con3.remove(1) # 1 é o valor, não o índice, afinal,...
class Local: def __init__(self, coordenada_x, coordenada_y): self.coordenada_x = coordenada_x self.coordenada_y = coordenada_y self.frequentadores = list() def adicionar_frequentador(self, frequentador): if frequentador not in self.frequentadores: self.frequentadores...
import json, requests, math # C:\Users\CowsillB\PycharmProjects\coinAnalysis\venv\Scripts # pip3 install requests url = 'https://api.coinmarketcap.com/v1/ticker/' # List containing coins of interest coins = ['bitcoin','cardano','ripple'] # Alert if price has risen or fallen beyond threshold def alert(metric): t...
'''ATM Simulator Written by Wyatt Smith 04/20/2020''' balance = 1000 def withdrawl(amount): global balance amount = float(input("How much to withdrawl? ")) while amount < 0 or amount > (balance - 5): if amount < 0: amount = float(input("You cannot withdrawl a negative amount. Please enter a different ...
import numpy as np def partition(array, start, end): pivot = array[end] i = start - 1 for j in range(start, end): if array[j] <= pivot: i += 1 array[i], array[j] = array[j], array[i] array[i + 1], array[end] = array[end], array[i + 1] return i + 1 def quick_sort(...
import numpy as np class PriorityQueue: def __init__(self, capacity): self.capacity = capacity self.elements_lenght = 0 self.values = np.empty(self.capacity, dtype=int) def __empty(self): return self.elements_lenght == 0 def __full(self): return self.elements_...
def separate(str): return str.replace('{', '').replace('}', '').split(',') def loadData(): lines = '' with open("automata.txt", "r")as f: x = f.readlines() for line in x: lines = lines + line content = lines.split(" ") states = separate(content[0]) alphabet = separa...
""" To test the Trie data structure and its methods """ from algorithm.trie import TrieNode, Trie class TestTrieNode: """ Test functionalities of TrieNode """ @staticmethod def test_trienode_basics(): """ Test whether node is generated as required """ node = TrieNode...
""" Module implements Trie Data structure with methods required """ class TrieNode: """ Trie Node data structure Stores: array of 26: children Trie Nodes bool : whether current node is End of the word """ def __init__(self): self.children = [None]*26 self.is_end_of_the_w...
#importamos las librerias de la siguiente manera import datetime #en este caso importamos absolutamente todo de "datetime" from dateutil.relativedelta import relativedelta #nos sirve para jugar con las fechas #me muestra la fecha del dia de hoy, toma la fecha del pc a = datetime.date.today() #muestra el momento exact...
# -*- coding: utf-8 -*- def main(): option = int(raw_input("ingresa la opcción que deseas ejecutar.\n1. deletrear una palabra.\n2. decir mierda x cantidad de veces.\n3.Ver como se cancela una funcion con break\n")) if option == 1: word = raw_input("ingresa la palabra que quieres deletrear\n") print_letter_by_let...
import os from graph import * def task3(): os.system('cls') size1 = int(input("Введите количество вершин графа 1:")) size2 = int(input("Введите количество вершин графа 2:")) os.system('cls') print("Выберети действие:\n" "1)Объединение\n" "2)Пересечение\n" "3)Кольцева...
def insertSort(nums): for i in range(1,len(nums)): j=i-1 temp=nums[i] while j>=0 and temp<nums[j]: nums[j+1]=nums[j] j-=1 nums[j+1]=temp return nums if __name__ == '__main__': print insertSort([4,2,3,1])
class Solution(object): def productExceptSelf(self, nums): result = [] product=1 for i in range(0,len(nums)): result.append(product) product= product*nums[i] product=1 for j in range(len(nums)-1, -1, -1): result[j]=result[j]*product ...
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ i, j, k =m-1, n-1, m+n-1 while i>=0...
#Author: Cecelia Williams #Last Revision: 04.30.2017 #Description: Chapter 18 Exercise 7 """ Write a function flatten that returns a simple list containing all the values in a nested list:""" def flatten(my_list_of_lists): return sum(([x] if not isinstance(x, list)else flatten(x) for ...
#Author: Cecelia Williams #Last Revision: 05.12.2017 #Description: Chapter 26 Exercise 2 class PriorityQueue: def __init__(self): self.items = [] def is_empty(self): return not self.items def insert(self, item): self.items.append(item) def remove(s...
#!/usr/bin/env python """Neural Network Simulator @author: Bill Tubbs Revision date: 2018-04-25 This Python module provides classes to simulate Multi-Layer Perceptron (MLP) neural networks for machine learning applications. It is an efficient vectorized implementation using numpy arrays and scipy optimization algorit...
import random cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def deal_card(): random_card = random.choice(cards) return random_card deal_card() def calculate_score(hand_cards): score = sum(hand_cards) if (11 in hand_cards) and score > 21: score -= 10 return score def has_blackjack(...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
#!/usr/bin/env python def delete_alpha(text): #deletes letters i=0 while (i<len(text)): if (text[i].isalpha() == True): del text[i] else: i=i+1 return text def matching(a,b, occ, pi, alf): for i in range (0,len(alf)): if a == pi[i] and b==occ[i]: return alf[i] return "error" if __name__ == "__mai...
"Desenvolvido por Flávia" qntd_pessoas = int(input()) cidade = input().upper() qntd_quartos = int(input()) if (cidade == "PIPA") and (qntd_quartos == 2 ): total_viajem = (600 + (75 * qntd_pessoas)) total_pessoa = total_viajem / qntd_pessoas print("{:.2f}".format(total_viajem)) print("{:.2f}".format(total_pess...
"Desenvolvido por Flávia" num = float(input()) dolar = 3.55 converter = num * dolar print("{:.2f}".format(converter))
"Desenvolvido por Flávia" idade = int(input()) tipo = input() if (idade < 0) or (idade > 130): print ("Idade invalida.") elif (tipo != "azar") and (tipo != "mmorpg") and (tipo != "moba") and (tipo != "casual"): print ("Jogo invalido.") elif (tipo == "azar" and idade >= 21) or (tipo == "mmorpg" and idade >= 14) ...
"Desenvolvido por Flávia" qntd_livros = int(input()) qntd_alunos = int(input()) media = qntd_alunos / qntd_livros if media >= 1 and media <= 8: print("A") elif media >= 1 and (media >= 9 and media <= 12): print("B") elif media >= 1 and (media >= 13 and media <= 18): print("C") elif media > 18: print("D"...
matriz = [[1,2,4],[8,10,12],[21,24,27]] linha = int(input("Digite sua linha para soma: ")) coluna = int(input("Digite sua coluna para soma: ")) soma = matriz[linha][coluna] if linha != 0: soma += matriz[linha-1][coluna] if linha != 2: soma += matriz[linha+1][coluna] if coluna != 0: soma += matriz[linha][...
qntd = int(input()) lista = [] for i in range(qntd): num = int(input()) lista.append(num) pulo = int(input()) for i in range(pulo,qntd): print(lista[i]) for i in range(pulo): print(lista[i])
"Desenvolvido por Flávia" circulo_1 = float(input()) circulo_2 = float(input()) pi = 3.14 raio_1 = float(pi * (circulo_1 ** 2)) raio_2 = float(pi * (circulo_2 ** 2)) if circulo_1 > circulo_2: print("Primeiro circulo") elif circulo_1 < circulo_2: print("Segundo circulo") elif circulo_1 == circulo_2: p...
# media, mediana, moda ''' from statistics import * # para importar todos os metodos de statistics ''' def media(lista): #mean(lista) # metodo facil pelo python media = sum(lista)/float(len(lista)) return media def mediana(lista): # vai ordenar e pegar os numeros centrais e tirar a média, se for impar só mo...
import abc #Interface class AbsStrategy(abc.ABCMeta): @abc.abstractmethod def calculate(self,order): pass #context class ShippingCost(object): def __init__(self, strategy:AbsStrategy): self._strategy = strategy def shipping_cost(self,order): return self._strategy.calculat...
import unittest #You need this module from lab3_duckmayr import * #This is the script you want to test class mytest(unittest.TestCase): def test_shout(self): self.assertEqual("I NEED A TOURNIQUET!", shout("I need a tourniquet.")) self.assertEqual("I NEED A TOURNIQUET!", shout("I need a tourniquet?")) self.ass...
class LinkedList(object): def __init__(self, value): self.start = Node(value) self.nodes = 1 def __str__(self): # This is complexity class n. For this, and all later reported complexity classes, I am considering worst-case complexity. I have not found a way to make any of these functions a lower complexity cla...
def get_divisible(number, factor, count = 0): if number % factor == 0: count += get_divisible(number // factor, factor) + 1 return count def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def decomp(n): decompos = ...
# Inspired from real-world Brainf**k, we want to create an interpreter of that language which will support the following instructions: # > increment the data pointer (to point to the next cell to the right). # < decrement the data pointer (to point to the next cell to the left). # + increment (increase by one, tru...
name=(input("ведите имя ")) familiay=(input("видите фамилия ")) s=name.upper()+familiay.upper() print(s)
# if-else # if statement one is true, then do something # if not then do something else # easy peasy lemon squeezy left = 200 right = 33 if left > right: print("Left is greater than Right") elif left == right: print("Left and Right are equal") else: print("Right is greater than Left") print() # and and ...
# dictionary is an unordered collection fo data # it stores data as key-value pairs # create a dictionary numbers_and_letters = {1: "A", 2: "B", 3:"C", 4:"D", 5:"E"} print("Dictionary:", numbers_and_letters) # access values in a dictionary # value = dictionary_name[key] value_of_key_1 = numbers_and_letters[1] # o...
""" CP1404/CP5632 Practical Colour codes in a dictionary """ COLOUR_CODES = {"AliceBlue": "#f0f8ff", "DarkGreen": "#006400", "GreenYellow": "#adff2f", "HotPink": "#ff69b4", "IndianRed": "#cd5c5c", "MediumSpringGreen": "#00fa9a", "MintCream": "#f5fffa", "PaleTurquoise": "#afeeee", "Saddl...
from Prac07.guitar import Guitar def main(): guitars = [] while True: name = input("Name: ") if not name: break year = int(input("Year: ")) cost = float(input("Cost: $")) guitar_object = Guitar(name, year, cost) guitars.append(guitar_object) ...
num_items = int(input("Please enter the number of different items being purchased: ")) while num_items < 0: print("Invalid number of items!") num_items = int(input("Please enter the number of different items being purchased: ")) quantities = [] costs = [] shipping_costs = [] total_item_cost = [] for i in ran...
x = int(input()) drinks = x #一開始買的 caps = x #一開始買的 所拿到的瓶蓋 while True: drinks = drinks + caps // 4 #後來飲料數會變成,原本的飲料+瓶蓋換的 caps = (caps%4) + (caps // 4) #頻蓋數 = 換剩下的 + 又換來的飲料的瓶蓋 if caps == 3: #如果最後瓶蓋數剩下3就可以借一瓶,所以飲料數+1 drinks += 1 break elif caps < 3: #如果小...
num=int(input("Enter the digit value:") v=num while(v!=0): digit=v%10 result +=digit*digit*digit v =v/10 if(result == num): print(armstong) else: print(no armstrong)
a=int(input("Enter the value:")) b=int(input("Enter the value:")) for i in range(a,b): sum=0 temp=n while temp > i: digit = temp % 20 sum = sum + digit ** 4 temp / = 20 if i == sum: print(i)
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' counter = 0 total = 0 while counter < 1000: if counter % 3 == 0 or counter % 5 == 0: total = total + counter ...
i=int(input('請輸入整數值:')) print('%d的資料型別為%s'%(i,type(i))) f=float(input('請輸入浮點數值:')) print('%f的資料型別為%s'%(f,type(f))) b=bool(input('請輸入布林值:')) print(b,'的資料型別為%s'%(type(b))) #因為布林值沒有對應的%型別字元 s=input('請輸入字串資料:') print('%s的資料型別為%s'%(s,type(s)))
name = ['老張', '發叔', '李董', '豪哥', '小何'] age = [54, 46, 50, 40, 38] ans = input('1. 由小到大排序 2. 由大到小排序 : ') if ans == '1': print('由小到大排序:', end =' ') for loop in range(1, 5): for index in range(0, (5-loop)): if age[index] > age[index+1]: aTemp = age[index] age[i...
income=int(input('請輸入您的綜合所得淨額: ')) if (income<=540000): tax=0; if ((income>540000) and (income<=1210000)): tax=0.12*income if ((income>1210000) and (income<=2420000)): tax=0.2*income if ((income>2420000) and (income<=4530000)): tax=0.3*income if ((income>4530000) and (income<=10310000)): tax=0.4*income if (income>10310...
# Insertion Sort Algorithm Impplementation Using Python def insertion_sort(list): for i in range(0,len(list)): for j in range(i-1,0,-1): if list[j]>list[j+1]: #swapping list[j],list[j+1] = list[j+1],list[j] return list list = [10,25,15,45,30] print(insertion_sort(list)) # output:[10,15,25...
#!/usr/bin/python import math from operator import itemgetter def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named clean...
def longest(tree): a, b = _longest(tree) return a - 1 def _longest(tree): if tree == []: return 0, 0 leftL, leftD = _longest(tree[0]) rightL, rightD = _longest(tree[2]) subL = Max(leftL, rightL) subD = Max(leftD, rightD) return Max(leftD + rightD, subL), subD + 1 def Max(a...
""" 647. Palindromic Substrings Medium Given a string, your task is to count how many palindromic substrings in this string.The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. """ class Solution: def countSubstrings(self, s: st...
def is_palindrome(s): revers_s = '' s = str(s) for i in s[::-1]: revers_s += i s = "".join(s.lower().split()) revers_s = "".join(revers_s.lower().split()) if s == revers_s: return True else: return False
from solution_15 import fact from solution_24 import get_the_permutation_in_place_of def find_all_multiplicand_multiplier_product(str_of_number): second_half = len(str_of_number) - len(str_of_number) // 2 return [(str_of_number[:i], str_of_number[i: second_half], str_of_number[second_half:]) for i in range(1, ...
import math from solution_3 import check_if_prime if __name__ == '__main__': def is_truncatable_left_to_right(num): tmp_num = num while tmp_num > 0: if not check_if_prime(tmp_num): return False tmp_num %= 10 ** (len(str(tmp_num)) - 1) return True ...
import math def check_if_prime(num): if num < 2: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True if __name__ == '__main__': dest_num = 600851475143 all_factors = [] for i in range(1, int(math.sqrt(dest_num))): ...
from fractions import Fraction if __name__ == '__main__': previous_denominator, current_denominator, previous_numerator, current_numerator = 1, 2, 1, 3 temp_denominator, temp_numerator = 0, 0 counter_of_expansions = 0 amount_of_exceeding = 0 while counter_of_expansions < 1000: if len(str(cu...
if __name__ == '__main__': all_nums_till = [x for x in range(2, 2_000_001)] is_nums_prime = [True for x in range(2, 2_000_001)] sum_of_primes = 0 for i in all_nums_till: if is_nums_prime[i-2]: j = 2 * i while j < 2_000_001: is_nums_prime[j-2] = False ...
# idan hakimi # # i m i k a h n a d i a=input("Enter full name: ") print(' '.join(a[::-1]))
'''Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number.''' # def positive(num): # sum=0 # for i in range(1,num): # sum=sum+(i**3) # print("The Summary is: " + str(sum)) # return sum # # # new_sum=po...
#‘r’ – Read mode which is used when the file is only being read #‘w’ – Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is activated) #‘a’ – Appending mode, which is used to add new data to the end of the file; that is new inform...
name=input("Enter your name: ") age=input("Enter your Age: ") mail=input("Enter your mail: ") print("\nFull name: " + name + "\nYour Age is: " + str(age) + "\nYour mail: " + mail)
def mix(s1, s2): # your code result = [] for i in range(ord('a'), ord('z') + 1): elem = None s1_number = s1.count(chr(i)) s2_number = s2.count(chr(i)) if s1_number > 1 or s2_number > 1: if s1_number > s2_number: elem = '1:' + chr(i) * s1_number ...
import collections def dogrid(grid, i, j): mydeque = collections.deque([(i, j)]) size = 0 while mydeque: i, j = mydeque.pop() if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == ' ': grid[i][j] = "#" mydeque.extend([(i+1, j),(i-1, j),(i, j+1),(i, j-1)...
from copy import deepcopy def determinant(matrix): # your code here if len(matrix[0]) == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] elif len(matrix[0]) == 1: return matrix[0][0] else: result = 0 for i in range(len(matrix[0])): a = ma...
import numpy as np from matplotlib import pyplot as pet import pandas as pd #import dataset using pandas library dataset = pd.read_csv("Position_Salaries.csv") x = dataset.iloc[:, 1:2].values y = dataset.iloc[:,2].values #spitting data set into training set and test set from sklearn.model_selection import train_test...
class RPS: choice_dict = { 1: "rock", 2: "paper", 3: "scissors", } score = { "your_score": [], "computer_score": [], } won_case = ((1, 3), (2, 1), (3, 2)) your_final_score = 0 computer_final_score = 0 def update_score(result): if result ==...
import pandas as pd class WeatherPreprocessor: """ input: the raw dataframe of weather, output: preprocessed dataframe with datetimeindex """ def __init__(self, path_to_weather): self.df_raw = pd.read_csv(path_to_weather, encoding='latin1', delimiter=";", header=1, na_values="?") df_d...
def lookaroundyou(data): i01.setHeadSpeed(0.8, 0.8, 0.6, 0.6, 1.0) for y in range(0, 3): if (data == "can i have your attention"): i01.mouth.speak("ok you have my attention") stopit() x = (random.randint(1, 6)) if x == 1: i01.head.neck.move...
def howdoyoudo(): global helvar if helvar <= 2: i01.mouth.speak("I'm fine thank you") helvar += 1 elif helvar == 3: i01.mouth.speak("you have already said that at least twice") i01.moveArm("left",43,88,22,10) i01.moveArm("right",20,90,30,10) i01.moveHand("left",0,0,0,0,0,119) i01.moveH...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/23 17:26 # @Author : Aries # @Site : # @File : GroupByDemo.py # @Software: PyCharm import pandas as pd import numpy as np from pandas import DataFrame,Series df=DataFrame({"key1":['a','a','b','b','a'], 'key2':['one','two','one','tw...
#exercicioVestibular n = int(input()) oficial = input() candidato = input() total = 0 for o,c in zip(oficial,candidato): if o == c: total += 1 print(total)
#Criando uma lista (Vetor), porém as listas podem receber elementos de vários tipos ao mesmo tempo lista = [1, 2, 3, 4, 5.6, "string"] #Acessar elemento da lista lista[0] = 10 #Adicionar elemento no final da lista lista.append(1) #Remover elemento da lista del lista[5] #imprimir lista print(lista) #numeros negativ...
#Entrada de Dados #Para ler valores separados com espaço tem que usar o comando split A,B = input().split() #O comando input sempre armazena os valores como string, então para usar como int temos que transforma-lo em int A = int(A) B = int(B) print(A+B) #Para receber em linhas diferentes pode fazer assim: A = int(...
#exercicioRisadaEngracada S = input() vogais = ['a','e','i','o','u'] R = '' for c in S: if c in vogais: R += c #R[::-1} é uma forma em python pra acessar a string ao contrario #metodo slice if R == R[::-1]: print("S") else: print("N")
Created on Tue Dec 18 21:53:23 2018 This is a demo task. Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the fu...
# given a letter, return true if the letter is valid for alpha-numeric # text and valse if not # # @param letter a single character string # @return True if the string is a letter or number # False if the character is something else def cleanLetter( letter ): # keep lower case letters if letter[0]>=...
#!/bin/python3 import math import os import random import re import sys # Complete the migratoryBirds function below. def migratoryBirds(arr): bird_counts_per_type = [arr.count(i) for i in range(1, 6)] # Sums 1 to index to get the corresponding bird type return bird_counts_per_type.index(max(bird_counts_...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getTotalX' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # def is_number_factor_of_all_array_elements(factor_number, a...
import unittest2 as unittest from classes.automobile import Automobile class TestAutomobile(unittest.TestCase): def setUp(self): self.automobile = Automobile() def tearDown(self): pass def test_can_wash_true(self): self.automobile.license_plate = '111112' can_wash, msg ...
#coding:cp949 coffee = 10 prompt=""" 1.ĿDZ 2.ĿܷȮ 3.α׷ ޴ ϼ : """ while True: print(prompt,end='') number = int(input()) if number==1: money = int(input("ݾ Էϼ : ")) if money == 300: print("ĿǸ ݴϴ.") coffee = coffee -1 elif money > 300: print(" Ž %d ...
""" https://www.youtube.com/watch?v=cKPlPJyQrt4 """ """ Full Data Model documentation: https://docs.python.org/3/reference/datamodel.html """ class Polynomial: def __init__(self, *coeffs): self.coeffs = coeffs def __repr__(self): return "Polynomial(*{!r})".format(self.coeffs) def _...
''' This Module is used to nake life easy for a user''' def add(num1,num2): '''This function is used to Add Two numbers''' return(num1+num2) def multiply(num1,num2): '''This function is used to Multiply Two numbers''' return(num1*num2) def greeting(name):...
#!/usr/bin/env python # coding:utf-8 ## 类:把一类事物的相同的特征和动作整合到一起就是类,类是一个抽象的概念 ## 对象:就是基于类而创建的一个具体的事物(具体存在的)也是特征和动作整合到一起 # class Chinese: # 经典类 python2中的区分 # '''这是一个中国人的类''' # pass # # print(Chinese) # # # class Chinese(object): # 新式类 python2中的区分 # pass # 实例化到底干了什么? # p1 = Chinese() # 实例化 并不像其它语言使用new # pri...
import random import numpy as np direction = {'up': (1,0), 'right': (0,-1), 'down':(-1,0), 'left':(0,1)} def new_game(size): """ Returns a new game with two random cells placed. """ board = np.zeros([size, size]).astype('int16') place_random(board) place_random(board) return board, 0 def place...
"""Represents the body of the server list data.""" import time class ServersModel(object): def __init__(self): self.server_list = "" self.server_list_dirty = True #key = client #value = (port, time, server_domain) self.servers = {} def register_server(...
# -*- coding: utf-8 -*- """ Created on Fri Dec 18 10:16:03 2020 @author: USER """ from math import pi class Modelo(): ## Calculo del cuadrado def area_cuadrado(self, l): area = l*l return area ## Calculo del Triangulo def area_triangulo(self, b,h): area = (b*h)/2...
no = int(input("Enter nth number: " )) p,q = 0,0 x = int(no) if x % 2 == 1: x = x / 2 p1 = x * 7 print(p1) else: x = x / 2; q = 6 * (x - 1) print(q)
fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() # rstrip() method remove all whitespace. if line.startswith('From:'): # startswith() method is used for whatever word or characters we want to print from. print(line)
import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, BatchNormalization, Dropout, MaxPooling2D, Activation, Flatten, Dense, AveragePooling2D def MicronNet(width, height, depth): """Generates the MicronNet network. Consists of 4 Convolutional layers and 3 F...
#!/usr/bin/env python # Pravin Paratey (http://pravin.insanitybegins.com) # # The number, 197, is called a circular prime because all rotations of # the digits: 197, 971, and 719, are themselves prime. There are # thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, # 73, 79, and 97. How many circular...
#!/usr/bin/env python # Pravin Paratey (http://pravin.insanitybegins.com) # # Why do we check only 6 digits? # # Because 9^5 = 59049 # # 4 digit number = 4 * 9^5 = 236196 # 5 digit number = 5 * 9^5 = 295245 # 6 digit number = 6 * 9^5 = 354294 # 7 digit number = 7 * 9^5 = 413343 # (which is less than t...
#FOR ITERATION IN LIST l=[12,13,26] for i in l: print(i)
#SET D x,y=[1,2,3,4,5],[5,4,3,2,1] print(x==y,end='') print(set(x)==set(y))
# Update() function for add more than one value in set s1={'Hello',45,(4,5),4.5} s2={8,10} s2.update({'cat':'billi','book':'kitab'}) print(s2) print(len(s2))