text
stringlengths
37
1.41M
import numpy as np arr = np.arange(0, 3*4) a = arr.reshape([3,4]) print(a) b = np.array([0,1,2,3,4]) print(b[2]) print(b[-1]) print(a) #콤마를 기준으로 앞,뒤:행 열 print(a[0,1]) print(a[-1,-1]) #인덱싱: 행 지정 후, 슬라이싱: 콤마 뒤 추출열 지정 print(a[0,: ]) #첫번째 행 전체를 추출 print(a[ :,1]) #두번째 열 전체를 추출 print(a[1, 1:]) # 두번째 행의 두번째 열부터 끝열까지 추출 print(a[:2, :2]) #[[0 1] # [4 5]] print(a[1, :]) # [4 5 6 7] print(a[1, :].shape) #(4,) rank=1 print(a[1:2, :]) # [[4 5 6 7]] print(a[1:2, :].shape) # (1, 4) rank=2 a = np.array([[1,2],[3,4],[5,6]]) #3행2열 print(a.shape) print(a) print(a[[0,1,2],[0,1,0]]) #a의 [0,0],[1,1],[2,0]로 짝을 지어 해당 행렬이 참조됨: [1 4 5] array로 출력, 벡터 print(a[0,0],a[1,1], a[2,0]) # 1 4 5 그냥 숫자값으로 출력, 스칼라 print([a[0,0],a[1,1], a[2,0]]) # [1, 4, 5] 대괄호를 붙이면서 리스트로 출력 print(np.array([a[0,0],a[1,1],a[2,0]])) # [1 4 5] 위 리스트를 array로 변환 a = np.array([[1,2],[3,4],[5,6]]) print(a) s = a[[0,1],[1,1]] print(s) #부울린 값 lst = [ [1,2,3], [4,5,6], [7,8,9] ] x = np.array(lst) bool_ind_arr = np.array([ [False, True, False], [True, False, True], [False, True, False], ]) print(type(lst)) #<class 'list'> print(type(bool_ind_arr)) #<class 'list'> res = x[bool_ind_arr] print(res) lst = [ [1,2,3], [4,5,6], [7,8,9] ] x = np.array(lst) bool_ind = x%2 #2가 lst 행렬구조에 맞게 확장(브로드캐스팅)되어 각 요소에 연산됨. print(bool_ind) bool_ind = (x%2==0) print(bool_ind) print(x[bool_ind]) #[2 4 6 8] print(x[x%2==0]) #[2 4 6 8]
for i in range(10): print(i, end=" ") print() for i in range(0, 10): print(i, end=" ") print() for i in range(0, 10, 1): print(i, end=" ") print() for i in range(10-1, -1, -1): print(i, end=" ") print() for i in reversed(range(10)): print(i, end=" ") print() s = 0 for i in range(5): s+=i print(s) s = '' for i in range(5): s +=str(i+1) + " " print(s) #
# 이벤트 처리 1 from tkinter import * from tkinter import messagebox # 함수 선언부 def clickLeft(event): xCor = event.x yCor = event.y mButton = event.num txt = "" #빈 문자열 준비 if mButton == 1: txt += '왼쪽' elif mButton == 2 : txt += '가운데' else: txt += '오른쪽' txt += '를' + str(xCor) + ',' + str(yCor) + '에서 클릭함' messagebox.showinfo("마우스", txt) def keyEvent(e): global textBox key = chr(e.keycode) if '0' <= key <= '9': pass else: txt = textBox.get() txt = txt[:-1] textBox.delete(0, 'end') #상자 다 지우기 textBox.insert(0, txt) # messagebox.showinfo("키보드", chr(code)) # 변수 선언부 window = None # 메인 윈도창 # 메인 코드부 window = Tk() window.geometry('400x400') textBox = Entry(window) textBox.bind("<KeyRelease>, keyEvent") textBox.pack(expand=1, anchor=CENTER) # photo = PhotoImage(file = "dog.gif") # label1 = Label(window, image = photo) # label1.pack(expand=1, anchor=CENTER) # label1.bind("<Button>", clickLeft) window.mainloop()
import numpy as np print(np.__version__) list1 = [1,2,3,4] a = np.array(list1) print(a) # [1 2 3 4] print(a.shape) # shape:(4,)=> rank:1 b = np.array([[1,2,3],[4,5,6]]) print(b) print(b.shape) # shape:(2, 3) 2행 3열, rank:2 print(b[0,0]) print(a[2]) print(type(b)) #<class 'numpy.ndarray'> 자료구조 print(type(list1)) #<class 'list'> # 벡터화 연산# #배열의 각 요소에 대한 반복연산을 하나의 명령으로 수행하기 때문에 속도가 빠름 data = [1,2,3,4,5] ans = [] for i in data: ans.append(2*i) print(ans) #[2, 4, 6, 8, 10] #위와 비교되는 벡터화 연산(for 반복문 없음, 속도 훨씬 빠름) x = np.array(data) print(2*x) # [ 2 4 6 8 10] 벡터화 연산으로 각 요소를 두배 print(2*data) #[1, 2, 3, 4, 5, 1, 2, 3, 4, 5] 리스트를 두배 a = np.array([1,2,3]) b = np.array([10,20,30]) print(a*2+b) print(a==2) print(b>10) print((a==2)&(b>10)) print(a.shape) print(a.ndim) #rank 출력 print(a.dtype) #int32:자료형, 4바이트 크기의 정수 저장 a = np.zeros(4) #[0. 0. 0. 0.] print(a) print(a.dtype) # float64: 자료형, 8바이트 실수 저장 a = np.zeros((2,2)) # 2행2열을 0으로 채워라 print(a) a = np.ones((2,3)) # 2행3열을 1로 채워라 print(a) a = np.full((2,3), 5) # 2행3열을 5로 채워라 print(a) a = np.eye(5) #단위행렬: 대각요소값 1 나머지 0: 동일한 구조의 행렬을 곱했을 때 자기자신이 나오는 항등원 행렬 print(a) print(range(20)) print(np.array(range(20)).reshape(4,5)) #1차원(20,) => 2차원(4,5) c = np.array(range(20)).reshape(4,5) print(len(c)) # 행의 개수 print(len(c[0])) #0번 행의 길이, 즉 열의 개수 print(c.ndim) #rank:2 print(c) print(c>10) # True or False print(c[c>10]) #[11 12 13 14 15 16 17 18 19] c[c>10]=99 #10보다 큰 요소들에 99를 대입한다. print(c) arr = np.arange(0, 3*2*4) # [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23] print(arr) print(len(arr)) # 24 v = arr.reshape([3,2,4]) # depth:3, 2행4열 print(v) print(len(v)) # 3 print(len(v[0])) # 2 print(len(v[0][0])) # 4
numStr = '', '' numStr = input("숫자를 입력하세요") print('') i=0 ch=numStr[i] while True: heartNum = int(ch) heartNum = "" for k in range(0, heartNum) : heartStr +="\u2665" k += 1 print(heartStr) i+= 1 if(i > len(numStr)-1) : break ch =
import random dice = input('What side dice are you rolling? ') number = input('How many are you rolling? ') print('You rolled ' + number + 'd' + dice + ' and got: ') for i in range(1, int(number) + 1): print(random.randrange(1, int(dice) + 1))
first = input('Enter first word') second = input('Enter second word') lst = [first, second] word = '-'.join(lst) print(word)
"""Make it rain""" import operator import urllib.request from bs4 import BeautifulSoup def read_in_file(file): f = open(file, 'r') unformatted_file = f.readlines() return unformatted_file def make_table(file): table = [line.split() for line in file] return table def strip_headers(unformatted_table): while unformatted_table[0] != ['------------------------------------------------------------------------------------------------------------------']: unformatted_table.pop(0) unformatted_table.pop(0) for L in unformatted_table: if '<' in L[0]: L.pop(0) # L[0].remove('</p>') # L.remove('</body>') # L.remove('</html>') print(unformatted_table) return unformatted_table def remove_hours(headless_table): return [L[:2] for L in headless_table] def convert_rain_to_int(table): """ # >>> convert_rain_to_int(['1', '2']) # ['1', 2] # # :param table: # :return: void # """ for L in table: if L[1] == '-': L[1] = 0 L[1] = int(L[1]) def find_highest_day(table): """ # >>> find_highest_day([['Mar', 1],['Feb', 2]]) # 'Feb' # # :param table: # :return: # """ convert_rain_to_int(table) highest_rain = 0 for L in table: if L[1] > highest_rain: highest_rain = L[1] highest_day = 'The highest day was ' + str(L[0]) + ' with ' + str(L[1]) + ' inches.' return highest_day def seperate_year(table): year_table = [[table[x][y] for y in range(len(table[0]))] for x in range(len(table))] for L in year_table: L[0] = int((L[0].split('-'))[2]) return year_table def find_highest_year(table): year = 2016 year_table = [] running_total = 0 for L in table: if L[0] == year: running_total += L[1] else: year_table.append([year, running_total]) year = L[0] running_total = L[1] highest_year = 0 for line in year_table: if line[1] > highest_year: highest_year = line[1] highest_year_string = ' ' + str(line[0]) + ' with ' + str(line[1]) return highest_year_string def seperate_date(table): for L in table: L.insert(1, L[0].split('-')) L.remove(L[0]) def create_average_day_dict(table): # date = [] data_by_date = {} #print(table) for L in table: if (L[0][0], L[0][1]) in data_by_date: data_by_date[L[0][0], L[0][1]] += L[1] else: data_by_date[L[0][0], L[0][1]] = L[1] return data_by_date def find_highest_average_day(data_by_date): highest_date = max(data_by_date, key=data_by_date.get) return highest_date def esitmate_rain_by_date(data_by_day, date_to_test): """ # >>> esitmate_rain_by_date(data_by_day) # # :param data_by_day: # :return: # """ average_rain_by_date = data_by_day[date_to_test]/12 #print(average_rain_by_date) return average_rain_by_date def input_date(): month_to_test = input('Enter the month ie JAN, FEB \n') day_to_test = input('Enter the day dd with leading 0s\n') date_to_test = (day_to_test, month_to_test) print(date_to_test) return date_to_test def output_answer(day, year, highest_average_day, estimation_for_date): print('The highest rainfall was on ' + day) print('The highest year for rainfall was' + year) print('The highest average rainfall per day is ' + str(highest_average_day)) print('It is estimated that the rainfall on your selected day will be ' + str(estimation_for_date) + 'inches') def menu_display(): quit = False while quit != True: print(""" The Rain Whisper: Everything you didn't want to know about Portland rain. Select Region 1. North Region # 2. NW Region # 3. NE Region # 4. SW Region # 5. SE Region # 6. Other 7. Quit """) answer = int(input()) quit = region(answer) def region(answer): if answer == 1: quit = north_region() # elif answer == 2: # quit = nw_region() # elif answer == 3: # quit = ne_region() # elif answer == 4: # quit = sw_region() # elif answer == 5: # quit = se_region() # elif answer == 6: # quit = other() elif answer == 7: quit = True else: print('Invalid entry, try again') quit = False return quit def north_region(): print(""" Select a Rain Gage 1. Hayden Island Rain Gage 2. Open Meadows School Rain Gage 3. Shipyard Rain Gage 4. Columbia IPS Rain Gage 5. Albina Rain Gage 6. Swan Island Rain Gage 122 7. Marine Drive Rain Gage 8. Simmons Rain Gage 9. Cascade PCC Rain Gage 10. WPCL Rain Gage 11. Terminal 4 NE Rain Gage 12. Astor Elementary School Rain Gage 13. Swan Island Rain Gage 14. Change Regions 15. Quit """) answer = 0 answer = int(input()) quit = False while quit != True: if answer == 1: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/hayden_island.rain') elif answer == 2: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/open_meadows.rain') elif answer == 3: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/shipyard.rain') elif answer == 4: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/columbia_ips.rain') elif answer == 5: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/albina.rain') elif answer == 6: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/swan_island.rain') elif answer == 7: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/marine_drive.rain') elif answer == 8: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/simmons.rain') elif answer == 9: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/pcc_cascade.rain') elif answer == 10: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/wpcl.rain') elif answer == 11: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/terminal4ne.rain') elif answer ==12: load_url_file('http://or.water.usgs.gov/non-usgs/bes/astor.rain') elif answer == 13: quit = load_url_file('http://or.water.usgs.gov/non-usgs/bes/swan_island_pump.rain') elif answer == 14: return False elif answer == 15: return True else: print('Invalid entry, try again') return quit def load_url_file(link): r = urllib.request.urlopen(link) soup = BeautifulSoup(r, "lxml") text = soup.getText() f = open('rain.txt', 'w') f.write(text) quit = run_data('rain.txt') return quit def run_data(file): unformatted_file = read_in_file(file) unformatted_table = make_table(unformatted_file) headerless_table = strip_headers(unformatted_table) daily_table = remove_hours(headerless_table) highest_day = find_highest_day(daily_table) year_table = seperate_year(daily_table) highest_year = find_highest_year(year_table) seperate_date(daily_table) data_by_day = create_average_day_dict(daily_table) highest_average_day = find_highest_average_day(data_by_day) # print(data_by_day) date_to_test = input_date() estimation_for_date = esitmate_rain_by_date(data_by_day, date_to_test) output_answer(highest_day, highest_year, highest_average_day, estimation_for_date) select = input('Would you like to view another?') if select == 'y' or select == 'Y': return False elif select == 'n' or select == 'N': return True else: print('Invalid entry. exiting') return True def main(): menu_display() main()
# write a program that reads the length of the base and the height of a right angled triangle and prints the area. every number is given on a separate line. length = int(input('enter the length of the base of right angled trianlgle')) height = int(input('enter the height of the right angled triangle')) area = 1/2 * length * height print('the area is', area)
#4.Given threeintegers, print the smallestone.(Threeintegers should be user input) num1 = int(input("enter first number")) num2 = int(input("enter second number")) num3 = int(input("enter third number")) if num1<num2 and num1<num3: print(f'{num1} is smallest') elif num2<num1 and num2<num3: print(f'{num2} is the smallest') else: print(f"{num3} is the smallest")
# 1. Найти функцию которая принимает несколько аргументов. # - С помощью partial передать часть (не все) аргументы в найденную функцию создав новую. # - Передать остаток аргументов получив результат вычисления from functools import partial def t66(a, b): return a + b fn2 = partial(t66, 4) print(fn2) print(fn2(6))
import streamlit as st import pandas as pd def app(): datafile = "bostoncrime2021.csv" df = pd.read_csv(datafile) datafile2 = "BostonPoliceDistricts.csv" df2 = pd.read_csv(datafile2) st.title('Analysis of Boston reported Crime Data') st.subheader("Hello! Welcome to the Boston Crime Data App. This app analyzes and visualizes crime incident data in the first half of 2021 in the city of Boston. ") from PIL import Image image = Image.open('police_report.jpeg') st.image(image) st.subheader("Background") st.markdown("Crime incident reports are provided by Boston Police Department (BPD) to document the initial details surrounding an incident to which BPD officers respond.") st.subheader("Dataset Preview") st.dataframe(df.head(10)) st.subheader("District Table") st.table(df2)
print('----小天使----') temp=input('猜一猜我的小天使是谁:') guess = temp if guess=="周 ": print("猜对了啦") print("猜对了也没奖励") else: print("猜错了") print("猜错了要请客吃饭") print("游戏结束")
''' 循环为多个客户端服务器 ''' import socket def main(): #1. 创建套接字 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #2. 绑定本地信息bind tcp_server_socket.bind(("127.0.0.1", 10000)) #3. 让默认套接字由主动改为被动listen tcp_server_socket.listen(128) while True: #4. 等待客户端的链接accept new_client_socket, client_addr = tcp_server_socket.accept() print("新客户端地址: %s" %str(client_addr)) #5. 接收客户端发来的信息 recv_data = new_client_socket.recv(1024) print("接受信息是: %s" %recv_data.decode("utf-8")) #6. 回送信息给客户端 new_client_socket.send("服务端收到信息".encode("utf-8")) #7. 关闭套接字 # 关闭accept返回的套接字,意味着不会为这个客户端服务 new_client_socket.close() # 将监听套接字关闭 tcp_server_socket.close() if __name__ == "__main__": main()
# Python file to test reading files. # Chp 5 last line exercises, Python Workbook. # Date: 8/5/2020 f = open('demofile.txt', 'rt') blob = f.read() print(blob) f.close() # Printed whole file with correct line spacing, # and without \n tags f = open('demofile.txt') lines = f.readlines() # read all lines into memory print(lines) # printed lines as a list with "" around string and \n at end of each line first_line = lines[0] last_line = lines[-1] print(first_line, last_line) # printed each line without "" but added 1 space between items. print(first_line) print(last_line) # gets rid of extra space? Yes. f.close() f = open('demofile.txt') line_a = f.read(1) # read one character print(line_a) f.close() f = open('demofile.txt') line_b = f.readlines(-2) # unexpected behavior print(line_b) f.close() # f.readlines() does not take number as a passed parameter # f.readlines()[-2] works. Index into iterable lines object.
""" Copy of book code, with my comments. """ from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y # x, y values passed in when class constructor is called def __repr__(self): return 'Vector(%r, %r)' % (self.x, self.y) # returns x, y as real numbers? def __abs__(self): return hypot(self.x, self.y) # absolute value of point (x, y) distance from (0, 0) origin def __bool__(self): return bool(abs(self)) # true if positive? def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) # pass in other, allows setting of 2nd private variable # add two numbers def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar) # vector multiplied by scaler number. # scaler is a passed in private variable
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1/(1+np.exp(-x)) def deriv_sigmoid(x): fx = sigmoid(x) return fx * (1 - fx) def mse_loss(y_true,y_pred): return ((y_true - y_pred) ** 2).mean() class neural_network: def __init__(self): self.w1 = np.random.normal() self.w2 = np.random.normal() self.w3 = np.random.normal() self.w4 = np.random.normal() self.w5 = np.random.normal() self.w6 = np.random.normal() self.b1 = np.random.normal() self.b2 = np.random.normal() self.b3 = np.random.normal() def feedforward(self,x): h1 = sigmoid(self.w1 * x[0] + self.w2*x[1]+self.b1) h2 = sigmoid(self.w3 * x[0] + self.w4*x[1]+self.b2) o1 = sigmoid(self.w5 * h1 + self.w6*h2+self.b3) return o1 def train(self,data,y_trues): learn_rate = 0.1 epochs = 1000 array_epoch = [] array_loss = [] for epoch in range(epochs): for x,y_true in zip(data,y_trues): sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1 h1 = sigmoid(sum_h1) sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2 h2 = sigmoid(sum_h2) sum_o1 = self.w5 * h1 + self.w6 * h2 + self.b3 o1 = sigmoid(sum_o1) y_pred = o1 d_l_d_ypred = -2 * (y_true - y_pred) d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1) d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1) d_ypred_d_b3 = deriv_sigmoid(sum_o1) d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1) d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1) d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1) d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1) d_h1_d_b1 = deriv_sigmoid(sum_h1) d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2) d_h2_d_w4 = x[1] * deriv_sigmoid(sum_h2) d_h2_d_b2 = deriv_sigmoid(sum_h2) self.w1 -= learn_rate * d_l_d_ypred * d_ypred_d_h1 * d_h1_d_w1 self.w2 -= learn_rate * d_l_d_ypred * d_ypred_d_h1 * d_h1_d_w2 self.b1 -= learn_rate * d_l_d_ypred * d_ypred_d_h1 * d_h1_d_b1 self.w3 -= learn_rate * d_l_d_ypred * d_ypred_d_h2 * d_h2_d_w3 self.w4 -= learn_rate * d_l_d_ypred * d_ypred_d_h2 * d_h2_d_w4 self.b2 -= learn_rate * d_l_d_ypred * d_ypred_d_h2 * d_h2_d_b2 self.w5 -= learn_rate * d_l_d_ypred * d_ypred_d_w5 self.w6 -= learn_rate * d_l_d_ypred * d_ypred_d_w6 self.b3 -= learn_rate * d_l_d_ypred * d_ypred_d_b3 if epoch % 10 == 0: y_preds = np.apply_along_axis(self.feedforward, 1, data) loss = mse_loss(y_trues,y_preds) print("epoch %d loss: %.3f" %(epoch,loss)) array_epoch.append(epoch) array_loss.append(loss) return array_epoch,array_loss data = np.array([ [-2,-3], [25,6], [17,4], [-15,-6]]) y_trues = np.array([1,0,0,1]) np.random.seed(1000) network = neural_network() arr_epoch, arr_loss = network.train(data,y_trues) rita = np.array([-7,-3]) jake = np.array([20,2]) print(network.feedforward(rita)) print(network.feedforward(jake)) plt.xlabel('Epochs') plt.ylabel("loss") plt.plot(arr_epoch, arr_loss)
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 15:54:50 2018 @author: user """ low = int(input("enter the lowest number of range:")) high = int(input("enter the highest number of range:")) """ def perfectSq(num): if num/math.sqrt(num) == math.sqrt(num): print("Sq root:", math.sqrt(num)) print("Number:", num) for i in range(low,high+1): perfectSq(i) """ def sumCheck(n): number = n total = 0 while n != 0: digit = n%10 total += digit n=n//10 if total < 10: print(number, " has sum less than 10") print("The perfect squares are:") def perfectSq(num): for i in range(1,num+1): if pow(i,2) == num: print(num) sumCheck(num) for i in range(low,high+1): perfectSq(i)
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 14:21:06 2018 @author: user """ list1 = [int(x) for x in input("enter the elements of the list1:").split()] list2 = [int(x) for x in input("enter the elements of the list2:").split()] mergedList = list1 + list2 print("Merged list:", mergedList) mergedList.sort() print("Sorted merged list:", mergedList)
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 14:48:07 2018 @author: user """ list1 = [int(x) for x in input("enter the elements of the list1:").split()] print("Element 3: ", list1[2]) print("Element 6: ", list1[5]) print("First 5 elements: ") for i in range(0,5): print(list1[i]) length = len(list1) print("Last elements: ") for i in range(6,length): print(list1[i]) list1[1] = 'x' list1[4] = 'y' print("After replacing: ", list1) del(list1[4]) print("After deletion: ", list1) print("Number of elements:", len(list1))
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 17:29:26 2018 @author: user """ string=input("Enter string:") list1=[] list1 = string.split() wordfreq=[list1.count(p) for p in list1] print(dict(zip(list1,wordfreq)))
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 16:17:05 2018 @author: user """ list1 = [int(x) for x in input("enter the elements of the list1:").split()] list2 = [] for i in range(0,len(list1)): total = 0 for j in range(0,i+1): total += list1[j] list2.append(total) print(list2)
# -*- coding: utf-8 -*- """ Created on Thu Jul 26 14:31:51 2018 @author: user """ a = [['Rhia',10,20,30,40,50], ['Alan',75,80,75,85,100], ['Smith',80,80,80,90,95]] #print(type(a)) list1 = [] for i in a: list1.append(i[0:2]) print("the original list is: ", a) print("the sliced list is: ", list1) a[2] = ['Sam',82,79,88,97,99] print("the updated list is: ", a) a[0][3] = 95 print("the updated list is: ", a) content = [73, 80, 85] for i, j in zip(a, content): i.append(j) print("the updated list is: ", a)
import types class Strategy: def __init__(self, Instance="Default", function=None): self.name = Instance def execute(self): print("{} is used!".format(self.name)) def strategy_one(self): print("{} is used to execute method".format(self.name)) def strategy_two(self): print("{} is used to execute method".format(self.name)) s0 = Strategy() s0.execute() s1 = Strategy("Strategy one",strategy_one) s1.execute() s2 = Strategy("Strategy Two", strategy_two) s2.execute()
""" [[1,3], [], [2], [4,5], [], [], []] moveCamel(3,1) return [[1], [3], [2], [4,5]] moveCamel(1,1) return [[], [1, 3], [2], [4,5]] moveCamel(2,1) return [[1], [3], [], [4,5,2]] [1 ,2] + [3] = [1, 2, 3] [0,1,2,3,4] [startind : endind : spacing] """ class Board(object): def __init__(self, boardstate): self.boardstate = boardstate #2d array def moveCamel(self, camelNum, spaces, oldboard): newBoard = oldboard[:] coordinate = self.findCamel(camelNum, oldboard) camelTile = oldboard[coordinate[0]] #camel picked up plus all above it stack = camelTile[ coordinate[1] : ] #taking out stack newBoard[coordinate[0]] = newBoard[coordinate[0]][:coordinate[1]] #moving stack newBoard[coordinate[0] + spaces] += stack return newBoard #takes in the number for the camel to locate. returns coordinate for where the camel is def findCamel(self, camelNum, boardstate): for i in range(len(boardstate)): curTile = boardstate[i] for j in range(len(curTile)): #[[], [camel1, camel2], [],[]] curCamel = curTile[j] if curCamel == camelNum: return [i,j] #returns the camelNum that is in front def findFrontCamel(self, board): for i in range(len(board)-1, -1, -1): curTile = board[i] if curTile != []: return curTile[-1] #assign all possible spaces to move for every camel, then assign the order to move camels, then run boardstate accordinly, then see if specific camel is in front. #[[3,1],[2,2],[5,1],[4,1],[1,1]] def chanceCamelWin(self, board): numTimesWin = [0,0,0,0,0] counter = 0 #assign all possible spaces to move for every camel for i in range(1,4): for j in range(1,4): for k in range(1,4): for l in range(1,4): for m in range(1,4): camelSpacesToMove = [[i],[j],[k],[l],[m]] #then assign the order to move camels camelsToChoose1 = [1,2,3,4,5] ordering = [] for n in range(len(camelsToChoose1)): ordering1 = ordering + [camelsToChoose1[n]] camelsToChoose2 = camelsToChoose1[:n] + camelsToChoose1[n+1:] for o in range(len(camelsToChoose2)): ordering2 = ordering1 + [camelsToChoose2[o]] camelsToChoose3 = camelsToChoose2[:o] + camelsToChoose2[o+1:] for p in range(len(camelsToChoose3)): ordering3 = ordering2 + [camelsToChoose3[p]] camelsToChoose4 = camelsToChoose3[:p] + camelsToChoose3[p+1:] for q in range(len(camelsToChoose4)): ordering4 = ordering3 + [camelsToChoose4[q]] camelsToChoose5 = camelsToChoose4[:q] + camelsToChoose4[q+1:] for r in range(len(camelsToChoose5)): ordering5 = ordering4 + [camelsToChoose5[r]] # by here, ordering should be a list of camel nums that will move the spacings in camelSpacesToMove #now make the camels move their respective amount camelNumSpacePairings = [] for a in range(5): camelNumSpacePairings += [[ordering5[a], camelSpacesToMove[a][0]]] newBoardState = Board.deeparraycopy(self, self.appendboxes(board)) for b in range(5): newBoardState = self.moveCamel(camelNumSpacePairings[b][0], camelNumSpacePairings[b][1], newBoardState) # print("final state:", end= '') # print(newBoardState) numTimesWin[self.findFrontCamel(newBoardState)-1] += 1 counter += 1 percentages = [0 for i in range(5)] for i in range(5): percentages[i] = numTimesWin[i]/counter print("initial board is: " + str(board)) for i in range(len(percentages)): print("chance win of " + str(i + 1) + ": " + str(percentages[i])) def deeparraycopy(self, array): if array == None: return None retarray = [] if isinstance(array, int): return array for i in range(len(array)): retarray += [Board.deeparraycopy(self, array[i])] return retarray def appendboxes(self, array): return array + [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] board = Board([[1,2,3,4,5]]) board.chanceCamelWin([[1],[2,3],[4,5]])
st=input('enter string').split(' ') if st[0]=='Is': s='' for i in st: s+=i print(s) else: st.insert(0,'Is') s='' for i in st: s+=i print(s)
str1=input('Enter ') print(str1) str2=input('Enter ') print(int(str2)+10)
num=int(input('Enter the number: ')) if num<17: diff=17-num print(diff) else: diff=abs(17-num)*2 print(diff)
a=int(input('enter number: ')) n1=int('%s'%a) n2=int('%s%s' %(a,a)) n3=int('%s%s%s'% (a,a,a)) print(n1+n2+n3)
string_value='1234' # here 1234 is a string print(int(string_value)+10) # you can convert int to a string but you cannot convert a string value as a string
# Parent class class Pets: dogs = [] def __init__(self, dogs): self.dogs = dogs # Parent class class Dog: # Class attribute species = 'mammal' # Initializer / Instance attributes def __init__(self, name, age): self.name = name self.age = age # Instance method def description(self): return self.name, self.age # Instance method def speak(self, sound): return "%s says %s" % (self.name, sound) # Instance method def eat(self): self.is_hungry = False # Child class (inherits from Dog class) class RussellTerrier(Dog): def run(self, speed): return "%s runs %s" % (self.name, speed) # Child class (inherits from Dog class) class Bulldog(Dog): def run(self, speed): return "%s runs %s" % (self.name, speed) # Create instances of dogs my_dogs = [ Bulldog("Timmy", 6), RussellTerrier("Fetcher", 7), Dog("Nimbus", 9) ] # Instantiate the Pets class my_pets = Pets(my_dogs) # Output print("I have {} dogs.".format(len(my_pets.dogs))) for dog in my_pets.dogs: print("{} is {}.".format(dog.name, dog.age)) print("And they're all {}s, of course.".format(dog.species))
""" 543. 二叉树的直径 https://leetcode-cn.com/problems/diameter-of-binary-tree/ 时间 O(N) 遍历每一个节点 空间 O(height) 不需要DP """ class Solution: ans = 0 def get_d(self, root): def depth(root): if not root: return -1 depth_l = depth(root.left) + 1 depth_r = depth(root.right) + 1 self.ans = max(self.ans, depth_l + depth_r) return max(depth_l, depth_r) depth(root) return self.ans class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None if __name__ == '__main__': t1 = TreeNode(1) t2 = TreeNode(1) t3 = TreeNode(1) t4 = TreeNode(1) t5 = TreeNode(1) t6 = TreeNode(1) t1.left = t2 t1.right = t3 t2.left = t4 t2.right = t5 t3.right = t6 res = Solution().get_d(t1) print(res)
from random import choice cpu = choice(["ROCK","PAPER","SCISSOR"]) print("ROCK..") print("PAPER>>") print("Scissor") player = input("enter ur move") for i in range(1,3): if player.upper()==cpu.upper(): print("TIE") player = input("enter ur move") else: if player.upper()=="ROCK": if cpu.upper()=="SCISSOR": print("Player1 won") player = input("enter ur move") break elif cpu.upper() =="PAPER": print("CPU WON") player = input("enter ur move") break if player.upper()=="Paper": if cpu.upper()=="SCISSOR": print("CPU won") player = input("enter ur move") break elif cpu.upper() =="ROCK": print("PLayer won") player = input("enter ur move") break if player.upper()=="SCISSOR": if cpu.upper()=="ROCK": print("CPU won") player = input("enter ur move") break elif cpu.upper() =="paper": print("PLayer won") player = input("enter ur move") break
def is_leap(year): leap = False # Write your logic here if year%4==0: if year%100==0 and year%400==0: leap=True elif year%100!=0 and year%400!=0: leap=True else: leap=False return leap year = input("Enter year") print(is_leap(int(year)))
from random import randint ran = randint(1,10) x = input("Enter the number") while(int(x)!=ran): if(int(x)<ran): print("Too low") x = input("Enter new guess") elif(int(x)>ran): print("too high") x = input("Enter new guess") print("{} yes u guessed it".format(int(x))) friend = ["Undertaker","John","Batista"] print(friend[0]) print(friend[2]) items =["Asif","Imad","Rizwan","Sarfaraz","Talha"] for num in range(len(items)): if items[num]=="Sarfaraz": print("found at {} and is {}".format(num,items[num])) if "Mujtaba" in items: print("True") else : print("False") test = ["Syed","Mujtaba","Arfat"] result = " " for x in test: x=x.upper() result +=x print(result)
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ self.board = board self.siz = len(board) self.solve() def findSlot(self): for i in range(self.siz): for j in range(self.siz): if self.board[i][j] == '.': return i, j return -1, -1 def solve(self): row, col = self.findSlot() if row == -1: return True nLst = range(1, 10) nLst = [str(c) for c in nLst] for n in nLst: #print row, col, n if self.solCheck(row, col, n): self.board[row][col] = n if self.solve(): return True self.board[row][col] = "." return False def solCheck(self, row, col, c): # row check if c in self.board[row]: #print c, " check false in", self.board[row] return False # col check for r in self.board: if r[col] == c: #print c, " check false in", r[col] return False # block check bs = int(self.siz ** 0.5) for i in range(row/bs*bs, row/bs*bs+bs): for j in range(col/bs*bs, col/bs*bs+bs): if self.board[i][j] == c: #print c, " check false at ", i, ", ", j return False return True
# coding=utf-8 # The MIT License (MIT) # Copyright (c) 2016 mateor from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import unittest import random # best/average = O(n^2) # very slow - minimal to zero production value. # O(1) space - sorts in place # Only thing it is good for is when list is already sorted # but insertion sort has that as well. # Keeps track of the last swapped element for every pass - everything after that # last swap is already known to be sorted. def bubblesort(A): try: A[:-1] = A[:-1] except TypeError: raise TypeError('This insertion sort requires that the input support indexing. Try a list instead! (was: {})'.format(type(A))) unsorted = len(A) while unsorted != 0: last_swapped = 0 for i in range(1, unsorted): if A[i - 1] > A[i]: A[i - 1], A[i] = A[i], A[i - 1] last_swapped = i unsorted = last_swapped return A
# coding=utf-8 # The MIT License (MIT) # Copyright (c) 2016 mateor from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) # ComplexityTheta(n log n) # A bit slower in practice than quicksort - but has a better # worst-case runtime. # It can be slower than quicksort in practice because the worst-case # of quicksort in most impls is very rare. And in heapsort # there are a lot of element swaps, even if the data is already # ordred. # Not stable! # Put the data in a min/max heap. The root is then the min/max. # When an element is removed from the heap, it self balances # so the next element will "bubble up" to the root. The # heap operations are all superlinear - putting the elements # in the list is dstrictly linear and is dominated by the heap operations. # Heap properties # Use a min-heap with the heap property of: A[PARENT (i)] <= A[i] # Height of tree with n nodes is floor(lg n) # nodes to height bounds: 2^h <= n <= 2^(h+1)-1 -- i.e. the last level must be between empty and full - 1. # heapify - add an element and bubble it up to its proper position in the heap. O(lg n) - the heigth of the tree # build_heap - linear time # heap sort - O(n lg n) # extract-min = remove the root rebalance= - O(lg n) # Heap is a full binary tree (no empty spaces in interior levels) - so it can be represented as an array, # which is space efficient. import random from betarepo.datastructures.comparison_mixin import ComparisonMixin from betarepo.datastructures.trees.heap import Heap def heapsort(A): # HEAPSORT procedure takes time O(n lg n), since the call to BUILD_HEAP takes time O(n) and # each of the n -1 calls to Heapify takes time O(lg n). # implement when the heap is done. pass ### Test Suite ### if __name__ == '__main__': #unittest.main() greg = Heap() nums = [2, 3, 6, 7, 8, 5, 90, 11, 78, 1, ] for num in nums: greg.heapify(num) import pdb; pdb.set_trace()
def factorial_last_zero(number): fact=1 temp=1 while temp <= number: fact*=temp temp+=1 print(fact) count = 0 while fact%10 == 0: fact //= 10 count += 1 return count def fau(number): count=0 i = 5; while i <= number: count+=number//i i*=5 return count if __name__ == '__main__': print(fau(0))
a=int(input("小明身上有幾元:")) b=int(input("有幾種飲料:")) t=0 for i in range(b): c=int((input("第"+str(i+1)+"種飲料:"))) if a>=c: t+=1 print("可以買的飲料:"+str(t))
a=int(input("國:")) b=int(input("英:")) c=int(input("數:")) d=int(input("體:")) e=int(input("程設:")) ans=(a+b+c+d+e)/5 t=[] t.append(a) t.append(b) t.append(c) t.append(d) t.append(e) t.sort() print("平均分數:"+str(round(ans,2))) print("最高分科目"+str(t[4])) print("最低分科目"+str(t[0]))
import random import _sqlite3 conn = _sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS card") create_table = 'create table if not exists card (id INTEGER, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);' insert_data1 = "insert into card(number, pin) values (?, ?);" insert_id = "insert into card(id) values (?);" get_number1 = "select * from card where number = ?;" all_data = "select * from card;" update = "update card set balance=? where number=?;" delete = "delete from card where number = ?;" cur.execute(create_table) def lhn_algorithm(card_number): number = list(card_number) for i in range(15): if (i + 1) % 2 != 0: number2 = int(number[i]) * 2 number[i] = str(number2) for i in number: if int(i) > 9: number2 = number.index(i) number[number2] = str(int(i) - 9) sum1 = 0 for i in range(len(number)): sum1 += int(number[i]) count = 0 if sum1 % 10 != 0: while True: sum1 += 1 count += 1 if sum1 % 10 == 0: break else: count = 0 number = str(card_number) number = list(number) number.append(str(count)) card_number_new = "".join(number) return card_number_new def lhn_algorithm2(card_number): number = list(card_number) for i in range(15): if (i + 1) % 2 != 0: number2 = int(number[i]) * 2 number[i] = str(number2) for i in number: if int(i) > 9: number2 = number.index(i) number[number2] = str(int(i) - 9) sum1 = 0 for i in range(len(number)): sum1 += int(number[i]) return sum1 % 10 != 0 def create_account(): cards_query = conn.execute("SELECT number FROM card").fetchall() account_list = [] for i in range(len(cards_query)): account_list.append(cards_query[i][0][6:-1]) account_identifier = ''.join(str(random.randint(0, 9)) for _ in range(9)) while account_identifier in account_list: account_identifier = ''.join(str(random.randint(0, 9)) for _ in range(9)) else: account_list.append(account_identifier) BIN_account = "400000" + account_identifier list_BIN_account = list(BIN_account) # Convert to integer for i in range(len(list_BIN_account)): list_BIN_account[i] = int(list_BIN_account[i]) # Multiply odd positions by 2 for i in range(len(list_BIN_account)): if i % 2 == 0 or i == 0: list_BIN_account[i] *= 2 # Subtract 9 for i in range(len(list_BIN_account)): if list_BIN_account[i] > 9: list_BIN_account[i] -= 9 # Sum all numbers checksum = sum(list_BIN_account) # Checksum + last digit if checksum % 10 == 0: account_number = BIN_account + "0" else: last_digit = str(10 - (checksum % 10)) account_number = BIN_account + last_digit PIN = ''.join(str(random.randint(0, 9)) for _ in range(4)) conn.execute("INSERT INTO card (number, pin) VALUES (?, ?)", (account_number, PIN)) conn.commit() print("\nYour card has been created\nYour card number:\n{}\nYour card PIN:\n{}\n".format(account_number, PIN)) data = {} id = 0 while True: print(""" 1. Create an account 2. Log into account 0. Exit""") take_input = int(input()) if take_input == 1: print("") create_account() print("") elif take_input == 2: print("") enter_acc = input("Enter your card number:\n") passwor = input("Enter your PIN:\n") data11 = cur.execute(("select number, pin from card where number=?"), (enter_acc,)).fetchall() print() try: if passwor == data11[0][1]: print("") print("You have successfully logged in!") while True: print(""" 1. Balance 2. Add income 3. Do transfer 4. Close account 5. Log out 0. Exit""") input2 = int(input()) if input2 == 1: print("") data12 = cur.execute(("select number, balance from card where number=?"),(enter_acc,)).fetchall() print(f'Balance: {data12[0][1]}') elif input2 == 2: print("") income = int(input("Enter income:\n")) data15 = cur.execute(("select number, balance from card where number=?"),(enter_acc,)).fetchall() income1 = data15[0][1] + income cur.execute(("Update card set balance = ? where number = ?"), (income1, enter_acc)) conn.commit() print("Income was added!") elif input2 == 3: print("") print("Transfer") card_info = input("Enter card number:\n") get_clr = lhn_algorithm2(card_info) if get_clr != 0: print("Probably you made a mistake in the card number. Please try again!") elif get_clr == 0: if enter_acc != card_info: details = cur.execute(("select number from card where number=?"), (card_info,)).fetchall() if details == []: print("Such a card does not exist.") else: add = int(input("Enter how much money you want to transfer:\n")) data13 = cur.execute(("select number, balance from card where number=?"), (enter_acc,)).fetchall() if data13[0][1] < add: print("not enough money") else: modify = data13[0][1] - add cur.execute(("Update card set balance = ? where number = ?"), (modify, enter_acc)) conn.commit() data14 = cur.execute(("select number, balance from card where number=?"), (card_info,)).fetchall() modify1 = data14[0][1] + add cur.execute(("Update card set balance = ? where number = ?"), (modify1, card_info)) conn.commit() print("Success!") else: print("You can't transfer money to the same account!") elif input2 == 4: print("") cur.execute(("delete from card where number=?"), (enter_acc,)) conn.commit() print("The account has been closed!") elif input2 == 5: print("") print("You have successfully logged out!") break elif input2 == 0: exit() else: print("") print("Wrong card number or PIN!") except KeyError: print("") print("Wrong card number or PIN!") except IndexError: print("") print("Wrong card number or PIN!") except TypeError: print("") print("Wrong card number or PIN!") elif take_input == 0: print("Bye!") break
# Get test data for sample of target words to evaluate accuracy. # Similar to get-data-train.py, but more to do here as we have to ensure not to select those already in train # set, meaning there are fewer potential sentences. import lib.utility as u import config as c import random if __name__ == "__main__": # Hard coded list of words to test with target_words = ['wonderful', 'love', 'excellent', 'great', 'classic', 'terrible', 'boring', 'worst', 'stupid', 'crap'] # Store all sentences in memory sentences_with = u.get_lines(c.output_dir + "sentences-with.txt") sentences_without = u.get_lines(c.output_dir + "sentences-without.txt") all_sentences = sentences_with + sentences_without # For each target word, find sample sentences (pos and neg) # N is number of pos/neg instances to select N = 500 i = 0 for word in target_words: #print "for:", word # Shuffle data first random.shuffle(sentences_with) random.shuffle(all_sentences) # Get train set in an array to check we don't get a sentence we already have train_set = u.get_lines(c.train_data_dir + word + ".txt") # Get positive instances (containing word) pos_data = [] count = 0 for s in sentences_with: # stop when we have enough if count == N: break # monitor whether it's been used already used = False words = s.split() # if sentence contains word and meets length threshold if (word in words and len(words) >= 8): # check it's not in training set for x in train_set: if s.strip() in x: used = True break if not used: pos_data.append(s.strip()) count += 1 print count # add another loop, only if we didn't get enough longer sentences if count < N: print "finding shorter sentences..." for s in sentences_with: if count == N: break # monitor whether it's been used already used = False words = s.split() # if sentence contains word and meets length threshold if (word in words and len(words) >= 5): # check it's not in training set for x in train_set: if s.strip() in x: used = True break if not used and s.strip() not in pos_data: pos_data.append(s.strip()) count += 1 print count # Get negative instances (not containing word) # Practically same procedure as above, but this time there are much more sentences to choose from neg_data = [] count = 0 for s in all_sentences: # stop when we have enough if count == N: break # monitor whether it's been used already used = False words = s.split() # if sentences meets length threshold if (len(words) >= 10: # check it's not in training set for x in train_set: if s.strip() in x: used = True break if not used: neg_data.append(s.strip()) count += 1 #print "p:", len(pos_data), "n:", len(neg_data) i += 1 # Write the test data to file #with open(c.output_dir + "target-test-data/" + word + ".txt", "w") as file: # for s in pos_data: # file.write("+1 " + s + "\n") # for s in neg_data: # file.write("-1 " + s + "\n")
''' Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? ''' ''' Time Limit Exceeded class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): visitedNodes = [] if head == None: return False if head.next == None: return False while head != None and head.next != None: if head.next in visitedNodes: return True if head != None: visitedNodes.append(head) else: return False head = head.next return False ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): ''' two points, one move one step and second moves two steps, if there is a circle, P2 can reach P1. ''' if head == None: return False if head.next == head: return True if head.next == None: return False if head.next.next == None: return False P1 = head.next P2 = head.next.next while P2 != None and P2.next != None: if(P1 == P2 and P1 != None): return True P1 = P1.next P2 = P2.next.next return False a =Solution() print a.()
''' Integer to Roman Total Accepted: 6260 Total Submissions: 19425 Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. ''' class Solution: # @return a string def intToRoman(self, num): dict = {1:"I", 2:"II", 3:"III", 4:"IV", 5:"V", 6:"VI", 7:"VII", 8:"VIII", 9:"IX", 10:"X", 20:"XX", 30:"XXX", 40:"XL", 50:"L", 60:"LX", 70:"LXX", 80:"LXXX", 90:"XC", 100:"C", 200:"CC", 300:"CCC", 400:"CD", 500:"D", 600:"DC", 700:"DCC", 800:"DCCC", 900:"CM", 1000:"M", 2000:"MM", 3000:"MMM" } thousand = num / 1000 hundred = (num - thousand * 1000) /100 ten = (num - thousand * 1000 - hundred * 100) /10 digit = num % 10 A = [] if thousand != 0: A.append(dict[thousand*1000]) if hundred != 0: A.append(dict[hundred*100]) if ten != 0: A.append(dict[ten*10]) if digit != 0: A.append(dict[digit]) return "".join(A)
''' Gas Station Total Accepted: 8759 Total Submissions: 36746 There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. Note: The solution is guaranteed to be unique. class Solution: # @param gas, a list of integers # @param cost, a list of integers # @return an integer def canCompleteCircuit(self, gas, cost): def sum(L): n = 0 for i in L: n += i return n; print len(gas) print range(0, len(gas)) diff = []# diff = gas - cost for i in range(0, len(gas)): print i diff.append(gas[i] - cost[i]) print gas print cost print diff mysum = sum(diff) if mysum < 0: return -1 index = 0 length = len(diff) for index in range(0, length): if diff[index] <= 0: continue curr_sum = 0 start_i = index while True: curr_sum += diff[start_i] if curr_sum < 0: break start_i += 1 if start_i == index: return index if start_i == length: start_i = 0 return -1 ''' class Solution: # @param gas, a list of integers # @param cost, a list of integers # @return an integer def canCompleteCircuit(self, gas, cost): def sum(L): n = 0 for i in L: n += i return n; def startSearch(diff, index): start_i = index curr_sum = 0 length = len(diff) while True: curr_sum += diff[start_i] if curr_sum < 0: return -1 start_i += 1 if start_i == index: return index if start_i == length: start_i = 0 diff = []# diff = gas - cost for i in range(0, len(gas)): diff.append(gas[i] - cost[i]) mysum = sum(diff) if mysum < 0: return -1 # only one station situation if len(diff) == 1 and mysum >= 0: return 0 index = 0 length = len(diff) lastNeg = diff[-1] <= 0 while index < length: if diff[index] <= 0: lastNeg = True index += 1 continue if lastNeg: res = startSearch(diff, index) if res >= 0: return res lastNeg = False index += 1 return -1 gas = [2,4,7] cost = [3,5,5] a =Solution() print a.canCompleteCircuit(gas, cost)
def chapter1(): p = (3,7) x,y = p print("x: " + str(x)) person = ["Mohamed","Developer",(1,1,1995)] name,job,birth = person print("name: " + name) # star expressions print("********* star expressions *************") data = ["somename", "many", "others", "information"] name, *others = data print("name: ", name) print(others) line = "somename:x:1000:1000:mbareck,,,:/home/mbareck:/bin/bash" name,_,*_,shell = line.split(":") print("name: " + name + ", shell: " + shell) #1.4 n largest or smallest items print("\n\n\n*********n largest or smallest items *************") import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3,nums),"heapq.nlargest") #1.5 priority queue q = PriorityQueue() if __name__ == '__main__': chapter1()
class student: prof_name="Kamal Sir" def __init__(self,r,n,m): self.rno=r self.name=n self.marks=m def talk(self): print("rno =",self.rno) print("name =",self.name) print("marks =",self.marks) def find_grade(self): if self.marks>80: print("Grade A") else: print("Grade B") @staticmethod def get_prof_name(): print("professor name=",student.prof_name) rno=int(input("enter rno ")) name=input("enter name ") marks=int(input("enter marks ")) s1=student(rno,name,marks) s1.talk() s1.find_grade() s1.get_prof_name() student.get_prof_name()
import random # Given a string s and an integer list indices of the same length. # The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. # Return the shuffled string. s = "odce" indices = [1, 2, 0, 3] ans = "" for i in range(len(indices)): ans += s[indices.index(i)] print(ans)
class Contato: #Contato telefonico def __init__(self, codigo): self.codigo = codigo self.nome = None self.telefone = None self.email = None self.proximo = None self.anterior = None """ self.contatos Lista com os contatos / implantar Fase 2""" """ self.interesses Lista com os interesses / implantar Fase 3""" #GETS def get_codigo(self): return self.codigo def get_nome(self): return self.nome def get_telefone(self): return self.telefone def get_email(self): return self.email def get_proximo(self): return self.proximo def get_anterior(self): return self.anterior #SETS def set_codigo(self, codigo): self.codigo = codigo def set_nome(self, nome): self.nome = nome def set_telefone(self, telefone): self.telefone = telefone def set_email(self, email): self.email = email def set_proximo(self, contato): self.proximo = contato def set_anterior(self, contato): self.anterior = contato """ Implantar Fase 2 def get_contatos(self): return self.contatos """ """ Implantar Fase 3 def get_interesses(self): return self.interesses """ """ Implantar Fase 3 def set_interesses(self, interesses): self.interesses = interesses """ """ Implantar Fase 2 def set_contatos(self, contatos): self.contatos = contatos """
import sys def main(): n = len(sys.argv) if(n > 3): print("Error") command = sys.argv[1] value = int(sys.argv[2]) if(command == "ABC"): print(2*value) if(command == "XYZ"): print(5*value) if(command == "FOO"): print(10*value) sys.exit(0) if __name__ == '__main__': main()
# To print odd or even number. num = int(input("Number: ")) if num % 2 == 0: print(f"Given {num} is Even Number.") else: print(f"Given {num} is Odd Number.")
from basic_list import List, Node class IncresingOrderLinkList(List): def bulk_insert(self, values): for value in values: self.insert(value) def insert(self, value): new_node = Node(value) if self.head is None: self.head = new_node;return head = self.head if head.data > value: self.head = new_node self.head.next = head else: while head.next is not None and head.next.data < value: head = head.next new_node.next = head.next head.next = new_node def delete(self, value): if self.head is None: return head = self.head while head.next is not None and head.next.data != value: head = head.next if head.next is not None: head.next = head.next.next alist = IncresingOrderLinkList() alist.bulk_insert([4, 1,2,4,3,5, 6, 11,9, 2,3,20,1]) alist.print_list() alist.delete(1) alist.print_list()
from math import sqrt class Vector: def __init__(self, a, b): self.a = a self.b = b def __add__(self, vector): return Vector(self.a + vector.a , self.b + vector.b) def __str__(self): return "Vector({},{})".format(self.a, self.b) ab= Vector(1,2) ac= Vector(5,8) print ab+ac x=1 print eval('sqrt(x+3)') import random print random.seed(3) print random.random() print random.seed(3) print random.random() print random.seed(3) print random.random() print random.random() print random.seed(3) print random.random() print random.random() print random.seed(3) print random.random()
class Node(): def __init__(self, value): self.value = value self.next = None class List(): def __init__(self): self.head = None def printList(self): tmp = self.head while (tmp): print tmp.value, tmp = tmp.next print "\n" def addNode(self, value): if not self.head: self.head = Node(value) return tmp= self.head while(tmp.next): tmp=tmp.next tmp.next = Node(value) def bulk_insert(self, values): for value in values: self.addNode(value) def reverse(self): prev = None curr = self.head while(curr): _next = curr.next curr.next = prev prev = curr curr = _next self.head = prev link = List() link.bulk_insert([1,2,3,4,5,6]) link.addNode(7) link.addNode(8) link.printList() link.reverse() link.printList()
import threading import time # semaforo1 = threading.Semaphore(1) # semaforo2 = threading.Semaphore(1) # semaforo3 = threading.Semaphore(1) def threadRed(n): semaforo2.acquire() semaforo3.acquire() for i in range(n): if i%3==0: semaforo1.acquire() print(i, end =" ") semaforo2.release() def threadYellow(n): for i in range(n): if i%3==1: semaforo2.acquire() print(i,end =" ") semaforo3.release() def threadGreen(n): for i in range(n): if i%3==2: semaforo3.acquire() print(i,end =" ") semaforo1.release() loop_count = 100 semaforo1 = threading.Lock() semaforo2 = threading.Lock() semaforo3 = threading.Lock() t_red = threading.Thread(target=threadRed, args=(loop_count,)) t_yellow = threading.Thread(target=threadYellow, args=(loop_count,)) t_green = threading.Thread(target=threadGreen, args=(loop_count,)) t_red.start() t_yellow.start() t_green.start() t_red.join() t_yellow.join() t_green.join() print("") # def even(max_count, lock): # for i in range(max_count+1): # if i%2==0: # with lock: # print i, # lock.notify() # if (max_count-i)>=1: # lock.wait() # # def odd(max_count, lock): # for i in range(max_count+1): # if i%2!=0: # with lock: # lock.wait() # print i, # lock.notify() # # # # lock = threading.Condition() # t1 = threading.Thread(target=even, args=(100,lock,), name="th1") # t2 = threading.Thread(target=odd, args=(100,lock,)) # t2.start() #odd # t1.start() # even # # t1.join() # t2.join()
""" First Pass ( 5 1 4 2 8 ) --> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) --> ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) --> ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) --> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass ( 1 4 2 5 8 ) --> ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) --> ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) --> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) --> ( 1 2 4 5 8 ) Third Pass ( 1 2 4 5 8 ) --> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) --> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) --> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) --> ( 1 2 4 5 8 ) """ arr = [4,2,6,1,22,42,55,-9, -11, 34] ln = len(arr) print arr for i in range(ln-1): for j in range(0, ln-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] print arr
# Python program to understand # the concept of pool import multiprocessing import os ############################################################## ############################################################## ############################################################## def square(n): print("Worker process id for {0}: {1}".format(n, os.getpid())) return (n * n) def multiprocessing_Pool(): mylist = [1,2,3,4,5] p = multiprocessing.Pool() result = p.map(square, mylist) print(result) ############################################################## ############################################################## ############################################################## # function to withdraw from account def withdraw(balance, lock): for _ in range(10000): lock.acquire() balance.value = balance.value - 1 lock.release() # function to deposit to account def deposit(balance, lock): for _ in range(10000): lock.acquire() balance.value = balance.value + 1 lock.release() def perform_transactions(): # initial balance (in shared memory) balance = multiprocessing.Value('i', 100) #balance = multiprocessing.Array('i', range(10)) # i: signed int, d: double precision float lock = multiprocessing.Lock() p1 = multiprocessing.Process(target=withdraw, args=(balance,lock)) p2 = multiprocessing.Process(target=deposit, args=(balance,lock)) p1.start() p2.start() p1.join() p2.join() # print final balance print("Final balance = {}".format(balance.value)) def multiprocessing_data_sharing_value(): for _ in range(10): perform_transactions() ############################################################## ############################################################## ############################################################## if __name__ == "__main__": multiprocessing_Pool() multiprocessing_data_sharing_value()
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 06:22:09 2020 @author: RAMPRIYAN """ from array import* arr1=array('i',[12,34,54,32,11,76]) arr1.insert(6,79) arr1.remove(12) arr1[0]=98 print(arr1.index(32)) for i in arr1: print(i)
a=input("Enter a :") b=input("Enter b:") temp=a a=b b=temp print("The value of a after swapping:{}".format(a)) print("The value of b after swapping:{}".format(b))
import docx import unidecode import re import csv ellipses_char = "\u2026" left_quote = "\u201c" right_quote = "\u201d" def get_file_as_word_list(file_name: str): """ Get all the words in the file as a word list. Parameters ---------- file_name: str The file name to get the words from. Returns ------- word_list: list[str] A list of all the words in the file. """ # Get the text as a string from the docx file document = docx.Document(file_name) text = '\n'.join([paragraph.text for paragraph in document.paragraphs]) text = text.replace('\n', ' ') text = text.replace(ellipses_char, ' ') # Split the text string into a list of words split_string = get_split_string() text_array = re.split(split_string, text) word_list = map(lambda x: unidecode.unidecode(x), text_array) return word_list def read_csv(file_name: str, grouped: bool = False): """ Get all the words in the file as a word list. Parameters ---------- file_name: str The file name to get the words from. grouped: bool Whether or not the words in the file are in groups. Returns ------- words: list[str] (ungrouped) or list[list[str]] (grouped) A list of all the words in the file. """ words = [] with open(file_name) as data: reader = csv.reader(data, delimiter=",", quotechar="|") for row in reader: if (grouped): words.append(row) else: words = words + row return words ##################################################### ### Private Functions ### ##################################################### def get_split_string(): """ Get the split string by which to split the text string into an array of words. Parameters ---------- None Returns ------- split_string: str """ quotations = left_quote + "|" + right_quote periods = "\.| \.| \. |\. " spaces = " | " commas = "\,| \,| \, |\, " question_marks = "\?| \?| \? |\? " exclamation_points = "\!| \!| \! |\! " other = "\;|\; |\:|\: |\.\.\." split_string = quotations + "|" + periods + "|" + spaces + "|" + commas + "|" + question_marks + "|" + exclamation_points + "|" + other return split_string
def BinarySearch(number_list,numbet_to_find): left_index = 0 right_index = len(number_list)-1 mid_index = 0 while left_index<=right_index: mid_index = (left_index+right_index)//2 mid_number = number_list[mid_index] if mid_number == numbet_to_find: return mid_index if mid_number < numbet_to_find: left_index = mid_index+1 else: right_index = mid_index-1 return -1 if __name__ == '__main__': number_list = [2,5,7,10,13,14,18,19,23,28,31] number_to_find = 7 bs = BinarySearch(number_list,number_to_find) print('The position of the number is {} in the list'.format(bs))
# merging sort def mergingSort (arr): if (len(arr)> 1): mid = len(arr)//2 left = arr[:mid] right= arr[mid:] mergingSort(left) mergingSort(right) i=j=k=0 while (i < len(left) and j < len(right)): if left[i] < right[j]: arr[k]= left[i] i+=1 else: arr[k] = right[j] j+=1 k+=1 ##### check whether any element missed or not while (i < len(left)): arr[k] = left[i] i+=1 k+=1 while (j < len(right)): arr[k] = right[j] j+=1 k+=1 arr = [45, 78, 34, 2, 5, 89, 67, 80] print ("Unsorted array : ", arr) mergingSort(arr) print ("This program has been follow divide and conqueor algorithm. MERGING SORT time complexity is o(nlogn)") print ("sorte array : ",arr)
import OthelloLogic import action1 import util from copy import deepcopy from pprint import pprint def action(board, moves): """ Args: board ${1:arg1} moves ${2:arg2} Returns: move 選択したmove """ pprint(moves) # 確定マスではない辺はなるべく取りたい sidePos = len(board) - 1 for move in moves: if isCorner(board, move): pass elif move[0] == 0 or move[0] == sidePos or move[1] == 0 or move[1] == sidePos: if not isStaticPoint(board, move): return move center = action1.getCenter(board) distances = [] for move in moves: distances.append( [util.getDistance([move[0], move[1]], [center[0], center[1]]), move] ) sorted(distances, key=lambda x: x[1]) moves = [] for distance in distances: moves.append(distance[1]) # 辺の確定マスにはなるべく打たない tmpH = [] tmpL = [] for move in moves: if isStaticPoint(board, move): tmpL.append(move) else: tmpH.append(move) tmpH.extend(tmpL) moves = tmpH # 角はなるべくとらない tmpH = [] tmpL = [] for move in moves: if isCorner(board, move): tmpL.append(move) else: tmpH.append(move) tmpH.extend(tmpL) moves = tmpH return moves[0] def isCorner(board, move): """角かどうかどうか判定する Args: move ${1:arg1} Returns: bool """ boardSize = len(board) - 1 l = [ [0, 0], [boardSize, 0], [0, boardSize], [boardSize, boardSize], ] for i in l: if i == move: return True return False def isStaticPoint(board, _move): """辺のうち、確定マスになる場合はtrue Args: board moves Returns: bool """ move = [] move.append(_move[1]) move.append(_move[0]) # なぜboardはboard[y][x]なのにmovesはmoves[x][y]なのか sidePos = len(board) - 1 # 角 if isCorner(board, move): return True # 辺でない場合はfalse if not (move[0] == 0 or move[0] == sidePos or move[1] == 0 or move[1] == sidePos): return False # 横辺 if move[0] == 0 or move[0] == sidePos: # 置くと両端が相手駒になり隙間がない場合も確定マスになる emptyFlag = False # 左に走査して相手駒か空きがあれば左は確定でない i = 1 while True: if move[1] - i < 0: return True cell = board[move[0]][move[1] - i] if cell == -1: break elif cell == 0: emptyFlag = True break else: i += 1 # 右に走査して相手駒が空きがあれば右は確定でない i = 1 while True: if move[1] + i > sidePos: return True cell = board[move[0]][move[1] + i] if cell == -1: break elif cell == 0: emptyFlag = True break else: i += 1 if not emptyFlag: return True # 縦辺 if move[1] == 0 or move[1] == sidePos: # 置くと両端が相手駒になり隙間がない場合も確定マスになる emptyFlag = False # 上に走査して相手駒か空きがあれば上は確定でない i = 1 while True: if move[0] - i < 0: return True cell = board[move[0] - i][move[1]] if cell == -1: break elif cell == 0: emptyFlag = True break else: i += 1 # 下に走査して相手駒が空きがあれば下は確定でない i = 1 while True: if move[0] + i == sidePos: return True cell = board[move[0] + i][move[1]] if cell == -1: break elif cell == 0: emptyFlag = 0 break else: i += 1 if not emptyFlag: return True return False # board = [ # [0, 1, -1, 1, 1, 1, 1, 0], # [-1, 1, -1, -1, 1, 1, -1, 0], # [0, -1, 1, 1, -1, -1, -1, -1], # [1, 1, 1, -1, -1, 1, -1, 0], # [1, 1, 1, 1, -1, 1, -1, 0], # [1, -1, -1, -1, 1, -1, 0, 0], # [-1, -1, -1, -1, -1, 1, -1, 1], # [0, -1, -1, -1, -1, -1, 1, 1], # ] # OthelloLogic.printBoard(board) # moves = OthelloLogic.getMoves(board, 1, 8) # print("----") # util.printMoves(deepcopy(board), moves) # for move in moves: # print("---") # util.printMoves(deepcopy(board), moves, move) # print(move) # print(isStaticPoint(board, move))
import math # IMPORT TP2 def pgcd(a, b): while b != 0: r = a % b a = b b = r return a def bezout(a, b): (u0, u1) = (1, 0) (v0, v1) = (0, 1) while b != 0: r = a % b q = (a - r) / b (a, b) = (b, r) (u0, u1) = (u1, u0 - q*u1) (v0, v1) = (v1, v0 - q*v1) return (a, u0, v0) if a > 0 else (-a, -u0, -v0) def inverse(a, n): res = 0 if n > 1 and pgcd(a, n) == 1: (a, u0, v0) = bezout(a, n) res = u0 % n # TODO: Afficher un message d'erreur si res == 0 return res def verifie_point(A, B, p, P): res = False if P != (0, 0): x, y = P # Calcul y^2 left_op = math.pow(y, 2) % p # Calcul X^3 + AX + B right_op = (math.pow(x, 3) + A*x + B) % p res = left_op == right_op else: res = True return res def addition_points(A, B, p, P, Q): Px, Py = P Qx, Qy = Q res = (0,0) if P == (0,0): res = Q elif Q == (0,0): res = P elif Px != Qx: lamb = ((Qy-Py)*inverse((Qx-Px), p)) % p resx = (math.pow(lamb, 2)-Px-Qx) % p resy = (lamb*(Px-resx)-Py) % p res = (resx,resy) elif Py == Qy: if Py != 0: lamb = ((3*math.pow(Px, 2)+A)*inverse(2*Py, p)) % p resx = (math.pow(lamb, 2)-Px-Px) % p resy = (lamb*(Px-resx)-Py) % p res = (resx,resy) return res def double_and_add(A, B, p, P, k): res = (0,0) b = bin(k)[2:] for di in b: res = addition_points(A, B, p, res, res) if (di) == "1": res = addition_points(A, B, p, P, res) return res def groupe_des_points(A, B, p): res = [] for x in xrange(p): for y in xrange(p): point = (x,y) if verifie_point(A, B, p, point): res.append(point) return res def generateur_du_groupe(A, B, p): res = [] points = groupe_des_points(A, B, p) nb_points = len(points) for point in points: stillLoop = True counter = 0 point_tmp = (0,0) while stillLoop: counter += 1 point_tmp = addition_points(A, B, p, point_tmp, point) if point_tmp == (0,0): stillLoop = False if counter == nb_points: res.append(point) return res
#!/usr/bin/python ''' This script returns the optimal path from one point to another on a 3D cost mask (e.g. brain mask). Note that this is a path and not an interpolation of electrodes along a path. It takes as inputs two sample voxel coordinates representing the starting and ending points on a mask surface as well as the mask itself used to determine the path on which to traverse. It outputs the path as determined by graph traversal using Djikstra's algorithm. ''' import time import numpy as np import networkx as nx import math __version__ = '0.0' __author__ = 'Xavier Islam' __email__ = 'islamx@seas.upenn.edu' __copyright__ = "Copyright 2016, University of Pennsylvania" __credits__ = ["Lohith Kini","Sandhitsu Das", "Joel Stein", "Kathryn Davis"] __license__ = "MIT" __status__ = "Development" def geodesic3D(start, end, mask): ''' returns a geodesic path when given a brain mask, a start point, and an end point. It takes as inputs two sample voxel coordinates (as tuples) representing two points (say corners of a grid for e.g.) along with the brain mask on which to perform geodesic marching. NOTE: the coordinates given and returned are in (i, j, k) notation, NOT ( x, y, z). This means that rows increase downward, columns increase to the right, and layers increase to the back. @param start : Starting coordinate (voxel coordinates) @param end : Ending coordinate (voxel coordinates) @param mask : Brain mask @type start: tuple @type end: tuple @type mask: numpy array @rtype list of tuples Example: >> mask_nib = nib.load('brain_mask.nii.gz) >> mask = mask_nib.get_data() >> geodesic3D((77, 170, 81),(65, 106, 112),mask) ''' # Load mask and initialize graph. mag_path = int(math.ceil(0.01*np.linalg.norm(np.subtract(end, start)))) if start[0] <= end[0]: zero_i = start[0]-mag_path nrow = end[0]+mag_path else: zero_i = end[0]-mag_path nrow = start[0]+mag_path if start[1] <= end[1]: zero_j = start[1]-mag_path ncol = end[1]+mag_path else: zero_j = end[1]-mag_path ncol = start[1]+mag_path if start[2] <= end[2]: zero_k = start[2]-mag_path nlay = end[2]+mag_path else: zero_k = end[2]-mag_path nlay = start[2]+mag_path zero_i = int(zero_i) zero_j = int(zero_j) zero_k = int(zero_k) nrow = int(nrow) ncol = int(ncol) nlay = int(nlay) G = nx.Graph() # Populate graph with nodes, with i being the row number and j being the column number. for i in xrange(zero_i, nrow): for j in xrange(zero_j, ncol): for k in xrange(zero_k, nlay): G.add_node((i, j, k), val=mask[i][j][k]) # Make edges for adjacent nodes (diagonal is also considered adjacent) and set default edge weight to infinity. for i in xrange(zero_i, nrow): for j in xrange(zero_j, ncol): for k in xrange(zero_k, nlay): if i == zero_i and j == zero_j and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) elif i == zero_i and j == zero_j and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) elif i == zero_i and j == zero_j and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) elif i == zero_i and j == ncol-1 and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) elif i == zero_i and j == ncol-1 and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) elif i == zero_i and j == ncol-1 and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) elif i == zero_i and j != zero_j and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) elif i == zero_i and j != zero_j and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) elif i == zero_i and j != zero_j and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) elif i == nrow-1 and j == zero_j and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) elif i == nrow-1 and j == zero_j and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) elif i == nrow-1 and j == zero_j and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) elif i == nrow-1 and j == ncol-1 and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) elif i == nrow-1 and j == ncol-1 and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i == nrow-1 and j == ncol-1 and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i == nrow-1 and j != zero_j and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) elif i == nrow-1 and j != zero_j and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i == nrow-1 and j != zero_j and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i != zero_i and j == zero_j and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) elif i != zero_i and j == zero_j and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) elif i != zero_i and j == zero_j and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) elif i != zero_i and j == ncol-1 and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) elif i != zero_i and j == ncol-1 and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i != zero_i and j == ncol-1 and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i != zero_i and j != zero_j and k == zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) elif i != zero_i and j != zero_j and k == nlay-1: G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) elif i != zero_i and j != zero_j and k != zero_k: G.add_edge((i, j, k), (i, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i+1, j-1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j+1, k-1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k+1), weight=float('inf')) G.add_edge((i, j, k), (i-1, j-1, k-1), weight=float('inf')) # Check neighbors to obtain zero count and assign edge weights accordingly. for i in xrange(zero_i, nrow): for j in xrange(zero_j, ncol): for k in xrange(zero_k, nlay): # Only care about nodes with value of 1. if G.node[(i, j, k)]['val'] == 1: G.node[(i, j, k)]['zc'] = 0 # Obtain zero count (number of neighbors with val of zero) of current node. for x in G.neighbors((i, j, k)): if G.node[x]['val'] == 0: G.node[(i, j, k)]['zc'] += 1 # Assign edge weights according to value. for i in xrange(zero_i, nrow): for j in xrange(zero_j, ncol): for k in xrange(zero_k, nlay): if G.node[(i, j, k)]['val'] == 1: for x in G.neighbors((i, j, k)): if 'zc' in G.node[x] and G.node[(i, j, k)]['zc'] != 0: if G.node[x]['zc'] >= 7: G.edge[(i, j, k)][x]['weight'] = 1 if G.node[x]['zc'] == 6: G.edge[(i, j, k)][x]['weight'] = 2 if G.node[x]['zc'] == 5: G.edge[(i, j, k)][x]['weight'] = 3 if G.node[x]['zc'] == 4: G.edge[(i, j, k)][x]['weight'] = 4 if G.node[x]['zc'] == 3: G.edge[(i, j, k)][x]['weight'] = 5 if G.node[x]['zc'] == 2: G.edge[(i, j, k)][x]['weight'] = 6 if G.node[x]['zc'] == 1: G.edge[(i, j, k)][x]['weight'] = 7 if G.node[x]['zc'] == 0: G.edge[(i, j, k)][x]['weight'] = 8 else: G.edge[(i, j, k)][x]['weight'] = float('inf') # Return Dijkstra's shortest path. return nx.dijkstra_path(G, start, end)
# IA - Particle Swarm Optimization # By: Isaac Montes Jiménez # Created: 10/13/2019 # Modified: 10/15/2019 import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D import numpy as np import random as ran import math #Define the range of the values by the objective function #Ackley function MAX_R_ACKLEY = 4 MIN_R_ACKLEY = -4 #Beale function MAX_R_BEALE = 4.5 MIN_R_BEALE = -4.5 # Max initial particle velocity MAX_V = 2 # C1 = the acceleration factor related to personal best # C2 = the acceleration factor related to global best C1 = 1 C2 = 2 # Store the best position found V_GLOBAL_BEST = [] # Amount of particles PARTICLES = 200 # Number of iterations ITE = 50 # Initial weight W = [0.9] W_REDUCTION = 0.01 # Reduction factor to each iteration # Flag to know if the model of the objective function is plotted # 0 = OFF # 1 = ON MODEL = 0 # Value between points of the model, lower = more quality MODEL_QUALITY = 0.3 # Speed of the iterations, lower = faster SPEED = 100 # Flag to know the objective function # 1 = ACKLEY # 2 = BEALE OBJ_FUNCTION = 2 # Objective function (Ackley) def fn_ackley_function(x,y): f = -20*math.exp(-0.2*math.sqrt(0.5*(x**2+y**2))) - math.exp(0.5*(math.cos(2*math.pi*x) + math.cos(2*math.pi*y))) + math.e + 20 return f # Objective function (Beale) def fn_beale_function(x,y): f = (1.5 - x + x*y)**2 + (2.25 - x + (x*y**2))**2 + (2.625 - x + (x*y**3))**2 return f class Particle: def __init__(self): self.vectorX = [] self.vectorpBest = [] self.vectorX.append(ran.uniform(MIN_R_ACKLEY, MAX_R_ACKLEY)) # current X position self.vectorX.append(ran.uniform(MIN_R_ACKLEY, MAX_R_ACKLEY)) # current Y position self.vectorpBest.append(self.vectorX[0]) # stores the position of the best solution found so far (by this particle) self.vectorpBest.append(self.vectorX[1]) if(OBJ_FUNCTION == 1): self.xFitness = fn_ackley_function(self.vectorX[0], self.vectorX[1]) # stores the current fitness of the particle elif(OBJ_FUNCTION == 2): self.xFitness = fn_beale_function(self.vectorX[0], self.vectorX[1]) self.pBestFitness = self.xFitness # stores the best fitness found by the particle self.velocityX = ran.uniform((-1*MAX_V), MAX_V) # stores the gradient (direction) to move self.velocityY = ran.uniform((-1*MAX_V), MAX_V) def setNextVelocity(self): r1 = ran.random() r2 = ran.random() cognitivoX = C1*r1*(self.vectorpBest[0] - self.vectorX[0]) cognitivoY = C1*r1*(self.vectorpBest[1] - self.vectorX[1]) socialX = C2*r2*(V_GLOBAL_BEST[0] - self.vectorX[0]) socialY = C2*r2*(V_GLOBAL_BEST[1] - self.vectorX[1]) self.velocityX = W[0] * self.velocityX + (cognitivoX + socialX) self.velocityY = W[0] * self.velocityY + (cognitivoY + socialY) def setNextPosition(self): self.vectorX[0] += self.velocityX self.vectorX[1] += self.velocityY def setFitness(self, newFitness): self.xFitness = newFitness def setBestFitness(self, newBestFitness): self.pBestFitness = newBestFitness def fn_createModelAckley(): vX = [] vY = [] vZ = [] x = -1 * MAX_R_ACKLEY while x < MAX_R_ACKLEY: y=-1 * MAX_R_ACKLEY while y < MAX_R_ACKLEY: vZ.append(fn_ackley_function(x,y)) vX.append(x) vY.append(y) y += MODEL_QUALITY x+= MODEL_QUALITY return vX, vY, vZ def fn_createModelBeale(): vX = [] vY = [] vZ = [] x = -1 * MAX_R_BEALE while x < MAX_R_BEALE: y=-1 * MAX_R_BEALE while y < MAX_R_BEALE: vZ.append(fn_beale_function(x,y)) vX.append(x) vY.append(y) y += MODEL_QUALITY x+= MODEL_QUALITY return vX, vY, vZ def main_PSO_3D(): particles = [] modelVX = [] modelVY = [] modelVZ = [] modelInfo = [] particles.append(Particle()) bestAbsFitness = math.fabs(particles[0].xFitness) V_GLOBAL_BEST.append(particles[0].vectorpBest[0]) V_GLOBAL_BEST.append(particles[0].vectorpBest[1]) MAX_PLOT_R = 0 MIN_PLOT_R = 0 if(OBJ_FUNCTION == 1): #Ackley function modelInfo = ['Ackley function', 'Solución: 0', 'x = 0', 'y = 0'] V_GLOBAL_BEST.append(fn_ackley_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1])) MAX_PLOT_R = MAX_R_ACKLEY MIN_PLOT_R = MIN_R_ACKLEY #initialize the particles for i in range(1, PARTICLES): particles.append(Particle()) if(math.fabs(particles[i].xFitness) < bestAbsFitness): bestAbsFitness = math.fabs(particles[i].xFitness) V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_ackley_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) elif(OBJ_FUNCTION == 2): #Beale function modelInfo = ['Beale function', 'Solución: 0', 'x = 3', 'y = 0.5'] V_GLOBAL_BEST.append(fn_beale_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1])) MAX_PLOT_R = MAX_R_BEALE MIN_PLOT_R = MIN_R_BEALE #initialize the particles for i in range(1, PARTICLES): particles.append(Particle()) if(math.fabs(particles[i].xFitness) < bestAbsFitness): bestAbsFitness = math.fabs(particles[i].xFitness) V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_beale_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) # Fill the first position of the particles in the animation x = [] y = [] z = [] for i in range(PARTICLES): x.append(particles[i].vectorX[0]) y.append(particles[i].vectorX[1]) z.append(particles[i].xFitness) # Create the figure to animate fig = plt.figure() ax = fig.add_subplot(111, projection='3d') sct, = ax.plot([], [], [], "ok", markersize=4) ax.grid(True, linestyle = '-', color = '0.75') scale = 1 ax.set_xlim([scale * MIN_PLOT_R, scale * MAX_PLOT_R]) ax.set_ylim([scale * MIN_PLOT_R, scale * MAX_PLOT_R]) ax.set_zlim([-1, 175000]) if(MODEL): if(OBJ_FUNCTION == 1): modelVX, modelVY, modelVZ = fn_createModelAckley() elif (OBJ_FUNCTION == 2): modelVX, modelVY, modelVZ = fn_createModelBeale() ax.plot_trisurf(modelVX, modelVY, modelVZ, cmap=plt.cm.Spectral, antialiased=False) def _update_plot(j): plt.title("Modelo: %s / %s / %s , %s \n\nIteraciones: %d / Mejor Fitness: %f / x = %f , y = %f" %(modelInfo[0], modelInfo[1], modelInfo[2], modelInfo[3], j, V_GLOBAL_BEST[2], V_GLOBAL_BEST[0], V_GLOBAL_BEST[1])) if(j == ITE): anim._stop() partX = [] partY = [] partZ = [] absBestFitness = math.fabs(V_GLOBAL_BEST[2]) if(OBJ_FUNCTION == 1): for i in range(PARTICLES): particles[i].setNextVelocity() particles[i].setNextPosition() particles[i].setFitness(fn_ackley_function(particles[i].vectorX[0], particles[i].vectorX[1])) # store the best fitness and position newAbsFitness = math.fabs(fn_ackley_function(particles[i].vectorX[0], particles[i].vectorX[1])) if(newAbsFitness < math.fabs(particles[i].pBestFitness)): particles[i].setBestFitness(fn_ackley_function(particles[i].vectorX[0], particles[i].vectorX[1])) particles[i].vectorpBest[0] = particles[i].vectorX[0] particles[i].vectorpBest[1] = particles[i].vectorX[1] # Check the best particle to update the reference of the best one if(newAbsFitness < absBestFitness): V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_ackley_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) absBestFitness = math.fabs(V_GLOBAL_BEST[2]) partX.append(particles[i].vectorX[0]) partY.append(particles[i].vectorX[1]) partZ.append(particles[i].xFitness) elif (OBJ_FUNCTION == 2): for i in range(PARTICLES): particles[i].setNextVelocity() particles[i].setNextPosition() particles[i].setFitness(fn_beale_function(particles[i].vectorX[0], particles[i].vectorX[1])) # store the best fitness and position newAbsFitness = math.fabs(fn_beale_function(particles[i].vectorX[0], particles[i].vectorX[1])) if(newAbsFitness < math.fabs(particles[i].pBestFitness)): particles[i].setBestFitness(fn_beale_function(particles[i].vectorX[0], particles[i].vectorX[1])) particles[i].vectorpBest[0] = particles[i].vectorX[0] particles[i].vectorpBest[1] = particles[i].vectorX[1] # Check the best particle to update the reference of the best one if(newAbsFitness < absBestFitness): V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_beale_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) absBestFitness = math.fabs(V_GLOBAL_BEST[2]) partX.append(particles[i].vectorX[0]) partY.append(particles[i].vectorX[1]) partZ.append(particles[i].xFitness) sct.set_data(partX, partY) sct.set_3d_properties(partZ) W[0] -= W_REDUCTION sct.set_data(x, y) sct.set_3d_properties(z) anim = animation.FuncAnimation(fig, _update_plot, interval = SPEED) plt.show() def main_PSO_2D(): particles = [] particles.append(Particle()) bestAbsFitness = math.fabs(particles[0].xFitness) V_GLOBAL_BEST.append(particles[0].vectorpBest[0]) V_GLOBAL_BEST.append(particles[0].vectorpBest[1]) modelInfo = [] if(OBJ_FUNCTION == 1): modelInfo = ['Ackley function', 'Solución: 0', 'x = 0', 'y = 0'] V_GLOBAL_BEST.append(fn_ackley_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1])) MAX_PLOT_R = MAX_R_ACKLEY MIN_PLOT_R = MIN_R_ACKLEY #initialize the particles for i in range(1, PARTICLES): particles.append(Particle()) if(math.fabs(particles[i].xFitness) < bestAbsFitness): bestAbsFitness = math.fabs(particles[i].xFitness) V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_ackley_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) elif(OBJ_FUNCTION == 2): modelInfo = ['Beale function', 'Solución: 0', 'x = 3', 'y = 0.5'] V_GLOBAL_BEST.append(fn_beale_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1])) MAX_PLOT_R = MAX_R_BEALE MIN_PLOT_R = MIN_R_BEALE #initialize the particles for i in range(1, PARTICLES): particles.append(Particle()) if(math.fabs(particles[i].xFitness) < bestAbsFitness): bestAbsFitness = math.fabs(particles[i].xFitness) V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_beale_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) x = [] y = [] for i in range(PARTICLES): x.append(particles[i].vectorX[0]) y.append(particles[i].vectorX[1]) fig = plt.figure() ax = fig.add_subplot(111) ax.grid(True, linestyle = '-', color = '0.75') scale = 2 ax.set_xlim([scale * MIN_PLOT_R, scale * MAX_PLOT_R]) ax.set_ylim([scale * MIN_PLOT_R, scale * MAX_PLOT_R]) sct, = ax.plot([], [], "or", markersize=3) # o = draw dots, r = red, red dots def update_plot(j): partX = [] partY = [] plt.title("Modelo: %s / %s / %s , %s \n\nIteraciones: %d / Mejor Fitness: %f / x = %f , y = %f" %(modelInfo[0], modelInfo[1], modelInfo[2], modelInfo[3], j, V_GLOBAL_BEST[2], V_GLOBAL_BEST[0], V_GLOBAL_BEST[1])) if(j == ITE): anim._stop() absBestFitness = math.fabs(V_GLOBAL_BEST[2]) if(OBJ_FUNCTION == 1): for i in range(PARTICLES): particles[i].setNextVelocity() particles[i].setNextPosition() particles[i].setFitness(fn_ackley_function(particles[i].vectorX[0], particles[i].vectorX[1])) # store the best fitness and position newAbsFitness = math.fabs(fn_ackley_function(particles[i].vectorX[0], particles[i].vectorX[1])) if(newAbsFitness < math.fabs(particles[i].pBestFitness)): particles[i].setBestFitness(fn_ackley_function(particles[i].vectorX[0], particles[i].vectorX[1])) particles[i].vectorpBest[0] = particles[i].vectorX[0] particles[i].vectorpBest[1] = particles[i].vectorX[1] # Check the best particle to update the reference of the best one if(newAbsFitness < absBestFitness): V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_ackley_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) absBestFitness = math.fabs(V_GLOBAL_BEST[2]) partX.append(particles[i].vectorX[0]) partY.append(particles[i].vectorX[1]) elif(OBJ_FUNCTION == 2): for i in range(PARTICLES): particles[i].setNextVelocity() particles[i].setNextPosition() particles[i].setFitness(fn_beale_function(particles[i].vectorX[0], particles[i].vectorX[1])) # store the best fitness and position newAbsFitness = math.fabs(fn_beale_function(particles[i].vectorX[0], particles[i].vectorX[1])) if(newAbsFitness < math.fabs(particles[i].pBestFitness)): particles[i].setBestFitness(fn_beale_function(particles[i].vectorX[0], particles[i].vectorX[1])) particles[i].vectorpBest[0] = particles[i].vectorX[0] particles[i].vectorpBest[1] = particles[i].vectorX[1] # Check the best particle to update the reference of the best one if(newAbsFitness < absBestFitness): V_GLOBAL_BEST[0] = particles[i].vectorpBest[0] V_GLOBAL_BEST[1] = particles[i].vectorpBest[1] V_GLOBAL_BEST[2] = fn_beale_function(V_GLOBAL_BEST[0], V_GLOBAL_BEST[1]) absBestFitness = math.fabs(V_GLOBAL_BEST[2]) partX.append(particles[i].vectorX[0]) partY.append(particles[i].vectorX[1]) sct.set_data(partX, partY) W[0] -= W_REDUCTION sct.set_data(x, y) anim = animation.FuncAnimation(fig, update_plot,interval = SPEED) plt.show() main_PSO_2D() #main_PSO_3D()
from util import is_prime def awesomeness(a, b): n = 0 while is_prime(n**2 + a * n + b): n += 1 return n ma, ans = 0, 0 # max awesomeness, answer for a in xrange(-999, 999+1): for b in xrange(-999, 999+1): ca = awesomeness(a, b) # current awesomeness if ca > ma: ma, ans = ca, a * b print ans
from math import sqrt def is_pentagonal(n): t = (sqrt(1 + 24 * n) + 1) / 6 return int(t) == t j = 1 done = False while not done: j += 1 P_j = j * (3 * j - 1) / 2 for k in xrange(j - 1, 1 - 1, -1): P_k = k * (3 * k - 1) / 2 if is_pentagonal(P_j - P_k) and is_pentagonal(P_j + P_k): print P_j - P_k done = True break
#! /usr/bin/env python import functools from math import sqrt import numpy import operator def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False for x in xrange(3, int(sqrt(n)) + 1, 2): if n % x == 0: return False return True def prime_generator(): yield 2 n = 3 while True: if is_prime(n): yield n n += 2 def product(seq): return reduce(operator.mul, seq) def factorial(n): assert n >= 0 return product(xrange(1, n + 1)) if n > 1 else 1 def combination(n, r): return factorial(n) / factorial(r) / factorial(n - r) from collections import Counter def prime_factorize(n): if n == 1: return Counter({1: 1}) factors = Counter() while n != 1: for x in xrange(2, n + 1): if n % x == 0: factors[x] += 1 n /= x break return factors def proper_divisors(n): factors = [(prime, multiplicity) for prime, multiplicity in prime_factorize(n).iteritems()] f = [0] * len(factors) while True: yield reduce(operator.mul, (factors[x][0] ** f[x] for x in xrange(len(factors))), 1) i = 0 while True: f[i] += 1 if f == [factor[1] for factor in factors]: return if f[i] <= factors[i][1]: break f[i] = 0 i += 1 if i == len(factors): return def d(n): return sum(proper_divisors(n)) def sigma_2(n): return n ** 2 + sum(x ** 2 for x in proper_divisors(n)) class memoize(object): # stolen shamelessly from python.org def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: value = self.func(*args) self.cache[args] = value return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def __get__(self, obj, objtype): """Support instance methods.""" return functools.partial(self.__call__, obj) def fib_gen(): a, b = 0, 1 while True: yield a a, b = b, a + b def gcd(a, b): return a if b == 0 else gcd(b, a % b) def lcm(a, b): return abs(a * b) / gcd(a, b) def phi(n): return len([x for x in xrange(1, n) if gcd(x, n) == 1]) def primesfrom2to(n): sieve = numpy.ones(n / 3 + (n % 6 == 2), dtype=numpy.bool) sieve[0] = False for i in xrange(int(n ** 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[((k * k) / 3)::2 * k] = False sieve[(k * k + 4 * k - 2 * k * (i & 1)) / 3::2 * k] = False return numpy.r_[2, 3, ((3 * numpy.nonzero(sieve)[0] + 1) | 1)]
from math import pi print('Введите два радиуса или длину хорды и ничего: ') t = int(input()) r2 = input() if r2 != '': r1 = t r2 = int(r2) del t radiuses_product = r1 * r2 else: radiuses_product = t ** 2 / 16 s = pi * 2 * radiuses_product print(round(s, 2))
def factorial(n): if n == 1: return 1 else: if n == 2: return 2 else: return n * factorial(n - 1) def count_end_nulls(res): res = str(factorial(n)) ind = len(res) - 1 count = 0 while res[ind] == '0': count += 1 ind -= 1 return count n = int(input("Введите основание факториала: ")) print(count_end_nulls(str(factorial(n))))
def is_prime(n, divider): if divider > n // 2: return True else: if n % divider != 0: return is_prime(n, divider + 1) else: return False for n in range(2, 1001): if is_prime(n, 2): print(n)
""" Задача: Если элемент матрицы равен 0, то всю строку и весь столбец нужно обнулить. """ from random import randint matrix = [[randint(0, 10) for i in range(0, 5)] for i in range(0, 4)] for inner_arr in matrix: for j in inner_arr: print(j, end=' ' * (5 - len(str(j)))) # хитрый способ настроить отступы для наилучшего вида print() rows = [] columns = [] for i in range(0, len(matrix)): for j in range(0, len(matrix[0])): if matrix[i][j] == 0: rows.append(i) columns.append(j) for row in rows: for col in range(0, len(matrix[0])): matrix[row][col] = 0 for col in columns: for row in range(0, len(matrix)): matrix[row][col] = 0 print() for inner_arr in matrix: for j in inner_arr: print(j, end=' ' * (5 - len(str(j)))) # хитрый способ настроить отступы для наилучшего вида print()
# Uses python3 import sys def optimal_weight(W, w): # write your code here val = [[None] * (len(w) + 1) for _ in range(W + 1)] for u in range(W + 1): val[u][0] = 0 print(val) for i in range(1, len(w) + 1): for u in range(W + 1): val[u][i] = val[u][i-1] if u >= w[i - 1]: val[u][i] = max(val[u][i], val[u - w[i-1]][i-1] + w[i-1]) return val[W][len(w)] if __name__ == '__main__': # input = sys.stdin.read() # W, n, *w = list(map(int, input.split())) W = 10 n = 3 w = [1, 4, 8] print(optimal_weight(W, w))
from sys import setrecursionlimit def fibonacci(prev=1, cur=1): swap = cur cur += prev prev = swap print(cur) print() return fibonacci(prev, cur) setrecursionlimit(2600) fibonacci()
from random import random n = int(input("Enter number of flips: ")) history = {'eagle': 0, 'tails': 0} for i in range(0, n): rand_num = random() if round(rand_num) == 0: history['eagle'] += 1 else: history['tails'] += 1 print(history)
x1 = int(input("Type x1: ")) x2 = int(input("Type x2: ")) y1 = int(input("Type y1: ")) y2 = int(input("Type y2: ")) a = abs(x2 - x1) b = abs(y2 - y1) print(a) print(b) if a / b == a // b or b / a == b // a: if a >= b: print(b + 1) else: print(a + 1) else: print(2)
fans_num1 = int(input('Введите кол-во болельщиков 1: ')) fans_num2 = int(input('Введите кол-во болельщиков 2: ')) places = int(input('Введите кол-во мест в номерах: ')) if fans_num1 % places == 0: rooms1 = fans_num1 // places else: rooms1 = fans_num1 // places + 1 if fans_num2 % places == 0: rooms2 = fans_num2 // places else: rooms2 = fans_num2 // places + 1 print(rooms1 + rooms2)
""" Задача: Дана гистограмма, она представлена числовым массивом: [3, 6, 2, 4, 2, 3, 2, 10, 10, 4] Нужно посчитать объем воды (1 блок в гистограмме), ктр наберется внутри нее. """ from matplotlib import pyplot as plt arr = [3, 6, 2, 4, 2, 3, 2, 10, 10, 4, 5, 6, 4, 10] plt.bar(range(len(arr)), arr) plt.show() water = 0 j = 0 for i in range(len(arr) - 1): if i < j: continue if arr[i + 1] < arr[i]: start = i j = start + 1 while arr[i] > arr[j]: water += arr[i] - arr[j] j += 1 print(water)
"""LAB1 CPE202 """ # import unittest #1 def get_max(int_list): """find the maximum in a list of integers Args: int_list (list): a list of integers Returns: int: max integer """ max_int = 0 if len(int_list) == 0: return None for i in range(len(int_list)): if int_list[i] > max_int: max_int = int_list[i] return max_int #2 def reverse(in_str): """reverse a string recursively w/o reverse string library Args: in_str (str): a string to reverse Returns: str: the reversed string """ if len(in_str) == 0: return in_str return reverse(in_str[1:]) + in_str[0] #3 def search(slist, targ): """find index of target integer in sorted list recursively Args: slist (list): sorted list of integers targ (int): value to search for Returns: int: index of largest integer """ low = 0 high = len(slist) mid = len(slist)//2 return search_helper(slist, targ, low, mid, high) def search_helper(slist, targ, low, mid, high): """helps search function find index of target integer in sorted list recursively Args: slist (list): sorted list of integers targ (int): value to search for low (int): lowest index of array mid (int): dynamic mid index used to find target high (int): largest index of array Returns: int: index of largest integer """ if low == mid or mid == high-1 or slist == []: if slist and (slist[mid] == targ): return mid return None if slist[mid] == targ: return mid if slist[mid] > targ: mid = mid//2 return search_helper(slist, targ, low, mid, high) # else slist[mid] > targ mid = (mid+high)//2 return search_helper(slist, targ, low, mid, high) #4 def fib(term): """find the value of the nth fibonacci number Args: term (int): the nth term to calculate fibonacci Returns: int: value of nth fibonacci number """ if term == (1 or 2): return 1 if term > 1: return fib(term-1) + fib(term-2) return 0 #5.1 factorial iterative version def factorial_iter(nth): """calculate the nth factorial iteratively Args: n (int): the nth factorial to be calculated Returns: int: value of the nth factorial """ res = 0 if nth < 2: return 1 while nth > 2: res += nth*(nth-1) nth = nth-1 return res #5.2 factorial recursive version def factorial_rec(nth): """calculate the nth factorial recursively Args: n (int): the nth factorial to be calculated Returns: int: value of the nth factorial """ if nth <= 1: return 1 return nth*factorial_rec(nth-1)
print("Please think of a number between 0 and 100!") low = 0 high = 100 inp = '' while inp != 'c': num = int((low + high)/2) print("Is your secret number %i?"% num) inp = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ") if inp == 'l': low = num elif inp == 'h': high = num elif inp == 'c': print("Game over. Your secret number was: %i"% num) else: print("Sorry, I did not understand your input.")
''' Find all of the numbers from 1-1000 that are divisible by 7 Find all of the numbers from 1-1000 that have a 3 in them Count the number of spaces in a string Remove all of the vowels in a string Find all of the words in a string that are less than 4 letters Challenge: Use a dictionary comprehension to count the length of each word in a sentence. Use a nested list comprehension to find all of the numbers from 1-1000 that are divisible by any single digit besides 1 (2-9) For all the numbers 1-1000, use a nested list/dictionary comprehension to find the highest single digit any of the numbers is divisible by ''' # Find all of the numbers from 1-1000 that are divisible by 7 def createList(f, t): return list(range(f, t)) def divisableBy7(n): return (n % 7) == 0 def divisableBy7ListCompre(li): return [number for number in range(1000) if divisableBy7(number)] def main(): print(divisableBy7ListCompre(createList(1, 1000))) if __name__ == '__main__': main()
strToSearch = "This is a test string" pattern = "is" #create a function called match that takes two arguments, one the pattern, the other the string, returns true or false if the pattern is found or not found. lenStr = len(strToSearch) lenPattern = len(pattern) for i in xrange(0,lenStr): if (!pattern[0] == strToSearch[i]): break; print ("false") elif ( else: print ("not found")
def is_even(): numbers = [1,56,234,87,4,76,24,69,90,135] print("The odd numbers are:",[number for number in numbers if not number%2==0]) # call fxn is_even()
#1a my_list = ["Amy", 1, "Beth", "Charlie", 6, "Daisy", 7, 2 ] #1b my_list[2] = "Sandy" print (my_list) #1c my_list [1] = 1**2 my_list [4] = 6**2 my_list [6] = 7**2 my_list [7] = 2**2 print(my_list) #1d my_list.count() #???
my_first_name = "Henrietta" print(my_first_name) x = "Blue" y = "Blue" z = "Blue" print(f"{x=} {y=} {z=}") print (f"{x.upper()}")
#3a question_list = ["q", "u", "e", "s", "t", "i", "o", "n"] print (question_list) #3b list_of_list = [[5,3,4], [1,3,2,1], [3,2,3], [10,1,5], [6,7,2]] def list_addition ()
#Python Item 40 exercises #This version was as instructed - but it prints age twice :-/ and seems sloppy print("This program determines how long you have lived in days, minutes and seconds") print(" ") name = input("What is your name?: ") print("Please enter your age: ") age = int(input("age: ")) days = age * 365 minutes = age * 525948 seconds = age * 31556926 print(name, "has been alive for", days,"days", minutes, "minutes and", seconds, "seconds.") print(" ") print(" ") #This version does the same thing, without redunancy and better output:-) print("This program determines how long you have lived in days, minutes, and seconds") def comma(num): if type(num) == int: return '{:,}'.format(num) elif type(num) == float: return '{:,.2f}'.format(num) else: print("Please enter a whole number for your age") print(" ") name = input("Hi! What's your name?: ") age = int(input("Please enter your age: ")) ''' in a perfect world there should be something here (like a function for age) if someone enters "20.5" or "twenty"; to ask for a whole number. I thought the comma function could kill two birds with one stone ...but it didn't work as intended for the error part ... ''' days = age * comma(365) minutes = age * comma(525948) seconds = age * comma(31556926) print(name, "has been alive for", days,"days,", minutes, "minutes, and", seconds, "seconds." )
#Python 2.7.14 #Sandy Glantz via Dan Christie TA video Nice or Mean print "Python Item 35" print "---------------------------------" print "---------------------------------" ''' def start(): print ("What\'s up {}?".format(get_number())) def get_number(): name = raw_input("What is your name? ") return name if __name__ == "__main__": start() ''' # End of first exercise ''' def start(): f_name = "Sarah" l_name = "Connor" age = 28 gender = "Female" get_info(f_name,l_name,age,gender) def get_info (f_name,l_name,age,gender): print("My name is {} {}. I am {} years old.".format(f_name, l_name, age, gender)) if __name__ == "__main__": start() ''' # End of second exercise def start(nice=0,mean=0,name=""): # get user's name name = describe_game(name) nice,mean,name = nice_mean(nice,mean,name) def describe_game(name): ''' Checks if new game; if new, get user's name. If not new game - thank player for playing again and continue with game ''' if name != "": # if no name they are new - and need to get name print("\nThank you for playing again, {}!".format(name)) else: stop = True while stop: if name == "": name = raw_input("\nWhat is your name? ").capitalize() if name != "": print("\nWelcome aboard {}!".format(name)) print("\nYou will meet several people. \nYou can be nice or mean.") print("Your actions will determine your fate.") stop = False return name def nice_mean(nice,mean,name): stop = True while stop: show_score(nice,mean,name) pick = raw_input("\nA stranger approaches you ... are you nice or mean? (n/m): ").lower() if pick == "n": print("They smile, wave, and walk away ...") nice = (nice + 1) stop = False if pick == "m": print("\nThe stranger laughs in an evil tone and starts to follow you ...") mean = (mean+1) stop = False score(nice,mean,name) # pass the three variables to the score() def show_score(nice,mean,name): print("\n{}, you currently have {} Nice, and {} Mean, points.".format(name,nice,mean)) def score(nice,mean,name): if nice > 5: win(nice,mean,name) if mean > 5: lose(nice,mean,name) else: nice_mean(nice,mean,name) def win(nice,mean,name): print("\nNice job {}, you win! \nEveryone loves you!".format(name)) again(nice,mean,name) #calls new variable called again def lose(nice,mean,name): print("\nA hermit\'s life for you, {}. \nGood thing your Mother still loves you!".format(name)) again(nice,mean,name) def again(nice,mean,name): stop = True while stop: choice = raw_input("\nDo you want to play again? (y/n): ").lower() if choice == "y": stop = False reset(nice,mean,name) if choice == "n": print("\nSee you later alligator!") stop = False exit() else: print("\nPlease enter 'y' for 'YES' - or 'n' for 'NO' ") def reset(nice,mean,name): nice = 0 mean = 0 start(nice,mean,name) if __name__ == "__main__": start()
import time import sys import numpy as np import random # This function generates a random problem instance def make_random_problem(n_variables, n_clauses): # This is a helper function to check if a row occurs in a matrix def find_row(mx, row): for i in range(mx.shape[0]): if np.all(mx[i, :] == row): return True return False # This is a helper function to make a random clause (represented as a row # in a Numpy matrix) def make_random_clause(n_variables): # Create a Numpy matrix to store the row clause_mx = np.zeros((1, n_variables)) # Fill in a random clause for i in range(n_variables): clause_mx[0, i] = random.choice((-1, 0, 1)) return clause_mx # Start with a random row (representing one clause) problem_mx = make_random_clause(n_variables) # Add unique, non-empty clauses until the problem reaches the required size while problem_mx.shape[0] < n_clauses: temp = make_random_clause(n_variables) if not find_row(problem_mx, temp) and not np.all(temp == np.zeros((1, n_variables))): problem_mx = np.vstack((problem_mx, temp)) return problem_mx # This function makes a random assignment of values to variables def make_random_assignment(n_variables): # Allocate a Numpy array assignment_mx = np.zeros((1, n_variables)) # Assign random truth values to the variables for i in range(n_variables): assignment_mx[0, i] = random.choice((-1, 1)) return assignment_mx # This function calculates the number of violations a solution has def calculate_violation(problem, solution): violations = 0 for i in range(problem.shape[0]): row_result = False exist_literal = False for j in range(problem.shape[1]): if problem[i, j] == 1: exist_literal = True literal = solution[0, j] == 1 row_result = row_result or literal elif problem[i, j] == -1: exist_literal = True literal = solution[0, j] == 1 row_result = row_result or literal if exist_literal and not row_result: violations += 1 return violations # Main program def main(): n_variables = int(input("Number of variables: ")) n_clauses = int(input("Number of clauses: ")) iterations_logging = True if len(sys.argv) > 1: if sys.argv[1] == "--no-logging": iterations_logging = False print("Generating problem...") problem = make_random_problem(n_variables, n_clauses) print("Generating starting solution...") candidate_solution = make_random_assignment(n_variables) steps = 0 start_time = time.time() print("Running Local Search...") for i in range(10): steps = i violations = calculate_violation(problem, candidate_solution) print(f"Iterations #{i + 1}") if iterations_logging: print("Problem:") print(problem) print("Candidate solution:") print(candidate_solution) print(f"Violations: {violations}") print() if violations == 0: print("-- Found global minimum --") break lowest_violations = violations lowest_idx = -1 for i in range(n_variables): candidate_solution[0, i] = 1 if candidate_solution[0, i] == -1 else -1 new_violations = calculate_violation(problem, candidate_solution) if new_violations < lowest_violations: lowest_violations = new_violations lowest_idx = i candidate_solution[0, i] = 1 if candidate_solution[0, i] == -1 else -1 if lowest_idx == -1: print("-- Found local minimum --") break else: candidate_solution[0, lowest_idx] = 1 if candidate_solution[0, lowest_idx] == -1 else -1 print("-- in {} step(s) --".format(steps)) print("-- in {:.5f} seconds".format(time.time() - start_time)) if not iterations_logging: print("Problem:") print(problem) print("Solution:") print(candidate_solution) if __name__ == "__main__": main()
hours = 1 while hours <=12: minutes = 00 while minutes <60: print(f'{hours}:{minutes}') minutes = minutes + 1 hours = hours + 1
import random vidaLeptude = 3 vidaJaque = 3 vezJaque = True print("Bem vindo as aventuras matemáticas de Leptude o Mago de patinete") print("Leptude por algum motivo entra em batalha com o sapo mago professor de matemática interdimensional Jaque, para vencer dele você precisa acertar suas perguntas de matemática ou então ele vai te matar de tédio") while(vidaLeptude > 0 and vidaJaque > 0): if(vezJaque): perguntaJaque = str(random.randint(1, 25))+"+"+str(random.randint(1,25)) resposta = input("Jaque te ataca com a pergunta: quanto é "+perguntaJaque+"? ") print("A resposta da pergunta era",eval(perguntaJaque)) if int(resposta) == eval(perguntaJaque): print("Acertou mizerávi") else: vidaLeptude-=1 print("Errou mizerávi, agora você está com",vidaLeptude,"pontos de vida") else: resposta = eval(input("Agora Leptude, ataque jaque com uma conta de matemática: ")) respostaJaque = random.randint(resposta - 1, resposta + 1) print("A resposta de sua pergunta é",resposta,"e Jaque respondeu ",respostaJaque) if resposta == respostaJaque: print("Jaque acertou sua pergunta") else: vidaJaque-=1 print("Jaque errou sua pergunta. Agora Jaque está com",vidaJaque,"pontos de vida") print("") vezJaque = not(vezJaque) if(vidaJaque > 0): print("Você perdeu a batalha e agora Jaque começa a te ensinar matemática, até que você morre de tédio") else: print("Jaque perdeu a batalha, então você começa a zuar ele, ele fica nervoso e volta a sua dimensão para ter reforço de matemática") print("FIN")
#Range vs xrange ==================== #range() vs xrange() in Python #range() and xrange() are two functions that could be used to #iterate a certain number of times in for loops in Python. #In Python 3, there is no xrange , but the range function behaves #like xrange in Python 2.If you want to write code that will run on #both Python 2 and Python 3, you should use range(). #range() – This returns a list of numbers created using range() function. #xrange() – This function returns the generator object that can be used to #display numbers only by looping. Only particular range is displayed on demand #and hence called “lazy evaluation“. #Both are implemented in different ways and have different characteristics associated with them. #The points of comparisons are: #Return Type #Memory #Operation Usage #Speed #Return Type : range() returns – the list as return type. xrange() returns – xrange() object. # Python code to demonstrate range() vs xrange() # on basis of return type # initializing a with range() a = range(1,10000) # initializing a with xrange() x = xrange(1,10000) # testing the type of a print ("The return type of range() is : ") print (type(a)) # testing the type of x print ("The return type of xrange() is : ") print (type(x)) #Memory: #The variable storing the range created by range() takes more memory as #compared to variable storing the range using xrange(). #The basic reason for this is the return type of range() is # list and xrange() is xrange() object. #Operations usage #As range() returns the list, all the operations that can be #applied on the list can be used on it. On the other hand, as #xrange() returns the xrange object, operations associated to list # cannot be applied on them, hence a disadvantage. #Speed : #Because of the fact that xrange() evaluates only #the generator object containing only the values that are #required by lazy evaluation, therefore is faster in #implementation than range(). #For the most part, xrange and range are the exact same in terms #of functionality. They both provide a way to generate a list of #integers for you to use, however you please. The only difference #is that range returns a Python list object and xrange returns an xrange object #range() and xrange() Functionality #In terms of functionality both range() and xrange() functions generates integer numbers within given range. #i.e range (1,5,1) will produce [1,2,3,4] and xrange(1,5,1) will produce [1,2,3,4] #so no difference in terms of functionality between range() and xrange(). #range() and xrange() return value #range() creates a list i.e. range returns a Python list object, for example, #range (1,500,1) will create a python list of 499 integers in memory. remember, #range() generates all numbers at once. #xrange() functions returns an xrange object that evaluates lazily. #that means xrange only stores the range arguments and generates the #numbers on demand. it doesn’t generate all numbers at once like range(). and #this object only supports indexing, iteration, and the len() function. #on the other hand xrange() generates the numbers on demand. that means it produces number #one by one as for Loop moves to the next number. In every iteration of for loop, #it generates the next number and assigns it to the iterator variable of for loop. #range() and xrange() return type #-->range() return type is Python list. #-->xrange() function returns xrange object. #as you know xrange doesn’t actually generate a static list at run-time like range does. #xrange() creates the values on demand as you need them using a technique called yielding. #range() function produced all numbers instantaneously before the for loop started executing. #The main problem with the original range() function is it uses a very large amount of memory #if you are producing a huge range of numbers #xrange() function always produces the next number on the fly i.e. #only keeps one number in memory at a time to consume less memory. #If you are dealing with a large range of numbers then I recommend you to use xrange() # i.e. you should always favor xrange() over a range() if we want to generate the huge range of numbers. #This is very helpful if your system has less memory like cell phones. #using xrange() you can prevent memory overflow errors. #As xrange() resolves each number lazily, if you stop iteration early, # you won’t waste time creating the whole list. #Scenarios where we can use range() function in python : #If you want to iterate over the list multiple times then I recommend you to use range(). # because xrange has to generate an integer object every time you access an index, this will be overhead. #If you need to generate fewer numbers then go for range() function. #range() returns the list, so you can use all list operations on it. #On the other hand, you know xrange() returns the xrange object, so you can’t use all list operations on it. #Compatibility of code – If you want to write code that will run on both Python 2 and Python 3, # use range() as the xrange function is deprecated in Python 3.
import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3 from tkinter import * from PIL import Image, ImageTk class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master=None): # parameters that you want to send through the Frame class. Frame.__init__(self, master) #reference to the master widget, which is the tk window self.master = master #with that, we want to then run init_window, which doesn't yet exist self.init_window() #Creation of init_window def init_window(self): # changing the title of our master widget self.master.title("Lucas & Ronald") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) # creating a menu instance menu = Menu(self.master) self.master.config(menu=menu) # create the file object) file = Menu(menu) # adds a command to the menu option, calling it exit, and the # command it runs on event is client_exit file.add_command(label="Exit", command=self.client_exit) #added "file" to our menu menu.add_cascade(label="File", menu=file) # create the file object) edit = Menu(menu) # adds a command to the menu option, calling it exit, and the # command it runs on event is client_exit edit.add_command(label="Show Img", command=self.showImg) edit.add_command(label="Show Text", command=self.showText) #added "file" to our menu menu.add_cascade(label="Edit", menu=edit) #added "file" to our menu menu.add_cascade(label="Edit", menu=edit) def showImg(self): load = Image.open("interface.png") render = ImageTk.PhotoImage(load) # labels can be text or images img = Label(self, image=render) img.image = render img.place(x=0, y=0) def showText(self): text = Label(self, text="Hey there good lookin!") text.pack() def client_exit(self): exit()
def addition(a, b): try: #check input types num1 = int(a) num2 = int(b) except: return None return num1 + num2 def subtraction(a, b): try: #check input types num1 = int(a) num2 = int(b) except: return None return num1 - num2 def multiplication(a, b): try: #check input types num1 = int(a) num2 = int(b) except: return None return num1 * num2 def division(a, b): try: #check input types num1 = int(a) num2 = int(b) except: return None if(b == 0): #divide by zero return None return num1 / num2
""" ====== Discount Sceme ====== Upto 1000 Rs. - No Discount 1000 to 1999 - 10% Discount 2000 to 4999 - 20% Discount 5000 and Above - 30% Discount """ """WAP to calculate total discount on final billing based on Above slabs""" Slab_20_Fix_Discount = 600 Slab_10_Fix_Discount = 100 def check_slab(amount): if amount > 5000: diff = amount - 5000 discount_applicable = diff * 0.3 my_dict = {"Slab30":discount_applicable} return my_dict elif amount > 2000 and amount <= 5000: diff = amount - 2000 discount_applicable = diff * 0.2 my_dict = {"Slab20":discount_applicable} return my_dict elif amount > 1000 and amount <= 2000: diff = amount - 1000 discount_applicable = diff * 0.1 my_dict = {"Slab10":discount_applicable} return my_dict elif amount <= 1000: discount_applicable = 0 my_dict = {"NoSlab":discount_applicable} return my_dict print(__doc__) print "\n" slab = dict() amount = int(raw_input("Enter total amount : ")) slab = check_slab(amount) for k, v in slab.iteritems(): if k == "Slab30": discount = v + Slab_20_Fix_Discount + Slab_10_Fix_Discount elif k == "Slab20": discount = v + Slab_10_Fix_Discount elif k == "Slab10": discount = v elif k == "NoSlab": discount = v billing_amount = amount - discount print "\nDiscount = {} INR".format(discount) print "\nBilling Amount = {} INR".format(billing_amount)
a=int(input("enter the number")) rev=0 while a>0: rev=(rev*10)+(a%10) a=a//10 print(rev) # a=int(input("enter the number")) # rev=0 # while a>0: # rev=(rev*10)+(a%10) # a=a//10 # print(rev)
w=input() i=0 for a in range (len(w)): if(w[a].isdigit() or w[a].isalpha() or w[a]==' '): continue else: i+=1 print(i)
re = input() b = ["a","e","i","o","u","A","E","I","O","U"] c=len(re) for i in range(0,c): if(re[i] in b): print("yes") break else: print("no")