text stringlengths 37 1.41M |
|---|
#Opeartors
# perform arthmetic operations on two variables
n1 = 30
n2= 20
sum = n1 + n2
print("sum = ", sum)
sub = n1 - n2
print("sub = ", sub)
mul = n1 * n2
print("mul = ", mul)
div1 = n1 / n2
print("div1 = ", div1)
div2 = n1 // n2
print("div2 = ", div2)
rem = n1 % n2
print("rem = ", rem)
z = f
print(z,f)
print(z is f) # identity operator ; both are points to same obj
a = 25
b = 10
e = 10 & 12 #prints8 compares binaries 1010 1100 -->1000 = 8 bits wise comparision
e = 10 | 12 # 1010 1100 -> 1110 prints 14
e = 10 >> 2 # converts 1010 to 10
print(e) # 2
e = 10 << 2 # converts 1010 to 101000
print(e) #40
# Examples of Bitwise operators
a = 10
b = 4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
"""
assignment:
---------------
sum of 30 and 20 is 50
sub of 30 and 20 is 10
mul of 30 and 20 is 600
div1 of 30 and 20 is 1.5
div2 of 30 and 20 is 1
rem of 30 and 20 is 10
"""
|
"""
take bankname(string) as input ,
if bankname value is "sbi" o/p => ROI is 10%
if bankname value is "icici" o/p => ROI is 11%
if bankname value is "hdfc" o/p => ROI is 12%
if bankname value is "citi" o/p => ROI is 13%
other than this o/p => invalid bank
"""
#approach1
x=input("enter value")
if x=="ICCI":
print("icci rate of interest 10%")
if x=="hdfc":
print("hdfc interest rate 13%")
if x=="city":
print("City bank rate is 12 %")
if x=="sbi":
print("sbi rate if interest is 12.6 %")
#approach2
x=input("enter bank name")
if(x=="hdfc"):
print("interest rate is 10%")
elif(x=="sbi"):
print("interest rate is 12%")
elif (x == "icic"):
print("interest rate is 15%")
elif (x == "yes"):
print("interest rate is 19%")
else:
print("bank name is invalid")
|
"""
take id ,age , usertype as input
perform validation
id should be positive:
age should be greater than 18:
usertype should be "admin":
if id,age,usertype is valid ==> print valid data
if any data found to be invalid ==> print invalid data
Req:
can we write multiple conditions in one if statement?
Yes
- and
if multiple conditions are joined using 'and' then the if block is executed only if all the conditions are satisfied
- or
if multiple conditions are joined using 'OR' then the if block is executed if atleast one condition is satisfied
"""
#take input for id , age , usertype
id = int(input("enter id: "))
age= int(input("enter age: "))
usertype = input("enter usertype: ")
#approach1
if id>0 and age>=18 and usertype=="admin":
print("Valid data")
else:
print("Invalid data")
#approach2
if id<0 or age<18 or usertype!="admin":
print("Invalid data")
else:
print("Valid data")
|
n1 = int(input("enter num1 "))
n2 = int(input("enter num2 "))
n3 = int(input("enter num3 "))
if n1 > n2:
#big is between n1 and n3
if n1 > n3:
print("Big = ", n1)
else:
print("Big = ", n3)
else:
# big is between n2 and n3
if n2 > n3:
print("Big = ", n2)
else:
print("Big = ", n3) |
# take numbers as input and perform sum , if the input is negative then stop the program ad print final sum
sum = 0
num = 0
while (num >= 0):
sum = sum + num
num = int(input("enter number"))
print(" sum = ", sum) |
"""
Req:
- Create person class with id, name , age as instance variables.
- id, name , age are private
- provide setters and getters
- create object and set the data and print the data
"""
class PersonInfo:
def __init__(self, pId, pName, pAge):
self.__id = pId
self.__name = pName
self.__age = pAge
# here __id , __name , __name are private [cannot access outside class]
def show(self):
print(self.__id,self.__name,self.__age)
#provide the setter and getter methods
# 3 setters and 3 getters
# for changing or accesisng use the methods
def getName(self):
return self.__name
def setName(self, name):
self.__name = name
def getId(self):
return self.__id
def setId(self, id):
self.__id = id
def getAge(self):
return self.__age
def setAge(self, age):
self.__age = age
p = PersonInfo(1200,"USER2",23)
#change id
p.setId(1300)
print(p.getId())
#change name
p.setName("Raj")
print(p.getName())
#change age
p.setAge(78)
print(p.getAge())
print("**************")
p.show() |
"""
can a developer create exception?
YES
STEPS:
-----------------------
1.Create exception obj
2.raise the exception
- raise the exception on conditional basis
- raise exception logic should be written inside the conditional blocks.
#syntax for Create exception obj:
ex1 = ValueError("invalid data")
ex2 = IndexError("invalid index value")
ex3 = ArithmeticError("invalid arthmetic ")
#syntax for raise exception
raise ex1
raise ex2
raise ex3
Req: Perform div of two nums
if the second num is zero then throw exception
"""
def div(n1, n2):
if n2 == 0:
raise ArithmeticError("NUM2 cannot be zero")
print(n1 / n2)
div(6,2)
div(6, 0)
div(6, 3)
print("end")
|
"""
1.open existing excel
2.Delete sheet
3.save file
How to create workBook obj for existing excel?
workbook = load_workbook('response.xlsx')
"""
from openpyxl import Workbook, load_workbook
# create workbook obj
workbook = load_workbook('response.xlsx')
# get the existing sheet
#sheet = workbook.get_sheet_by_name("my data")
sheet = workbook ["my data"]
#delete sheet
workbook.remove(sheet)
# save file
workbook.save(filename="response.xlsx")
|
"""
write a print statement for every method start
write a print statement for every method end
"""
def log(func):
def operation():
print("funtion start "+ str(func.__name__))
func()
print("funtion end " + str(func.__name__))
return operation;
@log
def sum():
print("In sum")
@log
def sub():
print("In sub")
sum()
sub() |
import re
"""
[] A set of characters
ATLEAST ONE OF THE CHAR EXISTS :
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[arn] Returns a match where one of the specified characters (a, r, or n) are present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
[^arn] Returns a match for any character EXCEPT a, r, and n
only [_.,!] Returns a match where any of the specified match is found
[0-39] is the same as [01239]
[^abc] means any character except a or b or c
[^0-9] means any non-digit character.
"""
"""
string should contain either 0 or 1 or 2 or 3
"""
pattern = "[0123]";
test_strings = ['hi123bye', '111', '9999', '5ggrrg', 'gg6']
for testStr in test_strings:
result = re.match(pattern, testStr)
if result:
print(testStr, " - valid successful.")
else:
print(testStr, " -Invalid.")
|
# 定义一个学生类,用来形容学生
# 定义一个空的类
class Student():
# 一个空类,pass 代表直接跳过,此处pass不能省略
pass
# 定义一个对象
mingyue = Student()
# 定义一个雷,用来描述听Python的学生
class PythonStudent():
# 用None给不确定的赋值
name = None
age = 18
course = "Python"
# def 需要注意缩进的层级
# 系统默认由一个self参数
def doHomework(self):
print("I'm doing my homework")
# 推荐在函数末尾使用return 语句
# 实例化一个叫yueyue的学生,具体是一个人
yueyue = PythonStudent()
print(yueyue.name)
print(yueyue.age)
# 注意成员函数的调用没有传递进入参数
yueyue.doHomework()
|
#!/usr/bin/env python
""" The Following module does mathematical operation with Roman numerals.
Author: Ravi Kishan Jha.
Date: 15th November 2017.
"""
def main():
'''This Function is the main function of the code. performs Arithmetic operations on the Roman
Numbers
Input Attributes: Roman Value1 of String type, Roman Value 2 of String Type
The Code has the use of operater on input attributes to perform different arithmetic operations
Output Attribute: Roman Value of Arithmetic operation of input String values. '''
num1 = input().upper()
op = input()
num2 = input().upper()
if (check_correct_roman(num1) == 1 and check_correct_roman(num2) == 1):
if (op == '+'):
result = add(num1,num2)
elif (op == '-'):
result = sub(num1,num2)
elif (op == '/'):
result = div(num1,num2)
elif (op == '*'):
result = mult(num1,num2)
print(result)
else:
print("error")
def check_correct_roman(s):
''' This function is used to check whether the INPUT Roman Number is valid or not.
Input attribute : Type String, is a roman number with letters such as C, X, L, V, I, M
Output is either 1 or 0 based on the condition satisfied.'''
if(len(s) < 4):
return 1
for pos in range(0, len(s)-3):
if(s[pos] == s[pos + 1] == s[pos + 2] == s[pos + 3]):
return 0
else:
return 1
def integer_to_roman(num):
''' This function is used to convert the integer value into its respective Roman value.
Input Attribute: Integer Value from range 1 to 3999 usually
Output Attribute : Roman Number which is string value of the corresponding Integer.'''
num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'),(50, 'L'), (40, 'XL'), (10, 'X'),
(9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
if(num < 4000):
roman = ''
while num > 0 :
for temp, roman_temp in num_map:
while num >= temp:
roman += roman_temp
num -= temp
return roman
else:
print("Out of range")
def roman_to_integer(s):
'''This Function is converting the Roman number into it's respective integer value.
Input Attribute: String Roman Value usually containing values such as C, M, X, V, I, D.
Output Attribute: Integer Value of the corresponding input Roman string.'''
roman_map = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
temp = 0
for i in range(0, len(s)-1):
if roman_map[s[i]] < roman_map[s[i + 1]]:
temp -= roman_map[s[i]]
else:
temp += roman_map[s[i]]
return temp + roman_map[s[-1]]
def add(num1, num2):
'''This Function performs Arithmetic operations on the Roman Numbers.
Input Attributes: Roman Value1 of String type, Roman Value 2
of String Type
The Code has conversion of input attributes using external functions Roman to Integer, perform
operations and then convert Integer to Roman.
Output Attribute: Roman Value of Addition of input String values.'''
val1 = roman_to_integer(num1)
val2 = roman_to_integer(num2)
return integer_to_roman(val1 + val2)
def sub(num1, num2):
'''This Function performs Arithmetic Subtraction on the Roman Numbers.
Input Attributes: Roman Value1 of String type, Roman Value 2
of String Type
The Code has conversion of input attributes using external functions Roman to Integer, perform
operations and then convert Integer to Roman.
Output Attribute: Roman Value of Subtraction of input String values.'''
val1 = roman_to_integer(num1)
val2 = roman_to_integer(num2)
if (val1 > val2):
return integer_to_roman(val1 - val2)
else:
return integer_to_roman(val2-val1)
def mult(num1, num2):
'''This Function performs Multiplication operation on the Roman Numbers.
Input Attributes: Roman Value1 of String type, Roman Value 2
of String Type
The Code has conversion of input attributes using external functions Roman to Integer, perform
operations and then convert Integer to Roman.
Output Attribute: Roman Value of Multiplication of input String values.'''
val1 = roman_to_integer(num1)
val2 = roman_to_integer(num2)
return integer_to_roman(val1 * val2)
def div(num1, num2):
'''This Function performs Division operation on the Roman Numbers.
Input Attributes: Roman Value1 of String type, Roman Value 2
of String Type
The Code has conversion of input attributes using external functions Roman to Integer, perform
operations and then convert Integer to Roman.
Output Attribute: Roman Value of Division of input String values.'''
val1 = roman_to_integer(num1)
val2 = roman_to_integer(num2)
return integer_to_roman(val1 / val2)
if __name__ == '__main__':
main()
|
#This program that keep asking you to type, litarally, "your name"
try:
Name = input()
except EOFError:
Name = ''
while Name != 'your name':
print('Try again, write your name')
try:
Name = input()
except EOFError:
Name = ''
print('Well done')
|
# Import libraries
import pandas as pd
import datetime as dt
def date_related_features(data_df):
"""
For each date column create three separate columns that store the corresponding month, year and week
For each date column create a column that stores the date in seconds from the reference date (1st January, 1970)
Create a column that stores the number of days stayed against each observation
Create a column that stores the number of days of advance booking for each observation
:param data_df: training set dataframe
:return: modified training and test set
"""
date_cols = ['booking_date', 'checkin_date', 'checkout_date']
for date_col in date_cols:
data_df[date_col] = pd.to_datetime(data_df[date_col], format='%d/%m/%y')
data_df[date_col + '_in_seconds'] = (data_df[date_col] - dt.datetime(1970, 1, 1)).dt.total_seconds()
data_df[date_col + '_month'] = data_df[date_col].dt.month
data_df[date_col + '_year'] = data_df[date_col].dt.year
data_df[date_col + '_week'] = data_df[date_col].dt.week
data_df['days_stay'] = (data_df['checkout_date'] - data_df['checkin_date']).dt.days
data_df['days_advance_booking'] = (data_df['checkin_date'] - data_df['booking_date']).dt.days
return data_df
# def merge_train_test(train, test):
# """
# Merge the train and test set in order to build features
# :param train: training set dataframe
# :param test: test set dataframe
# :return: a single merged dataframe
# """
#
# train = train.drop('amount_spent_per_room_night_scaled', axis=1)
# full_data = pd.concat([train, test]).reset_index(drop=True)
# full_data = full_data.sort_values(by='checkin_date').reset_index(drop=True)
#
# return full_data
def aggregate_features_by_memberid(data_df):
"""
Get the aggregate values of different columns grouped by memberid
['booking_date_in_seconds', 'checkin_date_in_seconds', 'days_stay',
'days_advance_booking', 'roomnights']: mean of all values
['days_stay', 'roomnights']: sum of all values
['resort_id']: number of unique values
:param data_df: full_data
:return: mini_data
"""
initial_columns = ['memberid', 'resort_id', 'state_code_residence', 'checkin_date', 'booking_date']
mini_data_df = data_df[['reservation_id'] + initial_columns]
# get the mean of important columns
for col in ['booking_date_in_seconds', 'checkin_date_in_seconds', 'days_stay', 'days_advance_booking',
'roomnights']:
if col == 'roomnights':
data_df[col] = data_df[col].astype('float64')
gdf = data_df.groupby('memberid')[col].mean().reset_index()
gdf.columns = ['memberid', 'member_' + col + '_mean']
mini_data_df = pd.merge(mini_data_df, gdf, on='memberid', how='left')
# get the sum of important columns
for col in ['days_stay', 'roomnights']:
gdf = data_df.groupby('memberid')[col].sum().reset_index()
gdf.columns = ['memberid', 'member_' + col + '_sum']
mini_data_df = pd.merge(mini_data_df, gdf, on='memberid', how='left')
# get the total #unique values of important columns
for col in ['resort_id']:
gdf = data_df.groupby('memberid')[col].nunique().reset_index()
gdf.columns = ['memberid', 'member_' + col + '_nunique']
mini_data_df = pd.merge(mini_data_df, gdf, on='memberid', how='left')
return mini_data_df
def cumulative_features_by_memberid(data_df, mini_data_df):
"""
Take cumulative values of different columns grouped by each memberid and add it to mini_data
:param data_df: full_data
:param mini_data_df: mini_data
:return: modified mini_data
"""
# Cumulative count of member bookings
mini_data_df['cumcount_member_bookings'] = data_df.groupby('memberid')['booking_date_in_seconds'].cumcount().values
# Cumulative sum of member stays at CM resorts (all inclusive)
mini_data_df['cumsum_member_days_stay'] = data_df.groupby('memberid')['days_stay'].cumsum().values
# Cumulative sum of total # people travelled with member at CM resorts (all inclusive)
data_df['total_pax'] = data_df['total_pax'].astype('int64')
mini_data_df['cumsum_member_total_pax'] = data_df.groupby('memberid')['total_pax'].cumsum().values
return mini_data_df
def time_gap_shift_1_features(data_df, mini_data_df):
"""
For each member, compute:
1. time gap between current booking date and previous booking date/next booking date
2. time gap between current checkin date and previous checkin date/next checkin date
3. time gap between current checkout date and previous checkout date/next checkout date
For each member-resort combination, compute:
1. time gap between current booking date and previous booking date/next booking date
2. time gap between current checkin date and previous checkin date/next checkin date
:param data_df: full_data
:param mini_data_df: mini_data
:return: modified mini_data
"""
# Compute time gap between current booking date and previous booking date/next booking date for each memberid and
# add it to mini_data
data_df['prev_booking_date_in_seconds'] = data_df.groupby('memberid')['booking_date_in_seconds'].shift(1)
mini_data_df['time_gap_booking_prev'] = data_df['booking_date_in_seconds'] - data_df[
'prev_booking_date_in_seconds']
data_df['next_booking_date_in_seconds'] = data_df.groupby('memberid')['booking_date_in_seconds'].shift(-1)
mini_data_df['time_gap_booking_next'] = data_df['next_booking_date_in_seconds'] - data_df[
'booking_date_in_seconds']
# Compute time gap between current checkin date and previous checkin date/next checkin date for each memberid and
# add it to mini_data
data_df['prev_checkin_date_in_seconds'] = data_df.groupby('memberid')['checkin_date_in_seconds'].shift(1)
mini_data_df['time_gap_checkin_prev'] = data_df['checkin_date_in_seconds'] - data_df[
'prev_checkin_date_in_seconds']
data_df['next_checkin_date_in_seconds'] = data_df.groupby('memberid')['checkin_date_in_seconds'].shift(-1)
mini_data_df['time_gap_checkin_next'] = data_df['next_checkin_date_in_seconds'] - data_df[
'checkin_date_in_seconds']
# Compute time gap between current checkout date and previous checkout date/next checkout date for each memberid
# and add it to mini_data
data_df['prev_checkout_date_in_seconds'] = data_df.groupby('memberid')['checkout_date_in_seconds'].shift(1)
mini_data_df['time_gap_checkout_prev'] = data_df['checkout_date_in_seconds'] - data_df[
'prev_checkout_date_in_seconds']
data_df['next_checkout_date_in_seconds'] = data_df.groupby('memberid')['checkout_date_in_seconds'].shift(-1)
mini_data_df['time_gap_checkout_next'] = data_df['next_checkout_date_in_seconds'] - data_df[
'checkout_date_in_seconds']
# Compute time gap between current booking date and previous booking date/next booking date for each
# memberid-resort_id combination and add it to mini_data
data_df['prev_resort_booking_date_in_seconds'] = data_df.groupby(['memberid', 'resort_id'])[
'booking_date_in_seconds'].shift(1)
mini_data_df['time_gap_booking_prev_resort'] = data_df['booking_date_in_seconds'] - data_df[
'prev_resort_booking_date_in_seconds']
data_df['next_resort_booking_date_in_seconds'] = data_df.groupby(['memberid', 'resort_id'])[
'booking_date_in_seconds'].shift(-1)
mini_data_df['time_gap_booking_next_resort'] = data_df['next_resort_booking_date_in_seconds'] - data_df[
'booking_date_in_seconds']
# Compute time gap between current checkin date and previous checkin date/next checkin date for each
# memberid-resort_id combination and add it to mini_data
data_df['prev_resort_checkin_date_in_seconds'] = data_df.groupby(['memberid', 'resort_id'])[
'checkin_date_in_seconds'].shift(1)
mini_data_df['time_gap_checkin_prev_resort'] = data_df['checkin_date_in_seconds'] - data_df[
'prev_resort_checkin_date_in_seconds']
data_df['next_resort_checkin_date_in_seconds'] = data_df.groupby(['memberid', 'resort_id'])[
'checkin_date_in_seconds'].shift(-1)
mini_data_df['time_gap_checkin_next_resort'] = data_df['next_resort_checkin_date_in_seconds'] - data_df[
'checkin_date_in_seconds']
return mini_data_df
def time_gap_shift_2_features(data_df, mini_data_df):
"""
For each member, compute:
1. time gap between current booking date and second last booking date/next-to-next booking date
2. time gap between current checkin date and second last checkin date/next-to-next checkin date
:param data_df: full_data
:param mini_data_df: mini_data
:return: modified mini_data
"""
# Compute time gap between current booking date and second last booking date/next-to-next booking date (shift 2)
# for each memberid and add it to mini_data
data_df['prev2_booking_date_in_seconds'] = data_df.groupby('memberid')['booking_date_in_seconds'].shift(2)
mini_data_df['time_gap_booking_prev2'] = data_df['booking_date_in_seconds'] - data_df[
'prev2_booking_date_in_seconds']
data_df['next2_booking_date_in_seconds'] = data_df.groupby('memberid')['booking_date_in_seconds'].shift(-2)
mini_data_df['time_gap_booking_next2'] = data_df['next2_booking_date_in_seconds'] - data_df[
'booking_date_in_seconds']
# Compute time gap between current checkin date and second last checkin date/next-to-next checkin date (shift 2)
# for each memberid and add it to mini_data
data_df['prev2_checkin_date_in_seconds'] = data_df.groupby('memberid')['checkin_date_in_seconds'].shift(2)
mini_data_df['time_gap_checkin_prev2'] = data_df['checkin_date_in_seconds'] - data_df[
'prev_checkin_date_in_seconds']
data_df['next2_checkin_date_in_seconds'] = data_df.groupby('memberid')['checkin_date_in_seconds'].shift(-2)
mini_data_df['time_gap_checkin_next2'] = data_df['next2_checkin_date_in_seconds'] - data_df[
'checkin_date_in_seconds']
return mini_data_df
def inter_visit_features(data_df, mini_data_df):
"""
For each member, compute:
1. Difference in days_stay between current and previous/next visit
2. Difference in roomnights between current and previous/next visit
3. Difference in days_advance_booking between current and previous/next visit
:param data_df: full_data
:param mini_data_df: mini_data
:return: modified mini_data
"""
# Compute more information on previous and next visits (for numerical columns)
for col in ['days_stay', 'roomnights', 'days_advance_booking']:
data_df['prev_' + col] = data_df.groupby('memberid')[col].shift(1)
mini_data_df['prev_diff_' + col] = data_df[col] - data_df['prev_' + col]
data_df['next_' + col] = data_df.groupby('memberid')[col].shift(-1)
mini_data_df['next_diff_' + col] = data_df['next_' + col] - data_df[col]
# Compute more information on previous and next visits (for categorical columns)
for col in ['channel_code', 'room_type_booked_code', 'resort_type_code', 'main_product_code']:
data_df['prev_' + col] = data_df.groupby('memberid')[col].shift(1)
mini_data_df['prev_diff_' + col] = (data_df[col] == data_df['prev_' + col]).astype(int)
data_df['next_' + col] = data_df.groupby('memberid')[col].shift(-1)
mini_data_df['next_diff_' + col] = (data_df[col] == data_df['next_' + col]).astype(int)
return mini_data_df
def pivot_features(data_df, mini_data_df):
"""
Pivot the data on row as memberid and column as each of ['resort_id', 'checkin_date_year', 'resort_type_code',
'room_type_booked_code'] in isolation
:param data_df: full_data
:param mini_data_df: mini_data
:return: modified mini_data
"""
# Create pivots on memberid and a host of other columns and add it to mini_data
for col in ['resort_id', 'checkin_date_year', 'resort_type_code', 'room_type_booked_code']:
gdf = pd.pivot_table(data_df, index='memberid', columns=col, values='reservation_id', aggfunc='count',
fill_value=0).reset_index()
mini_data_df = pd.merge(mini_data_df, gdf, on='memberid', how='left')
return mini_data_df
def ratio_features(data_df):
"""
Take ratio of values of two columns and present it as a new feature
:param data_df: full_data
:return: modified full_data
"""
for col1, col2 in [["roomnights", "days_stay"]]:
data_df[col1 + "_ratio_" + col2] = data_df[col1] / data_df[col2]
return data_df
def concatenated_features(data_df):
"""
Concatenate features and find the total count of reservations grouped by these features
:param: full_data
:return: modified full_data
"""
for col in [
"memberid", ["resort_id", 'checkin_date'],
["resort_id", "checkout_date"],
["state_code_residence", "checkin_date"],
["memberid", "checkin_date_year"],
["memberid", "checkin_date_month"],
["resort_id", "checkin_date_year"],
["resort_id", "checkin_date_month"],
["resort_id", "checkin_date_year", "checkin_date_month"],
["resort_id", "state_code_residence", "checkin_date"],
["resort_id", "state_code_residence", "checkout_date"],
["resort_id", "checkin_date_year", "checkin_date_week"],
["resort_id", "state_code_residence", "checkin_date_year", "checkin_date_week"],
["resort_id", "state_code_residence", "checkin_date_year", "checkin_date_month"],
["booking_date", "checkin_date"],
["booking_date", "checkin_date", "resort_id"]]:
if not isinstance(col, list):
col = [col]
col_name = "_".join(col)
gdf = data_df.groupby(col)["reservation_id"].count().reset_index()
gdf.columns = col + [col_name + "_count"]
data_df = pd.merge(data_df, gdf, on=col, how="left")
return data_df
|
#!/usr/bin/python
import time
def main():
max_digital_sum = 0
for a in range(100):
for b in range(100):
numero = a**b
s_numero = str(numero)
lista = [int(x) for x in s_numero]
sumatoria = sum(lista)
if sumatoria > max_digital_sum:
max_digital_sum = sumatoria
print("Maximum digital sum:", max_digital_sum)
if __name__ == "__main__":
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
|
#!/usr/bin/python
import time
from math import sqrt
listadoPrimos = []
def esPrimo(x:int) -> bool:
if x == 1: return False
if x < 4: return True
if x % 2 == 0: return False
if x < 9: return False
if x % 3 == 0: return False
sqrtx = int(sqrt(x))
i = 5
while i <= sqrtx:
if x % i == 0: return False
if x % (i+2) == 0: return False
i=i+6
return True
def main():
#Formula: n**2 + a*n + b, where |a|<1000 and |b|<=1000
maxCadena = 0
nMaxCadena = 0
for a in range(-999, 999):
print(a)
for b in range(-1000,1001):
n=0
while True:
pp = n*n + a*n + b
if pp < 1: break
if not esPrimo(pp): break
n += 1
if n > maxCadena:
maxCadena = n
nMaxCadena = a * b
print(nMaxCadena,"with",maxCadena,"primes")
if __name__ == "__main__":
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
|
#!/usr/bin/python
import time
import itertools
from math import sqrt
def isPrime(x):
if x == 1: return False
if x < 3: return True
if x%2==0: return False
if x < 9: return True
if x%3==0: return False
sqrtx = int(sqrt(x))
i = 5
while i <= sqrtx:
if x % i == 0: return False
if x % (i+2) == 0: return False
i=i+6
return True
def main():
digitos = ['1','2','3','4','5','6','7','8','9']
for ndigital in range(9,0,-1):
perm = itertools.permutations(digitos[:ndigital])
lperm = list(perm)
lperm.reverse()
for t in lperm:
if isPrime(int(''.join(t))):
print(int(''.join(t)))
break
if __name__ == "__main__":
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
|
#!/usr/bin/python
import time
def main():
number = 1
while True:
digits = sorted(list(str(number)))
flag = True
for i in range(2,7):
n = number * i
ndigits = sorted(list(str(n)))
if digits != ndigits:
flag = False
break
if flag:
print(number)
break
number += 1
if __name__ == "__main__":
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
|
#!/usr/bin/python3
import time
def main():
continuedFraction = [2]
for i in range(1,35):
continuedFraction.extend([1, 2*i, 1])
continuedFraction = continuedFraction[:100]
numerador = continuedFraction[99]
denominador = 1
for j in continuedFraction[:99][::-1]:
aux = denominador
denominador = numerador
numerador = j * denominador + aux
print(numerador, '/', denominador)
print('Suma de digitos:', sum([int(x) for x in list(str(numerador))]))
if __name__ == "__main__":
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
|
'''
测试
try...except...finally...
'''
for i in range(2)[::-1]:
try:
print('try...')
r = 10 / i
a = 'dfg'
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
a = 'fdfdg'
finally:
print('finally...')
t = ('evd', a, 'df')
print(t)
''' 结果
try...
except: division by zero
finally...
END
''' |
# Let's create a basic functions to greet
# Syntax def name():
# first iterations
# def greetings():
# return "Welcome to Cyber Security! " #
# print(greetings())
# # Second iteration
# def greeting_user(name):
# return "welcome on board1"
#
# # Take user name as input() and disply is back to them with greeting messages of your choice
#
# def greeting(name):
# print(f'Hello {name}')
# print('Welcome to Cyber Security')
#
# user = input('What is your name? ')
# greeting(user)
# creating a function that takes 2 args as ints
def add(value1, value2):
return value1 + value2
print(add(2,3))
def subtract(value1, value2):
return value1 - value2
print(subtract(9, 5))
#Activity:
#Create two functions:
# One that multiplies two numbers
# One that divides two numbers
def multiply(value1, value2):
return value1 * value2
print(multiply(3, 8))
def divide(value1, value2):
return value1 / value2
print(divide(6, 9))
|
'''
Author: Kwadwo Boateng Ofori-Amanfo
Purpose: Learn how to convert images from one format to another. We will use this file to perform the same actions done with image magic as outlined in the 'NB:' section below
Date: 2019. 11. 28. (목) 14:08:53 KST
Video Lecture(s): OpenCV Programming with Python on Linux Ubuntu Tutorial-6 Converting Images
link(s):
[1]
Reference(s):
[1]
NB: You'll need to install the imagemagick software. You can verify if it is already installed on you machine by typing the command into your terminal <identify -version>
Afterwards, the command(s):
1. <convert old_image.jpg new_image.png> for example, could be used to do a conversion of a 'jpg' image to a 'png' image
2. <convert old_image.jpg -resize 50% new_image.png>, could also be used to resize the image
'''
from PIL import Image
from numpy import *
from pylab import *
import cv2 # computer vision library
# windows to display image
cv2.namedWindow("Image")
# read image
#im = cv2.LoadImage("rose.jpeg")
im = cv2.imread("rose.jpg")
print(type(im))
cv2.namedWindow("rose", cv2.WINDOW_AUTOSIZE)
#cv2.ShowImage("New rose", im)
cv2.imshow("New rose", im)
#cv2.WaitKey(10000)
cv2.waitKey(10000)
#cv2.SaveImage("new_rose.png",im)
cv2.imwrite("new_rose.png",im)
#cv2.DestroyWindow("rose")
cv2.destroyAllWindows("rose")
|
import time
import turtle
import random
BREAK_FLAG = False #for snake eating itself
# Draw window
screen = turtle.Screen()
screen.title("Snake GAME NOKIA")
screen.bgcolor("lightgreen")
screen.setup(600,600)
screen.tracer(0) #for turning off animation
#Draw border
border = turtle.Turtle()
border.hideturtle()
border.penup()
border.goto(-300,300)#left up corner
border.pendown()
border.goto(300,300)
border.goto(300,-300)
border.goto(-300,-300)
border.goto(-300,300)
#draw 3 pieced snake wih black head
snake = []
for i in range(3):
snake_piece = turtle.Turtle()
snake_piece.shape("square")
snake_piece.penup()
if i>0:
snake_piece.color("gray")
snake.append(snake_piece)
#draw food for snake
food = turtle.Turtle()
food.shape("circle")
food.penup()
food.goto(random.randrange(-300,300,20), random.randrange(-300,300,20))
#snake control
#pause control
PAUSE = 0
T = 0.1
def p():
PAUSE=1
def u():
PAUSE=0
screen.listen()
screen.onkeypress(lambda: snake[0].setheading(90), "Up")
screen.onkeypress(lambda: snake[0].setheading(270), "Down")
screen.onkeypress(lambda: snake[0].setheading(180), "Left")
screen.onkeypress(lambda: snake[0].setheading(0), "Right")
screen.onkeypress(p, "w")
screen.onkeypress(u, "s")
#Game logic
while True:
#creating a new piece for snake
#if snake eats food
if snake[0].distance(food)<10:
food.goto(random.randrange(-300,300,20),random.randrange(-300,300,20))
snake_piece = turtle.Turtle()
snake_piece.shape("square")
snake_piece.color("gray")
snake_piece.penup()
snake.append(snake_piece)
#snake body movement
for i in range(len(snake)-1, 0, -1):
x = snake[i-1].xcor()
y = snake[i-1].ycor()
snake[i].goto(x,y)
#snake head movement
snake[0].forward(20)
#render
screen.update()
#snake collision with border
x_cor = snake[0].xcor()
y_cor = snake[0].ycor()
if x_cor > 300 or x_cor < -300:
screen.bgcolor("red")
break
if y_cor > 300 or y_cor < -300:
screen.bgcolor("red")
break
#snake collision with itself
for i in snake[1:]:
i = i.position()
if snake[0].distance(i) < 10:
screen.bgcolor("red")
BREAK_FLAG = True
if BREAK_FLAG:
screen.bgcolor("red")
break
if PAUSE == 1:
T = 2000
elif PAUSE == 0:
T = 0.1
time.sleep(T)
screen.mainloop() |
a=str(input("enter the character:"))
print("The ASCII Value of entered character is",ord(a))
|
# Asking for Video Link
video = input("Insert Video Link: ")
# Downloads video page
import urllib.request
urllib.request.urlretrieve(video, "video.html")
# Defines "everything_between"
def everything_between(text,begin,end):
idx1=content.find(begin)
idx2=content.find(end,idx1)
return content[idx1+len(begin):idx2].strip()
# Searches for video source
content = open('video.html').read()
videoLink = everything_between(content,'src: "','",')
videoTitle = everything_between(content,'<h1>','</h1>')
# Downloads video
title = videoTitle + ".mp4"
urllib.request.urlretrieve(videoLink, title)
print("Downloaded " + videoTitle)
# Deletes video page
import os
os.remove('video.html')
|
# coding:utf-8
# author: Tao yong
# Python
'''
matplotlib是一个第三方数学绘图库
模块pyplot包含了很多生成图标的函数
plot()----折线图
sctter()----散点图
'''
from matplotlib库.random_walk import RandomWalk
#添加中文字体
from pylab import *
# 添加中文字体
from pylab import *
from matplotlib库.random_walk import RandomWalk
mpl.rcParams['font.sans-serif'] = ['SimHei']
#利用plot函数绘制简单的折线图
#修改plot函数默认参数linewidth
#默认plot函数x轴的点是0,1,2,3,4,……,square表示g各x值对应的y值
input_value=[1,2,3,4,5]
#设置各点的x轴坐标
squares=[1,4,9,16,25]
#设置各点的y轴坐标
plt.plot(input_value,squares,linewidth=5)
#设置图表标题,给x,y轴加上标签
plt.title('Square Numbers',fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel('Square of Value',fontsize=14)
#设置刻度标记的大小
plt.tick_params(axis='both',labelsize=14)
plt.show()
#使用sctter()函数绘制散点图
# x_values=[1,2,3,4,5]
# y_values=[1,4,9,16,25]
#利用循环代替计算绘制1000个点的图,y=x^2
x_values=list(range(0,1000))
y_values=[x**2 for x in x_values]
#散点默认蓝色点和黑色轮廓,edgecolor实参可改变轮廓,none删除数据点轮廓
#参数c可改变数据点颜色,可指定颜色,例:c='red',也可以rgb模式(红,绿,蓝)自定义。例:c=(0,0,0.8)
#参数c的颜色映射,可根据函数实现颜色渐变,数值越小,颜色越浅,数值越大,颜色越深
plt.scatter(x_values,y_values,c=y_values,edgecolors='none',s=40)
#设置图表标题并给坐标轴加上标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of Value",fontsize=14)
#设置刻度标记的大小
plt.tick_params(axis='both',which='major',labelsize=14)
plt.show()
#例1:绘制前五个整数立方值的图形函数
def cube_5():
x_values=list(range(0,5))
y_values=[x**3 for x in x_values]
plt.scatter(x_values,y_values,s=40)
plt.title('前五个整数的立方值',fontsize=25)
plt.xlabel('整数',fontsize=14)
plt.ylabel('整数的立方值',fontsize=14)
plt.tick_params(axis='both',which='major',labelsize=14)
plt.show()
def cube_5000():
x_values=list(range(0,5000))
y_values=[x**3 for x in x_values]
plt.scatter(x_values,y_values,s=40)
plt.title('前五千个整数的立方值',fontsize=25)
plt.xlabel('整数',fontsize=14)
plt.ylabel('整数的立方值',fontsize=14)
plt.tick_params(axis='both',which='major',labelsize=14)
plt.show()
rw=RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 13:57:59 2020
@author: ANN by OMAAR,
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('Churn_Modelling.csv')
"""
X = dataset.iloc[:, 3:13].values #[:, [2,3]] is also correct !!
y = dataset.iloc[:, 13].values
#encoding categorical feature, independent variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features=[1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:] # to avoid dummy variable trap
#spliting data into training and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,random_state=0)
#feature scaling, because of euclidean distance
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# PART 2
# Importing the Keras module with packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initializing the ANN
classifier = Sequential()
# Adding the input layer and first hidden layer
classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu', input_dim=11))
# Adding the 2nd hidden layer
classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))
# Adding the output layer
classifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))
# compiling the ANN
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Fitting the ANN tom the training set
classifier.fit(X_train, y_train, batch_size=10, epochs=100)
# PART 3
# Making the prediction and importing the model
#Predicting the Test set result
y_pred = classifier.predict(X_test)
y_pred_1 = (y_pred > 0.5)
# Making a Confusion matrix
from sklearn.metrics import confusion_matrix, f1_score, classification_report
cm = confusion_matrix(y_test, y_pred_1)
print('\n')
f1 = f1_score(y_test, y_pred_1)
print('\n')
report = classification_report(y_test, y_pred_1)""" |
class juego:
"""Clases encargada de la generacion de la matriz a utilizar para desarrollar el juego"""
n = 0
m = 0
matriz=[]
def __init_(self,n,m,matriz):
self.n=n #se pide la cantidad n
self.m = m #se pide la cantidad m
self.matriz=matriz #variable para crear matriz
def crear_matriz(self,n,m):
#E:recibe el n y el m
#S:Generar matriz
#R:No presenta
"""Metodo que crea matriz de 25x40"""
for filas in range(n):
self.matriz.append([])
for columnas in range(m):
if filas == 0 or filas ==24:
self.matriz[filas].append(1)
else:
self.matriz[filas].append(0)
return self.matriz |
import streamlit as st
import numpy as np
import pandas as pd
from PIL import image
from sklearn.neighbors import KNeighborsClassifier
def welcome():
return "Welcome All"
def predict_heart_diseases( age , sex ,cp ,trestbps , chol , fbs , restecg , thalach , exang , oldpeak , slope , ca , thal):
classifier = KNeighborsClassifier(n_neighbors = 7)
classifier.fit(x_train.T,y_train.T)
prediction = classifier.predict([[age , sex ,cp ,trestbps , chol , fbs , restecg , thalach , exang , oldpeak , slope , ca , thal]])
print(prediction)
return prediction
def main():
st.title("Heart-Diseases Classifier")
html_temp = """
<div style="backgroud-color:tomato ; padding:10px">
<h2 style="color:white ; text-align: center ;">Streamlit Heart-Diseases Classifier ML app </h2>
st.markdown(html_temp , unsafe_allow_html = True )
@st.cache(persist=True)
def load_data():
data = pd.read_csv("heart.csv")
return data
@st.cache(persist=True)
def split(df):
y = df.target.values
x_data = df.drop(['target'], axis = 1)
x = (x_data - np.min(x_data)) / (np.max(x_data) - np.min(x_data)).values
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2,random_state=0)
return x_train, x_test, y_train, y_test
df = load_data()
x_train, x_test, y_train, y_test = split(df)
x_train = x_train.T
y_train = y_train.T
x_test = x_test.T
y_test = y_test.T
age = st.text_input("age", "Type Here")
sex = st.text_input("age", "Type Here")
cp = st.text_input("age", "Type Here")
trestbps = st.text_input("age", "Type Here")
chol = st.text_input("age", "Type Here")
fbs = st.text_input("age", "Type Here")
restecg = st.text_input("age", "Type Here")
thalach = st.text_input("age", "Type Here")
exang = st.text_input("age", "Type Here")
oldpeak = st.text_input("age", "Type Here")
slope = st.text_input("age", "Type Here")
ca = st.text_input("age", "Type Here")
thal = st.text_input("age", "Type Here")
results = ""
if st.button("Predict"):
result = predict_heart_diseases( age , sex ,cp ,trestbps , chol , fbs , restecg , thalach , exang , oldpeak , slope , ca , thal)
st.success('The output is {} '.format(result))
if st.button("About"):
st.text("Lets LEarn")
st.text("Built with Streamlit")
if __name == '__main__':
main()
|
#!/usr/bin/python3
# from random import seed
# from random import randint
def clear():
# clear the terminal screen
print("\n"*50)
def banner():
# prints a banner and game mode menu
print(""" &&& &&& &&&
& & & &
& & &
& & &
* * *
Welcome\n to\n Number Guess!!!
Note: Numbers only please, anything else
will probably crash the game
""")
mode = int(input("[1] You play computer\n[2] Computer plays you\n[3] Exit\n:"))
if mode == 1:
menu()
elif mode == 2:
pcmenu()
elif mode == 3:
exit(0)
else:
banner()
def menu():
clear()
from random import seed
from random import randint
global hidden_number
global turn
turn = 0
level = int(input("Choose a difficulty \n [1] Easy: 1-10\n [2] Medium: 1-100\n [3] Hard: 1-1000\n [4] Exit \n:"))
if level == 1:
hidden_number = randint(1,10)
print("Guess my number it is between 1 and 10...")
game()
elif level == 2:
hidden_number = randint(1,100)
print("Guess my number it is between 1 and 100...")
game()
elif level == 3:
hidden_number = randint(1,1000)
print("Guess my number it is between 1 and 1000...")
game()
elif level == 4:
banner()
else:
print("Thats not an option, Choose again")
menu()
def pcmenu():
clear()
global turn
global user_number
global high
global low
turn = 0
level = int(input("Welcome to Number Guess!!! \n \n Choose a difficulty \n [1] Easy: 1-10\n [2] Medium: 1-100\n [3] Hard: 1-1000\n [4] Exit \n:"))
if level == 1:
user_number = int(input("Enter a number from 1 to 10: \n"))
low = 1
high = 10
pcgame()
elif level == 2:
user_number = int(input("Enter a number from 1 to 100: \n"))
low = 1
high = 100
pcgame()
elif level == 3:
user_number = int(input("Enter a number from 1 to 1000: \n"))
low = 1
high = 1000
pcgame()
elif level == 4:
banner()
else:
print("Thats not an option, Choose again")
pcmenu()
def game():
global turn
turn+=1
guess = int(input("Guess the number:"))
if guess < hidden_number:
print ("Too Low!")
game()
elif guess > hidden_number:
print ("Too High")
game()
elif guess == hidden_number:
print("\n\n",guess,"is the Correct Number!\n\n You guessed the number in",turn,"turns!!!")
banner()
# else:
# except(ValueError)
# print("Thats not a number... try again")
# menu()
def pcgame():
global high
global low
guess = round((low + high)/2)
#print(guess)
print("Is your number",guess,"? \nL = too low \nH = too high \nY = You guessed correctly!!!\n")
ask = str(input())
# print(ask)
if ask == "L" or ask == "l":
low = guess
pcgame()
elif ask == "H" or ask == "h":
high = guess
pcgame()
elif ask == "Y" or ask == "y":
print("I guessed",guess,"and the number you thought of was",user_number)
print("Let's Play Again \n\n")
banner()
clear()
banner()
|
import sys
#import random
from random import randint
#from random import seed
#from datetime import datetime
# lets us have random integers
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
# defines the number list
sym = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '`',
'~', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|',
';', ':', "'", '"', ',', '.', '<', '>', '/', '?']
# defines the symbol list
low = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#defines the lowercase alphabet
upp = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
#defines the upcase alphabet
pw = "" #sets pw to an empty str variable
alpha = low + upp
charset = low
def choice():
global dif
global dif2
# request password length
dif = int(input("Enter Desired Password Length 8 - 300 characters:\n"))
while dif < 8 or dif > 300: # makes sure password length is correct
choice()
if 8 <= dif <= 300:
continue
dif2 = dif #backs up dif var so it can be reset to gen a second password
print("PASSWORD GENERATOR QUIZ!!!\n")
upper()
def upper():
global charset
global upp
option = str(input('Upper case y/n: '))
if option == 'y':
charset += upp
print("Including Upper Case...")
numb()
elif option == 'n':
numb()
else:
upper()
def numb():
global charset
global num
option = str(input('Numbers? y/n: '))
if option == 'y':
charset += num
print("Including Numbers...")
symb()
elif option == 'n':
symb()
else:
numb()
def symb():
global charset
global sym
option = str(input('Symbols? y/n: '))
if option == 'y':
charset += sym
print ("Including Symbols...")
exc1()
elif option == 'n':
exc1()
else:
symb()
def exc1():
global charset
option = str(input('Leave out i, l, L, 1 and !? y/n: '))
if option == 'y':
exclude = {'i', 'l', 'L', '1', '!'}
charset = [char for char in charset if char not in exclude] #iterate the charset and remove the exclude list
print("Removing Similar characters...")
exc2()
elif option == 'n':
exc2()
else:
exc1()
def exc2():
global charset
option = str(input('Leave out {}[]()/\\!\'",;:>,.? y/n: '))
if option == 'y':
exclude = {'{', '}', '[', ']', '(', ')', '/', '\\', '"', "'",
'!', ':', ';', '>', '<', ',', '.', '?'}
charset = [char for char in charset if char not in exclude]
print("Removing some symbols...")
first_letter()
elif option == 'n':
first_letter()
else:
exc2()
def first_letter():
global charset
option = str(input('Ensure the first character is a letter y/n: '))
if option == 'y':
fchar()
elif option == 'n':
pwgen()
else:
first_letter()
def fchar():
global pw
global dif
dif2 = dif
gen = ''
pw = alpha[(randint(1, len(alpha))-1)]
dif2 -= 1
while dif2 > 0:
gen += charset[(randint(1, len(charset))-1)]
dif2 -= 1
continue
pw = gen
print(pw 'is your new password, it has',dif,'characters.')
count()
def pwgen():
global dif
global pw
gen = ''
dif2 = dif
while dif2 > 0:
gen += charset[(randint(1, len(charset))-1)]
dif2 -= 1
continue
pw = gen
print(pw 'is your new password, it has',dif,'characters.')
count()
def count():
global dif
option = str(input('Would you like another password y/n/r: '))
if option == 'y':
# dif = dif2 #resets dif
first_letter()
elif option == 'r':
reset()
elif option == 'n':
sys.exit(0)
else:
count()
def reset():
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
# defines the number list
sym = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '`',
'~', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|',
';', ':', "'", '"', ',', '.', '<', '>', '/', '?']
# defines the symbol list
low = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#defines the lowercase alphabet
upp = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
#defines the upcase alphabet
pw = ""
alpha = low + upp
charset = []
choice()
#def leave():
# exit()
choice()
|
number = int(input("Enter a number: "))
print("Multiplication Table of: " + str(number))
for i in range(11):
print(number,'x',i,'=',number*i) |
try:
year = int(input("Enter Year: "))
if(year > 0):
if((year % 4) == 0) :
if(year % 100 == 0):
if(year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
else:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
else:
print("Please enter an integer larger than 0 for your year.")
except ValueError:
print("Not a valid year. Please enter an integer.")
|
def sum(x,y):
s=0
for i in range (x,y+1):
s=s+i
return s
x=int(input("enter the number"))
y=int(input("enter the number"))
print(sum(x,y))
|
import hashlib
class AbstractPlayer:
def __init__(self):
"""Abstract base class for a game player."""
# These variables are what .setup() and .run() can use
# to prepate and play against another player!
self.opponent = None
self.move = 0
self.state = None
self.theirLast = None
def getName(self):
name = self.__class__.__name__
s = hashlib.sha1()
s.update(self.setup.__code__.co_code)
s.update(self.play.__code__.co_code)
s.update(self.teardown.__code__.co_code)
return name + "-" + s.hexdigest()[::4]
def moveCount(self):
"""Return the number of move I get to make this turn"""
return self.state.run()
def setup(self):
"""
This is the time that the player can do static setup.
This time is not clocked, and occurs before gameplay can begin.
"""
def play(self):
"""This method defines the player."""
raise NotImplemented("Users must implement this.")
def teardown(self):
"""Mirror function to setup() use to close ports or cleanup etc."""
|
"""
functions used by multiple methods
TODO - probably rename the file lets be real 'shared_functions' is hardly clear
"""
import itertools
import collections
import random
def prime_factor_decomposition(val):
"""Reduce any integer into its unique prime decomposition, returning the input integer if the integer itself is
prime.
Parameters
----------
val : int
An integer to be decomposed
Returns
-------
list
List of prime factors of val, or an empty list if val is in [-1, 0, 1]
"""
val = abs(val)
if val not in [0, 1]:
divisors = list(set([d if val % d == 0 else val
for d in range(2, val // 2 + 1)]))
divisors = [d for d in divisors
if all(d % od != 0 for od in divisors if od != d)]
if val in [2, 3]:
divisors = divisors + [val]
return divisors
else:
return []
def get_prime_decomposition_list(
int_list,
text,
):
"""Break a list of integers down into their unique prime factors
Parameters
----------
int_list : list
List of integers to factorise.
text : bool
Set False to avoid printing any statements
Returns
-------
list
List of prime factor decompositions for input list.
"""
if text:
print('\ndecomposing input integers...\n')
prime_decomposition_list = [prime_factor_decomposition(i) for i in int_list
if prime_factor_decomposition(i) != []]
return prime_decomposition_list
def get_sols(prime_decomposition_list):
"""Get list of ints that are definitely within the solution to MinHItSet alg.
Parameters
----------
prime_decomposition_list : list
List of lists of prime numbers
Returns
-------
list
List of unique integers that were previously elements of all sub lists in prime_decomposition_list of length 1.
"""
sols = [decomposition for decomposition in prime_decomposition_list
if len(decomposition) == 1]
sols = list(set(itertools.chain(*sols)))
return sols
def get_remaining(
prime_decomposition_list,
sols,
):
"""Get list of all sub lists that are not included in the solution directly.
steps included:
1. get all decompositions not included in sols.
2. remove all remaining decompositions that are subsets of other decompositions i.e. [2, 3], [3, 2, 7] -> [3, 2, 7]
Parameters
----------
prime_decomposition_list : list
List of lists of prime numbers
sols : list
List of integers which if present as a list in prime_decomposition_list should be dropped.
Returns
-------
list
List of lists where each sublist if of length > 1.
"""
sols = [[i] for i in sols]
remaining = [decomposition for decomposition in prime_decomposition_list
if decomposition not in sols]
remaining_sets = [set(decomposition) for decomposition in remaining]
remaining = [decomposition_list for decomposition_list, decomposition_set in zip(remaining, remaining_sets)
if not any(decomposition_set < other for other in remaining_sets)]
return remaining
def check_if_solved(
remaining,
sols,
):
"""Check if sols is enough to solve MinHitSet alg.
Parameters
----------
remaining : list
List of lists of remaining decompositions to check if sols hit.
sols : list
List of integers that form an at least partial solution to MinHitSet algorithm.
Returns
-------
list
List of remaining solutions not hit by sols.
"""
check = []
for decomposition in remaining:
check.append(any(item in decomposition for item in sols))
if all(check):
return []
else:
indices = [i for i, x in enumerate(check) if x is False]
remaining = [remaining[i] for i in indices]
return remaining
def check_for_single_remaining_sol(
remaining,
sols,
):
"""Check if a single additional int is enough to hit the remaining decompositions.
Parameters
----------
remaining : list
List of lists of remaining decompositions to check if sols hit.
sols : list
List of integers that form an at least partial solution to MinHitSet algorithm.
Returns
-------
list
List of integers representing an at least partial solution to MinHitSet. Adds a random element from the
available sols in the case where multiple single integers will complete the solution.
"""
element_list = list(itertools.chain.from_iterable(remaining))
counts = collections.Counter(element_list)
check = []
for key, value in counts.items():
if value == len(remaining):
check.append(key)
if len(check) > 0:
sols.append(random.choice(check))
return sols
def remove_single_elements(remaining):
"""Remove elements that appear only once in the solution, if they appear in a decomposition containing at least one
other element that appears more than once.
Parameters
---------
remaining : list
List of lists of prime numbers.
Returns
-------
list
List of lists of remaining prime factor decompositions, with single elements removed from each sublist.
"""
element_list = list(itertools.chain.from_iterable(remaining))
counts = collections.Counter(element_list)
solo_elements = [key for key, value in counts.items()
if value == 1]
for decomposition in range(len(remaining)):
if (
any(element in solo_elements for element in remaining[decomposition])
and (not all(element in solo_elements for element in remaining[decomposition]))
):
remaining[decomposition] = [i for i in remaining[decomposition]
if i not in solo_elements]
return remaining
def solution_reduction(
remaining,
sols,
text,
):
"""Run the solution space reduction steps on remaining.
Parameters
----------
remaining : list
List of lists of remaining decompositions to check if sols hit.
sols : list
List of integers that form an at least partial solution to MinHitSet algorithm.
text : bool
Set False to avoid printing any statements
Returns
-------
list
List of either lists or ints depending on whether the reduction is enough to solve the algorithm or not.
"""
if text:
print('checking if problem solved without need for chosen algorithm...\n')
if len(remaining) == 0:
if text:
print('\tMinHitSet complete! solution = {}'.format(sols))
return sols
else:
sols = check_for_single_remaining_sol(remaining, sols)
remaining = check_if_solved(remaining, sols)
if len(remaining) == 0:
if text:
print('\tMinHitSet complete! solution = {}'.format(sols))
return sols
else:
remaining = remove_single_elements(remaining)
return remaining
|
nums = [4,3,2,7,8,2,3,1]
nums = [1,1]
nums = [2,2]
max(nums)
min(nums)
if nums == []:
print([])
ans = []
for num in range(1, len(nums)+1):
if num not in nums:
ans.append(num)
print(ans)
def findDisappearedNumbers(nums):
if nums == []:
return []
ans = []
for num in range(1, len(nums) + 1):
if num not in nums:
ans.append(num)
return ans
findDisappearedNumbers(nums)
class Solution:
def findDisappearedNumbers(self, nums):
if nums == []:
return []
ans = []
for num in range(1, len(nums) + 1):
if num not in nums:
ans.append(num)
return ans
|
word = "Dsdfs"
if len(word) > 1:
if word == word.upper() or word[1:] == word[1:].lower():
print(True)
else:
print(False)
else:
print(True)
class Solution:
def detectCapitalUse(self, word: str) -> bool:
if len(word) > 1:
if word == word.upper() or word[1:] == word[1:].lower():
return True
else:
return False
else:
return True |
input_ints = [4, 1, 1, 1, 1, 2, 2, 2, 3, 3]
def findTopTwo(input_ints):
result = {}
for input_int in input_ints:
if input_int in result.keys():
result[input_int] += 1
else:
result[input_int] = 1
fst_freq = sorted(result.values())[-1]
snd_freq = sorted(result.values())[-2]
for key, value in result.items():
if value == fst_freq:
print(key)
elif value == snd_freq:
print(key)
findTopTwo(input_ints)
|
bills = [5,5,5,10,20]
bills = [5,5,10]
bills = [10,10]
bills = [5,5,10,10,20]
check = True
wallet = {5:0, 10:0, 20:0}
for bill in bills:
if bill == 5:
wallet[bill] += 1
elif bill == 10:
if wallet[5] > 0:
wallet[5] -= 1
wallet[bill] += 1
else:
check = False
else:
if wallet[10]>0 and wallet[5]>0:
wallet[5] -= 1
wallet[10] -= 1
wallet[bill] += 1
elif wallet[5]>2:
wallet[5] -= 3
wallet[bill] += 1
else:
check = False
print(check)
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
check = True
wallet = {5: 0, 10: 0, 20: 0}
for bill in bills:
if bill == 5:
wallet[bill] += 1
elif bill == 10:
if wallet[5] > 0:
wallet[5] -= 1
wallet[bill] += 1
else:
check = False
else:
if wallet[10] > 0 and wallet[5] > 0:
wallet[5] -= 1
wallet[10] -= 1
wallet[bill] += 1
elif wallet[5] > 2:
wallet[5] -= 3
wallet[bill] += 1
else:
check = False
return check |
A = [1,2,5]
B = [2,4]
A = [1,1]
B = [2,2]
A = [1, 2]
B = [2, 3]
A = [2]
B = [1,3]
check = False
for itemA in A:
for itemB in B:
if sum(A)-itemA+itemB == sum(B)-itemB+itemA and check == False:
check = True
print([itemA, itemB])
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
check = False
for itemA in A:
for itemB in B:
if sum(A) - itemA + itemB == sum(B) - itemB + itemA and check == False:
check = True
return [itemA, itemB]
for item in A:
if item+(sum(B)-sum(A))/2 in set(B):
itemB =item+(sum(B)-sum(A))/2
print([item, int(itemB)])
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
for item in A:
if item + (sum(B) - sum(A)) / 2 in set(B):
itemB = item + (sum(B) - sum(A)) / 2
return [item, int(itemB)] |
A = [[1,2,3],[4,5,6]]
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
row = len(A)
col = len(A[0])
#print(row)
#print(col)
matrix = [[0 for x in range(row)] for y in range(col)]
#print(matrix)
for tcol, row in enumerate(A):
for trow, item in enumerate(row):
matrix[trow][tcol] = item
#print(matrix)
return matrix |
a = [5, 1, 6, 2]
print(a)
#This sorts the list, but the original list is untouched
print(sorted(a))
strs = ['aa', 'bb', 'zz', 'cc']
print(sorted(strs))
#you can customize the sorted function
#reverse = True means it will sort it in backwards
print(sorted(strs, reverse = True))
"""
Sorting with key
optional argument key
key takes 1 value and retruns 1 value
"""
#key = len --- this will calculate the length of the strings and then sort it
st= ['ccc', 'aaaa', 'd','bb']
print(sorted(st, key=len, reverse = True ))
"""
key = str.lower forces the sorting to treat
both uppercase and lowercase string as same
"""
"""
if you want to sort based on the last letter
create your function
and then assign it to key
def myfn(s):
retun s[-1]
"""
"""
List.sort() - doesn't return anything
Returns None
but it changes the underlying List
Sort - doesn't work on enumerations
Sorted - works on everything
"""
print(a.sort()) #doesn't work because sort function retruns None
print(a)
"""
TUPLE - fixed size .Same like lists but the size cannot be changed
Immutable - but not that strict
only the size cannot be changed
but the contents can be changed
"""
mytuple = (5, 8 , 'Hola')
print(mytuple)
print(len(mytuple))
print(mytuple[2])
mytuple = (1, 6, 'Hi')
print(mytuple)
#mytuple[2] = 'Hola' cannot be done.
|
import pandas as pd
reddit = pd.read_csv("/home/master/Projects/bil476/reddit.csv")
_input = 0
index = 101
pagenames = []
authors = []
titles = []
comments = []
targets = []
while (True):
pagename = reddit['pagename'][index]
author = reddit['author'][index]
title = reddit['title'][index]
comment = reddit['comment'][index]
print("\n=============\n", "index: " + str(index),"\npagename:\n", pagename, "\nauthor:\n",
author, "\ntitle:\n", title, "\ncomment:\n", comment)
_input = input("toxic? 1/0\n")
if(_input == "-1"):
break
pagenames.append(pagename)
authors.append(author)
titles.append(title)
comments.append(comment)
targets.append(_input)
index += 1
df = pd.DataFrame({'pagename': pagenames,
'author': authors,
'title': titles,
'target': targets})
df.to_csv('labeled_reddit.csv', index=False)
|
words = input("Enter the words of string:: ")
splitTheWords = words.split() #firstly spliting those words in list
NowReverseThoseWords = splitTheWords[::-1] #slicing the words in reverse order
NowJoinThoseReversedWords = ' '.join(NowReverseThoseWords) #joining those reversed words with a space between
print("Reverse Order Of Words are :: " , NowJoinThoseReversedWords) |
'''
Created on Feb 11, 2015
@author: daman
'''
import sys
from curses.ascii import isalnum
import re
def isRoman(s):
#tens character can be repeated up to 3 times
if re.search(r'I{4,}',s) or re.search(r'X{4,}',s) or re.search(r'C{4,}',s) or re.search(r'M{4,}',s):
#print 'error tens char issue'
print False
return
#fives characters cannot be repeated
if re.search(r'V{2,}', s) or re.search(r'L{2,}', s) or re.search(r'D{2,}', s):
#print 'error due to fives character'
print False
return
#certain chars cannot be present before others
if re.search(r'IC', s):
print False
return
l = re.findall('[IVXLCDM]+',s)
if len(l) == 1 and l[0] == s:
print 'True'
else:
print 'False'
def main():
inp = sys.stdin
isRoman(inp.readline().rstrip())
if __name__ == '__main__':
main() |
'''
Created on Jun 26, 2015
@author: damanjits
'''
import functools
from random import random
'''
https://codewords.recurse.com/issues/one/an-introduction-to-functional-programming
'''
def mapReduceFilter():
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},
{'name': 'Sam'}]
peopleWithHeight = list(filter(lambda x:'height' in x,people))
heightTotal = functools.reduce(lambda a,x:a+x['height'],
peopleWithHeight,
0)
print(heightTotal,heightTotal/len(peopleWithHeight))
'''
imperative version of car race program
'''
def carRaceNonFuncImperative():
time = 5
car_positions = [1, 1, 1]
while time:
# decrease time
time -= 1
print('')
for i in range(len(car_positions)):
# move car
if random() > 0.3:
car_positions[i] += 1
# draw car
print('-' * car_positions[i])
'''
declarative version of car race program
'''
def carRaceNonFuncDeclarative():
def move_cars():
for i, _ in enumerate(car_positions):
if random() > 0.3:
car_positions[i] += 1
def draw_car(car_position):
print('-' * car_position)
def run_step_of_race():
global time
time -= 1
move_cars()
def draw():
print('')
for car_position in car_positions:
draw_car(car_position)
time = 5
car_positions = [1, 1, 1]
while time:
run_step_of_race()
draw()
'''
functional version of car race program
'''
def carRaceFunctional():
def move_cars(car_positions):
return map(lambda x: x + 1 if random() > 0.3 else x,
car_positions)
def output_car(car_position):
return '-' * car_position
def run_step_of_race(state):
return {'time': state['time'] - 1,
'car_positions': move_cars(state['car_positions'])}
def draw(state):
print('')
print('\n'.join(map(output_car, state['car_positions'])))
def race(state):
draw(state)
if state['time']:
race(run_step_of_race(state))
race({'time': 5,
'car_positions': [1, 1, 1]})
'''
Use of pipe lines
'''
'''Initial imperative code'''
bands = [{'name': 'sunset rubdown', 'country': 'UK', 'active': False},
{'name': 'women', 'country': 'Germany', 'active': False},
{'name': 'a silver mt. zion', 'country': 'Spain', 'active': True}]
def wihoutPipelines():
def format_bands(bands):
for band in bands:
band['country'] = 'Canada'
band['name'] = band['name'].replace('.', '')
band['name'] = band['name'].title()
format_bands(bands)
print(bands)
'''
with pipelines
'''
def withPipelines():
def pipeline_each(data, fns):
return functools.reduce(lambda a, x: map(x, a),
fns,
data)
def assoc(_d, key, value):
from copy import deepcopy
d = deepcopy(_d)
d[key] = value
return d
def call(fn, key):
def apply_fn(record):
return assoc(record, key, fn(record.get(key)))
return apply_fn
print(pipeline_each(bands, [call(lambda x: 'Canada', 'country'),
call(lambda x: x.replace('.', ''), 'name'),
call(str.title, 'name')]))
tuple([1,2,3,4])
if __name__ == '__main__':
mapReduceFilter()
|
from byotest import *
usd_coins = [100, 50, 20, 10, 5, 1]
eur_coins = [100, 50, 20, 10, 5, 2, 1]
# Function 1
def get_change(amount, coins=eur_coins):
change = []
for coin in coins:
while coin <= amount: # Change is always going to be less, or in rare occasions, equal to amount spent
amount -= coin # Required to ensure the code deducts the amount of the coin from what was sent into the vending machine
change.append(coin)
return change
# Test 1 = When the amount of chnage we require is zero, then no coins are returned back
test_are_equal(get_change(0),[])
# Test 2 = The money required is represented by a single coin. Test is passed by creating if statement for Test 1, then return [1] for Test 2.
test_are_equal(get_change(1),[1])
# Test 3 = To send in a different coin to the vending machine. Test is passed by changing 'return [1] to return [amount]'.
# The Tests are now repeated to cover all coin values.
test_are_equal(get_change(2),[2])
test_are_equal(get_change(5),[5])
test_are_equal(get_change(10),[10])
test_are_equal(get_change(20),[20])
test_are_equal(get_change(50),[50])
test_are_equal(get_change(100),[100])
# Test 4 = Create a test where we need change in more than 1 coin. Below = 3p change, in 2p + 1p.
test_are_equal(get_change(3),[2,1])
# Test 5 = Similar to Test 4. However, need to create a generic code and ensure correct change is given from valuie sent into machine.
test_are_equal(get_change(7),[5,2])
# Test 6 = Create a test to check where we require more than 1 of a perticular denomination of coin.
test_are_equal(get_change(9),[5,2,2])
# Test 7 = Override current coin denominations
test_are_equal(get_change(35, usd_coins),[25,10])
print("All tests pass!")
|
a = int(input('a:'))
b = int(input('b:'))
c = int(input('c:'))
#1) Если нет ни одного 0, вывести "Нет нулевых значений"
x1 = bool(a) and bool(b) and bool(c) and "Нет нулевых значений!!!"
print(x1)
#2) Вывести первое нулевое значение. Если все нули, то "Введены все нули!"
x2 = a or b or c or "Введены все нули!"
print(x2)
#3)Если первое значение больше чем сумма второго и третьего, вывести a-b-c.
if a > (b + c):
print(a-b-c)
#4)Если первое значение меньше чем сумма второго и третьего, вывести b+c-a.
elif a < (b+c):
print(b+c-a)
#5) Если первое значение больше 50 и при этом одно из оставшихся значений больше первого, вывести "Вася"
if a > 50 and (b > a or c > a):
print("Вася")
#6) Если первое значение больше 5 или оба из оставшихся значений равны 7, вывести "Петя"
if a > 5 or (b==7 and c==7):
print("Петя")
|
import time
class TimerHandler:
def __init__(self):
self.current_timestamp = None
self.duration_unit = None
self.duration_unit_div = None
self.duration_length = None
self.duration_interval = None
# Setting functions
def set_timestamp(self):
self.current_timestamp = time.time()
def set_timer_settings(self, duration_unit, duration_length):
self.duration_unit = duration_unit
self.duration_length = duration_length
if duration_unit == 'second':
self.duration_unit_div = 1
elif duration_unit == 'minute':
self.duration_unit_div = 60
elif duration_unit == 'hour':
self.duration_unit_div = 60 * 60
self.duration_interval = self.duration_unit_div * self.duration_length
# Logic functions
def check_timer(self):
if self.current_timestamp is None:
self.set_timestamp()
return True, 0
time_diff = divmod((time.time() - self.current_timestamp), self.duration_interval)
if time_diff[0] > 0:
return True, time_diff[1]
else:
return False, time_diff[1]
|
# -*- coding:utf-8 -*-
# single process multi thread (spmt)
import threading
from time import ctime, sleep
class Entertainment:
def music(self, name):
for i in xrange(10):
print "%s listen music %s" % (ctime(), name)
sleep(1)
def movie(self, name):
for i in xrange(10):
print "%s watch movie %s" % (ctime(), name)
sleep(1)
if "__main__" == __name__:
entertainment = Entertainment()
threads = []
thread1 = threading.Thread(target=entertainment.music, args=("光辉岁月",))
threads.append(thread1)
thread2 = threading.Thread(target=entertainment.movie, args=("Avengers",))
threads.append(thread2)
for t in threads:
# t.setDaemon()用于设置守护线程
# 守护线程如果为True,则主线程不等待子线程结束即结束整个程序
# 守护线程如果为False,则主线程需要等待子线程结束才结束整个程序
# t.setDaemon(False)
t.start()
for t in threads:
# t.join()可以等待对应的子线程执行完才继续执行
t.join()
print "All threads end!!!"
|
class Point3D:
"""Class which stores point coordinates. All other structure objects from geometry module use one or more Point3D objects to build the structure."""
def __init__(self, x, y, z = None):
"""Class constructor for Point3D object. As a param it takes coordinates of the point. If z coordinate is not provided it is set to 0.0 by default"""
self.x = x
self.y = y
if z is None:
self.z = 0.0
else:
self.z = z
class Vertex:
"""Class which provides internal application format for vertex structure. Objects consist of Point3D point and properties: quality, label and groupId"""
def __init__(self, point):
"""Class constructor for Vertex object. As a param it takes Point3D object point"""
self.point = point
self.quality = 0.0
self.label = ""
self.groupId = 0
class Edge:
"""Class which provides internal application format for line structure. Objects consist of two Point3D points and properties: quality, label and groupId."""
def __init__(self, v1, v2):
"""Class constructor for Edge object. As a param it takes two Point3D objects v1 and v2"""
self.v1 = v1
self.v2 = v2
self.quality = 0.0
self.label = ""
self.groupId = 0
class TriangleFace:
""" Class which provides internal application format for face structure. Objects consist of three Point3D points and properties: quality, label and groupId."""
def __init__(self, v1, v2, v3):
"""Class constructor for TriangleFace object. As a param it takes three Point3D objects v1, v2 and v3"""
self.v1 = v1
self.v2 = v2
self.v3 = v3
self.quality = 0.0
self.label = ""
self.groupId = 0
class Block:
"""Class which provides internal application format for vertex structure. Objects consist of Point3D point and properties: quality, label and groupId"""
def __init__(self, v1, v2, v3, v4):
"""Class constructor for Block object. As a param it takes four Point3D objects v1, v2, v3 and v4"""
self.v1 = v1
self.v2 = v2
self.v3 = v3
self.v4 = v4
self.quality = 0.0
self.label = ""
self.groupId = 0
|
class Parent:
def __init__(self):
print("this is the parent class")
def parentFunc(self):
print("this is the parent func")
def test(self):
print("Parent")
class Child(Parent):
def __init__(self):
print("this is the Child class")
def childFunc(self):
print("this is the child func")
def test(self):
print("child")
p = Parent()
c = Child()
c.parentFunc()
c.test()
|
# #If the numbers 1 to 5 are written out in words: one, two, three, four, five, then
# there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
# how many letters would be used?
#
#
# NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)
# contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of
# "and" when writing out numbers is in compliance with British usage.
# Solution: Self-evident
digits = len('onetwothreefourfivesixseveneightnine')
tentonineteen = len('teneleventwelvethirteenfourteenfifteensixteenseventeeneighteennineteen')
tens = len('twentythirtyfortyfiftysixtyseventyeightyninety')
hundred = len('hundred')
thousand = len('onethousand')
_and = len('and')
one_to_99 = digits+tentonineteen+10*tens+8*digits
print 100*digits + 900*hundred + 891*_and + 10*one_to_99 + thousand |
import gym
import random
import pandas
import argparse
import numpy as np
import matplotlib.pyplot as plt
class QLearn:
def __init__(self, actions, epsilon, alpha, gamma):
self.q = {}
self.epsilon = epsilon # exploration constant
self.alpha = alpha # discount constant
self.gamma = gamma # discount factor
self.actions = actions
def getQ(self, state, action):
return self.q.get((state, action), 0.0)
def learnQ(self, state, action, reward, value):
'''
Q-learning:
Q(s, a) += alpha * (reward(s,a) + max(Q(s') - Q(s,a))
'''
oldv = self.q.get((state, action), None)
if oldv is None:
self.q[(state, action)] = reward
else:
self.q[(state, action)] = oldv + self.alpha * (value - oldv)
def chooseAction(self, state, return_q=False):
q = [self.getQ(state, a) for a in self.actions]
maxQ = max(q)
if random.random() < self.epsilon:
minQ = min(q);
mag = max(abs(minQ), abs(maxQ))
# add random values to all the actions, recalculate maxQ
q = [q[i] + random.random() * mag - .5 * mag for i in range(len(self.actions))]
maxQ = max(q)
count = q.count(maxQ)
# In case there're several state-action max values
# we select a random one among them
if count > 1:
best = [i for i in range(len(self.actions)) if q[i] == maxQ]
i = random.choice(best)
else:
i = q.index(maxQ)
action = self.actions[i]
if return_q: # if they want it, give it!
return action, q
return action
def learn(self, state1, action1, reward, state2):
maxqnew = max([self.getQ(state2, a) for a in self.actions])
self.learnQ(state1, action1, reward, reward + self.gamma * maxqnew)
def build_state(features):
return int("".join(map(lambda feature: str(int(feature)), features)))
def to_bin(value, bins):
return np.digitize(x=[value], bins=bins)[0]
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Q-Learning Demo')
parser.add_argument('-n', '--nepisodes', type=int, default=1500,
help='number of episodes to train agent')
parser.add_argument('-p', '--plotfreq', type=int, default=150,
help='frequency of rendering game')
args = parser.parse_args()
env = gym.make('CartPole-v0')
plot_freq = args.plotfreq
n_episodes = args.nepisodes
n_bins = 10
n_bins_angle = 10
goal_average_steps = 195
max_number_of_steps = 300
number_of_features = env.observation_space.shape[0]
last_time_steps = np.ndarray(0)
# number of states is huge so in order to simplify the situation
# we discretize the space to: 10 ** number_of_features
cart_position_bins = pandas.cut([-2.4, 2.4], bins=n_bins, retbins=True)[1][1:-1]
pole_angle_bins = pandas.cut([-2, 2], bins=n_bins_angle, retbins=True)[1][1:-1]
cart_velocity_bins = pandas.cut([-1, 1], bins=n_bins, retbins=True)[1][1:-1]
angle_rate_bins = pandas.cut([-3.5, 3.5], bins=n_bins_angle, retbins=True)[1][1:-1]
# q-learn algorithm
qlearn = QLearn(actions=range(env.action_space.n),
alpha=0.5, gamma=0.90, epsilon=0.1)
for i_episode in range(n_episodes):
observation = env.reset()
cart_position, pole_angle, cart_velocity, angle_rate_of_change = observation
# obtain initial state
state = build_state([to_bin(cart_position, cart_position_bins),
to_bin(pole_angle, pole_angle_bins),
to_bin(cart_velocity, cart_velocity_bins),
to_bin(angle_rate_of_change, angle_rate_bins)])
for t in range(max_number_of_steps):
if i_episode % plot_freq == 0:
env.render()
# pick an action based on the current state
action = qlearn.chooseAction(state)
# execute the action and get feedback
observation, reward, done, info = env.step(action)
# digitize the observation to get a state
cart_position, pole_angle, cart_velocity, angle_rate_of_change = observation
# obtain next state
nextState = build_state([to_bin(cart_position, cart_position_bins),
to_bin(pole_angle, pole_angle_bins),
to_bin(cart_velocity, cart_velocity_bins),
to_bin(angle_rate_of_change, angle_rate_bins)])
# perform q-learning
if not done:
qlearn.learn(state, action, reward, nextState)
state = nextState
else:
reward = -200
qlearn.learn(state, action, reward, nextState)
last_time_steps = np.append(last_time_steps, [int(t + 1)])
print(f'Episode: {i_episode}, Duration: {int(t+1)}')
break
env.close()
print(f'Overall score: {last_time_steps.mean()}')
def smooth(y, box_pts):
box = np.ones(box_pts) / box_pts
y_smooth = np.convolve(y, box, mode='same')
return y_smooth
last_time_smooth = smooth(last_time_steps, 20)
plt.figure()
plt.plot(last_time_steps, label='Q-Learning')
plt.plot(last_time_smooth, label='Q-Learning Smooth')
plt.ylabel('Episode Reward')
plt.xlabel('Episode #')
plt.legend()
plt.show()
|
name_of_user = input("Можете ввести свое имя: ")
surname_of_user = input("Можете ввести свою фамилию: ")
def get_name(name, surname):
print("Добрый день", name.title() +" "+ surname.title())
get_name(name_of_user, surname_of_user) |
#теперь мы можем попробовать считать файл с except
# filename = 'file.txt'
filename = 'file1.txt'
try:
with open(filename) as file:
content = file.read()
print(content)
except FileNotFoundError:
message = "Извиняйте, файл " + filename + " не существует"
print(message)
|
# дополнительная программа Python
import random
flag = input("Вы хотите поиграть в русскую рулетку? Введите да/нет: ")
baraban = [0, 0, 0, 0, 0, 0]
bullet_amount = 1
def try_play(bullet_amount):
# print("В револьвере " + str(bullet_amount) + " патрон")
print(bullet_amount)
for i in range(1, bullet_amount):
baraban[i] = 1
random.shuffle(baraban)
if baraban[0] == 1:
print(baraban)
print("Бабах")
else:
print("щелчок")
second_flag = input("Вы хотите поиграть ещё? Введите да/нет: ")
if second_flag == "да":
bullet_amount += 1
try_play(bullet_amount)
else:
return
if (flag == "да"):
try_play(bullet_amount)
else:
print("Ну и ладно") |
from survey import AnonymousSurvey
# Определяет вопрос, и сохраняет все вопросы
question = "Какой язык вы хотите изучить первым?"
my_survey = AnonymousSurvey(question)
# показывает вопрос и сохраняет ответ
my_survey.show_question()
print("Введите 'q' для окончания работы программы\n")
while True:
response = input("Язык: \n")
if response == 'q':
break
my_survey.store_response(response)
# Показывает результаты опроса
print("\n Спасибо за участие в этом опросе")
my_survey.show_results()
|
person = {'names':[], 'surnames': []}
def create_person(name, surname):
"""Возвращает словарь с информацией о человеке"""
person['names'].append(name)
person['surnames'].append(surname)
return person
user_size = int(input("Введите количество пользователей, которые должны появиться в этом словаре: "))
for user in range(user_size):
name = input("Введите имя пользователя")
surname = input("Введите фамилию пользователя")
create_person(name, surname)
print(person)
|
# мне она нравится тем, что существует огромная масса вариантов, как это можно написать и сделать
# давайте напишем несложнуую программу русской рулетки
# к примеру:
import random
amount_of_bullets = input(
'Сколько патронов вы собираетесь вставить в револьвер?')
aob = int(amount_of_bullets)
baraban = [0, 0, 0, 0, 0, 0]
for i in range(aob):
baraban[i] = 1
print("Посмотрите на барабан", baraban)
How_much = input("сколько раз вы собираетесь нажимать на курок?")
hm = int(How_much)
for i in range(hm):
random.shuffle(baraban)
print(baraban[0])
|
#!/usr/bin/python
# checkDuplicates.py
# Python 2.7.6
"""
Given a folder, walk through all files within the folder and subfolders
and get list of all files that are duplicates
The md5 checcksum for each file will determine the duplicates.
Then display dupes and give options to delete specified files.
"""
import os
import hashlib
from collections import defaultdict
import csv
src_folder = "/Users/benc/Documents/VIDEO_DUMP/TEST_DUPES"
class DeleteDuplicates:
def __init__(self, src_folder):
self.src_folder = src_folder
self.duplicate_files = None
self.deleted_dupes = None
def generate_md5(self, fname, chunk_size=1024):
"""
Function which takes a file name and returns md5 checksum of the file
"""
print fname
hash = hashlib.md5()
with open(fname, "rb") as f:
# Read the 1st block of the file
chunk = f.read(chunk_size)
# Keep reading the file until the end and update hash
while chunk:
hash.update(chunk)
chunk = f.read(chunk_size)
# Return the hex checksum
return hash.hexdigest()
def find_dupes(self):
# The dict will have a list as values
md5_dict = defaultdict(list)
file_types_inscope = ["ppt", "pptx", "pdf", "txt", "html",
"mp4", "jpg", "png", "xls", "xlsx", "xml",
"vsd", "py", "json", "ari", "ale"]
# Walk through all files and folders within directory
for path, dirs, files in os.walk(self.src_folder):
print("Analyzing {}".format(path))
for each_file in files:
if each_file.rsplit(".", 1)[-1].lower() in file_types_inscope:
# The path variable gets updated for each subfolder
file_path = os.path.join(os.path.abspath(path), each_file)
print file_path
# If there are more files with same checksum append to list
md5_dict[self.generate_md5(file_path)].append(file_path)
# Identify keys (checksum) having more than one values (file names)
self.duplicate_files = [
val for key, val in md5_dict.items() if len(val) > 1]
return self.duplicate_files
def delete_dupes_ui(self):
#. THIS IS THE USER INTERFACE TO DISPLAY & DELETE DUPES
self.deleted_dupes = []
os.system('clear')
if self.duplicate_files:
print "\nThe following files are duplicates:\n"
for dup in self.duplicate_files:
print dup[0][str(dup[0]).rfind("/")+1:]
## Print each duplicate and ask which copies to delete
for dup in self.duplicate_files:
print "\n\n" + "*" * 50 + "\n\nFILE: " + (dup[0])[str(dup[0]).rfind("/")+1:]
c = 1
tmp_dupes = {}
for i in dup:
print str(c) + " - " + i
tmp_dupes[str(c)] = i
c += 1
print "\n"
ans = True
while ans and len(tmp_dupes) > 1:
print "Which files would you like to delete? Press ENTER to finish and move to next duplicate."
resp = raw_input(": ")
if resp == "":
ans = False
elif tmp_dupes[resp]:
os.remove(tmp_dupes[resp])
print "\nDeleting: " + tmp_dupes[resp] + "\n"
self.deleted_dupes.append(tmp_dupes[resp])
tmp_dupes.pop(resp)
else:
print "Invalid entry. Please try again."
## Print the files which have been deleted
if self.deleted_dupes:
print "*" * 50 + "\nDeleted Duplicates: \n"
for i in self.deleted_dupes:
print i
print "\n"
else:
print "No files deleted.\n\n"
else:
print "\nNo duplicates found.\n\n"
def getValue(self, x):
a,_,b = x.partition(" ")
if not b.isdigit():
return (float("inf"), x)
return (a, int(b))
def make_dupes_csv(self):
# Write the list of duplicate files to csv file
with open("duplicates.csv", "w") as log:
# Lineterminator added for windows as it inserts blank rows otherwise
csv_writer = csv.writer(log, quoting=csv.QUOTE_MINIMAL, delimiter=",",
lineterminator="\n")
header = ["File Names"]
csv_writer.writerow(header)
for file_name in duplicate_files:
csv_writer.writerow(file_name)
def check_duplicates(self):
self.find_dupes()
self.delete_dupes_ui()
# print "\nThe following duplicates were deleted: "
# for i in self.delete_dupes:
# print self.delete_dupes[i]
if __name__ == "__main__":
DeleteDuplicates(src_folder).check_duplicates()
|
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'Chicago': 'chicago.csv',
'New York City': 'new_york_city.csv',
'Washington': 'washington.csv' }
def get_filters():
print('Hello! Let\'s explore some US bikeshare data!')
while True:
city = input('1. Which city would you like to explore? Chicago, New york City or Washington?').title().strip()
if city != 'Chicago' and city != 'New York City' and city != 'Washington':
print("Data type not found, try again.")
else:
break
while True:
month = input('2. What month? (Type from Ja, Fe, Ma, Ap, My, Ju or All)')
month = month.title().strip()
if month != 'Ja' and month != 'Fe' and month != 'Ma' and month != 'Ap' and month != 'My' and month != 'Ju' and month != 'All':
print("Please use the specified format.")
else:
break
while True:
day = input('3. And which day? (Type from Saturday, Sunday, Monday, Tuesday, Wednesday Thursday, Friday or All)')
day = day.title().strip()
if day != 'Sunday' and day != 'Monday' and day != 'Tuesday' and day != 'Wednesday' and day != 'Thursday' and day != 'Friday' and day != 'Saturday' and day != 'All':
print("Please use the specified format.")
else:
break
print('-'*40)
return city, month, day
def load_data(city, month, day):
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
if month != 'All':
months = ['Ja', 'Fe', 'Ma', 'Ap', 'My', 'Ju']
month = months.index(month) + 1
df = df[df['month'] == month]
if day != 'All':
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
print('\n 1.Calculating The Most Frequent Times of Travel...\n')
start_time = time.time()
pop_m = df['month'].mode()[0]
print('a) Popular Month - ', pop_m)
pop_d= df['day_of_week'].mode()[0]
print('b) Popular Day - ', pop_d)
pop_h = df['hour'].mode()[0]
print('c) Popular Hour - ', pop_h)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
print('\n 2.Calculating The Most Popular Stations and Trips...\n')
start_time = time.time()
pop_ss = df['Start Station'].mode()[0]
print("a) Popular Start Station - ", pop_ss)
pop_es = df['End Station'].mode()[0]
print("b) Popular End Station - ", pop_es)
grouped = df.groupby(['Start Station','End Station'])
pop_combo = grouped.size().nlargest(1)
print("c) Popular Combined Statitons - ", pop_combo)
print('-'*40)
def trip_duration_stats(df):
print('\n 3.Calculating Trip Duration...\n')
start_time = time.time()
tt = df['Trip Duration'].sum()
print('a) Total Time Travelled - ', tt)
mean_tt = df['Trip Duration'].mean()
print('b) Mean of Time Travelled - ', mean_tt)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df, city):
print('\n 4.Calculating User Stats...\n')
start_time = time.time()
print('a) Stats According to User Type - ')
print(df['User Type'].value_counts())
if city == 'Washington':
print("No Gender or Birth Data for this city.")
else:
gender = df['Gender'].value_counts()
print(gender)
print('b) Stats according to Birth Years - ')
pop_yr = df['Birth Year'].mode()[0]
print('c) Popular Date of Births - ',pop_yr)
rec_year = df['Birth Year'].max()
print('d) Recent Year - ', rec_year)
ear_year = df['Birth Year'].min()
print('e) Earliest Year - ', ear_year)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
return df,city
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df, city)
print('-'*40)
raw = input('Would you like to view the raw data? yes/no').lower().strip()
raw_data = 0
y = 5
while (raw == 'yes'):
x = df.iloc[raw_data : y]
print(x)
raw_data += 5
y += 5
raw = input('Would you like to view some more?').lower().strip()
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
# --(NumPy Array Example)--------------------------------------------------------
"""
This lesson demonstrates how the **TabularEditor** can be used to display
(large) NumPy arrays. In this example, the array consists of 100,000 random 3D
points from a unit cube.
In addition to showing the coordinates of each point, the example code also
displays the index of each point in the array, as well as a red flag if the
point lies within 0.25 of the center of the cube.
As with the other tabular editor tutorials, this example shows how to set up a
**TabularEditor** and create an appropriate **TabularAdapter** subclass.
In this case, it also shows:
- An example of using array indices as *column_id* values.
- Using the *format* trait to format the numeric values for display.
- Creating a *synthetic* index column for displaying the point's array index
(the *index_text* property), as well as a flag image for points close to the
cube's center (the *index_image* property).
"""
from builtins import str
#--<Imports>--------------------------------------------------------------------
from os.path \
import join, dirname
from numpy \
import sqrt
from numpy.random \
import random
from enthought.traits.api \
import HasTraits, Property, Array
from enthought.traits.ui.api \
import View, Item, TabularEditor
from enthought.traits.ui.tabular_adapter \
import TabularAdapter
from enthought.traits.ui.menu \
import NoButtons
from enthought.pyface.image_resource \
import ImageResource
#--<Constants>------------------------------------------------------------------
# Necessary because of the dynamic way in which the demos are loaded:
import enthought.traits.ui.api
search_path = [join(dirname(enthought.traits.ui.api.__file__),
'demo', 'Advanced')]
#--[Tabular Adapter Definition]-------------------------------------------------
class ArrayAdapter(TabularAdapter):
columns = [( 'i', 'index' ), ( 'x', 0 ), ( 'y', 1 ), ( 'z', 2 )]
font = 'Courier 10'
alignment = 'right'
format = '%.4f'
index_text = Property
index_image = Property
def _get_index_text(self):
return str(self.row)
def _get_index_image(self):
x, y, z = self.item
if sqrt((x - 0.5) ** 2 + (y - 0.5) ** 2 + (z - 0.5) ** 2) <= 0.25:
return 'red_flag'
return None
#--[Tabular Editor Definition]--------------------------------------------------
tabular_editor = TabularEditor(
adapter=ArrayAdapter(),
images=[ImageResource('red_flag', search_path=search_path)]
)
#--[ShowArray Class]------------------------------------------------------------
class ShowArray(HasTraits):
data = Array
view = View(
Item('data', editor=tabular_editor, show_label=False),
title='Array Viewer',
width=0.3,
height=0.8,
resizable=True,
buttons=NoButtons
)
#--[Example Code*]--------------------------------------------------------------
demo = ShowArray(data=random(( 100000, 3 )))
|
# Try it yourself, page 178
class Users:
"""Making a class for user profiles."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
self.login_attempts = 0
def describe_user(self):
"""Print a description of the user"""
print("\n" + self.first_name + " " + self.last_name)
print("Username: " + self.username)
print("Email: " + self.email)
print("Location: " + self.location)
def greet_user(self):
"""Prints a greeting to the user"""
print("Welcome, " + self.username + "!")
def increment_login_attempts(self):
"""Incrementing the value of login attempts by 1."""
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(Users):
"""Making a class for administrators"""
def __init__(self, first_name, last_name, username, email, location):
"""Initializing aspects of the administrators"""
super().__init__(first_name, last_name, username, email, location)
self.privileges = []
def show_privileges(self):
"""Prints privileges an admin has."""
print("An admin has a set of privileges that can do any of the following:")
for privilege in self.privileges:
print(privilege)
administer = Admin('blaine', 'west', 'man in charge', 'bwest@bullshit.com', 'denver')
administer.privileges = ['can add post', 'can delete post', 'can ban user', 'can change your name to something silly']
administer.describe_user()
administer.greet_user()
administer.show_privileges()
|
# try it yourself, page 64
numbers = []
for value in range(1, 11):
numbers.append(value**3)
for value in numbers:
print(value)
|
# Try it yourself, page 102
favorite_numbers = {
'blaine' : 6,
'sally' : 42,
'austin' : 14,
'phil' : 7,
'lee' : 9,
}
print("Blaine's favorite number is " + str(favorite_numbers['blaine']) + ".")
print("Sally's favorite number is " + str(favorite_numbers['sally']) + ".")
print("Austin's favorite number is " + str(favorite_numbers['austin']) + ".")
print("Phil's favorite number is " + str(favorite_numbers['phil']) + ".")
print("Lee's favorite number is " + str(favorite_numbers['lee']) + ".")
|
# Try it yourself, page 171
class Restaurant():
"""A simple attempt to model a restaurant."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and cuisine type"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""Prints a message describing the name and cuisine of the restaurant"""
print(self.restaurant_name.title() + " is a " + self.cuisine_type.title() + " style restaurant.")
def open_restaurant(self):
"""Message stating the restaurant is open"""
print(self.restaurant_name.title() + " is currently open!")
def set_number_served(self, served):
"""Sets the number of customers that have been served"""
self.number_served = served
print("Customers served: " + str(self.number_served))
def increment_number_served(self, additional_served):
"""Increments the total customers served"""
self.number_served += additional_served
restaurant = Restaurant('pizza hut', 'pizza')
print(restaurant.number_served)
restaurant.number_served = 13
print(restaurant.number_served)
print("\n")
restaurant.set_number_served(425)
print("\n")
restaurant.increment_number_served(127)
print(restaurant.number_served)
|
# Try it yourself, page 146
def city_country(city, country):
"""Return a string like 'Santiago, Chile'"""
return(city.title() + ", " + country.title()) # instead of doing full_name = first_name + " " + last_name
city = city_country('san diego', 'united states')
print(city)
city = city_country('beijing', 'china')
print(city)
city = city_country('moscow', 'russia')
print(city)
|
# Try it yourself, page 141
print("\n")
def make_shirt(size = 'L', message = 'I Love Python'):
"""Making a shirt"""
print("Shirt size: " + size)
print("Shirt message: " + message)
make_shirt()
print("\n\n")
make_shirt(size = 'M')
print("\n\n")
make_shirt(size = 'S', message = "THIS DOESN'T FIT")
print("\n")
make_shirt('XS', "It's a shirt for ants!")
|
# sorting a list permanently with the sort() method
cars = ['bmw', 'audi', 'toyota', 'suburu']
cars.sort()
print(cars)
print("\n")
# sorting in reverse alphabetical order..
cars = ['bmw', 'audi', 'toyota', 'suburu']
cars.sort(reverse = True)
print(cars)
print("\n")
# you can sort a list temporarily and maintain the original order of the list using the sorted() method
cars = ['bmw', 'audi', 'toyota', 'suburu']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the list in reverse alphabetical order:")
print(sorted(cars, reverse = True))
print("\nHere is the original list again:")
print(cars)
print("\n")
# printing the list in a reverse order..
cars = ['bmw', 'audi', 'toyota', 'suburu']
print(cars)
cars.reverse() # you can always reverse the order again to go back to the original order
print(cars)
print("\n")
# to find the length of a list use the len() function
cars = ['bmw', 'audi', 'toyota', 'suburu']
print(len(cars))
|
# You can also use a dictionary to store different kinds of information about one object
favorite_languages = {'jen' : 'python', 'sarah': 'c', 'edward' : 'ruby', 'phil' : 'python'}
# When you know a dictionary is going to take up more than one line... write it as so...
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")
# To break up a long print statement in to a bunch of lines you can do like so...
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".")
print('\n')
# Looping through the dictionary
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
for name, language in favorite_languages.items():
print("\nName: " + name.title())
print("Language: " + language.title())
print("\n")
# or..
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
print("\n")
# Looping through all the keys in a dictionary when you don't need the key's value
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
for name in favorite_languages.keys():
print(name.title())
print("\n")
# or...
for name in favorite_languages: # works the same because looping through the keys is the default behavior in Python...
print(name) # ...when looping through a dictionary
print("\n")
# Accessing a value associated with any key you care about inside the loop by using a current key
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + ".")
# This example confused me. To print the value you use the dictionary name followed by name as the key in brackets
# Using the keys method to find out if a person was polled
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
if 'erin' not in favorite_languages.keys():
print("\nErin, please take our poll!")
print("\n")
# Looping through a dictionaries keys in order
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
print("\n")
# Looping through all the values stored in a dictionary without listing any of the keys
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values(): # This example doesn't check for repeats
print(language.title())
print("\n")
# To see each language chosen without repetition, we can use a 'set'
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()): # Shows no repetition in languages mentioned
print(language.title())
print("\n")
##################################################################
# Making a list inside a dictionary
favorite_languages = {
'jen' : ['python', 'ruby'],
'sarah' : ['c'],
'edward' : ['ruby', 'go'],
'phil' : ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() +"'s favorite languages are:")
for language in languages:
print("\t" + language.title())
print("\n")
#################################################################
# Just practicing here. Adding an if statement at the beginning of the for loop...
# To detect if a person likes more than one language or not, and then changing the text to fit
avorite_languages = {
'jen' : ['python', 'ruby'],
'sarah' : ['c'],
'edward' : ['ruby', 'go'],
'phil' : ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
if len(languages) > 1:
print("\n" + name.title() +"'s favorite languages are:")
else:
print("\n" + name.title() + "'s favorite language is:")
for language in languages:
print("\t" + language.title())
print("\n")
|
# printing only even numbers in a list
even_numbers = list(range(2, 11, 2)) # prints even numbers starting at 2 that increase by 2 until it reaches the final value of 11, hence the 2 after the 11
print(even_numbers)
|
# Try it yourself, page 186
from random import randint
class Die:
def __init__(self, sides=6):
"""Initializes the die."""
self.sides = sides
def roll_die(self):
"""Return a random number between 1 and the number of sides of the die."""
return randint(1, self.sides)
# Rolling a 6 sided die 10 times
my_dice = Die()
results = []
for roll_num in range(10):
result = my_dice.roll_die()
results.append(result)
print(results)
# Making a 10 sides die and rolling 10 times
dice2 = Die(sides=10)
results2 = []
for roll_num2 in range(10):
result2 = dice2.roll_die()
results2.append(result2)
print(results2)
# Making a 20 sided die and rolling 10 times
dice3 = Die(sides=20)
results3 = []
for roll_num3 in range(10):
result = dice3.roll_die()
results3.append(result)
print(results3)
|
# Try it yourself, page 166
class Users():
"""Making a class for user profiles."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
def describe_user(self):
"""Print a description of the user"""
print("\n" + self.first_name + " " + self.last_name)
print("Username: " + self.username)
print("Email: " + self.email)
print("Location: " + self.location)
def greet_user(self):
"""Prints a greeting to the user"""
print("Welcome, " + self.username + "!")
user_1 = Users('blaine', 'west', 'bwest', 'bwest@yahoo.com', 'denver')
user_2 = Users('broc', 'west', 'brocman', 'brocman@yahoo.com', 'denver')
user_3 = Users('tyrion', 'lannister', 'righthandman', 'bigman@gmail.com', 'dragonstone')
user_1.describe_user()
user_1.greet_user()
print("\n")
user_2.describe_user()
user_2.greet_user()
print("\n")
user_3.describe_user()
user_3.greet_user()
|
# Inheritance: If the class you're writing is a specialized version of another class you wrote...
# ...you can use inheritance. When one class inherits from another, it automatically takes on all the attributes...
# ...and methods of the first class. The original is called the Parent Class, the new is called the Child Class.
# The __init__ method for a child class
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year): # Because this example is mainly for the child class, I deleted all of the..
self.make = make # ...descriptions for the methods as to save room on my screen
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back the odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""Represents aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class"""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print("\n")
print(my_tesla.get_descriptive_name())
print("\n")
##################################################################################################################
# Defining attributes and methods for the child class:
# Adding an attribute batter_size and writing a method that prints the description of the battery
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year): # Because this example is mainly for the child class, I deleted all of the..
self.make = make # ...descriptions for the methods as to save room on my screen
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back the odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""Represents aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kwh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
print("\n")
###################################################################################################################
# Instances as attributes: Breaking large classes into smaller classes that work together when classes get lengthy
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year): # Because this example is mainly for the child class, I deleted all of the..
self.make = make # ...descriptions for the methods as to save room on my screen
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back the odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery:
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=70):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kwh battery.")
class ElectricCar(Car):
"""Represents aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery() # Looks at the instance my_tesla, finds its battery attribute, then calls the...
print("\n") # ...method describe_battery.
######################################################################################################################
# Add another method to Battery that reports the range of the car based on battery size
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year): # Because this example is mainly for the child class, I deleted all of the..
self.make = make # ...descriptions for the methods as to save room on my screen
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back the odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery:
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=70):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kwh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Represents aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
|
# Using arbitrary keyword arguments
# Sometimes you'll want to accept an arbitrary number of arguments, but you won't know ahead of time...
# ...what kind of information will be passed to the function
# In this example you know you'll get information about a user, but you're not sure what kind of info that will be
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
|
import util
import functools
class Labels:
"""
Labels describing the WumpusWorld
"""
WUMPUS = 'w'
TELEPORTER = 't'
POISON = 'p'
SAFE = 'o'
"""
Some sets for simpler checks
>>> if literal.label in Labels.DEADLY:
>>> # Don't go there!!!
"""
DEADLY = set([WUMPUS, POISON])
WTP = set([WUMPUS, POISON, TELEPORTER])
UNIQUE = set([WUMPUS, POISON, TELEPORTER, SAFE])
POISON_CHEMICALS = 'c'
TELEPORTER_GLOW = 'g'
WUMPUS_STENCH = 's'
INDICATORS = set([POISON_CHEMICALS, TELEPORTER_GLOW, WUMPUS_STENCH])
def stateWeight(state):
"""
To ensure consistency in exploring states, they will be sorted
according to a simple linear combination.
The maps will never be larger than 20x20, and therefore this
weighting will be consistent.
"""
x, y = state
return 20*x + y
@functools.total_ordering
class Literal:
"""
A literal is an atom or its negation
In this case, a literal represents if a certain state (x,y) is or is not
the location of GhostWumpus, or the poisoned pills.
"""
def __init__(self, label, state, negative=False):
"""
Set all values. Notice that the state is remembered twice - you
can use whichever representation suits you better.
"""
x,y = state
self.x = x
self.y = y
self.state = state
self.negative = negative
self.label = label
def __key(self):
"""
Return a unique key representing the literal at a given point
"""
return (self.x, self.y, self.negative, self.label)
def __hash__(self):
"""
Return the hash value - this operator overloads the hash(object) function.
"""
return hash(self.__key())
def __eq__(first, second):
"""
Check for equality - this operator overloads '=='
"""
return first.__key() == second.__key()
def __lt__(self, other):
"""
Less than check
by using @functools decorator, this is enough to infer ordering
"""
return stateWeight(self.state) < stateWeight(other.state)
def __str__(self):
"""
Overloading the str() operator - convert the object to a string
"""
if self.negative: return '~' + self.label
return self.label
def __repr__(self):
"""
Object representation, in this case a string
"""
return self.__str__()
def copy(self):
"""
Return a copy of the current literal
"""
return Literal(self.label, self.state, self.negative)
def negate(self):
"""
Return a new Literal containing the negation of the current one
"""
return Literal(self.label, self.state, not self.negative)
def isDeadly(self):
"""
Check if a literal represents a deadly state
"""
return self.label in labels.DEADLY
def isWTP(self):
"""
Check if a literal represents GhostWumpus, the Teleporter or
a poisoned pill
"""
return self.label in labels.WTP
def isSafe(self):
"""
Check if a literal represents a safe spot
"""
return self.label == Labels.SAFE
def isTeleporter(self):
"""
Check if a literal represents the teleporter
"""
return self.label == Labels.TELEPORTER
class Clause:
"""
A disjunction of finitely many unique literals.
The Clauses have to be in the CNF so that resolution can be applied to them. The code
was written assuming that the clauses are in CNF, and will not work otherwise.
A sample of instantiating a clause (~B v C):
>>> premise = Clause(set([Literal('b', (0, 0), True), Literal('c', (0, 0), False)]))
or; written more clearly
>>> LiteralNotB = Literal('b', (0, 0), True)
>>> LiteralC = Literal('c', (0, 0), False)
>>> premise = Clause(set([[LiteralNotB, LiteralC]]))
"""
def __init__(self, literals):
"""
The constructor for a clause. The clause assumes that the data passed
is an iterable (e.g., list, set), or a single literal in case of a unit clause.
In case of unit clauses, the Literal is wrapped in a list to be safely passed to
the set.
"""
if not type(literals) == set and not type(literals) == list:
self.literals = set([literals])
else:
self.literals = set(literals)
def isResolveableWith(self, otherClause):
"""
Check if a literal from the clause is resolveable by another clause -
if the other clause contains a negation of one of the literals.
e.g., (~A) and (A v ~B) are examples of two clauses containing opposite literals
"""
for literal in self.literals:
if literal.negate() in otherClause.literals:
return True
return False
def isRedundant(self, otherClauses):
"""
Check if a clause is a subset of another clause.
"""
for clause in otherClauses:
if self == clause: continue
if clause.literals.issubset(self.literals):
return True
return False
def negateAll(self):
"""
Negate all the literals in the clause to be used
as the supporting set for resolution.
"""
negations = set()
for literal in self.literals:
clause = Clause(literal.negate())
negations.add(clause)
return negations
def __str__(self):
"""
Overloading the str() operator - convert the object to a string
"""
return ' V '.join([str(literal) for literal in self.literals])
def __repr__(self):
"""
The representation of the object
"""
return self.__str__()
def __hash__(self):
"""
Return the hash value - this operator overloads the hash(object) function.
"""
return hash(tuple(self.literals))
def __eq__(self, other):
if other == 'NIL':
return tuple(self.literals) == 'NIL'
else:
return tuple(self.literals) == tuple(other.literals)
def resolution(clauses, goal):
"""
Implement refutation resolution.
The pseudocode for the algorithm of refutation resolution can be found
in the slides. The implementation here assumes you will use set of support
and simplification strategies. We urge you to go through the slides and
carefully design the code before implementing.
"""
resolvedPairs = set()
setOfSupport = goal.negateAll()
while True:
clauses = removeRedundant(clauses, setOfSupport)
selectedClauses = selectClauses(clauses, setOfSupport, resolvedPairs)
if len(selectedClauses) == 0:
return False
for pair in selectedClauses:
resolvents = resolvePair(pair[0], pair[1])
resolvedPairs.add(pair)
if resolvents == 'NIL':
return True
else:
setOfSupport.add(resolvents)
for x in setOfSupport:
clauses.add(x)
def removeRedundant(clauses, setOfSupport):
"""
Remove redundant clauses (clauses that are subsets of other clauses)
from the aforementioned sets.
Be careful not to do the operation in-place as you will modify the
original sets. (why?)
"""
newClauses = []
for clause in clauses:
if clause.isRedundant(setOfSupport):
continue
else:
newClauses.append(clause)
return set(newClauses)
def resolvePair(firstClause, secondClause):
""" Resolve a pair of clauses. """
literalsNew = set()
deleted = 0
for literal in firstClause.literals:
if literal.negate() in secondClause.literals:
if deleted<1:
deletedLiteral = literal.negate()
deleted += 1
continue
else:
literalsNew.add(literal)
else:
literalsNew.add(literal)
if deleted==1:
for literal in secondClause.literals:
if literal==deletedLiteral:
continue
else:
literalsNew.add(literal)
if len(literalsNew) == 0:
#print 'Resolving... {}, {} ==>> {}'.format(firstClause, secondClause, 'NIL')
return 'NIL'
else:
#print 'Resolving... {}, {} ==>> {}'.format(firstClause, secondClause, Clause(literalsNew))
return Clause(literalsNew)
def selectClauses(clauses, setOfSupport, resolvedPairs):
""" Select pairs of clauses to resolve. """
selectedClauses = set()
for goalClause in setOfSupport:
for otherClause in clauses:
if (goalClause, otherClause) not in resolvedPairs:
if goalClause.isResolveableWith(otherClause):
selectedClauses.add((goalClause, otherClause))
return selectedClauses
def testResolution():
"""
A sample of a resolution problem that should return True.
You should come up with your own tests in order to validate your code.
"""
"""
~a v b |
~b v c | premises
a |
--------+
c | goal (needs to be negated first)
"""
premise1 = Clause(set([Literal('a', (0, 0), True), Literal('b', (0, 0), False)]))
premise2 = Clause(set([Literal('b', (0, 0), True), Literal('c', (0, 0), False)]))
premise3 = Clause(Literal('a', (0,0)))
goal = Clause(Literal('c', (0,0)))
print resolution(set([premise1, premise2, premise3]), goal)
def testResolution2():
"""
Dipl. problem
u v ~t |
t v a | premises
~u v ~a |
--------+
~t v ~a | goal (needs to be negated first)
"""
premise1 = Clause(set([Literal('u', (0, 0), False), Literal('t', (0, 0), True)]))
premise2 = Clause(set([Literal('t', (0, 0), False), Literal('a', (0, 0), False)]))
premise3 = Clause(set([Literal('u', (0, 0), True), Literal('a', (0, 0), True)]))
goal = Clause(set([Literal('t', (0, 0), True), Literal('a', (0, 0), True)]))
print resolution(set([premise1, premise2, premise3]), goal)
def testResolution3():
"""
1.13 iz knjige
~p v q v r |
s v ~q | premises
s v ~r |
-----------+
~p | goal (needs to be negated first)
s |
"""
premise1 = Clause(set([Literal('p', (0, 0), True), Literal('q', (0, 0), False), Literal('r', (0, 0), False)]))
premise2 = Clause(set([Literal('s', (0, 0), False), Literal('q', (0, 0), True)]))
premise3 = Clause(set([Literal('s', (0, 0), False), Literal('r', (0, 0), True)]))
goal = Clause(set([Literal('p', (0, 0), True), Literal('s', (0, 0), False)]))
print resolution(set([premise1, premise2, premise3]), goal)
def testResolution4():
"""
~c v b |
~b v e | premises
~e v b |
c |
~d v ~e |
-----------+
~d | goal (needs to be negated first)
~a |
"""
premise1 = Clause(set([Literal('c', (0, 0), True), Literal('b', (0, 0), False)]))
premise2 = Clause(set([Literal('b', (0, 0), True), Literal('e', (0, 0), False)]))
premise3 = Clause(set([Literal('e', (0, 0), True), Literal('b', (0, 0), False)]))
premise4 = Clause(set([Literal('c', (0,0), False)]))
premise5 = Clause(set([Literal('d', (0, 0), True), Literal('e', (0, 0), True)]))
goal = Clause(set([Literal('d', (0, 0), True), Literal('a', (0, 0), True)]))
print resolution(set([premise1, premise2, premise3, premise4, premise5]), goal)
def testResolutionFalse1():
"""
Example with result false
~a v b |
~b v c | premises
a |
--------+
~c | goal (needs to be negated first)
"""
premise1 = Clause(set([Literal('a', (0, 0), True), Literal('b', (0, 0), False)]))
premise2 = Clause(set([Literal('b', (0, 0), True), Literal('c', (0, 0), False)]))
premise3 = Clause(Literal('a', (0,0)))
goal = Clause(Literal('c', (0,0), True))
print resolution(set([premise1, premise2, premise3]), goal)
def testResolution4KRIVO():
"""
A v B v C v D |
~A v ~B v ~C | premises
~D |
--------------+
D | goal (needs to be negated first)
"""
premise1 = Clause(set([Literal('A', (0,0), False), Literal('B', (0,0), False), Literal('C', (0,0), False), Literal('D', (0,0), False)]))
premise2 = Clause(set([Literal('A', (0,0), True), Literal('B', (0,0), True), Literal('C', (0,0), True)]))
premise3 = Clause(Literal('D', (0,0), True))
goal = Clause(Literal('D', (0,0)))
print resolution(set([premise1, premise2, premise3]), goal)
def testResolutionFact():
"""
~a v b |
~b v ~a | premises
--------+
~a | goal (needs to be negated first)
"""
premise1 = Clause(set([Literal('a', (0, 0), True), Literal('b', (0, 0), False)]))
premise2 = Clause(set([Literal('b', (0, 0), True), Literal('a', (0, 0), True)]))
goal = Clause(Literal('a', (0,0), True))
print resolution(set([premise1, premise2]), goal)
def testEleven():
"""
s ~i
~s a
~a
-----
~s
"""
premise1 = Clause(set([Literal('s', (0, 0), False), Literal('i', (0, 0), True)]))
premise2 = Clause(set([Literal('s', (0, 0), True), Literal('a', (0, 0), False)]))
premise3 = Clause(set([Literal('a', (0, 0), True)]))
goal = Clause(set([Literal('s', (0, 0), True)]))
print resolution(set([premise1, premise2, premise3]), goal)
def testLab():
"""
A sample of a resolution problem that should return True.
You should come up with your own tests in order to validate your code.
"""
premise1 = Clause(set([Literal('a', (0, 0), True), Literal('a', (0, 0), True)]))
premise2 = Clause(set([Literal('a', (0, 0), False), Literal('a', (0, 0), False)]))
goal = Clause(set([Literal('a', (0, 0), False), Literal('a', (0, 0), True)]))
print resolution(set([premise1, premise2]), goal)
def test118Skripta():
premise1 = Clause(set([Literal('a', (0, 0), True), Literal('b', (0, 0), False)]))
premise2 = Clause(set([Literal('b', (0, 0), True), Literal('d', (0, 0), False)]))
premise3 = Clause(set([Literal('c', (0, 0), True), Literal('d', (0, 0), False)]))
premise4 = Clause(set([Literal('d', (0, 0), True), Literal('e', (0, 0), False)]))
premise5 = Clause(set([Literal('b', (0, 0), False), Literal('c', (0, 0), False)]))
goal = Clause(set([Literal('e', (0, 0), False)]))
print resolution(set([premise1, premise2, premise3, premise4, premise5]), goal)
if __name__ == '__main__':
"""
The main function - if you run logic.py from the command line by
>>> python logic.py
this is the starting point of the code which will run.
"""
test118Skripta() |
#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
# Write a generator that calculates the number of seconds since midnight for events in access_log,
# and show the first ten when the program is run
import calendar
import re
datetimeFormat2 = '%d/%b/%Y:%H:%M:%S %z'
def starttoday():
# built a today's midnight date with timezone in format similar to log timestamp
import time, datetime
# find the current time zone & make it a string of the timezone
localtz = datetime.timezone(datetime.timedelta(seconds=-time.timezone))
localtzl = str(localtz)[3:].split(':')
tzstr = localtzl[0] + localtzl[1]
# get today date & reformat it with timezone in a string
from datetime import date
tdl = str(date.today()).split('-')
tdstr = tdl[2] + '/' + (calendar.month_abbr[int(tdl[1])]) + '/' + tdl[0] + ':00:00:00 ' + tzstr
return (tdstr)
def nbrseconds(timestamp):
# alculates the number of seconds since midnight for events in access_log with correspeoding timestamp date
# timezone is taken in account (day ligth saving) for today's midnight & log event
import datetime
if option == 'A':
diff = (datetime.datetime.strptime(startdate, datetimeFormat2)) - (
datetime.datetime.strptime(timestamp, datetimeFormat2))
print(" =>Seconds:", int(diff.total_seconds()))
if option == 'C':
diff = (datetime.datetime.strptime(timestamp, datetimeFormat2)) - (
datetime.datetime.strptime(midnight, datetimeFormat2))
print(" =>Seconds:", int(diff.total_seconds()))
#start main
startdate = starttoday() # get startdate
# print an explanation for the coming list of 10 events
print("Since I found 3 possible interpretations of \n'since midnight for events in access_log' , I made 3 scripts:")
print (" Script # A: midgnight is Today\'s midnight ")
print (" Script # B: midgnight is the event\'s midnight ")
print (" Script # C: midgnight is the 1st event\'s midnight ")
#################################################################
print("=======SCRIPT A: midgnight is Today\'s midnight=======")
print('List of the first 10 log events with their times in seconds * ')
print('Since Today\'s midnight which is: ', startdate)
option ="A"
# set path of the file
log = '/etc/httpd/logs/access_log'
nb = 10 # fix the number of lines to scan
ct = 0 # create a counter for the number of timestamps found
# start3 =timer() #note the start time
gen = (line for line in open(log)) # create a generator for reading the line of the file
# use the generator to go line by line up to nb lines
while ct < nb:
# search the time stamp which is in the 1st brackets [] using regex in the next line of the generator
match = re.search('\[(.*?)\]', next(gen))
if match is not None:
print(match.group(1), end='\t') # if found it print it
nbrseconds(match.group(1)) # calculate the number of second between today midnight & curren timestamp
ct = ct + 1 # increase counter by 1
else:
break # stop no more lines
print(f"{ct} timestamps shown with number of seconds since today\'s midnight.")
print('*Note: For the seconds calculation time zones are taken into account for both timestamps')
#####################################################################################
print("=======SCRIPT B: midgnight is the event\'s midnight=======")
#give the path of the file
log = '/etc/httpd/logs/access_log'
#create a generator
gen =(line for line in open(log))
#use the generator to go line by line up to 10 lines
for ct in range(10):
gn = next(gen) # get next from generator
#search the time stamp which is in the 1st brackets [] using regex in the next line of the generator
match = re.search('\[(.*?)\-', gn) # get the timestamp
match2 = re.search('\:(.*?)\-',gn) # get the time from the timestamp
#if time stamp found print it
if match is not None: #if time stamp found print it
print(match.group(1)+ '->time in seconds since midnight same day:', end='\t')
t1 =(match2.group(1)).split(":") #make a list of the time to split in hour,minutes , seconds
print((1*int(t1[2]) + 60*(int(t1[1]))+3600*int(t1[0]))) #convert hr,min,sec in sec.Sum then & print
ct = ct + 1
else :
#stop no more lines
break
#at the end prntt the number of lines/time stamps shown
print(f"{ct} timestamps have been shown with number of seconds since their own midnight")
#######################################################################
print("=======SCRIPT C: midgnight is the 1st event\'s midnight=======")
log = '/etc/httpd/logs/access_log'
nb = 10 # fix the number of lines to scan
ct = 0 # create a counter for the number of timestamps found
#print('List of the first 10 log events with their times in seconds* since the midnight of the first even')
gen = (line for line in open(log)) # create a generator for reading the line of the file
option ="C"
# use the generator to go line by line up to nb lines
while ct < nb:
# search the time stamp which is in the 1st brackets [] using regex in the next line of the generator
match = re.search('\[(.*?)\]', next(gen))
if match is not None:
if ct == 0:
#calculate the midnigh's of the 1st event
split1=(match.group(1).split('/'))
day1=((match.group(1).split('/'))[0])
month1= split1[1]
year1 = (split1[2].split(':'))[0]
tz=(((split1[2].split(':'))[3]).split(' ') ) [1]
midnight =(day1 +'/'+month1+'/'+year1+':00:00:00 '+tz)
print('List of the first 10 log events with their times in seconds* since the midnight of the first even')
print('The midnight of the first even is:', midnight)
print(match.group(1),end='\t')
#print(' =>Seconds', end='\t')
match2 = re.search('\:(.*?)\-', match.group(1)) # get the time from the timestamp
t1 = (match2.group(1)).split(":") # make a list of the time to split in hour,minutes , seconds
sumit=(1 * int(t1[2]) + 60 * (int(t1[1])) + 3600 * int(t1[0])) # convert hr,min,sec in sec.Sum then
print(' =>Seconds:',sumit)
else :
print(match.group(1), end='\t') # if found it print it
nbrseconds(match.group(1)) #find duration in seconds & print it
ct = ct + 1 # increase counter by 1
else:
break # stop no more lines
print(f"\n{ct} timestamps shown with number of seconds since 1st event\'s midnight.")
print('*Note: For the seconds calculation time zones are taken into account for both timestamps\n')
|
"""
sales_report.py - Generates sales report showing the total number
of melons each sales person sold.
"""
salespeople = []
melons_sold = []
# Using dictionary as a data structure is recommended
# it will make the aggregation and the search faster
# sales_info = { "sale_person_name": {
# "sales_dollars": dollar value,
# "sales_quantity": quantity value}
# }
f = open("sales-report.txt")
# recommend using "sales_report_file" as variable for clear definition
# also recommend import sys - and using sys.argv to enable calling other files
# this for loop can be put into function for all the old reports to use
# That way, we can migrate the old data into the new data structure
for line in f:
line = line.rstrip()
entries = line.split("|")
# entries will contain values with three different characters
# recommend using "tokens"
salesperson = entries[0]
# "sales_person" for python-like code consistancy
melons = int(entries[2])
# "sales_quantity" for the variable recommended for clearer statement
# below section is recommended to be
# sales_info[sales_person][sales_amount] = \
# sales_info.get(sales_person, 0) + salse_info[sales_person][sales_amount]
if salesperson in salespeople:
position = salespeople.index(salesperson)
melons_sold[position] += melons
else:
salespeople.append(salesperson)
melons_sold.append(melons)
# for person in sales_info: # it will loop through
for i in range(len(salespeople)):
# change the output format according to the data structure
print "{} sold {} melons".format(salespeople[i], melons_sold[i])
|
# parameter: day counter, the db file name
# function: if it is Day1, and there are delivery data in db file
# Prints Day1 and all delivery information
def melonDeliveryByDays(day, file):
the_file = open(file)
print()
print ("Day %d"%day)
for line in the_file:
line = line.rstrip()
words = line.split('|')
melon = words[0]
count = words[1]
amount = words[2]
print ("Delivered {} {}s for total of ${}".format(
count, melon, amount))
the_file.close()
melonDeliveryByDays(1, "um-deliveries-20140519.txt")
melonDeliveryByDays(2, "um-deliveries-20140520.txt")
melonDeliveryByDays(3, "um-deliveries-20140521.txt")
"""
# it is possible to iterate through the file name
# by using the datetime with the filename + number + extension concatination
# the above three lines also can be changed into a separate funciton
# for this exercise, there are only three lines, so the method
# is not used to save some coding lines
# below is the code for looping the date
for i in xrange(10):
with open('file_{0}.dat'.format(i),'w') as f:
f.write(str(func(i)))
# below is the code for calculating number of days
import datetime as dt
print((dt.date(2014,1,1) -dt.date(2011,3,3)).days)
""" |
#all basic data types
x=2 #x is int
y=1.2 #y is float
z="python" #z is string
a=7j #a is complex
b=["tik","tok","pop"] #b is list
c=("tik","tok","pop") #c is tuple
d={"tik","tok","pop"} #d is set
e=range(5) #e is range
f=bool(2) #f is boolen
print(x,y,z,a,b,c,d,e,f)
print(type(x),type(y),type(z),type(a),type(b),type(c),type(d),type(e),type(f)) |
#enter lenghth in cm and convert into meter & km
cm=float(input("length:"))
m=cm/100
km=cm/(1000*100)
print(m)
print(km) |
# // Author: proRam
# // Name: Shubh Bansal
# // Dated: June 6, 2020
# // Question: https://www.codechef.com/JUNE20A/problems/TTUPLE
import sys
sys.stdin = open('JUNE20A/input.txt', 'r')
sys.stdout = open('JUNE20A/output.txt', 'w')
class Tuple(object) :
def __init__(self) :
self.f, self.s, self.t = None, None, None
def __str__(self) :
return (self.f, self.s, self.t)
str,tar = Tuple(),Tuple() ;
select2 = [3,5,6] ;
select1 = [1,2,4] ;
sixinit = [None]*6
# // For Answer 1 - op1 ================================================================================
def op1_0() :
# // only 1 element tranform needed
# // p <---x----> a
# // q .......... b
# // r .......... c
for i in select1 :
a,b,c,p,q,r = sixinit
if ( i==1 ) :
p = str.f ; a = tar.f ;
q = str.s ; b = tar.s ;
r = str.t ; c = tar.t ;
elif ( i==2 ) :
q = str.f ; b = tar.f ;
p = str.s ; a = tar.s ;
r = str.t ; c = tar.t ;
else :
r = str.f ; c = tar.f ;
q = str.s ; b = tar.s ;
p = str.t ; a = tar.t ;
if ( q==b and r==c ) :
return 1 ;
return 3 ;
def op1_1() :
# // only 2 element tranform needed
# // p <---x----> a
# // q <---x----> b
# // r .......... c
a,b,c,p,q,r = sixinit
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
if ( r!=c ) :
continue ;
# // try addition
if ( a-p == b-q ) :
return 1 ;
# // try multiplication
try :
if ( p!=0 and q!=0 and a%p==0 and b%q==0 and a//p==b//q ) :
return 1 ;
except :
pass
return 3 ;
def op1_2() :
# // all 3 element tranform needed
# // p <---x----> a
# // q <---x----> b
# // r <---x----> c
# // try addition
if ( tar.f-str.f == tar.s-str.s and tar.f-str.f == tar.t-str.t ) :
return 1 ;
# // try multiplication
try :
if ( str.f!=0 and str.s!=0 and str.t!=0 and tar.f%str.f==0 and tar.s%str.s==0 and tar.t%str.t==0 and
tar.f//str.f==tar.s//str.s and tar.t//str.t==tar.s//str.s ) :
return 1 ;
except :
pass
return 3 ;
# // For ANswer 2 - op2
def op2_0() :
# // p <---x---> a
# // q <---x---> b
# // r <---y---> c
# // we assume 3 is the answer
a,b,c,p,q,r = sixinit
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
# // 1. +x, (+y / *y)
if ( a-p==b-q ) :
return 2 ;
# // 2. *x, (+y / *y)
try :
if ( p!=0 and q!=0 and a%p==0 and b%q==0 and a//p==b//q ) :
return 2 ;
except :
pass
return 3 ;
def op2_1() :
# // p <---x---><---y---> a
# // q <---x---><---y---> b
# // r .........<---y---> c
a,b,c,p,q,r = sixinit
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
# // 1. operation reverse enginnering ****************************************************************
# // r reaches c by addition
if (True) :
diff = c-r ;
midp_req = a-diff ;
midq_req = b-diff ;
# // 1.1 check if we can reach midp and midq by addition
pjump = midp_req - p ;
qjump = midq_req - q ;
if ( pjump == qjump ) :
return 2 ;
# // 1.2 check if we can reach midp and midq by multiplication
try :
if ( p!=0 and midp_req%p==0 and q!=0 and midq_req%q==0 ) :
pjump = midp_req // p ;
qjump = midq_req // q ;
if ( pjump == qjump ) :
return 2 ;
except :
pass
# // **************************************************************** checking 1 ends
# // 2. operation reverse enginnering ****************************************************************
# // r reaches c by multiplication
if ( r!=0 and c%r==0 ) :
cjump = c//r ;
if ( cjump!=0 and a%cjump==0 and b%cjump==0 ) :
try :
midp_req = a//cjump ;
midq_req = b//cjump ;
except :
continue
# // 2.1 Reach from p,q to midp, midq by addition
if ( midp_req-p == midq_req-q ) :
return 2 ;
# // 2.2 Reache from p,q midwy by multiplication
try :
if ( p!=0 and midp_req%p==0 and q!=0 and midq_req%q==0 ) :
pjump = midp_req // p ;
qjump = midq_req // q ;
if ( pjump == qjump ) :
return 2 ;
except :
pass
# // **************************************************************** checking 2 ends
return 3 ;
def op2_2() :
# // p <---x---> a
# // q <---y---> b
# // r ......... c
# // we assume 3 is the answer
if ( str.f==tar.f or str.s==tar.s or str.t==tar.t ) :
return 2 ;
return 3 ;
def op2_3() :
# // p <---x---><---y---> a
# // q .........<---y---> b
# // r .........<---y---> c
# // we assume 3 is the answer
a,b,c,p,q,r = sixinit
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
# // 1. try +y
if ( b-q == c-r ) :
return 2 ;
# // 2. try *y
try :
if ( r!=0 and q!=0 and b%q==0 and c%r==0 and b//q==c//r ) :
return 2 ;
except :
pass
return 3 ;
def op2_4() :
# // p <---x---><---y---> a
# // q <---x---><---y---> b
# // r <---x---><---y---> c
# // +x, *y
# // *x, +y // div + mod
# // we assume 3 is the answer
a,b,c,p,q,r = sixinit;
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
# // 1.
# // px + y = a --1
# // qx + y = b --2
# // rx + y = c --3
# //
# // 5 x10 50 +3 53
# // 10 x10 100 +3 103
# // 20 x10 200 +3 203
try :
if ( p!=0 and q!=0 and r!=0 and a//p==b//q and a//p==c//r and a%p==b%q and a%p==c%r ) :
return 2 ;
except :
pass
# // 2.
# // (p+x)y = a => py + y = a
# // (q+x)y = b => qy + y = b
# // (r+x)y = c => ry + y = c
# // same as above
# // p + _ * _ + _ * _ = a
# // q + _ * _ + _ * _ = b
# // r + _ * _ + _ * _ = c
return 3 ;
def op2_5() :
# // p <---x--->......... a
# // q <---x---><---y---> b
# // r .........<---y---> c
# // 1 +2 - 3
# // 2 +2 x2 - 8
# // 3 x2 - 6
# // we assume 3 is the answer
a,b,c,p,q,r = sixinit;
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
# // 1. try to reach c from r by addition
diff = c-r ;
midq = b-diff ;
# // 1.1 try to reahc midway by addition
# // covered
# // 1.2 try to reach midway by multiplication
try :
if ( p!=0 and q!=0 and a%p==0 and midq%q==0 and a//p==midq//q ) :
return 2 ;
except :
pass
# // 2. try to reach c from r by multiplication
try :
if ( r!=0 and c%r == 0 ) :
cjump = c//r ;
if ( b%cjump!=0 ) :
continue ;
qmid = b//cjump ;
# // 2.1 try to reach midway by multiplication
try :
if ( p!=0 and q!=0 and a%p==0 and qmid%q==0 and a/p==qmid/q ) :
return 2 ;
except :
pass
# // 2.2 try to reach midway by addition
if ( a-p == qmid-q ) :
return 2 ;
except :
pass
return 3 ;
def op2_6() :
# // p <---x---><---y---> a
# // q .........<---y---> b
# // r .................. c
# // we assume 3 is the answer
a,b,c,p,q,r = sixinit ;
for i in select2 :
if ( i==3 ) :
p = str.s ;
q = str.t ;
r = str.f ;
a = tar.s ;
b = tar.t ;
c = tar.f ;
elif ( i==5 ) :
p = str.f ;
q = str.t ;
r = str.s ;
a = tar.f ;
b = tar.t ;
c = tar.s ;
else :
p = str.f ;
q = str.s ;
r = str.t ;
a = tar.f ;
b = tar.s ;
c = tar.t ;
if (r!=c) :
continue ;
# // 1. try to reach b from q by addition
diff = b-q ;
midp = a-diff ;
# // 1.1 try to reach midway by ADDITION
# // ===== ALREADY COVERED ========
# // 1.2 try to reach midway by multiplication
try :
if ( p!=0 and midp%p == 0 ) :
return 2 ;
except :
pass
# // 2. try to reach midway by multiplication
try:
if ( b%q!=0 ) :
continue ;
jump = b//q ;
# // 2.1 try to reach midway by multiplication
if ( p!=0 and jump%p == 0 ) :
return 2 ;
except :
pass
return 3 ;
def main():
for _ in range(int(input())) :
str.f ,str.s ,str.t = list(map(int,input().split()))
tar.f ,tar.s ,tar.t = list(map(int,input().split()))
ans = 3
# // CASE WHEN STR==TAR i.e. ans = 0
if ( tar.f==str.f and tar.t==str.t and tar.s==str.s ) :
print(0)
continue ;
# // Check if 1 possible solution
ans = min(min(op1_0(),op1_1()),op1_2());
if ( ans == 1 ) :
print(1)
continue ;
# // Check if 2 possible solution
# ans = op2_0() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
# ans = op2_1() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
# ans = op2_2() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
# ans = op2_3() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
# ans = op2_4() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
# ans = op2_5() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
# ans = op2_6() ;
# if ( ans == 2 ) :
# print(2)
# continue ;
print(2)
return 0 ;
main() |
primes = []
def __init__primes() :
global primes
primes = [2]
isprime = [True for i in range(102) ]
for i in range(3,102,2) :
if isprime[i] :
primes.append(i)
for j in range(i*i, 102, i) :
isprime[j] = False
def groupAnagrams( strs ) :
global primes
table = {}
for i in strs :
pro = 1
for j in i :
pro *= primes[ord(j)-97]
if pro not in table.keys() :
table[pro] = []
table[pro].append(i)
ans = []
for i in table.values() :
ans.append(i)
return ans
def main() :
l = input().split()
l = groupAnagrams(l) |
# -*- coding: utf-8 -*-
# 文字列の平文を数値化する
def str_to_int(chr):
list_ord = []
str_list = list(chr) # 文字列をリストに格納
for s in str_list:
ord_chr = ord(s)
list_ord.append(ord_chr)
return list_ord
# 数値化した平文を文字列に直す
def int_to_str(num_list):
chr_list = []
for i in num_list:
ori_chr = chr(i)
chr_list.append(ori_chr)
maped_list = map(str, chr_list)
original_message = "".join(maped_list)
print(original_message)
return original_message
|
"""Brain-calc game module."""
import operator
import random
FIRST_MIN_NUMBER = 0
FIRST_MAX_NUMBER = 20
SECOND_MIN_NUMBER = 1
SECOND_MAX_NUMBER = 10
RULES = 'What is the result of the expression?'
def get_question_and_answer():
"""Brain-calc game.
Generate math expression with two random numbers and a random operator.
Ask the user a question for a round of the game.
Calculate the correct answer.
Returns:
question for the user
correct answer value
"""
operators = {'+': operator.add, '-': operator.sub, '*': operator.mul}
first_num = random.randint(FIRST_MIN_NUMBER, FIRST_MAX_NUMBER)
second_num = random.randint(SECOND_MIN_NUMBER, SECOND_MAX_NUMBER)
random_operator = random.choice(list(operators.keys()))
question = '{0} {1} {2}'.format(
first_num, random_operator, second_num,
)
correct_answer = operators.get(random_operator)(first_num, second_num)
return question, correct_answer
|
#!/usr/bin/python3
from functools import lru_cache
# https://www.geeksforgeeks.org/cutting-a-rod-dp-13/
# A Dynamic Programming solution for Rod cutting problem
INT_MIN = -32767
# Returns the best obtainable price for a rod of length n and
# price[] as prices of different pieces
def cutRod(price, cost=0):
'''
Given a rod of length n inches and an array of prices that contains
prices of all pieces of size smaller than n. Determine the maximum
value obtainable by cutting up the rod and selling the pieces.
For example, if length of the rod is 8 and the values of different
pieces are given as following, then the maximum obtainable value is
22 (by cutting in two pieces of lengths 2 and 6)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
And if the prices are as following, then the maximum obtainable value
is 24 (by cutting in eight pieces of length 1)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 3 5 8 9 10 17 17 20
If parameter cost is non-zero, this is the cost to make the actual cut.
'''
n = len(price)
val = [0 for x in range(n+1)]
val[0] = 0
text = [''] * len(val)
# Build the table val[] in bottom up manner and return
# the last entry from the table
for i in range(1, n+1):
max_val = INT_MIN
max_text = ''
for j in range(i):
if i - j == 1:
this_price = price[j] + val[i-j-1]
else:
this_price = price[j] + val[i-j-1] - cost
if this_price > max_val:
#if max_val != INT_MIN:
# print(f"i={i} j={j} max_val={max_val}, max_text={max_text}")
# import pdb; pdb.set_trace()
max_val = this_price
max_text = f'1 cut of {j+1}, {text[i-j-1]}'
val[i] = max_val
text[i] = max_text
# print(f"The best way to cut {i} is max_text={max_text}")
# print(f"val={val}")
# print(f"text={text[n]}")
# print(f"The best way to cut a pipe of length {n} is {text[n]} for a cost of {val[n]}")
# text[n] = text[n].rstrip(' ').rstrip(',')
return val, text
# Driver program to test above functions
if __name__ == "__main__":
arr = [1, 5, 8, 9, 10, 17, 17, 20]
value, text = cutRod(arr)
assert value == 22
print(f"The maximum obtainable value for {arr} is {value} using {text}")
arr = [2, 3, 4, 9, 12, 17, 18, 22, 25, 30]
for index in range(len(arr)):
arr2 = arr[:index+1]
value, text = cutRod(arr2)
print(f"The maximum obtainable value for {arr2} is {value} using {text}")
@lru_cache(maxsize=1024)
def get_pipe_values(prices, costs):
''' Given a tuple of prices and costs, return a list of the rod cutiting values '''
return [ cutRod(prices[i], costs[i])[0][1:] for i in range(len(prices)) ]
|
#!/usr/bin/python3
# https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
# Dynamic Programming implementation of LCS problem
class LCS(object):
''' Create a LCS object '''
def __init__(self, X , Y):
self._X = X
self._Y = Y
# find the length of the strings
self._m = len(X)
self._n = len(Y)
# declaring the array for storing the dp values
self._L = [[None]*(self._n+1) for i in range(self._m+1)]
self._B = [[0]*(self._n+1) for i in range(self._m+1)]
"""Following steps build L[m+1][n+1] in bottom up fashion
Note: L[i][j] contains length of LCS of X[0..i-1]
and Y[0..j-1]"""
for i in range(self._m+1):
for j in range(self._n+1):
if i == 0 or j == 0 :
self._L[i][j] = 0
self._B[i][j] = 0
elif X[i-1] == Y[j-1]:
self._L[i][j] = self._L[i-1][j-1]+1
self._B[i][j] = 'DIAG'
else:
if self._L[i-1][j] >= self._L[i][j-1]:
self._B[i][j] = 'UP'
else:
self._B[i][j] = 'LEFT'
self._L[i][j] = max(self._L[i-1][j] , self._L[i][j-1])
self._sq = [[ f'{self._L[i][j]}{self._B[i][j]}' for i in range(0, self._m+1) ] for j in range(0, self._n+1) ]
# Following code is used to get the actual LCS
index = self._L[self._m][self._n]
# Create a character array to store the lcs string
self._lcs = [""] * (index+1)
# Start from the right-most-bottom-most corner and
# one by one store characters in self._lcs[]
i = self._m
j = self._n
while i >= 0 and j >= 0:
# If current direction is DIAG, then
# current character is part of LCS
if 'DIAG' == self._B[i][j]:
self._lcs[index-1] = X[i-1]
i-=1
j-=1
index-=1
# If UP, go up, else go left
elif 'UP' == self._B[i][j]:
i-=1
else:
j-=1
def square(self, i, j):
assert (0 <= i <= self._m) and (0 <= j <= self._n), f"square({i},{j}) must be less than {self._m},{self._n}"
return f'{self._L[i][j]}{self._B[i][j]}'
@property
def sq(self):
return self._sq
@property
def lcs(self):
return self._lcs
@property
def LCS(self):
# L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
return self._L[self._m][self._n]
# Driver program to test the above function
if __name__ == "__main__":
X = "AGGTAB"
Y = "GXTXAYB"
lcs = LCS(X,Y)
print(f"X={X}\nY={Y}\nLength of LCS is {lcs.LCS}")
|
# Import the functions from the menu option files in the project
from CreateDatabase import *
from AddRecord import *
from UpdateRecord import *
from DeleteRecord import *
from DisplayAllRecords import *
from DisplaySingleRecord import *
# Defines the main function
def main():
# Variable to quit out of program
qt = False
# Programs runs until qt is true aka user quits
while qt == False:
# Displays menu options for user
print("Database Manager \n"
"^^^^^^^^^^^^^^^^ \n"
"1. Create the Database \n"
"2. Add a Record \n"
"3. Update a record \n"
"4. Delete a record \n"
"5. Display all records \n"
"6. Display a single record \n"
"7. Quit \n")
# Validation to ensure menu option is an integer between 1 & 7
while True:
try:
option = int(input("Enter the menu option number: "))
except ValueError:
print('\nError! Value must be an integer between 1 & 7. Try again.\n')
else:
if (option < 1 or option > 7):
print("\nMenu option must be between 1 & 7.\n")
else:
break
# Depending on menu option selection, different menu function is called
if option ==1:
createDB()
elif option ==2:
addRecord()
elif option ==3:
updaterecord()
elif option == 4:
deleteRecord()
elif option == 5:
displayAllRecords()
elif option == 6:
displaySingleRecord()
# Quits the program
elif option ==7:
qt = True
# Call main function
main()
|
from heapq import heappop,heappush,heapify
heap=[]
nums=[12,3,-2,6,8]
#for num in numbs:
#heappush(heap,num)
#while heap:
#print(heappop(heap))
heapify(nums)
print(nums) |
"""
Given the root of a binary tree, invert the tree, and return its root.
"""
from test_utils import TreeNode
def invert_tree(root: TreeNode) -> TreeNode:
"""
Explanation
To invert a binary tree we need to reverse top down. Thus at root we swap the whole subtrees and iteratively do this
all the way down the tree. This is really just a BFS with swapping each node's children.
"""
if root is None:
return None
queue = [root]
while queue:
node = queue.pop(0)
# Swap pointers
temp = node.left
node.left = node.right
node.right = temp
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return root
"""
Run DETAILS
Runtime: 28 ms, faster than 86.23% of Python3 online submissions for Invert Binary Tree.
Memory Usage: 14.4 MB, less than 12.11% of Python3 online submissions for Invert Binary Tree.
"""
|
# Tests for Add Two Numbers
from problems.add_two_numbers import add_two_numbers
from test_utils import compare_list_nodes, ListNode
DEBUG = False
def test_add_two_numbers_1():
l1 = ListNode(2, ListNode(4, ListNode(3)))
l2 = ListNode(5, ListNode(6, ListNode(4)))
expected = ListNode(7, ListNode(0, ListNode(8)))
actual = add_two_numbers(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
def test_add_two_numbers_2():
l1 = ListNode(0)
l2 = ListNode(0)
expected = ListNode(0)
actual = add_two_numbers(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
def test_add_two_numbers_3():
l1 = ListNode(
9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9))))))
)
l2 = ListNode(9, ListNode(9, ListNode(9, ListNode(9))))
expected = ListNode(
8,
ListNode(
9,
ListNode(
9, ListNode(9, ListNode(0, ListNode(0, ListNode(0, ListNode(1)))))
),
),
)
actual = add_two_numbers(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
|
"""
Given the head of a sorted linked list, delete all duplicates such that each element appears only once.
Return the linked list sorted as well.
"""
from test_utils import ListNode
def delete_duplicates(head: ListNode) -> ListNode:
"""
Explanation
The first thing to notice is that each sorted number could have multiple duplicates. This informs how we solve.
1. The first thing to do is to keep a prev and current node as we traverse through the list.
2. Thus we can just check if the current val and next val are equal. If show, set current next to current next next
3. Return head
"""
curr = head
while curr is not None and curr.next is not None:
if curr.next.val == curr.val:
curr.next = curr.next.next
else:
curr = curr.next
return head
"""
Run DETAILS
Runtime: 44 ms, faster than 58.34% of Python3 online submissions for Remove Duplicates from Sorted List.
Memory Usage: 14.1 MB, less than 95.38% of Python3 online submissions for Remove Duplicates from Sorted List.
"""
|
"""
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number.
"""
from typing import List
def find_duplicate(nums: List[int]) -> int:
"""
Explanation
We are given the fact that there is exactly one duplicate in our array. If we think of this list as a linked list,
we are guaranteed a single cycle. Thus this is a perfect candidate for floyd's algorithm. The basic idea goes like
this:
* We have a tortoise and a hare. The hare moves twice as start as a tortoise to start.
* Eventually we will reach a point where hare and tortoise are at the same spot (the cycle)
* We then reset the tortoise to root and traverse both tortoise and the hare one increment at a time
and whenever they end up at the same point we have reached our cycle point.
"""
tortoise = hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
tortoise = nums[0]
while tortoise != hare:
tortoise = nums[tortoise]
hare = nums[hare]
return hare
"""
Run DETAILS
Runtime: 68 ms, faster than 54.88% of Python3 online submissions for Find the Duplicate Number.
Memory Usage: 16.5 MB, less than 77.89% of Python3 online submissions for Find the Duplicate Number.
"""
|
from problems.merge_two_sorted_lists import ListNode, merge_two_lists
from test_utils import compare_list_nodes
DEBUG = False
def test_merge_two_sorted_lists_1():
l1 = ListNode(1, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
expected = ListNode(
1, ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(4)))))
)
actual = merge_two_lists(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
def test_merge_two_sorted_lists_2():
l1 = None
l2 = None
expected = None
actual = merge_two_lists(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
def test_merge_two_sorted_lists_3():
l1 = None
l2 = ListNode(0)
expected = ListNode(0)
actual = merge_two_lists(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
def test_merge_two_sorted_lists_4():
l1 = ListNode(0)
l2 = None
expected = ListNode(0)
actual = merge_two_lists(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
def test_merge_two_sorted_lists_5():
l1 = ListNode(
-42,
ListNode(
-0,
ListNode(
1, ListNode(7, ListNode(37, ListNode(42, ListNode(49, ListNode(52)))))
),
),
)
l2 = ListNode(
-71,
ListNode(
-52,
ListNode(
-21,
ListNode(4, ListNode(10, ListNode(41, ListNode(55, ListNode(100))))),
),
),
)
expected = ListNode(
-71,
ListNode(
-52,
ListNode(
-42,
ListNode(
-21,
ListNode(
0,
ListNode(
1,
ListNode(
4,
ListNode(
7,
ListNode(
10,
ListNode(
37,
ListNode(
41,
ListNode(
42,
ListNode(
49,
ListNode(
52,
ListNode(55, ListNode(100)),
),
),
),
),
),
),
),
),
),
),
),
),
),
)
actual = merge_two_lists(l1, l2)
assert compare_list_nodes(expected, actual, DEBUG) is True
|
"""
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a
subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could
also be considered as a subtree of itself.
"""
from test_utils import TreeNode
def _identical(a: TreeNode, b: TreeNode) -> bool:
if not a and not b:
return True
if not a or not b:
return False
return (
a.val == b.val and _identical(a.left, b.left) and _identical(a.right, b.right)
)
def is_subtree(s: TreeNode, t: TreeNode) -> bool:
"""
Explanation
The key thing here is that we can look traverse the tree and check the substructure at any point. Thus
what we can do is check if s and t are identical, and if not recursively do the same thing. If no substructure
is ever found return False else return True
"""
if t is None:
return True
if s is None:
return False
if _identical(s, t):
return True
return is_subtree(s.left, t) or is_subtree(s.right, t)
"""
Run DETAILS
Runtime: 252 ms, faster than 44.38% of Python3 online submissions for Subtree of Another Tree.
Memory Usage: 15.7 MB, less than 5.88% of Python3 online submissions for Subtree of Another Tree.
"""
|
"""
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each
word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
"""
from collections import defaultdict
from typing import List, Union
def _work_break_dfs(s: str, word_dict: List[str]) -> List[str]:
pass
def word_break(s: str, word_dict: List[str]) -> List[str]:
"""
Explanation
The basic idea is to use recursion. We can recursively do the following with memoization
* Loop through the current input string and check if we have found a word.
* If so, recursively check for other words and get a list of all possible solutions for current word
* At the end return our total accumulated sub problems.
* We can optimize a little bit by checking for subproblems before recursion to avoid extra work.
"""
word_set = set(word_dict)
memo = defaultdict(list)
def _word_break_recurse(temp_str: str):
nonlocal word_set
nonlocal memo
if not temp_str:
return [[]]
if temp_str in memo:
return memo[temp_str]
for endIndex in range(1, len(temp_str) + 1):
word = temp_str[:endIndex]
if word in word_set:
for sub_problems in _word_break_recurse(temp_str[endIndex:]):
memo[temp_str].append([word] + sub_problems)
return memo[temp_str]
_word_break_recurse(s)
return [" ".join(words) for words in memo[s]]
"""
Run DETAILS
Runtime: 24 ms, faster than 98.04% of Python3 online submissions for Word Break II.
Memory Usage: 14.1 MB, less than 96.01% of Python3 online submissions for Word Break II.
"""
|
"""
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exists, otherwise return -1.
void put(int key, int value) Update the value of the key if the key exists. Otherwise,
add the key-value pair to the cache. If the number of keys exceeds the capacity from this
operation, evict the least recently used key.
Follow up:
Could you do get and put in O(1) time complexity?
"""
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self._capacity = capacity
self._dict = OrderedDict()
def get(self, key: int) -> int:
if key not in self._dict:
return -1
self._dict.move_to_end(key)
return self._dict[key]
def put(self, key: int, value: int) -> None:
if key in self._dict:
self._dict.move_to_end(key)
self._dict[key] = value
if len(self._dict) > self._capacity:
self._dict.popitem(last=False)
"""
Runtime: 172 ms, faster than 84.70% of Python3 online submissions for LRU Cache.
Memory Usage: 23.5 MB, less than 73.94% of Python3 online submissions for LRU Cache.
"""
|
from striprtf.striprtf import rtf_to_text
print("-----------------------------SGI-----------------------------")
print("Limpe seu texto do SISP-01")
continua = ''
linha = " "
while continua != 'n':
print("Digite seu código RTF: (ao final da cola digite um '.') ")
while True:
print("> ", end="")
line = input()
if line == ".":
break
linha += line
text = rtf_to_text(linha)
print()
print()
print()
print()
print(text)
print()
print()
print()
print("Deseja continuar? (s/n)")
continua = input()
linha = " "
else:
print()
print()
print()
print("Obrigado por utilizar a limpeza RTF do Griff -- Pressione qualquer tecla para finalizar")
print("-----------------------------SGI-----------------------------")
print()
input() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.