text
stringlengths
37
1.41M
# this program demonstrates how a floating-point number is displayed with no formatting amount_due = 5000.0 monthly_payment = amount_due / 12.0 print('the monthly payment is', monthly_payment)
from tkinter import * import sqlite3 def employee(): window = Tk() window.mainloop() def checkemp(): conn = sqlite3.connect("employe.db") c = conn.cursor() c.execute("SELECT username FROM login WHERE username=? AND password=?", (entry_e1.get(), entry_e2.get())) if c.fetchone(): main.d...
def caesarCipher(s): # Write your code here alpha = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' shifted = '2222223333334444445555556666667777777788888899999999' new = '' for w in s: new += shifted[alpha.index(w)] return new if __name__ == '__main__': s = 'ABCD' prin...
def timeConversion(s): t = s.split(':') if s[-2:] == 'PM': if t[0] != '12': t[0] = str(int(t[0]) + 12) else: t[0] = '12' else: if t[0] == '12': t[0] = '00' newtime = ':'.join(t) return str(newtime[:-2]) if __name__ == '__main__': s = ...
#!/usr/bin/python import tkinter as tk from tkinter import * import tkinter.messagebox class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() # create the application myapp = App() # # here are method calls to the window manager class # myapp.master.title("My D...
#SciPy.Optimazeを使う方法 from scipy import optimize, exp def f(x): return x**2-5*x+2 def g(x): return exp(x) def h(x): return f(x)-g(x) optimize.fsolve(h,0) #0近辺から解を探索 #ニュートン法 from math import exp def f(x): return x**2-5*x+2 def g(x): return exp(x) def h(x): return f(x)-g(x) def h_prime(x): re...
#------------------------------------------------------------------------------ # Copyright (c) 2016, The University of Manchester, UK. # # BSD licenced. See LICENCE for details. # # Authors: Robert Haines #------------------------------------------------------------------------------ import numpy as np import pandas ...
from tkinter import * from tkinter.ttk import Combobox root = Tk() root.geometry("500x500") #Valores que terão no combobox, para importar deve seguir a biblioteca acima v=['1', '2', '3', '4', '5'] combo = Combobox(root, values=v) combo.set("select") combo.pack() #Função para pegar valor do combobox def pegarvalor(...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import mpl_toolkits plt.rcParams['font.size'] = 9.0 arr=[] data = pd.read_csv("kc_house_data.csv") data2= pd.read_csv("datafile.csv") data3=pd.read_csv("houseShortage.csv") while(1): print("Choose the parameters to visualize...
# Filename: solver.py # Description: Solves a sudoku puzzle given as a 2D array using a backtracking # algorithm board = [ [0, 0, 0, 2, 6, 0, 7, 0, 1], [6, 8, 0, 0, 7, 0, 0, 9, 0], [1, 9, 0, 0, 0, 4, 5, 0, 0], [8, 2, 0, 1, 0, 0, 0, 4, 0], [0, 0, 4, 6, 0, 2, 9, 0, 0], [0, 5, 0, 0, 0...
numbers = [1,2,3,4,5,6,7,8,9,10] # 1.a for loop example - I want 'n' for each 'n' in numbers my_list = [] for n in numbers: my_list.append(n) print(my_list) # 1.b Comprehension - I want 'n' for each 'n' in numbers my_list = [n for n in numbers] print(my_list) # 2.a for loop example - I want 'n*n'...
import BinarySearchTree as BST bst = BST.BinarySeaarchTree() a = """ 1. Insert 2. Search 3. Delete 4. In-order 5. Pre-Order 6. Post-Order 7. Level-Order""" while True: print(a) choice = int(input('Enter your choice: ')) if choice ==1: dat = input('Enter the data you want to inser...
from Node import Node class LinkedList: """SLL with no tail refrence""" def __init__(self): self.head=None self.count=0 def PushFront(self,data): """Add the element at the beginning of the list""" node = Node(data) node.next=self.head self.head = n...
# Python script for generating a SAT instance for completing a given pair of partial Latin squares # Two partial Latin squares are read from standard input in the following format: # * First line contains the order n and the # of Latin squares k (this script requires k = 2) # * Next line is blank # * Next n lines cont...
#!/usr/bin/env python #funcion def mi_funcion(param1, param2): print param1 print param2 #docstring def otra_funcion(param1, param2): """Esta funcion imprime los dos valores pasados como parametros""" print param1 print param2 mi_funcion("hola",2) otra_funcion(param2 = 2, param1 = "hola") ...
#!/usr/bin/env python # Los threads son un concepto similar a los procesos: tambien # se trata de codigo en ejecucion. Sin embargo los threads se # ejecutan dentro de un proceso, y los threads del proceso # comparten recursos entre si. import threading class MiThread(threading.Thread): def __init__(self, num): ...
#!/usr/bin/env python import urllib, urllib2, cookielib from urllib2 import HTTPBasicAuthHandler try: f = urllib2.urlopen("http://www.python.org") print f.read() f.close() except HTTPError, e: print "Ocurrio un error" print e.code except URLError, e: print "Ocurrio un error" print e.reason...
#!/usr/bin/env python #raw_input: Esta funcion toma como parametro una cadena a usar # como prompt y devuelve una cadena con los caracteres # introducidos por el usuario hasta que pulso la tecla Enter nombre = raw_input("Como te llamas? ") print "Encantado, " + nombre try: edad = raw_input("Cuantos anyos tienes?...
def add(a,b): print "ADDING %d+%d" %(a,b) return a+b def subtract(a,b): print "SUBTRACTING %d - %d"%(a,b) return a-b def multiplying(a,b): print "MULTIPLYING %d * %d" %(a,b) return a*b def divide(a,b): print "DIVIDING %d / %d" %(a,b) return a/b print "Let's do some math with just functions!" age=add(30,5) hei...
#/usr/bin/env python #encoding:utf-8 ''' #5-3 import os def score(): while True: sco = raw_input("Enter a score :") if sco == 'q': quit() else: try: s = int(sco) except ValueError, e: print "Error:",e raw_input("please input again...") else: if s>=90 and s<=100: print "A" ...
#!/usr/bin/ python # encoding:utf-8 ''' #2-4 a = raw_input("Enter something:") b = int(a) print b #2-5 i = 0 while(i<11): print i, i+=1 print "\n" for i in range(11): print i, print '\n' #2-6 a = int(raw_input("Enter your number:\n")) if a>0: print "这是一个正数" else: print "这是一个负数" #2-7 str = str(raw...
''' Argparse is a module that allows for neat and familiar option and argument passing for our python programs. Help functions, and useful for handling a command line ''' import os import sys from argparse import ArgumentParser # def fibFast(n, memo): # if not n in memo: # memo[n] = fibFast(n-1, memo) + ...
from string import Template class MyTemplate(Template): delimiter = '#' def Cart(): cart = [] num = 0 numberItems = int(input("How many items do you want to buy? ")) for x in range(0,numberItems): items = str(input("Enter product's name : ")) prices = float(input("Enter product's...
# SLICING a = "RSEERAG" print(a[0:4:1]) # REVERSE STRING print(a[::-1]) # STRING CONCATENATE strAdd = "Sreerag" + " Pavithran" print(strAdd) #STRING LENGTH strlen = "Sandra" print(len(strlen)) # UPPER AND LOWER CASE loves = "Sreerag Sandra" print(loves.upper()) print(loves.lower()) # BOOLEAN METHOD number = "30" b...
# A brief description of the project # Date and class and name print('04/06/2020') print('CTI-110-P2T1 - Sales Prediction') print('Tia Early') # # Get the projected total sales. total_sales = float(input('Enter the projected sales: ')) # Calculatethe profit as 23 percent of total sales. profit = total_sa...
def trifeca(word): """ Checks whether word contains three consecutive double-letter pairs. word: string returns: bool """ pair_counter = 0 i = 1 while i<len(word): if word[i] == word[i-1]: pair_counter = pair_counter + 1 # pair_counter += 1 i += 1 ...
""" main.py Algorithm Created by Mohd Shoaib Rayeen on 31/07/18. Copyright © 2018 Shoaib Rayeen. All rights reserved. """ def CeilIndex(A, l, r, key): while (r - l > 1): m = l + (r - l)//2 if (A[m] >= key): r = m else: l = m return r ...
import numpy as np import scipy as sp import scipy.linalg as linalg def my_LDA(X, Y): """ Train a LDA classifier from the training set X: training data Y: class labels of training data """ classLabels = np.unique(Y) # different class labels on the dataset classNum = len(classLabels) d...
def countingSort(arr, exp1): n = len(arr) output = [0] * (n) count = [0] * (10) for i in range(0, n): index = int(arr[i]/exp1) count[ (index)%10 ] += 1 for i in range(1,10): count[i] += count[i-1] i = n-1 while i>=0: index = int(arr[i]/exp1) output...
class avlnode(object): def __init__(self, key): self.key = key self.left = None self.right = None self.node = None self.height = -1 self.balance = 0 def insert(root,key,i=0): if key.key <= root.key: if root.left is None: root.lef...
#!/usr/bin/python import argparse def find_max_profit(prices): #start at index 1 max_profit = prices[1]-prices[0] print(max_profit) for i in range(1, len(prices)): #counter for indices to compare for j in range(0, i): #compare prices of stocks at index to previous indices for p...
class Cadastro: def __init__(self): self.lista=[] self.ler() def ler(self): try: arquivo = open('Aulas/Aula23/exercicios/cadastro_atualizado.txt','r') for pessoa in arquivo: pessoa = pessoa.strip().split(';') dic = {'codigo':pess...
# Aula 18 - 03-11-2019 # Festa da HBSIS # 1 - Faça uma função que leia do arquivo cadastro.txt e retorne uma lista com dicionários. # cada linha possui os dados na seguinte posição: codigo, nome, sexo, idade # 2 - Como a entrada da festa é mais barata para mulheres (R$ 15,00) do que para os homens (R$ 35,00) # deve...
# Aula 22 - 09/12/2019 # Class # # 1 - Caracteristica de uma pessoa ? # ###### Atributos ( variaveis ) # nome # idade # telefone # sexo # # 2 - O que a pessoa faz ? # ###### Metodos (função/procedimento) # respira # dorme # corre # bebe # come # multiplica # # 3 - Com a pessoa esta agora ? # ###### Atributos de ...
# Estudos e teste com listas. b = [1,0,0] for x in range(3): print(b[x])
#! /usr/bin/python3 dict1 = {'book1':'pyton','book2':'java','book3':'shell','book3':'perl','book4':8777} new_dict = dict(zip(dict1.values(),dict1.keys())) print(new_dict) #######2nd######### dict1 = {'book1':'pyton','book2':'java','book3':'shell','book3':'perl','book4':8777} print({v: k for k, v in dict1.items()})
#! /usr/bin/python3 n1 = [[10,20],[40],[30,56,25],[10,20],[33],[40]] n2 = [] for i in n1: if i not in n2: n2.append(i) print(n2) #########2nd############ import itertools num = [[10,20],[40],[30,56,25],[10,20],[33],[40]] print('Orginal List', num) num.sort() new_num = list(num for num,_ in itertools.groupby(nu...
#! /usr/bin/python3 x = [10,20,30,40] y = [90,60,40] x[:0] = y print(x) ########2nd########### import itertools x = [10,20,30,40] y = [40,50,60] print(list((x, y))) ##########3rd############ a1= [10,30,40] a2 = [40,50,60] a3 = a1 + a2 print(a3)
#! /usr/bin/python3 t = [1,2,1,2,3,3,4,4,5,6,7,7,6,5,8,9,9,8] s = [] for i in t: if i not in s: s.append(i) print(s) l = [1,2,1,2,3,3,4,4,5,6,7,7,6,5,8,9,9,8] dup_list = [i for n,i in enumerate(l) if i not in l[:n]] print(dup_list) mylist = [1,2,1,2,3,3,4,4,5,6,7,7,6,5,8,9,9,8] cleanlist = [] [cleanlist.append(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from os import * def nome_turma_aluno(lista_turma): contador=1 for i in range(len(lista_turma)): print("ALUNO Nº", contador) lista_turma[i]=input("NOME: ") contador+=1 print("") return def ...
from collections import namedtuple from math import inf class Point(namedtuple('Point', ['x', 'y'])): def __str__(self): return f"({self.x:d}, {self.y:d})" if self.x is not inf and self.y is not inf else "O" class EC: def __init__(self, a, b, n) -> None: """ This class implements the...
def is_palindrome(word): i = int(len(word)/2) e = len(word) result = True for i in range(i): if(word[i] == word[e -1]): e-=1 result = True else: result = False return result print(is_palindrome("racecar")) print(is_palindrome("stars")) print(is_palin...
n=int(input("Enter the number :")) if (n%2)==0: print("Number is even") else: print("Number is odd")
length = float(input('Please Enter the Length :')) width = float(input('Please Enter the Width :')) perimeter = 2 * (length + width) area=length*width print("Perimeter of a Rectangle using:", perimeter) print("Area of Rectangle using:",area)
# Introducing convolutional neural networks import tensorflow as tf from tensorflow import keras mnist = tf.keras.datasets.fashion_mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() training_images=training_images.reshape(60000, 28, 28, 1) training_images=training_images / 255.0 t...
import torch x_data = [1.0, 2.0, 3.0] # 构建数据集 y_data = [2.0, 4.0, 6.0] w = torch.Tensor([1.0]) # w是权重,创建tensor变量,假设现在w只有一个值,就用1.0,要用中括号 w.requires_grad = True # 表示需要计算梯度 # sum=0#总的loss def forward(x): # 模型 return x * w # 注意w是一个tensor,所以这里的*已经被重载,表示tensor与tensor之间的数乘 # 但是x不一定是一个tensor所以要进行自动类型转换,把x转换成一个Ten...
class Car: def __init__(self, speed, color, brand): self.speed = speed self.color = color self. brand = brand def start(self): print("the " + self.color + "car has started to move with a speed of", self.speed) def stop(self): print("the "+ self.brand +" ca...
import pandas as pd def openDataFile(fileName) : """ Open dataset file and populate X, Y, and E Args: fileName (String) : filename of dataset, a structured (CSV) dataset where - The first N-2 columns are the features (X). - The next to last column is the label (Y...
""" In this we will illustrate the intersection point of two Linked List The procedure we will follow is: Let there be two Linked list a and b lenA = length of linked list a lenB = length of linked list b d = abs(lenA-lenB) //get the absolute value of difference among the linked list So among the Linked list a...
class Account: def __init__(self,owner,balance): self.owner = owner self.balance = balance def deposit(self, dep): self.balance = self.balance + dep print("Внесение выполнено") def withdraw(self, minus): if self.balance - minus < 0: print("Недостаточно с...
from collections import Counter def anagram(): word1 = "hello" word2 = "hello" print(Counter(word1) == Counter(word2)) anagram()
#!/usr/bin/python3 #Alessio Larios # Wesleyan University # COMP 332, Spring 2018 # Homework 1: Tic-tac-toe game import random class Board(): """ TicTacToe game board """ def __init__(self, n): self.n = n self.game_board = [[' - '] * n for i in range(n)] def display(self): ...
import operator PRECEDENCE = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} OPERATION = {"*": operator.mul, "/": operator.truediv, "-": operator.sub, "+": operator.add} CHARACTERS = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ") DIGITS = set("0123456789") LEFT_PAREN = "(" RIGHT_PAREN = ")" def to_postfix(infix_expression): opera...
class Student: def __init__(self, name, age=None): self.name = name self.age = age def say_hello(self): print("Hello! My name is " + self.name) print("********** Test 2 *************") student1 = Student("Alex Garcia", 27) student1.say_hello() student2 = Student("Sergi...
#!/usr/bin/env python #coding:utf-8 import xlsxwriter workbook = xlsxwriter.Workbook('chart.csv') #workbook = xlsxwriter.Workbook('chart.xlsx') worksheet = workbook.add_worksheet() # Create a new Chart object. chart = workbook.add_chart({'type': 'line'}) # Write some data to add to plot on the chart. data = [ [1, ...
#!/usr/bin/python # -*- coding=utf-8 -*- ####基础 #编码:utf-8 #标识符 #保留字 #注释:#或者三引号 #行与缩进:tab或者4空格(推荐) #多行语句:“\” #数字类型:int、bool、float、complex #字符串 #空行 #输入 #同一行显示多条语句:“;” #多个语句构成代码组 #print输出 #import和from …… import #命令行参数 ####基本数据类型 #多变量赋值 #数值 #字符串 #列表:[] #元祖:() #集合:{} #字典:{key:value} ####解释器 #交互式编程 #脚本式编程 ####运算符 #算术运算符 ...
#!/usr/bin/python3 # Script for counting money for ascii Dresden. # This is fairly well written python. One of my first little projects. name = "MyName" # Array that contains the values of rows. staggering = [1.5, 1, .8, .5, .2, .1] # Arrays for amounts of the bills and coins. amounts = {coin: 0 for coin in stagger...
#Import libraries import RPi.GPIO as GPIO import time import smbus from RPLCD.gpio import CharLCD #Define GPIO pins to LCD mapping. lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33,31,29,23], numbering_mode=GPIO.BOARD) lcd.write_string(u"Starting...") #Create a SMBus instance. bus = smbus.SMBus(1) #A...
# -*- coding: utf-8 -*- """ Created on Wed Jun 16 18:45:17 2021 @author: Brian """ import random import string import generators from collections import deque # A single node of a singly linked list class stack: # constructor def __init__(self): self.stack = deque() def pop(self): ...
import tkinter as tk from openpyxl.workbook import Workbook from tkinter import messagebox as msg import sys import pandas as pd import os.path import csv from tkintertable import TableCanvas root=tk.Tk() root.wm_title('Convert csv to Excel') canvas1 = tk.Canvas(root, width = 400, height = 300, relief = ...
''' Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters ''' mystr = input("Enter a string : ") mydict = {'uppercase': 0, 'lowercase': 0} for i in mystr: if i.isupper(): mydict['uppercase'] += 1 elif i.islower(): ...
def to_hex(x): # upper case is important return "0x%X" % x def from_hex(x): return int(x, 16) #es is a list of expresssions def es_to_string(es): return "[" + ",".join(map(lambda x: x.dump(), es)) + "]" # separate (t)fold expressions from ops def split_by_fold(ops): res = [] extra = [] for op in ops: if...
import numpy as np from scipy import ndimage import queue def region_grow(image, seed_point): """ Performs a region growing on the image from seed_point :param image: An 3D grayscale input image :param seed_point: The seed point for the algorithm :return: A 3D binary segmentation mask with the sam...
''' **Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. ''' #!/usr/bin/env python def collatz(num, count = 0): if num <= 1: return count if num %...
for n in range(1, 1000001): # print("round", n, ":") product = 1 for i in range(1, n + 1): product = product * i # print("******product:", product)
# import the libraries needed to find the website # and parse it import requests from bs4 import BeautifulSoup # create a variable to store the url of the target website, # retrieved using the get method from the requests library data = requests.get('https://ocw.mit.edu/courses/most-visited-courses/') # parse the web...
# See http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html import numpy as np import cv2 # open the default camera cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here...
from os import system #from time import sleep # main variables board = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] #winner = None def display_board(board): system('cls') print(' ' * 3 + '|' + ' ' * 3 + '|' + ' ' * 3) print(' ' + board[7] + ' ' + '|' + ' ' + board[8] + ' ' + '|' + ' ' + board[9] + '...
print('-*-' * 15) print('Digite três valores para calcular um triângulo!') print('-*-' * 15) primeiro = float(input('Digite o primeiro segmento: ')) segundo = float(input('Digite o segundo segmento: ')) terceiro = float(input('Digite o terceiro segmento: ')) if primeiro < segundo + terceiro and segundo < primeiro...
import math co = float(input('Comprimento do cateto oposto é: ')) ca = float(input('Comprimento do cateto adjacente é: ')) hip = math.hypot(co, ca) print('A hipotenusa vai medir: {:.2f}'.format(hip))
# -*- coding: utf-8 -*- """ zahlen.ds.tree.bst ~~~~~~~~~~~~~~~~~~ This module implements the Binary Search Tree data structure. :copyright: (c) 2014 by Subhajit Ghosh. :license: MIT, see LICENSE for more details. """ class Node(object): """A node in a binary search tree. :param key: va...
""" get a number and check if it's a even """ try: num=int(input("Enter a number:")) if num%2==0: print("it's a even number") else: print("it's a negative number") except ValueError: print("You have not entered a value type number")
from turtle import * shape("turtle") for x in range(6): for i in range(360): forward(2) left(1) left(45) speed(0) mainloop()
import requests import json import pprint def writeHTML(data): myfile = open("justinAPI.html","w") myfile.write("<h1>JSON file returned by API call</h1>") myfile.write("<p>Copy and paste to <a href='https://jsoneditoronline.org/'>JSON editor</a> for pretty format.</p>") myfile.write(data) myfile.close() def ...
# Brute Force Decryption Using Frequency Analysis # Fuction that Returns Weighted Score of a Decrypted Text def frequency_calculator(decrypted_text): # Character:Occurrence Pair metric = {'E':0.11162 , 'T':0.09356, 'A':0.08497,'I':0.0754,'O':0.07507,' ':0.17,'S':0.0652, 'H':0.06094,'R':0.0758, 'D':0.04253, 'L...
# Author: Mahima Manik # Date: 01-08-2017 import random from heapq import heappush, heappop from random import randint number_of_lists = randint(0,50) #number of lists is randomly generated number between 0 to 50 random_data = [] orderedL = [] heap = [] # maximum length of each list can be 100 #random.sample retu...
import n1_fire as f def autosup(spr): """ Calculates the probability of the fire suppression failure :param spr: spr is an boolean indicating the presence of sprinkler :return: the conditional probability of failure given a large fire depending on presence of sprinkler """ # re...
# -*- coding: utf-8 -*- # @Time : 2020/5/22 8:32 下午 # @Author : morningstarwang # @FileName: question123.py # @Blog: wangchenxing.com from copy import deepcopy from datetime import datetime from math import sqrt, sin, pi, atan, cos import question3_global_variable as glb def multiply_with_number(a, number): ...
import time import math def primeFactors(n): print("Empezamos") # Print the number of two's that divide n while n % 2 == 0: print (2) n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): ...
import math, decimal, copy, sys def get_sigfig_decimal_pos( v, n ): '''Determine the decimal position of the n'th significant figure''' # The simplest way to identify significant figures is to represent # a number in scientific notation. # # examples: # # num sci nota 1st sf 2nd sf # ...
""" VLSI CAD Design Tool - Boolean Expression to Transistor Netlist Author: R.Mukesh, IIITDM Kancheepuram Steps : 1. Read boolean expression 2. Convert expression to postfix 3. NOT (~) elimination from postfix | |--- Identify depth of NOT(~) effect in postfix 4. Postfix to TRANSISTOR NETLIST """ print( "Welcome t...
def is_leap(year): if year%100==0 and year%400!=0: return False if year%4==0: return True else: return False print(is_leap(1944), True) print(is_leap(2011), False) print(is_leap(1986), False) print(is_leap(1956), True) print(is_leap(1957), False) print(is_leap(1800), False) print(...
def workout_coach(lift_name): wt = 10 print("Time to", lift_name, wt, "pounds! You got this!") keep_going = input("Keep doing {lift_name}? ".format(lift_name=lift_name)) while keep_going == "Yes" or keep_going == "yes": if lift_name != "bench": wt+=10 print("Time to", lift_name, wt, "pounds! You...
for x in range(1,101): if x%15==0:print('fizzbuzz') elif x%3==0:print('fizz') elif x%5==0:print('buzz') else:print(x)
def Descending_Order(num): list = sorted(str(num),reverse=True) num_string = "" for num in list: num_string+=num return int(num_string) print(Descending_Order(83242834))
def new_list(string1): #step 1 creates list from string new1_list = [letter for letter in string1] return new1_list def replace(string1,old,new): #step 2: removes old value and adds new value list_string = new_list(string1) replace_list = [] for item in list_string:...
def alphabet_position(letter): lower_letters = "abcdefghijklmnopqrstuvwxyz" upper_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if letter.isalpha(): if letter.islower(): return lower_letters.index(letter) else: return upper_letters.index(letter) else: return 0 def encrypt(text, codeword): en...
def db_scan_clustering(df, lat_col, long_col, max_distance, min_sample): ''' Identifes clusters from a sample of points. Clusters are based on closest distance, however what defines a cluster is qualified below. The user can specify a minimum number of points needed to form a cluster, as well as specif...
q=int(input()) for i in range(q): x=int(input()) y=int(input()) z=int(input()) a=abs(x-z) b=abs(y-z) if(b>a): print("Cat A") elif(b<a): print("Cat B") else: print("Mouse C")
# 비밀번호 # def solution1(password): # capital_count, small_count, digit_count = 0,0,0 # for p in password: # if p >='A' and p<='Z': # capital_count += 1 # elif p>='a' and p<='z': # small_count += 1 # elif p>= '0' and p <= '9': # digit_count += 1 # if...
# A challenge that users face is that, for a given y-axis value (e.g. 42,000), # it is difficult to know which x-axis values are most likely to be representative, # because the confidence levels overlap and their distributions are different # (the lengths of the confidence interval bars are unequal). One of the s...
import math def isPrime(n): i = 2 while i <= math.sqrt(n): if n % i == 0: return False i += 1 return True def main(): n = int(input('Enter n: ')) count = -1 curr = 0 while count < n: curr += 1 if not isPrime(curr): count += 1 ...
def distance(str1, str2): """ Compute the Levenshtein distance between str1 and str2 :param str1: String to compute distance :param str2: String to compute distance :type str1: string :type str2: string :return: the Levenshtein distance between str1 and str2 :rtype: int """ dista...
from random import randint dice = input("What kind of dice are you playing with?: ") amountOfDice, amountOfSides = dice.split("d") rollList = [] for x in range(int(amountOfDice)): roll = randint(1, int(amountOfSides)) rollList.append(roll) print(sum(rollList), "\nInvidual rolls:", rollList)
cc=int(input()) count=0 hh='kabali' for i in range(0,cc,1): ss=input() if(sorted(hh)==sorted(ss)): count=count+1 print(count)
import math # in a "multiset", order doesn't matter, (like a set, but unlike a list), but repetition is allowed # (like a set, but unlike a list) # # The formula for a multiset is "(k + n - 1) choose k" or # # (k + n - 1)! / (k!(n - 1)!) # # this is because we are basically adding the total number of choices we have a...
from __future__ import print_function, division from collections import defaultdict from random import random, choice class Q2(object): """ Wrapping data structure for Q-Learning with a two levels of keys """ def __init__(self): self.Q = defaultdict(lambda: defaultdict(float)) def get(sel...
from __future__ import division, print_function import matplotlib.pyplot as plt def plot_temperatures(ideal, experienced): plt.title("Ideal temperature vs. experienced temperature") plt.plot(ideal, label='ideal') plt.plot(experienced, '.', label='experienced') # plt.plot(map(lambda t: abs(operator.su...
import sys import re import string def remove(line): if(line is None): return line = re.sub('['+string.punctuation+']', ' ', line) line = re.sub(' ', ' ', line) return line.lower() count = set() with open(sys.argv[1]) as f: for line in f: for word in remove(line).strip().split(): coun...
letters = list(input()) # print(letters) vowels = [ letter.upper() for letter in letters if (letter := random.choice(letters)) in list("aeoui") ] print(vowels)