text
stringlengths 37
1.41M
|
---|
def tower(programs):
supported = []
for i in programs:
program = i.split()
if len(program) > 2:
supported.extend("".join(program[3:]).split(","))
for i in programs:
if i.split()[0] not in supported:
return i
return None
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
题目:斐波那契数列。
程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。
在数学上,费波那契数列是以递归的方法来定义:
F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1]+ F[n-2](n=>2)
"""
def my_fib(n):
list1 = [0, 1]
if n == 0:
return 0
elif n ==1:
return 1
else:
return my_fib(n-2) + my_fib(n-1)
print(my_fib(10))
|
Write a Python program to reverse a string.
Ans::
def reverse(s):
Str = ""
for i in s:
Str = i + Str
return Str
L = "1234abcd"
reverse(L)
O/p::
dcba4321
|
Write a Python class to find the three elements that sum to zero from a set
Input array : [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
Ans::
class elements:
def Sum(self,I):
j = len(sorted(I))
result = []
for x in range(j):
for y in range (1,j):
for z in range (2,j):
if I[x]+I[y]+I[z] == 0:
result.append([I[x], I[y], I[z]])
res = list(set(tuple(sorted(sub)) for sub in result))
print(res)
if __name__=="__main__":
I = [-25, -10, -7, -3, 2, 4, 8, 10]
obj = elements()
obj.Sum(I)
O/P::
[(-7, -3, 10), (-10, 2, 8)]
|
class Number():
def __init__(self,i = 5, j = 1):
self.i = i
self.j = j
print("i is ",self.i, "\nj is ",self.j)
def fun(self):
return (f'{self.i} + {self.j}k')
obj = Number()
print(obj.fun())
print(obj.i)
O/P::
i is 5
j is 1
5 + 1k
5
Deleting::
1)
del obj.i
print(obj.i)
O/P:
AttributeError: 'Number' object has no attribute 'i'
2)
del obj
print(obj.fun())
O/P:
NameError: name 'obj' is not defined
3)
del Number.fun
print(obj.fun())
O/P::
AttributeError: 'Number' object has no attribute 'i'
|
8. Print the each character along with that index in a string i/o - "Python" o/p - P-0 y-1 t-2 h-3 o-4 n-5
Ans:
sol1:
I = "Python"
for x in range(len(I)):
a = I[x]
print('{}-{}'.format(a,x))
sol2:
list_enumerate = list(enumerate(I))
for i in list_enumerate:
print(i)
O/P:
P-0
y-1
t-2
h-3
o-4
n-5
|
Write a Python program to split a list every Nth element. Go to the editor
Sample list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
Expected Output: [['a', 'd', 'g', 'j', 'm'], ['b', 'e', 'h', 'k', 'n'], ['c', 'f', 'i', 'l']]
Ans::
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
n = 3
m = []
for i in range (n):
j = L[i::n]
m.append(j)
print(m)
O/P::
[['a', 'd', 'g', 'j', 'm'], ['b', 'e', 'h', 'k', 'n'], ['c', 'f', 'i', 'l']]
|
#Print unique rows in a given boolean matrix using Set with tuples
Ans:
mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]]
inputs = set(map(tuple, mat))
for i in list(inputs):
print(i)
O/P::
(1, 1, 1, 0, 0)
(0, 1, 0, 0, 1)
(1, 0, 1, 1, 0)
|
1)
class Mathematics:
def addNumbers(x, y):
return x + y
# create addNumbers static method
Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('The sum is:', Mathematics.addNumbers(5, 10))
O/P::
The sum is: 15
2)
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
date = Dates("15-12-2016")
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")
O/P::
Equal
|
class MyList(object):
data = None
Next = None
def __init__(self,val):
self.val = val
self.head = None
@classmethod
def add(cls,val):
if not cls.data:
head = cls(val)
cls.data = head
cls.Next = head
else:
head = cls(val)
cls.Next.head = head
cls.Next = head
return cls.data
def view(self):
iter_list = MyList.data
while iter_list:
print(iter_list.val)
iter_list = iter_list.head
if __name__=="__main__":
x = [2,3,4,6,7]
for i in x:
obj = MyList.add(i)
obj.view()
O/P:
2
3
4
6
7
|
Count occurrences of an element in a Tuple
Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
Ans::
T = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
Input = int(input("Enter the number:"))
count = 0
for i in T:
if Input == i:
count += 1
print(count,'time')
O/P:
Enter the number:4
0 time
|
Python3 program to remove Nth occurrence of the given word
Ans::
def Remove(Str,word,n):
newword = []
count = 0
for x in Str:
if x == word:
count += 1
if (count != n):
newword.append(x)
else:
newword.append(x)
lst = newword
if count == 0:
print("Item not found")
else:
print("Updated list is: ", lst)
return newword
# Driver code
l = ["geeks", "for", "geeks"]
word = "geeks"
N = 1
Remove(l, word, N)
O/P::
Updated list is: ['for', 'geeks']
|
e = list(range(15))
f = list(range(1,13))
g = list(range(1,12))
def splitter(randomseq, blocks=2):
static_length = len(randomseq)
block_size = static_length//blocks
start = 0
stop = block_size
for block in range(blocks):
if stop < static_length:
yield randomseq[start:stop]
start += block_size
stop += start
yield randomseq[start:]
print(list(splitter(g)))
'''
This is ultimately not how we want to split. Just example use with generators.
Would result in merged giveing the following result:
[1,6,11,2...]
rather than
[1,6,2,7...11]
'''
|
import time
# pulls addresses from a file. Assumes one address per line,
# and ignores empty lines or lines starting with a '#'.
class AddressLoader:
def __init__(self, location):
self.file = open(location, "r")
self.last = None
def is_address(self, line):
opline = self.__clean(line)
is_empty = (opline == "")
is_comment = opline.startswith("#")
# print(": {} {}", is_empty, is_comment, "'" + line + "'")
return not is_empty and not is_comment
def __clean(self, input):
return input.strip().replace('\n', '').replace('\r', '')
def get_address(self):
# time.sleep(2)
while True:
line = self.file.readline()
if self.is_address(line):
self.last = line
return self.__clean(line)
if line == self.last:
return self.__clean(line)
if line == "":
return line
|
#!/usr/bin/env python3
shopping_lists = []
from list_maker import Listmaker, GroceryItem
while True:
i=0
print("\n\nEnter your Choice or enter Q to quit")
print("1* Create a new shopping list")
print("2* Add items to a list")
print("3* Remove items from the app")
print("4* View your current lists\n")
menu_input=input("Please enter your choice: \n")
if menu_input.upper() == "Q":
break
elif menu_input == "1":
print("\n\nWhere would you like to shop at? ")
store_name = input("")
print("Where is this store located? ")
location = input("")
shopping_lists.append(Listmaker(store_name, location))
elif menu_input == "2":
for i in range(0, len(shopping_lists)):
if len(shopping_lists) == 0:
break
else:
print(f"{i}* {shopping_lists[i].store_name}")
try:
list_number = int(input("\nWhich store would you like to add an item to? "))
item_to_add = GroceryItem()
print("What would you like to add to the list?")
item_to_add.title = input("")
try:
print("How much does it cost?")
item_to_add.price = float(input(""))
print(f"How much {item_to_add.title} do you want to buy?")
item_to_add.quantity = input("")
except:
print("These are prices and quantity, they need to be numbers, not letters")
Listmaker.add_item(shopping_lists[list_number], item_to_add)
except ValueError:
print("You didn't pick a store number")
break
elif menu_input == "3":
try:
if len(shopping_lists) == 0:
break
else:
delete_choice = input("Do you want to want to delete a store or an item? ")
for i in range(0, len(shopping_lists)):
print(f"{i}* {shopping_lists[i].store_name}")
if delete_choice.lower() == "store":
store_choice = int(input("Which store would you like to remove? "))
shopping_lists.pop(store_choice)
elif delete_choice.lower() == "item":
list_number = int(input("\nWhich store would you like to remove an item from? "))
for item_index in range(0, len(shopping_lists[list_number].item_list)):
item = shopping_lists[list_number].item_list[item_index].title
print(f"{item_index}* {item}")
item_number = int(input("\nWhich item would you like to remove? "))
removed_item = shopping_lists[list_number].item_list.pop(item_number)
print(f"{removed_item.title} removed!")
print(f"{item_index}* {item}")
except:
print("You didn't enter the right input")
exit()
elif menu_input == "4":
Listmaker.view_list(shopping_lists)
else:
print("Sorry that wasn't a valid choice")
|
#!/usr/bin/env python3
first_number = None
second_number = None
operation = None
class Calculator():
def def __init__(self):
<#code#>
def addition(value1, value2):
print("Add some numbers")
sum = value1 + value2
return sum
def subtraction(value1, value2):
print("Subtract some numbers")
difference = value1 - value2
return difference
def multiplcation(value1, value2):
print("Multiply some numbers")
product = value1 * value2
return product
def division(value1, value2):
print("Divide some numbers")
remainder = value1 / value2
return remainder
total = 0
if (first_number== None):
first_number = float(input("Enter your first value: "))
if (second_number == None):
second_number = float(input("Enter your second value: "))
if (operation == None):
operation = input("Enter your what operation you want to use (+, -, *, /): ")
if (operation == "+"):
total = addition(first_number, second_number)
elif (operation == "-"):
total = subtraction(first_number, second_number)
elif (operation == "*"):
total = multiplcation(first_number, second_number)
elif (operation == "/"):
total = division(first_number, second_number)
print(total)
|
#!/usr/bin/env python3
class Palindrome:
def __init__(self, input):
self.word = input
self.length = len(input)
self.reversed = ""
def reverse_word(self):
for letter in range (0, self.length):
self.reversed += self.word[letter]
is_palindrome = Palindrome(input("Please enter a word: "))
print(f"The word is {is_palindrome.word}")
is_palindrome.reverse_word()
print(is_palindrome.reversed)
if (is_palindrome.reversed == is_palindrome.word):
print("This word is a palindrome!")
else:
print("This word is not a palindrome")
|
#!/usr/bin/env python3
friends = ["Kevin", "Josh", "James", "Taylor", "Jeremy"]
for person in friends:
print(person)
|
#!/usr/bin/env python3
numbers=[23, 17, 19, 33, 44, 90, 2, 45]
for num in reversed(numbers):
print(num)
|
import cv2
def bicubic():
# get scale settings from text file ---
# default bicubic scale is 2
try:
settings = open("settings/settings_bicubic.txt", "r")
bicubic_scale = settings.read()
BICUBIC_SCALE = float(bicubic_scale) #stored in variable
except Exception as e:
print("Error occured. You might be misconfig the settings, please check the bicubic settings again.")
print("Please make sure that bicubic setting must not a zero or negative numbers." + '\n')
print("Error! " + str(e) + '\n')
INPUT_NAME = "input/1.png"
OUTPUT_NAME = "output/1-bicubic.png"
# Read image
img = cv2.imread(INPUT_NAME, cv2.IMREAD_COLOR)
# Enlarge image with Bicubic interpolation method
img = cv2.resize(img, None, fx=BICUBIC_SCALE, fy=BICUBIC_SCALE, interpolation=cv2.INTER_CUBIC)
cv2.imwrite(OUTPUT_NAME, img)
# print success!
print("Bicubic enlargement with factor " + str(BICUBIC_SCALE) + " success!")
bicubic()
|
# !/usr/bin/env python
# -*- coding: iso-8859-1 -*-
def inverse(liste):
res=""
i=len(liste)
while(i>0):
res=res+liste[i-1]
i=i-1
return res
#return liste[::-1]
def palindrome(phrase):
phraseI=inverse(phrase)
if(phrase==phraseI):
return True
else:
return False
def position(mot,phrase):
if(not(mot in phrase)):
return None
else:
test=phrase.split(mot)
return len(test[0])
chaine="je suis Jean Nemard"
print(inverse(chaine))
print(palindrome(chaine))
print(position("mard",chaine))
|
def sol(n):
words = []
for i in range(0, n):
words.append(str(input()))
for i in range(0, n):
curr_word = words[i]
if (len(curr_word) > 10):
short_word = curr_word[0] + \
str(len(curr_word[1:len(curr_word)-1])) + curr_word[-1]
words[i] = short_word
else:
pass
for word in words:
print(word)
if __name__ == "__main__":
n = int(input())
sol(n)
|
lista=[]
suma=0
for x in range (10):
num= int(input("Ingresa un número"))
lista.append(num)
suma=suma+num
media=suma/10
print("La lista de valores ingresados es:")
print(lista)
print("La suma de los valores ingresados es:")
print(suma)
print("La media de lso valores ingresados es:")
print(media)
|
tupla=(432,7865,432,6754,231,8643,234,8,6,654,)
mayor=tupla[0]
for x in range (1,9):
if tupla[x]>mayor:
mayor=tupla[x]
print("El número mayor de la tupla es:")
print(mayor)
for x in range (1,9):
if tupla[x]<menor:
menor=tupla[x]
print("El número menor de la tupla es:")
print(menor)
|
k = []
print("Phần mêm quản lí nhân viên")
while True:
name = input("Enter worker's name, seperated by ',':")
a = input("nhập chức vụ:")
b = input("nhập mức lương")
c = input("nhập thời hạn hợp đồng")
d = {
"Tên nhân viên":(name),
"chức vụ" : (a),
"mức lương" : (b),
"thời hạn hợp đồng" : (c),
}
k.append(d)
# quest = input("Gõ bất cứ nút nào để tiếp tục hoặc gõ quit để dừng lại").lower()
# if quest == "quit":
# break
for i in k:
if i == 1:
print(i)
break
print(k)
|
a = ["evenger1", "avenger2", "averger3"]
print(a)
a.pop(1)
print(a)
b = ["evenger1","LOL", "avenger2", "averger3"]
print(b)
c = "LOL"
b.remove(c)
print(b)
if c in b:
print("Chưa xóa LOL")
else:
print("Đã xóa LOL")
|
a = ["Sport", "LOL", "DOTA", "BTS"]
for x in a:
print(x)
b = ["Sport", "LOL", "DOTA", "BTS"]
for y in b:
print(y.upper())
c = ["Sport", "LOL", "DOTA", "BTS"]
for i, item in enumerate(c):
print(i, item.upper())
|
from random import choice, shuffle
g = 0
while True:
a = ["fornite", "Lol", "PUBG", "Dota"]
x = choice(a)
y = [i for i in (x)]
shuffle (y)
print(*y)
e = input("sắp xếp thành 1 từ có nghĩa :")
if e == x:
g = g + 1
print("đúng", g)
else:
print("sai", g)
break
|
b = ["blue", "red", "teal", "green"]
a = input("nhập vào một vị trí hoặc một nội dung:")
if a.isdigit:
while True:
if 0 <= a <= len(b):
b.pop(a)
print(*b)
break
else:
print("Nhập lại đúng vị trí")
else:
b.remove(a)
print(*b)
|
while True:
a = input("your name?")
if a.isdigit():
print("Nhap lai")
else:
print(a)
break
|
import sqlite3
from sqlite3 import Error
def conectar():
try:
con = sqlite3.connect('db/datos.db')
return con
except Error as error:
print(str(error))
return None
def insert(_sql, lista):
try:
con = conectar()
if con:
ob_cursor = con.cursor()
filas = ob_cursor.execute(_sql, lista).rowcount
ob_cursor.close
con.commit()
con.close()
return filas
else:
print("No se pudo establecer una conexion a la base de datos.")
return -1
except Error as error:
print("Error al ejecutar SQL:" + str(error))
return -1
def select(_sql, lista):
try:
con = conectar()
if con:
con.row_factory = diccionarios
ob_cursor = con.cursor()
if lista:
ob_cursor.execute(_sql, lista)
else:
ob_cursor.execute(_sql)
filas = ob_cursor.fetchall()
ob_cursor.close
con.close
return filas
else:
print("No se pudo establecer una conexion")
return None
except Error as error:
print("Error al ejecutar select" + str(error))
return None
def diccionarios(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
|
import time
class Timer:
def __init__(self, prt=True):
self.start_time = time.time()
self.last_time = self.start_time
self.print = prt
def tick(self, msg=''):
res = time.time() - self.last_time
if self.print:
print('%.6f' % res, msg)
self.last_time = time.time()
return res
def tock(self, msg=''):
if self.print:
print(msg, '%.6f' % (time.time() - self.last_time))
return time.time() - self.last_time
from functools import wraps
def timing(f):
@wraps(f)
def decorated(*args, **kwargs):
start = time.time()
f(*args, **kwargs)
time_cost = time.time() - start
print("Time cost: %f" % time_cost)
return decorated
if __name__ == '__main__':
@timing
def x():
for i in range(1000000):
f = 12 * 342 +1243
x()
|
def palindrome(x):
rev=x[::-1]
if x==rev:
print("palindrome")
else:
print("Not a palindrome")
palindrome("OYo")
palindrome("dad")
palindrome("work")
palindrome("eye")
palindrome("111")
|
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Dense
from tensorflow.keras import backend as K
class MiniVGGNet:
"""
MiniVGG network is a substantially smaller architecture than the original VGGNet
VGG networks are characterized by two key components
1. All CONV layers are using only 3x3 filters
2. Stacks up multiple CONV -> RELU layer sets before applying a POOL layer
"""
@staticmethod
def build(width, height, depth, classes):
"""
The method that builds up the CNN architecture
:param width: width of the input images
:param height: height of the input images
:param depth: depth (channels in the image, 3 for RGB images (red, green, blue channels))
:param classes: number of classes to predict
:return:
"""
model = Sequential()
inputShape = (height, width, depth)
# Variable chanDim is set to -1 if the order of the inputShape is (height, width, depth)
# meaning the depth of the channel comes last in the triple
chanDim = -1
if K.image_data_format == "channel_first":
inputShape = (depth, height, width)
# if the channel is first in the triple (depth, height, width) we set chanDim to 1
# Batch normalization layers use the channel dimension in the process, that is why we specficy the order
chanDim = 1
# The first set of CONV -> RELU where after each we apply BN layers to avoid overfitting
# and a POOL -> DO that also help in reducing overfitting and increase the classification accuracy
# First set of CONV -> RELU -> BN use 32 filters each with 3x3 shape
# The consecutive CONV -> RELU -> BN layers allow the network to learn more rich features, which
# is a common practice when training deeper CNNs, before applying POOL layer to reduce the spatial dimensions
# of the input image
# Then we apply POOL layer with a size of 2x2, and since we do not provide explicitly stride, keras asumes 2x2 S
# Finally, a DROPOUT layer with a probabliy of 25%
model.add(Conv2D(32, (3, 3), padding="same", input_shape=inputShape))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(32, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# The second set of CONV -> RELU -> BN layers now learn 64 filters with 3x3 shape
# It is common to increase the number of filters as the spatial input size decreases deeper in the network.
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("relu"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# We add flatten layer to flatten the output of the previous layer
# Then we add the only FC layer (512 nodes) with a RELU activation and a BN
# Further applying a DO layer with p = 0.5
model.add(Flatten())
model.add(Dense(512))
model.add(Activation("relu"))
model.add(BatchNormalization())
model.add(Dropout(0.5))
# Finally a softmax classifier
model.add(Dense(classes))
model.add(Activation("softmax"))
return model
|
import numpy as np
class Perceptron:
def __init__(self, N, alpha=0.1):
"""
The constructor of the perceptron
:param N: number of columns in the feature vector
:param alpha: learning rate (common choices - 0.1, 0.01, 0.001)
"""
# Initializing the weight matrix with random values from a normal ("Gaussian") distribution
# the weight matrix will have N + 1 entries, one for each of the columns + 1 for the bias
# np.sqrt(N) - common technique to scale the weight matrix -> faster convergence
self.W = np.random.randn(N + 1) / np.sqrt(N)
self.alpha = alpha
def step(self, x):
"""
The step acitivation function
:param x: weighted vector
:return: predictions
"""
return 1 if x > 0 else 0
def fit(self, X, y, epochs=10):
"""
This function is used to train our model with the supplied dataset and corresponding target labels
:param X: the training dataset
:param y: the corresponding target labels for each of the data points in the dataset
:param epochs: number of epochs the perceptron should be trained for
"""
# applying the bias trick by adding extra column to each of the data points
X = np.c_[X, np.ones((X.shape[0]))]
for epoch in np.arange(0, epochs):
for (x, target) in zip(X, y):
# applying the step function to the dot product of each of the data point with the weigh matrix
# that gives a prediction
p = self.step(np.dot(x, self.W))
if p != target:
# compute the error
error = p - target
# update the weight matrix
self.W += -self.alpha * error * x
def predict(self, X, addBias=True):
"""
Predicts the class labels for a given set of input data
:param X: the set of data points to be classified
:param addBias: wether a bias should be added to the datapoints
:return: predictions for each of the data points
"""
# we ensure that the input dataset is at least a 2-Dimensional matrix
X = np.atleast_2d(X)
if addBias:
X = np.c_[X, np.ones((X.shape[0]))]
return self.step(np.dot(X, self.W))
|
# Filename: number_game_app.py
# Versions: Python 3
# A simple python programming app that showcases use of:
# - lists
# - loops
# - functions
# - user input
# - importing libraries
# - exceptions
# Features:
# - receives number guess from user, validating if within 1-100
# - tell user if hit or miss by comparing to secret number, give a hint if miss
# - user tries maximum of 5 times
# - user decides if wants to play a new game
import random
min = 1
max = 100
def show_hint(higher):
if higher:
print("Uh-oh. The secret number is something higher than that.")
else:
print("Uh-oh. The secret number is something lower than that.")
def new_game():
secret_number = random.randint(min,max)
tries = 1
while 5 >= tries:
guess = input("Give me a number from {}-{}: ".format(min,max))
try:
guess = int(guess)
except ValueError:
print("Oops.. {} is not a number. Please choose a number from {} to {}".format(guess,min,max))
continue
if secret_number == guess:
print("Lucky man! You got it! Secret number is indeed: {}".format(secret_number))
break
elif (guess > max) or (guess < 1):
print("Oops.. {} is not in range. Please choose a number from {} to {}".format(guess,min,max))
continue
if tries == 5:
print("Oh snap! You ran out of tries!")
print("The secret number was: {}".format(secret_number))
break
show_hint(secret_number > guess)
print("You have {} more tries".format(5 - tries))
tries += 1
while True:
new_game()
if (input("Start a new game? [Y for new game, any other character to exit]") != "Y"):
print("Bye now!")
break
|
import os
from quiz import Quiz
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def welcome():
name = input("Please enter your name: ")
clear_screen()
print("Hi {}! Welcome to Timed Math Quiz App Version 2!".format(name))
print("This game will measure how fast and accurate you can solve basic Math problems.")
input("Press ENTER to continue...")
def get_quiz_preference():
clear_screen()
try:
question_count = int(input("How many Math questions do you like to answer? "))
except ValueError:
print("Invalid value is given. Default value will be used. ")
question_count = 0
try:
max_number = int(input("What is the highest number you want to solve? "))
except ValueError:
print("Invalid value is given. Default will be used. ")
max_number = 0
return question_count, max_number
def play_quiz():
play = True
while play:
question_count, max_number = get_quiz_preference()
new_quiz = Quiz(0,0)
if (not question_count) and (not max_number):
new_quiz = Quiz()
elif question_count and max_number:
new_quiz = Quiz(question_count=question_count, max_num=max_number)
else:
new_quiz = Quiz(question_count=question_count) if question_count else Quiz(max_num=max_number)
new_quiz.take_quiz()
if input("Play again? <Enter> to play again, QUIT to exit: ").upper() == "QUIT":
print("Bye now!")
play = False
else:
clear_screen()
clear_screen()
welcome()
play_quiz()
|
# -*- coding: utf-8 -*-
pw=input("請輸入密碼:")
if (pw=="1234"):
print("歡迎光臨")
else :
print("密碼錯誤")
|
#1. Fibonacci series using Generators
def generateFibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, (a+b)
f = generateFibonacci()
counter = 0
for x in f:
print(x, " ")
counter +=1
if(counter > 10):
break
#2. Another implementation
def fib(a=0, b=1):
while True:
yield a
a, b = b, a + b
from itertools import islice
list(islice(fib(),10))
|
number=int(input('enter your number'))
if number==1:
print(' jan31 days')
elif number==2:
print('feb 28 days')
elif number==3:
print('march 31 days')
elif number==4:
print('april 30 days')
elif number==5:
print('may 31 days')
elif number==6:
print('june 30 days')
elif number==7:
print('july 31 dayd')
elif number==8:
print('august 31 days')
elif number==9:
print('sep 30 days')
elif number==10:
print('oct 31 days')
elif number==11:
print('nov 30 days')
elif number==12:
print('dec 31 days')
else:
print('nothing')
|
a=int(input('enter the age'))
b=int(input('enter the age'))
c=int(input('enter the age'))
if a>b and a>c:
print('a bda h ')
elif b>a and b>c:
print('b chota hai a se')
elif c>a and c>b:
print("c bada hai")
else:
print("brabr hai")
|
class DecisionTreeClassifier:
"""
Manual implementation of a Decision Tree Classifier
for numeric and/or ranked data, using the metric of gini impurity.
See example.py for sample implementation code.
Instantiation Parameters
----------
max_depth: int, default = None
Similar to the sklearn implementation, max_depth provides a parameter
to prevent the tree from overfitting. It is the maximum depth of the tree.
min_samples_split: int, default = 2
Similar to the sklearn implementation, min_samples_split provides the
minimum number of observations in a given leaf in order for
the leaf to split and become a parent node.
Methods
----------
.fit
Use the fit method to create a Decision Tree Classifier on a given dataset.
Data must be in the format of a list of lists,
and include target values as the far value of each row of the dataset.
.predict
Use the predict method to generate predictions after fitting a tree.
.accuracy
Use the accuracy method to calculate the accuracy of your predictions.
This method automatically calls the predict method, and can be used
independently after a tree is fit.
"""
def __init__(self, max_depth=None, min_samples_split=2):
self.max_depth = max_depth
self.min_samples_split = min_samples_split
def gini_impurity(self, groups, classes):
"""
Calculates the Gini impurity for a given potential data split
"""
# find number of observations at a given point
n_instances = float(sum([len(group) for group in groups]))
# find weighted Gini impurity for each
gini = 0.0
for group in groups:
size = float(len(group))
# eliminate possibility of divide by zero error
if size == 0:
continue
score = 0.0
# find score for group based on score for each class
for class_val in classes:
p = [row[-1] for row in group].count(class_val) / size
score += p * p
# weight the group's score based on size
gini += (1.0 - score) * (size / n_instances)
return gini
def find_split(self, index, value, dataset):
"""
Sort data at a given split point based on proposed split value.
"""
left, right = [], []
for row in dataset:
if row[index] < value:
left.append(row)
else:
right.append(row)
return left, right
def evaluate_split(self, dataframe):
"""
Evaluate potential splits to return the split with the best resulting
improvements in Gini impurity score.
"""
class_values = list(set(row[-1] for row in dataframe))
b_index, b_value, b_score, b_groups = 999, 999, 999, None
for index in range(len(dataframe[0])-1):
for row in dataframe:
groups = self.find_split(index, row[index], dataframe)
gini = self.gini_impurity(groups, class_values)
if gini < b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
return {'index': b_index, 'value': b_value, 'groups': b_groups}
def to_leaf(self, group):
"""
Creates a leaf node.
"""
outcomes = [row[-1] for row in group]
return max(set(outcomes), key=outcomes.count)
def split(self, node, depth):
"""
Generate data splits based on given node.
"""
left, right = node['groups']
del(node['groups'])
if not left or not right:
node['left'] = node['right'] = self.to_leaf(left + right)
return
# check if beyond max depth
if self.max_depth:
if depth >= self.max_depth:
node['left'], node['right'] = self.to_leaf(left), self.to_leaf(right)
return
# process left child
if len(left) < self.min_samples_split:
node['left'] = self.to_leaf(left)
else:
node['left'] = self.evaluate_split(left)
self.split(node['left'], depth+1)
# process right child
if len(right) < self.min_samples_split:
node['right'] = self.to_leaf(right)
else:
node['right'] = self.evaluate_split(right)
self.split(node['right'], depth+1)
def fit(self, train):
"""
Builds a decision tree based on input of training data.
"""
root = self.evaluate_split(train)
self.split(root, 1)
return root
def predict(self, node, row):
"""
Makes a prediction for new data from a trained tree.
"""
if row[node['index']] < node['value']:
if isinstance(node['left'], dict):
return self.predict(node['left'], row)
else:
return node['left']
else:
if isinstance(node['right'], dict):
return self.predict(node['right'], row)
else:
return node['right']
def accuracy(self, node, dataset):
"""
Generates an accuracy score by comparing expected versus actual
predictions of classifications.
"""
expected = []
predictions = []
for row in dataset:
expect = row[-1]
expected.append(expect)
prediction = self.predict(node, row)
predictions.append(prediction)
# Find the number of correct predictions
num_correct = sum(1 for x, y in zip(expected, predictions) if x == y)
# Calculate accuracy
accuracy = num_correct/len(expected)
return accuracy
|
import random
from words import words
import string
def get_valid_word(words):
word = random.choice(words)
while '-' in words or ' ' in word:
word = random.choice(words)
return word
def hangman():
word = get_valid_word(words)
word_letters = set(word)
alphabet = set(string.ascii_uppercase)
used_letters = set()
lives = 6
while len(word_letters)!=0 and lives>0:
# #lives completed
# if lives==0:
# print('All lives used .Restart the game!!!')
# break;
#letters already used
print('You have already used these letters: ',' '.join(used_letters))
#what the current word is
word_list = [letter if letter in used_letters else '-' for letter in word]
print('Current Word: ',' '.join(word_list))
#getting input
user_letter = input("Guess a letter: ").upper()
if user_letter in alphabet-used_letters:
used_letters.add(user_letter)
if user_letter in word_letters:
word_letters.remove(user_letter)
else:
lives = lives - 1
print(f'You have guessed the wrong letter!.Lives Remaining {lives}')
elif user_letter in used_letters:
print('You have already used that character. Please Try Again!')
else:
print('Invalid cahracter! PLease try again!!')
if lives==0:
print(f"Sorry!! all your lives are over!! The word was {word}")
else:
print("Yay! You guessed the word correctly!!")
hangman()
|
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def add(num1,num2):
return (num1+num2)
>>> add(3,5)
8
>>> add.__doc__
>>> def try(n1):
SyntaxError: invalid syntax
>>> def trytry(n1):
'wendang'
#zhushi
return (n1)
>>> trytry('ajgf')
'ajgf'
>>> trytry.__doc__
'wendang'
>>> help(trytry)
Help on function trytry in module __main__:
trytry(n1)
wendang
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>> def test(*params):
print('长度:', len(params))
print ('first:',params[0])
>>> test(1,2,3,4,5)
长度: 5
first: 1
>>> def test1(name, *params):
print(name)
print('长度:', len(params))
print ('first:',params[0])
>>> test1(wo, 1, 2, 3, 4)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
test1(wo, 1, 2, 3, 4)
NameError: name 'wo' is not defined
>>> test1('wo', 1, 2, 3, 4)
wo
长度: 4
first: 1
>>> def test1(*params, name):
print(name)
print('长度:', len(params))
print ('first:',params[0])
>>> test1(1, 2, 3, 4, name='wo')
wo
长度: 4
first: 1
>>> def test2(*params, name):
print(name)
print('长度:', len(params))
print ('first:',params[0])
>>> test2(1, 2, 3, 4, name='wo')
wo
长度: 4
first: 1
>>> test2(1, 2, 3, 4, 'wo')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
test2(1, 2, 3, 4, 'wo')
TypeError: test2() missing 1 required keyword-only argument: 'name'
>>> def test2(*params, name):
print(name)
print('长度:', len(params), end=' ')
print ('first:',params[0])
>>> test2(1, 2, 3, 4, name='wo')
wo
长度: 4 first: 1
>>>
|
#move function
def move(x, source, target):
print("move No.%d from %s to %s" % (x, source, target))
def hanoi(x, source, temp, target):
if x == 1:
move(x, source, target)
else:
hanoi(x-1, source, target, temp)
move(x, source, target)
hanoi(x-1, source, temp, target)
if __name__ == '__main__':
x = int(input('please input number of plate: \n'))
source = 'A'
temp = 'B'
target = 'Z'
hanoi(x, 'A', 'B', 'C')
|
name = input ("enter the string :")
alist = list(name)
alist.reverse()
finalstring = "".join(alist)
print(finalstring)
|
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict()
self.terminating = False
class Trie:
def __init__(self, K):
self.root = TrieNode()
self.K = K
def get_index(self, ch):
return ord(ch) - ord('a')
def insert(self, word):
root = self.root
len1 = len(word)
for i in range(len1):
index = self.get_index(word[i])
if index not in root.children:
root.children[index] = self.TrieNode()
root = root.children.get(index)
root.terminating = True
def find_scores(self):
root = self.root
for i in self.root.children:
if(i.size() > self.K):
root = root.children
if not root:
return False
root = root.children.get(index)
return root if root and root.terminating else None
|
"""A simple bookkeeping module"""
# Written in Python 3
import sqlite3
import os
import datetime
class Book:
"""A book for bookkeeping"""
def __init__(self, database_name):
"""Open an existing book.
Each instance has its own connection to the database. The connection
will be shared and used among methods of the instance.
"""
if os.path.exists(database_name):
self.conn = sqlite3.connect(database_name)
self.conn.row_factory = sqlite3.Row
self.conn.execute('PRAGMA foreign_keys = ON')
else:
raise FileNotFoundError
@classmethod
def new(cls, database_name):
"""Create a new book.
Create a new blank book by initializing an empty database. Return an
instance of the newly created book.
"""
if os.path.exists(database_name):
raise FileExistsError
else:
conn = sqlite3.connect(database_name)
with conn:
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
type_id INTEGER NOT NULL,
description TEXT,
hidden INTEGER NOT NULL,
FOREIGN KEY (type_id) REFERENCES account_types(id)
);''')
c.execute('''CREATE TABLE IF NOT EXISTS account_types(
id INTEGER PRIMARY KEY,
type TEXT UNIQUE NOT NULL
);''')
c.executemany('''INSERT INTO account_types (type) VALUES (?);''',
[('ASSET',), ('LIABILITY',), ('EQUITY',), ('INCOME',), ('EXPENSE',)])
c.execute('''CREATE TABLE IF NOT EXISTS transactions(
id INTEGER PRIMARY KEY,
date DATE NOT NULL,
description TEXT
);''')
c.execute('''CREATE TABLE IF NOT EXISTS splits(
id INTEGER PRIMARY KEY,
transaction_id INTEGER NOT NULL,
account_id INTEGER NOT NULL,
amount REAL NOT NULL,
description TEXT,
FOREIGN KEY (transaction_id) REFERENCES transactions(id),
FOREIGN KEY (account_id) REFERENCES accounts(id)
);''')
return cls(database_name)
#
# Account
#
# account_detail is a dict with the following key:
# name -- the name string of the account,
# type_id -- the id of the account type,
# description -- optional text description of the account,
# hidden -- boolean value representing whether account will be hidden.
#
# Account type falls into one of the basic types:
# ASSET -- with type_id 1,
# LIABILITY -- with type_id 2,
# EQUITY -- with type_id 3,
# INCOME -- with type_id 4, or
# EXPENSE -- with type_id 5.
#
def insert_account(self, account_detail):
"""Insert a new account with the provided account detail."""
name = account_detail['name']
type_id = account_detail['type_id']
if 'description' not in account_detail:
description = ''
if 'hidden' not in account_detail:
hidden = False
with self.conn:
c = self.conn.cursor()
c.execute(
'INSERT INTO accounts (name, type_id, description, hidden) VALUES (?,?,?,?);',
(name, type_id, description, hidden)
)
def update_account(self, account_id, account_detail):
"""Update the account detail of the given account id."""
with self.conn:
c = self.conn.cursor()
for key, value in account_detail.items():
if key in ['name', 'type_id', 'description', 'hidden']:
c.execute('UPDATE accounts SET %s=? WHERE id=?;' % key, (value, account_id))
def delete_account(self, account_id, move_to_id = 0):
"""Delete the specified account.
Delete the account with specified account id. If there are not existing
transactions related to the account, delete the account directly. If
there are transactions related to the account, one can specify another
account that substitute the to-be-deleted account using move_to_id
argument. If move_to_id is set to 0 (also as default value), all
transactions related to the account will be deleted."""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT COUNT(*) FROM splits WHERE account_id=?', (account_id,))
if c.fetchone()['COUNT(*)']:
if move_to_id:
c.execute('SELECT * FROM splits')
c.execute('UPDATE splits SET account_id=? WHERE account_id=?',
(move_to_id, account_id))
else:
c.execute('SELECT transaction_id FROM splits WHERE account_id=?',
(account_id,))
for row in c.fetchall():
self.delete_transaction(row['transaction_id'])
for row in c.fetchall():
print(row['transaction_id'], row[2], row[3], row[4])
c.execute('DELETE FROM accounts WHERE id=?', (account_id,))
def account_detail_by_id(self, account_id):
"""Return the account detail of the given id.
The returned account detail is a python dict.
"""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT * FROM accounts WHERE id=?', (account_id,))
cols = ['account_id', 'name', 'type_id', 'description', 'hidden']
account = dict(zip(cols, c.fetchone()))
return account
def account_type_id(self, account_type):
"""Return the type id of the account type name."""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT (id) FROM account_types WHERE type=?', (account_type,))
return c.fetchone()['id']
def account_ids(self):
"""Generator function of account ids"""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT id FROM accounts')
for row in c.fetchall():
yield row['id']
def account_ids_list(self):
"""Return a list of account id"""
return [i for i in self.account_ids()]
def account_balance(self, account_id):
with self.conn:
c = self.conn.cursor()
c.execute('SELECT SUM(amount) FROM splits WHERE account_id=?', (account_id,))
return c.fetchone()['SUM(amount)']
#
# Transaction
#
# Each transaction is a dict consists of
# date -- a date, which would be default to today,
# splits -- list of at least two splits which balance, and
# description -- an optional description.
#
# Each split has
# account_id -- the affected account id,
# amount -- the amount taking effect,
# which is either Dr. or Cr.,
# represented by positive or negative amount respectively, and
# description -- an optional description.
def insert_transaction(self, transaction_detail):
"""Insert a new transaction."""
with self.conn:
c = self.conn.cursor()
if 'date' not in transaction_detail:
transaction_detail['date'] = datetime.date.today()
if 'description' not in transaction_detail:
transaction_detail['description'] = ''
Book.check_split_sum(transaction_detail['splits'])
c.execute('INSERT INTO transactions (date, description) VALUES (?, ?)',
(transaction_detail['date'], transaction_detail['description'])
)
transaction_id = c.lastrowid
self.write_splits(transaction_id, transaction_detail['splits'])
def update_transaction(self, transaction_id, transaction_detail):
"""Update the transaction with the specified id.
Update the transaction detail and overwrite the splits of the
transaction.
"""
with self.conn:
c = self.conn.cursor()
for key, value in transaction_detail.items():
if key in ['date', 'description']:
c.execute('UPDATE transactions SET %s=? WHERE id=?' % key,
(value, transaction_id))
elif key == 'splits':
Book.check_split_sum(value)
self.write_splits(transaction_id, value)
def delete_transaction(self, transaction_id):
"""Delete the specified transaction."""
with self.conn:
c = self.conn.cursor()
c.execute('DELETE FROM splits WHERE transaction_id=?', (transaction_id,))
c.execute('DELETE FROM transactions WHERE id=?', (transaction_id,))
def transaction_detail_by_id(self, transaction_id):
"""Return the transaction detail with the specified id.
The transaction detail returned is a python dict.
"""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT * FROM transactions WHERE id=?', (transaction_id,))
transaction_detail = {}
row = c.fetchone()
transaction_detail['date'] = row['date']
transaction_detail['description'] = row['description']
transaction_detail['splits'] = []
c.execute('SELECT * FROM splits WHERE transaction_id=?', (transaction_id,))
for row in c.fetchall():
split = {
'account_id': row['account_id'],
'amount': row['amount'],
'description': row['description'],
}
transaction_detail['splits'].append(split)
return transaction_detail
def transaction_ids(self):
"""Generator function of transaction ids"""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT id FROM transactions')
for row in c.fetchall():
yield row['id']
def transaction_ids_list(self):
"""Return a list of transaction id"""
return [i for i in self.transaction_ids()]
def transaction_ids_between_date(self, start_date, end_date):
"""Generator function yielding transaction ids between dates
Both start_date and end_date are inclusive. Both start_date and
end_date are strings and follow the format "YYYY-MM-DD".
"""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT id FROM transactions WHERE date BETWEEN ? AND ?',
(start_date, end_date))
for row in c.fetchall():
yield row['id']
@staticmethod
def check_split_sum(splits):
"""Check whether the splits are balanced.
The total amount of debit, represented as positive, and credit,
represented as negative, for each transaction should be the same and
therefore should sums up to zero.
"""
if sum(split['amount'] for split in splits) != 0:
raise ValueError('Total debit and credit amount should balance')
def write_splits(self, transaction_id, splits):
"""Overwrite all existing splits related to the specified transaction."""
with self.conn:
c = self.conn.cursor()
c.execute('SELECT COUNT(*) FROM splits WHERE transaction_id=?', (transaction_id,))
if c.fetchone()['COUNT(*)']:
c.execute('DELETE FROM splits WHERE transaction_id=?', (transaction_id,))
for split in splits:
if 'description' not in split:
split['description'] = ''
c.execute(
'INSERT INTO splits (transaction_id, account_id, amount, description) VALUES (?, ?, ?, ?)',
(transaction_id, split['account_id'], split['amount'], split['description'])
)
|
# 6. В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
# Сами минимальный и максимальный элементы в сумму не включать.
from random import randint
max_, max_i = 0, 0
min_, min_i = 100, 0
arr = [randint(max_, min_) for _ in range(10)]
print(arr)
for i in range(len(arr)):
if arr[i] > max_:
max_ = arr[i]
max_i = i
if arr[i] < min_:
min_ = arr[i]
min_i = i
a, b = None, None
if max_i < min_i:
a = max_i
b = min_i
else:
a = min_i
b = max_i
sum_ = 0
for i in arr[a + 1: b]:
sum_ += i
print(f'max number in index {max_i}, min number in index {min_i}, sum between them: {sum_}')
|
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
from random import randint
max_, max_i = 0, 0
min_, min_i = 100, 0
arr = [randint(max_, min_) for _ in range(10)]
print(arr)
for i in range(len(arr)):
if arr[i] > max_:
max_ = arr[i]
max_i = i
if arr[i] < min_:
min_ = arr[i]
min_i = i
arr[min_i], arr[max_i] = max_, min_
print(arr)
|
# https://programmers.co.kr/learn/courses/30/lessons/17679?language=python3
def gravity(n, m, board):
for y in range(m):
temp = []
for x in range(n):
if board[x][y] != ' ':
temp.append(board[x][y])
board[x][y] = ' '
for x in range(len(temp)):
board[n-x-1][y] = temp[-(x+1)]
def solution(n, m, board):
for i in range(len(board)):
board[i] = list(board[i])
ans = 0
while True:
visit = [[0]*m for _ in range(n)]
removed = False
for i in range(n-1):
for j in range(m-1):
if board[i][j] == board[i][j+1] == board[i+1][j] == board[i+1][j+1] != ' ':
visit[i][j] = visit[i][j+1] = visit[i+1][j] = visit[i+1][j+1] = 1
removed = True
if not removed: return ans
for i in range(n):
for j in range(m):
if visit[i][j]:
board[i][j] = ' '
ans += 1
gravity(n, m, board)
|
# https://www.acmicpc.net/problem/1406
# linked list로 풀 수도 있음, 근데 스택 두개로도 풀 수 있음
# 왼쪽 스택, 오른쪽 스택 사이에 커서 있다고 생각하면 됨
# 커서에 따라서 왼쪽, 오른쪽으로 옮기고 마지막 출력은 (왼쪽 스택) + (오른쪽 스택역순)
from sys import*
input = lambda: stdin.readline().strip()
a = input()
left, right = [], []
for i in range(len(a)):
left.append(a[i])
for i in range(int(input())):
commands = list(map(str, input().split()))
if commands[0] == 'L':
if left:
right.append(left.pop())
elif commands[0] == 'D':
if right:
left.append(right.pop())
elif commands[0] == 'B':
if left:
left.pop()
elif commands[0] == 'P':
left.append(commands[1])
print("".join(left) + "".join(right[::-1]))
|
#https://www.acmicpc.net/problem/1918
# 후위 표기식2 문제에 괄호가 추가됨
# 피연산자는 출력(or 문자열 추가)
# 연산자는 우선순위에 따라 처리(스택 빌 때까지 or 스택 맨 위에 있는게 더 우선순위가 낮은거 일때까지 꺼냄)
# 괄호 => 짝궁 괄호 나올 때까지
stack = []
string = input()
priority = {'(':2, '*':1, '/':1, '+':0, '-':0}
res = ''
for i in range(len(string)):
#피연산자면 출력
if 'A' <= string[i] <= 'Z' or 'a' <= string[i] <= 'z': res += string[i]
#닫힌 괄호면 열린거(짝꿍) 나올때까지 출력
elif string[i] == ')':
while stack:
top = stack.pop()
if top == '(':
break
else:
res += top
#나머지 연산자들 나왔을때
else: #연산자:: *, /, +, -, (
while stack:
if priority[stack[-1]] < priority[string[i]] or stack[-1] == '(':
break
else:
res += stack.pop()
stack.append(string[i])
#스택에 남은 연산자들 출력
while stack:
res += stack.pop()
print(res)
|
# https://programmers.co.kr/learn/courses/30/lessons/72412
class Node:
def __init__(self):
self.child = {}
class Trie:
def __init__(self):
self.root = Node()
def insert(self, node, pos, info):
if pos == len(info) - 1:
if 'score' not in node.child:
node.child['score'] = []
node.child['score'].append(int(info[pos]))
return
if info[pos] not in node.child:
node.child[info[pos]] = Node()
self.insert(node.child[info[pos]], pos+1, info)
if '-' not in node.child:
node.child['-'] = Node()
self.insert(node.child['-'], pos+1, info)
def sort_score(self, node):
if not node: return
for k, v in node.child.items():
if k == 'score':
v.sort()
else:
self.sort_score(v)
def search(self, node, pos, info):
if pos == len(info) - 1:
return self.binary_search(node.child['score'], int(info[pos]))
if info[pos] not in node.child: return 0
return self.search(node.child[info[pos]], pos+1, info)
def binary_search(self, arr, target):
l, r = 0, len(arr)-1
while l <= r:
m = (l + r) // 2
if arr[m] < target:
l = m + 1
else:
r = m - 1
return len(arr) - l
def solution(info, query):
trie = Trie()
for x in info:
trie.insert(trie.root, 0, list(x.split()))
trie.sort_score(trie.root)
answer = []
for x in query:
answer.append(trie.search(trie.root, 0, x.replace('and', '').split()))
return answer
print(solution(["java backend junior pizza 150", "python frontend senior chicken 210", "python frontend senior chicken 150", "cpp backend senior pizza 260", "java backend junior chicken 80", "python backend senior chicken 50"], ["java and backend and junior and pizza 100", "python and frontend and senior and chicken 200", "cpp and - and senior and pizza 250", "- and backend and senior and - 150", "- and - and - and chicken 100", "- and - and - and - 150"]))
|
# 트라이는 문제 풀면서 적용하기
# https://www.acmicpc.net/problem/5052
from sys import*
input = lambda: stdin.readline().strip()
class Node:
def __init__(self):
self.child = {}
self.end = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, string):
node = self.root
for i, char in enumerate(string):
if i == len(string) - 1:
# 마지막인데 더 내려갈 수 있음(앞에서 이미 이 경로를 따라간 더 긴게 나왔음, 즉 이 단어는 접두어가 됨)
if char in node.child: return False
# 다음 갈 문자 없으면 노드 생성해줌
if char not in node.child: node.child[char] = Node()
# 다음 노드로
node = node.child[char]
# 아직 이 단어 다 확인 안했는데 end가 있으면 지금 단어보다 더 짧은 접두어가 있음
if node.end: return False
node.end = True
return True
if __name__ == "__main__":
for tc in range(int(input())):
trie = Trie()
isCorrect = True
for i in range(int(input())):
string = input()
# 이미 False면 볼 필요 없음
if not isCorrect: continue
if not trie.insert(string): isCorrect = False
if isCorrect: print("YES")
else: print("NO")
|
def hanoi(cnt, a, b, c): #from by to
if cnt == 1:
print(a, c)
return
hanoi(cnt-1, a, c, b)
print(a, c)
hanoi(cnt-1, b, a, c)
return
n=int(input())
res = 0
for i in range(n):
res += (1 << i)
print(res)
if n <= 20: hanoi(n, 1, 2, 3)
|
# https://www.acmicpc.net/problem/2309
# 7개 고르는데 100이 되는 수
def solve(pos, cnt, total):
# 데이터 약해서 가지치기 안해도 됨, 대신 2798 블랙잭은 해야함
# if cnt > 7 or total > 100: return
if pos == 9:
if cnt == 7 and total == 100:
picked.sort()
for p in picked:
print(p)
exit()
return
picked.append(heights[pos])
solve(pos+1, cnt+1, total+heights[pos])
picked.pop()
solve(pos+1, cnt, total)
heights = []
picked = []
for i in range(9):
heights.append(int(input()))
solve(0, 0, 0)
|
# 양방향으로 만들어볼까
# 삽입 기본은 맨 뒤에, 삽입할 곳 파라미터 주어지면 그 원소 찾아서 삽입하는 오버로딩 함수 만들면 될듯
# 삭제는 찾아서 삭제하도록?
# 그럼 head, tail로 처음과 끝 표시해두자
# 근데 원래 이렇게 복잡함? 예외처리 따로 해주지말고 tail None으로 처리하면 편하려나?
class Node:
def __init__(self, data):
self.data = data
self.prev = self.next = None
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = self.tail = None
self.size = 0
def isEmpty(self):
return False if self.getSize() else True
def getSize(self):
return self.size
# 파이썬 함수 오버로딩 제공 안해준대! argument 여러개 받는식으로 해결
def insert(self, *args):
self.size += 1
if len(args) == 1: self._insert(*args)
else:
self.head = self.searchInsert(self.head, *args)
def _insert(self, data):
if self.head is None:
newNode = Node(data)
self.head = newNode
self.tail = newNode
else:
newNode = Node(data)
newNode.prev = self.tail
self.tail.next = newNode
self.tail = newNode
def searchInsert(self, node, data, searchData):
# 마지막 노드면 그냥 삽입
if node is self.tail:
newNode = Node(data)
newNode.prev = self.tail
self.tail.next = newNode
self.tail = self.tail.next
return node
# 중간에 삽입하는 거면 잘 연결해줌
if node.data == searchData:
newNode = Node(data)
node.next.prev = newNode
newNode.next = node.next
newNode.prev = node
node.next = newNode
return node
node.next = self.searchInsert(node.next, data, searchData)
return node
def delete(self, searchData):
self.head, deletedNode = self._delete(self.head, searchData)
if deletedNode is not None: self.size -= 1
return deletedNode
def _delete(self, node, searchData):
deletedNode = None
if node is None: return node, deletedNode
if node.data == searchData:
deletedNode = node
# head면
if node == self.head:
if self.getSize() == 1:
self.head = self.tail = None
else:
self.head = node.next
return node.next, deletedNode
# tail이면
if node == self.tail:
self.tail = node.prev
return None, deletedNode
# 중간이면
node.prev.next = node.next
node.next.prev = node.prev
return node.next, deletedNode
node.next, deletedNode = self._delete(node.next, searchData)
return node, deletedNode
def list(self):
def _list(node):
if node is None: return
print(node, end=' ')
_list(node.next)
_list(self.head)
print()
if __name__ == "__main__":
linkedList = LinkedList()
for x in [3, 4, 5, 6, 7]:
linkedList.insert(x)
linkedList.list()
linkedList.insert(9, 3)
linkedList.insert(10, 7)
linkedList.insert(11, 5)
linkedList.list()
for x in [3, 10, 5, 5]:
print(linkedList.delete(x))
linkedList.list()
for x in [9, 4, 11, 6, 7]:
print(linkedList.delete(x))
linkedList.list()
print(linkedList.head, linkedList.tail)
|
# https://www.acmicpc.net/problem/17143
# pypy3 제출
# 큐에 상어 정보 넣고 dic로 체크하면서 상어 정보 채워넣는 식으로 짜면 될듯?
# 잡는건?? 2차원 board 하나 만들어야 할듯
from sys import*
from collections import*
input = stdin.readline
def changeDirection(d):
if d==U: return D
if d==R: return L
if d==L: return R
if d==D: return U
U, R, D, L = (-1, 0), (0, 1), (1, 0), (0, -1)
directions = [U, D, R, L]
n, m, k = map(int, input().split())
sharks = {}
q = deque()
fishingList = []
fisher = 1
for i in range(k):
x, y, speed, d, size = map(int,input().split())
q.append((x, y, speed, directions[d-1], size))
if y==fisher: fishingList.append((x, y, size))
res = 0
for i in range(m):
died = (-1, -1)
if fishingList:
fishingList.sort(key = lambda x:x[0])
x, y, size = fishingList[0]
died = (x, y)
res += size
sharks = {}
fishingList = []
fisher += 1
if not q: break
while q:
x, y, speed, d, size = q.popleft()
if died == (x, y): continue
dx, dy = d
for _ in range(speed):
x, y = x+dx, y+dy
if x<1 or y<1 or x>n or y>m:
d = changeDirection(d)
dx, dy = d
x, y = x+(2*dx), y+(2*dy)
if (x, y) not in sharks:
sharks[(x, y)] = (speed, d, size)
elif sharks[(x, y)][2] < size:
sharks[(x, y)] = (speed, d, size)
for (x, y), (speed, d, size) in sharks.items():
q.append((x, y, speed, d, size))
if y==fisher: fishingList.append((x, y, size))
print(res)
|
t = int(input())
if t <= 10:
print("Arthur")
if 10 < t <= 30:
print("Luiz")
if 30 < t <= 100:
print("Pedro")
if t > 100:
print("Nenhum")
|
'''
Daily Algorithm Coding
2021. 03. 30.
Dijkstra Algorithm
'''
import heapq
INF = 999
n, m = map(int, input().split())
distance = [INF]*(n+1)
visited = [False]*(n+1)
start = int(input())
graph = [[] for i in range(n+1)]
for i in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
print("\ninput data test")
print("n, m, start : %d, %d, %d"%(n, m, start))
print("graph")
for i in range(len(graph)):
print("{} : {}".format(i, graph[i]))
print("{} : {}".format('distance', distance))
print("{} : {}\n".format('visited', visited))
def get_smallest_node():
min_value = INF
#최소값을 갱신하기 위한 변수 min_value
index = 0
for i in range(1, n+1):
#방문하지 않은 노드 중에서
#거리가 제일 짧은 노드를 구하기 위한 반복문
if distance[i] < min_value and not visited[i]:
#최단 거리 테이블인 distance에서 최소값을 갱신하기 위한 변수 min_value보다 작은 경우
#방문을 하지 않은 경우
min_value = distance[i]
#최소값을 갱신
index = i
#갱신할 때의 index값을 저장
return index #방문하지 않은 노드 중에서 거리가 제일 짧은 노드를 반환
def Dijkstra(start):
distance[start] = 0
visited[start] = True
for i in graph[start]:
distance[i[0]] = i[1]
for x in range(n-1):
now = get_smallest_node()
visited[now] = True
for i in graph[now]:
cost = distance[now] + i[1]
if cost < distance[i[0]]:
distance[i[0]] = cost
Dijkstra(start)
print("After Dijkstra Algorithm")
for i in range(1, len(distance)):
print("{} : {}".format(i, distance[i]))
distance = [INF]*(n+1)
def ImprovedDijkstra(start):
q = []
heapq.heappush(q, (0, start))
distance[start] = 0
visited[start] = True
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for i in graph[now]:
cost = dist + i[1]
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
ImprovedDijkstra(start)
print("\nAfter Improved Dijkstra Algorithm")
for i in range(1, len(distance)):
print("{} : {}".format(i, distance[i]))
''' 입력 예시
6 11
1
1 2 2
1 3 5
1 4 1
2 3 3
2 4 2
3 2 3
3 6 5
4 3 3
4 5 1
5 3 1
5 6 2
'''
|
'''
2021. 06. 05.
Daily Algorithm Coding
DFS/BFS Algorithm
'''
from collections import deque
#basis data
graph = [
#인덱스를 노드, 그 인덱스의 요소가 해당 노드의 인접 노드
#인접 리스트 방식으로 그래프를 표현
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
#DFS : 1 2 7 6 8 3 4 5
#BFS : 1 2 3 8 7 4 5 6
start = 1
#Depth First Search Algorithm Code
visited = [False]*(len(graph))
def DFS(v, graph, visited):
visited[v] = True
print(v, end=' ')
for i in graph[v]:
if visited[i] == False:
DFS(i, graph, visited)
DFS(start, graph, visited)
print()
#Breath First Search Algorithm Code
visited = [False]*(len(graph))
q = deque([start])
visited[start] = True
while q:
v = q.popleft()
print(v, end=' ')
for i in graph[v]:
if visited[i] == False:
q.append(i)
visited[i] = True
print()
|
'''
2021. 04. 26.
Daily Algorithm Coding
topology sort
'''
from collections import deque
node, edge = map(int, input().split())
indegree = [0]*(node+1)
graph = [[] for _ in range(node+1)]
for i in range(edge):
x, y = map(int, input().split())
graph[x].append(y)
indegree[y] += 1
queue = deque()
for i in range(1, node+1):
if indegree[i] == 0: queue.append(i)
while queue:
now = queue.popleft()
print(now, end=' ')
for i in graph[now]:
indegree[i] -= 1
if indegree[i] == 0: queue.append(i)
''' topology sort algorithm input data
7 8
1 2
1 5
2 3
2 6
3 4
4 7
5 6
6 4
node edge
edge data
edge data : start node, end node
'''
|
'''
2021. 04. 23.
Daily Algorithm Coding
Binary Search
'''
arr = [2,4,1,5,3]
def bs(start, end, target, arr):
if start > end: return None
mid = (start+end)//2
if arr[mid] == target:
return mid
if arr[mid] < target:
return bs(mid+1, end, target, arr)
if arr[mid] > target:
return bs(start, mid-1, target, arr)
print(bs(0, len(arr)-1, 6, arr))
|
#Breath First Search
#너비 우선 탐색
from collections import deque
def bfs(graph, start, visited):
queue = deque([start])
#deque 메소드의 인수값으로는 iterable을 받기 때문에
#start라는 인수값 변수를 요소로서 []에 담아서 사용
visited[start] = True
#방문 처리
while queue:
#queue가 빌 때까지
v = queue.popleft()
#가장 먼저 들어온 요소값을 빼서 변수 v에 대입
print(v, end=' ')
for i in graph[v]:
#queue에서 빼서 v에 담은 노드의 인접 노드
if not visited[i]:
#그 노드들 중에서 방문한 적이 없는 노드
queue.append(i)
#queue에 추가
visited[i] = True
#방문 처리
graph = [
#인덱스를 노드, 그 인덱스의 요소가 해당 노드의 인접 노드
#인접 리스트 방식으로 그래프를 표현
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
#BFS : 1 2 3 8 7 4 5 6
visited = [False]*9
bfs(graph, 1, visited)
print()
|
N=int(input()) #입력
count=0
n=0 #각 자리의 숫자를 더한 숫자가 담기는 변수 n
N_list=[] #자리마다 수를 분리하여 담는 리스트
while not 0<=N<=99:
#입력 조건을 충족하는지에 대한 검사
print("입력이 잘못되었습니다. 다시 입력해주세요.")
N=int(input())
finish=N #맨 처음 지정된 숫자
#print() #test
while finish!=N or count==0: #새로운 수가 처음 입력한 수와 같아질 때까지 무한 루프
#각 자리수를 분리하여 N_list 리스트에 담는 과정
N_list=[] #밑의 append를 위해서 N_list를 빈 리스트로 초기화
N_list.append(N//10)
N_list.append(N-N_list[0]*10)
#print(N_list) #test
n=0 #밑의 for문을 위해서 n을 0으로 초기화
for i in N_list: n=n+i #분리한 각 자리의 숫자를 더한 n
#print("분리한 각 자리의 숫자를 더한 값은 %d"%n) #test
N=N_list[1]*10
#십의 자리의 수는 기존의 수의 일의 자리의 수,
N=N+n-n//10*10
#1의 자리의 수는 새로운 수 n의 일의 자리의 수
count=count+1
#print("새로운 수는 %d"%N) #test
#print() #test
print(count)
|
class Restaurant:
def __init__(self, restaurant_type, cuisine_type):
self.restaurant_type = restaurant_type
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f"This is {self.restaurant_type} restaurant and it serves {self.cuisine_type}")
def open_restaurant(self):
print(f"Restaurant is open")
restaurant = Restaurant("Indian", "Vegeterian Foods")
restaurant.describe_restaurant()
restaurant.open_restaurant()
|
friends = ['Amit', 'Ranjan', 'Jack', 'Paula', 'Mukesh']
print(friends[0])
print(friends[1])
print(friends[2])
print(friends[3])
print(friends[4])
print(f"Good Morning, {friends[0]}")
print(f"Good Morning, {friends[1]}")
print(f"Good Morning, {friends[2]}")
print(f"Good Morning, {friends[3]}")
print(f"Good Morning, {friends[4]}")
|
""" A class that models real world cars """
class Car:
""" A simple attempt to represent a car"""
def __init__(self, name, model, year):
self.name = name
self.model = model
self.year = year
self.odometer_reading = 0
def describe_car(self):
car = f"{self.name} {self.model} {self.year} {self.odometer_reading}"
return car
def update_odometer(self, new_odometer_reading):
if self.odometer_reading > new_odometer_reading:
print("Sorry, you can't roll back existig readings")
else:
self.odometer_reading = new_odometer_reading
def increment_odometer_reading(self, increment_mileage):
self.odometer_reading += increment_mileage
def fill_gas_tank(self):
print("Gas tank filled")
""" A real world car battery """
class Battery:
"""A Simple attempt to model a battery"""
def __init__(self, battery_power=75):
self.battery_power = battery_power
def describe_battery(self):
print(f"This car has a battery of {self.battery_power} KWh")
""" A real world Electric Car"""
class ElectricCar(Car):
""" A simple attempt to model an electric car """
def __init__(self, name, model, year):
super().__init__(name, model, year)
#self.battery_power = 75
self.battery = Battery()
def describe_battery(self):
print(f"{self.name} has battery of {self.battery.battery_power} KWh")
def fill_gas_tank(self):
print(f"{self.name} is an electric car and it does not have a gas tank")
|
FavGames = []
def add_game(game):
FavGames.append(game)
def print_fav_games():
for game in FavGames:
print(game)
def read_file():
file = open("AllFavouriteGames", "r")
for game in file:
add_game(game)
file.close()
def save_file():
file = open("AllFavouriteGames", "w")
file.write(str(FavGames))
file.close()
read_file()
print("Your Favourite Games are: " + str(FavGames))
AddAnotherGame = input("\nWould you like to add a new game?\n")
if AddAnotherGame[0] == "Y":
AddAnotherGame = True
while AddAnotherGame:
NewGameTitle = input("What is the name of your game?\n")
NewGameRating = input("On a scale from 1 to 10, how would you rate the game?\n")
NewGameGenre = input("Finally, what is the genre of the game?\n")
add_game({NewGameTitle, NewGameRating, NewGameGenre})
print_fav_games();
FinalChoice = input("Would you like to add another?")
if FinalChoice[0] == "N":
print("Thanks for your contribution(s)")
save_file()
break
|
import re
import urllib2
import oauth2 as oauth
import json
headers = {}
headers["Accept"] = "application/vnd.github.preview"
url = "https://api.github.com/search/users?q=language:java&"
#request = urllib2.Request(url, headers=headers)
#response = urllib2.urlopen(request)
#results = response.read()
# Create our client.
consumer = oauth.Consumer(key="230", secret="a6a2da87d995e56665de9a2de8e70960d1db2340")
client = oauth.Client(consumer)
# The OAuth Client request works just like httplib2 for the most part.
with open("github.users.out",'w') as f:
for i in range(0,200):
resp, content = client.request("https://api.github.com/search/users?q=language:java&per_page=100&page="+str(i), "GET", headers=headers)
json_data = json.loads(content)
for item in json_data['items']:
f.write(json.dumps(item) + ",\n")
|
#冒泡排序,第一次排序进行n-1次,如果顺序不对,则调换
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i],alist[i+1] = alist[i+1],alist[i]
return alist
aList=[54,56,85,91,20,3,26,59,22,30,20,20,20]
print(bubbleSort(aList))
|
#优化冒泡排序,提前结束运行
def shortBubbleSort(alist):
passnum = len(alist) - 1
exchange = True
while passnum > 0 and exchange:
exchange = False
for i in range(passnum):
if alist[i] > alist[i+1]:
exchange = True
alist[i],alist[i+1] = alist[i+1],alist[i]
passnum = passnum-1
return alist
aList=[54,56,85,91,20,3,26,59,22,30,20,20,20]
print(shortBubbleSort(aList))
|
import turtle
tina=turtle.Turtle()
tina.shape('turtle')
tina.color('purple')
def triangle():
tina.forward(100)
tina.lt(120)
tina.forward(100)
tina.lt(120)
tina.forward(100)
tina.lt(120)
triangle()
turtle.mainloop()
|
import turtle
tina=turtle.Turtle()
tina.shape("turtle")
colors=["red","orange","yellow","green","blue","purple","black"]
for color in colors:
angle=360/len(colors)
tina.color(color)
tina.circle(40)
tina.circle(20)
tina.rt(angle)
tina.forward(30)
turtle.mainloop()
|
import turtle
def make_circle(turtle,color,size,x,y):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x,y)
turtle.begin_fill()
turtle.pendown()
turtle.circle(size)
turtle.end_fill()
tina=turtle.Turtle()
tina.shape("turtle")
make_circle(tina,"green",100,50,0)
make_circle(tina,"blue",100,0,0)
make_circle(tina,"yellow",100,-50,0)
tina.penup()
tina.color("black")
tina.goto(0,-50)
tina.write("Let's Learn Python!",align="center",font=(None,20,"bold"))
tina.goto(0,-80)
turtle.mainloop()
|
import ps0 #ps0.py file has to be in the same directory as this file
#0
print("\nTesting Program 0.")
print(0 , "is" , ps0.odd_even(0))
print(24 , "is" , ps0.odd_even(24))
print(5 , "is" , ps0.odd_even(5))
#1
print("\nTesting Program 1.")
print("The number of digits in", 43, "is" , ps0.number_digits(43))
print("The number of digits in", 0, "is" , ps0.number_digits(0))
print("The number of digits in", 345, "is" , ps0.number_digits(345))
#2
print("\nTesting Program 2.")
print("The sum of the digits in", 0, "is" , ps0.sum_digits(0))
print("The sum of the digits in", 654, "is" , ps0.sum_digits(654))
print("The sum of the digits in", 21, "is" , ps0.sum_digits(21))
#3
print("\nTesting Program 3.")
print("The sum of integers less than", 3, "is" , ps0.sum_lessthan(3))
print("The sum of integers less than", 57, "is" , ps0.sum_lessthan(57))
print("The sum of integers less than", 0, "is" , ps0.sum_lessthan(0))
#4
print("\nTesting Program 4.")
print("The factorial of ", 0, "is" , ps0.factorial(0))
print("The factorial of ", 1, "is" , ps0.factorial(1))
print("The factorial of ", 5, "is" , ps0.factorial(5))
#5
print("\nTesting Program 5.")
x = 27
y = 3
if ps0.factor(x,y) == True:
print(y, "is a factor of" , x)
else:
print(y , "is not a factor of" , x)
x = 5
y = 3
if ps0.factor(x,y) == True:
print(y, "is a factor of" , x)
else:
print(y , "is not a factor of" , x)
x = 17
y = 3
if ps0.factor(x,y) == True:
print(y, "is a factor of" , x)
else:
print(y , "is not a factor of" , x)
#6
print("\nTesting Program 6.")
x = 2
if ps0.is_Prime(x) == True:
print(x , "is prime")
else:
print(x , "is not prime")
x = 21
if ps0.is_Prime(x) == True:
print(x , "is prime")
else:
print(x , "is not prime")
x = 53
if ps0.is_Prime(x) == True:
print(x , "is prime")
else:
print(x , "is not prime")
#7
print("\nTesting Program 7.")
x = 496
if ps0.is_Perfect(x) == True:
print(x, "is a perfect number")
else:
print(x, "is not a perfect number")
x = 1
if ps0.is_Perfect(x) == True:
print(x, "is a perfect number")
else:
print(x, "is not a perfect number")
#8
print("\nTesting Program 8.")
x = 9
if ps0.divide_by_FactorSum(x) == True:
print("The sum of the digits of ",x, "evenly divides into", x)
else:
print("The sum of the digits of ",x, "does not evenly divide into", x)
x = 13
if ps0.divide_by_FactorSum(x) == True:
print("The sum of the digits of ",x, "evenly divides into", x)
else:
print("The sum of the digits of ",x, "does not evenly divide into", x)
x = 21
if ps0.divide_by_FactorSum(x) == True:
print("The sum of the digits of ",x, "evenly divides into", x)
else:
print("The sum of the digits of ",x, "does not evenly divide into", x)
|
import numpy as np
import matplotlib.pyplot as plt
def cost(X, y, theta):
m = y.shape[0]
return 1/(2*m) * np.sum((X.dot(theta) - y) ** 2)
def gradient_descent(X, y, theta, alpha, iterations):
m = y.shape[0]
costs = []
for i in range(iterations):
theta = theta - alpha / m * X.T.dot(X.dot(theta) - y)
costs.append(cost(X,y,theta))
plt.plot(range(iterations), costs)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.show()
return theta
|
#!/usr/bin/env python
# coding=utf-8
"""
约数之和
数字等于它的约数之和
6=1+2+3
"""
def gcd(n):
result = []
for i in range(1,n):
if n % i == 0:
result.append(i)
return result
def sum_gcd(n):
result = gcd(n)
summary = 0
for i in result:
summary += i
if summary == n:
return True
else:
return False
if __name__ == '__main__':
for i in range(1,100):
if sum_gcd(i):
print i
|
#!/usr/bin/env python
# coding=utf-8
"""
有number个button, button可以开可以关,每按一次转换一次操作
现在先按 2n 的顺序依次按button
2, 4, 6,... 2n各按一次
3, 6, 9,... 3n各按一次
...
100n 各按一次
最后灯的状态
"""
size = 10
light = [0 for i in range(size)]
def switch_light(item):
if item == 0:
return 1
else:
return 0
def status(light):
for i in range(2, size+1):
for j in range(i, size+1, i):
#前面二层循环是为了得到2n, 3n,4n
#i 是2,3,4
#range(i, size+1,i)可以得到2,4,6,
#3,6,9
for k in range(1, size+1):
#最后一层是原始的字符串
if j==k:
light[k-1]=switch_light(light[k-1])
return light
if __name__ == '__main__':
result = status(light)
for i in result:
print i
|
import matplotlib.pyplot as plt
#import random
maxRandom=4294967296
def randomLcg(seed):
seed = (1664525 * seed + 1013904223) % maxRandom
return seed
k=3
n=50000
sumList =[0]*(k*6+1)
seed=12345
for i in range(n):
sum=0
for j in range(k):
seed = randomLcg(seed)
die = int ( seed/maxRandom * 6 + 1 )
#print(die)
sum += die
sumList[sum] += 1
#mean=sum/k
meanList = [x/k for x in range(k*6+1)]
#print(mean)
#plt.figure(1)
#plt.title('dice plot')
#plt.plot(sumList,'ro')
#plt.show()
plt.figure(1)
plt.subplot(211)
plt.xlim(0,20)
plt.title('sum (k='+str(k)+')')
plt.plot(sumList,'ro')
plt.subplot(212)
plt.plot(meanList,sumList,'ro')
plt.title('mean')
plt.tight_layout()
plt.show()
# alternative way to generate random number with built-in function
# die=random.randint(1,6)
|
def main():
dict_ingrediants = {'taco':5, 'meat': 4, 'beef':3, 'rice':1}
print(dict_ingrediants['meat'])
max_value = max(dict_ingrediants['meat'], dict_ingrediants['beef'], dict_ingrediants['rice'])
min_value = min(dict_ingrediants['meat'], dict_ingrediants['beef'], dict_ingrediants['rice'])
remaining_value = max_value - min_value
item1 = [k for k, v in dict_ingrediants.iteritems() if v == max_value]
item2 = [k for k, v in dict_ingrediants.iteritems() if v == min_value]
total_items = [k for k, v in dict_ingrediants.iteritems()]
print(total_items)
list_items = [item1.pop(), item2.pop(),'taco']
print(list_items)
item3 = list(set(total_items)-set(list_items)).pop()
print(item3)
value_item3 = dict_ingrediants[str(item3)]
total_items_made = min_value+min(remaining_value, value_item3)
print("total Items that can be made"+ str(min(total_items_made,dict_ingrediants['taco'])))
if __name__ == '__main__':
main()
|
#1 请找出以下代码的错误,并修改使其正常运行
# age = input('请输入数字: ')
# if age == 10
# print('小明今年%d岁了'%age)
# print('程序结束')
def age():
age = int(input('请输入数字: '))
if age == 10:
print('小明今年%d岁了'%age)
else:
print('程序结束')
age()
#2 请修改以下代码的错误,并修改使其正常运行(代码实现对列表求和)
# list = [1,2,3,4]
# def run():
# he = sum(list)
# print(he)
# run()
list = [1,2,3,4]
def run():
he = sum(list)
print(he)
run()
|
# def bubble_sort(data):
# data_length = len(data)
# for i in range(data_length):
# for j in range(data_length-i-1):
# if data[j] > data[j+1]:
# temp = data[j]
# data[j] = data[j+1]
# data[j+1] = temp
# if __name__ == "__main__":
# data = [12, 25, 75, 84, 4, 5, 6, 7, 10]
# bubble_sort(data)
# print("Bubble sort is: ", data)
# def bubble_sort(data_list):
# n = len(data_list)
# for i in range(n):
# for j in range(n-i-1):
# if data_list[j] < data_list[j+1]:
# return data_list[j]
# if data_list[j] > data_list[j+1]:
# temp = data_list[j]
# data_list[j] = data_list[j+1]
# data_list[j+1] = temp
# if __name__ == "__main__":
# data_list = [1, 2, 5, 45, 85, 75, 35]
# bubble_sort(data_list)
# print("sorted list: ", data_list)
# def sorted_list(list):
# n = len(list)
# for i in range(n-1):
# mid_index = i
# for j in range(i+1, n):
# if list[j] < list[mid_index]:
# mid_index = j
# if mid_index != i:
# result = list[i]
# list[i] = list[mid_index]
# list[mid_index] = result
# if __name__ == "__main__":
# list = [12, 24, 45, 78, 45, 50]
# sorted_list(list)
# print(list)
# n = 5
# for i in range(n-1):
# print("first loop: ", i)
# for j in range(i+1, n):
# print("Second loop", j)
# def bubble_sort(list):
# n = len(list)
# for i in range(n):
# for j in range(n-i-1):
# if list[j] > list[j+1]:
# result = list[j]
# list[j] = list[j+1]
# list[j+1] = result
# if __name__ == "__mian__":
# list = [12, 5, 6, 4, 87, 50]
# bubble_sort(list)
# print(list)
# def bubble_sort(list):
# n = len(list)
# for i in range(n):
# print("first loop", i)
# for j in range(n-1-i):
# if list[j] > list[j+1]:
# result = list[j]
# list[j] = list[j+1]
# list[j+1] = result
# #print("second loop: ", j)
# if __name__ == "__main__":
# list = [1, 2, 3, 4, 7, 6]
# bubble_sort(list)
# print(list)
def bubble_sort(list):
n = len(list)
for i in range(n):
swap = False
print("frist loop", i)
for j in range(n-i-1):
if list[j] > list[j+1]:
result = list[j]
list[j] = list[j+1]
list[j+1] = result
swap = True
#print("second loop", j)
if swap == False:
break
if __name__ == "__main__":
list = [1, 2, 3, 4, 7, 6]
bubble_sort(list)
print(list)
|
# list = [12, 25, 65, 78, 89, 45, 50]
# search = 50
# for i in range(len(list)):
# result = list[i]
# if result == search:
# print("Found in index: ", i)
# print("Not found this list")
# list = [12, 25, 65, 78, 89, 45, 50]
# search = 50
# found = False
# for i in range(len(list)):
# result = list[i]
# if result == search:
# found = True
# break
# if found == True:
# print("Foun in index: ",i)
# else:
# print("Not found this list")
# def linear_search(list, found, search):
# for i in range(len(list)):
# result = list[i]
# if result == search:
# found = True
# break
# if found == True:
# return "Found here in index", i
# else:
# return "Not found in list"
# list = [12, 56, 78, 56, 87, 98]
# search = 87
# found = False
# print(linear_search(list, found, search))
# def linear_search(list, found, search):
# for i in range(len(list)):
# result = list[i]
# if result == search:
# found = True
# break
# if found == True:
# print("Found here in index:",i)
# else:
# print("Not found in list")
# list = [12, 56, 78, 56, 87, 98]
# search = 87
# found = False
# linear_search(list, found, search)
# Recursive function to search x in arr[l..r]
def recSearch( arr, l, r, x):
if r < l:
return -1
if arr[l] == x:
return l
if arr[r] == x:
return r
return recSearch(arr, l+1, r-1, x)
# Driver Code
arr = [12, 34, 54, 2, 3]
n = len(arr)
x = 3
index = recSearch(arr, 0, n-1, x)
if index != -1:
print ("Element", x,"is present at index %d" %(index))
else:
print ("Element %d is not present" %(x))
# Contributed By Harshit Agrawal
|
# def sorted_list(item_value):
# item_length = len(item_value)
# for i in range(item_length - 1):
# mid_index = i
# for j in range(i+1, item_length):
# if item_value[j] < item_value[mid_index]:
# mid_index = j
# if mid_index != i:
# result = item_value[i]
# item_value[i] = item_value[mid_index]
# item_value[mid_index] = result
# if __name__ == "__main__":
# item_value = [23, 68, 78 ,75, 45, 50]
# sorted_list(item_value)
# print("sorted item_value is: ", item_value)
def double_sort(list):
n = len(list)
for i in range(0, n):
start_index = i
for j in range(0, n-i-1):
|
class queue:
def __init__(self) -> None:
self.item = []
def is_empty(self):
if self.item == []:
return "This is empty"
return "This is not empty"
def enqueue(self, add_item):
self.item.append(add_item)
def dequeue(self):
if len(self.item) < 1:
return None
return self.item.pop(0)
def size(self):
return len(self.item)
def output(self):
print(self.item)
x = queue()
x.enqueue(10)
x.enqueue(20)
x.enqueue(30)
x.enqueue(40)
x.enqueue(50)
x.output()
x.dequeue()
x.dequeue()
x.output()
print(x.size())
print(x.is_empty())
def create_queue():
item = []
return item
def is_empty(item):
if len(item) == []:
return "This is empty"
return "This is not empty"
def enqueue(item, value):
return item.append(value)
def dequeue(item):
return item.pop(0)
def size(item):
return len(item)
x = create_queue()
enqueue(x, 10)
enqueue(x, 20)
enqueue(x, 30)
enqueue(x, 40)
enqueue(x, 50)
print(x)
dequeue(x)
dequeue(x)
dequeue(x)
print(x)
print("size is: ",size(x))
print(is_empty(x))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python 2.7
# py-heap-sort-demo-1.py
class HeapSortDemo1():
def DisplayData(self, data):
print ', '.join([str(i) for i in data])
def Heapify(self, data, i, size):
left_child = 2 * i + 1
right_child = 2 * i + 2
max = i
if left_child < size and data[left_child] > data[max]:
max = left_child
if right_child < size and data[right_child] > data[max]:
max = right_child
if max != i:
data[i], data[max] = data[max], data[i]
self.Heapify(data, max, size)
def HeapSort(self, data):
# BuildHeap
heap_size = len(data)
for i in xrange(heap_size / 2 - 1, -1, -1):
self.Heapify(data, i, heap_size)
# HeapSort
while heap_size > 1:
heap_size -= 1
data[0], data[heap_size] = data[heap_size], data[0]
self.Heapify(data, 0, heap_size)
if __name__ == '__main__':
data = [76, 11, 11, 43, 78, 35, 39, 27, 16, 55, 1, 41, 24, 19, 54, 7, 78, 69, 65, 82]
hsd = HeapSortDemo1()
hsd.DisplayData(data)
hsd.HeapSort(data)
hsd.DisplayData(data)
|
NORTH, S, W, E = (0, -1), (0, 1), (-1, 0), (1, 0) # directions
turn_right = {NORTH: E, E: S, S: W, W: NORTH} # old -> new direction
turn_left = {NORTH: W, E: NORTH, S: E, W: S} # old -> new direction
def spiral(width, height):
if width < 1 or height < 1:
raise ValueError
x, y = width // 2, height // 2 # start near the center
dx, dy = NORTH # initial direction
matrix = [[None] * width for _ in range(height)]
count = 0
while True:
count += 1
if (count == 1):
matrix[y][x] = count # visit
else:
matrix[y][x] = getVal(matrix, y, x, width, height) # visit
# try to turn left
if (count == 1):
new_dx, new_dy = E
else:
new_dx, new_dy = turn_left[dx, dy]
new_x, new_y = x + new_dx, y + new_dy
if (0 <= new_x < width and 0 <= new_y < height and
matrix[new_y][new_x] is None): # can turn right
x, y = new_x, new_y
dx, dy = new_dx, new_dy
else: # try to move straight
x, y = x + dx, y + dy
if not (0 <= x < width and 0 <= y < height):
return matrix # nowhere to go
def getVal(matrix, y, x, width, height):
val = 0
print(matrix[1][2])
a = x - 1
b = x + 1
c = y - 1
d = y + 1
if (a > width) and (matrix[y][a] != None):
val = val + matrix[y][a]
if (b > width) and (matrix[y][b] != None):
val = val + matrix[y][b]
if (c > height) and (matrix[c][x] != None):
val = val + matrix[c][x]
if (d > height) and (matrix[d][x] != None):
val = val + matrix[d][x]
if (a > width) and (d > height) and (matrix[d][a] != None):
val = val + matrix[d][a]
if (b > width) and (d > height) and (matrix[d][b] != None):
val = val + matrix[d][b]
if (a > width) and (c > height) and (matrix[c][a] != None):
val = val + matrix[c][a]
if (b > width) and (c > height) and (matrix[c][b] != None):
val = val + matrix[c][b]
return val
def print_matrix(matrix):
width = len(str(max(el for row in matrix for el in row if el is not None)))
fmt = "{:0%dd}" % width
for row in matrix:
print(" ".join("_" * width if el is None else fmt.format(el) for el in row))
matrix = spiral(3, 3)
print_matrix(matrix)
arr = []
for x in range(0, len(matrix)):
smallList = matrix[x]
tmp = []
for y in range(0, len(smallList)):
if (smallList[y] != None):
tmp.append(smallList[y])
if (tmp != []):
arr.append(tmp)
x1 = 0
y1 = 0
x361527 = 0
y361527 = 0
for x in range(0, len(arr)):
smallList = arr[x]
for y in range(0, len(smallList)):
if (smallList[y] == 1):
x1 = y + 1
y1 = x + 1
elif (smallList[y] == 361527):
x361527 = y + 1
y361527 = x + 1
manhattan_distance = abs(x361527 - x1) + abs(y361527 - y1)
print(manhattan_distance)
|
class Graph():
def __init__(self):
self._adjacency_list = {}
def add_node(self, value):
node = Node(value)
self._adjacency_list[node] = []
return node
def add_edge(self, start_node, end_node, weight=0):
if start_node not in self._adjacency_list:
raise KeyError('No start node.')
if end_node not in self._adjacency_list:
raise KeyError('No end node.')
self._adjacency_list[start_node].append((end_node, weight))
def get_nodes(self):
return self._adjacency_list.keys()
def get_neighbors(self, start_node):
return self._adjacency_list[start_node]
def size(self):
return len(self._adjacency_list)
class Node():
def __init__(self, value):
self.value = value
|
from data_structures_and_algorithms.data_structures.linked_list_insertions.linked_list_insertions import (
LinkedList, Node
)
""" Required Tests """
# Can successfully add a node to the end of the linked list
# Can successfully add multiple nodes to the end of a linked list
# Can successfully insert a node before a node located i the middle of a linked list
# Can successfully insert a node before the first node of a linked list
# Can successfully insert after a node in the middle of the linked list
# Can successfully insert a node after the last node of the linked list
def test_str():
ll = LinkedList()
ll.insert('blahblah')
ll.insert('blah1')
assert ll.__str__() == '{ blah1 } -> { blahblah } -> NULL'
def test_insert_first():
"""
Can properly insert into the linked list
"""
ll = LinkedList()
ll.insert('blah')
assert ll.head.data == 'blah'
def test_instantiate_linked_list():
"""
Can successfully instantiate an empty linked list
"""
ll = LinkedList()
assert ll.head == None
def test_insert_multiple_nodes():
"""
Can properly insert multiple nodes into the linked list
"""
ll = LinkedList()
ll.insert('blah2')
ll.insert('blah1')
assert ll.head.data == 'blah1'
assert ll.head.next.data == 'blah2'
def test_found_value_true():
"""
Will return true when finding a value within the linked list that exists
"""
ll = LinkedList()
ll.insert('blah1')
ll.insert('blah2')
assert ll.includes('blah1')
def test_found_value_false():
"""
Will return false when searching for a value in the linked list that does not exist
"""
ll = LinkedList()
ll.insert('blah1')
ll.insert('blah2')
assert ll.includes('blah3') == False
def test_return_all_nodes():
"""
Can properly return a collection of all the values that exist in the linked list
"""
ll = LinkedList()
ll.insert('blahblah')
ll.insert('blah1')
assert ll.__str__() == '{ blah1 } -> { blahblah } -> NULL'
def test_append():
"""
Can successfully add a node to the end of the linked list
"""
ll = LinkedList()
ll.append('blah')
assert ll.head.data == 'blah'
def test_add_multiple_append():
"""
Can successfully add multiple nodes to the end of a linked list
"""
ll = LinkedList()
ll.append('blah')
ll.append('blah2')
assert ll.head.data == 'blah'
assert ll.head.next.data == 'blah2'
def test_insert_before_middle():
"""
Can successfully insert a node before a node located in the middle of a linked list
"""
ll = LinkedList()
ll.append('blah1')
ll.append('blah2')
ll.append('blah3')
ll.insert_before('blah2', 33)
assert ll.head.next.data == 33
def test_insert_before_first_node():
"""
Can successfully insert a node before the first node of a linked list
"""
ll = LinkedList()
ll.append('blah1')
ll.insert_before('blah1', 22)
assert ll.head.data == 22
def test_insert_after_after_middle():
"""
Can successfully insert after a node in the middle of the linked list
"""
ll = LinkedList()
ll.append('blah1')
ll.append('blah2')
ll.append('blah3')
ll.insert_after('blah2', 33)
assert ll.head.next.next.data == 33
def test_insert_after_last():
"""
Can successfully insert a node after the last node of the linked list
"""
ll = LinkedList()
ll.append('blah1')
ll.append('blah2')
ll.append('blah3')
ll.insert_after('blah3', 33)
assert ll.head.next.next.next.data == 33
|
from collections import deque
class BinaryTree:
"""Simple BinaryTree with enough functionality for breadth first adding"""
def __init__(self):
self.root = None
def add(self, value):
node = Node(value)
if not self.root:
self.root = node
return
q = Queue()
q.enqueue(self.root)
while not q.is_empty():
current = q.dequeue()
if current.left:
q.enqueue(current.left)
else:
current.left = node
break
if current.right:
q.enqueue(current.right)
else:
current.right = node
break
class BinarySearchTree():
"""BinarySearchTree with enough functionality for breadth first adding"""
def __init__(self, value=None):
self.root = value
def add(self, value, current=None):
pass
class Node:
""" Tree Node"""
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class Queue:
"""Implementation of Queue that compose built in deque class"""
def __init__(self):
self.dq = deque()
def enqueue(self, value):
self.dq.appendleft(value)
def dequeue(self):
return self.dq.pop()
def peek(self):
return self.dq[-1]
def is_empty(self):
return len(self.dq) == 0
def breadth_first(tree):
"""
Breadth first traversal that takes in binary tree,
traverses the tree using breadth first method and finally
returns a list of the values in order
"""
if not tree.root:
return None
q = Queue()
lst = []
q.enqueue(tree.root)
while not q.is_empty():
node = q.dequeue()
lst.append(node.value)
if node.left:
q.enqueue(node.left)
if node.right:
q.enqueue(node.right)
return lst
|
# funtional programming
# ---------------------
# use of function for special modulalisation in could be done.
# they are two types of function
# 1.pre defined
# 2.over defined
# function has 3 main components
# 1.definition
# 2.implementation
# 3.function call
# A function is class function the definition+implememtation
# are manditory component the function call is optional.
# *definition +implementation occur only once where as call
# can occur multiple time.
# *Each function is written for ingle function
# function are classified into 4 types based on parameter + return types
# syntax:
# def<function name>():<implementation>
# <function name>()
# *If the multiple function are defined with same name then the latest
# implementation taken into the function.
# *call trigers the function to get the output.
# def sayhello():
# print("hello")
# print("hi")
# sayhello()
# print(sayhello)
# print(sayhello())
# print(type(sayhello))
# print(type(sayhello()))
# parameter
# --------
# parameter are also terms as argument they are input that passes
# to functions.
# *python function accept two types of parameter
# 1.formal parameter
# 2.actual parameter
# *The formal parameter are nomial+variables defined in the function defination.
# *actual parameter are the values those are passed to the formal parameter.
# Actual parameter are written in function call
# 4 kinds of parameters
# 1.positional
# 2.default
# 3.variables
# 4.keyword
# POSITIONAL:
# no.of formal parameter=no.of actual parameter
# def addnums(a,b):
# ans=a+b
# print(ans)
# addnums(10,20)
# def addnums(a,b):
# ans=a+b
# return ans
# ans=addnums(20,30)
# print(ans)
# def addnums(a,b):
# ans=a+b
# return 100
# ans=addnums(20,30)
# print(ans)
# return of a function is the output of a particular function
# mostly.It can be used in 4 ways
# 1.return of values
# 2.return of variables
# 3.return of function name
# 4.return of function call
# enter a number 40
# enter a number 10
# addnums 40,10-->50
# subnums 50,10-->40
# mulnums 40,10-->400
# divnums 400,10-->40
# def addnums(a,b):
# ans=a+b
# return ans
# def subnums(a,b):
# ans=a-b
# return ans
# def mulnums(a,b):
# ans=a*b
# return ans
# def divnums(a,b):
# ans=a/b
# return ans
# addans=addnums(40,10)
# subans=subnums(addans,10)
# mulans=mulnums(subans,10)
# divans=divnums(mulans,10)
# print(divans)
# function can have any return if multiple returns is passed
# the first returns will be considered.
# Default parameter:is used to pass the default values to variables in the function
# here we use variable in actual parameter and values in formal parameter.
# def login(user,role):
# print("the user is "+ user)
# print("the role is "+ role)
# login("khan","pd")
# login(role="pd",user="khan")
# def makecake(flvr="vennila",wei="2",shape="square"):
# print("the flavour of cake " +flvr)
# print("the weight of cake " +wei)
# print("the shape of cake "+shape)
# makecake("choc","3","round")
# makecake(flvr="pine",shape="round")
# makecake(flvr="choc",wei="3")
# makecake(wei="3")
# makecake()
# Variable parameter:
# Variable parameter are dynamic parameter which change according to the parameter
# passed in the function call.
# they are given by"args" where args is atuple they are passed in the function definition"*args".
# def avg(*args):
# print(args)
# print(type(args))
# avg(10,20,30,40)
# average of numbers
# def avg (*args):
# mean=sum(args)/len(args)
# print(mean)
# avg(10,20,30,40,50)
# def avg(a,b,*args):
# print(a)
# print(b)
# print(args)
# avg(10,20,30,14,7)
# avg(10,20)
# NOTE:
# The function belongs to class function and function call belongs
# to class of the return type.
# def addnums(a,b):
# ans=a+b
# return(ans)
# print(addnums)
# print(type(addnums))
# print(addnums(100,200))
# print(type(addnums(100,200)))
# getindex("pyhton and machine language"," ")
# checkchar()
# stmt="python and machine language"
# char=" "
# def checkchar(statement,character):
# if character in statement:
# return statement.count(character)
# else:
# return 0
# def getindex(stmt,char):
# reps=checkchar(stmt,char)
# if reps>0:
# i=-1
# while reps>0:
# i=stmt.index(char,i+1)
# reps=reps-1
# print(i)
# getindex(stmt,char)
# calsum([1,2,3,4],[100,200,300,400])
# [(1,100)(2,200)(3,300)(4,400)]
# [101,202,303,404]
# def calsum(l1,l2):
# zo=zip(l1,l2)
# ans=list(zo)
# print(ans)
# for i in range (len(ans)):
# sumTuple=sum(ans[i])
# ans.remove(ans[i])
# ans.insert(i,sumTuple)
# print(ans)
# calsum([1,2,3,4],[100,200,300,400])
# DOCSTRING:
# Docstring is matadata of a function it is return just after the definition
# as multiline comment it is store in variable __ doc __
# <functionname>.__doc__
# def demo():
# '''
# this is demo function
# '''
# demo()
# print(demo.__doc__)
# print(len.__doc__)
# print(list.append__doc__)
# print(.__doc__)
# def convert(a):
# str="".join(a)
# return str
# a=("s","a","r","i")
# str=(convert(a))
# print(str)
# def reverse (a):
# b=a[::-1]
# return b
# a=("dharmateja")
# print(reverse(a))
# KEYWORD PARAMETER:
# -----------------
# keyword parameter stores the excess values in the
# parameter as pair of keys and values in a dictionaries.
# The name of dictionaries is "kwargs".It is given in the function
# definition as "**kwargs".
# def makecake(flvr="vannila",shape="square",wei="3",**kwargs):
# print("flavour of cake"+flvr)
# print("shape of cake"+shape)
# print("weight of cake"+wei)
# makecake("choc","round","3")
# makecake("choc","round","3",toppings="almond")
# LAMBDA FUNCTION/ANONYMOUS FUNCTION:
# It is used to havea one line implementation of the code.
# lambda function is auto return .
# it is both parameterised and non parameterised.
# syntax:
# <functionname>=lambda<parameter>:<implementation>
# addnums=lambda a,b:a+b
# print(addnums(10,20))
# makemail=lambda user ,cname:"user"+"@"+"cnmae"+".com"
# print(makemail("hira","hcl"))
# def first (name):
# print("hello "+ name)
# def second(name):
# print("bye "+ name)
# return first
# print(first("hira"))
# print(second("hira"))
# a=second("john")
# a("khan")
# def first (name):
# print("hello "+name)
# def second(name):
# print("bye "+name)
# return first(name)
# print(type(second("khan")))-->class none
# def first(name):
# print("hello "+name)
# return 100
# def second(name):
# print("bye "+name)
# return first(name)
# print(type(second("khan")))-->class int
# MAP:
# map is the pre-defined function that returns the map
# object it takes function name and collections of its parameter.
# It is used to calculate the associate operation of the collections.
# <mapobject>=map(<functionname>,<collection(s)>)
# NOTE:
# The functionname passes it needs the return type.
# square of number
# l1=[i for i in range(10)]
# def square (num):
# return num**2
# print(list(map(square,l1)))
# l1=[i for i in range(10)]
# l2=[i for i in range(10,20)]
# print(list(map(lambda a,b:a+b,l1,l2)))
# stmt="python is easy programming language"
# print(list(map(len,stmt.split())))
# def addnums(a,b):
# return a+b
# mo=map(addnums,l1,l2)
# l=list(mo)
# print(l)
# FILTER:filter function is used to return filter object
# which has all the truth values of a collection for a
# condition it takes a function name and collection as input.
# syntax:
# <filtername>-filter(<filtername>,<collection>)
# l1=[i for i in range (30)]
# f=filter(lambda a:a%2==0,l1)
# print(list(f))
# f=filter (lambda a:a%2!=0,l1)
# print(list(f))
# Reduce:-Reduce is an internal imported function
# *It is imported from functools.it performs cumulative operation.
# *It takes functionname and collection as input and it returns cumulative output.
# ex:sum of list, product of list,sub of list.
# syntax:
# <ans>=reduce(<functionname>,<collection>)
# l1=[i for i in range (1,31)]
# from functools import reduce
# pro=reduce(lambda a,b:a*b,l1)
# print(pro)
# ans=reduce(lambda a,b:a+b,l1)
# print(ans)
# import sys
# def getargs(l):
# if len(l)==3:
# if int(l[1])<=26 and int(l[2]) in(1,2):
# return (int(l[1]),int(l[2]))
# else:
# print("invalid input")
# def generator ():
# inps=getargs(sys.argv)
# op=" "
# if inps[1]==1:
# for i in range (inps[0]):
# op=op+str(i)
# else:
# for i in range (97,97+int(inps[0])):
# op=op+str(i)
# print("op")
# generator()
# file handing:
# ------------
# file is the data storage component which stores in various form.
# file contain 3 components:
# 1:location
# 2:file name
# 3:extension
# *By default python works with txt files it can also
# handle "html"files
# *If excel csv needs to use "pandas"
# *if csv alone needs to use"csv"
# *if excel alone needs to use "xlsxwriter"
# *if pdf alone needs to use"pypdf2"
# NOTE:
# using of file helps to stores history of data unlike
# collection which initailze each timr and run the code.
# *The encoding format for the files in windows is CP1252
# LINUX/UNIX is utf-8
# There are 7 modes of operation of a file
# 1.read-->r
# 2.write-->w
# 3.append-->a
# 4.read binary-->rb
# 5.write binary-->wb
# 6.update-->multiple purpose-->rb+,wb+
# *files in python is autosaved and explicit buffer is absent.
# *python creates file object for each file instant.
# OPEN FUNCTION:
# open function is used to create and open aa file if file
# doesn't exists or to open a file if file exists,and it takes
# 2 inputs.
# if file should be created and open mode should be write as
# <fileobject>=open("<filename>","<mode>")
# *fileobject should be closed aftera write code.
# <operation>
# <fileobject>.close()
# fo=open("first.txt","w")
# fo.close()
# writing data onto the file :-
# we have 2 object
# 1.fileobject .write
# 2.fileobject
# we can only write strings on to the file
# *write are used to write a single stirng writelines is used to
# write a collection of lines.
# fo=open ("hira.txt","w")
# fo.write("first\n")
# fo.write("second\n")
# lines=["python\n","java\n","html\n"]
# fo.writelines(lines)
# fo.close()
# fo=open("hira.txt","w")
# lines=[str(i) for i in range (0,n)]
# fo.writelines(lines)
# print(lines)
# fo.close()
# append mode:-
# append mode is used to write the data without erase
# the previous data it does not make the file empty before
# data unlike write,writelines function.
# fo=open("hira.txt","a")
# fo.write("first\n")
# fo.write("second\n")
# fo.close()
# n=8
# fo=open("hira.txt","w")
# a=[chr(i)+"\n" for i in range(97,97+n)]
# fo.writelines(a)
# fo.close()
# n=5
# fo=open("hira.txt","w")
# a=[chr(i)*(i-96)+"\n" for i in range(97,97+n)]
# fo.writelines(a)
# fo.close()
# n=5
# fo=open("hira.txt","w")
# a=[str(i)*i+"\n" for i in range(1,n+1)]
# fo.writelines(a)
# fo.close()
# reverse of num:
# n=5
# fo=open("hira.txt","w")
# a=[" "*(n-i)+str(i)*i+"\n" for i in range(1,6)]
# fo.writelines(a)
# fo.close()
# ascii
# n=5
# fo=open("hira.txt","w")
# for i in range(0,n+1):
# for j in range(97,97+i):
# fo.write(chr(j))
# fo.write("\n")
# fo.close()
# n=5
# fo=open("hira.txt","w")
# for i in range(1,6):
# for j in range(1,i+1):
# fo.write(str(j))
# fo.write("\n")
# fo.close
# reverse of star
# n=5
# fo=open("hira.txt","w")
# a=[" "*(n-i)+"*"*i+"\n" for i in range(1,6)]
# print(a)
# fo.writelines(a)
# fo.close()
# star
# fo=open("hira.txt","w")
# a=["*"*i +"\n" for i in range(1,6)]
# fo.writelines(a)
# fo.close()
# Reading file :
# we have 3 functions in python to read the python file.
# 1.fo.read :it reads enter data from file from starting to end.
# fr=open ("hira.txt","r")
# data=fr.read()
# print(data)
# A Numeric parameter is passed to read only "n" character from the file.
# data=fr.read(5)
# Readline:it is used to print first line of data from current curser position.
# the default position of curser is at the start of file.
# Readlines: it is used to read enter data as a list of all the lines.
# print(fr.readlines())
# fr=open("hira.txt","r")
# data1=fr.read().split(",")
# print(data1[:6])
# print(data1[5:11])
# print(data1[10:17])
# fr.close()
# n=18
# fo=open("hira.txt","w")
# for i in range(0,17):
# fo.write(str(i)+",")
# fo.close()
# fr=open("hira.txt","r")
# data1=fr.read().split(',')
# for i in range(6):
# print(data1[i],end=' ')
# print()
# for i in range(5,11):
# print(data1[i], end = ' ')
# print()
# for i in range(10, n):
# print(data1[i], end = ' ')
# fo.close()
# fr=open("hira.txt","r")
# data=fr.read()
# print(data)
# data1=fr.read(2)
# print(data[-1]+data1)
# fr.close()
# n=8
# fo=open("hira.txt","w")
# a=[chr(i) for i in range(97,97+n)]
# fo.writelines(a)
# fo.close()
# fr=open("hira.txt","r")
# data=fr.read()
# for i in range(0,4):
# print(data[i],end=" ")
# print()
# for i in range(3,6):
# print(data[i],end=" ")
# fr.close()
# Modules and packages:
# There are 3 kinds of Modules
# 1.internal default
# 2.internal import
# 3.external
# module-->any python file is called module.-->(.py,.ipynb,.pyc)
# internal default: Module have their components on every module by default.
# ex: print,len,sort.
# Internal import:these are available in library but not on the module
# ex:reduce--> from functools import reduce
# kw-->import sys
# argb-->import keyword
# External:- There are not available either on the module or in the default
# python libraries we need to download the modules,install them then import
# and use.we use packages manager for this purpose pyhton have pre-defined
# package manager .python packaging index[pip]
# * pip need installed to using it is available to install during installation.
# * if unavailable run "get-pip.py" file available externally.
# pip list:- it shows all the modules in the curent installation.
# pip list-->all modules(pip,setuptools)
# *pip install<modulename>
# *pip unstall<modulename>
# pip freeze:-returns the moduleds or packages that are manually installed.
# The installed packages using pip gets installed "site-packages location".
# packages:-package is a collection of python modules along with the special
# module[installation__ int__.py]
# complete importing: it import all components from module it can
# be access to using complete import module refrence.
# <modulename>.<component>
# import module4
# print(module4.d)
# print(module4.mixed)
# NOTE:it import all the components but module reference are not need.
# from module4 import*
# print(d)
# print(mixed)
# Specific import:
# Specificcomponents are imported but reference are not
# from<modulename>import<component>
# from module4 import d,mixed
# print(d)
# print(mixed)
# ALISING:
# import<modulename> as <mn>
# <mn>,<component>
# Random module:
# It is used to generation of pseudo random number it work
# with random module is used with number and collection.it is an internal
# interperted module.
# import random
# print(random.random())
# it generate random float between 0 and 1.
# randint:it generate the random numbers between the range inclusive
# of end points.
# print(random.randint(2,10))
# randrange:it generate the random numbers between the range inclusive of
# end points.
# print(random.randrange(2,10))
# random for collections:
# shuffle function :it randomly shuffles the collections
# import random
# l1=[i for i in range(12)]
# random.shuffle(l1)
# print(l1)
# choice function :it returns one random number from the collections
# print(random.choice(l1))
# sample function:it returns "k" randomnumbers from the collections. where "k"
# is called population.
# print(random.sample(l1))
# or
# print(random.sample(l1,k=3))
# os module:
# os module is used for 2 purpose
# 1.working with directories
# 2.system path manipulation
# * os is an internal import module
# import os
# print(os.name)-->nt is family of windows os
# print(os.getcwd)-->current working directory
# making of directories 1.os.mkdir
# 2os.makedirs
# mkdir: mkdir is used to createan single empty directory in the cwd location
# print(os.mkdir("demo"))
# os.makedirs:makedirs is used to create tree of empty directories in cwd location.
# print(os.makedirs(r" dir1\dir2\dir3"))
# Removing of directories:
# To remove directoriesfrom cwd we have 2 functions
# 1. os.rmdir
# 2.os.removedirs
# python can remove only empty directories
# print(os.rmdir("demo"))
# print(os.removedirs(r" dir1\dir2\dir3"))
# print(os.path.split(r"C:\Users\Mohammad\Desktop"))
# print(os.path.split(r"C:\Users\Mohammad\Desktop\hira"))
# print(os.path.splitext(r"C:\Users\Mohammad\Desktop\hira"))
# os.walk
# for paths,dirs,files in os.walk(r"C:\Users\Mohammad\Desktop"):
# print(paths)
# print(dirs)
# print(files)
# print()
# print(os.path.isfile(r"C:\Users\Mohammad\Desktop\module1"))
# print(os.path.isdir(r"C:\Users\Mohammad\Desktop"))
# print(os.path.exists(r"C:\Users\Mohammad\downloads"))
# class double:
# def __init__(self,last):
# self,last=last
# def __iter__(self):
# self.n=0
# return self
# def __next__(self):
# if self.n<=self.last:
# res=2*self.n
# self.n +1
# return res
# else:
# rise stopiteration
# for i in double(10):
# print(i,end=" ")
print(5^7)
|
import wikipedia
from tkinter import *
from tkinter.messagebox import showinfo
win = Tk()
win.title("wikipedia")
win.geometry("500x200")
def serach_wiki():
serach = entry.get()
answer = wikipedia.summary(serach)
showinfo("wikipedia Answer",answer)
label = Label(win,text="wikipedia Search: ")
label.grid(row=0,column=0)
entry = Entry(win)
entry.grid(row=1,column=0)
button = Button(win,text="Search",command=serach_wiki)
button.grid(row=1,column=1,padx=10)
win.mainloop()
|
from turtle import turtle
t = Turtle()
def spiral(n):
if n < 300:
t.forward(n)
t.right(89)
spiral(n+1)
spiral(30)
|
totalPrice = int(input("Input Price:"))
def vatCalculate(totalPrice):
result = (totalPrice+(totalPrice*7/100))
return result
print("Include Vat 7% :", vatCalculate(totalPrice))
|
car = 'Audi'
for c in car:
print(c)
print(len(car))
print('A' in car)
print('d' in car)
print('Au' in car)
print('x' in car)
print('Ad' in car)
|
"""
LEGB
L: Local
E: Enclosing function locals
G: Global
B: Built-in
"""
"""
Local scope :
"""
# Global variable x
x = 14;
def my_func():
# Local variable x
x = 23;
return x;
# print(x);
# print(my_func());
# output - 14 23
# my_func();
# print(x);
# output - 14
"""
Enclosing function locals
"""
# Global name
name = "This is global";
# Local x in lambda function
print(filter(lambda x:x**2,[2,3,4]));
# enclosing function locals
def greet():
name = "Shuvo";
def hello():
print("Hello",name); # another way to print. puts whitespace automatically
hello();
print(name);
greet();
print(name);
# This is global
# Hello Shuvo
# This is global
"""
Built-in
"""
len([]);
"""
Global variable changed inside local scope
always avoid using "global" keyword (until compelled to)
"""
print(x);
def redefine():
global x;
x = 1000;
print(" before function call x:",x);
redefine();
print(" after function call x:",x);
|
# https://en.wikipedia.org/wiki/War_(card_game)
import random;
class Deck():
suits = "H D S C".split();
values = "A K Q J 10 9 8 7 6 5 4 3 2".split();
highs = ["J","Q","K","A"];
cards = [];
def __init__(self):
self.prepare_deck();
def prepare_deck(self):
for suit in self.suits:
for value in self.values:
self.cards.append(suit+":"+value);
def shuffle_deck(self):
random.shuffle(self.cards);
def compare_cards(self,card1,card2):
card1_value = card1.split(":")[1];
card2_value = card2.split(":")[1];
#print("{} and {}".format(card1_value,card2_value));
if(card1_value in self.highs and not card2_value in self.highs):
#print("24");
return 1;
elif(card2_value in self.highs and not card1_value in self.highs):
#print("27");
return -1;
elif(card1_value in self.highs and card2_value in self.highs):
#print("30");
return self.highs.index(card1_value) - self.highs.index(card2_value);
#print("32");
return int(card1_value) - int(card2_value);
class Hand():
def __init__(self):
self.card_stack = [];
self.cards_in_hand = [];
def draw_card(self):
return self.cards_in_hand.pop(0);
def put_in_stack(self,cards):
self.card_stack.extend(cards);
class Player():
def __init__(self,name):
self.name = name;
self.hand = Hand();
self.next_card = "";
def show_next_card(self):
card = self.hand.cards_in_hand.pop(0);
print("Player {} has {}".format(self.name,card));
self.next_card = card;
return card;
def put_card_on_table(self):
return self.hand.cards_in_hand.pop(0);
class Table():
status_battle = 1;
status_war = 2;
def __init__(self):
self.face_up_cards = [];
self.face_down_cards = [];
self.deck = Deck();
def clear_table(self):
del self.face_up_cards[:];
del self.face_down_cards[:];
def take_hidden_card(self,card):
self.face_down_cards.append(card);
def take_shown_card(self,card):
self.face_up_cards.append(card);
def determine_winner(self,player1,player2):
#print("comparing {} and {} ".format(player1.next_card,player2.next_card));
result = self.deck.compare_cards(player1.next_card,player2.next_card);
#print("result:",result);
if(result == 0):
return self.status_war;
elif(result>0):
print("Player {} Gets the cards".format(player1.name));
player1.hand.card_stack.extend(self.face_down_cards);
player1.hand.card_stack.extend(self.face_up_cards);
else:
print("Player {} Gets the cards".format(player2.name));
player2.hand.card_stack.extend(self.face_down_cards);
player2.hand.card_stack.extend(self.face_up_cards);
self.clear_table();
print();
return self.status_battle;
print("Let's Play");
player2 = Player("Computer");
print("Player {} is ready".format(player2.name));
name = input("Enter your name : ");
player1 = Player(name);
table = Table();
print("Shuffling deck");
table.deck.shuffle_deck();
player1.hand.cards_in_hand = table.deck.cards[:26];
player2.hand.cards_in_hand = table.deck.cards[26:];
print("Cards are distributed.");
table.face_up_cards = [player2.show_next_card()];
table.face_up_cards = [player1.show_next_card()];
status = table.determine_winner(player1,player2);
while (len(player1.hand.cards_in_hand) != 0 and len(player2.hand.cards_in_hand) != 0):
if(status == table.status_war):
print("It's WAR!");
table.take_hidden_card(player2.put_card_on_table());
table.take_hidden_card(player1.put_card_on_table());
table.take_shown_card(player2.show_next_card());
input("continue");
table.take_shown_card(player1.show_next_card());
elif(status == table.status_battle):
print("Battle!");
table.take_shown_card(player2.show_next_card());
input("continue");
table.take_shown_card(player1.show_next_card());
status = table.determine_winner(player1,player2);
if(len(player1.hand.card_stack) == len(player2.hand.card_stack)):
print("IT'S A DRAW !!");
elif(len(player1.hand.card_stack)> len(player2.hand.card_stack)):
print("Player {} Wins !!".format(player1.name));
else:
print("Player {} Wins !!".format(player2.name));
print("Player {} collected : ".format(player1.name));
print(player1.hand.card_stack);
print("Player {} collected : ".format(player2.name));
print(player2.hand.card_stack);
|
# Vector addition function
###################################################
# Student should enter code below
def add_vector(a, b):
x = [(a[0] + b[0]), (a[1] + b[1])]
return x
###################################################
# Test
print add_vector([4, 3], [0, 0])
print add_vector([1, 2], [3, 4])
print add_vector([2, 3], [-6, -3])
###################################################
# Output
#[4, 3]
#[4, 6]
#[-4, 0]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.