text
stringlengths 37
1.41M
|
---|
# b = {
# "name": "teacher1",
# "subject": "math",
# "salary": 1000,
# "age": 50
# }
# keys = []
# values = []
# for i in b:
# keys.append(i)
# values.append(b[i])
# print(keys)
# print(values)
d = {}
keys = ['name', 'subject', 'salary', 'age']
values = ['teacher1', 'math', 1000, 50]
# code
n = len(keys)
# i = 0
# while i < n:
# d[keys[i]] = values[i]
# i += 1
for i in range(n):
d[keys[i]] = values[i]
print(d) # {'name': 'teacher1', 'subject': 'math', 'salary': 1000, 'age': 50}
# teacher2 = {
# "name": "teacher2",
# "subject": "history",
# "salary": 3000,
# }
# teacher3 = {
# "name": "teacher3",
# "subject": "math",
# "salary": 2000,
# "age": 30
# }
|
numbers = [
["футболка", 2],
["шорты", 4],
["кофта", 6],
]
# 0 1
# 0[1, 2],
# 1[3, 4],
# 2[5, 6],
# 3[7, 8]
print(numbers[0][0], numbers[0][1]) # футболка
print(numbers[1][0], numbers[1][1])
print(numbers[2][0], numbers[1][1])
|
#while -> пока(до тех пор)
# while условие:
# действия
number = 20
while number != 10:
print("ok", number)
number = number - 1
print("end of cycle") |
# Пользователь делает вклад в размере a рублей сроком на years лет под 10% годовых
# (каждый год размер его вклада увеличивается на 10%. Эти деньги прибавляются к сумме вклада,
# и на них в следующем году тоже будут проценты)
a = int(input("сумма:"))
years = int(input("года:"))
percent = 0.1
i = 1
while i <= years:
a = a + a * percent
i += 1
print(a)
|
number=int(raw_input())
for i in range(2, number):
if number%i == 0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")
|
print("Enter an integer")
if (number % 2 == 0):
print("the number is even")
else:
print("the number is odd")
|
from basic.stack import Stack
# 一维字符串的消消乐
def xiaoxiaole(strings):
s = Stack()
list = []
for str in strings: # 如果与栈顶相同则消去栈顶, 不同则压入栈顶
if str == s.peek():
s.remove()
else:
s.push(str)
if s.isEmpty():
return None
else:
while not s.isEmpty():
list.insert(0, s.pop()) # 取出栈中的每个元素,注意排列顺序
return "".join(list)
if __name__ == "__main__":
print(xiaoxiaole("beepooxxxyz"))
print(xiaoxiaole("abbacddccc00"))
|
from basic.stack import Stack
def parChecker(string):
s = Stack()
index = 0
balance = True
while index < len(string) and balance:
symbol = string[index]
if symbol in "{[(":
s.push(symbol)
else:
if s.isEmpty():
balance = True
else:
top = s.pop()
if not match(top, symbol):
balance = False
index = index + 1
if balance and s.isEmpty():
return True
else:
return False
def match(a, b):
opens = "{[("
closes = "}])"
return opens.index(a) == closes.index(b)
if __name__ == "__main__":
print(parChecker("{{[]}}"))
print(parChecker("[[][{{"))
|
import argparse
import youtube_dl
import os.path
parser = argparse.ArgumentParser(
description="Converts a Youtube video to MP3",
epilog="python youtube_mp3.py --video_url 'https://www.youtube.com/watch?v=CMNry4PE93Y'"
)
parser.add_argument("--video_url", required=True, help="URL of video to be converted")
parser.add_argument("--out_file", help="Directory to save mp3")
args = parser.parse_args()
def run():
video_info = youtube_dl.YoutubeDL().extract_info(
url = args.video_url,download=False
)
if not args.out_file:
filename = f"{video_info['title']}.mp3"
else:
if os.path.isdir(args.out_file):
filename = os.path.join(args.out_file,f"{video_info['title']}.mp3")
else:
print(f"{args.out_file} does not exist, try another directory")
quit()
options={
'format':'bestaudio/best',
'keepvideo':False,
'outtmpl':filename,
}
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download([video_info['webpage_url']])
print(f"Download complete... {filename}")
if __name__=='__main__':
run()
|
def distance(a,b):
if a in r.smembers(b) or b in r.smembers(a):
return 1
elif r.smembers(a).isdisjoint(r.smembers(b)) !=True:
return 2
else:
second_degree = set()
for s in r.smembers(a):
second_degree = second_degree.union(r.smembers(s))
print second_degree
print r.smembers(b)
print second_degree & r.smembers(b)
if second_degree.isdisjoint(r.smembers(b)):
return 0
else:
return 3
from collections import Counter
def friend_recommend(a):
second_degree = []
for s in r.smembers(a):
second_degree.extend(list(r.smembers(s)))
return Counter(second_degree)
|
# Problem: 5 (in base 10) = 101 (in base 2). Invert 101 to 010 (in base 2) = 2 (in base 10)
# Input: 5
# Output: 2
def getIntegerComplement(n):
a = ''
while (n > 0):
a = str(abs(1 - (n % 2))) + a
n /= 2
i = 1
num = 0
for j in xrange(len(a) - 1, -1, -1):
num += i * int(a[j])
i *= 2
return num
print getIntegerComplement(10)
|
# Complete the function below.
def say_what_you_see(input_strings):
res = []
for s in input_strings:
curr = s[0]
count = 1
cres = ""
for c in s[1:]:
if c != curr:
cres += str(count) + curr
curr = c
count = 1
else:
count += 1
cres += str(count) + curr
res.append(cres)
return res
if __name__ == '__main__':
print say_what_you_see(['215', '5', '0'])
|
from random import randint
def start():
print('''
#################### Игра "15 спичек" ################
Всего в куче 15 спичек. Каждый игрок по очерди берёт от
################### 1 до 3 спичек. ####################
Выигрывает тот, кто заберёт последние спички из кучи.
''')
#
def get_turn():
print('''
Введите 0, чтобы ходить первым.
Введите 1, чтобы первым ходил компьютер.
Введите 2, чтобы очерёдность хода выбиралась случайно.
''')
turn = input()
while not (turn == '0' or turn == '1' or turn == '2'):
print('Ошибка! Проверьте корректность вашего ввода. Вы должны ввести 0, 1 или 2.')
turn = input()
if turn == '2':
turn = randint(0, 1)
return int(turn)
|
#!/usr/bin/env python
# coding: utf-8
# ### Observations from the data
# * 1. Male players are signficantly more numerous than female players, with more than five times the number of players. This can inform future advertising and promotional efforts, advertising in bars, live streams of sporting events, and male-centric programming.
# * 2. Roughly 66% of the players are between the ages of 16-25, which suggests a marketing campaign targeted toward late high school students, college students and young professionals could be effective.
# * 3. For the most part, the most popular items are also on the higher end of their item cost scale, and are among the most profitable. This suggests that the company is doing a good job to incentivize or create demand for their more expensive items.
# In[49]:
# Dependencies and Setup
import pandas as pd
import numpy as np
# File to Load (Remember to Change These)
game_file = "Resources/purchase_data.csv"
# Read Purchasing File and store into Pandas data frame
game_data_df = pd.read_csv(game_file)
game_data_df.head()
# ## Player Count
# * Display the total number of players
#
# In[50]:
game_data_df.columns
# In[51]:
player_count = len(game_data_df["SN"].unique())
player_count
# In[52]:
player_count_df = pd.DataFrame({"Total Players" : [player_count]})
player_count_df
# ## Purchasing Analysis (Total)
# * Run basic calculations to obtain number of unique items, average price, etc.
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display the summary data frame
#
# In[53]:
#Determine the number of unique items for purchase
num_unique_items = len(game_data_df["Item ID"].unique())
num_unique_items
# In[54]:
#Determine average purchase price
average_purchase_price = game_data_df["Price"].mean()
average_purchase_price = round((average_purchase_price), 2)
average_purchase_price
# In[55]:
#Determine number of purchases
number_of_purchases = len(game_data_df["Purchase ID"].unique())
number_of_purchases
# In[56]:
#Determine total revenue
total_revenue = game_data_df["Price"].sum()
total_revenue
# In[57]:
sales_table = pd.DataFrame({"Number of Unique Items": [num_unique_items], "Average Price": average_purchase_price,
"Number of Purchases" :number_of_purchases, "Total Revenue": total_revenue})
sales_table
# ## Gender Demographics
# * Percentage and Count of Male Players
#
#
# * Percentage and Count of Female Players
#
#
# * Percentage and Count of Other / Non-Disclosed
#
#
#
# In[58]:
#Determine number of unique players of each gender
gender_ids = game_data_df[["SN", "Gender"]]
gender_ids.head()
gender_ids_uni = gender_ids.drop_duplicates(["SN"])
unique_gender_count = gender_ids_uni["Gender"].value_counts()
unique_gender_count
# In[59]:
#Determine % of overall players by gender
male_players = 484
female_players = 81
other_players = 11
male_players_pct = (male_players/576) *100
female_players_pct = (female_players/576) *100
other_players_pct = (other_players/576) *100
male_players_pct = round(male_players_pct)
female_players_pct = round(female_players_pct)
other_players_pct = round(other_players_pct)
print(male_players_pct)
print(female_players_pct)
print(other_players_pct)
# In[60]:
#Create data frame of players by gender
players_by_gender_df = pd.DataFrame({"Gender": ["Male", "Female", "Other / Undisclosed"],
"Total Number": [str(male_players), str(female_players), str(other_players)],
"Percent of Players" : [male_players_pct, female_players_pct, other_players_pct]
}
)
players_by_gender_df
#
# ## Purchasing Analysis (Gender)
# * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender
#
#
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display the summary data frame
# In[61]:
#Group purchase data by gender, and set up unique users per genre
purchases_by_gender = game_data_df.groupby("Gender")
unique_gender_values = purchases_by_gender["SN"].nunique()
# In[62]:
#Determine number of purchases by gender
purchase_count_gnd = purchases_by_gender["Purchase ID"].count()
# In[63]:
#Determine average purchase price by gender
avg_purchprice_gnd = purchases_by_gender["Price"].mean()
avg_purchprice_gnd = round((avg_purchprice_gnd),2)
# In[64]:
#Determine total purchase value by gender
tot_purchprice_gnd = purchases_by_gender["Price"].sum()
# In[65]:
#Determine average purchase total per person by gender
apt_pp_gnd = tot_purchprice_gnd / unique_gender_values
apt_pp_gnd = round((apt_pp_gnd),2)
# In[66]:
# Create summary data frame for purchases by gender
purchase_summary_bygender = pd.DataFrame({"Purchase Count": purchase_count_gnd,
"Total Purchase Value" : tot_purchprice_gnd,
"Average Purchase Price": avg_purchprice_gnd,
"Avg Total Purchase per Person": apt_pp_gnd})
purchase_summary_bygender
# ## Age Demographics
# * Establish bins for ages
#
#
# * Categorize the existing players using the age bins. Hint: use pd.cut()
#
#
# * Calculate the numbers and percentages by age group
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: round the percentage column to two decimal points
#
#
# * Display Age Demographics Table
#
# In[67]:
#Establish age bins
age_bins = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
group_names = ["5-10", "11-15", "16-20", "21-25", "26-30", "31-35", "36-40", "41-45", "46+"]
# In[68]:
# Assign all players to an age bin
game_data_df["Player Age Group"] = pd.cut(game_data_df["Age"],age_bins, labels=group_names)
game_data_df
# In[69]:
#Reconfigure data by age group
age_groups = game_data_df.groupby("Player Age Group")
# In[70]:
#Determine total players by age category
total_byagegroup = age_groups["SN"].nunique()
# In[71]:
#Determine percentage of players by age category
percentage_byage = (total_byagegroup/player_count) * 100
percentage_byage = round((percentage_byage), 2)
# In[72]:
#Create data frame for age demographics summary
age_demo_summary = pd.DataFrame({"Total Count": total_byagegroup, "Percentage of Players": percentage_byage})
age_demo_summary
# ## Purchasing Analysis (Age)
# * Bin the purchase_data data frame by age
#
#
# * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below
#
#
# * Create a summary data frame to hold the results
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display the summary data frame
# In[73]:
#Bin purchases by age group
purchases_byage = age_groups["Purchase ID"].count()
# In[74]:
#Determine average purchase price by age group
avg_purchase_price_byage = age_groups["Price"].mean()
avg_purchase_price_byage = round((avg_purchase_price_byage), 2)
# In[75]:
#Determine total purchase value by age group
total_purchase_value_byage = age_groups["Price"].sum()
# In[76]:
#Average total per person by age group
avg_totalpp_byage = total_revenue/total_byagegroup
avg_totalpp_byage = round((avg_totalpp_byage), 2)
# In[77]:
#DataFrame for purchases by age group
purchases_df_byagegroup = pd.DataFrame({"Purchase Count": purchases_byage,
"Average Purchase Price": avg_purchase_price_byage,
"Total Purchase Value": total_purchase_value_byage,
"Average Total Purchase Per Person": avg_totalpp_byage})
purchases_df_byagegroup
# ## Top Spenders
# * Run basic calculations to obtain the results in the table below
#
#
# * Create a summary data frame to hold the results
#
#
# * Sort the total purchase value column in descending order
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display a preview of the summary data frame
#
#
# In[78]:
#Group total purchases by Screen Names
totals_bysn = game_data_df.groupby("SN")
# In[79]:
#Determine total purchases by Screen Names
total_purchcnt_bysn = totals_bysn["Purchase ID"].count()
# In[80]:
#Determine average purchase price by Screen Name
avg_purch_bysn = totals_bysn["Price"].mean()
avg_purch_bysn = round((avg_purch_bysn), 2)
# In[81]:
#Determine purchase total value by Screen Name
total_purchval_bysn = totals_bysn["Price"].sum()
# In[82]:
#Create Data Frame for Screen Name summary
sn_summary_df = pd.DataFrame({"Purchase Count": total_purchcnt_bysn,
"Average Purchase Price": avg_purch_bysn,
"Total Purchase Value": total_purchval_bysn})
# In[83]:
# Sort descending to list top five spenders by Screen Name
top_spenders_bysn = sn_summary_df.sort_values(["Total Purchase Value"], ascending=False).head()
top_spenders_bysn
# ## Most Popular Items
# * Retrieve the Item ID, Item Name, and Item Price columns
#
#
# * Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value
#
#
# * Create a summary data frame to hold the results
#
#
# * Sort the purchase count column in descending order
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display a preview of the summary data frame
#
#
# In[84]:
#Retrieve Item ID, Item Name and Item Price columns
item_info = game_data_df[["Item ID", "Item Name", "Price"]]
# In[85]:
#Group by Item ID and Item Name
popular_items = item_info.groupby(["Item ID", "Item Name"])
# In[86]:
#Determine purchase count by item
count_byitem = popular_items["Price"].count()
# In[87]:
#Determine total value of items
totval_byitem = (popular_items["Price"].sum())
# In[88]:
#Determine individual item price
price_byitem = (totval_byitem / count_byitem)
# In[89]:
#Create summary data frame for most popular items
popular_summary = pd.DataFrame({"Purchase Count": count_byitem,
"Item Price": price_byitem,
"Total Value of Item": totval_byitem,
})
most_popular_summary = popular_summary.sort_values(["Purchase Count"], ascending=False).head()
most_popular_summary
# ## Most Profitable Items
# * Sort the above table by total purchase value in descending order
#
#
# * Optional: give the displayed data cleaner formatting
#
#
# * Display a preview of the data frame
#
#
# In[90]:
#Sort Most Popular Item Data Frame by purchase value in descending order
most_profitable_byvalue = most_popular_summary.sort_values(["Total Value of Item"],
ascending=False).head()
most_profitable_byvalue
# In[ ]:
# In[ ]:
|
r = float(input("Enter the radius of the sphere: "))
x = input("Enter P for Perimeter, A for Area and V for volume: ")
if x == 'P':
def sphere_perimeter():
p = 4*3.14*r
print("Perimeter of the sphere is: ", p)
sphere_perimeter()
elif x == 'A':
def sphere_area():
a = (4*3.14*r*r)
print("Area of sphere is: ", a)
sphere_area()
elif x == 'V':
def sphere_volume():
v = (4*3.14*r*r*r)/3
print("Volume of sphere is: ", v)
sphere_volume()
else:
print("You have entered the wrong choice, please try again")
|
# Copyright (C) 2015 by Per Unneberg
class NotInstalledError(Exception):
"""Error thrown if program/command/application cannot be found in path
Args:
msg (str): String described by exception
code (int, optional): Error code, defaults to 2.
"""
def __init__(self, msg, code=2):
self.msg = msg
self.code = code
class SamplesException(Exception):
"""Error thrown if samples missing or wrong number.
Args:
msg (str): String described by exception
code (int, optional): Error code, defaults to 2.
"""
def __init__(self, msg, code=2):
self.msg = msg
self.code = code
class OutputFilesException(Exception):
"""Error thrown if outputfiles missing or wrong number.
Args:
msg (str): String described by exception
code (int, optional): Error code, defaults to 2.
"""
def __init__(self, msg, code=2):
self.msg = msg
self.code = code
|
#this program should take a video and display the grayscaled version to the user, i had some issues with this program and im not sure what is wrong:(
import numpy as np #bring numpy in and call it np for aberivation
import cv2 as cv # import cv2 module as cv
#this program gave me a number of issues when i put my information in for instance right now when i compile it cannot read ret correctly
#earlier it could not find my camera so i re configured.
cap = cv.VideoCapture('MARYD.mp4')# this should name create an object called cap and set the object to my video file
if not cap.isOpened():#if the object is unable to be found & openned then print the message to the console window letting the user know
print("Cannot open camera")
exit()
while True: #while the object is located run the code below
# Capture frame-by-frame
ret, frame = cap.read() #read the image object and return the reterval var and the image(frame)
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break #exit the condiational statement
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)#this converts our colored image to gray scale (black & white)
# Display the resulting frame
cv.imshow('frame', gray)
#cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'): #the user can terminate the program by entering q to quit
break
# When everything done, release the capture
cap.release() #we mustt do this to clear the buffer so we can excute agin just like in C
cv.destroyAllWindows() #destory the windows so it doesnt keep running in the background |
# Binary Search Algorithm is one of the most important and fundamental search algorithms every programmer should know.
# In order to perform binary search, it is crucial that the list is sorted first.
# We will be using our merge sort algorithm to sort our list.
# Then, we will perform binary search.
# Time Complexity is O(log n). Space Complexity is O(1)
def main():
myList = [83, 50, 14, 39, 59, 127, 75, 43, 34, 125, 27, 18, 23, 4, 28, 60, 36, 61, 123, 95, 37, 103, 19, 116, 99]
mySortedList = mergesort(myList)
# Now that we have obtained our sorted list, we can call the binary search function to perform search.
# If found, index will be returned. Else, -1 will be returned.
print(mySortedList)
index = binarySearch(mySortedList, 23)
if index == -1:
print("Not Found")
else:
print("Found at index " + str(index))
# In order to perform mergesort, the mergesort function utilizes a concept called recursion. Recursion is when a function calls itself and is useful for situations such as this.
def mergesort(a_list):
# In recursive functions, there is a base condition which determines when function should exit recursion
# In our case, when the len of the list is less than 2, return the list
if len(a_list) < 2:
return a_list
else:
middle = int(len(a_list) / 2) # The middle represents a point where we split the list into two sublists
left = a_list[:middle] # Create the left sublist by splitting on middle index
right = a_list[middle:] # Create the right sublist by splitting on midde index
newLeft = mergesort(left) # Recursive call sending left sublist
newRight = mergesort(right) # Recursive call sending right sublist
newList = merge(newLeft,newRight) # Merge will merge the two sorted sublists
return newList
def merge(list_a, list_b):
# These variables will represent the indexes used to merge the two sublists to one whole list
i = 0
j = 0
mergedList = []
# As long as the length of the list has not been met, we will compare each value and decide which value to put before
while i < len(list_a) and j < len(list_b):
if list_a[i] <= list_b[j]: # If this condition is met, list_a[i] will be put into mergedList and index will be incremented.
mergedList.append(list_a[i])
i += 1
else:
mergedList.append(list_b[j]) # If condition was not met, list_b[i] will be put into mergedList and index will be incremented
j += 1
# This next portion will handle any thing that was left over in list_a or list_b
# Since the previous while loop exited due to one of the conditions failing, only one of the while loops on the bottom will run.
while i < len(list_a):
mergedList.append(list_a[i])
i += 1
while j < len(list_b):
mergedList.append(list_b[j])
j += 1
return mergedList
def binarySearch(mySortedList, value):
found = False # If found, will become true
index = -1 # If never found, index returned will be -1
# First and Last are necessary to calculate middle point
first = 0
last = len(mySortedList)
# If the value has not been found and first <= last, check to see if value is in list
while not found and first <= last:
middle = int((first + last)/2) # We will use the middle value to find the value
# It is possible for middle to end up being greater than the length - 1. If thats the case, the value was not found
if(middle > len(mySortedList) - 1):
break
if mySortedList[middle] == value: # If middle index is where value is located, set found to True and set index to middle
found = True
index = middle
elif mySortedList[middle] < value: # If value in middle index is less than value, everything to left of middle does not matter
first = middle + 1
else:
last = middle - 1 # If value in middle index is greater than value, everything to right of middle does not matter.
return index
main()
|
products = [] # 有一個叫做 products 的空清單
while True: # 進入迴圈
name = input('請輸入商品名稱:') # 請使用者輸入商品名稱,創建為 name
if name == 'q': # 如果使用者輸入 q
break # 離開程式
price = input('請輸入商品價格:') # 請使用者輸入商品價格,創建為 price
products.append([name, price]) # 把 p 這個清單裝到 products 這個清單裡
print(products)
products[0][0] # products 清單的第 0 格中的第 0 格 |
# =============================================================================
# tuple()
# =============================================================================
a = ("Doreamon","sdjfhan","Tom and Jerry")
b = (1,2,3,4,5,3,3)
print(b.count(3))
print(sorted(a,reverse=True))
print(a.index("Tom and Jerry"))
print(sum(b))
print(min(b))
print(len(a))
print(b+a)
print(a*2)
if "Shinchan" in a:
print("found")
else:
print("not found")
for i in a:
print(i)
a = ()
print(a)
b = list(a)
b.append("sjdhf")
print(a,b,sep="\n")
a = tuple(b)
print(a)
print(a)
print(a[-3:-1])
b = ("Doreamon",["Shinchan",2,3,4],("codinglaugh","marjuk"),1,4,7,2)
print(len(b[1]))
for i in b:
if type(i) is list:
for j in i:
print(j)
elif type(i) is tuple:
for j in i:
print(j)
else:
print(i)
b[1][0] = "djhbf"
print(b)
|
# =============================================================================
# print() or output
# =============================================================================
print("codinglaugh","learn","something","everyday",10,20,sep="*")
print("codinglaugh","hdsjbhfh",end="\n\n")
print("learn something everyday")
#pass value as parameter
a = "I"
b = "Love"
c = "You"
print("Hey",a,b,c)
#sequential formatiing pass value
a = "I"
b = "You"
c = "Me"
print("{} love {}".format(a, b))
print("{} love {}".format(b, c))
#number formatiing pass value
a = "I"
b = "You"
c = "Me"
print("{0} love {1}".format(a, b))
print("{1} love {0}".format(b, c))
#names formatiing pass value
a = "I"
b = "You"
c = "Me"
print("{name2} love {name}".format(name = a, name2=b))
print("{} love {}".format(b, c))
#tuple pass value
a = "I"
b = "You"
c = "Me"
print("%s love %s"%(a,b))
print("{} love {}".format(b, c))
#tuple pass value
a = "I"
b = "You"
c = "Me"
print("%(hoi)s love %(hey)s"%{"hey" : a,"hoi" : b})
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 17:31:45 2019
@author: niko1
"""
def resolver1(pal1,pal2):
#frozenset re ordena los caracteres en formato ASCII, pasando, por ejemplo, la palabra cosa a a-c-o-s
x = frozenset(pal1)
y = frozenset(pal2)
if(x==y):
print(pal2,' es un anagrama de ',pal1)
else:
print(pal2,' no es un anagrama de ',pal1)
def resolver2(pal1,pal2):
#este metodo vera si las letras de ambas palabras coinciden, si todas coinciden, quiere decir que son anagramas, pues elimina la revision de una misma letra
aux = []
aux2 = []
pasa=1
for i in range (len(pal1)): #vamos letra por letra evaluando la palabra 1
for j in range (len(pal1)): #lo mismo con la palabra 2
if(pal1[i]==pal2[j]):
if not aux:
aux.append(j)
aux2.append(pal2[j])
break
else:
pasa=1
for k in range (len(aux)):
if(aux[k]==j):
pasa=0
if(pasa==1):
aux.append(j)
aux2.append(pal2[j])
if(len(pal1)==len(aux2)):
print(pal2,' es un anagrama de ',pal1)
else:
print(pal2,' no es un anagrama de ',pal1)
def resolver3(x,y):
cont=0
letrasx = []
letrasy = []
contx = []
conty = []
seguir=1
for i in range (len(x)):
entra=1
if not letrasx:
letrasx.append(x[i])
cont=cont+1
else:
for j in range (len(letrasx)):
if(letrasx[j]==x[i]):
entra=0
if(entra==1):
letrasx.append(x[i])
cont=cont+1
cont=0
for i in range (len(y)):
entra=1
if not letrasy:
letrasy.append(y[i])
cont=cont+1
else:
for j in range (len(letrasy)):
if(letrasy[j]==y[i]):
entra=0
if(entra==1):
letrasy.append(y[i])
cont=cont+1
for i in range (len(letrasx)):
igual=0
for j in range (len(letrasy)):
if(letrasx[i]==letrasy[j]):
igual=1
if(igual==0):
print(y,' no es un anagrama de ',x)
seguir=0
break
if(seguir==1):
for i in range (len(letrasx)):
contador=0
for j in range (len(x)):
if(letrasx[i]==x[j]):
contador=contador+1
contx.append(contador)
for i in range (len(letrasy)):
contador=0
for j in range (len(y)):
if(letrasy[i]==y[j]):
contador=contador+1
conty.append(contador)
for i in range (len(letrasx)):
for j in range (len(letrasy)):
if(letrasx[i]==letrasy[j]):
print(contx[i])
if(contx[i]!=conty[j]):
print(y,' no es un anagrama de ',x)
seguir=0
break
if(seguir==1):
print (y,'es un anagrama de ',x)
x=input('escriba una palabra: ')
y=input('escriba otra palabra: ')
if(len(x)==len(y)): #len() nos da el tamaño del string, si son iguales, entrara en alguna funcion
resolver1(x,y)
resolver2(x,y)
resolver3(x,y)
else:
print(y,'no puede ser un anagrama de ',x,' pues no tienen el mismo largo de letras')
|
import numpy as np
class Hill_cipher:
'Hill cipher is use matrix as key. in this block by block encryption'
list1=[]
list2=[]
pt=[]
pt1=[]
ct=[]
k=[]
n=1
key=[]
inverseKey=[]
result=[]
planeText=""
cipherText=""
def input_pt(self):
#only enter 9 element
self.planeText=input('enter the plane text:')
#self.key=[[2,4,5],[9,2,1],[3,17,7]]
self.key=[[3,10,20],[20,9,17],[9,4,17]]
self.inverseKey=[[11,22,14],[7,9,21],[17,0,3]]
def input_key(self):
print('for matrix size')
print('enter 1 for 3x3')
print('enter 2 or greter than 2 for 4x4')
self.n=int(input('enter 1 or 2 for matrix size:'))
if(self.n==1):
#self.key=[[0,0,0],[0,0,0],[0,0,0]]
for i in list(range(3)):
for j in list(range(3)):
self.key[i][j]=int(input())
else:
self.key=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for i in list(range(4)):
for j in list(range(4)):
self.key[i][j]=int(input())
def encryption(self):
self.pt=list(self.planeText)
for i in list(range(len(self.pt))):
self.pt1.append(ord(self.pt[i])-97)
m=0
if(self.n>-1):
a=[[0],[0],[0]]
for i in list(range(3)):
for j in list(range(3)):
a[j][0]=ord(self.pt[m])-97
m=m+1
#print(a)
r=np.matmul(self.key,a)
#print(r)
for q in list(range(3)):
self.ct.append(chr(r[q][0]%26+97))
#print(self.ct)
self.cipherText = ''.join(str(e) for e in self.ct)
else:
print('1')
def decryption(self):
self.ct1=list(self.cipherText)
m=0
#print(self.inverseKey)
a=[[0],[0],[0]]
for i in list(range(3)):
for j in list(range(3)):
a[j][0]=ord(self.ct1[m])-97
m=m+1
#print(a)
r=np.matmul(self.inverseKey,a)
#print(r)
for q in list(range(3)):
self.pt1.append(chr(r[q][0]%26+97))
#print(self.ct)
self.cipherText = ''.join(str(e) for e in self.ct1)
def display1(self):
print('--------------------------------------------------------------------------------------------------------------------------------------------')
print('-----------encryption--------------')
print('plane text is : ',self.planeText)
print('cipher text is: ',self.cipherText)
print('key is : ',self.key)
print('--------------------------------------------------------------------------------------------------------------------------------------------')
def display2(self):
print('--------------------------------------------------------------------------------------------------------------------------------------------')
print('-----------encryption--------------')
print('plane text is : ',self.planeText)
print('cipher text is: ',self.cipherText)
print('key is : ',self.inverseKey)
print('--------------------------------------------------------------------------------------------------------------------------------------------')
h=Hill_cipher()
h.input_pt()
print(h.key)
#h.input_key()
h.encryption()
h.display1()
h.decryption()
h.display2()
|
import pygame
import defs
import colors
import random
pygame.init()
class Grid():
def __init__(self):
self.x = defs.width * defs.x_grid_gap
self.y = defs.height * defs.y_grid_gap
self.square_len = defs.grid_square_len
self.width = self.square_len * defs.x_grid_squares
self.height = self.square_len * defs.y_grid_squares
self.dominos = defs.dominos[:]
self.grid_numbers = []
self.grid = []
self.false_value = 8
def grid_number_place(self, domino1, domino2):
# random chance to place the domino vertically or horizontally
x_or_y = random.randrange(0, 2)
for row in range(len(self.grid_numbers)):
for square in range(len(self.grid_numbers[row])):
if self.grid_numbers[row][square] == self.false_value:
self.grid_numbers[row][square] = domino1
if row == defs.y_grid_squares - 1 and self.grid_numbers[row][square + 1] == self.false_value or self.grid_numbers[row + 1][square] != self.false_value:
self.grid_numbers[row][square + 1] = domino2
return
if square == defs.x_grid_squares - 1 and self.grid_numbers[row + 1][square] == self.false_value or self.grid_numbers[row][square + 1] != self.false_value:
self.grid_numbers[row + 1][square] = domino2
return
if x_or_y == 0 and self.grid_numbers[row][square + 1] == self.false_value:
self.grid_numbers[row][square + 1] = domino2
return
if x_or_y == 1 and self.grid_numbers[row + 1][square] == self.false_value:
self.grid_numbers[row + 1][square] = domino2
return
else:
return False
def init_grid_numbers(self):
self.grid_numbers = []
self.dominos = defs.dominos[:]
# Fill with false values
for y in range(defs.y_grid_squares):
row = []
for x in range(defs.x_grid_squares):
row.append(self.false_value)
self.grid_numbers.append(row)
# Places dominos in grid
for n in range(len(self.dominos)):
random_index = random.randrange(0, len(self.dominos))
domino = self.dominos.pop(random_index)
domino1 = domino[0]
domino2 = domino[1]
# random chance to invert the domino
invert = random.randrange(0, 2)
if invert == 1:
domino1 = domino[1]
domino2 = domino[0]
self.grid_number_place(domino1, domino2)
def render_grid(self):
pygame.draw.rect(defs.display, colors.BLACK, (self.x - 1, self.y - 1 , self.width + 2, self.height + 2), 1)
for y in range(defs.y_grid_squares):
for x in range(defs.x_grid_squares):
pygame.draw.rect(defs.display, colors.BLACK, (self.x + (self.square_len * x), self.y + (self.square_len * y), self.square_len, self.square_len), 1)
self.grid.append(pygame.Rect(self.x + (self.square_len * x), self.y + (self.square_len * y), self.square_len, self.square_len))
def square_highlight(self, rect):
pygame.draw.rect(defs.display, colors.YELLOW, (rect))
|
# making right trinagle
'''
like this:
*
**
***
****
*****
******
'''
x = int(input('inter the hight of triangle: '))
star = "*"
for i in range(x):
print('{}'.format(star * i))
# making isosceles triangle
for i in range(x):
print("{}".format((star*i).center(x+1)))
# making right 90^ triangle
for i in range(x):
print('{}'.format((star*i).rjust(x+1)))
|
"""
INSERT YOUR NAME HERE
"""
from __future__ import division
from __future__ import print_function
import sys
import cPickle
import numpy as np
# This is a class for a LinearTransform layer which takes an input
# weight matrix W and computes W x as the forward step
class LinearTransform(object):
def __init__(self, W, b):
# DEFINE __init function
def forward(self, x):
# DEFINE forward function
def backward(
self,
grad_output,
learning_rate=0.0,
momentum=0.0,
l2_penalty=0.0,
):
# DEFINE backward function
# ADD other operations in LinearTransform if needed
# This is a class for a ReLU layer max(x,0)
class ReLU(object):
def forward(self, x):
# DEFINE forward function
def backward(
self,
grad_output,
learning_rate=0.0,
momentum=0.0,
l2_penalty=0.0,
):
# DEFINE backward function
# ADD other operations in ReLU if needed
# This is a class for a sigmoid layer followed by a cross entropy layer, the reason
# this is put into a single layer is because it has a simple gradient form
class SigmoidCrossEntropy(object):
def forward(self, x):
# DEFINE forward function
def backward(
self,
grad_output,
learning_rate=0.0,
momentum=0.0,
l2_penalty=0.0
):
# DEFINE backward function
# ADD other operations and data entries in SigmoidCrossEntropy if needed
# This is a class for the Multilayer perceptron
class MLP(object):
def __init__(self, input_dims, hidden_units):
# INSERT CODE for initializing the network
def train(
self,
x_batch,
y_batch,
learning_rate,
momentum,
l2_penalty,
):
# INSERT CODE for training the network
def evaluate(self, x, y):
# INSERT CODE for testing the network
# ADD other operations and data entries in MLP if needed
if __name__ == '__main__':
data = cPickle.load(open('cifar_2class_py2.p', 'rb'))
train_x = data['train_data']
train_y = data['train_labels']
test_x = data['test_data']
test_y = data['test_labels']
num_examples, input_dims = train_x.shape
# INSERT YOUR CODE HERE
# YOU CAN CHANGE num_epochs AND num_batches TO YOUR DESIRED VALUES
num_epochs = 10
num_batches = 1000
mlp = MLP(input_dims, hidden_units)
for epoch in xrange(num_epochs):
# INSERT YOUR CODE FOR EACH EPOCH HERE
for b in xrange(num_batches):
total_loss = 0.0
# INSERT YOUR CODE FOR EACH MINI_BATCH HERE
# MAKE SURE TO UPDATE total_loss
print(
'\r[Epoch {}, mb {}] Avg.Loss = {:.3f}'.format(
epoch + 1,
b + 1,
total_loss,
),
end='',
)
sys.stdout.flush()
# INSERT YOUR CODE AFTER ALL MINI_BATCHES HERE
# MAKE SURE TO COMPUTE train_loss, train_accuracy, test_loss, test_accuracy
print()
print(' Train Loss: {:.3f} Train Acc.: {:.2f}%'.format(
train_loss,
100. * train_accuracy,
))
print(' Test Loss: {:.3f} Test Acc.: {:.2f}%'.format(
test_loss,
100. * test_accuracy,
))
|
# tutorial: https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/
import numpy as np
import pandas as pd
import keras
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, confusion_matrix
from matplotlib import pyplot as plt
# losses from training
losses = []
# callback used to append losses during training
class LossHistory(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
losses.append(logs.get('loss'))
# convert time series to supervised learning problem
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = pd.DataFrame(data)
cols, names = list(), list()
# input sequence (t-n, ..., t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
# forecast sequence (t, t+1, ..., t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
# put all together
agg = pd.concat(cols, axis=1)
agg.columns = names
# drop row with NaN vals
if dropnan:
agg.dropna(inplace=True)
return agg
# create a differenced series (each data point is changed from a price to a change in price)
def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i-interval]
diff.append(value)
return pd.Series(diff)
# transform series into train and test sets for supervised learning
def prepare_data(series, n_test, n_lag, n_seq):
raw_values = series.values
# transform data to be stationary
diff_series = difference(raw_values, 1)
diff_values = diff_series.values
diff_values = diff_values.reshape(len(diff_values), 1)
# rescale vals to -1, 1
scaler = MinMaxScaler(feature_range=(-1, 1))
scaled_values = scaler.fit_transform(diff_values)
scaled_values = scaled_values.reshape(len(scaled_values), 1)
# transform into supervised learning problem X, y
supervised = series_to_supervised(scaled_values, n_lag, n_seq)
supervised_values = supervised.values
# split into train and test sets
train, test = supervised_values[0:-n_test], supervised_values[-n_test:]
return scaler, train, test
# fit an LSTM network to training data
def fit_lstm(train, n_lag, n_seq, n_batch, n_epoch, n_neurons):
# reshape training into [samples, timesteps, features]
X, y = train[:, 0:n_lag], train[:, n_lag:]
X = X.reshape(X.shape[0], 1, X.shape[1])
# design network
model = keras.models.Sequential()
model.add(keras.layers.LSTM(n_neurons, batch_input_shape=(n_batch, X.shape[1], X.shape[2]), stateful=True))
model.add(keras.layers.Dense(y.shape[1]))
model.compile(loss='mean_squared_error', optimizer='adam')
history = LossHistory()
print("Training progress:")
# fit network, manually loop through epochs to control statefulness of model
for i in range(n_epoch):
if np.mod(i, n_epoch/10) == 0 and i != 0:
print('%d%% complete' % (i*100/n_epoch))
model.fit(X, y, epochs=1, batch_size=n_batch, verbose=0, shuffle=False, callbacks=[history])
model.reset_states()
print('Done')
print('Losses =', losses)
return model
def update_lstm(model, train, n_lag, n_batch, n_epoch):
# reshape training into [samples, timesteps, features]
X, y = train[:, 0:n_lag], train[:, n_lag:]
X = X.reshape(X.shape[0], 1, X.shape[1])
# fit network, manually loop through epochs to control statefulness of model
for i in range(n_epoch):
model.fit(X, y, epochs=1, batch_size=n_batch, verbose=0, shuffle=False)
model.reset_states()
return model
def forecast_lstm(model, X, n_batch):
# reshape input pattern to [samples, timesteps, features]
X = X.reshape(1, 1, len(X))
# make forecast
forecast = model.predict(X, batch_size=n_batch)
# convert to array
return [x for x in forecast[0, :]]
# make price prediction
def make_forecasts(model, n_batch, train, test, n_lag, n_seq, updateLSTM=False):
forecasts = list()
print('\nMaking predictions')
for i in range(len(test)):
X, y = test[i, 0:n_lag], test[i, n_lag:]
# LSTM forecast
forecast = forecast_lstm(model, X, n_batch)
# store forecast
forecasts.append(forecast)
# add new data to retrain
if updateLSTM:
if np.mod(i, round(len(test)/10)) == 0 and i != 0:
print('%d%% complete' % round(i * 100 / len(test)))
row = train.shape[0]
col = train.shape[1]
train = np.append(train, test[i])
train = train.reshape(row + 1, col)
model = update_lstm(model, train, n_lag, n_batch, n_epoch=1)
print('Done')
return forecasts
# invert differenced forecast
def inverse_difference(last_ob, forecast):
# invert first forecast
inverted = list()
inverted.append(forecast[0] + last_ob)
# propagate difference forecast using inverted first val
for i in range(1, len(forecast)):
inverted.append(forecast[i] + inverted[i-1])
return inverted
# inverse data transform on forecasts
def inverse_transform(series, forecasts, scaler, n_test):
inverted = list()
for i in range(len(forecasts)):
# create array from forecast
forecast = np.array(forecasts[i])
forecast = forecast.reshape(1, len(forecast))
# invert scaling
inv_scale = scaler.inverse_transform(forecast)
inv_scale = inv_scale[0, :]
# invert differencing
index = len(series) - n_test + i - 1
last_ob = series.values[index]
inv_diff = inverse_difference(last_ob, inv_scale)
# store
inverted.append(inv_diff)
return inverted
# evaluate the RMSE for each forecast time step
def evaluate_forecasts(test, forecasts, n_lag, n_seq):
for i in range(n_seq):
actual = [row[i] for row in test]
predicted = [forecast[i] for forecast in forecasts]
predictedDirections = list()
for j, currentPrice in enumerate(actual):
if j == (len(actual)-1):
break
predictedDir = np.sign(predicted[j+1] - currentPrice)
predictedDirections.append(predictedDir)
actualDirections = np.sign(np.diff(actual))
tn, fp, fn, tp = confusion_matrix(actualDirections, predictedDirections, [-1, 1]).ravel()
accuracy = (tp+tn) / (tp+tn+fp+fn)
rmse = (mean_squared_error(actual, predicted))**0.5
print('\nt+%d' % (i+1))
print('RMSE: %f' % rmse)
print('Accuracy of direction: %f' % accuracy)
# plot forecasts in context of original dataset
# also connect persisted forecast to actual persisted value in original dataset
def plot_forecasts(series, forecasts, n_test):
# plot entire dataset in blue
plt.plot(series.values)
# plot forecasts in red
for i in range(len(forecasts)):
off_s = len(series) - n_test + i - 1
off_e = off_s + len(forecasts[i]) + 1
xaxis = [x for x in range(off_s, off_e)]
yaxis = [series.values[off_s]] + forecasts[i]
plt.plot(xaxis, yaxis, color='red')
plt.xlabel('Data point')
plt.ylabel('Price')
# plot loss of training
def plot_loss():
plt.plot(losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
# save trained network
def save_network(model, n_neurons, n_epochs):
# serialize model to JSON
model_json = model.to_json()
filename = "saved_networks/model_%dneu_%depoch" % (n_neurons, n_epochs)
with open(filename + ".json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights(filename + ".h5")
print("Saved model to disk")
# load previously trained network
def load_network(n_neurons, n_epochs):
filename = "saved_networks/model_%dneu_%depoch" % (n_neurons, n_epochs)
# load json and create model
json_file = open(filename + ".json", "r")
loaded_model_json = json_file.read()
json_file.close()
loaded_model = keras.models.model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights(filename + ".h5")
loaded_model.compile(loss='mean_squared_error', optimizer='adam')
print("Loaded model from disk")
return loaded_model
# configure parameters
# number of previous timesteps (in his case the timestep is one day) to
# use in making predictions (t-n_lag, t-n_lag+1, ..., t-2, t-1)
n_lag = 3
# number of timesteps to predict program will predict the next n_seq
# prices from each testing timestep (t, t+1, ..., t+n_seq)
n_seq = 1
# number of epochs to train network or used to train loaded network
n_epochs = 4
# batch size
n_batch = 1
# number of LSTM neurons in model
n_neurons = 1
# specifies if network should retrain with new data after making each prediction (greatly slows down forecasts)
updateLSTM = False
# specifies if network should be trained or loaded from last training
load_model = True
# load dataset
series = pd.read_csv('5yr-SP-data.csv')
sp_series = series['S&P Open']
# use only last ~500 data points (1259 total)
sp_series = sp_series[800:]
# number of timesteps to test model
n_test = int(len(sp_series) * 0.20)
# prepare data
scaler, train, test = prepare_data(sp_series, n_test, n_lag, n_seq)
if load_model:
model = load_network(n_neurons, n_epochs)
else:
# fit network
model = fit_lstm(train, n_lag, n_seq, n_batch, n_epochs, n_neurons)
# make forecast
forecasts = make_forecasts(model, n_batch, train, test, n_lag, n_seq, updateLSTM)
# inverse transform forecasts and test
forecasts = inverse_transform(sp_series, forecasts, scaler, n_test+n_seq-1)
actual = [row[n_lag:] for row in test]
actual = inverse_transform(sp_series, actual, scaler, n_test+n_seq-1)
# evaluate and plot forecasts
print('\nParameters:\nNeurons =', n_neurons, '\nLag =', n_lag, '\nEpochs =', n_epochs)
evaluate_forecasts(actual, forecasts, n_lag, n_seq)
plt.figure(1)
# if model was loaded, just plot forecast, else plot loss as well
if load_model:
plot_forecasts(sp_series, forecasts, n_test + n_seq - 1)
else:
plt.subplot(211)
plot_forecasts(sp_series, forecasts, n_test+n_seq-1)
plt.subplot(212)
plot_loss()
plt.show()
if not load_model:
save_model = input('Do you want to save this network? This will overwrite any previously saved network with the same parameters\n(y/n) ')
if save_model.lower() == 'y':
# save network
save_network(model, n_neurons, n_epochs) |
import math
import unittest
from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if i - coin < 0:
continue
else:
dp[i] = min(dp[i], 1 + dp[i - coin])
return int(dp[-1]) if dp[-1] != amount + 1 else -1
class Test(unittest.TestCase):
def test_one(self):
coins = [1, 2, 5]
amount = 11
answer = 3
result = Solution().coinChange(coins, amount)
self.assertEqual(answer, result)
def test_two(self):
coins = [2]
amount = 3
answer = -1
result = Solution().coinChange(coins, amount)
self.assertEqual(answer, result)
|
import unittest
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(pos, target):
if 0 == target:
res.append(stack[:])
elif 0 < target:
for i in range(pos, len(candidates)):
if i > pos and candidates[i] == candidates[i - 1]: # 排序后, 如果以当前节点作为子树根节点已经搜索过, 则剪枝
continue
if target - candidates[i] < 0: # 排序后, 如果stack已经大于target, 剪枝掉后续的子树
break
stack.append(candidates[i])
backtrack(i + 1, target - candidates[i])
stack.pop()
res = []
stack = []
candidates.sort()
backtrack(0, target)
return res
class Test(unittest.TestCase):
def test_one(self):
candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
answer = [[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]]
result = Solution().combinationSum2(candidates, target)
self.assertEqual(answer, result)
|
import unittest
from typing import List
class Solution:
def convertToBase7(self, num: int) -> str:
base7 = []
isNegative = False
if num < 0:
isNegative = True
num = -num
while num >= 7:
base7.append(str(num % 7))
num = num // 7
base7.append(str(num))
if isNegative:
base7.append('-')
base7.reverse()
return ''.join(base7)
class Test(unittest.TestCase):
def test_one(self):
nums = 100
answer = "202"
result = Solution().convertToBase7(nums)
self.assertEqual(answer, result)
|
import unittest
from typing import List
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
def dfs(pos, B):
print(num, A[pos], B)
if pos == len(A) or len(B) == 0:
result.append(num[0])
return
for i in range(len(B)):
if A[pos] == B[i]:
num[0] += 1
dfs(pos + 1, B[i + 1:])
num[0] -= 1
return
else:
dfs(pos, B[i + 1:])
num = [0]
result = []
print(result)
dfs(0, B)
return max(result)
class Test(unittest.TestCase):
def test_one(self):
A = [1, 4, 2]
B = [1, 2, 4]
answer = 2
result = Solution().maxUncrossedLines(A, B)
self.assertEqual(answer, result)
def test_two(self):
A = [1, 3, 7, 1, 7, 5]
B = [1, 9, 2, 5, 1]
answer = 2
result = Solution().maxUncrossedLines(A, B)
self.assertEqual(answer, result)
|
import unittest
from typing import List
class Solution:
def __init__(self):
self.dp = []
for i in range(5):
self.dp.append(i)
def integerBreak(self, n: int) -> int:
if n < 4:
return n - 1
elif 4 < n < len(self.dp):
return self.dp[n]
for i in range(len(self.dp), n + 1):
max_i = 0
for j in range(2, i // 2 + 1):
max_i = max(self.dp[j] * self.dp[i - j], max_i)
self.dp.append(max_i)
return self.dp[n]
class Test(unittest.TestCase):
def test_one(self):
nums = 10
answer = 36
result = Solution().integerBreak(nums)
self.assertEqual(answer, result)
|
import unittest
from collections import defaultdict
from typing import List
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
d = {0: -1}
count = 0
max_len = 0
for index, num in enumerate(nums):
if num == 0:
count -= 1
else:
count += 1
if count not in d.keys():
d[count] = index
else:
max_len = max(max_len, index - d[count])
return max_len
class Test(unittest.TestCase):
def test_one(self):
nums = [0, 1, 0, 0, 1, 1, 0]
answer = 6
result = Solution().findMaxLength(nums)
self.assertEqual(answer, result)
class Test(unittest.TestCase):
def test_one(self):
nums = [0, 1]
answer = 2
result = Solution().findMaxLength(nums)
self.assertEqual(answer, result)
|
import math
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def push(self, x):
self.stack.append(x)
self.min_stack.append(min(x, self.min_stack[-1]))
def pop(self):
self.stack.pop()
self.min_stack.pop()
def top(self):
print(self.stack[-1])
return self.stack[-1]
def getMin(self):
print(self.min_stack[-1])
return self.min_stack[-1]
miniStack = MinStack()
n = int(input())
for i in range(n):
line = input().split()
if len(line) == 2:
miniStack.push(int(line[1]))
elif line[0] == 'top':
miniStack.top()
elif line[0] == 'pop':
miniStack.pop()
elif line[0] == 'getMin':
miniStack.getMin()
|
import requests
import json
host_url = "http://thetestingworldapi.com"
body = {
"id": 555,
"first_name": "monika",
"middle_name": "sen",
"last_name": "gupta",
"date_of_birth": "11/11/1985"
}
response_code = requests.post(host_url+"/api/studentsDetails", data=body)
print("the response for this GET request is")
print(response_code)
if response_code.ok:
print("This request has no error")
else:
print("This request has an error")
response_result = (json.dumps(response_code.json(), indent=4))
print(response_result)
if response_result.lower():
print("The strings are lowerCase")
else:
print("The strings are not lower case")
# parse the JSON object into a dict
slideInfo = json.loads(response_result)
print(slideInfo["first_name"])
|
import anagram, getopt, Levenshtein, string, sys, ap_encoding
THRESHHOLD = 3
def distance(w1, w2):
return Levenshtein.distance(w1,w2)
def get_distance(text):
exclude = set(string.punctuation)
text = ''.join(ch for ch in text if not ch in exclude)
words = text.split()
return [words[i] for i in xrange(len(words)) if i < len(words) - 1 and distance(words[i], words[i+1]) <= THRESHHOLD]
def main(argv):
global THRESHHOLD
#get arguments passed, where "text" is path to scratch/
try:
opts,args = getopt.getopt(argv,"t:l:",["text=","lttr="])
except getopt.GetoptError:
print "levdistance.py -t <text> -l <distance>"
sys.exit(2)
for opt,arg in opts:
if opt == "-h":
print "levdistance.py -t <text> -l <distance>"
elif opt in ("-t","--text"):
text = arg
elif opt in ("-l","--dist"):
if arg: THRESHHOLD = int(arg)
else:
sys.exit(2)
#read file from path
text = ap_encoding.read_file(text)
result = get_distance(text)
print ' '.join(result)
if __name__ == "__main__":
main(sys.argv[1:])
|
#! /usr/bin/python
import getopt, re, sys, ap_encoding
def powerball(text,balls):
#initialize containers, explode word array, parse out the last number as the "powerball"
index = 0
result = ""
ball = []
full_text = text.split()
ball = balls.split()
powerball = ball[5]
#remove the last number of sequence from searchable array
del ball[-1]
#search text, pulling out appropriate numbers based on current sequence
for x in range(0,len(full_text)):
for i in range (0,len(ball)):
index = index + int(ball[i])-1
if index < len(full_text):
result = result + full_text[index] + " ";
if x < len(full_text):
result = result + "\n"
#return text in addition to the "powerball" word as title
return full_text[int(powerball)] + "\n" + " " + "\n" + result.rstrip()
def main(argv):
#get argumetns passed, where "text" is path to scratch/, "lttr" is numerical powerball sequence
try:
opts,args = getopt.getopt(argv,"t:l:",["text=","lttr="])
except getopt.GetoptError:
print "powerball.py -t <text> -l <Powerball numbers (in sequence)>"
sys.exit(2)
for opt,arg in opts:
if opt == "-h":
print "powerball.py -t <text> -l <Powerball numbers (in sequence)>"
elif opt in ("-t","--text"):
text = arg
elif opt in ("-l","--balls"):
balls = arg
else:
sys.exit(2)
#read text from file
text = ap_encoding.read_file(text)
print powerball(text,balls)
if __name__ == "__main__":
main(sys.argv[1:])
|
def toStr(n,base):
convertString='0123456789ABCDEF'
if n<base:
return convertString[n]
else:
return toStr(n//base,base)+convertString[n%base]
# 使用栈
class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
rStack=Stack()
def toStrStack(n,base):
convertString='0123456789ABCDEF'
while n>0:
if n<base:
rStack.push(convertString[n])
else:
rStack.push(convertString[n%base])
n=n//base
res=""
while not rStack.isEmpty():
res=res+str(rStack.pop())
return res
print(toStrStack(10,2))
import turtle
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
def drawSpiral(myTurtle, lineLen):
if lineLen > 0:
myTurtle.forward(lineLen)
myTurtle.right(90)
drawSpiral(myTurtle,lineLen-5)
# drawSpiral(myTurtle,100)
# myWin.exitonclick()
# 绘制树
def tree(branchLen,t):
if branchLen > 5:
t.forward(branchLen)
t.right(20)
tree(branchLen-15,t)
t.left(40)
tree(branchLen-15,t)
t.right(20)
t.backward(branchLen)
# def main():
# t = turtle.Turtle()
# myWin = turtle.Screen()
# t.left(90)
# t.up()
# t.backward(100)
# t.down()
# t.color("green")
# tree(100,t)
# myWin.exitonclick()
# main()
# 绘制三角形
def drawTriangle(points,color,myTurtle):
myTurtle.fillcolor(color)
myTurtle.up()
myTurtle.goto(points[0][0],points[0][1])
myTurtle.down()
myTurtle.begin_fill()
myTurtle.goto(points[1][0],points[1][1])
myTurtle.goto(points[2][0],points[2][1])
myTurtle.goto(points[0][0],points[0][1])
myTurtle.end_fill()
def getMid(p1,p2):
return ((p1[0]+p2[0])/2,(p1[1]+p2[1])/2)
def sierpinski(points,degree,myTurtle):
colormap=['blue','red','green','white','yellow','violet','orange']
drawTriangle(points,colormap[degree],myTurtle)
if degree>0:
sierpinski([points[0],getMid(points[0],points[1]),
getMid(points[0],points[2])],
degree-1,myTurtle)
sierpinski([points[1], getMid(points[0], points[1]),
getMid(points[1], points[2])],
degree - 1, myTurtle)
sierpinski([points[2], getMid(points[2], points[1]),
getMid(points[0], points[2])],
degree - 1, myTurtle)
def main():
myTurtle=turtle.Turtle()
myWin=turtle.Screen()
myPoints=[[-100,-50],[0,100],[100,-50]]
sierpinski(myPoints,3,myTurtle)
myWin.exitonclick()
main()
|
class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s=Stack()
# 检测括号(是否匹配
def parChecker(symbolString):
s=Stack()
balanced=True
index=0
while index<len(symbolString) and balanced:
symbol=symbolString[index]
if symbol=='(':
s.push(symbol)
else:
if s.isEmpty():
balanced=False
else:
s.pop()
index=index+1
if balanced and s.isEmpty():
return True
else:
return False
# 检测符号[]{}()匹配
def parChecker1(symbolString):
s=Stack()
balanced=True
index=0
while index<len(symbolString) and balanced:
symbol=symbolString[index]
if symbol in '([{':
s.push(symbol)
else:
if s.isEmpty():
balanced=False
else:
top=s.pop()
if not matched(top,symbol):
balanced=False
index=index+1
if balanced and s.isEmpty():
return True
else:
return False
def matched(open,close):
opens='([{'
closers=')]}'
return opens.index(open)==closers.index(close)
# print(parChecker1('{[][()]()}'))
# 除2算法
def divideBy2(decNumber):
remstack=Stack()
while decNumber>0:
rem=decNumber%2
remstack.push(rem)
decNumber=decNumber//2
binString=""
while not remstack.isEmpty():
binString=binString+str(remstack.pop())
return binString
# print(divideBy2(233))
# 十进制数和 2-16之间的任何基数
def baseConverter(decNumber,base):
digits="0123456789ABCDEF"
remstack=Stack()
while decNumber>0:
rem=decNumber%base
remstack.push(rem)
decNumber=decNumber//base
newString=""
while not remstack.isEmpty():
newString=newString+digits[remstack.pop()]
return newString
# print(baseConverter(233,2))
# print(baseConverter(233,16))
# 中缀表达式转后缀
# 使用一个名为prec的字典来保存操作符的优先级
# 这个点将每个运算符映射到一个整数,可以与其他运算符的优先级(是固体部分整数3,2,1)进行比较
# 左括号被赋予最低的值,这样,与其进行比较的任何运算符都将具有更高的优先级,将被放置在它的顶部
def infixToPostfix(infixexpr):
prec={}
prec['*']=3
prec['/']=3
prec['+']=2
prec['-']=2
prec['(']=1
opStack=Stack()
postfixList=[]
tokenList=infixexpr.split()
for token in tokenList:
if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in "0123456789":
postfixList.append(token)
elif token=='(':
opStack.push(token)
elif token==')':
topToken=opStack.pop()
while topToken!='(':
postfixList.append(topToken)
topToken=opStack.pop()
else:
while(not opStack.isEmpty()) and (prec[opStack.peek()]>=prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)
# 计算后缀表达式的值
def postfixEval(postfixExpr):
operandStack=Stack()
tokenList=postfixExpr.split()
for token in tokenList:
if token in '0123456789':
operandStack.push(int(token))
else:
operand2=operandStack.pop()
operand1=operandStack.pop()
result=doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
def doMath(op,op1,op2):
if op=="*":
return op1*op2
elif op=='/':
return op1/op2
elif op=='+':
return op1+op2
else:
return op1-op2
print(postfixEval('7 8 + 3 2 + /'))
|
#python内建的filter()函数用于过滤序列
#和map()类似,filter()也接收一个函数和一个序列,和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False
#决定保留还是丢弃该元素
#在一个list中,删掉偶数,只保留奇数:
def is_odd(n):
return n%2==1
list(filter((is_odd,[1,2,3,4,5,6,7,8])))
|
#当我们在传入函数时,有时候不需要显示定义函数,直接传入匿名函数更方便
list(map(lambda x:x*x,[1,2,3,4,5,6]))
#通过对比可以看出,匿名函数lamaba x:x*x实际上就是
def f(x):
return x*x
#关键字lamba表示匿名函数,冒号前面的x表示函数参数
#匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果
#用匿名函数的好处是,函数没有名字,不必担心函数名冲突。
#此外,匿名函数也是一个函数对象,也可以吧匿名函数复制给一个变量,在利用变量来调用该函数。
f=lambda x:x*x
#也可以吧匿名函数作为返回值返回
def build(x,y):
return lambda :x*x+y*y |
# Maximum Edge of a Triangle
# Create a function that finds the maximum range of
# a triangle's third edge, where the side lengths are all integers.
def next_edge(side1, side2):
# side1 - side2 < side3 < side1 + side2
side3_max = (side1 + side2) - 1
print(side3_max)
return (side1 + side2) - 1
next_edge(8, 10) #17
next_edge(5, 7) # 11
next_edge(9, 2) # 10 |
# Luke, I Am Your ...
# Luke Skywalker has family and friends.
# Help him remind them who is who.
# Given a string with a name,
# return the relation of that person to Luke.
# Person Relation
# Darth Vader father
# Leia sister
# Han brother in law
# R2D2 droid
# Examples
# relation_to_luke("Darth Vader") ➞ "Luke, I am your father."
# relation_to_luke("Leia") ➞ "Luke, I am your sister."
# relation_to_luke("Han") ➞ "Luke, I am your brother in law."
relationships = {"Darth Vader" : "father",
"Leia" : "sister",
"Han" : "brother in law",
"R2D2" : "droid"}
def relation_to_luke(relationship):
print(f"Luke, I am your {relationships[relationship]}.")
relation_to_luke("Darth Vader")
relation_to_luke("Leia")
relation_to_luke("Han")
print("----")
def relation_to_luke2(name):
family={'Darth Vader':'father','Leia':'sister','Han':'brother in law','R2D2':'droid'}
return "Luke, I am your {}.".format(family[name])
print(relation_to_luke2('Leia'))
print(relation_to_luke2("Darth Vader"))
print(relation_to_luke2("Han")) |
# Find the Perimeter of a Rectangle
# Create a function that takes
# length and width and finds the perimeter of a rectangle.
def find_perimeter(side1, side2):
perimeter = (side1 + side2) * 2
print(perimeter)
return (side1 + side2) * 2
find_perimeter(6, 7) # ➞ 26
find_perimeter(20, 10) # ➞ 60
find_perimeter(2, 9) # ➞ 22 |
import numpy as np
a=np.array([1,2,3]) #declares an array with type as numpy.ndarray
print(a.shape) #prints size
#all the elements can be changed and can be brought by normal indexing
b = np.array([[1,2,3],[4,5,6]]) #2d array
print(b.shape) # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0]) # [x,y] x is for lists y is for elements in the list
a = np.zeros((2,2)) # Create an array of all zeros
print(a) # Prints "[[ 0. 0.][ 0. 0.]]"
b = np.ones((1,2)) # Create an array of all ones
print(b) # Prints "[[ 1. 1.]]"
c = np.full((2,2), 7) # Create a constant array
print(c) # Prints "[[ 7. 7.][ 7. 7.]]"
d = np.eye(2) # Create a 2x2 identity matrix
print(d) # Prints "[[ 1. 0.][ 0. 1.]]"
arr=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
# slicing van also be done here
sub_arr=arr[:2,1:3] #rows x columns
#below are the same statements
print(arr[[0, 1, 2], [0, 1, 0]]) #prints (0,0) (1,1) (2,0)
poi=np.arange(4) #gives array from 0 to 3
#math funcs + - * / sqrt mean can be called
#dot function is used to make matrix multiplication
l=np.array([1,5,8,6])
m=np.array([[1],[5],[6],[8]])
print(l.dot(m)) # both are same
print(np.dot(l,m))
print(np.sum(arr)) # Compute sum of all elements;
print(np.sum(arr, axis=0)) # Compute sum of each column;
print(np.sum(arr, axis=1)) # Compute sum of each row
arr.transpose()
fgt = np.empty_like(arr) # Create an empty matrix with the same shape as arr
npoints = 20
slope = 2
offset = 3
x = np.arange(npoints)
y = slope * x + offset + np.random.normal(size=npoints)
print(y)
p = np.polyfit(x,y,2)
print(p)
#gives a coefficients of polynomial according to given values
p = np.poly1d([1, 2, 3])
print(np.poly1d(p))
#creates a polynomial |
#used for predicting catogarical values
"""
classification can be done by
decision trees
naive bias
linear discriminent analysis
k-nearest neighbor
logistic regression
neural networks
support vector machines
mechanism->
by given data we can obtain a scatter plot
then we find nearest point for our values which are to predicted
but taking only one is not perfect as outliers can ruin prediction
so we consider 'k' nearest neighbours
this KNN or k-nearest neighbour algorithm
algorithm->
1] pick a value for k
2] find distance form neighbours
this is obtained by euclidian distance
for example vars are x1,x2,x3 and so on
then d=sqrt(diff.x1^2+diff.x2^2+diff.x3^2)
k is calculated by running training with differnt k and evaluating them
1]jakkerd index
jakkerd index= y ∩ ypred / y U ypred
higher j shows higher accuracy
F1 score-> obtained from confusion plots
higher j shows higher accuracy
log loss gives prob of failure
so it should be less for a good model
"""
import itertools as itl
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
import pandas as pd
import numpy as np
import matplotlib.ticker as ticker
import sklearn.preprocessing as spr
import sklearn.model_selection as sms
import sklearn.neighbors as snb
import sklearn.metrics as smt
path="/home/ashifer/code/datasets/teleCust1000t.csv"
df=pd.read_csv(path)
cc=df['custcat'].value_counts()
print(cc)
cols=['region', 'tenure', 'age', 'marital', 'address', 'income', 'ed',
'employ', 'retire', 'gender', 'reside', 'custcat']
x_data=df[['region', 'tenure', 'age', 'marital', 'address', 'income', 'ed',
'employ', 'retire', 'gender', 'reside']]
y_data=df["custcat"]
x_data=spr.StandardScaler().fit_transform(x_data)
k=4 #doing for 4 neighs
x_train,x_test,y_train,y_test=sms.train_test_split(x_data,y_data,test_size=0.2,random_state=1)
neigh=snb.KNeighborsClassifier(n_neighbors=k).fit(x_train,y_train)
pred=neigh.predict(x_test)
acc=smt.accuracy_score(y_test,pred)#gives jaccard
acc1=smt.f1_score(y_test,pred,average='micro')
acc2=smt.f1_score(y_test,pred,average='macro')
acc3=smt.f1_score(y_test,pred,average='weighted')
#micro macro are to be used
print(acc,acc1,acc2,acc3)
#plotting for precision
mns=[]
for ks in range(1,10):
neigh=snb.KNeighborsClassifier(n_neighbors=ks).fit(x_train,y_train)
pred=neigh.predict(x_test)
mns.append(smt.accuracy_score(y_test,pred))
ar=[i for i in range(1,10)]
plt.plot(ar,mns)
plt.show()
#from graph k=8 is best val |
"""
Board module for tic tac toe. Displays and maintains the
state of the board
"""
import sys
import numpy as np
class Board:
"""
maintains board state as a numpy int array where:
-1 -> blakn
0 -> player 1 mark
1 -> player 2 mark
"""
M = -1
N = -1
K = -1
def __init__(self, *args):
"""
initalizes board based on what arguments are given
if given 0: create a default board
if given 3: interpret as M, N, K dimensions -- create board based on that
if given 4: interpret as created board, with M, N, K dimensions --
create board based off existing board
"""
if len(args) == 0: #I will create a default board
self.M, self.N, self.K = 3, 3, 3
self.board = np.zeros(shape=(self.M, self.N))
self.board.fill(-1)
elif len(args) == 4: #i'm expecting a completed board
self.M, self.N, self.K = args[1], args[2], args[3]
self.board = np.array(args[0]).reshape((self.M, self.N))
elif len(args) == 3: #they supplied dimensions (M, N, K)
self.M, self.N, self.K = args[0], args[1], args[2]
if self.K < 3:
print "must match at least 3"
self.board = None
elif min(self.M, self.N) < self.K:
print "min dimension of board must be greater than K"
self.board = None
elif self.M > 10 or self.N > 10:
print "dimensions exceeds limit"
self.board = None
else:
self.board = np.zeros(shape=(self.M,self.N))
self.board.fill(-1)
def display(self):
"""
display the entire grid
"""
sys.stdout.write('\n-------\n')
for row in self.board:
sys.stdout.write('|')
for elem in row:
char = ' '
if elem == 0:
char = 'X'
elif elem == 1:
char = 'O'
sys.stdout.write(char + '|')
sys.stdout.write('\n-------\n')
def checkMove(self, row, col):
"""
verify if row, col would be a valid move,
return true if it's a valid move else false
"""
if row >= self.M or row < 0 or col >= self.N or col < 0:
print "Input out of Bounds"
return False
if self.board[row][col] != -1:
#print "Slot already taken"
return False
return True
def setMove(self, row, col, tick):
"""
sets a valid move on the grid
"""
self.board[row][col] = tick
def isOver(self):
"""
checks all iterations of the board to see if it's finished
"""
catscnt = 0 #keeping track of if all the subboards that are cat's game'd
subboardcnt = 0
tempboard = np.zeros(shape=(self.K,self.K)) #temp square board to check game
for i in xrange(self.K, self.M + 1):
for j in xrange(self.K, self.N + 1):
tempboard = self.board[i-self.K:i,j-self.K:j]
ret = self.checkSquare(tempboard)
subboardcnt = subboardcnt + 1
if ret == 2:
catscnt = catscnt + 1 #if any subboard returns a non-cat's game, it's not over
if ret != 2 and ret != -1:
return ret #one of the players won the sub array
if catscnt == subboardcnt:
return 2
return -1 #nobody won and it's not a cat's game
def checkSquare(self, board):
"""
returns element causing game over or 2 if cats game
"""
CATS_GAME = 2
GAME_ONGOING = -1
# checks if everything in a row is the same
check_func = lambda arr: arr[0] != -1 and all(elem == arr[0] for elem in arr)
# all same marker in a row
for row in board:
if check_func(row):
return row[0]
# all same marker in a col
for col in [board[:, idx] for idx in range(self.K)]:
if check_func(col):
return col[0]
# check pos_diag
pos_diag = board.diagonal()
neg_diag = [board[idx][(self.K - 1) - idx] for idx in range(self.K)]
if check_func(pos_diag):
return pos_diag[0]
# check neg_diag
elif check_func(neg_diag):
return neg_diag[0]
# cats game
if np.count_nonzero(board == -1) == 0:
return CATS_GAME
# game not over
return GAME_ONGOING
|
def binary_search(key, arr):
low = 0
high = len(arr)-1
mid = (low+high)//2
while(high>low):
if(arr[mid]==key):
return mid
if(arr[mid] > key):
high = mid-1
elif(arr[mid] < key):
low = mid+1
mid = (low+high)//2
return mid
# take input
Q = int(input())
queries = []
# getting minimum L and max R to construct the primes list
min_L = 1000000
max_R = 2
for _ in range(Q):
current_query = list(map(int, input().split()))
queries.append(current_query)
curr_L = current_query[0]
curr_R = current_query[1]
min_L = min(min_L, curr_L)
max_R = max(max_R, curr_R)
# construct list between 1 and max_R using sieve
primes_sieve = [True]*(2*max_R+1) # (1 based indexing)
primes_sieve[0] = False
primes_sieve[1] = False
primes_sieve[2] = True
prev = []
strong_primes = []
factor = 2
while(True):
if(primes_sieve[factor] == False):
factor+=1
continue
for num in range(2*factor, len(primes_sieve), factor):
primes_sieve[num] = False
if(len(prev)==3):
prev.pop(0)
prev.append(factor)
if(len(prev)==3):
low, mid, high = prev
if(2*mid > (low + high)):
strong_primes.append(mid)
if(factor > max_R):
break
factor+=1
#print(strong_primes)
for q in queries:
L,R = q[0], q[1]
if R < 11:
print(0)
continue
start_range = 0
end_range = len(strong_primes)-1
if(L>strong_primes[0]):
start_range = binary_search(L, strong_primes)
if(strong_primes[start_range]<L):
start_range+=1
if(R<strong_primes[-1]):
end_range = binary_search(R, strong_primes)
if(strong_primes[end_range]>R):
end_range-=1
#print(start_range,end_range)
print(end_range-start_range+1)
######################################################################################
T=int(input())
arr=[0]*1000001
for i in range(3,1000001,2):
arr[i]=1
for i in range(3,1000001,2):
if arr[i]==1:
for j in range(i*i,1000001,i):
arr[j]=0
arr[1]=arr[0]=0
arr[2]=1
prime=[]
strong=[]
for i in range(2,1000001):
if arr[i]==1:
prime.append(i)
if i>5:
if 2*prime[-2]>prime[-3]+prime[-1]:
strong.append(prime[-2])
for _ in range(T):
L,R=[int(x) for x in input().split()]
c=0
for i in range(L,R+1):
left=0
right=len(strong)-1
mid=(left+right)//2
while left<=right:
if i==strong[mid]:
c+=1
break
elif i<strong[mid]:
right=mid-1
else:
left=mid+1
mid=(left+right)//2
print(c)
##########################################
T=int(input())
arr=[0]*1000001
for i in range(3,1000001,2):
arr[i]=1
for i in range(3,1000001,2):
if arr[i]==1:
for j in range(i*i,1000001,i):
arr[j]=0
arr[1]=arr[0]=0
arr[2]=1
prime=[]
strong=[]
for i in range(2,1000001):
if arr[i]==1:
prime.append(i)
if i>5:
if 2*prime[-2]>prime[-3]+prime[-1]:
strong.append(prime[-2])
for _ in range(T):
L,R=[int(x) for x in input().split()]
c=[]
for i in [L,R+1]:
left=0
right=len(strong)-1
mid=(left+right)//2
while left<=right:
if i==strong[mid]:
c.append(mid)
break
elif i<strong[mid]:
right=mid-1
else:
left=mid+1
mid=(left+right)//2
c.append(left)
print(len(strong[c[0]:c[1]]))
|
#Counting Organizations
#This application will read the mailbox data (mbox.txt) count up the number email messages per organization
#(i.e. domain name of the email address) using a database with the following schema to maintain the counts.
#CREATE TABLE Counts (org TEXT, count INTEGER)
#When you have run the program on mbox.txt upload the resulting database file above for grading.
#If you run the program multiple times in testing or with dfferent files, make sure to empty out the data before each run.
#You can use this code as a starting point for your application: http://www.pythonlearn.com/code/emaildb.py.
#The data file for this application is the same as in previous assignments: http://www.pythonlearn.com/code/mbox.txt.
#Because the sample code is using an UPDATE statement and committing the results to the database as each record is
#read in the loop, it might take as long as a few minutes to process all the data. The commit insists on completely writing all the data to disk every time it is called.
#The program can be speeded up greatly by moving the commit operation outside of the loop.
#In any database program, there is a balance between the number of operations you execute between commits and
#the importance of not losing the results of operations that have not yet been committed.
import sqlite3
conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Counts''')
cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'mbox.txt'
fh = open(fname)
for line in fh:
line.rstrip().strip()
print line
if not line.startswith('From: ') : continue
pieces = line.split()
email = pieces[1]
domain = email.split("@")[1]
print domain
cur.execute('SELECT count FROM Counts WHERE org = ? ', (domain, ))
row = cur.fetchone()
if row is None:
cur.execute('''INSERT INTO Counts (org, count)
VALUES ( ?, 1 )''', ( domain, ) )
else :
cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?',
(domain, ))
# This statement commits outstanding changes to disk each
# time through the loop - the program can be made faster
# by moving the commit so it runs only after the loop completes
conn.commit()
# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
print
print "Counts:"
for row in cur.execute(sqlstr) :
print str(row[0]), row[1]
cur.close()
|
class Product:
def __init__(self, name, price, discount=0, stock=0, max_discount=20.0):
self.name = name.strip()
if not len(self.name) >= 2:
raise ValueError('Too short name')
self.price = abs(float(price))
self.stock = abs(int(stock))
self.max_discount = abs(int(max_discount))
if self.max_discount > 99:
raise ValueError('Discount is too big')
self.discount = abs(float(discount))
if self.discount > self.max_discount:
self.discount = self.max_discount
def sell(self, items_count=1):
if items_count > self.stock:
raise ValueError('Item is not in stock at the moment')
self.stock -= items_count
def discounted(self):
return self.price - self.price * self.discount / 100
def __repr__(self):
return f'<Product name: {self.name}, price: {self.price}, stock: {self.stock}>'
iPhone = Product('iPhone', 70000, stock=10)
print(iPhone)
iPhone.sell(5)
print(iPhone)
|
if 10 > 5:
print("10 greater than 5")
print("Program ended")
spam = 7
if spam > 5:
print("five")
if spam > 8:
print("eight")
num = 12
if num > 5:
print("Bigger than 5")
if num <= 47:
print("Between 5 and 47")
x = 4
if x == 5:
print("Yes")
else:
print("No")
num = 7
if num == 5:
print("Number is 5")
elif num == 11:
print("Number is 11")
elif num == 7:
print("Number is 7")
else:
print("Number isn't 5, 11 or 7")
|
# 要求:设计一个简单的计算器,让用户输入2个数字,返回这两个数的和
# print("the sum is:" + str(float(input("input 1st number:"))@
# + float(input("input 2nd number:"))))
# x = input("input 1st number:")
# y = input("input 2nd number:")
# print("the sum is:" + str(float(x) + float(y)))
x = float(input("input 1st number:"))
y = float(input("input 2nd number:"))
sum = x + y
print("the sum is:", sum)
|
import random
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if ints:
ints_len = len(ints)
if ints_len < 2:
return ints[0], ints[0]
i = 0
min = max = ints[0]
while i + 1 < ints_len:
if max < ints[i + 1]:
max = ints[i + 1]
elif min > ints[i + 1]:
min = ints[i + 1]
i += 1
return min, max
print('The list should not be empty.')
return None
def main():
## Example Test Case of Ten Integers
l = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(l)
print("Pass" if get_min_max(l) == (0, 9) else "Fail")
# edge cases
l = []
print("Pass" if get_min_max(l) is None else "Fail")
l = [5]
print("Pass" if get_min_max(l) == (5, 5) else "Fail")
if __name__ == '__main__':
main()
|
print("====Calculo de total de calorias num dia====")
calorias_total = 0
alimentos = int(input("Quantos alimentos consumiu hoje? "))
for x in range(1,alimentos+1):
calorias = int(input("Quantas calorias tem o alimento {}? ".format(x)))
calorias_total = calorias_total + calorias
print("Você consumiu {} alimentos, totalizando {} calorias.".format(alimentos, calorias_total)) |
from bs4 import BeautifulSoup
#HTML Code - the html content that we are going to parse using Beautiful Soup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; their names:
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
<b class="boldest">Extremely bold</b>
<blockquote class="boldest">Extremely bold</blockquote>
<b id="1">Test 1</b>
<b another-attribute="1" id="verybold">Test 2</b>
"""
#Creating a file called "index.html" and then, write the html content above to this file
with open('index.html', 'w') as f:
f.write(html_doc)
#Create a Beautiful Soup object based on the html_doc string variable that we defined above
#This will allow us to parse the HTML content
soup = BeautifulSoup(html_doc, "lxml")
#If you want to print out nicely formatted HTML
#print(soup.prettify())
#print(soup) #prints it out normally
#Tag:
# Finds the FIRST occurrence of usage for a "b"
# bold tag.
#print(soup.b) #this prints out <b>The Dormouse's story</b>
# The "find" function also does the same, where it
# only finds the FIRST occurrence in the HTML doc
# of a tag with "b"
#print(soup.find('b')) #this also prints out <b>The Dormouse's story</b>
# If we want to find ALL of the elements on the page
# with the "b" tag, we can use the "find_all" function.
#print(soup.find_all('b'))
# Name:
# This gives the name of the tag. In this case, the
# tag name is "b".
#print(soup.b.name)
# We can alter the name and have that reflected in the
# source. For instance:
#tag = soup.b #this is currently <b>The Dormouse's story</b>
#tag.name = "blockquote" #now tag printed is <blockquote>The Dormouse's story</blockquote>
# Attributes:
#Finds all instances of bold tags, and then returns the THIRD occurence of the bold tags (index 2)
#tag = soup.find_all('b')[2]
# This specific tag has the attribute "id", which
# can be accessed like so:
#print(tag['id']) #prints 1 since ID is 1 in <b id="1">Test 1</b>
#tags can have multiple attributes assigned to it
#For example:
#tag = soup.find_all('b')[3] #here tag is <b another-attribute="1" id="verybold">Test 2</b>
# We can then access multiple attributes that are
# non-standard HTML attributes:
#print(tag['id'])
#print(tag['another-attribute'])
# If we want to see ALL attributes, we can access them
# as a dictionary object:
#tag = soup.find_all('b')[3]
#print(tag.attrs) #prints a dictionary where the key is the name of the attribute and the value is the value of the attribute
# These properties are mutable, and we can alter them
# in the following manner.
#tag = soup.find_all('b')[3]
#tag['another-attribute'] = 2 #now the value for this attribute is 2 and not 1
# We can also use Python's del command for lists to
# REMOVE attributes:
#tag = soup.find_all('b')[3]
#del tag['id']
#del tag['another-attribute']
#Navigable String
#returns the string content between the tags
#tag = soup.find_all('b')[3]
#print(tag.string)
# We can use the "replace_with" function to replace
# the content of the string with something different:
#tag = soup.find_all('b')[3]
#tag.string.replace_with("This is another string")
|
import sys
n = int(input('Please enter an integer value: '))
a = 1
b = 1
while a>=1 and b>=1:
print(a)
temp = a + b
a = temp + b
print(a) |
import sys
n = str(input('Please enter a binary number: '))
a = str.len(n)
#c = n.count(0)
for i in range(0,2)
b = i(2**a)
while b = i:
break
if n%10 = 0:
while 1 == 1:
a -= 1
b = 2**a + 2**(a)
print(b) |
import sys
import math
## t= temperature in Fahrenheit
## v= wind speed in miles per hour
## w= wind chill
t = float(sys.argv[1])
v = float(sys.argv[2])
if math.fabs(t) > 50:
print("Error: t should be greater than -50 and less than 50.")
exit()
if (v > 120 or v < 3):
print("Error: v should be greater than 3 and less than 120.")
exit()
w = 35.74 + (0.6215 * t) + (0.4275 * t - 35.75) * (v ** 0.16)
print ('Wind Chill: ',w) |
line = input().split(" ")
x, y, z = line
a = float(x)
b = float(y)
c = float(z)
if a >= b and a >= c and a < (b + c):
print("Perimetro = %.1f" %(a+b+c))
elif b >= a and b >= c and b < (a + c):
print("Perimetro = %.1f" %(a+b+c))
elif c >= a and c >= b and c < (a + b):
print("Perimetro = %.1f" %(a+b+c))
else:
print("Area = %.1f" %((a+b)*c/2))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
res = []
if root is None:
return 0
if root.left is None and root.right is None:
return 0
q = deque([root])
while len(q) > 0:
curr_tn = q.popleft()
if curr_tn.left is not None:
q.append(curr_tn.left)
# leaf check.
if curr_tn.left.left is None and curr_tn.left.right is None:
res.append(curr_tn.left.val)
if curr_tn.right is not None:
q.append(curr_tn.right)
return sum(res)
|
import time
import random
welcome_message = 'welcome to the magic number game!'
print(welcome_message)
ask_user_for_number = int(input('Can you please select a number between 0-10? '))
time.sleep(0.5)
magic_number = random.randint(0,10)
magic_number_message = f'The magic number for this round was {magic_number}, you selected {ask_user_for_number}'
print(magic_number_message)
tries = [1,2,3,4,5]
for count in tries:
if ask_user_for_number == magic_number:
print('You Have Won This Round!')
break
print ('Well done !')
elif ask_user_for_number > magic_number:
print('Your guess was above the magic number, Try Again!')
ask_user_for_number = int(input('Can you please select a number between 0-10? '))
continue
else:
print('Your guess was below the magic number, Try again')
ask_user_for_number = int(input('Can you please select a number between 0-10? '))
continue
|
''' Carly's Clippers
You are the Data Analyst at Carly’s Clippers, the newest hair salon on the block.
Your job is to go through the lists of data that have been collected in the past couple of weeks.
You will be calculating some important metrics that Carly can use to plan out the operation of the business for the rest of the month.
You have been provided with three lists:
hairstyles: the names of the cuts offered at Carly’s Clippers
prices: the price of each hairstyle in the hairstyles list
last_week: the number of each hairstyle in hairstyles that was purchased last week. '''
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2]
total_price = 0
for price in prices:
total_price += price
average_price = total_price / (len(prices))
print(f"Average Haircut Price: {average_price}")
new_prices = [price - 5 for price in prices]
print(new_prices)
total_revenue = 0
for i in range(len(hairstyles)):
total_revenue += prices[i] * last_week[i]
print(f"Total Revenue: {total_revenue}")
average_daily_revenue = total_revenue /7
cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]
print(cuts_under_30)
|
#importing the necessary libraries
import pandas as pd
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
import rasterio as rt
from rasterio.mask import mask
import shutil
from Typing import List, Dict
class GeoTiff:
"""
Class GeoTiff is where we get all the details about the GeoTiff files
It has four functions namely:
:check_tiff function to check from which tiff file the address is
:get_tiff function to download the necessary tiff files
:mask_tiff function to create the masked tiff files from the DTM and DSM files
:get_chm function to get the CHM of the tiff files
"""
def check_tiff(x: str, y: str) -> str:
"""
check_tiff function is where we check from which tiff file the address belongs to.
It needs the x and y coordinates as a parameter
:attrib bbox will read the bounding-box.csv which contains the list of all the tiff files
It will then go inside a for loop and check if the x and y is inside the bounding box of the tiff file
Once it is done, the for loop will break and it will return the attrib i
:attrib i will contain from which index the tiff file belongs to
:attrib num will contain the number of the tiff file
"""
bbox = pd.read_csv('./data/bounding-box.csv')
for i in range(bbox.shape[0]):
if bbox['Left (X)'][i] <= x:
if bbox['Right (X)'][i] >= x:
if bbox['Bottom (Y)'][i] <= y:
if bbox['Top (Y)'][i] >= y:
i = i
break
if i < 9:
num = f'k0{i+1}'
else:
num = f'k{i+1}'
return num
def get_tiff(num: str):
"""
get_tiff function is where it will download the necessary tiff files connected to the address
It requires the num from the check_tiff as the parameter and then it will return a print statement
:attrib files is a dictionary containing the DSM and DTm with the links on where to download it
It will then go inside a for loop and use the urlopen, ZipFile, BytesIO to be able to extract the file without
downloading the zip file. It will save the file in the data/temp-raster folder
"""
files = {'DSM': f"https://downloadagiv.blob.core.windows.net/dhm-vlaanderen-ii-dsm-raster-1m/DHMVIIDSMRAS1m_{num}.zip",
'DTM': f"https://downloadagiv.blob.core.windows.net/dhm-vlaanderen-ii-dtm-raster-1m/DHMVIIDTMRAS1m_{num}.zip"}
for key, value in files.items():
with urlopen(value) as zipresp:
print(f"Downloading the {key} zip file......")
with ZipFile(BytesIO(zipresp.read())) as zfile:
print(f"Extracting the {key} zip file .......")
zfile.extractall(f'./data/temp-raster/{key}')
print(f"Done extracting the {key} zip file to temp-raster/{key} folder!")
print("Successfully extracted the tiff files!")
def mask_tiff(num: str, polygon: Dict[str, str]) -> Dict[str,str]:
"""
mask_tiff function will create the masked files for the DSM and DTM
it requires the num and polygon as the parameter
:attrib raster_files is a dictionary containing the path to the tif files
:attrib masked_files is a dictionary that will contain the path of the masked files
It will go inside a for loop and create the masked files using the rasterio mask module
After masking the file, it will save the masked tiff file in the data/masked-files folder
Then it will delete the data/temp-raster folder using the shutil module
The function will return the masked files in a dictionary format
"""
raster_files = {'DSM' : f"./data/temp-raster/DSM/GeoTiff/DHMVIIDSMRAS1m_{num}.tif",
'DTM' : f"./data/temp-raster/DTM/GeoTiff/DHMVIIDTMRAS1m_{num}.tif"}
masked_files = {}
for name, file in raster_files.items():
data = rt.open(file)
out_img, out_transform = mask(dataset=data, shapes=[polygon], crop=True)
out_meta = data.meta.copy()
epsg_code = int(data.crs.data['init'][5:])
out_meta.update({"driver": "GTiff",
"height": out_img.shape[1],
"width": out_img.shape[2],
"transform": out_transform,
"crs": epsg_code,
"developer-name": "Arlene Postrado"
})
with rt.open(f"./data/masked-files/{name}_masked.tif", "w", **out_meta) as dest:
dest.write(out_img)
print(f"Successfully created a new masked file for {name}.")
masked_files[f'{name}'] = f"./data/masked-files/{name}_masked.tif"
shutil.rmtree(f"./data/temp-raster/{name}/", ignore_errors=True)
print(f"Successfully deleted the files inside the temp-raster folder for {name}")
return masked_files
def get_chm(masked_files: Dict[str,str]):
"""
get_chm function will get the CHM from the dsm and dtm
It requires the masked_files as the parameter and returns the CHM
:attrib dsm_tiff will contain the DSM masked file
:attrib dsm_array will read the 1st band of the the dsm_tiff
:attrib dtm_tiff will contain the DTM masked file
:attrib dtm_array will read the 1st band of the dtm_tiff
:attrib chm contains the CHM array
"""
dsm_tiff = rt.open(masked_files['DSM'])
print("Reading the 1st band of the DSM as an array")
dsm_array = dsm_tiff.read(1)
dtm_tiff = rt.open(masked_files['DTM'])
print("Reading the 1st band of the DSM as an array")
dtm_array = dtm_tiff.read(1)
print("Creating the CHM file for this address.")
chm = dsm_array - dtm_array
return chm
|
def letter_histogram(word):
result = {}
for char in word:
result[char] = word.count(char)
print(result)
if __name__ == "__main__":
letter_histogram(input("Give a word to start. ")) |
letras = ['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', '.', '!', '#']
numeros = [0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 , 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
palavra = str(input('Digite a palavra: ')).strip().upper()
palavra.replace(' ', '#')
if len(palavra) % 2 != 0:
palavra += '#'
numero_palavra = [[],[]]
ct = 0
for p in range(len(palavra)):
ct += 1
if ct > len(palavra) // 2:
numero_palavra[1].append(numeros[letras.index(palavra[p])])
else:
numero_palavra[0].append(numeros[letras.index(palavra[p])])
matriz_multiplicar = [
[3, 1],
[2, 1]
]
matriz_final = [[],[]]
ct1 = 0
print(numero_palavra)
for a in range(2):
for b in range(len(palavra)):
calc = matriz_multiplicar[a][b]
print(calc)
# calc = matriz_multiplicar[a][b] * numero_palavra[a][b] + matriz_multiplicar[a][b+1] * numero_palavra[a+1][b]
ct += 1
if ct1 > len(palavra) // 2:
matriz_final[1].append(calc)
else:
matriz_final[0].append(calc)
print(matriz_final[0])
print(matriz_final[1])
print(palavra)
|
def add_list_to_words(words: dict, new_words: list):
for word in new_words:
words[word] = words.get(word, 0) + 1
def get_repeated_words(words: dict) -> list:
return [k for k, v in words.items() if v > 1]
def get_unique_words(words: dict) -> list:
return [k for k, v in words.items() if v == 1]
def get_top_five_frequent_words(words: dict) -> list:
sorted_words = sorted(words.items(), key=lambda x: x[1], reverse=True)
top_five_words = [k for k, v in sorted_words if v > 1][:5]
if len(top_five_words) < 5:
top_five_words = top_five_words + [None] * (5 - len(top_five_words))
return top_five_words
|
# For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
i = 0
while i < len(y):
x.append(y[i])
i+=1
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
i = 0
while i < len(x):
if(x[i] == 8):
x.pop(i)
i+=1
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
x.insert(5, 99)
print(x)
# Print the length of list x
# YOUR CODE HERE
print(len(x))
# Print all the values in x multiplied by 1000
# YOUR CODE HERE
i=0
while i < len(x):
print(x[i]*1000)
i+=1 |
import tkinter as tk # 使用Tkinter前需要先匯入
import tkinter.messagebox
from evaluate import evaluate
# 第1步,例項化object,建立視窗window
window = tk.Tk()
# 第2步,給視窗的視覺化起名字
window.title('政治立場分析')
# 第3步,設定視窗的大小(長 * 寬)
window.geometry('500x300') # 這裡的乘是小x
# 第4步,在圖形介面上設定輸入框控制元件entry框並放置
# 第5步,定義兩個觸發事件時的函式insert_point和insert_end(注意:因為Python的執行順序是從上往下,所以函式一定要放在按鈕的上面)
def judge(): # 在滑鼠焦點處插入輸入內容
var=t.get("1.0",'end')
x=evaluate(var,'1')
tkinter.messagebox.showinfo(title='分析結果', message=x)
def judge1(): # 在滑鼠焦點處插入輸入內容
var=t.get("1.0",'end')
x=evaluate(var,'2')
tkinter.messagebox.showinfo(title='分析結果', message=x)
def judge2(): # 在滑鼠焦點處插入輸入內容
var=t.get("1.0",'end')
x=evaluate(var,'3')
tkinter.messagebox.showinfo(title='分析結果', message=x)
# 第6步,建立並放置兩個按鈕分別觸發兩種情況
l = tk.Label(window, text='請輸入文字', bg='PeachPuff', font=('Arial', 12), width=30, height=2)
l.pack()
t = tk.Text(window, height=15)
t.pack()
b1 = tk.Button(window, text='NB', bg='LightBlue',font=('Times'), width=17,
height=2, command=judge)
b1.pack(side='left')
b2 = tk.Button(window, text='KNN', bg='PeachPuff',font=('Times'), width=19,
height=2, command=judge1)
b2.pack(side='left')
b3 = tk.Button(window, text='SVM', bg='LightBlue',font=('Times'), width=17,
height=2, command=judge2)
b3.pack(side='left')
# 第7步,建立並放置一個多行文字框text用以顯示,指定height=3為文字框是三個字元高度
# 第8步,主視窗迴圈顯示
window.mainloop() |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
[簡答題] 請問 type(...) 跟 a.dtype 這兩個語法有什麼不同?
# In[1]:
import numpy as np
a=np.arange(12).reshape(3,4)
print(a)
print('dtype:',a.dtype)
print('type(a):', type(a))
#type(...)得出的是numpy array的類型
#a.dtype則是得出a 的data 種類
# In[ ]:
[簡答題] 承上題,請判斷下列三種寫法為何不正確?
# In[18]:
def is_dtype(a, t):
return a.dtype is t
# is 必須跟 np.dtype比較
def is_dtype(a, t):
return type(a) == np.dtype(t)
# type(a) 為numpy array的類型, 而非比較內容 data type
def is_dtype(a, t):
return type(a) is np.dtype(t)
#同上
# In[ ]:
請撰寫一個判斷 a 的元素是否等於指定資料型態的函式
# In[19]:
a=np.random.randint(10,size=(3,4))
print(a)
print('a.dtype:',a.dtype)
# In[24]:
print(a.dtype == "int32")
print(type(a) == np.dtype("int32"))
print(a.dtype == np.dtype('int32'))
print(type(a) is np.dtype('int32'))
print(a.dtype is np.dtype('int32'))
# 進階
# In[ ]:
|
import requests, json
from requests.exceptions import ConnectionError
from urllib3.exceptions import NewConnectionError
print("Let's look at the weather today!")
ZIPCODE = input("Enter zipcode: ")
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
URL = BASE_URL + "zip=" + ZIPCODE + ",us&appid=" + "98629f50c06f233ce10f89323ae5167c" + "&units=imperial"
def getValidInput():
print("Let's try it again!")
ZIPCODE = input("Enter zipcode: ")
def validateZipcode():
if not (ZIPCODE.isdigit()):
print("Invalid entry.")
getValidInput()
elif len(ZIPCODE) != 5:
print("Invalid entry.")
getValidInput()
def anotherSearch():
print("Would you like another search? (yes or no) ")
another_search = input()
if (another_search == "yes" or another_search == "y"):
nextSearch()
elif (another_search == "no" or another_search == "n"):
print("Thank you! Have a great day!")
else:
nextSearch()
def getWeather():
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
URL = BASE_URL + "zip=" + ZIPCODE + ",us&appid=" + "98629f50c06f233ce10f89323ae5167c" + "&units=imperial"
response = requests.get(URL)
if response.status_code == 200:
data = response.json()
main = data ["main"]
sys = data["sys"]
temperature = main["temp"]
feels_like = main["feels_like"]
country = sys["country"]
try:
r = requests.get(URL)
except ConnectionError:
print("An error occured. Please re-run this module to try again.")
else:
print(f"{ZIPCODE:-^30}")
print(f"Temperature: {temperature}°F")
print(f"Feels like: {feels_like}°F")
print(f"{country:-^30}")
finally:
anotherSearch()
def nextSearch():
print("Let's try it again!")
next_zipcode = str(input("Enter next zipcode: "))
if not(next_zipcode.isdigit()):
print("Oh, no! Invalid entry. Let's try it again!")
getNextWeather()
elif len(next_zipcode) != 5:
print("Oh, no! Invalid entry. Let's try it again!")
getNextWeather()
NEXT_URL = BASE_URL + "zip=" + next_zipcode + ",us&appid=" + "98629f50c06f233ce10f89323ae5167c" + "&units=imperial"
response = requests.get(NEXT_URL)
if response.status_code == 200:
data = response.json()
main = data ["main"]
sys = data["sys"]
temperature = main["temp"]
feels_like = main["feels_like"]
country = sys["country"]
try:
r = requests.get(URL)
except ConnectionError:
print("An error occured. Please re-run this module to try again.")
except NewConnectionError:
print("An error occured. Please re-run this module to try again.")
else:
print(f"{next_zipcode:-^30}")
print(f"Temperature: {temperature}°F")
print(f"Feels like: {feels_like}°F")
print(f"{country:-^30}")
finally:
anotherSearch()
def getNextWeather():
next_zipcode = str(input("Enter next zipcode: "))
NEXT_URL = BASE_URL + "zip=" + next_zipcode + ",us&appid=" + "98629f50c06f233ce10f89323ae5167c" + "&units=imperial"
response = requests.get(NEXT_URL)
if response.status_code == 200:
data = response.json()
main = data ["main"]
sys = data["sys"]
temperature = main["temp"]
feels_like = main["feels_like"]
country = sys["country"]
try:
r = requests.get(URL)
except ConnectionError:
print("An error occured. Please re-run this module to try again.")
except NewConnectionError:
print("An error occured. Please re-run this module to try again.")
else:
print(f"{next_zipcode:-^30}")
print(f"Temperature: {temperature}°F")
print(f"Feels like: {feels_like}°F")
print(f"{country:-^30}")
finally:
anotherSearch()
validateZipcode()
getWeather() |
""" 该类的作用主要是 对文件的增删改查操作
读取配置文件:返回一个dict
写配置文件:传入key-value值,根据相应的key值,修改配置文件
可以照着其他的类写,所有的变量都要求是私有的,用@property来进行获取或者赋值,可参照其他类
"""
import configparser
#import os
# _*_ coding:utf-8 _*_
class FileUtil(object):
def __init__(self, file: str):
self.__configfile = file
self.__cfg = configparser.ConfigParser()
# def cfg_read(self):
# self.__cfg.read(self.__configfile,encoding='utf8')
# d = dict(self.__cfg.sections()) # 这里不能直接dict会报错
# sections() 返回的是section的列表并不是所有的key-value
# for k in d:
# d[k] = dict(d[k])
# return d
def del_item(self, section: str, key: str):
self.__cfg.remove_option(section, key)
def del_section(self, section: str):
self.__cfg.remove_section(section)
def add_section1(self, section: str):
self.__cfg.add_section(section)
def set_item(self, section: str, key: str, value: str):
self.__cfg.set(section, key, value)
def save(self):
fp = open(self.__configfile, 'w')
self.__cfg.write(fp)
fp.close()
@property
def configfile(self):
return self.__configfile
@property
def conf(self):
return self.__cfg
class MyParser(configparser.ConfigParser): # 读取并返回字典
def as_dict(self):
d = dict(self._sections)
for k in d:
d[k] = dict(d[k])
return d
if __name__ == '__main__':
a = FileUtil("../resources/static.config")
b = MyParser()
b.read("../resources/static.config", encoding="utf8")
c = b.as_dict()
# print(b.as_dict().get('C')+'123')
print(c)
print(a.add_section1("C"))
print(a.save())
print(a.set_item("C", "X", "4"))
print(a.set_item("C", "M", "4"))
print(a.save())
print(a.add_section1("d"))
print(a.save())
print(a.set_item("d", 'length', '4'))
print(a.set_item('d', 'width', '5'))
print(a.save())
#print(a.del_section("C"))
#print(a.save())
# 每次进行一次增删改操作,都要写入文件一次,即调用save()一次 |
""" 画text的类
"""
import pygame
class Text:
def __init__(self, text: str, posx: int, posy: int, text_height: int=10,
font_color: tuple=(0, 0, 0), background_color: tuple=(255, 255, 255)):
self.__text = text
self.__pos_x = posx
self.__pos_y = posy
self.__text_height = text_height
self.__font_color = font_color
self.__background = background_color
def draw_text(self, screen):
fontObj = pygame.font.SysFont('arial', self.__text_height) # 通过字体文件获得字体对象
textSurfaceObj = fontObj.render(self.__text, True, self.__font_color, self.__background) # 配置要显示的文字
textRectObj = textSurfaceObj.get_rect() # 获得要显示的对象的rect
textRectObj.center = (self.__pos_x, self.__pos_y) # 设置显示对象的坐标
screen.blit(textSurfaceObj, textRectObj) # 绘制字
@property
def text(self):
return self.__text
@text.setter
def text(self, text: str):
self.__text = text
@property
def text_pos(self):
return self.__pos_x, self.__pos_y
@text_pos.setter
def text_pos(self, new_pos: tuple):
self.__pos_x = new_pos[0]
self.__pos_y = new_pos[1]
@property
def text_height(self):
return self.__text_height
@text_height.setter
def text_height(self, new_height: int):
self.__text_height = new_height
@property
def font_color(self):
return self.__font_color
@font_color.setter
def font_color(self, new_color: tuple):
self.__font_color = new_color
@property
def background(self):
return self.__background
@background.setter
def background(self, new_background):
self.__background = new_background
|
from datetime import timedelta
intervals = {
'y': timedelta(days=365.25),
'w': timedelta(days=7),
'd': timedelta(days=1),
'h': timedelta(hours=1),
'm': timedelta(minutes=1),
's': timedelta(seconds=1),
}
def parse_interval(text: str) -> timedelta:
current = ''
total = timedelta(seconds=0)
for i, char in enumerate(text):
if char.isdigit():
current += char
elif char in intervals:
if not current:
raise ValueError("Missing value at position {}".format(i))
total += int(current) * intervals[char]
else:
raise ValueError("{} is not a valid interval multiplier".format(char))
if current:
total += int(current) * intervals['s']
return total
|
numero = float(input('Digite um número: '))
if numero > 0:
print('O numero digitado é posivito!')
elif numero < 0:
print('O número digitado é negativo!')
else:
print('O numero digitado é o elemeno neutro 0.') |
print('Programa para ler uma temperatura em Celsius e retornar os valores destas temperaturas em Fahrenheit e Kelvin')
celsius = float(input('Digite a temperatura, em Celsius: '))
kelvin = celsius + 273
fahrenheit = ((9/5) * celsius) + 32
print('Temperatura em Celsius: {:.1f}° C; Temperatura em Fahrenheit: {:.1f}° F; Temperatura em Kelvin: {:.1f} K'.format(celsius, fahrenheit, kelvin)) |
ang1 = int(input('Digite o primeiro valor do ângulo interno do triângulo: '))
ang2 = int(input('Digite o segundo valor do ângulo interno do triângulo: '))
ang3 = int(input('Digite o terceiro valor do ângulo interno do triângulo: '))
# TESTE PARA VERIFICAR SE OS VALORES ANGULARES DIGITADOS FORMAM UM TRIÂNGULO
triangulo = ang1 + ang2 + ang3
if triangulo == 180:
# CLASSIFICAÇÃO DOS TRIÂNGULOS
if ang1 < 90 and ang2 < 90 and ang3 < 90:
print ('Triângulo agudo')
elif ang1 == 90 or ang2 == 90 or ang3 == 90:
print('Triângulo reto')
else:
print('Triângulo obtuso')
else:
print('Os valores angulares digitados não formam um triângulo!')
|
from queue import Queue
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self,root):
self.root = Node(root)
def traverse(self,type):
if type is"preorder":
print(type+" "+self.preorder_traversal(self.root,""))
return
elif type is"inorder":
print(type+" "+self.inorder_traversal(self.root,""))
return
elif type is"postorder":
print(type+" "+self.postorder_traversal(self.root,""))
return
elif type is"levelorder":
print(type+" "+self.levelorder_traversal(self.root))
return
else:
print(type+" is not available !")
return
def preorder_traversal(self,start,traverse):
'''root->left->right'''
if start:
traverse += (str(start.value)+" ")
traverse = self.preorder_traversal(start.left,traverse)
traverse = self.preorder_traversal(start.right,traverse)
return traverse
def inorder_traversal(self,start,traverse):
'''left->root->right'''
if start:
traverse = self.inorder_traversal(start.left,traverse)
traverse += (str(start.value)+" ")
traverse = self.inorder_traversal(start.right,traverse)
return traverse
def postorder_traversal(self,start,traverse):
'''left->right->root'''
if start:
traverse = self.postorder_traversal(start.left,traverse)
traverse = self.postorder_traversal(start.right,traverse)
traverse += (str(start.value)+" ")
return traverse
def levelorder_traversal(self, start):
''' level by level '''
if start:
q=Queue()
q.enqueue(start)
traverse=""
while len(q)>0:
traverse += str(q.peek())+" "
node = q.dequeue()
if node.left:
q.enqueue(node.left)
if node.right:
q.enqueue(node.right)
return traverse
if __name__ == '__main__':
t = BinaryTree(20)
t.root.left = Node(17)
t.root.right = Node(23)
t.root.left.left = Node(10)
t.root.left.right = Node(19)
t.root.right.left = Node(21)
t.traverse("preorder")
t.traverse("inorder")
t.traverse("postorder")
t.traverse("levelorder")
|
# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# from math import *
# from itertools import *
# import random
def isprime(x):
for i in range(2, x):
if x % i == 0:
return False
else:
return True
n, k = map(int, input().split())
count_ = 0
if isprime(k) == False:
print("NO")
else:
for i in range(n + 1, k):
# this part of code need to improvise
if isprime(i) == True:
print("NO")
count_ = 1
break
else:
# count_ += 1
continue
if count_ == 0:
print("YES")
|
# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# from math import *
# from itertools import *
# import random
cd = input()
col = cd[0]
row = int(cd[-1])
if col == "a" or col == "h":
if row == 1 or row == 8:
print(3)
else:
print(5)
elif col == "b" or col == "c" or col == "d" or col == "e" or col == "f" or col == "g":
if row == 1 or row == 8:
print(5)
else:
print(8)
|
# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# from math import *
# from itertools import *
t = int(input())
for i in range(t):
n = int(input())
arr = list(input())
if n < 11:
print("NO")
elif n == 11 and arr[0] != "8":
print("NO")
elif n == 11 and arr[0] == "8":
print("YES")
elif n > 11 and "8" not in arr:
print("NO")
elif n > 11 and "8" in arr:
arr.reverse()
# print(arr)
temp = arr[10:]
# print(temp)
if "8" not in temp:
print("NO")
else:
print("YES")
|
n = int(input())
if n % 3 <= 1:
print(1, 1, n-2)
else:
print(1, 2, n-3)
|
class rankMatrix():
def __init__(self, matrix):
self.rows = len(matrix)
self.cols = len(matrix[0])
def swap(self, matrix, row1, row2, col):
for i in range(col):
temp = matrix[row1][i]
matrix[row1][i] = matrix[row2][i]
matrix[row2][i] = temp
def rankOfMatrix(self, matrix):
rank = self.cols
for row in range(0, rank, 1):
if matrix[row][row] != 0:
for col in range(0, self.rows, 1):
if col != row:
multiplier = (matrix[col][row] /
matrix[row][row])
for i in range(rank):
matrix[col][i] -= (multiplier *
matrix[row][i])
else:
reduce = True
for i in range(row + 1, self.rows, 1):
if matrix[i][row] != 0:
self.swap(matrix, row, i, rank)
reduce = False
break
if reduce:
rank -= 1
for i in range(0, self.rows, 1):
matrix[i][row] = matrix[i][rank]
row -= 1
return (rank) |
#4.1
myList=[7,9,'a','cat',False]
print myList
#4.2
#a
myList.append(3.14)
myList.append(7)
print myList
#b
myList.insert(2,'dog')
print myList
#c
myList.index("cat")
print myList
#d
myList.count(7)
print myList
#e
myList.remove(7)
print myList
#f
myList.pop(myList.index('dog'))
print myList
#4.3
a="the quick brown fox"
b=a.split( )
print b
#4.4
c="mississippi"
d=c.split('i')
print d
#4.5
def Split(sentence):
e=sentence.split( )
return len(e)
print Split('my name is Rohan')
#4.6
#a
def count(aList,item):
var=list.count(item)
return var
#b
def in(aList,item):
if item>=0:
return True
else:
return False
#c
def reverse(aList):
aList.reverse()
return aList
#e
def insert(aList,item,index):
aList.insert(index,item)
return aList |
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
def prime_factors(n):
"Returns all the prime factors of a positive integer"
factors = []
d = 2
while (n > 1):
while (n % d == 0):
factors.append(d)
n /= d
d = d + 1
if (d * d > n):
if (n > 1):
factors.append(n)
break
return factors
print max(prime_factors(600851475143)) # prints 6857
|
""""
https://open.kattis.com/problems/nodup
https://repl.it/repls/ShoddySuperBagworm
different inputs:
THE RAIN IN SPAIN
IN THE RAIN AND THE SNOW
"""
string_input = input().split()
flag = True
for i in string_input:
count = string_input.count(i)
if count > 1:
print("no")
flag = False
break
else:
continue
if flag is True:
print("yes")
|
# Exercise 5
from pathlib import Path
import numpy as np
import pandas as pd
import xarray as xr
import urllib.request
# import functions from utils here
data_dir = Path("data")
solution_dir = Path("solution")
# 1. Go to http://surfobs.climate.copernicus.eu/dataaccess/access_eobs.php#datafiles and
# download the 0.25 deg. file for daily mean temperature. Save the file into the data directory
# but don't commit it to github. [2P]
urllib.request.urlretrieve("https://www.ecad.eu/download/ensembles/data/Grid_0.25deg_reg_ensemble/tg_ens_mean_0.25deg_reg_v19.0e.nc", data_dir/"tg_ens_mean_0.25deg_reg_v19.0e.nc")
# 2. Read the file using xarray. Get to know your data. What's in the file?
data = xr.open_dataset(data_dir/"tg_ens_mean_0.25deg_reg_v19.0e.nc")
# Calculate monthly means for the reference periode 1981-2010 for Europe (Extent: Lon_min:-13, Lon_max: 25, Lat_min: 30, Lat_max: 72). [2P]
data_crop = data.sel(latitude=slice(30,72),longitude=slice(-13,25),time=slice("1981-01-01","2010-12-31"))
means = data_crop.groupby("time.month").mean("time")
# 3. Calculate monthly anomalies for 2018 for the reference period and extent in #2.
# Make a quick plot of the anomalies for the region. [2P]
data_18 = data.sel(latitude=slice(30,72),longitude=slice(-13,25),time=slice("2018-01-01","2018-12-31")).groupby("time.month").mean("time")
anom_18 = data_18 - means
anom_18["tg"].plot(x="longitude", col="month")
# 4. Calculate the mean anomaly for the year 2018 for Europe and compare it to the anomaly of the element which contains
# Marburg. Is the anomaly of Marburg lower or higher than the one for Europe? [2P]
mean_anom_18 = anom_18.mean()["tg"]
mean_anom_18_marb = anom_18.sel(latitude = 50.81, longitude = 8.77, method = "nearest").mean()
if mean_anom_18_marb["tg"] > mean_anom_18:
print("The mean anomaly for Marburg is higher than for Europe")
else:
print("The mean anomaly of Europe is higher than for Marburg")
# 5. Write the monthly anomalies from task 3 to a netcdf file with name "europe_anom_2018.nc" to the solution directory.
# Write the monthly anomalies for Marburg to a csv file with name "marburg_anom_2018.csv" to the solution directory. [2P]
anom_18.to_netcdf(solution_dir/"europe_anom_2018.nc")
anom_18.sel(latitude= 50.80, longitude=8.77, method="nearest").to_dataframe()["tg"].to_csv(solution_dir/"marburg_anom_2018.csv", header=True)
|
'''''
You are here: Home / Basics / Date and Time in Python
Date and Time in Python
Author: PFB Staff Writer
Last Updated: August 27, 2020
Date and Time in Python
In my last post about datetime & time modules in Python, I mostly used the strftime(format) method to print out the dates and times.
In this post, I will show you how you can do it without that by just using datetime.datetime.now().
The second part of the post is about the the timedelta class, in which we can see the difference between two date, time, or datetime instances to microsecond resolution.
Date and Time Script
The last example is a short script for counting how many days there is left for any given date (birthday in this example).
'''''
import datetime
now = datetime.datetime.now()
print "-" * 25
print now
print now.year
print now.month
print now.day
print now.hour
print now.minute
print now.second
print "-" * 25
print "1 week ago was it: ", now - datetime.timedelta(weeks=1)
print "100 days ago was: ", now - datetime.timedelta(days=100)
print "1 week from now is it: ", now + datetime.timedelta(weeks=1)
print "In 1000 days from now is it: ", now + datetime.timedelta(days=1000)
print "-" * 25
birthday = datetime.datetime(2012,11,04)
print "Birthday in ... ", birthday - now
print "-" * 25
'''''
You should see an output simimlar to this:
-------------------------
2012-10-03 16:04:56.703758
2012
10
3
16
4
56
-------------------------
The date and time one week ago from now was: 2012-09-26 16:04:56.703758
100 days ago was: 2012-06-25 16:04:56.703758
One week from now is it: 2012-10-10 16:04:56.703758
In 1000 days from now is it: 2015-06-30 16:04:56.703758
-------------------------
Birthday in ... 31 days, 7:55:03.296242
-------------------------
'''''
|
maior = 0
salarios = [
[float(input("Digite seu salário: ")), float(input("Digite seu salário: ")), float(input("Digite seu salário: "))],
[float(input("Digite seu salário: ")), float(input("Digite seu salário: ")), float(input("Digite seu salário: "))],
[float(input("Digite seu salário: ")), float(input("Digite seu salário: ")), float(input("Digite seu salário: "))]
]
menor = salarios[0][0]
for linha in salarios:
for salario in linha:
if salario > maior:
maior = salario
elif salario < menor:
menor = salario
print("Maior salário: ", maior)
print("Menor salário: ", menor)
|
# Vasya was appointed the manager of the tourist group and he approached the preparation responsibly,
# compiling a food guide indicating calories per 100 grams,
# as well as the content of proteins, fats and carbohydrates per 100 grams of product.
# He could not find all the information, so some cells were left blank
# (you can consider their value equal to zero).
# He also used some strange office suite and separated the integer and fractional parts with a comma.
# The table is available at https://stepik.org/media/attachments/lesson/245290/trekking3.xlsx
#
# Vasya made a product layout for the entire trip (it is on the "Layout" sheet) with the number of the day,
# product name and quantity in grams. For each day, count 4 numbers:
# total calories and grams of proteins, fats and carbohydrates.
# Round down the numbers to the nearest whole number and enter them separated by a space.
# Information about each day should be displayed on a separate line.
""""""
# Васю назначили завхозом в туристической группе и он подошёл к подготовке ответственно,
# составив справочник продуктов с указанием калорийности на 100 грамм,
# а также содержание белков, жиров и углеводов на 100 грамм продукта.
# Ему не удалось найти всю информацию, поэтому некоторые ячейки остались незаполненными
# (можно считать их значение равным нулю).
# Также он использовал какой-то странный офисный пакет и разделял целую и дробную часть чисел запятой.
# Таблица доступна по ссылке https://stepik.org/media/attachments/lesson/245290/trekking3.xlsx
#
# Вася составил раскладку по продуктам на весь поход (она на листе "Раскладка") с указанием номера дня,
# названия продукта и его количества в граммах. Для каждого дня посчитайте 4 числа:
# суммарную калорийность и граммы белков, жиров и углеводов.
# Числа округлите до целых вниз и введите через пробел.
# Информация о каждом дне должна выводиться в отдельной строке.
import pandas as pd
import math
data = pd.ExcelFile('D:\\Downloads\\trekking3.xlsx')
sheet_1 = data.parse(data.sheet_names[0])
sheet_2 = data.parse(data.sheet_names[1])
dict_items = sheet_1.sort_values(by=['Unnamed: 0'])["Unnamed: 0"].to_list()
dict_calorie_content = sheet_1.sort_values(by=['Unnamed: 0'])['ККал на 100'].to_list()
dict_protein_content = sheet_1.sort_values(by=['Unnamed: 0'])['Б на 100'].to_list()
dict_fat_content = sheet_1.sort_values(by=['Unnamed: 0'])['Ж на 100'].to_list()
dict_carbohydrates_content = sheet_1.sort_values(by=['Unnamed: 0'])['У на 100'].to_list()
for el in sheet_2.groupby(by="День"):
# print("-----------------DAY {day}-----------------".format(day=el[0]))
sum_calorie = 0
sum_protein = 0
sum_fat = 0
sum_carbohydrates = 0
for item in el[1][['Продукт', 'Вес в граммах']].values:
food, amount = item
calorie = dict_calorie_content[dict_items.index(food)]
protein = dict_protein_content[dict_items.index(food)]
fat = dict_fat_content[dict_items.index(food)]
carbohydrates = dict_carbohydrates_content[dict_items.index(food)]
sum_calorie = sum_calorie + (amount / 100 * calorie)
sum_protein = sum_protein + (amount / 100 * protein)
sum_fat = sum_fat + (amount / 100 * fat)
if dict_carbohydrates_content[dict_items.index(food)] > 0:
sum_carbohydrates = sum_carbohydrates + (amount / 100 * carbohydrates)
print(math.trunc(sum_calorie), end=" ")
print(math.trunc(sum_protein), end=" ")
print(math.trunc(sum_fat), end=" ")
print(math.trunc(sum_carbohydrates))
|
'''
Product Inventory Project - Create an application which manages an inventory of products.
Create a product class which has a price, id, and quantity on hand.
Then create an inventory class which keeps track of various products and can sum up the inventory value.
(additional requirement: name, sku number, batch number)
'''
class Product(object):
def __init__(self, name = None, sku_num = None, batch_num = None,
unit_cost = None, unit_price = None, batch_quantity = None, receive_date = None):
self.name = name
self.sku_num = sku_num
self.batch_num = batch_num
self.unit_cost = unit_cost
self.unit_price = unit_price
self.batch_quantity = batch_quantity
self.receive_date = receive_date
def entry(self):
self.sku_num = input("Enter SKU number: ")
self.name = input("Enter product name: ")
self.batch_num = input("Enter batch number: ")
self.batch_quantity = float(input("Enter batch quantity: "))
self.unit_cost = float(input("Enter unit cost($): "))
self.unit_price = float(input("Enter unit price($): "))
self.receive_date = input("Enter product receiving date(YYYY-MM-DD): ")
def value(self):
return self.unit_cost*self.batch_quantity
class Inventory(object):
def __init__(self, product_dict = {}):
self.product_dict = product_dict
def entry(self, product):
# Enter product information into inventory
if product.sku_num not in self.product_dict:
self.product_dict[product.sku_num] = []
self.product_dict[product.sku_num].append(product)
def product_num(self):
# number of products in inventory
return len(self.product_dict)
def product_list(self):
# report the list of the products in inventory as a tuple of sku number & sku name
list_prod = []
for product in self.product_dict:
sku_number = self.product_dict[product][0].sku_num
sku_name = self.product_dict[product][0].sku_name
if (sku_number, sku_name) not in list_prod:
list_prod.append(sku_number, sku_name)
else:
continue
return list_prod
def value(self):
# Calculate total inventory value
value_sum = 0
for product in self.product_dict:
for entry in self.product_dict[product]:
value_sum+=entry.value()
return value_sum
def inventory_report(self):
list_report = []
request = input("Enter SKU number: ")
for entry in self.product_dict[request]:
list_report.append((entry.sku_num,
entry.name,
entry.batch_num,
entry.batch_quantity,
entry.value(),
entry.receive_date))
return list_report
import unittest
class Test_Inventory(unittest.TestCase):
def setUp(self):
self.product_1_B1 = Product('sleep bag','100-1','1709001',10,29.99,100, '2017-10-01')
self.product_1_B2 = Product('sleep bag','100-1','1710002',10,29.99,50, '2017-10-14')
self.product_2_B1 = Product('tent','110-22','1701001',25,79.99,250, '2017-03-17')
self.product_2_B2 = Product('tent','110-22','1705002',25,79.99,110, '2017-06-22')
self.product_3_B1 = Product('lamp','43-05','1605001',2.25,14.99,700, '2017-06-22')
self.product_3_B2 = Product('lamp','43-05','1609002',2.25,14.99,900, '2017-08-15')
self.product_4_B1 = Product('airbed','20-11','1612001',19.80,49.99,400, '2017-02-28')
self.product_4_B2 = Product('airbed','20-11','1703002',19.80,49.99,800, '2017-05-25')
self.inventory = Inventory()
self.inventory.entry(self.product_1_B1)
self.inventory.entry(self.product_1_B2)
self.inventory.entry(self.product_2_B1)
self.inventory.entry(self.product_2_B2)
self.inventory.entry(self.product_3_B1)
self.inventory.entry(self.product_3_B2)
self.inventory.entry(self.product_4_B1)
self.inventory.entry(self.product_4_B2)
def test_value(self):
self.assertEqual(self.inventory.value(), 37860)
def test_product_num(self):
self.assertEqual(self.inventory.product_num(), 4)
def test_inventory_report(self):
self.assertEqual(self.inventory.inventory_report(),
[('100-1','sleep bag','1709001',100,1000,'2017-10-01'),
('100-1','sleep bag','1710002',50,500,'2017-10-14'),
('110-22','tent','1701001',250,6250,'2017-03-17'),
('110-22','tent','1705002',110,2750,'2017-06-22'),
('43-05','lamp','1605001',700,1575,'2017-06-22'),
('43-05','lamp','1609002',900,2025,'2017-08-15'),
('20-11','airbed','1612001',400,7920,'2017-02-28'),
('20-11','airbed','1703002',800,15840,'2017-05-25')])
def __del__(self):
pass
def tearDown(self):
del self.product_1_B1
del self.product_1_B2
del self.product_2_B1
del self.product_2_B2
del self.product_3_B1
del self.product_3_B2
del self.product_4_B1
del self.product_4_B2
del self.inventory
print("Test objects are deleted!")
if __name__ == '__main__':
unittest.main(verbosity=2)
|
def insertion_sort(list):
n = len(list)
for i in range(1,n):
key = list[i]
j = i-1
while j >=0 and key < list[j]:
list[j+1] = list[j]
j -= 1
list[j+1] = key
print(list)
insertion_sort([2,1,0,5,6])
|
class Counter(object):
def __init__(self,low,high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
c=Counter(5,10)
iterator = iter(c)
while True:
try:
x=iterator.__next__()
print(x,end=' ')
except StopIteration as e:
break
|
def left_slash(num):
for i in range(int(num)):
print("\\", end="")
def right_slash(num):
for i in range(int(num)):
print("/", end="")
def jump_line(num):
for i in range(int(num)):
print()
def space(num):
for i in range(int(num)):
print(" ", end="")
def upper_part(diameter):
start_spc=diameter/2-1
for i in range(int(diameter/2)):
space(start_spc-i)
right_slash(1)
space(i*2)
left_slash(1)
jump_line(1)
def lower_part(diameter):
for i in range(int(diameter/2)):
space((0+1)*i)
left_slash(1)
space(diameter-(i+1)*2)
right_slash(1)
jump_line(1)
# what tutor does is ...
# start_space=diameter/2
# for i in range(int(diameter / 2)):
# space(i)
# left_slash(1)
# space(start_space- i * 2)
# right_slash(1)
# jump_line(1)
def parallelogram(diameter):
upper_part(diameter)
lower_part(diameter)
parallelogram(20)
|
#place objects
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.title("My window")
window.geometry("200x200")
""""""""" #方法1: pack+side
tk.Label(window, text=1).pack(side="top")
tk.Label(window, text=1).pack(side="bottom")
tk.Label(window, text=1).pack(side="left")
tk.Label(window, text=1).pack(side="right")
"""
""""""""" #方法2: grid + row + column
for i in range(4):
for j in range(3):
tk.Label(window, text=1).grid(row=i, column=j,
padx=10, pady=10) #padx, pady是用作扩展每一个label的占地面积,是可选选项
"""
#方法3:place + pixel(x, y)
tk.Label(window, text=1).place(x=10, y=100, anchor="nw") #anchor对于图片效果明显指出铆定的角
window.mainloop() |
# Read file into list
with open("names.txt", "r") as f:
for line in f.readlines():
names = line.split(",")
names.sort()
total = 0
for i in range(len(names)):
#for name in names:
sum = 0
names[i] = names[i].strip('\"').lower()
for letter in names[i]:
sum += (ord(letter) - ord('a') + 1)
#print("The name " + names[i] + " has a value of " + str(sum*(i+1)))
total += (sum*(i+1))
print(total)
|
#Printing hello
limit=int(input())
for i in range(limit):
print("Hello")
|
print("Quiz 2")
# Marathon App using loops Quiz 2:
# Declaration and intialization
distance_to_cover = 102 # in miles
distance_covered_by_first_walker = 0 # in miles per hour
distance_covered_by_second_walker = 0 # in miles per hour
walking = True
while walking: # Start loop
distance_covered_by_first_walker += 2 # Increment till when rate_of_first_walker + rate_of_second_walker = 102
distance_covered_by_second_walker += 1 # Increment till when rate_of_first_walker + rate_of_second_walker = 102
# The two walkers will meet at a point where the sum of the distances they have covered equate to the distance to cover
if distance_covered_by_first_walker + distance_covered_by_second_walker == 102:
print("They meet at {} miles from the start point of the first walker".format(distance_covered_by_first_walker))
print("And at {} miles from the start point of the second walker ".format(distance_covered_by_second_walker))
|
# I reffered an article for this. Please
# check it if you have trouble understanding this
# Brief Introduction to OpenGL in Python with PyOpenGL
# By Muhammad Junaid Khalid
# https://stackabuse.com/brief-introduction-to-opengl-in-python-with-pyopengl/
# This code includes refernces using
# unique reference code so that you can
# search, find and understand each line
# of code. Please visit
# https://github.com/naseemshah/OpenGLlabs/tree/master/Refrences
# and search for refernce code there.
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
w, h = 500,500
# Sqquare
GLOBAL_X = 0.0
FPS = 60.0
def square(): # in this function we define vertices of square to draw
glBegin(GL_QUADS) # RE1000
glVertex2f(GLOBAL_X, 100) # RE1001 | Coordinates for the bottom left point
glVertex2f(GLOBAL_X +100, 100) # RE1001 | Coordinates for the bottom right point
glVertex2f(GLOBAL_X +100, 200) # RE1001 | Coordinates for the top right point
glVertex2f(GLOBAL_X, 200) # RE1001 | Coordinates for the top left point
glEnd() # RE1000
glutSwapBuffers()
def update(value):
global GLOBAL_X
global FPS
glutPostRedisplay()
glutTimerFunc(int(1000/FPS),update,int(0))
GLOBAL_X = GLOBAL_X + 1.0
def showScreen(): #This function we use to show stuff on screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # RE1002 Remove everything from screen
glLoadIdentity() # RE1003 | Reset all graphic/shape's position
iterate()
glColor3f(1.0, 0.0, 3.0) # RE1005 | gives color to following code
square() # Draw square
# glutSwapBuffers() # RE1004 | Swaps buffers
# However, our code is still not complete. What it currently
# does is draw the square once, and then clear the screen again.
# We don't want that. Actually, we won't even be able to spot the
# moment when it actually draws the square because it would appear
# and disappear in a split second. iterate() is used to avoid this.
def iterate():
glViewport(0, 0, 500,500) # RE1006
glMatrixMode(GL_PROJECTION) # RE1007
glLoadIdentity() # RE1003
glOrtho(0.0, 2000, 0.0, 2000, 0.0, 1.0) # RE1008
glMatrixMode (GL_MODELVIEW) # RE1007
glLoadIdentity() # RE1003
glutInit()
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) # Set the display mode to be colored
glutInitWindowSize(500, 500) # Set the w and h of your window
glutInitWindowPosition(0, 0) # Set the position at which this windows should appear
wind = glutCreateWindow("Draw a Square | Naseem's OpenGLlabs") # Set a window title
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen) # Keeps the window open
glutTimerFunc(int(0),update,int(0))
glutMainLoop() # Keeps the above created window displaying/running in a loop |
matrix = []
test = []
def countCharVal():
sum = 0
for val in test:
sum += val
print("Total sum of all decripted character values is {}".format(sum))
def testForEnglish():
isEnglish = False
times = 0 # number of 'the ' found in text // 116 104 101 32
for index in range(3,len(test)):
if (test[index] == 32 and test[index-1] == 101 and test[index-2] == 104 and test[index-3] == 116):
times += 1
if times > 10:
isEnglish = True
else:
isEnglish = False
return isEnglish
def decript():
key = [0,0,0]
for a in range(97,123): #lower case ascii range
for b in range(97,123):
for c in range(97,123):
test.clear()
key[0] = a
key[1] = b
key[2] = c
print("Key {} {} {}".format(a,b,c))
index = 0
for val in matrix:
cypher = key[index] ^ val
index += 1
if index > 2:
index = 0
test.append(cypher)
if testForEnglish():
testArray()
countCharVal()
return
def loadMatrix():
f = open("p059_cipher.txt", "r") # file comes from PE problem 59
a = f.read()
f.close()
b = a.split(',')
for val in b:
matrix.append(int(val))
def testArray(): #print the test array ascii values
for val in test:
print(chr(val), end='')
print("\n", end='\n')
loadMatrix()
decript()
|
print("Amicable Numbers Q21")
#Evaluate the sum of all the amicable numbers under 10000.
def divisorSum(num):
sum = 0
for divisor in range(1,int(num/2)+1): #int(num/2+1)
if num % divisor == 0:
sum += divisor
return sum
total = 0
for n in range(1,10000):
a = divisorSum(n)
b = divisorSum(a)
if b == n and a != b:
total += n
print("The total of amicable numbers is {}.".format(total))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.