text
stringlengths
37
1.41M
num1=0 num2=0 num1 = int (input("dame tu primer numero")) num2 =int (input("dame tu segundo numero ")) if num1 and num2 >= o : if num1> num2 : print ("el primer numero es mayor ") else : print ("el segundo numero es mayor ")
""" Module for test Square class """ import unittest from io import StringIO from unittest.mock import patch from models.square import Square from models.rectangle import Rectangle from models.base import Base import os.path class TestSquareMethods(unittest.TestCase): """ Suite to test Square class """ def s...
#!/usr/bin/python3 """Module for add_atribute method""" def add_attribute(obj, att, val): """Module for add_atribute method""" if hasattr(obj, '__dict__') is True: setattr(obj, att, val) else: raise TypeError("can't add new attribute")
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): new_matrix = matrix.copy() for x in range(len(new_matrix)): new_matrix[x] = list(map(lambda x: x ** 2, new_matrix[x])) return new_matrix
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMax_integer(unittest.TestCase): """Class to tests the function Max_integer """ def test_max_integer(self): """Method to test thw function max_integer with unitt...
#!/usr/bin/python3 def remove_char_at(str, n): for i in range(len(str)): if n == i: dup = str.replace(str[n], "") return dup else: return str
def compare(a,b): if a>b: return 1 return -1 # def h(a,b): if a>0 and b>0: return (a**2+b**2)**0.5 print ('SB')
# -*- coding: utf-8 -*- """ author : GerryLuo blog : blog.gerryluo.cn function : 每一张牌型的定义 """ class Card(object): num = 0 def __init__(self, num=0): # [-7, 26] # 先进行必要的初始化 super(Card, self).__init__() self.num = 0 # 然后再赋值 self.num = num def __cmp_...
from flask import Flask from .palindrome import detect_palindrome app = Flask(__name__) @app.route("/palindrome") def palindrome(): word = "Racecar" is_palindrome = detect_palindrome(word) is_palindrome = word + ' is a palindrome' if is_palindrome else word + ' is not a palindrome' return is_palindrome
def remove_duplicates(l); new_l = [] for k in s; if k not in new_l; new_l.append(k) return new_l print(remove_duplicates([1,1,2,3,4,4,5,5]))
#Exercise 5.5. #Read the following function and see if you can figure out what it does. Then run #it (see the examples in Chapter 4). import turtle bob = turtle.Turtle() def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) ...
#Exercise 5.4. #If you are given three sticks, you may or may not be able to arrange them in #a triangle. For example, if one of the sticks is 12 inches long and the other #two are one inch long, you will not be able to get the short sticks to meet in #the middle. For any three lengths, there is a simple test to...
Def is_triangle(a, b, c): if a<=b+c and b<=a+c and c<=a+b: return 'yes' else: return 'no' is_triangle(1, 12, 3) 'no'
#Exercise 18.3 from random import shuffle class Card(object): """Represents a standard playing card.""" def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4',...
# A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice: def do_twice(f): f() f() # Here's an example that uses do_twice to call a function named print_spam twice. def print_sp...
'''Exercise 15.1. Write a function called distance_between_points that takes two Points as arguments and returns the distance between them.''' def distance_between_points(x,y): a=abs(x[0]-y[0]) b=abs(x[1]-y[1]) c=(x**2+y**2)**.5 return c
#Exercise 9.8. def is_palindrome(word): return word == word[::-1] def searched_number(number): if is_palindrome(str(number)[2:]): number += 1 if is_palindrome(str(number)[1:]): number += 1 if is_palindrome(str(number)[1:5]): number += 1 ...
#!/usr/bin/python """ simulatedAnnealing.py ------------------------------ * Optimize a function by means of simulated annealing """ # Import NumPy try: import numpy as np except ImportError: print "Error: NumPy is not installed" exit() def simulatedAnnealing( costFunction, theta, T_init, T_end, cool_rate, it...
import math class Vector: def __init__(self): self.x = 0 self.y = 0 def setVector(self,x,y): self.x = x self.y = y def getSize(self): return math.sqrt(self.x*self.x + self.y*self.y) def getVector(self): return self.x , self.y def P...
#https://www.careercup.com/question?id=5680043955060736 #Output top N positive integer in string comparison order. For example, let's say N=1000, then you need to output in string comparison order as below: #1, 10, 100, 1000, 101, 102, ... 109, 11, 110, ... #O(1) space, O(n) time def f(n,s=''): if not s or int(s)<...
''' Question from https://www.careercup.com/question?id=6335704 Given a N*N Matrix. All rows are sorted, and all columns are sorted. Find the Kth Largest element of the matrix. My solution: We can solve with problem with O(1) space and O(N) time, where N is the width and height of the matrix. One possible flaw in...
# !/bin/python3 # main.py """Integrating the quadtree algorithm with GUI.""" import pygame import quadtree # Initializing pygame pygame.init() # width and height of the main window screen width, height = 1200, 600 # Creating a surface surface = pygame.display.set_mode((width, height)) # Title of the window: pygame.d...
class Location: """ represents a global location by lat and long can add methods to get interesting info from location """ _lat = None _long = None def __init__(self, latitude, longitude): self._lat = latitude self._long = longitude @property def lat(self):...
import os import csv cereal_csv = os.path.join("..","Cereal", "Resources", "cereal.csv") with open(cereal_csv, 'r') as file: csv_reader=csv.reader(file) next(csv_reader, None) for row in csv_reader: fiberCount = row[8] cereal = row[0] if float(fiberCount) >= 5: print(f'{cer...
#!/usr/bin/env python # coding: utf-8 a=6 b=10 print(a<b) print(a>b) tf = a<=b print(tf) print(b==10) print(b!=10) if a==5: print("Wow!!") else: print("Nope. Inte lika med fem...") # Först några variabler att jobba med x = 7 y = 3 z = 7 # enkla jämförelser # kolla om "mindre än" samt "större än" if y ...
""" Assignment 2: Automatic Puzzle Solver ============================== This code is provided solely for the personal and private use of students taking the CSC148 course at the University of Toronto. Copying for purposes other than this use is expressly prohibited. All forms of distribution of this code, whether as g...
import LinkedListNode class LinkedList: """ Time Complexity: O(1) """ def __init__(self): self.n = 0 self.left = self.right = None ########################################################################### # Set operations #######################################################...
def count_bits(n): count = 0 while (n>0): if n%2: count +=1 n //=2 return count print(count_bits(9)) #def countBits(n): # return bin(n).count("1")
def duplicate_count(text): text = text.lower() S = set (list(text)) counter = 0 for a in S: if text.count(a) > 1: counter += 1 return counter print(duplicate_count("abcdeaB")) """ #ESTA FUNCION L=[] for i in text: L.append(text.count(i)) return max(L) pr...
import sys import re valid_passwords = 0 with open(sys.argv[1]) as file: for line in file: # Almost did line[:-2] but then the last line would be too short line = line.replace('\n', '') # Split line into [minimum, maximum, char, password] min_occurances, max_occurances, char, pass...
import argparse parser = argparse.ArgumentParser(description="Handheld Halting") parser.add_argument("file", metavar="INPUT_FILE", type=str, help="Input filename") parser.add_argument( "--verbose", "-v", action="store_true", default=False, help="Verbose output" ) args = parser.parse_args() def vprint(*x): i...
import argparse from enum import IntEnum parser = argparse.ArgumentParser(description="Rain Risk") parser.add_argument("file", metavar="INPUT_FILE", type=str, help="Input filename") parser.add_argument( "--verbose", "-v", action="store_true", default=False, help="Verbose output" ) args = parser.parse_args() def...
#traditional Method """ fruits=["apples","kiwi","mangoes","bannas"] newfruit=[] for x in fruits: if "n" in x: newfruit.append(x) print(newfruit) """ #in compereshio fruitss=["apples","kiwi","mangoes","bannas"] newfruits=[z for z in fruitss if "a" in z] print(newfruits)
#list,touple,dict #list are changeble,allow duplicate,oredered #we can append and remove by using #list.remove() #list.append() """ lis=["bannab","cherry","apple"] lis.remove("cherry") print(lis) """ # touple not call able,not change able,allow duplictae,ordered """ fruits = ("apple", "banana", "cherry") print(fruits...
def insertionSort(alist): #the comparison starts at index 1 and compares backwards #at increments of one #it evaluates and reassigns to its left #it indexes and increments from left to right for index in range(1, len(alist)): currentvalue = alist[index] position = index #Stays in this loop unti...
# Note-Taking Program 8 """ Details: Create a note-taking program. When a user starts it up, it should prompt them for a filename. If they enter a file name that doesn't exist, it should prompt them to enter the text they want to write to the file. After they enter the text, it should save the file and exit. If they e...
''' В школе решили набрать три новых математических класса. Так как занятия по математике у них проходят в одно и то же время, было решено выделить кабинет для каждого класса и купить в них новые парты. За каждой партой может сидеть не больше двух учеников. Известно количество учащихся в каждом из трёх к...
# Scholarship Picker # Designed and developed by Nate Stutte # # Project created 8.6.2020 # Last update was 8.7.2020 # # Repo : https://github.com/magfmur/Scholarship-Picker import random import sys scholarships = [] scholarshipspool = [] scholarshipstrashpool = [] def create_scholarship_dict(): f = import_fi...
""" Demonstrates the use of Counter https://docs.python.org/3/library/collections.html#collections.Counter """ from collections import Counter cnt = Counter(["red", "blue", "red", "green", "blue", "blue"]) print("string counter -> ", cnt) cnt = Counter("sdadsdddsssaa") print("most common (2) -> ", cnt.most_common(2)...
print("hello world") op='0' num1=0 num2=0 resultado=0 print("0 para sair") print("1 para somar") print("2 para subtrair") print("3 para dividir") print("4 para multiplicar") while(op=='0'or op=='1'or op=='2'or op=='3'or op=='4'): op=input("digite operacao ou 0 para sair") if (op=='0'): break elif(...
def add_one(x): return x + 1 def apply_function(f, lst): length = len(lst) for n in range(length): lst[n] = f(lst[n]) lst = [1, 2, 3] print(lst) apply_function(add_one, lst) print(lst)
a = set(range(100)) # create a set of numbers 1-100 print(a) print(50 in a) print(200 in a) a.remove(50) a.add(200) print(50 in a) print(200 in a) x = set(range(75)) # Create a set of numbers from 0 to 74 y = set(range(50, 100)) # Create a set of numbers from 50 to 100 print(x.intersection(y)) # Get the numbers that ar...
import abc # abstract base class class Foo(abc.ABC): @abc.abstractmethod def print_me(self): pass class XBar(Foo): def __init__(self, x): self.x = x def print_me(self): print(self.x.lower()) class YBar(Foo): def __init__(self, y): self.y = y def print_me(self...
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-03-20 ................................................... ''' from Hash_Set_array import * from List_array import * from Word import * def insert_words(...
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-02-01 ................................................... ''' from Stack_array import Stack from utilities import array_to_stack #identifting the source...
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-01-17 ................................................... ''' from functions import is_leap_year year = int(input('Enter a year: ')) print(is_leap_year...
''' ................................................... CP164 - Data Structures Author: laith Adi ID: 170265190 Email: Adil5190@mylaurier.ca Updated: 2019-03-15 ................................................... ''' from copy import deepcopy class _PQ_Node: def __init__(self, value, _nelt): ...
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-01-31 ................................................... ''' from Stack_array import Stack def stack_reverse(source): """ --------------------...
import unittest def reverse(A): if len(A) <= 1: return A for i in range(len(A) // 2): tmp = A[len(A) - 1 - i] A[len(A) - 1 - i] = A[i] A[i] = tmp return A class ReverseTestCase(unittest.TestCase): def test(self): self.assertEqual(reverse([]), []) sel...
import unittest def binary_sum(A, B, C): borrow = 0 for j in range(len(A)-1, -1, -1): x = A[j] + B[j] + borrow if x == 0: C[j+1] = 0 borrow = 0 elif x == 1: C[j+1] = 1 borrow = 0 elif x == 2: C[j+1] = 0 bor...
""" ============================ Author : XiaoLei.Du Time : 2019/11/26 18:59 E-mail : 506615839@qq.com File : python基本语法.py ============================ """ import random # import decimal # num=random.random() # print(num) # num1=random.randint(1,9) # print(num1) # num2=num+num1 # print(num2) # a=decimal.Deci...
""" ============================ Author : XiaoLei.Du Time : 2019/10/28 22:19 E-mail : 506615839@qq.com ============================ """ ''' 1、一家商场在降价促销。如果购买金额50-100元(包含50元和100元)之间,会给打九折, 如果购买金额大于100元会给打八折。编写一程序,询问购买价格,再打印出折扣和最终价格。 ''' print('\n'+'*'*6+'第一题'+'*'*6) try: price = float(input('请问你购买了多少钱?')) i...
from .base import _BaseAggregator def _compute_scores(distances, i, n, f): """Compute scores for node i. Arguments: distances {dict} -- A dict of dict of distance. distances[i][j] = dist. i, j starts with 0. i {int} -- index of worker, starting from 0. n {int} -- total number of worke...
# Author: Andrew Thompson # Description: Application for encrypting and decrypting Strings using a columnar transposition. # # # Currently working on the functionality of the GUI # import random from appJar import gui def generateKey(raw_key): #return permutation with no duplicates acc='' acc1='' acc2=...
import scipy.io import math import pandas as pd import numpy as np import matplotlib.pyplot as plt # Load the AllSamples dataset data_set = scipy.io.loadmat("C:/Users/Chandan Yadav/Downloads/AllSamples.mat") X = data_set["AllSamples"] # List of number of values for k k_dist = [2, 3, 4, 5, 6, 7, 8, 9, 10]...
from ex16_2 import create_list ls = create_list() print(ls) avg = sum(ls)/len(ls) close = 0 for i in ls: if abs(avg-i) < abs(avg-close): close = i print(f'The closest element to average {avg} is {close} ')
# Переводим температуру по цельсию в Фаренгейты на GUI tkinter from tkinter import * def convert(): convert = (int(entry.get()) - 32)*(5/9) label2.config(text=convert) def quit(): exit() root = Tk() root.title('Cels to Fahrenheit') frame = Frame(root) frame.pack() label1 = Label(frame, text='Temperatu...
class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return '({0.x}, {0.y})'.format(self) def func(self): return abs(self.x-self.y) a = Point() print(str(a)...
casa = float(input('Valor da casa: R$')) salario = float(input('Salário do comprador: R$')) anos = int(input('Quantos anos de financiamento? ')) prestação = casa / (anos * 12) minimo = salario * 30 / 100 print(f'para pagar uma casa de {casa:.2f} em {anos} anos', end='' ) print(f'a prestação será de {prestação:.2f}') ...
# -*- coding: utf-8 -*- """ Created on Mon Jul 8 12:39:03 2019 @author: Yajat """ #DATA PREPROCESSING #Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import scipy.misc #Importing the dataset data = pd.read_csv('input.csv') labels = pd.read_csv('output.csv') #Split...
class book: """ Book class used to populate a "shelf" of books based on ISBN scanning from inventorying """ def __init__(self, ISBN): import datetime """ Initialize a book with the ISBN (can be 10 or 13, but can't have dashes) Use setApiKey(string) to override the default Google Books API key """ se...
nums = [] with open('input/day1puzzle1.txt', 'r') as puzzle_input: for line in puzzle_input: nums.append(int(line.strip())) # confirm input print(nums) # start algorithm # use a set of complements to figure out which pair adds up to 2020 complement = set() for number in nums: if 2020 - number in compl...
#-------------------------------------------------# # Title: To Do list # Dev: Jinee Han # Date: May 06, 2019 # Jinee edits Assignment 05 to use Class and Dictionary # #------------------------------------------------------# objFileName = "Todo.txt" strData = "" dicRow = {} lstTable = [] #-- Input/Output --# # Us...
def add(a,b): return a+b def sub(a,b): return a-b i=int(input("enter the value for a")) j=int(input("enter the value for b")) d=add(i,j) print("addtion",d) print("subtraction",sub(i,j))
# sorting a list numbers=[10,20,90,54,67,23,13,45,68,5,7] big_numbers=[] for num in numbers: count=0 while count < len(numbers): big_numbers.append(max(numbers)) numbers.remove(max(numbers)) count+=1 print(big_numbers) # getting top big numbers in a list numbers=[10,20...
###Enter the rank fo the number of Fibronacci list that you want generate def suit_fibronacci(n): if n==1 or n==2: return 1 else: x=1 y=1 for i in range (n-2): z=x+y x=y y=z return y for i in range (1,12): print(suit_fibronacci...
import cv2 import numpy as np #Capturing video through Camera cap = cv2.VideoCapture(0) # Initialising our face classifier face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") skip = 0 face_data = [] # Path to store face data dataset_path = 'C://Users//kshitij goel//Desktop//Real-Time-...
C = int(input("Enter temperature in degree celsius:")) F = float(C*1.8)+32 print(F)
Name = input("What's your name?") Food = input("What's your favorite food?") print(Name +" likes " +Food)
#Program 3 - Guessing game import random setno=random.randint(1,10) def guessnumber(): g=input("Guess the secret number: ") g=int(g) return g g=guessnumber() i=1 while i<=3: if g==setno: print("You won") break elif i<3: i+=1 g=guessnumber() else: pr...
from collections import OrderedDict def main(): # list of teams with wins and losses teams = [ ('a', (30, 20)), ('b', (20, 30)), ('c', (50, 0)), ('d', (25, 25)) ] # sort the list by no of wins sorted_team = sorted(teams, key=lambda t: t[1][0], reverse=True) pr...
#приклад з float while True: x = float x = input("1-0.3+1.3+0.7-0.3 Введіть вашу відповідь: ") if x == '2.4': print("Молодець, відповідь правильна!") break else: print("Відповідь неправильна")
import math T = int(input()) for t in range(T): n = int(input()) angle = (((2 * math.pi) / (2 * n)) / 2) toFlat = 0.5 / math.sin(angle) print(2 * toFlat)
import random def get_random_priority(gate_connections): """Get random priority for each connection""" connection_numbers = [] # fills the list with connections for connection_nr in gate_connections.keys(): connection_numbers.append(connection_nr) # randomizes the order of the list with ...
import math from decimal import Decimal, getcontext # 设置 Decimal 数据类型小数点后保留的位数 getcontext().prec = 19 # 设置公差,用于判断变量是否为零 TOLERANCE = 1e-10 class Vector(object): # 实例(instance)的创建 def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple([Decimal(x...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns values = np.array([1, 3, 2, 4, 1, 6, 4]) example_df = pd.DataFrame({ 'value': values, 'even': values % 2 == 0, 'above_three': values > 3 }, index=['a', 'b', 'c', 'd', 'e', 'f', 'g']) # Change False to True for ea...
#!/usr/bin/python import urllib2 from lxml import etree as ET import cgi # As mentioned in class, and in the presentation (see .pdf), this # accepts a zipcode from Angel, queries google for the information, # parses it to create a forecast, and then puts it in a format Angel # can understand. wbURL = "http://www.goog...
file = open("module4bonustext.txt", "rt") text = file.read() word_counts = {} for word in text.split(): if word in word_counts: word_counts[word] += 1 else: word_counts[word] = 1 print(f'{"WORD":<12}COUNT') for word, count in sorted(word_counts.items()): print(f'{word...
from decimal import Decimal string1 = "79-900" string2 = "80-155" def generator(arg1,arg2): generator_list = [] start = None start = arg1[0:2] start +=arg1[3:7] start = int(start) start += 1 end = None end = arg2[0:2] end +=arg2[3:7] end = int(end) for i in range(start,en...
from tkinter import * window = Tk() window.config(bg="#111") window.geometry("450x450") list_lab = Label(window, bg="white", width=20, height=2) list_lab.place(x=150, y=150) list_lab2 =Label(window, bg="white", width=20, height=2, text="42, 12, 13, 89, 63, 11") list_lab2.place(x=150, y=100) def dort(): Numbers...
# Ch08 資料運算 ## 算術運算 import pandas as pd data = {"C1":[1,4],"C2":[2,5],"C3":[3,6]} df = pd.DataFrame(data,index = ["S1","S2"]) df df["C1"] + df["C2"] df["C1"] - df["C2"] df["C1"] * df["C2"] df["C1"] / df["C2"] df["C1"] + 2 df["C1"] - 2 df["C1"] * 2 df["C1"] / 2 ## 比較運算 df df["C1"]...
#Below program counts frequency of words in a file. import re import operator import collections mydict = dict() with open ('myTextFile.txt','r') as infile: for line in infile: line = re.sub('[!@#$]', '', line) lst = list() lst = line.lower().split() for word in lst: ...
''' There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location and moves at a rate of meters per jump. The second kangaroo starts at location and moves at a rate of meters per jump. Given the starting locations and movement rates f...
from collections import deque d = deque() d.append(1) # adiciona do lado direito (Segundo, Final) d.appendleft(2) # adiciona do lado esquerdo (Primeiro, Inicio) d.append(3) d.appendleft(4) # 4, 2, 1, 3 #pop remove do lado direito #popleft remove do lado esquerdo d.remove(2) #remove o elemento for i in d: print(i,...
nome = 'Jose Neto' print(len(nome)) lista = [1,2,3] print(len(lista)) d = {'marcos': 28, 'Neto': 25} for chave in d: print(d[chave]) num = 10 if(num % 2 == 0): print("Número eh par") else: print("Número eh ímpar") numero = 0 while(numero < 11): print(numero) numero += 1 def ehPar(num): ...
def fat(n): if(n == 0): return 1 return (n * fat(n - 1)) print(fat(3)) fat_ = lambda n: n * fat(n - 1) if n > 1 else 1 print(fat_(5)) #map (aplicar uma função pra mais de uma sequencia) lista = [1,2,3] m = map(lambda x: x ** 2, lista) for i in m: print(i) #reduce (aplica uma funcao sobre uma ...
# -*- coding: utf-8 -*- """ Created on Sun Jun 17 16:08:57 2018 @author: Jordan Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since...
from datetime import datetime class Utility: """ A small utility class for printing things """ def __init__(self): self.step = 1 def get_timestamp(self): """ Gets a nicely formatted timestamp to keep track of output files :return: """ raw = datetime...
import random import copy import os boardsize = int(input("enter the boardsize :")) print(boardsize) won = int(input("enter the number required for winning :")) board = [[0 for i in range(boardsize)] for j in range(boardsize) ] def display(): largest = board[0][0] for row in board: for element in row:...
#!/usr/bin/env python3 # RyanWaltersDev Jun 26 2021 -- TIY 8-9 def show_messages(messages): '''Prints each message in the list''' print("Here's a list of sample text messages:") for message in messages: print(f"\n{message}") message_list = ["Hello!", "How's it going?", "Hope you're doing well!"] s...
#/usr/bin/env python3 # RyanWaltersDev Jun 17 2021 - TIY 8-3 and TIY 8-4 # Initial function def make_shirt(size, text): '''Print summary of shirt.''' print(f"The shirt will be a size {size.title()} and say {text.title()}.") make_shirt('large', "wu tang clan ain't nuttin ta fuck wit") make_shirt(text="wu tang ...
# given number is prime or not a=int(input("Enter any number:")) i=2 while i<a: if a%i == 0: print('given number is not a prime number') break i+=1 else: print( 'given number is prime')
vString = 'apple peach' vInt = int('1') vList = [ 'apple', 'peach'] vTuple = ('apple', 'peach') vDictionary = { "apple : red", "peach : pink" } print(vString) print(vInt) print(vList) print(vTuple) print(vDictionary)
import Calculadora as C from unittest import TestCase, main class Testes(TestCase): def testar_soma(self): calculador = C.Calculadora() result = calculador.calcular(2, 3, 'somar') self.assertEqual(result, 5) def testar_multiplicacao(self): calculador = C.Calculadora() r...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # import dataset letters = pd.read_csv('letter.csv') # print some initial info about the dataset print(letters.info()) # print the first 5 lines of the dataset print(letters.head()) # see the distribution of the outputs : very evenly split p...
x, y, z, n = int(input()), int(input()), int(input()), int(input()) #taking input from the user print ([[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n ])
''' This module contains functions used to generate paths and explore them. ''' import numpy as np import pandas as pd import geopandas as gpd def __segment(r0, c0, r1, c1, path, rcs): ''' Creates a straight segment between two locations using Bresenham algorithm. Parameters ---------- r...
from datetime import datetime now = datetime.now() today = '%s/%s/%s' %(now.month, now.day, now.year) bday = raw_input("What is the day of your birthday?") bmonth = raw_input("What is the month of your birthday?") byear = raw_input("What is the year of your birthday?") age = int(now.year) - int(byear) if int(now.year) ...
def hello_name(name): return "hello, ", name partner_name = "Daniel" print hello_name(partner_name) def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1,num2): return num1 * num2 def divide(num1, num2): return num1 / num2 def modulo(num1, num2): return num1 ...
from datetime import datetime now = datetime.now() bday = raw_input("What is the day of your birthday?") bmonth = raw_input("What is the month of your birthday?") byear = raw_input("Which year were you born in?") # Doesn't work if birthday is 29/2 and current month is Feb of the normal year. # Doens't work if raw_inpu...