text stringlengths 37 1.41M |
|---|
"""
Defines an RGBA color.
"""
class Color(object):
"""
Defines an C{RGBA} (Red, Green, Blue, Alpha) color. A Color is considered a primitive, so its values may be accessed directly.
"""
def __init__(self, r, g, b, a=1.0):
"""
Initialization method.
@param r: The red value.
@type r: C{float} between C{0.0... |
# ----------
# User Instructions:
#
# Define a function, search() that takes no input
# and returns a list
# in the form of [optimal path length, x, y]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return th... |
# 4▹ Pomyśl co sprawia, że ssak jest ssakiem? Utwórz klasę ssaki. Stwórz kilka obiektów klasy ssaki np. wilk, koń, ssaki.
class Mammals():
def __init__(self, name, covered_with, breathe_with, blood_system):
self.name = name
self.covered_with = covered_with
self.breathe_with = breathe_with
... |
# 6. Przekopiuj zawartość import this do zmiennej.
#
# >>> import this
# Policz liczbę wystąpień słowa better.
# Usuń z tekstu symbol gwiazdki
# Zamień jedno wystąpienie explain na understand
# Usuń spacje i połącz wszystkie słowa myślnikiem
# Podziel tekst na osobne zdania za pomocą kropki
# ... |
# xmas.py
def print_triangle(n):
for size in range(1, n+1, 2):
print(size * "*")
for i in range(2, 5):
print_triangle(i) |
# Stwórz plik bmi.py i napisz program, który obliczy BMI:
# BMI = (masa (kg)) / (wzrost (m))²
weight = 64
height = 1.68
BMI = weight / height ** 2
BMI_rounded = round(BMI, 2)
print("Your BMI is:", BMI)
|
# Maksymalna liczba z trzech podanych
def max_of_2(x,y):
return x if x > y else y
def maximum_of(num1, num2, num3):
return max_of_2(max_of_2(num1, num2), num3)
if __name__ == "__main__":
a, b, c = (78, 111, 70)
v = maximum_of(a, b, c)
print("Moja większa liczba to: ", v)
|
# Rozwiń kod bmi.py z pierwszych zajęć dodając teraz instrukcję warunkową,
# która wyświetli w zależności od wyniku: niedowaga / waga normalna / nadwaga / otyłość.
# BMI = (masa (kg)) / (wzrost (m))²
weight = int(input('Podaj swoją wagę [kg]:'))
height_cm = int(input('Podaj swój wzrost [cm]:'))
height_m = height_cm / ... |
# Utwórz klasę Customer, która ma pola imię nazwisko, oraz email klienta
# Dodaj metodę rejestracji, która zwraca datę o tyle dni do przodu ile customer ma liter w imieniu i nazwisku
import datetime as t
class Customer:
def __init__(self, name, surname, client_email):
self.name = name
self. surnam... |
# Zadanie 4
# Napisz skrypt, który zapyta użytkownika o trzy liczby całkowite,
# a następnie pomnóż dwa pierwsze. przed podzieleniem wyniku przez trzecią liczbę.
# Wejście i wyjście powinny być zrozumiałe dla użytkownika.
print("Podaj proszę 3 liczby całkowite")
print()
user_input1 = int(input("Pierwsza liczba: "))
... |
class Point:
def __init__(self, num):
self.__x = '0'
self.num = num
def get_x(self):
return self.__x
def set_x(self, x):
self.__x = x
p1 = Point(10)
print(p1.num)
print(p1.__x) # nie zadziała, atrybut prywatny! potrzebujemy getter
print(p1.get_x())
p1.set_x(5)
print(p1... |
class Animals:
def __init__(self, animal_name):
self.animal_name = animal_name
print("Animals is one of the kingdoms in nature.")
def feeding(self):
print("Animals cannot be feed by photosynthesis.")
class Mammals(Animals):
def __init__(self, animal_name):
super().__init_... |
# Zadanie 7
# Napisz konwerter walut.
# Program poprosi użytkownika o kwotę pieniędzy, jaką wezmą na wakacje
# a następnie przeliczy tę kwotę w euro oraz w dolarach.
# Zignoruj wszelkie centy, które mogą wyniknąć z konwersji.
# Wejście i wyjście powinny być zrozumiałe dla użytkownika.
amount_of_money_PLN = int(input('... |
# Oblicz koszt wyprawy znając dystans, spalanie na 100km i cenę litra benzyny.
# Załóżmy, że spalanie na 100km wynosi 6,4 l, trasa to 120km, litr benzyny kosztuje 5,04 zł.
# Zmodyfikuj skrypt tak, by przyjmował wartości od użytkownika.
print("Please provide values for:")
mileage_per_100 = float(input("Mileage per 1... |
# Stwórz zmienną password. Hasło powinno składać z liter i cyfr, zwierać conajmniej 1 dużą literę i mieć długość conajmniej 8 znaków.
# Poinformuj użytkownika, jeśli wpisane hasło jest nie poprawne. Wyświetl różne komunikaty w zależności od rodzaju błędu.
password = (input('Please provide your password: '))
if len(pa... |
# Utwórz 2 krotki.
# Następnie utwórz listę będącą połączeniem elementów o parzystym indeksie z pierwszej krotki,
# oraz nieparzystych elementów z drugiej.
# Przekształć powstałą listę w set.
tuple1 = ('a', 'b', 'c', 'd', 'e')
tuple2 = (0, 1, 2, 'c', 4, 5)
list1 = list(tuple1[::2])
print(list1)
list2 = list(tuple2[1:... |
# Stwórz zmienną password. Hasło powinno składać z liter i cyfr, zwierać conajmniej 1 dużą literę i mieć długość conajmniej 8 znaków.
# Poinformuj użytkownika, jeśli wpisane hasło jest nie poprawne. Wyświetl różne komunikaty w zależności od rodzaju błędu.
password = input("Stwórz hasło, które składa się z liter i cyfr... |
# 5▹ Stwórz grę ciepło zimno.
#
# Komputer losuje liczbę z zakresu od 1 do 100.
#
# Użytkownik podaje swój traf.
#
# Komputer odpowiada ciepło zimno, ale nie więcej niż 6 razy.
#
# Jeśli użytkownik zgadnie wygrywa gracz.
#
# Jeśli po 6 próbach użytkownik nie zgadnie - wygrywa kom... |
import torch
import math
# Can't use nn package, so how do we create a torch class ? For now, a normal python class.
class Flatten:
def __init__(self):
pass
def cuda(self):
return self
def forward(self, input):
B = input.shape[0]
output = input.reshape(B, -1)
return output
def backward(self, input, g... |
from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('D:/tmp/nihao.PNG').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255, 255, 255, 0))
# get a font
fnt = ImageFont.truetype('C:\\Windows\\Fonts\\simsun.ttc', 40)
... |
contador=0
while(contador<100):
if(contador%2!=0 and contador%7!=0):
print(contador)
contador=contador+1 |
def main():
for n in range(2,10):# n 在[2,10)遍历,for循环是遍历,而while循环是条件
for x in range(2,n):
if n % x == 0:
print(n,'equals',x,'*',n//x)# //是商的取证,向下取整
break #break是结束整个循环
else:#else后面的表达式在for循环列表遍历完毕后或while条件语句不满足时执行
# loop fell through witho... |
#猴子吃桃问题。猴子第一天摘下若干桃子,当即吃掉一半,还不过瘾,又多吃了一个;
#第二天又将剩下的吃了一半,又多吃了一个。以后每天都吃前一天剩下的一半多一个
#第五天吃完后正好剩一个
#问:猴子第一天摘了多少桃子
n = 1
for i in range(5,0,-1): #意思是从列表的下标为5的元素开始,倒序取到下标为0的元素(但是不包括下标为0元素),步长为-1
#range(start, end, step) ,都取不到 end 上的数值
n = (n+1)<<1 #<<符号是按位左移的意思,就是把对象转为2进制,有效数字往左移动。
'''
<< 1就是按位左移1个单位。比如2<<1... |
from graphics import *
win = GraphWin("Celsius Converter", 600,500)# 创建窗口对象,长宽400 ×300像素,默认为200×200
win.setCoords(0.0, 0.0, 3.0, 4.0)
# setCoords (xll, yll, xur,yur) 设置窗口的坐标系。 左下是(xll,yll), 右上角是(xur,yur)。 所有后面的绘制都以这个坐标系做参照(plotPexil 除外)
# 绘制接口
Text(Point(1, 3), " Celsius Temperature:").draw(win)
#Text(anchor... |
num1=int(input('enter number 1'))
num2=int(input('enter number 2'))
num3=int(input('enter number 3'))
if(num1>num2)&(num1>num3):
if(num2>num3):
print('number 2 is second largest')
else:
print('number 3 is second largest')
if(num2>num1)&(num2>num3):
if(num1>num3):
print('number 1 is s... |
num1=int(input('enter number 1'))
num2=int(input('enter number 2'))
num3=int(input('enter number 3'))
if(num1>num2)&(num1>num3):
print('number 1 is maximum')
elif(num2>num3)&(num2>num1):
print('number 2 is maximum')
else:
print('number 3 is maximum')
|
def add(num1,num2):
result=num1+num2
return result
def sub(num1,num2):
result=num1-num2
return result
def mul(num1,num2):
result=num1*num2
return result
|
salary=int(input('enter your salary'))
exp=int(input('enter your experience'))
if(exp>5):
print('bonus=',0.05*salary)
else:
print('no bonus') |
import re
#
# x='axy+' #only this group position revealed
# r='aaa a gaaaa aarCVXYaxynnnxayt'
# matcher=re.finditer(x,r)
# for match in matcher:
# print(match.start())
# print(match.group())
# x='a*' #A'S POSITION AS GROUPS/NOT, ALL VALID AND OTHERS POSTION SEPARATELY-ie, g,r,t positon number will be shown c... |
lst=[10,10.5,True,"jhancy"] #heterogeneous data support
print(lst)
lst=[10,10.5,True,"jhancy","jhancy"]# duplicate data support
print(lst)
lst=[False,10,10.5,True,"jhancy"]#insertion order preserve
print(lst)
print(lst[2]) #index 0 to n-1
lst[1]=5
print(lst) #list is mutable
|
lst=[10,20,21,22,23,24]
flag=0
num=int(input("enter element to search"))
for i in lst:
if(i==num):
flag=1
break
else:
pass
if(flag>0):
print("element found")
else:
print("element not found") |
"""
A module that helps classify types of triangles.
"""
import argparse
import sys
from typing import List, Tuple
def classify_triangle(side1: float, side2: float, side3: float) -> str:
"""
@brief Classify the type of a triangle based on its sides.
Returns a string with the type of triangle according to... |
#!./venv/bin/python
"""
Generate world.
"""
# TODO: https://stackoverflow.com/questions/35590724/filling-color-on-image-with-python
# PIL.ImageDraw.floodfill
# TODO: GREAT IDEA: PERLIN LINE TO CREATE CLIMATE ZONES
import os
import random
import time
import math
import timeit
import sys
import cv2
import noise
impo... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 14:27:34 2020
Simulating Monty Hall
There are 3 doors in front of you, and there is a prize behind one of them.
Once you select a door, Host will open one of the other doors that not have a prize behind it
You will then have the opportunity to switch from the door... |
import heapq
# open the file and read the data into a list
file = open("rand1000000.txt","r")
data = file.read().split(" ")
for index,element in enumerate(data):
data[index] = element.strip()
data = [int(x) for x in data if x != '']
# this function creates two sublists of size 50 to sort with radix and bucket sor... |
import math
def quadratic(a, b, c):
x1 = ((-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)) #quadratic fomular for ax^2+bx+c=0
x2 = ((-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))
print(x1, x2)
a = 1
b = -1
c = 1
quadratic(a, b, c) |
""" Problem 16
Start: Sep/13/2021 9:35pm
Finished: Sep/13/2021 9:40pm
"""
def compute(pw):
num = 2**pw
digits = list(map(int,str(num)))
return sum(digits)
n = 1000
print(f"The Sum of the Digits of the Number 2^{n} Is: {compute(n)}") |
""" Problem 15
Start: Sep/12/2021 5:50pm
Finished: Sep/13/2021 9:35pm
"""
from math import factorial, prod
# pascal triangle skip 2 rows per n, middle value is the number of possible routes
def compute4(n):
n = n*2+1
nums = [[1],[1,1]]
tmp = []
for _ in range(1,n-1):
tmp.append(1)
for ... |
class Item:
def __init__(self, name):
print(f"An instance crated:{name}")
print("i am crated")
def calculate_total_Price(self, x, y):
return x*y
item1 = Item('laptop')
item1.name = 'Phone'
item1.price = 100
item1.quantity = 5
print(item1.calculate_total_Price(item1.price, item1.quanti... |
pip install package_name
# or #
conda install package_name
pip install package_name
# or #
conda install package_name
import pandas as pd
import numpy as np
import pandas as pd
import numpy as np
student = pd.read_csv('/data/class.csv')
student = pd.read_csv('/data/class.csv')
# Notice you must specif... |
for i in range(5): # range is creating a list from 0-5 (not including 5 offcourse)
print(i)
print("----------------")
for i in range (5,10): # you can pick upper/down bounds
print(i)
print("------------------")
a = ["Mary","had","a","little",'lamb']
for i in range(len(a)): # measuring the length of a
p... |
# -*- coding: utf-8 -*-
# @Time : AD 2021/02/03 21:14
# @Author : Lim Yoona
# @Site :
# @File : 08_producer_consumer.py
# @Software: PyCharm
"""
生产者消费者模式
1.队列:先进先出
2.栈:先进后出
python的Queue模块提供了同步和线程安全的队列类
FIFO(先进先出):Queue
LIFO(后进先出):LifoQueue
优先级队列:PriorityQueue
"""
... |
# -*- coding: utf-8 -*-
# @Time : AD 2021/02/03 18:40
# @Author : Lim Yoona
# @Site :
# @File : 01_threading.py
# @Software: PyCharm
"""
多线程-threading
1.使用threading模块
"""
import threading,time
def saySorry():
print('darling, i am so sorry, can i have dinner?')
time.sleep(1)
if __name__ ... |
# coding=utf-8
"""
函数引用
"""
# 创建函数
def test1():
print('test1')
# 调用函数
test1()
# 引用函数
ret = test1
print(id(ret))
print(id(test1))
# 通过引用调用函数
ret()
# 闭包
def test(num):
# 创建内部函数,通过外部传递参数到内部函数实现闭包
def test_in(num_in):
print("in test_in 函数, number_in is %d" % num_in)
return num + num... |
# -*- coding: utf-8 -*-
# @Time : 2021/2/7 10:05
# @Author : Lim Yoona
# @Site :
# @File : 03_algorithm_analysis.py
# @Software: PyCharm
""""""
"""
时间复杂度与大O记法
大O记法:
定义:对于一个单调的整数函数f,若存在一个整数函数g和实常数c>0,
使得充分大的n总有f(n)<=c*g(n),就可以说函数g是一个渐进函数,
记为f(n)=O(g(n))... |
# -*- coding: utf-8 -*-
# @Time : 下午4:43
# @Author : gutianyu
# @Site :
# @File : 01_binary_tree
# @Software: PyCharm
"""树(tree)"""
"""
树是一种抽象的数据类型(ADT)或是数据结构,用于模拟具有树状结构性质的数据集合。
特点:
1.每个节点有零个或多个子节点
2.没有父节点的节点称为根节点
3.每一个非根节点有且只有一个父节点
4.除了根节点以外,每个子节点可以分为多个不相交的子树
... |
# -*- coding: utf-8 -*-
# @Time : 2021/2/10 16:52
# @Author : Lim Yoona
# @Site :
# @File : 02_double_ended_queue.py
# @Software: PyCharm
"""
双端队列(deque,double-ended queue)
"""
"""
具有队列和栈的性质的数据结构
双端队列的任意一端入队和出队
"""
class Deque:
def __init__(self):
self.items = []
def is_empty(... |
# -*- coding: utf-8 -*-
# @Time : 2021/2/10 17:09
# @Author : Lim Yoona
# @Site :
# @File : 01_bubble_sort.py
# @Software: PyCharm
"""
冒泡排序
""""""
比较两个元素,不符合排序要求的则调换两者顺序,遍历整个队列直至排序完成
算法运作:
1.比较相邻的元素。如果第一个比第二个大(升序),就交换他们两个。
2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
... |
"""Views for posting questions"""
from flask import jsonify, request
from flask_restful import Resource
from app.api.v2.questions.models import QuestionsModel
from app.api.v2.token_decorator import require_token
from app.api.v2.users.models import UserModel
from app.api.validators import (
non_existance_question, ... |
sample_str = " This is a python string object "
# search related functions
# count() # number of occurrences of a substring
# index() # index of substring; error if not found
# find() # index of substring; -1 if not found
print("Character 'd' found ", sample_str.count("d"), " time(s)")
print("Index of first ... |
n=int(input())
if(n<=20):
if n==0:
fact=1
else:
fact=1
for c in range(1,n+1):
fact=fact*c
print(fact)
|
#!/usr/bin/python3
import os, re, sys
class CodeWriter:
def __init__(self, file):
self.file = file
self.labelNo = 0
def _get_next_label(self):
self.labelNo += 1
return 'LABEL' + str(self.labelNo)
def write(self, line):
self.file.write(line + '\n')
def write_comment(self, text):
self.write('// ' + t... |
# The example below is a basis class in python. the constructor is defined using the method name '__init__'.
# the 'self' syntax denotes the instance of the class. It is a requisite for each method
class Person:
def __init__(self, name, age, wake_up_time):
self.name = name
self.age = age
se... |
#capitulo 9: archivos
#en vez de escribir la direccion, mejor usar la funcion path del modulo os, para juntar los nombres de las carpetas
#asi vana funcionar sin importar el sistema operativo donde se corran
import os
os.path.join("Users","bob","st.txt") #ojo que falta algo que poner antes que User
# r obre archuv... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 12:34:45 2020
@author: 780020
"""
import turtle
def drawBar(t, height):
t.begin_fill()
t.left(90)
t.forward(height)
t.write(' '+ str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.... |
#Problem 9: Special Pythagorean Triplet
#Kyle Verhoog August 2, 2014
#A Pythagorean Triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
#For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
u = 1000... |
#Problem 4: Largest Palindrome Product
#Kyle Verhoog August 1, 2014
#A palindrome number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99
#Find the largest palindrome made from the product of two 3-digit numbers
def reverse(s):
r = ""
for i in range(len... |
#ATM
#http://www.codechef.com/problems/HS08TEST
bank_charge = 0.50
s = input()
s = s.split(" ")
x = int(s[0])
y = float(s[1])
if (x % 5) == 0:
if x + bank_charge <= y:
y -= x + bank_charge
print('{:.2f}'.format(y))
|
def readFiles(paths):
return [open(path) for path in paths]
def lineCounts(files):
for file in files:
counter = 0
for line in file:
counter += 1
print(file.name + "\t\t" + str(counter))
def checkArticles(file):
maxi = -1
mini = -1
minline = ""
maxline = "... |
def median(aList):
ct = len(aList)
if (ct % 2 == 0):
i1 = ct // 2
i2 = i1 - 1
return (aList[i1] + aList[i2])/2
else:
return aList[ct//2]
|
#Joseph Lee
#Text Mining Project for Software Design
#This document contains the code used to compare word frequencies between the
#Douay Rheims bible and the third revision of the Koran. The goal was to look for
#possible similarities between the two religions
#Helper functions:
import pickle
def strip_punc(strin... |
#sum all the digits below 1000 that are divisible by 3 or 5
print(sum([x for x in range(1, 1000) if x%3 == 0 or x%5 == 0]))
#or
counter = 0
for x in range(0,1000):
if x%3 ==0 or x%5 == 0:
counter += x
print counter
|
kilometers = int(input())
timeOfTheDay = input()
list = []
taxPrice = 0;
if timeOfTheDay == 'day':
taxPrice = 0.70 + 0.79 * kilometers
list.append(taxPrice)
elif timeOfTheDay == 'night':
taxPrice = 0.70 + 0.90 * kilometers
list.append(taxPrice)
if kilometers >= 20 and kilometers < 100:
busPrice =... |
steps = input()
totalSteps = 0
while totalSteps <= 10000:
if steps != "Going home":
steps = int(steps)
totalSteps += steps
if totalSteps >= 10000:
print("Goal reached! Good job!")
break
steps = input()
else:
steps = input()
steps = int(... |
count = int(input())
for x in range(0, count):
print("$", end = "")
for i in range(x):
print(" $", end="")
print() |
facebook = 150
instagram = 100
reddit = 50
number_of_open_tabs = int(input())
salary = int(input())
n = number_of_open_tabs
ouput = "You have lost your salary."
while n > 0:
currentSite = input()
if currentSite == "Facebook":
salary -= facebook
if salary <= 0:
print(ouput)
... |
firstName = input()
secondName = input()
age = int(input())
town = input()
print("You are " + firstName + " " + secondName + ", a " + str(age) + "-years old person from " + town + ".")
#print(f"You are {firstName} {lastName}, a {age}-years old person from {town}.")
|
import math
a = float(input())
b = float(input())
c = float(input())
d = float(input())
totalTime = 1 / (1/a + 1/b + 1/c)
totalTime = totalTime + totalTime * 0.15
d = d - totalTime
if d >= 0:
print(f"Cleaning time: {totalTime:.2f}")
print(f"Yes, there is a surprise - time left -> {math.floor(d)} hours.")
else... |
size = int(input())
pointX = int(input())
pointY = int(input())
lowerRectangleX1 = 0
lowerRectangleY1 = 0
lowerRectangleX2 = 3*size
lowerRectangleY2 = size
upperRectangleX1 = size
upperRectangleY1 = size
upperRectangleX2 = 2 * size
upperRectangleY2 = 4 * size
if pointX >= lowerRectangleX1 and pointX <= lowerRectangl... |
budget = float(input())
type = input()
peopleCOunt = int(input())
moneyLeft = 0
if peopleCOunt >= 1 and peopleCOunt <= 4:
moneyForTransport = budget - budget * 75 / 100
elif peopleCOunt >= 5 and peopleCOunt <= 9:
moneyForTransport = budget - budget * 60 / 100
elif peopleCOunt >= 10 and peopleCOunt <=24:
... |
firstInput = input()
inputToMatch = input()
firstInput = firstInput.lower()
inputToMatch = inputToMatch.lower()
if firstInput == inputToMatch:
print("yes")
else:
print("no")
|
#! /usr/bin/python3
import sys
sys.version_info[0]
lab_exercise = "Classes"
lab_type = "solution-code"
python_version = ("%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]))
print("Exercise: %s" % (lab_exercise))
print("Type: %s" % (lab_type))
print("Python: %s\n" % (python_version))
... |
#code
def count_triplets():
t = int(input())
count = 1
count_triplets = 0
while count<=t:
array_size = int(input())
array = [int(s) for s in input().split(" ")]
array = sorted(array)
min_element = array[0]
max_element = array[array_size-1]
i = 0
... |
#! /usr/bin/env Pyrhon3
# Implement a program that prints out a multiplication table for a number given as its cmd line argument
import sys
def multiplication_table(arg):
for i in range(1, 11):
print(str(i) + ' * ' + str(int(arg)) + ' = ' + str(i * (int(arg))))
multiplication_table(sys.argv[1])
|
#! /usr/bin/env Pyrhon3
list_of_tuples_even = []
list_of_tuples_odd = []
for i in range(1, 11):
for j in range(1, 11):
if i % 2 == 0:
list_of_tuples_even.append((i, j, i * j))
else:
list_of_tuples_odd.append((i, j, i * j))
print(list_of_tuples_odd)
print('****************... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class MyInt:
def __init__(self, value):
self.value = value
def __lt__(self, other):
print('lt called')
if isinstance(other, MyInt):
return self.value < other.value
return False
def __le__(self, other):
pri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from enum import Enum
# Let's have plain enum
# The enum elements are effectively constants
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
red = Color.RED # We can assign the enum elements
print(red) # and print them
if red is Color.RED: # We... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal:
def __init__(self):
super().__init__()
print('Animal.__init__')
def foo(self):
print('Animal.foo')
class HasLegs(Animal):
def __init__(self):
super().__init__()
print('HasLegs.__init__')
def foo(sel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class File:
"""
Our context manager for files. It is totally useless as the file objects are context
managers, but it allows us to see the concept.
"""
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
... |
#! /usr/bin/env Python3
# Implement a function that counts a factorial of its argument
import sys
def factorial():
tmp = 1
upperBound = sys.argv[1]
for i in range(1, int(upperBound) + 1):
tmp *= i
print(tmp)
factorial()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############
# namedtuple
##############
# Let's have data about patients eyes
vision = (9.5, 8.8) # (left eye, right eye)
print(f'Both eyes {vision}')
print(f'Left eye {vision[0]}, right eye {vision[1]}') # we need to remember that left eye is the index 0 and rhe... |
#!/usr/bin/env python3
# Let's create a list of squares
squares = []
for x in range(10):
squares.append(x**2)
# It's fine but it takes 3 lines
# A better option is to use the list comprehensions
squares = [x**2 for x in range(10)]
# A list comprehension consists of brackets containing an expression followed by ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Base class with cat behaviour
class Cat:
def meow(self):
print("meow")
# Base class with dog behaviour
class Dog:
def woof(self):
print("woof")
# Derived DogCat class combining both parents
class CatDog(Cat, Dog):
def meow_woof(self):
... |
"""
Assignment: Develop a module for logging. It should be used as given below. It defines three functions:
- set_log_fn - allows the client to provide custom output function for log entries. The parameters to the function are the
log message and a set of custom parameters that can be passed via function log
- set_... |
"""Utilities for input validation."""
import numpy as np
import pandas as pd
from pandas.api.types import is_categorical_dtype, is_numeric_dtype
__all__ = [
"check_uniq",
"check_column_existence",
"check_is_dataframe",
"is_numeric",
"find_sparsity",
"check_continuity"
]
def check_uniq(X):... |
def AskBiman(height,weight):
biman = weight/pow((height/100),2)
if(biman < 18.5):
print("저체중입니다.")
elif(biman>=18.5 and biman<23):
print("정상체중입니다.")
elif(biman>=23 and biman<25):
print("과체중입니다.")
elif (biman >= 25 and biman < 30):
print("경도비만입니다.")
elif (biman >=... |
# 행과 열의 크기를 입력받아 바둑판형태의 2차원 공간의 각 칸마다 행 번호와 열번호를 곱한 값을 출력하시오.
row = int(input("row?= "))
columns = int(input("columns?= "))
for i in range(1,row+1):
for j in range(1,columns+1):
print("%d"%(i*j),end=' ')
print('') |
def PrintStar(size):
for i in range(size.__len__()):
print("*"*size[i])
inputSize = []
for i in range(10):
inputSize.append(int(input("높이를 입력하세요")))
PrintStar(inputSize) |
# 019 문자열 곱하기
#
# 변수가 다음과 같이 문자열을 바인딩하고 있을 때 실행 예와 같이 출력하는 프로그램을 작성하라.
#
# >>> t1 = 'python'
# >>> t2 = 'java'
#
# 실행 예:
# python java python java python java python java
# python java java python java java
t1 = 'python'
t2 = 'java'
print((t1 + " " + t2 + " ") * 3)
print((t1 + " " + (t2 + " ") * 2) * 2)
|
# 국어, 영어, 수학 점수를 입력받아 이 점수의 총점과 평균을 계산하고, 평균 점수에 따라 등급을 정하여 출력하세요. (수, 우, 미, 양, 가)
# 90이상 : 수 / 80 ~ 90미만 : 우 / 70 ~ 80미만 : 미 / 60 ~ 70 미만 : 양
# 60미만 : 가
# 총점은 “국어점수 + 영어점수 + 수학점수”, 평균 “총점/3.0” 으로 하면 됩니다.
# 사용하는 변수는
# kor, eng, math 과목 점수
# total 총점
# average 평균점수
kor=int(input("국어점수를 입력하세요.: "))
eng = ... |
# 반복해서 0부터 100 사이의 숫자를 입력받아 지금까지 입력된 숫자들 중 가장 큰 수와 가장 작은 수가
# 무엇인지 출력하세요. 범위를 넘으면 종료하게 하세요. 반복은 while 문을 사용하세요.
# 사용하는 변수는
# number #입력받은 수
# max_num, min_num #가장 큰 숫자, 가장 작은 숫자
max_num = 0;
min_num = 100;
number = 0;
while (number<100):
number = int(input("0~100"))
if(number>max_num):
max... |
# 숫자 2개를 입력받은 후 1부터 100까지의 숫자 중에 이 두 숫자 중 하나의 숫자에 대해서만 배수인 수를
# 모두 출력하세요, 즉 숫자의 공통배수인 숫자는 출력하면 안됩니다.
# Ex (15, 20입력시 > 15, 20, 30, 40, 45, 75, 80, 90, 100)
# 반복은 for문을 사용하세요.
# 사용하는 변수는
# num1, num2 #입력받은 두개의 수
# index # 반복문 사용을 위한 변수
num1 = int(input("1수"))
num2 = int(input("2수"))
for i in range(1,101):... |
# 숫자를 한 개 입력받은 후에 그 숫자의 높이를 가지는 직각삼각형을 “ * “ 문자로 화면에 출력하세요. 예를 들어 3이 입력되면
#
# *
# **
# *** 와 같은 형태로 출력되어야 합니다.
#
# 사용하는 변수는
# height #출력하려는 삼각형의 높이
height = int(input("숫자를 입력하세요."))
for i in range(1,height+1):
for j in range(0,i):
print("*",end='')
print('') |
# 숫자를 입력받은 후 이 숫자가 1보다 큰 경우 1부터 이 숫자까지의 모든 정수를 더한 값을 출력하세요.
# 수열의 합 공식 쓰지 말고, 반복은 for 문으로 하세요.
# 사용하는 변수는
# number #입력받은 수
# totalsum #1부터 더한 결과값의 수
# index #반복문 사용을 위한 변수
number = int(input("입력받은 수"))
totalsum = 0
if(number>1):
for i in range (number+1) :
totalsum+=i
print(totalsum) |
class Hash:
def __init__(self,tam):
self.tab = {}
self.tam_max = tam
def funcaohash(self, chave):
v = int(chave)
return v%self.tam_max
def cheia(self):
return len(self.tab) == self.tam_max
def imprime(self):
for i in self.tab:
... |
"""
Code Challenge
Name:
JSON Parser
Filename:
json.py
Problem Statement:
Get me the other details about the city
Latitude and Longitude
Weather Condition
Wind Speed
Sunset Rise and Set timing
"""
import requests
entry = input("enter the city name")
url1 = "http://a... |
# -*- coding: utf-8 -*-
"""
Code Challenge
Filename:
map2.py
Problem Statement:
names = ['Mary', 'Isla', 'Sam']
for i in range(len(names)):
names[i] = hash(names[i])
print (names)
(Hopefully, the secret agents will have good memories and won’t forget each other’s secret code names during the secret m... |
"""
Code Challenge
Name:
Zoo Management
Filename:
zoo.py
Problem Statement:
Create different functions to :
read the zoo.csv file using readlines and print them
Print in list of animals in groups (elephant / tiger / lion / zebra / kangaroo)
print the total number of water need by elepha... |
"""
Code Challenge:
Name:
Bid Plus
Filename:
bid_plus.py
Problem Statement:
USE SELENIUM
Write a Python code to Scrap data and download data from given url.
url = "https://bidplus.gem.gov.in/bidlists"
Make list and append given data:
1. BID NO
2. items
... |
# -*- coding: utf-8 -*
"""
Created on Fri May 10 15:55:22 2019
@author: Abhishek
"""
filename1=str(input("write the file name which you want to copy::" ))
filename2=str(input("write the file name of new file::" ))
filename1=open(filename1, mode='r')
filename2=open(filename2,mode='w')
for line in filename1:
file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.