text
stringlengths
37
1.41M
input = [] with open('input.txt') as my_file: for line in my_file: input.append(line.strip()) assert input[0][8] == "#" assert input[2][8] == "." def treesEncountered(map, right, down): i = 0 j = 0 trees = 0 while i < len(input)-1: j += right i += down if map[i][j%len(input[i])] == "#": trees += 1 return trees print("answer", treesEncountered(input, 3, 1))
# I wanted to try making some classes as practice. RUNNING = True RESTING = False class Reindeer: def __init__(self, line): """ :param line: Parses line into the class. :return: nothing """ line = line.split() self.speed = int(line[3]) self.running_time = int(line[6]) self.resting_time = int(line[13]) self.state = RUNNING self.state_timer = int(line[6]) self.distance = 0 self.points = 0 def next_step(self): """ Uses a second of a race. :return: nothing """ if self.state == RUNNING: self.distance += self.speed self.state_timer -= 1 if self.state_timer <= 0: if self.state == RUNNING: self.state = RESTING self.state_timer = self.resting_time else: self.state = RUNNING self.state_timer = self.running_time def add_point(self): """ Adds one point. :return: nothing """ self.points += 1 all_reindeer = [] with open("inputData.txt", "r") as infile: for line in infile: # Make the reindeer objects. all_reindeer.append(Reindeer(line)) for i in range(2503): for reindeer in all_reindeer: reindeer.next_step() # Calculate the largest distance of all the reindeer distances = [x.distance for x in all_reindeer] max_score = max(distances) # Search through the reindeer, and add a point to any reindeer that have travelled the 'largest distance'. for reindeer in all_reindeer: if reindeer.distance == max_score: reindeer.add_point() # Print out the points of the largest reindeer with the most points. final_scores = [x.points for x in all_reindeer] print(max(final_scores))
import itertools data = [] """ Process inputData.txt and put it into the data array. """ with open("inputData.txt", "r") as infile: for line in infile: data.append(int(line)) valid_permutations = 0 def checkIfValid(permutation): return 1 if sum(permutation) == 150 else 0 """ Main loop This is the best explanation I could come up with: 1. For every possible amount of containers (e.g. if there are 4 containers, try 1, 2, 3, and 4) 2. And for every possible combination of that amount of containers """ for i in range(0, len(data)): for permutation in itertools.combinations(data, i): valid_permutations += checkIfValid(permutation) print("Answer: " + str(valid_permutations))
alphabet = list(map(chr, range(97, 123))) dataInput = "hxbxwxba" def increment(a): a_number = letter_number(a) if a_number == 25: return "a" return alphabet[a_number + 1] def full_increment(a): should_increment = True i = len(a) - 1 while should_increment: new_letter = increment(a[i]) a_2 = list(a) a_2[i] = new_letter a = ''.join(a_2) i -= 1 if not new_letter == "a": should_increment = False return a # Test `a` against the rules # 'Passwords must include one increasing straight of at least three letters' def rule_one(a): for i in range(len(a)-2): letters = [letter_number(a[i]), letter_number(a[i+1]), letter_number(a[i+2])] if letters[1] == letters[0] + 1 and letters[2] == letters[0] + 2: return True return False # 'Passwords may not contain the letters i, o, or l' def rule_two(a): return not("i" in a or "o" in a or "l" in a) # 'Passwords must contain at least two different, non-overlapping pairs of letters' def rule_three(a): pairs = 0 incrementer = 0 while incrementer < len(a) - 2: incrementer += 1 if a[incrementer] == a[incrementer + 1]: pairs += 1 incrementer += 1 return pairs >= 2 def all_rules(a): return rule_one(a) and rule_two(a) and rule_three(a) def letter_number(a): return alphabet.index(a) def next_password(a): password = a while not all_rules(password): password = full_increment(password) return password print(next_password(dataInput))
"""Script for taking restaurant.json data and transferring it to MongoDB.""" import sqlite3 import pymongo import json # Username and password to be set by user. username = "TODO" password = "TODO" cluster = "TODO" group = "TODO" # Load json and select data. json_data = open("restaurant.json").read().replace("$", "").split("\n") json_data = [x for x in json_data if x != ""] data = json.loads("[" + ",".join(json_data) + "]") # Access MondoDB, create restaurant db and restaurant collection s = "mongodb+srv://{}:{}@{}-{}.mongodb.net/admin".format(username, password, cluster, group) client = pymongo.MongoClient(s) dbnames = client.list_database_names() if 'restaurant' in dbnames: client.drop_database('restaurant') rest_db = client["restaurant"] x = rest_db["restaurants"].insert_many(data) # Print number of objects added to MongoDB. print(len(x.inserted_ids))
from collections import OrderedDict item = OrderedDict() for _ in range(int(input())): j = input().rpartition(" ") item[j[0]] = int(j[-1]) + item[j[0]] if j[0] in item else int(j[-1]) for k in item: print(k, item[k])
#Read madLibText.txt and show corresponding prompt and let user enter word. #Replace corresponding word in the text and save the result. with open('madLibText.txt') as source: text = source.read() while 'ADJECTIVE' in text: adj = input('Enter an adjective. ') text = text.replace('ADJECTIVE', adj, 1) while 'NOUN' in text: noun = input('Enter a noun. ') text = text.replace('NOUN', noun, 1) while 'VERB' in text: verb = input('Enter a verb. ') text = text.replace('VERB', verb, 1) print(text) with open('madLibResult.txt', 'w') as result: result.write(text)
# backupToZip.py - Copies an entire folder and its contents into # a ZIP file whose filename increments. import os, zipfile def backupToZip(folder): absfolder = os.path.abspath(folder) print('The folder to be zip: %s \n' % absfolder) # Name the zip file number = 1 while True: zipName = os.path.basename(absfolder) + '_' + str(number) + '.zip' if os.path.exists(zipName): number += 1 else: break # Create zip file backupZip = zipfile.ZipFile(zipName, 'w') # Walk through the folder for foldername, subfolders, filenames in os.walk(absfolder): backupZip.write(foldername) for filename in filenames: # Don't add zip file newBase = os.path.basename(absfolder) + '_' if filename.startswith(newBase) and filename.endswith('.zip'): continue filenameInZip = os.path.join(foldername, filename) backupZip.write(filenameInZip) print('Add file: ', filenameInZip) backupZip.close() print('Done') if __name__ == '__main__': backupToZip('.')
#Listas podem conter qualquer tipo de variaveis e um numero infinito de variaveis #Delcarar que e uma lista mylist = [] mylist.append(1) mylist.append(2) mylist.append(3) #Ou entao poderia ser usado desta forma #mylist = [1,2,3] print(mylist[0]) print(mylist[1]) print(mylist[2]) print("---- Break ----") mylist.append(4) mylist.append(5) mylist.append(6) for x in mylist: print(x) #Outra forma de imprimir seria print("\nOutra forma de imprimir os valores que estao dentro da lista") print(mylist) #Tentar aceder a um index que nao existe gera um erro obviamente mylist = [1,2,3] #print(mylist[10])
#O Python usa exceptions para fazer o tratamento de erros #As vezes quando encontramos erros nao queremos fazer algo por isso para resolver devemos usar um try/except block def do_stuff(n): print(n) the_list = (1, 2, 3, 4, 5) for i in range(20): try: do_stuff(the_list[i]) except IndexError: #Erro criado quando tentamos aceder a um index que nao existe print("Bateu num index que nao existe") do_stuff(0) #Lista de exceptions --> https://docs.python.org/3/library/exceptions.html #Pode dar jeito --> https://docs.python.org/3/tutorial/errors.html#handling-exceptions
#Sets sao listas que nao tem valores duplicados print(set("My name is Eric and Eric is my name".split())) print #Nota-se que o output e uma lista sem palavras repetidas #Sets sao uma ferramenta poderosa porque permite veridicar dois sets independentes e determinar se existem alguns valores repetidos entre ambos a = set(["Jake","John","Eric"]) b = set(["John","Jill"]) print(a.intersection(b)) print(b.intersection(a)) print #O oposto da intersection entre dois sets print(a.symmetric_difference(b)) print(b.symmetric_difference(a)) print #Para determinar quais dos elementos sao exclusivos a uma dos sets print(a.difference(b)) print(b.difference(a)) print #Obter uma lista da interseccao de todos os valores sem repetidos print(a.union(b)) print
''' A function called predict_with_network() which will generate predictions for multiple data observations. The function called predict_with_network() accepts two arguments - input_data_row and weights - and returns a prediction from the network as the output. ''' import numpy as np input_data = np.array([2,3]) weights = {'node_0' : np.array([1,1]), 'node_1' : np.array([-1,1]), 'output' : np.array([2,-1])} def relu(input): # Calculate the value for the output of the relu function: output output = max(input, 0) # Return the value just calculated return(output) def predict_with_network(input_data_row, weights): # Calculate node 0 value node_0_input = (input_data_row * weights['node_0']).sum() node_0_output = relu(node_0_input) # Calculate node 1 value node_1_input = (input_data_row * weights['node_1']).sum() node_1_output = relu(node_1_input) # Put node values into array: hidden_layer_outputs hidden_layer_outputs = np.array([node_0_output, node_1_output]) # Calculate model output input_to_final_layer = (hidden_layer_outputs * weights['output']).sum() model_output = relu(input_to_final_layer) # Return model output return(model_output) # Create empty list to store prediction results results = [] for input_data_row in input_data: # Append prediction to results results.append(predict_with_network(input_data_row, weights)) # Print results print(results)
# 1. print(3**4) # 2. def to_power(num, pow_num): return pow(num, pow_num) print(to_power(3, 3)) # 3. def to_power(num, pow_num): result = 1 for index in range(pow_num): result *= num return result print(to_power(3, 2))
sticks: int = 10 users = [] while len(users) < 2: users.append(input('please write your name: ')) cur_user = 0 while sticks > 1: while True: move = input('{user} please enter number from 1 to 3: '.format(user = users[cur_user])) if int(move) > 3 or int(move) < 1: print('wrong number') else: break sticks -= int(move) print("{user} removed {move} sticks, on the table now {sticks}".format(user = users[cur_user], move = move, sticks = sticks)) if cur_user == 0: cur_user = 1 else: cur_user = 0 if sticks == 1: print('{} is lost'.format(users[cur_user]))
testcase = int(input()) i = 0 while i != testcase: a, b = [int(k) for k in input().split()] N = int(input()) n = 0 recive = "GGWP" start = a+1 #upper stop = b while (recive != "CORRECT") and recive != "WRONG_ANSWER" and n !=N: mid = int((start+stop)/2) print(mid) recive = str(input()) if recive == "TOO_SMALL": start = mid+1 elif recive == "TOO_BIG": stop = mid-1 n+=1 i+= 1
import math import random BOARD_SIZE = 3 PLAYER_KEY = 'x' COMPUTER_KEY = 'o' EMPTY_KEY = ' ' def create_board(size): # Creates 1-dimensional game board for storing played values. 0 is empty, # -1 is the computer played value, 1 is the player value. return [0] * size ** 2 def board_to_string(board): # converts the numeric values of the game board to 'x', 'o', and blank # space. Adds column numbers and row letters for easy input of cell row_length = int(math.sqrt(len(board))) board_str = '' for k in range(row_length + 1): board_str += ' ' + str(k) + ' ' board_str += '\n' for i in range(row_length): row_string = ' ' + chr(65 + i) + ' ' for j in range(row_length): key = EMPTY_KEY if board[i * row_length + j] == 1: key = PLAYER_KEY elif board[i * row_length + j] == -1: key = COMPUTER_KEY row_string += '[' + key + ']' board_str += row_string + '\n' return board_str def get_column(board): row_length = int(math.sqrt(len(board))) while True: column_str = input('Choose a column (1, 2, etc): ') if column_str.isnumeric() and\ int(column_str) - 1 in range(row_length): return int(column_str) - 1 print('Sorry, please input a number between 1 and ' + str(row_length) + ': ') def get_row(board): row_length = int(math.sqrt(len(board))) while True: row_str = input('Choose a row (A, B, etc): ').upper() if len(row_str) == 1 and ord(row_str) - 65 in range(row_length): return ord(row_str) - 65 print('Sorry, please input a letter between A and ' + str(chr(64 + row_length)) + ': ') def valid_move(row, col, board): size = int(math.sqrt(len(board))) index = row * size + col return board[index] == 0 def make_move(row, col, board, player): size = int(math.sqrt(len(board))) index = row * size + col if player == 'Player': board[index] = 1 elif player == 'Computer': board[index] = -1 def get_choice(player, board): size = int(math.sqrt(len(board))) if player == 'Player': column = get_column(board) row = get_row(board) elif player == 'Computer': column = random.randint(0, size - 1) row = random.randint(0, size - 1) return column, row def game_turn(player, board): while True: column, row = get_choice(player, board) if valid_move(row, column, board): make_move(row, column, board, player) return board if player == 'Player': print('Sorry, that spot\'s been taken, try again: ') WINNING_PATHS = [ # rows [0, 1, 2], [3, 4, 5], [6, 7, 8], # columns [0, 3, 6], [1, 4, 7], [2, 5, 8], # diagonals [0, 4, 8], [2, 4, 6] ] def check_win(board): # To be called after player and computer turns. Returns True if 3 in a row # is made from turn just played. Returns False if no win is detected, and # returns None if there is a tie. for path in WINNING_PATHS: check_sum = 0 for i in range(len(path)): check_sum += board[path[i]] if abs(check_sum) == 3: return True # Check for full board if no wins, indicates a tie if 0 not in board: return None return False print('Welcome to Heidi\'s Tic-Tac-Toe game!') game_board = create_board(BOARD_SIZE) print(board_to_string(game_board)) players = ['Player', 'Computer'] game_complete = False while game_complete is False: for player in players: print('Turn: ' + player) game_board = game_turn(player, game_board) print(board_to_string(game_board)) turn_result = check_win(game_board) if turn_result: print(player + ' wins!') game_complete = True break if turn_result is None: print('Catscratch! Nobody wins.') game_complete = True break
import datetime import pandas as pd pos_orders = open("pos_orders.txt", "a") clock = datetime.datetime.now() print("Lo's Concessions!") employeeID = input("Enter employee ID: ") print("Welcome, " + employeeID + "!") print(clock) menu = {'Item': ["Hamburger", "Cheeseburger", "Hotdog", "Chili Cheese Dog", "Cheese Pizza", "Pepperoni Pizza", "Nachos", "Salted Pretzel", "Popcorn", "Boxed Candy", "Bottled Soda", "Bottled Water"], 'Price': [3.00, 4.50, 3.00, 5.00, 3.50, 4.50, 6.00, 3.00, 2.50, 4.00, 3.00, 3.00]} df = pd.DataFrame(menu) df.index += 1 print(df) question = input("Are you ready to order? ") total = 0 while question == 'yes' or 'y': pos_orders = open("pos_orders.txt", "a") order = int(input("What would you like? ")) if order == 1: print("If you're done ordering, press 0.") total = total + 3.0 pos_orders = open("pos_orders.txt", 'a') pos_orders.write("Hamburger" + '\n') pos_orders.close() print(total) continue elif order == 2: print("If you're done ordering, press 0.") total = total + 4.5 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Cheeseburger" + '\n') pos_orders.close() print(total) continue elif order == 3: print("If you're done ordering, press 0.") total = total + 3.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Hotdog" + '\n') pos_orders.close() print(total) continue elif order == 4: print("If you're done ordering, press 0.") total += 5.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Chili Cheese Dog" + '\n') pos_orders.close() print(total) continue elif order == 5: print("If you're done ordering, press 0.") total += 3.5 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Cheese Pizza" + '\n') pos_orders.close() print(total) continue elif order == 6: print("If you're done ordering, press 0.") total += 4.5 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Pepperoni Pizza" + '\n') pos_orders.close() print(total) continue elif order == 7: print("If you're done ordering, press 0.") total += 6.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Nachos" + '\n') pos_orders.close() print(total) continue elif order == 8: print("If you're done ordering, press 0.") total += 3.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Salted Pretzel" + '\n') pos_orders.close() print(total) continue elif order == 9: print("If you're done ordering, press 0.") total += 2.5 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Popcorn" + '\n') pos_orders.close() print(total) continue elif order == 10: print("If you're done ordering, press 0.") total += 4.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Boxed Candy" + '\n') pos_orders.close() print(total) continue elif order == 11: print("If you're done ordering, press 0.") total += 3.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Bottled Soda" + '\n') pos_orders.close() print(total) continue elif order == 12: print("If you're done ordering, press 0.") total += 3.0 pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Bottled Water" + '\n') pos_orders.close() print(total) continue elif order == 0: print(total) pos_orders = open("pos_orders.txt", "a+") pos_orders.write("Total: ") pos_orders.write(str(total)) pos_orders.write('\n') pos_orders.write('\n') pos_orders.close() break
a score = (mean of sample1 - mean)/std_deviation print("the a score is =", a_score) mean of sampling distribution:- 50.69924 Standard deviation of sampling distribution:- 2.879529182125215 Mean of sample1:- 50.41 the a score is = -0.10044697646944323 def_random_set_of_mean(counter): dataset = [] for i in range(0,counter) def random_set_of_mean(counter): dataset = [] for i in range(0, counter): random_index= random.randint(0,len(data)) value = data[random_index] dataset.append(value) mean = statistics.mean(dataset) return mean def setup(): mean_list = [] for i in range(0,250): set_of_means= random_set_of_mean(30) mean_list.append(set_of_means) show_fig(mean_list) def show_fig(mean_list): df = mean_list fig = ff.create_distplot([df], ["temp"], show_hist=False) fig.show() #this is to find both the standard deviation and ending values first_std_deviation_start, first_std_deviation_end = mean-std_deviation, mean+std_deviation second_std_deviation_start, second_std_deviation_end = mean-(2*std_deviation), mean+(2*std_deviation) third_std_deviation_start, third_std_deviation_end = mean-(3*std_deviation), mean+(3*std_deviation) print("std1" ,first_std_deviation_start, first_std_deviation_end) print("std2" ,second_std_deviation_start, second_std_deviation_end) print("std3" ,third_std_deviation_start, third_std_deviation_end) #this is to plot the graph with the traces fig = ff.create_distplot([mean_list], ["absent students"], show_hist=False) fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode="line", name="MEAN")) fig.add_trace(go.Scatter(x=[first_std_deviation_start, first_std_deviation_start], y=[0, 0.17], mode="line", name="MEAN")) fig.add_trace(go.Scatter(x=[first_std_deviation_start, first_std_deviation_start], y=[0, 0.17], mode="line", name="MEAN")) fig.add_trace(go.Scatter(x=[second_std_deviation_start, second_std_deviation_start], y=[0, 0.17], mode="line", name="MEAN")) fig.add_trace(go.Scatter(x=[second_std_deviation_start, second_std_deviation_start], y=[0, 0.17], mode="line", name="MEAN")) fig.add_trace(go.Scatter(x=[third_std_deviation_start, third_std_deviation_start], y=[0, 0.17], mode="line", name="MEAN")) fig.add_trace(go.Scatter(x=[third_std_deviation_start, third_std_deviation_start], y=[0, 0.17], mode="line", name="MEAN")) fig.show()
import numpy as np class Paraboloid: """ Square function. f(x,y) = \frac{x^2}{a^2} + \frac{y^2}{b^2} dx = \frac{2x}{a^2} dy = \frac{2y}{b^2} """ def __init__(self,a=1,b=1): """ Args: - a,b (int|float): Curvature controls """ self.a = a self.b = b self.dx = None self.dy = None def calculate(self,x,y): """ Calculates the square of the function and calculates its gradient. This function is intended for single steps. If you want to calculate the Z value use the "function" method. """ self.gradient(x,y) z = self.function(x,y) return(z) def gradient(self,x,y): """ Calculates the gradient of the function. """ self.dx = (2*x)/np.power(self.a,2) self.dy = (2*y)/np.power(self.b,2) def function(self,x,y): """ Calculates the square of the function. """ pt1 = np.power(x,2)/np.power(self.a,2) pt2 = np.power(y,2)/np.power(self.b,2) z = pt1 + pt2 return(z) class HyperbolicParaboloid: """ Saddle surface. f(x,y) = x^2 - y^2 Gradients: dx = 2x dy = -2y """ def __init__(self): """ """ self.dx = None self.dy = None def calculate(self,x,y): """ Calculates the square of the function and calculates its gradient. This function is intended for single steps. If you want to calculate the Z value use the "function" method. """ self.gradient(x,y) z = self.function(x,y) return(z) def gradient(self,x,y): """ Calculates the gradient of the function. """ self.dx = 2*x self.dy = -2*y def function(self,x,y): """ Calculates the square of the function. """ z = np.power(x,2) - np.power(y,2) return(z) class MonkeySaddle: """ Saddle surface. f(x,y) = x^3 - 3xy^2 Gradients: dx = 3x^2 - 3y^2 dy = -6xy """ def __init__(self): """ """ self.dx = None self.dy = None def calculate(self,x,y): """ Calculates the square of the function and calculates its gradient. This function is intended for single steps. If you want to calculate the Z value use the "function" method. """ self.gradient(x,y) z = self.function(x,y) return(z) def gradient(self,x,y): """ Calculates the gradient of the function. """ self.dx = 3*np.power(x,2) - 3*np.power(y,2) self.dy = -6*x*y def function(self,x,y): """ Calculates the square of the function. """ z = np.power(x,3) - 3*x*np.power(y,2) return(z) class Rosenbrock: """ Vizualization in x_range [-3,3], y_range [-0,4] Formulation: f(x,y) = (a - x)^2 - b(y - x^2)^2 ----- (a-x)^2 = a^2 - 2ax + x^2 (y-x^2)^2 = y^2 - 2x^2y + x^4 ----- f(x,y) = a^2 - 2ax + x^2 + by^2 - 2bx^2y + bx^4 Gradients: dx = -2a + 2x - 4bxy + 4bx^3 dy = 2by - 2bx^2 """ def __init__(self,a=1,b=1): """ """ self.dx = None self.dy = None self.a = a self.b = b def calculate(self,x,y): """ Calculates the square of the function and calculates its gradient. This function is intended for single steps. If you want to calculate the Z value use the "function" method. """ self.gradient(x,y) z = self.function(x,y) return(z) def gradient(self,x,y): """ Calculates the gradient of the function. """ self.dx = -2*self.a + 2*x - 4*self.b*x*y + 3*self.b*np.power(x,3) self.dy = 2*self.b*y - 2*self.b*np.power(x,2) def function(self,x,y): """ Calculates the square of the function. """ pt1 = self.a - x pt2 = y - np.power(x,2) z = np.power(pt1,2) + self.b*np.power(pt2,2) return(z) class Balea: """ Vizualization in x_range [-4,4], y_range [-4,4] Formulation: f(x,y) = (1.5 - x + xy)^2 + (2.25 - x + xy^2)^2 + (2.625 - x + xy^3)2 ----- (1.5 - x + xy)^2 = 2.25 - 1.5x + 1.5xy - 1.5x + x^2 - x^2y + 1.5xy - x^2y + x^2y^2 = 2.25 - 3x + 3xy + x^2 -2x^2y + x^2y^2 (2.25 - x + xy^2)^2 = 5.0625 - 2.25x + 2.25xy^2 - 2.25x + x^2 - x^2y^2 + 2.25xy^2 - x^2y^2 + x^4y^4 = 5.0625 - 5.5x + x^2 + 5.5xy^2 - 2x^2y^2 + x^4y^4 (2.625 - x + xy^3)2 = 6.890625 - 2.625x + 2.625xy^3 - 2.625x + x^2 - x^2y^3 + 2.625xy^3 - x^2y^3 + x^2y^6 = 6.890625 - 5.25x + x^2 + 5.25xy^3 - 2x^2y^3 + x^2y^6 ----- f(x,y) = 14.203125 - 13.75x + 3x^2 + 3xy - 2x^2y + 5.5xy^2 + 5.25xy^3 - x^2y^2 - 2x^2y^3 + x^2y^6 + x^4y^4 Gradients: dx = -13.75 + 6x + 3y - 4xy + 5.5y^2 + 5.25y^3 - 2xy^2 - 4xy^3 + 2xy^6 + 4x^3y^4 dy = 3x - 2x^2 + 11xy + 15.75xy^2 - 2x^2y - 6x^2y^2 + 6x^2y^5 + 4x^4y^3 """ def __init__(self): """ """ self.dx = None self.dy = None def calculate(self,x,y): """ Calculates the square of the function and calculates its gradient. This function is intended for single steps. If you want to calculate the Z value use the "function" method. """ self.gradient(x,y) z = self.function(x,y) return(z) def gradient(self,x,y): """ Calculates the gradient of the function. """ self.dx = -13.75 + 6*x + 3*y - 4*x*y + 5.5*np.power(y,2) + 5.25*np.power(y,3) self.dx += -2*x*np.power(y,2) - 4*x*np.power(y,3) + 2*x*np.power(y,6) self.dx += 4*np.power(x,3)*np.power(y,4) self.dy = 3*x - 2*np.power(x,2) + 11*x*y + 15.75*x*np.power(y,2) - 2*np.power(x,2)*y self.dy += -6*np.power(x,2)*np.power(y,2) + 6*np.power(x,2)*np.power(y,5) self.dy += 4*np.power(x,4)*np.power(y,3) def function(self,x,y): """ Calculates the square of the function. """ z = 4.203125 - 13.75*x + 3*np.power(x,2) + 3*x*y - 2*np.power(x,2)*y + 5.5*x*np.power(y,2) z += 5.25*x*np.power(y,3) - np.power(x,2)*np.power(y,2) - 2*np.power(x,2)*np.power(y,3) z += np.power(x,2)*np.power(y,6) + np.power(x,4)*np.power(y,4) return(z)
# -*- encoding: utf-8 -*- print "Program za vnos dnevnega menija." jedilni_list = "meni.txt" dnevni_meni = {} while True: ime_jedi = raw_input("Vnesite ime jedi: ") cena_jedi = raw_input("Vnesite ceno jedi: ") dnevni_meni[ime_jedi] = cena_jedi print("Danes na meniju: " + ime_jedi + " " + str(cena_jedi)+"€") nadaljuj = raw_input("Želite vnesti še kakšno jed? Da/Ne ") print if nadaljuj.lower() == "ne": break with open("meni.txt", "w+") as meni_file: for jed in dnevni_meni: meni_file.write("- " + ime_jedi + " : " + str(cena_jedi) + "€" + "\n")
''' A lambda function can take any number of arguments, but can only have one expression. to run this code: $ python3 lamda_function.py ''' def power(num): return lambda a : a**num test = power(2) test2 = test(5) print(test2)
classmates = {'Ala': 'Moja niunia', 'Konrad': 'Ziomeczek', 'Wojtek': 'Kryminalista'} for key,value in classmates.items(): print(key + ' ' + value)
import random c = int(input('What number you want to start from?\n')) d = -1 while c > d: d = int(input('What number should be the last one? (Cant be lesser than starting one)\n')) a = random.randint(c,d) b = int(input('Input a number beetwen ' + str(c) + ' and ' + str(d) + '\n')) while a != b: print(a) if b > a: print('Your number is higher than generated\n') elif b < a: print('Your number is lesser than generated\n') b = int(input('Input a number beetwen ' + str(c) + ' and ' + str(d) + '\n')) print('You guessed it\n')
"""Analyze the word frequencies in a book downloaded from Project Gutenberg.""" import string def get_word_list(file_name): """Read the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. All words are converted to lower case. """ pass def get_top_n_words(word_list, n): """Take a list of words as input and return a list of the n most frequently-occurring words ordered from most- to least-frequent. Parameters ---------- word_list: [str] A list of words. These are assumed to all be in lower case, with no punctuation. n: int The number of words to return. Returns ------- int The n most frequently occurring words ordered from most to least. frequently to least frequentlyoccurring """ pass if __name__ == "__main__": print("Running WordFrequency Toolbox") print(string.punctuation)
#연습문제 4-1 #coding=utf-8 #1 print("#1") def is_odd(num): result = num % 2 if result == 1: print("홀수") else: print("짝수") is_odd(3) is_odd(4) #2 print("#2") def avg(*args): sum = 0 for i in args: sum += i return sum / len(args) print(avg(1,2,3,4,5,6,7,8,9,10)) #3 print("#3") def googoodan(num): for i in range(1, 10): print(f"{num}X{i}={num * i}") googoodan(8) #4 print("#4") def fib(num): if num == 0: return 0 elif num == 1: return 1 else: return fib(num - 1) + fib(num - 2) print(fib(3)) #5 print("#5") myfunc = lambda numbers: [number for number in numbers if number > 5] print(myfunc([2,3,4,5,6,7,8]))
# 연습문제 2-5 # coding=utf-8 # 1 print("#1") a = {'name': '홍길동', 'birth': '1128', 'age': '30'} print(a) # 2 print("#2") a = dict() a['name'] = 'python' a[('a',)] = 'python' # a[[1]] = 'python' 리스트는 변하는 값 a[250] = 'python' print(a) # ※ Key에는 변하지 않는 값을 사용하고, Value에는 변하는 값과 변하지 않는 값 모두 사용할 수 있다. # 3 print("#3") a = {'A': 90, 'B': 80, 'C': 70} print(a['B']) del a['B'] # a.pop('B') print(a) # 4 print("#4") a = {'A': 90, 'B': 80} print(a.get('C', 70)) # 5 print("#5") a = {'A': 90, 'B': 80, 'C': 70} a1 = list(a.values()) a1.sort() print(a1[0]) print(min(a.values())) # 6 print("#6") a = {'A': 90, 'B': 80, 'C': 70} a1 = list(a.items()) a1.sort() print(a1)
from copy import deepcopy #연습문제 2-8 #coding=utf-8 #1 print("#1") a = [1, 2, 3] b = [1, 2, 3] print(a is b) #False : 각 변수가 가리키는 매모리의 주소가 다름 print(id(a)) print(id(b)) #2 print("#2") a = [1, 2, 3] b = a print(a is b) #True : 변수가 가리키는 메모리의 주소가 같다 print(id(a)) print(id(b)) #3 print("#3") a = b = [1, 2, 3] a[1] = 4 print(b) #b[1] 도 4로 바뀐다 : a와 b가 같은 메모리 주소를 가리키기 때문 #a = [1, 2, 3] #b = a 과 같다 print(id(a)) print(id(b)) #4 print("#4") a = [1, 2, 3] b = a[:] print(a is b) #False : a와 b의 메모리 주소가 다르며 b = a[:]은 a를 복사한것과 같다 #5 print("#5") a = [1, 2, 3] b = a[:] a[1] = 4 print(b) #a=[1,4,3] b=[1,2,3] #6 print("#6") a = [1, 2, 3] print(id(a)) a = a + [4,5] print("+연산: "+str(id(a))) #a=[1, 2, 3, 4, 5] a = [1, 2, 3] print(id(a)) a.extend([4, 5]) print("extend: "+str(id(a))) #a=[1, 2, 3, 4, 5] #7 print("#7") a = [1, [2, 3], 4] b = a[:] a[1][0] = 5 #a=[1, [5, 3], 4] print(b) #b=[1,[5,3],4] : b = a[:]는 2depth 이상의 리스트는 copy하지 못함 a = [1, [2, 3], 4] b = deepcopy(a) a[1][0] = 5 #a=[1, [5, 3], 4] print(b)
#튜플 #data=(10,20,30,40,50) # data=10,20,30,40,50 # 소괄호를 사용 안해도 괜찮다 # print(data[0]) # # data[1] = 200 / 변경이 불 가능하다 #두 수를 바꾸기 (순서) # a=10;b=20 # # temp=a # a=b # b=temp # # print(a,b) # 패킹과 언패킹 a=10;b=20; b,a=a,b print(a,b) a= 1; b=2; c=3 a,b,c=c,a,b print(a,b,c)
#모듈 # import time # print(time.localtime().tm_year,'년',time.localtime().tm_mon,'월',time.localtime().tm_hour,'시',time.localtime().tm_min,'분',time.localtime().tm_sec,'초',end='') # print(time.localtime().tm_year,'년') # print(time.localtime().tm_mon,'월') # print(time.localtime().tm_hour,'시') # print(time.localtime().tm_min,'분') # print(time.localtime().tm_sec,'초') # import datetime # now = datetime.datetime.now() # print(now) # print(now.strftime('%Y-%m-%d %H:%M:%S')) # from datetime import datetime # now =datetime.now() # print(now) # print(now.strftime('%Y-%m-%d %H:%M:%S')) #time 모듈 실습 # 1초마다 화면에 타이머를 출력 # #sleep 함수 : 프로그램 실행 속도를 제어 # import time # print('시작') # time.sleep(3) # print('3초지남') #time 모듈 실습 # 1초마다 화면에 타이머를 출력 # import time # sec = int(input('몇초')) # print("타이머시작") # for x in range(1,sec+1): # time.sleep(1) # print(x,"초") # print("타이머종료") # from time import sleep # sec = int(input('몇초')) # print("타이머시작") # for x in range(1,sec+1): # 5sleep(1) # print(x,"초") # print("타이머종료") #난수모듈 #주사위 게임 # awin=0 # bwin=0 # import random # while True : # a = random.randint(1, 6) # b = random.randint(1, 6) # if a>b:awin+1 # print('a가 이겼습니다') # if a<b:bwin+1 # print('b가 이겼습니다') # if awin or bwin==3: # break #sample() # import random # print(random.sample(range(1,46),6)) #choice() # import random # print(random.choice(['가위','바위','보'])) # # # #shiffle():섞는다 # data=['나비','벌','나비','벌','꽃','꽃'] # random.shuffle(data) # print(data) import turtle turtle.shape('turtle') turtle.color('red') for x in range(8): turtle.forward(100) turtle.right(90) turtle.done()
from tictactoe import TicTacToeGame import ast from draw_board import draw_board import matplotlib.pyplot as plt if __name__ == '__main__': tt = TicTacToeGame() tie = None winner = None players = ['x', 'o'] current_player = 1 draw_board(tt.board) while winner is None and tie is None: current_player = 1 - current_player position = input('Input {}\'s move: '.format(players[current_player])) position = ast.literal_eval(position) tt.make_move(player = players[current_player], position = position) # Close the old plot plt.close() draw_board(tt.board) # tt.pretty_print_board() winner = tt.check_for_winner() tie = tt.check_for_tie() if winner != None: print('{} wins'.format(players[current_player])) elif tie != None: print('The game is a draw') # Keep final plot open until pressing enter input('Press Enter to exit.')
from estudiante import cargar_datos, cargar_datos_corto def verificar_numero_alumno(alumno): # Levanta la excepción correspondiente numero_alumno = alumno.n_alumno if alumno.carrera == "Ingeneria": digito_carrera = "63" elif alumno.carrera == "College": digito_carrera = "61" if numero_alumno.isalnum: if numero_alumno[-1] == "J": pass else: raise ValueError("El numero de alumno es incorrecto") if numero_alumno[0] + numero_alumno[1] == str(alumno.generacion)[-2:]: if numero_alumno[2] + numero_alumno[3] == digito_carrera: pass else: raise ValueError("El numero de alumno es incorrecto") return True def corregir_alumno(estudiante): # Captura la excepción anterior try: verificar_numero_alumno(estudiante) except ValueError as error: print(f"Error: {error}") print("El numero esta malo, arreglando...") if estudiante.carrera == "Ingeniería": digito_carrera = "63" elif estudiante.carrera == "College": digito_carrera = "61" elif estudiante.carrera == "Profesor": digito_carrera = "60" estudiante.n_alumno = str(estudiante.generacion)[2] + str(estudiante.generacion)[3] + digito_carrera else: print("El codigo esta correcto!") finally: print(estudiante.nombre + " esta correctamente inscrite en el curso, todo en orden \n") # ************ def verificar_inscripcion_alumno(n_alumno, base_de_datos): # Levanta la excepción correspondiente if n_alumno not in base_de_datos: raise KeyError("El numero de alumno no se encuentra en la base de datos.") return base_de_datos[n_alumno] def inscripcion_valida(estudiante, base_de_datos): # Captura la excepción anterior try: verificar_inscripcion_alumno(estudiante.n_alumno,base_de_datos) except KeyError: print("¡Alerta! ¡Puede ser Dr. Pinto intentando atraparte!\n") # ************ def verificar_nota(alumno): # Levanta la excepción correspondiente if not isinstance(alumno.promedio, float): raise TypeError("El promedio no tiene el tipo correcto") return True def corregir_nota(estudiante): # Captura la excepción anterior try: verificar_nota(estudiante) except TypeError as error: print(f"Error: {error}") estudiante.promedio = str(estudiante.promedio).replace(",",".") estudiante.promedio = float(estudiante.promedio) finally: print("Procediendo a hacer git hack sobre " + str(estudiante.promedio) + "...\n") if __name__ == "__main__": datos = cargar_datos_corto("alumnos.txt") # Se cargan los datos for alumno in datos.values(): if alumno.carrera != "Profesor": corregir_alumno(alumno) inscripcion_valida(alumno, datos) corregir_nota(alumno)
from funciones import checkear_apodo, crear_mapas, ranking from juego import jugar x = True class Jugador: def __init__(self,apodo,mapa): self.apodo = apodo self.mapa = mapa self.barcos_derrivados = 0 while x: # Este while corresponde al funcionamiento del programa print(" ","-- Menu de inicio --","","¿Que desea hacer?","[0] Iniciar partida","[1] Ver Ranking de puntajes","[2] Salir del programa",sep="\n") a = 0 while a != 2: # Este while corresponde a cualquier opcion que no sea el menu de inicio. a = input() if a == "0": # En este caso se inicia la partida # Partida: print("Ingrese un apodo:") apodo = input() check = checkear_apodo(apodo) if check[1]: # check[1] es un bool, en este caso el juego se ejecuta ya que el apodo esta correcto apodo = check[0] print("Ingrese Las dimensiones del tablero, primero las filas, y luego las columnas.") while x: # Ingreso de Filas y columnas, es un loop para prevenir el caso en que se equivoque en poner los numeros. print("Filas:") f = input() permitidos = "3456789101112131415" if f not in permitidos: # Para prevenir el caso de que no se ponga el comando valido print("Ingrese un numero valido") continue if int(f) < 3 or int(f) > 15: print("El tablero debe tener entre 3 y 15 filas, ingrese nuevamente") continue break while x: print("Columnas:") c = input() permitidos = "3456789101112131415" if c not in permitidos: print("Ingrese un numero valido") continue if int(c) < 3 or int(c) > 15: print("El tablero debe tener entre 3 y 15 columnas, ingrese nuevamente") continue break mapa = crear_mapas(f,c) computador = Jugador("computador",mapa[0]) usuario = Jugador(apodo,mapa[1]) juego = jugar(computador,usuario,c) # el mapa[0] corresponde al mapa del computador if juego[0] == "g": with open("puntajes.txt","a") as guardar: texto = "\n" + apodo + "," + str(juego[1]) guardar.write(texto) guardar.close() a = 2 if juego[0] == "p": a = 2 if juego[0] == "rendir": with open("puntajes.txt","a") as guardar: texto = "\n" + apodo + "," + str(juego[1]) guardar.write(texto) guardar.close() print("Te has rendido! de todas formas tu puntaje fue", juego[1]) a = 2 elif juego == "salir": x = False a = 2 else: # Si check no era True, se vuelve al menu de inicio. break elif a == "1": # En este caso se presenta el Top Ranking del momento. print("-- Ranking puntajes -- \n") ranking() print("","[0] volver al inicio", "[1] Cerrar programas",sep="\n") while x: # Loop por si se equivoca opcion = input() if opcion == "0": a = 2 break elif opcion == "1": x = False a = 2 continue else: print("comando invalido") continue elif a == "2": # En este caso se cierra el programa. print("Adios") x = False break else: # Este es en caso de que se equivoque en ingresar un comando. print("Comando invalido, intentelo de nuevo") continue
# class math # กลุ่มคำลั่ง คณิตศาสตร์ import math #import function math มาฃใช้ num = math.pow(2,3) #คำสั่งยกกำลัง 2^3 จะได้=8 print (num) num1 = math.sqrt(25) #คำสั่งถอดราก 25 ได้เท่ากับ 5 print(num1) num2 = math.ceil(3.1) #คำสั่งปัดเศษขึ้น 3.1 เป็นเท่ากับ 4 print (num2) num3 = math.floor(3.09) #คำสั่งปัดเศษขึ้น 3.09 เป็นเท่ากับ 3 print(num3) num4 = math.pi #แสดงค่า พาย print(num4) #EX.1 ทดสอบการคิดเลข print (num*num1) print (math.ceil(num4*math.sqrt(16)))
# LAB.8 จัดการข้อมูลด้วย Dictionary product = {101:"กล้วยทอด",102:"มันทอด",103:"เผือกทอด"} print (product[101]) food1 = {"ของว่าง":("กล้วยทอด","มันทอด","เผือกทอด"),"น้ำดื่ม":("ชานม","ชาเขียว","ชาไข่มุข")} print (food1 ["ของว่าง"]) #- ฟังก์ชั่นที่ดำเนินการกับ Dictionary
# 複数のインスタンス # menu_item1, menu_item2 class MenuItem: pass menu_item1 = MenuItem() menu_item1.name = 'サンドイッチ' print(menu_item1.name) menu_item1.price = 500 print(menu_item1.price) # MenuItemクラスのインスタンスを生成してください menu_item2 = MenuItem() # menu_item2のnameに「チョコケーキ」を代入してください menu_item2.name = 'チョコケーキ' # menu_item2のnameを出力してください print(menu_item2.name) # menu_item2のpriceに「400」を代入してください menu_item2.price = 400 # menu_item2のpriceを出力してください print(menu_item2.price) #===================================================================== # クラスの中では関数(メソッド)を定義できる # ・メソッド:第1引数にselfを追加する必要がある # ・インスタンス・メソッド()で、メソッドを呼び出せる # class MenuItem: # infoメソッドを定義してください def info(self): print('メニューの名前と値段が表示されます') menu_item1 = MenuItem() menu_item1.name = 'サンドイッチ' menu_item1.price = 500 # menu_item1に対してinfoメソッドを呼び出してください menu_item1.info() menu_item2 = MenuItem() menu_item2.name = 'チョコケーキ' menu_item2.price = 400 # menu_item2に対してinfoメソッドを呼び出してください menu_item2.info() #===================================================================== # インスタンスメソッドの第1引数に指定した self には、そのメソッドを呼び出した # インスタンス自身が代入される # class MenuItem: def info(self): # 「○○: ¥□□」となるように出力してください print(self.name + ': ¥' + str(self.price)) menu_item1 = MenuItem() menu_item1.name = 'サンドイッチ' menu_item1.price = 500 menu_item1.info() menu_item2 = MenuItem() menu_item2.name = 'チョコケーキ' menu_item2.price = 400 menu_item2.info() #===================================================================== # インタンスメソッド(戻り値) class MenuItem: def info(self): # print()の中身を戻り値として返してください return self.name + ': ¥' + str(self.price) menu_item1 = MenuItem() menu_item1.name = 'サンドイッチ' menu_item1.price = 500 # menu_item1.info()の値を出力してください print(menu_item1.info()) menu_item2 = MenuItem() menu_item2.name = 'チョコケーキ' menu_item2.price = 400 # menu_item2.info()の値を出力してください print(menu_item2.info())
x = 7 * 10 y = 5 * 6 # xが70と等しい場合に「xは70です」と出力してください if x == 70: print('xは70です') # yが40と等しくない場合に「yは40ではありません」と出力してください if y != 40: print('yは40ではありません') #===================================================================== # if x = 10 # xが30より大きい場合に「xは30より大きいです」と出力してください if x > 30: print('xは30より大きいです') money = 500 apple_price = 200 # moneyの値がapple_priceの値以上の時、「りんごを買うことができます」と出力してください if money >= apple_price: print('りんごを買うことができます') #===================================================================== # if, else money = 100 apple_price = 200 if money >= apple_price: print('りんごを買うことができます') # if文の条件に当てはまらない場合に「お金が足りません」と出力してください else: print('お金が足りません') #===================================================================== # if, elif, else money = 100 apple_price = 100 if money > apple_price: print('りんごを買うことができます') # 変数の値が等しい場合に「りんごを買うことができますが所持金が0になります」と出力してください elif money == apple_price: print('りんごを買うことができますが所持金が0になります') else: print('お金が足りません') #===================================================================== # and, or, not x = 20 # xが10以上30以下の場合に「xは10以上30以下です」と出力してください if x >= 10 and x <= 30: print('xは10以上30以下です') y = 60 # yが10未満または30より大きい場合に「yは10未満または30より大きいです」と出力してください if y < 10 or y > 30: print('yは10未満または30より大きいです') z = 55 # zが77ではない場合に「zは77ではありません」と出力してください if not z == 77: print('zは77ではありません') #=====================================================================
# Program Leap Year Checker # Description: # This program will check if input year is leap year or not. # Author: Daniel Hong # Date: 2/7/21 # Revised: # <revision date> # list libraries used # Declare constants (name in ALL_CAPS) # Declare Variable types (EVERY variable used) year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("It is a leap year") else: print("It is not a leap year") else: print("It is a leap year") else: print("It is not a leap year") # End Program
# Program: Check-In Functions # Description: This is a list of functions that will be used for checking in the patient. # Author: Chang Yeon Hong # Date: 12 May 2021 # Revised: # <revision date> # list libraries used # Declare global constants (name in ALL_CAPS) # Function checkUserAccount() # Description: This will check if the user already has an account # Calls: # createUserAccount() # Parameters: # userID, searchType # Returns: # foundIt def checkUserAccount (userID, searchType): # Declare Local Variable types (NOT parameters) foundIt = False createAccountChoice = str() checker = str() patientList = [] counter1 = 0 counter2 = 0 try: file1 = open("database.txt", "r") # } end try except: createUserAccount() # } end except else: checker = file1.read() patientList = checker.split("/") patientList.pop() for counter1 in range (len(patientList)): cutter = str() newList = [] cutter = patientList[counter1] cutter = cutter.replace("[","") cutter = cutter.replace("]","") cutter = cutter.replace("'","") newList = cutter.split(",") patientList[counter1] = newList # } end for for counter2 in range (len(patientList)): if searchType == 1: if patientList[counter2][0] == userID: print(patientList[counter2][1] + patientList[counter2][2] + ", thanks for visiting us today.\n") foundIt = True # } if end # } if end else: if patientList[counter2][0] == userID: print("First Name: " + patientList[counter2][1]) print("Last Name: " + patientList[counter2][2]) print("Birth Date: " + patientList[counter2][3]) print("Username: " + patientList[counter2][0]) print("Address1: " + patientList[counter2][4]) print("Address2: " + patientList[counter2][5]) print("City: " + patientList[counter2][6]) print("State: " + patientList[counter2][7]) print("Zipcode: " + patientList[counter2][8]) print("Phone Number: " + patientList[counter2][9]) print("Email Address: " + patientList[counter2][10] + "\n") foundIt = True # } end # } end for if foundIt == False: print("Couldn't find your username in the database") print("Would you like to create an account?") createAccountChoice = str(input("Enter 1 = Yes / 2 = No : ")) while createAccountChoice != "1" and createAccountChoice != "2": createAccountChoice = str(input("Please, enter the correct number: ")) # } end while if createAccountChoice == "1": createUserAccount() # } end if # } end if # Return the return variable, if any return foundIt #} end Function createUserAccount() # Function createUserAccount() # Description: This will check if the user already has an account # Calls: # none # Parameters: # none # Returns: # none def createUserAccount (): # Declare Local Variable types (NOT parameters) first_name = str() last_name = str() birth_date = int() userID = str() address1 = str() address2 = str() city = str() state = str() zipcode = str() phoneNumber = str() emailAddress = str() duplicateChecker = str() file1 = str() newAccount = [] try: file1 = open("database.txt","r") except: print("There is no data in the database. Please create one.") else: duplicateChecker = file1.read() file1.close() first_name = input("What is your First Name: ") last_name = input("What is your Last Name: " ) birth_date = (input("When is your Birthday in MMDDYYYY format: ")) userID = (first_name[0]+last_name+str(birth_date)).lower() address1 = input("What is your street address: ") address2 = input("APT/Suite/Building#: ") city = input("Which City: ") state = input("Which State: ") zipcode = input("Postal code: ") phoneNumber = input("Phone Number in ###-###-#### format: ") emailAddress = input("Your Email Address: ") if userID in duplicateChecker: print("You already have an account!\n") else: newAccount = [userID, first_name, last_name, birth_date, address1,address2, city,state,str(zipcode),str(phoneNumber),emailAddress.lower()] file1 = open("database.txt","a") file1.write(str(newAccount)+"/") file1.close() print("Your username is: " + userID) print ("User Account Successfully Created \n") # so I can test-run the template and not get an error # Return the return variable, if any #} end Function createUserAccount()
import sortint import sortintmelhorado import sortintmelhorado2 import sortchar import sortcharmelhorado import sortcharmelhorado2 menuSeletor = int(input('Escolha a opção que desejar: \n[1]Ordenação de inteiros;\n[2]Ordenação de caracteres;\n[3]Ordenação de Strings.\n')) if menuSeletor == 1: resultadosortint = sortint.ordsortint() resultadosorintmelhorado = sortintmelhorado.ordsortintmelhorado() resultadosorintmelhorado2 = sortintmelhorado2.ordsortintmelhorado2() print(f'Diferença de comparações vetor de 3000 - 5000: ') print(f'\nSort {resultadosortint[0]} Sort1° {resultadosorintmelhorado[0]} Sort2° {resultadosorintmelhorado2[0]}') print(f'Diferença de trocas vetor de 3000 - 5000: ') print(f'\nSort {resultadosortint[1]} Sort2° {resultadosorintmelhorado[1]} Sort2° {resultadosorintmelhorado2[1]}') print(f'Diferença de tempos vetor de 3000 - 5000: ') print(f'\nSort {resultadosortint[2]} Sort2° {resultadosorintmelhorado[2]} Sort2° {resultadosorintmelhorado2[2]}') elif menuSeletor == 2: print()
import sortchar import sortcharmelhorado import sortcharmelhorado2 def menuchar(): menuseletor = int(input('Escolha a opção que deseja >>\n[1] Sort\n[2] Sort 1° versão melhorado\n[3] Sort 2° versão melhorado\n')) if menuseletor == 1: sortchar.ordsortchar() elif menuseletor == 2: sortcharmelhorado.ordsortcharmelhorado() elif menuseletor == 3: sortcharmelhorado2.ordsortcharmelhorado2() else: print('[ERRO!!!] Por favor digite um valor válido!')
s = int(input("Enter a single digit: ")) a = str(s) n = int(input("Enter the number of repetition: ")) x = [] for i in range(1,n+1): x.append(a*i) z = [] for i in range(len(x)): z.append(int(x[i])) print(z) y = 0 for i in range(len(x)): y = y+int(x[i]) print(y)
s = str(input("Enter some words: ")) x = s.split(' ') for i in range(len(x)): for j in range(len(x)-1-i): if(len(x[j])>len(x[j+1])): t = x[j+1] x[j+1] = x[j] x[j] = t else: pass print(x)
s = str(input("Enter entries separated by space: ")) x = s.split() y = [] for i in range(len(x)): if(int(x[i])%2==0): pass else: y.append(int(x[i])**2) print(y)
############################################################# # FILE : asteroidMain.py # WRITER : Dan Kufra , dan_kufra , # EXERCISE : intro2cs ex8 # DESCRIPTION: # This is a version of the classic game "Asteroids". The goal is to control # the spaceship and destroy the asteroids. ############################################################# from torpedo import * from asteroid import * from spaceship import * from gameMaster import * import math import sys class GameRunner: def __init__(self, amnt = 3): self.game = GameMaster() self.screenMaxX = self.game.get_screen_max_x() self.screenMaxY = self.game.get_screen_max_y() self.screenMinX = self.game.get_screen_min_x() self.screenMinY = self.game.get_screen_min_y() shipStartX = (self.screenMaxX-self.screenMinX)/2 + self.screenMinX shipStartY = (self.screenMaxY-self.screenMinY)/2 + self.screenMinY self.game.set_initial_ship_cords( shipStartX, shipStartY ) self.game.add_initial_astroids(amnt) # created a new class object called dead_torpedos that is a list of # our marked for deletion torpedos. self.dead_torpedos = [] def run(self): self._do_loop() self.game.start_game() def _do_loop(self): self.game.update_screen() self.game_loop() # Set the timer to go off again self.game.ontimer(self._do_loop,5) def move_object(self, obj): """ Function that moves and object to the proper coordinates :param obj: the object we want to move """ # set our variables to the old coordinates and the speed of the object x_cord = obj.get_x_cor() y_cord = obj.get_y_cor() speed_x = obj.get_speed_x() speed_y = obj.get_speed_y() delta_x = self.screenMaxX - self.screenMinX delta_y = self.screenMaxY - self.screenMinY # calculate the new coordinates new_cord_x = ((speed_x + x_cord - self.screenMinX) % delta_x) + \ self.screenMinX new_cord_y = ((speed_y + y_cord - self.screenMinY) % delta_y) + \ self.screenMinY # use the move method to move our object obj.move(new_cord_x, new_cord_y) def move_asteroids(self, asteroid_list): ''' :param asteroid_list: our list of asteroids ''' for asteroid in asteroid_list: self.move_object(asteroid) def move_ship(self, ship): """ Function that moves the ship based on which buttons the player presses :param ship = our ship object """ # get our ship and it's starting speed speed_x = ship.get_speed_x() speed_y = ship.get_speed_y() # increase or decrease the angle based on what the player presses if self.game.is_right_pressed(): ship.decrease_angle() elif self.game.is_left_pressed(): ship.increase_angle() # if the player presses the up arrow, increase the speed in the # correct angle elif self.game.is_up_pressed(): angle = ship.get_angle() new_speed_x = speed_x + (math.cos(math.radians(angle))) new_speed_y = speed_y + (math.sin(math.radians(angle))) ship.set_speed_x(new_speed_x) ship.set_speed_y(new_speed_y) # move the ship using our move_object() method. self.move_object(ship) def fire_torpedo(self, ship, torpedo_list): """ Function that adds torpedos to our game when the space bar is pressed :param ship = our ship object :param torpedo_list = our list of torpedos """ # use methods to get our ship object, it's speed, angle and location speed_x = ship.get_speed_x() speed_y = ship.get_speed_y() x_cord = ship.get_x_cor() y_cord = ship.get_y_cor() angle = ship.get_angle() # set our maximum torpedo amount to 20 and get our list of torpedos MAX_TORPEDO = 20 # if clauses that check whether the fire is pressed, if it was and # there aren't the maximum amount of torpedos then fire a torpedo. if self.game.is_fire_pressed(): if len(torpedo_list) < MAX_TORPEDO: tor_speed_x = speed_x + (2 * math.cos(math.radians(angle))) tor_speed_y = speed_y + (2 * math.sin(math.radians(angle))) self.game.add_torpedo(x_cord, y_cord, tor_speed_x, tor_speed_y, angle) def mark_torpedo(self, torpedo_list): """ Function that marks torpedos whose lifespan has ended :param torpedo_list = our list of torpedos """ # Set the lifespan limit to 0 life_span_ended = 0 # iterate over the list and if the lifespan ran out, append them to # our list of dead torpedos for i in range(len(torpedo_list)): life_span = torpedo_list[i].get_life_span() if life_span <= life_span_ended: self.dead_torpedos.append(torpedo_list[i]) def move_torpedo(self, torpedo_list): """ Function that moves the torpedos :param torpedo_list = our list of torpedos """ # iterate over our list of torpedos and call the move_object method # on them for i in range(len(torpedo_list)): self.move_object(torpedo_list[i]) def create_asteroids(self, old_asteroid, torpedo, size): """ Function that creates new asteroids when hit by a torpedo :param old_asteroid: the asteroid that explodes :param torpedo: the torpedo that destroyed the asteroid :param size: the size of the asteroid that was destroyed """ # set our variables to the coordinates and speed of the old asteroid # and torpedo x_co = old_asteroid.get_x_cor() y_co = old_asteroid.get_y_cor() speed_x = old_asteroid.get_speed_x() speed_y = old_asteroid.get_speed_y() torpedo_speed_x = torpedo.get_speed_x() torpedo_speed_y = torpedo.get_speed_y() # calculate the new speed new_speed_x = ((torpedo_speed_x + speed_x) / (math.sqrt((speed_x ** 2) + (speed_y ** 2)))) new_speed_y = ((torpedo_speed_y + speed_y) / (math.sqrt((speed_x ** 2) + (speed_y ** 2)))) # update the size of the new asteroids new_size = size - 1 # use the add_asteroid method to create the new asteroids going in # opposite directions. self.game.add_asteroid(x_co, y_co, new_speed_x, new_speed_y, new_size) self.game.add_asteroid(x_co, y_co, -1 * new_speed_x, -1 * new_speed_y, new_size) def blow_asteroids(self, torpedo_list, asteroid_list): """ Function that checks whether our torpedo hit an asteroid, updates the score, removes the asteroid, and adds 2 smallers ones if needed. :param torpedo_list: our list of torpedos :param asteroid_list: our list of asteroids """ # Iterates over our torpedo list, asteroid list and checks whether # the torpedo collided with any asteroid. for torpedo in torpedo_list: for asteroid in asteroid_list: # if they did collide, get the asteroids size and update # score accordingly if self.game.intersect(torpedo, asteroid): self.dead_torpedos.append(torpedo) asteroid_size = asteroid.get_size() if asteroid_size == 3: self.game.add_to_score(30) self.create_asteroids(asteroid, torpedo, 3) elif asteroid_size == 2: self.game.add_to_score(50) self.create_asteroids(asteroid, torpedo, 2) elif asteroid_size == 1: self.game.add_to_score(100) # remove the asteroid that was hit self.game.remove_asteroid(asteroid) def remove_objects(self, obj): """ Removes our dead torpedos. :param obj: our dead torpedo list """ self.game.remove_torpedos(obj) def ship_collision(self, ship, asteroid_list): """ Function checks whether the ship has collided with an asteroid. If it did, remove a life and show a message. :param ship: our ship :param asteroid_list: our asteroid list """ # set our title and message variables title = "Collision!" message = "Watch out! You have lost 1 life!" # iterate over the asteroids for asteroid in asteroid_list: # check whether any has collided with our ship, if it has print # a message, remove the asteroid and take off 1 life. if self.game.intersect(ship, asteroid): self.game.remove_asteroid(asteroid) self.game.ship_down() self.game.show_message(title, message) def end_game(self, asteroid_list): ''' Checks whether the game ended and prints the appropriate message :param asteroid_list: our list of asteroids ''' # set our constant EMPTY to 0 and our variable lives to lives we have EMPTY = 0 lives = self.game.get_num_lives() # set the game_end to False while game isn't lost game_end = False # check if the different lose clauses exist, if they do update the # message and change the boolean value of game_end if lives <= EMPTY: title = "You lose!" message = "You lost the game!" game_end = True elif len(asteroid_list) == EMPTY: title = "You win!" message = "Congratulations! You have destroyed all the asteroids!" game_end = True elif self.game.should_end(): title = "You quit!" message = "You have quit the game." game_end = True # if the game ended, print the message and quit the game if game_end: self.game.show_message(title, message) self.game.end_game() def game_loop(self): ''' Function that runs the game and calls the appropriate methods. ''' # set our variables that we will use in multiple methods. torpedo_list = self.game.get_torpedos() asteroid_list = self.game.get_asteroids() ship = self.game.get_ship() #call the appropriate methods that the game uses self.move_asteroids(asteroid_list) self.move_ship(ship) self.fire_torpedo(ship, torpedo_list) self.mark_torpedo(torpedo_list) self.move_torpedo(torpedo_list) self.blow_asteroids(torpedo_list, asteroid_list) self.remove_objects(self.dead_torpedos) self.ship_collision(ship, asteroid_list) self.end_game(asteroid_list) def main(amount): runner = GameRunner(amount) runner.run() if __name__ == "__main__": # Set the default amount of asteroids to 3 amount = 3 # if an argument is entered in the command line set the asteroid amount # to that argument if len(sys.argv) == 2: amount = int(sys.argv[1]) # call our main function with the amount of asteroids main(amount)
# import our classes and os from WordTracker import * from WordExtractor import * import os class PathIterator: """ An iterator which iterates over all the directories and files in a given path (note - in the path only, not in the full depth). There is no importance to the order of iteration. """ def __init__(self, path): # set our instances for the path, the directories and files inside # it and the empty list of full paths self.path = path self.content = os.listdir(path) self.list_paths = [] def __iter__(self): """ An iter method that creates our list of full paths. """ for item in self.content: self.list_paths.append(os.path.join(self.path, item)) return self def __next__(self): """ Next method that returns the first index of our list of full paths. If the list is empty returns a StopIteration """ if len(self.list_paths) == 0: raise StopIteration return self.list_paths.pop() def path_iterator(path): """ Returns an iterator to the current path's filed and directories. Note - the iterator class is not outlined in the original version of this file - but rather is should be designed and implemented by you. :param path: A (relative or an absolute) path to a directory. It can be assumed that the path is valid and that indeed it leads to a directory (and not to a file). :return: An iterator which returns all the files and directories in the *current* path (but not in the *full depth* of the path). """ # create an object using the PathIterator class, this object is an # iterator containing the list of items in the given directory file_path = PathIterator(path) #return the object return file_path def print_tree_helper(path, first_path, sep): ''' Helper function for our print_tree function that allows us to save the first path given. And using it, prints a tree of the absolute path recursively. :param path: The path we want to explore :param first_path: The first path which we want to save and use for spacing :param sep: the separator between branches in our tree :return: None ''' # set a variable to the iterator in our previous function that holds all # the paths inside the directory recur_index = 1 list_directories = path_iterator(path) # for every path in that iterator, split it into a list of paths without # the "/" character for directory in list_directories: split_directory = directory.split('/') # set place to equal the length of the full path minus the first # path we got - 1. This gives us the proper spacing for our tree. place = len(split_directory) - len(first_path.split('/')) - recur_index # if the path given leads to a directory, print the directory and # then explore it recursively by calling our function again. if os.path.isdir(directory): print((place * sep) + split_directory[-1]) print_tree_helper(directory, first_path, sep) # if it isn't a directory, just print it else: print((place * sep) + split_directory[-1]) def print_tree(path, sep=' '): """ Print the full hierarchical tree of the given path. Recursively print the full depth of the given path such that only the files and directory names should be printed (and not their full path), each in its own line preceded by a number of separators (indicated by the sep parameter) that correlates to the hierarchical depth relative to the given path parameter. :param path: A (relative or an absolute) path to a directory. It can be assumed that the path is valid and that indeed it leads to a directory (and not to a file). :param sep: A string separator which indicates the depth of current hierarchy. """ # call our helper function that allows us to save the first path return print_tree_helper(path, path, sep) def file_with_all_words(path, word_list): """ Find a file in the full depth of the given path which contains all the words in word_list. Recursively go over the files in the full depth of the given path. For each, check whether it contains all the words in word_list and if so return it. :param path: A (relative or an absolute) path to a directory. In the full path of this directory the search should take place. It can be assumed that the path is valid and that indeed it leads to a directory (and not to a file). :param word_list: A list of words (of strings). The search is for a file which contains this list of words. :return: The path to a single file which contains all the words in word_list if such exists, and None otherwise. If there exists more than one file which contains all the words in word_list in the full depth of the given path, just one of theses should be returned (does not matter which). """ # save the iterator object from our previous function as a variable list_path = path_iterator(path) # set our default found_file to None, this will change if we find a file found_file = None # run over the files in our path for item in list_path: # if the item is a directory, recall our function recursively and # explore the inner directory if os.path.isdir(item): found_file = file_with_all_words(item, word_list) # if it's a file, search the file for the words in our list else: # create an object which holds our list of words using WordTracker our_words = WordTracker(word_list) # create an object that holds our file using WordExtractor.py file = WordExtractor(item) # for that loops over the iterator we created and returns a word # each time for word in file: # use our encounter() method from WordTracker on our word our_words.encounter(word) # check if after using the =method all our words were found, # if they were return the file name if our_words.encountered_all(): return item # return the found file, if none was found it'll return None return found_file
#!/usr/bin/env python # -*- coding: utf-8 -*- isim=raw_input("senin adın ne:") if isim== "ferhat": print("ne güzel isim") else: print("ismini sevmedim")
# !/usr/bin/env python # -*- coding: cp1254 -*- alinannot1=int(raw_input("notunuzu girin:")) alinannot2=int(raw_input("ikinci notunuzu girin:")) if alinannot1 <0 or alinannot1>100 or alinannot2<0 or alinannot2>100: print "gecersiz bir not.." else: ortalama=(alinannot1 + alinannot2)/2 if ortalama <=100: karnenotu =5 if ortalama <85: karnenotu =4 if ortalama <70: karnenotu =3 if ortalama < 55: karnenotu =2 if ortalama < 45: karnenotu =1 print "ortalamanız:",ortalama print "karnenotunuz:",karnenotu
# -*- coding:utf-8 -*- def asal(kaca_kadar): """Asal sayı bulan fonksiyon Girdi olarak bir sayı alır Bu sayıya kadar olan asal sayıları ekrana basar. """ asallar = [2] if kaca_kadar < 2: return None elif kaca_kadar == 2: return asallar else: for i in range(3,kaca_kadar): bolundu = False for j in range(2,i): if i % j == 0: bolundu=True break if bolundu == False: asallar.append(i) return asallar if __name__ == "__main__": # join kullanmak için, listedekiler str olmalı. print "\n".join(map(str,asal(1000))) """ Bu aşamada map() bilinmiyorsa, list comprehension veya for döngüsü kullanılır. print "\n".join([str(asal) for asal in asal(1000)]) for asal in asal(1000) print asal """
#!/usr/bin/env python # -*- coding: utf-8 -*- import random kntrl = "" while True: if kntrl == 'q' or kntrl== 'Q': break else: loto=random.sample(xrange(1,50),6) stopu1=random.sample(xrange(1,35),5) stopu2=random.sample(xrange(1,15),1) onnum = random.sample(xrange(1,81),10) sloto=random.sample(xrange(1,55),6) loto.sort() stopu1.sort() onnum.sort() sloto.sort() print "\n\nsayısal loto:\n%s \n" %(loto) print "sans topu=\n%s + %s \n" %(stopu1,stopu2) print "on numara:\n %s \n " %(onnum) print "super loto:\n%s\n " %(sloto) kntrl =raw_input("yeni sayılar için \"enter\" ,\ cıkmak icin \"Q \" tusuna basın..")
""" Read fields to check from file like byr (Birth Year) iyr (Issue Year) eyr (Expiration Year) hgt (Height) hcl (Hair Color) ecl (Eye Color) pid (Passport ID) cid (Country ID) """ def read_fields(fname="fields.txt"): """ read fields to check """ # byr (Birth Year) fields = () with open(fname, "r") as inp: for line in inp.readlines(): fields += (line.strip().split("(")[0].strip(),) return fields if __name__ == "__main__": print(read_fields())
from gmpy import mpq,mpz from random import randint,seed from time import time def rand_matrix(n, typ=int, N=10): ''' A function to matrix with random elements ''' m = [] for i in range(n): a = [] for j in range(n): p = randint(0, N) a.append(p) m.append(a) return m def madd(a, b): ''' A function to add two matrices ''' n = len(a) c = [] for i in range(n): c.append(a[i][:]) for i in range(n): c1 = c[i] b1 = b[i] for j in range(n): c1[j] += b1[j] return c def imadd(a, b): ''' A function to ''' n = len(a) for i in range(n): a1 = a[i] b1 = b[i] for j in range(n): a1[j] += b1[j] return a def msub(a, b): ''' A function to substract two matrices ''' n = len(a) c = [] for i in range(n): c.append(a[i][:]) for i in range(n): c1 = c[i] b1 = b[i] for j in range(n): c1[j] -= b1[j] return c def imsub(a, b): ''' A function to substract two matrices''' n = len(a) for i in range(n): a1 = a[i] b1 = b[i] for j in range(n): a1[j] -= b1[j] return a def mmul(a, b): ''' A function to multiply two matrices in a traditional way ''' n = len(a) c = [] for i in range(n): cv = [] a1 = a[i] for j in range(n): r = 0 for k in range(n): r += a1[k] * b[k][j] cv.append(r) c.append(cv) return c def mmul(a, b, trans=0): ''' A function to multiply transitive matrices ''' n = len(a) c = [] if not trans: bt = [[0]*n for _ in range(n)] for i in range(n): for j in range(n): bt[i][j] = b[j][i] b = bt for i in range(n): a1 = a[i] cv = [] for j in range(n): b1 = b[j] r = 0 for k in range(n): r += a1[k]*b1[k] cv.append(r) c.append(cv) return c def strassen_mul(a,b,trans=0): ''' Strassem multiply implementation ''' n = len(a) if n % 2 == 1 or n <= 128: return mmul(a,b,trans) rn0 = range(n/2) rn1 = range(n/2, n) A00 = [a[i] [:n/2] for i in rn0] A01 = [a[i] [n/2:] for i in rn0] A10 = [a[i] [:n/2] for i in rn1] A11 = [a[i] [n/2:n] for i in rn1] if trans: B00 = [b[i] [:n/2] for i in rn0] B10 = [b[i] [n/2:] for i in rn0] B01 = [b[i] [:n/2] for i in rn1] B11 = [b[i] [n/2:n] for i in rn1] else: B00 = [[b[j][i] for j in rn0] for i in rn0] B01 = [[b[j][i] for j in rn0] for i in rn1] B10 = [[b[j][i] for j in rn1] for i in rn0] B11 = [[b[j][i] for j in rn1] for i in rn1] M1 = strassen_mul(madd(A00, A11), madd(B00, B11), 1) M2 = strassen_mul(madd(A10, A11), B00, 1) M3 = strassen_mul(A00, msub(B01, B11), 1) M4 = strassen_mul(A11, msub(B10, B00), 1) M5 = strassen_mul(madd(A00, A01), B11, 1) M6 = strassen_mul(msub(A10, A00), madd(B00, B01), 1) M7 = strassen_mul(msub(A01, A11), madd(B10, B11), 1) C00 = madd(msub(madd(M1, M4), M5), M7) C01 = madd(M3, M5) C10 = madd(M2, M4) C11 = madd(madd(msub(M1, M2), M3), M6) c = [C00[i] + C01[i] for i in rn0] for i in rn0: c.append(C10[i] + C11[i]) return c def test_1(N): seed(2) for n in range(100, 1000, 100): a = rand_matrix(n, mpq, N) b = rand_matrix(n, mpq, N) t0 = time() C = mmul(a, b) t1 = time() c = strassen_mul(a,b) t2 = time() assert c == C print 'dimension=%d traditional way: %.2f strassen: %.2f' %(n, t1-t0, t2-t1) test_1(1000000)
from sys import stdin n = int(stdin.readline()) numbers = [x for x in stdin.readline().split()] for number in numbers: sum = 0 for i in number: if i != '\n': sum += int(i) print(sum)
word = input() up = 0 lo = 0 for i in word: if i.isupper(): up+=1 else: lo+=1 if lo>=up: print(word.lower()) else: print(word.upper())
import sys import math # math.factorial() import numpy as np def debug_print(information): print("DEBUG: ", information, file=sys.stderr) # get your team & get your board team = input() first_row = input() second_row = input() third_row = input() # print out the inputs you're getting debug_print(team) debug_print(first_row) debug_print(second_row) debug_print(third_row) # outputs the contents of my board # board == incoming board plus my coordinates #team = input() #first_row = input() #second_row = input() #third_row = input() #almost_board = [[first_row], [second_row], [third_row]] #board = np.array(almost_board) almost_board = [first_row], [second_row], [third_row] board = np.array(almost_board) def game_logic(board, team): # logic for bot choice # functions as a hierarchy of move choices A = (board.flat[0][2]) B = (board.flat[0][0]) C = (board.flat[2][0]) D = (board.flat[2][2]) E = (board.flat[0][1]) F = (board.flat[2][1]) G = (board.flat[1][0]) H = (board.flat[1][2]) I = (board.flat[1][1]) if team not in board: # middle blocks and wins first if A and C != '_' and I == '_' or E and F != '_' and I == '_': print('1 1') elif B and D != '_' and I == '_' or G and H != '_' and I == '_': print('1 1') # side blocks and wins third elif B and C != '_' and G == '_' or H and I != '_' and G == '_': print('1 0') elif E and I != '_' and F == '_' or C and D != '_' and F == '_': print('2 1') elif I and F != '_' and E == '_' or B and A != '_' and E == '_': print('0 1') elif G and I != '_' and H == '_' or A and D != '_' and H == '_': print('1 2') # diaganol blocks and wins second elif I and A != '_' and C == '_' or B and G != '_' and C == '_': print('2 0') elif F and D != '_' and C == '_': print('2 0') elif I and D != '_' and B == '_' or C and G != '_' and B == '_': print('0 0') elif E and A != '_' and B == '_': print('0 0') elif C and I != '_' and A == '_' or B and E != '_' and A == '_': print('0 2') elif D and H != '_' and A == '_': print('0 2') elif B and I != '_' and D == '_' or A and H != '_' and D == '_': print('2 2') elif C and F != '_' and D == '_': print('2 2') # normal game play elif A and B != '_' and E == '_': print ('0 1') elif B and C != '_' and G == '_': print('1 0') elif C and D != '_' and F == '_': print('2 1') elif A and D != '_' and H == '_': print('1 2') elif '_' == A: print('0 2') elif '_' == B: print('0 0') elif '_' == D: print('2 2') elif '_' == C: print ('2 0') elif '_' == B: print('0 0') elif '_' == A: print('0 2') elif '_' == E: print('0 1') elif '_' == F: print('2 1') elif '_' == G: print('1 0') elif '_' == H: print('1 2') elif '_' == D: print('2 2') elif '_' == I: print('1 1') elif '_' == F: print('2 1') elif '_' == G: print('1 0') def main(): game_logic(board, team) main()
prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3 } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15 } # for fruit in prices: # print(".",fruit,":", prices[fruit],sep = " ") # print() what = input("which fruit do you want? ") print(".",what) if what in prices: print(". price : ",prices[what]) if what in stock: print(". stock : ",stock[what]) total = 0 for fruit in prices: total = total + (prices[fruit] * stock[fruit]) print("The total price: ",total)
# from random import choice # x = 3 # op = choice(["+", "-", "*", "/"]) # y = 7 # # result = -999 # # if op == "+": # result = x + y # elif op == "-": # result = x - y # elif op == "*": # result = x * y # else: # result = x / y # # print(result) from random import choice def calc(x, y, op): if op == "+": result = x + y elif op == "-": result = x - y elif op == "*": result = x * y else: result = x / y return result # res = calc(3, 7, "+") # print(res) # # r = calc(1, 2, "-") # print(r) # argument, parameter # calc() # op = choice(["+", "-", "*", "/"]) # calc(3, 7, "-")
items = ["T-shirt", " Sweater"] running = True while running: want = input("Welcome to our shop, what do you want(C, R, U, D)? ") if want == "R": print("Our items: ", *items, sep = ", ") elif want == "C": new = input("Enter new item: ") items.append(new) print("Our items: ", *items, sep = ", ") elif want == "U": update = int(input("Update position: ")) newitem = input("New item: ") items[update - 1] = newitem print("Our items: ", *items, sep = ", ") elif want == "D": delete_position = int(input("Delete position: ")) del items[delete_position] print("Our items: ", *items, sep = ", ") else: running = False
print("Skipping loop") pineapple = .5 for Numbers in range(7): print(Numbers) pineapple = pineapple * 2 #print (pineapple)
#!/usr/bin/env python3 # Created by: Teddy Sannan # Created on: October 2019 # This program takes user number # and displys the weekday def main(): while True: # input print("Enter a number between 1 and 7") number = int(input("1 being Monday and 7 being Sunday: ")) # process if number == 1: # output print() print("Monday") # process elif number == 2: # output print() print("Tuesday") # process elif number == 3: # output print() print("Wednesday") # process elif number == 4: # output print() print("Thursday") # process elif number == 5: # output print() print("Friday") # process elif number == 6: # output print() print("Saturday") # process elif number == 7: # output print() print("Sunday") # prevents program from crashing if number not in [1, 2, 3, 4, 5, 6, 7]: print() print("Please enter a valid response") print() continue # breaks out of while loop else: break if __name__ == "__main__": main()
word = str(raw_input("enter a word ")) new_word = "" counter = len(word) - 1 for x in word: new_word += word[counter] counter -= 1 #User enters a string print("the word you entered backwards is: ", new_word)
#!/usr/bin/env python3 import os import sys args = sys.argv if len(args) < 2: print('Usage: {} STRING'.format(os.path.basename(args[0]))) sys.exit(1) else: z=0 #not using i, worrried I will get the vowels and the count confused for letter in args[1]: if letter in 'aeiou': z+=1 if z == 1: print('There is 1 vowel in "{}."'.format(args[1])) elif z > 1: print('There are {} vowels in "{}."'.format(z,args[1])) else: print('There are 0 vowels in "{}."'.format(args[1]))
import adivinhacao import forca def escolhe_jogos(): print('**************************') print('*****Escolha seu jogo*****') print('**************************') print('(1)Adivinhação -- (2)Forca') jogo = int(input('Digite o número do seu jogo: ')) if jogo == 1: print('Jogando adivinhação!') adivinhacao.jogar() elif jogo == 2: print('Jogando forca!') forca.jogar() if __name__ == "__main__": escolhe_jogos()
class User: ''' This class shall be used for the user's login information, the username and their password. Credentials shall also be saved under a user's information ''' user_list = [] #list to store our users def __init__(self,user_name,login_password): self.user_name = user_name self.login_password = login_password def save_user(self): User.user_list.append(self) def delete_user(self): User.user_list.remove()
N = int(input()) #ler quantidade de repetições de caracteres for i in range(N): #executa de acordo com a quantidade informada c = input() #ler os caracteres informados diamante = 0 # variavel que irá contabilizar o número de diamantes menor = 0 #variavel que irá contabilizar a quantidade de caracter = < for j in range(len(c)): # percorre os caracteres informados if(c[j] == '<'): # valida se em cada caracter informado existe um que seja = ao '<' menor += 1 # soma + 1 sinal identificado if(c[j] == '>' and menor > 0): # valida se em cada caracter informado existe um que seja = ao '>' e se a quantidade de sinais = '<' é maior que 0 diamante += 1 # se condição acima é válida contabiliza mais um diamante menor -= 1 # desconsidera um sinal < que foi comparado print(diamante) #informa a quantidade de diamantes identificados
# -*- coding: utf-8 -*- """ Created on Fri Jan 22 14:41:18 2021 @author: Dragneel """ #%% Function to return path value def pathValue(startPoint, endPoint, cost = 0): if (startPoint, endPoint) in pairList: print(str(cost + valueDict[(startPoint, endPoint)]) + ' ') for (i, j) in pairList: if i == startPoint: pathValue(j, endPoint, cost + valueDict[(i, j)]) #%% Input Handling and Calling recursive Function valueDict = {('i', 'a') : 35, ('i', 'b') : 45, ('a', 'c') : 22, ('a', 'd') : 32, ('b', 'd') : 28, ('b', 'e') : 36, ('b', 'f') : 27, ('c', 'd') : 31, ('c', 'g') : 47, ('d', 'g') : 30, ('e', 'g') : 26} pairList = [('i', 'a'), ('i', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('c', 'd'), ('c', 'g'), ('d', 'g'), ('e', 'g')] start = str(input('Enter Starting point: ')) end = str(input('Enter Ending point: ')) print('The length of path is: ') pathValue(start, end)
import psycopg2 import urllib.request import json import pandas as pd # Goes to the indicated url, parses through the json and stores into a dictionary and additionally a data frame with urllib.request.urlopen("http://api.worldbank.org/v2/countries/CHN/indicators/NY.GDP.MKTP.CD?per_page=5000&format=json") as url: data = json.loads(url.read().decode()) print(json.dumps(data, indent=2, sort_keys=True)) # Excludes the title of the json when copying the dictionary into the dataframe df = pd.DataFrame.from_dict(data[1]) # Reverses the indexes of the dataframe df = df.iloc[::-1] #Establishes connection to the database con = psycopg2.connect( host="ec2-52-6-77-239.compute-1.amazonaws.com", database="d2bo0a226irnot", user="lghdwoxqblmbcc", password="2e79c2ca9ef38dd79d8569c53112ecb42e1bdc35bd44a74723915bc0eed755b5", port="5432" ) #cursor cur = con.cursor() # For loop iterates through gdp values and inserts them into table for row in df.itertuples(): cur.execute("insert into china_gdp (country, date, value) values(%s, %s, %s)", (row.countryiso3code,row.date,row.value)) con.commit() #execute query cur.execute("select country, date, value from china_gdp") # Fetches all of the gdp china values and prints them rows = cur.fetchall() for r in rows: print(f"country {r[0]} date {r[1]} value {r[2]}") #close the connection and cursor cur.close() con.close()
""" 线程: api 文档:https://docs.python.org/zh-cn/3/library/threading.html 协程:Coroutine """ import threading import time ''' 创建新线程 threading.Thread(target=single()) 需要导入模块 threading ''' class MyThread(threading.Thread): # # # def __init__(self): # print("myThread init") def run(self): print("myThread is running") def single(): num = 0 while num < 5: print(f'single {num}') time.sleep(1) num += 1 print(threading.current_thread().getName()) def dance(): num = 0 while num < 5: print(f'dance {num}') time.sleep(1) num += 1 print(threading.current_thread().getName()) t1 = threading.Thread(target=single) t2 = threading.Thread(target=dance, name='good') t1.start() t2.start() # 自定义线程 t3 = MyThread() t3.start()
import random """ 语句的使用 条件语句:if ... else ... 三目运算符: 循环 """ # 条件成立,执行带缩进的代码行 if True: print("name") print("james") else: print("koby") # 多重判断 if ... elif ... else # age = int(input('input age')) age = random.randint(1, 50) if age > 30: print(age) elif age > 20: print(age) else: print(age) # 三目运算符 语法如下:条件成立执行的表达式 if 条件 else 条件不成立的表达式 ''' while 条件: 代码1 代码2 ... if i==4: break 终止循环,while...else中的代码不执行 else: continue 终止本次循环, 进行下一次循环 else: while...else 当循环征程结束之后要执行的代码 for 临时变量 in 序列: 代码1 代码2 '''
""" 运算符 算数运算符 赋值运算符 复合赋值运算符 比较运算符 逻辑运算符 """ ''' // 整除 % 取余 ** 指数 2**4 即2*2*2*2 ''' ''' 赋值运算符 ''' # 多个变量赋值 num, weight, name = 1, 2.3, 'james' ''' 复合赋值运算符 += c+=a 等价于 c = c + a -= *= ... ''' ''' 比较运算符 ''' ''' 逻辑运算符 and or not ''' ''' 公共操作 + 字符串, 元组, 列表 * 字符串, 元组, 列表 ''' list1 = [1, 3] list2 = [2, 4, 3] print(list1 + list2)
# Built-Ins: from typing import Any BOOLEAN_ENV_TRUE = ("1", "enable", "enabled", "on", "true", "yes") BOOLEAN_ENV_FALSE = ("0", "disable", "disabled", "off", "false", "no") def env_to_boolean(value_str: str) -> bool: """Convert a (string) environment variable to a Python bool :raises ValueError: value_str failed boolean validation """ if (value_str is None): return False value_str_lower = value_str.lower() if (value_str_lower in BOOLEAN_ENV_TRUE): return True elif (value_str_lower in BOOLEAN_ENV_FALSE): return False else: raise ValueError("Environment variable failed boolean validation") def mandatory(val: Any) -> Any: """Raises a ValueError if the provided input is None, otherwise returns it""" if (val is None): raise ValueError("Missing mandatory configuration value") return val
import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import numpy as np df=pd.read_excel('automobile.xlsx') mean=df['highway-mpg'].mean() df['highway-mpg'].replace(np.nan,mean,inplace=True) mean=df['price'].mean() df['price'].replace(np.nan,mean,inplace=True) lm=LinearRegression() x=df[['highway-mpg']] y=df['price'] lm.fit(x,y) y=lm.predict(df[['highway-mpg']]) mse=mean_squared_error(df['price'],y) print(mse) print() rsquared=lm.score(df[['highway-mpg']],df['price']) print(rsquared)
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_predict df=pd.read_excel('automobile.xlsx') mean=df['highway-mpg'].mean() df['highway-mpg'].replace(np.nan,mean,inplace=True) mean=df['price'].mean() df['price'].replace(np.nan,mean,inplace=True) x_data=df['highway-mpg'] y_data=df['price'] x_train,x_test,y_train,y_test=train_test_split(x_data,y_data,test_size=0.3,random_state=0) '''print(x_train) print(x_test) print(y_train) print(y_test)''' print() lm=LinearRegression() yhat=cross_val_predict(lm,df[['highway-mpg']],df[['price']],cv=3) print(yhat) print(len(yhat)) scores=cross_val_score(lm,df[['highway-mpg']],df[['price']],cv=3) print(scores) print(np.mean(scores))
dias = int(input('Dias: ' )) horas = int(input('Horas: ')) minutos = int(input('Minutos: ')) segundos = int(input('Segundos: ')) totalSegundos = 0 totalSegundos += segundos totalSegundos += (minutos * 60) totalSegundos += (horas * 60 * 60) totalSegundos += (dias * 24 * 60 * 60) print ('Total em segundos ', totalSegundos)
def show(*args): print(args) total = 0 for num in args: total += num num = (1, 2, 3) # show(num) #((1, 2, 3),) Invalido show(*num)
#!/usr/bin/env python # coding=utf8 from copy import deepcopy from random import randint class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): if self.size() == 0: return None else: value = deepcopy(self.queue[0]) del self.queue[0] return value def size(self): return len(self.queue) def queue_rotation(queue_size, iterations_count): # Creating and initializing queue queue = Queue() for i in range(queue_size): queue.enqueue(randint(0, 42)) for i in range(iterations_count): queue.enqueue(queue.dequeue()) print("Queue status: {0}".format(queue.queue))
#1 задание Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) # и метод running (запуск). Атрибут реализовать как приватный. В рамках метода реализовать переключение # светофора в режимы: красный, желтый, зеленый. Продолжительность первого состояния (красный) составляет 7 секунд, # второго (желтый) — 2 секунды, третьего (зеленый) — на ваше усмотрение. Переключение между режимами должно осуществляться только в # указанном порядке (красный, желтый, зеленый). # Проверить работу примера, создав экземпляр и вызвав описанный метод. from time import sleep class TrafficLight: color = [Красный, желтый, зеленый] def running(self): i < 3 while i == 0 print('светофор переключится\n' f{TrafficLight.color[i]}) sleep(7) elif i == 1 sleep(2) elif i==6 sleep(10) i+=1
# Brady Nokes 9/23/20 Cash Register Assignment numItems = 4 costPerItem = 10.00 taxRate= 0.08 subTotal = costPerItem * numItems taxAmount = subTotal * taxRate totalPrice = subTotal + taxAmount print("SALES RECEIPT") print("Number of Items: " + str(numItems)) print("Cost per Item : " ,"$"+ str(costPerItem) ) print("Tax Rate : " + str(taxRate),) print("Tax Amount : " ,"$"+ str(taxAmount)) print("Total Sale Price : ","$"+ str(totalPrice))
## Brady Nokes 9/24/20 logical expressions and IF statements ## ## Boolean Value ## Must have either True or False and they must be capitalized ## ##boolvar = True ##isAwake = True ##isInClass = True ## ## when you print it out it is not a string it will be a boolean ## ##print(type(boolvar)) ##print(isAwake) ##print(isInClass) ## ## Logical Expressions, Either greater than or less than. ## ##logicExp = 12==5 ##print(logicExp) ## when you print out that logicExp it will come out either as true or false ## you can add an equals sign to the end of the less than or greater than to check to see if it is equal/ ## if you want to see if it will not be equal to it you have to do a != ## when you want to see if the number is equal to something then you have to do == two equal signs ## you need to know all of the operators. ##> greter than ##< less than ##>= less than or equal to ##>= greater that or equal to ##!= does not equal to ##== equals to ##input1 = input("Enter a Number: ") ##input2 = input("Enter a Number: ") ## ## the block of code after your expression will only execute if the expressin is true ## ##if input1 > input2 : ## print("1st number was bigger than the second number") password = "Password1!" userPass = input("Password Please: ") if userPass == password : print("You Shall Pass") elif password != userPass : print("You Shall Not Pass!") elif not password : else:
#Tic Tac Toe #Plays the game of tic tac toe against a human opponent # Brady Nokes 11/20 # Global Constants X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 # Function definitions ######################################### def display_instructions(): """Display game instructions. to use ( display_instructions() )""" print( """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, 0-8. The number will correspond to the board position as illustrated: \t0 | 1 | 2 \t----------- \t3 | 4 | 5 \t----------- \t6 | 7 | 8 Prepare yourself human. The ultimate battle is about to begin. \n """ ) def next_turn(currentTurn): """this function switches the turn in the game. to use (turn = next_turn(currentTurn))""" if currentTurn == X: return O else: return X def pieces(): """Determine if player or computer goes first. to use ( computer,human = pieces() )""" goFirst = ask_yes_no("Do you require the first move? (y/n): ") if goFirst == "y" or goFirst == "yes": human = X computer = O print("\nThen take the first move. You will need it.") else: print("\nYour bravery will be your undoing... I will go first.") human = O computer = X return computer, human def ask_yes_no(question) : """Ask a yes or no question and get back a yes or no answer. to use (answer = ask_yes_no(question)) """ response = None while response not in ("y","n","yes","no"): response = input(question).lower() return response def new_board(): """Create new game board full of empty spaces. to use ( board = new_board() )""" board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board def display_board(board): """Display game board on screen. to use ( display_board(board) )""" print(str.format("\t{} | {} | {} ",board[0],board[1],board[2],)) print("\t","-----------------") print(str.format("\t{} | {} | {} ",board[3],board[4],board[5],)) print("\t","-----------------") print(str.format("\t{} | {} | {} ",board[6],board[7],board[8],)) def legal_move(board): moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves def human_move(board): """Get human move. to use ( move = human_move() )""" legal = legal_move(board) move = None while move not in legal: move = ask_number("Where will you move? (0 - 8): ",0,NUM_SQUARES) if move not in legal: print("\nSquare is occupied foolish0 human choose another one\n") print("Fine") return move def winner(board): """Determine the game winner""" WAYS_TO_WIN = ((0,1,2), #top row (0,4,8), #diagonal (2,4,6),#diagonal (1,4,7),# middle (3,4,5), (6,7,8), (0,3,6), (2,5,8) ) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board: return TIE return None def computer_move(board, computer, human): """Make Computer move""" # make a copy to work with since function will be changing list board = board[:] BEST_MOVES2 = (4,0,2,6,8,1,3,5,7) BEST_MOVES1 = (0,8,2,6,4,1,3,5,7) ## (4,1,3,5,7,0,2,6,8) unbeatable print("I shall take the number", end =" ") # if pc can win, take that move for move in legal_move(board): board[move] = computer if winner(board) == computer: print(move) return move board[move] = EMPTY #if human can win block that move for move in legal_move(board): board[move] = human if winner(board) == human: print(move) return move board[move] = EMPTY # since no one can win on next move,pick best open square if computer == X: for move in BEST_MOVES1: if move in legal_move(board): print(move) return move else: for move in BEST_MOVES2: if move in legal_move(board): print(move) return move def ask_number(question,low,high): """ Ask for a number within a range. to use ( answer = ask_number(question,low,high) )""" response = None while response not in range(low,high): response = int(input(question)) return response ########################################## # main Game def main(): players = input("1 or 2 players") display_instructions() turn = X computer,human = pieces() board = new_board() while not winner(board): if players == "2": display_board(board) move = human_move(board) board[move] = turn turn = next_turn(turn) else: if turn == human: move = human_move(board) board[move] = turn display_board(board) else: move = computer_move(board,computer,human) board[move] = turn display_board(board) turn = next_turn(turn) win = winner(board) print(win) main()
# Calculator Program # By Abe and Brady # IMPORTS from tkinter import * # Initializing the basic settings for GUI HEIGHT = 361 WIDTH = 291 TITLE = "Calculator" BACKGROUND = "darkgrey" FONT = "Sans_Serif" class App(Frame): def __init__(self, master): super(App, self).__init__(master) self.grid() self.screen = "0" self.opperand1 = "" self.opperand2 = "" self.operator = "" self.create_widgets() # # making widgets def create_widgets(self): self.lbl = Label(self, bg="white", width=32, height=4, text="", font=9) self.lbl.grid(row=0, column=0, columnspan=4) self.one = Button(self, text="1", command=self.num1, width=9, height=4).grid(row=1, column=0) self.two = Button(self, text="2", command=self.num2, width=9, height=4).grid(row=1, column=1) self.three = Button(self, text="3", command=self.num3, width=9, height=4).grid(row=1, column=2) self.four = Button(self, text="4", command=self.num4, width=9, height=4).grid(row=2, column=0) self.five = Button(self, text="5", command=self.num5, width=9, height=4).grid(row=2, column=1) self.six = Button(self, text="6", command=self.num6, width=9, height=4).grid(row=2, column=2) self.seven = Button(self, text="7", command=self.num7, width=9, height=4).grid(row=3, column=0) self.eight = Button(self, text="8", command=self.num8, width=9, height=4).grid(row=3, column=1) self.nine = Button(self, text="9", command=self.num9, width=9, height=4).grid(row=3, column=2) self.clear = Button(self, text="C", command=self.delete, width=9, height=4).grid(row=4, column=0) self.zero = Button(self, text="0", command=self.num0, width=9, height=4).grid(row=4, column=1) self.enter = Button(self, text="=", command=self.equals, width=9, height=4).grid(row=4, column=2) self.plus = Button(self, text="+", command=self.add, width=9, height=4).grid(row=1, column=3) self.minus = Button(self, text="-", command=self.subtract, width=9, height=4).grid(row=2, column=3) self.multiply = Button(self, text="*", command=self.multiple, width=9, height=4).grid(row=3, column=3) self.divide = Button(self, text="/", command=self.div, width=9, height=4).grid(row=4, column=3) def num1(self): if self.screen == "0": self.screen = "1" else: self.screen += "1" self.lbl.config(text=self.screen) def num2(self): if self.screen == "0": self.screen = "2" else: self.screen += "2" self.lbl.config(text=self.screen) def num3(self): if self.screen == "0": self.screen = "3" else: self.screen += "3" self.lbl.config(text=self.screen) def num4(self): if self.screen == "0": self.screen = "4" else: self.screen += "4" self.lbl.config(text=self.screen) def num5(self): if self.screen == "0": self.screen = "5" else: self.screen += "5" self.lbl.config(text=self.screen) def num6(self): if self.screen == "0": self.screen = "6" else: self.screen += "6" self.lbl.config(text=self.screen) def num7(self): if self.screen == "0": self.screen = "7" else: self.screen += "7" self.lbl.config(text=self.screen) def num8(self): if self.screen == "0": self.screen = "8" else: self.screen += "8" self.lbl.config(text=self.screen) def num9(self): if self.screen == "0": self.screen = "9" else: self.screen += "9" self.lbl.config(text=self.screen) def num0(self): self.screen += "0" self.lbl.config(text=self.screen) def add(self): self.opperand1 = self.screen self.screen = "0" self.operator = "+" self.lbl.config(text=self.screen) def subtract(self): self.opperand1 = self.screen self.screen = "0" self.operator = "-" self.lbl.config(text=self.screen) def multiple(self): self.opperand1 = self.screen self.screen = "0" self.operator = "*" self.lbl.config(text=self.screen) def div(self): self.opperand1 = self.screen self.screen = "0" self.operator = "/" self.lbl.config(text=self.screen) def delete(self): self.opperand1 = "" self.operator = "" self.opperand2 = "" self.screen = "0" self.lbl.config(text=self.screen) def equals(self): self.opperand2 = self.screen if self.opperand2 == "0" and self.operator == "/": self.lbl.config(text="Error") else: if self.operator == "+": self.lbl.config(text=int(self.opperand1)+int(self.opperand2)) elif self.operator == "-": self.lbl.config(text=int(self.opperand1)-int(self.opperand2)) elif self.operator == "*": self.lbl.config(text=int(self.opperand1)*int(self.opperand2)) elif self.operator == "/": self.lbl.config(text=int(self.opperand1)/int(self.opperand2)) # main loop def main(): root = Tk() root.geometry(str.format("{}x{}", WIDTH, HEIGHT)) root.title(TITLE) root.config(bg=BACKGROUND) app = App(root) root.mainloop() main()
def f(s): return s.title() l = ['adam', 'LISA', 'barT'] print map(f, l) l = [1, 2, 3, 4] def f(a, b): return a*b print reduce(f, l)
from bs4 import BeautifulSoup html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" class="special"> <title>First HTML Page</title> </head> <body> <div id="first"> <h3 data-example="yes">hi</h3> <p>more text.</p> </div> <ol> <li class="special">This list item is special.</li> <li class="special">This list item is also special.</li> <li>This list item is not special.</li> </ol> <div data-example="yes">bye</div> </body> </html> """ soup = BeautifulSoup(html, "html.parser") # method one # el = soup.select(".special")[0] # print(el.get_text()) # also print(el) will work for retriveing a singular element - comes in handy # for bits and pieces of data. # ############################################################################ # ############################################################################ # method two # for el in soup.select(".special"): # print(el.get_text()) # Output - how ever many items with the class special # ############################################################################ # ############################################################################ # method three for el in soup.select(".special"): print(el.name) # Output - two li's and meta # ############################################################################ # ############################################################################ # method four for el in soup.select(".special"): print(el.attrs) # Output - meta li li {'charset': 'UTF-8', 'class': ['special']} {'class': ['special']} {'class': ['special']}
import random import math import enemy import sys class human: """大体共通するクラス""" def __init__(self,name,job,hp,mp,n_attack): self.name=name self.job=job self.max_hp=hp self.hp=hp self.max_mp=mp self.mp=mp self.n_attack=n_attack self.power=1 self.power_turn=0 self.cri_up_turn=0 self.poison=0 self.mahi=0 self.blood=0 def show(self): print("\n名前:{} | 職業:{} | hp:{}/{} | mp:{}/{} |".format(self.name,self.job,self.hp,self.max_hp,self.mp,self.max_mp)) def check(self): if self.poison>0: self.poison_status() else: pass def remaing_hp(self,damage): self.hp-=damage print("\n{}は{}のダメージをうけた\n".format(self.name,damage)) if self.hp<=0: print("死んだ") sys.exit() def remaing_mp(self,used_mp): self.mp-=used_mp def charge_hp(self,care_hp): if self.hp<self.max_hp: self.hp+=care_hp print("\n{}は\nhpを{}回復した\n".format(self.name,care_hp)) if self.hp>self.max_hp: self.hp=self.max_hp else: print("これ以上回復できない") def charge_mp(self,care_mp): if self.mp<self.max_mp: self.mp+=care_mp print("\n{}は\nmpを{}回復した\n".format(self.name,care_mp)) if self.mp>self.max_mp: self.mp=self.max_mp else: print("これ以上回復できない") def poison_status(self): self.remaing_hp(15) self.poison-=1 print("毒で15のダメージ") if self.hp<=0: print("死んだ") sys.exit() def receive_poison(self,poison_turn): self.poison=poison_turn def base_attack(self,trick): self.power_status(self.power_turn) if self.cri_up_turn>0: self.cri=random.randint(1,10) if self.cri>3: self.cri_rate=1.4 else: self.cri_rate=1 self.cri_up_turn-=1 else: self.cri=random.randint(1,10) if self.cri>8: self.cri_rate=1.4 else: self.cri_rate=1 attack_value=math.floor(trick*self.cri_rate*self.power) enemy.ene.remaing_hp(attack_value) def power_status(self,power_turn): self.power_turn=power_turn if self.power_turn>0: self.power=1.5 self.power_turn-=1 elif self.power_turn<0: self.power=0.5 self.power_turn+=1 else: self.power=1 def next_do(self): while True: try: do=int(input("1:攻撃 2:アイテム 3:特技 4:ステータス\n")) if do>4 and do<=0: print("入力し直し") elif do>0 and do<5: break else: print("入力し直し") except: print("入力し直し") if do==1: self.base_attack(self.n_attack) elif do==2: item.choice_item(self.name) elif do==3: self.special() elif do==4: show_status().show_info(self.name) class show_status: def show_info(self,name): self.name=name man2.show() enemy.ene.show() if self.name=="man": self.name=man2 self.name.next_do() class Item: def __init__(self): self.hp_recover=10 self.mp_recover=10 self.gedoku=10 self.siketu=10 self.itamidome=10 def choiced_hp_recover(self): if self.hp_recover>0: self.name.charge_hp(50) self.hp_recover-=1 else: print("薬がない") self.choice_item(self.name) def choiced_mp_recover(self): if self.mp_recover>0: self.name.charge_mp(50) self.mp_recover-=1 else: print("薬がない") self.choice_item(self.name) def choiced_gedoku(self): if self.gedoku>0: self.name.receive_poison(0) else: print("薬がない") self.choice_item(self.name) def choiced_siketu(self): pass def choiced_itamidome(self): pass def choice_item(self,name): if name=="man": self.name=man2 while True: try: choice=int(input("1:hp回復薬 {} |2:mp回復薬 {} |3:解毒剤 {} |4:戻る".format(self.hp_recover,self.mp_recover,self.gedoku))) if choice>4 and choice<1: print("やり直し") else: break except: print("やり直し") if choice==1: self.choiced_hp_recover() elif choice==2: self.choiced_mp_recover() elif choice==3: self.choiced_gedoku() elif choice==4: self.name.next_do() class man(human): def do_power_up(self): if self.mp>0: self.remaing_mp(10) self.power_status(5) print("強化した\n") else: print("mpが足りない!") def strong_attack(self): if self.mp>0: self.remaing_mp(5) self.base_attack(50) else: print("mpが足りない!") def critical_up(self): if self.mp>0: self.remaing_mp(10) self.cri_up_turn=5 print("集中した\n") else: print("mpが足りない!") def special(self): while True: try: do=int(input("1:強化 2:強攻撃 3:集中 4:戻る\n")) if do>4 and do<=0: print("入力し直し") elif do>0 and do<5: break else: print("入力し直し") except: print("入力し直し") if do==1: self.do_power_up() elif do==2: self.strong_attack() elif do==3: self.critical_up() else: self.next_do() item=Item() man2=man("man","デバック",300,300,30)
print("Programa que converte temperaturas") print("Escolha o tipo de conversao") print("----------------------------------------") print("Codigo | Funcao") print(" 1 | Celsius para Fahrenheit") print(" 2 | Fahrenheit para Celsius") ver=0 while(ver==0): try: codigo = int(input("codigo:")) if codigo == 1: C = float(input("Insira a temperatura em Celsius:")) F = (C * 9 / 5) + 32 print(F, "Fahrenheit") ver=1 elif codigo == 2: F = float(input("Insira a temperatura em Fahrenheit:")) C = (F - 32) * 5 / 9 print(C, "Celsius") ver=1 else: print("Valor invalido, digite novamente") except ValueError: print("Valor Invalido, digite novamente")
''' An object is used to represent and encapsulate all the information needed to call a method at a later time. Client instantiates the command object and provides the information to call the method later Invoker decides when the method should be called Receiver is an instance of the class that contains the method's code ''' #http://en.wikipedia.org/wiki/Command_pattern#Python class Switch(object): """INVOKER""" def __init__(self, flip_up_cmd, flip_down_cmd): self.flip_up = flip_up_cmd self.flip_down = flip_down_cmd class Light(object): """RECEIVER""" def turn_on(self): print "The light is on" def turn_off(self): print "The light is off" class LightSwitch(object): """CLIENT""" def __init__(self): lamp = Light() self._switch = Switch(lamp.turn_on, lamp.turn_off) def switch(self, cmd): if cmd == "ON": self._switch.flip_up() elif cmd == "OFF": self._switch.flip_down() else: print 'Only accepts "ON" or "OFF"' light_switch = LightSwitch() light_switch.switch("ON") light_switch.switch("OFF") light_switch.switch("*****")
a=[] c=[] n1=int(input("Enter number of elements:")) for i in range(1,n1+1): b=int(input("Enter element:")) a.append(b) n2=int(input("Enter number of elements:")) for i in range(1,n2+1): d=int(input("Enter element:")) c.append(d) new=a+c new.sort() print("Sorted list is:",new)
import random def generate(columns=30,max=100): result=[] for i in range(columns): result.append(random.randint(0,max-1)) return result n=1000 k=500 list1=generate(n,k) def quickSort(list1): recursive_quicksort(list1,0,len(list1)-1) return list1 def recursive_quicksort(A,p,q): if p<q: r=partition(A,p,q) recursive_quicksort(A,p,r-1) recursive_quicksort(A,r+1,q) def partition(A,p,q): i=p-1 pivot=A[q] for j in range(p,q): if A[j]<=pivot: i+=1 A[i],A[j]=A[j],A[i] A[i+1],A[q]=A[q],A[i+1] return i+1 print quickSort(list1)
# Character Picture Grid practice project, pg. 108 grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] # Create a program to take the above grid and print a version rotated 90 degrees to show an ascii heart for y in range(len(grid[0])): for x in range(len(grid)): print(grid[len(grid) - 1 - x][y], end='') #print each character subsequently print() # go to a new line after printing all of the characters in a line
#! python3 # spiralDraw.py - a simple program to take control of the mouse and draw a square spiral # in the window of a drawing app. When run, the user has 5 seconds to position the mouse # cursor over the window of a drawing app, and the script will do the rest # Automate the Boring Stuff with Python 2e, Ch.20, pg.479 # NOTE: though the book says the drag() function defaults to left button, this wouldn't work # until I explicitly included it as an argument import pyautogui, time time.sleep(5) # wait 5 seconds pyautogui.click() # click to make the window under the mouse active distance = 300 change = 20 while distance > 0: pyautogui.drag(distance, 0, duration=0.2, button='left') # move right distance = distance - change pyautogui.drag(0, distance, duration=0.2, button='left') # move down pyautogui.drag(-distance, 0, duration=0.2, button='left') # move left distance = distance - change pyautogui.drag(0, -distance, duration=0.2, button='left') # move up
'''There is a contest with interactive problems where N people participate. Each contestant has a known rating. Chef wants to know which contestants will not forget to flush the output in interactive problems. Fortunately, he knows that contestants with rating at least r never forget to flush their output and contestants with rating smaller than r always forget to do it. Help Chef! Input The first line of the input contains two space-separated integers N and r. Each of the following N lines contains a single integer R denoting the rating of one contestant. Output For each contestant, print a single line containing the string "Good boi" if this contestant does not forget to flush the output or "Bad boi" otherwise. ''' N,r=map(int,input().split()) for i in range(N): R=int(input()) if R>=r: print("Good boi") else: print("Bad boi")
#There is an array with some numbers. All numbers are equal except for one. Try to find it! def find_uniq(arr): x=max(arr) y=min(arr) z=0 for i in range(3): if arr[i]==x: z+=1 if(z>=2): return y # n: unique integer in the array else: return x
''' Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage. When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A? More generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A? The result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages. If v1 >= v2 then return nil, nothing, null, None or {-1, -1, -1} for C++, C, Go, Nim, [] for Kotlin or "-1 -1 -1". ''' def race(v1, v2, g): if(v2>v1): l=[] j=0 k=0 i=(g*3600)//(v2-v1) if i>=3600: j+=i//3600 i=i-(3600*j) if i>=60: k+=i//60 i=i-(60*k) l.append(j) l.append(k) l.append(i) return l else: return None
import math #Ingreso de la llave mykey=input("NOTA: Su palabra clave NO puede repetir letras \nIntroducir Clave:") mykey=mykey.upper() def encryptMessage(msg): cipher = "" k_indx = 0 msg_len = float(len(msg)) msg_lst = list(msg) key_lst = sorted(list(mykey)) # Número de columnas de la matriz col = len(mykey) # Número de filas de la matriz row = int(math.ceil(msg_len / col)) # Llenado de lugares vacios en la matriz fill = int((row * col) - msg_len) msg_lst.extend('X' * fill) # Creación de la matriz matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)] for _ in range(col): curr_idx = mykey.index(key_lst[k_indx]) cipher += ''.join([row[curr_idx] for row in matrix]) k_indx += 1 return cipher def decryptMessage(cipher): msg = "" # Indices de la llave k_indx = 0 msg_indx = 0 msg_len = float(len(cipher)) msg_lst = list(cipher) # Número de columnas col = len(mykey) # Filas de la matriz row = int(math.ceil(msg_len / col)) # Ordena la llave de manera alfabeticamente key_lst = sorted(list(mykey)) # crea la matriz para desencriptar dec_cipher = [] for _ in range(row): dec_cipher += [[None] * col] # Acomoda las columnas de acuerdo al orden de la llave for _ in range(col): curr_idx = mykey.index(key_lst[k_indx]) for j in range(row): dec_cipher[j][curr_idx] = msg_lst[msg_indx] msg_indx += 1 k_indx += 1 # Conversión a string try: msg = ''.join(sum(dec_cipher, [])) except TypeError: raise TypeError("This program cannot", "handle repeating words.") null_count = msg.count('_') if null_count > 0: return msg[: -null_count] return msg msg = str(input("Ingrese un mensaje:")) msg = msg.upper() cipher = encryptMessage(msg) print("Mensaje encriptado: {}". format(cipher)) print("Mensaje desencriptado: {}". format(decryptMessage(cipher)))
#!/usr/bin/python import math wheelbase = 33 print("Enter x1: ") x1 = raw_input() x1 = float(x1) print("Enter y1: ") y1 = raw_input() y1 = float(y1) radius = (x1*x1 + y1*y1 )/ (2 * x1) radius = -radius steer_angle = math.atan(wheelbase/radius) print("radius: " + str(radius) + " steering angle: " + str(steer_angle))
import re # вариант 3 # ищем все фамилии в тексте и помещаем их в массив def find_surnames(filename): file_to_check = open(filename) test_text = file_to_check.read() surnames = re.findall(r'\b[А-Яё][а-яё]+ [А-ЯЁ].[А-ЯЁ].', test_text) return surnames # пробегаемся по тестам и выводим фамилии, обрезая инициалы for i in range(1, 6): string_name = 'string_' + str(i) + '.txt' finalSurnames = find_surnames(string_name) if len(finalSurnames) == 0: print('Тест ' + str(i)) print("Нет фамилий") print() else: print('Тест ' + str(i)) for surname in sorted(finalSurnames): print(surname[:-5]) print()
wert1 = 1 wert2 = 2 if wert1 > wert2: print(str(wert1)) elif wert1 < wert2: print(str(wert2)) else: print("Die Werte sind gleichgross")
""" Generator of fibonacci numbers input: amount of numbers """ from typing import Iterator def fibonacci(limit: int = 10) -> Iterator[int]: yield 1 yield 1 prev = 1 current = 1 limit -= 2 while limit: prev, current = current, prev + current yield current limit -= 1 def main(): n = int(input()) print(fibonacci(n)) if __name__ == "__main__": main() def test_success(): generator = fibonacci(10) assert [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] == [i for i in generator], 'Неверные числа Фибоначчи'
class Palindrome: @staticmethod def is_palindrome(word): reverse = word[::-1] if reverse.upper() == word.upper(): return True else: return False word = input() print(Palindrome.is_palindrome(word))
def solution(n): def convert_3(num): note = '012' q, r = divmod(num, 3) w = note[r] return convert_3(q) + w if q else w n_3 = convert_3(n) answer = 0 for i, v in enumerate(n_3): answer += 3 ** i * int(v) return answer
n=input("enter the number") sum=0 while(n>0): n=n-1 sum=sum+n print(sum)