text
stringlengths
37
1.41M
#48 FAÇA UM PROGRAMA QUE CALCULE A SOMA ENTRE TODOS OS NUMEROS IMPARES QUE SAO MULTIPLOS DE TRES #E QUE SE ENCONTRAM NO INTERVALO DE 1 ATE 500. from time import sleep cores = { 'limpa':'\033[m', 'sublinhado':'\033[4m', 'azul':'\033[4;34m' } #IMPAR = DIVIDE POR 2 E RESTA 1 #DIVISIVEL POR 3 E QUANDO SE DI...
#54 CRIE UM PROGRAMA QUE LEIA O ANO NASCIMENTO DE SETE PESSOAS. # NO FINAL MOSTRE QUANTAS PESSOAS AINDA NAO ATINGIRAM A MAIORIDADE E QUANTAS JA SAO MAIORES (21 ANOS). from datetime import date anoatual = date.today().year print('-=-' * 20) print('{:^50}'.format('VAMOS BRINCAR COM IDADES!')) print('-=-' * 20) totmen...
#34 FAÇA UM PROGRAMA QUE PERGUNTE O SALARIO DE UM FUNCIONARIO E CALCULE O VALOR DO AUMENTO # (PARA SALARIOS SUPERIORES A R$ 1250,00 CALCULE 10% E PARA INFERIORES 15%) print('Vamos ter uma serie de aumentos na empresa!') print('Desta forma vamos precisar saber o seu salario para calcular seu aumento.') salario = float(...
#25 CRIE UM PROGRAMA QUE LEIA O NOME DE UMA PESSOA E RETORNE SE ELA TEM SILVA NO NOME nome = str(input('Digite o seu nome: ')).strip() print('O Seu nome tem Silva? {}'.format('SILVA' in nome.upper()))
# criar um conversor de temperaturas temp = float(input('Informe a temperatura em ºC: ')) convertf = ((temp * 9) / 5) + 32 print('A temperatura atual é {}ºC e se convertermos em Fahrenheit sera {}ºF.'.format(temp, convertf)) #(oC x 9) / 5) + 32
#69 crie um programa que leia a idade e o sexo de varias pessoas, # a cada pessoa cadastrada o programa devera perguntar se o # usuario quer ou nao quer continuar, no final mostre: #A Quantas pessoas tem mais de 18 anos. #B Quantos homens foram cadastrados. #C Quantas mulheres tem menos de 20 anos. from time import s...
#47 CRIE UM PROGRAMA QUE MSOTRE NA TELA TODOS OS NUMEROS PARES QUE ESTAO EM UM INTERVALO DE 1 E 50. print('Vamos descobrir quais os numeros sao pares entre 0 e 50!') for c in range(0,50): p = c % 2 if p == 1: print(c) print('TEMOS A LISTAGEM DE NUMEROS PARES ACIMA!')
#57 FAÇA UM PROGRAMA QUE LEIA O SEXO DE UMA PESSOA (M OU F),CASO ESTEHA ERRADO PEÇA A DIGITAÇÃO NOVAMENTE. sexo = str(input('Informe seu sexo[M/F]: ')).strip().upper()[0] while sexo not in 'MmFf': sexo = str(input('Dados invalidos, por favor informe seu sexo: ')).strip().upper()[0] print('Sexo {} registrado com su...
#9 faça um programa que leia o seu numero e fale a tabuada do mesmo tab = int(input('Digite um numero e descubra a tabuada: ')) print('-' *12) print('{} x {:2} = {}'.format(tab,1, tab * 1)) print('{} x {:2} = {}'.format(tab,2, tab * 2)) print('{} x {:2} = {}'.format(tab,3, tab * 3)) print('{} x {:2} = {}'.format(tab,4...
import random def UpAndDown(): num1=random.randrange(0,100) for i in range(0,20): num2=int(input("Try and guess a number between 1~100 : ")) if num1<num2: print "Down" elif num1>num2: print "Up" elif num1==num2: print "You are righ...
""" @author j.Kim @since 160406 """ import random """ This is for Up and down game at wk6 """ def m35(): result = 0 for i in range(1,1000): if i%3 == 0 or i%5==0: result +=i return result def a(): year = float(input("year:")) if(year%4==0)and(year%100!=0 ...
''' Created on Sep 25, 2015 @author: gaurav ''' from Smoothing.Perplexity import getUnigramPerplexity, getBigramPerplexity def classifyBooksWithUnigram(): ''' Find the perplexities of the test books using the bigram model and classify the book into the respective genres using these value ''' ...
# Given the participants' score sheet for your University Sports Day, # you are required to find the runner-up score. You are given N scores. # Store them in a list and find the score of the runner-up. # The first line contains N. The second line contains an array A[] of integers each separated by a space. # Print the ...
import math import os import random import re import sys # # Complete the 'stringAnagram' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. STRING_ARRAY dictionary # 2. STRING_ARRAY query # def stringAnagram(dictionary, query): # Write y...
import string import random import time import sqlite3 import hashlib, binascii import os #variables chars = string.ascii_letters + string.digits salt = string.punctuation word = '' hase = '' #directory change os.chdir('random-g') #change here #sqilite database lol conn = sqlite3.connect('ranwords...
# Week 2 - Files # This script provides two simple examples of writing and reading files # This block will open a file that already exists and write 500 # random numbers file_loc = "C:\\DSA_OU\\boomerNumbers.txt" import random f = open(file_loc, 'w') for count in range(500): number = random.randint(1,...
import decimal import visualiser as vis import random def hillclimber (self, results): """ This is the algorithm used for a hillclimber on a random configuration """ # initialize the values total_distance = results[0] connections = results[1] distances_total = dict() key = 1 # Hill...
class Battery(object): """ Representation of a battery in SmartGrid """ def __init__(self, id, name, capacity, price): """ Initiazes a Battery """ self.id = id self.name = name self.price = price self.capacity = capacity self.currentCapaci...
""" This module contains the `Hat` class. The class takes a variable number of arguments that specify the number of balls of each color that are in the hat. For example, a class object could be created in any of these ways: ```python hat1 = Hat(yellow=3, blue=2, green=6) hat2 = Hat(red=5, orange=4) hat3 = Hat(red=5, o...
class Screen(object): # __slots__ = ('width','height') 好像不能再定义 #用property装饰器来定义 setter函数,等同于建立一个获取属性的方法 @property def width(self): return self._width @width.setter def width(self,w): self._width = w @property def height(self): return self._height @...
# n1 = int(input('Entre com um número: ')) # if n1 > 10: # print('Este número é maior que 10!') # elif n1 >= 1: # print('Este número é menor que 10!') # elif n1 < 1: # print('Você digitou um número menor que 1!') # else: # print('Fim') # for c in range(1, 1001, 98): # print(c +1) # print('FIM!') #...
#imports import numpy as np import pandas as pd #using Numpy a = np.array([1,2,3,4,5,6,7,8]) #this will print out elements of a that are > 4 print(a[a>4]) #print(a) #should print out the array. print(a.dtype) items = [1,2,3,4,5] def inc(x): return x+1 list(map(inc,items)) #print(items) #using Pandas #here, I will ...
# Given a binary tree, return the preorder traversal of its nodes' values. # # Example # Example 1: # # Input:{1,2,3} # Output:[1,2,3] # Explanation: # 1 # / \ # 2 3 # it will be serialized {1,2,3} # Preorder traversal # Example 2: # # Input:{1,#,2,3} # Output:[1,2,3] # Explanation: # 1 # \ # 2 # / # 3 # it...
# Given a binary tree, return all root-to-leaf paths. # # Example # Example 1: # # Input:{1,2,3,#,5} # Output:["1->2->5","1->3"] # Explanation: # 1 # / \ # 2 3 # \ # 5 # Example 2: # # Input:{1,2} # Output:["1->2"] # Explanation: # 1 # / # 2 """ Definition of TreeNode: class TreeNode: def __init__...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 18:13:50 2020 @author: master Walled In A turtle bounces around the screen 5 times using the same function from bounceTurt.py Another turtle draws a line behind it, which turns into a wall. isCollision to detect interactions. HOW TO USE THIS...
import pygame class Button: name = "" # rect (top left corner), (width, height) rect = pygame.Rect((10, 10), (50, 20)) color = (255, 255, 255) def notify(self): for i in self.listeners: i.get_event(self.name) def __init__(self, name, rect, color): self.name = name...
#How are all leaves of a binary search tree printed?# #Given a BST print all the leaf nodes from left to right (all the leaf nodes) class node: def __init__(self, data): self.data = data self.left = None self.right = None def PrintLeafnodes(root: node) -> None: if(not root): ...
import numpy as np def cal_cost(theta,X,y): ''' Calculates the cost function given X and Y. x = Row of x's np.zeros((2,j)) y = Actual y's np.zeros((2,1)) where: j is the no of features ''' m = len(y) predictions = X.dot(theta) cost = (1/2*m)* np.sum(np.square(predictions=y)) return cost
def is_even(numb): # return False if numb%2 else True return numb%2 == 0 def test_is_even(): assert is_even(2) == True assert is_even(3) == False assert is_even(80) == True print('Even is correct') test_is_even() def string_lenght(string): return len(string) print(string_lenght('hellop')) def last_letter(st...
def reverse(lst): empty_list = list() # use this! for item in lst: empty_list.insert(0,item) return empty_list assert reverse(list([1,None,14,"two"])) == ["two",14,None,1]
import pandas as pd ### ways of reading different types of files df = pd.read_csv('../../pandas-master/pokemon_data.csv') df_xlsx = pd.read_excel('../../pandas-master/pokemon_data.xlsx') df_txt = pd.read_csv('../../pandas-master/pokemon_data.txt', delimiter='\t') ### show only 5 rows # print(df_txt.head(3)) ### re...
def zero(oper=''): return 0 if oper=='' else operation(0, oper) def one(oper=''): return 1 if oper=='' else operation(1, oper) def two(oper=''): return 2 if oper=='' else operation(2, oper) def three(oper=''): return 3 if oper=='' else operation(3, oper) def four(oper=''): return 4 if oper=='' else operation(4, oper) d...
# solution("camelCasing") == "camel Casing" def solution(s): #transform to array sol = list(s) length = len(sol) i = 0 #finding the breaking point while i <= length-1: if sol[i].isupper() and sol[i-1] != ' ': break_point = i sol.insert(break_point, ' ') length = len(sol) i+=2 ...
# matplotlib是绘图库 # 功能:生产可发布的、可视化内容,如折线图、直方图、散点图 import matplotlib.pyplot as plt import numpy as np # 在-10和10之间生成一个数列,共100个数 x = np.linspace(-10,10,100) # 用正弦函数创建第二个数组 y = np.sin(x) # plot函数绘制一个数组关于另一个数组的折线图 plt.plot(x,y,marker="x") plt.show()
# NumPy是Python科学计算的基础包 # 功能:多维数组、高等数学函数(线性代数、傅里叶变换)、伪随机数生成器 # NumPy核心功能:ndarray类,即多维数组。(多维数组的所有元素必须是同一类型) # scikit-learn用到的所有数据必须转成NumPy数组。 import numpy as np x = np.array([[1,2,3],[4,5,6]]) print("x:\n{}".format(x))
#Counting Sort def counting_sort(A): m = max(A) count = [0] * (m+1) for x in A: count[x] += 1 A=[] for i in range(m+1): A += [i] * count[i] return A input_str = input('Enter "non negetive"!!! numbers (Use Comma to separate the numbers)\nExample: 9,5,6,44,50\nNumbers: ') inpu...
class BankAccount: Allinstances = [] def __init__ (self, balance = 0.0, int_rate = 0.01): self.balance = balance self.int_rate = int_rate BankAccount.Allinstances.append(self) def deposit(self, amount): self.balance += amount return self def withdraw(self, am...
import numpy as np from random import shuffle def softmax(x): """Compute softmax values for each sets of scores in x.""" return np.exp(x) / np.sum(np.exp(x) , axis = -1 , keepdims = True) def get_one_hot(targets, nb_classes): res = np.eye(nb_classes)[np.array(targets).reshape(-1)] return res.reshape(l...
#!/usr/bin/env python3 from sklearn import tree from sklearn.datasets import load_iris from utils import exportDecisionTree def main(): # 1. Minimal dataset # Create a tree classifier with a very simple dataset. A classifier stores # the results into different classes. In this example, the data is an a...
def compare(x,y): if x > y: return 1 if x < y: return -1 else: return 0 def is_between(x,y,z): if x <= y and y <=z: print 'ok' else: print 'not ok'
def histogram(word): d=dict() for letter in word: d[letter]=d.get(letter,0)+1 return d
# function to check whether the given two strings are anagrams def is_anagram(word1,word2): if len(word1)!=len(word2): # if words are of different length return false return False else: # if words are of same length convert the string into lists and sort them in ascending order word_a=lis...
from point1 import * import math import copy def distance_between_points(p1,p2): '''To calculate the distance between 2 points''' distance = math.sqrt(((p1.x - p2.x)**2) + ((p1.y - p2.y)**2)) return distance def move_rectangle(rect,dx,dy): '''To move the rectangle by its corner''' new_rect = copy....
# Program for scanning a wordlist and returning the most frequently used lettersin descending order import operator # Defining a function for accepting a word & returning a list of tuples with letters used and its frequency def most_frequent(wrd): d={} for letter in wrd: d[letter] = d.get(letter,0)+1 letter_fre...
# Binary search # Creating the sorted word list wordlist =sorted([x.strip() for x in open('/home/dheeraj/repos/think-python/words.txt')]) # Function for binary search def binary(word): # first = 1st index in the list..initially 0 first = 0 # last = last index in the list..initially len(list) last = len(wordlist...
def inverse_dict(d): inverse=dict() for key in d: value=d[key] inverse.setdefault(value,[]).append(key) return inverse print(inverse_dict({'a':1,'b':1,'c':2}))
# https://www.codewars.com/kata/530e15517bc88ac656000716 def rot13(message): output = '' for c in message: if not c.isalpha(): output += c continue # Nth alphabet (lowercase) alphabet_n = ord(c.lower()) - ord('a') # == 26 alphabet_count = ord('...
def datacollect(mathmode): modus=mathmode value1 = input("Please enter the first number of your {} ".format(modus)) value2 = input("Please enter the second number of the calculation ") return value1, value2 def addition(value1,value2): added = int(value1) + int(value2) return added def subtracti...
import turtle, random turtle.bgcolor("black") benny = turtle.Turtle() colors = ["red","green","blue","orange","purple","pink","yellow","purple","blue"] #List of colors benny.width(1) benny.hideturtle() for i in range(250): color = random.choice(colors) benny.circle(25+i*2.5) benny.forward(-i) benny.lef...
def test_recipe(food_1, food_2): foodcombo=("{} with {}".format(food_1,food_2)) return foodcombo food1=input("Please input a food ") food2=input("please input a side ") dishname=test_recipe(food1,food2) print("Today the restuarant is serving {}.".format(dishname))
list = [] def countbetween(start,end,step): for i in range(start,(end+step),step): list.append(i) return list print("This program will help you count!") num1=int(input("Where should we start? ")) numn=int(input("When should we stop? ")) print("Ok!") if num1<numn: counting=countbetween(num1,numn,1) ...
#This is most basic and simplesr ,use of matplotlib #W import matplotlib as my_plt for easy reference from matplotlib import pyplot as my_plt #Here we are manually feeding data for x and Y a #my_plt.plot([1,2,3,4,5],[1,3,5,7,9],) #Here we add lables (that tell us what are values of X and Y ) to x and y axi...
# -*- coding: utf-8 -*- """ Created on Sun Apr 16 17:05:37 2017 @author: KingDash """ Error="N" try: x=int(input('Enter an integer:')) except ValueError: print('invalid entry') Error="Y" except NameError: print('undefined entry') Error="Y" if Error=="N": if x<0: y...
# Code To convert Hinglish text to Hindi. consonant=['b','c','C','d','D','f','g','h','j','k',\ 'l','m','n','N','p','q','r','R','s','S','t','T','v','w','x','y','z'] vowels=['a', 'e', 'i', 'o', 'u'] def dumb_seg(g): listee=[] pntr=0 for x in g: if(x in consonant or pntr==0): pntr+=1; ...
raw_input("Enter a word:") original = raw_input() if len(original) > 0 and original.isalpha(): #isalpha() checks if the string contains non-letter characters word = original.lower() first = word[0] print original else: print "empty" hobbies = [] for i in range(3): hobby = str(raw_input("Your ...
import sys def binary_search(target, low, high): if target > high: print "too big dude!" elif target < low: print "too small dude! ;p" else: if low > high: return False else: mid = (low+high)//2 if target == mid: return Tru...
def find_unique_character(string: str) -> str: chars = string.lower() size = len(chars) for target_index in range(size): current = chars[target_index] if chars.index(current) == chars.rindex(current): return chars[target_index] return '{} has no unique character'...
import sys #Создайте функцию, принимающую на вход имя, возраст и город проживания человека. Функция должна возвращать строку вида «Василий, 21 год(а), проживает в городе Москва»************************ def person_info(name, age, city): print('{}, {} years old, living in {}'.format(name, age, city)) return '{}, ...
# print print print # In gujarat,India day name be like this :D days = "Somvar Mangalvar Budhvar Gurvar Shukravar Shanivar Ravivar" ''' don't worry its like Somvar = Monday Mangalvar = Tuesday Budhvar = Wednusday Gurvar = Thursday Shukravar = Friday Shanivar = Saturday Ravivar = Sunday note: If you want to lea...
from sklearn import datasets iris = datasets.load_iris() # X = features, y = target_label X = iris.data y = iris.target # Partition the data set using train_test_split from sklearn.model_selection import train_test_split # Here we are saying we will split the X into half and do the same with the y X_train, ...
# 2(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # What is the sum of the digits of the number 2(1000)? def digit_sum(num): sum = 0 while(num > 0): mod = int(num % 10) sum += mod num = num // 10 return sum n = 2 ** 1000 print(digit_sum(n))
import math def simplify(x, y): # Quick and dirty gcf ax, ay = abs(x), abs(y) if ax == 0: return 0, y//ay if ay == 0: return x//ax, 0 for n in range(2, min(ax, ay)+1): if x % n == 0 and y % n == 0: return simplify(x // n, y // n) return x, y def get_line...
def read(): with open("input") as f: a, b, _ = f.read().split("\n") return a.split(","), b.split(",") def dist(p): return abs(p[0]) + abs(p[1]) def make_path(steps): path = {} x = 0 y = 0 i = 1 for step in steps: d = step[0] dist = int(step[1:]) dx, ...
""" This module defines the function that we want to try to learn with NNs. """ import random # The actual functions to learn def f_identity(seq): return seq def f_reverse(seq): t = [0]*len(seq) for j in range(len(seq)): t[len(seq)-j-1] = seq[j] return t def f_swap01(seq): t = [] ...
#getcofreqs.py #USAGE: python getcofreqs [token file] #EXAMPLE: python getcofreqs tokens.txt #The token file must contain one token per line. #_______ import sys win_one_side=int(sys.argv[2]) #How many words on either side of the target? i.e. 5 corresponds to a 11_word window win_both_sides=int(win_one_side) * 2 win_...
import unittest from daily.d6_reverse_linked_list.solution import ListNode, reverse_iterative, reverse_recursive class MyTestCase(unittest.TestCase): def test_iterative(self): head = self._get_test_list() new_head = reverse_iterative(head) self.assertEqual('0 1 2 3 4 ', str(new_head)) ...
""" [Daily Problem] Add two numbers as a linked list You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7...
import database import scraping import testing import visualization prompt = '''Please choose from the following:\n database Reinitializes the database/cache.\n scraping Makes a call to the API and dynamically scrapes stories from BBC.\n testing Runs a few unit tests to ensure the database is initialized p...
def gcd(a,b): if b==0: return a return gcd(b,a%b) def leftRotate(arr,d): n=len(arr) for i in range(0,gcd(n,d)): t=arr[i] j=i while True: k=j+d if k>=n: k=k-n if k==i: break arr[j]=arr[k] ...
words=s.split(' ') res=[] for word in words: r="".join(reversed(word)) res.append(r) re="" for i in res: re=re+str(i)+" " return re.rstrip()
""" (This problem is an interactive problem.) A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't ex...
arr=[-2, -3, 4, -1, -2, 1, 5, -3] max_sum=arr[0] curr_sum=arr[0] for i in range(1,len(arr)): curr_sum=max(curr_sum+arr[i],arr[i]) max_sum=max(max_sum,curr_sum) print(max_sum)
a=[2, 3, 10, 6, 4, 8, 1] max_diff=a[1]-a[0] min_element=a[0] for i in range(1,len(a)): max_diff=max(max_diff,a[i]-min_element) min_element=min(min_element,a[i]) print(max_diff)
# Maria Ali # Machine Learning Assignment 3 # Regression on the Data of monthly experience and income distribution of different employees # Importing the libraries and the dataset for evaluation import matplotlib.pyplot as plt import pandas as pd import numpy as np dataset = pd.read_csv('monthlyexp vs incom.cs...
def sequentialSearch(aList, item): pos = 0 found = False while pos < len(aList) and not found: if aList[pos] == item: found = True else: pos = pos + 1 return found l = [1,2,5,134,23412312,3213,4523,12,3213,123123123123123123,123123123,123123123] print(sequentia...
numero_ganador = 5 numero_usuario = int(input("Adivine el numero(1-10): ")) if numero_usuario == numero_ganador: print("¡Has ganado!") else: print("Has perdido, el número ganador era {} y has escogido el número {}".format(numero_ganador, numero_usuario))
agenda = dict() confirmacion = False while True: accion = input("Que desea hacer? (Añadir[A] / Consultar[C] / Salir[S]) ") if accion.upper() == "A": print("Se añadirá un año de nacimiento al sistema.") print("+++++++++++++++++++++++++++++++++++++++++++\n") nombre = input("Nombre: ") ...
lista_numeros = [1, 2, 3, 45, 83, 95, 24, 642, 567, 24] multiplos_dos = [] multiplos_tres = [] multiplos_cinco = [] multiplos_siete = [] print("Lista inicial: {}".format(lista_numeros)) for numero in lista_numeros: if numero % 2 == 0: multiplos_dos.append(numero) if numero % 3 == 0: multiplos_...
# 1 class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def personlnfo(self): print(self.name + ' ' + str(self.age), self.sex) class Student(Person): def __init__(self, name, age, sex, college, clas): super().__init__(na...
""" This Example will use Classes with List , Dictionary and Linq expression 1. Empty Check for List or Dictionary 2. Checking Key in Dictionary 3. Dictionary Initialization 4. pass keyword """ """ "pass" keyword (a statement) to indicate that nothing happens—the function, class or loop is empty. ...
# import unit test module of python import unittest from Examples import Example class MyTestCase (unittest.TestCase): #method should be prefixed with keyword 'test' @classmethod #Use annotation @classmethod def setUpClass(cls): print("This will run before all the methods") @classmethod ...
# Tuple is created using circular brackets (), Ordered ,Indexed,unchangeable,duplicates my_tuple = ("Tokyo", "Lisbon", "New York") print ( my_tuple ) # ('Tokyo', 'Lisbon', 'New York') print ( my_tuple[2] ) # New York print ( my_tuple[-1] ) # New York print ( my_tuple[0:2] ) # ('Tokyo', 'Lisbon') for val in my_tupl...
dict = {} naam = input('enter name: ') while naam != '': if naam in dict: dict[naam] += 1 else: dict[naam] = 1 naam = input('enter name: ') for naam,value in dict.items(): if value == 1: print('Er is {} student met de naam {}'.format(value, naam)) else: print('Er zijn ...
from datetime import datetime as dt # import date time Module t1=input('enter date in HH:MM:SS:') t2=input('enter date in HH:MM:SS:') format= "%H:%M:%S" # format Time def timedifference(time1, time2): try: t1 = dt .strptime(time2,format)-dt.strptime(time1, format) retu...
#interest calculation money=int(input('enter principal amount:')) rate=float(input('enter the rate of interst per 100:')) time=int(input('enter time period in months:')) interest=money*rate*time/100 # formula=P*T*R/100; P= Principal Amount, T=TimePeriod, R=Rate Of Interest print('interest amount',interest,'\n'...
class Solution: def two_sum_sorted(self, numbers, target): left = 0 right = len(numbers) - 1 while left < right: result = numbers[left] + numbers[right] if result == target: return [left + 1, right + 1] elif result < target: ...
from BST import Searchtree from Intervaltree import Intervaltree __author__ = 'Ward Schodts en Robin Goots' class Algo1(object): circle_list = list() intersection_list = list() def __init__(self, circle_list): self.circle_list = circle_list def execute(self): """ Voer het a...
from random import random from Cirkel import Cirkel def generate_cirkels(amount, radius = 1): cirkels = list() for a in range(amount): cirkels.append(Cirkel(1*random(), 1*random(), 1*random())) return cirkels def write_to_file(cirkels): with open('input.txt', 'w') as f: f.write("3...
# def operation(b, a, op): # if op == '+': # return int(a) + int(b) # if op == '-': # return int(a) - int(b) # if op == '*': # return int(a) * int(b) # else: # return int(int(a) // int(b)) def evalRPN(A): polish_list = [] for op in A: # if op not in ['+'...
from collections import deque from binarytree import bst, heap from queue import LifoQueue import sys class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @return an integer def minDepth(self, A): ...
def compare(num, aDeviner, nbEssais): if num < aDeviner: print("plus") return(0) elif num > aDeviner: print("moins") return(0) else: print("Il vous a falu", nbEssais, "coups") return(1) aDeviner = int(input("Entrez un nombre entre 1 et 100\n")) nbEssais = 1 num = 101 a = 0 while a != 1: num = int(inpu...
''' def tri(tab): tabtrie=[] ind=-1 for i in range(len(tab)): min=tab[0] for j in range(len(tab)): if min<tab[j] and j!=ind: min=tab[j] ind=j tabtrie[i]=min return tabtrie ''' def select_tri(tab): min=tab[0] for j in range(len(tab)): if min>tab[j]: ...
"""Задание на execute_script В данной задаче вам нужно будет снова преодолеть капчу для роботов и справиться с ужасным и огромным футером, который дизайнер всё никак не успевает переделать. Вам потребуется написать код, чтобы: Открыть страницу http://SunInJuly.github.io/execute_script.html. Считать значение для перемен...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 6 19:46:36 2018 @author: dinesh """ import math as mat # the input for 'radians' function is degrees def app(x): x = mat.radians(x) num = (16*(mat.pi-float(x)))*float(x) denom = (5*(mat.pi)**2)-((4*(mat.pi-float(x)))*float(x)) ret...
enter='Enter your CA grade for week ', ' <A/B/C/D/F/X/LOA> : ','A - 4.0, B - 3.0, C - 2.0, D - 1.0, F - 0.0, X - 0.0, LOA - Not counted towards average total' wk01 = raw_input(enter[0] + '1' + enter[1]) wk02 = raw_input(enter[0] + '2' + enter[1]) wk03 = raw_input(enter[0] + '3' + enter[1]) wk04 = raw_input(enter[0...
def power(x,y): result=1 i=0 while i<y: result=result*x i=i+1 return result def fact(n): i=1 fact = 1 while i <= n: fact=fact*i i=i+1 return fact list=[] sum=0 i=0 while i == 0: if i == 0: n=input('input n: ') r=...
joinedCodeList = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm' codeList = list(joinedCodeList) pointList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26] pointList = pointList + pointList i=0 while i == 0: rawMsg = raw_input('Type in the word or q to exit: ') if rawMsg =...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Lesson 3.2: Use Functions # Mini-Project: Secret Message # Your friend has hidden your keys! To find out where they are, # you have to remove all numbers from the files in a folder # called prank. But this will be so tedious to do! # Get Python to do it for you! # Use ...
""" matrix transform with successive blocks of columns """ def matrixElementsSum(matrix): def matrix_transform(matrix): idx_blk = [] for i in range(0, len(matrix)): for j in range(0, len(matrix[0])): #print(matrix[i][j]) if matrix[i][j] == 0: idx_blk.append(j) if j in idx_blk: matrix[i][j]...
""" ThreeLetters Given two integers A and B, return a string which contains A letters "a" and B letters "b" with no three consecutive letters being the same. """ def threeletters(A,B): str = [] while A > 0 and B > 0: return "".join(str) if __name__ == "__main__": def test(value, expect): test = firstunique...