text stringlengths 37 1.41M |
|---|
'''class Person:
pass
from oop import Person
swetha=Person()
print(swetha)
print(type(swetha))
if type(swetha)==Person:
print("True")
else:
print("False")'''
'''class Person:
def say_hello(self):
print("Hello")
print(self)
from oop import Person
swetha=Person()
swetha.say_hello()'''
'''c... |
def reverse_words(sentence):
word_list = sentence.split()
return ' '.join(word_list[::-1])
|
import sqlite3
conn = sqlite3.connect('ProductDatabase.db')
c = conn.cursor()
import json
#Deletes the table of the read side
c.execute('''DROP TABLE Product''')
#Creates the table of the read side
c.execute('''CREATE TABLE Product(
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name text NOT ... |
import pandas as pd
import re
#read_html module in pandas can be used to read html pages
#and to run that we need html5lib
import html5lib
url="https://en.wikipedia.org/wiki/List_of_airports_by_IATA_code:_A"
url_read=pd.read_html(url,header=0)[0]
#re module =whitespace character remove in a file(regular expression)
sp... |
#!/usr/bin/python2
class zombie(object):
# constructor
def __init__(self, hitpoints = 10):
# global
self.hitpoints = hitpoints
# protected: one underscore
self._infestation = 100
# private: two underscores
self.__brains_eaten = 0
# same modifier as attribute... |
numbers = [1,2,3,4]
while True:
inpt = input()
if inpt == 'e':
break
else:
if int(inpt) not in numbers:
print('no')
else:
print('yes')
break
|
from tkinter import *
from tkinter import ttk # ttk is them of tk
import csv
#csv File
def WritetoCSV(data):
with open('data.csv','a',newline='',encoding='utf-8') as file:
fw = csv.writer(file) # fw = file writer
fw.writerow(data)
print('บันทึกไฟล์สำเร็จ')
#เครื่องหมาย #... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 20:01:18 2021
@author: Livia Alves
"""
city = input('Em que cidade você nasceu: ')
city = city.upper().strip()
corte = city.split(' ')
print(corte[0] == 'SANTO')
|
# -*- coding: utf-8 -*-
"""
Created on Sun May 30 19:50:54 2021
@author: Livia Alves
"""
tempc = float(input('Informe a temperatura em °C: '))
tempf = 32 + tempc*9/5
print('A temperatura de {:.2f}°C corresponde a {:.2f}°F'.format(tempc, tempf)) |
# -*- coding: utf-8 -*-
"""
Created on Sun May 30 15:24:20 2021
@author: Livia Alves
"""
n = int(input('Digite um número: '))
print('Seu sucessor é {} e seu antecessor é {}'.format(n+1, n-1)) |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 16:50:58 2021
@author: 55349
"""
p = int(input('Primeiro valor: '))
s = int(input('Segundo valor: '))
t = int(input('Terceiro valor: '))
if p > s and p > t:
print('O maior valor digitado foi {}'.format(p))
if p < s and p < t:
print('O menor valor digitado fo... |
def fac(n):
if n == 0:
return 1
else:
return fac(n-1) * n
print(fac(5))
def gcd(num1, num2):
if num1 > num2:
return gcd(num1-num2, num2)
elif num1 < num2:
return gcd(num1, num2-num1)
else:
return num1
print(gcd(68,119))
def reverse(word):
if word == ""... |
"""
Adapter pattern example.
"""
from abc import ABCMeta, abstractmethod
NOT_IMPLEMENTED = "You should implement this."
RECHARGE = ["Recharge started.", "Recharge finished."]
POWER_ADAPTERS = {"Android": "MicroUSB", "iPhone": "Lightning"}
CONNECTED = "{} connected."
CONNECT_FIRST = "Connect {} first."
class Rechar... |
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
num_valleys = 0
numUp = 0
numDown = 0
for i in range(len(s)):
if s[i] =='U':
numUp += 1
else:
numDown += 1
if numDown == numUp and s[i]... |
from tkinter import *
root = Tk()
root.title("Simple Calculator")
#variable_sect
insertedNumber = []
totalNum = 0
def addNumber(number):
num=inputField.get()
inputField.insert(len(num), number)
def operate(opt):
if opt == "+" :
insertedNumber.append(inputField.get())
... |
def main():
# membuat judul program
print('Menentukan Nilai Terbesar Dari Dua Bilangan')
# menentukan input user
a = int(input("masukan bilangan pertama: "))
b = int(input("masukan bilangan kedua: "))
# Menentukan Nilai Bilangan dengan if else
if a > b:
maks = a
else:
... |
#!usr/bin/env python3
"""
Author: Mild Z Ferdinand
Capitalize Words
Challenge Description:
Write a program which capitalizes the first letter of each word in a sentence.
"""
import sys
input_file = sys.argv[1]
def main():
with open(input_file, 'r') as text:
for line in text:
mystring = lin... |
#!usr/bin/env/ python3
"""
Author: Mild Z Ferdinand
Description: Hex to Decimal challenge. You will be given a hexadecimal(base 16)
number. Convert it into decimal (base 10).
"""
import sys
def main():
try:
input_file = sys.argv[1]
except:
return "Please supply file name as a command line arg... |
operacion=input("elige la operacion deseada (multi/divi/suma/resta/poten):")
primer_digito=int(input("escribe el primer digito:"))
segundo_digito=int(input("escribe el segundo digito:"))
if operacion==("multi"):
print("el resuntado es:{}".format(primer_digito * segundo_digito))
elif operacion==("divi"):
prin... |
def partition(start, end, array):
pivot = array[start]
while start < end:
while start < len(array) and array[start] <= pivot:
start += 1
# Decrement the end pointer till it finds an
# element less than pivot
while array[end] > pivot:
end -= 1
# ... |
#/bin/usr/python
#String operations
import string
import random
import time
def PalindromeCheck():
string = input("Enter value of string: ")
j= len(string)-1
for i in range(0,len(string)):
if string[i] == string[j]:
i+= 1
j-= 1
if i == j:
print(... |
#/usr/bin/python3
#Number guessing game
import sys
import random
def PlayGame(num):
TypeOfOperation = input( "Do you want to attempt system generated attempts or custom, Insert 'S' OR 'C' : ")
if TypeOfOperation.upper() == 'C':
N = int(input("Enter number of Attempts : "))
else:
N = random... |
#!/bin/usr/python
#Tuple operations test
def TupleOperations(tup1):
for ele in tup1:
print("Elements: ", ele)
print("Size of Tuple : ", tup1.__sizeof__())
def FlattenTuple(t):
print("Original Tuple :", t)
Tuple2 = t
str1 =""
for ele in range(len(t)):
print("Elements :", tuple(t[... |
phone_dir = {}
def inp():
print("\nEnter your Name : ")
name = str(input()).lower()
if( not name.isalpha()) :
print("Error! Not a valid Name!!")
return
phone_num = str(input("Enter your Phone Number : "));
if((not phone_num.isdigit() ) or len(phone_num) > 10) :
print("Error!... |
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num, "Even Number")
else:
print(num, "Odd number") |
a = "My name is Abdur-Rakib"
print("".join(reversed(a)))
"""Number = int(input("Please Enter any Number: "))
Reverse = 0
while (Number > 0):
Reminder = Number % 10
Reverse = (Reverse * 10) + Reminder
Number = Number // 10
print("\n Reverse of entered number is = %d" % Reverse)"""
"""txt = "... |
import datetime
from datetime import date , timedelta
monday1 = 0
months = range(1,13)
today = date.today()
yearnow = today.year
x = int(yearnow)
yearsplus = today + timedelta( 365 * 10 )
years10 = yearsplus.year
y = int(years10)
for year in range(x, y):
for month in months:
if date(year, month,... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 8 11:35:38 2019
@author: john
"""
def intcode(input_list, l):
l = [int(x) for x in l] # Convert list values to ints
end = False # set up a condition for the while
pointer = 0 # initialize the pointer to the first position
... |
# 10진수 정수값을 입력받아 2~36진수로 변환하여 출력
def card_conv(x: int, r: int) -> str:
"""정수 x를 r 진수로 변환한 뒤 그 수를 나타내는 문자열을 반환"""
d = '' # 변환 뒤 문자열
dchar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n = len(str(x)) # 변환하기 전의 자릿수
print(f'{r:2} | {x:{n}d}')
while x > 0:
print(' +' + (n + 2) * '-')
... |
# 각 열에 1개 퀸을 배치한 조합을 재귀적으로 나열하기
# 각 열별로 8칸이 존재하니 총 8가지가 존재, 그래서 8 을 8번 곱한다..
# 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 = 16,777,216 ( 위 규칙을 추가할 경우 퀸을 배치하는 조합의 수)
pos = [0] * 8 # 각 열에서 퀸의 위치를 출력
# print(pos)
def put() -> None:
"""
각 열에 배치한 퀸의 위치를 출력
퀸을 더이상 배치할 필요가 없으므로 퀸을 배치한 위치를 출력하는 것.
출력하는 값은 배열 pos 의 원소값들이다... |
# 파이썬에서 변수는 객체와 연결된 이름에 불과. 그래서 리스트 튜플의 원소자료형을 미리 정할 필요가 없다.
x = [15, 64, 7, 3.14, [32, 55], 'ABC']
for i in range(len(x)):
print(f'x[{i}] = {x[i]}')
# 출력이 된다.
|
from babel import Locale
def get_language_name(language):
return Locale.parse(language).get_language_name().capitalize()
class Localized(object):
""" Wraps a dictionary containing localized / non-localized data and offers
it through attribute access, returning the current language.
e.g.
>>... |
###############################################################################
# NonInertialFrameForce: Class that implements the fictitious forces
# present when integrating orbits in a non-intertial
# frame
##########################################################... |
def print_formatted(number):
n = number
space = ' ' * len(bin(n)[2:])
for i in range(1, number + 1):
end = '\n'
if i == n:
end = ''
first = str(i)
second = oct(i)[2:]
third = hex(i)[2:].upper()
four = bin(i)[2:]
ns = len(space)... |
#!/bin/python3
from math import factorial
import math
import os
import random
import re
import sys
# Complete the extraLongFactorials function below.
def extraLongFactorials(n):
print(factorial(n))
if __name__ == '__main__':
n = int(input())
extraLongFactorials(n)
|
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import OrderedDict
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice):
new_lst = list(reversed(sorted(set(scores))))
print(new_lst)
i = len(alice) - 1
j =0
... |
for i in range(0, 10):
for j in range(0, 10):
product = i+j
print(f"{product:>3}", end='')
print() # untuk print di baris baru
|
# Algoritma Sorting
# Kompleksitas 0(N**2)
def selectionSort(arr):
for i in range(len(arr)-1):
minIndex = i
for j in range(i+1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
arr[i], arr[minIndex] = arr[minIndex], arr[i]
a = [1, 5, 2, 7, 4, 9, 8]
selectionS... |
numbers = []
while True:
s = input("Enter a number or empty to calculate the average: ")
if not s:
break
try:
numbers.append(int(s))
except:
print("That didn't look like a number, try again?")
print("The average is %s" % (sum(numbers) / len(numbers)))
|
a=3
b=2
list=[3,5,7,8,9]
if (a in list):
print("a is in list")
else:
print("a is not in list")
if (b in list):
print("b is in list")
else:
print("b is not in list")
x=2
print(x == 2)
print(x == 3)
print(x < 3)
|
#перечисление элементов списка в квадратных скобках
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
#название первого велосипеда в списке bicycles выводится следующим образом
print(bicycles[0])
#отформатировать при помощи метода title
print(bicycles[0].title())
#выводится второй и чет... |
def readInts():
return map(int, raw_input().split())
def readInt():
return int(input())
for __ in range(readInt()):
r,b,m = readInts()
ans = 0
for i in range(m+1):
j = m-i
# print(i,j,r,b)
if i>r or j>b:
continue
ans+=1
print ans
'''
Input:
2
1 1 2
... |
"""
class definition for the block class
Author: Matthew Henschke
"""
from hashlib import sha256
from datetime import datetime
# class definition
class Block:
def __init__(self, transactions, prev_hash, nonce = 0):
"""
Constructor
:param transactions : list of transactions
:param p... |
class Solution:
def unique(self, string):
if len(string) > 128:
return False
char_set = [False for _ in range(128)]
for char in string:
ascii_val = ord(char)
if char_set[ascii_val]:
return False
# Char already found in string
... |
"""
The knows API is already defined for you.
@param a, person a
@param b, person b
@return a boolean, whether a knows b
you can call Celebrity.knows(a, b)
"""
class Solution:
# @param {int} n a party with n people
# @return {int} the celebrity's label or -1
def findCelebrity(self, n):
# Write you... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
""" A wrapper for the jbofihe parser. """
from Helpers import run_jbofihe
from Helpers import sanitize_input
class LojbanParser:
""" A wrapper for jbofihe. """
def __init__(self, args):
self.verbose = args.verbose
def parse(self, inp):
"""... |
# import chapter8
def make_pizza_fun(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
def play_sports(size, *balls):
"""球类运动"""
print("\nballs: " + str(size) +
... |
"""
chapter 9 类
Python中,首字母大写的名称指的是类。
类中的函数成为方法,类中的函数称为方法;你前面学到的有关函数的一切都适用于方法,就目前而言,唯一重要的差别是调用方法的方式
"""
# 9.1 创建和使用类
# 9.1.1 创建dog类
'''
为何必须在方法定义中包含形参self呢?因为
Python调用这个__init__()方法来创建Dog实例时,将自动传入实参self。每个与类相关联的方法
调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。
'''
class Dog():
def __init__(self, name, age):
... |
# coding:utf-8
"""
iter(iterable)
yield
"""
def _next(iter_obj):
try:
return next(iter_obj)
except:
return None
iter_0 = iter([1, 2, 3])
result = next(iter_0)
print(result)
print(_next(iter_0))
print(_next(iter_0))
print(_next(iter_0))
print(_next(iter_0))
res = (i for i in (1, 2, 3)) # ... |
# coding:utf-8
"""
序列化
class set def 不可以进行序列化
json ,pickle
"""
import json
import pickle
result = json.dumps([1, 2])
print(result)
a = {'name': '张三'}
a_json = json.dumps(a)
print(a_json)
print(json.loads(result))
print(json.loads(a_json))
none_json = json.dumps(None)
print(none_json)
print(json.loads(none_json))... |
# coding: utf-8
'''
__setattr__ 拦截不存在属性,并为其设置值
'''
class Person(object):
def __getattr__(self, item):
print('__getattr__ {}'.format(item))
return 'iterm {}'.format(item)
def __setattr__(self, key, value):
# if key not in self.__dict__:
self.__dict__[key] = value
print... |
# coding:utf-8
class Person(object):
name = None
age = None
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person(name='libai', age=12)
person1.name = "lisi"
print('name = %s ,age = %d' % (person1.name, person1.age))
|
#This is a string type
data = "The quick python bit me "
print( data )
#numbers
num1 = 100
num2 = 2.987654
print( num1 * num2 )
print( type(num1) )
print( type(num2) )
print( type(data) )
print( data * 6 )
data = data * 10
print( data )
print (10 > 20)
print( 10 == 10)
print ("kenys" == "Kenya")
|
scores = [34, 56, 56, 78, 74, 23, 45, 12, 25, 12, 90, 12, 47, 90]
total = 0
for mark in scores:
# print(mark)
total += mark
count = len(scores)
avg = total/count
print("Average is " + str(avg))
print("The average is {0} of this total {1}".format(avg, total))
count = 0
for mark in scores:
if mark % 2 == ... |
"""
Working with namedtuples
It is similar to creating a database table structure
where Card is the table name, and rank / suit are the columns.
the attributes in the [ ] act as the record primary key.
len() is equivalent to returning the number of rows in the table
items can be retrived using the row number (index)
... |
#lists hold marious objects, seperated by commas
#python also has arrays, and they do have differences
#can use multiple types, ordered list
myList = ['STRING', 100]
#len function to get length
print(len(myList))
#access indexs
myList[0]
#slice the same as strings
print(myList[:1])
#can concatenate by adding lists toge... |
#tuples are very similar to lists only one main difference
#THEY ARE IMMUTABLE
#they are not contained in brackets, they are in parens
tup = (1, 2, 3)
lis = [1, 2 ,3]
print(type(tup))
print(type(lis))
#can grab indexes
print(tup[1])
print(tup[2])
tup = (1, 2, 1, 1, 3)
#count items
print(tup.count(1))
#find index of fir... |
# most objects in python are iterable
# you can iterate over keys in dictionaries
my_list = [1, 2, 3]
for item_name in my_list:
print(item_name)
# some general for loop examples
# you know how these work Bobby good lord
# how to loop through values in a dictionary
my_iterable = {'key1': 1, 'key2': 2}
for key in m... |
liste = []
newliste = []
sayac = 0
boyut = int(input("Kac sayi girmek istersiniz ->"))
while sayac < boyut:
sayi = int(input("{}. sayiyi giriniz:".format(sayac+1)))
liste += [sayi]
sayac += 1
for i in liste:
if i % 2 != 0:
newliste += [i]
print("Girdiginz sayilardaki tek sayil... |
def stringCheck(s,lg):
counter = 1
words = ""
for i in s:
if counter <= lg:
words += i
counter += 1
else:
words += "\n"
words += i
counter = 2
return words
string = input("Pls enter the string:")
length = int(input("Pls enter the length:"))
print(stringCheck(string,length))
... |
sayi1 = input("Bir sayi giriniz:")
sayi2 = input("Bir sayi giriniz:")
try:
sayi1 = int(sayi1)
sayi2 = int(sayi2)
print(sayi1/sayi2)
except ValueError: #Eger degerlerden biri string bir ifade girilirse ValueError hatasi verir
print("String bir ifade girdiniz.Lütfen sayi giriniz.")
except Ze... |
import math
def max_magnitude(user_val1, user_val2):
if abs(int(user_val1)) > abs(int(user_val2)):
return user_val1
else:
return user_val2
if __name__ == '__main__':
a = input()
b = input()
print(max_magnitude(a, b))
|
male_names = { 'John', 'Bailey', 'Charlie', 'Chuck', 'Michael', 'Samuel', 'Jayden', 'Aiden', 'Henry', 'Lucas' }
female_names = { 'Elizabeth', 'Meghan', 'Kim', 'Khloe', 'Bailey', 'Jayden', 'Aiden', 'Britney', 'Veronica', 'Maria' }
# Use set methods to create sets all_names, neutral_names, and specific_names.
all_names... |
coat_check = False
while coat_check == False:
my_string = input('Enter input string:\n')
if my_string == 'q':
coat_check = True
break
while ',' not in my_string:
print('Error: No comma in string.\n')
my_string = input('Enter input string:\n')
word_list = my_string... |
# pass_maker.py
# FIXED
# Output all the values on a single line
favorite_color = input('Enter favorite color:\n')
pets_name = input('Enter pet\'s name:\n')
a_number = int(input('Enter a number:\n'))
print('You entered:', favorite_color, pets_name, a_number)
# FIXED
password1 = favorite_color
print('\nFirst passwor... |
lemon_juice_cups = float(input('Enter amount of lemon juice (in cups):\n'))
# Finish reading other items into variables, then output the three ingrdients
water_cups = float(input('Enter amount of water (in cups):\n'))
agave_cups = float(input('Enter amount of agave nectar (in cups):\n'))
total_servings = float(input('... |
# Output a menu of automotive services and the corresponding cost of each service.
services = {'Oil change': 35, 'Tire rotation': 19, 'Car wash': 7, 'Car wax': 12}
print('Davy\'s auto shop services')
for n, x in services.items():
print('%s -- $%d' % (n, x))
# Prompt the user for two services from the menu.
first... |
user_input = input()
new_list = user_input.split()
my_list = new_list
more_input = input()
ran_list = more_input.split()
rangers = ran_list
print(my_list)
print(rangers)
int_list = ''
for n in my_list:
if (int(n) >= int(rangers[0])) and (int(n) <= int(rangers[1])):
int_list += n + ' '
print(int_list, e... |
def find_max(num_1, num_2):
max_val = 0.0
if (num_1 > num_2): # if num1 is greater than num2,
max_val = num_1 # then num1 is the maxVal.
else: # Otherwise,
max_val = num_2 # num2 is the maxVal
return max_val
num_a = 5.0
num_b = 10.0
num_y = 3.0
num_z = 7.0
max_sum =... |
# out_with_the_vars.py
user_num = int(input('Enter integer:\n'))
print('You entered:', user_num)
sq_num = user_num * user_num
print(user_num,'squared is', sq_num)
sq_num *= user_num
print('And', user_num, 'cubed is', sq_num, '!!')
print('Enter another integer:')
new_int = int(input())
num_x = user_num + new_int
print(u... |
some_list = list()
some_list.append(2)
print(some_list[0])
some_list.append(3)
some_list.append(4)
some_list.append(8)
x = int(input())
some_list.append(x)
for i in range(len(some_list)):
print(some_list[i])
while x > 0:
some_list.append(x)
x = int(input())
print(max(some_list))
print(min(some_list)) |
# real_estate.py
current_price = int(input())
last_months_price = int(input())
change = current_price - last_months_price
mortgage = (float(current_price) * 0.045) / 12.0
print('This house is $%d. The change is $%d since last month.' % (current_price, change))
print('The estimated monthly mortgage is $%.2f.' % mortg... |
num_rows = 2
num_cols = 3
# Note 1: You will need to declare more variables
# Note 2: Place end=' ' at the end of your print statement to separate seats by spaces
for i in range(1, num_rows + 1):
my_char = 'A'
for j in range(num_cols):
print('%d%c' % (i, my_char), end = ' ')
my_char = chr(ord(... |
import random
unsorted = [2,5,7,1,9,3,8,6,4,0,10,12,14,13,17,15,16]
def quick_sort(to_sort):
if len (to_sort) <= 1:
return to_sort
pivot = random.choice(to_sort)
to_sort.remove(pivot)
to_sort.insert(0, pivot)
print to_sort
i = 1
for j in range(1,len(to_sort)):
if to_sort[j] < pivot:
to_sor... |
import time
'''
def fib(n):
if n < 2:
return 1
return fib(n-2) + fib(n-1)
'''
class Calculator(object):
def fib_cached(self, n, cache):
if n < 2:
return 1
try:
result = cache[n]
except:
cache[n] = self.fib_cached(n-2, cache) + self.fib_ca... |
'''
Exercise05 - CircleWithPrivateRadius Functions.
Chung Yuan Christian University
written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.)
'''
import math
class Circle:
def __init__(self, radius=1):
self.__radius = radius
def getRadius(self):
return self.__radius
de... |
import turtle
import time
turtle.showturtle()
# Initialization.
self_angle = turtle.heading()
turtle.right(self_angle)
'''
Step by step: Drawing star by using Turtle module.
'''
turtle.pensize(4) # Change the pen size to "4".
turtle.penup() # Take the pen up.
turtle.goto(-100,0) # Go to (x, y) = (-100, 0)... |
'''
Exercise03 - printList Functions.
Chung Yuan Christian University
written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.)
'''
def printList(lst):
for element in lst:
print(element)
lst = [3, 1, 2, 6, 4, 2]
printList(lst)
|
'''
Exercise05 - Tic Tac Toe Functions.
Chung Yuan Christian University
written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.)
'''
lst = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
k = 0
for i in range(4):
print("-------------")
for j in range(4):
if j == 3:
pri... |
'''
Exercise02 - Give the turtle module a try.
Chung Yuan Christian University
written by Woody Lo (the teaching assistant of Python Course_Summer Camp.)
'''
import turtle
import time
turtle.screensize(550,550) # Set the screensize for canvas.
turtle.showturtle() # Open the window (default size is 400x400)
... |
'''
Exercise03 - Quick Sort.
Chung Yuan Christian University
written by Woody Lo (the teaching assistant of Python Course_Summer Camp.)
'''
def Partition(A, p, r):
x = A[r]
i = p - 1
for j in range(p, r):
if A[j] <= x :
i = i + 1
A[i], A[j] = A[j], A[i]
# End if
# End for loop
A[i+1], A[r] = A[r], A[i... |
'''
Exercise08 - FootToMeter Functions.
Chung Yuan Christian University
written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.)
'''
def footToMeter(foot):
meter = 0.305 * foot
return meter
def meterToFeet(meter):
foot = meter / 0.305
return foot
def main():
print(format("Fee... |
import random
# setup a list of random 64-bit values to be used by BitHash
__bits = [0] * (64*1024)
__rnd = random.Random()
# seed the generator to produce repeatable results
__rnd.seed("BitHash random numbers")
# fill the list
for i in range(64*1024):
__bits[i] = __rnd.getrandbits(64)
def BitH... |
def find_sum(n):
sum, count = 0, 1
while n * count < 1000:
sum += n * count
count += 1
return sum
def lcm(a, b):
return a*b//gcd(a, b)
def gcd(a, b):
if 0 in [a, b]:
return max(a, b)
if a == b:
return a
if a > b:
return gcd(a-b, b)
return gcd(b... |
import math
table = {}
power_table = {}
def modular_power(a, b, p):
if (a == 0):
return 0
if (b == 0):
return 1
if (a, b) in power_table:
return power_table[(a, b)]
y = None
if (b % 2 == 1):
y = a % p
y = (y * modular_power(a, b - 1, p) % p) % p
else:
y = modular_pow... |
import numpy as np
import pylab as pl
class Pendulum():
'''Here is a pendulum under zero gravity, The idea is to attach \
multiple pendulums to each others end to obtain spirograph like \
figures.'''
def __init__(self, pivot_x, pivot_y, length, k=1.0):
'pivot point is the points at which pendu... |
from typing import List
from math import log
class Topic:
""" The object for topics in the system
...
Attributes
----------
id : int
The id of the topic
query : str
Content of the topic
question : str
Question that the topic seeks answers
narrative : Tenso... |
class BBVA:
"Atríbuto"
cajeros= "8"
escritorios= "10"
gerente= "1"
asientos= "30"
tabletas= "5"
camaras= "10"
maquina_contar_billetes = "3"
copiadoras= "15"
scaner_de_huella= "20"
caja_fuerte="1"
"Métodos"
def retirar(self):
print("retirar dinero")
def depositar(self):
print("depo... |
class estudiante:
"atríbutos"
mochila=1
libreta= 8
marca_texto=3
colores=12
lapicera=1
#métodos
def aprender(self):
print("aprender")
def estudiar(self):
print("estudiar")
def __init__(self):
pass
class preparatoria(estudiante):
#atríbutos
uniforme=2
... |
# Introduction to OOP using python
class Robot:
cost = 0
def __init__(self, name, color, weight): # Class Constructor, each instantiation will have its own values
self.name = name
self.color = color
self.weight = weight
def IntroduceSelf(self):
print("My name is " ... |
"""
Problem Statement: WAP to make a Windows App which can calculate
BMI (Body Mass Index) when provided with height
in centimeters and Weight in Kgs. Refer the
Image below for sample design.
Category BMI range - kg/m2
... |
"""
Problem Statement: WAP to make a Faculty class with properties name, department and subjects.
also add a method to return all the subjects taken by the faculty in a
comma seperated format. Now create a new class Hod which should extend the Faculty class
... |
"""
Problem Statement: WAP to find the second largest number.
Author: Prof. Shiburaj
INPUT:
2 3 4 2 1 5 6 4 7 8
OUTPUT:
7
"""
a = sorted(list(set(map(int,input().split()))))
print(a[-2]) |
"""
Problem Statement: WAP to print following pattern.
Author: Prof. Shiburaj
INPUT:
5
OUTPUT:
*
**
***
****
*****
"""
n = int(input())
for i in range(1,n+1):
print(f"{'*'*i:>{n}}") |
"""" Advent of Code 2016 - Day 3 - Squares with Three Sides """
def is_valid_triangle(a, b, c):
if a + b > c and a + c > b and c + b > a:
return True
return False
def main():
with open('input3.txt', 'r') as fh:
triangles = fh.readlines()
valid = 0
for l in triangles:
a,... |
class Direction(object):
north = 1
west = 2
east= 3
south = 4
def main():
currentPos = (0,0)
currentDir = Direction.north
inputfile = open("input")
inputdata = inputfile.read()
inputfile.close()
instructions = []
visited = dict()
splitdata = inputdata.split(", ")
... |
import sys
from typing import Type
def main(intxt):
try:
intxt = str(intxt)
except TypeError:
print("Text should be a string")
return(sys.exit(1))
letterno = float(letters(intxt))
wordsno = float(words(intxt))
sentenceno = float(sentences(intxt))
avgl... |
# pythonds - Programming Exercises - (#4)
# Based on https://runestone.academy/runestone/books/published/pythonds/AlgorithmAnalysis/Exercises.html
# Given a list of numbers in random order, write an algorithm that works in O(nlog(n)) to find the kth smallest number in the list
def findKthSmallestNumber(listOfNumber, k... |
import datetime
import calendar
import time
from customer import Customer
from hotel import Hotel
import operator
class HotelReservation:
booked_room_details = {}
def store_hotel_details(self, hotelsDetails):
hotels_details = {}
for hotelDetails in hotelsDetails:
hotelName = hote... |
l=list(map(int,input().split()))
n1=l[0]
n2=l[1]
n3=l[2]
if n1>n2 and n1>n3:
print(n1)
elif n2>n3:
print(n2)
else:
print(n3)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.