text
stringlengths
37
1.41M
#José Everton da Silva Filho #AdS - P1 - Unifip - Patos/PB ##### #6. Escreva um programa que leia um valor inteiro e calcule o seu quadrado. valor_inteiro = int(input('Digite o valor inteiro a ser calculado: ')) valor_quadrado = int(valor_inteiro ** 2) print(f'O quadrado de {valor_inteiro} é {valor_quadrado}.')
#José Everton da Silva Filho #Exercício 02 - AdS - P1 - Unifip - Patos/PB ##### # 6 - Faça um Programa que leia três números e mostre o maior deles. n1 = float(input('Digite um número: ')) n2 = float(input('Digite outro número: ')) n3 = float(input('Pra finalizar, digite mais um número: ')) if n1 == n2 == n3: print...
#José Everton da Silva Filho #Exercício 04 - AdS - P1 - Unifip - Patos/PB ##### ''' 1 - As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes. Faça um programa que recebe o salário de um colaborador e o reajuste segund...
# José Everton da Silva Filho # Exercício 04 - AdS - P1 - Unifip - Patos/PB ##### ''' 10 - Faça um Programa para leitura de três notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e presentar: - A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada; - A...
exclamation = input("enter exclamation: ") adverb= input("enter adverb: ") noun=input("enter a noun: ") adjective=input("enter an adjective: ") #story output=f"{exclamation}! he said {adverb} as he jumped into his convertible {noun} and drove off with his {adjective} wife." print(output)
import emoji def start(): print("\nYou are standing in a dark room.") print("There is a door to your left and right, which one do you take?") input1=input("type ('l' or 'left') or ('r' or 'right')\n>>>").lower() if (input1=="l" or input1=="left"): bear_room() elif(input1=="r" or input...
from timeit import default_timer as timer n = 200 mem = [[-1 for j in range(n + 2)] for i in range(n + 2)] # list of lists that will set -1 n+2 times on n + 2 lists # first dimension is height, second is how many bricks i have left apparently def custom_mem(height, left): global mem if mem[height][left] != ...
# -*- coding: utf-8 -*- # !/usr/bin/env python # @File : 元组.py # @Author: 杨崇 # @Date : 2019/1/10 # @Desc : 元组 # 定义一个元组 # tu = ('jack', 12, ['张三', '李四']) # print(tu) # print(type(tu)) # print(tu[0: 2]) # print(tu[1:]) # print(len(tu)) # print(tu.index('jack')) # # if 'jack' in tu: # print('存在') # count = len(tu)...
# -*- coding: utf-8 -*- # !/usr/bin/env python # @File : dd.py # @Author: 杨崇 # @Date : 2019/1/6 # @Desc : null # # name = "小明" # age = None # sex = "男" # height = 180.5 # weight = 75.5 # isDetele = True # print(name, age, sex, height, weight) # # print(type(name)) # print(type(isDetele)) # print(type(height)) # prin...
# -*- coding: utf-8 -*- # !/usr/bin/env python # @File : work.py # @Author: 杨崇 # @Date : 2019/1/12 # @Desc : null # 1.完成下列操作 list1 = ['xiaoming', 'xiaohua', 'xiaohong'] # (1)循环遍历出列表的所有元素 count = len(list1) for i in range(0, count): print(list1[i]) # (2)把列表list2[“jack”,”marry”,”tom”]中的每个元素逐一添加到list列表中 list2 = [...
#!/bin/python3 import sys def isMatchingpair(a, b): if a =='(' and b == ')': return 'YES' if a =='{' and b == '}': return 'YES' if a =='[' and b == ']': return 'YES' return 'NO' def isBalanced(s): ''' :type s: str :rtype: bool ''' opening = set(['(', '{','[']) closing = set([')','}',']']) stack = []...
#!/bin/python3 import sys def roadsAndLibraries(n, c_lib, c_road, cities): # Complete this function if __name__ == "__main__": q = int(input().strip()) for a0 in range(q): n, m, c_lib, c_road = input().strip().split(' ') n, m, c_lib, c_road = [int(n), int(m), int(c_lib), int(c_road)] cities = [] for citie...
# **************************************************************************** # # # # ::: :::::::: # # 03b.Inorder_Traversal.py :+: :+: :+: ...
# **************************************************************************** # # # # ::: :::::::: # # 01b.Preorder_Traversal.py :+: :+: :+: ...
#!/bin/python3 import sys def shortPalindrome(s): # Complete this function n = len(s) count = 0 for i in range(n-3): for j in range(i+1, n-2): for k in range(j+1, n-1): if s[j] == s[k]: count += s[k+1:].count(s[i]) return count % (10**9 + 7) if __name__ == "__main__": # s = input().strip() # s =...
string=raw_input("") for i in string: if (i=='a' or i=='e' or i=='i' or i=='o' or i=='u'): print("Vowel") else: print("Consonant")
def F(n,m): fib=[1, 1] for i in range (2, n+1): # print(fib) if i > m: fib.append(fib[i-1]+fib[i-2]-fib[i-m-1]) elif i == m: fib.append(fib[i-1]+fib[i-2] - 1) else: fib.append(fib[i-1]+fib[i-2]) return fib[n-1] # print(F(5, 3)) 3 for i i...
with open ('input.txt') as f: for line in f: line = line.strip().strip() m = 0 if m < int(line[1]): m = int(line[1]) return m
def F(n): if n==0 or n==1: return n else: return F(n-1) + F(n-2)
def F(string): string = list(string) alph = 'abcdefghijklmnopqrstuvwxyz' vow = 'aeiouy' postvow = 'bfjpvz' for letter in range(len(string)): if string[letter] in vow: string[letter] = postvow[vow.find(string[letter])] elif string[letter] in alph: string[lette...
def ejercicio01(): #definir variables print("Ejemplo Esctructura Condicional 01") montoP=0 #datons de entrada cantidadx=int(input("Ingrese Cantidad de Lapices")) #proceso >condicional if cantidadx>=1000: montoP=cantidadx*0.80 else: montoP=cantidadx*0.90 #datos de salida print("El Monto a Pag...
#definir variables print("Ejercicio 16") #datos de entrada salario= 950 puntosP=int(input("Ingrese sus puntos obtenidos:")) if puntosP >=0 and puntosP <=100 : premio = salario elif puntosP >= 101 and puntosP <=150 : premio = salario * 2 elif puntosP >=151 : premio = salario * 3 print("El bono que le corresponde ...
#!/usr/bin/python3 # Listedeki duplike elemanların count'larıyla bir dict oluşturma örneği from collections import Counter if __name__ == '__main__': L = [ ]; for _ in range(int(input())): string_input = input(); L.append( string_input ); #dictOfWords = { i : L.count(i) for i in L }...
# 6) Задан целочисленный массив. Определить количество участков массива, # на котором элементы монотонно возрастают (каждое следующее число # больше предыдущего) import random lst = [random.randint(0, 20) for el in range(10)] print(lst) result=0 count=0 for j in range(len(lst)-2): if lst[j+2] > lst[j+1] > lst[j]: ...
""" This module could be used to automate creation and modification of Excel sheets specifically is useful when you are dealing with Working functions: - updating values of specific column in all sheet - updating column titles of all the sheets - Creating Excel sheet/s with its column headers """ import o...
# Autor: Humberto Carrillo Gómez, A01377246 # Descripcion: Este proglama calcula el porcentaje de hombres y mujeres inscritos en una clase. # Escribe tu programa después de esta línea. m=int(input("Teclea el número de mujeres inscritas: ")) h=int(input("Teclea el número de hombres inscritos: ")) numeroTotal= m+h por...
just_try = "{} {} {} {}" print(just_try.format(1,2,3,4)) print(just_try.format("one","two","three","four")) print(just_try.format(1,1,1,1)) print(just_try.format(just_try,just_try,just_try,just_try)) print(just_try.format( "Try your", "Own text here", "Maybe a poem", "Or a song about fear" )...
#!/usr/bin/env python import sys @outputSchema('variance:double') # fuction returns standard deviation and this should be double, float type may lead to some problems def finding_variance(x): # x is a bag of pig, i.e., list of tuples, in our case all tuples have one components sum=0 num=0 for tuple_...
# 3. zadanie: zarovnaj # autor: Matúš Gál # datum: 15.11.2017 def vypis(meno_suboru, sirka): with open(meno_suboru, encoding='utf-8') as f: # subor treba otvorit cez with, inak testovac vypise chybu words = f.read().split('\n') # precita cely subor po znakoc...
number1 = (input("What is your width?")) print("Your width is " + number1) number2 = (input("What is your length?")) print("Your length is " + number2) area = (int(number1) * int(number2)) print("The area is " + str(area))
#! /usr/bin/env python3 import json import sys import pandas as pd import json def count_contractions(pressure_data): """ Count the number of contractions for a pressure curve :param pressure_data: a list of pressure points :return: The total number of contractions """ # FIXME count=0 ...
def gen(i): print('mid:',i) yield 'this is yielded.' for j in range(i): print('i:',i,',j:',j) yield j*'*' yield 'end' ia = gen(5) print('-------------') for i in ia: print ('i:',i) for i in ia: print ('i:',i)
''' 可以发现:python的类变量和C++的静态变量不同,并不是由类的所有对象共享。 类本身拥有自己的类变量(保存在内存),当一个TestClass类的对象被构造时, 会将当前类变量拷贝一份给这个对象,当前类变量的值是多少,这个对象拷贝得到的类变量的值就是多少; 而且,通过对象来修改类变量,并不会影响其他对象的类变量的值,因为大家都有各自的副本, 更不会影响类本身所拥有的那个类变量的值;只有类自己才能改变类本身拥有的类变量的值。 类变量定义后 ,通过类变量方式引用和通过实例变量方式引用的是两个变量,只是名字相同而已 ''' class TestClass(object): val1 = 100 def __i...
''' 问题: Python的函数定义中有两种特殊的情况,即出现*,**的形式。 如:def myfun1(username, *keys)或def myfun2(username, **keys)等。 解释: * 用来传递任意个无名字参数,这些参数会一个Tuple的形式访问。 **用来处理传递任意个有名字的参数,这些参数用dict来访问。* 应用: ######################### # “*” 的应用 ######################### ''' def fun1(*keys): print ("keys type=%s" % typ...
str=input() if str.find('f')==-1: print('-2') if str.find('f')!=-1: a=str.find('f') s=str[a+1:len(str)+1] if s.find('f')!=-1: print (s.find('f')+a+1) else: print('-1')
i=1 while i<10: if i%8 == 0: print ("{0} here is 8".format (i)) break if i%2 == 0: print ("{0} - even".format (i)) i+=1 continue print ("insert 1") elif i%2 == 1: print ("{0} - odd".format (i)) i+=1 continue print(...
size = int(input()) #получаем размеры матрицы = количество строк, которые нужно обработать k = 0 #заводим счетчик стпеней otvet = [] #заводим список, куда будем складывать значения степеней while size > 0: #пока еще остаются вершины, которые нужно обработать row = list(map(int, input().split())) #получа...
m = int(input()) max = m while m!=0: if m>max: max = m m = int(input()) print (max)
# -*- coding: utf-8 -*- __author__ = 'fuhao' ''' * User: fuhao * Date: 13-2-28 : 下午4:33 ''' # 函数通过def关键字定义。def关键字后跟一个函数的 标识符 名称,然后跟一对圆括号。 # 圆括号之中可以包括一些变量名,该行以冒号结尾。接下来是一块语句,它们是函数体 def sayHello(): print 'Hello World!' # block belonging to the function sayHello() # call the function # 带参数的函数 def printMax(a, b):...
# -*- coding: utf-8 -*- __author__ = 'fuhao' ''' * Created with PyCharm. * User: fuhao * Date: 14-5-5 * Time: 下午3:32 * To change this template use File | Settings | File Templates. ''' import types class Student(object): @property def score(self): return self._score @score.setter def sco...
#%% ## Getting Started #In this lab, you will see how decision trees work by implementing a decision tree in sklearn. #We'll start by loading the dataset and displaying some of its rows. #%% # Import libraries import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree ...
#metaclass是类的模板,所以必须从‘type’类型派生 class ListMetaclass(type): def __new__(cls,name,bases,attrs): attrs['add']=lambda self,value:self.append(value) return type.__new__(cls,name,bases,attrs) class MyList(list,metaclass=ListMetaclass): pass
#4-2.py import math #利用栈实现大整数加法 #栈的实现 #主函数入口 if __name__=="__main__": #输入两个加数 add1 = input("请输入第一个加数:") add2 = input("请输入第二个加数:") #建立建立加数栈1、加数栈2和结果栈 add1List = [] add2List = [] result = [] #加数1和加数2按照由高位到低位分别入栈 for s in add1: add1List.append(ord(s)-ord('0')) for s in add...
class Student(object): #def __init__(self,name,score): # self.__name =name # self.__score=score def print_score(self): print('%s :%s' %(self.__name,self.__score)) def get_name(self): return self.__name def get_score(self): return self....
def BinSearch (arr, left, right, x_pos): # check that arguments are correct if right >= left: mid = left + (right - left)//2 if arr[mid] == x: return mid # If smaller than mid, go to left array part elif arr[mid] > x: return BinSe...
import pygame, sys, random from pygame.locals import * # Initialize the game engine pygame.init() # Set FPS fps = 30 fps_clock = pygame.time.Clock() # Constants SCREEN_WIDTH = 600 SCREEN_HEIGHT = 400 BALL_RADIUS = 20 BALL_VELOCITY_INCREMENT = 1.3 GUTTER_SCREEN_WIDTH = 1 PAD_WIDTH = 8 PAD_HEIGHT = 80 PAD_SPEED = 10 H...
r""" Quadrature methods, or numerical integration, is broad class of algorithm for performing integration of any function :math:`g` that are defined without requiring an analytical definition. In the scope of ``chaospy`` we limit this scope to focus on methods that can be reduced to the following approximation: .. mat...
""" Evaluate three terms recurrence coefficients (TTR). Example usage ------------- Define a simple distribution and data:: >>> class Exponential(chaospy.Dist): ... def _ttr(self, k_data, alpha): return (2*k_data+1)/alpha, (k_data/alpha)**2 >>> dist = Exponential(alpha=2.) >>> k_data = numpy.arra...
""" Function for changing polynomial array's shape. """ import numpy from chaospy.poly.base import Poly def flatten(vari): """ Flatten a shapeable quantity. Args: vari (chaospy.poly.base.Poly, numpy.ndarray): Shapeable input quantity. Returns: (chaospy.poly.base.Poly, nu...
""" Evaluate distribution bounds: The location where it is reasonable to define the distribution density is located between. Example usage ------------- Define a simple distribution and data:: >>> class Uniform(chaospy.Dist): ... def _bnd(self, x_data, lo, up): return lo, up >>> dist = Uniform(lo=1, ...
""" Python 2020-2021 Assignment 06 """ def read_file_to_dict(input_file): """ Read in the contents of the input file in such a way that you can retrieve the contents of columns 2, 3, and 4 by the (unique) values in column 1. """ dct = {} with open(input_file) as f: for...
#input--> berfungsi untuk menerima baris input dari user dan mengembalikan dalam bentuk string #int--> berfungsi untuk menkonversi bilangan maupun string angka menjadi bilangan bulat a=int(input("masukan nilai A: ")) b=int(input("masukan nilai B: ")) a +=3 print(a) b -=10 print(b) a *=4 print(a) b *...
#레벤슈타인 거리 구하기 def calc_distance(a, b): """레벤슈타인 거리 계산하기""" if a == b : return 0 a_len = len(a) b_len = len(b) if a == "" : return b_len if b == "" : return a_len #2차원 표 생성 및 초기화 matrix = [[] for i in range(a_len + 1)] for i in range(a_len + 1): matrix[i] = [0 for j in range(b_len + 1)] for i in...
numbers = [1, 1, 1, 1, 1] new_numbers = [2, 2, 2, 3, 3] print(numbers + new_numbers) print(numbers * 5)
import re string = "My name is jonarth. Hi I am jonarth." pattern = r"jonarth" newstring = re.sub(pattern, "prabhu", string) print(newstring)
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if (head == None): ...
# encoding = utf-8 class ShortInputException(Exception): '''一个由用户定义的异常类''' def __init__(self,length,atlest): Exception.__init__(self) self.length = length self.atleast = atlest try: text = input("enter something") if len(text)<3: raise ShortInputExceptio...
#!/usr/bin/python #coding:utf8 def NumberSequence(number): base = 2 while (number - base * (base + 1) / 2) >= 0 : if (number - base * (base + 1) / 2) % base == 0: start = (number - base * (base + 1) / 2) / base print range(start + 1, start + base + 1) base += 1 N...
print("S") for i in range(5): for j in range(7): # if(i==0 or i==2 or i==4): # print("*", end="") if(i==1): if(j==0): print("*",end="") # else: # print(" ",end="") elif(i==3): if(j==6): pr...
start=int(input("Enter first number: ")) end=int(input("Enter last number: ")) if(start>end or start<1 or end<1): print("invalid entry") else: flag=0 if(start==1): start+=1 for i in range(start,end+1): for x in range(2,i//2): if(i%x==0): break ...
inp = tuple(input("Enter the numbers separated by space: ").split()) odd = 0 even = 0 for i in inp: if int(i)%2==0: even+=1 else: odd+=1 print("There are {} odd numbers and {} even numbers in the tuple".format(odd, even))
s = input("Enter a String: ") def length(s): l = 0 for i in s: l+=1 return l print("length of {} is {}".format(s,length(s)))
import csv # Ask for a file name. file_name = input("Enter the name of the file: ") # Create the new file out_file = open(file_name + '.csv', 'w', newline='') out_file_writer = csv.writer(out_file) # Writing the header row out_file_writer.writerow(['Injection', 'Protein(uM)', 'amt to add(uL)', 'total volume(...
a=input("What is your name?") print(a) b=input("What is your age?") print(b) c=input("What is your hobby?") print(c) d=input("What is your branch ?") print(d) e=input("What is your clg name?") print(e) f=input("Where do you live?") print(f) intro=""" my name is{}. i am {} year old. my ...
import webbrowser import os import json class Browser(): """ Browser of all links """ def __init__(self, file): self.file = file self.data = {} def load_links(self): """ Load links from a json file """ if os.path.exists(self.file): with open(self.file) as json_...
print("Answer the following algebra question: ") ques={ "If x=8 then what is value of 4(x+3) ?" : [35,36,40,44], "Jack scored these marks in 5 math tests 49, 81, 72, 66 and 52. What is the mean ?" : [55,65,75,85], } ans={ "If x=8 then what is value of 4(x+3) ?": 4, "Jack scored these marks in 5 math tests 49,...
import random n=random.randint(1,10) while True: i=int(input("Đoán xem? ~(˘▾˘~) : ")) if (n-i)<0: print("A little too large ¯\_(ツ)_/¯") print() elif (n-i)>0: print("Too small ლ(ಠ益ಠლ)") print() else: print() print("Nice try (ノ◕ヮ◕)ノ*:・゚✧") ...
from turtle import * speed(0) d=0 for i in range(50): forward(d) left(90) d+=10 mainloop()
favs = ["origin", "steam", "uplay"] print(favs) while True: n=int(input("muon xoa vi tri nao? ")) favs.pop(n) if n >=len(favs): print("ko xoa dc") else: print(favs) break
import random user_points = 0 bot_points = 0 game = True while game: randnum = random.randrange(0, 3) computer = random.choice(["rock", "paper", "scissors"]) print("User Points: {} Computer Points: {}\n\n".format(user_points, bot_points)) user = input("Rock, Paper, Scissors:\nMake a Move:").lower() ...
class Game(object): """ A class is will store single game data """ def __init__(self, word, status, badGuesses, missedLetters, score, progressWord, attempted): """ Parameters ---------- word : str The string for guessing game status : str T...
import time import numpy as np import sys # Creates the delayed printing that exists in the traditional pokemon games def delay_print(s): # print one character at a time # https://stackoverflow.com/questions/9246076/how-to-print-one-character-at-a-time-on-one-line for c in s: sys.stdout.w...
# Create a class from scratch (look it up) that implements a stack. # The class should have the following three functions. # Push(n): puts n on the top of the stack. # Pop(): removes and returns the value on top of the stack. # Peek(): returns but does not remove the value ontop of the stack. # # Examples: # ----------...
"""Problem #1 from DailyCodingProblem.com Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17 """ def sum_integers(lt, k): """Return whether any two numbers from the list add up to k Given ...
def commonCharacterCount(s1, s2): #find intersection(common elements) and put them into a list s = list(set(s1)) sum1 = 0 for i in s: #count the no.of occurances of each char in s1 and s2 and take the min to avoid duplication sum1+=min(s1.count(i),s2.count(i)) return sum1
import socket import ssl PORT = 9750 HOST = socket.gethostbyname(socket.gethostname()) """SSL context for secured connections, we are not using any special certificate loading only the default certificates""" sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) """the bob.crt certificate file and bob.key pri...
def get_key(val): for key, value in myDict.items(): if val == value: return "success" return "key doesn't exist" myDict = {'java':100,'python':20,'c':300, 20:22, 32:42} print(get_key(100)) print(get_key(20)) print(get_key(67))
x = int(input()) y = int(input()) def sub(x,y): c = x - y return c res = sub(x,y) print(res)
##Problem1: PAYING THE MINIMUM def problem1(bal,anInt,monPay): print('MonthBalance Minimum Payment Total Paid Interest') total = 0 month = 0 while month <= 11: mPay = bal * monPay bal -= mPay bal += anInt / 12.0 * bal tota...
fixedPayment1 = 0 bal = int(input("Balance as a polynomial: ")) anInt = int(input("AnnualInterestRate as a decimal: ")) def remain(bal,anInt,fixedPayment1): month = 1 while month <= 12: bal -= fixedPayment1 bal += (anInt/12.0)*bal month += 1 if bal <= 0...
def odd(t1): if len(t1) == 1: print(t1[0]) else: print(t1[0::2]) t1 = input() odd(t1)
def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed ''' a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',...
def rectangle_perimeter(x, y): if x <= 0 or y <= 0: print("Incorrect input!") else: print((x+y)*2) ''' num, num -> num Returns the area of the rectangle with dimensions:width & height >>> rectangle_area(4,5) 20 ''' x = int(input()) y = int(input()) ...
number1 = int(input("Enter the first number: ")) number2 = int(input("Enter the second number: ")) operator = (input("Enter an operator: ")) def choose(): if operator == 'add': print('Result is '+ str(number1 + number2)+',') elif operator == 'subtract': print('Result is '+ str(number1 - number2)+...
def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. '''...
# range 18'den sonrası için hep aynı sonucu verdiği için kısa sürede sonuç # elde etmek adına range'in durduğu noktayı 18 olarak belirledim value_exp = 0 def faktoriyel(i): if i==0: return 1 else: return i * faktoriyel(i-1) for i in range(0,18): value_exp += 1/faktoriyel(i) print("...
# Insertion sort import random rand_list = random.sample(range(1,50,1),10) def insertionSort(arr): for i in range(1,len(arr)): maxVal = arr[i] j = i - 1 while j >= 0 and maxVal < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = maxVal return arr print (rand...
print("practice 01") import datetime x = datetime.datetime.now() print(x) #02 print("practice 02") import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) #03 print("practice 03") import datetime x = datetime.datetime(2020, 5, 17) print(x) #04 print("practice 04...
from turtle import * turtle = Turtle() turtle.color('red') turtle.pensize(4) turtle.shape('turtle') turtle.speed(0) for x in range(5): turtle.forward(50) turtle.left(144) mainloop()
# assigment 11 Armstrong Number sum = 0 a = True while a == True: number = input("Please enter a number: ") if not number.isnumeric(): a = True elif int(number) < 0: a = True else: a = False print(a * "it is an invalid entry. Don't use non-numeric, float, or negative values...
import Node class Huffman: def __init__(self): self.codes = {} self.tree = None def compress(self, text): # this dict will store chars as tree and their frequencies as values frequency = {} # iterate over the user input text and calculate their frequencies for ...
# Attempting first using no resource as help # Getting User input str = input("the string you want to reverse: ") # Method that reversed the input - also added upper - not for any specific reason just looks def uppercase_reverse(text): uppercase = str.upper() return uppercase[::-1] # calling the method and add...
""" Uses multinomial Naive Bayes to train a model Authors: Kenny, Raymond, Rick Date: 5/1/2019 """ from sklearn.metrics import confusion_matrix, accuracy_score from sklearn.naive_bayes import MultinomialNB from collections import Counter class NaiveBayes: def __init__(self): self.clf = MultinomialNB ...
import matplotlib.pyplot as plt import billionaires list_of_billionaire = billionaires.get_billionaires() gender = [] age = [] wealth = [] male = [] female = [] maleTotal = 0 femaleTotal = 0 maleAge = [] femaleAge = [] maleWealth = [] femaleWealth = [] # for i in list_of_billionaire: # gender = i["demographi...
import unittest def binarySearch(array, value): if len(array) == 0: return False middle = int(len(array) / 2) if array[middle] == value: return True if array[middle] > value: return binarySearch(array[:middle], value) if array[middle] < value: return binarySearc...
import unittest class Node: def __init__(self, data, next = None): self.data = data self.next = next class TestNodes(unittest.TestCase): def test_node(self): node = Node(10) self.assertEqual(node.data, 10) node2 = Node(2, node) self.assertEqual(node2.data, 2) self.assertEqual(node2....
def fib(n, memo): if n == 1 or n == 0: return n if n not in memo: memo[n] = fib(n - 1, memo) + fib(n-2, memo) return memo[n] memo = {} for i in range(0, 100): print('fib(', i, '):', fib(i, memo))
# -*- coding: utf-8 -*- import codecs import csv def load_csv_with_legend(fpath): csv = UnicodeReader(open(fpath, 'rb')) legend = cvs.next() rv = [] for row in csv: code = {} for k, v in zip(legend, row): code[k] = v rv.append(code) return rv class UTF8Recoder: ...
# coding: utf-8 """ @File : distance.py @Author : garnet @Time : 2020/10/20 23:36 """ import numpy as np from scipy.optimize import linprog def wasserstein_distance(p, q, D): """ Use linear programming method to calculate Wasserstein distance. `p` and `q` are discrete distribute, `D_{ij}` is the cos...
n= int(input()) val=n%7 if(val==0): print("yes") else: print("no")