text stringlengths 37 1.41M |
|---|
#--- Exercício 1 - Funções - 1
#--- Escreva uma função que imprima um cabeçalho
#--- O cabeçalho deve ser escrito usando a multiplicação de carácter
#--- resultado esperado: -------------- Cadastro Serasa --------------------------
#--- O cabeçalho deve conter o nome de uma empresa, que será uma variável
#--- Realize... |
# Exercicio 18
# Peça para o usuário digitar os valores de a, b e c
#
# Calcule o delta "delta = (b**2)-(4*a*c)"
#
# Se o delta der negativo, então deve aparecer a seguinte mensagem: "Delta negativo! Equação não pode ser resolvida!"
#
# Se o delta der igual a zero, então deve aparecer a seguinte mensagem: "Delta igu... |
# Exercicio 1
#
# Faça um programa que peça 2 numeros inteiros e mostre o maior deles.
#
#
num1 = int(input("Digite o primeiro número para a comparação: "))
num2 = int(input("Digite o segundo número: "))
if(num1>num2):
print(num1, "é maior que",num2)
else:
print(num2, "é maior que",num1) |
"""Exercicio 07
Faça um programa que receba 10 idades e mostre a seguinte mensagem:
Para maiores de 18 anos: Ingreços da Rave liberado!
De 16 a 18 anos: Ingreços de cinema liberado
De 13 a 16 anos: Ingreços para fliperama liberado
Menores de 13 anos: Psicina de bolinhas liberado
"""
print("""EM COMEMORAÇÃO AO ANIVE... |
#If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
#
#If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
#
#
#NOTE: Do not count spaces or hyphens. For example, 342 ... |
#Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
#If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
#
#For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; t... |
import math
c1 = float(input('Digite o valor de um dos catetos: '))
c2 = float(input('Digite o valor do outro cateto: '))
hip = ((c1**2) + (c2**2))**(1/2)
hip2 = math.hypot(c1, c2)
print('O valor da hipotenusa do triangulo é: {:.2f}!'.format(hip))
print('A hipotenusa calculada pelo modulo math.hypot é igual a {:.2f}'.... |
nome = input('Escreva seu nome: ').upper()
if nome == 'MATEUS':
print('Que nome lindo você tem!')
else:
print('Que nominho sem graça!')
print('Seja bem vindo, {}!'.format(nome.title()))
n1 = float(input('Agora me diga quanto você tirou na primeira prova do trimestre: '))
print('Ok.')
n2 = float(input('Agora me... |
# Faca um programa que leia a largura e a altura de uma parede em metros, calcule sua area e a quantidade de tinta
# necessaria para pinta-la, sabendo que cada litro de tinta pinta uma area de 2m^2
l = float(input('Digite a largura da parede: '))
a = float(input('Digite a altura da parede '))
a2 = a * l
lt = a2 / 2
pr... |
import random
money = 100
#Is bet amount appropriate?
def check_bet_amount_against_balance(bet_amount):
if bet_amount.isdigit() == False:
print("Try entering a number.")
print()
return False
elif int(bet_amount) <= money:
return True
... |
import random as r
def make_question():
'''문제를 만드는 함수'''
#숫자를 랜덤으로 생성 *2
#연산자를 랜덤으로 생성
#숫자연산자숫자
#return
a=r.randint(1,100)
b=r.randint(1,100)
c=r.randint(1,3)
if c==1:
t='+'
elif c==2:
t='-'
elif c==3:
t='*'
result=str(a)+t+str(b)
return result
while True:
y=make_question()
u=input('그만하고 싶으면 st... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: RaoPeng
arr = [1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,65555,45,33,45]
max_num = 0
for i in arr:
if i>max_num:
max_num = i
print 'max num is %s' %(max_num)
|
#use pre-trained word embeddings - word2vec
import gensim
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('D:\datasets\word2vec\GoogleNews-vectors-negative300.bin', binary=True)
#get the vector of any word in Google News Corpus
vector = model['London']
print(vector)
#get words ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains the main model for GEOG5995 Assignment 2
Planning for drunks
@author: nastazjalaskowski
"""
# Import all the required packages for the programme
import csv # for reading and writing files
import matplotlib
matplotlib.use('TkAgg') # allows selecti... |
import TreeNode
class Solution:
def is_mirror(self, left: TreeNode, right: TreeNode) -> bool:
if left is None and right is None:
return True
if left is None or right is None:
return False
return left.val == right.val and (
self.is_mirror(left.right, righ... |
import random
import string
def key_generator():
letters = string.ascii_lowercase
key = ''.join(random.choice(letters) for i in range(26))
return key
message = ""
keycode = ""
enc_message = ""
def remove(string):
return string.replace(" ", "")
def vigenere_encryption(plaintext, key):
cipher... |
"""
A module defining routines for creating antenna array configurations. Input arguments for each function are
arbitrary, but the return value is always a dictionary with keys representing antenna numbers, and values
giving the 3D position of each antenna.
"""
import numpy as np
def linear_array(nants, sep=14.6):
... |
from typing import List, Dict, Set, Callable
import enum
class Parity(enum.Enum):
ODD = 0
EVEN = 1
def gen_list(start: int, stop: int, parity: Parity) -> List[int]:
"""
Creates a list that starts at the variable start (inclusive) and ends at the
variable stop (exclusive). It will give you even o... |
import numpy as np
# import matplotlib.pyplot as plt
#y_array must be given with float elements at this point.
#box_half_width will determine the size of the box.
def marginalize(y_array, box_half_width):
size = len(y_array)
y_marg = np.zeros((size))
for indice, element in enumerate(y_array):
#Keep the first few ... |
n=int(input())
if(n>=5):
if(n%5!=0):
print (n//5+1)
else:
print (n//5)
else:
print (1)
|
s=0
for i in range(1,1000):
if i%3==0 or i%5==0:
s+=i
print (s)
|
#function Template for python3
"""
# Node Class
class node:
def __init__(self, val):
self.data = val
self.next = None
"""
# your task is to complete this function
# function shouldn't return anything
# use self.head to access head in the method
def reverseList(self):
# Code here
if self.... |
class Square:
def __init__(self, edge):
self.edge = edge
def calculate_area(self):
area = self.edge ** 2
return area
def calculate_circuit(self):
circuit = 4 * self.edge
return circuit
square_1 = Square(5)
print(square_1.calculate_area())
|
#access = False
with open("logins.txt", "r") as check_file:
username = str(input("Enter your username: "))
password = str(input("Enter your password: "))
for check in check_file:
u_name, u_pass = check.strip().split(":")
if username == u_name and password == u_pass:
prin... |
#Write a program to ask the user for numbers, and then print any repeating numbers in a list. Example:
#Enter a number: 5
#Enter a number: 2
#Enter a number: 6
#Enter a number: 98
#Enter a number: 7
#Enter a number: 6
#Enter a number: 5
#Enter a number: x
#Repeating numbers: [5, 6]
import collections
... |
#Design a repetition loop that ask for the number of times a loop should run.
#In the loop, a number will be entered and a running total of the numbers entered in each iteration of the loop will be calculated.
#This total will be printed once you exit the loop.
#total = 0
number = int(input("Enter a number: "))... |
#Write a program to compare two strings. Get a password from the user. If the password is “Rela238#” accept the password.
#Otherwise inform the user that the password is incorrect. Set the password using a variable at the start of the program.
password = str("Rela238#")
user_pass = str(input("Please, enter... |
#Write a python script that keeps asking for names, until they enter an empty name,
#then creates a file called 'people.txt' and adds names on a separate line.
name = 0
with open("people.txt", "w") as filename:
while name != "":
name = input("Enter any name: \n")
filename.writelines(str(nam... |
#Design a program that simulates the toss of a coin. It generates 1 and 2 .
#Designate 1 as head and 2 as tail. Import random function and use randint option.
#Toss the coin 10 times. Count the number of heads and tails and print them.
#Modify the program and use a while loop with an option to let the user quit t... |
import random
score_human = 0
score_machine = 0
choices = ["rock", "paper", "scissors"]
print("Rock wins sciccors. Scissors cut paper. Paper covers rock.")
player = input("Choose rock, paper or scissors. If you want to quit, print 'Quit': \n")
while player == True:
player = player.lower()
comp... |
def comb(n,k):
if n < k:
print("Impossible!")
if n == k:
return [[i for i in range(1, n + 1)]]
if k == 1:
return [[i] for i in range(1, n + 1)]
result = list()
sub = comb(n - 1, k)
sub2 = comb(n - 1, k - 1)
for j in sub2:
j.append(n)
result.append(j)
... |
import unittest
from geometry import Rectangle
from geometry import Square
class SquareTest(unittest.TestCase):
def test_square_is_a_derivative_of_rectangle(self):
square = Square(0, 0, 5)
self.assertTrue(isinstance(square, Square))
# self.assertTrue(isinstance(square, Rectangle))
... |
import math
class Point(object):
z = 5
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, point):
return math.sqrt((point.y - self.y) ** 2 + (point.x - self.x) ** 2)
def __eq__(self, other_point):
return self.x == other_point.x and self... |
import pyttsx3
from datetime import datetime
import speech_recognition as sr
import pyaudio
import wikipedia, os
import webbrowser
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 8 01:18:51 2016
@author: songxf
"""
hour=input('Enter hours you worked:')
try:
hour=int(hour)
rate=input('Enter your wage rate:')
try:
rate=int(rate)
print(hour*rate)
except:
print('Error,please enter numeric input')
except:
p... |
# -*- coding: utf-8 -*-
"""
Created on 15:20 2016/10/15
author songxf
"""
usf=input('Enter the US Floor:') #在Python3中input返回一个string,可使用int(some_string)将其转化成为一个整数
usf=int(usf)
wf=usf-1
print('Non-US Floor Number is',wf)
movies=list()
movie1=dict()
movie1['Director']='James Cameron'
movie1['Title']='Avatar'
movi... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 7 20:43:01 2016
@author: songxf
"""
astr="Hello Bob"
try:
istr=int(astr)
except:
istr=-1
print('First',istr)
astr='123'
try:
istr=int(astr)
except:
istr=-1
print('Second',istr) |
class Heap:
def __init__(self, value):
self.array = list()
self.array.append(None)
self.array.append(value)
def insert_check(self, inserted_idx):
if inserted_idx <= 1:
return False
parent_idx = inserted_idx // 2
if self.array[inserted_idx] > self.... |
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class NodeControl:
def __init__(self, data):
self.head = Node(data)
# Data 삽입
def insert(self, data):
if self.head == '':
self.head = Node(data)
e... |
'''
Write two function to convert temperatures to and from celsius, fahrenheit.
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ]
Expected Output :
60°C is 140 in Fahrenheit
45°F is 7 in Celsius
'''
temperature = input('Enter a celcious or faherenheit number: ')
... |
''' Various scoring metrics. '''
__all__ = ['count', 'levenshtein_distance']
def count (seq, default=1) :
''' Score a sequence based on how many times it has been encountered. '''
try :
return seq.count if not callable(seq.count) else default
except AttributeError :
return default
def l... |
''' This module covers the representation of objects when they're being printed to the screen (with the <__repr__>
magic method). This makes reading outputs slightly more pleasant. '''
from itertools import chain
__all__ = ['represented_nonliterally', 'represented_literally', 'pretty_truncate', 'pretty_string', ... |
''' Tools for dealing with multithreaded programs. '''
from concurrent.futures import ThreadPoolExecutor, as_completed
from nlplib.general.iterate import chunked
__all__ = ['simultaneously']
def simultaneously (function, iterable, max_workers=4) :
''' This runs the given function over the iterable concurrently... |
from game.dealer import dealer
class Director:
"""A code template for a person who directs the game. The responsibility of
this class of objects is to keep track of the score and control the
sequence of play.
Attributes:
"""
def __init__(self):
"""The class constructor.... |
class Document:
def __init__(self, filename):
self.characters = []
self.cursor = Cursor(self)
if len(filename) == 0:
raise FileNameInvalid("Invalid filename")
else:
self.filename = filename
def insert(self, character):
if not hasattr(character, '... |
import csv
import pandas as pd
import plotly.express as px
df = pd.read_csv("./data.csv")
score_list = df["Score"].tolist()
accepted_list = df["Accepted"].tolist()
fig = px.scatter(x = score_list, y = accepted_list)
fig.show()
import numpy as np
score_array = np.array(score_list)
accepted_array = ... |
#!/usr/bin/env python
# coding: utf-8
# <h1>The Sparks Foundation<h1>
# <h2>Task#2: Prediction using Unsupervised ML<h2>
# <h4>From the given ‘Iris’ dataset, predict the optimum number of clusters and represent it visually.<h4>
# <h3>Author: Muhammad Yazdan<h3>
# In[ ]:
import numpy as np
import pandas as pd
import... |
class classemp:
empcnt=0
def __init__(self,name,fam,dep,sal):
self.name=name
self.fam=fam
self.sal=sal
self.dep=dep
classemp.empcnt+=1
def display(self):
print("name:",self.name,"\tFamily name:",self.fam,"\tDepartment:",self.dep,"\tsalary:",self.sal)
class fulltimeemp(classem... |
#!/usr/bin/env python
""" A chatbot that greets people
"""
import random
greetings = set('hola hello hi Hi hey! hey'.split())
question = {'How are you?','How are you doing?'}
responses = set("Okay | I'm fine".split(" | "))
def conversation_start():
while True:
user_input = input(">>> ")
if user_i... |
"""
Bully Stock Market
"""
from yahoo_finance import *
import urllib2
import webbrowser
class Stock:
def __init__(self, stock):
self.stock = str(stock)
self.search_stock()
incorrect = True
while incorrect:
try:
self.yahoo = Share(sel... |
"""
Author: RedFantom
License: MIT License
Copyright (C) 2018 RedFantom
"""
from database import open_database, execute_query
"""Open the Database"""
connection = open_database("northwind.db")
"""List all tables"""
query1 = """SELECT name FROM sqlite_master WHERE type='table';"""
tables = execute_query(connection, ... |
import time
import random
def sequential_search(lists, item):
"""search function.
Args:
lists(list): list of data.
item(mix): search value.
Returns:
Returns tuple.
Examples:
>>> search(lists, 10)
(True, 2.2172927856445312e-05)
"""
init_time = time.time(... |
#William Brown
#CIS129 with Gregory Wagner
#Date 4/3/2017
#Module 6 Driver's Test Exam Assignment
#To get full points you will need to have and use: an array for the correct answers, an array for the answers given, and a function passing an array by reference.
#Your program should store these correct answers in a list... |
import os
def renaming():
#variables
savedPath = os.getcwd()
print("Current Directory " + savedPath)
# 1) get the file name and open it
fileList = os.listdir("/Users/jamekaechols/Desktop/PythonShenanigans/HiringManagersOpenME")
print(fileList)
os.chdir("/Users/jamekaechols/Desktop/Python... |
class DebugClass:
"""
Clase preparada para que cualquier clase la herede
Al activar el modo debug, las funciones de esta clase se ejecutan
Si se tiene desactivado, pasan como si no existiesen
"""
__debug_mode: bool = False
@property
def _debug_mode(self) -> bool:
return self.__d... |
a = "Hello World"
print(a[1])
a = "Hello World"
print(a[2:5])
a = "Hello World"
print(a.strip())
a = "Hello World"
print(a.lower())
a = "Hello World"
print(a.upper())
a = "Hello World"
print(a.replace("H", "J"))
a = "Hello World"
print(a.split(",")) |
a = float(input('Informe o Primeiro lado do triângulo: '))
b = float(input('Informe o Segundo lado do triângulo: '))
c = float(input('Informe o Terceiro lado do triângulo: '))
if (a + b < c) or (a + c < b) or (b + c < a):
print('\n Nãoo é um triângulo')
elif (a == b) and (a == c):
print('\n O tipo desse triân... |
import speech_recognition as sr
import gtts,os
from translate import Translator
r=sr.Recognizer()
with sr.Microphone() as source:
print("SPEAK SOMETHING")
audio = r.listen(source)
t=r.recognize_google(audio)
print("you said :" ,format(t))
print("TIME'S UP..........THANKS")
print(" PLEASE ENT... |
# With an empty list and a for loop and then to append to list
squares = []
for i in range(1, 101):
squares.append(1**2)
print(squares)
# This gives you a list from 1 to 10000, each number squared
#Now with list comprehension
squares2 = [i**2 for i in range(1, 101)]
print(squares2)
# Does the same work as for... |
def print_stats(f):
"""Too bad there is no overloading in Python"""
import pandas as pd
if isinstance(f, pd.DataFrame):
frame_stats(f)
else:
series_stats(f)
def frame_stats(df):
"""Prints summary information about DataFrame"""
import numpy as np
print('\n')
print(df.columns)
print('\nCOL\t MIN\t MAX\t MEA... |
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import numpy as np
import argparse
# Function to reverse array which will be called recursively
def reverseArray(array, start, end):
"""
array : input array to reverse
start : starting index of the array
end : ending index of the array
"""
# Check if you have already gone through the array
... |
def get_split_point(number_list, first_index, last_index):
pivot_value = number_list[first_index]
left_position = first_index + 1
right_position = last_index
done = False
while not done:
while left_position <= right_position and number_list[left_position] <= pivot_value:
left_... |
def bank():
class BankAccount:
bank_name = "YourPay"
def __init__(self, balance=0):
self.name = "User name"
self.balance = balance
def greet(self, name):
print(f"Welcome {name} :) \nwhat would you like todo ? ")
def deposit(self, money):
... |
# An object could represent an animal with proerties like name, age, breed, behaviors etc
# Classes include methods, variables and can be used as a blueprint to produce many objects with the same properties and behaviors. The obects of a class are called instances.
class Dog:
species = 'mammal'
def __init__(self, n... |
"""
날짜 : 2021/04/29
이름 : 김진우
내용 : 실습 튜플 객체 예 교재 p93
"""
# (1) 원소가 한 개인 경우
t = (10, )
print(t)
# (2) 원소가 여러 개인 경우
t2 = (1,2,3,4,5,3)
print(t2)
# (3) 튜플 색인
print(t2[0], t2[1:4], t2[-1])
# (4) 수정 불가
# t2[0] = 10 # error
# (5) 요소 반복
for i in t2 :
print(i, end=' ')
# (6) 요소 검사
print('\n') # 그냥 줄바꾼 것
if 6 in t2 :
... |
"""
날짜 : 2021/04/27
이름 : 김진우
내용 : 실습 관계연산자 예 교재 p40
"""
num1 = 2
num2 = 1
# (1) 동등비교
bool_result = num1 == num2 # 두 변수의 값이 같은지 비교
print(bool_result)
bool_result = num1 != num2 # 두 변수의 값이 다른지 비교
print(bool_result)
# (2) 크기비교
bool_result = num1 > num2 # num1값이 큰지 비교
print(bool_result)
bool_result = num1 >= num2 # num1값... |
"""
날짜 : 2021/04/27
이름 : 김진우
내용 : 실습 외부상수 출력 예 교재 p47
"""
name = "홍길동"
age = 35
price = 125.456
# (6) 외부 상수 인수
print("이름 : {}, 나이 : {}, data={}".format(name,age,price))
print("이름 : {1}, 나이 : {0}, data={2}".format(age,name,price))
# (7) format 축약형(SQL문 작성)
uid = input("id input : ")
query = f"select * from member wher... |
"""
날짜 : 2021/04/29
이름 : 김진우
내용 : 실습 추가,삭제,수정,삽입 예 교재 p88
"""
# (1) 단일 리스트 객체 생성
num = ['one','two','three','four']
print(num) # ['one','two','three','four']
print(len(num)) # 4
# (2) 리스트 원소 추가
num.append('five') # 추가
print(num) # ['one','two','three','four','five]
# (3) 리스트 원소 삭제
num.remove('five') # 삭제
print(num)
... |
"""
날짜 : 2021/04/27
이름 : 김진우
내용 : 파이썬 조건문 if 실습 교재 p60
"""
# if - ()와{} 를 사용하지않고 조건 뒤에 : 를 쓰고 들여쓰기를 사용
num1, num2 = 1, 2
if num1 > 0:
print('num1은 0보다 크다.')
if num1 > num2:
print('num1은 num2 보다 크다.')
if num1 > 0:
if num2 > 1:
print('num1은 0보다 크고 num2는 1보다 크다.')
if num1 > 0 and num2 > 1:
print(... |
import re
import sys
def solve(l):
word, segment = l.split(',')
# Apparently sometimes segment has some other non-standard/working regex char
if re.findall(segment, word):
return 'true'
else:
return 'false'
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
l = ... |
def map(f,lis):
#new_lis=[]
#for elem in lis:
# new_lis.append(f(elem))
#return new_lis
return [f(elem) for elem in lis]
def func(x):
return x+2
def func1(x):
return x+3
n=[10,20,30]
print(map(func1,map(func,n)))
def reduce(g,init,lis):
sum=init
temp=lis[0]
for i in lis:
... |
import numpy as np
import matplotlib.pylab as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def step_function(x):
return np.array(x > 0, dtype=np.int)
def relu(x):
return np.maximum(0, x)
x = np.arange(-5.0, 5.0, 0.1)
y1 = step_function(x)
y2 = sigmoid(x)
y3 = relu(x)
plt.plot(x, y1, label="step fun... |
class Song:
def __init__(self,name):
self.__name = name
def set_name(self,name):
self.__name = name
def get_name(self):
return self.__name
def __str__(self):
return 'The name of song is:' + str(self.__name) |
import turtle
def drawPolygon(t, sideLength, numSides):
for i in range(6):
t.forward(sideLength)
t.left(numSides)
def main():
wn = turtle.Screen()
wn.bgcolor("Lightgreen")
alex = turtle.Turtle()
drawPolygon(alex, 150, 60)
drawCircle(alex, 150)
wn.exitonclick()
def dra... |
list = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
target = 15
def binary_search(target):
low = 0
high = len(list) - 1
while low <= high:
mid = int((low + high)/2)
if target == list[mid]:
return mid
elif target < list[mid]:
high = mid-1
... |
import Movie
from .song import Song
import csv
# Write program that allows a user to perform binary search on a collection of Movie/Song objects
# Ask user to enter name of movie/song
# Write program that makes a list of 100 random numbers between 1-100.
# Sort it using selection or insertion sort, then print lis... |
# https://www.geeksforgeeks.org/longest-increasing-subarray/
def solution(arr):
i = m = l = 1
while i < len(arr):
if arr[i] > arr[i-1]:
l = l + 1
else:
if m < l:
m = l
l = 1
i = i + 1
if m < l:
m = 1
return m
print... |
import time
import asyncio
'''
steps:
- create event loop to handle coroutine
- create coroutine function (async)
- create await to this coroutine for async progress
NOTE: do not use any sunc function in coroutine (EX - time.sleep())
'''
def is_prime(x):
return not any(x//i == x/i for i in range(x-1... |
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
class AnimatedScatter(object):
"""An animated scatter plot using matplotlib.animations.FuncAnimation."""
def __init__(self):
self.stream = self.data_stream()
# ... |
__author__ = 'rcarino'
# dijkstra to find shortest path in matrix
import sys
from heapq import heappush, heappop
small_m = [
[131, 673, 234, 103, 18],
[201, 96, 342, 965, 150],
[630, 803, 746, 422, 111],
[537, 699, 497, 121, 956],
[805, 732, 524, 37, 331]
]
def shortest_path(m, goal_x,goal_y):
... |
import datetime
start = datetime.datetime.now()
def get_divisors(n):
divisors = []
for i in reversed(xrange(1, n/2 + 1)):
if n % i == 0:
divisors.append(i)
return divisors
def is_abundant(n):
if sum(get_divisors(n)) > n:
return True
return False
# The naive approach tak... |
__author__ = 'rcarino'
def is_pandigital(n):
s = set()
i = 1
while s != set(str(123456789)):
cur = n * i
new_s = set(str(cur))
if len(new_s) != len(str(cur)) or s & new_s:
return False
i += 1
s |= new_s
return True
def get_prod(n):
i = 1
s = ... |
from turtle import *
import turtle
def my_test():
speed(10)
penup()
seth(180)
fd(200)
seth(0)
penup() #外圈头
circle(150, 40)
pendown()
fillcolor('dodgerblue')
begin_fill()
circle(150, 280)
end_fill() #外圈头
fillcolor("red")
begin_fill() #外圈头
seth(0) #... |
def madLibs():
adjective = input("Please enter an adjective: ")
noun = input("Please enter a noun: ")
verb_past = input("Please enter a verb, past tense: ")
second_adjective = input("Enter another adjective: ")
final_adjective = input("Enter another adjective: ")
final_noun = input("Enter anothe... |
# Jessica Oh Hui Yu
import sys
from suffixTree import *
def traverseToSuffixIndex(node, suffixIndexesList):
"""
This function traverses down until the leaves to get the suffix indexes and creates the suffix array using recursion.
:param node:
:param suffixIndexesList:
:return:
complexity: wor... |
# Jessica Oh Hui Yu
# 29886465
# FIT3155 Advanced algorithms and data structures
# Assignment 3
# Task 1
import sys
import random
def dec2binbits(dec):
"""
This function converts an integer with base 10 (dec) to binary.
:param dec:
:return: binaryList
:complexity worse case = O(log(N))
where N... |
"""The birthday paradox says that the probability that two people in a room
will have the same birthday is more than half, provided n, the number of
people in the room, is more than 23. This property is not really a paradox,
but many people find it surprising. Design a Python program that can test
this paradox by a... |
#Write a Python program that can take a positive integer greater than 2 as
#input and write out the number of times one must repeatedly divide this
#number by 2 before getting a value less than 2.
def division_count(x):
count=0
if x>2:
while x>2:
x=x/2
count+=1
... |
from functools import reduce
class Solution
def reverseWords(self, s: str) -> str:
flag = True
for i in range(len(s)):
if s[i] != ' ':
start = i
flag = False
break
words = []
if flag:
return ''
s += ' '... |
class Solution:
def fib(self, n: int) -> int:
return self.iteration(n)
def recursive(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
return self.recursive(n-1) + self.recursive(n-2)
def iteration(self, n: int) -> int:
h = [0, 1]... |
from typing import List
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
s = 0
for i in range(len(nums)):
s += nums[i] if i % 2 == 0 else 0
return s
if __name__ == "__main__":
nums = [6, 2, 6, 5, 1, 2]
s = Solution()
print(s.arra... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head is None or head.val is None:
return head
n = 1
t = p = head
wh... |
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
self.... |
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> bool:
# we need to know where this sequence is sorted.
# if nums[mid] == nums[start], start += 1
# if nums[mid] > nums[start], nums[start:mid] is sorted
# if nums[mid] < nums[end], nums[mid:en... |
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not ro... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution :
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
p_a, p_b = headA, headB
while p_a and p_b:
p_a = p_a.next
... |
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
return self.method2(nums)
def method1(self, nums):
t = 0
i = 1
while i < len(nums):
if nums[i] == nums[i - 1]:
t += 1
else:
t = 0... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
... |
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s3) != len(s1) + len(s2):
return False
if len(s3) == 0:
return True
if len(s1) == 0:
return s2 == s3
if len(s2) == 0:
return s1 == s3
self.s1 = s1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.