text stringlengths 37 1.41M |
|---|
import numpy as np
import cv2
# Load the Image
img = cv2.imread("assets/logo.jpg", cv2.IMREAD_GRAYSCALE)
# Available mode while reading an image
# -1, cv2.IMREAD_COLOR : Loads in color image, Any transparency of image will be neglected, its the default flag
# 0, cv2.IMREAD_GRAYSCALE : loads an image in grayscale
... |
import re
# 常规方式驼峰转小写下划线
def convert_Camel_to_low_underline(str):
str_camel = ''
x = 0
for s in str:
if (x != 0 and s.islower() == False):
s = '_' + s
str_camel += s
x += 1
return str_camel.lower()
# 正则方式驼峰转小写下划线
def convert_Camel_to_low_underline_by_regular(st... |
# The following functions allow addition, subtraction, mult, etc
# to take an arbitrary number of arguments (as opposed to just two)
def add(args):
return sum(args)
def subtract(args):
return reduce(lambda x,y: x-y, args)
def mult(args):
return reduce(lambda x,y: x*y, args)
def div(args):
return red... |
#fibonacci sequence
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
print('Fibonacci Sequence:')
fib(2000)
print()
#Calculate factorial of n
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
#Call ... |
n = input()
# Try convert input to integer, otherwise say alert and quit
try:
n = int(n)
except:
print('Please enter a number.')
quit()
counter = 0
while counter < n:
print(counter ** 2)
counter += 1
|
a = input()
b = input()
# Try convert input to interger, otherwise say alert and quit
try:
a = int(a)
b = int(b)
except:
print('Please, enter only a number.')
quit()
integer_part = int(a / b)
floating_part = a / b
print(integer_part)
print(floating_part)
|
import os
#assumes starting directory is ~/imageLabeling
def extract_from(path):
"""
Outputs a list with the names of all files (text files and another formats) in a specific directory.
Does not find the names of files in the subdirectories.
"""
#getting user input for the right path
va... |
from random import randint as rand
import json
def generate_maze_visible(rows, cols):
'''
Returns: a tuple containing the generated maze and the visibility matrix.
'''
maze = generate_maze(rows + 2, cols + 2)
maze = [i[1:-1] for i in maze[1:-1]]
visible = [[False] * len(maze[0]) for i ... |
example_puzzle_input = open("example_input.txt", "r")
example = example_puzzle_input.readlines()
puzzle_input = open("input.txt", "r")
puzzle = puzzle_input.readlines()
# The soonest bus is the one greater than but closest to the timestamp.
# Multiply each bus number by the ceiling division of the timestamp and bus.... |
import re
example_puzzle_input = open("example_input.txt", "r")
example_puzzle = example_puzzle_input.readlines()
puzzle_input = open("input.txt", "r")
puzzle = puzzle_input.readlines()
# *** Part 1 ***
def process_input(data):
data = [x.strip() for x in data]
fields = data[:data.index("")]
data = data[... |
import requests
import json
# class for weather api homework
# makes api requests and gets desired information
weatherundrgrnd_api_key = 'c847353b2b521fd7'
base_url = 'http://api.wunderground.com/api/{}/'.format(weatherundrgrnd_api_key)
class CurrentConditions:
def __init__(self, zipcode):
self.zipcode... |
#!/usr/bin/env python
import fileinput
def factorial(x):
if (x == 1):
return 1
else:
return x*factorial(x-1)
for line in fileinput.input():
x = 1
sum = int(line)
while factorial(x) < sum:
x += 1
x -= 1
factoradic = ""
factSum = 0
while x >= 1:
temp = 0
whi... |
import random
def getKthDigit(n, k):
if n < 0:
n *= -1
n //= (10**k)
return n%10
def countMatchingDigits(x, y):
strX, strY = str(x), str(y)
count = 0
for digit in strX:
for yDigit in strY:
if digit == yDigit:
count += 1
return count
def playPig(... |
# OOP, Linked Lists, Efficiency
# 1.1
# >>> snape = Professor("Snape")
#
# >>> harry = Student("Harry", snape)
# There are now 1 students
# >>> harry.visit_office_hours(snape)
# Thanks, Snape
# >>> harry.visit_office_hours(Professor("Hagrid"))
# Thanks, Hagrid
# >>> harry.understanding
# 2
# >>> [name for name in snap... |
# Discussion 1: Control, Environment Diagrams
# 1.1
def wears_jacket_with_if(temp, raining):
if temp < 60 or raining:
return True
else:
return False
def wears_jacket(temp, raining):
return temp < 60 or raining
# 1.2
# >>> square(so_slow(5))
# Error: infinite loop. x will always be greater
# than zero so we ne... |
class person:
def __init__(self,mame,age,gendar):
self.name = mame
self.age = age
self.gendar = gendar
def setdata(self):
print("i am ", self.name, "and my age is = ", self.age, "years and i am a", self.gendar)
class student(person):
def __init__(self,mame,age,gendar,subje... |
# Method Overloading
class student():
def stu_detail(self,name=None, age=None):
if(name!= None and age != None):
print("name: ",name, " and Age : ", age)
elif (name == None):
print("Age is :", age)
elif (age == None):
print("Name is : " , name)
# def ... |
total_amount = int(input('合計金額を入れてね>'))
total_number_of_people = int(input('合計人数を入れてね>'))
print(f'一人あたりの金額は{total_amount // total_number_of_people}円です。\n端数は{total_amount % total_number_of_people}円です。')
|
# Define a procedure, find_element,
# that takes as its inputs a list
# and a value of any type, and
# returns the index of the first
# element in the input list that
# matches the value.
# If there is no matching element,
# return -1.
''' way 1 '''
def find_element_1(stack,key):
pos = -1
for index in range(0,len(s... |
def checkDigit(barcode):
arrBarcode = enumerate(str(barcode))
total = 0
for index, value in arrBarcode:
value = int(value)
total += index % 2 == 0 and value * 1 or value * 3
return int(str(barcode) + str((10 - total % 10) % 10))
barcode = 275036569845
barcodeWithCheckDigit = checkDi... |
# python3
from itertools import combinations
def compute_inversions_naive(a):
"""
This naive function computes and returns the number of inversions in an array
by checking every combination of a pair of two array elements.
"""
number_of_inversions = 0
# since the input sequence "range(len(a)) ... |
#Alexandra Montgomery
#Exam Q3
def main():
cars = textFileToDictionary("Mileage.txt")
outputResult(cars)
# convert Mileage.txt into a dictionary named cars
def textFileToDictionary(fileName):
infile = open(fileName, 'r')
cars = {}
for line in infile:
split = line.split(',')
... |
class Node(object):
def __init__(self, data=None, ):
self.value = data
self.next = None
class LinkedListSingly(object):
def __init__(self, data=None):
self.head = Node(data)
self.tail = self.head
self.length = 1
def append(self, data):
self.tail.next = Node... |
money = 20000
card = 1
if money > 30000:
print("Go Taxi")
pass
elif card==1:
print("Go Bus")
else:
print("Go Work")
a = input("Input Text : ")
print(a)
print("Life","is","short")
|
def division(a, b):
"""Ésta función regresa una tupla con el cociente
y el residuo de la división de dos números enteros dados
Los valores de entrada (a,b) son el dividendo y divisor respectivamente,
las salidas q y r son el cociente y el residuo respectivamente
Ejemplo: division(7,7) = (1,0) q... |
#!/usr/bin/python
## Imports
import socket
from ast import literal_eval
## Funções
'''
Função modular entre dois números
'''
def mod(a,b): # mod function
if(a<b):
return a
else:
c=a%b
return c
def keep():
while True:
try:
b = int(input("digite 0 para cancel... |
#!/usr/bin/env python3
import os
import sys
message = sys.argv[1]
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def hackcaesar(text):
for key in range(len(LETTERS)):
translated = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
num = num - key
... |
# groupby
#
# Group an array of arrays by identity using the given field number
#
# example (group by the third value)
#
# print groupby([
# ["house", "4", "false" ],
# ["house", "3", "true" ],
# ["car", "1", "false" ],
# ["dog", "0", "false" ]
# ], 2)
#
# ... |
#GUESS THE NUMBER GAME
#Maximum chances are 5, hidden number is in Range 1-100
import random
hidden = random.randint(1, 100)
guesses = 5
while(guesses>0):
ip = int(input("Enter a num to guess the hidden number in Range (1-100)\n"))
if ip > hidden :
guesses = guesses - 1
print("guess is g... |
number = int(input('Enter a positive integer: '))
def factor(number, divisor):
if number % divisor:
return False
return True
for i in range(1, number + 1):
if factor(number, i):
print('{} is a divisor of {}'.format(i, number))
|
#! /usr/bin/python3
import struct
binary = [1, 2, 3, 4, 1024, 2048]
print('Original binary:', binary)
print('\nshort:')
for b in binary:
print(struct.pack('h', b))
print('\nlong:')
for b in binary:
print(struct.pack('l', b))
|
n = int(raw_input('Digite um numero binario: '))
decimal = 0
i = 0
while n > 0:
resto = n % 10
n /= 10
decimal = decimal + resto * 2**i
i += 1
print 'Decimal:', decimal
|
# principais sintaxes do python
# ---------------------------------------------------------------
# http://www.swaroopch.org/notes/Python_pt-br:Operadores_e_Expressoes
# operadores em Python
# operadores aritmeticos
# ** potencia
# // divisao inteira 4 // 3 retorna 1
# % modulo
# operadores relaconais
# == igual... |
'''
Problema 1.4 - Dados um número inteiro n >= 0, e uma sequência com n inteiros,
determinar a soma dos inteiros positivos da sequência. Por exemplo, para
a sequência 6, -2, 7, 0, -5, 8, 4 o programa deve escrever o número 25.
Note que no exemplo n = 6. E a sequencia é -2, 7, 0, -5, 8, 4.
Solução:
'''
n = int(input... |
n = 9
m = []
for i in range(n + 1):
m.append([])
for j in range(n + 1):
m[i].append(0)
m[0][0] = 9
m[1][1] = 9
for i in range(n + 1):
for j in range(n + 1):
print m[i][j],
print ''
|
#!/usr/bin/python
# datademo.py
# a simple script to pull some data from MySQL
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="dados")
# create a cursor for the select
cur = db.cursor()
# execute an sql query
cur.execute("SELECT name FROM dados.contatos")
# Iterate
for row in cur.... |
'''Problema 1.2 - Dados os números inteiros n e k com k >= 0, determinar n^k.
Por exemplo, dados os números 3 e 4 o programa deve escrever o número 81.
Solução:
'''
n = int(input("Digite um número: "))
k = int(input("Digite outro número: "))
resultado = 1
potencia = 0
while potencia < k:
resultado = resultado * n
... |
import sys
data = open(sys.argv[1], 'r')
data_arr = []
for line in data:
for number in line.split():
data_arr.append(number)
def res_calc(arr):
total_sum = 0
for i in range(0,50):
total_sum += float(arr[2*i])
return total_sum / 50.
print "The random rr average residue is %f." % res_... |
# Creating 3d graphics from 2d graphics
# Imports
from graphics import *
import math
from time import sleep
# TODO:
# Fix lookAt matrix
# Make lighting use 3d vectors instead of 2d
# Dont render anything thats off the screen
# Fix depth tests
# Data classes
class Vec3:
"""Holds a position in... |
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
length,index,t = len(nums),1,nums[0]
for i in nums[1:]:
if i != t:
nums[index] = i
index +... |
from matplotlib.colors import ListedColormap
import numpy as np
import matplotlib.pyplot as plt
#Perceptron class, functions as a rudimentary basis for neural nets
#Created by Elijah Flinders, 2020
class Perceptron(object):
#class initialization
def __init__(self, learning_rate = 0.01, no_iter = 10):... |
#!/usr/bin/python
import commands, os, sys, string, re, math
def files_from_list(file):
"""
returns a list of files from a file
"""
files = []
try:
MYFILE = open(file)
except:
print "unable to open file:",file
return files
for line in MYFILE:
line = line.rstrip()
files.append(line)
MYFILE.clo... |
#!/usr/bin/python
"""
vector3d.py
class for storage and manipulation of 3d data
"""
__author__ = ['Andrew Wollacott (amw215@u.washington.edu)']
__version__ = "Revision 0.1"
import math
class vector3d:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __getitem__(self, ... |
# -*- coding: utf-8 -*-
# v. python 3.7
"""
Created on Mon Nov 11 2019
@author: geoFluxus Team
"""
import pandas as pd
import matplotlib.pyplot as plt
import variables as var
# ______________________________________________________________________________
# FUNCTIONS
# ______________________________________________... |
def compress(str1):
final_length = count_compression(str1)
if (final_length >= len(str1)):
return str1
compressed = []
count_consecutive = 0
for i in range(len(str1)):
count_consecutive+=1
if (i+1 >= len(str1) or str1[i] != str1[i+1]):
compressed.append(str1[i])
... |
def is_permutation_of_palindrome(phrase):
bit_vector = create_bit_vector(phrase)
return bit_vector == 0 or check_exactly_one_bit_set(bit_vector)
def create_bit_vector(phrase):
bit_vector=0
for c in phrase:
x = get_char_number(c)
bit_vector = toggle(bit_vector, x)
return bit_vector
... |
class partial_sum:
def __init__(self):
sum1 = None
carry = 0
def add_lists(l1, l2):
len1 = get_length(l1)
len2 = get_length(l2)
if (len1 < len2):
l1 = pad_list(l1,len2-len1)
else:
l2 = pad_list(l2, len1-len2)
sum1 = add_lists_helper(l1,l2)
if (sum1.carry =... |
def count_paths_with_sum(root, target_sum):
dict1 = dict()
return count_paths_with_sum(root, target_sum, 0, dict1)
def count_paths_with_sum(node, target_sum, running_sum, path_count):
if (node is None):
return 0
running_sum += node.data
sum1 = running_sum - target_sum
total_paths = path_count[sum1] if sum1 ... |
def partition(node, x):
head = node
tail = node
while (node is not None):
next1 = node.next
if (node.data < x):
node.next = head
head = node
else:
tail.next = node
tail = node
node = next1
tail.next=None
return head
|
from autocomplete import Autocomplete
import sys, os
if __name__ == "__main__":
ac = Autocomplete('test.txt')
while True:
user_input = raw_input("Enter input: ").strip('\n')
if ac.is_word(user_input):
print "lol it's a word"
else:
print ac.closest_word(user_inp... |
import requests,openpyxl
print('What URL would you like to scrape?')
url = input()
#url = 'https://www.optus.com.au/mobile/plans/shop'
res = requests.get(url,headers={'User-Agent':'Mozilla/5.0'})
res.raise_for_status()
##Format Source Code
print('Source Code received. Saving to file.')
final_source = []
... |
from stringop import *
s=input('Enter the string:')
print('The string is:',s)
print('Reverse of',s,'is',StrRev(s))
print('No. of UpperCase:',UppCount(s))
print('No. of LowerCase:',LowCount(s))
print('The string is palindrome:',Palindrome(s))
print('The string is pangram:',Pangram(s))
|
from datetime import datetime,timedelta
now=datetime.now()
time=now.time()
print('current Time:',time)
today=datetime.today()
print('Current date:',today)
dy=today-timedelta(5)
print('5 days before current date:',dy)
print('Yesterday:',today-timedelta(1))
print('Tomorrow:',today+timedelta(1))
print('5 days af... |
ax = int(input("Value of the only purely numeric term in x "))
cyx = int(input("Coeffcient of y in equation of x "))
czx = int(input("Coeffcient of z in equation of x "))
dx = int(input("Denominator of equation of x "))
print() #Line break
ay = int(input("Value of the only purely numeric term in y "))
cxy = int(input("... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 16:06:24 2021
@author: charlelito
charlelito@yahoo.com.br
Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre
em graus Fahrenheit.
C = 5 * ((F-32) / 9).
"""
try:
print("Programa que converte temperatura de graus Fahrenheit para Celsius... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 16:36:09 2021
@author: charlelito
charlelito@yahoo.com.br
Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo
que calcule seu peso ideal, usando a seguinte fórmula:
P = (72.7*altura) - 58
"""
print("Programa que calcula seu peso ideal ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 17:06:14 2021
@author: charlelito
charlelito@yahoo.com.br
Faça um Programa que pergunte quanto você ganha por hora e o número de horas
trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês,
sabendo-se que são descontados 11% para o Imposto de R... |
from matrix_tools import eye, zeros
from Matrix import Matrix
def test_zeros():
"""
Test matrix filled with zeros of different shapes
:return:
"""
A = zeros(3)
assert A == 0 and A.shape == (3, 3)
A = zeros((10, 1))
assert A == 0 and A.shape == (10, 1)
A = zeros(((1, 5)))
assert... |
# José Emanuel Lopes Santos
# Matrícula: 201851368558
# ----------------- AV2 IA ----------------------
import random
from numpy import array
# Classe que defini os atributos de cada entrada
class Entrada():
def __init__(self, valor, pesos):
self.valor = int(valor)
self.pesos = pesos
# Gera entra... |
def productOfArray(arr):
if len(arr) == 0:
return 1
else:
return arr[0] * productOfArray(arr[1:])
arr=[1,2,3]
print(productOfArray(arr))
|
print("Nhập số: ")
n = int(input())
x = 1
if (n < 2):
x = 2
elif (n == 2):
x = 1
elif (n % 2 == 0):
x = 2
else:
for i in range(3, n, 1):
if (n % i == 0):
x = 2
if x == 1:
print(" là số nguyên tố")
else:
print(" không phải là số nguyên tố") |
# ex005.py
# -- coding: utf-8 --
name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
height_in_metric = height * 2.54 # centimenters
weight_in_metric = weight * 0.453592 #kilograms
print "Let's talk about %s." % name
print "He's %d inches tal... |
# ex001.py
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
# 1. Make your script print another line.
print 'This is me printing another line. Whee.'
# 2. Make your script print only... |
from tkinter import *
root = Tk()
num = 0
num1 = 0.0
num2 = 0.0
operator = '?'
ctr = 0
answer = 0.0
displaystr = StringVar()
canvas = Canvas(root, width=400, height=600)
canvas.grid(columnspan=4, rowspan=6)
# Code
def calculate(x, y, z):
if (z == '/' and y==0): ... |
'''All submissions for this problem are available.
A Little Elephant and his friends from the Zoo of Lviv like candies very much.
There are N elephants in the Zoo. The elephant with number K (1 ≤ K ≤ N) will be happy if he receives at least AK candies. There are C candies in all in the Zoo.
The Zoo staff is intereste... |
#!/usr/bin/python2
class Person:
def __init__(self,name):
self.name = name
def sayHi(self):
print("ink")
print('hello' , self.name)
p = Person('world')
p.sayHi()
|
'''
Yizhuo Wu 14863527
'''
import my_points
import math
class Disc:
'''
This class will initialize the point of user's clicked point.
'''
def __init__(self,center: my_points.Disc,radius_frac: float,color:str):
'''
This function will initialize the center, radius and color of... |
#!/usr/bin/python3
class MRUQueue:
q = []
def __init__(self, n: int):
self.q.clear()
for i in range(n):
self.q.append(i + 1)
def fetch(self, k: int) -> int:
e = self.q[k - 1]
self.q.remove(e)
self.q.append(e)
return e
obj = MRUQueue(3)
print(f... |
def reverse_num(n_list):
sum_list = []
for i in range(0, len(n_list)):
reverse_num = ""
for j in range(1, len(n_list[i])+1):
reverse_num += n_list[i][len(n_list[i])-j]
sum_num = int(n_list[i]) + int(reverse_num)
sum_list.append(sum_num)
return sum_list
def sa... |
node = int(input())
tree_info = [[] for _ in range(node + 1)]
for _ in range(node - 1):
parent, child, length = map(int, input().split())
tree_info[parent].append((child, length))
# BFS함수로 정렬하기
def bfs(graph_list, start):
visited = []
queue = [start]
while queue:
node = queue.pop(0)
... |
N = int(input())
N_list = []
for i in range(0, N):
N_list.append(input())
# N_list = ["but", "i", "wont", "hesitate", "no", "more", "no", "more", "it", "cannot", "wait", "im", "yours"]
N_list = list(set(N_list))
N_list.sort()
len_list = []
for i in range(0, len(N_list)):
len_list.append(len(N_list[i]))
for... |
class Solution:
def solveEquation(self, equation: str) -> str:
a, b = equation.split('=')
if a[0] != '-':
a = '+' + a
if b[0] != '-':
b = '+' + b
n= self.getx(a.replace('+x', '+1x').replace('-x','-1x'))
m= self.getx(b.replace('+x', '+1x').replace('-x'... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
c = self.getnum(l1) + self.getnum(l2)
ls = []
if c == 0:
ls.appe... |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [{} for _ in range(9)]
columns = [{} for _ in range(9)]
boxes = [{} for _ in range(9)]
for i in range(9):
for j in range(9):
num = board[i][j]
box_index = i//3+... |
'''
1. 숫자 및 문자열 분리 (파이썬)
문자와 숫자가 섞인 문자열을 입력받은 후, 숫자와 문자를 분리하시오.
input:
"c910m6ia 1ho"
output:
str : cma ho
int : 91061
'''
text = "c910m6ia 1ho"
def Separate(text):
strings = ''
integer = ''
for i in text:
if i.isdigit():
integer += i #
else:
strings += i
prin... |
'''
1. a = [1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
# 앞쪽 절반을 출력해 보세요.
# 뒤쪽 절반을 출력해 보세요.
# 거꾸로 출력해 보세요.
# 거꾸로 짝수 번째만 출력해 보세요.
# 거꾸로 홀수 번째만 출력해 보세요.
'''
a = [1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
print(a[:5])
print(a[5:])
print(a[::-1])
print(a[-2::-2])
print(a[::-2])
'''
피보나치 수열 구하기
13
피보나치 수열이란, 첫 번째 항의 값이 0이고 두 번째 항의 값이 1일 때, 이후의 항들은 ... |
choice=int(input("1.Even\n2.Odd\n"))
num=int(input("Enter The Limits\n"))
for i in range(1,num+1):
if(choice==1 and i%2==0):
print(i)
if(choice==2 and i%2!=0):
print(i)
else:
print() |
lower =int(input("Enter Lower Limits"))
upper =int(input("Enter Upper Limits"))
print("Prime numbers between",lower,"and",upper,"are:")
for i in range(lower,upper + 1):
if i > 1:
for j in range(2,i):
if (i % j) == 0:
break
else:
print(i)
print("Composites numbers b... |
m=[10,20,30,40,50,60,70,80,90,100,110]
def search (m,num):
l=0
u=len(m)
while(l<=u):
mid=(l+u)//2
if m[mid]==num:
print("Found")
break
else:
if(m[mid]<num):
l=mid
if(m[mid]>num):
u=mid
if(num<... |
import Login
def main():
print("Enter Your choise")
print("1. SignUp")
print('2. LogIn')
print()
choise=input()
if(choise=='1'):
Login.signup()
elif(choise=='2'):
username = input ("Enter Mail Id")
password = input ("Enter Password")
Login.login(username,passw... |
x=int(input("Enter a 4 digit number"))
digit1=x//1000
stage1=x%1000
digit2=stage1//100
stage2=stage1%100
digit3=stage2//10
digit4=stage2%10
if(digit1%2==0):
digit1=0
else:
digit1=digit1
if(digit2%2==0):
digit2=0
else:
digit2=digit2
if(digit3%2==0):
digit3=0
else:
digit3=digit3
if(digit4%2==0):
digit4=0
else:
di... |
#import nltk
from nltk.tokenize import sent_tokenize,word_tokenize
#nltk.download()
#tokenizing - word tokenizing and sentence tokenizing
#corpora - body of text: ex: medical journals, prersidental speech
#lexicon - word and their means
#invester-speak .. regular english-speak
#investor speak 'bull' = someone who ... |
def shell_sort(list):
n = len(list)
# 初始步长
gap = n // 2
while gap > 0:
for i in range(gap, n):
# 每个步长进行插入排序
temp = list[i]
j = i
# 插入排序
while j >= gap and list[j - gap] > temp:
list[j] = list[j - gap]
j -... |
import socket
import ssl
def parsed_url(url):
"""
手写url解析函数,有的函数本身美不起来,只能老老实实写
:param url:
:return: (protocol host port path)
"""
# 检查协议
protocol = 'http'
if url[:7] == 'http://':
u = url.split('://')[1]
elif url[:8] == 'https://':
protocol = 'https'
u = url... |
# 一个 Set 的类, 无序且元素不重复,内部使用数组来存储元素
class Set(object):
def __init__(self, *args):
self.data = []
for x in args:
self.add(x)
def __repr__(self):
ds = [str(x) for x in self.data]
s = ', '.join(ds)
m = '{' + '{}'.format(s) + '}'
return m
def __eq__(se... |
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
numbers = [11,12,13,14,15,16,17,18]
done = False
i = 2
c = 0
b = 0
while not done:
a = 19 * i
b =... |
import re
def checkCondition(number):
string = str(number)
isAscending = lambda a: all(a[i] <= a[i+1] for i in range(len(a)-1))
hasTwoAdjacents = lambda a: any(a[i] == a[i+1] or a[i] == a[i-1] \
for i in range(1,(len(a) - 1)))
return isAscending(string) and hasTwoAdj... |
"""
Author: D Jayme Green
Extracts the data from the csv given by the NCAA D1 Lacrosse
that I care about (the percentage and per game) that happen to be at
the end of the rows
"""
import csv
"""
Reading in the .csv file and putting it into listOfData which
has the team name and then the data that I want (happens to b... |
# Create the FlightService enumeration that defines the following items (services):
# snack, free e-journal, priority boarding, selection of food and drinks,
# free onboard wifi, and an item for cases when services are not specified.
#
# Create the Passenger class with the following attributes:
# - name - passenger nam... |
# %%
def search4vowels(word: str) -> set():
"""Search vowels in the input word."""
vowels = 'aeiou'
found = search4letters(word, vowels)
return found
def search4letters(phrase:str, letters4search:str) -> set():
"""Search the letters4search in the phrase."""
found = sorted(list(set(letters4searc... |
def countdown(a):
for a in range (a,0,-1):
print(a)
print(countdown(9))
def printreturn(a,b):
print(a)
return b
print(printreturn(5,7))
def first_length(a):
sum = a[0] + len(a)
return sum
print(first_length([1,2,3,4,5,6,10]))
def values(a):
b = []
if len(a) < 2:
return F... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 10:12:18 2019
@author: sundooedu
"""
def add(a,b):
return a+b
if __name__ == '__main__':
print(add(3,4))
print(__name__)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 10:08:39 2019
@author: sundooedu
"""
def add_mul(choice, *args):
if choice == "add":
result = 0 # 0값으로 초기화
if(args==True):
for i in args:
result = result + i
elif choice == "mul":
res... |
#!/usr/bin/env python
# coding: utf-8
# In[30]:
#Programmer: Henri Geneste
#Student ID#: 1675311
#Date: 1/25/2019
#Compiler Used: Jupyter Notebooks (Hyperion.ucsc.edu)
#Purpose: Calculate average GPA of a student with user inputted data
#Initial Conditions
done = str('nope')
totalCredits = 0.0
totalGrade = 0.0
#Ma... |
"""
"17" 3
"011" 2
print(list("17"), list("011"))
"""
from itertools import permutations
# def solution(numbers):
# answer = 0
# lst = list(numbers)
# lst_length = len(lst)
#
# for i in range(len(lst)):
# for j in range(len(lst)):
# # if i != j:
# lst.ap... |
'''for 문을 이용해서 1~10 까지의 숫자 중 홀수만 출력하기. 단, if문은 쓰지 말 것'''
# for i in range(1, 11, 2): # hint: range 함수를 이용할 것
# print(i)
# hint
# for i in range(0, len(number)):
# if number[i] % 2 == 0:
# cnt += 1
# print("짝수")
# else:
# cnt02 += 1
# print("홀수")
''' for 문과 if 문을... |
#!/bin/python3
n= int(input())
if n<1 or n>100:
n=int(input())
exit()
x=n%2
if x!=0:
print("Weird")
elif n==2 or n==4:
print("Not Weird")
elif n>6 and n<=20:
print("Weird")
elif n>20:
print("Not weird")
|
year= int(input())
l= False
t= True
def is_leap(year):
if year%4!=0:
return l
elif year%100==0:
if year%400==0:
return t
else:
return l
else:
return t
print(is_leap(year))
|
class Node():
def __init__(self, data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def append(self,data):
new_node = Node(data)
if self.head ... |
class EventDispatcher(object):
'''
A simple framework for event handlers or Observer Pattern.
Define a class for observers and handler methods.
Event handlers' names must be the lower case of the event name.
>>> class Observer(object):
... @EventDispatcher.event_handler
... def on_clic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.