text stringlengths 37 1.41M |
|---|
#tabuada com for
n = float(input('Digite um número: '))
print('Tabuada do número {}'.format(n))
for i in range (0, 11):
print('{} x {} = {}'.format(i, n, i*n)) |
#soma de números pares com for
soma = 0
cont = 0
for i in range(6):
n = (int(input('digite o {}º número: '.format(i+1))))
if n % 2 == 0:
soma += n
cont += 1
print('A quantidade de números pares foi {} e sua é: {}'.format(cont, soma))
|
# lambda 활용법
'''
x = lambda a: a+10
print(x(5))
x = lambda a,b : a *b
print(x(5,6))
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
mytripler = myfunc(3)
print(mytripler(11))
'''
def a(n):
return lambda i: i*n
mydoubler = a(2)
print(mydoubler(11))
|
'''
생성자 (Constructor)
상속 : 일반화
**클래스를 상속하기 위해서는 다음처럼 클래스 이름 뒤 괄호 안에
상속할 클래스 이름을 넣어주면 된다.
형식 ] class 클래스 이름(상속할 클래스 이름)
'''
class FourCal:
def __init__(self,first,second):
self.first = first
self.second = second
def sum(self,bbb):
result = self.first + self.second
return result
class MoreFourCal(FourCal):
... |
#튜플 요솟값을 삭제하려 할 때
t1 = (1,2,'a','b')
print(t1[0])
#del t1[0] # 삭제시 error 발생
#t1[0]='c' #변경 시 error 발생
#인덱싱하기
t1 = (1,2,'a','b')
print(t1[0])
print(t1[3])
#슬라이싱하기
print(t1[1:])
print("-"*20) |
#a = [1,2,3,4]
#result = [n + 2 for n in a if n % 2 == 1]
#
#print(result)
#결과값에 2의 배수만 출력하시오
a = [6,8,12,33]
result = [n*3 for n in a if n % 2 == 0]
print(result) |
#1~10 까지의 홀수합 출력!!
odd=0
even=0
#for i in range(1,11,2):
# odd = odd+i
#print(odd)
#다른방법으로 해보세요~!
a = 0
b = 0
for i in range(1,11):
if i % 2 == 1:
a = a+i
print("1~10까지의 홀수의 합은 : ",a)
for j in range(1,11):
if j % 2 == 0:
b = b+j
print("1~10까지의 짝수의 합은 : ",b) |
a= ' hi '
print(a)
print(a.lstrip()+'Chk')
print(a.rstrip()+'Chk')
print(a.strip()+'Chk') ##공백제거
print('-'*15)
#문자열 바꾸기(replace)
a='Life is too short'
print(a)
cng=a.replace('Life','Your leg')
print(cng)
print('-'*15) |
menu = ['오렌지','딸기','복숭아','망고','포도','종료']
# 0 1 2 3 4 5
money = [1000,2500,1500,2000,2000]
# 0 1 2 3 4
while True:
print("="*50)
print("*****홍익 대학교 과일 판매머신 V03 *****")
print("="*50)
for i in range(0,5):
print (i+1,'번 ',menu[i] , ":" , money[i] , "원")
print('6. 종료')
print("="*50)
n = input("... |
# return문을 2번 사용하면,
# 두 번째 return문인 return a*b는 실행되지 않는다
def add_and_mul(a, b):
return a+b
return a*b
result = add_and_mul(2,3)
print(result)
print('-'*10)
# [return의 또 다른 쓰임새]
# return을 단독으로 써서 함수를 즉시 빠져나갈 수 있다
def say_nick(nick):
if nick == "바보":
return nick
# print("나의 별명은 %s 입니다." %nick)
say_nick('야호')
s... |
import math as m;
i=int(input("Enter a number to find factorial: "))
print("Factorial of {} = {}".format(i,m.factorial(i)))
|
from person import Person
from metode import print_contacts
from metode import add_contact
from metode import edit_contact
from metode import delte_contact
def main():
print("Dobrodosli v programu Contact Book")
john = Person(first_name="John", last_name="Clark", phone_number="89348239429", email="john@clark.... |
import csv
def insert_rec(data):
with open('records.csv', 'a') as csvfile:
fw = csv.writer(csvfile)
fw.writerow(data)
print('Record inserted')
def display_rec():
try:
with open('records.csv', 'r') as csvfile:
fr = csv.reader(csvfile)
for row in fr:
... |
# consists of brackets containing an expression followed by
# a for clause, then zero or more for or if clauses
# result is a new list resulting from evaluating the in the context of the
# for and if clauses which follow it.
# squares / list comprehension example
squares = [x**2 for x in range(10)]
print(squares)
... |
# Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
# The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
# You must write an algorithm that runs in O(n) time and without using the division oper... |
# Given a string s, find the length of the longest substring without repeating characters.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# Maintain set of words encountered so far
w = set()
res = 0
l = 0
# Maintaining window of only uni... |
# You are given an array prices where prices[i] is the price of a given stock on the ith day.
# You want to maximize your profit by choosing a single day to buy one stock
# and choosing a different day in the future to sell that stock.
# Return the maximum profit you can achieve from this transaction.
# If you cann... |
#Given the root of a binary tree, return its maximum depth.
# A binary tree's maximum depth is the number of nodes along the longest path from the root node
# down to the farthest leaf node.
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
#print(root)
stack = []
... |
# Given the root of a binary tree, return the length of the diameter of the tree.
# The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
# The length of a path between two nodes is represented by the number of edges between th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import operator
from collections import namedtuple
from itertools import islice
from math import sin, cos, atan2, radians, sqrt
LatLon = namedtuple('LatLon', 'lat, lon')
def distance(x, y):
"""Implements https://en.wikipedia.org/w... |
# Unlike arrays, sets cannot contain duplicates, so we an use a set to automatically filter out these duplicate terms
terms = set()
for a in range(2, 101):
for b in range(2, 101):
terms.add(a**b)
print(len(terms))
|
# Consumes a natural number n and returns the sum of the numbers on the diagonals on an n by n matrix
def sumOfDiagonals(n):
sum = 1
current = 1
count = 1
# This question required recognizing the pattern of how the numbers on the diagonal are determined.
# Once that is determ... |
# sumOfDiv consumes a number and returns the sum of the numbers divisors
def sumOfDiv(n):
sum = 1
i = 2
# We only need to check up until the square root of the number
while i * i < n:
if n % i == 0:
sum += i + n // i
i += 1
... |
# coding: utf-8
# In[1]:
# find out male and female survived proportion
import pandas as pd
df=pd.read_csv('data3/train.csv')
# total number of passengers
total_passengers=len(df)
print "total number of passenngers",total_passengers
# male female passengers count
df_total=df.groupby('Sex').count()['PassengerId']
df_... |
str_symbol_map={'PLUS':'+','MULTIPLY':'*','DIVISION':'/'}
def evaluate(expr):
for i in str_symbol_map.iteritems():
expr=expr.replace(i[0],i[1])
return eval(expr)
while True:
print """
1. Go for evaluation
2. Quit
"""
opt = raw_input("Enter an option: ")
if opt == '1':
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class foobase:
def hello(self):
print "hello"
class foo:
pass
#obj=foo()
#obj.hello()
'''ubuntu@huzhi-dev:~/www/python-patterns$ python mixin-test.py
Traceback (most recent call last):
File "mixin-test.py", line 12, in <module>
obj.hello()
Attribute... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod, abstractproperty
class Foo(object):
__metaclass__ = ABCMeta # 在 Python3 中的写法是 class Foo(metaclass=ABCMeta)
@abstractmethod
def spam(self, a, b):
pass
@abstractproperty
def name(self):
pass
cla... |
print('This is my first python game')
name=input('enter your name')
age=input('enter your age')
print('hello',name,'you are',age,'years old' )
health=10
if int(age) >= 18:
print('you are old enough to play!')
wants_to_play=input('do you want to play? ').lower()
if wants_to_play=='yes':
... |
import numpy as np
"""
Os pixels vizinhos são definidos conforme slide 66 do Tópico 2.
Para um pixel p temos:
[ (x-1, y-1); (x, y-1); (x+1, y-1) ]
[ (x-1, y); p; (x+1, y) ]
[ (x-1, y+1); (x, y+1); (x+1,y+1) ]
Os vizinhos em relação a p são denotados como:
sudoeste, sul, sudeste, leste, nordeste, norte, n... |
def get_start():
start = float(input("Enter the Starting Value for the counter: "))
return start
def get_stop():
stop = float(input("Enter the Stopping Value for the counter: "))
return stop
def get_increment():
increment = float(input("Enter the value you would like to increment by: "))
... |
def calculateOrder(shipping, tax, total):
order = total + shipping + tax
return order
def calculateShipping(total):
if total >= 100:
shipping = 0
else:
shipping = total * 0.1
return shipping
def calculateTax(total):
tax = total * 0.07
return t... |
def get_quantity():
print ("Enter the number of items: ")
quantity = int(input())
return quantity
def get_price():
print ("Enter the price per item: ")
price = float(input())
return price
def calculate_total(quantity, price):
total = (price * quantity)
return total
def calculate... |
for i in range(1,100):
fizz = False;
buzz = False;
if i % 3 == 0:
fizz = True;
if i % 5 == 0:
buzz = True;
if fizz:
if buzz:
print("fizzbuzz");
else:
print("fizz");
elif fizz:
print("fizz");
else:
print(i); |
#Python code to do transpose of a given matrix
def display_matrix(matrix):
"""
To display a given matrix.
:param matrix: Multi dimensional matrix
:return: Nothing
"""
print("__________________")
for each_row in matrix:
print(each_row)
print("__________________")
input_matrix = ... |
a = 2
sum = 0
temp = a
for i in range(5):
temp = temp*a
sum += temp
|
import pandas as pd
#數字處理
# data = pd.Series([6, 8, -8, 689, 9])
# #print(data.sum(), data.prod())#相加總合 相乘總和
# #print(data.mean(), data.std()) #平均 標準差
# print(data.nlargest(3)) #前三大數
# print(data.nsmallest(2)) #前兩小數
#字串處理
data =pd.Series(["你好", "Python", "Pandas"],index=["a","b","c"]) #可自行更改索引
print(data.str.lower(... |
import pygame as pg
#pg.init()
#設定視窗背景
width, height = 640, 480
screen = pg.display.set_mode((width, height))
pg.display.set_caption("Sean's game")
bg = pg.Surface(screen.get_size())
bg = bg.convert()
bg.fill((255,255,255))
#藍球建立
ball = pg.Surface((70,70)) #建立球矩形繪圖區
ball.fill((25... |
# 입력: 첫째 줄에 단어가 주어진다.
# 단어는 알파벳 소문자와 대문자로만 이루어져 있으며, 길이는 100을 넘지 않는다.
# 길이가 0인 단어는 주어지지 않는다.
# 출력: 입력으로 주어진 단어를 열 개씩 끊어서 한 줄에 하나씩 출력한다.
# 단어의 길이가 10의 배수가 아닌 경우에는 마지막 줄에는 10개 미만의 글자만 출력할 수도 있다.
#
words = input()
temp = ""
n = 0
for i in words:
temp += i
n += 1
if n % 10 == 0:
print(temp)
temp... |
def partition(left_index, right_index, list_to_sort):
if left_index >= right_index:
return
pivot_index = left_index
j = pivot_index
for i in range(left_index + 1, right_index + 1):
if list_to_sort[i] < list_to_sort[pivot_index]:
j += 1
list_to_sort[i], list_to_so... |
# 입력: 첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.
# 출력: 첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.
N = int(input())
line = ""
for i in range(1, N+1):
line += "*"
print(line)
|
# https://ratsgo.github.io/data%20structure&algorithm/2017/10/16/countingsort/
# digit 은 1, 10, 100...
def counting_sort(arr, digit):
n = len(arr)
# 배열의 크기에 맞는 output 배열을 생성하고 10개의 0을 가진 count란 배열을 생성한다.
output = [0] * n
count = [0] * 10
# digit, 자릿수에 맞는 count에 += 1을 한다.
for i in range(0, n):
... |
def num_to_base(n, b):
convert = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n == 0:
return 0
digits = ['0']
while n:
to_append = int(n % b)
digits.append(convert[to_append])
n //= b
# 역순을 리턴
return digits[::-1]
|
def BinarySearch(num_list, target):
num_list.sort()
start = 0
end = len(num_list) - 1
mid = (start + end) // 2
while start <= end:
if num_list[mid] == target:
return mid
if num_list[mid] < target:
start = mid + 1
continue
if num_list[mi... |
class MinHeap:
def __init__(self, arg_list=None):
self.queue = [0]
if arg_list is not None:
self.queue += arg_list
for i in range(len(arg_list)//2, 0, -1):
self.min_heapify(i)
def last(self):
return len(self.queue) - 1
@staticmethod
def p... |
# https://www.acmicpc.net/problem/2447
# 입력: 첫째 줄에 N이 주어진다.
# N은 항상 3의 제곱꼴인 수이다. (3, 9, 27, ...)
# (N=3^k, 1 ≤ k < 8)
# 출력: 첫째 줄부터 N번째 줄까지 별을 출력한다.
import math
import sys
def draw_star(ret, power, first_point_row, first_point_col):
if power == 1:
ret[first_point_row + 1][first_point_col + 1] = " "
... |
from la.vector import Vector
if __name__ == "__main__":
# vector = [5, 2]
# vector2 = [3, 1]
# zero_2 = [0, 0]
# zero_3 = [0, 0, 0]
vector = Vector([5, 2])
vector2 = Vector([3, 1])
zero_2 = Vector.zero(2)
zero_3 = Vector.zero(3)
print("vector = {}".format(vector))
print("vector2... |
from PIL import Image
from io import BytesIO
filename = "test.jpg"
pil_image = Image.open(filename)
width, height = pil_image.size
print("width",width )
print("height",height )
r_width = 400
r_height = int(r_width*((height/width)))
pil_image = pil_image.resize((width, height), Image.ANTIALIAS)
pil_image_rgb = pi... |
###########################
# 6.00.2x Problem Set 1: Space Cows
from ps1_partition import get_partitions
import time
#================================
# Part A: Transporting Space Cows
#================================
def load_cows(filename):
"""
Read the contents of the given file. Assumes the file conten... |
from parsing.token import Token, TokenType
""" A lexical analyser for LTL.
The class is initialized with a string containing the LTL formula, and
tokens can then be retrieved from the string in a lazy fashion by invoking
the get_next_token() method. Only significant tokens are returned by the
... |
#1 list.append(obj)
#Appends object obj to list
#2 list.count(obj)
#Returns count of how many times obj occurs in list
#3 list.extend(seq)
#Appends the contents of seq to list
# https://stackoverflow.com/questions/252703/difference-between-append-vs-extend-list-methods-in-python
#4 list.index(obj)
#Returns the lowes... |
######################## Decorator #################################
# Decorator functions are software design patterns. They dynamically alter the functionality of a function, method, or
# class without having to directly use subclasses or change the source code of the decorated function. When used
# correctly, deco... |
# coding: utf-8
# # while loops
#
# The **while** statement in Python is one of most general ways to perform iteration.
# A **while** statement will repeatedly execute a single statement or group of
# statements as long as the condition is true. The reason it is called a 'loop'
# is because the code statements ar... |
wines = (1, 4, 2, 3, 9)
#wines = (1, 4)
memo = [[-1 for i in range(0, len(wines))] for j in range(0, len(wines))]
def chooseWineMemo(year, left, right):
global numCalls
numCalls += 1
print("chooseWine y:" + str(year) + " l:" + str(left) + " r:" + str(right))
if memo[left][right] != -1:
return m... |
## ID: 20180373 NAME: Kim Hyeonji (김현지)
######################################################################################
# Problem 2a
# minimax value of the root node: 6
# pruned edges: h, m, x
######################################################################################
from util import manhattanDistan... |
""" This program takes in the population census data from
(https://www.census.gov/data/tables/time-series/dec/metro-micro/tract-change-00-10.html)
in CSV format and writes, the average population percent change for a particular Core Based Statistical Area (CBSA)
along with other relevant information, to a CSV file.
To ... |
#!/usr/bin/env python
class Solution(object):
def trap(self, height):
"""
:type height: list of int
:rtype: int
"""
water = 0
height_len = len(height)
if height_len < 3:
return water
max_level = max(height)
max_level_index = heig... |
# Capturando dados do terminal - Input
nome = input('Digite seu nome: ')
print('O nome digitado foi:', nome)
# conversao de sring para int (cast)
idade = int(input(nome + ' digite sua idade: '))
print('A idade digitada foi:', idade)
|
# Curso: Python Fundamentos Proway
# Aula : Dia 2 - Parte 3
# Assunto: Dicionários
# Data: 2021-08-28
#bebidas =
lista = ['maykon']
tuplas = ('maykon')
lista[0]
tuplas[0]
# Criando um dicionario
dicionario = {'nome':'maykon', 'sobrenome':'granemann', 'idade':10}
# Lendo dados de um dicionario
print(dicionario['no... |
#coding:utf-8
import matplotlib.pyplot as plt
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
# 数据生成
x = np.arange(0,1,0.002)
y = np.random.randn(500,)/10
y = y + x**2
#... |
#from goto import goto, comefrom, label
# -*- coding: utf-8 -*-
import os
import time
has1stkey = 0
questmaterials = 0
hascasefile = 0
print
print "Noir Clue"
print
print raw_input("It was a dark and stormy night. [Enter]")
print raw_input("Well, actually it was only sprinkling, and it was closer to dawn than anything... |
# Brandon Coats
# CTI 110
# M6T2_FeetToInches
# Solves feet to inches.
INCHES_PER_FOOT = 12
def main():
feet = int(input('Enter a number of feet: '))
print(feet,'equals', feet_to_inches(feet), 'inches.')
def feet_to_inches(feet):
return feet * INCHES_PER_FOOT
main()
|
class QuickSort:
def partition(self, array, low, high):
pivot = array[low]
i = low + 1
j = high
while True:
while i <= j and array[j] >= pivot:
j -= 1
while i <= j and array[i] <= pivot:
i += 1
if i <= j:
... |
import re
def preprocess(s,display):
operand=re.findall(r'\d+',s)
operator=re.findall(r'[^\d ]',s)
if len(operand)>2 or len(operator)>1:
return "Error: Numbers must only contain digits."
if len(operand[0])>4 or len(operand[1])>4:
return "Error: Numbers cannot be more than four digits."
... |
def isAnagram(s1,s2):
s1 = s1.replace(" ","").lower()
s2 = s2.replace(" ","").lower()
hm = dict()
for s in s1:
if s in hm:
hm[s] += 1
else:
hm[s] = 1
for s in s2:
if s in hm:
hm[s] -= 1
else:
hm[s] = 1
for i in h... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
newNode = Node(data)
if self.head is None:
self.head = newNode
self.head.... |
class MyClass:
def __init__(self, x, y):
self.x = y
self.y = x
obj1 = MyClass(2, 5)
print('x =', obj1.x)
print('y =', obj1.y) |
handle = open("Writing_Files/test.txt","w")
handle.write("This is just a test")
handle.close()
handle = open("Writing_Files/test.txt","r")
while True:
data = handle.read(1024)
print(data)
if not data:
break
print('-------------------------------------------------------------------')
# Python ha... |
from LinkedList import LinkedList
def nth_to_the_last_node(list, n):
length = list.length()
if n <= length:
n = length - n
count = 0
cur = list.head
while cur:
if count == n:
return cur.data
count += 1
cur = cur.next
return... |
import datetime
class Schedule:
def __init__(self, start, end, name, other): # Constructor
self.start = self.str_convert(start) # Schedule start time (ex. 9:00)
self.end = self.str_convert(end) # Schedule end time (ex. 22:00)
... |
# Polyalphabetic cipher- Vigenere Cipher
# Uses multiple Caesar ciphers to shift each letter in input based on the key
# References: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
# Limitations: converts all characters to lowercase, can be changed, just how I set it up
def vigEncrypt(input, key):
keyLength = ... |
# In the 'mimsmind' game, the computer program
# will generate a random integer number and prompt the human player to guess the number.
# After each guess, the computer will
# provide feedback to guide the human in making his/her next guess.
# The game will end when the player correctly guesses the number
# or whe... |
#coding: utf-8
a=[]
cant=input("Cuantas palabras tendrá la lista?")
for i in range(1,cant+1):
aux=raw_input("Dígame la palabra "+str(i)+":")
a.append(aux)
print "La lista creada es: ",a
aux=raw_input("Sustituir la palabra:")
aux2=raw_input("Por la palabra:")
count=a.count(aux)
for b in range(count):
p=a.index(aux)
... |
import cv2
img = cv2.imread("1.png")
font = cv2.FONT_HERSHEY_PLAIN
cv2.line(img, (100, 50), (300, 400), (0, 0, 255), 5) # draws a line, positions are (x, y), color is bgr -> (image matrix, start pos, end pos, color, width)
cv2.rectangle(img, (200, 500), (800, 900), (0, 132, 195), 10) # draws a rectangle, posi... |
"""класс куча"""
class queue():
def __init__(self, arr, mod):
"""
def __init__(self, arr, mod)
arr - массив из которого будет построена куча
mod - строка "min" или "max" в зависимости от этого параметра
будет построена куча по минимуму или максимуму соответственно
"""
i... |
#Fucntion to read from a c++ style file.dat
def read_from_file(name):
"""Function to read from a file called name
it return a matrix of the various numbers"""
f= open(name,'r')
lines=f.readlines()
lines2=[x.replace("\t"," ") for x in lines]
lines3=[x.replace("\n","") for x in lines2]
resul... |
import random
import matplotlib.pyplot as plt
heads = 0
tails = 0
iterations = 0
results = []
def askUserHowManyFlips():
amountOfFlips = int(input("How many flips?:"))
return amountOfFlips
def flip(flips):
global heads, tails, iterations
for i in range(flips):
flip = random.randrange(2)
... |
#!/usr/bin/python
import sys
import re
import copy
import random
assert len(sys.argv) == 2, sys.argv[0] + " requires 1 argument!"
class Player:
def __init__(self, damage, armor, cost):
self.damage = damage
self.armor = armor
self.hp = 100
self.cost = cost
def printMe(... |
class Vector:
def __init__(self, values):
self.values = values
@staticmethod
def itol(value):
i = 0
ret = []
while i < value:
ret.append(float(i))
i += 1
return ret
@staticmethod
def ttol(value):
ret = []
for i in ran... |
from recipe import Recipe
from book import Book
livro = Book("teste")
print(livro.name)
print(livro.creation_date)
print(livro.recipes_list)
teste = Recipe("wincenty", 5, 20, ["6", "pedra", "vestido"], "starter",
"otima refeicao")
teste2 = Recipe("outra", 5, 20, ["6", "pedra", "vestido"], "dessert",
... |
from __future__ import division
import time
import sys
import random
from collections import defaultdict
import os
index = defaultdict(list)
def init_words():
global words
with open("dictionary.txt") as file:
for line in file:
word = line.strip().lower()
index[len(word)].append... |
from os import system
from time import sleep
def clear():
system('clear')
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
if(y == 0):
print ("Division by ZERO!!!")
return None
return x / y
def mathFunc(func, x, y):... |
import random
# 1) generate random number
# 2) take an input (number) from user
# 3) compare input to generated number
# 4) add higher and lower statements
# 5) add 5 guess
number = random.randint(1, 50)
print('''
Hello welcome to guess game.
You have 5 guesses to find the number I have thought.
The number is 1 to... |
# Find the greatest common denominator of two numbers
# using Euclid's algorithm
def gcd(larger_num, smaller_num):
original_large = larger_num
original_small = smaller_num
remainder = 1
while(remainder != 0):
remainder = larger_num % smaller_num
if remainder == 0:
print(f'{... |
from string import ascii_lowercase
class Puzzle:
def __init__(self, test=False):
filename = "test.txt" if test else "input.txt"
self.data = self.load_into_memory(filename)
def load_into_memory(self, filename):
"""load input into memory (list)"""
with open(filename) as ... |
from collections import deque, defaultdict
from itertools import cycle
class Puzzle:
def __init__(self, test=False):
self.players = 9 if test else 459
self.marbles = 25 if test else 72103
def solve_part1(self):
"""Returns result for part 1"""
d = deque([0])
scores = de... |
#!/usr/bin/env python3
# Random sentence generator
# CMPU 240, Fall 2019
import sys
import fileinput
import random
import re
grammar = {}
def error(msg):
"""Print an error message and exit."""
print(msg, file=sys.stderr)
sys.exit()
for line in fileinput.input():
# Skip blank lines
if not line... |
#kieran burnett
#10-10-2014
#ASCII task one
num = int(input("Please enter a number to be converted to ASCII: "))
text = input("Please enter a word to be turned into its ASCII number: ")
num_p = chr(num)
text_p = ord(text)
print(" The number you entered in ASCII: ",num_p)
print(" Then number of the letter ... |
"""
Catalogue manages library items. It uses LibraryItemGenerator to prompt user with an UI to add
different types of library items.
"""
__author__ = "Jack Shih"
__version__ = "Jan 2021"
import difflib
from library_item_generator import LibraryItemGenerator
class Catalogue:
def __init__(self, library_item_list)... |
"""
This module contains the Transaction class, which represents one transaction.
"""
__author__ = "Jack Shih & Tegvaran Sooch"
__version__ = "Feb 2021"
class Transaction:
"""
Represents a transaction and the money going
in and out of the bank account.
"""
def __init__(self, timestamp, amount, b... |
"""
This module contains all the Products that the Store sells. For each festive season, the store stocks a unique toy.
There are three festive seasons (Christmas, Halloween, Easter) and three types of products (Toy, StuffedAnimal, Candy)
for each season, for a total of 9 Products.
"""
__author__ = "Jack Shih & Tegvar... |
# emoji converter dictionary
message = input(">") # user input
words = message.split(' ') # returns an array split by spaces ' '
emojis = { # define a dictionary of text to emoji
":)": "🙂",
":(": "☹"
}
output = ""
for word in words: # append emoji to output when found, defau... |
#Olympic Logo
import turtle as p
def drawCircle(x,y,c = 'red'):
p.pu()
p.goto(x,y)
p.pd()
p.color(c)
p.circle(30,360)
p.pensize(7)
drawCircle(0,0,'blue')
drawCircle(60,0, 'black')
drawCircle(120,0,'red')
drawCircle(90,-30,'green')
drawCircle(30,-30,'yellow')
p.done() |
#Multiple Inhertance
class A(object):
def dothis(self):
print('doing this in A')
class B(A):
pass
class C(object):
def dothis(self):
print('doing this in C')
class D(B,C):
pass
d_inst = D()
d_inst.dothis()
print(D.mro())
# Output
# doing this in A
# ... |
'''
import Adafruit_DHT
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
# Set GPIO sensor is connected to
gpio=17
# Use read_retry method. This will retry up to 15 times to
# get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retr... |
#!/usr/bin/evn python
# -*-conding:utf-8 -*-
name = input("name:")
Age = input("Age:")
Job = input("Job:")
Salary = input("Salary:")
info ='''
--------- info of %s-------
name:%s
Age:%s
Job:%s
Salary:%s
''' % (name,name,Age,Job,Salary)
print(info)
info2 = '''
------ info of {_name} ------
Name:{_name}
Age:{_Age}... |
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #dictionary
>>> d1={"sno":525,"sname":"prabhas","year":2001}
>>> print(type(d1))
<class 'dict'>
>>> d1
{'sno': 525, 'sname': 'prabhas', 'year... |
"""
Polymorphism is the ability to leverage the same interface for different underlying forms such as data types or classes
"""
print(12 + 13)
print("edureka" + "rocks")
print([1, 2] + [3, 4])
# Same Interface but different underlying forms
# Prem
class Animal:
def __init__(self, name):
self.name = ... |
import tkinter as tk
# App Class
class App(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.winfo_toplevel().title("[ Periodic Table of the Elements ]" )
self.topLabel = tk.Label(self, text="Click o... |
#!/usr/bin/python3
"""Square Class"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""Square class based on Rectangle"""
def __init__(self, size=None, x=0, y=0, id=None):
"""init method"""
super().__init__(size, size, x, y, id)
@property
def size(self):
"""s... |
#!/usr/bin/python3
"""This program devides each element of a matrix"""
def matrix_divided(matrix=None, div=None):
"""function checks all contents of matrix and divides all by div"""
error = "matrix must be a matrix (list of lists) of integers/floats"
if type(matrix) is not list:
raise TypeError(er... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.