text
stringlengths 37
1.41M
|
---|
# file: dirlist.py
# Author: Nikhil Gorantla
# Data: 1/Jan/2018
# Description: This is simple Directory listing program and which give the size of the files in the given directory
#!/usr/bin/python3
import os
dirName = input("Enter the Directory name to list the size of the files: ")
for file in os.listdir(dirName):
info = os.stat(file)
print("%-20s : size %d" % (file, info.st_size))
|
# file: archiving.py
# Author: Nikhil Gorantla
# Data: 14/Jan/2018
# Description: This python program helps to tar archive several 100's of log files.
#!/usr/bin/python3
import os
import tarfile
import sys
dPath = input("Enter the directory name to archive the file: ")
os.chdir(dPath)
# Add file f to archive t
def add_to_archive(f, t):
try:
t.add(f)
except PermissionError as e:
print("sorry %s " % e, file=sys.stderr)
if len(sys.argv) < 2:
list = ["."]
else:
list = sys.argv[1:]
with tarfile.open("/logs/logs1.tar", "w") as t:
for file in list:
# os.walk only works on directories
if os.path.isdir(file):
for root, dirs, files in os.walk(file):
for name in files:
add_to_archive(root + "/" + name, t)
# ordinary files are just added individually
else:
add_to_archive(file, t)
|
"""Simple calculator
Usage:
app.py <operation> <number1> <number2>
app.py (-h | --help)
Arguments
number1 First Number
number2 Second Number
Options:
-h --help Show this screen.
"""
from docopt import docopt
if __name__ == '__main__':
args = docopt(__doc__, version='Simple calculator')
functions = {
'add': lambda number1, number2: number1 + number2,
'subtract': lambda number1, number2: number1 - number2,
'multiply': lambda number1, number2: number1 * number2,
'divide': lambda number1, number2: number1 / number2
}
print functions[args['<operation>']](int(args['<number1>']), int(args['<number2>']))
|
"""
Following program get as input
city name and print the temperature
and humidity of that city.
"""
import requests
def get_request_jason(url):
resp = requests.get(url)
if resp.status_code != 200:
# This means something went wrong.
raise requests.RequestException('GET ERROR {}'.format(resp.status_code))
j_resp = resp.json()
return j_resp
#city = input("Please Enter you city:")
city="haifa"
#resp_map = get_request_jason('http://maps.googleapis.com/maps/api/geocode/json?address='
#+ city)
resp_map = get_request_jason('http://maps.googleapis.com/maps/api/geocode/json?address="haifa"')
dic1 = (resp_map['results'])[0]
cor1 = str(dic1['geometry']['location']['lat'])
cor2 = str(dic1['geometry']['location']['lng'])
print("Your City: " + city )
print("City cordinators: " + cor1 + ' ' + cor2)
print("============================================")
j_whether = get_request_jason('https://api.darksky.net/forecast/0d584daf877a4ff2998afe4329840ef9/'+
cor1 +',' + cor2)
print("Your City temperature: " , j_whether['currently']['temperature'])
print("Your City humidity: " , j_whether['currently']['humidity'])
|
def has_unique_char(string):
alph = [False for x in range(129)]
for char in string:
if(alph[ord(char)]):
return False
alph[ord(char)] = True
return True
print(has_unique_char('apple'))
print(has_unique_char('pear'))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Animals(object):
def __init__(self,name = 'wang san'):
self.name = name
def run(self):
print ('%s is runing...'%(self.name))
class Dog(Animals):
pass
class Cat(Animals):
pass
dog = Dog('lili')
dog.run()
|
#HCD
#Add Two Numbers
#9/4/18
numone=input('First Number: ')
numtwo=input('Second Number: ')
ione=int(numone)
itwo=int(numtwo)
total=ione+itwo
print("%i plus %i equals %i"%(ione,itwo,total))
#---------------------------------------------------
numone=int(input('First Number: '))
numtwo=int(input('Second Number: '))
print("%i plus %i equals %i"%(numone,numtwo,(numone+numtwo)))
|
#Python code to demonstrate
#conversion of list of ascii values
#to string
#Initialising list
ini_list= [118, 101, 114, 115, 101, 95, 115, 107, 95, 100, 101, 112, 108, 111, 121, 109, 101, 110, 116]
# Printing initial list
print ("Initial list", ini_list)
# Using Naive Method
res = ""
for val in ini_list:
res = res + chr(val)
# Printing resultant string
print ("Resultant string:", str(res))
|
from StackQueue.stack_queue import Stack,Queue
if __name__ == "__main__":
while True:
num = int(input("**************Menu Driven**************\n1.Implementing Stack\n2.Implementing Queue\n3.Exit\n"))
if num == 1:
s = Stack()
while True:
n = int(input("1.Push\n2.Pop\n3.Display\n4.Back\n"))
if n == 1:
s.push(input("Enter element you want to push: "))
elif n == 2:
s.pop()
elif n == 3:
s.display()
elif n == 4:
break
else:
print("You pressed wrong key please try agin")
elif num == 2:
q = Queue()
while True:
n = int(input("1.Enqueue\n2.Dequeue\n3.Display\n4.Back\n"))
if n == 1:
q.enqueue(input("Enter element you want to enqueue: "))
elif n == 2:
q.dequeue()
elif n == 3:
q.display()
elif n == 4:
break
else:
print("You pressed wrong key please try agin")
elif num == 3:
break
else:
print("You pressed wrong key please try again")
|
import numpy as np
x = int(input("enter number of rows: "))
y = int(input("enter number of columns: "))
matrix = lambda : [list(map(int,input().strip().split())) for _ in range(x)]
for i in range(2):
print("matrix: ", i + 1)
if i==0:
mat1=np.array(matrix())
elif i==1:
mat2=np.array(matrix())
print("matrix 1 is: ")
print(mat1)
print("matrix 2 is: ")
print(mat2)
res = np.dot(mat1, mat2)
print("Multiplication of matrix 1 and 2 is : \n",res)
|
mutex,full,empty,x = 1,0,3,0
def wait(s):
global mutex,full,empty,x
s -=1
return s
def signal(s):
global mutex,full,empty,x
s += 1
return s
def producer():
global mutex,full,empty,x
mutex = wait(mutex)
full = signal(full)
empty = wait(empty)
x +=1
print("Producer produces the item: "+str(x))
mutex = signal(mutex)
def consumer():
global mutex,full,empty,x
mutex = wait(mutex)
full = wait(full)
empty = signal(empty)
print("Consumer consumes item: "+str(x))
x -=1
mutex = signal(mutex)
if __name__ == "__main__":
print("55_Adnan Shaikh")
print("1.Producer \n2.Consumer \n3.Exit")
while(1):
n = int(input("Enter your choice: "))
if n == 1:
if mutex == 1 and empty != 0:
producer()
else:
print("Buffer is full")
elif n == 2:
if mutex == 1 and full != 0:
consumer()
else:
print("Buffer is empty!!")
elif n == 3:
break
else:
print("You pressed wrong key please try")
|
class Family:
def show_family(self):
print("This is Cujoh Family:")
class Father(Family):
fathername = ""
def show_father(self):
print(self.fathername)
class Mother(Family):
mothername = ""
def show_mother(self):
print(self.mothername)
class Child(Father, Mother):
def __init__(self):
super().__init__()
self.childname = ""
def show_parent(self):
print("Son name: ",self.childname)
print("Father :", self.fathername)
print("Mother :", self.mothername)
if __name__ == "__main__":
s1 = Child()
s1.childname = "Jotaro Cujoh"
s1.fathername = "Sadao Cujoh"
s1.mothername = "Holy Cujoh"
s1.show_family()
s1.show_parent()
|
def findDuplicate(nums):
nums.sort()
l = 0; r = 1
while r < len(nums):
if nums[r] == nums[l]:
return nums[r]
else:
l += 1
r = l+1
print findDuplicate([1,1])
|
def lengthOfLastWord(s):
array = s.split()
if len(array) == 0:
return 0
else:
return len(array[-1])
print lengthOfLastWord('')
|
import collections
def intersect(nums1,nums2):
cnt = collections.Counter()
for val in nums1:
cnt[val] += 1
ans = []
for val in nums2:
if cnt.has_key(val) and cnt[val] > 0:
ans.append(val)
cnt[val] -= 1
return ans
print intersect([1,2,3,2,1,1], [2,3,2,2,1,1])
|
def moveZeros(nums):
for x in nums:
if x == 0:
nums.remove(x)
nums.append(x)
print nums
moveZeros([0,1,0,3,12])
|
def compareVersion(version1, version2):
v1 = list(); v2 = list()
if '.' not in version1:
v1.append(version1)
v1.append('0')
else:
v1 = version1.split('.', 1)
if '.' not in version2:
v2.append(version2)
v2.append('0')
else:
v2 = version2.split('.', 1)
if int(v1[0]) > int(v2[0]):
return 1
elif int(v1[0]) < int(v2[0]):
return -1
else:
if int(v1[1])> int(v2[1]):
return 1
elif int(v1[1]) < int(v2[1]):
return -1
else:
return 0
print compareVersion("01","1")
|
def getSum(a, b):
p, g, i = a ^ b, a & b, 1
while True:
if (g << 1) >> i == 0:
return a ^ b ^ (g << 1)
if ((p | g) << 2) >> i == ~0:
return a ^ b ^ ((p | g) << 1)
p, g, i = p & (p << i), (p & (g << i)) | g, i << 1
print getSum(3,2)
|
"""
Split the dataset into training and test set with split being (80, 20)
Cross-validation will choose random people from the training set and do so
for k-different folds.
"""
from sklearn.cross_validation import train_test_split
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import StratifiedKFold
def split_dataset(X, y):
Xtr, Xte, ytr, yte = train_test_split(X, y, stratify=y, \
test_size=0.2, random_state=1221)
return (Xtr, Xte, ytr, yte)
def perform_cross_validation(X, y, est):
cv = StratifiedKFold(y, n_folds=5, random_state=1231)
cv_scores = cross_val_score(est, X, y, cv=cv, scoring='accuracy', n_jobs=-1)
return cv_scores
def perform_cross_validation_multiple(X, y, estimators, ensemble=False):
for est_name, model in estimators:
cv_scores = perform_cross_validation(X, y, model)
print('Accuracy score for: %s is: %f and std: %f'%(est_name, cv_scores.mean(), cv_scores.std()))
|
# import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
class Overview:
"""
This class instantiates an object that provides an overview of a data frame.
Example:
>> overview = Overview(df)
# get summary statistics
>> overview.summary_stats()
## check for missing values
>> overview.check_missing()
## generate a specific univariate plot
>> overview.gen_uni_plot("column_name")
## generate all univariate plots
>> overview.gen_all_unis()
"""
def __init__(self, df):
self.df = df
def summary_stats(self, mem_usage="deep", include="O"):
"""
Returns a dictionary containing the following summary stats:
- col names: df.dtype
- data types + memory consumption: df.info
- set mem_usage to "" if you don't want to spend more time on "deeper" memory estimates
- summary: df.describe
- set include to "" if you don't wish to include categorical variables
"""
column_names = list(self.df.columns)
# returns a function. Evaluate to get info.
## This is because df.info is just a print side effect
data_types = lambda: self.df.info(memory_usage=mem_usage)
summary = self.df.describe(include=include).T
return {
"col_names": column_names,
"data_types": data_types,
"summary": summary,
}
def check_missing(self):
"""
Returns the counts of missing values in the dataframe
"""
return self.df.isna().sum()
def gen_uni_plot(self, column_name):
"""
Generates a univariate density plot for the given column name. Requires a numeric or datetime column
"""
new_plot = UnivariatePlot(self.df, column_name)
new_plot.gen_plot()
def gen_all_unis(self):
# the [:-1] is because the text field is too large to fix in the axis labels
return [self.gen_uni_plot(i) for i in self.summary_stats()["col_names"][:-1]]
# un_overview = Overview(un)
# un_overview.gen_all_unis()
class UnivariatePlot:
sns.set(palette="colorblind")
def __init__(self, df, column_name, keep_null=False):
self.column_name = column_name
# if you wish to keep the null values, pass True to keep_null
if keep_null:
self.df = df[column_name].to_frame()
else:
self.df = df[column_name].dropna().to_frame()
# def gen_dist_plot(self):
# """
# Generates a univariate density plot for the given column name. Requires a numeric or datetime column
# """
# plt.close()
# # plot a single distribution plot
# sns.displot(data=self.df, kind="kde")
# sns.rugplot(data=self.df)
# plt.title(self.column_name.title())
# plt.show()
def gen_dist_plot(self):
"""
Generates a pair of plots:
- a box and whisker plot on the left
- a histogram on the right
"""
plt.subplot(1, 2, 1)
self.df[self.column_name].plot(kind="box", vert=False)
plt.title("Speech Length (Characters)")
plt.subplot(1, 2, 2)
self.df[self.column_name].plot(kind="hist", bins=30)
plt.show()
def gen_count_plot(self, top_n=10):
"""
Generates a count plot for the given column name.
Returns @top_n values ordered by highest cardinality
"""
plt.close()
sns.countplot(
y=self.column_name,
data=self.df,
order=self.df[self.column_name].value_counts().iloc[:top_n].index,
)
plt.title(self.column_name.title())
plt.show()
def gen_plot(self):
if self.df[self.column_name].dtype == "object":
self.gen_count_plot()
elif self.df[self.column_name].dtype in ["int64", "datetime", "float"]:
self.gen_dist_plot()
else:
raise ValueError("Column type not in [object, int64, datetime, float]")
# un_len = UnivariatePlot(un, "length")
# un_position = UnivariatePlot(df=un, column_name="country")
# un_position.gen_plot()
# un_len.gen_plot()
# un_len.gen_dist_plot_double()
|
#@author: github.com/guidoenr4
#@date: 07-09-2020
import bcolors, time
from random import randrange
def test_cases(cases):
changing, staying = 0, 0
bcolors.print_warning("Testing..")
for i in range(0, cases):
correct, choice = new_case()
if not choice == correct : changing+=1
else : staying+=1
bcolors.print_green("changing the door: " + str(changing) + " cases" )
bcolors.print_blue("staying with your decision: " + str(staying) + " cases" )
def new_case():
return randrange(3), randrange(3)
if __name__ == '__main__':
bcolors.print_red("MONTY-HALL PARADOX, @author> guidoenr4")
cases = int(input("insert the cases to test (with 3 doors): "))
start_time = time.time()
test_cases(cases)
bcolors.print_cviolet('time elapsed: ' + str(time.time() - start_time))
|
from preprocess import *
from lm_train import *
from math import log
def log_prob(sentence, LM, smoothing=False, delta=0, vocabSize=0):
"""
Compute the LOG probability of a sentence, given a language model and whether or not to
apply add-delta smoothing
INPUTS:
sentence : (string) The PROCESSED sentence whose probability we wish to compute
LM : (dictionary) The LM structure (not the filename)
smoothing : (boolean) True for add-delta smoothing, False for no smoothing
delta : (float) smoothing parameter where 0<delta<=1
vocabSize : (int) the number of words in the vocabulary
OUTPUT:
log_prob : (float) log probability of sentence
"""
#TODO: Implement by student.
if 'uni' not in LM and 'bi' not in LM:
print("log_prob: warning: the result is incompleted")
if not smoothing:
delta = 0
vocabSize = 0
log_prob = 0
lsTokens = sentence.split()
nLen_tokens = len(lsTokens)
for i in range(1, nLen_tokens):
iNumo = delta
iDeno = delta * vocabSize
flLog_oneword = 0
if lsTokens[i - 1] in LM['bi'] and lsTokens[i] in LM['bi'][lsTokens[i - 1]]:
iNumo = LM['bi'][lsTokens[i - 1]][lsTokens[i]] + delta
if lsTokens[i - 1] in LM['uni']:
iDeno = LM['uni'][lsTokens[i - 1]] + delta * vocabSize
if iNumo == 0 or iDeno == 0:
flLog_oneword = float('-inf')
log_prob += flLog_oneword
break
else:
flLog_oneword = log(iNumo, 2) - log(iDeno, 2)
log_prob += flLog_oneword
return log_prob
|
from cell import Cell
from typing import List, Tuple
import pygame
from settings import *
import math
surface = pygame.Surface(size)
surface.fill(WHITE)
class FlatBoard:
"""
_board:
A 2 dimensional board that has a size length * length.
Each unit of the board is a size 1 Cell.
"""
_board: List[List[Cell]]
def __init__(self, length: int) -> None:
"""
Initialize the game board, with <length> columns and <length> rows to
generate a square 2 dimensional array of Cells.
"""
self._board = []
for i in range(length):
column = []
x = i * (size[0] // length)
for j in range(length):
y = j * (size[1] // length)
column.append(Cell(x, y, 0))
self._board.append(column)
def __len__(self):
return len(self._board)
def create_copy(self) -> 'FlatBoard':
"""Create a copy of the board, so when checking if neighbours are
alive/dead, can make valid comparisons, meanwhile changing status of
Cell in the original board"""
board_copy = FlatBoard(len(self))
board_copy.set_cell_neighbours()
for column in self._board:
for cell in column:
board_copy._board[cell.x // spacing][
cell.y // spacing].set_state(cell.get_state())
return board_copy
def get_cell(self) -> Cell:
"""Return a cell found at coordinates, x, y"""
mouse_pos = pygame.mouse.get_pos()
mouse_pos_update = (mouse_pos[0] - spacing//2,
mouse_pos[1] - spacing//2)
return self._get_cell_at_position(mouse_pos_update)
def _get_cell_at_position(self, location: Tuple[int, int]) -> Cell:
"""Get the cell that is has a position under <location>"""
x = location[0]
y = location[1]
if x % spacing < math.ceil(spacing / 2):
# if the remainder is less than half of spacing, then round down
x -= (x % spacing)
else:
# if the remainder is greater than half of spacing, the round up
x += (spacing - (x % spacing))
if y % spacing < math.ceil(spacing / 2):
y -= (y % spacing)
else:
y += (spacing - (y % spacing))
return self._board[x//spacing][y//spacing]
def update_cell_status(self, cell: Cell, status: int) -> None:
"""Update the status of a cell"""
cell.set_state(status)
def set_cell_neighbours(self) -> None:
# set the neighbours for every cell
for column in self._board:
for cell in column:
# get all potential positions of cells
diff = size[0] // length
neighbours_pos = [(cell.x - diff, cell.y - diff),
(cell.x - diff, cell.y),
(cell.x - diff, cell.y + diff),
(cell.x, cell.y - diff),
(cell.x, cell.y + diff),
(cell.x + diff, cell.y - diff),
(cell.x + diff, cell.y),
(cell.x + diff, cell.y + diff)]
# check if any of the neighbours are out of bounds
neighbour_cells = []
for pos in neighbours_pos:
if (len(self) > (pos[0] // spacing) >= 0) and \
(len(self) > (pos[1] // spacing) >= 0):
neighbour_cells.append(self._board[pos[0] // spacing]\
[pos[1] // spacing])
cell.set_neighbours(neighbour_cells)
def draw_board(self, active: bool) -> pygame.Surface:
"""Draw a rectangle for each cell on the board."""
for column in self._board:
for cell in column:
if cell.get_state() == 0:
pygame.draw.rect(surface, GREY, (cell.x, cell.y,
size[0]//length,
size[0]//length), 1)
else:
colour = len(cell.get_active_neighbours())
# draw a filled rectangle based on active neighbours
pygame.draw.rect(surface, cell_colour[colour],
(cell.x, cell.y,
size[0] // length,
size[0] // length), 0)
# draw a black outline
pygame.draw.rect(surface, BLACK,
(cell.x, cell.y,
size[0] // length,
size[0] // length), 1)
# draw a black box over the current highlighted cell
if active:
curr_cell = self.get_cell()
pygame.draw.rect(surface, BLACK, (curr_cell.x, curr_cell.y,
size[0]//length,
size[0]//length), 1)
return surface
def update_board(self) -> None:
"""Update <self> to be the next generation of the board."""
board_copy = self.create_copy()
for column in board_copy._board:
for cell in column:
active = cell.get_active_neighbours()
if (cell.get_state() == 0) and (len(active) == 3):
# if the cell is dead, but has 3 active neighbours,
# it becomes alive in the next generation, as by
# reproduction
self._board[cell.x//spacing][cell.y//spacing].set_state(1)
elif (cell.get_state() == 1) and \
((len(active) == 2) or (len(active) == 3)):
# if the cell is alive, and has 2 or 3 live neighbours,
# survives to the next generation
self._board[cell.x//spacing][cell.y//spacing].set_state(1)
else:
# all other cells die
self._board[cell.x//spacing][cell.y//spacing].set_state(0)
def reset_board(self) -> None:
for column in self._board:
for cell in column:
cell.set_state(0)
|
# Python script to show RankList starting from Rank 1 in Terminal
# Author : Pranay Ranjan
from urllib import urlopen
from json import load
response = urlopen(" http://codeforces.com/api/user.ratedList?activeOnly=")
json_obj = load(response)
for obj in json_obj['result']:
print("Handle : "+obj['handle'])
print("Rating : "+str(obj['rating']))
if 'firstName' in obj.keys():
print "Name : "+obj['firstName']+" ",
if 'lastName' in obj.keys():
print obj['lastName'],
print("")
if 'country' in obj.keys():
print "Country/City : "+obj['country']+"/",
if 'city' in obj.keys():
print obj['city'],
print("")
if 'organisation' in obj.keys():
print("Organisation : "+obj['organization'])
print("Contribution : "+str(obj['contribution']))
print("Rank : "+obj['rank'])
print("MaxRank : "+obj['maxRank'])
print("")
print("No. of entries : "+str(len(json_obj['result'])))
|
#"""Sample code to read in test cases:
import sys
test_cases = open(sys.argv[1], 'r')
def rtrip(s):
parts=[int(y) for x,y in [s.strip().split(',') for s in [x for x in s.split(';') if len(x)>1]]]
parts.sort()
for i in range(len(parts)-1,0,-1):
parts[i] -= parts[i-1]
print(','.join(str(x) for x in parts))
for test in test_cases:
# ignore test if it is an empty line
# 'test' represents the test case, do something with it
# ...
# ...
test=test.strip()
if len(test)==0:
continue
rtrip(test)
test_cases.close()
#"""
|
#"""Sample code to read in test cases:
import sys
test_cases = open(sys.argv[1], 'r')
human='This program is for humans'
res=['Still in Mama\'s arms'] * 3 + ['Preschool Maniac'] * 2 + ['Elementary school'] * 7 + ['Middle school' ] * 3 + ['High school' ] * 4 + ['College'] * 4 + ['Working for the man' ] * 43 + ['The Golden Years' ] * 35
for test in test_cases:
# ignore test if it is an empty line
# 'test' represents the test case, do something with it
# ...
# ...
test=test.strip()
if len(test)==0:
continue
i=int(test)
print(res[i] if 0 <= i <= 100 else human)
test_cases.close()
#"""
|
#"""Sample code to read in test cases:
import sys
test_cases = open(sys.argv[1], 'r')
def bal(s):
prev,d,ml,mr=None,0,0,0
for c in s:
if '('==c:
if ':' == prev: ml += 1
else: d += 1
elif ')'==c:
if ':' == prev:
mr += 1
else:
if d > 0: d -= 1
else:
if ml > 0: ml -= 1
else:
d=mr+1
break
prev = c
# comment
print('YES' if d<=mr else 'NO')
for test in test_cases:
# ignore test if it is an empty line
# 'test' represents the test case, do something with it
# ...
# ...
test=test.strip()
if len(test)==0:
continue
bal(test)
test_cases.close()
#"""
|
class Solution():
# Ex 1
# Pascal triangle.
def generate_pascal_triangle(self, rows_num):
if (rows_num == 0):
return []
else:
result = [[1]]
for i in range(1, rows_num):
result.append([0] * (i + 1))
for k in range(i + 1):
if k == 0 or k == i:
result[i][k] = 1
else:
result[i][k] = result[i - 1][k - 1] + result[i - 1][k]
y=sum([2,3])
return result
#Ex. 11
#Calculate the sum of two integers but you are not allowed to use operator + and -
def get_sum_using_list(self,a,b):
result=[a,b]
return sum(result)
def get_sum_using(self,a,b):
return a.__add__(b)
#Ex.
#For a given array find all subsets of the set.
def all_subsets(self,a_list):
if len(a_list)==0:
return [[]]
else:
subsets=self.all_subsets(a_list[1:])
return subsets+[[a_list[0]]+x for x in subsets]
def subsets_of_k_elements(self,a_list,k):
all_sub=self.all_subsets(a_list)
new_list=[]
for x in range(len(all_sub)):
if (len(all_sub[x])==k):
temp=all_sub[x]
new_list.append(temp)
return new_list
# Ex 19
# Given an integer x, find square root of it. If x is not a perfect square, then return floor(√x).
# Algorithm:
# 1) Start with 'start' = 0, end = 'x',
# 2) Do following while 'start' is smaller than or equal to 'end'.
# a) Compute 'mid' as (start + end)/2
# b) compare mid*mid with x.
# c) If x is equal mid*mid, return mid
# d) If x is greater do binary search between mid+1 and end
# e) If x is smaller, do binary search between start and mid-1 GfG
def sqrt_by_binary_search(self,x):
if (x==0 or x==1):
return x
start=1
end=x
while(start<=end):
mid=(start+end)//2
if (mid*mid==x): #case for perfect square
return mid
if(mid*mid<x):
start=mid+1
result=mid
else:
end=mid-1
return result
# Ex (Missing numbers)
# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
def missing_number(self,nums):#mu solution submitted
sum_given=sum(nums)
all_numbers=range(0,len(nums)+1)
sn=sum(all_numbers)
missing_num=sn-sum_given
return missing_num
def missingNumber_lc_solution(self, nums):#lc_solution =solution from leetcode
nums.sort()
# Ensure that n is at the last index
if nums[-1] != len(nums):
return len(nums)
# Ensure that 0 is at the first index
elif nums[0] != 0:
return 0
# If we get here, then the missing number is on the range (0, n)
for i in range(1, len(nums)):
expected_num = nums[i - 1] + 1
if nums[i] != expected_num:
return expected_num
def missing_number_gauss_approach(self,nums):
expected_sum=len(nums)*(len(nums)+1)/2
actual_sum=sum(nums)
return expected_sum-actual_sum
def count_primes(self,n):
primes=[1,2,3,4,5,6,7,8,9,10]
x=primes[3:10:2]
primes[3:10:2]=[0]*len(primes[3:10:2])
return
#Ex
#The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the
# set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
#Given an array nums representing the data status of this set after the error.
# Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
def find_duplicated_number(self,nums):#TODO it doesn't work for [1,1],[2,2]
s_n=sum(nums)
remove_duplicated=set(nums)
duplicated_number=s_n-sum(remove_duplicated)
i=nums[0]
normal_sequence=[i for i in range(nums[0],nums[-1]+1)] #sequence
missing_num=sum(normal_sequence)-sum(remove_duplicated)
return [duplicated_number,missing_num]
if __name__ == "__main__":
o_solution=Solution()
sqrt_binary=o_solution.sqrt_by_binary_search(x=7)
i_missing_numb=o_solution.missing_number(nums=[9,6,4,2,3,5,7,0,1])
erastosthenes=o_solution.count_primes(10)
set_mismatch=o_solution.find_duplicated_number(nums=[2,2])
print('The End')
|
import os
def bubbleSort(array, n):
for i in range(0, n-1):
#last i items are in order, inner loop doesnt need to look at them
for j in range(0,n-1-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
print(array)
array = [2,1,6,4, 8, 10, 100, -24]
n = len(array)
print(array)
bubbleSort(array, n)
|
"""
Spiking Neural Network Solver for Constraint Satisfaction Problems.
This package has been developed by Gabriel Fonseca and Steve Furber at The University of Manchester as part of the
paper:
"Using Stochastic Spiking Neural Networks on SpiNNaker to Solve Constraint Satisfaction Problems"
Submitted to the journal Frontiers in Neuroscience| Neuromorphic Engineering
A constraint satisfaction problem (CSP) is generally described by a set of variables {X_i} taking values over a certain
set of domains {D_i}, over which the set of constraints {C_ij} is imposed. The problem consists in finding assignations
for all variables X_i's so that all C_ij's are satisfied.
To solve a particular CSP import the CSP class from snn_solver.py and create an instance object. To build the solver network
you may implement methods of the CSP class
Additionally, you will be able to keep track of the network dynamics through the functions available in the analysis.py module
e.g. an entropy vs. time plot which colourizes distinctively the regions satisfying the constraints (in Blue) and the ones violating
them (in Red). If an unsatisfying configuration is visited again it will be plotted in green.
Depending on the CSP, you will have a straightforward or a complicated description of the constraints, for the later
it is advised to create a script translating the original problem to a CSP description, examples of this procedure
have been included for:
Sudoku: sudoku2csp.py
Ising Spin Systems spin2csp.py
Travelling Salesman Problem: tsp2csp.py
when the constraints are simple to describe, e.g. for an antiferromagnetic spin chain, we generate the constraints list
on the example script. In the examples subdirectory of the project folder (SpiNNakerCSPs) we provide example implementations for:
Coloring Map Problem: australia_cmp.py and world_cmp.py
Sudoku Puzzle: sudoku_easy.py, sudoku_hard.py and escargot.py
Spin Systems: spin_system.py
In the case of Sudoku, you will find a sudoku_puzzles.py inside the puzzles folder containing some example puzzles to be
imported on examples/sudoku.py
"""
from snn_creator import CSP
from analysis import plot_entropy
from translators.sudoku2csp import sudoku2csp
from translators.spin2csp import spin2csp
from translators.world_bordering_countries import world_borders, world_countries
from puzzles.sudoku_puzzles import puzzles
__all__ = ['snn_creator', 'analysis','CSP','plot_entropy','sudoku2csp','puzzles','spin2csp','world_borders',
'world_countries']
|
def reverse(x):
if abs(x) > 2**31 -1:
return 0
if x >= 0:
if int(str(x)[::-1]) > 2**31 -1:
return 0
return int(str(x)[::-1])
if x < 0:
y = abs(x)
if int(str(y)[::-1]) > 2**31 -1:
return 0
return -int(str(y)[::-1])
print(reverse(100000))
|
# LANG : Python 3.5
# FILE : 01-simple-linear-regression.py
# AUTH : Sayan Bhattacharjee
# EMAIL: [email protected]
# DATE : 27/JULY/2018
# INFO : How does hot soup sale change in winter based on temperature?
# : Here, we do linear regression with ordinary least squares
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
def simple_linreg(n,x,y):
""" Perform simple linear regression
@param n : number of data points for calculation
@param x : the x co-ordinate of the data
@param y : the y co-ordinate of the data
"""
x_bar = sum(x)/float(n) # average of x
y_bar = sum(y)/float(n) # average of y
m = sum((x-x_bar)*(y-y_bar))/ float(sum((x-x_bar)**2) ) # slope
b = y_bar - m*x_bar # y intercept
print("The linear regression has resulted in ...")
print("m(slope) : ",m )
print("b(y intercept) : ",b )
return m,b
if __name__ == "__main__":
# We get the data using which we want to perform linear regression
n = 100 # no. of data points
temp = np.linspace(3, 30, n) # temperature (deg C)
noise = np.random.randint(-2,5,size = n) # noise to simulate RL
soup_sale = np.linspace(40, 22 , n, dtype = 'int') + noise # soup sale count
m,b = simple_linreg(n,temp,soup_sale)
plt.scatter(temp,soup_sale)
plt.plot(temp,m*temp + b,'-r')
plt.title("Temperature vs Soup Sale"
" \n (linear regression with ordinary least squares)")
plt.xlabel("Temp in degree Celcius")
plt.ylabel("Hot soup bowls sold")
plt.grid()
plt.show()
|
# Problem: Receive miles and convert to kilometers
# kilometers = miles * 1.60934
# Enter Miles 5
# 5 miles equals 8.04 kilometers
# Ask the user to input the number of miles and assign it to the miles variable
miles = input("Enter the number of miles you wish to convert: ")
# Convert from string to integer
miles = int(miles)
# Perform caclulation by multiplying 1.60934
kilometers = miles * 1.60934
# Print the result to the screen
#print(miles, "miles equals", kilometers, "kilometers")
print("{} miles equals {} kilometers".format(miles, kilometers))
|
#!/usr/bin/python
#-*- coding:utf-8 -*-
#对训练数据和测试数据 进行过滤 生成字典文件 并去除 非法字符
import codecs,collections,sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def read_data(filename):
fp = codecs.open(filename,'r','utf8');
wordlist = list();
taglist = list();
idx = 0;
while True:
line = fp.readline().strip('\r\n');
if not line: break;
for i in line:
if idx % 2 <> 0:
taglist.append(i);
else:
wordlist.append(i);
idx = idx + 1;
fp.close();
return wordlist,taglist;
if __name__ == '__main__':
if len(sys.argv) <> 2:
print 'Usage: %s pretfile' %sys.argv[0];
sys.exit(-1);
w,t = read_data(sys.argv[1]);
idx = 0;
ws = ts = '';
while True:
if idx >= len(w): break;
if t[idx] == '@':
ws = ws + w[idx];
elif t[idx] == '^':
ws = ws + ' ' + w[idx];
else:
ws = ws + w[idx] + ' ';
idx = idx + 1;
print ws;
|
# Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
def concat(*args, sep="/"):
return sep.join(args)
print(concat("earth", "mars", "venus"))
print(concat("earth", "mars", "venus", sep="."))
|
# The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.
stack = [3, 4, 5]
print (stack)
stack.append(6)
stack.append(7)
print(stack)
print("pop", stack.pop())
print(stack)
print("pop" ,stack.pop())
print(stack)
print("pop", stack.pop())
print(stack)
|
#Operator: +, -, /, *, // (floor division), % (remainder)
print ("2 + 2 = ")
print (2 + 2)
print('')
print ("50 - 5*6 = ")
print (50 - 5*6)
print('')
print ("(50 - 5*6) / 4 = ")
print ((50 - 5*6) / 4)
print('')
print ("8 / 5 = ") #division always returns a floating point number
print (8/5)
print('')
print ("17 / 3 = ") #classic division returns a float
print (17 / 3)
print('')
print ("17 // 3 = ") #floor divions discards the fractional part
print (17 // 3)
print('')
print ("17 % 3 = ") #using the % operator returns the remainder
print (17 % 3)
print('')
print ("5 ** 2 = ") ##using the ** you can calulate powers
print (5 ** 2) #This is equal to 5 squared
print('')
print ("2 ** 7 = ") #2 to the power of 7
print (2 ** 7)
print('')
width = 20
height = 5 * 9
print ("width * height = ")
print (width * height)
print('')
print ("4 * 3.75 - 1 = ")
print (4 * 3.75 - 1)
print ('')
|
# -*- coding: utf-8 -*-
"""
Shows some attacks that can be done against this program.
The different Hijacks were attacks to which we defended. This program is surely
vulnerable to many possible attacks, but not these ones.
Created on Wed May 5 18:02:12 2021
@author: Joachim Favre & Alberts Reisons
"""
import theorem_set as thmset
import theorem as thm
from proof import Proof
class Hijack1(thm.Equality):
"""
(False) theorem that states that a + b^2 = a + b*a + b.
The order of the unknowns is the following: a, b.
It tries to use the fact that the order of operations may not be defined.
"""
def __init__(self, param_list):
super().__init__(param_list,
name="hijack 1",
conclusion="a + b^2 = a + b*a + b",
unknowns=['a', 'b'])
def get_proof(self):
proof = Proof(self, 'a + b^2')
proof.evolve_equality('a + b*a + b',
"a + b^2 = a + b*a + b",
thmset.SquareDistribution(['a + b']))
proof.conclude()
return proof
class Hijack2(thm.Equality):
"""
(False) theorem that states that 2*x + 3*x^2 = 5*x^2.
The order of the unknowns is the following: x.
It tries to use the fact that the order of operations may not be defined.
"""
def __init__(self, param_list):
super().__init__(param_list,
name="hijack 2",
conclusion="2*x + 3*x^2 = 5*x^2",
unknowns=['x'])
def get_proof(self):
proof = Proof(self, '2*x + 3*x^2')
proof.evolve_equality('5*x^2',
'2*x + 3*x = 5*x',
thmset.LitteralAddition(['2', '3', 'x']))
proof.conclude()
return proof
class Hijack3(thm.Equality):
"""
(False) theorem that states that (a + b)^2 = a + b^2.
The order of the unknowns is the following: a, b.
It tries to use the fact that the order of operations may not be defined.
"""
def __init__(self, param_list):
super().__init__(param_list,
name="hijack 3",
conclusion="(a + b)^2 = a + b^2",
unknowns=['a', 'b'])
def get_proof(self):
proof = Proof(self, '(a + b)^2')
proof.evolve_equality('a + b^2',
'(a+b) = a + b',
thmset.RemovalOfParenthesis(['a+b']))
proof.conclude()
return proof
class Hijack4(thm.Equality):
"""
(False) theorem that states that a^2 = a.
The order of the unknowns is the following: a, b.
It tries to use the fact that it may be able to use another theorem to
prove itself, while the other theorem uses this one for its proof. This
other theorem is Hijack4Bis.
"""
def __init__(self, param_list):
super().__init__(param_list,
name="hijack 4",
conclusion="a^2 = a",
unknowns=['a'])
def get_proof(self):
proof = Proof(self, 'a^2')
proof.evolve_equality('a',
'a^2 = a',
Hijack4Bis(['a']))
proof.conclude()
return proof
class Hijack4Bis(thm.Equality):
"""
(False) theorem that states that a^2 = a.
The order of the unknowns is the following: a, b.
It tries to use the fact that it may be able to use another theorem to
prove itself, while the other theorem uses this one for its proof. This
other theorem is Hijack4.
"""
def __init__(self, param_list):
super().__init__(param_list,
name="hijack 4 bis",
conclusion="a^2 = a",
unknowns=['a'])
def get_proof(self):
proof = Proof(self, 'a^2')
proof.evolve_equality('a',
'a^2 = a',
Hijack4(['a']))
proof.conclude()
return proof
|
#!/usr/bin/env python3
# RyanWaltersDev Jun 14 2021 -- introducing the break statement
# Initial prompt
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\n(Enter 'quit' when you are finished.) "
# While loop with break
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"{city.title()} looks beautiful! I'd love to go some day.")
# END OF PROGRAM
|
#!/usr/bin/env python3
# RyanWaltersDev Jun 16 2021 -- Filling a dictionary with user input
# Empty dictionary
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
#Prompt for the person's name and response
name = input("\nWhat is your name? ")
response = input("\nWhich mountain would you like to climb some day? ")
# Store the response in a dictionary
responses[name] = response
# Find out if anyone else is going to take the poll
repeat = input("Would you like to let another person respond? (yes / no) ")
if repeat == 'no':
polling_active = False
# Polling is complete. Print the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
# END OF PROGRAM
|
"""
Uzrakstiet Python programmu, lai iegūtu
starpību starp ievadīto skaitli un 17.
Ja skaitlis ir lielāks par 17, iegūstiet absolūtās starpības dubultu.
"""
def starpiba(a,b):
starpiba=a-b
return starpiba
a=float(input("Ievadi skaitli:"))
print(starpiba(a,17))
|
class Parent():
def __init__(self, last_name, eye_color):
print("Parent constructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print "Last name -",self.last_name
print "Eye color -",self.eye_color
teruzane = Parent("Utada","nebula")
print teruzane.last_name
class Child(Parent):
def __init__(self,last_name,eye_color,num_toys):
print("Child constructor called")
Parent.__init__(self,last_name,eye_color)
self.num_toys = num_toys
def show_info(self):
print "Last name -",self.last_name
print "Eye color -",self.eye_color
print "Number of toys -",self.num_toys
hikaru = Child("Utada","radiant",9999999)
hikaru.show_info()
|
import urllib
folder = r"C:\Users\natal\Documents\Web Dev Nanodegree\0_Programming_Foundations\MiniProjects"
movie = "\movie_quotes.txt"
profane = "\list_of_bad_words.txt"
wdyl = "http://www.wdyl.com/profanity?q="
def read_text(path):
quotes = open(path)
contents = quotes.read()
quotes.close()
return contents
def check_profanity(text_to_check):
#connection = urllib.urlopen(wdyl+text_to_check)
#print connection.read()
#connection.close()
# code is out of date for how wdyl works
contents = read_text(folder+profane)
for word in text_to_check.split():
if word in contents and len(word)>3:
print word,"is a bad word"
return True
return False
check_profanity(read_text(folder+movie))
check_profanity("oh shit I forgot")
check_profanity("oh shoot I forgot")
check_profanity("he's a fucking beast")
check_profanity('fuck')
|
"""lostc.combine
Global combine functions
"""
def combination(items, sequential=True):
"""Generate a combination.
- items: a list like object
- sequential: need sequential? True/False
Return a combination generated from items.
Example:
data = [1, 2]
combination(data) -> {(1, 2), (1, 1), (2, 1), (2, 2)}
combination(data, sequential=False) -> {(1, 2), (1, 1), (2, 2)}
"""
if sequential:
return {tuple(item) for item in product(items, repeat=2)}
else:
return {tuple(sorted(item)) for item in product(items, repeat=2)}
def product(*lists, repeat=1):
"""Generate a product.
- lists: a list of list like object
- repeat: the repeat number of lists
Return a product iterator generated from lists.
Example:
list(product([1, 2], [2, 3])) -> [(1, 2), (1, 3), (2, 2), (2, 3)]
list(product([1, 2])) -> [(1,), (2,)]
list(product()) -> [()]
"""
def _product(lists):
if not lists:
yield tuple()
else:
for item in lists[0]:
for rest in _product(lists[1:]):
yield (item,) + rest
return _product(lists * repeat)
if __name__ == "__main__":
from pprint import pprint as pp
pp(list(product([1, 2, 3], [2, 3, 4])))
pp(list(product([1, 2, 3])))
pp(list(product()))
pp(combination([1, 2, 3]))
pp(combination([1, 2, 3], sequential=False))
|
def show_magicians(printed_names):
for printed_name in printed_names:
print(printed_name.title())
def make_great(changed_lists):
for i in range(4):
#####先用变量i来作为一个标志,然后用range()函数创建0、1、2、3四个数字,
#####用来对应魔术师姓名列表的四个姓名,最后用for循环将姓名之前加上”The Great”,循环结束后返回
changed_lists[i] = 'the Great ' + changed_lists[i]
return changed_lists
magicians = ['job', 'jane', 'stand', 'smile']
magicians_2=magicians[:]######创建副本
make_great(magicians_2)
show_magicians(magicians_2)
|
import csv
import sys
def bubbleSort(list_1):
for i in range(len(list_1)-1):
for j in range(len(list_1)-1):
if list_1[j]>list_1[j+1]:
temp = list_1[j]
list_1[j]=list_1[j+1]
list_1[j+1]=temp
def ortalama(list):
top,index=0,0
leng = len(list)
for i in range(leng):
top = list[i] + top
index=index+1
a = top // index
return a
def cokluhisto(list,dictionary):
for element in list:
for i in element:
if int(i) not in dictionary:
dictionary[int(i)]=1
else:
dictionary[int(i)]=dictionary[int(i)]+1
return dictionary
def histo(array):
dic = dict()
for i in array:
if i not in dic:
dic[i]=1
else:
dic[i]=dic[i]+1
return dic
with open("sys.argv[1]+"\input_hw_2.csv", "r") as file:
reader = csv.reader(file,delimiter = ';')
mainarray= []
for row in reader:
stri = str(row[3])
splited1= stri.split()
stri2= splited1[0]
splited2= stri2.split("-")
mainarray.append(splited2)
aylar = []
for i in mainarray:
aylar.append(i[1])
a = histo(aylar)
toplam,index = 0,0
values=[]
for key, value in a.items():
print(f"{key}. ay {value} kişi ayrıldı")
toplam=toplam+value
index=index+1
values.append(value)
bubbleSort(values)
ort = toplam//index
result = 0
if index %2 == 1:
result = index//2
medyan=values[result]
stringg = f"ortalama: {ort} \nmedyan: {medyan}"
txtdosyasi = open(sys.argv[2]+"\170401021_hw_2_output.txt","w")
txtdosyasi.write(stringg)
txtdosyasi.close()
|
#!/usr/bin/python
import sys
import datetime
# compute the time difference between the first and the last visit for each host
prev_host = ''
count = 0
# initialize start time and end time for the host
start_time = datetime.datetime(datetime.MAXYEAR, 12, 31)
end_time = datetime.datetime(datetime.MINYEAR, 1, 1)
for line in sys.stdin:
line = line.strip()
host, timestamp = line.split("\t")
# decode timestamp to datetime class
# the format of datetime is (year, month, day, hour, minute, second)
time = datetime.datetime.strptime(timestamp, '%d/%b/%Y:%H:%M:%S')
if host == prev_host:
# compare current timestamp with start time and end time
if time < start_time:
start_time = time
if time > end_time:
end_time = time
count += 1
else:
if prev_host:
# if a host visits only once then print the timestamp of the visit
# the count value indicates the frequency of host appearing in the input
if count == 1:
print "%s\t%s" % (prev_host, start_time)
else:
print "%s\t%s" % (prev_host, str(end_time-start_time))
# clear and load the new time
start_time = time
prev_host = host
count = 1
end_time = datetime.datetime(datetime.MINYEAR, 1, 1)
else:
# prev_host that is null means that this is the first host read in
start_time = time
prev_host = host
count = 1
# emit the last host and its visit time difference
if count == 1:
print "%s\t%s" % (prev_host, start_time)
else:
print "%s\t%s" % (prev_host, str(end_time-start_time))
|
#!/usr/bin/python
import sys
import re
# mapper emits student name and his/her grade point average(gpa)
if __name__ == '__main__':
name = ''
grade = 0
gpa = 0
for line in sys.stdin:
line = line.strip().split()
# check if the student takes more than 4 courses
if len(line) > 6:
gpa = 0
grade = 0
name = line[0]
for i in range(2,len(line)):
# use regular expression module to extract the mark of each course
grade += int(re.findall(r"[\w']+", line[i])[-1])
# calculate the gpa
gpa = float(grade)/(len(line)-2)
# emit name/gpa pair
print "%s\t%s" % (name,str(round(gpa,2)))
|
# age = int(input('Enter your age:'))
# if age < 10:
# print('your are young stargn one')
# elif age < 40:
# print('the fire is you is strong, strange one')
# else:
# print('you are wise beyond doubt, strange one')
meaty = input('Do you eat meat? (y/n')
if meaty == 'y':
print('you meaty mofo you')
else:
print('here is the veggie')
|
def squares_by_comp(n):
return [k**2 for k in range(n) if k % 3 == 1]
def squares_by_loop(n):
"""Re-wrote the squares_by_comp function to return the squares by loop instead"""
liste = []
for number in range(n):
if number % 3 == 1:
liste.append(number**2)
return liste
if __name__ == '__main__':
if squares_by_comp(10) != squares_by_loop(10):
print('Error!')
|
SUITS = ('C', 'S', 'H', 'D')
VALUES = range(1, 14)
def deck_loop():
deck = []
for suit in SUITS:
for val in VALUES:
deck.append((suit, val))
return deck
def deck_comp():
"""This function returns a deck of cards where 1 equals ace and
13 equals king etc. C is clubs, S is spade, H is hearts and D is diamonds"""
deck = [(suit, val) for suit in SUITS for val in VALUES]
return deck
if __name__ == '__main__':
if deck_loop() != deck_comp():
print('ERROR!')
|
# printing board
def boardt(board):
print('\n'*20)
print(' | |')
print(' ' + board[7] + ' | ' + '' + board[8] + ' |' + ' ' + board[9])
print(' | |')
print('------------')
print(' | |')
print(' ' + board[4] + ' | ' + '' + board[5] + ' | ' + ' ' + board[6])
print(' | |')
print('------------')
print(' | |')
print(' ' + board[1] + ' | ' + '' + board[2] + ' | ' + ' ' + board[3])
print(' | |')
x=['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
yes=False
def win_check(board,m):
return(board[1]==board[2]==board[3]==m or
board[4]==board[5]==board[6]==m or
board[7]==board[8]==board[9]==m or
board[1]==board[4]==board[7]==m or
board[2]==board[5]==board[8]==m or
board[3]==board[6]==board[9]==m or
board[7]==board[5]==board[3]==m or
board[1]==board[5]==board[9]==m)
def board_check(board):
if ' ' in board[1:]:
return False
else:
return True
i=0
p1=input('Please select your marker X or O').capitalize()
if p1 == 'X':
p2 = 'O'
else:
p2 = 'X'
while i<=3:
position1=int(input('Player 1:: Where Do you wanna Mark your Marker'))
x[position1]=p1
boardt(x)
if win_check(x,'X')==True:
print('Player 1 wins!!')
else:
if win_check(x,'O')==True:
print('Player 2 wins!!')
else:
print('Match is a tie')
if win_check(x,'O')==True or win_check(x,'X')==True:
play = input('Do you wanna play again (y/n)')
if play=='y':
yes=True
i=0
else:
print('Thanks for playing :-)')
break
position2 = int(input('Player 2:: where do you wanna mark your marker'))
x[position2] = p2
boardt(x)
i += 1
|
import pandas
import numpy
import sklearn
import sklearn.model_selection
import sklearn.linear_model
import matplotlib.pyplot as pyplot
from matplotlib import style
import pickle
data = pandas.read_csv("student-mat.csv", sep=';')
data = data[["G1", "G2", "G3", "studytime", "failures", "absences", "age", "freetime", "Dalc"]]
predict = "G3"
X = numpy.array(data.drop([predict], 1))
Y = numpy.array(data[predict])
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, Y, test_size = 0.1)
'''
best = 0
for _ in range(30):
# x_train is an arbitrarily selected section of 90% of the attributes, and x_test is the other 10%.
# y_train is an arbitrarily selected section of 90% of the labels, and y_test is the other 10%.
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, Y, test_size = 0.1)
linearModel = sklearn.linear_model.LinearRegression()
linearModel.fit(x_train, y_train)
accuracy = linearModel.score(x_test, y_test)
if accuracy > best:
print('Accuracy: ', accuracy)
best = accuracy
with open("studentmodel.pickle", "wb") as file:
pickle.dump(linearModel, file)
'''
pickle_in = open("studentmodel.pickle", "rb")
linearModel = pickle.load(pickle_in)
print('Coefficient: ', linearModel.coef_)
print('Intercept: ', linearModel.intercept_)
# predictions = linearModel.predict(x_test)
# for i in range(len(predictions)):
# print(predictions[i], x_test[i], y_test[i])
#Visualize attribute effect
effect = 'Dalc'
style.use("ggplot")
pyplot.scatter(data[effect], data["G3"])
pyplot.xlabel(effect)
pyplot.ylabel("Final Grade")
pyplot.show()
|
'''
Dada una concesionaria de autos, un cliente va a solicitar un presupuesto,
debe preguntarsele:
*Nombre y apellido del comprador.
*Marca
*Puertas
*Color
Marcas posibles y sus precios:
1. Ford: $100000
2. Chevrolet: $120000
3. Fiat: $80000
Por la cantidad de puertas se añade un precio:
2: $50000
4: $65000
5: $78000
Dependiendo del color, se deben sumar:
1. Blanco: $10000
2. Azul: $20000
3. Negro: $30000
'''
car_value = 0
client_name = ""
def client_full_name():
client_name = str(input('Indique nombre y apellido, por favor: '))
return client_name
def car_brand_budget():
car_brand = int(input('Marque 1 si desea un Ford, 2 si desea un Chevrolet o 3 si desea un Fiat: '))
if car_brand == 1:
return 100000
elif car_brand == 2:
return 120000
elif car_brand == 3:
return 80000
print(' El auto de esa marca vale ', car_brand, 'pesos' )
def car_door_budget():
car_doors = int(input('¿Desea 2, 4 o 5 puertas?: '))
if car_doors == 2:
return 50000
elif car_doors == 4:
return 65000
elif car_doors == 5:
return 78000
print ('Con ese número de puertas vale', car_doors, 'pesos')
def car_color_budget():
car_color = int(input('Marque 1 para el color blanco, 2, para el color azul, 3 para el color negro: '))
if car_color == 1:
return 10000
elif car_color == 2:
return 20000
elif car_color == 3:
return 30000
print('Ese color tiene un valor de ', car_color)
def car_total_price():
amount = car_value
print(client_name, 'El costo del auto es de', car_value, 'pesos')
client_full_name()
car_brand_budget()
car_door_budget()
car_color_budget()
car_total_price()
|
import pygame
from pygame.sprite import Group
from ship import Ship
class Scoreboard:
"""Report score information."""
def __init__(self, game):
""""""
self.settings = game.settings
self.screen = game.screen
self.screen_rect = self.screen.get_rect()
self.stats = game.stats
self.game = game
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
# Prepare the initial scoring information.
self.prep_score()
self.prep_high_score()
self.prep_level()
self.prep_ships()
def prep_score(self):
"""Turn the score text into the image."""
rounded_score = round(self.stats.score, -1)
score = "{:,}".format(rounded_score)
self.score_img = self.font.render(
score, True, self.text_color, self.settings.bg_color)
# Display the score at the top right of the screen
self.score_img_rect = self.score_img.get_rect()
self.score_img_rect.top = 20
self.score_img_rect.right = self.screen_rect.right - 20
def prep_high_score(self):
"""Turn the high score into the image."""
high_score_rounded = round(self.stats.high_score, -1)
hight_score_str = "{:,}".format(high_score_rounded)
self.high_score_img = self.font.render(
hight_score_str, True, self.text_color, self.settings.bg_color)
# Display the score at the top top of the screen
self.high_score_img_rect = self.high_score_img.get_rect()
self.high_score_img_rect.centerx = self.screen_rect.centerx
self.high_score_img_rect.top = 20
def prep_level(self):
"""Turn the level into the image."""
level_str = str(self.stats.level)
self.level_img = self.font.render(
level_str, True, self.text_color, self.settings.bg_color)
# Position the level below the score.
self.level_img_rect = self.level_img.get_rect()
self.level_img_rect.top = self.score_img_rect.bottom + 10
self.level_img_rect.right = self.score_img_rect.right
def prep_ships(self):
"""Show how many ships are left."""
self.ships = Group()
for ship_number in range(self.stats.ships_left):
ship = Ship(self.game)
ship.rect.x = 10 + ship_number * ship.rect.width
ship.rect.y = 10
self.ships.add(ship)
def show_score(self):
"""Draw score to the screen."""
self.screen.blit(self.score_img, self.score_img_rect)
self.screen.blit(self.high_score_img, self.high_score_img_rect)
self.screen.blit(self.level_img, self.level_img_rect)
self.ships.draw(self.screen)
def check_high_score(self):
"""Check if there is a new high score."""
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
self.prep_level()
|
a=input("enter the value:")
while(a!='q'):
print("Enter another value")
a=input()
|
# dynamic array similar to build-in list data structure in python
import ctypes
class DynamicArray:
def __init__(self):
self._n = 0 # current total numbers in array
self._size = 1 # underlaying size of array, increased by double every time
self._array = self._make_array(self._size) # underlaying static array
def __len__(self): # returns length of array
return self._n
def __getitem__(self,k): # this is for working of a[k] indexing operation over array
if not 0 <= k < self._n:
raise IndexError('Index out of bound')
return self._array[k]
def append(self,val): # append val at the end of array
if self._n == self._size:
self._resize(2 * self._size)
self._array[self._n] = val
self._n += 1
def _resize(self,new_size): # resize the internal array to new_size
temp = self._make_array(new_size)
for i in range(self._n):
temp[i] = self._array[i]
self._array = temp
self._size = new_size
def _make_array(self,size): # using cytypes for array
return (size * ctypes.py_object)()
if __name__ == "__main__":
arr = DynamicArray()
arr.append(3)
arr.append(5)
print(len(arr))
print(arr[5])
|
# implementing priority queue using heapq
import heapq
class Item:
def __init__(self,name):
self._name = name
def __str__(self):
return 'Item({!r})'.format(self._name)
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority): # pushing -priority as it's min queue, pushing index to make tuple unique as even the element having same priority it will check
# for index which will definately different and higher gets priority
heapq.heappush(self._queue, (-priority, self._index, item ))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)
if __name__ == "__main__":
q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('foo1'), 8)
q.push(Item('foo2'), 5)
q.push(Item('foo3'), 3)
print(q._queue)
print(q.pop())
|
# diameter of tree
# diameter is longest distance between two nodes of tree
# diameter does not need to pass from root
class Node:
def __init__(self,val):
self.left = None
self.right = None
self.val = val
def height(root):
if root is None:
return 0
else:
return 1 + max(height(root.left),height(root.right))
def diameter(root):
if root is None:
return 0
lheight = height(root.left)
rheight = height(root.right)
ldiameter = diameter(root.left)
rdiameter = diameter(root.right)
# it's max of two cases, if first argument is max that means diameter passes through
# root and if it's second argument then it's other case where diameter doesn't passes through root
return max(1 + lheight + rheight, max(ldiameter,rdiameter))
# Create a root node
root = Node(5)
root.left = Node(3)
root.right = Node(8)
print(diameter(root))
|
# Generate all subsets
# adding each element in one row, i.e for cur_comb call recursively for adding element and not adding element
# complexity 2^n
class Solution:
def generateSubsets(self,arr,cur_comb,n):
if n == 0: # base condition to end
print(cur_comb)
else:
self.generateSubsets(arr,cur_comb, n - 1)
cur_comb.append(arr[n-1])
self.generateSubsets(arr,cur_comb, n - 1)
cur_comb.pop() # otherwise we have to send seperate copy to each call
if __name__ == "__main__":
obj = Solution()
arr = [1,2,3]
obj.generateSubsets(arr,[],len(arr))
|
"""
list uses dynamic allocation inside, this can be evident from fixed size of object when new elements are added.
Internally it allocates memeory greater than it requested.
"""
import sys
test_list = []
iteration = 25
for i in range(iteration):
n = len(test_list)
size = sys.getsizeof(test_list) # get the size of given object
print("Length of list: {0}, size of list in bytes: {1}".format(n,size))
test_list.append(i)
|
""" min oriented priority queue implemented with binary heap array based implementation """
from python_priority_queue import PriorityQueueBase
class HeapPriorityQueue(PriorityQueueBase):
def _parent(self,j):
return (j - 1) // 2
def _left(self,j):
return 2*j + 1
def _right(self,j):
return 2*j + 2
def _has_left(self,j):
return self._left(j) < len(self._data)
def _has_right(self,j):
return self._right(j) < len(self._data)
def _swap(self,i,j):
""" swap the elements at indices i and j """
self._data[i], self._data[j] = self._data[j], self._data[i]
def _upheap(self,j):
parent = self._parent(j)
if j > 0 and self._data[j] < self._data[parent]:
self._swap(j,parent)
self._upheap(parent)
def _downheap(self,j):
if self._has_left(j):
left = self._left(j)
small_child = left
if self._has_right(j):
right = self._right(j)
if self.data[right] < self.data[left]:
small_child = right
if self.data[small_child] < self.data[j]:
self.swap(j, small_child)
self.downheap(small_child)
########################## Public Methods #############################
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def add(self,key,value):
self._data.append(self._Item(key,value))
self._upheap(len(self._data) - 1 )
def min(self):
if self.is_empty():
raise Empty('Priority queue is empty')
item = self._data[0] # getting root element
return (item._key,item._value)
if __name__ == "__main__":
heapq = HeapPriorityQueue()
heapq.add(3,4)
heapq.add(8,21)
heapq.add(2,3)
heapq.add(4,5)
print(heapq.min())
|
# import XML libraries
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import HTMLParser
# Function to create an XML structure
def make_problem_XML(
problem_title='Missing title',
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'correctness': 'true', 'text': 'Answers are missing'}],
solution_text = '<p>Missing solution</p>',
options = {'problem_type': 'MC'}):
"""
make_problem_XML: a function to create an XML object for an edX problem.
The actual work is done by other functions below,
make_choice_problem_XML() and make_line_problem_XML(),
which use the arguments as listed below.
Arguments:
- problem_title: The title of the problem. Required.
- problem_text: The extended text for the problem, including paragraph tags and other HTML.
This argument is genuinely optional.
- label_text: The action statement for the problem. Should be a single line of text.
This is the instruction for the student and is required.
- description_text: Additional info, like "check all that apply" for those kinds of problems.
This argument is genuinely optional.
- answers: A list of dictionaries as follows:
For Numerical and Text problems:
[{'answer': a correct answer}, {'answer': another correct answer}, {etc}]
For MC and Checkbox problems, each item in the list will become an answer choice:
[{'correctness': 'true' or 'false', 'answer': 'the text for this option'}, {etc}, {etc}]
The text for MC and Checkbox can include LaTeX and images. No hints currently included.
- solution_text: The extended text for the solution, including paragraph tags and other HTML.
- options: A dictionary of options. Currently accepts:
"problem_type", which can be...
"MC": Multiple-choice problems
"Checkbox": Select-all-that-apply. Does partial credit by default.
"Numerical": Numerical problems, with a 5% tolerance
"Text": Text-entry problem
"AnyText": A custom-grader problem that marks any text entered as correct
"showanswer",
"weight",
"rerandomize", and
"max_attempts",
which take the typical values for those arguments in edX
"tolerance" for numerical problems.
Please send a decimal and we'll interpret it as a percentage. 0.1 = 10% tolerance.
Later this may include other problem types, partial credit info, etc.
The default values for these arguments are used for troubleshooting.
Return: an XML element tree.
"""
# Create the tree object with its root element
problem_tag = ET.Element('problem')
problem_tag.set('display_name', problem_title)
problem_tree = ET.ElementTree(problem_tag)
# Add a script tag so our problems can re-render properly
# with a minimum of download burden.
# Relies on having Prism.js available.
script_tag = ET.SubElement(problem_tag, 'script')
script_tag.set('type', 'text/javascript')
script_raw = """
$(document).ready(function(){
console.log('highlighting MATLAB syntax');
$('.language-matlab').each(function(e){
window.Prism.highlightAllUnder(this);
});
});
"""
script_tag.text = script_raw
# Set other problem options. For partial documentation see:
# https://edx.readthedocs.io/projects/edx-open-learning-xml/en/latest/components/problem-components.html
if 'showanswer' in options:
problem_tag.set('showanswer', options['showanswer'])
if 'weight' in options:
problem_tag.set('weight', options['weight'])
if 'rerandomize' in options:
problem_tag.set('rerandomize', options['rerandomize'])
if 'max_attempts' in options:
problem_tag.set('max_attempts', options['max_attempts'])
# Add the problem text
if problem_text is not False:
problem_tag.text = problem_text
# Pass the tree to functions that build the rest of the problem XML.
if options['problem_type'] == 'Numerical' or options['problem_type'] == 'Text':
return make_line_problem_XML(
problem_tree, problem_tag, problem_text, label_text, description_text,
answers, solution_text, options
)
elif options['problem_type'] == 'MC' or options['problem_type'] == 'Checkbox':
return make_choice_problem_XML(
problem_tree, problem_tag, problem_text, label_text, description_text,
answers, solution_text, options
)
elif options['problem_type'] == 'AnyText':
return make_anytext_problem_XML(
problem_tree, problem_tag, problem_text, label_text, description_text,
answers, solution_text, options
)
else:
# Leaving out error messages until we decide which version of Python we're using.
# print 'The ' + str(options['problem_type']) + ' problem type is not currently supported.'
return False
# Function to create the XML structure for MC and checkbox problems
# Parameters are described under make_problem_XML() above.
def make_choice_problem_XML(
problem_tree,
problem_tag,
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'correctness': 'true', 'answer': 'Answers are missing'}],
solution_text = '<p>Missing solution</p>',
options = {'problem_type': 'MC'}):
# Create the structure for the problem.
if options['problem_type'] == 'MC':
type_tag = ET.SubElement(problem_tag, 'multiplechoiceresponse')
type_tag.set('type','MultipleChoice')
elif options['problem_type'] == 'Checkbox':
type_tag = ET.SubElement(problem_tag, 'choiceresponse')
type_tag.set('partial_credit', 'EDC')
# Needs some expansion for various extra credit options.
if 'extra_credit' in options:
type_tag.set('extra_credit', options['extra_credit'])
label_tag = ET.SubElement(type_tag, 'label')
label_tag.text = label_text
if options['problem_type'] == 'Checkbox' and description_text is False:
description_text = 'Check all that apply.'
if description_text is not False:
description_tag = ET.SubElement(type_tag, 'description')
description_tag.text = description_text
if options['problem_type'] == 'MC':
choicegroup_tag = ET.SubElement(type_tag, 'choicegroup')
elif options['problem_type'] == 'Checkbox':
choicegroup_tag = ET.SubElement(type_tag, 'checkboxgroup')
# Iterate over the choices and add them one by one.
for item in answers:
item_tag = ET.SubElement(choicegroup_tag, 'choice')
item_tag.set('correct', item['correctness'])
item_tag.text = item['answer']
if 'hint' in item:
hint_tag = ET.SubElement(item_tag, 'choicehint')
hint_tag.text = item['hint']
# Create the structure for the solution
solution_tag = ET.SubElement(type_tag, 'solution')
solution_div_tag = ET.SubElement(solution_tag, 'div')
solution_div_tag.set('class', 'detailed-solution')
explanation_p_tag = ET.SubElement(solution_div_tag, 'p')
explanation_p_tag.text = 'Explanation'
explanation_p_tag.tail = solution_text
return problem_tree
# Function to create the XML structure for numerical or text problems.
# Parameters are described under make_problem_XML() above.
def make_line_problem_XML(
problem_tree,
problem_tag,
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'answer': '-1'}],
solution_text = '<p>Missing solution</p>',
options = {'problem_type': 'Text'}):
# Create the structure for the problem.
if options['problem_type'] == 'Numerical':
type_tag = ET.SubElement(problem_tag, 'numericalresponse')
if 'tolerance' not in options:
options['tolerance'] = 0.05 # 5% tolerance on numerical problems by default.
else:
type_tag = ET.SubElement(problem_tag, 'stringresponse')
type_tag.set('type', 'ci') # case-insensitive by default.
# Needs some expansion for various extra credit options.
# if 'extra_credit' in options:
# type_tag.set('extra_credit', options['extra_credit'])
type_tag.set('answer', answers[0]['answer'])
label_tag = ET.SubElement(type_tag, 'label')
label_tag.text = label_text
if description_text is not False:
description_tag = ET.SubElement(type_tag, 'description')
description_tag.text = description_text
# Add additional answers if they exist.
if len(answers) > 1:
for item in answers:
additional_answer_tag = ET.SubElement(type_tag, 'additional_answer')
additional_answer_tag.set('answer', item['answer'])
if options['problem_type'] == 'Numerical':
input_tag = ET.SubElement(type_tag, 'formulaequationinput')
tolerance_tag = ET.SubElement(type_tag, 'responseparam')
tolerance_tag.set('type', 'tolerance')
tolerance_tag.set('default', str(int(float(options['tolerance']) * 100)) + '%')
else:
input_tag = ET.SubElement(type_tag, 'textline')
input_tag.set('size', '30')
# Create the structure for the solution
solution_tag = ET.SubElement(type_tag, 'solution')
solution_div_tag = ET.SubElement(solution_tag, 'div')
solution_div_tag.set('class', 'detailed-solution')
explanation_p_tag = ET.SubElement(solution_div_tag, 'p')
explanation_p_tag.text = 'Explanation'
explanation_p_tag.tail = solution_text
return problem_tree
# Function to create the XML structure for "anything is correct" problems.
# Parameters are described under make_problem_XML() above.
def make_anytext_problem_XML(
problem_tree,
problem_tag,
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'correctness': 'true', 'answer': 'Answers are missing'}],
solution_text = '<p>Missing solution</p>',
options = {'problem_type': 'AnyText', 'feedback':'Thank you for your response.'}):
# Insert the python grading script
pythonscript = """
<![CDATA[
def test_text(expect, ans):
if ans:
return True
def hint_fn(answer_ids, student_answers, new_cmap, old_cmap):
aid = answer_ids[0]
hint = ''
hint = '""" + options['feedback'] + """'.format(hint)
new_cmap.set_hint_and_mode(aid,hint,'always')
]]>
"""
script_tag = ET.SubElement(problem_tag, 'script')
script_tag.set('type','loncapa/python')
script_tag.text = pythonscript
# Make the customresponse tag and its sub-tags
type_tag = ET.SubElement(problem_tag, 'customresponse')
type_tag.set('cfn', 'test_text')
type_tag.set('expect', 'anything')
textline_tag = ET.SubElement(type_tag, 'textline')
textline_tag.set('size', '40')
textline_tag.set('correct_answer', 'anything')
textline_tag.set('label', 'Your response')
hintgroup_tag = ET.SubElement(type_tag, 'hintgroup')
hintgroup_tag.set('hintfn', 'hint_fn')
# Create the structure for the solution
solution_tag = ET.SubElement(type_tag, 'solution')
solution_div_tag = ET.SubElement(solution_tag, 'div')
solution_div_tag.set('class', 'detailed-solution')
explanation_p_tag = ET.SubElement(solution_div_tag, 'p')
explanation_p_tag.text = 'Explanation'
explanation_p_tag.tail = solution_text
return problem_tree
def write_problem_file(problem_XML, problem_filename):
"""
write_problem_file: write a complete edX problem XML structure to disk.
Arguments:
- problem_XML: The ElementTree object for the problem.
- problem_filename: The filename.
Return: True if successful, False if not.
Outputs: A pretty-printed XML file at 4 spaces per indent
"""
# HTML entities in the problem text get encoded during the XML-writing step, so we need to decode them here.
parser = HTMLParser.HTMLParser()
xml_string = minidom.parseString(ET.tostring(problem_XML.getroot())).toprettyxml(indent=" ")
xml_string = parser.unescape(xml_string)
with open(problem_filename, "w") as f:
# We start from character 23 because the XML declaration is an unwanted 22 characters (counting \r).
# I should do this better, but this works for now.
f.writelines(xml_string[23:])
#################
# Testing code
#################
"""
# Make an MC problem
title = 'Sample MC Problem'
text = '<p>test text</p>'
label = 'test label'
answers = [{'answer': 'wrong one', 'correctness': 'false', 'hint':'Don\'t choose the wrong one.'}, {'answer': 'right one', 'correctness': 'true', 'hint':'The right one was right!'}]
solution = '<p>blank solution</p>'
options = {'problem_type': 'MC'}
the_xml = make_problem_XML(
problem_title = title,
problem_text = text,
label_text = label,
answers = answers,
solution_text = solution,
options = options)
write_problem_file(the_xml, 'test_MC_problem.xml')
# Make a checkbox problem
title = 'Sample Checkbox Problem'
text = '<p>test text</p>'
label = 'test label'
answers = [{'answer': 'wrong one', 'correctness': 'false'}, {'answer': 'right one', 'correctness': 'true'}]
solution = '<p>blank solution</p>'
options = {'problem_type': 'Checkbox'}
the_xml = make_problem_XML(
problem_title = title,
problem_text = text,
label_text = label,
answers = answers,
solution_text = solution,
options = options)
write_problem_file(the_xml, 'test_check_problem.xml')
# Make a numerical problem
title = 'Sample Numerical Problem'
text = '<p>The answer is 50</p>'
label = 'test label'
answers = [{'answer': '50'}]
solution = '<p>blank solution</p>'
options = {'problem_type': 'Numerical'}
the_xml = make_problem_XML(
problem_title = title,
problem_text = text,
label_text = label,
answers = answers,
solution_text = solution,
options = options)
write_problem_file(the_xml, 'test_numerical_problem.xml')
# Make a text problem
title = 'Sample Text Problem'
text = '<p>The answer is "kaboom"</p>'
label = 'test label'
answers = [{'answer': 'kaboom'}]
solution = '<p>blank solution</p>'
options = {'problem_type': 'Text'}
the_xml = make_problem_XML(
problem_title = title,
problem_text = text,
label_text = label,
answers = answers,
solution_text = solution,
options = options)
write_problem_file(the_xml, 'test_text_problem.xml')
# Make an AnyText problem
title = 'Sample AnyText Problem'
text = '<p>Any answer should work</p>'
label = 'test label'
answers = [{'answer': 'this should never appear'}]
solution = '<p>blank solution</p>'
options = {'problem_type': 'AnyText', 'feedback':'Thank you for your response.'}
the_xml = make_problem_XML(
problem_title = title,
problem_text = text,
label_text = label,
answers = answers,
solution_text = solution,
options = options)
write_problem_file(the_xml, 'test_anytext_problem.xml')
"""
|
"""
This File Contains Menu for Customer Account Operations
pylint Score--9.08
"""
# pylint: disable-msg=C0103
from customer import Customer
def open_account_interface():
"""
Prompt User to Enter valid account no and Customer Name
:return: Customer instance for Current User
"""
while True:
print "Enter Account No"
read_account = raw_input()
print "Enter name"
read_username = raw_input()
current_customer = Customer(read_username)
current_customer.open_account(int(read_account))
if current_customer.check_balance() != -1:
check_account_details_interface(current_customer)
return current_customer
else:
print "Enter valid Account NO and Name"
def check_account_details_interface(input_customer):
"""
Shows Menu to Customer-- Customer is able to get his account details
:param input_customer: Takes Customer instance as parameter
:return: None
"""
while True:
print "1: Press 1 to Deposit Money"
print "2: Press 2 to get your Account Number"
print "3: Press 3 to Check Balance"
print "4: Press 4 to Withdraw Amount"
print "5: Press 5 to Transfer Amount"
print "6: Press 6 to Pay Bills"
print "7: Press 7 to get Account Type"
print "8: Press 8 to exit"
read_menu = raw_input()
if read_menu == "8":
break
elif read_menu == "1":
print "Enter amount to deposit"
read_amount = raw_input()
input_customer.deposit(int(read_amount))
elif read_menu == "2":
print input_customer.get_account_number()
elif read_menu == "3":
print input_customer.check_balance()
elif read_menu == "4":
print "Enter amount to withdraw"
read_amount = raw_input()
input_customer.withdraw(int(read_amount))
elif read_menu == "5":
print "Enter other account to which to Transfer amount"
read_account = raw_input()
print "Enter Amount to Transfer"
read_amount = raw_input()
input_customer.transfer_money(int(read_account), int(read_amount))
elif read_menu == "6":
print "Enter Amount to PayBills"
read_amount = raw_input()
input_customer.pay_bills(int(read_amount))
elif read_menu == "7":
print input_customer.get_account_type()
else:
print "Enter valid Number"
# Command Line based Interface
while True:
print "1: Press 1 to open a new Account"
print "2: Press 2 to open an existing Account"
print "3: Press 3 To Compare balance of Two accounts"
print "4: Press 4 To exit"
input_read = raw_input()
if input_read == "4":
break
if input_read == "1":
print "Please Enter your Name"
read_name = raw_input()
customer = Customer(read_name)
print "Please Specify Account Type. S for Saving and C for checking "
while True:
read_Type = raw_input()
if read_Type == "S":
customer.request_new_account("S")
break
elif read_Type == "C":
customer.request_new_account("C")
break
else:
print "Please Enter Valid Account Type"
check_account_details_interface(customer)
if input_read == "2":
customer = open_account_interface()
if input_read == "3":
customer1 = open_account_interface()
print customer1.check_balance()
customer2 = open_account_interface()
print customer2.check_balance()
value = customer1.compare_accounts(customer2)
if value == 0:
print "balance Equal in these accounts"
elif value == 1:
print "1st Account balance is Greater than 2nd"
else:
print "1st Account balance is less than 2nd"
|
#!/usr/bin/python
import csv
class Account(object):
def __init__(self):
""" Initilize Account object
to default value
"""
self.account_no=-1
self.account_type=""
self.balance=-1
def set_account(self,a_id,a_type,a_balance):
""" Sets values of all attributes of
Account to Specified values
"""
self.account_no=a_id
self.account_type=a_type
self.balance=a_balance
def withdraw(self, amount):
""" Withdraw Specified amount
from current account
"""
if self.balance > amount:
self.balance-=amount
self.makeupdate()
return self.balance
# MakeUpdate in Storage
def makeupdate(self):
""" Update Balance
in the Storage
"""
new_rows_list = []
with open('customercom.csv', 'rb') as f:
reader = csv.reader(f,delimiter=',')
for row in reader:
if(int(row[2])==self.account_no ):
row[4]=self.balance
new_rows_list.append(row)
f.close()
with open('customercom.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(new_rows_list)
f.close()
# Deposit amount in account
def deposit(self, amount):
""" Deposit Specified amount
to the Current Balance value
"""
self.balance += amount
self.makeupdate();
return self.balance
# Check Available balance
def Checkbalance(self):
return self.balance
# Deposit Utility Bills
def PayBills(self,amount):
self.Transfer_Money(4,amount)
# Return Account Types
def get_account_type(self):
return self.account_type
# Overload equal operator
def __eq__(self,other_account):
if(self.balance==other_account.balance):
return 1
else:
return 0
# Overload Less than Operator
def __lt__(self,other_account):
if(self.balance<other_account.balance):
return 1
else:
return 0
# Overload Greater than Operator
def __gt__(self,other_account):
if(self.balance>other_account.balance):
return 1
else:
return 0
# Compare Amount of Two Accounts
def CompareAccounts(self,other_account):
if(self==other_account):
return 0
elif(self>other_account):
return 1
elif(self<other_account):
return 2
else:
return 3
def Transfer_Money(self,account_no,amount):
""" Transfer amount from the Current open account_no
to Specified account
"""
previous_balance=self.balance;
with open('customercom.csv', 'rb') as f:
reader = csv.reader(f,delimiter=',')
for row in reader:
if(int(row[2])==account_no):
temp_customer=Customer(row[1])
temp_customer.open_account(int(row[2]))
if(temp_customer.account.balance!=-1):
self.withdraw(amount)
if(self.balance!=previous_balance):
temp_customer.account.deposit(amount)
# Global method to get if for new account
class Customer(object):
# Constructor Initillizes attributes
def __init__(self,name):
self.c_name=name
self.c_id=-1
self.account=Account()
def Request_new_account(self,account_type):
""" Customer open a new account
"""
self.c_id=self.get_customer_id()
self.account.set_account(self.c_id,account_type,0)
custmr=[self.c_id,self.c_name,self.c_id,account_type,0]
with open('customercom.csv', 'ab') as f:
writer = csv.writer(f)
writer.writerow(custmr)
f.close()
def open_account(self,account_no):
""" Open an existing account
"""
#print "Hello"
with open('customercom.csv', 'rb') as f:
reader = csv.reader(f,delimiter=',')
for row in reader:
#print row
if(int(row[2])==account_no):
if(row[1]==self.c_name):
self.c_id=int(row[0])
self.account.set_account(int(row[2]),row[3],int(row[4]))
return 1
return 0
f.close()
def get_customer_id(self):
with open('customercom.csv', 'rb') as f:
reader = csv.reader(f,delimiter=',')
for row in reader:
#print row
customer_id=int(row[0])
customer_id+=1
return customer_id
f.close()
import unittest
class CustomerTestCases(unittest.TestCase):
def test__init__(self):
self.my_customer = Customer("Rabia")
self.my_customer.c_id=11
self.my_customer.account=Account()
self.my_customer.account.set_account(11,"S",100)
def test_balance(self):
"""
Tests if balance is set successfully or not
"""
self.test__init__()
self.assertEqual(self.my_customer.account.balance,100,msg=" Balance not Set")
def test_deposit(self):
"""
Tests if depost Work properly
"""
self.test__init__()
self.my_customer.account.deposit(500)
self.assertEqual(self.my_customer.account.balance,600,msg=" Balance Not Updated after deposit")
def test_withdraw(self):
"""
Tests if withdraw Work properly
"""
self.test__init__()
self.my_customer.account.withdraw(50)
self.assertEqual(self.my_customer.account.balance,50,msg=" Balance Not Updated after withdraw")
self.my_customer.account.withdraw(500)
self.assertEqual(self.my_customer.account.balance,50,msg=" Withdraw Even when Not enough amount Available")
def test_checkbalance(self):
self.test__init__()
self.assertEqual(self.my_customer.account.Checkbalance(),100,msg=" Checkbalance not works Properly")
def test_transfermoney(self):
"""
Tests if customer able to Transfer amount Successfully
"""
self.test__init__()
# open an exisiting account as destination
# amount should Transfer to pass test
dest_customer=Customer("Gulnaz")
dest_customer.open_account(5)
prev_balance=dest_customer.account.Checkbalance()
self.my_customer.account.Transfer_Money(5,50)
self.assertEqual(self.my_customer.account.Checkbalance(),50,msg=" Trasfer from source Account")
dest_customer.open_account(5)
new_balance=dest_customer.account.Checkbalance()
self.assertEqual(prev_balance+50,new_balance,msg=" Amount not comes in destination Account")
# open an account that not exist
# amount should not transfer to pass test
self.test__init__()
self.my_customer.account.Transfer_Money(15,50)
self.assertEqual(self.my_customer.account.Checkbalance(),100,msg=" Amount Transfer But dest not exist")
def test_PayBills(self):
"""
Tests if customer able to paybills Successfully
"""
self.test__init__()
self.my_customer.account.PayBills(50)
self.assertEqual(self.my_customer.account.Checkbalance(),50,msg=" Bills not Pay")
def test_requestnewaccount(self):
"""
Tests when request for new account is made it is
opened or not
"""
dest_customer=Customer("Tempcust")
dest_customer.Request_new_account("S")
dest_customer.account.deposit(500)
acnt_no=dest_customer.account.account_no
dest_customer.open_account(acnt_no)
self.assertEqual(dest_customer.account.Checkbalance(),500,msg=" New Account Not Opened")
def test_openaccount(self):
"""
Tests if an account Open Suceesfully when exist
and not opened when not exist
"""
f_customer=Customer("huma")
f_customer.open_account(2)
self.assertNotEqual(f_customer.account.Checkbalance(),-1,msg=" Account Not Opened But it exists")
s_customer=Customer("huma")
s_customer.open_account(15)
self.assertEqual(s_customer.account.Checkbalance(),-1,msg=" Account Open when it not exist")
if __name__ == '__main__':
unittest.main()
|
class Account:
# whole currency units only
# need to read & store balance value
def __init__(self, filepath):
with open(filepath, 'r') as file:
self.balance = int(file.read()) # instance variable / property
self.filepath = filepath
def withdraw(self, amount):
self.balance = self.balance - amount
def deposit(self, amount):
self.balance = self.balance + amount
def commit(self):
with open(self.filepath, 'w') as file:
file.write(str(self.balance))
class CheckingAccount(Account):
''' This class d'generate checking account objects '''
# the above is a docstring
type = 'checking-account' # a class (not instance) variable
def __init__(self, filepath, fee): # self passed even if sub-class
Account.__init__(self, filepath) # invoking base account
self.fee = fee # NB instance variable from constructor into sub-class
def transfer(self, amount):
self.balance = self.balance - amount - self.fee
account = Account('balance.txt') # instantiate
print(account) # diagnostic
print(account.balance)
account.withdraw(100)
print(account.balance)
account.commit()
jack_checking = CheckingAccount('jack.txt', 50)
print(jack_checking.balance)
jack_checking.deposit(200)
jack_checking.commit()
print(jack_checking.balance)
jack_checking.transfer(300)
jack_checking.commit()
print(jack_checking.balance)
print(jack_checking.type) # check class variable
john_checking = CheckingAccount('john.txt', 20)
print(john_checking.balance)
john_checking.deposit(100)
john_checking.commit()
print(john_checking.balance)
john_checking.transfer(200)
john_checking.commit()
print(john_checking.balance)
print(john_checking.type)
print(john_checking.__doc__)
|
# coding: utf8
def fizz_buzz(value):
# Comprobamos el tipo de la variable
tipo_de_la_variable = type(value) # int, float, str, dict, list, etc...
if tipo_de_la_variable not in (int, float):
raise TypeError
# Comprobamos que sea divisible por 5 y por 3
if value % 3 == 0 and value % 5 == 0:
return 'fizz buzz'
# Comprobamos que sea divisible por 3
if value % 3 == 0:
return 'fizz'
# Comprobamos que sea divisible por 5
if value % 5 == 0:
return 'buzz'
return value
|
#load numpy as np
import numpy as np
#method1 - use slice
a_array = np.arange(10) ##[0 1 2 3 4 5 6 7 8 9]
s = slice(2,7)
print(a_array[s]) ##[2 3 4 5 6]
#method2 - array[start, stop, step]
a_array = np.arange(10) ##[0 1 2 3 4 5 6 7 8 9]
print(a_array[2:7]) ##[2 3 4 5 6]
#step = 2
print(a_array[2:7:2]) ##[2 4 6]
#2 <= num < stop
print(a_array[2:]) ##[2 3 4 5 6 7 8 9]
#start <= num < 7
print(a_array[:7]) ##[0 1 2 3 4 5 6]
#-1 => first from behind
print(a_array[2:-1]) ##[2 3 4 5 6 7 8]
#it can also be applied to multi-dimensional ndarray
a_array = np.arange(24) ##[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
a_array = np.reshape(a_array, [4,6])
'''
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]
'''
print(a_array[2:])
'''
[[12 13 14 15 16 17]
[18 19 20 21 22 23]]
'''
print(a_array[:,:2])
'''
[[ 0 1]
[ 6 7]
[12 13]
[18 19]]
'''
print(a_array[:2,-1:])
'''
[[ 5]
[11]]
'''
#if step == -1: reverse
print(a_array[::-1])
'''
[[18 19 20 21 22 23]
[12 13 14 15 16 17]
[ 6 7 8 9 10 11]
[ 0 1 2 3 4 5]]
'''
print(a_array[::-1,::-1])
'''
[[23 22 21 20 19 18]
[17 16 15 14 13 12]
[11 10 9 8 7 6]
[ 5 4 3 2 1 0]]
'''
|
def chunks(l, n):
"""
Yields chunks of size n from the list l.
"""
for i in range(0, len(l), n):
yield l[i: i+n]
|
import pygame
import random
import math
# initialize window
pygame.init()
words = ['CHETAN', 'CRICKET', 'DEVELOPER', 'ELEPHANT','PYGAME', 'PYTHON']
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Hangman Game")
logo = pygame.image.load('hangman.png')
pygame.display.set_icon(logo)
Letter_font = pygame.font.SysFont('comicsans', 40)
WORD_FONT = pygame.font.SysFont('comicsans',70)
mode = True
state = 0
image = []
word = words[random.randint(0,5)]
guessed= []
for i in range(7):
image.append(pygame.image.load('hangman' + str(i) + '.png'))
print(image)
letter= []
xs=43
ys=440
A=65
for i in range(26):
if i ==13:
xs=43
ys=500
letter.append([xs,ys,chr(A+i),True])
xs+=60
def draw_game():
screen.blit(image[state], (100, 150))
# X=43
# Y=440
# A = 65
display_word=""
for j in word:
if j in guessed:
display_word += j + " "
else:
display_word += "_ "
text = WORD_FONT.render(display_word,1,(0,0,0))
screen.blit(text,(400,200))
for i in range(26):
if letter[i][3]:
x,y,C=letter[i][0],letter[i][1],letter[i][2]
pygame.draw.circle(screen, (0, 0, 0), (x,y), 20, 3)
text = Letter_font.render(C, 1, (0, 0, 0))
screen.blit(text, (x - text.get_width() / 2, y - text.get_width() / 2))
running = True
while (running):
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
print(pygame.mouse.get_pos())
m_x, m_y = pygame.mouse.get_pos()
for i in range(26):
if letter[i][3]:
x,y,A=letter[i][0],letter[i][1],letter[i][2]
dist = math.sqrt((x - m_x) ** 2 + (y - m_y) ** 2)
if dist<20:
print(A)
letter[i][3]=False
if A in word:
guessed.append(A)
else:
if state==5:
screen.fill((255, 255, 255))
screen.blit(pygame.image.load('hangman6.png'), (100, 150))
text = WORD_FONT.render("YOU LOSE!!!", 1, (0, 0, 0))
screen.blit(text,(325, 265))
pygame.display.update()
pygame.time.delay(3000)
pygame.quit()
state+=1
# screen.blit(cell,(200,300))
won= True
for i in word:
if i not in guessed:
won = False
break
if won:
screen.fill((255,255,255))
screen.blit(pygame.image.load('congratulation.png'), (100, 250))
text=WORD_FONT.render("YOU WON!!!",1,(0,0,0))
screen.blit(text,(325,265))
pygame.display.update()
pygame.time.delay(3000)
break
if mode:
draw_game()
pygame.display.update()
|
#!/usr/bin/python3
def print_arg(long):
for num_arg in range(1, long):
print("{:d}: {:s}".format(num_arg, sys.argv[num_arg]))
if __name__ == "__main__":
import sys
long = len(sys.argv)
if long == 1:
print("{:d} arguments.".format(long - 1))
elif long == 2:
print("{:d} argument:".format(long - 1))
else:
print("{:d} arguments:".format(long - 1))
print_arg(long)
|
#!/usr/bin/python3
def print_last_digit(number):
print(int(str(number)[-1]), end="")
return int(str(number)[-1])
|
#!/usr/bin/python3
"""appends a string at the end of a text file
"""
def append_write(filename="", text=""):
"""appened string at end
"""
with open(filename, mode="a") as data_file:
return data_file.write(text)
|
#!/usr/bin/python3
"""module to write file
"""
def write_file(filename="", text=""):
"""write file with text input
"""
with open(filename, "w", encoding="utf-8") as data_file:
return data_file.write(text)
|
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt
r = input('Enter the name of the image you want: ')
def array_to_image(r):
img=mpimg.imread(r)
imgplot = plt.imshow(img)
plt.show()
array_to_image(r)
#img.shape
#http://matplotlib.org/users/image_tutorial.html
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'Mad Dragon'
__mtime__ = '2018/12/28'
# 我不懂什么叫年少轻狂,只知道胜者为王
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
fish_records = [18,8,7,2,3,6,1,1]
i = 0
compare = 0
fish_len = len(fish_records)
while i < fish_len:
j = 1
while j < fish_len -i:
if fish_records[j-1] > fish_records[j]:
compare = fish_records[j-1]
fish_records[j-1] = fish_records[j]
fish_records[j] = compare
j+=1
i+=1
print(fish_records)
|
import random
class RandomGenerator:
def __init__(self):
pass
"""returns a random number betweeen [x, y), returns an integer if both ranges are integers"""
@staticmethod
def range(x, y):
if type(x) == int and type(y) == int:
return random.randrange(x, y)
return random.random() * (y - x) + x
@staticmethod
def rangeSeeded(seed, x, y):
random.seed(seed)
return RandomGenerator.range(x, y)
@staticmethod
def rangeListSeeded(seed, n, x, y):
data = []
for i in range(n):
data.append(RandomGenerator.range(x, y))
return data
@staticmethod
def choose(data):
return data[RandomGenerator.range(0, len(data))]
@staticmethod
def chooseN(data, n):
choices = []
for x in range(n):
choices.append(RandomGenerator.choose(data))
return choices
@staticmethod
def chooseNSeeded(data, seed, n):
random.seed(seed)
return RandomGenerator.chooseN(data, n)
|
def conversor(tipo_moneda, tasa_conversion_dolares):
pesos = input("¿Cuantos pesos " + tipo_moneda + " deseas convertir a dolares? ")
pesos = round(float(pesos), 2)
tasa_conversion_dolares = tasa_conversion_dolares
dolares = round((pesos / tasa_conversion_dolares), 2)
print("$" + str(pesos) + " pesos " + tipo_moneda + " son $" + str(dolares) + " dolares americanos")
menu = """Bienvenido al programa de convesion de moneda
1 - Pesos Colombianos a Dolares.
2 - Pesos Argentinos a Dolares.
3 - Pesos Mexicanos a Dolares.
Por favor, selecciona una opcion para convertir: """
opcion = int(input(menu))
if opcion == 1:
conversor("Colombianos", 3875)
elif opcion == 2:
conversor("Colombianos", 93)
elif opcion == 3:
conversor("Colombianos", 19)
else:
print("Selecciona una opción valida por favor")
|
import random
def run():
opciones = ('piedra', 'papel', 'tijeras')
puntos_maquina = 0
puntos_jugador = 0
for i in range(0, 3):
jugador = input('Selecciona piedra, papel o tijeras ').lower().strip()
maquina = opciones[random.randint(0, 2)]
if(jugador == maquina):
print(f"Empate. Maquina eligio {maquina}")
elif((jugador == 'piedra' and maquina == 'papel') or (jugador == 'papel' and maquina == 'tijeras') or (jugador == 'tijeras' and maquina == 'piedra')):
print(f"Maquina gana esta ronda, eligio {maquina}")
puntos_maquina += 1
else:
print(f"Tu ganas esta ronda. Maquina eligio {maquina}")
puntos_jugador += 1
if puntos_maquina == 2 or puntos_jugador == 2:
break
if(puntos_jugador == puntos_maquina):
print("Nadie gana el juego, es un empate")
elif(puntos_maquina > puntos_jugador):
print("Maquina gana el juego")
else:
print("Tu ganas el juego")
if __name__ == "__main__":
run()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file : permutation_list.py
@time : 20/2/16 14:13
@author : leizhen
@contact : [email protected]
@doc : 对迭代进行排列组合
"""
from itertools import permutations, combinations, combinations_with_replacement
# itertools 模块提供了三个函数
# 便利一个集合中语速的所有可能排列或组合
items = 'abc'
print('1. 排列')
for p in permutations(items):
print(p)
# 如果想得到指定长度的所有排列
# 可以传递一个可选的长度参数
print('指定排列组合的长度')
for p in permutations(items, 2):
print(p)
print('2. 组合')
print('对于组合来说,元素的顺序已经不重要了')
for c in combinations(items, 3):
print(c)
print('组合参数为 2')
for c in combinations(items, 2):
print(c)
print('3. 允许同一个元素被选取多次')
for c in combinations_with_replacement(items, 3):
print(c)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'leizhen'
__mtime__ = '2017/8/10'
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
# Python 通过 re 模块提供对正则表达式的支持。使用 re 的一般步骤是先将正则表达式的字符形式编译成 Pattern 实例,然后使用
# Pattern 实例处理文本并获得匹配结果(一个 Match 实例),最后使用 Match 实例获的信息,进行其他的操作。
import re
def re_in_python():
# 1. 将正则表达式编译成 Pattern 对象
pattern = re.compile(r'hello')
# compile 是一个工厂类方法,用于将字符串形式的正则表达式编译成 Pattern 对象。
# 第二个参数 flag 可选,匹配模式
# 2. 使用 Pattern 匹配文本,获得匹配结果,无法匹配时将返回 None
match = pattern.match('hello world!')
# Match 对象是第一次匹配结果,包含了很多关于此次匹配的信息
# 3. 使用 Match 获取分组信息
if match:
print(match.group())
if __name__ == '__main__':
re_in_python()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time : 2020/8/1 08:56
# @Author : Lei Zhen
# @Contract: [email protected]
# @File : using_threading_lock.py
# @Software: PyCharm
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
# 某些变量,让他们在各自的线程中独立
import threading
import time
num = 0
lock = threading.RLock()
def show(arg):
lock.acquire()
global num
time.sleep(.3)
num += 1
print('bb', arg, ' num', num)
lock.release()
print('主线程', threading.current_thread().name, ' 开始')
for i in range(5):
t = threading.Thread(target=show, args=(i,))
t.start()
t.join()
class WorkThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
def run(self) -> None:
global num
while True:
lock.acquire()
print(f'\n{self.t_name} locked, number: {num}')
if num >= 10:
lock.release()
print(f'{self.t_name} released, number: {num}')
break
num += 1
print(f'{self.t_name} released, number: {num}')
lock.release()
local_manager = threading.local()
def thread_poc():
lock.acquire()
try:
print(f'Thread={local_manager.thread_name}')
print(f'Name={local_manager.name}')
finally:
lock.release()
class MyThread(threading.Thread):
def __init__(self, thread_name, name):
super().__init__(name=thread_name)
self._name = name
def run(self) -> None:
global local_manager
local_manager.thread_name = self.name
local_manager.name = self._name
thread_poc()
for i in range(5):
t = MyThread(f'A-{i}', f'a-{i}')
t.start()
t1 = WorkThread('A-worker')
t2 = WorkThread('B-worker')
t1.start()
t2.start()
print('主线程', threading.current_thread().name, ' 结束')
|
# coding=utf-8
from collections import Iterable
if __name__ == '__main__':
print isinstance('abc', Iterable)
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
for value in d.itervalues():
print value
for value in d.iteritems():
print value
print isinstance(d, Iterable)
print d.keys(), d.items(), d.values()
print d.iterkeys()
# 在遍历的过程中,同时迭代索引和元素本身
for i, value in enumerate(['a', 'b', 'c']):
print i, value
for x, y in [(1, 'a'), (2, 'b'), (3, 'c')]:
print x, y
L = ['Hello', 'world', 2016, 1114]
newL = [isinstance(s, str) and s.lower() or s for s in L]
print newL
|
import abc
class Database(object):
"""Generic Database object, every different database connection should
implement these functions."""
__metaclass__ = abc.ABCMeta
DATABASE: str
connection: any
@abc.abstractmethod
def connect(self, config, setup):
pass
@abc.abstractmethod
def add_order(self, order_id, user_id):
pass
@abc.abstractmethod
def delete_order(self, order_id):
pass
@abc.abstractmethod
def get_order(self, order_id):
pass
@abc.abstractmethod
def add_item_to_order(self, order_id, item_id):
pass
@abc.abstractmethod
def remove_item_from_order(self, order_id, item_id):
pass
|
print("enter 2 nos")
a=input()
b=input()
c=a*b
print('Product='+str(c))
|
#-*- coding: utf-8 -*-
import re
import time
from os import system
from datetime import datetime
import random
import pesquisa
from responder import responder
from pesquisa import defina, definicao
def main():
frase = ''
nome = str(input('Bot: Diga-me seu nome: '))
botNome = str(input('Bot: Agora o meu nome por gentileza: '))
while frase!='sair':
frase = str(input(f'{nome}: '))
resposta = responder(frase)
print(f'{botNome}: {resposta}')
main()
|
class Ciclos:
def __init__ (self):
pass
def usoFor(self,):
dat = ["Daniel", 50, True]
num = (2,5.6,4,1)
doc = {'nombre': 'Daniel', 'edad': 50, 'fac': 'faci'}
lisNota = [(30,40),[20,40],(50,40)]
lisAlum = [{"nombre":"Erick","ExmF":70},{"nombre":"Yady","ExmF":60},{"nombre":"Danny","ExmF":80}]
for i in range(5):
print("i={}".format(i), end=" ")
for i in range(2,10,2):
print("i={}".format(i), end=" ")
for i in range(20,0,-4):
print("i={}".format(i))
long = len(dat)
for i in range(long):
print(dat[i], end=" ")
for i in range(long-1,-1,-1):
print("for", dat[i])
for dato in num:
print(dato)
for dato in ['H','O','L', 'A', 'como','estas']:
print(dato)
print("\nDiccionario de notas")
for clave, valor in doc.items():
print(clave, ":", valor, end= " ")
for alumnos in lisAlum:
for clave, valor in alumnos.items():
print(clave, ":", valor, end= " ")
buc1 = Ciclos()
buc1.usoFor()
|
numeros = input().split()
A = int(numeros[0])
B = int(numeros[1])
print (abs(A-B))
|
D = int (input())
print (D)
notas = [100, 50, 20, 10, 5, 2, 1]
for i in notas:
print ("{} nota(s) de R$ {},00".format(int(D/i), i))
D = D%i
|
num = input().split()
num = [int(i) for i in num]
[print(i) for i in sorted(num)]
print("")
[print(i) for i in num]
|
r = float (input ())
π = 3.14159
area = π * r * r
print ("A=%.4f" %area)
|
vetor = []
for i in range(5):
num = float(input())
if num%2==0:
vetor.append(num)
print(str(len(vetor)) + ' valores pares')
|
def add(a,b):
result = a + b
return result
def sub(a,b):
result = a - b
return result
def mul(a,b):
result = a * b
return result
|
from functools import wraps
class greater_than_zero(object):
def __init__(self, function):
print("greater_than_zero.__init__")
self.function = function
self.__name__ = 'greater_than_zero'
def __call__(self, *args, **kwargs):
print("greater_than_zero.__call__({},{})".format(args, kwargs))
for item in args:
if item < 0:
print("Invalid argument `{}`".format(item))
return
self.function(*args, **kwargs)
class greater_than(object):
def __init__(self, value):
print("greater_than_{}.__init__".format(value))
self.value = value
def __call__(self, function):
print("greater_than_{}.__call__({})".format(self.value, function))
def wrapped_f(*args, **kwargs):
print "Inside wrapped_f()"
for item in args:
if item < self.value:
print("Invalid argument `{}`".format(item))
return
function(*args, **kwargs)
return wrapped_f
def decorator(function):
def inner(*args, **kwargs):
print("decorator[inner]")
function(*args, **kwargs)
return inner
def decorator2(function):
@wraps(function)
def inner(*args, **kwargs):
print("decorator[inner]")
function(*args, **kwargs)
return inner
@greater_than_zero
def test(*args):
print("test({})".format(args))
@greater_than(2)
def test2(*args):
print("test2({})".format(args))
@decorator
def test3():
pass
@decorator2
def test4():
"""Interesant nu ?"""
pass
if __name__ == "__main__":
test(1, 2, 3, 4, 5)
print("-" * 10)
test(-1, 0, 1, 2)
print("-" * 10)
test2(2, 3, 4, 5)
print("-" * 10)
test2(1, 2, 3)
print("-" * 10)
print(test.__name__)
print(test2.__name__)
print(test3.__name__)
print(test4.__name__)
print(test4.__doc__)
|
"""
Advent of code day two
Reference: https://adventofcode.com/2016/day/2
"""
import os
INPUT_DIRECTORY = "../inputs/"
INPUT_FILE_EXTENSION = "_input.txt"
KEYBOARD_PART_ONE = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
KEYBOARD_PART_TWO = [
[None, None, 1, None, None],
[None, 2, 3, 4, None],
[5, 6, 7, 8, 9],
[None, 'A', 'B', 'C', None],
[None, None, 'D', None, None]
]
def load_input(input_file):
"""
Read from input file and parse them into individual instructions
"""
instructions = []
relative_path = os.path.join(os.path.dirname(__file__), INPUT_DIRECTORY + input_file)
with open(relative_path, 'r') as opened_file:
content = opened_file.readlines()
for line in content:
instructions.append(list(line.strip()))
return instructions
def read_instruction(keyboard, keyboard_size, position, positions, direction):
"""
Read from direction and add new position to the list
"""
i = position[0]
j = position[1]
if direction == 'U':
i = max(i - 1, 0)
if direction == 'D':
i = min(i + 1, keyboard_size)
if direction == 'L':
j = max(j - 1, 0)
if direction == 'R':
j = min(j + 1, keyboard_size)
if keyboard[i][j] is None:
positions.append((position[0], position[1]))
return (position[0], position[1])
else:
positions.append((i, j))
return (i, j)
def part_one(instructions, keyboard):
"""
What is the bathroom code?
"""
positions = []
position = (1, 1)
for instruction in instructions:
partial = []
for direction in instruction:
position = read_instruction(KEYBOARD_PART_ONE, 2, position, partial, direction)
positions.append(partial)
code = ""
for position in positions:
code += str(keyboard[position[-1][0]][position[-1][1]])
return code
def part_two(instructions, keyboard):
"""
What is the bathroom code?
"""
positions = []
position = (2, 0)
for instruction in instructions:
partial = []
for direction in instruction:
position = read_instruction(KEYBOARD_PART_TWO, 4, position, partial, direction)
positions.append(partial)
code = ""
for position in positions:
code += str(keyboard[position[-1][0]][position[-1][1]])
return code
def main():
"""
Main function
"""
current_file = os.path.splitext(os.path.basename(__file__))[0]
instructions = load_input(current_file + INPUT_FILE_EXTENSION)
print "Part one answer:", part_one(instructions, KEYBOARD_PART_ONE)
print "Part two answer:", part_two(instructions, KEYBOARD_PART_TWO)
if __name__ == "__main__":
main()
|
sen=input("enter a sentence:").split()
s=" "
for i in range(len(sen)):
sen[i]=sen[i][::-1]
s=s.join(sen)
print(s)
|
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# dp[index] denotes the maximum amount of money consisting money nums[index]
# dp[index] = nums[index] + max(dp[index - 2], dp[index - 3])
dp = [0 for i in range(len(nums) + 3)]
for index in range(3, len(dp)):
dp[index] = nums[index - 3] + max(dp[index - 2], dp[index - 3])
return max(dp[-2:])
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
symmetric = [True]
def isSymmetricHelper(node1, node2):
if not node1 and not node2:
return
if not node1 or not node2 or node1.val != node2.val:
symmetric[0] = False
return
isSymmetricHelper(node1.left, node2.right)
isSymmetricHelper(node1.right, node2.left)
if root:
isSymmetricHelper(root.left, root.right)
return symmetric[0]
|
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# zero denotes the index of the first zero
# nonZero denotes the index of the first non-zero element after the first zero
zero = nonZero = 0
while nonZero <= len(nums) - 1 and zero <= len(nums) - 1:
nums[nonZero], nums[zero] = nums[zero], nums[nonZero]
# find the first zero
while zero <= len(nums) - 1 and nums[zero] != 0:
zero += 1
# find the first non-zero after the first zero
nonZero = zero + 1
while nonZero <= len(nums) - 1 and nums[nonZero] == 0:
nonZero += 1
|
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# dp[row][col] denotes the minimum sum of all numbers along the path from top left to grid[row][col]
# dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[row][col]
m = len(grid)
n = len(grid[0])
dp = grid
for col in range(1, n):
dp[0][col] = dp[0][col - 1] + grid[0][col]
for row in range(1, m):
dp[row][0] = dp[row - 1][0] + grid[row][0]
for row in range(1, m):
for col in range(1, n):
dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[row][col]
return dp[-1][-1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.