text
stringlengths 37
1.41M
|
---|
import turtle
def circle(t):
t.circle(100)
t.forward(10)
def main():
t = turtle.Pen()
for i in range(int(input())):
circle(t)
if __name__ == "__main__":
main()
|
# author :: HimelSaha
text = input("Text: ") # input text from user
letterCount = 0
spaceCount = 0
sentenceCount = 0
for i in range(0, len(text)):
if (text[i] == '.' or text[i] == '!' or text[i] == '?'): # if iteration encounters these characters, increase sentence counter by 1
sentenceCount += 1
elif (text[i] >= 'A' and text[i] <= 'Z'): # if iteration encounters these characters, increase letter counter by 1
letterCount += 1
elif (text[i] >= 'a' and text[i] <= 'z'): # if iteration encounters these characters, increase letter counter by 1
letterCount += 1
elif (text[i] == ' '): # if iteration encounters these characters, increase space counter by 1
spaceCount += 1
else: # otherwise skip iteration
continue
wordCount = spaceCount + 1 # wordCount is 1 more than space count
first = (100 * (letterCount / wordCount)) # the average number of letters per 100 words in the input text
second = (100 * (sentenceCount / wordCount)) # the average number of sentences per 100 words in the input text
index = round((0.0588 * first) - (0.296 * second) - 15.8) # calculated readability
if (index >= 16):
print("Grade 16+\n")
elif (index < 1):
print("Before Grade 1\n")
else:
print("Grade", index) |
import argparse
import re
from math import sqrt, floor
indexes = ["", "6", "7", "9", "10", "11", "12", "13", "14", "15", "16",
"17", "18","22", "25"]
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
def syllable_count(word):
word = word.strip(",.!?;:").lower()
n_syllables = 0
if word[-1] == "e":
word = word[:-1]
previous_letter = None
for i, letter in enumerate(word):
if letter in vowels and (i == 0 or previous_letter not in vowels):
n_syllables += 1
previous_letter = letter
if n_syllables < 1:
n_syllables = 1
return n_syllables
parser = argparse.ArgumentParser(description="This program prints Readability index")
parser.add_argument("--infile", "--infile", help="Pass a file which contains text")
parser.add_argument("--words", "--words", help="Pass a file which contains difficult words")
args = parser.parse_args()
file_name = args.infile
text = ""
with open(file_name) as f:
for line in f:
text += line
with open(args.words) as d:
difficult_words = d.read().split()
print("The text is:")
print(text)
characters = sum(1 for c in line if c not in ('\n', ' ', '\t'))
sentences = re.split('[!.?]', text)
num_of_sent = 0
words = 0
syllable = 0
poly = 0
difficult_word = 0
for sentence in sentences:
if sentence:
words += len(sentence.split())
num_of_sent += 1
for w in sentence.split():
if w.strip(" ,.?!:;)(").lower() not in difficult_words:
difficult_word += 1
c = syllable_count(w.strip(",.!:;?"))
if c > 2:
poly += 1
syllable += c
ari_score = 4.71 * (characters / words) + 0.5 * (words / num_of_sent) - 21.43
fk_score = 0.39 * (words / num_of_sent) + 11.8 * (syllable / words) - 15.59
smog_score = 1.043 * sqrt((poly * 30) / num_of_sent) + 3.1291
colman_score = (0.0588 * ((characters / words) * 100)) - (0.296 * ((num_of_sent / words) * 100)) - 15.8
pb_score = 0.1579 * (difficult_word / words) * 100 + 0.0496 * (words / num_of_sent)
if (difficult_word / words) * 100 > 5:
pb_score += 3.6365
print("Words:", words)
print("Difficult words:", difficult_word)
print("Sentences:", num_of_sent)
print("Characters:", characters)
print("Syllables:", syllable)
print("Polysyllables:", poly)
choice = input("Enter the score you want to calculate (ARI, FK, SMOG, CL, PB, all): ")
if choice == "ARI" or choice == "all":
age_ari = indexes[min(round(ari_score), 14)]
print("\nAutomated Readability Index:", round(ari_score, 2),
f"(about {age_ari}-year-olds)")
if choice == "FK" or choice == "all":
age_fk = indexes[min(round(fk_score), 14)]
print("Flesch–Kincaid readability Index:", round(fk_score, 2),
f"(about {age_fk}-year-olds)")
if choice == "SMOG" or choice == "all":
age_sm = indexes[min(round(smog_score), 14)]
print("Simple Measure of Gobbledygook:", round(smog_score, 2),
f"(about {age_sm}-year-olds)")
if choice == "CL" or choice == "all":
age_cl = indexes[min(round(colman_score), 14)]
print("Coleman–Liau index:", round(colman_score, 2),
f"(about {age_cl}-year-olds)")
if choice == "PB" or choice == "all":
year = 0
score = round(pb_score, 1)
if score <= 4.9:
year = 10
elif score < 6:
year = 12
elif score < 7:
year = 14
elif score < 8:
year = 16
elif score < 9:
year = 18
elif score < 10:
year = 24
else:
year = 25
print("Probability-based score:", round(pb_score, 2), f"(about {year}-year-olds)")
print("This text should be understood in average by",
(int(age_ari) + int(age_fk) + int(age_cl) + int(age_sm) + year) / 5, "year olds.")
|
import sqlite3
# SQLite DB 연결
conn = sqlite3.connect("test.db")
# Connection 으로부터 Cursor 생성
cur = conn.cursor()
# SQL 쿼리 실행
cur.execute("select * from magnet_list order by id")
# 데이타 Fetch
rows = cur.fetchall()
for row in rows:
print(row)
# Connection 닫기
conn.close()
|
#!/usr/bin/python
#working with methods/functions in python relating to method Str()...
#string-str-function.py
"""
the str() function converts the non-string values into string values
str(2) will resture "2"
"""
"""Declare and assign your variable on line 4,
then call your method on line 5!"""
pi = 3.14
pi_str = str(pi)
print "converted into text value of pi", pi_str
print str(pi)
print "\n This computer program was developed by Tom"
|
#!/usr/bin/python
#Using the String Formating2 in python language...
# NOT using the default concatenating... use % to replace the strings and concat 'em
string_1 = "ABCDEF"
string_2 = "XYZ"
print "Greetings %s, %s is a Farzi company" % ( string_1, string_2 )
|
import os
import sys
import re
#This script must be run as root! It validate the MAC address format
def check_privilege():
if os.geteuid()!= 0:
sys.exit('This script must be run as root!')
else:
print("You have root privileges. You can run the script! ")
Search_mac = []
def validate_mac(mac):
try:
valid_mac = re.match("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", mac.lower()).group()
if (bool(valid_mac)):
print("MAC Address : {} ".format(valid_mac))
print("Valid MAC address!!")
return Search_mac.append(valid_mac)
except:
print("MAC: {}".format(mac))
print("Incorrectly formatted MAC address. Please check the address")
check_privilege()
mac_list = input("Please enter mac address: ")
for item in mac_list.split(","):
validate_mac(item)
for mac in Search_mac:
print(mac + " added in valid mac list")
|
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
del new_class[5]
print(new_class)
# Code ends here
# --------------
# Code starts here
courses = {'Math': 65, 'English': 70 , 'History' : 80, 'French': 70, 'Science':60}
total = sum(courses.values())
print(total)
percentage = (total * 100)/500
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics = {'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50,
'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75}
topper = max(mathematics,key = mathematics.get)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
first_name = topper.split()[0]
last_name = topper.split()[1]
full_name = last_name +' ' + first_name
certificate_name = full_name.upper()
print(certificate_name)
# Code ends here
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 09:08:35 2020
@author: LG
"""
import sqlite3
dbpath = 'chinook.db'
#연결
conn = sqlite3.connect(dbpath)
#커서
cur = conn.cursor()
# SQL 문
strSQL = 'SELECT * FROM employees'
#실행
cur.execute(strSQL)
item_list = cur.fetchall()
# fetch 가져오다
for it in item_list:
print(it)
print(item_list[0])
print(item_list[0][1]) |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 13:24:00 2020
@author: LG
"""
# by reference
def my_function(input_arg):
print('Value received: ', input_arg, 'id: ', id(input_arg))
input_arg *= 10
print('Value multipied: ', input_arg, 'id: ', id(input_arg))
x = 10
print('Value before being passed: ', x, 'id: ', id(x))
my_function(x)
print('Value after being passed: ', x, 'id: ', id(x))
###############################################################
# global variable
def say_hello():
# global user_name
user_name = 'Steve'
print("Changed name: ", user_name)
return
user_name = 'John'
print("user name before called = ", user_name)
say_hello()
print("user name after called = ", user_name)
###############################################################
|
# [실습 7] 주가 조회하기 - Timer
from threading import Timer
from time import sleep
import bs4
from urllib.request import urlopen
import datetime as dt
# Timer 출처
# https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
def getCurrentStockPrice(idx_stock):
naver_index = 'https://finance.naver.com/item/sise.nhn?code=' + idx_stock
source = urlopen(naver_index).read()
source = bs4.BeautifulSoup(source, 'lxml')
curPrice1 = source.find_all('em', class_='no_up')[0]
# print(curPrice1)
curPrice2 = curPrice1.find_all('span')[0].text
# print(curPrice2)
# curPrice = int(curPrice2.replace(',',''))
curPrice = curPrice2.replace(',','')
tmpTime = dt.datetime.now()
# curTime = str(tmpTime.year) + '-' + str(tmpTime.month) + '-' + str(tmpTime.day) \
# + ' ' \
# + str(tmpTime.hour) + ':' + str(tmpTime.minute) + ':' + str(tmpTime.second)
curTime = tmpTime.strftime('%Y-%m-%d %H:%M:%S')
print(idx_stock, ',', curTime, ',', curPrice)
return curPrice
print('Starting...')
idx_stock = '004170'
rt = RepeatedTimer(1, getCurrentStockPrice, idx_stock)
try:
sleep(10)
finally:
rt.stop()
|
# if 구문
price = int(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
amt = price * qty
if amt > 1000:
print('10% discount is applicable')
discount = amt * 10 / 100
amt = amt - discount
print("Amount payable: ", amt)
|
# Dictionary vs. Set
# Dictionary
capitals = {"USA":"Washington", "France":"Paris", "India":"New Delhi"}
print(capitals.get('France'))
print(capitals.get('Paris'))
capitals['USA'] = 'Washington, D.C.'
print(capitals.get('USA'))
del capitals['India']
for key in capitals:
print("Key = " + key + ", Value = " + capitals[key])
print(capitals.keys())
print(capitals.values())
capitals.update({"India":"New Delhi"})
for key in capitals:
print("Key = " + key + ", Value = " + capitals[key])
dict1 = {"Fruit":["Mango","Banana"], "Colour":["Blue", "Red"]}
print(dict1.get('Fruit')) # ['Mango', 'Banana']
print(dict1.get('Fruit')[0]) # Mango
print(dict1.get('Fruit')[1]) # Banana
# Set
setStudent = {1, "Bill", 75.50}
print(setStudent)
setNumbers = {1, 2, 2, 3, 4, 4, 5, 5}
print(setNumbers)
a = 3 > 5
if a:
print('True')
else:
print('False')
|
# Time Complexity : O(logn)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : Yes, was trying to do using recursion. But couldn't device a perfect base case
# Your code here along with comments explaining your approach
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
# Binary search to get left most index
def binarySearchLeft(nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left) // 2
# Move till you find first target
if target > nums[mid]:
left = mid + 1
# Movement of right index is not an issue
else:
right = mid - 1
return left
def binarySearchRight(nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left) // 2
# Move left till you cross last target
if target >= nums[mid]:
left = mid + 1
# Move right once to capture the last target and exit while loop
else:
right = mid - 1
return right
# Initialise left and right index from two methods
left, right = binarySearchLeft(nums, target), binarySearchRight(nums, target)
return (left, right) if left <= right else [-1, -1]
|
# -*- coding: utf-8 -*-
'''
Created on 2016年4月26日
@author: todoit
'''
#BubbleSort
#冒泡排序,生成器方法
def bubbleSort(data):
size = len(data)
for i in range(size):
for j in range(1,size-i):
if data[j-1] > data[j]:
data[j-1],data[j]=data[j],data[j-1]
#print(data)
#每一次比较都返回数据
#如果把yield放到第二个循环中,就是老师的slow方法,目前是老师的fast方法
yield data
if __name__=="__main__":
param = [17,9,10,8,7,6,4]
data = bubbleSort(param)
i = 10
while i>=0:
print(next(data))
i-=1
|
# -*- coding: utf-8 -*-
'''
Created on 2016年4月22日
@author: todoit
'''
'''
思路: 两个共用一条边的正三角形都围绕其中一个三角形的中心旋转
'''
import matplotlib.pyplot as plt
import numpy as np
#对一个点进行旋转
#输入参数,a是转换前的点的坐标,p是围绕旋转的点,angle是旋转的度数
def rotatePoint(a, p, angle):
#计算出该点到某一点的距离,即半径
print("旋转前的点: ",a)
#旋转后点的坐标
b0 = p[0] + (a[0]-p[0]) * np.cos(angle * np.pi/180) - (a[1] - p[1]) * np.sin(angle * np.pi/180)
b1 = p[1] + (a[0]-p[0]) * np.sin(angle * np.pi/180) + (a[1] - p[1]) * np.cos(angle * np.pi/180)
b = (b0, b1)
print("旋转后的点: ",b)
return b
#对一个曲线图形(用两个list表示)进行旋转,返回旋转后的两个list,
#方法为对曲线中的每个点进行旋转
#输入lines是两个list,两个list的长度必须相同, angle是旋转度数
def rotateLines(lines, p, angle):
size = len(lines[0])
#判断两个list长度是否相等
assert size == len(lines[1]), "两个list长度不同!"
m,n = [None] * size, [None] * size #初始化输出结果
for i in range(0, size):
print(i)
m[i],n[i] = rotatePoint((lines[0][i],lines[1][i]), p , angle)
return m,n
def gen_circle_point(num):
#从上面三角形旋转得到的灵感,定义了两个正三角形,共用一条边。
#两个三角形都围绕其中一个三角形的中心旋转
#最后去掉外部三角形的底边,去掉内部三角形中除公用边外的两个边
#内部正三角形
x = [-1,1]
y = [0,0]
#内部三角形的中心为,需要围绕该点旋转
p = (0, np.tan(30*np.pi/180))
#外部正三角形
x1 = [-1,0,1]
y1 = [0,-3**0.5,0]
plt.xticks([-3,-2,-1,0,1,2,3])
plt.yticks([-3,-2,-1,0,1,2,3])
plt.ylim([-3,3])
plt.xlim([-3,3])
#plt.plot(x1,y1)
#把圆分成num+1等分,,每个角度的度数为360%(num+1),围绕点p进行旋转
#返回的内外部点的list
result_list = []
angle = 0
while angle <= 120:
result_list.append([rotateLines([x,y], p, angle),rotateLines([x1,y1], p, angle)])
result_list.append([rotateLines([x,y], p, angle+120),rotateLines([x1,y1], p, angle+120)])#加上120度可以和相对应的三角形连起来,成为直线
result_list.append([rotateLines([x,y], p, angle+240),rotateLines([x1,y1], p, angle+240)])#加上240度可以和相对应的三角形连起来,成为直线
angle += 360/(num)
return result_list
if __name__ == '__main__':
N=15
fig = plt.figure()
for p1,p2 in gen_circle_point(N-1):
plt.plot(p1[0],p1[1],'b.')
plt.plot(p2[0],p2[1],'r')
plt.show()
|
# Python script to convert images to Pencil like Sketches
import cv2
def sketchit(path):
image=cv2.imread(path)
grey_img=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
invert=cv2.bitwise_not(grey_img)
blur=cv2.GaussianBlur(invert,(21,21),0)
invertedblur=cv2.bitwise_not(blur)
sketch=cv2.divide(grey_img , invertedblur,scale=256.0)
cv2.imwrite('sketch.png',sketch)
path=input("Enter Path of Image: ")
sketchit(path) |
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n=len(matrix)
for i in range(n):
for j in range(0,i):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for ele in matrix:
ele.reverse()
|
class Solution:
def calculate(self, s: str) -> int:
if not s:
return 0
stack, curr_num, operator = [], 0, "+"
all_operators = {"+", "-", "*", "/"}
nums = set(str(x) for x in range(10))
for indx in range(len(s)):
char = s[indx]
if char in nums:
curr_num = curr_num * 10 + int(char)
if char in all_operators or indx == len(s) - 1:
if operator == "+":
stack.append(curr_num)
elif operator == "-":
stack.append(-curr_num)
elif operator == "*":
stack[-1] *= curr_num
elif operator == "/":
stack[-1] = int(stack[-1] / curr_num)
curr_num = 0
operator = char
return sum(stack)
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#2.>leap year
y=eval(input('enter the year'))
if(y%100==0):
if(y%400==0):
print('It is a leap year')
else:
print('it is not a leap year')
else:
if(y%4==0):
print('It is a leap year')
else:
print('it is not a leap year')
# In[2]:
#1.>even odd
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")
# In[1]:
#3.>vowel or consonants
n=str(input("enter any alphabet:"))
if(n=='a'or n=='e'or n=='i'or n=='i'or n=='u'):
print("vowels")
else:
print("consonats:"+n)
# In[3]:
#5.>factorial of an no
n=int(input("enter any no.:"))
fact=1
if(n<0):
print("factorial not possible")
elif(n==0):
print("factorial of 0 is 1")
else:
for i in range(1,n+1):
fact=fact*i
print("factorial of",n,"is",fact)
# In[5]:
#6.>print this pattern
print(' '+"*")
print(' '+"*"+' '+"*")
print(' '+"*"+' '+"*")
print(' '+"*"+"*"+' '+"*"+''+"*")
# In[6]:
#8.>prime no.
n=int(input("enter any no.:"))
if n>1:
for i in range (2,n):
if(n%i)==0:
print(n,"not a prime no.")
break
else:
print("it is a prime no")
# In[7]:
#9.>calculator
n1=eval(input('enter the first no.'))
n2=eval(input('enter the second no.'))
print('select a opertor (+,-,*,/,//,%,**)')
op=input('enter the above operator')
if(op=='+'):
print(n1+n2)
elif(op=='-'):
print(n1 - n2)
elif(op=='*'):
print(n1*n2)
elif(op=='/'):
print(n1/ n2)
elif(op=='//'):
print(n1 //n2)
elif(op=='%'):
print(n1 %n2)
elif(op=='**'):
print(n1 **n2)
else:
print('enter a valid operator')
# In[8]:
#4.>smallest of two no.s
n1=eval(input('enter the first no.'))
n2=eval(input('enter the second no.'))
if(n1<n2):
print("n1 is smallest")
else:
print("n2 is smallest")
# In[ ]:
|
import numpy as np
#Recursive Finder Class
class RecursiveFinder:
def find(self, arr, key, low, high):
if low > high:
return False
else:
mid = (low + high) // 2
if key == arr[mid]:
return True
elif key < arr[mid]:
return RecursiveFinder.find(self, arr, key, low, mid - 1)
else:
return RecursiveFinder.find(self, arr, key, mid + 1, high)
|
from classes.passenger_vehicle_class import PassengerVehicle
class Bicycle(PassengerVehicle):
vehicle_type = 'bicycle'
def __init__(self, id, hire_date, return_date, max_num_of_passengers, classification):
super().__init__(id, hire_date, return_date, max_num_of_passengers)
self.classification = classification
list_of_classifications = ['road', 'mountain', 'folding', 'electric']
#Validating classification:
if classification not in list_of_classifications:
raise ValueError('Bicycle classification not valid') |
import pdb
def sort_list(mylist):
#this function actally change the mylist to mysortedlist, the original mylist doesn't eist anymore
mysortedlist = []
for i in range (0, len(mylist)):
for j in range (1+i, len(mylist)):
max = mylist[i]
if mylist[j] > max:
max = mylist[j]
mylist[j] = mylist[i]
mylist[i] = max
mysortedlist.append(mylist[i])
#print(mylist)
#print(mysortedlist)
#mylist and mysortedlist are the same
return mysortedlist
mylist = [1,4,6,8,10,100,56,78,90,43,33,20,11,5,6]
print(mylist)
my_sorted_mylist = list(sort_list(mylist)) #make a copy
my_sorted_mylist_2 = sort_list(mylist) #asign list referent
print(my_sorted_mylist)
print(my_sorted_mylist_2) |
# def uniq(alist):
# unique_list = []
# dup_list =[]
# for x in alist:
# if x not in unique_list:
# unique_list.append(x)
# else:
# dup_list.append(x)
# print unique_list
# print dup_list
# return
def uniq_2(alist):
a=set(alist)
aa=str(a)
aaa=aa.replace ('set([','')
aaaa=aaa.replace('])','')
print a
#print aa
#print aaa
print aaaa
#print all except the duplicate
b=set(x for x in alist if alist.count(x) >1)
bb=str(b)
bbb=bb.replace ('set([','')
bbbb=bbb.replace('])','')
print b
print bbbb
#print the duplicates
c=set(x for x in alist if alist.count(x) ==1)
cc=str(c)
ccc=cc.replace ('set([','')
cccc=ccc.replace('])','')
print c
print cccc
#print not including the elements that are duplicated
return
mylist=[1,1,2,3,5,6,7,8,9,10,7,6]
#uniq(mylist)
uniq_2(mylist)
|
def split_sentence(sentence):
alist=[]
asentence=''
bsentence=''
alist=sentence.split()
asentence=''.join(alist)
bsentence=''.join(sentence).split()
#alist=sentence.split('',1)
return alist, asentence, bsentence
my_sentence='Boston is a nice city'
print split_sentence(my_sentence) |
def sort(mylist):
less = []
equal = []
greater = []
if len(mylist) > 1:
pivot = mylist[0]
for x in mylist:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
greater.append(x)
# Don't forget to return something!
return sort(less)+equal+sort(greater) # Just use the + operator to join lists
# Note that you want equal ^^^^^ not pivot
else: # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the list.
return mylist
mylist = [12,4,5,6,7,3,1,15, 26,37,54,8,9]
x = sort(mylist)
print x
|
"""
In this exercise, you'll be playing around with the sys module,
which allows you to access many system specific variables and
methods, and the os module, which gives you access to lower-
level operating system functionality.
"""
import sys
# See docs for the sys module: https://docs.python.org/3.7/library/sys.html
# Print out the command line arguments in sys.argv, one per line:
for index, arg in enumerate(sys.argv):
print(f"{index}: {arg}")
# Print out the OS platform you're using:
print(f"My system platform is {sys.platform}")
# Print out the version of Python you're using:
print(f"My Python interpreter is version {sys.version_info[0]}." \
f"{sys.version_info[1]}.{sys.version_info[2]}")
import os
# See the docs for the OS module: https://docs.python.org/3.7/library/os.html
# Print the current process ID
print(f"The current process ID is {os.getpid()}")
# Print the current working directory (cwd):
print(f"The current working directorh is {os.getcwd()}")
# Print out your machine's login name
print(f"The current user is {os.getlogin()}")
import getpass
print(f"Another way to get the current user: {getpass.getuser()}")
|
# generate the monthly oustanding mortgage
# input: annual interest rate, a floating-point percentage
rate = 0.05
# input: monthly payment, a positive integer in a currency
payment = 200
# input/output: morgage, positive number, same currency
mortgage = 1000
print('Outstanding mortgage:', mortgage)
while mortgage > 0:
interest = mortgage * rate / 12
mortgage = mortgage + interest - payment
print('Outstanding mortgage:', mortgage) |
from food import Pizza, Gaseosa, Agua, Plato
from abc import ABC, abstractmethod
import random
# Completar las clases donde corresponda #
class Personalidad(ABC):
def reaccionar(self, plato):
# Rellenar aquí
pizza=plato.pizza
bebestible=plato.bebestible
if (pizza.calidad + bebestible.calidad)/2 >= 50:
self.feliz()
else:
self.molesto()
@abstractmethod
def feliz(self):
pass
@abstractmethod
def molesto(self):
pass
class Persona:
def __init__(self, nombre):
self.nombre = nombre
# Rellenar Aquí con las nuevas clases #
class Empatico:
def __init__(self):
pass
def feliz(self):
print("Cosa ma wena, voy a poner puros 7")
def molesto(self):
print("No me gustó, pondré puros 5")
class Exigente:
def __init__(self,nombre):
pass
def feliz(self):
print("Esta merienda está muy buena, los alumnos se merecen el 4")
def molesto(self):
print("Que bruto, póngale 0")
class Chef(Persona):
def __init__(self,nombre):
super().__init__(self,nombre)
def ingredientes(self):
lista_ing = ["pepperoni", "piña", "cebolla", "tomate", "jamón", "pollo"]
ing_1 = random.choice(lista_ing)
ing_2 = random.choice(lista_ing)
ing_3 = random.choice(lista_ing)
ingredientes = [ing_1,ing_2,ing_3]
return ingredientes
def Preparar_Plato(self,Plato):
pass
class Ayudante(Persona):
def __init__(self,nombre,personalidad):
super().__init__(self, nombre)
self._personalidad=personalidad |
# Write a list or lists.
# iterate through the list using for loop.
taco_toppings = ['meat', 'cheese', 'lettuce', 'salsa']
for topping in taco_toppings:
print 'I am hungry and {} sounds good on my taco'.format(taco_toppings[0])
|
pi = 3.14
print type(pi)
print str(pi)
text = 'The value of pi is %d' % pi
print text
text = 'The value of pi is %r' % pi
print text
#below comment will fail
text = 'The value of pi is ' + pi
text = 'The value of pi is ' + str(pi)
print text
input_value = raw-input("Enter a radius: ")
radius = float(input_value)
area = 3.14159 * radius **2
print 'The area of a circle with radius is %r' % area
|
#Branch 1 removing my_ from variable names.
name = 'Amigo'
age = 30
height = 170 #Cm
height_in_inches = height*0.393701
weight = 88 #KGs
weight_in_pounds = weight*2.20462
eyes = 'Brown'
teeth = 'White'
hair = 'Black'
print ("Let's talk about %s." % name)
print ("He's %r centimeters tall which is %f inches" % (height,height_in_inches))
print ("He's %d kilos weight which is %f pounds." % (weight,weight_in_pounds))
print ("Actually that's not too heavy.")
print ("He's got %s eyes and %s colored hair." % (eyes,hair))
print ("He's got %s teeth." % teeth)
#Tricky part
print ("If i add %d,%d,%d, I'd get %d" % (age,height,weight,age+height+weight))
|
import hashlib
type_of_hash = str(input('MD5 or SHA1, what would you like to hash?: '))
password_list_path = str(input('Enter the path to your password list: '))
hash_to_decrypt = str(input('Enter the hash value: '))
with open(password_list_path, 'r') as file:
for line in file.readlines():
if type_of_hash == 'md5' or 'MD5':
hash_object = hashlib.md5(line.strip().encode())
hashed_word = hash_object.hexdigest()
if hashed_word == hash_to_decrypt:
print('Found password: ' + line.strip())
exit(0)
if type_of_hash == 'sha1' or 'SHA1':
hash_object = hashlib.sha1(line.strip().encode())
hashed_word = hash_object.hexdigest()
if hashed_word == hash_to_decrypt:
print('Found password: ' + line.strip())
exit(0)
print('404, Password not found!')
|
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # int datatype
>>> num = 5
>>> type(num)
<class 'int'>
>>> #float datatype
>>> num = 6.5
>>> type(num)
<class 'float'>
>>> #string datatype
>>> num = "conversions"
>>> type(num)
<class 'str'>
>>> #bool datatype
>>> num = 2+3
>>> bool(num)
True
>>> #complex datatype
>>> a=6
>>> b=3
>>> c=complex(a,b)
>>> print(c)
(6+3j)
>>> num=6+3j
>>> type(num)
<class 'complex'>
>>>
>>> #int to float
>>> a=7
>>> float(a)
7.0
>>> #float toint
>>> a=2.34
>>> int(a)
2
>>> #string with values
>>> a=str("py")
>>> print(a)
py
>>> |
# a = [1, 2, 3, 4]
# for x in a:
# if x == 2:
# # 强行终止循环
# # break
# # 跳过此循环
# continue
# print(x)
# print("=========")
# # range(0,10,2):表示从0开始到10结束,中间间隔为2递增数列
# # range(10,0,-2):表示从10开始到0结尾的数列中,中间间隔为2的等差数列
# for x in range(0, 10, 2):
# print(x, end='|')
# for y in range(10, 0, -2):
# print(y, end='|')
# print('========')
# a = [1, 2, 3, 5, 9, 678]
# # 遍历数组的等差数列
# for x in range(2, len(a), 2):
# print(a[x], end=' | ')
# b = a[2:len(a):2]
# print(b)
c = 20 |
# ------- coding:utf-8 --------
'''
题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head_node):
prev_node = None
current_node = head_node
next_node = None
reverse_head_node = None
while current_node != None:
next_node = current_node.next
if next_node == None:
reverse_head_node = current_node
current_node.next = prev_node
prev_node = current_node
current_node = next_node
return reverse_head_node
if __name__ == '__main__':
s = Solution()
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
head = s.reverseList(a)
print head.val
head = head.next
print head.val
head = head.next
print head.val
head = head.next
print head.val
head = head.next
print head.val
|
# ------ coding:utf-8 ----------
'''
题目:输入两颗二叉树A和B,判断B是不是A的子结构
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
'''
书上的思路:遍历father,如果father的根结点和child的根结点一样的话,就调用doesTree1haveTree2判断接下来的结构是否一样
如果father的根结点不与child的根结点一样的时候,就遍历father
'''
def hasSubTree(self, father_root_node, child_root_node):
result = False
if father_root_node != None and child_root_node != None:
if father_root_node.val == child_root_node.val:
result = self.doesTree1haveTree2(father_root_node, child_root_node)
if not result:
result = self.hasSubTree(father_root_node.left, child_root_node)
if not result:
result = self.hasSubTree(father_root_node.right, child_root_node)
return result
def doesTree1haveTree2(self, father_root_node, child_root_node):
# 这里一定要先判断child是否为空,再判断father
if child_root_node == None:
return True
if father_root_node == None:
return False
if father_root_node.val != child_root_node.val:
return False
return self.doesTree1haveTree2(father_root_node.left, child_root_node.left) and \
self.doesTree1haveTree2(father_root_node.right, child_root_node.right)
if __name__ == '__main__':
s = Solution()
a = TreeNode(8)
b1 = TreeNode(8)
b2 = TreeNode(7)
c1 = TreeNode(9)
c2 = TreeNode(2)
d1 = TreeNode(4)
d2 = TreeNode(7)
a.left = b1
a.right = b2
b1.left = c1
b1.right = c2
c2.left = d1
c2.right = d2
p = TreeNode(8)
p.left = TreeNode(9)
p.right = TreeNode(2)
print s.hasSubTree(a, p)
|
# --------- coding:utf-8 ---------
'''
题目:实现函数power(base, exponent),求bese的exponent次方
不得使用库函数,不需要考虑大数问题
'''
class Solution:
'''
注意:
区分base是否为1
区分exponent的正负情况
'''
def power(self, base, exponent):
if base == 0:
return 0
else:
if exponent == 0:
return 1
elif exponent > 0:
for i in range(exponent-1):
base *= base
return base
else:
base = 1.0/base
for i in range(-exponent-1):
base *= base
return base
if __name__ == '__main__':
s = Solution()
print s.power(2, 3), s.power(2,-2), s.power(5,0), s.power(0.0, -5)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 9 16:58:04 2017
@author: Administrator
"""
import random
def buildLargeMenu(numItems, maxVal, maxCost):
items = []
for i in range(numItems):
items.append(Food(str(i),
random.randint(1, maxVal),
random.randint(1,maxCost)))
return items
for numItems in range(5,46,5):
items = buildLargeMenu(numItems, 90, 250)
testMaxVal |
from time import sleep
import RPi.GPIO as GPIO
from gpiozero import Motor,RGBLED, Button, LED
def on():
global sensorOn
global sensorOff
global state
global speed
while True:
sensorOn = GPIO.input(sensorPinon)
sensorOff = GPIO.input(sensorPinoff)
if sensorOn == GPIO.LOW:
motor.forward(speed)
state = "on"
print("ON")
if sensorOff == GPIO.LOW:
motor.stop()
state = "off"
print("OFF")
if state == "off":
mainled.off()
mainled.red = 1
motor.stop()
sleep(0.5)
elif state == "on":
mainled.off()
mainled.green = 1
sleep(0.5)
def speedcheck():
global speed
if button.is_pressed:
if speed == 0.5:
speed = 1
elif speed == 1:
speed = 0.5
try:
sensorPinon = 14
sensorPinoff = 26
motor = Motor(20,21)
mainled = RGBLED(2,3,4)
#button = Button()
speed = 0.6
state = "off"
GPIO.setup(sensorPinon, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(sensorPinoff, GPIO.IN, pull_up_down=GPIO.PUD_UP)
on()
finally:
mainled.red = 0
mainled.green = 0
mainled.blue = 0
mainled.off()
GPIO.cleanup()
|
scores={}
points={0:0,1:15,2:30,3:40,4:"40+1",5:"40+1+1"}
setWinner=[]
setScore={"set1":[],"set2":[],"set3":[]}
gameWinner=[]
#Function to find the winner of the match.
def calculate_matchwinner(player1,player2):
if setWinner.count(player1) > setWinner.count(player2):
return player1
elif setWinner.count(player1) < setWinner.count(player2):
return player2
#Function to find the winner of a single set.
def calculate_set_winner(player1,player2):
if gameWinner.count(player1) >= 6 and (gameWinner.count(player1)-gameWinner.count(player2)) >= 2:
return player1
elif gameWinner.count(player2) >= 6 and (gameWinner.count(player2)-gameWinner.count(player1)) >= 2:
return player2
else:
return ""
#Function to find the winner of each game in the set.
def calculate_game_winner(player1,player2):
print(scores[player1],scores[player2])
if scores[player1] == 4 and scores[player2] == 4:
scores[player1]=3
scores[player2]=3
if scores[player1] >=4 and (scores[player1]-scores[player2]) >= 2:
return player1
elif scores[player2] >=4 and (scores[player2]-scores[player1]) >= 2:
return player2
else:
return ""
#Obtaining input from user
player1=input("Enter the name of player 1:")
player2=input("Enter the name of player 2:")
message="Who starts the first serve?(1 for {}, 2 for {})".format(player1,player2)
scores[player1]=0
scores[player2]=0
firstServe=input(message)
while True:
text = input("Waiting for the game to start(Hit Enter)")
if text == "":
i=1
message="Winner of next point(1 for {}, 2 for {})".format(player1,player2)
while i<4:
point=input(message)
try:
if int(point) == 1:
score=scores[player1]+1
scores[player1]=score
elif int(point) == 2:
score=scores[player2]+1
scores[player2]=score
except ValueError:
print("Enter 1 or 2 as option")
continue
if scores[player1] >= 4 or scores[player2] >= 4:
winner=calculate_game_winner(player1,player2)
if winner != "":
print("Game over")
print("Current Score")
print("-------------------------------------------")
print("Set\t1\t2\t3")
print("-------------------------------------------")
player1score=""
player2score=""
if i == 2:
player1score+="%s\t%s"%(player1,setScore["set1"][0])
player2score+="%s\t%s"%(player2,setScore["set1"][1])
elif i == 3:
player1score+="%s\t%s\t%s"%(player1,setScore["set1"][0],setScore["set2"][0])
player2score+="%s\t%s\t%s"%(player2,setScore["set1"][1],setScore["set2"][0])
if winner == player1:
print(player1score+"\t"+str(gameWinner.count(player1)+1))
print(player2score+"\t"+str(gameWinner.count(player2)))
gameWinner.append(player1)
else:
print(player1score+"\t"+str(gameWinner.count(player1)))
print(player1score+"\t"+str(gameWinner.count(player2)+1))
gameWinner.append(player2)
scores={player1:0,player2:0}
print("Game Score %s-%s"%(str(points[scores[player1]]),str(points[scores[player2]])))
if len(gameWinner) >=6:
swinner=calculate_set_winner(player1,player2)
if swinner != "":
setWinner.append(swinner)
setScore["set"+str(i)]=[gameWinner.count(player1),gameWinner.count(player2)]
gameWinner=[]
i+=1
print("Match over. " + calculate_matchwinner(player1, player2)+" Wins!")
break
else:
print("Press enter to begin the game") |
def parenbuilder(num_pairs):
if num_pairs > 0:
result = []
pairs_doubled = num_pairs * 2
_parenbuilder(pairs_doubled-1, 1, 0, num_pairs, '(', result)
return result
def _parenbuilder(num_pairs, num_open, num_closed, pairs_in, cur_res, result):
#try to open paren
if num_open > pairs_in or num_closed > pairs_in:
return
if num_pairs == 0 and num_closed == num_open:
result.append(cur_res)
return
if num_open <= pairs_in:
_parenbuilder(num_pairs-1, num_open+1, num_closed, pairs_in, cur_res + '(', result)
if num_closed < num_open:
_parenbuilder(num_pairs-1, num_open, num_closed+1, pairs_in, cur_res + ')', result)
if __name__ == '__main__':
print(parenbuilder(2))
print
print(parenbuilder(3))
print
print(parenbuilder(4))
|
import itertools
def floor_puzzle():
floors = bottom, _, _, _, top = [1,2,3,4,5]
orderings = list(itertools.permutations(floors))
result = next((Hopper, Kay, Liskov, Perlis, Ritchie) for
(Hopper, Kay, Liskov, Perlis, Ritchie) in orderings
if Hopper is not top
and Kay is not bottom
and Liskov is not top
and Liskov is not bottom
and Perlis > Kay
and abs(Ritchie - Liskov) > 1
and abs(Liskov - Kay) > 1)
return list(result)
print floor_puzzle()
|
import time
def mergeSort(arr,low,high):
if low < high:
mid = (low + (high-1))//2
mergeSort(arr, low, mid)
mergeSort(arr, mid + 1, high)
merge(arr, low, mid, high)
def merge(arr, l, m, h):
b = [0] * len(arr)
low = l
med = m
count = l - 1
while low <= m and med+1 <= h:
if arr[low] < arr[med+1]:
count += 1
b[count] = arr[low]
low += 1
else:
count += 1
b[count] = arr[med+1]
med += 1
if low <= m:
for i in range(low,m+1):
count +=1
b[count] = arr[i]
elif med+1 <= h:
for i in range(med+1,h+1):
count +=1
b[count] = arr[i]
for i in range(l,h+1):
arr[i] = b[i]
arr = [64, 34, 25, 12, 22, 11, 90]
start_time = time.time()
mergeSort(arr,0,len(arr)-1)
print("%s seconds" % (time.time() - start_time))
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]), |
def Solution(A):
if A is None or len(A) == 0:
return
first_row = False
first_col = False
if A[0][0] == 0:
first_row = True
first_col = True
else:
# for i in range(1,len(A[0])):
# if A[0][i] == 0:
if 0 in A[0]:
first_row = True
# break
for i in range(1,len(A)):
if A[i][0] == 0:
first_col = True
break
for i in range(1,len(A)):
for j in range(1,len(A[0])):
if A[i][j] == 0:
A[i][0] = 0
A[0][j] = 0
for i in range(1,len(A)):
for j in range(1,len(A[0])):
if A[i][0] == 0 or A[0][j] == 0:
A[i][j] = 0
print("A",first_col,first_row)
if first_row:
A[0] = [0]*len(A[0])
if first_col:
for i in range(len(A)):
A[i][0] = 0
return A
A = [[0,1,1,0],[1,1,0,1],[1,1,1,1]]
# A = [[0,0,0],[0,0,1]]
A = [[1,1],[0,0]]
print(Solution(A)) |
def solution(A):
slow = A[0];
fast = A[A[0]];
while (slow != fast):
slow = A[slow];
fast = A[A[fast]];
# print("S",slow)
# print("F",fast)
# print(slow,fast)
fast = 0;
while (slow != fast):
slow = A[slow];
fast = A[fast];
# print("S",slow)
# print("F",fast)
return slow;
A = [1,4,2,5,3,6,7,5]
print(solution(A)) |
import init_music
def initialise(sentence):
sentence = sentence.lower()
song_dict = init_music.init_music()
#print (song_dict)
check_song_name(sentence, song_dict)
def check_song_name(sentence, song_dict):
sentence = sentence.split()
name = sentence[1:]
n = len(name)
flag = True
for song_det in song_dict:
input_name = ""
for i in range(0, n):
if i == 0:
input_name = input_name + str(name[i])
else:
input_name = input_name + " " + str(name[i])
if input_name in song_det:
flag = False
break
if not flag:
break
if not flag:
play_song(input_name, song_det[input_name], song_dict)
def play_song(name, type, song_dict):
if type == 'name':
print('Playing song', name, "......")
exit(0)
else:
print ('Choose song.....\n')
for song in song_dict:
if name in song:
print (song)
exit(0) |
soma = 0
total = 0
while total < 2:
notas = float(input())
if notas >= 0 and notas <= 10:
soma += notas
total += 1
else:
print("nota invalida")
print("media = {:.2f}".format(soma/2))
|
from math import sqrt, pow
test = True
while test:
try:
values = [int(num) for num in input().split()]
x = values[0]
y = values[1]
a = values[2]
b = values[3]
v = values[4]
r1 = values[5]
r2 = values[6]
space = v * 1.5
n = sqrt(pow((x - a), 2) + pow((y - b), 2)) + space
skill = abs(r1 + r2)
if skill >= n:
print('Y')
else:
print('N')
except EOFError:
test = False
|
def limitador(caractere):
total = ''
total += str(caractere)
k = len(total)
if k > 80:
return print("NO")
else:
return print("YES")
n = input()
limitador(n)
|
n = int(input())
while n > 0:
termos = int(input())
if termos % 2 == 0:
soma = n * (1 - 1)
print(soma)
else:
soma = n * (1 - 1) + 1
print(soma)
n -= 1
|
def year_bissexto(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("This is leap year.")
huluculu(year)
buluculu(year)
elif year % 15 == 0:
huluculu(year)
else:
print("This is an ordinary year.")
def huluculu(year):
if year % 15 == 0:
print("This is huluculu festival year.")
def buluculu(year):
if year % 55 == 0:
print("This is bulukulu festival year.")
i = 0
test = True
while test:
try:
if i:
print('')
i = 1
year = int(input())
year_bissexto(year)
except EOFError:
test = False
break
|
distance = int(input())
cont = distance * 2
print("{} minutos".format(cont))
|
from math import pow
test = True
try:
while test:
volume = float(input())
d = float(input())
pi = 3.14
r = d / 2
area = pi * pow(r, 2)
h = volume / area
print("ALTURA = {:.2f}".format(h))
print("AREA = {:.2f}".format(area))
except EOFError:
test = False
|
N = int(input())
if N >= 3600:
hora = N // 3600
mim = (N % 3600) // 60
seg = (N % 3600) % 60
else:
if N < 3600:
hora = 0
mim = N // 60
seg = N % 60
print("{}:{}:{}".format(hora, mim, seg))
|
n = float(input())
if n > 0:
print('+%.4E' % n)
elif n < 0:
print('%.4E' % n)
elif n == 0 and str(n)[0] != '-':
print('+%.4E' % n)
elif n == 0 and str(n)[0] == '-':
print('%.4E' % n)
|
number = float(input())
if number < 0 or number > 100:
print("Fora de intervalo")
else:
if 0 <= number <= 25:
print("Intervalo [0,25]")
elif 25 < number <= 50:
print("Intervalo (25,50]")
elif 50 < number <= 75:
print("Intervalo (50,75]")
elif 75 < number <= 100:
print("Intervalo (75,100]")
|
cont = 0
def food(meal):
global cont
if meal == 1:
return cont
if meal < 1:
return cont
else:
meal /= 2
cont += 1
return food(meal)
n = int(input())
while n > 0:
meal = float(input())
print("{} dias".format(food(meal)))
cont = 0
n -= 1
|
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
#
class Solution:
def merge(self, intervals):
intervals = [[x.start, x.end] for x in intervals]
intervals.sort(key=lambda x: (x[0], x[1]))
#print(intervals)
i = 1
#Len = len(intervals)
while i < len(intervals):
if intervals[i][0] <= intervals[i - 1][1]:
intervals[i][0], intervals[i][1] = intervals[i - 1][0], max(intervals[i][1], intervals[i - 1][1])
intervals.pop(i - 1)
i += 1
else:
i += 1
return intervals
#
# x = Solution()
# a = Interval()
# p
#print(x.merge(list(a)))
a = [1,2,3]
a.remove(1)
print(a) |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 寻找环的第一个节点的方法是:
# 首先假定链表起点到入环的第一个节点A的长度为a【未知】
# 到快慢指针相遇的节点B的长度为(a + b)【这个长度是已知的】。
# 现在我们想知道a的值,注意到快指针p2始终是慢指针p走过长度的2倍,所以慢指针p从B继续走(a + b)又能回到B点
# 如果只走a个长度就能回到节点A
# 所以通过一个指针从头节点出发,每次走一步,同时慢指针从当前位置出发,当相遇时,则是环的第一个节点
slow = fast = head
flag = False
# 若有环则在第一次相遇时停止
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
flag = True
break
# 如果存在环形
if flag:
temp = head
while temp != slow:
slow = slow.next
temp = temp.next
return slow
# 如果不存在环形
else:
return None
|
from math import sqrt
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
else:
temp = 1
i = 2
ans = 2
while i < n:
temp, ans = ans, temp + ans
i += 1
return ans
# fibs = [0, 1]
# i = 2
# while i <= n + 1:
# fibs.append(fibs[i - 1] + fibs[i - 2])
# i += 1
# return fibs[-1]
#"""递归运行太慢"""
#"""本质是Fibonaci数列"""
# if n == 1:
# return 1
# if n == 2:
# return 2
# else:
# return (self.climbStairs(n - 1) + self.climbStairs(n - 2))
x = Solution()
print(x.climbStairs(4))
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, t: TreeNode) -> str:
self.ans = []
self.preOrder(t)
return ''.join(self.ans)
def preOrder(self, root):
if not root:
return
self.ans.append(str(root.val))
if root.left:
self.ans.append('(')
self.preOrder(root.left)
self.ans.append(')')
if root.right:
#如果左子树没有,需要增加一个括号
if not root.left:
self.ans.append('()')
self.ans.append('(')
self.preOrder(root.right)
self.ans.append(')')
|
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.Min = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.Min or x <= self.Min[-1]:
self.Min.append(x)
def pop(self) -> None:
x = self.stack.pop()
if x == self.Min[-1]:
self.Min.pop()
def top(self) -> int:
return self.stack[-1] if self.stack else -1
def getMin(self) -> int:
return self.Min[-1] if self.Min else -1
# 这样太慢
# class MinStack:
# def __init__(self):
# """
# initialize your data structure here.
# """
# self.stack = []
# def push(self, x: int) -> None:
# self.stack.append(x)
# def pop(self) -> None:
# self.stack.pop()
# def top(self) -> int:
# return self.stack[-1]
# def getMin(self) -> int:
# # if len(self.stack) > 0:
# # return min(self.stack)
# # else:
# # return None
# return min(self.stack)
|
class Solution:
def sortColors(self, nums) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# dic = {}
# dic['0'] = nums.count(0)
# dic['1'] = nums.count(1)
# dic['2'] = nums.count(2)
# nums = []
# for num in ['0', '1', '2']:
# while dic[num] > 0:
# nums.append(int(num))
# dic[num] -= 1
# idx0 = 0
# idx2 = len(nums) - 1
# for i in range(0, len(nums)):
# if idx0 >= idx2:
# break
# if nums[i] == 0:
# nums[idx0], nums[i] = nums[i], nums[idx0]
# idx0 += 1
# elif nums[i] == 2:
# nums[idx2], nums[i] = nums[i], nums[idx2]
# idx2 -= 1
# return nums
l = 0
r = len(nums)-1
#cur=0
for cur in range(0, len(nums)):
if l>= r:
break
if nums[cur] ==0 :
nums[l],nums[cur] = nums[cur],nums[l]
l += 1
#cur += 1
elif nums[cur] ==2 :
nums[r],nums[cur] = nums[cur],nums[r]
r -= 1
#else:
#cur += 1
return nums
# dic = {'0': 2, '1': 3}
# for num in dic:
# while dic[num] > 0:
# print(num)
# dic[num] -= 1
x = Solution()
print(x.sortColors([2,0,2,1,1,0]))
|
class Solution:
def containsDuplicate(self, nums) -> bool:
nums.sort()
temp = nums[0]
type = 1
for num in nums:
if temp != num:
type += 1
temp = num
return type != len(nums)
|
'''
class Solution:
def longestCommonPrefix(self, strs):
List = list(strs)
minLen = 10000
str = ''
for i in range(len(List)):
if len(List[i]) < minLen:
minLen = len(List[i])
for i in range(minLen):
for j in range(0, len(List) - 1):
if List[j][i] != List[j + 1][i]:
return str
str += List[0][i]
return str
x = Solution()
strs = ["","","a"]
print(x.longestCommonPrefix(strs))
'''
'''
class Solution:
def longestCommonPrefix(self, strs):
List = list(strs)
minLen = 10000
str = ''
for i in range(len(List)):
if len(List[i]) < minLen:
minLen = len(List[i])
temp = List[0][:minLen]
for i in temp:
for j in range(len(List)):
if List[j] !=
'''
class Solution:
def longestCommonPrefix(self, strs):
List = list(strs)
minLen = 10000
str = ''
for i in range(len(List)):
if len(List[i]) < minLen:
minLen = len(List[i])
low = 0
high = minLen
while low <= high:
test = False
mid = (high + low) // 2
for i in range(len(List)):
if List[i][:mid] != List[0][:mid]:
test = False
else:
test = True
if test == False:
high = mid - 1
elif test == True:
low = mid + 1
return List[0][: mid]
x = Solution()
str = ["dog","racecar","car"]
print(x.longestCommonPrefix(str)) |
#!/usr/bin/env python3
# an example Python program
# by Erin Coffey
# 10 January 2018
import sys
MODULES_DIR = "/Users/erin/Documents/Development/Python/modules/"
sys.path.append(MODULES_DIR)
# import local module for welcome message
import stringer
# import module for tracking lost time
import timer
NAME = "Test Scores"
AUTHOR = "Erin Coffey"
def display_help():
print("Enter 'x' to exit")
# end display_help
def get_score():
while True:
score = input("Enter test score: ")
if score.lower() == "x":
return score
else:
try:
score = int(score)
except ValueError:
print ("ERROR, Score must be an integer number. Please try again.")
continue
if score < 0 or score > 100:
print ("ERROR, Score must be greater than 0 and, less than 100. Please try again.")
continue
else:
return score
# end get_score()
def get_scores(scores):
while True:
score = get_score()
if score != "x":
scores.append(score)
else:
break
if len(scores) > 0:
return 1
else:
return "x"
# end get_scores()
def calculate_total_score(scores):
total = 0
for score in scores:
total += score
return total
# end calculate_total_score()
def display_results(scores):
scores.sort()
# get med index by divide and truncate
median_index = len(scores) // 2
median_value = scores[median_index]
total_score = calculate_total_score(scores)
# calculate average score
average_score = round(total_score / len(scores))
# format and display the result
print("======================")
print("Total Score: ", total_score,
"\nNumber of Scores: ", len(scores),
"\nAverage Score: ", average_score,
"\nLow Score: ", min(scores),
"\nHigh Score: ", max(scores),
"\nMedian Score: ", median_value)
print()
if average_score > 89:
print ("Congratulations!!! You are an 'A' student!!!")
elif average_score > 79:
print ("Congratulations!! You are a 'B' student!!")
elif average_score > 69:
print ("Congratulations! You are a 'C' student.")
elif average_score > 59:
print ("Congratulations. You are still a student.")
else:
print ("Perhaps, you should find vocational work.")
# end display_results()
def main():
myTimer = timer.begin_timer()
stringer.show_welcome(NAME)
display_help()
while True:
scores = []
response = get_scores(scores)
if response != "x":
display_results(scores)
print()
choice = input("Try again? (y/n): ")
if choice.lower() != "y":
break
# end while loop
timer.stop_timer(myTimer)
print("Bye!")
# end main
#if the current module is the main module
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# an example Python program
# by Erin Coffey
# 10 January 2018
import sys
MODULES_DIR = "/Users/erin/Documents/Development/Python/modules/"
sys.path.append(MODULES_DIR)
# import local module for welcome message
import stringer
# import module for tracking lost time
import timer
NAME = "Rectangle Area and Perimiter"
AUTHOR = "Erin Coffey"
def main():
myTimer = timer.begin_timer()
stringer.show_welcome(NAME)
should_Exit = False
while not should_Exit:
print()
# get input from the user
length = float(input("Enter Rectangle length:\t"))
width = float(input("Enter Rectangle width:\t"))
# calculate
area = round(length * width,2)
perimiter = round(length * 2 + width * 2,2)
print()
print("Area =\t\t",area)
print("Perimiter =\t",perimiter)
print()
choice = input("Try again? (y/n): ")
if choice.lower() != "y":
should_Exit = True
# end while loop
timer.stop_timer(myTimer)
print("Bye!")
# end main
#if the current module is the main module
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# an example Python program working with dictionaries
# by Erin Coffey
# 29 January 2018
import sys
MODULES_DIR = "/Users/erin/Documents/Development/Python/modules/"
sys.path.append(MODULES_DIR)
# import local module for welcome message
import stringer
# import module for tracking lost time
import timer
# import object classes
from objects import Product, Book, Movie
# ifor input validation
import validation as val
AUTHOR = "Erin Coffey"
NAME = "Object Oriented Product Viewer"
def show_products(products):
print("PRODUCTS")
for i in range(len(products)):
product = products[i]
print(str(i+1) + ". ",product,end="")# use overridden object string representation method
if isinstance(product, Book):
print(" (Book)")
elif isinstance(product, Movie):
print(" (Movie)")
else:
print()
print()
# end show_products()
def show_product(product):
print("PRODUCT DATA")
print("Name: {:s}".format(product.name))
if isinstance(product, Book):
print("Author: {:s}".format(product.author))
if isinstance(product, Movie):
print("Year: {:d}".format(product.year))
print("Price: {:.2f}".format(product.price))
print("Discount percent: {:d}%".format(product.discountPercent))
print("Discount amount: {:.2f}".format(product.getDiscountAmount()))
print("Discount price: {:.2f}".format(product.getDiscountPrice()))
print()
# end show_product()
def main():
myTimer = timer.begin_timer()
stringer.show_welcome(NAME)
print()
# tuple of product objects demonstrating polymorphism
products = (Product("Heavy hammer", 12.99, 62),
Product("Light nails", 5.06, 0),
Movie("Blade Runner", 29.99, 0, 1984),
Book("Moby Dick", 19.99, 0, "Herman Melville"),
Product("Medium tape", 7.24, 0))
show_products(products)
while True:
print()
try:
number = val.get_int("Enter Product number: ",len(products),0)
product = products[number - 1]
show_product(product)
except Exception as e:
print("There was an Error processing your product.", e)
break
choice = input("View another? (y/n): ").lower()
if choice != "y":
break
# end while loop
timer.stop_timer(myTimer)
print("Bye!")
# end main()
#if the current module is the main module
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
#@pfiff, christina
class Person:
def __init__(self,name,age=20,size=10):
self.name=name[0].upper() + name[1:]
self._age=age
self.__size=size
def __str__(self):
return "ich heiße: {}".format(self.name)
pass
class Student(Person):
pass
class GuiElement:
def __init__(self, x = 0, score = 20):
self.x = x
self.score = score
def move(self):
self.x = self.x + 10
return self.x
def __add__(self, other):
return self.score + other.score
class ItStudent(Student, GuiElement):
def __init__(self, name, x = 10):
Student.__init__(self, name)
GuiElement.__init__(self, x)
pass
susi = ItStudent("Susi")
print(susi.move())
gui = GuiElement()
print(susi+gui+susi)
print(gui.move())
martin = Student("martin")
print(martin.name)
print(martin._age)
#print(martin.__size)
print(isinstance(martin,Person))
print("geht") |
#!/usr/bin/python3
#author leitner mitterer
class Paper():
def __init__(self,text):
self.text=text
class Timer():
def __init__(self, time):
self.time=time
class Securepaper(Paper, Timer):
def __init__(self, encryptiontype, text, time):
Paper.__init__(self,text)
Timer.__init__(self,time)
self.encryptiontype = encryptiontype
def __add__(self, other):
sRet= Securepaper( self.encryptiontype,
self.text+other.text,
(self.time+other.time)/2)
return sRet
def __str__(self):
return "SecurePaper: Enc: {0}, Text: {1}, Time: {2}".format(
self.encryptiontype,
self.text,
str(self.time))
s1 = Securepaper("md5","Gruppe 1",5)
s2 = Securepaper("md5","Gruppe 2",12)
s3 = Securepaper("md5","Gruppe x",1)
print(s1 + s2 + s3) |
#! /usr/bin/python3
# @author Christina, Viktoria
def add(a,b):
return a+b
print(add(1,3))
def add(a,b=1):
return a+b
print(add(2))
print("Done") |
#!/usr/bin/python3
#@sakaijun, taucherp
#print("Hallo")
def generator(s):
slist=s.split()
for el in slist:
yield(el)
#yield(slist)
g=generator("Heute ist das Wetter nicht schoen")
for a in g:
print(a) |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
from sklearn.cluster import MeanShift
from sklearn import preprocessing
df = pd.read_excel('titanic.xls')
original_df = pd.DataFrame.copy(df)
# print(df.head())
df.drop(['name', 'body'], 1, inplace=True)
df.convert_objects(convert_numeric=True)
df.fillna(0, inplace=True)
# print(df.head())
# this function converts all the string data to number data
def handle_non_numerical_data(df):
# here we extract all the column headers in a list(.values) and (.columns) gives us all the column objects
columns = df.columns.values
# here we iterate on all the values of each columns which require change
for column in columns:
# we will store all the unique data of a single column in this dictionary with a number value corresponding to it
text_digit_val = {}
# use this function to map the string to their corresponding numbers from the above dictionary
def convert_to_int(val):
return text_digit_val[val]
# if the column data is not a number then only perform these else skip
if df[column].dtype != np.int64 and df[column].dtype != np.float64:
# extracting all rows of the column in a list
column_contents = df[column].values
# extracting all the unique rows of the column in a list
unique_elements = set(column_contents)
x = 0
# putting these unique rows in the dictionary with unique numbers
for unique in unique_elements:
if unique not in text_digit_val:
text_digit_val[unique] = x
x += 1
# using pandas map function to map all the column rows with the new data obtained after passing it to the function
# syntax = map(func, arg)
# NOTE- list() is optional here just to show that the output is a list
df[column] = list(map(convert_to_int, df[column]))
return df
df = handle_non_numerical_data(df)
# print(df.head())
X = np.array(df.drop(['survived'], 1).astype(float))
X = preprocessing.scale(X)
Y = np.array(df['survived'])
clf = MeanShift()
clf.fit(X)
labels = clf.labels_
cluster_centers = clf.cluster_centers_
# createss an entire column and appends nan as the value in each row
original_df['cluster_group'] = np.nan
for i in range(len(X)):
original_df['cluster_group'].iloc[i] = labels[i]
n_clusters = len(np.unique(labels))
survival_rates = {}
for i in range(n_clusters):
# here temp_df becomes an collection of data of a particular group
temp_df = original_df[ original_df['cluster_group']==float(i) ]
survival_cluster = temp_df[ temp_df['survived']==1 ]
survival_rate = float(len(survival_cluster))/len(temp_df)
survival_rates[i] = survival_rate
print(survival_rates)
# Analysis
print(original_df[original_df['cluster_group']==0])
print(original_df[original_df['cluster_group']==1])
print(original_df[original_df['cluster_group']==2])
print(original_df[original_df['cluster_group']==0]).describe()
print(original_df[original_df['cluster_group']==0]).describe()
print(original_df[original_df['cluster_group']==0]).describe()
|
def is_leap(year):
#all statements evalueate to booleans, therefore function returns a boolean
return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)
def print_ints(n):
nums = ""
for i in range(1, n+1):
nums += str(i)
return nums
print(is_leap(2100))
print(print_ints(5)) |
#LIFO - Last in first out. E.G. A stack of books. A new book will be added to the top of the stack.
#Removing a book will remove the book at the top of the stack.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""Accepts an item as a parameter and appends it to the end of our list.
Returns nothing
The runtime for this method is 0(1), or constant time, because appending
to the end of the list happens in constant time.
"""
self.items.append(item)
def pop(self):
"""Returns and removes the last item for the list, which is also the top item
in the stack.
The runtime here is constant time, because all it does is index to the last item of the list.
"""
if self.items:
return self.items.pop()
return None
def peek(self):
"""this method return the last item in the list, which is also
the top item in the stack.
This method runs in constant time because indexing into a list
is done in constant time"""
if self.items:
return self.items[-1]
return None
def size(self):
"""This method returns the length of the listthat is representing the stack.
The method runs in constant time becasue finding the length of a list happens
in constant time
"""
return len(self.items)
def is_empty(self):
"""This method returns a boolean value describing whether or not the stack is empty.
Testing for equality happensin constant time.
"""
return self.items == []
|
from Deque import Deque
def main(data):
deque = Deque()
for character in data:
deque.add_rear(character)
while deque.size() >= 2:
front_item = deque.peek_front()
rear_item = deque.peek_rear()
deque.remove_front()
deque.remove_rear()
if rear_item != front_item:
return False
return True
print(main("nitin"))
print(main("car"))
|
def first_three_multiples(num):
print(num * 1)
print(num * 2)
print(num * 3)
return num *3
def tip(total, percentage):
result = total * (percentage / 100)
return result
def introduction(first_name, last_name):
return last_name+ ", " + first_name + " " + last_name
def dog_years(name, age):
dog_age = age * 7
return name + ", you are " + str(dog_age) + " years old in dog years"
def lots_of_math(a,b,c,d):
result_one = a + b
print(result_one)
result_two = c-d
print(result_two)
result_three = result_one * result_two
print(result_three)
return result_three % a
first_three_multiples(10)
print(tip(100, 15))
print(introduction("James", "Bond"))
print(dog_years("Rio", 15))
print(lots_of_math(1,2,3,4))
|
def in_range(num, lower, upper):
if num >= lower and num <= upper:
return True
else:
return False
def same_name(your_name, my_name):
if your_name == my_name:
return True
else:
return False
def always_false(num):
if num > num or num < num:
return True
else:
return False
def movie_review(rating):
if rating >= 9:
return "Outstanding!"
elif rating >=5:
return "This one was fun."
else:
return "Avoid at all costs!"
def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
elif num3 > num1 and num3 > num2:
return num3
else:
return "It's a tie!"
print(in_range(10, 1, 20))
print(same_name("Jim", "Jim"))
print(always_false(5))
print(movie_review(9))
print(max_num(1,2,2)) |
#Method Overiding. 자식 클래스 메소드를 쓰고플 때 새로 메소드를 정의하여 사용
class unit:
def __init__(self, name, hp, velocity):
self.name = name
self.hp = hp
self.velocity = velocity
def move(self, location):
print("Unit move")
print("{0} : {1} location. velocity {2}"\
.format(self.name, location, self.velocity))
class attackunit(unit): # unit 상속
def __init__(self, name, hp, velocity, damage):
unit.__init__(self, name, hp, velocity) #unit name, hp 상속
self.damage = damage
def attack(self, location):
print("{0} : {1} location. Damage {2} ".format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} damaged".format(self.name, damage))
self.hp -= damage
print("{0} : now hp is {1}".format(self.name, self.hp))
if self.hp <= 0:
print("{0} : destroyed".format(self.name))
class flyable:
def __init__(self, speed):
self.speed = speed
def fly(self, name, location):
print("{0} : flying to {1}, speed {2}".format(name, location, self.speed))
class flyable_attack(attackunit, flyable): #have 2 parents
def __init__(self, name, hp, damage, speed):
attackunit.__init__(self, name,hp,0,damage) #velocity = 0
flyable.__init__(self, speed)
def move(self, location):
print("fly unit move")
self.fly(self.name, location)
vulture = attackunit("Vulture", 80, 10, 20)
battlecruiser = flyable_attack("BattleCruiser",500,25,3)
vulture.move("Westside")
battlecruiser.fly(battlecruiser.name, "Southsa")
battlecruiser.move("Wessa")
class buildingunit(unit):
def __init__(self, name, hp, location):
# pass : act like its done
super().__init__(name,hp,0) # = unit.__init__(self, name, hp, 0)
self.location = location
supply_depot = buildingunit("Supply depot", 500, "Northa")
def game_start():
print("Game starts..")
def game_over():
pass
|
hours = float(input("Enter Hours:")) #45
rate = float(input("Enter Rate:")) #10.50
def computepay(h,r):
if h >40:
return (h-40)*r*1.5 + 40*r
else :
return h*r
p = computepay(hours, rate)
print("Pay",p)
|
class Unit:
def __init__(self):
print("Unit 생성자")
class Flyable:
def __init__(self):
print("Flyable 생성자")
class Flyable_Unit(Unit,Flyable):
def __init__(self):
# super().__init__() #다중 상속 시 마지막 부모 클래스만.. 그래서 unit.__init__(self) 로 초기화해야함
Unit.__init__(self)
Flyable.__init__(self)
dropship = Flyable_Unit() |
from tkinter import *
from tkinter.scrolledtext import ScrolledText
from book import Database
database = Database()
class Window(object):
def __init__(self,window):
self.window = window
self.window.wm_title("Book Reminder")
l1 = Label(window,text="Title")
l1.grid(row=0,column=0)
l2 = Label(window,text="Author")
l2.grid(row=0,column=2)
l3 = Label(window,text="Rating")
l3.grid(row=1,column=0)
l4 = Label(window,text="Finished")
l4.grid(row=1,column=2)
l5 = Label(window,text="Opinion ")
l5.grid(row=0,column=4)
self.title_text = StringVar()
self.e1 = Entry(window,textvariable=self.title_text)
self.e1.grid(row=0,column=1)
self.author_text = StringVar()
self.e2 = Entry(window,textvariable=self.author_text)
self.e2.grid(row=0,column=3)
self.rating_text = StringVar()
self.e3 = Entry(window,textvariable=self.rating_text)
self.e3.grid(row=1,column=1)
self.finished_text = StringVar()
self.e4 = Entry(window,textvariable=self.finished_text)
self.e4.grid(row=1,column=3)
self.e5 = ScrolledText(window,height=6,width=35)
self.e5.grid(row=1,column=5)
self.list1 = Listbox(window,height=10,width=60)
self.list1.grid(row=2,column=0,rowspan=6,columnspan=2)
sb1 = Scrollbar(window)
sb1.grid(row=2,column=2,rowspan=6)
self.list1.configure(yscrollcommand=sb1.set)
sb1.configure(command=self.list1.yview)
self.list1.bind('<<ListboxSelect>>',self.get_selected_row) #bind selected row with event
b1 = Button(window,text="View all",width=12,command=self.view_command)
b1.grid(row=2,column=3)
b2 = Button(window,text="Add entry",width=12,command=self.add_command)
b2.grid(row=3,column=3)
b3 = Button(window,text="Search entry",width=12,command=self.search_command)
b3.grid(row=4,column=3)
b4 = Button(window,text="Update selected",width=12,command=self.update_command)
b4.grid(row=5,column=3)
b5 = Button(window,text="Delete selected",width=12,command=self.delete_command)
b5.grid(row=6,column=3)
b6 = Button(window,text="Close",width=12,command=window.destroy)
b6.grid(row=7,column=3)
def get_selected_row(self,event):
try:
index = self.list1.curselection()[0]
self.selected_tuple = self.list1.get(index)
self.e1.delete(0,END)
self.e1.insert(END,self.selected_tuple[1])
self.e2.delete(0,END)
self.e2.insert(END,self.selected_tuple[2])
self.e3.delete(0,END)
self.e3.insert(END,self.selected_tuple[3])
self.e4.delete(0,END)
self.e4.insert(END,self.selected_tuple[4])
self.e5.delete('1.0','end-1c')
self.e5.insert(END,self.selected_tuple[5])
except IndexError:
pass
def view_command(self):
self.list1.delete(0,END)
for row in database.view():
self.list1.insert(END,row)
def search_command(self):
self.list1.delete(0,END)
for row in database.search(self.title_text.get(),self.author_text.get()):
self.list1.insert(END,row)
def add_command(self):
database.add_book(self.title_text.get(),self.author_text.get(),self.rating_text.get(),self.finished_text.get(),self.e5.get('1.0','end-1c'))
self.list1.delete(0,END)
self.list1.insert(END,(self.title_text.get(),self.author_text.get(),self.rating_text.get(),self.finished_text.get(),self.e5.get('1.0','end-1c')))
def delete_command(self):
database.delete(self.selected_tuple[0])
def update_command(self):
database.update(self.selected_tuple[0],self.title_text.get(),self.author_text.get(),self.rating_text.get(),self.finished_text.get(),self.e5.get('1.0','end-1c'))
window = Tk()
Window(window)
window.mainloop()
|
#This is a simple
import random
guess_made=0
name=raw_input('hello,what is your name?\n')
number=random.randint(1,20)
print 'well {0},i am thinking a number between 1 and 20.'.format(name)
while guess_made <6:
guess=int(raw_input('Take a guess:'))
guess_made +=1
if guess <number:
print 'your guess is too low'
elif guess >number:
print 'your guess is too high'
else:
break
if guess==number:
print 'good job, {0}!you guessed my number in {1} guesses!'.format(name,guess_made)
else:
print 'Nope, The number I was thinking of was {0}'.format(number)
|
'''
Game of Life:
Rules:
1.Any live cell with fewer than two live neighbors dies, as if caused by under-population.
2.Any live cell with two or three live neighbors lives on to the next generation.
3.Any live cell with more than three live neighbors dies, as if by over-population..
4.Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
'''
def gameOfLife(board) :
if board == [] :
return
n = len(board)
m = len(board[0])
ret = [[0 for _ in range(m)] for _ in range(n)]
step = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]
for i in range(n) :
for j in range(m) :
cnt = 0
for s in step :
if i+s[0]>=0 and i+s[0]<n and j+s[1]>=0 and j+s[1]<m and board[i+s[0]][j+s[1]]==1 :
cnt += 1
if board[i][j] == 1 :
if cnt < 2 :
ret[i][j] = 0
elif cnt < 4:
ret[i][j] = 1
else :
ret[i][j] = 0
else :
if cnt == 3 :
ret[i][j] = 1
else :
ret[i][j] = 0
for i in range(n):
board[i] = ret[i]
if __name__ == "__main__":
board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
gameOfLife(board)
print(board)
|
def findMinStep(board , hand) :
def status(board , idx , ball) :
board = board[:idx]+ ball + board[idx:]
i = 0
while i <len(board)-2 :
if board[i] == board[i+1] and board[i+2] == board[i+1] :
j = i + 2
while j<len(board) and board[j]==board[i] :
j += 1
board = board[:i] + board[j:]
i = 0
else :
i += 1
return board
def search(board , hand, n) :
#print(board , hand)
if board == '' :
return n
if hand == '' :
return -1
ret = 1<<32
for i in range(len(board)) :
for j in range(len(hand)) :
t = search(status(board,i,hand[j]) , hand[:j]+hand[j+1:] , n+1)
if t>0 and ret>t :
ret = t
if ret<(1<<32) :
return ret
else :
return -1
import collections
def dfs(s, c):
if not s: return 0
res, i = float("inf"), 0
while i < len(s):
j = i + 1
while j < len(s) and s[i] == s[j]: j += 1
incr = 3 - (j - i)
if c[s[i]] >= incr:
incr = 0 if incr < 0 else incr
c[s[i]] -= incr
tep = dfs(s[:i] + s[j:], c)
if tep >= 0: res = min(res, tep + incr)
c[s[i]] += incr
i = j
return res if res != float("inf") else -1
return dfs(board, collections.Counter(hand))
if __name__ == '__main__' :
print(findMinStep("WWRRBBWW","WRBRW")) |
#import module from tkinter for UI
from tkinter import Tk, Label, Button
from _tkinter import *
import os
#creating instance of TK
root=Tk()
root.configure(background="#80D8FF")
#root.geometry("600x600")
def function1():
os.system("python training.py")
def function2():
os.system("python face_recognition.py")
def function3():
os.system("python face_datasets.py")
def function4():
os.system("python showdata.py")
#setting title for the window
root.title("AUTOMATIC ATTENDANCE MANAGEMENT USING FACE RECOGNITION")
#creating a text label
Label(root, text="Smart Attendance",font=("helvatica",40),fg="white",bg="#00BFA5",height=2).grid(row=0,rowspan=2,columnspan=2,padx=5,pady=5)
#creating a button
Button(root,text="Train DATABASE",font=("times new roman",30),bg="#3F51B5",fg='white',command=function1).grid(row=3,columnspan=2,padx=5,pady=5)
#creating second button
Button(root,text="Take Attendance",font=("times new roman",30),bg="#3F51B5",fg='white',command=function2).grid(row=4,columnspan=2,padx=5,pady=5)
#creating third button
Button(root,text="New Entry",font=('times new roman',30),bg="#3F51B5",fg="white",command=function3).grid(row=5,columnspan=2,padx=5,pady=5)
#creating fourth button
Button(root,text="View Attendance",font=('times new roman',30),bg="#3F51B5",fg="white",command=function4).grid(row=6,columnspan=2,padx=5,pady=5)
root.mainloop()
|
import time
import RPi.GPIO as GPIO
from time import sleep
mtc1 = 7
mtc2 = 32
enar = 29
in1r = 31
in2r = 33
enal = 11
in1l = 12
in2l = 13
temp1=1
GPIO.setmode(GPIO.BOARD)
GPIO.setup(mtc1, GPIO.IN)
GPIO.setup(mtc2, GPIO.IN)
GPIO.setup(in1r,GPIO.OUT)
GPIO.setup(in2r,GPIO.OUT)
GPIO.setup(enar,GPIO.OUT)
GPIO.setup(in1l,GPIO.OUT)
GPIO.setup(in2l,GPIO.OUT)
GPIO.setup(enal,GPIO.OUT)
GPIO.output(in1r,GPIO.LOW)
GPIO.output(in2r,GPIO.LOW)
GPIO.output(in1l,GPIO.LOW)
GPIO.output(in2l,GPIO.LOW)
p=GPIO.PWM(enar,1000)
p.start(100)
p1=GPIO.PWM(enal,1000)
p1.start(100)
try:
time.sleep(2) # to stabilize sensor
while True:
if GPIO.input(mtc1):
print("Motion Detected...")
print("run")
GPIO.output(in2r,GPIO.HIGH)
GPIO.output(in1r,GPIO.LOW)
GPIO.output(in2l,GPIO.HIGH)
GPIO.output(in1l,GPIO.LOW)
time.sleep(1.5)
GPIO.output(in2r,GPIO.LOW)
GPIO.output(in1r,GPIO.HIGH)
GPIO.output(in2l,GPIO.HIGH)
GPIO.output(in1l,GPIO.LOW)
print("forward")
time.sleep(5)
GPIO.output(in2r,GPIO.LOW)
GPIO.output(in1r,GPIO.HIGH)
GPIO.output(in2l,GPIO.LOW)
GPIO.output(in1l,GPIO.HIGH)
time.sleep(1.5)
if GPIO.input(mtc2):
print("Motion Detected...")
time.sleep(5)
print("run")
GPIO.output(in2r,GPIO.LOW)
GPIO.output(in1r,GPIO.HIGH)
GPIO.output(in2l,GPIO.LOW)
GPIO.output(in1l,GPIO.HIGH)
time.sleep(1.5)
GPIO.output(in2r,GPIO.HIGH)
GPIO.output(in1r,GPIO.LOW)
GPIO.output(in1l,GPIO.HIGH)
GPIO.output(in2l,GPIO.LOW)
print("Back")
GPIO.output(in2r,GPIO.HIGH)
GPIO.output(in1r,GPIO.LOW)
GPIO.output(in2l,GPIO.HIGH)
GPIO.output(in1l,GPIO.LOW)
time.sleep(1.5)
time.sleep(0.1)
except:
print("END...")
GPIO.cleanup() |
# ВНИМАНИЕ! Извините было мало времени, не успел в методах обработать ошибки по вводу цифр, символов и букв
# чтобы пользователь не сломал программу.
class TV_controller:
def __init__(self, model, channels):
self.model = model
self.channels = channels
self.selected_channel = 0
def first_channel(self):
print(self.channels[0])
def last_channel(self):
print(self.channels[-1])
def turn_channel(self, N):
if N > len(self.channels) or N < 1:
print('Такого канала не существует')
else:
self.selected_channel = N - 1
print(self.channels[self.selected_channel])
def next_channel(self):
self.selected_channel += 1
if self.selected_channel >= len(self.channels):
self.selected_channel = 0
print(self.channels[self.selected_channel])
else:
print(self.channels[self.selected_channel])
def previous_channel(self):
self.selected_channel -= 1
if self.selected_channel < 0:
self.selected_channel = len(self.channels) - 1
print(self.channels[self.selected_channel])
else:
print(self.channels[self.selected_channel])
def current_channel(self):
print('Сейчас включен - ' + self.channels[self.selected_channel])
def is_exist(self, search):
self.search = str(search)
if self.search.isdigit():
if int(self.search) > len(self.channels) or int(self.search) < 1:
print('Такого канала нет')
else:
print('Да, такой канал есть')
elif self.search in self.channels:
print('Да, такой канал есть')
else:
print('Такого канала нет')
|
class Product(object):
def __init__(self,price,item_name,weight,brand,cost,status="For Sale"):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.cost = cost
self.status = status
self.tax = 0.06
# Sell: changes status to "sold"
def sell(self):
self.status == "Sold"
# self.returnA.status ==
# takes tax as a decimal amount as a parameter and returns the price of the item including sales tax
def addTax(self):
return self.tax
# takes reason for return as a parameter and changes status accordingly.
def returnA(self):
self.addTax()
if self.status == 'Defective':
self.status = 'Take IT'
self.price = 0
elif self.status == 'In the box':
self.status = "Like New, For SALE"
self.price = ("{0:.2f}".format(float(self.price + (self.price * self.tax))))
else:
self.status = "Open Box"
self.price = ("{0:.2f}".format(float((.8 * self.price )+ (self.price * self.tax))))
return self
# show all product details.
def display_info(self):
self.returnA()
print "Price :", self.price
print "Item name :", self.item_name
print "Weight :", self.weight
print "Brand :", self.brand
print "Cost :", self.cost
print "Status :", self.status
product1 = Product(800.23,'Iphone','2lbs','Apple',500,'In the box')
print product1.display_info()
|
# Print num 1-255
def print1to255():
for some_number in range(0, 256): # for looping in range 0 -256
print some_number
# print1to255()
# Print array with odds
arr =[1,2,3,4,5,6,7,8,9]
def withOdds(arr):
for some_element in range(0, len(arr)):
if arr[some_element] % 2 != 0:
arr[some_element] = "you are odd"
print arr
#withOdds(arr)
# Condotional
age = 21
if age >= 18:
print 'Legal age'
elif age == 17:
print 'You are seventeen.'
else:
print 'You are so young!'
for val in "string":
if val == "i":
break
print val
|
print ("Hell World")
x = "Hello Python"
print x
y = 42
print y
#String
name = "Zen"
print "My name is", name
name = "Zen"
print "My name is" + name
# String Interpolation using {}
first_name = "Zen"
last_name = "Coder"
print "My name is {} {}".format(first_name, last_name)
'''
The following is a list of commonly used string methods:
a. string.count(substring): returns number of occurrences of substring in string.
b. string.endswith(substring): returns a boolean based upon whether the last characters of string match substring.
c. string.find(substring): returns the index of the start of the first occurrence of substring within string.
d. string.isalnum(): returns boolean depending on whether the string's length is > 0 and all characters are alphanumeric (letters and numbers only). Strings that include spaces and punctuation will return False for this method. Similar methods include .isalpha(), .isdigit(), .islower(), .isupper(), and so on. All return booleans.
e. string.join(list): returns a string that is all strings within our set (in this case a list) concatenated.
f. string.split(): returns a list of values where string is split at the given character. Without a parameter the default split is at every space.
'''
# List
x = [1,2,3,4,5]
x.append(99)
print x
x = [99,4,2,5,-3];
print x[:]
#the output would be [99,4,2,5,-3]
print x[1:]
#the output would be [4,2,5,-3];
print x[:4]
#the output would be [99,4,2,5]
print x[2:4]
#the output would be [2,5];
# List method: https://docs.python.org/2/tutorial/datastructures.html
# List Buildin function: https://docs.python.org/2/library/functions.html
# List buildin method: https://docs.python.org/2/tutorial/datastructures.html
|
class InventoryItem(object):
def __init__(self, description, cost, quanity):
self.description = description
self.cost = cost
self.quantity = quanity
inventoryList = [
InventoryItem('Monitor', 149.99, 5),
InventoryItem('Keyboard', 29.99, 12),
InventoryItem('Mouse', 24.99, 13),
InventoryItem('USB Drive (32gb)', 26.99, 23),
]
print('+----------------------------------------------------+')
print('| {:<20} | {:>12} | {:>12} |'.format('Description', 'Cost ($)', 'Quantity'))
print('|----------------------------------------------------|')
for item in inventoryList:
print('| {:<20} | {:>12} | {:>12} |'.format(item.description, item.cost, item.quantity))
print('+----------------------------------------------------+')
|
# Get our numbers from the command line
import sys
numbers= sys.argv[1].split(',')
numbers= [int(i) for i in numbers]
# Your code goes here
index = int()
highest_number = int()
integer = int()
result = int()
highest_number = numbers[0]
index = 0
for index in range(0, len(numbers)):
integer = numbers[index]
if integer > highest_number:
highest_number = integer
result = index
print(result)
|
num_days = int()
num_weeks = int()
snow_fall = float()
daily_total = float()
weekly_total = float()
for num_weeks in range(1,3):
for num_days in range(1,4):
snow_fall = float(input("Enter how much snow has fallen: "))
daily_total = daily_total + snow_fall
print("Total Daily Snowfall: ", daily_total)
weekly_total = weekly_total + daily_total
print("Total Weekly Snowfall: ", weekly_total)
|
#Variables
daily_cans = int()
weekly_cans = int()
total_cans = int()
#outer loop keeping track of number of weeks
for weeks in range(1,3):
#inner loop keeps track of days
for days in range (1,4):
daily_cans = int(input("Enter total cans collected today: "))
weekly_cans = weekly_cans + daily_cans
#end loop
print("Total cans collected this week: ", weekly_cans)
total_cans = total_cans + weekly_cans
print("Total cans collected for the entire drive: ", total_cans)
weekly_cans = 0
#end outer loop
|
from collections import defaultdict
import random
from flow_utilities import generate_flow_network, delete_node_from_network,modify_link_from_network,generate_flow_randomly
import time
from flow_visualize import generate_graph, generate_flow_distribution
class Graph:
"""This class uses a 2D array in python to represent a directed graph which denotes a adjaceny matrix representation"""
def __init__(self, graph):
self.graph = graph # residual graph
self.ROW = len(graph)
self.COL = len(graph[0])
"""Returns true if there is a path from source 's' (source) to sink 't' (sink) in
residual graph and fills parent[] to store the path """
def breadth_first_search(self, s, t, parent):
visited = [False] * (self.ROW) # Create array with indicex and mark them as unvisited
queue = [] # standard queue for the BFS
# Mark and enque the source: 's'
queue.append(s)
visited[s] = True
while queue: #standard BFS loop
u = queue.pop(0)
# Get all adjacent vertices of the dequeued vertex u
# If a adjacent has not been visited, then mark it
# visited and enqueue it
for ind, value in enumerate(self.graph[u]):
if visited[ind] == False and value > 0:
queue.append(ind)
visited[ind] = True
parent[ind] = u
if visited[t] == True: #If the sink is reached from source via BFS ->
return True
else:
return False
def FordFulkerson(self, source, sink):
"""return the maximum flow of given graph between the given nodes source and sink
with the final residual graph.
"""
# This array is filled by BFS and to store path
parent = [-1] * (self.ROW)
# This array stores the flow paths added
flow_dist = [[0 for i in range(self.ROW)] for j in range(self.ROW)]
# set initial flow to zero
max_flow = 0
# Augment the flow while there is path from source to sink
while self.breadth_first_search(source, sink, parent):
# Find minimum capacity in the path filled by BFS
path_flow = float("Inf")
s = sink
path = []
while (s != source):
path_flow = min(path_flow, self.graph[parent[s]][s])
path.append([s, parent[s]])
s = parent[s]
max_flow += path_flow
# update residual capacities of the edges and reverse edges to current graph
# update flow graph to keep track of flow paths
v = sink
while (v != source):
u = parent[v]
self.graph[u][v] -= path_flow
flow_dist[u][v] -= path_flow
self.graph[v][u] += path_flow
flow_dist[v][u]+= path_flow
v = parent[v]
return max_flow,flow_dist
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import hashlib
__all__ = ['hasher']
def hasher(string, size=8):
"""Simple function to generate a SHA1 hash of a string.
Parameters:
- string : string or bytes
The string to be hashed.
- size : int
Size of the output hash string.
Returns:
- h : string
Hash string trunked to size.
"""
string = str(string)
h = hashlib.sha256(string.encode()).hexdigest()
return h[:size]
|
start = 99
while start:
print("{} bottles of beer on the wall".format(start))
print("{} bottles of beer.".format(start))
print("Take one down, pass it around")
start -= 1
print("{} bottles of beer on the wall.".format(start))
if start == 0:
print('All outta beer') |
list = []
def show_help():
print('What do you want to add to your list?')
print('''
type "SHOW" to show current list
type "HELP" to show a list of app commands
type "DONE" to stop adding items
''')
def show_list():
print('Here is your list:')
for item in list:
print(item)
def add_items(new_item):
list.append(new_item)
print('Added {} to list. List now has {} items'.format(new_item, len(list)))
def main():
show_help()
while True:
new_item = input('> ')
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
add_items(new_item)
show_list() |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.