text stringlengths 37 1.41M |
|---|
N=int(input("Enter number: "))
rev=1
while(N>1):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of given number is:",rev)
|
num=raw_input()
num=int(num)
factorial=1
for i in range(1,num + 1):
factorial = factorial*i
print factorial
|
def for_demo():
for i in range(6):
print('hello world')
def for_demo2():
for i in range(1,50,2):
print(i)
def for_list():
alist = ['1','5','6','7','8','窝',1,2,3]
for b in alist:
print(b)
for b in range(len(alist)):
print(b)
def for_for():
for i in range(1,10):
... |
from math import log
def find_narcissistic_number(start: int, end: int):
lst = []
for i in range(start, end):
n = int(log(i, 10)) + 1
s = int(0)
x = int(i)
while x > 0:
s = s + pow(x % 10, n)
x = x // 10
# print(s, i)
if s == i:
... |
import re
class MacAddress:
"""
Object representation of device MAC address.
"""
def __init__(self, mac) -> None:
self.mac = mac
def getMAC(self) -> str:
return self.mac
def validMac(self):
return isinstance(self.mac, str) and re.match("[0-9a-f]{2}([:]?)[0-9a-f]{2}(... |
class CalcAlcohol:
"""
Is used by the beverage class.
Calculates the amount of alcohol in a beverage in different in different units.
"""
@staticmethod
def gram_to_oz(gram):
"""Converts grams go ounces"""
return gram * 0.035274
@staticmethod
def gram_to_miligra... |
num=int(input('Enter No : '))
total = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
total = total*i
print ("The factorial of",num,"is",total) |
import numpy as np
import matplotlib.pyplot as plt
import operator
class FitzHughNagumo(object):
""" An abstract model of a neuron. See http://www.scholarpedia.org/article/FitzHugh-Nagumo_model """
def __init__(self, istate=np.array([0.0, 0.0]), dc_current=0.0):
self.initial_state = istate
s... |
import cv2,sys
faceClassifier=cv2.CascadeClassifier('/work/haarcascade_frontalface_default.xml')
# cv2.CascadeClassifier('/work/haarcascade_frontalface_default.xml') # the HAAR cascade file, which contains the machine learned data for face detection
objImage=cv2.imread(sys.argv[1]) # use cv2 to load image file
cvtIm... |
from collections import defaultdict
class graph(object):
connections=defaultdict(list)
def __init__(self):
nodes=raw_input('Enter the nodes of the ').strip().split(' ')
self.connect(nodes)
def connect(self,nodes):
for node in nodes:
for j in nodes:
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def f(x,y):
return(x**2+x*y-10)
def g(x,y):
return(y+3*x*y**2-57)
def fx(x,y):
return(2*x+y)
def fy(x,y):
return(x)
def gx(x,y):
return(3*y**2)
def gy(x,y):
return(1+6*x*y)
xi = float(input("başlangıç tahmini girin: "))
yi = float(input("başla... |
import turtle as tt
for i in range(5):
al=tt.circle(25)
if i%2==0:
tt.penup()
tt.sety(-15)
else:
tt.penup()
tt.sety(+5)
tt.forward(25)
tt.pendown()
tt.done
|
# Definição de funções
def comparar_jogada (jogador1, jogador2):
if jogador1 == "papel" and jogador2 == "tesoura":
print("Jogador 2 ganhou com a Tesoura!!!")
return
if jogador1 == "pedra" and jogador2 == "papel":
print("Jogador 2 ganhou com o Papel!!!")
return
if jogador1 == ... |
def Values( ):
L = list( )
for x in range(1,21):
L.append(x**2)
print(L)
Values( )
|
from link_list import LinkList
class LinkListStack(object):
def __init__(self, size):
self.top = 0
self._size = size
self._items = LinkList()
def __len__(self):
return self.top
def push(self, value):
if self.top >= self._size:
raise Exception("stack is full")
self._items.append(value)
self.t... |
# -----------------------------------------------------------------------------
# Name: Challenge 1
# Purpose: To challenge myself
#
# Author: 767571
# Created: Nov-29-19
# Updated: Nov-29-19
# -----------------------------------------------------------------------------
def add_two_integers(i... |
a = input()
b = input()
c = input()
d = input()
e = input()
UserNameA = dict(User = a, cash = 500)
UserNameB = dict(User = b, cash = 500)
UserNameC = dict(User = c, cash = 500)
UserNameD = dict(User = d, cash = 500)
UserNameE = dict(User = e, cash = 500)
UserName=[UserNameA,UserNameB,UserNameC,UserNameD,UserNameE]
... |
import re
date = "Hello, My number is 989-097-4840"
regex = re.findall("\d{3}-\d{3}-\d{4}", date)
if regex:
print("Valide")
else:
print("invalide") |
import re
string="""
Hello
this is python class
You'r learning Regex
"""
regex=re.findall("\S",string)
print(string)
data=" ".join(regex)
print(data)
#\w [A-Za-z0-9]
#\W[^A-Za-z0-9] |
#########################################################################
# Date: 2018/10/02
# file name: 2nd_assignment_main.py
# Purpose: this code has been generated for the 4 wheel drive body
# moving object to perform the project with line detector
# this code is used for the student only
#########################... |
# Experiment with different ranges and slices to get a feel for how they work.
# Remember that you can print the range as well as iterating through it to print
# its values, to check that your ranges are what you expected.
# You may also want to include things like.
#
o = range(0, 100, 4)
print(o)
p = o[::5]
pr... |
myList = ("a", "b", "c", "d")
newString = ''
# for c in myList:
# newString+= c + ","
# Instead of using the above code to join the elements of myString to
# form a single string, we can directly use the following code :
newString = ",".join(myList)
# .join no longer requires a loop so we can omit the for l... |
locations = { 0: "You are sitting in front of a laptop",
1: "You are standing in a road",
2: "You are at the top of a hill",
3: "You are in a building",
4: "You are in the valley",
5: "You are in a forest"}
exits = [{"Q" : 0},
{"W": 2... |
primerNumero = 10
segundoNumero =20.5
def sumar():
resultadoDeOperacion=primerNumero + segundoNumero
return resultadoDeOperacion
print('el resultado es => ' + str(sumar()))
def sumar(primerNumero, segundoAlumno):
resultadoDeOperacion= primerNumero + segundoAlumno
return resultadoDeOperacion
print(' m... |
# # base=int(input('enter the value of base'))
# # height=int(input('enter the value of height'))
# # print('area of the triangle is ',0.5*base*height)
# # x='awesome'
# # def myfunc():
# # global x
# # x='fantastic'
# # myfunc()
# # print('python is'+x)
# # y=10.6
# # print(type(y))
# # # assigning string to a vari... |
from collections import Counter
import string
ALHPABET_LENGTH = 26
def main():
#key = list("LEMON") #enter the key in all caps
user_key = input("enter a key: ")
modified_key = list(user_key.upper())
fff = input("enter file to read from: ")
user_input = get_text_from_file(fff)
#user_input = input("Enter ... |
import math
def poly_sum(n, s):
"""Calculates the area of a regular polygon, then calculates the
square of its perimeter and returns the sum of both calculations.
Arguments:
'n' corresponds to the number of sides of the regular polygon.
's' corresponds to the length of every side of that polygon.... |
import glob
import os
def delete_files(source_dir, pattern):
"""Delete files matching `pattern` in `source_dir`."""
# Retrieve a list of all matching files
matching_files = glob.glob(pattern)
if matching_files == []:
print("There is no file to delete.")
else:
print(f"Files found ... |
"""
E.g., input (as CSV):
COL1 COL2 COL3
A B C
A B D
A B E
A B F
Output:
COL1 COL2 COL3
A B C
D
E
F
Or merge on COL1 and COL2:
MERGED_COL COL3
A C
B D
E
F
"""
import csv
COLUMNS_TO_TRACK_UNIQUE_V... |
def is_matched(expression):
"""Return True if a string contains correctly matched pairs of brackets."""
mapping = dict(zip("({[<", ")}]>"))
queue = []
for letter in expression:
if letter in mapping:
queue.append(mapping[letter])
elif letter not in mapping.values():
... |
"""
Avoid recursion limit with tail-recursive algorithms
Source: http://www.usrsb.in/Bouncing-Python-s-Generators-With-A-Trampoline.html
"""
import types
def tramp(gen, *args, **kwargs):
g = gen(*args, **kwargs)
while isinstance(g, types.GeneratorType):
g = next(g)
return g
# Example of a tail... |
print("Ingrese el valor para A")
A = input()
print("Ingrese el valor para B")
B = input()
print(f"El valor de A es: {A} y el valor de B es: {B}")
A, B = B,A
print("")
print("Intercambiando valores...")
print("")
print(f"El valor de A es: {A} y el valor de B es: {B}") |
import board
def main():
"""
main func
"""
command = ''
list_of_commands = ['Clear', 'exit', 'Make a move', 'Make computer move', 'Chose the best move']
Game = board.Board()
while command != 'exit':
print(Game)
print('List of commands:')
for i in list_of_... |
"""
Andrew Kung
BMI203: Algorithms - W18
Using our neural network framework to make an autoencoder
"""
import numpy as np
from bmi203final import algs
"""
Training set: identity matrix
[[1,0,0,0,0,0,0,0]
[0,1,0,0,0,0,0,0]
[0,0,1,0,0,0,0,0]
[0,0,0,1,0,0,0,0]
[0,0,0,0,1,0,0,0]
[0,0,0,0,0,1,0,0]
[0,0,0,0,0,0,1,0]... |
from operator import mul
import math
"""Financial formulas as given in requirements"""
def calc_common_dividend_yield(last_dividend, price):
"""Calculate dividend yield for common stocks.
:param float last_dividend: the last dividend
:param float price: current price
:return: yield
"""
retur... |
#print Hello world
print('Hello world\n')
#displaying text
print("The capybara is the world's largest rodent")
print("It's a beautiful day in Kenya") #do not use single quotes here
print("It is a beautiful day in the neighborhood")
print('Hickory Dickory\nThe Car is back')
print("""Hello Friends, I am af... |
##File name: /Users/laptopuser/Documents/courses/cs127/class_exercises/f22/lecture7_class_exercises/groupby_Age.py
##name: Tong Yi
##email: ty680@hunter.cuny.edu
#Date: 2022-09-30 Fri 10:49 AM
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("student_info.csv")
#Name,Gender,Age,Grade Level,Score
#... |
##File name: /Users/laptopuser/Documents/courses/cs127/class_exercises/f22/lecture10_class_exercises/getYear_error.py
##name: csci teaching staff
#Write a function that asks a user for number after 2000 but
#before 2021. The function should repeatedly ask the user for a number until
#they enter one within the range ... |
import folium
import pandas as pd
import webbrowser #display html file
import os #use to find directory
#Use pandas (alias pd) to read a csv file,
#save the return data frame object in variable cuny.
cuny = pd.read_csv('cunyLocations.csv')
#Create a map object centered at 40.75, -74.125,
#save in variable mapCUNY.
ma... |
##File name: /Users/laptopuser/Documents/courses/cs127/class_exercises/f22/lecture7_class_exercises/groupby_GradeLevel.py
##name: Tong Yi
##email: ty680@hunter.cuny.edu
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("student_info.csv")
#print(df)
grouped = df.groupby("Grade Level")
print("avera... |
from link_node import Node
class ForwardLink:
"""单向链表"""
def __init__(self, *args):
"""插入个链表,如果有节点就插入,没有就让头节点为空"""
self.head = None
for item in args:
self.append(item)
def is_empty(self):
"""is_empty() 链表是否为空"""
if not self.head:
return Tru... |
import time
def calc_1():
"""# 计算a+b+c == 1000 且 a^2+b^2=c^2"""
time_start = time.time()
for a in range(0, 1001):
for b in range(0, 1001):
for c in range(0, 1001):
if a+b+c == 1000 and a**2 + b**2 == c**2:
print("%s + %s + %s = 1000" % (a, b, c))
... |
#Tipo de Datos Entero o Largo
numero = 15
print(numero, type(numero))
#Tipo de Dato Flotentate
numero_flotante = 15.5
print (numero_flotante, type(numero_flotante))
#Tipo de Dato Numero Complejo
numero_complejo = 5 + 6j
print (numero_complejo, type(numero_complejo))
#Tipo d Dato string "Cadenas"
nombre = "Angie"... |
# list 类似与其他语言的数组或者对象的形式,可以追加,删除,计算数量
classmates = ['Michael', 'Bob', 'Tracy']
newBody = 'vitamin'
classmates[0] = 'beautyGirl'
classmates.insert(1, 'bug')
classmates.append(newBody)
classmates.pop(-1)
print(len(classmates))
print('\n'+str(classmates))
print('\n'+classmates[0])
print('\n'+classmates[1])
print('\n'+clas... |
import sys
words = 'The lazy cat jumped over the zealous fox.'.split()
list = [[w.upper(), w.lower(), len(w)] for w in words]
for index in list:
print(index)
|
#! python3
# Detects all e-mails and phone numbers in clipboard text.
import sys, re, pyperclip
phone = re.compile(r'''
(\d{3}|\(\d{3}\)) # area code
([- ])? # optional separator
(\d{3}) # phone number part 1
([- ])? # optional separator
(\d{4}) ... |
T=[]
N=int(input("taille du tableau"))
Z=int(N/2)
i=1
a=1
while (i<=N):
T.append(a)
i +=1
a +=1
print (T)
X=float(input("Saisir l'élément à trouver"))
|
# Définition d'un tableau
T=[]
V=[1,10,5,6]
T=V[1,:]+V[0,3]
W=list()
A=range(10)
print(T)
print(V)
print(W)
print(A)
# Saisie d'un tableau T(n)
n=int(input(Saisir n\n*)
i=0
#print(n)
while i<n:
n=int(input("I"+str(i)+" ")
T.append(n) # Méthode append impérative pour l'ajout d'uin tableau
print(T[i]... |
import pygame
#initializing pygame
pygame.init()
#Creating the screen
screen=pygame.display.set_mode((800,600))
#title and icon
pygame.display.set_caption("SPACE INVADERS")
icon=pygame.image.load('pycon.png')
pygame.display.set_icon(icon)
#adding player
playerimg=pygame.image.load("battleship.png")
playerX=370
playe... |
def getSeqs():
"""Function to get input sequences"""
s1 = raw_input("Enter sequence 1: ")
s2 = raw_input("Enter sequence 2: ")
return s1, s2
def calcOpt(s1, s2, gap, mismatch, match):
"""Calculates dynamic programming matrix"""
#initialize 2d list with all zeros
optMatrix = make2dList(len(s1)+1, len(s2)+1)
... |
from tkinter import *
operator = ''
def implement(num):
global operator
operator = operator + str(num)
exp.setvar('operator', operator)
def clear():
global operator
operator = ''
exp.setvar('operator', operator)
def equals():
global operator
sumup = eval(operato... |
#Places = ["London", "Korea", "Japan", "Flordia", "California", "Germany", "Jamacia"]
#Numbers = [1, 2, 3, 4 ,5 ,6 ,7]
#Fruit = ["Apple", "Orange", "Strawberry", "Pineapple", "Banana", "Kiwi"]
#print (len(Places))
#print (len(Numbers))
#print (len(Fruit))
#print(Places[2])
#for letter in Fruit:
#print... |
from helpers import alphabet_position, rotate_character
def encrypt(text, rot):
'''encryptics a message using a Caesar cipher'''
encrypted = ''
for char in text:
if not char.isalpha():
encrypted += char
else:
encrypted += rotate_character(char, rot)
return encry... |
from round import Round
class Hand:
def __init__(self, hand_rank):
self.hand_rank = hand_rank
self.next_hand_rank = []
def Cycle_To_Leader(self, leader):
'''
Cycles through the players until the player at the
front of hand_rank is the leader from the previous
... |
"""
Given a matrix with N rows and M columns, the task is to check if the matrix is a Binary Matrix. A binary matrix is a matrix in which all the elements are either 0 or 1.
Input Format:
The first line of the input contains two integer number N and M which represents the number of rows and the number of columns resp... |
"""
Given a list A of numbers (integers), you have to print those numbers which are not multiples of 5.
Input Format:
The first line contains the numbers of list A separated by a space.
Output Format:
Print the numbers in a single line separated by a space which are not multiples of 5.
Example:
Input:
1 2 3 4 5... |
"""
A Lower triangular matrix is a square matrix (where the number of rows and columns are equal) where all the elements above the diagonal are zero.
For example, the following is an upper triangular matrix with the number of rows and columns equal to 3.
1 0 0
4 5 0
7 8 9
Write a program to convert a square matrix ... |
"""
程序思路
# 1.安装、导入工具包
pip3 install openpyxl
# 2.打开excel
# 3.阅读内容
# 4.找到包含abc的记录
# 5.做统计
# 6.输出结果
"""
# 1.安装、导入工具包
import openpyxl
# 1.1 找到文件路径
wenjian_lujin = r"C:\Users\Jiang\Desktop\data.xlsx"
# 1.2 要查找的关键字
guanjianzi="abc"
# 2.打开excel
xm_excel = openpyxl.load_workbook(wenjian_lujin)
# 3.阅读内容 ,内容在Sheet1中
xm_sheet1... |
#Creating a text editor with tkinter
from tkinter import *
from tkinter import filedialog
start=Tk()
class texteditor:
#function to open file
current_open_file="No file"#it is used to check whether a new file is created or previous is opened
def open_file(self):
open_return=filedialog.askopenfile(i... |
from football import Football
def pretty_print(players, max_len, title):
""" Prints the bench in a nice fancy way """
print('┌──────┬─{l:─^{n}}─┬───────┐\n'
'│ POS │ {t: <{n}} │ PTS │\n'
'├──────┼─{l:─^{n}}─┼───────┤'
.format(l='─', n=max_len, t=title))
for player in playe... |
from tkinter import * #imports Python's GUI from the database
B_FONT = ("Helvetica",42)
root = Tk()
root.title("Tic Tac Toe") #Creates the title of the Window and labels it to something relevant
bclick = True
def tictactoe(buttons): # a function used to define the buttons used to in the game
glob... |
#!/usr/bin/python3
# This is the Python 3.x client-sided script for a Chat Server.
from socket import socket, AF_INET, SOCK_STREAM, error
HOST = 'localhost'
PORT = 1337
serverAddress = (HOST, PORT)
Client_Socket = socket(family=AF_INET, type=SOCK_STREAM)
try:
Client_Socket.connect(serverAddress)... |
# coding making python 3.6
# fonte: https://trinket.io/python/43bc79b582
# -*- coding: utf-8 -*-
import turtle
# criação da janela e turtle
janela = turtle.Screen()
janela.bgcolor('black')
arte = turtle.Turtle()
# sequencia de fibonacci
n = 1
t = 0
s = 0
lista = []
while(n<=100):
t = n
n = n + s
s = t
... |
# Note: converted from .ipynb format
import numpy as np
import pandas as pd
import sklearn as sk
from sklearn import linear_model
# file paths
TRAIN_PATH = "data/train.csv"
TEST_PATH = "data/test.csv"
# read in the datasets from the respective CSV files
train_data = pd.read_csv(TRAIN_PATH)
test_data = pd.read_csv(TES... |
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World!'
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
@app.ro... |
def eliminar_duplicados(lista):
for i in lista:
while lista.count(i) >=2:
lista.pop(lista.index(i))
print(lista)
if __name__=="__main__":
lista=[2,3,3,2,"hola","adios","hola"]
eliminar_duplicados(lista) |
try:
dividendo=int(input('Introduce un numero: '))
divisor=int(input('Introduce otro numero: '))
a = dividendo/divisor
except ZeroDivisionError :
print("El divisor no puede ser 0")
except ValueError:
print("Error al instroducir los numeros")
else:
contador=0
while dividendo > divisor:
... |
control=0
while control != 1:
try:
nota = float(input("Introduzca puntuación: "))
except ValueError:
print("Error al introducir la información")
else:
if nota >= 0.0 and nota <= 1.0:
control=1
if nota < 0.6:
print("Insuficiente")
el... |
for i in range(51):
if i%2 == 0:
if i == 50:
print(i)
else:
print(i,end=', ') |
import operator
#Creamos el diccionario para guardar las puntuaciones, ya unas metidas para poder hacer otras opciones
saltos={
'Louganis': {'salto1':23, 'salto2':24, 'salto3':28, 'salto4':22, 'salto5':19},
'Xiao': {'salto1':27, 'salto2':26, 'salto3':24, 'salto4':28, 'salto5':23},
... |
import random
def comprobar(x,y):
if y==x:
print("Enhorabuena has acertador")
return True
elif y<x+2 and y>x-2:
print("Estas muy cerca")
return False
elif y<x:
print("El numero es mas pequeño")
return False
else:
print("El numero es mas grande")
... |
def eliminar_extremos(lista):
lista.remove(lista[0])
lista.remove(lista[len(lista)-1])
return lista
def valoracion(lista):
media = 0
lista=eliminar_extremos(sorted(lista))
for i in lista:
media+=i
return media/len(lista)
if __name__=="__main__":
lista=[3,2,1,4,8,7,6,5]
prin... |
def en_orden_ascendente(lista):
if lista == sorted(lista):
return True
else:
return False
def esta_ordenada(lista):
if lista == sorted(lista) or lista==sorted(lista,reverse=True):
return True
else:
return False
if __name__=="__main__":
lista=[3,2,1]
print(esta_o... |
import sys
def opcion_l(lista):
try:
archivo=open(lista[1])
except FileNotFoundError:
print("El archivo no existe")
else:
con_l=1
for linea in archivo:
if linea.find(lista[0]) == -1:
con_l+=1
continue
print(f"{linea[:-1]... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
josephus问题:假设n个人围坐一圈,从第K个人开始报数,报到m个数的人退出,
然后下一个人接着报数,直到所有人退出
使用list实现 时间开销约为O(n^2)
'''
def josephus_L(n, k, m):
people = list(range(1, n + 1))
num, i = n, k - 1
for num in range(n, 0, -1):
i = (i + m - 1) % num
print(people.po... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
prime,最小生成树算法
'''
inf = float('inf') # inf的值比任何float值都大
class GraphError():
pass
class Graph():
def __init__(self, mat, unconn=0):
vnum = len(mat)
for x in mat:
if len(x) != vnum: # 检查是否为方阵
raise ValueError('Argumen... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
插入排序,时间复杂为O(n^2),稳定算法
'''
def insert_sort(lists):
count = len(lists)
for i in range(1, count):
key = lists[i]
j = i
while j > 0 and lists[j - 1] > key:
lists[j] = lists[j - 1] # 反序逐个后移元素,确定插入位置
j -= 1
lists... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
交叉路口的红绿灯安排
思路:转化为涂色问题
'''
def coloring(G):
color = 0
groups = set()
verts = vertices(G) # 取得G的所有顶点
while verts:
new_group=set()
for v in list(verts):
if not_adjacent_with_set(v,new_group,G):
new_group.add(v)
... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
优先队列 基于线性表list实现
'''
class PrioQueueError(ValueError):
pass
class PrioQue():
def __init__(self, elist=[]):
self._elems = list(elist)
self._elems.sort(reverse=True)
def enqueue(self, e):
i = len(self._elems) - 1
while i > 0... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
冒泡排序,时间复杂度为O(n^2),稳定排序
'''
def bubble_sort(lists):
count = len((lists))
for i in range(count): # 从0开始排序
for j in range(1, count - i):
if lists[j - 1] > lists[j]:
lists[j - 1], lists[j] = lists[j], lists[j - 1]
p... |
# Binary tree implemention
# Author: Swapnil Trambake, trambake.swapnil@gmail.com
from enum import Enum
# Enumeration for node position
class NodePosition_E(Enum):
Left = 0
Right = 1
# Node structure to hold node value and it's corresponding left and right child link
class Node():
def __init__(self... |
# How many ways we can tile a board of length n with red tile of length p and blue tile of length q
# Assume we have infinite amount of red & blue tile
from unittest import TestCase
class Solution():
def __init__(self) -> None:
self.__dp = None
self.__tile1Length = 0
self.__tile2Length = ... |
from math import pi
radius = float(input('Enter the radius: '))
print(f'Area = {pi * radius * radius}')
|
from tkinter import *
import mysql.connector
root=Tk()
def Database():
global connection, cursor
connection = mysql.connector.connect(
host='localhost',
database='lab1',
user='root',
... |
a = float(input("Input first number: "))
b = float(input("Input second number: "))
c = float(input("Input third number: "))
median = -1
if b < a < c or c < a < b:
median = a
elif a < b < c or c < b < a:
median = b
elif a < c < b or b < c < a:
median = c
print(median)
|
"""
Uses the Spotify API, plus several Python libraries - Spotipy, a wrapper for the Spotify API,
and Markovify, a library for Markov chains - to pull track names of a genre from Spotify,
then use Markov chains to create random song names of a certain genre.
@author: Matt Brucker
"""
import argparse
from spotipy impo... |
# This program factor an integer n giving by the user
#Prompt the user to enter an integer less than or equal to 10,000
n = eval(input("Enter an integer less than or equal to 10,000: "))
myArray = []
print("The factors of ", n, " are: ")
for i in range(n+1):
#b = -1
myArray.append(-1)
for j in range(2, n+1):... |
# grab word 'ink' from 'tinker'
my_string = "tinker"
print("Printing 'ink' using index slicing")
print(my_string[1:4])
|
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Site:
# @File: shell.py
# @Author: zheng
# @Time: 4月 28, 2020
class Shell():
def sort(self, nums):
length = len(nums)
h = 1
while h < length / 3:
h = 3*h + 1
while h >= 1:
for i in range(h, length):
... |
class Movie:
def __init__(self):
self.movie = []
def __len__(self):
return len(self.movie)
def __getitem__(self, item):
return self.movie[item]
def __repr__(self):
return f'<Movie {self.movie}>'
def __str__(self):
return f'{self.movie}'
my_movie = Movie()... |
"""
This module is used to create a inverted index file from the corpus. To run this
program , the user has to provide 2 parameters through command line
1) corpus-file : A file which contains document-ids and stem-words for that document
2) output-file : The file where the inverted index will be stored
... |
import numpy as np
class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
... |
"""
This Class represents the rectangle where rovers are landed
atributes:
-> Plateau size
-> occupied array storing occupied coordinates (if any)
actions:
-> starts rover's exploring process
-> for each rover position, checks if this position is valid or not based on:
- rover cant be outside... |
numbers = [345, 465, 43, 1, 12, 214, 67, 4213, 2, 34, 77]
print(sorted(numbers))
print(sorted(numbers, reverse=True)) |
__author__ = 'Горюшко Сергей Михайлович'
# Задача-1: Дано произвольное целое число (число заранее неизвестно).
# Вывести поочередно цифры исходного числа (порядок вывода цифр неважен).
# Подсказки:
# * постарайтесь решить задачу с применением арифметики и цикла while;
# * при желании решите задачу с применением цикла... |
import re
#solution to question number 1
s = 'zuck26@facebook.com'
a="page33@google.com"
b="jeff42@amazon.com"
matchObj = re.match(r'(.*)@(.*).(com)', s, re.M|re.I)
matchObj1 = re.match(r'(.*)@(.*).(com)', a, re.M|re.I)
matchObj2 = re.match(r'(.*)@(.*).(com)', b, re.M|re.I)
print(matchObj.groups())
if matchObj:
pr... |
#solution to question number 1
a=3
try:
if a<4:
a=a/(a-3)
print(a)
except ZeroDivisionError:
print("this is a zero division error case!! try again")
#solution to question number 2
l=[1,2,3]
try:
print(l[3])
except IndexError:
print("out of index error")
#solution to question number 3
An excepti... |
from replit import clear
#HINT: You can call clear() to clear the output in the console.
from art import logo
print(logo)
should_cont = True
auction_list = {}
def win_cond(auction):
for key, val in auction.items():
if win_value == val:
return key
while should_cont :
auctor = input("Please type in your n... |
'''
This function estimates the parameters of a Gaussian distribution
using the data in X
'''
import numpy as np
def estimateGaussian(X):
'''
The input X is the dataset with each n-dimensional data point in one row
The output is an n-dimensional vector mu, the mean of the data set and
the variances s... |
'''
Plots the data points X and y into a new figure with
the decision boundary defined by theta
'''
import matplotlib.pyplot as plt
import numpy as np
from plotData import plotData
from mapFeature import mapFeature
def plotDecisionBoundary(theta, X, y):
'''
plots the data points with + for the positive examp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.