text stringlengths 37 1.41M |
|---|
#the code for ultrasonic sensor is adapted from "https://gist.github.com/eyllanesc/f8464b57e091777a5aef48fdd9ea9067"
import RPi.GPIO as GPIO
import time
from datetime import datetime #
from datetime import date
class ProjectTwo(object):
"the class for the project to meausre the distance and based on teh distance... |
import pandas as pd
import numpy as np
df = pd.read_csv('carbonemissiondata.csv')
list_of_lists = df.values.tolist()
my_formatted_list = [[np.round(float(i), 3) for i in nested] for nested in list_of_lists]
print(my_formatted_list) |
#! /usr/bin/env python3
import argparse
import os
import re
import sys
from datetime import datetime
from datetime import datetime
import os
def input_to_python(date_input):
return date_input.replace('YYYY', '%Y').replace('YY', '%y').replace('MM', '%m').replace('DD', '%d')
def input_to_regex(date_input):
re... |
import simple_draw as sd
def rainbow(point, radius, step):
rainbow_colors = (sd.COLOR_RED, sd.COLOR_ORANGE, sd.COLOR_YELLOW, sd.COLOR_GREEN,
sd.COLOR_CYAN, sd.COLOR_BLUE, sd.COLOR_PURPLE)
for i in rainbow_colors:
radius += step
sd.circle(center_position=point, radius=rad... |
# -*- coding: utf-8 -*-
# Вывести на консоль жителей комнат (модули room_1 и room_2)
# Формат: В комнате room_1 живут: ...
from room_1 import folks as room1
from room_2 import folks as room2
print('В комнате room_1 живут: ', ' , '.join(room1))
print('В комнате room_2 живут: ', ' , '.join(room2))
|
a = input("input:")
print(a)
print("a""b""c")
print("a"+"b"+"c")
print("a","b","c") #콤마는 띄어쓰기
for i in range(1,11):
print(i,end=' ')
|
def sumall(*args):
sum = 0
for i in args:
sum += i
return sum
result = sumall(3,4,5,6,7)
print(result)
result = sumall(1,2,3)
print(result)
def summul(choice, *args):
if choice == "sum":
result = 0
for i in args:
result += i
elif choice == "mul":
result ... |
from enum import Enum
class Color(Enum):
red = 1
green = 2
blue = 3
Color2 = Enum('Color2','red green blue')
print(Color.blue.name)
print(Color.blue.value)
|
"""
Created on Sat Nov 24 19:45:24 2018
@author: chetanbommu
"""
## Importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
## Importing dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,1].values
## Splitting dataset into training a... |
class first():
def __init__(self):
self.__a = 100
def getters(self):
print("val of a",self.__a)
def setters(self,val):
self.__a = val
f = first()
f.getters()
print("Now changed outside the class")
f.__a = -100
f.getters()
print("Now changing inside the class")
f.setters(-100)
f.g... |
from collections import defaultdict
import re
import unicodedata
import inflect
class Preprocessor(object):
'''
A class containing methods for preprocessing a sentence.
'''
def remove_non_ascii(self, words):
"""Remove non-ASCII characters from list of tokenized words"""
new_words = []... |
# #!/usr/bin/python
# # -*- coding: utf-8 -*-
# from time import time, sleep
# def deco(func):
# def wrapper():
# start_time = time()
# print "start time = %s" %start_time
# func()
# # sleep(1)
# print "end time = %s, %s runs %s seconds." %(time(), func, time() -... |
from player import Player
from gesture import Gesture
import random
class Computer(Player):
def __init__(self):
super().__init__()
def pvp(self):
print("Choose a gesture!")
print(Gesture().gestures)
self.choice_1 = int(input("Player One Enter Choice: "))
while self.... |
from tkinter import *
# from NLP_FINAL import XYZ
insertSentencesWindow = Tk()
insertSentencesWindow.title("Welcome to project number 18")
insertSentencesWindow.geometry('450x400')
# State
numberOfEnteredSentences = 0
S1 = []
S2 = []
# Insert sentences layout string variables
instructionsLabelStringVariable = Strin... |
import matplotlib.pyplot as plt
import numpy as np
def generate_city_populations(num_cities, population_range):
# Generate city populations following Zipf's Law
ranks = np.arange(1, num_cities + 1)
populations = np.round(population_range[0] / (ranks ** 0.8))
return populations
def calculate_concentra... |
import networkx as nx
import matplotlib.pyplot as plt
# Number of nodes in the initial network
m0 = 5
# Number of edges to attach from a new node to existing nodes
m = 2
# Create an empty graph
ba_network = nx.Graph()
# Add the initial nodes to the graph
ba_network.add_nodes_from(range(m0))
# Iterate to add new no... |
'''
A python implementation of the Earthmover distance metric.
'''
import math
from collections import Counter
from collections import defaultdict
from ortools.linear_solver import pywraplp
def euclidean_distance(x, y):
return math.sqrt(sum((a - b)**2 for (a, b) in zip(x, y)))
def earthmover_distance(p1, p2):... |
from collections import deque, namedtuple
Vertex = namedtuple('Vertex', ['name', 'incoming', 'outgoing'])
def build_doubly_linked_graph(graph):
"""
Given a graph with only outgoing edges, build a graph with incoming and
outgoing edges. The returned graph will be a dictionary mapping vertex to a
Vertex namedtu... |
from collections import namedtuple, defaultdict
from Queue import PriorityQueue
Edge = namedtuple('Edge', ['target', 'weight'])
def dijkstra(graph, source, target):
"""
Given a directed graph (format described below), and source and target
vertices, returns a shortest path as a list of vertices going from sourc... |
from collections import namedtuple
from union_find import DisjointSet
# Putting weight as the first element means Edges will sort by weight first,
# then source and target (lexicographically).
Edge = namedtuple('Edge', ['weight', 'source', 'target'])
def kruskal_mst(n, edges):
"""
Given a positive integer n (nu... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
age = input()
if int(age) >= 18:
pass
else:
print('Child')
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# At range [1, 11)
print([x for x in range(1, 11)])
print([x * x for x in range(1, 11)])
print([x * x for x in range(1, 11) if x % 2 == 1])
print([m + n for m in 'ABC' for n in 'XYZ'])
import os
print([d for d in os.listdir('.')])
L = ['Hello', 'World', 'IBM', 'Apple']
pr... |
#ques1
skrillex=['EDM','LEGEND','DUBSTEP','LEVEL']
print(skrillex)
#ques2
Avicii=['google','apple','facebook','microsoft','tesla']
print(skrillex+Avicii)
#ques3
number=[1,1,1,2,3,4]
print(number.count(1))
#ques4
numbers=[1,2,3,6,5,4,7]
numbers.sort()
print(numbers)
#ques5
list6=[]
list1=[1,2,5,6,7]
list2=[8,7,9,4]
list... |
slowo = str(input('Podaj slowo:'))
print(slowo + ' ?? ' + slowo[::-1])
if slowo == slowo[::-1]:
print('Palindrom')
else:
print('Gowno, a nie palindrom') |
name = input ('Podaj swoje imie:')
age = int ( input ('Podaj swoj wiek:') )
kopia = int (input('Podaj liczbe calkowita:'))
for number in range(1,kopia+1):
print('{}. Witaj {}, będziesz miał 100 lat w {} roku.'.format(number,name,2019+100-age))
|
s = """We encourage everyone to contribute to Python.
If you still have questions after reviewing the material
in this guide, then the Python Mentors
group is available to help guide new contributors through the process.""".replace("," ,"").replace(".","")\
.replace("\n","").upper()
words = s.split(" ")
frequenc... |
# Notes for MidTerm
THE SOFTWARE DEVELOPMENT PROCESS
# 1. Analyze the Problem
# Do we understand the exact problem to be solved?
# 2. Determine the Specifications:
# What are the inputs, outputs, and how they relate to one another?
# Here we list each input, each output, and how they relate to each othe... |
import networkx as nx
import matplotlib.pyplot as plt
import random
#Distribution graph for Erdos_Renyi model.
def distribution_graph(g):
print(nx.degree(g))
all_node_degree = list(dict((nx.degree(g))).values())
unique_degree = list(set(all_node_degree))
unique_degree.sort()
nodes_with_degree = [... |
import json
import os
def read_json(f):
if isinstance(f, str):
# If it refers to a filename, need to open and use ``json.load``
if os.path.exists(f):
with open(f, 'r', encoding='utf-8') as f:
return json.load(f)
# Support for filename input which lacks the `.js... |
prime_list = [2]
def check_prime(n):
for x in prime_list:
if n % x == 0:
return False
return True
n, m = map(int, input().split())
for i in range(3, m+1):
if check_prime(i):
prime_list.append(i)
if i > n:
print(i)
|
from datetime import datetime
from typing import Callable
"""
Annotated experiments on decorators.
Beware: using with no arguments, as in @dec a decorator that expects arguments,
as in @dec(args), breaks your code. The correct syntax if you want to pass
no arguments to such a decorator is @dec().
practica... |
# Assignment 7
# By: Joshua Rifkin
import argparse
import random
from itertools import cycle
class Dice(object):
def __init__(self):
self.sides = 6
def rollDie(self):
return random.randint(1, 6)
class Player(object):
def __init__(self, name):
self.playerScor... |
#Un comentario solo para decir lo mal que está escrito esto
def abrirarchivo():
archivo=input('Archivo: ')
while True:
try:
arch=open(archivo)
break
except:
print('El archivo no existe')
archivo=input('Archivo: ')
return arch
def probararchivo(arch):
a=1
cuenta=0
for linea in arch:
if a%7==1 a... |
# -*- coding: utf-8 -*-
#
# Voici un petit exemple de fonction
#
def maFonction( x, y ):
"""
maFonction(x,y) calcule 2*x + 3*y^2
"""
# On calcule d'abord 2 x
z1 = 2*x
# Puis 3 y au carré
z2 = 3*y^2
# Puis on additionne les deux
résultat = z1 + z2
# Et on renvoie le résultat
... |
reponse = 3
proposition = int(input("Donne-moi un nombre entre 1 et 10 : "))
if proposition == reponse: # si 1
print("Bravo, tu as trouvé !")
elif proposition < reponse: # sinon si 1
print("Trop petit... Recommence")
else: # sinon
print("Trop gra... |
#
# Ce petit programme calcule la somme des n premiers entiers
# n est le nombre d'entiers qu'on veut additionner
#
n = 5
sauven = n
# s va contenir la somme
s = 0
# Boucle de calcul
while n > 0:
print("J'en suis à n = ", n)
# accumuler n dans s
s = s + n
print("S vaut maintenant: ",s)
# Décrémenter n
n = n... |
from math import sqrt # ==> math.sqrt calcule la racine carrée
def ecart_type(maliste):
moy = sum(maliste) / len(maliste)
i = 0
somme = 0 # commence à 0
while i < len(maliste):
somme = somme + (maliste[i] - moy)**2
i = i + 1
return sqrt(somme / len(maliste))
maliste = [1, 2, 3, 4... |
import string
def duplicate_count(text):
return len([x for x in set(text.lower()) if text.lower().count(x) > 1])
def sort_array(source_array):
odds = iter(sorted(el for el in source_array if el % 2))
return [next(odds) if el % 2 else el for el in source_array]
def rot13(message):
alphabet = list(str... |
while True:
try:
num1 = int(input("Enter a number: "))
op = str(input("Enter an operation: "))
num2 = int(input("Enter a number: "))
except ValueError:
continue
break
if op == "+":
print("Result: {}".format(num1 + num2))
if op == "-":
print("Result: {}".format(num1 - ... |
print("Enter 6 integer(3 coordinates x,y), use only numbers(-100 - 100)!")
while True:
try:
ax = int(input("Enter a=>x[value]: "))
ay = int(input("Enter a=>y[value]: "))
bx = int(input("Enter b=>x[value]: "))
by = int(input("Enter b=>y[value]: "))
cx = int(input("Enter c=>x[... |
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(11, GPIO.IN)
GPIO.setup(13, GPIO.IN)
p = GPIO.PWM(16, 50)
p.start(0)
dc = 5
p.ChangeDutyCycle(dc)
try:
while 1:
inputValue1 = GPIO.input(11)
inputValue2 = GPIO.input(13)
if inputValue1 == Fa... |
def callback(MoistureSensor1):
#if GPIO.input(MoistureSensor1):
if GPIO.gpio_function(15) == GPIO.HIGH:
print("MoistureSensor on")
GPIO.output(Pump1, GPIO.HIGH)
GPIO.output(Pump2, GPIO.HIGH)
time.sleep(0.25)
else:
print("MoistureSensor off")
GPIO.output(Pump1,... |
# Import OS for Traversing Directories
import os
# Import Numpy for Mathematical Functions
import numpy as np
# Function to Obtain a List of Files
def getFileList(directory):
fileList = []
fileSize = 0
folderCount = 0
# For Loop to Cycle Through Directories
for root, dirs, files in os.walk(direct... |
a = int(input("number:"))
r1 = int("%s" % a)
r2 = int("%s%s" % (a, a))
r3 = int("%s%s%s" % (a, a, a))
r4 = int("%s%s%s%s" % (a, a, a, a))
print(r1 + r2 - r3 * r4) |
# authors - Dawei Ju and Bo Liu
import random
global deck
global discard
class myStatic:
hand_status = hand_status = [False] * 10
status_check = False
deck = range(1,61)
discard = []
def shuffle():
'''This function shuffles the deck or the discard pile\
1.initial game: shuffle the deck\
2.The... |
def readFile():
'''read the text file 'resume.txt' into list'''
my_lines = []
f = open('resume.txt','rU')
line = f.readline()
while line:
my_lines.append(line)
line = f.readline()
f.close()
return my_lines
def detectName(my_lines):
'''extract the name from file lines'''
... |
# s=map(lambda x:x*2 ,[1,2,34,5])
# for i in s:
# print(i)
from functools import reduce
# var=filter(lambda x:x%2==0,[2,4,8,9])
# for y in var:
# print(y)
#
var1=reduce(lambda x,y:x*y,[1,2,3,5])
print(var1)
|
e=1
try:
1/0
except ZeroDivisionError as e:
print('error:{}'.format(e))
# print(e)
#运行上面代码,执行结果 NameError: name 'e' is not defined
# 官方文档说明:
# except E as N:
# foo
# 就等于
# except E as N:
# try:
# foo
# finally:
# del N
# 因为上面例子的e最后被delete,所以会抛NameError
import datetime
prin... |
"""
12. 아래 두 함수를 정의한다.
① 여러 개의 숫자를 매개변수로 받아서, 해당 숫자 중에 가장 큰 값을 반환하는 max. 어떤 개수의 숫자가 매개변수로 넘어와도 작동해야 한다.
② 여러 개의 숫자를 매개변수로 받아서, 해당 숫자 중에 가장 작은 값을 반환하는 min. 어떤 개수의 숫자가 매개변수로 넘어와도 작동해야 한다.
max(6, 8, 9, -10, 4), min(6, 8, 9, -10, 4)를 호출하여 출력
<출력 예>
최대값: 9
최소값: -10
"""
def max(*a) :
max_num = a[0]
f... |
"""
9.
매개변수로 넘어온 자연수가 소수인지 여부를 판별하여, 소수이면 True, 아니면 False를 반환하는 함수 is_prime을 정의하라. 2,3,5,7,11,13 등
1과 자기자신이외의 약수가 없는 자연수를 소수라 한다.
"""
def is_prime(a) : # 매개변수 값을 a에 저장
count = 0 # 약수를 담을 변수 count 초기화
for i in range(1, a+1) : # 1~a까지 반복
if a % i == 0 : # a 나누기 i 의 나머지가 0이라면
count += 1 # i가 a의... |
"""
챕터: Day 6
주제:class 상속/계승
문제: shape,circlerectangle class define
작성자: 김기범
작성일:2018.11.01
"""
"""
1.Define shape class, method로 area(), perimeter()를 가지고 있다.
A.area()는 면적, perimeter()는 둘레를 반환한다. 하지만,shape class는 0을 반환
B.__str__()를 정의한다. "도형"을 반환
2.Shape를 계승하는, Circle,Rectangle,Triangle을 정의한다,__init__(),area(),perimet... |
"""
챕터: Day 6
주제: class
문제:
숫자를 하나씩 발생시키는 Counter 클래스 정의
작성자: 김기범
작성일: 2018.10.18.
"""
# Counter 클래스 정의, instance는 아직 생성되지 않음
class Counter :
def __init__(self, start = 0):
"""
특별한 메소드이다.
instance를 생성할 때 초기화하는 메소드, instance를 생성할 때 자동 호출됨
:param start:
"""
self.count ... |
"""
챕터: Day 4
주제: 반복문(for 문)
문제: while 문을 이용하여 100에서 1까지 2의 배수를 크기가 작아지는 순서로 출력하시오
작성자: 김기범
작성일: 2018.09.20.
"""
x = 100 # x를 초기화
while x > 0 : # x가 0보다 크면
print(x) # x를 출력
x -= 2 # x = x - 2 |
"""
챕터: Day 5
주제: 재귀함수(recursion)
자기 자신을 호출하는 함수
문제:
A. 팩토리얼 계산 함수 fact를 재귀함수로 정의하여, fact(5)를 호출한 결과를 출력하라.
작성자: 김기범
작성일: 2018.10.11.
"""
def fact(a) : # 재귀함수 fact 정의
if a == 1 : # a가 1이면
return 1 # 1 반환
else :
return a * fact(a-1) # 재귀함수
print(fact(5)) # 매개변수 5로 호출 |
"""
챕터: Day 6
주제: exception
문제: 사용자로부터 숫자를 입력받아, 1부터 해당 숫자까지의 합을 구하라.
만약 숫자가 아닌 값이 입력되면, "숫자를 입력하세요"라는 문장을 출력한 후
다시 입력을 받는다
작성자: 김기범
작성일: 2018.11.27.
"""
# exception을 사용하여 프로그래밍
sum = 0 # 합을 저장할 변수 정의
while True: # 숫자를 입력할 때까지 반복
try: # 숫자값이 입력되는지 검사를 위해 try 사용
n = int(input("숫자 입력: ")) # int로 변환되는 과정에서 ... |
"""
챕터: Day 6
주제: class
문제: 좌표를 표현하는 클래스 Coordinate를 정의한다.
1. __init__는 x, y 좌표를 받아서 self의 x, y에 배정
2. 거리를 구하는 distance 메소드를 정의한다. self와 다른 좌표 other를 매개 변수로 받는다.
거리는 ( x좌표 사이의 차의 제곱(**2로 계산)과 y좌표 사이 차의 제곱의 합)의 제곱근이다. 제곱근(**0.5로 계산)
작성자: 김기범
작성일: 2018.10.18.
"""
# 클래스 정의
class Coordinate :
def __init__(self, x = ... |
"""
챕터: Day 4
주제: 반복문(for 문)
문제:
사용자가 입력한 영문자를 아래와 같이 출력
예)
BINGO
INGO
NGO
GO
O
작성자: 김기범
작성일: 2018.09.27.
"""
S = input() # 문자열 입력받기
#1
for i in range(0, len(S)) : # 0부터 문자열 끝 앞 번호까지 반복문
print(" " * i, end = "") # 줄 길이만큼 앞에 여백 늘리기
print(S[i:]) # i부터 끝까지 출력하기
#2
for i in range(0, len(S)) : # 문자열 길이만... |
# This is a demo task.
# Write a function:
# def solution(A)
# that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
# For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
# Given A = [1, 2, 3], the function should return 4.
# Gi... |
print ("\n\nWelcome!") # Print single line
print """
\nThis program creates text file if you
type in some informations.
It won't take too long...
Enjoy!
""" # Print multiple lines
response = raw_input("*** To continue, press ENTER. ***") # Make variable called response with line of texts
if response == "": # If vari... |
# UNIDAD 6: ECUACIONES DIFERENCIALES ORDINARIAS
import time
import numpy as np
import sympy as sym
import matplotlib.pyplot as plt
from sympy import sin, cos
t, y = sym.symbols("t y")
# Método de Euler
def euler(ODE, t0, y0, tf, h):
"""
Entrada: una Ecuación Diferencial Ordinaria de primer orden ODE(t, y), ... |
dob= list(map(int,input().split(":")))
todays=list(map(int,input().split(":")))
dob.reverse()
todays.reverse()
if dob[0]<todays[0]:
if dob[1]< todays[1]:
print(str(todays[0]-dob[0])+" Years",end=" ")
print(str(todays[1]-dob[1])+" Months",end=" ")
print(str((30-dob[2])+todays[2])+" Da... |
from Player import Player
class Traitor(Player):
starting_ability_charge = 0
def __init__(self, name):
"""player role will be protected since it is good information to keep secret
each traitor will start with full ability charge, and a defined role as Traitor"""
super().__init__()
... |
N=int(input("Tamano de la lista: "))
A=[int(input("Inserte un numero: ")) for x in range(N)]
for x in range(1,N):
i=x-1
j=A[x]
while i>=0 and j<A[i]:
A[i+1]=A[i]
i=i-1
A[i+1]=j
print (A)
|
Name='Joel'
weight=80
str="this is string example.....wow!!"
str2="THIS IS STRING EXAPLE"
print "My name is %s and weight is %d kg!" % (Name,weight)
print"------------------------------------------"
print"str.capitalize() : ", str.capitalize()
#this works of make the first word in mayuscula
print"---------------------... |
A=257
B=257
if( A is B):
print"is true"
else:
print "is false"
print "---------------------"
if not (A is B):
print"is false"
else:
print "is true"
|
import sys
import time
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.20,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
... |
five = 5
ten = 10
print("five is " + ("bigger" if five > ten else "smaller") + " than ten")
print("ten is " + ("bigger" if ten > five else "smaller") + " than five")
|
# def f1():
# x=100
# print(x)
# x=+1
# f1()
tuple = (1,2,3)
tuple.append((4,5))
print(len(tuple)) |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
性能优化示例-循环
@module performance_optimizing_circle
@file performance_optimizing_circle.py
"""
import datetime
DOT_RANGE_NUM = 10000000
DOT_WORDS = [
'test', 'for', 'circle', 'performance', 'optimizing', 'dot'
]
def dot_in_circle():
_str = ''
for _i in r... |
import numpy as np
""" Implementation of a Markov chain using states (which can be numbers, strings or
even functions)"""
class Chain:
"""Object representing a stochastic markov chain"""
def __init__(self, states, transitions):
""" Initialize a markov chain with a list of states and list of list o... |
if __name__ == '__main__':
s = input()
isalnum = False
isalpha = False
isdigit = False
islower = False
isupper = False
for i in s:
if i.isalnum():
isalnum = True
if i.isalpha():
isalpha = True
if i.isdigit():
isdigit = True
... |
"""Defines operation functions that can be put on the board"""
from model.board.board import Board
from model.board.modifiers.resource import Resource
def copy_board(dest, src, rect=None, pos=None):
"""Copies tiles from src board to destinations.
If rect is given than a rect, starting from the x,, y corner ... |
'''
Time complexity : O(M \times N)O(M×N) where MM is the number of rows and NN is the number of columns.
Space complexity : worst case O(M \times N)O(M×N) in case that the grid map is filled with lands where DFS goes by M \times NM×N deep
'''
class Solution:
def numIslands(self, grid):
if not grid:
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root):
def collect(node, depth):
if node:
if dep... |
class Solution:
def jump(self, nums: List[int]) -> int:
jump = 0
currJumpEnd = 0
farthest = 0
for index in range(len(nums)-1):
farthest = max(farthest, index+nums[index])
#if we've reached the end of currJump and need another jump
... |
class Solution:
def trap(self, height: List[int]) -> int:
if not height: return 0
#two pointer approach
left = 0
right = len(height) - 1
answer = 0
#when water is greater at one end, left or right, we only need to subtract it from that direction
... |
class Solution:
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token not in "+-/*":
stack.append(int(token))
continue
number_2 = stack.pop()
number_1 = stack.pop()
result = 0
if token == "... |
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
#sorts the course according to the 2nd index of all elements in the list
courses.sort(key = lambda x:x[1])
#print(courses) #to visualize the code after sorting it
maxHeap = [] # to store the negative values of the c... |
class Solution:
def maximumSwap(self, num: int) -> int:
#idea: from right to left, have a max at hand, each smaller one is a candidate to swith
# 98368: 8 -> 6 -> 3
digits = list(str(num))
max_digit = (-1, -1) #val, index
candidate = (-1, -1) # candidate pair of indexes
... |
print('wordcount and frequency')
# with open we are reading text.txt file that in our Homework3 folder 'r' open file for reading.
with open('text.txt', 'r') as f:
f_cotents = f.read()
#splitting words
word_list=(f_cotents.split())
#checking if this worked
print(word_list)
#init dictionary
##... |
a = input('one')
b = input('two')
m = int(a)
n = int(b)
def gcd(m, n):
if n == 0:
print(m)
else:
print(gcd(n, m%n))
print(gcd(m, n))
|
def checkrange(name, value, l, u):
if not (l <= value <= u):
raise ValueError(f'{name} be {l}...{u}')
class Datetime:
def __init__(self, year, month, day, hour, minute):
self._year(year)
self.set_month(month)
self.set_day(day)
self.set_hour(hour)
self.smin(minute... |
#!/usr/bin/env python3
a = input('what')
x = int(a)
if x > 0:
print('ghh')
else:
print('kjj')
|
def stackinterpreter():
l = []
while True:
line = input('command')
words = line.split()
if len(words) == 0:
pass
elif words[0] == 'show':
print(l)
elif words[0] == 'push':
l.extend(words[1:])
elif words[0] == 'pop':
... |
"""Write a program which takes 4 inputs, where each input consists of 2 numbers in the format x,y.
You are required to print a two dimensional array having x rows and y columns for each input.
The elements of the arrays should be whole numbers starting from 1 and incrementing by 1.
Example
Suppose the following 4 inp... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
node... |
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
results = []
def findCombination(start, target, result, results):
if target == 0:
r... |
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
mapping = {
'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
}
if digits == '': r... |
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
results = []
def findCombination(start, target, result, results):
if target == 0:
... |
def binarySearch(values, k):
top = len(values)-1
bottom = 0
values.sort()
print(values)
found = False
while(found != True):
mid = (top+bottom) // 2
if(values[mid] == k):
print(str(k) + " found at index: " + str(top))
found = True
return True
elif(values[mid] < k):
bottom = mid + 1
elif(values... |
from sys import argv
from random import randint
from math import gcd, log
from prime import factorize
DEFAULT_S = 10
def p1_pollard(n, primes, s):
base = primes[:s]
a = randint(2, n - 2)
d = gcd(a, n)
if d >= 2:
return d
for i in range(s):
power = int(log(n) / log(base[i]))
... |
#Víctor Hugo Flores Pineda 155990
#Rebeca Baños García 157655
#Python 3
import numpy as np
import matplotlib.pyplot as plt
import huffman as hf
#1
x = np.random.randint(1,6,20)
print("Cadena aleatoria de numeros: ")
print(x)
print("\n")
#2
xB = np.zeros(20)
for i in range(0,20):
xB[i] = np.binary_repr(x[i],3)
pr... |
List=['p','y','t','h','o','n','f','o','r','g','a','m','e','s']
sliced_List = List[3:8]
sliced_List = List[::-1]
print(sliced_List)
x={"apple","banana","cherey"}
y={"google","microsoft","facebook"}
z=x.isdisjoint(y)
print(z)
x={'a','b','c'}
y={"f","e","d","c","b","a"}
z=x.issuperset(y)
print(z)
x={"f","e","d... |
import os
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
#adding a title
root.title("Image-Viewer")
#adding a favicon/icon
root.iconbitmap("3-Basics_2\\favicon.ico")
# #adding an image
# my_img = ImageTk.PhotoImage(Image.open("3-Basics_2\\images\\picture.png"))
# #creating a label for the image
# m... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
#讀取 json 的程式
def jsonTextread(path, target):
with open(path,encoding="utf-8") as f:
inputtext = json.load(f)[target]
return inputtext
#將字串轉為「句子」列表的程式
def text2Sentence(inputSTR):
sentence_LIST = []
start = 0
k = 0
length_STR = ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
#讀取 json 的程式
def jsonReader(jsonFILE):
with open(jsonFILE, encoding="utf-8") as f:
jsonContent = f.read()
txt = json.loads(jsonContent)
try:
return txt["text"]
except:
return txt["sentence"]
#將字串轉為「句子」列表的程式
def sent... |
# search.py
# ---------------
# Licensing Information: You are free to use or extend this projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to the University of Illinois at Urbana-Champaign
#
# Create... |
# tips_07.py
# coding:utf-8
'''
time.clock(): 获取毫秒信息
'''
import time
start = time.clock()
for i in range(10000):
print i
end = time.clock()
print start, end
print 'different is %6.3f' % (end - start) |
# test_interview_10.py
# coding: utf-8
'''
十道题
1. 讲下list和tuple的区别
2. 讲下类方法和静态方法的区别
3. list的切片用法
4. 强制转换
5. 编程实现十进制转换为八进制
6. copy和deepcopy的区别
7. lamda的使用
8. with的使用
9. <.*>和<.*?>匹配的区别
10. Set如何使用?
'''
seq = [1,2,3,4]
def compare(a1,a2):
if a1==a2:
print 'correct'
else:
print 'wrong'
compare(seq[:2],[1,2]) # 不包含右... |
# factory_mode.py
# coding:utf-8
'''
工厂方法模式去掉了简单工厂模式中工厂方法的静态属性,使得它可以被子类继承。对于python来说,就是工厂类被具体工厂继承。这样在简单工厂模式里集中在工厂方法上的压力可以由工厂方法模式里不同的工厂子类来分担。也就是工厂外面再封装一层。
1) 抽象工厂角色: 这是工厂方法模式的核心,它与应用程序无关。是具体工厂角色必须实现的接口或者必须继承的父类。
2) 具体工厂角色:它含有和具体业务逻辑有关的代码。由应用程序调用以创建对应的具体产品的对象。
3) 抽象产品角色:它是具体产品继承的父类或者是实现的接口。在python中抽象产品一般为父类。
4) 具体产品角... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.