text stringlengths 37 1.41M |
|---|
def largest(arr):
l = arr[0]
for i in arr:
if i > l:
l = i
return l
aList = [4, 6, 8, 24, 12, 2]
print(largest(aList)) |
def concat(a1, a2):
x = 0
result = []
while x < len(a1):
temp = a1[x] + a2[x]
result.append(temp)
x += 1
return result
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
print(concat(list1, list2)) |
import math
def thirds(arr):
third = int(math.floor(len(arr) / 3))
x = 0
first = []
second = []
three = []
while x < 3:
if x == 0:
first = arr[:third]
first = first[::-1]
print(first)
elif x == 1:
second = arr[third: third * 2]
second = second[::-1]
print(second)
else:
three = arr[third * 2:]
three = three[::-1]
print(three)
x += 1
l = [11, 45, 8, 23, 14, 12, 78, 45, 89]
thirds(l)
|
def hyphen(s):
arr = s.split('-')
for x in arr:
print(x)
str1 = 'Emma-is-a-data-scientist'
hyphen(str1) |
#!/usr/bin/env python3
VALUES = {'black': 0, 'blue': 6, 'brown': 1, 'green': 5, 'red': 2}
MULT = {'black': 1, 'blue': 1000000, 'brown': 10, 'green': 100000, 'red': 100}
def compute_resistance(bands):
if bands is None: return None
band1, band2, mult = reversed(bands)
base = VALUES[band1] * 10 + VALUES[band2]
return base * MULT[mult]
from display import display
from camera import Camera
from classifier import Classifier
display.welcome_screen()
while 1:
image = Camera.capture()
bands = Classifier.extract_resistor_bands(image)
print(bands)
value = compute_resistance(bands)
display.draw_resistance(value)
|
#Yevgeny Khessin
#A39652176
#HW1
#test1
import sieve
#run once to check if value produced is 3.
def test1():
s = sieve.sieve() #make a sieve object from file sieve
i = iter(s) #make iterator
val=i.next() #run iterator once, put value in val
assert val == 3 #check if value is 3. if not 3, fail.
print "Value should be 3, actual value is:"
print val
#call test
test1() |
# A minion object is a card
from Card import Card
class Minion(Card):
def __init__(self,cost,name,ATK,HP):
Card.__init__(self,cost,name)
self.ATK = ATK
self.HP = HP
def printMinionInfo(self):
print("Name: " + str(self.name))
print("Cost: " + str(self.cost))
print("Attack: " + str(self.ATK))
print("HP: " + str(self.HP) + '\n') |
################################################
#randomColor.py
#Generating the random RGB colors
#Version 1.0
###############################################
import random
'''Generating random colours'''
def colourGen(trans):
myColours = []
for i in range(0,trans):
r = lambda: random.randint(0,255)
myColours.append('#%02X%02X%02X' % (r(),r(),r()))
return myColours
|
################################### RULE BASED CLASSIFICATION ########################################
# A game company wants to create level-based new customer definitions (personas) by using some
# features ( Country, Source, Age, Sex) of its customers, and to create segments according to these new customer
# definitions and to estimate how much profit can be generated from the new customers according to these segments.
# In this study, how to do rule-based classification and customer-based revenue calculation
# have been discussed step by step.
########################## Importing Libraries ##########################
print(14 * " >", "\t\t n.B.a. \t", "< " * 14, "\n\n\n")
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 20)
pd.set_option('display.max_rows', 15)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
pd.set_option('display.expand_frame_repr', True)
########################## Load The Data ##########################
def load_dataset(datasetname):
return pd.read_csv(f"{datasetname}.csv")
df = load_dataset("persona")
df.head()
########################### Describe The Data ######################
def check_df(dataframe):
print(f"""
##################### Shape #####################\n\n\t{dataframe.shape}\n\n
##################### Types #####################\n\n{dataframe.dtypes}\n\n
##################### Head #####################\n\n{dataframe.head(3)}\n\n
##################### NA #####################\n\n{dataframe.isnull().sum()}\n\n
##################### Quantiles #####################\n\n{dataframe.quantile([0, 0.05, 0.50, 0.95, 0.99, 1]).T}\n\n""")
check_df(df)
######################## Selection of Categorical and Numerical Variables ########################
# Let's define a function to perform the selection of numeric and categorical variables in the data set in a parametric way.
def grab_col_names(dataframe, cat_th=10, car_th=20):
"""
Veri setindeki kategorik, numerik ve kategorik fakat kardinal değişkenlerin isimlerini verir.
Not: Kategorik değişkenlerin içerisine numerik görünümlü kategorik değişkenler de dahildir.
Parameters
------
dataframe: dataframe
Değişken isimleri alınmak istenilen dataframe
cat_th: int, optional
numerik fakat kategorik olan değişkenler için sınıf eşik değeri
car_th: int, optional
kategorik fakat kardinal değişkenler için sınıf eşik değeri
Returns
------
cat_cols: list
Kategorik değişken listesi
num_cols: list
Numerik değişken listesi
cat_but_car: list
Kategorik görünümlü kardinal değişken listesi
Examples
------
import seaborn as sns
df = sns.load_dataset("iris")
print(grab_col_names(df))
Notes
------
cat_cols + num_cols + cat_but_car = toplam değişken sayısı
num_but_cat cat_cols'un içerisinde.
"""
# cat_cols, cat_but_car
cat_cols = [col for col in dataframe.columns if dataframe[col].dtypes == "O"]
num_but_cat = [col for col in dataframe.columns if dataframe[col].nunique() < cat_th and
dataframe[col].dtypes != "O"]
cat_but_car = [col for col in dataframe.columns if dataframe[col].nunique() > car_th and
dataframe[col].dtypes == "O"]
cat_cols = cat_cols + num_but_cat
cat_cols = [col for col in cat_cols if col not in cat_but_car]
# num_cols
num_cols = [col for col in dataframe.columns if dataframe[col].dtypes != "O"]
num_cols = [col for col in num_cols if col not in num_but_cat]
print(f"Observations: {dataframe.shape[0]}")
print(f"Variables: {dataframe.shape[1]}")
print(f'cat_cols: {len(cat_cols)}')
print(f'num_cols: {len(num_cols)}')
print(f'cat_but_car: {len(cat_but_car)}')
print(f'num_but_cat: {len(num_but_cat)}')
return cat_cols, num_cols, cat_but_car
cat_cols, num_cols, cat_but_car = grab_col_names(df)
######################## General Exploration for Categorical Data ########################
def cat_summary(dataframe, plot=False):
# cat_cols = grab_col_names(dataframe)["Categorical_Data"]
for col_name in cat_cols:
print("############## Unique Observations of Categorical Data ###############")
print("The unique number of " + col_name + ": " + str(dataframe[col_name].nunique()))
print("############## Frequency of Categorical Data ########################")
print(pd.DataFrame({col_name: dataframe[col_name].value_counts(),
"Ratio": dataframe[col_name].value_counts() / len(dataframe)}))
if plot: # plot == True (Default)
sns.countplot(x=dataframe[col_name], data=dataframe)
plt.show()
cat_summary(df, plot=True)
######################## General Exploration for Numerical Data ########################
def num_summary(dataframe, plot=False):
numerical_col = ['PRICE', 'AGE'] ##or grab_col_names(dataframe)["Numerical_Data"]
quantiles = [0.25, 0.50, 0.75, 1]
for col_name in numerical_col:
print("########## Summary Statistics of " + col_name + " ############")
print(dataframe[numerical_col].describe(quantiles).T)
if plot:
sns.histplot(data=dataframe, x=col_name)
plt.xlabel(col_name)
plt.title("The distribution of " + col_name)
plt.grid(True)
plt.show(block=True)
num_summary(df, plot=True)
######################## Data Analysis ########################
def data_analysis(dataframe):
# Unique Values of Source:
print("Unique Values of Source:\n", dataframe[["SOURCE"]].nunique())
# Frequency of Source:
print("Frequency of Source:\n", dataframe[["SOURCE"]].value_counts())
# Unique Values of Price:
print("Unique Values of Price:\n", dataframe[["PRICE"]].nunique())
# Number of product sales by sales price:
print("Number of product sales by sales price:\n", dataframe[["PRICE"]].value_counts())
# Number of product sales by country:
print("Number of product sales by country:\n", dataframe["COUNTRY"].value_counts(ascending=False, normalize=True))
# Total & average amount of sales by country
print("Total & average amount of sales by country:\n", dataframe.groupby("COUNTRY").agg({"PRICE": ["mean", "sum"]}))
# Average amount of sales by source:
print("Average amount of sales by source:\n", dataframe.groupby("SOURCE").agg({"PRICE": "mean"}))
# Average amount of sales by source and country:
print("Average amount of sales by source and country:\n", dataframe.pivot_table(values=['PRICE'],
index=['COUNTRY'],
columns=["SOURCE"],
aggfunc=["mean"]))
data_analysis(df)
######################## Defining Personas ########################
# Let's define new level-based customers (personas) by using Country, Source, Age and Sex.
# But, firstly we need to convert age variable to categorical data.
def define_persona(dataframe):
# Let's define new level-based customers (personas) by using Country, Source, Age and Sex.
# But, firstly we need to convert age variable to categorical data.
bins = [dataframe["AGE"].min(), 18, 23, 35, 45, dataframe["AGE"].max()]
labels = [str(dataframe["AGE"].min()) + '_18', '19_23', '24_35', '36_45', '46_' + str(dataframe["AGE"].max())]
dataframe["AGE_CAT"] = pd.cut(dataframe["AGE"], bins, labels=labels)
dataframe.groupby("AGE_CAT").agg({"AGE": ["min", "max", "count"]})
# For creating personas, we group all the features in the dataset:
df_summary = dataframe.groupby(["COUNTRY", "SOURCE", "SEX", "AGE_CAT"])[["PRICE"]].sum().reset_index()
df_summary["CUSTOMERS_LEVEL_BASED"] = pd.DataFrame(["_".join(row).upper() for row in df_summary.values[:, 0:4]])
# Calculating average amount of personas:
df_persona = df_summary.groupby("CUSTOMERS_LEVEL_BASED").agg({"PRICE": "mean"})
df_persona = df_persona.reset_index()
return df_persona
define_persona(df)
######################## Creating Segments based on Personas ########################
def create_segments(dataframe):
# When we list the price in descending order, we want to express the best segment as the A segment and to define 4 segments.
df_persona = define_persona(dataframe)
segment_labels = ["D", "C", "B", "A"]
df_persona["SEGMENT"] = pd.qcut(df_persona["PRICE"], 4, labels=segment_labels)
# df_segment = df_persona.groupby("SEGMENT").agg({"PRICE": "mean"})
# Demonstrating segments as bars on a chart, where the length of each bar varies based on the value of the customer profile
# plot = sns.barplot(x="SEGMENT", y="PRICE", data=df_segment)
# for bar in plot.patches:
# plot.annotate(format(bar.get_height(), '.2f'),
# (bar.get_x() + bar.get_width() / 2,
# bar.get_height()), ha='center', va='center',
# size=8, xytext=(0, 8),
# textcoords='offset points')
return df_persona
create_segments(df)
######################## Prediction ########################
def ruled_based_classification(dataframe):
df_segment = create_segments(dataframe)
def AGE_CAT(age):
if age <= 18:
AGE_CAT = "15_18"
return AGE_CAT
elif (age > 18 and age <= 23):
AGE_CAT = "19_23"
return AGE_CAT
elif (age > 23 and age <= 35):
AGE_CAT = "24_35"
return AGE_CAT
elif (age > 35 and age <= 45):
AGE_CAT = "36_45"
return AGE_CAT
elif (age > 45 and age <= 66):
AGE_CAT = "46_66"
return AGE_CAT
COUNTRY = input("Enter a country name (USA/EUR/BRA/DEU/TUR/FRA):")
SOURCE = input("Enter the operating system of phone (IOS/ANDROID):")
SEX = input("Enter the gender (FEMALE/MALE):")
AGE = int(input("Enter the age:"))
AGE_SEG = AGE_CAT(AGE)
new_user = COUNTRY.upper() + '_' + SOURCE.upper() + '_' + SEX.upper() + '_' + AGE_SEG
print(new_user)
print("Segment:" + df_segment[df_segment["CUSTOMERS_LEVEL_BASED"] == new_user].loc[:, "SEGMENT"].values[0])
print("Price:" + str(df_segment[df_segment["CUSTOMERS_LEVEL_BASED"] == new_user].loc[:, "PRICE"].values[0]))
return new_user
ruled_based_classification(df) |
import plotly.express as plot
import numpy as np
np.random.seed(45)
# declaring size of the array
size = 100
x = np.random.randint(low=0, high=100, size=size)
y = np.random.randint(low=0, high=100, size=size)
fig = plot.scatter(x=x, y=y)
# Adjusting width and height of the image
fig.layout.template = 'plotly_dark'
fig.update_layout(
title='Scatter Plot',
xaxis_title='X Axis Title',
yaxis_title='Y Axis Title',
xaxis_tickangle=-30,
width=500,
height=500,
autosize=False,
margin=dict(l=50, r=50, b=100, t=100, pad=4)
)
fig.show() |
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encrypt(msg, shift=13):
output = ""
for i in range(len(msg)):
c = msg[i]
j = alpha.find(c)
k = (j + shift)%len(alpha)
output += alpha[k]
return output
def decrypt(msg, shift=13):
output = ""
for i in range(len(msg)):
c = msg[i]
j = alpha.find(c)
k = (j - shift)%len(alpha)
output += alpha[k]
return output
inp = input("Enter message to encrypt: ")
out = encrypt(inp)
print(out)
print("Decrypted it's "+decrypt(out))
|
import random
import string
import json
class VariousFunctions:
def random_string(self, string_size, chars=string.ascii_uppercase + string.digits):
self.string_size = string_size
final_string = ''.join(random.choice(chars) for i in range(string_size))
return final_string
def create_json(self, json_data, json_path):
self.json_data = json_data
self.json_path = json_path
with open(self.json_path, 'w') as json_file:
json.dump(self.json_data, json_file, indent=4)
json_file.close()
def random(self, pref):
value = self.random_string(random.randint(5, 10))
return pref + value
|
# Напишите программу, которая запрашивает у пользователя начальное количество денег и,
# пока оно меньше 10 000, запрашивает число, которое выпало на кубике (от 1 до 6).
# Если на кубике выпало 3, то выводится сообщение «Вы проиграли всё!», и деньги обнуляются.
# Если выпало другое число, к сумме прибавляется 500.
summ = int(input('Начальное количество денег: '))
while summ < 10000:
cube = int(input('Какое число выпало на кубике? '))
if cube == 3:
print('Вы проиграли все!')
summ = 0
break
summ += 500
print('Вы выиграли 500 рублей!')
print('Игра закончена.')
print('Итого осталось: ', summ) |
# В некоторых странах действует так называемая прогрессивная шкала налогообложения:
# чем больше ты зарабатываешь, тем больший налог платишь. Нужно написать программу,
# которая будет рассчитывать сумму налога исходя из прибыли. Если прибыль до 10 000
# — ставка налога равна 13%, начиная с 10 000 и до 50 000 — 20%. А начиная с 50 000
# — 30%. А также нужно добавить «проверку на дурака»: если ввели число меньше нуля,
# то вывести сообщение: «Ошибка: доход не может быть отрицательным».
summ = int(input('Сколько вы зарабатываете? '))
if summ < 0:
print('Ошибка: доход не может быть отрицательным.')
elif summ <= 10000:
tax = summ * 13 / 100
print('Налог составит (13%): ', tax)
elif summ <= 50000:
tax = summ * 20 / 100
print('Налог составит (20%): ', tax)
else:
tax = summ * 30 / 100
print('Налог составит (30%): ', tax) |
# Планируется построить театр под открытым небом, но для начала нужно хотя бы примерно
# понять сколько должно быть рядов, сидений в них и какое лучше сделать расстояние между рядами.
# Напишите программу, которая получает на вход кол-во рядов, сидений и свободных метров между рядами,
# затем выводит примерный макет театра на экран.
row = int(input('Введите кол-во рядов: '))
seat = int(input('Введите кол-во сидений в ряде: '))
meter = int(input('Введите кол-во метров между рядами: '))
print('Сцена')
for scene in range(row):
print('=' * seat, end = ' ')
print('*' * meter, end = ' ')
print('=' * seat)
|
#! /usr/local/bin/python3
# Caitlin M
"""AoC Day 4: Giant Squid
Original problem at https://adventofcode.com/2021/day/4
"""
BINGO_SIZE = 5
def mark_bingo_boards(bingo_num):
"""Replace specified number with X in all boards"""
global bingoboards
for board in bingoboards:
for line in board:
try:
line[line.index(bingo_num)] = "X"
except ValueError:
pass
def check_bingo_board(board_num):
"""Check a bingo board for 5 Xs in a row"""
winning_board = False
for i in range(BINGO_SIZE):
if bingoboards[board_num][i].count("X") == 5:
winning_board = board_num
for j in range(BINGO_SIZE):
col = list(map(lambda x: x[j], bingoboards[board_num]))
if col.count("X") == 5:
winning_board = board_num
return winning_board
def count_bingo_board(board_num):
"""Count score of a winning board"""
bingo_score = 0
for row in bingoboards[board_num]:
bingo_score += sum(list(filter(lambda x: x != "X", row)))
return bingo_score
def load_input(input_name):
"""Load the input file (a line-seperated list of numbers)."""
with open(input_name) as input_file:
bingonumbers = list(map(int, input_file.readline().split(",")))
boards = []
board_num = -1
board_row = -1
for line in input_file.readlines():
if line.strip() == "":
board_num += 1
board_row = -1
boards.append([])
else:
boards[board_num].append(list(map(int, line.split())))
return (bingonumbers, boards)
if __name__ == "__main__":
(bingonumbers, bingoboards) = load_input("d04-input.txt")
all_winners = []
winning_board = False
winning_score = 0
for bingo_num in bingonumbers:
mark_bingo_boards(bingo_num)
for board_num in range(len(bingoboards)):
if check_bingo_board(board_num) and board_num not in all_winners:
winning_board = board_num
winning_score = count_bingo_board(board_num) * bingo_num
all_winners.append(winning_board)
print(f"the winner is {winning_board} {bingoboards[winning_board]} with a score of {winning_score}")
if len(bingoboards) == 0:
break |
#! /usr/local/bin/python3
# Caitlin M
def load_input(input_name):
"""Load the input file (a line-seperated list of numbers)."""
with open(input_name) as input_file:
input_list = []
for line in input_file:
input_list.append(int(line.strip()))
return input_list
if __name__ == "__main__":
expenses = load_input("d01-input.txt")
for expense in expenses:
for other_expense in expenses:
if (expense + other_expense == 2020):
print(f"the good numbers are {expense} and {other_expense} and multiplied they make {expense*other_expense}")
sorted_expenses = sorted(expenses)
for expense in sorted_expenses:
for other_expense in sorted_expenses:
if (expense + other_expense > 2020):
break
for other_other_expense in sorted_expenses:
if (expense + other_expense + other_other_expense > 2020):
break
if (expense + other_expense + other_other_expense == 2020):
print(f"the three good numbers are {(expense, other_expense, other_other_expense)} and they multiply to {expense*other_expense*other_other_expense}")
|
#!/usr/bin/env python
"""Advent of Code 2017 Day 07 - Recursive Circus
http://adventofcode.com/2017/day/7
Find the root node name of a tree of "programs".
Given: list of nodes, weight and names of child nodes
in format "xxxx (ww) -> yyyy, zzzz"
"""
import re
INPUT_FILENAME = "d07-input.txt"
RE_NODE = r"^([a-z]+) \(([0-9]+)\)"
RE_PARENT_NODE = RE_NODE + r" -> ((?:[a-z]+(?:, )?)+)$"
end_node_re = re.compile(RE_NODE)
parent_node_re = re.compile(RE_PARENT_NODE)
def parse_node(line, tree_weights, tree_children):
line_node_match = end_node_re.match(line)
if line_node_match is not None:
node_name = line_node_match.group(1)
tree_weights[node_name] = int(line_node_match.group(2))
# Check if children
line_parent_match = parent_node_re.match(line)
if line_parent_match is not None:
tree_children[node_name] = line_parent_match.group(3).split(", ")
else:
print "WARN: Couldn't match line {0}".format(line)
if (__name__ == "__main__"):
tree_weights = {}
tree_children = {}
# Take in input from file
with (open(INPUT_FILENAME)) as f:
for line in f:
parse_node(line, tree_weights, tree_children)
print tree_children
|
#!/usr/bin/python
#conversion from float to int,string,long,hex,oct
x=445.125
print(int(x))
print(long(x))
print(str(x))
print(repr(x))
|
from collections import defaultdict
mass_content = dict()
#Creating monoisotopic mass dictionary
with open("data/monoisotopic_mass_table.txt") as monoisotopic_mass_dict:
'''
The monoisotopic mass table for amino acids is a
table listing the mass of each possible amino acid
residue, where the value of the mass used is the
monoisotopic mass of each residue:
A 71.03711
C 103.00919
D 115.02694
E 129.04259
F 147.06841
G 57.02146
H 137.05891
I 113.08406
K 128.09496
L 113.08406
M 131.04049
N 114.04293
P 97.05276
Q 128.05858
R 156.10111
S 87.03203
T 101.04768
V 99.06841
W 186.07931
Y 163.06333
'''
for line in monoisotopic_mass_dict:
mass_content[line.split()[0]] = float(line.split()[1])
count_mass = 0
#Opening sequence file and calculating the protein mass
with open("data/rosalind_prtm.txt", "r") as sampleInput:
string = sampleInput.read().strip()
for i in string:
if i in mass_content.keys():
#Getting i.values()
count_mass += mass_content.get(i)
print(count_mass)
|
#!/usr/bin/env python3
from algorithm import *
from ev3dev2.sensor import INPUT_4
from ev3dev2.sensor.lego import TouchSensor
def main():
begin, end, board = scan()
for row in board:
for col in row:
if col is None:
print(0, end="")
elif col is begin:
print(2, end='')
elif col is end:
print(3, end='')
else:
print(1, end='')
print('')
path = bfs(begin, end)
for node in path:
x = node.x
y = node.y
print(x, y)
print("")
print("wait for pressed")
touch = TouchSensor(INPUT_4)
touch.wait_for_pressed()
print("go")
follow_path(path)
def test():
with open("z.txt", "r") as f:
lines = f.readlines()
begin, end, board = scan_test(lines)
for row in board:
line = ""
for col in row:
if col is None:
line = line + "0"
elif col is begin:
line = line + "2"
elif col is end:
line = line + "3"
else:
line = line + "1"
print(line)
path = bfs(begin, end)
board = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
for node in path:
print(node.x, node.y)
board[node.y][node.x] = 1
print("")
for l in board:
print(l)
if __name__ == "__main__":
main()
#test()
|
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
X = np.random.random(size=(20, 1))
y = 3*X.squeeze()+2+np.random.randn(20)
model = LinearRegression()
model.fit(X, y)
# Plot the data and the model prediction
X_fit = np.linspace(0, 1, 100)[:, np.newaxis]
y_fit = model.predict(X_fit)
print X, X.squeeze(), y, X_fit
plt.plot(X.squeeze(), y, 'o')
plt.plot(X_fit.squeeze(), y_fit)
plt.show()
|
numbers = input().split(", ")
numbers = [bin(round(float(item))).count("1") for item in numbers]
numbers.sort()
print(*numbers, sep=", ")
|
# Python example of command-line argument processing
import sys
num_args = len(sys.argv)
print ("{0} argument{1}" . format(num_args, "s" if (num_args != 1) else ""))
index = 0
for arg in sys.argv:
print ("sys.argv[{0}]: \"{1}\"" . format(index,arg))
index += 1
|
#!/usr/bin/python
from itertools import permutations
def checkValid(numlist):
"""check the validity of a number as described: """
if listToDigit(numlist[1:4])%2!=0: return False
if listToDigit(numlist[2:5])%3!=0: return False
if listToDigit(numlist[3:6])%5!=0: return False
if listToDigit(numlist[4:7])%7!=0: return False
if listToDigit(numlist[5:8])%11!=0: return False
if listToDigit(numlist[6:9])%13!=0: return False
if listToDigit(numlist[7:10])%17!=0: return False
return True
def listToDigit(list):
return int(''.join(str(u) for u in list))
lists=permutations(range(0,10))
sum=0
for i in lists:
if checkValid(i):
sum+=listToDigit(i)
print sum
|
#!/usr/bin/python
import math
def factorize(num):
"""return the set of factors"""
s=set([])
ori=num
bound=int(math.sqrt(ori))+1
while ori!=bound:
change=False
for i in range(2, bound+1):
if ori%i == 0:
ori//=i
s.add(i)
bound=int(math.sqrt(ori))+1
change=True
break
if change==False:
s.add(ori)
break
return s
for i in range(700,1000000):
if(len(factorize(i))==4):
if len(factorize(i+1))==4 and len(factorize(i+2))==4 and len(factorize(i+3))==4:
print i
break
print "done"
|
import numpy as np
grid = [[0,9,0,3,0,0,0,7,0],
[0,5,3,4,0,9,0,0,0],
[0,0,2,0,0,0,0,5,0],
[0,0,0,2,0,0,0,0,0],
[2,0,0,1,0,0,6,4,0],
[0,0,4,5,0,0,0,1,2],
[0,3,6,0,0,0,4,0,5],
[0,0,0,9,0,0,0,0,0],
[1,0,0,0,0,8,0,0,0]]
print("Entered Grid:")
print(np.matrix(grid))
def possible(y,x,n):
global grid
for i in range(0,9):
if grid[y][i] == n:
return False
for i in range(0,9):
if grid[i][x] == n:
return False
x0 = (x//3)*3
y0 = (y//3)*3
for i in range(0,3):
for j in range(0,3):
if grid[y0+i][x0+j] == n:
return False
return True
#test conditions
# print("Is the middle square 3? " + str(possible(4,4,3)))
# print("Is the middle square 5? " + str(possible(4,4,5)))
# print(0//3*3)
# print(1//3*3)
# print(2//3*3)
# print(3//3*3)
# print(4//3*3)
# print(5//3*3)
# print(6//3*3)
# print(7//3*3)
# print(8//3*3)
def solve():
global grid
for y in range(9):
for x in range(9):
if grid[y][x] == 0:
for n in range(1,10):
if possible(y,x,n):
grid[y][x] = n
solve()
grid[y][x] = 0
return
print(np.matrix(grid))
print("Solution")
solve() |
#Exercise 1
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'octo', 'nov', 'dec']
for month in months:
if month[0] == 'j':
print(month)
#Exercise 2
integers = list(range(100))
for divisable in integers:
if divisable % 10 ==0:
print(divisable)
#Exercise 3
horton = "A person's a person, no matter how small."
vowels = "aeiouAEIOUI"
for vowel in horton:
for x in vowels:
if vowel == x:
print(vowel)
#Exercise 4
word = input('Word?')
y = 'False'
for i in range(len(word)-1):
if word[i] == word[i + 1]:
y = 'True'
print(y)
#Exercise 5
words = ['poop', 'ity', 'scoop', 'whoop', 'diddy', 'scoop']
total_length = 0
for word in words:
total_length += len(word)
average = total_length / len(words)
print(average)
|
class Worker:
def __init__(self, name, surname, worker_position, income):
self.name = name
self.surname = surname
self.position = worker_position
self._income = income
class Position(Worker):
def get_full_name(self):
return f"{self.name} {self.surname}"
def get_total_income(self):
return f"{self._income['wage'] + self._income['bonus']}"
position = Position('Andrey', 'Burov', 'Java Developer', {'wage': 20000, 'bonus': 5000})
print(position.get_full_name())
print(position.get_total_income())
|
n = input("Enter a number: ")
result = int(n) + int(n + n) + int(n + n + n)
print(f"{n} + {n}{n} + {n}{n}{n} = {result}")
|
a = float (input ())
litr = a * 3.78541181779
bar = a / 19.5
co2 = a * 20
ch = (a * 115000) / 75700
cost = a * 3.00
day = ((litr / 8,6) * 449800)
year = ()
print (litr,"литров", "\n", bar, "баррелей", "\n", co2, "фунтов углекислого газа", "\n", ch, "галлонов этанола", cost, "долларов США", day, "литров в Новосибисрке в день", year, "литров в России в год" sep=" ") |
# open alice.txt, print lines that startwith
# 'Alice' and print out result with right-hand whitespace
# removed
with open('alice.txt') as file:
for line in file:
line = line.rstrip()
if line.startswith("Alice"):
print(line)
|
# open alice.txt, count the lines, and
# print out number of lines
with open('alice.txt') as file:
count = 0
for line in file:
count += 1
print('Line Count:', count)
|
"""An implementation of tabbed pages using only standard Tkinter.
Originally developed for use in IDLE. Based on tabpage.py.
Classes exported:
TabbedPageSet -- A Tkinter implementation of a tabbed-page widget.
TabSet -- A widget containing tabs (buttons) in one or more rows.
"""
from tkinter import *
class InvalidNameError(Exception): pass
class AlreadyExistsError(Exception): pass
class TabSet(Frame):
"""A widget containing tabs (buttons) in one or more rows.
Only one tab may be selected at a time.
"""
def __init__(self, page_set, select_command,
tabs=None, n_rows=1, max_tabs_per_row=5,
expand_tabs=False, **kw):
"""Constructor arguments:
select_command -- A callable which will be called when a tab is
selected. It is called with the name of the selected tab as an
argument.
tabs -- A list of strings, the names of the tabs. Should be specified in
the desired tab order. The first tab will be the default and first
active tab. If tabs is None or empty, the TabSet will be initialized
empty.
n_rows -- Number of rows of tabs to be shown. If n_rows <= 0 or is
None, then the number of rows will be decided by TabSet. See
_arrange_tabs() for details.
max_tabs_per_row -- Used for deciding how many rows of tabs are needed,
when the number of rows is not constant. See _arrange_tabs() for
details.
"""
Frame.__init__(self, page_set, **kw)
self.select_command = select_command
self.n_rows = n_rows
self.max_tabs_per_row = max_tabs_per_row
self.expand_tabs = expand_tabs
self.page_set = page_set
self._tabs = {}
self._tab2row = {}
if tabs:
self._tab_names = list(tabs)
else:
self._tab_names = []
self._selected_tab = None
self._tab_rows = []
self.padding_frame = Frame(self, height=2,
borderwidth=0, relief=FLAT,
background=self.cget('background'))
self.padding_frame.pack(side=TOP, fill=X, expand=False)
self._arrange_tabs()
def add_tab(self, tab_name):
"""Add a new tab with the name given in tab_name."""
if not tab_name:
raise InvalidNameError("Invalid Tab name: '%s'" % tab_name)
if tab_name in self._tab_names:
raise AlreadyExistsError("Tab named '%s' already exists" %tab_name)
self._tab_names.append(tab_name)
self._arrange_tabs()
def remove_tab(self, tab_name):
"""Remove the tab named <tab_name>"""
if not tab_name in self._tab_names:
raise KeyError("No such Tab: '%s" % tab_name)
self._tab_names.remove(tab_name)
self._arrange_tabs()
def set_selected_tab(self, tab_name):
"""Show the tab named <tab_name> as the selected one"""
if tab_name == self._selected_tab:
return
if tab_name is not None and tab_name not in self._tabs:
raise KeyError("No such Tab: '%s" % tab_name)
# deselect the current selected tab
if self._selected_tab is not None:
self._tabs[self._selected_tab].set_normal()
self._selected_tab = None
if tab_name is not None:
# activate the tab named tab_name
self._selected_tab = tab_name
tab = self._tabs[tab_name]
tab.set_selected()
# move the tab row with the selected tab to the bottom
tab_row = self._tab2row[tab]
tab_row.pack_forget()
tab_row.pack(side=TOP, fill=X, expand=0)
def _add_tab_row(self, tab_names, expand_tabs):
if not tab_names:
return
tab_row = Frame(self)
tab_row.pack(side=TOP, fill=X, expand=0)
self._tab_rows.append(tab_row)
for tab_name in tab_names:
tab = TabSet.TabButton(tab_name, self.select_command,
tab_row, self)
if expand_tabs:
tab.pack(side=LEFT, fill=X, expand=True)
else:
tab.pack(side=LEFT)
self._tabs[tab_name] = tab
self._tab2row[tab] = tab_row
# tab is the last one created in the above loop
tab.is_last_in_row = True
def _reset_tab_rows(self):
while self._tab_rows:
tab_row = self._tab_rows.pop()
tab_row.destroy()
self._tab2row = {}
def _arrange_tabs(self):
"""
Arrange the tabs in rows, in the order in which they were added.
If n_rows >= 1, this will be the number of rows used. Otherwise the
number of rows will be calculated according to the number of tabs and
max_tabs_per_row. In this case, the number of rows may change when
adding/removing tabs.
"""
# remove all tabs and rows
while self._tabs:
self._tabs.popitem()[1].destroy()
self._reset_tab_rows()
if not self._tab_names:
return
if self.n_rows is not None and self.n_rows > 0:
n_rows = self.n_rows
else:
# calculate the required number of rows
n_rows = (len(self._tab_names) - 1) // self.max_tabs_per_row + 1
# not expanding the tabs with more than one row is very ugly
expand_tabs = self.expand_tabs or n_rows > 1
i = 0 # index in self._tab_names
for row_index in range(n_rows):
# calculate required number of tabs in this row
n_tabs = (len(self._tab_names) - i - 1) // (n_rows - row_index) + 1
tab_names = self._tab_names[i:i + n_tabs]
i += n_tabs
self._add_tab_row(tab_names, expand_tabs)
# re-select selected tab so it is properly displayed
selected = self._selected_tab
self.set_selected_tab(None)
if selected in self._tab_names:
self.set_selected_tab(selected)
class TabButton(Frame):
"""A simple tab-like widget."""
bw = 2 # borderwidth
def __init__(self, name, select_command, tab_row, tab_set):
"""Constructor arguments:
name -- The tab's name, which will appear in its button.
select_command -- The command to be called upon selection of the
tab. It is called with the tab's name as an argument.
"""
Frame.__init__(self, tab_row, borderwidth=self.bw, relief=RAISED)
self.name = name
self.select_command = select_command
self.tab_set = tab_set
self.is_last_in_row = False
self.button = Radiobutton(
self, text=name, command=self._select_event,
padx=5, pady=1, takefocus=FALSE, indicatoron=FALSE,
highlightthickness=0, selectcolor='', borderwidth=0)
self.button.pack(side=LEFT, fill=X, expand=True)
self._init_masks()
self.set_normal()
def _select_event(self, *args):
"""Event handler for tab selection.
With TabbedPageSet, this calls TabbedPageSet.change_page, so that
selecting a tab changes the page.
Note that this does -not- call set_selected -- it will be called by
TabSet.set_selected_tab, which should be called when whatever the
tabs are related to changes.
"""
self.select_command(self.name)
return
def set_selected(self):
"""Assume selected look"""
self._place_masks(selected=True)
def set_normal(self):
"""Assume normal look"""
self._place_masks(selected=False)
def _init_masks(self):
page_set = self.tab_set.page_set
background = page_set.pages_frame.cget('background')
# mask replaces the middle of the border with the background color
self.mask = Frame(page_set, borderwidth=0, relief=FLAT,
background=background)
# mskl replaces the bottom-left corner of the border with a normal
# left border
self.mskl = Frame(page_set, borderwidth=0, relief=FLAT,
background=background)
self.mskl.ml = Frame(self.mskl, borderwidth=self.bw,
relief=RAISED)
self.mskl.ml.place(x=0, y=-self.bw,
width=2*self.bw, height=self.bw*4)
# mskr replaces the bottom-right corner of the border with a normal
# right border
self.mskr = Frame(page_set, borderwidth=0, relief=FLAT,
background=background)
self.mskr.mr = Frame(self.mskr, borderwidth=self.bw,
relief=RAISED)
def _place_masks(self, selected=False):
height = self.bw
if selected:
height += self.bw
self.mask.place(in_=self,
relx=0.0, x=0,
rely=1.0, y=0,
relwidth=1.0, width=0,
relheight=0.0, height=height)
self.mskl.place(in_=self,
relx=0.0, x=-self.bw,
rely=1.0, y=0,
relwidth=0.0, width=self.bw,
relheight=0.0, height=height)
page_set = self.tab_set.page_set
if selected and ((not self.is_last_in_row) or
(self.winfo_rootx() + self.winfo_width() <
page_set.winfo_rootx() + page_set.winfo_width())
):
# for a selected tab, if its rightmost edge isn't on the
# rightmost edge of the page set, the right mask should be one
# borderwidth shorter (vertically)
height -= self.bw
self.mskr.place(in_=self,
relx=1.0, x=0,
rely=1.0, y=0,
relwidth=0.0, width=self.bw,
relheight=0.0, height=height)
self.mskr.mr.place(x=-self.bw, y=-self.bw,
width=2*self.bw, height=height + self.bw*2)
# finally, lower the tab set so that all of the frames we just
# placed hide it
self.tab_set.lower()
class TabbedPageSet(Frame):
"""A Tkinter tabbed-pane widget.
Constains set of 'pages' (or 'panes') with tabs above for selecting which
page is displayed. Only one page will be displayed at a time.
Pages may be accessed through the 'pages' attribute, which is a dictionary
of pages, using the name given as the key. A page is an instance of a
subclass of Tk's Frame widget.
The page widgets will be created (and destroyed when required) by the
TabbedPageSet. Do not call the page's pack/place/grid/destroy methods.
Pages may be added or removed at any time using the add_page() and
remove_page() methods.
"""
class Page(object):
"""Abstract base class for TabbedPageSet's pages.
Subclasses must override the _show() and _hide() methods.
"""
uses_grid = False
def __init__(self, page_set):
self.frame = Frame(page_set, borderwidth=2, relief=RAISED)
def _show(self):
raise NotImplementedError
def _hide(self):
raise NotImplementedError
class PageRemove(Page):
"""Page class using the grid placement manager's "remove" mechanism."""
uses_grid = True
def _show(self):
self.frame.grid(row=0, column=0, sticky=NSEW)
def _hide(self):
self.frame.grid_remove()
class PageLift(Page):
"""Page class using the grid placement manager's "lift" mechanism."""
uses_grid = True
def __init__(self, page_set):
super(TabbedPageSet.PageLift, self).__init__(page_set)
self.frame.grid(row=0, column=0, sticky=NSEW)
self.frame.lower()
def _show(self):
self.frame.lift()
def _hide(self):
self.frame.lower()
class PagePackForget(Page):
"""Page class using the pack placement manager's "forget" mechanism."""
def _show(self):
self.frame.pack(fill=BOTH, expand=True)
def _hide(self):
self.frame.pack_forget()
def __init__(self, parent, page_names=None, page_class=PageLift,
n_rows=1, max_tabs_per_row=5, expand_tabs=False,
**kw):
"""Constructor arguments:
page_names -- A list of strings, each will be the dictionary key to a
page's widget, and the name displayed on the page's tab. Should be
specified in the desired page order. The first page will be the default
and first active page. If page_names is None or empty, the
TabbedPageSet will be initialized empty.
n_rows, max_tabs_per_row -- Parameters for the TabSet which will
manage the tabs. See TabSet's docs for details.
page_class -- Pages can be shown/hidden using three mechanisms:
* PageLift - All pages will be rendered one on top of the other. When
a page is selected, it will be brought to the top, thus hiding all
other pages. Using this method, the TabbedPageSet will not be resized
when pages are switched. (It may still be resized when pages are
added/removed.)
* PageRemove - When a page is selected, the currently showing page is
hidden, and the new page shown in its place. Using this method, the
TabbedPageSet may resize when pages are changed.
* PagePackForget - This mechanism uses the pack placement manager.
When a page is shown it is packed, and when it is hidden it is
unpacked (i.e. pack_forget). This mechanism may also cause the
TabbedPageSet to resize when the page is changed.
"""
Frame.__init__(self, parent, **kw)
self.page_class = page_class
self.pages = {}
self._pages_order = []
self._current_page = None
self._default_page = None
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.pages_frame = Frame(self)
self.pages_frame.grid(row=1, column=0, sticky=NSEW)
if self.page_class.uses_grid:
self.pages_frame.columnconfigure(0, weight=1)
self.pages_frame.rowconfigure(0, weight=1)
# the order of the following commands is important
self._tab_set = TabSet(self, self.change_page, n_rows=n_rows,
max_tabs_per_row=max_tabs_per_row,
expand_tabs=expand_tabs)
if page_names:
for name in page_names:
self.add_page(name)
self._tab_set.grid(row=0, column=0, sticky=NSEW)
self.change_page(self._default_page)
def add_page(self, page_name):
"""Add a new page with the name given in page_name."""
if not page_name:
raise InvalidNameError("Invalid TabPage name: '%s'" % page_name)
if page_name in self.pages:
raise AlreadyExistsError(
"TabPage named '%s' already exists" % page_name)
self.pages[page_name] = self.page_class(self.pages_frame)
self._pages_order.append(page_name)
self._tab_set.add_tab(page_name)
if len(self.pages) == 1: # adding first page
self._default_page = page_name
self.change_page(page_name)
def remove_page(self, page_name):
"""Destroy the page whose name is given in page_name."""
if not page_name in self.pages:
raise KeyError("No such TabPage: '%s" % page_name)
self._pages_order.remove(page_name)
# handle removing last remaining, default, or currently shown page
if len(self._pages_order) > 0:
if page_name == self._default_page:
# set a new default page
self._default_page = self._pages_order[0]
else:
self._default_page = None
if page_name == self._current_page:
self.change_page(self._default_page)
self._tab_set.remove_tab(page_name)
page = self.pages.pop(page_name)
page.frame.destroy()
def change_page(self, page_name):
"""Show the page whose name is given in page_name."""
if self._current_page == page_name:
return
if page_name is not None and page_name not in self.pages:
raise KeyError("No such TabPage: '%s'" % page_name)
if self._current_page is not None:
self.pages[self._current_page]._hide()
self._current_page = None
if page_name is not None:
self._current_page = page_name
self.pages[page_name]._show()
self._tab_set.set_selected_tab(page_name)
def _tabbed_pages(parent):
# test dialog
root=Tk()
width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
root.geometry("+%d+%d"%(x, y + 175))
root.title("Test tabbed pages")
tabPage=TabbedPageSet(root, page_names=['Foobar','Baz'], n_rows=0,
expand_tabs=False,
)
tabPage.pack(side=TOP, expand=TRUE, fill=BOTH)
Label(tabPage.pages['Foobar'].frame, text='Foo', pady=20).pack()
Label(tabPage.pages['Foobar'].frame, text='Bar', pady=20).pack()
Label(tabPage.pages['Baz'].frame, text='Baz').pack()
entryPgName=Entry(root)
buttonAdd=Button(root, text='Add Page',
command=lambda:tabPage.add_page(entryPgName.get()))
buttonRemove=Button(root, text='Remove Page',
command=lambda:tabPage.remove_page(entryPgName.get()))
labelPgName=Label(root, text='name of page to add/remove:')
buttonAdd.pack(padx=5, pady=5)
buttonRemove.pack(padx=5, pady=5)
labelPgName.pack(padx=5)
entryPgName.pack(padx=5)
root.mainloop()
if __name__ == '__main__':
from idlelib.idle_test.htest import run
run(_tabbed_pages)
|
#!/usr/bin/python
# -*-coding: utf-8-*-
import re
import sys
def readFile(file_path):
file_object = open(file_path)
try:
return file_object.read( )
finally:
file_object.close( )
if __name__ == '__main__':
if len(sys.argv) == 1:
str='abcd(006531)(hello)'
arr = re.findall(r'[^()]+', str)
for item in arr:
print item
else:
str = readFile(sys.argv[1])
for item in re.findall(r'[^()]+', str):
if item.startswith('00') or item.startswith('60'):
print item
|
#################
## Left Rotate ##
#################
def reverse(A,s,f):
while s < f:
A[s],A[f] = A[f],A[s]
f -= 1
s += 1
return A
# The following function shift all the elements of A by k positions on the left
# the first k elements are attached at the end of A
# This is done in place in O(n)
def left_rotate(A,k):
n = len(A)
k = k % n
A = reverse(A,0,n-1)
A = reverse(A,0,n-k-1)
A = reverse(A,n-k,n-1)
return A
A = [1,2,3,4,5,6,7,8,9,10]
A = left_rotate(A,4)
|
class disjointSets:
def __init__(self, n):
self.sets = [-1]*n
self.size = n
# returns true or false as to weather or not a union was preformed
def union(self, a, b): # union by size
rootA = self.find(a)
rootB = self.find(b)
if rootA == rootB:
return False # union was not preformed
newSize = self.sets[rootA]+self.sets[rootB]#size is negative the number of elements of the set
# rootA has more elements
if self.sets[rootA] < self.sets[rootB]:
self.sets[rootB] = rootA
self.sets[rootA] = newSize
else: # B has more or same
self.sets[rootA] = rootB
self.sets[rootB] = newSize
self.size -= 1
return True # union was preformed
def find(self, a): # finds root of element with id 'a'
# also make the parents of this node the root in order to decrease tree height
parent = self.sets[a]
if parent < 0:
return a
root = self.find(parent)
self.sets[a] = root
return root
|
#coding:utf-8
class Animals():
def breathe(self):
print("breathing")
def move(self):
print("moving")
def eat(self):
print("eating food")
class Mammals(Animals):
def breastfeed(self):
print("feeding young")
class Cats(Mammals):
def _init_(self,spots):
self.spots=spots
def catch_mouse(self):
print("catch mouse")
def left_foot_forward(self):
print ("left foot forward")
def left_foot_backward(self):
print("left foot backward")
def dance(self):
self.left_foot_forward()
self.left_foot_backward()
self.left_foot_forward()
self.left_foot_backward()
kitty=Cats(10)
print(kitty.spots)
kitty.dance()
kitty.breastfeed()
kitty.move()
|
#!/usr/bin/python3
# sempre que vai buscar algo, é necessário buscar pela chave
# pessoa = {}
# pessoa = {'nome':'daniel','email':'daniel@daniel'}
# pessoa['nome']
# 'daniel'
# pprint é uma biblioteca para organizar o dicionario e exibir um abaixo do outro
# from pprint import pprint
# pessoas = [
# {'nome':'daniel', 'idade':24},
# {'nome':'joao', 'idade':45},
# {'nome':'maria', 'idade':45},
# {'nome':'pedro', 'idade':20},
# ]
# # print(type(pessoas[0])) -- ver o tipo
# print(pessoas)
# pessoa.key() -- para exibir as chaves
# pessoa.value() -- exibir os valores das chaves
# pessoa.items() -- exibe as chaves e os valores separadamente
# list(pessoa.key()) -- exibe os valores
# pessoa = {'nome':'daniel','email':'daniel@daniel'}
# for x in pessoa.keys():
# print(x)
# for x in pessoa.values():
# print(x)
# pessoa = {'nome':'daniel','email':'daniel@daniel'}
# for x,y in pessoa.items(): # sempre quando for percorrer items é necessário 2 variáveis
# print(x,y)
# pessoa = {'nome':'daniel','email':'daniel@daniel'}
# print(pessoa.get('idade', 0)) # get é para fazer uma busca dentro do dicionário
# print(pessoa.get('idade', 'nao achei'))
# print(pessoa.get('nome', 'nao achei'))
# pessoa = {'nome':'daniel','email':'daniel@daniel'}
# del pessoa['nome'] # -- deleta uma pessoa
# print(pessoa) |
#!/usr/bin/python3
# escrever uma função se o número for par ou impar
import pdb
def par_impar(num):
if num %2 == 0:
return'Par'
else:
return'impar'
resultado = par_impar(10)
print(resultado)
|
print(' dict '.center(60, '*'))
student1 = {
'name': 'Python 3',
'age': 11,
'id': 11-21-21,
'phone': '+88016 7839743',
1 : 34
}
student1['add'] = 'Dhaka, Dangladesh'
student1['name'] = 'Python 2'
print(student1['name'])
print(student1.get('jfsl'))
print(student1.items())
print(student1.keys())
print(student1.values())
student1.popitem()
print(student1)
if not 'nme' in student1:
student1.pop('name')
else:
print('Name is not in student1')
print(student1)
|
class Turtle:
#atri
color = 'green'
weight = 10
def eat(sel):
sel.color = 'red'
print('I am eating')
tt =Turtle()
print(tt.color)
tt.eat()
print(tt.color)
|
import sys
import copy
import time
#The input and the goal states are passed through an input file
with open('input.txt', 'r') as input_file:
data_item = [[int(num) for num in line.split()] for line in input_file if line.strip() != ""]
#Extracting the Input and Goal States from the input file.
start_state = data_item[0:3].copy()
goal_state = data_item[3:6].copy()
termination_time = 3600 # Termination time in seconds of program if the solution is not obtained within the timit limit
total_nodes = 0
#Defining the structure of the node.
class node:
def __init__(self, starts=None, path=None, move=None, h=None):
self.state = starts
self.hvalue = h
self.curPath = path
self.operation = move
def display(self, tlist):
for i in range(0, 3):
print(tlist[i])
#Finding the neighbors/Children of the current node.
def generate_sub_space(self, parent, h=None, total_nodes=None):
children = []
x = None
y = None
#Finding the Position of Blank Space
for i in range(0, 3):
for j in range(0, 3):
if parent.state[i][j] == 0:
x = i
y = j
break
if x is not None:
break
#Defining actions on all possible moves of the Blank space and generating children.
if x != 0:
tpath = copy.deepcopy(parent.curPath)
tpath.append("Up")
child = node(copy.deepcopy(parent.state), tpath, "Up", h)
child.state[x - 1][y], child.state[x][y] = child.state[x][y], child.state[x - 1][y] #Swapping of Blank Space with a Numbered Tile
children.append(child)
total_nodes += 1;
if x != 2:
tpath = copy.deepcopy(parent.curPath)
tpath.append("Down")
child = node(copy.deepcopy(parent.state), tpath, "Down", h)
child.state[x + 1][y], child.state[x][y] = child.state[x][y], child.state[x + 1][y]
children.append(child)
total_nodes += 1;
if y != 0:
tpath = copy.deepcopy(parent.curPath)
tpath.append("Left")
child = node(copy.deepcopy(parent.state), tpath, "Left", h)
child.state[x][y - 1], child.state[x][y] = child.state[x][y], child.state[x][y - 1]
children.append(child)
total_nodes += 1;
if y != 2:
tpath = copy.deepcopy(parent.curPath)
tpath.append("Right")
child = node(copy.deepcopy(parent.state), tpath, "Right", h)
child.state[x][y + 1], child.state[x][y] = child.state[x][y], child.state[x][y + 1]
children.append(child)
total_nodes += 1;
return [s for s in children if s]
def to_String(self, temp_state):
s = ''
for i in temp_state:
for j in i:
s = s + str(j)
return s
def heuristic_tiles(self, state):
displacement = 0
for i in range(0, 3):
for j in range(0, 3):
if state[i][j] != 0:
if state[i][j] != goal_state[i][j]:
displacement = displacement + 1
return displacement
def hill_climbing_with_misplaced_Tiles(self):
max_list_size = -sys.maxsize - 1
time_flag = 0
start_time = time.time()
queue = []
start_node = node(start_state, [], '', self.heuristic_tiles(start_state))
queue.append(start_node)
while (queue):
if len(queue) > max_list_size:
max_list_size = len(queue)
temp_time = time.time()
if (temp_time - start_time >= termination_time):
time_flag = 1
break
current_node = queue.pop(0)
if current_node.state == goal_state:
print("\n Success")
print("\n Number of Moves : " + str(len(current_node.curPath)))
print(str(current_node.curPath))
print("\n Total number of states explored : " + str(len(current_node.curPath)))
print("\n Time taken by Hill climbing for execution : " + str(time.time() - start_time))
print("\n Maximum list size : " + str(max_list_size))
break
h_val = self.heuristic_tiles(current_node.state)
next_state = False
for s in self.generate_sub_space(current_node,self.heuristic_tiles(current_node.state), total_nodes):
h_val_next = self.heuristic_tiles(s.state)
if h_val_next <= h_val:
next_state = s
h_val = h_val_next
if next_state:
queue.append(next_state)
else:
print("cannot find solution")
print("\n Total number of states explored : " + str(total_nodes))
print("\n Hill Climbing with tile displacement terminated after " + str(
int(time.time() - start_time) / 60) + " minutes without solution")
if time_flag == 1:
print("\n Failure, The program is not able to give solution within the time limit")
print("\n Total number of states explored : " + str(total_nodes))
print("\n Hill climbing with tile displacement terminated after " + str(
int(time.time() - start_time) / 60) + " minutes without solution")
if __name__ == "__main__":
obj1 = node()
print("\n Start State is : ")
obj1.display(start_state)
print("\n Goal State is : ")
obj1.display(goal_state)
obj1.hill_climbing_with_misplaced_Tiles()
|
#dictionaries and generator expressions
prices = {'apple' : 0.40, 'banana' : 0.50}
my_purchase = {
'apple' : 1,
'banana' : 6 }
grocery_bill = sum(prices[fruit] * my_purchase[fruit]
for fruit in my_purchase)
print 'I owe the grocer $%.2f' % grocery_bill |
graph = {
'a': ['b'],
'b': ['c', 'f'],
'c': [],
'd': ['a', 'e'],
'e': ['f'],
'f': ['c']
}
def depth_first_search(graph):
visited = {}
for v in graph.keys():
visited[v] = False
for vertex in graph.keys():
dfs(vertex, graph, visited)
def dfs(vertex, graph, visited):
if visited[vertex]:
return
visited[vertex] = True
print(vertex)
for path in graph[vertex]:
dfs(path, graph, visited)
depth_first_search(graph)
|
def quick_sort(array, i, j):
if i >= j:
return []
pivot = find_pivot(array, i, j)
k = partition(array, i, j, pivot)
quick_sort(array, i, k-1)
quick_sort(array, k, j)
def find_pivot(array, i, j):
for k in range(i, j+1):
if array[i] != array[k]:
if array[i] > array[k]:
return array[i]
else:
return array[k]
def partition(array, l, r, pivot):
while True:
print(array, pivot, l, r, 'start')
while array[l] < pivot:
l += 1
while array[r] >= pivot:
r -= 1
print(array, pivot, l, r, 'end')
if l > r:
return l
array[l], array[r] = array[r], array[l]
array = [1, 5, 2, 4, 3]
quick_sort(array, 0, 4)
print(array)
|
def bubble_sort(array):
for i in range(len(array)-2):
for j in reversed(range(i+1, len(array)-1)):
if array[j-1] > array[j]:
array[j-1], array[j] = array[j], array[j-1]
return array
print(bubble_sort([4, 6, 1, 3, 7]))
|
"""
Title: Library_Dhiraj
Authour: Dhiraj Meenavilli
Date: October 26 2018
"""
### --- Inputs --- ###
def operations():
customer = str(input("What is the customer's name?"))
print("")
return customer
def served():
try:
ask = int(input("Was the previous customer served justice ice tea? (1 yes, 2 no)"))
except ValueError:
return served()
return ask
|
import pandas as pd
# *********** LOAD DATA ***********
headers = ["age", "workclass", "fnlwgt", "education",
"education-num", "marital-status", "occupation",
"relationship", "race", "sex", "capital-gain",
"capital-loss", "hours-per-week", "native-country", "answer"]
df = pd.read_csv("./adult.csv", header=None skip_initial_)
df.columns = headers
print(df.head(20))
# Replace missing values "?" with
# --> Strip out that row (rows with ?)
# --> Replace with mean XXX
print((df[headers] == ' ?').sum()) # has missing data
df = df.drop(df[df.workclass == " ?"].index)
df = df.drop(df[df.occupation == " ?"].index)
df = df.drop(df[df["native-country"] == " ?"].index) # would be intereesting to see that there is very very little correlation between missing native-country and the other 2 commonly missing values
print((df[headers] == ' ?').sum()) # no more missing data
# Encode Categorical Data
# --> Strip out categorical 'education' because numeric 'education-num' covers it fine
# -->
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Simple iterator that print all files.
Author: Ronen Ness.
Since: 2016.
"""
from .. import files_iterator
class PrintFiles(files_iterator.FilesIterator):
"""
Iterate over files and print their names.
"""
def process_file(self, path, dryrun):
"""
Print files path.
"""
if not dryrun:
print path
return path
|
import pickle
import os
class hello:
#实例初始化时调用方法
def __init__(self,name):
self.dd=name
self.sd=name+':'+name
print('1202初始化.....')
#无参数方法,Python类的方法的参数列表,必须至少有一个self 参数,调用时则可以不赋值,相当于JAVA中的this
def hhle(self):
print('Hi, this is my python class. my name is ',self.dd, '. The sd is',self.sd)
print(os.path)
#类的实例化
myhello=hello('thomas')
#实例调用类的方法
myhello.hhle()
class human:
#实例初始化时调用方法
def __init__(self,name,address,age):
self.name=name
self.address=address
self.age=age
print('人类初始化:{}'.format(self.name))
def tell(self):
'''打印出父类详细情况'''
print('name:{},address:{},age:{}'.format(self.name,self.address,self.age),end=' ')
#父类human派生类man
class man(human):
#子类man实例初始化时调用方法
def __init__(self,name,address,age,huzi):
#子类调用父类初始化的方法
human.__init__(self,name,address,age)
self.huzi=huzi
print('男人初始化:{}'.format(self.name))
def tell(self):
human.tell(self)
print('huzi:{}'.format(self.huzi))
#父类human派生类woman
class woman(human):
#子类woman实例初始化时调用方法
def __init__(self,name,address,age,breast):
#子类调用父类初始化的方法
human.__init__(self,name,address,age)
self.breast=breast
print('女人初始化:{}'.format(self.name))
def tell(self):
human.tell(self)
print('breast:{}'.format(self.breast))
m1=man('关羽','成都',35,'胡子长')
m2=man('张飞','成都',33,'胡子短')
m3=man('刘备','成都',40,'胡子短')
w1=woman('小乔','苏州',23,'漂亮')
w2=woman('曹鹅','苏州',25,'孝顺')
print()
members=[m1,m2,m3,w1,w2]
for member in members:
member.tell()
print('输出结束!')
# 下面是另一段 try ...except...finally 异常处理程序, 该代码段也可以被 with 语句代替
try:
flnm=u'三国人物.txt'
f=open(flnm,'wb')
pickle.dump(m1,f)
#f.write(members)
f.close()
f=open(flnm,'rb')
store=pickle.load(f)
print(store)
except:
print('代码出错了!')
finally:
f.close()
print('File is closed.')
# 上面的 try ...except...finally 异常处理程序, 也可以被 with 语句代替
with open(flnm,'rb') as f:
for line in f:
print(line)
class abc:
def __init__(self, name, add, age):
self.name = name
self.add = add
self.age = age
print('The class abc is intializing...')
def call(self):
print('class function is calling now!')
print('My name is ', self.name, ',', end='')
print('and I live in ', self.add, ',', end='')
print('and I am', self.age, 'years old.')
#print('My name is {}:I live in {}:I am {} years old.'.format(self.name, self.add, self.age))
ruotong = abc('Guanruotong', 'Guangzhou', 5)
ruotong.call()
chunhui = abc('Chunhui', 'Guangzhou', 10)
chunhui.call()
ruotong.call()
chunhui.call()
class book :
def __init__(self, name, author, publishtime):
self.name = name
self.author = author
self.publishtime = publishtime
print('book initializing......')
def input(self, count):
self.count = count
|
'''
: string的实际使用技巧
:python cookbook3
: 2018-10-12
'''
import re
line='asdf fjdk; afed,fjek,asdf, foo'
#使用多个界定符分割字符串
my=re.split(r'[;,\s]\s*', line)
print(my)
m1=tuple(my) #list type convert into tuple type
print(m1)
m2=list(m1) #tuple type convert into list type
print(m2)
#文件名匹配检查,返回 True or False
from fnmatch import fnmatch,fnmatchcase
s1='foo.txt'
print(fnmatch(s1,'*.txt'))
print(fnmatchcase(s1,'*.TXT'))
dc=re.compile(r'\d+/\d+/\d+') # 正则表达式编译后,可以多次调用
# Simple matching: \d+ means match one or more digits
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
print(dc.match(text)) # match从字符串开始位置进行匹配,此例返回false
print(dc.findall(text)) # findall从字符串任意位置进行匹配,此例返回两个日期['11/27/2012', '3/13/2013']
from calendar import month_abbr
re.IGNORECASE
#sub(被查的特定字符串,替换为字符串,被查找完整字符串,查找时忽略大小写标识)
text2 = 'UPPER PYTHON, lower python, Mixed Python'
print(re.sub('python', 'snake', text2, flags=re.IGNORECASE)) #查找并替换,忽略查找字符串的大小写
def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
text3='this is a book.'
print(text3.capitalize(), text3.upper(), text3.lower())
#unicodedata 标准化
import unicodedata
s = '\ufb01' # A single character
print(unicodedata.normalize('NFC',s))
print(unicodedata.normalize('NFD',s))
mm=re.compile(r'\d+')
ss='this is my score 112 113 114'
print(mm.findall(ss))
#strip, lstrip, rstrip,去除空格
gstr=' hello world '
print(gstr.strip())
print(gstr.lstrip())
print(gstr.rstrip())
x = 1.2345
print(format(x, '*>30')) #右对齐,宽度30个字符,空白位置用 * 填充
print(format(x, '*<30')) #左对齐,宽度30个字符,空白位置用 * 填充
print(format(x,'^30.2f')) #居中对齐,2位小数,浮点型
sa='Hello'
sb='everyone'
sc='good afternoon!'
print(sa,sb,sc,sep=': ')
print('{} {}'.format(1,2))
#使用textwrap 模块来格式化字符串的输出
import textwrap
import os
s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."
print(textwrap.fill(s,70,initial_indent=' ')) #格式化成每行70个字符,首行缩进空格
#字节字符串,返回整数不是字符
s = b'Hello World'
print(s)
print(s[0])
print(s.decode('ascii')) #解码后正常输出
|
#实现一个电话本,屏幕录入联系人信息,并写入文件,可查看、修改、删除操作。
import os
import time
import pickle
#文件名和存储路径
filename='电话本.txt'
filedir='d:\\PycharmProjects\\test'
filepath=filedir+os.sep+filename
print('电话本存储路径是:',filepath)
content={':':'-'}
class contactbook:
def __init__(self,name,sex,age,address,phone):
self.name=name
self.sex=sex
self.age=age
self.address=address
self.phone=phone
print('联系薄对象初始化中......')
def inputcontactbook(self):
isinput=True
while isinput:
self.name=str(input('请输入联系人姓名:'))
self.sex=str(input('请输入联系人性别:'))
self.age=str(input('请输入联系人年龄:'))
self.address=str(input('请输入联系人地址:'))
self.phone=str(input('请输入联系人电话:'))
#content=content+str(self.name)+str(self.sex)+str(self.age)+str(self.address)+str(self.phone)
# dict 的赋值 key=value
content[str(self.name)]='姓别:'+str(self.sex)+' '+\
'年龄:'+str(self.age)+' '+\
'地址:'+str(self.address)+' '+\
'电话:'+str(self.phone)+' '
f=open(filename,'wb')
#f.write(content)
pickle.dump(content,f)
f.close()
f=open(filename,'rb')
storedcontent=pickle.load(f)
#del content[''] #删预置的第1条数据,按key删除
print(storedcontent)
s=input('您还要继续输入吗?请回答Y/N:')
if s=='N':
print('您已退出登记薄输入程序!')
isinput=False
f.close()
break
elif s=='n':
break
else:
continue
# 类实例化:
mycontactbook=contactbook('','','','','')
# 类方法调用:
mycontactbook.inputcontactbook()
|
from decimal import Decimal
from decimal import localcontext
n1=Decimal('1.245')
n2=Decimal('2.8992')
print(n1+n2)
# 通过上下文设置输出精度
with localcontext() as ctx:
ctx.prec=20 #设置运算结果的精度
print(n1/n2)
# 格式化输出
n3=10
print(format(n3,'b')) #将数字转化为二进制输出
print(format(n3,'o')) #将数字转化为八进制输出
print(format(n3,'x')) #将数字转化为十六进制输出
#numpy模块的使用,对列表、数组有强大的运算能力
import numpy as np
a=[1,2,3,4,5]
b=[6,7,8,9,10]
print(a+b) #输出结果是两个列表的连接
print(sum(x for x in a))
print(sum(x*x for x in a))
ax=np.array([1,2,3,4,5]) #使用numpy构建数组
bx=np.array([6,7,8,9,10])
print(ax+bx) #输出结果是两个列表的元素求和,条件是两个列表的元素个数必须相等
print(ax*2, bx*2, ax*bx)
import random
a1=[1,2,3,4,5]
print(random.choice(a1)) #随机输出指定列表中的元素
print(random.sample(a1,2)) #随机从指定列表中抽取特定数目的样本
print(random.randint(0,100)) #随机生成100内的整数
'''
:一个猜数字小游戏
:利用random.randint()生成一个随机数
:玩游戏者通过提示最终猜到这个随机数
'''
import pickle
tips='''
Please select the game level:
1. Grade 1;
2. Grade 2;
3. Grade 3;
'''
#print(tips)
print('{0:*^150}'.format(tips))
grade=int(input('You select the Grade: '))
if grade==1:
sjsh=random.randint(0,10)
elif grade==2:
sjsh=random.randint(0,50)
else:
sjsh=random.randint(0,100)
jx=True #控制循环
cishu=0 #统计累计猜的次数
neirong={} #dic数据结构保存记录
#neirong.keys=input('Pls input your name: ')
#name=input('Pls input your name: ')
while jx:
a=int(input('Pls input a number: '))
if a==sjsh:
cishu+=1
print('Great!The suijishu is:',sjsh)
print('You have guessed times:',cishu)
with open('猜一猜.txt','ab') as f: #open()参数a,追加写入文件
neirong[input('Pls input your name: ')]=cishu
#jilu=name+': '+str(cishu)
pickle.dump(neirong,f) #序列化写入文件
#f.write(neirong)
jx=False
elif a<sjsh:
print('Small!')
cishu+=1
continue
else:
print('Big!')
cishu+=1
continue
#print(format('猜数字排行榜','^50')
with open('猜一猜.txt','rb') as f:
while True:
try:
line=pickle.load(f) #反序列化输出文件
print(line)
except EOFError:
break #抛出异常时退出
#line=f.readline() #普通文件输出方式
#if len(line)==0:
# break
#else:
# print(line)
|
"""
This python file is shown how to use the Character function.
It includes all kinds of character usage.
It is from a web article.
Let's begin from March, 31st, 2022.
"""
'''
///第一部分:字符串切片操作///
'''
test = "python programming"
print("The string is: ", test)
for i in range(len(test)):
print(test[i], '--', end='')
print()
# 输出首字母
first_char = test[:1]
print("The first character of the string is:", first_char)
# 输出尾字母
last_char = test[-1:]
print("The last character of the string is:", last_char)
# 输出除去首字母的所有字符
except_char = test[1:]
print("The except first character of the string is:", except_char)
# 输出除去尾字母的所有字符
except_last = test[:-1]
print("The except last character of the string is:", except_last)
# 输出首字母和尾字母中间的所有字符
between_two = test[2:-2]
print("The between two character of the string is:", between_two)
# 跳过一个字符输出
skip_one = test[0:18:2] # [start:stop:step]
print("The skip one character of the string is:", skip_one)
# 反转输出字符串
reverse_char = test[::-1]
print("The reverse character of the string is:", reverse_char)
'''
///第二部分:返回某字母出现的次数///
'''
import re
from collections import Counter
sentence = "Canada is located in the northern part of North America"
counter = len(re.findall('a', sentence))
print(counter)
counter = sentence.count('a')
print(counter)
g = (x * x for x in range(10))
print(g)
|
# This is my first program in Python.
print("Hello,World!")
print("Hello,Thomas!")
print('{0} is my son, his age is {1}'.format('春晖',8))
print('{0:.6f}'.format(2/3))
print('this is first line,\nthis is second line.')
print("what's your name?") #字符串输出,用双引号
print('what\'s your name?') #字符串输出,用单引号+转义字符\
i=5
print(i)
i=i+1
print(i)
s='''
this is third line.
this is fourth line
''' #三个引号,表达多行字符串
print(s)
t = 'hello, hello ,hello,\
we remeber you forever!'
print(t)
length = 10
width = 8
area = length*width
print('The area is', area)
print('{0:*^120}'.format('The Log File Output End'))
'''
Python数据类型:
1)常量,数值型常量或字符型常量,字符型要用引号括起来
2)int, float
3) string
字符串可以用单引号,也可以用双引号,多行字符串用三引号
4)format,字符串格式化输出
5) 运算符:+-* /, **, //, %
'''
|
import unittest
import cap
#you will inheret from unittest the class TestCase
class TestCap(unittest.TestCase):
# crate a function for each test
def test_one_word(self):
# going to test cap_text function you need to test with criteria (text = 'python')
# make sure you function performs as expected
text = 'python'
result = cap.cap_text(text)
self.assertEqual(result, 'Python')
def test_multiple_words(self):
text = 'monty python'
result = cap.cap_text(text)
self.assertEqual(result, 'Monty Python')
if __name__ == '__main__':
unittest.main() |
# DocQuery-example.py
# Collin Lynch and Travis Martin
# 9/8/2021
# The DocQuery code is taked with taking a query and a set of
# saved documents and then returning the document that is closest
# to the query using either TF/IDF scoring or the sum vector.
# When called this code will load the docs into memory and deal
# with the distance one at a time.
# Imports
# ---------------------------------------------
import spacy
import os
import scipy.spatial
import nltk
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
# Core Code.
# ---------------------------------------------
"""
input: document directory
1. load the pacy vocab
2. look in the document directory and load all files in it
3. do not load the url file
4. put all the loaded files into a list
output: all the doc names that need to be loaded
"""
def load_docs(DocDir):
BaseVocab = spacy.vocab.Vocab()
Loaded_Docs = {}
for file in os.listdir(Directory):
if file != 'infile.txt':
LoadedDoc = spacy.tokens.Doc(BaseVocab).from_disk(Directory + file)
Loaded_Docs[file] = LoadedDoc
return Loaded_Docs
"""
input: spacy model, docs as a dict, query string, compfunction
1. set the closest document as the first in the list
2. decide to do a vector or tfidf comparison
3. if doing a vec comparison
a. sum the vectors for the words in the query
b. set closest distance to be 1 - farthest two sets can be apart
c. take in a single document and find the sum of all the word vectors in the doc
d. check to see if computed distance is smaller than current distance
e. set closest document and name
4. if doing a tfidf comparison
a. create a tfidf model for documents in the corpus
b. set closest distance to -1 = nonsensical value
c. take the query and sum up the words that appear in each document to geta score
d. check to see if new score higher than the rest - highest score is better
e. set closest doc and name
5. return the closest document and name
output: closest document and closest name
"""
def get_closest(SpacyModel, Docs, Query, CompFunc):
# Store the first doc in the list as the closest.
ClosestName = list(Docs.keys())[0]
ClosestDoc = Docs[ClosestName]
# Now we iterate over the remainder simply checking
# their distance and updating if they are closer.
if CompFunc == "VEC":
query_vec = 0
for word in Query:
query_vec += word.vector
ClosestDist = 1
for key in Docs.keys():
tempdist = get_vec_dist(SpacyModel, Docs[key], query_vec)
if tempdist < ClosestDist:
ClosestDist = tempdist
ClosestName = key
ClosestDoc = Docs[key]
elif CompFunc == "TFIDF":
TFIDFModel, Dct, Corpus = compute_tfidf_value(Docs)
ClosestDist = -1
for n in range(len(Corpus)):
tempdist = get_tfidf_dist(Query.text, TFIDFModel[Corpus[n]], Dct)
if tempdist > ClosestDist:
ClosestDist = tempdist
ClosestName = list(Docs.keys())[n]
ClosestDoc = Docs[ClosestName]
# Now return the best as a pair.
return ClosestName, ClosestDoc
"""
input: all the documents in the corpus
1. create an empty list
2. go through all the documents in the set
3. tokenize the document and add it to the list
4. create a dictionary with a unique key for each word in the corpus
5. cycle through all the text and count the frequency of each word
6. create a tfidf model based on the text above
output: the model, dictionary, and corpus of text
"""
def compute_tfidf_value(Docs):
all_doc_words = []
for key in Docs.keys():
word_tokens = nltk.word_tokenize(Docs[key].text)
all_doc_words.append(word_tokens)
Dct = Dictionary(all_doc_words)
Corpus = [Dct.doc2bow(line) for line in all_doc_words]
Model = TfidfModel(Corpus)
return Model, Dct, Corpus
"""
input: query as a string, tfidf models individual corpus, dictionary
1. set total score to 0 = lowest value possible
2. go through the entire vaector passed in and look to see if the words in the query string are present
3. if they are present add the score values
4. return the total score
output: total score
"""
def get_tfidf_dist(Query, Vector, Dct):
total_score = 0
for id, score in Vector:
if Dct[id] in Query:
#print(Dct[id], " = ", score)
total_score += score
return total_score
"""
input: spacy model, doc, query asa vector
1. set total vec to 0 = nonsensical value
2. iterate through the document and find the vector for each word in the doc
3. sum all the vectors together
4. compute cosine distance for the query and doc
output: the cosine distance computed
"""
def get_vec_dist(SpacyModel, Doc, Query):
total_vec = 0
for word in Doc:
total_vec += word.vector
tempdist = scipy.spatial.distance.cosine(Query, total_vec)
return tempdist
if __name__ == "__main__":
#initial declarations
URL_File = 'infile.txt'
#Type = "VEC"
Type = "TFIDF"
Directory = '/home/aaronl/PycharmProjects/pythonProject/start/'
Query_String = 'The happiest place on Earth'
#open the url file and store the webpage names for later
webpage_names = []
with open(URL_File, 'r') as InFile:
website = InFile.readline()[:-1]
while website:
webpage_names.append(website)
website = InFile.readline()[:-1]
InFile.close()
#load the spacy model
Model = spacy.load("en_core_web_sm")
#load the documents created in the doc downloader program
Loaded_Docs = load_docs(Directory)
#create a spacy model for the query string
Query_Model = Model(Query_String)
#find the lcosest document and name for the query
ClosestName, ClosestDoc = get_closest(Model, Loaded_Docs, Query_Model, Type)
#print the results
print("The closest website to the query string is: " + str(ClosestName))
|
def sayHello(name):
return 'Hello, ' + name + '!'
name = input(
print(sayHello(name)) |
print("Hello World - Coding")
print(5) #숫자
print(100000)
print(5*3+(2-2)/4)
print("장하다.") #문자
print('잘하고있다')
print("넌 할수있다"*3)
# 한줄 주석사용하기
'''여러줄 주석처리하기
방법'''
# 들여쓰기
print('a"')
print('b')
print('c')
# 조건 참/거짓
print(5>10)
print(5<10)
print(True)
print(False)
# 줄바꿈 ( \n ) 같음 ( == )
# 변수, 이름규칙(영문자( 대,소문자구분). - (언더스코어), 숫자(1)만사용 단 숫자는-첫글짜불가
a = 10
b = 5
print(a)
print(b)
print(a*b)
b = 7
print(a*b)
var = 7
print(type(var))
var = '문자열'
print(type(var))
#함수-이름(인자값,인자값,인자갑, ...) ---> 리턴 값
# 자료형함수 / type()
# perfix '0b'는 2진수,'0o'는 8진수,'0x'는 16진수 입니다.
print(0b10)
# 숫자형 (정수형-int, 실수형-float, 복수형-complex)
# 산술연산자 ( +, -, *, /, //(몫), %(나머지))
a=10
b=5
c=2.0
d=0.5
print(a+b)
print(a//b) # 몫
print(a%c) # 나머지
print(a**d) # 제곱
# 논리연산자 ( or, and, not )
print((100 > 10) or (30 <= 3)) # True or False -> True
print((10 == 10) and (3 != 3)) # True and False -> False
print(not (3 <= 3)) # not True -> False
# boolean type : bool ( True( 1, 비어있지않음), False( 0, 비어있음) )
# 비교연산자 ( < , <=, >, >=, ==(같음), !=(같지않음) )
a = 100
b = 50
print(a>=b)
print(a<=b)
print(a>=b)
print(a==b)
# 문자열형 ( str ~, ' ', " ", '''''', """ """, / 문자+문지, 문자*정수)
py = "파이썬으로 코딩을 배우자"
print(py[3])
print(py[1])
print(py[-1])
print(len(py))
# 문자열 slicing (자르기) / [ ? : ? ]
print(py[3])
print(py[4:9])
print(py[:4])
print(py[4:])
# count(), find(), index()
py = "python programming"
print(py.count('p'))
print(py.find('o'))
print(py.index('o'))
print(py.find('w'))
# 대소문자전환 ( upper(), iower() )
print(py.upper())
print(py.lower())
# 문자열 변경하기 ( replace() )
py = "파이썬 공부는 너무 재밌어요!"
print(py.replace("파이썬","HTML"))
print(py)
# 문자열 나누기 ( spiit() 띄어쓰기, 공백기준 )
print(py.split(' '))
print(py.split())
print(py)
# 조건문
# if ~ else
con = "sweet"
if con == "sweet":
print("삼키다")
else:
print("뱉는다")
season = "summer"
if season == "spring":
print("봄이 왔네요!")
else:
if season == "summer":
print("여름에는 더워요~")
else:
if season == "fall":
print("가을은 독서의 계절!")
else:
if season == "winter":
print("겨울에는 눈이 와요~")
# if ~ elif
season = 'winter'
if season == 'spring':
print ("봄")
elif season == "summer":
print (여름)
elif season == 'fall':
print ('가을')
elif season == 'winter':
print ('겨울')
# if pass - 아무일 하지않기
temp = 30
if temp < 26:
pass
else:
print ('에어컨을 켠다.')
num = int (input('숫자 하나 입력 : '))
if num > 0 :
print('{} 은 양수입니다')
# if ~ elif ~ else
# iteration statement - 반복문
# while 조건: - 실행코em / 조건이 참일때 실행반복
i = 1
while i < 11: # 조건식
print("파이썬 " + str(i))
i = i + 1 # 탈출 조건
# 무한루프
a = int ( input('a'))
while a<=2 :
print('실행')
# for문- n번, ~까지 반복하기 / for 변수 in (문자열,tuple,list) 명령문
str = "파이썬 프로그래밍"
for ch in str:
print(ch)
# range(마지막정수)/(시작정수,마지막정수)
for col in range(2,3):
for row in range(1,5):
print (col,'x',row, '=',col*row)
# break와 continue
for col in range(2,10):
if col > 3:
break
for row in range (1,10):
print (col,'x',row,'=',col*row)
for n in range(1,11):
if n % 2 == 0:
continue
print(n, '은 홀수입니다')
# 데이터 구조 ( )
# 군집자료형 ( list, tuple, set, dictionary)
# list type ( 대괄호[] ,쉼표','로구분 )
primes = [2,3,5,7]
for p in primes:
print(p)
print(len(primes))
print(primes[0])
print(primes[-1])
print(primes[1]+primes[3])
# 문자열 slicing ( 콜론 - : , )
print(primes[3])
print(primes[1:3])
print(primes[:3])
print(primes[2:])
print(primes)
# 리스트 복사하기01-주소만 넘겨줌
copy = primes
copy.append(10)
print(copy)
print(primes)
# 리스트 복사하기01-제대로복사/슬라이싱사용
copy = primes[:]
copy.append(11)
print(copy)
print(primes)
#리스트끼리연산
list1 = [1,2,3]
list2 = [4,5,6]
print(list1*3)
print(list1 + list2)
list1.extend(list2) # 원본리스트 변경함
# 리스트 요소추가,제거(요소가 두개이상시 인덱스가 낮은요소제거)
print(list1)
list1 = [1,2,3,4,5]
list1.append(10)
print(list1)
list1.remove(4)
list1.remove(3)
print(list1)
# 리스트에 요소삽입(insert(인수,요소))이나 꺼내기(pop(인수))
list1 = [1,2,3,4,5]
list1.insert(3,9)
print(list1)
list1.pop(4)
print(list1)
# 리스트 뒤집거나(rever()) 정렬하기(sort())
list1 = [1,2,3,4,5]
list2 = [5,2,4,1,3]
list1.reverse()
print(list1)
list1.sort() # 원본변경
print(list1)
print(sorted(list2)) # 원본변경없음
print(list2)
# 중첩 리스트
matrix = [[1,2,3],['하나','둘','셋']]
print(matrix[0])
print(matrix[1])
print(matrix[0][0])
print(matrix[1][2])
# tuple ( 쉼표(,)로구분, 소괄호()로 감싸거나 아예 감싸지 않는다.)
# 튜플명 = (요소,1요소2,요소3)/요소1,요소2,요소3...
tuple1 = (1,2,3)
tuple2 = 1,2,3,
tuple3 = 1,
tuple4 = 1
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
tuple1 = (1, 2, 3)
tuple2 = tuple(["원", "투", "쓰리"])
# 튜플 요소 선택하기
print(tuple1[0])
print(tuple2[-1])
# 튜플 자르기
print(tuple1[1:])
print(tuple2[:2])
# 튜플끼리의 연산
print(tuple1 + tuple2)
print(tuple1 * 2)
# 패킹-packing
tuple = 10,"열",True
# unpacking
a,b,c = tuple
print(a),print(b),print(c)
# 특정요소의포함여부 - in, not in 참-true/ 거짓-false
print(10 in tuple)
print("일곱" in tuple)
print("일곱" not in tuple)
# set tyoe ( 세트선언 중괄호{}/ 요소구분 쉼표(,)/중복제거,순서무시)
# 세트명 = (요소1, 요소2, 요소3, ...)
set1 = {1,2,3}
set2 = set("python")
set3 = set("hello")
print(set1)
print(set2)
print(set3)
set1 = {}
set2 = set()
print(type(set1))
print(type(set2)) # empty set
set1 = {1,2,3}
set1.add(4) # set 요소추가
print(set1)
set1.update((5,6)) # set 여러요소추가
print(set1)
set1.remove(2) # set 요소제거
print(set1)
# 집합연산
set1 = {1,2,3,4,5}
set2 = {1,3,5,7,9}
print(set1 | set2) # 합집합
print(set1 & set2) # 교집함
print(set1 - set2) # 차집합
print(set1 ^ set2) # 여집합 = 합집합 - 교집합
# dictionary ( 선언-중괄호/구분-쉼표(,)/key와 value연결-콜론(:))
dict1 = {'하나':1,'둘':'two','파이':3.14}
dict2 = dict({'하나':1,'둘':'two','파이':3.14})
dict3 = dict([('하나',1),('둘','two'),('파이',3.14)])
dict4 = dict(하나=1,둘='teo',파이=3.14)
print(dict1)
print(dict2)
print(dict3)
print(dict4)
dict1 = {'하나':1, 2:'two', 3.14:'pi'}
dict2 = {('ten',10):['열',10.0]}
print(dict1)
print(dict2)
# 대괄호([])안에 key를 가지고 value를 알수있다. / get()함수 사용
dict1 = {'하나':1, 2:'two', 3.14:'pi'}
dict2 = {('ten',10):['열',10.0]}
print(dict1['하나'])
print(dict1.get('two'))
print(dict1.get(2))
# 요소삽입 - 대괄호([])안에 key를 넣고 대입연산자(=)를 사용하여 value를 저장
dict1 = {'하나':1, 2:'two', 3.14:'pi'}
dict1 ['파이썬'] = 100
print(dict1)
del dict1[2] # del = key 워드 / clear()
print(dict1)
dict1['하나'] = 1000
print(dict1)
# keys()-key값들 / values()-value값들 / items()-key,value값들
print(dict1.keys())
print(dict1.values)
print(dict1.items())
# 찾기- in = key 워드
print('하나'in dict1)
print('HTML'in dict1)
dict1.clear()
print(dict1)
## 함수 function - 하나의 특정작업을 수행하기위한 프로그램코드집합
## def 함수명 (매개변수-parameter1,...) /
# 실행할 코드1,
# 실행할 코드2
# return 결과값
def hello():
print("hello")
print("-함수시작-")
print("안녕")
hello() # 함수호출
hello() # 함수호출
# 인수 arguments - 함수호출시 내부에서 사용할 데이터 전달 역할.
# 소괄호()안에 쉼표로(,)로 구분
def sum(a,b):
print(a + b)
sum(1,2)
sum(3,4)
# 값을 반환(return)하는 함수
def sum (a, b):
print('함수시작')
print('함수끝')
return a+b
c = sum (1, 2)
print(c)
print(sum(3,4))
def sum (a, b):
print('함수시작')
return a+b
print('함수끝')
c = sum (1, 2)
print(c)
print(sum(3,4))
# 인수 전달시 매개변수 지정
def sub(a,b):
print(a-b)
sub(1,2)
sub(a=1,b=2)
sub(b=1,a=2)
# parameters의 기본값 설정
def total(a,b=5,c=10):
print(a+b+c)
total(1)
total(1,2)
total(1,2,3)
# variable parameters 가변매개변수
# 매개변수명 앞에 별(*)기호를 추가선언
def add(*paras):
print(paras)
total = 0
for para in paras:
total += para
return total
print(add(10))
print(add(10,100))
print(add(10,100,1000))
# 매개변수로 딕서너리 시용시 명앞에 별(**)기호를 추가선언
def print_map(**dicts):
for item in dicts.items():
print(item)
print_map(하나=1)
print_map(one=1,two=2)
print_map(하나=1,둘=2,셋=3)
# 여러개의 결과값 반환하기
def arith(a,b):
add = a+b
sub = a-b
return add,sub
i,j = arith (10,1)
print(i)
print(j)
# lambda - 간단한 함수의 선언과 호출을 하나의 식으로
def add(a,b):
return a+b
print(add(1,2))
print((lambda a,b:a+b)(1,2))
## variable scope 변수의 유효범위
# 지역변수 local variable
def func():
local_var = "local variable"
print(local_var)
func()
# print( locar_variable)
# 전역변수 global variable
def func():
global global_var
local_var = "local variable"
print(local_var)
print(global_var)
global_var = 'global variable'
func()
print(global_var)
def func():
var = '지역변수'
print(var)
var = '전역변수'
print(var)
func()
print(var)
# 자료형 변환
# 함수
def order():
print('주문하실 음료를 알려주세요')
drink = input()
print(drink,'주문하셨습니다.')
order()
print("XX행 열차가 들어오고 있습니다.")
station = "광주행"
print(station + "열차가 들어오고 있습니다.")
#함수-이름(인자값,인자값,인자갑, ...) ---> 리턴 값
print('hi','hellow')
name = input ('이름을 입력하세요?')
print('안녕하세요?',name)
# class와 object / objec-oriented programming
# class member / attribute-속성(변수)와 method-메소드(함수)
class Dog:
name = '삼식이'
age = 3
breed = '골든 리트리버'
def bark(self):
print(self.name +'가 멍멍하고 짖는다.')
# instance란 class를 기반으로한 object-객체
# 소괄호()로 생성, 닷(.)연산지를 사용하여 호출
my_dog = Dog()
print(my_dog.breed)
my_dog.bark()
# 초기화 메소드 (initialize method) / __init__
class Dog:
def __init__(self,name):
self.name = name
def bark(self):
print(self.name + "가 멍멍하고 짖는다.")
# class variable - 모든 인스턴스가 값을 공유
# instance variable - __init__()내에 선언된 변수
class Dog:
sound = '멍멍'
def __init__(self,name):
self.name = name
def bark(self):
print(self.name + "가 멍멍하고 짖는다.")
my_dog = Dog ("삼식이")
your_dog = Dog ("콩이")
print(my_dog.sound)
print(my_dog.name)
print(your_dog.sound)
print(your_dog.name)
# inheritance(상속) - parent(base) class / child(derived) crass
# 소괄호(())사용
class Bird:
def __init__(self):
self.flying = True
def birdsong(self):
print('새소리')
class Sparrow(Bird):
def birdsonf(self):
print('짹짹')
my_pet = Sparrow()
print(my_pet.flying)
my_pet.birdsong()
# method overriding
class Bird:
def __init__(self):
self.flying = True
def birdsong(self):
print('새소리')
class Sparrow(Bird):
def birdsong(self):
print('짹짹')
class Chicken(Bird):
def __init__(self):
self.flying = False
my_sparrow = Sparrow()
my_chicken = Chicken()
my_sparrow.birdsong()
my_chicken.birdsong()
# access control -접근제어
# public = (_)포함되지않음/
# private = (__)두개,접두사/
# protected = (_)한개,접두사
## 입출력및 예외처리
# module - 모듈 / import문 / 코드맨앞유리 / 닷(.)연산자
# import 모듈명/ from 모듈명 import * / from 모듈명 import 함수명또는 클래스명
import math
print(math.pi)
print(math.pow(2,2)) # pow함수 = 2^N
from math import *
print(pi)
print(pow(2,2))
e = '내가 정의한 변수e'
print(e)
from math import * # e - 오일러의 수
print(e)
print(pi)
e = '내가 정의한 변수e'
from math import pi
print(e)
print(pi)
# 파일 입출력-input(), print() / open(), close()
# r(read mode, 기본값)/w(write mode)/a(append mode)
# t(text mode,기본값)/b(binary mode)
# x(exclusive mode)/+(update mode)
# 파일내용 읽기 - 1.read()/readline()/readlines()
# 파일내용추가 - write()
# 자동으로 파일 닫기 - with문
# exception handling - 예외처리
# try문~finally절, excet문~else문
# 예외 발생시키기 - raise 키워드
class Bird:
def birdsong(self):
raise NotImplementedError
class Chicken(Bird):
def birdsong(self):
print("짹짹")
my_chicken = Chicken()
my_chicken.birdsong()
|
from playsound import playsound
import os
import random
def speak_number(number):
audio_path = "audio-numbers/" + str(number) + '.wav'
playsound(audio_path)
def play():
os.system('clear')
picked_numbers = []
numbers = [i for i in range(1, 91)]
random.shuffle(numbers)
while len(picked_numbers) < 90:
rand_num = numbers.pop()
if rand_num not in numbers:
picked_numbers.append(rand_num)
print("Your Number is:", rand_num)
speak_number(rand_num)
input()
print("""
Welcome!! Let's play Thambola. Hit 'Enter' to start.
""")
input()
play()
|
from Compiler.error_handler.runtime_error import RunTimeError
class Number:
def __init__(self, number_value):
self.number_value = number_value
self.set_position()
self.pos_start = None
self.pos_end = None
def set_position(self, pos_start=None, pos_end=None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def add_to(self, other):
if isinstance(other, Number):
return Number(number_value=self.number_value + other.number_value), None
def sub_by(self, other):
if isinstance(other, Number):
return Number(number_value=self.number_value - other.number_value), None
def mul_to(self, other):
if isinstance(other, Number):
return Number(number_value=self.number_value * other.number_value), None
def div_by(self, other):
if isinstance(other, Number):
if other.number_value == 0:
return None, RunTimeError(pos_start=self.pos_start, pos_end=self.pos_end, error_details='Division by '
'Zero')
return Number(number_value=self.number_value / other.number_value), None
def raised_to(self, other_operand):
if isinstance(other_operand, Number):
return Number(number_value=self.number_value**other_operand.number_value), None
def get_comparison_eq(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value == other_operand.number_value)), None
def get_comparison_ne(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value != other_operand.number_value)), None
def get_comparison_lt(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value < other_operand.number_value)), None
def get_comparison_gt(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value > other_operand.number_value)), None
def get_comparison_lte(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value <= other_operand.number_value)), None
def get_comparison_gte(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value >= other_operand.number_value)), None
def anded_by(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value and other_operand.number_value)), None
def ored_by(self, other_operand):
if isinstance(other_operand, Number):
return Number(int(self.number_value or other_operand.number_value)), None
def notted(self):
return Number(1 if self.number_value == 0 else 0), None
def is_true(self):
return self.number_value != 0
def copy(self):
copy = Number(self.number_value)
copy.set_position(pos_start=self.pos_start, pos_end=self.pos_end)
return copy
def __repr__(self):
return str(self.number_value)
|
from __future__ import annotations
from math import sqrt, sin, cos
class Vector:
"""A Python implementation of a vector class and some of its operations."""
values = None
def __init__(self, *args):
self.values = list(args)
def __str__(self):
"""String representation of a vector is its components surrounded by < and >."""
return f"<{str(self.values)[1:-1]}>"
__repr__ = __str__
def __len__(self):
"""Defines the length of the vector as the number of its components."""
return len(self.values)
def __hash__(self):
"""Defines the hash of the vector as a hash of a tuple with its components."""
return hash(tuple(self))
def __eq__(self, other):
"""Defines vector equality as the equality of all of its components."""
return self.values == other.values
def __setitem__(self, i, value):
"""Sets the i-th vector component to the specified value."""
self.values[i] = value
def __getitem__(self, i):
"""Either returns a new vector when sliced, or the i-th vector component."""
if type(i) == slice:
return Vector(*self.values[i])
else:
return self.values[i]
def __delitem__(self, i):
"""Deletes the i-th component of the vector."""
del self.values[i]
def __neg__(self):
"""Defines vector negation as the negation of all of its components."""
return Vector(*iter(-component for component in self))
def __add__(self, other):
"""Defines vector addition as the addition of each of their components."""
return Vector(*iter(u + v for u, v in zip(self, other)))
__iadd__ = __add__
def __sub__(self, other):
"""Defines vector subtraction as the subtraction of each of its components."""
return Vector(*iter(u - v for u, v in zip(self, other)))
__isub__ = __sub__
def __mul__(self, other):
"""Defines scalar and dot multiplication of a vector."""
if type(other) == int or type(other) == float:
# scalar multiplication
return Vector(*iter(component * other for component in self))
else:
# dot multiplication
return sum(u * v for u, v in zip(self, other))
__rmul__ = __imul__ = __mul__
def __truediv__(self, other):
"""Defines vector division by a scalar."""
return Vector(*iter(component / other for component in self))
def __floordiv__(self, other):
"""Defines floor vector division by a scalar."""
return Vector(*iter(component // other for component in self))
def __matmul__(self, other):
"""Defines cross multiplication of a vector."""
return Vector(
self[1] * other[2] - self[2] * other[1],
self[2] * other[0] - self[0] * other[2],
self[0] * other[1] - self[1] * other[0],
)
__imatmul__ = __matmul__
def __mod__(self, other):
"""Defines vector mod as the mod of its components."""
return Vector(*iter(component % other for component in self))
def magnitude(self):
"""Returns the magnitude of the vector."""
return sqrt(sum(component ** 2 for component in self))
def rotated(self, angle: float, point: Vector = None):
"""Returns this vector rotated by an angle (in radians) around a certain point."""
if point is None:
point = Vector(0, 0)
return self.__rotated(self - point, angle) + point
def __rotated(self, vector: Vector, angle: float):
"""Returns a vector rotated by an angle (in radians)."""
return Vector(
vector[0] * cos(angle) - vector[1] * sin(angle),
vector[0] * sin(angle) + vector[1] * cos(angle),
)
def unit(self):
"""Returns a unit vector with the same direction as this vector."""
return self / self.magnitude()
def abs(self):
"""Returns a vector with absolute values of the components of this vector."""
return Vector(*iter(abs(component) for component in self))
def repeat(self, n):
"""Performs sequence repetition on the vector (n times)."""
return Vector(*self.values * n)
def distance(p1: Vector, p2: Vector):
"""Returns the distance of two points in space (represented as Vectors)."""
return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
|
# Gives Square root of first 10 Even Numbers
sq2 = [n**2 for n in range(10) if not (n %2)]
print("Square of first 10 Even numbers", sq2)
|
from stack import Stack
st2 = Stack()
def revstring(mystr):
liststr = []
# Bread the string into characters
# [liststr.append(mystr[i]) for i in range(0, len(mystr))]
[st2.push(i) for i in liststr]
# for ch in mystr:
# st2.push(ch)
return liststr
revstring("hello")
output = ''
while not st2.isEmpty():
output = output + st2.pop()
print(output)
|
#This program computes the combination of a set of letters.
let = 'ABCD'
pairs = [(let[a], let[b]) for a in range(len(let))
for b in range(a, len(let))]
#Outputs the pairs
print(pairs)
|
import numpy as np
import matplotlib.pyplot as plt
pointsnum=300
learning_rate = 0.01
def labeling(array) :
for i in range(pointsnum) :
if array[i][0] + array[i][1] - 1 > 0 : # (x1 + x2 - 1 > 0)
array[i][2] = 1
else :
array[i][2] = -1
class perceptron :
def __init__(self) :
self.weights = np.random.random_sample((1,2))
self.bias = 0.5
def output(self,input) :
if (self.weights.dot(input)+self.bias)>0 :
return 1
else :
return -1
def update(self,input, error):
self.weights = self.weights + np.matrix.transpose(learning_rate*(error)*input)
self.bias = self.bias + learning_rate*error
#Initializing dataset
randomPoints = np.random.uniform(-5,5,[pointsnum, 3])
labeling(randomPoints)
#End
p = perceptron()
err=0
CounterErrors = 0
i=0
while i<pointsnum :
inputs = np.matrix.transpose(np.copy([[randomPoints[i][0],randomPoints[i][1]]]))
output = p.output(inputs)
plt.scatter(inputs[0], inputs[1], c='r')
if output != randomPoints[i][2] :
err = randomPoints[i][2] - output
CounterErrors+=1
p.update(inputs, err)
i += 1
print("Number Of Errors", CounterErrors)
#Show Data
x = np.linspace(-5, 5, 100)
y = -(p.weights[0][0] / p.weights[0][1]) * x - (p.bias / p.weights[0][1]) # (x1(w1) + x2(w2) - 1(w0) = 0) ==> x1 = -(w1/w2)x2 - (bias/w2)
plt.plot(x, y)
plt.show()
|
# -*- coding: utf-8 -*-
print "你进去了一个漆黑的房间,里面有两扇门,你准备进入第一扇门还是第二扇门呢?"
door = raw_input("> ")
if door == "1":
print "房间里面有个老虎在吃肉,你准备采取以下哪种动作呢?"
print "1. 和它一起分享肉。"
print "2. 对老虎大叫。"
bear = raw_input("> ")
if bear == "1":
print "干的好,老虎把你一起吃了"
elif bear == "2":
print "干的好,老虎把你一起吃了"
else:
print "干的好,老虎被你 %s 吓跑了" % bear
elif door == "2":
print "真倒霉,门后面藏了一个恶鬼,你被吃了。"
else:
print "你站在门口犹豫了半天,被后面的僵尸吃了脑子。" |
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
order = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
def printAnimalAt(number):
print 'The animal at ' + str(number) + " is the " + str(number + 1) + "st animal and is a " + animals[number] + "."
def printTheAnimal(number):
print 'The ' + order[number - 1] + "(" + str(number) + "th) animal is at " + str(number - 1) + " and is a" + animals[number - 1] + "."
printAnimalAt(1)
printTheAnimal(3)
printTheAnimal(1)
printAnimalAt(3)
printTheAnimal(5)
printAnimalAt(2)
printTheAnimal(6)
printAnimalAt(4) |
"""Generate Markov text from text files."""
from random import choice
# import sys
# input_path = sys.argv[1]
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
text = open(file_path).read()
return text
def make_chains(text_string, n):
"""Take input text as string; return dictionary of Markov chains.
A chain will be a key that consists of a tuple of (word1, word2)
and the value would be a list of the word(s) that follow those two
words in the input text.
n is the number of elements in the tuple key.
For example:
>>> chains = make_chains('hi there mary hi there juanita')
Each bigram (except the last) will be a key in chains:
>>> sorted(chains.keys())
[('hi', 'there'), ('mary', 'hi'), ('there', 'mary')]
Each item in chains is a list of all possible following words:
>>> chains[('hi', 'there')]
['mary', 'juanita']
>>> chains[('there','juanita')]
[None]
"""
# {('hi', 'there'):['mary', 'juanita'], ('mary', 'hi'):['there'], ('there', 'mary'):['hi'], ('there', 'juanita'):[None]}
# n_gram: {('hi', 'there', 'mary'):['hi'], ('there', 'mary', 'hi'):['there'], ('mary', 'hi','there'):['juanita'], ('hi','there', 'juanita'):[None]}
chains = {}
clean_string = text_string.split()
for i in range(len(clean_string) - n):
key = []
if i == 0:
for num in range(n):
key.append(clean_string[num])
else:
for num in range(i,n+i):
key.append(clean_string[num])
key = tuple(key)
if len(chains.get(key,[])) == 0:
chains[key] = chains.get(key,[clean_string[i+n]])
else:
chains[key].append(clean_string[i+n])
# need to make the key into a tuple of n elements
key = []
index_list = sorted([(-1)*i for i in range(1,n+1)])
for num in index_list:
key.append(clean_string[num])
key = tuple(key)
chains[key] = [None]
return chains
def make_text(chains,n):
"""Return text from chains."""
words = []
key = choice(list(chains.keys()))
words.extend(key)
value = choice(chains[key])
words.append(value)
key_list = []
index_list = sorted([(-1)*i for i in range(1,n+1)])
for num in index_list:
key_list.append(words[num])
key_tuple = tuple(key_list)
while chains.get(key_tuple,[]) != [None]:
new_key = key_tuple
if len(chains.get((new_key),[])) > 0:
value = choice(chains[new_key])
words.append(value)
key_list = []
for num in index_list:
key_list.append(words[num])
key_tuple = tuple(key_list)
return ' '.join(words)
input_path = 'gettysburg.txt'
input_text = open_and_read_file(input_path)
# Get a Markov chain
chains = make_chains(input_text, 3)
# Produce random text
random_text = make_text(chains,3)
print(random_text)
|
dict1 = {
"april_batch":{
"student":{
"name":"Mike",
"marks":{
"python":80,
"maths":70
}
}
}
}
# Access "Mike"
print(dict1['april_batch']['student']['name'])
# Access 80
print(dict1['april_batch']['student']['marks']['python'])
# change "Mike" to "Your name"
dict1['april_batch']['student']['name']="Onkar"
print(dict1['april_batch']['student']['name'])
print(dict1)
# add ML = 80 and DL = 80 inside marks
dict1['april_batch']['student']['marks']['ML']=80
dict1['april_batch']['student']['marks']['DL']=80
print(dict1) |
Airthmatic operations using functions
num1=int(input("Enter first number: "))
num2=int(input("Enter Second number: "))
def add(num1,num2):
return num1+num2
def sub(num1,num2):
return num1-num2
def mul(num1,num2):
return num1*num2
def div(num1,num2):
return num1/num2
print(""" Enter your choice from below
Press 1 for Addition
Press 2 for Subtraction
Press 3 for Multiplication
Press 4 for Division""")
choice=int(input())
print(choice)
if choice not in range(1,5):
print("Enter Operation number correctly")
else:
if choice==1:
print(f'Addition of {num1} and {num2} is {add(num1,num2)}')
if choice==2:
print(f'Subtraction of {num1} and {num2} is {sub(num1,num2)}')
if choice==3:
print(f'Multiplication of {num1} and {num2} is {mul(num1,num2)}')
if choice==4:
print(f'Division of {num1} and {num2} is {div(num1,num2)}') |
"""Пользователь вводит номер буквы в алфавите. Определить, какая это буква."""
letter = input('input eng letter: ').lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
if letter in alphabet:
position = alphabet.index(letter)+1
print(f'position of your letter "{letter}" is: {position}')
else:
print('try again, enter a letter from eng alphabet') |
'''
Euler6.py - a program to solve euler problem 6 - sum of squares
Nate Weeks October 2018
'''
# squaresum = 0
# sum = 0
# for i in range(101):
# squaresum += i ** 2
# sum += i
#
# answer = (sum ** 2) - squaresum
# print(answer)
class Euler6(object):
''' object takes a max number - includes methods to find
square of the sums and the sum of the sqaures'''
def __init__(self, max):
self.max = max
def squaresum(self):
''' method to find the square of the sums under max'''
result = 0
for num in range(self.max + 1):
result += num ** 2
return result
def sumsquared(self):
''' method to find the sum of the squares under max '''
result = 0
for num in range(self.max + 1):
result += num
result = result ** 2
return result
if __name__ == "__main__":
thing = Euler6(100)
sumsquared = thing.sumsquared()
squaresum = thing.squaresum()
answer = sumsquared - squaresum
print(answer)
|
n=input("Enter a number")
for i in n:
if (int(i)%2)!=0:
print(i,"\t")
|
def prod(iterable):
result = 1
for n in iterable:
result *= n
return result
parser = argparse.ArgumentParser(description='Multiply some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='*',
help='an integer for the accumulator')
parser.add_argument('--product', dest='accumulate', action='store_const',
const=prod, default=max,
help='Multiply the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers)) |
# Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# use a with statement to open the text, and save it to a variable
with open('ciphertext.txt', 'r') as f:
words = f.read()
# bad characters do not need to get deciphered
bad_chars = ('\n',' ','!','"','(',')',',','.','1',':',';','?','-')
#initiate a blank dictionary for counting characters
char_count={}
#loop through each word
for i in words:
# if the word is being counted
if i in char_count:
# add 1
char_count[i] += 1
# if the word isnt in the count yet
else:
# initialize it to 1
char_count[i] = 1
# for each character in the bad chars
for i in bad_chars:
# take that character out of char_count
char_count.pop(i)
#now we create a sorted version of the character count.
# this makes our encoded character counter sort the maximum values to the beginning of the dictionary
char_count = dict(sorted(char_count.items(),key = lambda x: x[1], reverse=True))
# take out the blanks
char_count.pop("'")
#now to match the encoded frequencies with the proper ones
#same with statement for the readme
with open('README.md', 'r') as f:
readme = f.readlines()
#initialize a list for frequencies
char_frequency = []
for i in readme:
if i[:2] == '| ':
char_frequency.append(i[1:6].strip())
char_frequency.pop(0)
for a,b in zip(char_count, char_frequency):
char_count[a] = b
for i in words:
try:
if i in bad_chars:
print(i,end='')
else:
print(char_count[i],end='')
except KeyError:
continue |
#!/usr/bin/env python
import argparse
import textwrap
def get_args():
'''This function parses and return arguments passed in'''
parser = argparse.ArgumentParser(
prog='filterFastaByName',
description='Filter fasta file by sequence name')
parser.add_argument('fasta', help="path to fasta input file")
parser.add_argument('feature_names', help="feature names to keep")
parser.add_argument(
'-o',
dest="outfile",
default="your_output.fa",
help="Output fasta file")
args = parser.parse_args()
infile = args.fasta
names = args.feature_names
outfile = args.outfile
return(infile, names, outfile)
def read_fasta(fasta):
"""
READS A FASTA FILE INTO A DICT
INPUT:
fasta(string) path to fasta file
OUTPUT:
all_sequences(dict) sequences in a dictionary
"""
all_sequences = {}
with open(INFILE, "r") as f:
for line in f:
line = line.rstrip()
if line.startswith(">"):
seqname = line[1:len(line) + 1]
all_sequences[seqname] = ""
else:
all_sequences[seqname] += line
return(all_sequences)
def filter_fasta_dict_by_name(fasta_dict, seqnames):
"""
FILTER A FASTA DICT BY SEQUENCE NAME
INPUT:
fasta_dict(dict) dictionary of a fasta file
seqnames(list) sequences names to keep
OUTPUT:
filtered_fasta(dict) filtered dictionary of a fasta file
"""
filtered_fasta = {}
for akey in fasta_dict.keys():
short_name = akey.split()[0]
if short_name in seqnames:
filtered_fasta[akey] = fasta_dict[akey]
return(filtered_fasta)
def write_fasta(fasta_dict, outfile):
"""
WRITE A FASTA DICT TO FILE
INPUT:
fasta_dict(dict) dictionary of a fasta file
outfile(str) name of output file
"""
with open(outfile, "w") as f:
for akey in fasta_dict.keys():
f.write(">" + akey + "\n" +
textwrap.fill(fasta_dict[akey], 80) + "\n")
if __name__ == "__main__":
INFILE, NAMES, OUTFILE = get_args()
seqnames = []
with open(NAMES, "r") as f:
for line in f:
line = line.rstrip()
seqnames.append(line)
myfasta = read_fasta(INFILE)
filtered_fasta = filter_fasta_dict_by_name(myfasta, seqnames)
write_fasta(filtered_fasta, OUTFILE)
print("--------------------\nFiltered fasta written to", OUTFILE)
|
import random
import string
class Application:
users = {}
def register(self, user):
"""
if user doesnot exist already, it creates a new use
:param user:
:return:
"""
if user.email not in self.users.keys():
self.users[user.email] = user
return True
return False
def log_in(self, email, password):
"""
checks if the password entered matches the password entered
:param email:
:param password:
:return:
"""
if email in self.users:
return self.users[email].password == password
return False
def current_user(self, email):
if email in self.users:
return self.users[email]
return False
def random_id(self):
"""
Generates a random key/Id
:return:
"""
return ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(4)])
|
#!/usr/bin/python3
import pickle
import base64
CANVSIZE = 16
canvas = [[" " for i in range(CANVSIZE)] for j in range(CANVSIZE)]
def print_canvas(canvas):
print("#" * (CANVSIZE + 2))
for line in canvas:
print("#", end="")
for char in line:
print(char, end="")
print("#")
print("#" * (CANVSIZE + 2))
def print_help():
print("Listing commands...")
print("display Display the canvas")
print("clearall Clear the canvas")
print("set [row] [col] Set a particular pixel")
print("clear [row] [col] Clear a particular pixel")
print("export Export the canvas state")
print("import [canvas] Import a previous canvas")
print("exit Quit the program")
def change_pixel(command):
row = int(command[1])
col = int(command[2])
if row < 0 or row >= CANVSIZE or col < 0 or col >= CANVSIZE:
print("Index out of range!")
return
canvas[row][col] = "0" if command[0] == "set" else " "
print_canvas(canvas)
# PROGRAM STARTS BELOW
print("Welcome to the Paint Program!")
print("Paint us a new poster for the Jellyspotters 2021 convention. Make Kevin proud.")
print("Type 'help' for help.")
while True:
userinput = input("> ")
split = userinput.split(" ")
cmd = split[0]
if cmd == "?" or cmd == "help":
print_help()
elif cmd == "":
continue
elif cmd == "display":
print_canvas(canvas)
elif cmd == "clearall":
canvas = [[" " for i in range(CANVSIZE)] for j in range(CANVSIZE)]
elif cmd == "set" or cmd == "clear":
change_pixel(split)
elif cmd == "export":
out = base64.b64encode(pickle.dumps(canvas)).decode("ascii")
print("Exported canvas string:")
print(out)
elif cmd == "import":
if len(split) < 2:
print("Expected argument (canvas export string). Import failed.")
continue
print("Importing...")
imp = pickle.loads(base64.b64decode(split[1]))
print("Done!")
canvas = imp
print_canvas(canvas)
pass
elif cmd == "exit" or cmd == "quit":
break
else:
print(f"Unrecognized command '{cmd}'.")
print("Thank you for using the Paint Program! Goodbye.") |
import random as rand
import abc
class LinkedList :
# Initializes an empty linked list.
def __init__(self):
self.list = [] # beginning of linked list
# Returns the number of items in this linked list.
def size(self):
return len(self.list)
# Returns true if this linked list is empty.
def isEmpty(self):
return self.size() == 0
# Returns the first item added to this linked list
def check(self):
if self.isEmpty():
raise ValueError("linked list underflow: ")
return self.list[0]
#Removes and returns the first item in the linked list
def peek(self):
if self.isEmpty():
raise ValueError("linked list underflow")
return self.list.pop(0)
def append(self, item):
self.list.append(item)
def prepend(self, item):
self.list.insert(0, item)
def accept(self, visitor):
visitor.visit(self)
class Queue(LinkedList):
# Initializes an empty queue.
def __init__(self, max_size, *args, **kwargs):
self.max_size = max_size
super(Queue, self).__init__(*args, **kwargs)
def isFull(self):
return self.size() == self.max_size
# Adds the item to this queue.
def enqueue(self, item):
if self.isFull():
raise ValueError("Queue overflow")
self.append(item)
#Removes and returns the item on this queue that was least recently added.
def dequeue(self):
try:
return self.peek()
except ValueError:
raise ValueError("Queue underflow")
class Stack(LinkedList):
# Initializes an empty stack.
def __init__(self, max_size, *args, **kwargs):
self.max_size = max_size
super(Stack, self).__init__(*args, **kwargs)
# Returns true if this stack is full.
def isFull(self):
return self.size() == self.max_size
# Adds the item to this stack.
def push(self, item):
if self.isFull():
raise ValueError("Stack overflow")
self.prepend(item)
# Removes and returns the item most recently added to this stack.
def pop(self):
try:
return self.peek()
except ValueError:
raise ValueError("Stack underflow")
class AutoAdaptiveStack(Stack):
def __init__(self, max_trials, size_increment, waitingQueueSize, *args, **kwargs):
self.max_trials = max_trials
self.size_increment = size_increment
self.trials = 0
self.waitingQueue = Queue(waitingQueueSize)
super(AutoAdaptiveStack, self).__init__(*args, **kwargs)
def push(self, item):
try:
super(AutoAdaptiveStack, self).push(item)
except:
try:
self.waitingQueue.enqueue(item)
except:
print("There is no free space actually :( try later")
self.trials += 1
if self.trials == self.max_trials:
self.max_size += self.size_increment
self.trials = 0
while not self.isFull() and not self.waitingQueue.isEmpty():
self.push(self.waitingQueue.dequeue())
#redefinition de pop
def pop(self):
elem = super(AutoAdaptiveStack, self).pop()
if not self.waitingQueue.isEmpty():
self.push(self.waitingQueue.dequeue())
return elem
class AutoAdaptiveQueue(Queue):
def __init__(self, max_trials, size_increment, waitingQueueSize, *args, **kwargs):
self.max_trials = max_trials
self.size_increment = size_increment
self.trials = 0
self.waitingQueue = Queue(waitingQueueSize)
super(AutoAdaptiveQueue, self).__init__(*args, **kwargs)
def enqueue(self, item):
try:
super(AutoAdaptiveQueue, self).enqueue(item)
except ValueError:
try:
self.waitingQueue.enqueue(item)
except:
print("There is no free space actually :( try later")
self.trials += 1
if self.trials == self.max_trials:
self.max_size += self.size_increment
self.trials = 0
while not self.isFull() and not self.waitingQueue.isEmpty():
self.enqueue(self.waitingQueue.dequeue())
#redefinition de dequeue
def dequeue(self):
ret = super(AutoAdaptiveQueue, self).dequeue()
if not self.waitingQueue.isEmpty():
self.enqueue(self.waitingQueue.dequeue())
return ret
class Printer(object, metaclass=abc.ABCMeta):
def __init__(self, name):
self.name = name
def visit(self, list_obj):
if isinstance(list_obj, Stack):
display_message = "\n-------\n"
for elem in list_obj.list:
display_message += ' '+str(elem)+' '
display_message += "\n-------\n"
elif isinstance(list_obj, Queue):
display_message = "\n|"
for elem in list_obj.list:
display_message += str(elem) + "|"
display_message += "\n"
else:
display_message = "\n("
for elem in list_obj.list:
display_message += str(elem)
if elem != list_obj.list[len(list_obj.list)-1]:
display_message += ","
display_message += ")\n"
self.log(display_message)
@abc.abstractmethod
def log(self, display_message):
raise NotImplementedError('child objects must define log to create a printer')
class ScreenPrinter(Printer):
def __init__(self, *args, **kwargs):
super(ScreenPrinter, self).__init__(*args, **kwargs)
def log(self, display_message):
print(self.name)
print(display_message)
class FilePrinter(Printer):
def __init__(self, file_path, *args, **kwargs):
self.file_path = file_path
super(FilePrinter, self).__init__(*args, **kwargs)
def log(self, display_message):
with open(self.file_path, 'a') as f:
f.write(self.name)
f.write(display_message)
class Calculator:
@staticmethod
def union(first_list, second_list):
if isinstance(first_list,Queue) and isinstance(second_list,Queue):
merged_queue = Queue(max_size=first_list.max_size+second_list.max_size)
for elem in first_list.list:
merged_queue.enqueue(elem)
for elem in second_list.list:
merged_queue.enqueue(elem)
return merged_queue
elif isinstance(first_list,Stack) and isinstance(second_list,Stack):
merged_stack = Stack(max_size=first_list.max_size+second_list.max_size)
for elem in reversed(first_list.list):
merged_stack.push(elem)
for elem in reversed(second_list.list):
merged_stack.push(elem)
return merged_stack
elif isinstance(first_list,LinkedList) and isinstance(second_list,LinkedList):
list1 = first_list.list
list2 = second_list.list
first_list.list = first_list.list.copy()
second_list.list = second_list.list.copy()
merged_list = LinkedList()
while not first_list.isEmpty() and not second_list.isEmpty():
if(rand.uniform(0,1) < 0.5):
merged_list.append(first_list.peek())
else:
merged_list.append(second_list.peek())
while not first_list.isEmpty():
merged_list.append(first_list.peek())
while not second_list.isEmpty():
merged_list.append(second_list.peek())
first_list.list = list1
second_list.list = list2
return merged_list
else:
raise ValueError('The types of both lists are different') |
class Ingredient(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost
def get_name(self):
return self.name
def get_weight(self):
return self.weight
def get_cost(self):
return self.cost
class Pizza(object):
def __init__(self, name):
self.name = name
ingredient = []
def add_ingredient(self, ingredient):
self.ingredient.append(ingredient)
def get_name(self):
return self.name
def get_weight(self):
weight = 0
for i in self.ingredient:
weight += i.get_weight()
return weight / 1000
def get_cost(self):
cost = 0
for i in self.ingredient:
cost += i.get_cost()
return cost
class Order(object):
pizza = list()
def add_pizza(self, pizza):
self.pizza.append(pizza)
def get_cost(self):
cost = 0
for i in self.pizza:
cost += i.get_cost()
return cost
def print_receipt(self):
for i in self.pizza:
print(f'{i.get_name()} ({"%.3f" % i.get_weight()}кг) - {"%.2f" % i.get_cost()}руб') |
import random
from random import randrange
print("Give me two numbers, a minimum and a maximum")
a = int(input("Select minimum. "))
b = int(input("Select maximum. "))
c = 0
while c < 10:
print(randrange(a, b))
c += 1 |
# problem 2. counting words
'''
Description
The method count() returns the number of occurrences of substring sub in
the range [start, end]. Optional arguments start and end are interpreted
as in slice notation.
Syntax
str.count(sub, start= 0,end=len(string))
Parameters
sub -- This is the substring to be searched.
start -- Search starts from this index. First character starts from 0 index.
By default search starts from 0 index.
end -- Search ends from this index. First character starts from 0 index.
By default search ends at the last index.
Return Value
Centered in a string of length width.
'''
name = raw_input('what is the input string? ')
name_len = len(name)
if(name_len == 0):
print('input something plz')
else:
print(name+' has '+str(name_len)+' characters.')
|
# 단어 정렬
n = int(input())
# 1. 단어를 입력받음
words = []
for i in range(n):
words.append(input())
# 2. 중복되는 단어를 삭제
# 중복을 허용하지 않는 set
set_words = list(set(words))
# 3. 길이와 단어 쌍으로 묶어서 저장
sort_words = []
for i in set_words:
sort_words.append((len(i), i))
# 4. 단어 정렬
result = sorted(sort_words)
for len_word, word in result:
print(word)
|
def swap(input_list,a,b):
temp = input_list[a]
input_list[a] = input_list[b]
input_list[b] = temp
def permutation_looper(numpad_list,start,end):
if start == end:
permutation_output.append(numpad_list.copy())
else:
for i in range(start,len(numpad_list)):
swap(numpad_list,start,i)
permutation_looper(numpad_list,start+1,end)
swap(numpad_list,i,start)
numpad_list = [1,2,3]
n = len(numpad_list)
permutation_output = []
permutation_looper(numpad_list,0,n-1)
print(permutation_output)
|
import random
def guessing_game():
count = 0
while True:
count += 1
if count > 5:
break
try:
n = int(input('Guess a number between 1 and 10: '))
r = random.randint(1, 10)
if n > 0 and n < 11:
if r == n:
print(f'Congratulations! You are right. The correct number was {r}')
break
else:
print(f"Try again the correct number was {r}. Tries left {5-count}")
else:
print('Please enter the number between 1 and 10')
except ValueError:
print('Gibberish? Please enter the number between 1 and 10')
continue
return 0
guessing_game()
|
#Name: Shane Bastien
#Email: sachabastien@gmail.com
#Date: October 20, 2019
#ask the user to specify the input file,
#ask the user to specify the output file,
#make a plot of the fraction of the total population that are children over time from the data in input file, and
#store the plot in the output file the user specified.
import pandas as pd
import matplotlib.pyplot as plt
homeless = pd.read_csv(input("please enter name of file:"))
outfile= input("please enter name of output file:")
homeless["Fraction Children"]= homeless["Total Children in Shelter"]/homeless["Total Individuals in Shelter"]
homeless.plot(x= "Date of Census", y= "Fraction Children")
plt.gca().invert_xaxis()
plt.show()
fig= plt.gcf()
fig.savefig(outfile)
|
from Tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side = BOTTOM)
def button(buttonText, fgcolour,bgcolour):
button1 = Button(topFrame, text= buttonText, fg = fgcolour, bg = bgcolour)
button1.pack(side = LEFT)
def label(textOne):
label1 = Label(topFrame, text = textOne)
label1.pack()
button('Hello', 'white','black')
button('World' ,'blue', 'orange')
button('!', 'black', 'cyan')
label('dhujdhjsdj')
root = mainloop()
|
def is_palindrome(text):
end = len(text)
for i in range(0, int(end/2)):
if not text[i] == text[end-1-i]:
return False
return True
def binary_str(num):
exp = 0
while 2**exp <= num:
exp = exp + 1
result = ""
while exp > 0:
exp = exp - 1
mult = 2**exp
if num - mult >= 0:
result += "1"
num = num - mult
else:
result += "0"
return result
cumulative = 0
for i in range(0,999999):
if is_palindrome(str(i)) is True and is_palindrome(binary_str(i)) is True:
cumulative = cumulative + i
print(i)
print(cumulative)
|
import math
def list_of_primes(max_prime):
if max_prime < 2:
return []
primes = [2]
for i in range(3,max_prime+1):
is_prime = True
square = math.sqrt(i)
for prime in primes:
if i % prime == 0:
is_prime = False
break
elif prime > square:
break
if is_prime is True:
primes.append(i)
return primes
def is_prime(num, prime_list):
square = math.sqrt(num)
for prime in primes:
if num % prime ==0:
return False
elif prime > square:
return True
return True
primes = list_of_primes(1000000)
print("created list")
def circular_primes(num, prime_list):
num = str(num)
primes = []
for i in range(0,len(num)):
if not int(num) in prime_list:
return []
primes.append(int(num))
num = num[1:] + num[0]
return primes
circulars = []
for prime in primes:
if prime in circulars:
pass
else:
circulars = circulars + circular_primes(prime, primes)
print(list(set(circulars)))
print(len(list(set(circulars))))
|
def contains_same_digits(num1, num2):
str1 = str(num1)
str2 = str(num2)
if not len(str1) == len(str2):
return False
for i in range(0, len(str1)):
if not str1.count(str1[i]) == str2.count(str1[i]):
return False
return True
not_found = True
num = 10
while not_found is True:
correct = True
mult = 2
while contains_same_digits(num, num*mult) is True:
print(num*mult)
mult = mult + 1
if mult > 6:
print(num)
break
num += 1
print(num)
print(contains_same_digits(1,2)) |
def numDivisors(x):
numDiv = 1;
i = 2;
while i < x**(1/2.0):
if x%i==0:
numDiv+=2;
i+=1;
return numDiv;
sum = 0;
num = 0;
bool = True;
max_divisors = 0;
while bool:
sum = sum + num;
num+=1;
z = numDivisors(sum);
if z > max_divisors:
max_divisors = z;
print(z);
if max_divisors>500:
bool = False;
print(sum);
|
# -*- coding: utf-8 -*-
"""
iter_fibo.py
Created on Sat Apr 23 11:19:17 2019
@author: madhu
"""
#%%
class TestIterator:
value = 0
def __next__(self):
self.value += 1
if self.value > 10: raise StopIteration
return self.value
def __iter__(self):
return self
print('-'*30)
ti = TestIterator()
print(list(ti))
print('-'*30)
#%%
#%%
class Fibs:
def __init__(self):
self.a = 0
self.b = 1
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
def __iter__(self):
return self
print('-'*30)
fibs = Fibs()
for f in fibs:
if f > 1000:
print(f)
break
print('-'*30)
#%%
#%%
it = iter([1, 2, 3])
print('next(it):')
print(next(it))
print('-'*30)
print(next(it))
print('-'*30)
print(next(it))
print('-'*30)
print('Alas:',next(it))
print('-'*30)
print('-'*30)
#%%
|
# https://www.hackerrank.com/challenges/string-validators/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
if __name__ == '__main__':
s = input()
halnum =[ 1 if x.isalnum()==True else 0 for x in s ]
print('True' if sum(halnum)>=1 else 'False')
halpha =[ 1 if x.isalpha()==True else 0 for x in s ]
print('True' if sum(halpha)>=1 else 'False')
hdigit =[ 1 if x.isdigit()==True else 0 for x in s ]
print('True' if sum(hdigit)>=1 else 'False')
hlower =[ 1 if x.islower()==True else 0 for x in s ]
print('True' if sum(hlower)>=1 else 'False')
hupper =[ 1 if x.isupper()==True else 0 for x in s ]
print('True' if sum(hupper)>=1 else 'False') |
# link https://www.hackerrank.com/challenges/nested-list/problem?h_r=next-challenge&h_v=zen
# Nested List
'''
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
'''
if __name__ == '__main__':
score = []
for _ in range(0,int(input())):
score.append([input(), float(input())])
second_low = sorted(list(set([result for name, result in score])))[1]
#set to merge repeated scores. #make it a list. #sort it in ascending order. #second lowest is in index position [1].
print('\n'.join([n for n,r in sorted(score) if r == second_low]))
''' old
if __name__ == '__main__':
n = int(input())
low=0
ns=[]
score_card = [[input(), float(input())] for x in range(n)]
low = min(score_card, key=lambda x:x[1]) #sort list by (list, key=lambda // sort by nested list's position[1]# 2nd position ==value
ns=[score_card.remove(n,r) for n,r in score_card if r==low]
print(score_card)
print('\n'.join([name for name,result in sorted(score_card) if result==min(score_card, key=lambda y:y[1])[1]])) #'\n'--> print result in new Line
'''
'''
old code
score_card=[]
for _ in range(int(input())):
name = input()
score = float(input())
score_card.append([name,score])
sorted(score_card)
scoremin= 0
for i in range(len(score_card)):
if score_card[i-1][1] < score_card[i][1]:
scoremin=score_card[i-1][1]
print(scoremin)
''' |
# -*- coding: utf-8 -*
import urllib
import urllib2
import requests
class DownloadFile:
def __init__(self):
self.downloadPath="F:\\Development\\DownloadsTest\\20171119"
def downloadOneFileWithUrlLib(self,url,fileName):
urllib.urlretrieve(url, self.downloadPath + fileName)
def downloadOneFileWithRequest(self,url,fileName):
r = requests.get(url)
with open( self.downloadPath + fileName, "wb") as code:
code.write(r.content)
def downloadOneFileWithUrlLib2(self,url,fileName):
f = urllib2.urlopen(url)
data = f.read()
with open( self.downloadPath + fileName, "wb") as code:
code.write(data)
if __name__ == "__main__":
downloadFile = DownloadFile()
url="http://c.siimg.com/u/20171119/222152291.jpg"
path="222152291.jpg"
downloadFile.downloadOneFileWithRequest(url,path) |
def count_consonants(str):
consonants = "bcdfghjklmnqrstvwxz"
count = 0
for iter in str:
for item in consonants:
if iter == item:
count = count + 1
return count
def main():
print(count_consonants("choise"))
if __name__ == '__main__':
main() |
def sum_of_min_and_max(arr):
min = arr[0]
max = arr[0]
for item in arr:
if item < min:
min = item
if item > max:
max = item
sum = min + max
return sum
def main():
print(sum_of_min_and_max([1,2,3]))
print(sum_of_min_and_max([1,2,3,4,5,6,8,9]))
print(sum_of_min_and_max([-10,5,10,100]))
print(sum_of_min_and_max([1]))
if __name__ == '__main__':
main()
|
def is_decreasing(seq):
iter = 0
while iter <= len(seq) - 2:
if seq[iter] <= seq[iter + 1]:
return False
else:
iter = iter + 1
return True
def main():
print(is_decreasing([5,4,3,2,1]))
print(is_decreasing([1,2,3]))
print(is_decreasing([100, 50, 20]))
print(is_decreasing([1,1,1,1]))
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.