text
stringlengths
37
1.41M
from tkinter import simpledialog, messagebox, Tk, Canvas import math # Write a Python program that asks the user for the radius of a circle. # Next, ask the user if they would like to calculate the area or circumference of a circle. # If they choose area, display the area of the circle using the radius. # Otherwise, display the circumference of the circle using the radius. if __name__ == '__main__': window = Tk() window.withdraw() radius = simpledialog.askinteger(None, None) aoc = simpledialog.askstring(None, "a or c") if aoc == "a": messagebox.showinfo(None, str(math.pi*radius**2)) else: messagebox.showinfo(None, str(2*math.pi*radius)) #Area = πr^2 #Circumference = 2πr
# Тип данных строка (str) # Инициализация temp_str = 'Марка авто "Volvo"' print(temp_str) # Экранирование #temp_str = 'Марка авто \'Volvo\' # Обращение к символам, подстрокам # выведет в кажд-ю строку, одну букву. Вывод ПОСИМВОЛЬНО for i in range(len(temp_str)): print(temp_str[i]) # Срезы print(temp_str[1:4]) print(temp_str[:]) print(temp_str[0:]) # одинарный срез print('--') print(temp_str[-3:3]) # это не печатает!?!?! print('*') print(temp_str[1:-3]) print('- Конец срезы -') # Функ-ции со строками print(temp_str, len(temp_str)) print('- Конец Функ-ции со строками -') # Операции со строками print() print('- Операции со строками -') temp_str2 = 'Mersedes' print(temp_str + temp_str2) # !!!!! рекомен НЕ ПОЛЬЗОВАТЬСЯ + , т.к. трудоемко компику!!! print(temp_str2 * 2) print('- Конец Операции со строками -') # Форматирование строк # Строки это не изменяемый тип, поэтому проще создать новую print() print('- Форматирование строк -') car = 'Марка: {} цена: {}'.format('Volvo', 1.5) print(car) print(' *') brend = 'Volvo' price = 1.5 car2 = 'Марка: {} цена: {}'.format(brend, price) print(car2) print('* *') car3 = f'Марка: {brend} цена: {price}' # это самый ПРЕДПОЧТИТЕЛЬНЫЙ способ print(car3) print('- Конец Форматирование строк -') # Методы print() print('- Методы -') print(temp_str.split()) print('*') cars = 'Volga,Audi,BMW,Reno,Lada,SAAB' print(cars.split()) # Разобьет на отде-е элементы (если есть пробелы!!!) print(cars.split(',')) # мы указали РАЗДЕЛИТЕЛЬ!!! и... print('* *') # Методы форматирования строк print(cars.upper()) # все буквы ЗАГЛАВНЫЕ print('* * *') print(cars.title()) # ПЕРВЫЕ буквы ЗАГЛАВНЫЕ print(cars.lower()) # все буквы маленькие print('* * * *') # Замена подстроки в строке my_kontakt = 'eMail: _xxx_' eMail2 = '[email protected]' print(my_kontakt.replace('_xxx_', eMail2)) print('- Конец Методы -')
# Тип данных Словарь dict dict_temp = {} print(type(dict_temp), dict_temp) dict_temp = {'dict': 1, 'dict2': 2.1, 'dict3': 'name', 'dict4': [1, 2, 3]} print(type(dict_temp), dict_temp) print(' * ') dict_temp = dict.fromkeys(['a', 'b']) # fromkeys создает словарь с КЛЮЧАМИ без ЗНАЧЕНИЙ print(type(dict_temp), dict_temp) print(' * * ') dict_temp = dict.fromkeys(['a', 'b'], [12, '2020']) # наполняем значениями print(type(dict_temp), dict_temp) print(' * * * ') dict_temp = dict(brend = 'Volvo', volume_engine = 1.5) # dict метод наполнения print(type(dict_temp), dict_temp) print(' * * * * ') # Генератор словаря dict_temp = {a: a**2 for a in range(10)} print(dict_temp) # Обращене к содержимому словаря print(' Обращене к содержимому словаря ') print(dict_temp[8]) print(' выыод всех ключей СЛОВАРЯ ') print(dict_temp.keys()) print() # но обычно приводят к листу print(' но обычно приводят к листу ') print(list(dict_temp.keys())) print(' - - ') # Получение значений print(' Получение значений ') print(list(dict_temp.values())) print() # также можно рабоать с парами (ключ:знач) = items, он возвращает КОРТЕЖИ print(' также можно рабоать с парами (ключ:знач) = items ') print(list(dict_temp.items())) print() # Работа с элементами print(' Работа с элементами ') print(type(dict_temp), dict_temp) dict_temp[0] = 100 # к опред ключу присвоим значение print(type(dict_temp), dict_temp) print(' - - - - - -') # Добавляем новую ПАРУ print(' Добавляем новую ПАРУ ') dict_temp['name'] = 'Dima' print(type(dict_temp), dict_temp) print(' / / / / / ') # Методы # Удаляем значение по ключу pop print(' Удаляем значение по ключу ') dict_temp.pop('name') print(type(dict_temp), dict_temp) # или вывести значение которое удалил print('вывести значение которое удалил') temp = dict_temp.pop(0) # почему оно не удалено!?!?! print(temp) print(dict_temp) print(' *-*-*-*-*-*-*') # Итерирование по словарю print(' Итерирование по словарю ') for pair in dict_temp.items(): print(pair) # Итерирование по словарю II способ print(' * Итерирование по словарю II способ * ') for key, value in dict_temp.items(): print(key, value) print(' + + + + + + + ') # Итерирование по ключам print(' Итерирование по ключам ') for key in dict_temp.keys(): print(key) print('&&&&&&&&&&&&&') # Итерирование по ЗНАЧЕНИЯМ print(' Итерирование по ЗНАЧЕНИЯМ ') for value in dict_temp.values(): print(value)
#TP4 : Table de Multiplication #Exercice 1 : Open Class Room #Src : https://openclassrooms.com/fr/courses/235344-apprenez-a-programmer-en-python/231442-avancez-pas-a-pas-vers-la-modularite-1-2 import os def multipl(number,max=11): """ docstring de la fonction multipl : Table de multiplication Taper : help(multipl) """ for i in range(max): print(i," * ",number," = ",i*number) #test de la fonction table if __name__=="__main__": number=int(input("Entrer un nombe !!\n")) multipl(number)
from random import randint # available weapons => store this in an array choices = ["Rock", "Paper", "Scissors"] player = False player_lives = 5 computer_lives = 5 # make the computer pick one item at random computer = choices[randint(0, 2)] # show the computer's choice in the terminal window print("computer chooses", computer) # set up our loop while player is False: player = input("Rock, Paper or Scissors?\n") print("Player chooses", player) if (player == computer): print("Tie! Live to shoot another day") elif player == "Rock": if computer == "Paper": # computer won print("You lose!", computer, "covers", player) else: print("You win!", player, "smashes", computer) elif player == "Paper": if computer == "Scissors": print("You lose!", computer, "cuts", player) else: print("You won!", player, "covers", computer) elif player == "Scissors": if computer == "Rock": print("You lose!", computer, "smashes", player) else: print("You win!", player, "cuts", computer) elif player == "Quit": exit() else: print("Not a valid option. Check again, and check your spelling!\n") #checking win/lose if player_lives is 0: print("Zero lives, play again?") choice = input("Y / N? ") if choice == "Y" or choice == "y": player_lives = 5 computer_lives = 5 player = False computer = choices[randint(0,2)] elif choice == "N" or choice =="n": print("you've had enough losing") exit() if computer_lives is 0: print("computer out of lives, play again?") choice = input("Y / N? ") if choice == "Y" or choice == "y": player_lives = 5 computer_lives = 5 player = False computer = choices[randint(0,2)] elif choice == "N" or choice =="n": print("you've had enough losing") exit() player = False computer = choices[randint(0, 2)]
from playsound import playsound import keyboard def sound(): playsound('') #add the name of the mp3 file here, you want to play when you press the buton. exit = True while (exit): if(keyboard.is_pressed('space')): #Change here for which button you want to play the mp3 file. sound() exit = not (keyboard.is_pressed('esc'))
import time import requests from datetime import datetime import billboard """ File that reads in a date from the command line and finds the top song on that day for all years since that date""" def validate_input(bday_raw): """ Validates string passed is a valid birthday Returns: tuple containing (invalid_input, formatted_bday) where invalid_input is a boolean set to True if input is invalid """ try: month = int(bday_raw[:2]) date = int(bday_raw[2:4]) year = int(bday_raw[4:]) bday = datetime(month=month, day=date, year=year) if bday <= datetime.now(): return (False, bday) except (TypeError, ValueError): return (True, None) return (True, None) # Grab date from input def grab_birthday(): """ Prompts a user for their birthday in the form of MMDDYYYY""" invalid_input = True bday = None while invalid_input: invalid_input = False bday_raw = input("Please enter your birthday (MMDDYYYY): ") if len(bday_raw) != 8: invalid_input = True print("Must input 8 characters!") print() continue invalid_input, bday = validate_input(bday_raw) if invalid_input: print("Invalid Input, Birthday format must be MMDDYYYY") print() continue return bday # Iterate through all years since that date and query billboard for the #1 song on that date def get_top_songs(bday): top_songs = [] for year in range(bday.year, datetime.now().year): date = datetime(month=bday.month, day=bday.day, year=year) formatted_date = date.strftime("%Y-%m-%d") chart = billboard.ChartData("hot-100", date=formatted_date, timeout=None) top_songs.append(chart[0]) return top_songs
n=int(input("enter te no.plz")) for i in range(0,n+1): print (" "*(n-i),"*"*(i*2-1)) for i in range(n-1,0,-1): print (" "*(n-i),"*"*(i*2-1))
n=int(input("enter the value of list : ")) l=[] for i in range(0,n): a=int(input("value of list : ")) l.append(a) l.sort() print(l) c=0 l2=[] for i in range(0,n-1): if l[i+1] == l[i]: l2.append(l[i]) l2.sort() print(l2) l3=[] for i in range(0,n-1): if l[i+1] != l[i]: l3.append(l[i]) l3.sort() l4=l2+l3 print(l4)
short_names = ['Jan', 'Sam', 'Ann', 'Joe', 'Tod'] short_names.sort() short_names.reverse() print(short_names)
from Stack import Stack def main(): stack = Stack() stack.push(0) assert stack.data == [0, None] assert stack.capacity == 2 assert stack.size == 1 stack.push(1) assert stack.data == [0, 1] assert stack.capacity == 2 assert stack.size == 2 stack.push(2) assert stack.data == [0, 1, 2, None] assert stack.capacity == 4 assert stack.size == 3 stack.push(3) assert stack.data == [0, 1, 2, 3] assert stack.capacity == 4 assert stack.size == 4 print("Expected:", "['0', '1', '2', '3'] Capacity: 4") print("Output:", str(stack)) main()
def high_and_low(numbers): numbers_arr = numbers.split(" ") numbers_arr = [int(num) for num in numbers_arr] high_number = numbers_arr[0] low_number = numbers_arr[0] for num in numbers_arr: if(num > high_number): high_number = num low_number = high_number for num in numbers_arr: if(num < low_number): low_number = num return f"{high_number} {low_number}" print(high_and_low("1 2 3 4 5"))
import numpy as np class Mullayer: def __init__(self): self.x=None self.y=None def forward(self,x,y): self.x=x self.y=y out=x*y return out def backward(self,dout): dx=dout*self.y dy=dout*self.x return dx,dy ''' apple=100 apple_num=2 tax=1.1 mul_apple_layer=Mullayer() mul_tax_layer=Mullayer() #forward apple_prick=mul_apple_layer.forward(apple, apple_num) price=mul_tax_layer.forward(apple_prick,tax) print(price) #backward dprice=1 dapple_prick,dtax=mul_tax_layer.backward(dprice) print(dapple_prick) print(dtax) dapple,dapple_num=mul_apple_layer.backward(dapple_prick) print(dapple) print(dapple_num) '''
import numpy as np import matplotlib.pylab as plt def function_1(x): return x**3 def function_2(x,k,b): return k*x+b def function_3(f1,k,x): return f1(x)-k*x def numerical_diff(f,x): h=0.0001 return (f(x+h)-f(x-h))/(2*h) def k_line(f1,x,c): k=numerical_diff(f1, c) b=function_3(f1,k,c) z=function_2(x,k,b) plt.plot(x,z,linestyle = "--",) #x=np.arange(-5,5,0.1) #y=function_1(x) #plt.plot(x,y) #k_line(function_1,x,0) #plt.show()
# https://www.hackerrank.com/challenges/arrays-ds/problem # Complete the reverseArray function below. def reverseArray(a): a = reversed(a) return a
#!/usr/bin/env python3 def main(): szam = input("Szám: ") print(int(str(szam)[::-1])) if __name__ == ('__main__'): main()
def ciklus(start, end, debug=False): if debug: print('#ciklus kezdete') inp = [str(n ) +',' for n in range(start, end + 1)] print(''.join(inp)[:-1]) if debug: print('#ciklus vége') def main(): ciklus(1, 10) ciklus(1, 10, True) if __name__ == '__main__': main()
#!/usr/bin/env python3 def main(): x = input('Páros szám:') print(str(diamond(x))) def diamond(x): if int(x) % 2 == 0: return 'Csak páratlan számok!' else: n = '' for i in range(1, int(x)+1, 2): subs = '*' * i n = n + subs.center(int(x)+1) + '\n' for i in reversed(range(1, int(x),2)): subs = '*' * i n = n + subs.center(int(x)+1) + '\n' n.strip() return n if __name__ == '__main__': main()
""" Create a list of five IP addresses. Use the .append() method to add an IP address onto the end of the list. Use the .extend() method to add two more IP addresses to the end of the list. Use list concatenation to add two more IP addresses to the end of the list. Print out the entire list of ip addresses. Print out the first IP address in the list. Print out the last IP address in the list. Using the .pop() method to remove the first IP address in the list and the last IP address in the list. Update the new first IP address in the list to be '2.2.2.2'. Print out the new first IP address in the list. """ from __future__ import print_function, unicode_literals my_list = ["10.1.1.1", "10.1.2.1", "10.1.3.1", "8.8.8.8", "10.1.4.1"] my_list.append("10.2.1.1") my_list.extend(["10.4.1.1", "10.4.1.2"]) my_list = my_list + ["10.4.10.1", "10.4.10.2"] print(my_list) print(my_list[0]) print(my_list[-1]) first_ip = my_list.pop(0) last_ip = my_list.pop(-1) my_list[0] = "2.2.2.2" print(my_list[0])
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg # TODO 2. Use color transforms, gradients, etc., to create a thresholded binary image. # Define a function that applies Sobel x or y, # then takes an absolute value and applies a threshold. def abs_sobel_thresh(img_gray, orint='x', sobel_kernel=3, abs_thresh=(0, 255)): if 'x' == orint: sobel = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) elif 'y' == orint: sobel = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) else: print('illegal direction!') return abs_sobel = np.absolute(sobel) scale_sobel = np.uint8(abs_sobel * 255 / np.max(abs_sobel)) img_binary = np.zeros_like(img_gray) img_binary[(scale_sobel >= abs_thresh[0]) & (scale_sobel <= abs_thresh[1])] = 1 return img_binary # Define a function that applies Sobel x and y, then computes the # magnitude of the gradient and applies a threshold def mag_thresh(img_gray, sobel_kernel=3, mag_thresh=(0, 255)): xsobel = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) ysobel = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) mag_sobel = np.sqrt(xsobel * xsobel + ysobel * ysobel) factor = np.max(mag_sobel) mag_sobel = (mag_sobel * 255 / factor).astype(np.uint8) img_binary = np.zeros_like(img_gray) img_binary[(mag_sobel >= mag_thresh[0]) & (mag_sobel <= mag_thresh[1])] = 1 return img_binary # Define a function that applies Sobel x and y, # then computes the direction of the gradient def dir_thresh(img_gray, sobel_kernel=3, dir_thresh=(0, np.pi / 2)): xsobel = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) ysobel = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) dir_sobel = np.arctan2(np.absolute(ysobel), np.absolute(xsobel)) img_binary = np.zeros_like(img_gray) img_binary[(dir_sobel >= dir_thresh[0]) & (dir_sobel <= dir_thresh[1])] = 1 return img_binary # Define a function that thresholds the channel of HLS # Use exclusive lower bound (>) and inclusive upper (<=) def hls_channel(img_origin, channel='h', thresh=(0, 255)): hls = cv2.cvtColor(img_origin, cv2.COLOR_RGB2HLS) if 'h' == channel: img_channel = hls[:, :, 0] elif 'l' == channel: img_channel = hls[:, :, 1] elif 's' == channel: img_channel = hls[:, :, 2] else: print('illegal image channel!') return # Threshold color channel img_binary = np.zeros_like(img_channel) img_binary[(img_channel > thresh[0]) & (img_channel <= thresh[1])] = 1 return img_channel, img_binary def combinations(img): img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) xsobel_binary = abs_sobel_thresh(img_gray, 'x', 3, (40, 100)) ysobel_binary = abs_sobel_thresh(img_gray, 'y', 3, (20, 120)) mag_binary = mag_thresh(img_gray, 3, (30, 100)) dir_binary = dir_thresh(img_gray, 15, (0.7, 1.3)) l_channel, l_binary = hls_channel(img, 'l', (200, 255)) s_channel, s_binary = hls_channel(img, 's', (90, 255)) combined_binary = np.zeros_like(img_gray) combined_binary[(xsobel_binary == 1) | (l_binary == 1) | (s_binary == 1)] = 255 # Save the binary image cv2.imwrite('output_images/image_binary.jpg', combined_binary) # Display images f, ax = plt.subplots(5, 2, figsize=(6, 15)) f.tight_layout() ax[0, 0].imshow(img) ax[0, 0].set_title('Original Image', fontsize=12) ax[0, 1].imshow(combined_binary, cmap='gray') ax[0, 1].set_title('Combine Binary Image', fontsize=12) ax[1, 0].imshow(xsobel_binary, cmap='gray') ax[1, 0].set_title('X Gradient Binary Image', fontsize=12) ax[1, 1].imshow(ysobel_binary, cmap='gray') ax[1, 1].set_title('Y Gradient Binary Image', fontsize=12) ax[2, 0].imshow(mag_binary, cmap='gray') ax[2, 0].set_title('Magnitude Gradient Binary Image', fontsize=12) ax[2, 1].imshow(dir_binary, cmap='gray') ax[2, 1].set_title('Direction Gradient Binary Image', fontsize=12) ax[3, 0].imshow(l_channel, cmap='gray') ax[3, 0].set_title('L Channel', fontsize=12) ax[3, 1].imshow(l_binary, cmap='gray') ax[3, 1].set_title('L Binary Image', fontsize=12) ax[4, 0].imshow(s_channel, cmap='gray') ax[4, 0].set_title('S Channel', fontsize=12) ax[4, 1].imshow(s_binary, cmap='gray') ax[4, 1].set_title('S Binary Image', fontsize=12) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.) plt.show() image_undist = mpimg.imread('output_images/test1.jpg') combinations(image_undist)
list1 = ["b", "c"] dict1 = {"b":1, "c":2, "d":3} keys = list(dict1.keys()) # list1とdict1の一致要素 test1 = [l1 for l1 in list1 if l1 in keys] print(test1) test1plus = list(set(list1) & set(keys)) print(test1plus) # list1にあってdict1にない要素 test2 = [l1 for l1 in list1 if l1 not in keys] print(test2) test2plus = list(set(list1) - set(keys)) print(test2plus) # dict1にあってlist1にない要素 test3 = [d1 for d1 in keys if d1 not in list1] print(test3) test3plus = list(set(keys) - set(list1)) print(test3plus) for i in test3: # listが空だとfor以下の処理が実行されない。 if i: print(i) else: print("not exist")
# 台形法による数値積分 # 関数f(x) def f(x): return 3 * x ** 2 + 10 # 台形法 def trapezoidal(a, b, n): h = (b - a) / n # 微小区間 G = h / 2 * ((f(a) + f(b)) + 2 * sum(f(a + h * i) for i in range(1, n))) return G, h # 区間の設定 a = 1.0 b = 3.0 # 入力 n = int(input('定義域内の分割数(整数)を入力してください')) # 結果の出力 print('結果および微小区間hは', *trapezoidal(a, b, n)) print('分割数n', n)
#!/usr/bin/env python from ants import * from Graph import GraphNode from Graph import Graph, RectGrid import random import time # define a class with a do_turn method # the Ants.run method will parse and update bot input # it will also run the do_turn method for us class MyBot: def __init__(self): # define class level variables, will be remembered between turns self.orig_hive = None self.directions = ['n','e','s','w'] self.grid = None; self.water_nodes = set() self.priority = 'FOOD' self.explored = set(); self.turn = 0 ; # do_setup is run once at the start of the game # after the bot has received the game settings # the ants class is created and setup by the Ants.run method def do_setup(self, ants): # initialize data structures after learning the game settings #self.get_original_hive( ants ) self.grid = RectGrid(2,2)#ants.cols, ants.rows); grid = self.grid for hcol in range( grid.cols ): for vrow in range( grid.rows ): cell_index = hcol + vrow * grid.cols this_node = grid.get_node_from_indices( hcol, vrow ) #this_node.data = str(cell_index) + "("+str(hcol)+","+str(vrow)+")"; def get_original_hive( self, ants ): #pass if self.orig_hive == None: self.orig_hive = list(ants.my_hills())[0] print("updated hive to ", self.orig_hive ) def update_obstacles(): pass def get_food_ant_map( self, ants ): grid = self.grid #in this version the only thing we do is to search for food. #for each visible food, there must be one ant that is the closest to the food #we will try to attack every food item if we have enough ants but will prioritize the closer foods. #this code simple finds the closest foods and sort them by food index #food_list = [ ants.food() ] print("total foods ", len( ants.food())," total ants ", len(ants.my_ants())) food_ant_dict = {} food_index = -1; for food_loc in ants.food(): #this is a location food_index = food_index + 1 #food_ant_dict[ food_index ] = list() food_ant_dict[ food_loc ] = list() #####food_node = grid.get_node_from_indices( food_loc[1], food_loc[0] ) min_path_length = None #for this food ant_index = -1 for ant_loc in ants.my_ants(): #this is a location and_index = ant_index + 1 vrow = ant_loc[0] hcol = ant_loc[1] ######ant_node = grid.get_node_from_indices( hcol, vrow ) #slow way #path_ant_food = grid.first_search_path( ant_node, food_node, max_depth = 20, sort_function = None ) #path_length = len( path_ant_food ) #quick_way path_length = ants.distance(ant_loc, food_loc) #it may be the case that the food is not reachable within the search distance #it may also happen that more than one food has the same closest ant #more ants thant food, more food than ants if not min_path_length or min_path_length > path_length: min_path_length = path_length #closest_ant = ant_loc food_ant_dict[ food_loc ].append( min_path_length ) #print("This food: closest ant ", closest_ant," path length ", min_path_length ) food_ant_dict = sorted(food_ant_dict.items(), key=lambda pair: min(pair[1]) ) xx = { item[0]:item[1] for item in food_ant_dict} food_ant_dict = xx; #for each food, get its closest non-asigned ant asigned_ants = set() for food_loc in food_ant_dict: ant_list = food_ant_dict.get( food_loc ) #some other food took already some ants. aux = 0 for asigned in asigned_ants: ant_list[ asigned ] = 99999999 aux = aux + 1 if aux < len(ant_list) and min(ant_list) < 99999999: #from whatever is left, pick the closest ant. closest_ant_index = ant_list.index(min(ant_list)) asigned_ants.add( closest_ant_index ) food_ant_dict[ food_loc ] = [closest_ant_index] else: food_ant_dict[ food_loc ] = [] #print("food searching resulted in ", food_ant_dict ) food_ant_dict = { k:v[0] for k,v in food_ant_dict.items() if len(v)>0} #print("Returning ", food_ant_dict ) return food_ant_dict def walk_ant( self, ants, ant_loc, busy_locations): pass def get_available_walk_directions( self, ants, ant_loc, busy_locations, target_loc = None, try_avoid_loc = None ): available_locs = [] target_loc_dist = {} avoid_loc_dist = {} aux = ['s','n','w','e'] random.shuffle( aux ) for d in aux: new_loc = ants.destination(ant_loc, d) c1 = ants.passable(new_loc) c2 = ants.unoccupied(new_loc) c3 = True if new_loc not in busy_locations else False c4 = False if try_avoid_loc and new_loc == try_avoid_loc else True; if c1 and c2 and c3 and c4: available_locs.append( d ) if target_loc: dist = ants.distance( target_loc, new_loc ) target_loc_dist[ d ] = dist if target_loc: w = sorted( target_loc_dist.items(), key = lambda x: x[1]) available_locs =[ k[0] for k in w ] # The locations are now sorted based on the closeness to the target food. # Yet, lets do a second pass and eliminate those that would end up on top of locs to avoid return available_locs def send_food_seekers( self, ants, busy_ants, busy_locations ): #print("sending food collectors...."); food_loc_ant_dict = self.get_food_ant_map( ants ) #for each food, get its ant #then get a list of the ant's available cells to walk to #pick the closest to the food (if any ) #send the ant there, update busy_ants hive_loc = ants.my_hills()[0] if len( ants.my_hills() )>0 else (99999,99999) start = time.time() frozen_ants = 0 moving_ants = 0 ant_locs = ants.my_ants() for food_loc in food_loc_ant_dict: ant_index = food_loc_ant_dict.get( food_loc ); if ant_index not in busy_ants: #print("this one will be checked ") busy_ants.append( ant_index ) ant_loc = ant_locs[ ant_index ] #available dirs to move to #sorted by new location distance to closest food to this ant dirs = self.get_available_walk_directions(ants, ant_loc, busy_locations,target_loc = food_loc, try_avoid_loc = hive_loc ) if len(dirs)> 0: new_loc = ants.destination(ant_loc, dirs[0]) ants.issue_order( (ant_loc, dirs[0]) ) busy_locations.append( new_loc ) moving_ants = moving_ants + 1 print("food collector ant ", ant_index," is moving ", dirs[0], " to food ", food_loc ) else: #the ant will not move anywhere nobody should move and crash to it. busy_locations.append( ant_loc ) frozen_ants = frozen_ants + 1 food_loc_ant_dict = self.get_food_ant_map( ants ) return moving_ants, frozen_ants def send_killers( self, ants, busy_ants, busy_locations ): pass def send_explorers( self,ants, busy_ants, busy_locations ): #for each ant that is not busy #then get a list of the ant's available cells to walk to #pick if any the furthest from the hive that is not already explored and it is not water and nobody is going there. #print("sending explorers...."); hive_loc = ants.my_hills()[0] if len(ants.my_hills()) else (99999,99999) #move the ants that are not busy to non busy locations as far as possible from the hive. moving_ants = 0 frozen_ants = 0; ant_index = -1; for ant_loc in ants.my_ants(): ant_index = ant_index + 1 if ant_index not in busy_ants: dirs = self.get_available_walk_directions( ants, ant_loc, busy_locations, target_loc = None, try_avoid_loc = hive_loc ) #print("ant index is not busy ", ant_index, "getting its available directions, dirs = ", dirs ) # if len(dirs) > 0: distances = [0,0,0,0] scores = [0,0,0,0] explored = [0,0,0,0]; i = -1; for d in dirs: i = i + 1 new_loc = ants.destination(ant_loc, d) #distances[i] = 1.0 + ants.distance( ant_loc, hive_loc ) was_explored = self.is_explored( new_loc ) if was_explored == True: scores[i] = scores[i] -1 explored[i] = True else: scores[i] = scores[i] +1 explored[i] = False scores[i] = scores[i] + (-1 if new_loc==hive_loc else 1) #aux = max(distances) #print("aux=",aux) #distances = [ int( d/aux ) for d in distances ] #for i in range(len(distances)): # scores[i] = scores[i] + distances[i] #i = distances.index(max(distances)) #scores[i] = scores[i] + 1 winner_dir = dirs [ scores.index( max(scores) ) ] new_loc = ants.destination(ant_loc, winner_dir ) ants.issue_order( (ant_loc, winner_dir) ) busy_locations.append( new_loc ) moving_ants = moving_ants + 1 busy_ants.append( ant_index ) print("explorer ant ", ant_index, "loc", ant_loc, " is moving ", winner_dir, " scores ", scores, "dirs = ",dirs , "explored", explored) else: frozen_ants = frozen_ants + 1 def is_explored( self,loc): return True if loc in self.explored else False def update_explored( self, ants ): for loc in ants.my_ants(): self.explored.add( loc ) def xxdo_turn(self, ants): print("-------------------------TURN ", self.turn , "--ants",len(ants.my_ants()),"-----------------------") def do_turn(self, ants): self.turn = self.turn + 1 print("-------------------------TURN ", self.turn , "--ants",len(ants.my_ants()),"-----------------------") self.update_explored( ants ) #first thing we will do it to try to get something from the environment. #check all the positions that each ant can move to and flag unknown obstacles. #this affects tremendously the search for food busy_ants = [] busy_locations = [] #in this version the only thing we do is to search for food but we prioritize the closer foods. #this code returns the food index sorted by closeness to any ant, and the ant it is closer to it. #will look like { 0: 3, 1: 11, 3: 4 ...} where key is food index and value is ant index if self.priority == 'FOOD': #self.send_food_seekers( ants, busy_ants, busy_locations ) free_ants = len(ants.my_ants()) - len(busy_ants) if free_ants: self.send_explorers( ants, busy_ants, busy_locations ) #free_ants = len(ants.my_ants()) - len(busy_ants) #if free_ants: # self.send_killers( ants, busy_ants, busy_locations ) elif self.priority == 'KILL': self.send_killers( ants, busy_ants, busy_locations ) self.send_explorers( ants, busy_ants, busy_locations ) self.send_food_seekers( ants, busy_ants, busy_locations ) else: self.send_explorers( ants, busy_ants, busy_locations ) #food_ant_dict = self.get_food_ant_map( ants ) #print("food_ant_dict = ", food_ant_dict) #priority: 1-food 2-unseen 3-away from hive. All under the condition that loc is not selected #all the ants asigned for food, go for the food if possible, the rest do a random walk. #if in the search for food, an ant cant for any reason, then random walk. #direction = 'n' #for loc in ants.my_ants(): # ants.issue_order((loc, direction)) #orders[new_loc] = loc # do turn is run once per turn # the ants class has the game state and is updated by the Ants.run method # it also has several helper methods to use def do_turn_old(self, ants): #print("grid rows = ", self.grid.rows, " grid cols ", self.grid.cols ) #self.directions = ['n','s','e','w'] dirs = list( self.directions ) orders = {} def check_move_direction(loc, direction ): new_loc = ants.destination(loc, direction) if (ants.unoccupied(new_loc) and new_loc not in orders): return True, new_loc return False, new_loc #for food_loc in ants.food(): # print("food location ", food_loc ) #print("\n\nthis is my bot\n\n", ants.ant_list ); # loop through all my ants and try to give them orders # the ant_loc is an ant location tuple in (row, col) form for loc in ants.my_ants(): #print("and loc ", loc ) # try all directions in random order (uninformed) random.shuffle(dirs) found_dir = False; for direction in dirs: valid, new_loc = check_move_direction(loc, direction) if valid: ants.issue_order((loc, direction)) orders[new_loc] = loc found_dir = True #print("new loc ", new_loc ) break; #print("and found diretion ", direction ); # the destination method will wrap around the map properly # and give us a new (row, col) tuple ##new_loc = ants.destination(ant_loc, direction) # passable returns true if the location is land ##if (ants.passable(new_loc)): ## # an order is the location of a current ant and a direction ## ants.issue_order((ant_loc, direction)) ## # stop now, don't give 1 ant multiple orders ## break # check if we still have time left to calculate more orders if ants.time_remaining() < 10: break if __name__ == '__main__': # psyco will speed up python a little, but is not needed try: import psyco psyco.full() except ImportError: pass try: # if run is passed a class with a do_turn method, it will do the work # this is not needed, in which case you will need to write your own # parsing function and your own game state class Ants.run(MyBot()) except KeyboardInterrupt: print('ctrl-c, leaving ...')
#!/usr/local/bin/python # -*- coding: UTF-8 -*- import random, string, time import names, place_name_generator def make_ghost(place=None, current_year=None): #set up some basic stuff first of all... if place == None: #make something up... place = place_name_generator.make_name() place = "%s %s" % (place, random.choice(("Castle", "House", "Manor", "Cathedral", "Palace", "Castle", "House", "Manor", "Cathedral", "Palace", "Abbey", "Abbey", "Rectory", "Tavern", "Tower", "Chapel"))) if current_year == None: current_year = int(time.localtime()[0]) else: current_year = int(current_year) report_year = current_year - random.choice(range(3,15)) past_year= random.choice(range(1500,1920)) if place[0] != string.upper(place[0]): place = "%s%s" % (string.upper(place[0]), place[1:]) #"The 18th-century St Marks' church" -> "St Marks' church" if string.find(string.lower(place), "church") > -1: place = string.strip(place[string.find(place, " S")+1:]) #'the Jarman Museum of Art (with its internationally known Conceptual Art collection)' -> 'the Jarman Museum of Art' elif string.find(string.lower(place), "museum") > -1: if string.find(string.lower(place), "(") > -1: place = string.strip(place[:string.find(place, "(")-1]) #OK, now get to the ghosty stuff... randmonth = random.choice(("January","February","March","April", "May","June","July","August", "September","October","November","December")) if randmonth == "February": randday = random.choice(range(1,28)) elif randmonth in ["April","June","September","November"]: randday = random.choice(range(1,30)) else: randday = random.choice(range(1,31)) random_day_of_year = "%s %s" % (randday, randmonth) ghost_gender = random.choice(("female", "female", "female", "male")) namestyle = random.choice(("Spanish", "Italian", "French")) if ghost_gender == "female": ghost_pronoun = random.choice(("She", "She", "It", "This")) persons_name = names.getFemaleName(Style=namestyle, UseLongName=0) persons_name2 = names.getFemaleFirstName() person_pronoun = "her" person_pronoun2 = "herself" person_pronoun3 = "she" else: ghost_pronoun = random.choice(("He", "He", "It", "This")) persons_name = names.getMaleName(Style=namestyle, UseLongName=0) persons_name2 = names.getMaleFirstName() person_pronoun = "his" person_pronoun2 = "himself" person_pronoun3 = "he" persons_first_name = string.split(persons_name)[0] phrase1 = random.choice(("is haunted by", "is said to be haunted by", "is rumoured to be haunted by", "is reputedly haunted by", "is reportedly haunted by", "is believed to be haunted by", "is allegedly haunted by")) female_ghost_name= random.choice(("The Brown Lady", "The Grey Lady", "The White Lady", "The Blue Lady", "The Red Lady", "The Green Lady", "the Brown Lady", "the Grey Lady", "the White Lady", "the Blue Lady", "the Red Lady", "the Green Lady", "the Lady in Red", "the Lady in Brown", "the Lady in Grey", "the Lady in White", "the Lady in Blue", "the Lady in Green", "The Headless Nun", "The Screaming Nun", "The Ghost Nun", "The Ghostly Nun", "Bloody %s" % persons_first_name, "Bloody %s" % persons_name2, "Bloody %s" % persons_name2, "Headless %s" % persons_first_name, "Headless %s" % persons_name2, )) male_ghost_name = random.choice(("The Ghostly Drummer", "The Ghostly Piper", "The Man in Brown", "The Man in Grey", "The Man in White", "The Man in Blue", "The Man in Red", "The Man in Green", "Bloody %s" % persons_first_name, "Bloody %s" % persons_name2, "Bloody %s" % persons_name2, "Headless %s" % persons_first_name, "Headless %s" % persons_name2, "The Headless Monk", "The Screaming Monk", "The Ghost Monk", "The Ghostly Monk", )) if ghost_gender == "female": ghost_name = female_ghost_name else: ghost_name = male_ghost_name clothing_colour = None if string.find(ghost_name, "Brown") > -1: clothing_colour = "brown" elif string.find(ghost_name, "Grey") > -1: clothing_colour = "grey" elif string.find(ghost_name, "White") > -1: clothing_colour = "white" elif string.find(ghost_name, "Blue") > -1: clothing_colour = "blue" elif string.find(ghost_name, "Red") > -1: clothing_colour = "red" elif string.find(ghost_name, "Green") > -1: clothing_colour = "green" else: clothing_colour = " " people = random.choice(("Visitors and staff", "Visitors", "Staff", "Visitors and staff members", "Staff members", "Witnesses", "Residents")) people2 = random.choice(("Visitors and staff", "Visitors", "Staff", "Visitors and staff members", "Staff members", "Witnesses", "Residents", "People")) signs = random.choice(("have heard apparitional piano music", "have heard ghostly piano music", "have heard voices and whispers in the empty %s" % (random.choice(("hall", "rooms", "building"))), "have heard voices in the empty %s" % (random.choice(("hall", "rooms", "building"))), "have heard whispers in the empty %s" % (random.choice(("hall", "rooms", "building"))), "have reported hearing the sound of children laughing and singing, only to find that there were no children present", "have been plagued by strange noises and unexplained occurrences", "have been plagued by unexplained occurrences and strange noises", "have been plagued by strange noises", "have been plagued by unexplained occurrences", "have felt strong presences and seen strange lights", "have seen strange lights and felt strong presences", "have reported strange lights and strong presences", "have seen floating lights and strange apparitions", "have also reported seeing the ghost of a small, sad girl", "have also reported the sound of a mysterious harp playing", )) addenda = "There is also %s%s and %s associated with this place." % (random.choice(("an indelible bloody stain, ", "a bloody stain which could not be removed, ", "a poltergeist, ", "extreme poltergiest activity, ", "a terrifying presence, ", "a ghostly soldier, ")), random.choice(("two apparitions", "three apparitions", "four apparitions", "five apparitions", "two ghosts", "three ghosts", "four ghosts", "five ghosts", "the ghosts of two teen girls", "the ghosts of three teen girls", "the ghosts of four teen girls", "the ghosts of five teen girls", "the ghosts of two young women", "the ghosts of three young women", "the ghosts of four young women", "the ghosts of five young women", "the ghosts of two young girls", "the ghosts of three young girls", "the ghosts of four young girls", "the ghosts of five young girls", "the ghosts of two children", "the ghosts of three children", "the ghosts of four children", "the ghosts of five children", "other apparitional figures", )), random.choice(("a curse", "two curses", "three curses", "four curses", "five curses", "many reported paranormal occurrences", "many paranormal occurrences", "floating lights", "the ghostly cry of a wailing baby")) ) addenda2 = random.choice(("Guard dogs bark into empty room where %s walks." % person_pronoun3, "Dogs are particularly troubled by some kind of sinister presence.", "Dogs seem particularly troubled by some kind of sinister presence.", "Dogs seem particularly troubled by some kind of sinister presence at this site.", "%s report strange experiences and inexplicable events." % people2, "%s report sinister sensations and inexplicable events." % people2, "%s have reported hearing voices and loud footsteps late at night in areas they know to be empty." % people2, "%s have also reported the figure of a spectral %s gazing from a window." % (people2, random.choice(("woman", "man"))), "In %s, %s named %s as as one of the top %s most haunted places in the %s." % (report_year, random.choice(("The Guardian", "The Times", "The Daily Mail", "The Daily Telegraph", "the BBC")), place, random.choice(("five","ten","twenty","five","ten","twenty","fifty","hundred")), random.choice(("United Kingdom", "UK", "country")) ), #"According to at least one source, " '%s describe "a most dreadful expression of distress" on %s face.' % (people2, person_pronoun), '%s describe "an appalling expression of grief" on %s face.' % (people2, person_pronoun), )) last_bit = random.choice(("%s %s. " % (people,signs), addenda, addenda2, "%s %s. %s. %s" % (people,signs, addenda, addenda2), "%s. %s." % (addenda, addenda2), "%s %s. %s" % (people,signs, addenda), "%s %s %s. " % (addenda, people,signs), "%s %s. %s" % (people,signs, addenda2), "%s %s %s. " % (addenda2, people,signs), "", )) #combine this with stuff above...but later... if ghost_gender == "female": # appears as an elderly woman # a young woman # a high school age girl # a school age girl # a school age girl # a young girl if clothing_colour in [None, "", " "]: wearing = random.choice(("She appears in a long gown.", "Her ghost appears in a long gown.", "Her ghost is seen wearing a long rustling gown.", "Her ghost is seen wearing a long rustling ball gown.", "Her ghost is seen wearing a long rustling ball gown and a tall head of black hair.", "Her ghost is seen wearing a long rustling ball gown and a tall head of blonde hair.", "Her ghost is seen wearing a long rustling ball gown and a tall head of red hair.", "She is seen wearing a long rustling gown.", "She is seen wearing a long rustling ball gown.", "She is seen wearing a long rustling ball gown and a tall head of black hair.", "She is seen wearing a long rustling ball gown and a tall head of blonde hair.", "She is seen wearing a long rustling ball gown and a tall head of red hair.")) else: wearing = random.choice(("She appears in a long %s gown." % clothing_colour, "Her ghost appears in a long %s gown." % clothing_colour, "Her ghost is seen wearing a long rustling %s gown." % clothing_colour, "Her ghost is seen wearing a long rustling %s ball gown." % clothing_colour, "Her ghost is seen wearing a long rustling %s ball gown and a tall head of black hair." % clothing_colour, "Her ghost is seen wearing a long rustling %s ball gown and a tall head of blonde hair." % clothing_colour, "Her ghost is seen wearing a long rustling %s ball gown and a tall head of red hair." % clothing_colour, "She is seen wearing a long rustling %s gown." % clothing_colour, "She is seen wearing a long rustling %s ball gown." % clothing_colour, "She is seen wearing a long rustling %s ball gown and a tall head of black hair." % clothing_colour, "She is seen wearing a long rustling %s ball gown and a tall head of blonde hair." % clothing_colour, "She is seen wearing a long rustling %s ball gown and a tall head of red hair." % clothing_colour, "%s report a woman dressed in %s who disappears without trace." % (people2, clothing_colour) )) elif ghost_gender == "male": if clothing_colour in [None, "", " "]: wearing = random.choice(("He appears as a man in a long coat who appears accompanied by a chill in the air.", "He appears as a man in a long coat who appears accompanied by an overwhelming smell of lavender.", "His ghost appears as a man in a long coat who appears accompanied by an overwhelming smell of lavender.", "He appears as a tall, dark stranger.", "He appears as a tall slender figure dressed in a long cape.", "His ghost appears as a man in a long coat who appears accompanied by a chill in the air.", "His ghost appears as a man in a long coat who appears accompanied by an overwhelming smell of lavender.", "His ghost appears as a tall, dark stranger.", "His ghost appears as a tall slender figure dressed in a long cape." "He is said to appear in great pain, wearing trousers and a shirt.", "His ghost is said to appear in great pain, wearing trousers and a shirt.", "He is said to appear in great pain.", "His ghost is said to appear in great pain.", "He is said to appear to be in great pain.", "His ghost is said to appear to be in great pain.", )) else: wearing = random.choice(("He appears as man in a %s coat who appears accompanied by a chill in the air." % clothing_colour, "He appears as man in a %s coat who appears accompanied by an overwhelming smell of lavender." % clothing_colour, "He appears as a tall, dark stranger dressed in %s." % clothing_colour, "He appears as a tall slender figure dressed in %s with a long %s cape." % (clothing_colour, clothing_colour), "His ghost appears as man in a %s coat who appears accompanied by a chill in the air." % clothing_colour, "His ghost appears as man in a %s coat who appears accompanied by an overwhelming smell of lavender." % clothing_colour, "His ghost appears as a tall, dark stranger dressed in %s." % clothing_colour, "His ghost appears as a tall slender figure dressed in %s with a long %s cape." % (clothing_colour, clothing_colour), "He is said to appear in great pain, wearing %s trousers and a shirt." % clothing_colour, "His ghost is said to appear in great pain, wearing %s trousers and a shirt." % clothing_colour, "%s report a man dressed in %s who disappears without trace." % (people2, clothing_colour), )) grisly_fate1 = random.choice(("was killed by", "was murdered by", "was killed in unexplained circumstances, allegedly by", "was brutally murdered by", "was murdered while %s slept by" % person_pronoun3, "was murdered in %s sleep by" % person_pronoun, "was strangled by", "was strangled while %s slept by" % person_pronoun3, "was strangled in %s sleep by" % person_pronoun, "was poisoned by", "was killed on the orders of", "was imprisoned and murdered by", "suffered a grisly fate at the hands of")) if ghost_gender == "female": grisly_fate1 = "%s %s" % (grisly_fate1, random.choice(("her mother", "her father", "her husband", "her lover", "a jealous lover", "a spurned lover", "a servant girl", "a maid", "a servant", "her uncle", "her stepmother", "her stepfather")) ) elif ghost_gender == "male": grisly_fate1 = "%s %s" % (grisly_fate1, random.choice(("his mother", "his father", "his wife", "his lover", "a jealous lover", "a spurned lover", "a servant girl", "a maid", "a servant", "his uncle", "her stepmother", "her stepfather")) ) grisly_fate2 = random.choice(("tragically died in a fire", "died in a fire", "died in a suspicous fire", "drowned %s" % person_pronoun2, "killed %s" % person_pronoun2, "was killed in a tragic accident", "was killed in an accident", "was killed in a horrifying accident", "was killed in a terrible accident", "was decapitated in a tragic accident", "was decapitated in a horrifying accident", "was decapitated in a terrible accident", "was murdered", "was brutally murdered", "committed suicide", "flung %s, or fell, from the roof" % person_pronoun2, "flung %s from the roof" % person_pronoun2, "fell from the roof and died", "drowned %s in the nearby river after the murder of %s lover" % (person_pronoun2, person_pronoun), "flung %s from the roof after the murder of %s lover" % (person_pronoun2, person_pronoun), "committed suicide after the murder of %s lover" % (person_pronoun), "was killed on Christmas Day", "was murdered on Christmas Day", "was brutally murdered on Christmas Day", "was the victim of a brutal crime of passion", "went mad after being rejected by %s fiancee" % person_pronoun, "went mad and killed %s after being rejected by %s fiancee" % (person_pronoun2, person_pronoun), "drowned %s in the nearby river after being abused by %s uncle" % (person_pronoun2, person_pronoun), "flung %s from the roof after being abused by %s uncle" % (person_pronoun2, person_pronoun), "committed suicide after being abused by %s uncle" % (person_pronoun), "died suddenly (in suspicious circumstances)", "died in suspicious circumstances", "starved to death", "was walled up alive", )) randnum = random.choice((0,1)) if randnum == 0: grisly_fate = grisly_fate1 else: grisly_fate = grisly_fate2 if string.find(grisly_fate, "Christmas") > -1: random_day_of_year = "Christmas Day" bit2 = random.choice(("It is thought that", "It is rumoured that", "Researchers claim that", "Paranormal researchers claim that", "Researchers say that", "Paranormal researchers say that", "Researchers think that", "Paranormal researchers think that", "Locals claim that", "Locals say that", "Locals think that", "One theory is that", "It is possible that", "Believers say that", "Believers claim that", "Believers think that", "A story is told that", "According to the legends,", "According to legend,", )) bit3 = "%s is the %s of %s, who %s in %s" % (string.lower(ghost_pronoun), random.choice(("restless spirit", "spirit", "shade", "ghost", "tormented soul")), persons_name, grisly_fate, past_year ) bit4 = "The %s%s" % (random.choice(("terrifying ", "ghostly ", "frightening ", "", "")), random.choice(("apparation", "figure", "spectre"))) bit4 = "%s%s " % (bit4, random.choice((", which has been captured on CCTV,", ", which sometimes appears as a %smist," % ("%s " % clothing_colour), "" ))) bit5 = random.choice(("is said to wander the %s on stormy nights" % random.choice(("building", "site", "premises")), "is reputed to wander the %s on stormy nights" % random.choice(("building", "site", "premises")), "wanders the %s on stormy nights" % random.choice(("building", "site", "premises")), "is said to visit at midnight on All Hallows Eve", "is said to visit the %s at midnight on All Hallows Eve" % random.choice(("building", "site", "premises")), "visits at midnight on All Hallows Eve", "visits the %s at midnight on All Hallows Eve" % random.choice(("building", "site", "premises")), "wanders the %s at midnight on All Hallows Eve" % random.choice(("building", "site", "premises")), "is said to be seen only at midnight", "is seen only at midnight", "is said to be seen only at midnight on All Hallows Eve", "is seen only at midnight on All Hallows Eve", "is said to be seen only at midnight on the anniversary of %s death" % person_pronoun, "is seen only at midnight on the anniversary of %s death" % person_pronoun, "is said to be seen only on the anniversary of %s death" % person_pronoun, "is seen only on the anniversary of %s death" % person_pronoun, "is said to be seen only at midnight on the anniversary of %s death (%s)" % (person_pronoun, random_day_of_year), "is seen only at midnight on the anniversary of %s death (%s)" % (person_pronoun, random_day_of_year), "is said to be seen only on the anniversary of %s death (%s)" % (person_pronoun, random_day_of_year), "is seen only on the anniversary of %s death (%s)" % (person_pronoun, random_day_of_year), "is said to be seen only at midnight on %s birthday (%s)" % (person_pronoun, random_day_of_year), "is seen only at midnight on %s birthday (%s)" % (person_pronoun, random_day_of_year), "is said to be seen only on %s birthday (%s)" % (person_pronoun, random_day_of_year), "is seen only on %s birthday (%s)" % (person_pronoun, random_day_of_year), "is said to be seen only at midnight on %s birthday" % (person_pronoun), "is seen only at midnight on %s birthday" % (person_pronoun), "is said to be seen only on %s birthday" % (person_pronoun), "is seen only on %s birthday" % (person_pronoun), "is frequently spotted late at night", "is frequently seen late at night", "is only seen after the sun goes down", "is only ever seen after the sun goes down", "is only observed after the sun goes down", "has only been observed after the sun goes down", "has only even been seen after the sun goes down", "is only seen after dusk", "is only ever seen after dusk", "is only observed after dusk", "has only been observed after dusk", "has only ever been seen after dusk", "is often seen during the daytime", "is, unusually, seen mainly during the daytime", "is seen mainly during the daytime", "seems to be able to be seen at any time of day or night", "seems, unusually, to be able to be seen at any time of day or night", )) bit4_and_5 = "%s%s." % (bit4, bit5) bit4_and_5 = random.choice((bit4_and_5, "%s %s" % (bit4_and_5, wearing), "%s %s " % (wearing, bit4_and_5) )) try: ghost_description = "%s %s %s" % (place, phrase1, ghost_name) ghost_description = "%s. %s %s" % (ghost_description, bit2, bit3) ghost_description = "%s. %s " % (ghost_description, bit4_and_5) ghost_description = "%s%s " % (ghost_description, last_bit) except: try: ghost_description = "%s %s %s" % (place.decode("UTF-8", "ignore"), phrase1.decode("UTF-8", "ignore"), ghost_name.decode("UTF-8", "ignore")) ghost_description = "%s. %s %s" % (ghost_description, bit2.decode("UTF-8", "ignore"), bit3.decode("UTF-8", "ignore")) ghost_description = "%s. %s " % (ghost_description, bit4_and_5.decode("UTF-8", "ignore")) ghost_description = "%s%s " % (ghost_description, last_bit.decode("UTF-8", "ignore")) except: ghost_description = "%s %s %s" % (place.encode("UTF-8", "ignore"), phrase1.encode("UTF-8", "ignore"), ghost_name.encode("UTF-8", "ignore")) ghost_description = "%s. %s %s" % (ghost_description, bit2.encode("UTF-8", "ignore"), bit3.encode("UTF-8", "ignore")) ghost_description = "%s. %s " % (ghost_description, bit4_and_5.encode("UTF-8", "ignore")) ghost_description = "%s%s " % (ghost_description, last_bit.encode("UTF-8", "ignore")) #Easier to fix these here than to track down the original errors. # Yeah, call me lazy. :) while string.find(ghost_description, " ") > -1: ghost_description = string.replace(ghost_description, " ", " ") while string.find(ghost_description, ".. ") > -1: ghost_description = string.replace(ghost_description, ".. ", ". ") return ghost_description if __name__ == "__main__": for f in range(0,5): ghosty_stuff = make_ghost() print ghosty_stuff print print
''' Blockchain A Blockchain is a sequential chain of records, similar to a linked list. Each block contains some information and how it is connected related to the other blocks in the chain. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data. For our blockchain we will be using a SHA-256 hash, the Greenwich Mean Time when the block was created, and text strings as the data. Use your knowledge of linked lists and hashing to create a blockchain implementation. We can break the blockchain down into three main parts. First is the information hash: import hashlib def calc_hash(self): sha = hashlib.sha256() hash_str = "We are going to encode this string of data!".encode('utf-8') sha.update(hash_str) return sha.hexdigest() We do this for the information we want to store in the block chain such as transaction time, data, and information like the previous chain. The next main component is the block on the blockchain: ''' import hashlib import datetime class Block: def __init__(self, timestamp, data, previous_hash): self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.calc_hash(data) self.next = None def calc_hash(self, o_str): sha = hashlib.sha256() hash_str = o_str.encode('utf-8') sha.update(hash_str) return sha.hexdigest() def __repr__(self): return str(self.timestamp) + str(' | ') \ + str(self.data) + str(' | ') + str(self.previous_hash) \ + str(' | ') + str(self.hash) class BlockChain(object): def __init__(self): self.head = None self.tail = None def append(self, data): if data is None or data == '': return elif self.head is None: self.head = Block(datetime.datetime.utcnow(), data, 0) self.tail = self.head else: self.tail.next = Block(datetime.datetime.utcnow(), data, self.tail.hash) return def to_List(self): out = [] block = self.head while block: out.append([block]) block = block.next return out # Test case for Blocks for BlockChain1 b1 = Block(datetime.datetime.utcnow(), 'First block b1', 0) b2 = Block(datetime.datetime.utcnow(), 'Second block b2', b1) b3 = Block(datetime.datetime.utcnow(), 'Third block b3', b2) # Test case for BlockChain1 block_chain1 = BlockChain() block_chain1.append('First block chain bc1') block_chain1.append('Second block chain bc2') block_chain1.append('Third block chain bc3') # Tests print('The b1 data: ', b1.data) print('The b1 hash value: ', b1.hash) print('The b1 timestamp: ', b1.timestamp) print('The previous block data of b2: ', b2.previous_hash.data) print('The block_chain tail data: ', block_chain1.tail.data) print('The block_chain previous hash data: ', block_chain1.tail.previous_hash) # Test case for Blocks for BlockChain2 b1 = Block(datetime.datetime.utcnow(), 'b1 is first', 0) b2 = Block(datetime.datetime.utcnow(), 'b2 is second', b1) b3 = Block(datetime.datetime.utcnow(), 'b3 is third', b2) # Test case for BlockChain2 block_chain2 = BlockChain() block_chain2.append('bc1 is the 1st block chain') block_chain2.append('bc2 is the 2nd block chain') block_chain2.append('bc3 is the 3rd block chain') # Tests print('The b1 data: ', b1.data) print('The b1 hash value: ', b1.hash) print('The b1 timestamp: ', b1.timestamp) print('The previous block data of b2: ', b2.previous_hash.data) print('The block_chain tail data: ', block_chain2.tail.data) print('The block_chain previous hash data: ', block_chain2.tail.previous_hash) # Test case for Blocks for BlockChain3 b1 = Block(datetime.datetime.utcnow(), '1st block b1', 0) b2 = Block(datetime.datetime.utcnow(), '2nd block b2', b1) b3 = Block(datetime.datetime.utcnow(), '3rd block b3', b2) # Test case for BlockChain3 block_chain3 = BlockChain() block_chain3.append('now is the 1st bc1') block_chain3.append('now is the 2nd bc2') block_chain3.append('now is the 3rd bc3') # Tests print('The b1 data: ', b1.data) print('The b1 hash value: ', b1.hash) print('The b1 timestamp: ', b1.timestamp) print('The previous block data of b2: ', b2.previous_hash.data) print('The block_chain tail data: ', block_chain3.tail.data) print('The block_chain previous hash data: ', block_chain3.tail.previous_hash) # Test case for the edge case that BlockChain length should be 0 # Didn't build blockchain. # Test case for BlockChain3 block_chain4 = BlockChain() block_chain4.append(None) block_chain4.append(None) block_chain4.append(None) # Tests if block_chain3 == None: print('The b1 data: ', b1.data) print('The b1 hash value: ', b1.hash) print('The b1 timestamp: ', b1.timestamp) print('The previous block data of b2: ', b2.previous_hash.data) print('The block_chain tail data: ', block_chain4.tail.data) print('The block_chain previous hash data: ', block_chain4.tail.previous_hash) ''' Above is an example of attributes you could find in a Block class. Finally you need to link all of this together in a block chain, which you will be doing by implementing it in a linked list. All of this will help you build up to a simple but full blockchain implementation! '''
# Задание-1: # Реализуйте описаную ниже задачу, используя парадигмы ООП: # В школе есть Классы(5А, 7Б и т.д.), в которых учатся Ученики. У каждого ученика есть два Родителя(мама и папа). # Также в школе преподают Учителя, один учитель может преподавать в неограниченном кол-ве классов # свой определенный предмет. Т.е. Учитель Иванов может преподавать математику у 5А и 6Б, но больше математику не # может преподавать никто другой. # Выбранная и заполненная данными структура должна решать следующие задачи: # 1. Получить полный список всех классов школы # 2. Получить список всех учеников в указанном классе(каждый ученик отображается в формате "Фамилия И.О.") # 3. Получить список всех предметов указанного ученика (Ученик --> Класс --> Учителя --> Предметы) # 4. Узнать ФИО родителей указанного ученика # 5. Получить список всех Учителей, преподающих в указанном классе class Person: def __init__(self, name, surname, patronymic): self.name = name self.surname = surname self.patronymic = patronymic # self.age = age # self.classroom = classroom def get_full_name(self): return self.name + ' ' + self.patronymic + ' ' + self.surname def get_short_name(self): return f"{self.surname.title()}, {self.name[0].upper()}, {self.patronymic[0].upper()}" if __name__ == '__main__': # Тестирование. people1 = Person('Иван', 'Иванович', 'Иванов') print(people1.get_full_name()) print(people1.get_short_name()) class Student(Person): def __init__(self, name, patronymic, surname, mother, father, school_class): super().__init__(name, surname, patronymic) self.name = name self.surname = surname self.patronymic = patronymic self.mother = mother self.father = father self.school_class = school_class # def all_classes(self): # pass # # # if __name__ == '__main__': # Тестирование. # st_1 = Student('Семен', 'Семенович', 'Семенов', 'Анна Михайлова', 'Алексанр Семенов', '7а') # st_2 = Student('Сергей', 'Сергеевич', 'Сергеев', 'Ольга Сергеева', 'Андрей Сергеев', '7б') # st_3 = Student('Олег', 'Олегович', 'Петров', 'Юлия Петрова', 'Олег Петров', '7а') # print(Student.all_classes(st_1)) class Teacher(Person): def __init__(self, name, patronymic, surname, subject): Person.__init__(self, name, patronymic, surname) self.subject = subject class ClassRooms: def __init__(self, class_room, teachers): self.class_room = class_room self.teachersdict = {t.subject: t for t in teachers} if __name__ == '__main__': # Тестирование. teachers = [Teacher('Иван', 'Иванович', 'Иванов', 'Математика'), Teacher('Петр', 'Петрович', 'Петров', 'Литература'), Teacher('Сидор', 'Сидорович', 'Сидоров', 'Физика'), Teacher('Дмитрий', 'Дмитриевич', 'Дмитриев', 'История'), Teacher('Никита', 'Никитиевич', 'Никишин', 'Биология')] classes = [ClassRooms('11 А', [teachers[0], teachers[1], teachers[2]]), ClassRooms('11 Б', [teachers[1], teachers[3], teachers[4]]), ClassRooms('10 А', [teachers[3], teachers[1], teachers[0]])] parents = [Person('Семен', 'Семенович', 'Семенов'), Person('Светлана', 'Савельевна', 'Семенова'), Person('Роман', 'Романович', 'Романов'), Person('Римма', 'Романовна', 'Романова'), Person('Сергей', 'Сергеевич', 'Сергеев'), Person('Юлия', 'Викторвна', 'Сергеева')] students = [Student('Игорь', 'Cеменович', 'Семенов', parents[0], parents[1], classes[0]), Student('Ольга', 'Романова', 'Романова', parents[2], parents[3], classes[1]), Student('Александр', 'Сергеевич', 'Сергеев', parents[4], parents[5], classes[2])] print('Список классов в школе: ') for f in classes: print(f.class_room) for f in classes: print('Учителя, преподающие в {} классе:'.format(f.class_room)) for teacher in classes[0].teachersdict.values(): print(teacher.get_full_name()) for f in classes: print("Ученики в классе {}:".format(f.class_room)) for st in students: print(st.get_short_name()) for f in students: print('Список предметов ученика {}'.format(f.school_class)) for teacher in classes[0].teachersdict.values(): print(teacher.get_full_name())
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() newList = ["яблоко", "банан", "киви", "арбуз"] i = 0 while len(newList) > i: print(i + 1, newList[i]) i += 1 newList = ["яблоко", "банан", "киви", "арбуз"] print('1.', newList[0]) print('2.', newList[1]) print('3.', newList[2]) print('4.', newList[3]) newList = ["яблоко", "банан", "киви", "арбуз"] listLength = len(newList) for i in range(listLength): print(str(i + 1) + '. ' + '{}'.format(newList[i])) # Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. spisok_1 = {1, 33, 45, "привет", 15.4, "мир"} spisok_2 = {45, "мир", "осталось", 12, 33, 1} spisok_3 = spisok_2 - spisok_1 print(list(spisok_3)) # Задача-3: # Дан произвольный список из целых чисел. # Получите НОВЫЙ список из элементов исходного, выполнив следующие условия: # если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два. lessonList = [1, 22, 13, 14, 95, 11, 78, 15, 64] newList = [] lessonVar = len(lessonList) for i in range(lessonVar): if lessonList[i] % 2 == 0: newList.append(lessonList[i] / 4) else: newList.append(lessonList[i] * 2) print(newList)
import pandas as pd import matplotlib.pylab as plt import numpy as np # Read data from csv pga = pd.read_csv("pga.csv") # Normalize the data 归一化值 (x - mean) / (std) pga.distance = np.linspace(300, 0, 197) + np.random.random(197)*50 pga.accuracy = np.linspace(100, 200, 197) + np.random.random(197)*50 pga.distance = (pga.distance - pga.distance.mean()) / pga.distance.std() pga.accuracy = (pga.accuracy - pga.accuracy.mean()) / pga.accuracy.std() print(pga.head()) plt.scatter(pga.distance, pga.accuracy) plt.xlabel('normalized distance') plt.ylabel('normalized accuracy') plt.show() # ### accuracy = $\theta_1$ $distance_i$ + $\theta_0$ + $\alpha$ # - $\theta_0$是bias # In[4]: # accuracyi=θ1distancei+θ0+ϵ from sklearn.linear_model import LinearRegression import numpy as np # We can add a dimension to an array by using np.newaxis print("Shape of the series:", pga.distance.shape) print("Shape with newaxis:", pga.distance[:, np.newaxis].shape) # The X variable in LinearRegression.fit() must have 2 dimensions lm = LinearRegression() lm.fit(pga.distance[:, np.newaxis], pga.accuracy) theta1 = lm.coef_[0] print(theta1) # ### accuracy = $\theta_1$ $distance_i$ + $\theta_0$ + $\alpha$ # - $\theta_0$是bias # - #### 没有用梯度下降来求代价函数 # In[9]: # The cost function of a single variable linear model # 单变量 代价函数 def cost(theta0, theta1, x, y): # Initialize cost J = 0 # The number of observations m = len(x) # Loop through each observation # 通过每次观察进行循环 for i in range(m): # Compute the hypothesis # 计算假设 h = theta1 * x[i] + theta0 # Add to cost J += (h - y[i]) ** 2 # Average and normalize cost J /= (2 * m) return J # The cost for theta0=0 and theta1=1 print(cost(0, 1, pga.distance, pga.accuracy)) theta0 = 100 theta1s = np.linspace(-3, 2, 100) costs = [] for theta1 in theta1s: costs.append(cost(theta0, theta1, pga.distance, pga.accuracy)) plt.plot(theta1s, costs) plt.show() # In[6]: import numpy as np from mpl_toolkits.mplot3d import Axes3D # # Example of a Surface Plot using Matplotlib # # Create x an y variables # x = np.linspace(-10, 10, 100) # y = np.linspace(-10, 10, 100) # # We must create variables to represent each possible pair of points in x and y # # ie. (-10, 10), (-10, -9.8), ... (0, 0), ... ,(10, 9.8), (10,9.8) # # x and y need to be transformed to 100x100 matrices to represent these coordinates # # np.meshgrid will build a coordinate matrices of x and y # X, Y = np.meshgrid(x, y) # # print(X[:5,:5],"\n",Y[:5,:5]) # # Compute a 3D parabola # Z = X ** 2 + Y ** 2 # # Open a figure to place the plot on # fig = plt.figure() # # Initialize 3D plot # ax = Axes3D(fig) # # Plot the surface # ax.plot_surface(X=X, Y=Y, Z=Z) # plt.show() # Use these for your excerise theta0s = np.linspace(-2, 2, 30) theta1s = np.linspace(-2, 2, 30) COST = np.empty(shape=(30, 30)) # Meshgrid for paramaters T0S, T1S = np.meshgrid(theta0s, theta1s) # for each parameter combination compute the cost for i in range(30): if i % 10 == 0: print(i) for j in range(30): COST[i, j] = cost(T0S[0, i], T1S[j, 0], pga.distance, pga.accuracy) # make 3d plot print("aaaa") fig2 = plt.figure() ax1 = Axes3D(fig2) plt.xlabel('theta0s',fontsize=12,color='red',rotation=60,verticalalignment='top') plt.ylabel('theta1s',fontsize=14,color='blue',rotation=30,horizontalalignment='center') ax1.plot_surface(X=T0S, Y=T1S, Z=COST) point = (2, 2) x = np.linspace(point[0]-0.13333, point[0]+0.13333, 2) y = np.linspace(point[1]-0.13333, point[1]+0.13333, 2) x, y = np.meshgrid(x, y) z = np.zeros((2, 2)) for i in range(2): for j in range(2): z[i, j] = cost(x[0, i], y[j, 0], pga.distance, pga.accuracy) ax1.plot_surface(X=x, Y=y, Z=z) plt.show() # ### 求导 # In[21]: # 对 theta1 进行求导 def partial_cost_theta1(theta0, theta1, x, y): # Hypothesis h = theta0 + theta1 * x # Hypothesis minus observed times x diff = (h - y) * x # Average to compute partial derivative partial = diff.sum() / (x.shape[0]) return partial partial1 = partial_cost_theta1(0, 5, pga.distance, pga.accuracy) print("partial1 =", partial1) # 对theta0 进行求导 # Partial derivative of cost in terms of theta0 def partial_cost_theta0(theta0, theta1, x, y): # Hypothesis h = theta0 + theta1 * x # Difference between hypothesis and observation diff = (h - y) # Compute partial derivative partial = diff.sum() / (x.shape[0]) return partial partial0 = partial_cost_theta0(1, 1, pga.distance, pga.accuracy) print("partial0 =", partial0) # ### 梯度下降进行更新 # In[22]: # x is our feature vector -- distance # y is our target variable -- accuracy # alpha is the learning rate # theta0 is the intial theta0 # theta1 is the intial theta1 def gradient_descent(x, y, alpha=0.1, theta0=-1, theta1=1): max_epochs = 1000 # Maximum number of iterations 最大迭代次数 counter = 0 # Intialize a counter 当前第几次 c = cost(theta1, theta0, pga.distance, pga.accuracy) ## Initial cost 当前代价函数 costs = [c] # Lets store each update 每次损失值都记录下来 # Set a convergence threshold to find where the cost function in minimized # When the difference between the previous cost and current cost # is less than this value we will say the parameters converged # 设置一个收敛的阈值 (两次迭代目标函数值相差没有相差多少,就可以停止了) convergence_thres = 0.0000000000000001 cprev = c + 10 theta0s = [theta0] theta1s = [theta1] # When the costs converge or we hit a large number of iterations will we stop updating # 两次间隔迭代目标函数值相差没有相差多少(说明可以停止了) while (np.abs(cprev - c) > convergence_thres) and (counter < max_epochs): cprev = c # Alpha times the partial deriviative is our updated # 先求导, 导数相当于步长 update0 = alpha * partial_cost_theta0(theta0, theta1, x, y) update1 = alpha * partial_cost_theta1(theta0, theta1, x, y) # Update theta0 and theta1 at the same time # We want to compute the slopes at the same set of hypothesised parameters # so we update after finding the partial derivatives # -= 梯度下降,+=梯度上升 theta0 -= update0 theta1 -= update1 # Store thetas theta0s.append(theta0) theta1s.append(theta1) # Compute the new cost # 当前迭代之后,参数发生更新 c = cost(theta0, theta1, pga.distance, pga.accuracy) # Store updates,可以进行保存当前代价值 costs.append(c) counter += 1 # Count print(counter) # 将当前的theta0, theta1, costs值都返回去 return {'theta0': theta0, 'theta1': theta1, "costs": costs} res = gradient_descent(pga.distance, pga.accuracy) print("Theta0 =", ['theta0']) print("Theta1 =", res['theta1']) print("costs =", res['costs']) descend = gradient_descent(pga.distance, pga.accuracy, alpha=.01) plt.scatter(range(len(descend["costs"])), descend["costs"]) plt.show()
import matplotlib.pylab as pyl import numpy as np def operation(): pass if __name__ == '__main__': X_ = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) Y_ = np.array([1, 2.3, 2.7, 4.3, 4.7, 6.3, 7, 8, 9]) # X_ = np.array([1]) # Y_ = np.array([1]) n = len(X_) for i in range(3): x_ = X_[i*3:(i+1)*3] y_ = Y_[i*3:(i+1)*3] w = (np.sum(x_) * np.sum(y_) - n * np.sum(x_ * y_)) / (np.square(np.sum(x_)) - n * np.sum(np.square(x_))) b = (np.sum(y_) - w * np.sum(x_))/n print(w, b) y = w * x_ + b pyl.plot(x_, y) pyl.plot(x_, y_, 'o') pyl.show()
from display import * from matrix import * from draw import * """ Goes through the file named filename and performs all of the actions listed in that file. The file follows the following format: Every command is a single character that takes up a line Any command that requires arguments must have those arguments in the second line. The commands are as follows: circle: add a circle to the edge matrix - takes 4 arguments (cx, cy, cz, r) hermite: add a hermite curve to the edge matrix - takes 8 arguments (x0, y0, x1, y1, rx0, ry0, rx1, ry1) bezier: add a bezier curve to the edge matrix - takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3) line: add a line to the edge matrix - takes 6 arguemnts (x0, y0, z0, x1, y1, z1) ident: set the transform matrix to the identity matrix - scale: create a scale matrix, then multiply the transform matrix by the scale matrix - takes 3 arguments (sx, sy, sz) move: create a translation matrix, then multiply the transform matrix by the translation matrix - takes 3 arguments (tx, ty, tz) rotate: create a rotation matrix, then multiply the transform matrix by the rotation matrix - takes 2 arguments (axis, theta) axis should be x y or z apply: apply the current transformation matrix to the edge matrix display: clear the screen, then draw the lines of the edge matrix to the screen display the screen save: clear the screen, then draw the lines of the edge matrix to the screen save the screen to a file - takes 1 argument (file name) quit: end parsing See the file script for an example of the file format """ ARG_COMMANDS = [ 'line', 'scale', 'move', 'rotate', 'save' ] def parse_file( fname, edges, transform, screen, color ): finput = open(fname, 'r') instructions = finput.read().split("\n") i = 0 while(i < len(instructions)): upshift = 1 if(instructions[i] == 'ident'): ident(transform) if(instructions[i] == 'apply'): matrix_mult(transform, edges) if(instructions[i] == 'display'): clear_screen(screen) draw_lines(edges, screen, color) display(screen) if(instructions[i] == "save"): clear_screen(screen) draw_lines(edges, screen, color) display(screen) save_extension(screen, instructions[i+1]) upshift = 2 if(instructions[i] == "line"): newpoints = instructions[i+1].split() add_edge(edges, int(newpoints[0]), int(newpoints[1]), int(newpoints[2]), int(newpoints[3]), int(newpoints[4]), int(newpoints[5])) upshift = 2 if(instructions[i] == "scale"): newpoints = instructions[i+1].split() matrix_mult(make_scale(int(newpoints[0]), int(newpoints[1]), int(newpoints[2])), transform) upshift = 2 if(instructions[i] == "rotate"): nextstuff = instructions[i+1].split() if(nextstuff[0] == "x"): matrix_mult(make_rotX(int(nextstuff[1])), transform) if(nextstuff[0] == "y"): matrix_mult(make_rotY(int(nextstuff[1])), transform) if(nextstuff[0] == "z"): matrix_mult(make_rotZ(int(nextstuff[1])), transform) upshift = 2 if(instructions[i] == "move"): newpoints = instructions[i+1].split() matrix_mult(make_translate(int(newpoints[0]), int(newpoints[1]), int(newpoints[2])), transform) upshift = 2 if instructions[i] == "circle": p = [int(y) for y in instructions[i + 1].split(" ")] add_circle(edges, p[0], p[1], p[2], p[3]) upshift = 2 if instructions[i] == "hermite": p = [int(y) for y in instructions[i + 1].split(" ")] add_hermite(edges, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]) upshift = 2 if instructions[i] == "bezier": p = [int(y) for y in instructions[i + 1].split(" ")] add_bezier(edges, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]) upshift = 2 if instructions[i] == "sector": p = [int(y) for y in instructions[i + 1].split(" ")] add_sector(edges, p[0], p[1], p[2], p[3], p[4], p[5]) upshift = 2 if instructions[i] == "quit": break if instructions[i] == 'box': p = [int(y) for y in instructions[i + 1].split(" ")] add_box(edges, p[0], p[1], p[2], p[3], p[4], p[5]) upshift = 2 elif instructions[i] == 'sphere': p = [int(y) for y in instructions[i + 1].split(" ")] add_sphere(edges, p[0], p[1], p[2], p[3]) upshift = 2 elif instructions[i] == 'torus': p = [int(y) for y in instructions[i + 1].split(" ")] add_torus(edges, p[0], p[1], p[2], p[3], p[4]) upshift = 2 i += upshift
#!/usr/bin/python3 import sqlite3 db = "./students.db" conn = sqlite3.connect(db) c = conn.cursor() cmd = "CREATE TABLE students (Name TEXT, Last TEXT)" c.execute(cmd) conn.commit() data = [ ("Robert", "Tables"), ("Toby", "Huang"), ("Hannah", "Sindorf"), ("Daniel", "Frey"), ("Ray", "Ruazol"), ("Roger", "Huba"), ("Joyce", "Liao"), ("Scott", "Curie"), ("Vince", "Masten"), ("Matthew", "Brown") ] c.executemany("INSERT INTO students VALUES (?,?)", data) conn.commit() conn.close()
from pygame import display, draw, time, event from pygame import KEYDOWN import random class Circle: def __init__(self, center, radius): self.center = center self.radius = radius screen = display.set_mode([800, 600]) screen.fill([0]*3) # RGB white = [255, 255, 255] ''' center = [400, 300] radius = 50 draw.circle(screen, white, center, radius, 1) display.flip() # time.wait(2000) # milliseconds ''' circles = [] ''' # creepy white circles <3 while not event.poll().type == KEYDOWN: circles.append(Circle([random.randint(20, 780), random.randint(20, 580)], 20)) for c in circles: c.radius += 1 draw.circle(screen, white, c.center, c.radius) clock = time.Clock() clock.tick(60) display.flip() ''' while not event.poll().type == KEYDOWN: screen.fill([0] * 3) circles.append(Circle([random.randint(20, 780), random.randint(20, 580)], random.randint(20, 30))) for c in circles[:]: if c.radius > 55: circles.remove(c) else: c.radius += 1 draw.circle(screen, white, c.center, c.radius, 1) clock = time.Clock() clock.tick(60) display.flip() # for c in circles[:] # slice for copy, bc. cannot delete list i am iterating
import rooms import barriers import objects import items import player class adventure: def __init__(self, y=1, x=1): self.x = x self.y = y self.map = [] for i in range(2*y+1): self.map.append([]) for j in range(2*x+1): self.map[i].append(None) def __str__(self): s = "" for row in self.map: for room in row: if room: r = repr(room) else: r = "" s += r spacing = len(r) while spacing < 20: s += " " spacing += 1 s += "\n" return s def add_room(self, room, y, x): if x < self.x and x >= 0 and y < self.y and y >= 0: self.map[2*y+1][2*x+1] = room else: print("Room coordinates out of bounds") def add_barrier(self, barrier, y, x, dir="N"): if x < self.x and x >= 0 and y < self.y and y >= 0: if dir.upper() == "N": y_offset = -1 x_offset = 0 elif dir.upper() == "S": y_offset = 1 x_offset = 0 elif dir.upper() == "W": y_offset = 0 x_offset = -1 elif dir.upper() == "E": y_offset = 0 x_offset = 1 else: y_offset = 0 x_offset = 0 if x_offset or y_offset: # If a valid direction, dir, was given. self.map[2*y+1+y_offset][2*x+1+x_offset] = barrier else: print("Direction is not valid.") else: print("Coordinates out of bounds.") if __name__ == "__main__": a = adventure(2,3) ### Rooms room = rooms.room() red_room = rooms.red_room() blue_room = rooms.blue_room() green_room = rooms.green_room() goal = rooms.final_room() a.add_room(room, 1,1) a.add_room(red_room, 0,0) a.add_room(blue_room, 0,1) a.add_room(green_room, 0,2) a.add_room(goal, 1, 2) ### Barriers passage = barriers.passage() passage_2 = barriers.passage() passage_3 = barriers.passage() door = barriers.door() a.add_barrier(passage, 1,1, "N") a.add_barrier(passage_2, 0,1, "W") a.add_barrier(door, 0,1, "E") a.add_barrier(passage_3, 0,2, "S") print(a)
name = input("Please enter your name. > ") print("Hello, " + name.split(" ")[0].title() + "!") x = input("Give me an integer to add: ") try: x = int(x) except: print("The value you entered is not a number.") else: y = input("Give me another integer to add: ") try: y = int(y) except: print("The second value you entered is not a number.") else: print("The sum of your numbers is: " + str(x + y))
##################### ### Base classes. ### ##################### class room: repr = "room" m_description = "You are in a simple room." def __init__(self, contents=[]): self.contents = contents def __str__(self): s = "" for object in self.contents: s += " " + str(object) return self.m_description + s def __repr__(self): return self.repr ###################### ### Child classes. ### ###################### class blue_room(room): repr = "b. room" m_description = "You are in a blue room." class red_room(room): repr = "r. room" m_description = "You are in a red room." class green_room(room): repr = "g. room" m_description = "You are in a green room." class final_room(room): repr = "goal" m_description = "You found the hidden room!"
# logic operator # конструкция if test = 'String' if test: print('hello, world') human = 100 robots = 1000 if robots > human: #если роботов больше чем людей print('all right')# если роботов действительно больше(если переменная robots больше чем переменная human) выводить на экран это сообщ # конструкция else if 2+2 > 5: print('вы нарушили правила математики') else: print('естественно меньше') # new constraction if ports = [80, 91, 255, 300] def gameRules(portsVal): if input(r'Хотите ли Вы сыграть игру <<Угадай порт>> ?>>>').lower() == 'да': if ports[int(input('Выберите любое число от 0 до 3 >>>'))] == 80: print('Поздравляю!!! Вы выиграли') else: print('К сожалению Вы проиграли. Попробуйте еще раз') gameRules(ports) else: print('Удачного дня!') gameRules(ports)
class Person: name ='' surname ='' quality = 0 def __init__(self, n, s, q): self.name = n self.surname = s self.quality = q def showPerson(self): print(self.name, self.surname, self.quality, 'количество трудового стажа в годах') def __del__(self): delit = int(input('Введите номер сотрудникаn\nNiklai введите - 1:\nOlga введите - 2:\nMita введите - 3:\n')) if delit == 1: print('досведания мистер', nikola.name, nikola.surname) if delit == 2: print('досведания мистер', olga.name, olga.surname) if delit == 3: print('досведания мистер', mita.name, mita.surname) else: print('Введите число от 1 до 3') nikola = Person('nikolai', 'Ivanov', 2) nikola.showPerson() olga = Person('olga', 'Petrova', 7) olga.showPerson() mita = Person('mita', 'Nita', 3) mita.showPerson() nikola.__del__()
from tkinter import * import os creds = 'tempfile.temp' # This just sets the variable creds to 'tempfile.temp' failure_max = 3 def delete3(): screen4.destroy() def password_not_recognised(): global screen4 screen4 = Toplevel(screen) screen4.title("Access Denied") screen4.geometry("220x100") Label(screen4, text = "Wrong username or password \n Try Again!").pack() Label(screen4, text = "").pack() Button(screen4, text = "OK", command =delete3).pack() #Show the tkinter window at the center windowWidth = screen4.winfo_reqwidth() windowHeight = screen4.winfo_reqheight() positionRight = int(screen4.winfo_screenwidth()/2 - windowWidth/2) positionDown = int(screen4.winfo_screenheight()/2.4 - windowHeight/2) screen4.geometry("+{}+{}".format(positionRight, positionDown)) def enter(event): login_verify() def login_verify(failures=[]): with open(creds) as f: data = f.readlines() # This takes the entire document we put the info into and puts it into the data variable username = data[0].rstrip() # Data[0], 0 is the first line, 1 is the second and so on. password = data[1].rstrip() # Using .rstrip() will remove the \n (new line) word from before when we input it if username_entry1.get() == username and password_entry1.get() == password: # Checks to see if you entered the correct data. screen.destroy() return failures.append(1) username_entry1.delete(0, END) # if username or password is wrong, it delete the old entry and blank for new entry password_entry1.delete(0, END) if sum(failures) >= failure_max: screen.destroy() #Captures a image of unautorized person try: from Capture_Image import camera_capture except: pass #Send email try: from Email import send except: pass #Shutdown computer if unauthorize person detect os.system('start shutdown /r') raise SystemExit('Unauthorized login attempt') else: password_not_recognised() def main_screen(): from PIL import ImageTk, Image import os global screen screen = Tk() # Logo setup img = ImageTk.PhotoImage(Image.open("logo.png")) panel = Label(screen, image = img) panel.place(x = 430, y = 350) screen.geometry('1396x1280') screen.overrideredirect(1) screen.title("Notes 1.0") Label(text = "Smart Login Protection", bg = "grey", fg = "White", width = "300", height = "2", font = ("Calibri", 18)).pack() Label(text = "").pack() Label(text = "Please Login", font = ("Calibri", 15)).pack() Label(text = "").pack() # Login Checkup global username_entry1 global password_entry1 Label(screen, text = "Username * ", font = ("Calibri", 13)).pack() username_entry1 = Entry(screen, borderwidth=3) username_entry1.pack() Label(screen, text = "").pack() Label(screen, text = "Password * ", font = ("Calibri", 13)).pack() password_entry1 = Entry(screen, borderwidth=3, show = "*") password_entry1.pack() Label(screen, text = "").pack() Button(screen, text = "Login", borderwidth=2,bg = "Blue", fg = "White", width = 14, height = 1, font = ("Calibri", 13), command = login_verify).pack() screen.bind('<Return>', enter) #bind ENTER button username_entry1.focus_set() #Set cursor to username by default screen.mainloop() main_screen()
#This program imports data from a link, cleans the data and then generates a boxplot, histogram and QQ-Plot for a specific column of the data #each plot is saved and printed to the screen #Observations: From the boxplot and histogram it is apparent that the data is skewed right (mean<median). #Observations (cont'd): From the QQ-Plot there is a high R**2 between the data and the theoretical normal but the fact that the data at the smallest and largest quantiles does not fit well indicates to me a normal distribution is not an optimal fit and a distribution with "fatter tails" would probably better suit the data import matplotlib.pyplot as plt #import plotting package import pandas as pd #import pandas package as pd import scipy.stats as stats#import stats portion of scipy as stats loansData=pd.read_csv('https://spark-public.s3.amazonaws.com/dataanalysis/loansData.csv')#read in csv data from given link and enters data into loansData loansData.dropna(inplace=True)#removes rows with null values #boxplot plt.figure()#generate new figure loansData.boxplot(column='Amount.Requested')#generate boxplot for data in "Amount Requested" col plt.savefig('Amount_Funded_By_Investors_BOXPLOT.png')#saves boxplot plt.show()#prints boxplot #histogram plt.figure()#generate new figure loansData.hist(column='Amount.Requested')#generate histogram for data in "Amount Requested" col plt.savefig('Amount_Funded_By_Investors_HISTOGRAM.png')#save histogram plt.show()#prints histogram #QQ Plot plt.figure()#generate new figure graph=stats.probplot(loansData['Amount.Requested'], dist="norm",plot=plt)#generate QQ-Plot for data in "Amount Requested" col against normal dist plt.savefig('Amount_Funded_By_Investors_QQPLOT.png')#save QQ-Plot plt.show()#prints QQ-Plot
name='helen' name1= name.capitalize() print(name1) title='GREATWALL' title2=title.casefold() print(title2) name='Helen' name.count('e') fname='string.py' x=fname.endwith('.py') print(x) s1='238' s2='ww2' s1.isnumeric() s2.isnumeric() a='' while not a.isnumeric(): print('please input a number:') a=input() name=' helen ' name =='helen' name1=name.strip() print(name1) line='helen, 90, 89, 70' la=line.split(',') print(la) name=la[0] math=int(la[1].strip()) print(name) print(math) today='8-3-2021' la=today.split('-') month=int(la[0]) date=int(la[1]) year=int(la[2]) print(month+date+year) la=['helen','claire','nancy'] ','.join(la)
from os import get_terminal_size print('a good day') print('helen') name='helen' print('hello '+ name) print(f'hello {name}') air='off' temp=92 too_hot=temp>95 if too_hot: air='on' print('too hot') temp=92 air='' if temp>90: air='on' else: air='off' print(air) temp=65 go_out= False if temp>=50 and temp<70: go_out=True print('go out...') age=12 school='GMS' if age>11 and age<15: print('middle school') elif age>20: print('college') age=14 school='GMS' if age>11 and age<15: print('middle school') if school in ['GMS','CMS']: print('WWP MS') else school in ['PUMS','Monty']: print('not WWP MS') else: ('not MS')
def print_factors(a): for i in range(1,a+1): if a % i ==0: print(i) print_factors(100) def factors(a): la=[] for i in range(1,a+1): if a%i==0: la.append(i) return la la=factors(20) print(la) def welcome(school='GMS', student) print(f'{school} welcome {student}') welcome('GMS', 'Claire') welcome('CMS', 'Helen')
import numpy as np import pandas as pd import re #class for regular expression from nltk.corpus import stopwords # stopwords are wirds like the, is etc. that do not have any importance while classifying emails as spam or not STOPWORDS = set([]) # set(stopwords.words('english')) def clean_text(text): text = text.lower() text = re.sub(r'[^a-z\s]', '', text) # eliminate single letter words and white spaces text = ' '.join([word for word in text.split() if word not in STOPWORDS]) # removing the stop words return text def tokenize(text, word_to_idx): tokens = [] # list of tokens i.e. words when converted to ids for word in text.split(): tokens.append(word_to_idx[word]) return tokens def pad_and_truncate(messages, max_length=30): features = np.zeros((len(messages), max_length), dtype=int) for i, email in enumerate(messages): if len(email): features[i, -len(email):] = email[:max_length] return features if __name__ == '__main__': #to read from the text file #data = pd.read_csv('./data/EmailSpamCollection.txt', sep='\t', header=None, names=['label', 'email']) #to read from a csv file data = pd.read_csv('./data/EmailSpamCollection-mini.csv', names=['label', 'email']) data.email = data.email.astype(str) # to avoid pandas to consider email text as floating point numbers data.email = data.email.apply(clean_text) words = set((' '.join(data.email)).split()) word_to_idx = {word: i for i, word in enumerate(words, 1)} tokens = data.email.apply(lambda x: tokenize(x, word_to_idx)) inputs = pad_and_truncate(tokens) labels = np.array((data.label == 'spam').astype(int)) np.save('./data/labels.npy', labels) np.save('./data/inputs.npy', inputs)
def jumpingOnClouds(c): count = 0 i = 0 while True: if i+2 < len(c) and c[i+2] == 0: count += 1 i = i+2 print('count: ', count, 'jumps:', 2, 'increment:', i) elif i+1 < len(c) and c[i+1] == 0: count += 1 i = i+1 print('count: ', count, 'jumps:', 1, 'increment:', i) if i == len(c) - 1: return count print(jumpingOnClouds([0, 0, 1, 0, 0, 1, 0])) print(jumpingOnClouds([0, 0, 0, 1, 0, 0])) # print(jumpingOnClouds()) # print(jumpingOnClouds())
#python program to classify the handwritten digits (MNIST Dataset) using pytorch and GPU import torch import matplotlib.pyplot as plt import numpy as np import torchvision #importing the dataset import torchvision.transforms as transforms #transform the dataset to torch.tensor import torch.optim as optim # for use of optim algorithms in backprop import torch.nn as nn #to define a neural network in pytorch #loading the data batch_size = 128 classes = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())#transforms convert raw image downloaded into tensor for pytorch trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True) testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transforms.ToTensor()) testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False) #defining the class for the CNN class LeNet(nn.Module): def __init__(self): super(LeNet, self).__init__() self.cnn_model = nn.Sequential( nn.Conv2d(1, 6, 5), # (N, 3, 32, 32) -> (N, 6, 28, 28) nn.Tanh(), nn.AvgPool2d(2, stride=2), # (N, 6, 28, 28) -> (N, 6, 14, 14) nn.Conv2d(6, 16, 5), # (N, 6, 14, 14) -> (N, 16, 10, 10) nn.Tanh(), nn.AvgPool2d(2, stride=2) # (N,16, 10, 10) -> (N, 16, 5, 5) ) self.fc_model = nn.Sequential( nn.Linear(256,120), # (N, 400) -> (N, 120) nn.ReLU(), nn.Linear(120,84), # (N, 120) -> (N, 84) nn.ReLU(), nn.Linear(84,20), # (N, 84) -> (N, 10) nn.ReLU(), nn.Linear(20,10) ) def forward(self, x): # define forward propogation for CNN x = self.cnn_model(x) x = x.view(x.size(0), -1) # After CNN operation convert images into 1D array to fed to Neural network x = self.fc_model(x) return x #return output def evaluation(self,dataloader): # to calculate accuracy total, correct = 0, 0 for data in dataloader: inputs, labels = data inputs, labels = inputs.to(device), labels.to(device) #move inputs and labels to gpu outputs = net(inputs) _, pred = torch.max(outputs.data, 1) total += labels.size(0) correct += (pred == labels).sum().item() #check correct predictions return 100 * correct / total #return accuracy def fit(self,trainloader, opt, max_epoch=10): for epoch in range(max_epoch): for i, data in enumerate(trainloader, 0): inputs, labels = data inputs, labels = inputs.to(device), labels.to(device) opt.zero_grad() # make all the gradients of optim to zero outputs = self.forward(inputs) loss = loss_fn(outputs, labels) loss.backward() #calculate the derivatives in pytorch opt.step() #take a set of GD according to the optim print('Epoch: %d/%d' % (epoch, max_epoch)) #check if gpu is availabe and use it device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net = LeNet().to(device) #class instantiation loss_fn = nn.CrossEntropyLoss() #define loss function opt = optim.Adam(net.parameters(),lr=1e-3, weight_decay=1e-4) #set optim agorithm and its parameters net.fit(trainloader,opt,30) #fit the data print('Test acc: %0.2f, Train acc: %0.2f' % (net.evaluation(testloader), net.evaluation(trainloader))) #check accuracy
import random N = int(input("Please eneter a number : ")) Counter = 1 Numbers = [] Numbers.append(random.randint( 0, 1000)) while Counter < N : Duplicate = False Rnd = random.randint(0, 1000) for i in range(len(Numbers)) : if Numbers[i] == Rnd : Duplicate = True if Duplicate == False : Numbers.append(Rnd) Counter +=1 for i in range(N): print(Numbers[i] ,end=' ')
# This file generates data to use in `intro_to_pandas.py` file. # NOTE: This file is used to generate random data in csv file. You can modify this file # according to your requirement. Add/update/delete values in `list_of_columns`, which # stores column detail and generate data for that column according to given detail. # TODO: Make this function with multiple arguments required which can be called # from another script to generate random data #### Import libraries #### # To get current directory import os # To generate random numbers import random # To work with csv files import csv def generate_random_csv_data_to_file( list_of_columns, no_of_values=10, file_name='data.csv' ): #### Variables you can modify according to your requirement #### # You can modify following variables for different cases # Add new dict in list to add new column in data # Variable Name : Description # list_of_columns : stores csv column meta data # name : name of column or header # min_value : minimum value column data can have # max_value : maximum value column data can have # no_of_value : no of experimental data in each column # file_name : file to store data into #### Example data #### # list_of_columns = [ # dict( # name='age', # min_value=0, # max_value=100, # ), # dict( # name='annual_income', # min_value=0, # max_value=24000000, # ), # dict( # name='weight', # min_value=1, # max_value=200, # ), # ] # All coulmns will have same no of values # no_of_values = 10 # file_name = 'data.csv' # TODO: Allow to add list of choices and randomly allocate values from give choices # TODO: Allow to generate different number of values for each column and set NaN # for remaining empty values in other columns # TODO: Allow to create file in sub or other directory #### Script to generate random csv data and store in file #### get_dict_key_values = lambda key: [column[key] for column in list_of_columns] # Generate list of random values coulmn_labels = get_dict_key_values('name') columns_min_values = get_dict_key_values('min_value') columns_max_values = get_dict_key_values('max_value') # DEBUG print(coulmn_labels, columns_max_values, columns_min_values) list_of_values = [random.sample(range(columns_min_values[i], columns_max_values[i]), no_of_values) for i in range(len(list_of_columns))] # DEBUG print(list_of_values) # Get path to file where data will be stored current_dir = os.getcwd() data_file_path = os.path.join(current_dir, file_name) # TODO: Add new flag to column value to indicate how to store vallues in csv # file--in quote or not. And use `wr_quote_value` wrtier or `wr_unquote_value` # writer according to given flag for column value. # Store data(list of random values) as comma seprated values to csv file with open(data_file_path, 'w+') as file_to_write: wr_quote_value = csv.writer(file_to_write, quoting=csv.QUOTE_ALL) wr_unquote_value = csv.writer(file_to_write) # Add column header value with quote in csv wr_quote_value.writerow(coulmn_labels) for row_no in range(no_of_values): # DEBUG: print(row_no) wr_unquote_value.writerow([column_val[row_no] for column_val in list_of_values])
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import os a = tf.constant([.0,.0,.0,.0], tf.float32) b = tf.constant([1.,2.,3.,4.], tf.float32) result1 = tf.nn.softmax(a) result2 = tf.nn.softmax(b) sess = tf.Session() print(sess.run(result1)) print(sess.run(result2)) #softmax输入是一个向量,输入后是一个归一化后的向量,用于计算向量各个值在整个向量中的权重 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) #one_hot=True 表示用非零即1的数组保存图片表示的数值,如 图片上写的是0,内存不是直接存一个0,而是存一个数组[1,0,0,0,0,0,0], 一个图片上写的是,保存的就是[0,1,0,0,0,0,0] #假定数据集中只有16张照片,那么y的最终结果是16*10的矩阵,每一行代表一张图片 y_ = tf.placeholder(tf.float32,[None,10])
APPROVED = ['firstNames.txt', 'lastNames.txt'] def getEntries(file): # returns a list of entries from filename file.seek(0) file.readline() #skip past entry count entries = [] for line in file: entries.append(line.rstrip()) return entries def deleteContent(file): file.seek(0) file.truncate() def retotal(filename): #totals number of entries #prints result if filename not in APPROVED: return F = open(filename, 'r') F.readline() total = 0 while F.readline() != '': total+=1 F.close() print(total) def alphabetize(filename): # alphabetizes file entries if filename not in APPROVED: return F = open(filename, 'r+') entries = getEntries(F) entries.sort() F.seek(0) #delete file content F.truncate() # for i in range(len(entries)-1): F.write(entries[i] + '\n') #return newline characters F.write(entries[-1]) #except for final entry F.close() def find(target, filename): # return True if target is entry in filename, False if not F = open(filename, 'r') entries = getEntries(F) F.close() return target in entries
#!/usr/bin/env python3 # -*- coding: utf-8 -*- list001=range(101) a=0 n=int(input("请输入准备取前几个数:")) list002=[] while a<n: list002.append(list001[a]) a=a+1 print(list002)
#--coding:utf-8-- h=input("请输入你的身高\n") kg=input("请输入你的体重\n") h=float(h) kg=float(kg) bmi=kg/(h*h) if bmi<18.5 : print("过轻") elif bmi<=25 : print("正常") elif bmi<=28: print("过重") elif bmi<=32: print("肥胖") elif bmi>32: print("严重肥胖")
#! /usr/bin/env python3 # coding=utf-8 name=input("请输入你的名字!:") age=int(input("请输入你的年龄:")) a_dict={'testname':29} a_dict[name]=age print(a_dict)
#! /usr/bin/env python3 # coding=utf-8 sum=0 for x in [1,2,3,4,5,6,7,8,9,10]: sum=sum+x print(sum)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- L1=['Hello','World',18,'Apple',None] L2=[s.lower() for s in L1 if isinstance(s,str) ] print(L2)
class simpleOperations(object): def __init__(self, x,y): self.x = x self.y = y # all of simple operations can call x because of this self function def productXY(self): prod = [self.x[i]*self.y[i] for i in range(len(self.x))] return prod def addOneX(self): print self.x self.x = [self.x[i]+i for i in range(len(self.x))] print self.x def differenceXY(self,x=None,y=None): if (x==None and y!=None) or (x!=None and y==None): raise XanaError('NeedBothError') if x!=None and y!=None: if len(x)!=len(y): raise XanaError('NeedSameLength') if x==None: x=self.x if y==None: y=self.y diff = [self.x[i]-self.y[i] for i in range(len(self.x))] return diff def printDefaults(self,x=1,y=3,z=4): print 'x=',x print 'y=',y print 'z=',z # increase the values by 1 # calculate the product def newFun(self): print self.x self.x = [self.x[i]+i for i in range(len(self.x))] print self.x print self.y self.y = [self.y[i]+i for i in range(len(self.y))] print self.y prod = [self.x[i]*self.y[i] for i in range(len(self.x))] return prod # x = [2,5,3] # y = [4,5,7] # # ranObj = simpleOperations(x,y) # prod = ranObj.productXY() # # print x, y, prod # # ranObj = simpleOperations(x,y) # # ranObj.addOneX() # # ranObj.addOneX()
#!/usr/local/bin/python # given a list of integers, prints fizz for any value that is a multiple of 3 # prints buzz for any value that is a multiple of 5, and for any value that # is a multiple of 3 and 5 prints fizzbuzz import sys for numstr in sys.argv[1:]: num = int(numstr) if num % 3 == 0 and num % 5 == 0: print('fizzbuz') elif num % 3 == 0: print('fizz') elif num % 5 == 0: print('buzz') else: print(num)
#Python program to count number of characters in a string. a = input("Enter the string :") f = {} for i in a: if i in f: f[i] += 1 else: f[i] = 1 print ("Count of all characters is :\n "+str(f)) #Output #Enter the string :afxghbk #Count of all characters is : # {'a': 1, 'f': 1, 'x': 1, 'g': 1, 'h': 1, 'b': 1, 'k': 1}
# Examine the code below. # What is it doing? # Could you make this code better? def printevens(x): y = 0 while(y < len(x)): if y % 2 == 0: print(x[y], end=" ") y += 1
#Imagine you are creating a program to give advice about # what activities to do based on the weather #TODO: Write some code to check what the weather is # today and print out what to do if the weather is sunny # then print "Let's go to the park!" if the weather is # foggy print "Let's go see a movie" if the weather is # rainy print "Let's read a book indoors" else print # "Going out to eat is good in any weather" weather = "cloudy"
# Homework: Create a madlib. Imagine a story where some of the words are # supplied by user input. Using python you will use input to collect # words for a story and then display the story. # Use input to collect each word to a variable # Use an f string to display the story # Your madlib must collect at least 6 words! # -------------------------------------------------- # Partial solution # name = input("Name:") # color = input("color:") # num = input("Number:") # print(f"{name} wore {color} shoes while they counted to {num}")
# Homework: Your job is to make a custom calculator. # Your calculator should accept at least three values. # For example height, width, length # It should print a prompt that makes it clear what # is being calculated. # For example: # Enter height, width, and length to calculate the area of a cube # Height: 3 # Width: 4 # Length: 2 # After accepting input the calculator should perform # an accurate calculation and display the results in # a clear and well formatted message. # For example: A cube with a height of 3, width of 4, and length of 2 has an area of 24 # You can accept string input that becomes part of the descirption. # For example: Input units: inches # Be sure to convert your numeric values to numbers before performing math operations!
numbers = [2,15,0,-3] def insertion_sort(arr): for iterater in range(len(arr)): #the variable cursor is assigned the value of the iterater for each int in numbers cursor = (arr[iterater]) #the variable position is assigned the index of each num in numbers list position = iterater while position > 0 and arr[position-1] > cursor: #swapping the number down the list arr[position] = arr[position-1] position = position -1 #when the loops breaks, we assign the iterator of arr to the cursor arr[position] = cursor return arr print(insertion_sort([-2, 100, 10, 5, 8]))
class TreeNode(object): def __init__(self, key, val, left=None, right=None, parent=None): self.key = key self.payload = val self.left_child = left self.right_child = right self.parent = parent def has_left_child(self): return self.left_child def has_right_child(self): return self.right_child def is_left_child(self): return self.parent and self.parent.left_child == self def is_right_child(self): return self.parent and self.parent.right_child == self def is_root(self): return not self.parent def is_leaf(self): return not (self.left_child or self.right_child) def has_any_children(self): return self.left_child or self.right_child def has_both_children(self): return self.left_child and self.right_child def replace_node_data(self, key, val, right, left): self.key = key self.payload = val self.left_child = left self.right_child = right if self.has_left_child(): self.left_child.parent = self if self.has_right_child(): self.right_child.parent = self def __iter__(self): if self: if self.has_left_child(): for element in self.left_child: yield element yield self.key if self.has_right_child(): for element in self.right_child: yield element class BinarySearchTree(object): def __init__(self): self.root = None self.size = 0 def length(self): return self.size def __len__(self): return self.size def __iter__(self): return self.root.__iter__() def put(self, key, val): if self.root: self._put(key, val, self.root) else: self.root = TreeNode(key, val) self.size += 1 def _put(self, key, val, current_node): if key < current_node.key: if current_node.has_left_child(): self._put(key, val, current_node.left_child) else: current_node.left_child = TreeNode(key, val, parent=current_node) else: if current_node.has_right_child(): self._put(key, val, current_node.right_child) else: current_node.right_child = TreeNode(key, val, parent=current_node) def __setitem__(self, key, value): self.put(key, value) def get(self, key): if self.root: node = self._get(key, self.root) if node: return node.payload return None return None def _get(self, key, current_node): if key == current_node.key: return current_node if key < current_node.key: if current_node.has_left_child(): return self._get(key, current_node.left_child) else: if current_node.has_right_child(): return self._get(key, current_node.right_child) return None def __getitem__(self, key): return self.get(key) def __contains__(self, key): return True if self._get(key, self.root) else False def delete(self, key): if self.size > 1: node_to_remove = self._get(key, self.root) if node_to_remove: self.remove(node_to_remove) self.size -= 1 else: raise KeyError('Error! Key is not found in the tree!') elif self.size == 1 and self.root.key == key: self.root = None self.size = 0 else: raise KeyError('Error! Key is not found in the tree!') def __delitem__(self, key): self.delete(key) def find_min_child(self, current_node): while current_node.left_child: current_node = current_node.left_child return current_node def remove(self, node_to_remove): if node_to_remove.is_leaf(): if node_to_remove == node_to_remove.parent.left_child: node_to_remove.parent.left_child = None else: node_to_remove.parent.right_child = None elif not node_to_remove.has_both_children(): if node_to_remove.parent: if node_to_remove.is_left_child(): if node_to_remove.has_left_child(): node_to_remove.parent.left_child = node_to_remove.left_child node_to_remove.left_child.parent = node_to_remove.parent else: node_to_remove.parent.left_child = node_to_remove.right_child node_to_remove.right_child.parent = node_to_remove.parent else: if node_to_remove.has_left_child(): node_to_remove.parent.right_child = node_to_remove.left_child node_to_remove.left_child.parent = node_to_remove.parent else: node_to_remove.parent.right_child = node_to_remove.right_child node_to_remove.right_child.parent = node_to_remove.parent else: node_to_remove.replace_node_data(node_to_remove.left_child.key, node_to_remove.left_child.payload, node_to_remove.right_child, node_to_remove.left_child) else: node_to_replace = self.find_min_child(node_to_remove.right_child) if node_to_replace.is_leaf(): if node_to_replace.is_left_child(): node_to_replace.parent.left_child = None else: node_to_replace.parent.right_child = None else: if node_to_replace.has_right_child(): node_to_replace.right_child.parent = node_to_replace.parent if node_to_replace.is_left_chid(): node_to_replace.parent.left_child = node_to_replace.right_child else: node_to_replace.parent.right_child = node_to_replace.right_child else: node_to_replace.left_child.parent = node_to_replace.parent if node_to_replace.is_left_chid(): node_to_replace.parent.left_child = node_to_replace.left_child else: node_to_replace.parent.right_child = node_to_replace.left_child node_to_remove.key = node_to_replace.key node_to_remove.payload = node_to_replace.payload
import unittest from Implementation.binary_tree import BinaryTree class MyTestCase(unittest.TestCase): def test_something(self): r = BinaryTree('a') self.assertEqual(r.get_root_value(), 'a') self.assertEqual(r.get_left_child(), None) self.assertEqual(r.get_right_child(), None) r.insert_left('b') self.assertEqual(r.get_left_child().get_root_value(), 'b') r.insert_right('c') self.assertEqual(r.get_right_child().get_root_value(), 'c') r.in_order_traverse(r) r.pre_order_traverse(r) r.post_order_traverse(r) r.get_right_child().set_root_value('hello') self.assertEqual(r.get_right_child().get_root_value(), 'hello') if __name__ == '__main__': unittest.main()
from PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGui from PyQt5.QtGui import * from PyQt5.QtCore import * import copy import tictactoe from minimax import MiniMax import sys # Create window class class Window(QMainWindow): #constructor def __init__(self): super().__init__() # setting title self.setWindowTitle("Tic Tac Toe by Jason Carter") # setting geometry self.setGeometry(100, 100, 300, 550) # calliing method self.UiComponents() # Showing all the widgets self.show() # Initalize game self.game = tictactoe.TicTacToe() self.is_ai = False def UiComponents(self): # Create a push button list self.push_list = [] # creating 2d list of push buttons for _ in range(3): temp = [] for _ in range(3): temp.append((QPushButton(self))) # adding 3 push button in single row self.push_list.append(temp) # x and y coord x = 90 y = 80 self.player = QPushButton("Click to Play Against Computer", self) self.player.setGeometry(20, 30, 260, 60) self.player.clicked.connect(self.play_ai) # traversing through the push button list for i in range(len(self.push_list)): for j in range(len(self.push_list)): # setting geometry to the button self.push_list[i][j].setGeometry(x*i + 20, y*j + 120, 80, 80) # setting font to the button self.push_list[i][j].setFont(QFont(QFont('Times', 17))) # adding action to the button self.push_list[i][j].clicked.connect(self.action_called) # creating label to display who wins self.label = QLabel(self) # setting geomoetry to the label self.label.setGeometry(20, 400, 260, 60) # setting style sheet to the label self.label.setStyleSheet("QLabel" "{" "border : 2px solid black;" "background : white;" "}") # setting label alignment self.label.setAlignment(Qt.AlignCenter) # setting font to the label self.label.setFont(QFont('Times', 15)) # creating push button to restart the score reset_game = QPushButton("Reset-Game", self) # Setting geometry reset_game.setGeometry(50, 480, 200, 50) # adding action to reset the push button reset_game.clicked.connect(self.reset_game_action) # method called by reset button def reset_game_action(self): # reinitalize game to reset self.game = tictactoe.TicTacToe() # making label text empty self.label.setText("") # traverse push list for buttons in self.push_list: for button in buttons: # making all the button enabled button.setEnabled(True) # removing text of all the buttons button.setText("") # action called by the push buttons def action_called(self): # get the button that called the action button = self.sender() # disable button button.setEnabled(False) # traverse through the buttons to get the coords of button (there is probably a better way to do this) for i in range(len(self.push_list)): for j in range(len(self.push_list)): if button == self.push_list[i][j]: move = (i, j) break if self.is_ai is True: # set the text of the button to X button.setText(self.game.get_X_player()) # make the move in the game self.game.make_move(self.game.get_X_player(), move) # if the game is unfinished, make the AI move if self.game.get_status() == "UNFINISHED": game_object = copy.deepcopy(self.game) ai = MiniMax(game_object) ai_move = ai.minimax(game_object) button = self.push_list[ai_move[0]][ai_move[1]] button.setText(self.game.get_O_player()) button.setEnabled(False) self.game.make_move(self.game.get_O_player(), ai_move) else: turn = self.game.get_current_player() if turn == self.game.get_X_player(): button.setText(self.game.get_X_player()) self.game.make_move(self.game.get_X_player(), move) else: button.setText(self.game.get_O_player()) self.game.make_move(self.game.get_O_player(), move) # determine if there is a win or draw win = self.game.get_status() # set the game status label to empty text text = "" if win == "X_WON": text = "X WON" if win == "O_WON": text = "O WON" if win == "DRAW": text = "DRAW" self.label.setText(text) def play_ai(self): if self.is_ai is False: self.player.setText("Click to play against human") self.is_ai = True else: self.player.setText("Click to play against computer") self.is_ai = False app = QApplication(sys.argv) window = Window() sys.exit(app.exec())
# Merge Sort def merge_sort(arg): if len(arg) > 1: mid = len(arg) // 2 lx = arg[:mid] rx = arg[mid:] merge_sort(lx) # Divide Left side merge_sort(rx) # Divide Right side li, ri, i = 0,0,0 while li < len(lx) and ri < len(rx): if lx[li] > rx[ri]: # Compare them arg[i] = rx[ri] ri += 1 else: arg[i] = lx[li] li += 1 i += 1 arg[i:] = lx[li:] if li != len(lx) else rx[ri:] # If left value has exist... a = [] size = int(input('Input Size of List: ')) # Input List's size index = 0 while (index < size): data = int(input('Input List''s data: ')) # Input List's value a.append(data) index += 1 # Before index = 0 while (index < size): print(a[index], end=' ') index += 1 print() # Sorting List merge_sort(a) # After index = 0 while (index < size): print(a[index], end=' ') index += 1
#Problem 15 """ Q. John works at a clothing store and he's going through a pile of socks to find the number of matching pairs. More specifically, he has a pile of n loose socks where each sock i is labeled with an integer, ci, denoting its color. He wants to sell as many socks as possible, but his customers will only buy them in matching pairs. Two socks, i and j, are a single matching pair if they have the same color (ci == cj). Given n and the color of each sock, how many pairs of socks can John sell? Input The first line contains an integer, n, denoting the number of socks. The second line contains n space-separated integers describing the respective values of c0, c1, c2, ... , cn-1. Output Print the total number of matching pairs of socks that John can sell. Sample 9 10 20 20 10 10 30 50 10 20 -> 3 """ def distinct_value(indexes): result = [] for value in list: if value not in result: result.append(value) return result def count_value(indexes, unique_index): pair_count = 0 for i in unique_index: tmpCount = indexes.count(i) pair_count += tmpCount // 2 return pair_count n = int(input()) # 총 양말 갯수 indexes = list(map(int, input().split(" "))) # 각 양말 별 index number unique_index = distinct_value(indexes) # index 종류 확인 count = count_value(indexes, unique_index) print(count)
def solution(record): answer = [] dic = dict() for data in record: cmd = data.split(' ')[0] if cmd == 'Enter' or cmd == 'Change': cust_id = data.split(' ')[1] nick = data.split(' ')[2] dic[cust_id] = nick for data in record: cmd = data.split(' ')[0] cust_id = data.split(' ')[1] if cmd == 'Enter': answer.append(dic[cust_id] + "님이 들어왔습니다.") elif cmd == 'Leave': answer.append(dic[cust_id] + "님이 나갔습니다.") return answer
# Problem 20 """ Q. Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is <=1. Input The first line contains a single integer, n, denoting the size of the array. The second line contains n space-separated integers describing the respective values of a0, a1, ... , an-1. Output A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is <=1. Sample 6 4 6 5 3 3 1 -> 3 """ def find_count(arg): max_count = max((arg.count(x) + arg.count(x + 1) for x in set(arg))) return max_count n = int(input().strip()) a = [int(a_temp) for a_temp in input().strip().split(' ')] result = find_count(a) print(result)
from datetime import date def access(user_birthday): """ Checks the user's age. If more than 13, it allows access, otherwise blocked user. :param user_birthday: user birthday in datetime format :return user access """ if user_birthday: curr_year = date.today().year age = curr_year - user_birthday.year if age > 13: return "Allowed" else: return "Blocked" else: return "Unknown"
#board is a list of rows of the same size. #each entry of board is 0 (invalid move) or 1 (valid move). #the function should return a valid move, for example [0,0] (which is a loosing move, of course) def move(board): import random moves = [] real_width=len(board[0]) for i in range (0,len(board)): for j in range (0,real_width): if i==0 and j==0: continue if board[i][j]==1: moves.append([i,j]) else: real_width=j break if len(moves)==0: return [0,0] return random.choice(moves)
n = int(input()) parents = dict() childs = dict() def read(): cl = input() st = '' for i in range(len(cl)): # разбили на созданный класс и его предков if cl[i] == ' ': st = cl[i + 3:] cl = cl[:i] break if cl not in parents: parents[cl] = set() if st != '': # у нашего класса есть предки pars = st.split() pars1 = set(pars) pars1.update(parents[cl]) for p in pars: # составили полный список родителей класса if p in parents: pars1.update(parents[p]) else: parents[p] = set() chls = set() # составили полный список детей класса if cl in childs: chls = childs[cl] for p in pars1: # всем родителям приписали в дети класс и его детей if p in childs: childs[p].update(chls) childs[p].add(cl) else: childs[p] = set() childs[p].add(cl) childs[p].update(chls) for c in chls: # всем детям класса приписали предков parents[c].update(pars1) parents[cl] = pars1 def search(par, child): if par == child: return 'Yes' if child not in parents: return 'No' if par in parents[child]: return 'Yes' return 'No' for i in range(n): read() n = int(input()) for i in range(n): par, child = input().split() print(search(par, child))
from xml.etree import ElementTree as Et s = input() root = Et.fromstring(s) colors = {'red': 0, 'green': 0, 'blue': 0} def func(elem, val): attr = elem.attrib colors[attr['color']] += val for child in elem: func(child, val + 1) func(root, 1) for val in colors.values(): print(val, end = ' ')
choice_of_operation = input('Enter 1 for addition and 2 for subtraction, enter 3 for multiplication and 4 for division. ') if choice_of_operation == '1': value_1 = input('What is the value of the first number? ') value_2 = input('What is the value of the second number? ') print(float(value_1) + float(value_2)) if choice_of_operation == '2': value_1_sub = input('What is the value of the first number? ') value_2_sub = input('What is the value of the second number? ') print(float(value_1_sub) - float(value_2_sub)) if choice_of_operation == '3': value_1_multi = input('What is the value of the first number? ') value_2_multi = input('What is the value of the second number? ') print(float(value_1_multi) * float(value_2_multi)) if choice_of_operation == '4': value_1_div = input('What is the value of the first number? ') value_2_div = input('What is the value of the second number? ') print(float(value_1_div) / float(value_2_div))
# -*- coding: utf-8 -*- """ Created on Wed Mar 24 09:48:32 2021 @author: raj patil """ for i in range(int(input())): n = input() if n == n[::-1]: print('wins') else: print('loses')
# -*- coding: utf-8 -*- """ Created on Mon Mar 15 13:43:51 2021 @author: raj patil """ t = int(input()) for i in range(t): sum = 0 num = input() sum = sum + int(num)%10 + int(num)//pow(10,len(num) - 1) print(sum)
def gradingStudents(grades): for i in range(len(grades)): current = grades[i] if (current < 38) or (current % 5) < 3: pass else: grades[i] = (current + 5) - (current % 5) return grades # OR # return [max(n, (n + 2) // 5 * 5) if n >= 38 else n for n in grades]
import tkinter as tk import random import sys class Category: def __init__(self,filein,fileout):#contains two parameters:input file and output file wordlist=filein.readlines()#read the document into a list of lines #instance variables include the output file, list of lines, dictionary of advance level difficulty, common level and basic level, and include a list containing wrong words self.fileout=fileout self.wordlist=wordlist self.advance={} self.common={} self.basic={} self.wrong=[] check1=False#create flag variable for item in self.wordlist: if item[:]=="Common Words\n": check1=True elif check1==True and item[:]!="\n": wordkey=item.split(" (")#split the item by "(" into the word and its meaning self.common[wordkey[0]]="("+wordkey[1] if item[:]=="\n": check1=False check2=False for item in self.wordlist: if item[:]=="Basic Words\n": check2=True elif check2==True and item[:]!="\n": wordkey=item.split(" (") self.basic[wordkey[0]]="("+wordkey[1] if item[:]=="\n": check2=False check3=False for item in self.wordlist: if item[:]=="Advanced Words\n": check3=True elif check3==True and item[:]!="\n": wordkey=item.split(" (") self.advance[wordkey[0]]="("+wordkey[1] elif item[:]=="\n": check3=False def spelling(self):#create spelling mode #interact with user let them choose differnt level print("Welcome to the GRE vocabulary spelling mode") n=input("Please choose a mode by typing 1,2 or 3 (1:common, 2:basic, 3:advance):") while(n!="1" and n!="2" and n!="3"):#make sure the unexpected answer won't go through print("I don't understand. Please type 1, 2 or 3.") n=input("Your pick:") while True:#check if the input is a valid positive integer in a while loop try: questionNum=int(input("please type a number that represents the questions you want to take:")) assert(questionNum>0) break except: print("not valid") right=0#keep track of score for i in range (questionNum):#start asking question if n=="1": answer=list(self.common.keys())[random.randint(0,len(self.common)-1)] meaning=self.common[answer] if n=="2": answer=list(self.basic.keys())[random.randint(0,len(self.basic)-1)] meaning=self.basic[answer] if n=="3": answer=list(self.advance.keys())[random.randint(0,len(self.advance)-1)] meaning=self.advance[answer] print("Question",i+1,meaning) userInput=input("Please spell the word of the meaning showing above:") if userInput != answer:#if wrong write the wrong words to a file print("You are wrong, the correct answer is:",answer) self.wrong.append(answer+meaning) else: print("You are right") right+=1#add one if correct print("Your score is",right,"/",questionNum) print("Thanks for studying with me!") self.writeWrong(self.fileout) def multipleChoice(self):#create multiple choice function print("Welcome to the GRE vocabulary multiple choice mode") n=input("Please choose a mode by typing 1,2 or 3 (1:common, 2:basic, 3:advance):") while(n!="1" and n!="2" and n!="3"): print("I don't understand. Please type 1, 2 or 3.") n=input("Your pick:") right=0 while True:#also check if the number is a positive integer try: questionNum=int(input("please type a number that represents the questions you want to take:")) assert(questionNum>0) break except: print("not valid") for num in range (questionNum):#start asking question if n=="1": answer=list(self.common.keys())[random.randint(0,len(self.common)-1)]#randomly choose a word from dictionary meaning=self.common[answer] if n=="2": answer=list(self.basic.keys())[random.randint(0,len(self.basic)-1)] meaning=self.basic[answer] if n=="3": answer=list(self.advance.keys())[random.randint(0,len(self.advance)-1)] meaning=self.advance[answer] print("Question",num+1,meaning) choices=[answer]#a list that contains the correct answer and other choices if n=="1": answerlist=list(self.common.keys()) if n=="2": answerlist=list(self.basic.keys()) if n=="3": answerlist=list(self.advance.keys()) answerlist.remove(answer)#remove the correct answer from the list in case repetition if len(answerlist)>3:#randomly choose three words from the dictionary for i in range(3): idx=random.randint(0,len(answerlist)-1) choices.append(answerlist[idx]) answerlist.pop(idx) else: choices+=answerlist correctPos = random.randint(0, len(choices) - 1)#randomly generate the correct answer's positon tmp = choices[correctPos] choices[correctPos] = choices[0] choices[0] = tmp answerList = 'abcd'#start print the choices for i in range(len(choices)): print(answerList[i] + ") " + choices[i]) userAnswer=input("Your answer: ")#ask user for their answer while(userAnswer!="a" and userAnswer!="b" and userAnswer!="c" and userAnswer!="d"): userAnswer=input("I don't understand. Please type a, b, c, or d.Your answer: ") if userAnswer==answerList[choices.index(answer)]: print("Correct!") right+=1 else: print("Sorry, the correct answer was","'",answer,"'") self.wrong.append(answer+meaning)#add wrong words and its meaning to the list print("Your final score was: ",right, "/",questionNum) print("Thanks for studying with me!") self.writeWrong(self.fileout) def writeWrong(self,fileout):#create a write wrong method that takes wrong words to a output file with its meaning for item in self.wrong: fileout.write(item) def quit(self): self.root.destroy() def main(): fin=open(sys.argv[1],"r")#read input file fout=open(sys.argv[2],"w")#read output file c1=Category(fin,fout)#create a class object #create GUI root = tk.Tk() l1 = tk.Label(root, text="please click spelling or multiple choice mode") f1 = tk.Frame(root) l1.grid(row=0, column=1) f1.grid(row=1, column=1, sticky="nsew") b1 = tk.Button(f1, text="spelling",command=c1.spelling) b2 = tk.Button(f1, text="multiple choice", command=c1.multipleChoice) b1.pack(side="top") b2.pack(side="top") root.mainloop() fin.close()#close file fout.close() main()
import string t0 = dir(string) t = t0 [-5:] print ("This is TUPLE: ", tuple (t)) print ("This is LIST: ",list (t)) t.insert (2,"capwords") print ("The result is: ", tuple (t))
from random import randint def set_doors(): l = ['g','g','g'] a = randint(0,2) l[a] = 'c' return l def player_first_choice(): ''' this code returns an integer that is the player's choice ''' first = randint(0,2) return first def host_show_goat(l,first): ''' this code removes the player's choice(integer) from the possible pool of choices ''' possibilities = [0,1,2] possibilities.remove(first) ''' this code is for when the player chose a goat, we want to find out which other door is the goat for the host to return as another integer ''' if l[first] == 'g': a = l.index('c') possibilities.remove(a) return possibilities[0] if l[first] == 'c': a = randint(0,1) return possibilities[a] def monty_hall(): ''' this code calculates frequency of winning for all choices ''' count_keep = 0 count_change = 0 count_same_prob = 0 i = 0 while i < 1000: poss = [0,1,2] l = set_doors() first = player_first_choice() host = host_show_goat(l,first) if l[first] == 'c': count_keep += 1 poss.remove(host) #remove goat shown by the host, so the elements of the list are for keeping or changing a = randint(0,1) same = poss[a] if l[same] == 'c': count_same_prob += 1 poss.remove(first) #remove player's first choice, so only element in the list is for changing if l[poss[0]] == 'c': count_change += 1 i += 1 return [count_keep/1000,count_change/1000,count_same_prob/1000] def main(): a = monty_hall() print("{:37}{:10}{:12}{:12}".format('','Keep Door','Change Door','Same Chance')) print("{:37}{:7}{:10}{:13}".format('Relative Frequency (1000 simulations)',a[0],a[1],a[2])) if __name__ == '__main__': main()
# Второй максимум # Последовательность состоит из различных натуральных # чисел и завершается числом 0. Определите значение # второго по величине элемента в этой последовательности. # Гарантируется, что в последовательности есть хотя бы # два элемента. max1 = int(input()) max2 = 0 b = 1 while b != 0: b = int(input()) if b > max1 and b > max2: max1, max2 = b, max1 elif b > max2: max2 = b print(max2)
# Високосный год # Дано натуральное число. Требуется определить, является ли год с данным номером високосным. # Если год является високосным, то выведите YES, иначе выведите NO. Напомним, что в # соответствии с григорианским календарем, год является високосным, если его номер кратен 4, # но не кратен 100, а также если он кратен 400. year = int(input()) if (((year % 4) == 0) and ((year % 100) != 0)): print('YES') elif ((year % 400) == 0): print('YES') else: print('NO')
# Удалить элемент # Дан список из чисел и индекс элемента в списке k. # Удалите из списка элемент с индексом k, сдвинув # влево все элементы, стоящие правее элемента с # индексом k. # Программа получает на вход список, затем число k. # Программа сдвигает все элементы, а после этого # удаляет последний элемент списка при помощи метода # pop() без параметров. # Программа должна осуществлять сдвиг непосредственно # в списке, а не делать это при выводе элементов. # Также нельзя использовать дополнительный список. # Также не следует использовать метод pop(k) с # параметром. a_list = [int(i) for i in input().split()] k = int(input()) for i in range(k, len(a_list) - 1): a_list[i] = a_list[i + 1] a_list = a_list[0:len(a_list) - 1] for i in a_list: print(i, end=' ')
# Шахматная доска # Даны два числа n и m. Создайте двумерный массив # размером # n×m и заполните его символами "." и # "*" в шахматном порядке. В левом верхнем углу # должна стоять точка. n, m = [int(i) for i in input().split()] l_list = [['*' for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if (i + j) % 2 == 0: l_list[i][j] = '.' for row in l_list: print(' '.join([str(elem) for elem in row]))
# Утренняя пробежка # В первый день спортсмен пробежал x километров, а затем # он каждый день увеличивал пробег на 10% от предыдущего # значения. По данному числу y определите номер дня, на # который пробег спортсмена составит не менее y километров. # Программа получает на вход действительные числа x и y и # должна вывести одно натуральное число. x = float(input()) y = float(input()) day = 1 while y > x: x = x + x * 0.1 day += 1 print(day)
# Проценты # Процентная ставка по вкладу составляет P процентов # годовых, которые прибавляются к сумме вклада. Вклад # составляет X рублей Y копеек. Определите размер вклада # через год. # Программа получает на вход целые числа P, X, Y и должна # вывести два числа: величину вклада через год в рублях и # копейках. Дробная часть копеек отбрасывается. P = int(input()) X = int(input()) Y = int(input()) coin = X * 100 + Y sum = coin + coin * P / 100 Xres = int(sum // 100) Yres = int(sum % 100) print(str(Xres), str(Yres))
# Часы - 3 # С начала суток часовая стрелка повернулась на # угол в α градусов. Определите сколько полных # часов, минут и секунд прошло с начала суток, # то есть решите задачу, обратную задаче «Часы - # 1». Запишите ответ в три переменные и выведите # их на экран. angle = float(input()) H = angle // 30 M = (angle - H * 30) // 0.5 S = (angle - H * 30 - M * 0.5) // 0.008333333 print(str(H), str(M), str(S))
# Больше своих соседей # Дан список чисел. Определите, сколько в этом # списке элементов, которые больше двух своих # соседей, и выведите количество таких элементов. # Крайние элементы списка никогда не учитываются, # поскольку у них недостаточно соседей. a_list = [int (i) for i in input().split()] count = 0 for i in range(1, len(a_list) - 1): if a_list[i] > a_list[i - 1] and a_list[i] > a_list[i + 1]: count += 1 print(count)
# Минимум из трех чисел # Даны три целых числа. Выведите значение наименьшего из них. a = int(input()) b = int(input()) c = int(input()) if a <= b and a <= c: print(a) elif b <= a and b <= c: print(b) elif c <= a and c <= b: print(c)
# Первая цифра после точки # Дано положительное действительное число X. Выведите # его первую цифру после десятичной точки. import math x = float(input()) first = int((x - int(x)) * 10) print(first)
# Обращение фрагмента # Дана строка, в которой буква h встречается как # минимум два раза. Разверните последовательность # символов, заключенную между первым и последним # появлением буквы h, в противоположном порядке. s = input() h1Pos = s.find('h') hLPos = s.rfind('h') sWithoutH = s[h1Pos + 1:hLPos] sNew = s[0:h1Pos + 1] + sWithoutH[::-1] + s[hLPos:len(s)] print(sNew)
# Шоколадка # Шоколадка имеет вид прямоугольника, разделенного # на n×m долек. Шоколадку можно один раз разломить # по прямой на две части. Определите, можно ли таким # образом отломить от шоколадки часть, состоящую # ровно из k долек. Программа получает на вход три # числа: n, m, k и должна вывести YES или NO. n = int(input()) m = int(input()) k = int(input()) all = n * m if all < k: print('NO') elif (all - k) % n == 0 or (all - k) % m == 0: print('YES') else: print('NO')
from statistics import mean, median, mode, stdev, StatisticsError def prompt(value_type): return input("Please input a {}. Blank line to end: ".format(value_type)) def string_length_stats(strings): lengths =[] for string in strings: lengths.append(len(string)) return {'min':min(lengths),'max':max(lengths),'avg':(sum(lengths)/len(lengths))} def character_counter(string): characters = {} for character in string: if character in characters: characters[character]+=1 else: characters[character]=1 return characters def display_numbers(numbers): print(20*'=') print("You input {} numbers.".format(len(numbers))) print("The numbers sum to {:0.2f}.".format(sum(numbers))) if len(numbers)== 0: print("Average, mean, meadian, mode, and standard deviation are undefined for 0 numbers.") else: print("Their {} is {:0.2f}".format("average",sum(numbers)/len(numbers))) print("Their {} is {:0.2f}".format("mean",mean(numbers))) print("Their {} is {:0.2f}".format('median',median(numbers))) try: print("Their {} is {}".format('mode',mode(numbers))) except StatisticsError: print("This list has no mode.") print("Their {} is {:0.2f}".format('standard deviation',stdev(numbers))) def display_strings(strings): print(20*'=') string_stats = string_length_stats(strings) all_together =''.join(strings) characters = character_counter(all_together) print(all_together) print("That was {} separate strings.".format(len(strings))) print("The shortest string was {} characters.".format(string_stats['min'])) print("The longest string was {} characters.".format(string_stats['max'])) print("The average string was {:0.2f} characters.".format(string_stats['avg'])) if 'e' in characters: print("The letter 'e' was used {} times.".format(characters['e'])) else: print("The letter 'e' was never used.") def number_list(inputs): print("This will be a list of numbers.") while True: user_in = prompt("number") if user_in == "": break else: try: inputs.append(float(user_in)) except ValueError: mixed = input("That was not a number. Do you want to change to a mixed list? [Y/n]") if mixed.lower().startswith('n'): continue else: inputs.append(user_in) mixed_list(inputs) return display_numbers(inputs) def string_list(inputs): print("This will be a list of strings.") while(True): user_in = prompt("string") if user_in =="": break else: try: float(user_in) except ValueError: inputs.append(user_in) else: mixed = input("That was a number. Do you want to change to a mixed list? [Y/n]") if mixed.lower().startswith('n'): continue else: inputs.append(float(user_in)) mixed_list(inputs) return display_strings(inputs) def mixed_list(inputs): print("This is now a mixed list. Your previous entry in now in the list.") while(True): user_in = prompt("value") if user_in =="": break else: try: inputs.append(float(user_in)) except ValueError: inputs.append(user_in) display_strings([x for x in inputs if type(x) is str]) display_numbers([x for x in inputs if type(x) is not str]) inputs = [] first_in = prompt("value") if first_in == "": pass else: try: inputs.append(float(first_in)) except ValueError: string_list([first_in]) else: number_list(inputs) print(20*'='+"\nGoodbye.")
import logging def sum(n): if not n: #empty string logging.debug("empty string. return 0") return 0 else: logging.debug("first digit: {} invoking func with remaining string: {}".format(n[0], n[1:])) intermediate_sum = (int(n[0]) + sum(n[1:])) logging.debug("intermediate_sum: {}".format(intermediate_sum)) return intermediate_sum
password="kevin" guess="" print "WELCOME TO THE KEVSMART ATM, ENJOY YOUR STAY!" print "" while (password!=guess): guess=raw_input("Enter the password: ") print "" print("Access Granted") print "" canaccount=100.00 usaccount=100.00 while True: print "Current value of Canadian account is $",canaccount print "" print "Current value of American account is $",usaccount print "" print "1.Deposit" print "2.Withdraw" print "3.Transfer" print "4.Exit" print "" choice=input("Would you like to do today? ") if (choice==4): print "" print "Thanks for using KEVsmart Account Management, have a nice day!" print "" break if (choice==1): print "" print "1.Canadian" print "2.American" print "" choice1=input("What account would you like to use? ") if (choice1==1): print "" print "You have chosen the Canadian Account." print "" value=input("How much in Canadian Dollars do you want to deposit? ") canaccount=canaccount+value print "" print "You have deposited $",value print "" if (choice1==2): print "" print "You have chosen the American Account." print "" value=input("How much in Canadian Dollars do you want to deposit? ") usaccount=usaccount+value print "" print "You have deposited $",value if (choice==3): print "" print "1.Canadian" print "2.American" print "" choice3=input("Which account would you like to transfer money into?") if (choice3==1): print "" value=input("How much money would you like to transfer into your Canadian Account?: ") usaccount=usaccount-value canaccount=canaccount+value*1.04 print "" print "You have transfered $",value if (choice3==2): print "" value=input("How much money would you like to transfer into your American Account?: ") usaccount=usaccount+value*0.96 canaccount=canaccount-value print "" print "You have transfered $",value print "" if (choice==2): print "" print "1.Canadian" print "2.American" print "" choice2=input("Which account would you like to withdraw money out of?") if (choice2==1): print "" print "You have chosen your Canadian account." print "" value=input("How much money would you like to withdraw from your account?: ") canaccount=canaccount-value print "" print "You have withdrawn $",value print "" if (choice2==2): print "" print"You have chosen your American account." print "" value=input("How money would you like to withdraw from your account?: ") usaccount=usaccount-value print "" print "You have withdrawn $",value print ""
import sqlite3 def db_connect(sqlite_file): """ Make connection to an SQLite database file """ return sqlite3.connect(sqlite_file) def db_close(conn): """ Close connection to the database """ conn.close() def db_init(conn): """ Create table and delete yesterday's not done tasks """ cur = conn.cursor() with conn: # 1 - done, 0 - not cur.execute("""CREATE TABLE IF NOT EXISTS todolist ( task_id INTEGER PRIMARY KEY AUTOINCREMENT, task_name TEXT NOT NULL, task_status INTEGER NOT NULL, date TEXT NOT NULL )""") # If we didn't finish any tasks yesterday they will be deleted automatically the next day cur.execute("DELETE FROM todolist WHERE task_status = 0 AND date < date('now', 'localtime')") def get_current_tasks(conn): """ Get current tasks """ cur = conn.cursor() cur.execute("SELECT task_name FROM todolist WHERE task_status = 0") return cur.fetchall() def insert_task(conn, task_name, task_status): """ Insert task with its status """ cur = conn.cursor() with conn: cur.execute("INSERT INTO todolist (task_name, task_status, date) VALUES (?, ?, date('now'))", (task_name, task_status)) def complete_task(conn, task_name): """ Mark task as complete """ cur = conn.cursor() with conn: cur.execute("UPDATE todolist SET task_status = 1 WHERE task_status = 0 AND task_name = :task_name", {'task_name': task_name}) # We are deleting task in that case when we added one with wrong name or we decided we wouldn't do it today, # so in WHERE clause we check task_status (you can't delete task that already done) and date. def delete_task(conn, task_name): """ Delete task""" cur = conn.cursor() with conn: cur.execute("DELETE FROM todolist WHERE task_status = 0 AND date == date('now', 'localtime') and task_name = :task_name", {'task_name': task_name}) def get_todays_completed_tasks(conn): """ Get today's completed tasks """ cur = conn.cursor() cur.execute("SELECT task_name FROM todolist WHERE task_status = 1 AND date == date('now', 'localtime')") return cur.fetchall()
boletim = list() dados = list() notas = list() while True: print(f'Aluno {len(boletim)+1}: ') dados.append(str(input('Nome: ')).strip().capitalize()) notas.append(float(input('1ª nota: '))) notas.append(float(input('2ª nota: '))) dados.append(notas[:]) boletim.append(dados[:]) notas.clear() dados.clear() op = ' ' while op not in 'SN': op = str(input('Deseja continuar? [S/N]: ')).strip().upper()[0] if op == 'N': break print('-'*40) print(f'{" Boletim ":^40}') print('-'*40) print(f'| No. | {"Aluno":<20} | {"Média":^7} |') print('-'*40) for n, a in enumerate(boletim): print(f'| {n:>3} | {a[0]:<20} | {(a[1][0]+a[1][1])/2:>7.1f} |') print('-'*40) print(f'{f"Quantidade de alunos: {len(boletim)}":>39}') while True: aluno = str(input('\nDigite o nome do aluno para consulta [S=sair]: ')).strip().capitalize() if aluno.upper() == 'S': break for a in boletim: if aluno in a: print(f'Aluno: {a[0]}\n1ª nota: {a[1][0]:>7.1f}\n2ª nota: {a[1][1]:>7.1f}\nMédia: {((a[1][0]+a[1][1])/2):>7.1f}') print('Programa finalizado!')
altura = float(input('Informa a altura (em metros): ')) largura = float(input('Informe a largura (em metros): ')) area = altura * largura print('altura = {:.3f} mt, largura = {:.3f}mt, área = {:.3f} m²'.format(altura, largura, area)) print('serão necessários {:.3f} litros de tinta para a pintura.'.format(area/2))
v = int(input('Informe um valor inteiro: ')) print('O sucessor de {} é {}'.format(v, v+1)) print('O antcessor de {} é {}'.format(v, v-1))
n1 = int(input('Informe o primeiro número: ')) n2 = int(input('Informe o segundo número: ')) n3 = int(input('Informe o terceiro número: ')) nme = n1 nma = n1 if nme > n2: nme = n2 if nme > n3: nme = n3 if nma < n2: nma = n2 if nma < n3: nma = n3 print('O menor número é {} e o menor é {}'.format(nme, nma))