blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5fce1e2595ed7c9c7fb24b8e96de88d84edbe971
UW-ParksidePhysics/Jones-Julia
/4.2_f2c_cml_02.py
375
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 29 16:13:56 2020 @author: julia """ ### Program to convert Farenheit to Celcius via the command line import sys # Command line user input F = int(sys.argv[1]) # 4.2_f2c_cml_[02].py 300 # Function code def T(F): T = (5 / 9) * (F - 32) return T print("Temperature in Celsius degrees =", C(F))
44c7c8f2f55257e5cbf9b4f21a5a4f1f87a048ea
yuvalperes/Distributed-computing
/consensus_repeated_majority.py
5,451
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sun June 02 18:05:49 2019 This program implements the repeated majority protocol for distributed computing (population protocol model). There are n nodes, each having an initial belief (a bit in {0, 1}). The goal is that after running some distributed protocol each node has the correct initial belief with high probability. Relevant parameters are the amount of memory that each node has, the time to consensus, the amount of communication used. System dynamics: each node keeps track of a state which is either 0, 1, or ?. Initially each node has state 0 or 1. In each round, a node gets selected uniformly at random and is matched with a random other node. The nodes that get matched exchange state and update their own state based on this communication. The repeated majority protocol works as follows: Let U, V, and S represent, respectively, the set of nodes storing 0, 1, and ? --> If a node in U (resp. V) contacts a node in U, S (resp. V, S), then it does not update its value. --> If a node in U (resp. V) contacts a node in V (resp. U), it updates its value to ? (resp. ?). --> If a node in S contacts a node in U (resp. V), then it updates it’s value to 1 (resp. 0). """ import random import numpy import math import matplotlib.pyplot as plt qval = 5 # simulate one round of the process, in which two random nodes get matched; # we work here with milan's version, where the initiator updates state # the input parameters are: # n = number of nodes, t = time unit, b = belief vector, correct/wrong/q are vectors with the number of nodes that # are 1 (correct), 0 (wrong), and q (?) throughout time def simulate_round(n, t, b, correct, wrong): i = random.randint(0, n-1) # node that communicates in this round. This node will get matched with a random other node jj = random.randint(0, n-2) if jj < i: # we have to fix a bit the index of the node that i contacts possibly j = jj else: j = jj + 1 # the pair (i,j) talks now, with i being the initiator if (b[i] == 0 and b[j] == 1): b[i] = qval wrong[t] = wrong[t] - 1 elif (b[i] == 1 and b[j] == 0): b[i] = qval correct[t] = correct[t] - 1 elif (b[i] == qval): b[i] = b[j] if b[j] == 1: correct[t] = correct[t] + 1 elif b[j] == 0: wrong[t] = wrong[t] + 1 return [b, correct, wrong] # simulate the system dynamics def sim(n, c, T, correct, wrong): total_time = 0 b = [1 for e in range(n)] # b[i] is the initial belief bit of node i z = math.ceil(c * n) for i in range(z): b[i] = 0 # the nodes from 0 to z are in the minority and have the wrong bit correct[0] = n - z # number of nodes with majority opinion (initially) wrong[0] = z # number of nodes with minority opinion t = 1 # round number while (t < T): # while did not run until the max number of allowed rounds and there are beliefs different from 1 (i.e. the correct bit) correct[t] = correct[t-1] wrong[t] = wrong[t-1] [b, correct, wrong] = simulate_round(n, t, b, correct, wrong) if (correct[t] == n): print("Reached consensus at time", t) return [correct, wrong, t] t = t + 1 return [correct, wrong, t] def main(): n = 0 # simulating a system with 5000 nodes; this can be changed N_Default = 1000 try: n_user = input("Enter the number of nodes (default: 1000):") n = int(n_user) except ValueError: print("Using default n =", N_Default) n = N_Default c = 0 # initial minority fraction; should be a number in [0, 1/2) try: c_user = input("Enter the initial minority fraction (default: 0.333)") c = float(c_user) except ValueError: print("Using default minority fraction = 1/3") c = 1/3 T = 10 * n * math.ceil(math.log(n)) # number of rounds for simulating the system dynamics correct = [0 for i in range(T)] # correct[t] contains the fraction of correct nodes at time t wrong = [0 for i in range(T)] # wrong[t] contains the fractions of wrong nodes at time t q = [0 for i in range(T)] # q[t] contains the fraction of ? nodes at time t time = 0 # keep track of the exact time it takes to run the simulation [correct, wrong, time] = sim(n, c, T, correct, wrong) q = [0 for e in range(time)] for t in range(time): correct[t] = correct[t] / n wrong[t] = wrong[t] / n q[t] = (n - correct[t] - wrong[t]) / n print("Showing the fraction of correct, incorrect, and ? nodes over time") plt.figure(0) plt.ylabel("Fraction of correct nodes") plt.xlabel("Time") plt.plot(correct[0:time], color='blue') plt.figure(1) plt.ylabel("Fraction of wrong nodes") plt.xlabel("Time") plt.plot(wrong[0:time], color='red') plt.figure(2) plt.ylabel("Fraction of question marks") plt.xlabel("Time") plt.plot(q[0:time], color = 'orange') plt.show() main()
f96c5201ecea49527afcc2bb93eaf384eddd31aa
pallavije/-An-Analysis-of-the-Effect-of-News-Sentiment-on-the-Stock-Market-using-LSTM
/stockPredictions_Without_News.py
3,440
3.640625
4
# Importing the libraries import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout # loading dataset dataset = pd.read_csv("AppleNewsStock.csv") # dropping news column dataset.drop(columns="News", inplace=True) print(dataset.head()) # visualizing the dataset plt.figure() plt.plot(dataset["Open"]) plt.plot(dataset["High"]) plt.plot(dataset["Low"]) plt.plot(dataset["Close"]) plt.title('Apple stock price history') plt.ylabel('Price (USD)') plt.xlabel('Days') plt.legend(['Open', 'High', 'Low', 'Close']) plt.show() # Plotting the volume history plt.figure() plt.plot(dataset["Volume"]) plt.title('Apple stock price history') plt.ylabel('Volume') plt.xlabel('Days') plt.show() # checking null values in the dataset print(dataset.isna().sum()) # splitting dataset into train and test data features = ["Open","High","Low","Close",'Adj Close', 'Volume', 'Index'] train, test = train_test_split(dataset, test_size=0.2, random_state=3) print("Train data shape : ", train.shape) print("Test data shape : ", test.shape) print("Sample Input data") print(train.iloc[0:2]) # normalization scaler = MinMaxScaler() normalizedTrain = scaler.fit_transform(train[features]) normalizedTest = scaler.fit_transform(test[features]) print("Post normalization - shape of data :-") print("\tNormalized train data shape : ", normalizedTrain.shape) print("\tNormalized test data shape : ", normalizedTest.shape) print("\tSample Input data") print(normalizedTrain[0:2]) # converting data into 3D data for LSTM in the timestep of 2 months X_train = [] y_train = [] for i in range(60, len(normalizedTrain)): X_train.append(normalizedTrain[i-60:i, 0]) y_train.append(normalizedTrain[i, 0]) X_train, y_train = np.array(X_train), np.array(y_train) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) print("3D data shape both input and output") print(X_train.shape) print(y_train.shape) # defining model model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1))) model.add(Dropout(0.2)) model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(units=1)) model.compile(optimizer='adam', loss='mean_squared_error') # Training trainedModel = model.fit(X_train, y_train, epochs=100, batch_size=32) # plotting the results plt.figure(figsize=(16, 5)) plt.plot(trainedModel.history['loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train'], loc='upper right') plt.show() X_test = [] for i in range(60, len(normalizedTest)): X_test.append(normalizedTest[i-60:i, 0]) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) predicted = model.predict(X_test) predictedDataset = np.zeros(shape=(len(predicted), 7)) predictedDataset[:, 0] = predicted[:, 0] predict = scaler.inverse_transform(predictedDataset)[:, 0] print(predict) # Visualising the results plt.plot(predict, color='blue', label='Predicted Apple Stock Price') plt.title('Apple Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Apple Stock Price') plt.legend() plt.show()
297c6e0a12304e5487609c3f792d8d33dfdd2a75
Adiboy3112/KOSS-TEACHING-TASK
/Koss_codes/Context Managet tutorial code/class_contextmanager.py
723
3.84375
4
class open_file(): def __init__(self,filename, mode):#will take the parameters to open file self.filename=filename self.mode = mode self.file = open(self.filename,self.mode) print("your file has been opened!") #file opened def __enter__(self):#will give access to user to work) return self.file def __exit__(self, exc_type, exc_value, exc_traceback): self.file.close() print("File is closed?") print(self.file.closed) #file closed with open_file("class.txt", "w") as f: print("starting to write in file") f.write("Good to go to create ur custom context manager!")
57b85d6d1fd74764abb6c050da06652cdaaf24dd
proleaders/python_problem_solving
/Minimum Distances.py
1,217
4.0625
4
#!/bin/python3 import math import os import random import re import sys # Complete the minimumDistances function below. def minimumDistances(a): li = [] # nested loop is applied to find out the the matching pair of elements in the given array for i in range(len(a)): for j in range(len(a)): if a[i] == a[j] and i != j: # we don't consider i == j ,because if we consider i == j then it means we pair we the same element itself i.e., (0,0) if j > i: li.append([i,j]) if len(li) == 0: # if there are no matching pair then, we then w have to return (-1) return (-1) else: # if there are matching pair res = [] for i in li: res.append(abs(i[0]-i[1])) # this is given that we have to find the absoulute diffrence between the mathing pair of the given element # print(res) return(min(res)) # here we return the minimum value among all the diffrences if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) a = list(map(int, input().rstrip().split())) result = minimumDistances(a) fptr.write(str(result) + '\n') fptr.close()
a755bf44d79525affb7c53c13d367878cdd3819c
stoneeve415/LintCode
/_56_k_sum.py
5,223
3.65625
4
""" @title: 56 57 58,K个数之和 @author: evestone """ ''' 2-sum ''' # 使用hash表 # 2-sum def two_sum(arr, target): hash = {} for i, item in enumerate(arr): if target-item in hash: return [hash[target-item], i] hash[item] = i return [-1, -1] # 遍历即可 # 2-sum class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None def two_sum_bst(root, target): stack = [] sets = set() while root is not None or len(stack) != 0: while root is not None: val = root.val if val in sets: return [val, target-val] sets.add(target - val) stack.append(root) root = root.left root = stack.pop(-1).right # 头尾指针 # 2-sum sorted array def two_sum_arr(nums, target): _len = len(nums) left = 0 right = _len - 1 while left < right: _sum = nums[left] + nums[right] if _sum > target: right -= 1 elif _sum < target: left += 1 else: return [left+1, right+1] return [] ''' 3-sum ''' # 一层循环加两个头尾指针 # 3-sum def three_sum(numbers): numbers.sort() res = [] for k, item in enumerate(numbers[:-2]): # 最小数大于0 结束 if numbers[k] > 0: break # 去掉重复 if k > 0 and numbers[k] == numbers[k - 1]: continue target = -item i, j = k+1, len(numbers)-1 while i < j: if numbers[i] + numbers[j] > target: j -= 1 elif numbers[i] + numbers[j] < target: i += 1 else: res.append([numbers[k], numbers[i], numbers[j]]) i += 1 j -= 1 # 去掉重复 while i < j and numbers[i] == numbers[i-1] and numbers[j] == numbers[j+1]: i += 1 j -= 1 return res # 一层循环叫两个头尾指针 # 3-sum-c def three_sum_c(numbers, target): numbers.sort() min_gap = 65536 for k, item in enumerate(numbers[:-2]): # 去掉重复 if k > 0 and numbers[k] == numbers[k - 1]: continue i, j = k+1, len(numbers)-1 while i < j: gap = numbers[k] + numbers[i] + numbers[j] - target if abs(min_gap) > abs(gap): min_gap = gap if gap > 0: j -= 1 elif gap < 0: i += 1 else: min_gap = 0 return min_gap + target return min_gap + target # 一层循环加两个头尾指针 # 3-sum-triangle def triangle_count(S): S.sort() count = 0 # ite为当前最大值 for k, item in enumerate(S[2:],start=2): i, j = 0, k-1 while i < j: if S[i]+S[j] > item: count += j-i j -= 1 else: i += 1 return count ''' 4-sum ''' # 两层循环加两个头尾指针 # 4-sum def four_sum(numbers, target): numbers.sort() res = [] for k, item1 in enumerate(numbers[:-3]): # 去掉重复 if k > 0 and numbers[k] == numbers[k - 1]: continue for m, item2 in enumerate(numbers[k+1:-2],start=k+1): # 去掉重复 if m > k+1 and numbers[m] == numbers[m - 1]: continue tar = target - item1 - item2 i, j = m+1, len(numbers)-1 while i < j: if numbers[i] + numbers[j] > tar: j -= 1 elif numbers[i] + numbers[j] < tar: i += 1 else: res.append([numbers[k], numbers[m], numbers[i], numbers[j]]) i += 1 j -= 1 # 去掉重复 while i < j and numbers[i] == numbers[i-1] and numbers[j] == numbers[j+1]: i += 1 j -= 1 return res if __name__ == '__main__': two_1 = 2 # # 两数之和 # arr = [2, 7, 11, 15] # target = 9 # print(two_sum(arr, target)) two_2 = 2 # # 两数之和BST树 # root = TreeNode(4) # for i in range(1,9): # name = 'node' + str(i) # locals()[name] = TreeNode(i) # root.left = node2 # root.right = node6 # node2.left = node1 # node2.right = node3 # node6.left = node5 # node6.right = node7 # node7.right = node8 # target = 9 # print(two_sum_bst(root, target)) two_3 = 2 # nums = [2, 7, 11, 15] # target = 9 # print(two_sum_arr(nums, target)) three_1 = 3 # # 三数之和 # arr = [-8,0,-7,-101,-123,-1,-2,0,-1,0,-1111,0,-1,-2,-3,-4,-5,-6,-100,-98,-111,-11] # print(three_sum(arr)) three_2 = 3 # # 最近三数之和 # arr = [2, 7, 11, 15] # target = 3 # print(three_sum_c(arr, target)) three_3 = 3 S = [3, 4, 6, 7] print(triangle_count(S)) four_1 = 4 # # 四数之和 # arr = [1, 0, -1, 0, -2, 2] # target = 0 # print(four_sum(arr, target))
2da242c99607b5007458aa04fcae524c871a94b7
Dheebhika/Python-beginner
/day_2/parameters.py
231
3.640625
4
def with_default_parameters(number1=10, number2=10): if number1 != number2: return number1 + number2 else: return (number1 + number2) * 2 print(with_default_parameters()) print(with_default_parameters(2))
d9146a29ae5785023096c03d44a9188271d17419
NTR1407/python
/Prueba/ordenamiento.py
216
3.671875
4
def ordenamiento(lista): z = [] for i in lista: z.append(''.join(sorted(i,key=str.upper))) return z print(ordenamiento(lista = ["Hola","soy","el","candidato","al","cargo","Data Expert"]))
30872f86a64ea320710460c5f9967c65d92fe727
EMIAOZANG/assignment4
/lw1582/answer8.py
204
3.671875
4
#!/usr/bin/env python d = {'first' : [2,1],'second' : [2,3],'third' : [3,4]} a = d['first'] d['first'] = d['third'] d['third'] = a d["third"].sort() d['fourth'] = d['second'] del d['second'] print d
a5d9f3b74fbe6142295a57668edc4fdbb6d567d0
CowsSayOink/Euler
/Euler36.py
403
3.78125
4
def conv(x): """ Converts from binary to decimal""" return int(x[2:]) def ispal(x): a=str(x) b=len(a) for c in range((b//2)+1): if a[c]!=a[-1-c]: return False return True total=0 for a in range(1000000): if ispal(a)and ispal(conv(bin(a))): total+=a print(total)
0ed0bf532065c01e8ca4f7a9cbb8527e26f57ae1
robert/programming-feedback-for-advanced-beginners
/editions/1-2-tic-tac-toe/original.py
10,771
3.984375
4
## This code is made available under the Creative Commons Zero 1.0 License (https://creativecommons.org/publicdomain/zero/1.0) # -*- coding: utf-8 -*- """ Created on Tue Oct 29 10:40:33 2019 """ from random import randint class Board: """ Class defining a tic-tac-toe board and associated methods """ def __init__(self, dim=3, num_players=2): self.num_players = num_players if dim > 9: raise ValueError("Board too big") self.dim = dim self.board = [[None for i in range(0, self.dim)] for j in range(0, self.dim)] self.players = ["X", "O"] + [chr(i) for i in range(65, 90)] def __str__(self): return self.__repr__() def __repr__(self): """ print a board in this form: 1 2 3 ------ 1 - X O 2 X - O 3 X - O """ return_string = ( " " + "".join([str(i).rjust(2, " ") for i in range(1, len(self.board[0]) + 1)]) + "\n" ) return_string = return_string + "--" * (len(self.board[0]) + 1) + "\n" i = 1 for row in self.board: return_string = return_string + str(i) + ":" for item in row: if item is not None: return_string = return_string + self.players[item] + " " else: return_string = return_string + "- " return_string = return_string + "\n" i = i + 1 return return_string def random_board(self, fill_level=0): """ returns a correcty filled board with fill_level fields filled """ if fill_level == 0: fill_level = self.dim ** 2 if fill_level > self.dim ** 2: raise ValueError("fill_level too high") self.board = [[None for i in range(0, self.dim)] for j in range(0, self.dim)] player = 0 for _ in range(0, fill_level): pos = self.get_move_random_position() self.update(pos, player) player = (player + 1) % self.num_players return self def flatten(self): """ returns a 1d array of the board """ flattened = [] for row in self.board: flattened = flattened + row return flattened def reshape(self, flattened): """ reshapes a 1d array to a rectangular board """ self.board = [ flattened[i : i + self.dim] for i in range(0, len(flattened), self.dim) ] def update(self, coord, player): """ Sets a position on a board for a player. No check if position is legal done at this point """ # new_board = self.board x_coord = coord[0] - 1 y_coord = coord[1] - 1 if self.board[x_coord][y_coord] is None: self.board[x_coord][y_coord] = player # self.board = new_board else: raise ValueError("position already filled") def valid_move(self, coord): """ Returns True if the move is valid (i.e. position not yet blocked and coordinates not out of range) """ x_coord = coord[0] - 1 y_coord = coord[1] - 1 try: valid_move = self.board[x_coord][y_coord] is None except IndexError: valid_move = False return valid_move def winner(self): """ Decide whether there is a winner on the current board. Currently this only works for 3x3 boards """ if self.dim != 3: raise ValueError("winner not implemented for dimensions other than 3") rows_and_cols = ( [[self.board[i][j] for i in range(0, 3)] for j in range(0, 3)] + [[self.board[j][i] for i in range(0, 3)] for j in range(0, 3)] + [[self.board[i][i] for i in range(0, 3)]] + [[self.board[2 - i][i] for i in range(0, 3)]] ) for row in rows_and_cols: winner = (len(set(row)) == 1) and (row[0] is not None) if winner: winning_player = self.players[row[0]] return winning_player if None in self.flatten(): return None return "Draw" def get_move_user_input(self, player): print(self.__repr__()) input_string = input(f"{self.players[player]}: ") x_coord, y_coord = int(input_string[0]), int(input_string[1]) return x_coord, y_coord def get_move_random_position(self, player=0): """ Find a random open position and return it. First count all None's, then find a random one in the board """ legal_moves = self.get_all_legal_moves() if len(legal_moves) == 0: return None pos = randint(0, len(legal_moves) - 1) return legal_moves[pos] def get_move_heuristic_1(self, player=0): """ Check if center position is empty, if yes, take it """ x_coord = int((self.dim + 1) // 2) y_coord = int((self.dim + 1) // 2) if self.valid_move((x_coord, y_coord)): return x_coord, y_coord return self.get_move_random_position() def get_move_heuristic_2(self, player=0): """ Check if center position is empty, otherwise put weights on corners and choose best corner """ x_coord = int((self.dim + 1) // 2) y_coord = int((self.dim + 1) // 2) if self.valid_move((x_coord, y_coord)): return x_coord, y_coord corners = [(1, 1), (3, 1), (1, 3), (3, 3)] free_corners = {} for corner in corners: free_corners[corner] = 1 * self.valid_move(corner) # calculate weights by looking if adjacent corners are also empty if sum(free_corners.values()) > 0: weights = {} weights[(3, 3)] = free_corners[(3, 3)] * ( 1 + free_corners[(3, 1)] + free_corners[(1, 3)] ) weights[(1, 1)] = free_corners[(1, 1)] * ( 1 + free_corners[(3, 1)] + free_corners[(1, 3)] ) weights[(3, 1)] = free_corners[(3, 1)] * ( 1 + free_corners[(1, 1)] + free_corners[(3, 3)] ) weights[(1, 3)] = free_corners[(1, 3)] * ( 1 + free_corners[(1, 1)] + free_corners[(3, 3)] ) max_value = max(weights.values()) best_corner = list(weights.keys())[list(weights.values()).index(max_value)] return best_corner return self.get_move_random_position() def find_two_in_row(self, player): rows_and_cols_idx = ( [[(i, j) for i in range(0, 3)] for j in range(0, 3)] + [[(j, i) for i in range(0, 3)] for j in range(0, 3)] + [[(i, i) for i in range(0, 3)]] + [[(2 - i, i) for i in range(0, 3)]] ) for pairs in rows_and_cols_idx: row = [self.board[c[0]][c[1]] for c in pairs] if row.count(player) == 2 and (None in row): ret_val = pairs[row.index(None)] return ret_val[0] + 1, ret_val[1] + 1 return None def get_move_heuristic_3(self, player): """ Check if there is a winning move, then if there is a loosing move, finally choose a random move """ if self.dim != 3: raise ValueError( "get_move_heuristic_3 not implemented for dimensions other than 3" ) # check for winning move move = self.find_two_in_row(player) if move is not None: # print("found winning: ", move) return move # check for losing move # print("checking for losing") move = self.find_two_in_row(1 - player) if move is not None: # print(move) return move return self.get_move_random_position(player) def get_move_heuristic_4(self, player): """ Check if there is a winning move, then if there is a loosing move, finally use heuristic 2 as a fallback """ if self.dim != 3: raise ValueError( "get_move_heuristic_3 not implemented for dimensions other than 3" ) # check for winning move move = self.find_two_in_row(player) if move is not None: # print("found winning: ", move) return move # check for losing move # print("checking for losing") move = self.find_two_in_row(1 - player) if move is not None: # print(move) return move return self.get_move_heuristic_2(player) def get_all_legal_moves(self): flt_board = self.flatten() none_count = flt_board.count(None) if none_count == 0: return None x_coord, y_coord = 1, 1 # walk through the board, count None's and stop at pos-th None # to get its coordinate legal_moves = [] for row in self.board: for item in row: if item is None: legal_moves.append((x_coord, y_coord)) y_coord = (y_coord % self.dim) + 1 x_coord = (x_coord % self.dim) + 1 return legal_moves def get_move_minmax(self, player): # moves = self.get_legal_moves() # scores = [] # for move in moves: # saved_board = self.board # self.update(move, player) # winner = self.winner() # if winner is None: # return 0 # if winner == player: # return 10 # else: # return -10 # return self.get_move_random_position(player) def play_games(player_1, player_2, rounds=1): players = {0: player_1, 1: player_2} stats = {"X": 0, "O": 0, "Draw": 0} for _ in range(rounds): board = Board() # randomize which player starts active_player = randint(0, 1) # active_player = 0 while board.winner() is None: # print(board) coords = players[active_player](board, active_player) board.update(coords, active_player) active_player = 1 - active_player stats[board.winner()] += 1 # print("Winner: ", board.winner()) ratio = stats["X"] / sum(stats.values()) return ratio if __name__ == "__main__": result = play_games(Board.get_move_minmax, Board.get_move_minmax, rounds=100) print(f"{100*result:10.1f}", end="")
eb4d5b1f85c330dbdb68e8785a4333656069cb9b
danielmoralesp/python-basics
/basics-2/binary_search.py
777
4
4
# -*- coding: utf-8 -*- def binary_search(numbers, number_to_find, low, high): if low > high: return False mid = (low + high) // 2 if numbers[mid] == number_to_find: return True elif numbers[mid] > number_to_find: return binary_search(numbers, number_to_find, low, mid - 1) else: return binary_search(numbers, number_to_find, mid + 1, high) if __name__ == '__main__': numbers = [3, 5, 6, 21, 22, 23, 28, 31, 34, 36, 39, 41, 44, 52, 56, 59, 66, 74, 90, 94] number_to_find = int(input('Ingresa un numero: ')) result = binary_search(numbers, number_to_find, 0, len(numbers) - 1) if result is True: print('El numero si esta en la lista') else: print('El numero no esta en la lista')
b70686b6a8dc48f2c1a5b7e5fd47bfabf5ddc36c
Masum148/php
/Python-If-Else.txt
391
3.734375
4
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': a = int(input().strip()) if (a%2==0): if(a>=2 and a<=5): print("Not Weird") elif(a>=6 and a<=20 ): print("Weird") elif(a>20): print("Not Weird") elif (a%2!=0): print("Weird")
08330146e994f6d55272b41892f22d932e013014
VamsiKumarK/Practice
/_00_Assignment_Programs/_02_Functions/_03_Factorial.py
555
4.125
4
''' Created on Nov 20, 2019 @author: Vamsi ''' ''' finding factorial of a given number using while loop ''' num = 5 def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num print('The factorial of given number: ', factorial(num)) print("__________________________________________________") ''' using recursive ''' def fact(num1): if num1 == 0 or num1 == 1: return 1 else: num1 = num1 * factorial(num1 - 1) return num1 print('The factorial of given number: ', fact(5))
2b69c039afdef2acd5cac18328278a6ff2c767cd
chetan2469/git
/pythonDemos/skicit.py
549
3.546875
4
# load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # store the feature and target names feature_names = iris.feature_names target_names = iris.target_names # printing features and target names of our dataset print("Feature names:", feature_names) print("Target names:", target_names) # X and y are numpy arrays print("\nType of X is:", type(X)) # printing first 5 input rows print("\nFirst 5 rows of X:\n", X[:5])
0ab9e5d178d189ae5cae448a1d491dce5b804cc6
syurskyi/Python_Topics
/115_testing/_exercises/exercises/The_Ultimate_Python_Unit_Testing_Course/Section 9 Testing Efficiency/fourth_project.py
429
3.546875
4
# """ # the FibonacciSequence class has two methods that are able to compute the Fibonacci Sequence. # """ # f____ ma.. _______ sqrt # # # c_ FibonacciSequence # # ___ recursive_method n # __ ? __ 0 # r_ 0 # ____ ? __ 1 # r_ 1 # e___ # r_ ?(? - 1) + ?(? - 2) # # ___ math_method n # r_ ((1 + sqrt(5)) ** ? - (1 - sqrt(5)) ** ?) / (2 ** ? * sqrt(5)) #
7ade6fe5b01f92fd24adf8c3d451700dfbb2e445
wangha43/learnpythonthehardway
/ex24.py
893
3.71875
4
print "Let's practice everything." print "You\'d need to know \'bout escapes with \\ that do \n newline and \t tabs." poem = """ \t The lovely world with logic so firmly planted can not discern \n the needs of lovely nor comprehend passion from intuition and requires an explanation \n\t\t where there is none """ print "-----------" print poem print "-----------" five = 10-2+3-6 print "this should be five %s" % five def secret_formula(started): jelly_beans=started*500 jars = jelly_beans/1000 crates = jars/100 return jelly_beans,jars,crates start_point = 10000 beans,jars,crates = secret_formula(start_point) print "With a starting point of:%d" %start_point print "We'd have %d beans,%d jars,and %d crates."%(beans,jars,crates) start_point = start_point /10 print "We can also do that in this way" print "We'd have %d beans ,%d jars,and %d crates."% secret_formula(start_point)
fe25237f837fe32df590ac3ad461d7df6190965f
mrtn-c/DHSolo
/EJERCICIOS/String/ej3.py
741
4.125
4
'''modificar el programa para que reciba dos números enteros que permitandefinir el comienzo y el fin de caracteres a extraer del string original''' str = input("Ingrese una frase ") cond = True pos1 = 0 pos2 = 0 while (cond): pos1 = int(input("Escoga un numero, esta sera la posicion comienzo del string: ")) if (pos1 <= len(str)): break print("Se excedio el rango, intente de nuevo con un numero mas chico") while (cond): pos2 = int(input("Escoga un numero, esta sera la posicion comienzo del string: ")) if (pos2 <= len(str)): break print("Se excedio el rango, intente de nuevo con un numero mas chico") if (pos1 > pos2): aux = pos1 pos1 = pos2 pos2 = aux print(str[pos1-1:pos2])
30c9bca193f0be87507330d811ef7b8120954aec
ParulProgrammingHub/assignment-1-Dhruvil12345
/program1.py
208
4.28125
4
length = float(input("ENTER THE LENGTH:")) breadth = float(input("ENTER THE BREADTH:")) perimeter = (2*breadth)+(2*length) area = length*breadth print ("PERIMETER = "+"",perimeter) print ("AREA = "+"",area)
17311a91568745564287fab293fe070df630323b
gordonmannen/The-Tech-Academy-Course-Work
/Python/Python In A Day - Richard Wagstaff - Py2.7/Chap7 Going Loopy.py
486
4.4375
4
# Start counter at 0 counter = 0 # While 'counter' is less than or equal to 5, # run the loop while counter < 5: # Show counter value print counter # Shortcut to increase counter by 1 counter = counter + 1 # can shortcut above to counter += 1 # Run loop in range 0 - 5 # Counter changes automatically in each iteration for counter in range (0,5): # Show the value of counter print counter # It will iterate from 0 through 4, but will not show 5.
d333b0264f1b2c0a88168bffe9a994f910887ca5
marcoportela/python
/exercicio02_marco_07.py
971
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 13 19:26:36 2014 7. Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total. Obs. : somente são vendidos um número inteiro de latas. @author: portela.marco@gmail.com """ area = float(input('Informe o tamanho da área em metros quadrados a ser pintada: ')) LATA = 18 PRECO_UNIT = 80.00 #Cada litro rende 3 metros quadrados de pintura rendimento = LATA * 3 if area <= rendimento: nrLatas = 1 else: #somente são vendidos um número inteiro de latas nrLatas = int(area / rendimento) + 1 precoTotal = PRECO_UNIT * nrLatas print('O número de latas necessárias é %d' %nrLatas) print('O preço total é R$ %3.2f' %precoTotal)
0c7f4faed3c125af1e379025c60f7708e1e58eab
forbearing/mypython
/1_python/4_字符串.py
4,834
4.21875
4
1:概念: 1:以单引号或双引号扩起来的任意文本 2:字符串是不可变的 2:字符串运算 str1 = "Hello Linux" str2 = "Hello Python" str3 = str1 + str3 3:输出重复字符串 str4 = "hello" print(str4 * 3) 4:字符串索引下标,访问某一字符 str5 = "Hello Python" print(str5[4]) 5:字符串截取 str1 = "Hello linux, Hello python" print(str1[2:7]) # 包含2,不包含7 print(str1[:7]) # 从头截取到给定下标之前 print(str1[7:]) # 从给定下标处开始截取到结尾 6:格式化输出 print("num =", num) # 逗号产生空格 print("num = %d" %(num)) print("num = %d, str = %s" %(num, str1)) print("num = %d, str = %s f = %f" %(num, str1, f)) print("num = %d\nstr = %s\nf = %f" %(num, str1, f)) print("f = %.3f" %f) # 精确到小数点后三位,还会四舍五入 print(''' Hello Linux Hello Python ''') print(r"C:\\Uses\hybfkuf\Desktop\file.txt") # 当个存在多个转义符 常用方法 eval(string) 功能: 将字符串 string 当成有效的表达式来求值并返回计算结果 num = eval("123") print(eval("+123")) # 正确 print(eval("1+2")) # 正确,结果位3 print(eval("2-1")) print(eval("1a2")) # 报错 len(string) 功能: 返回字符串的长度 len(str1) string.lower() 功能: 转换字符串中的大写字母为小写字母 string.lower() string.upper() 功能: 转换字符串中的小写字母为大写字母 string.swapcase() 功能: 转换大小写 string.capitalize() 功能: 首字母大写,其他字母为小写 string.title() 功能: 每个单词的首字母大写,其他字母不变 string.center(width[, fillchar]) 功能: 返回一个指定宽度的居中字符串,fillchar 为填充的字符串,默认空格填充 string.center(40, "*") string.ljust(width [,fillchar]) 功能: 返回一个指定宽度的左对齐字符串,fillchar 为填充的字符串,默认空格填充 string.ljust(40) string.ljust(40, "*") string.rjust(width [,fillchar]) 功能: 返回一个指定宽度的右对齐字符串,fillchar 为填充的字符串,默认空格填充 string.rjust(40) string.rjust(40,"*") string.zfill(width) 功能: 返回一个长度为 width 的右对齐字符串,默认用0填充 string.zfill(40) string.count(str,start=0,end=len(string)) 功能: 返回 str 在 start 和 end 之间在 string 里面出现的次数,默认从头到尾 string.count("Hello") string.count("hello", 15, len(string)) string.find(str,start=0,end=len(string)) 功能: 检查字符串是否包含在 string 中,如果是返回开始的索引值,否则返回-1 string.find("Python") string.find("Python", 10, len(string)) string.rfind() string.rfind("Hello", 10, len(string)) string.index(str1, start=0, end=len(string)) 功能: 跟 find 一样,只不过如果 str1 找不到会报一个异常 string.index("Hello") string.index("Hello", 10, len(strin)) string.rindex() 功能: 同 string.index(),不同是从右边往左查找 string.strip() 功能: 截掉字符串两侧指定的字符,默认为空格 str1 = "Hello Linux, heLLo Python" str2 = str1.ljust(40) str3 = str2.strip() string.strip("*") string.lstrip() 功能: 截掉字符串左侧指定的字符,默认为空格 string.rstrip() 功能: 截掉字符串右侧指定的字符,默认为空格 string.replace(str1, str2, count) 功能: 把 string 中的 str1 替换成 str2,如果 count 指定,泽替换不超过 count 次 string.split(tr="str1", maxsplit) 功能: 以 str1 为分隔符切片 string,如果 maxsplit 有指定值,则分割maxsplit 个字符串 string.split(".") string.startwith("str1") 功能: 检查字符串是和否以 "str1" 开头,是则返回 True,否则返回 False string.endwith("str1") 功能: 检查字符串是否是以 obj 结束,如果是返回 True,否则返回 False 其他 字符串比较 从第一个字符开始比较,谁的 ASCII 值大谁就大,如果相等则会比较下一个字符的 ASCII 值大小。那么谁的值就大 print("str1" > "str2") print(str1 > str2) print(str == str2) # 错误 print("str2" == "str2") # 正确
3dfa25519b2ef21b856a425e0605562373a14716
NaraJulia/programacao-orientada-a-objetos
/listas/lista-de-exercicio-05/Questao08.py
102
3.625
4
QUESTAO 08 def digitos(n): s = str(n) return len(s) n = int(input()) func = digitos(n) print(func)
31e4d3826757422b1fb7eff333e5b58d13995fc0
prashantstha1717/python-assignment-II
/7.py
692
4.28125
4
# 7. Create a list of tuples of first name, last name, and age for your friends and colleagues. # If you don't know the age, put in None. Calculate the average age, skipping over any None values. # Print out each name, followed by old or young if they are above or below the average age. peoples = [('Ram', 'Karki', 50), ('Prabin', 'Bhandari', 19), ('Sita', "Poudel", 20), ('Hari', 'Gurung', 18)] age = [] for i in range(len(peoples)): age.append(peoples[i][2]) print(age) avg = sum(age)/len(age) print(f"The average age is: {avg}") for i in range(len(peoples)): if peoples[i][2] > avg: print(peoples[i][0] + " is old") else: print(peoples[i][0] + " is young")
77f8727007b837834cef787bce83311a5e70d01f
TimBeishuizen/GraduationFilesGithub
/Data Mining Seminar/SkinDiseaseTPOT/PipelineFinder/PipelineSelection.py
1,586
3.515625
4
from tpot import TPOTClassifier from sklearn.model_selection import train_test_split from DataExtraction import DataExtraction as DE import os def select_pipeline_tpot(data_name, train_size, max_opt_time, n_gen, pop_size): """ Selects the best pipeline with tpot and exports its file :param data_name: Name of the data :param train_size: The sizes of the training and test set, in a fraction of the complete set :param max_opt_time: The maximal optimization time for the tpot classifier :param n_gen: The number of generations used in the tpot classifier :param pop_size: The population size used in the tpot classifier :return: an exported python file containing the best pipeline """ # Extract data print('Extracting data...') X, y, gene_ids, sample_ids = DE.extract_data(data_name) # Splitting into test and training print('Splitting into test and training...') X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=train_size, test_size=1-train_size) # Use tpot to find the best pipeline print('Starting PipelineFinder optimization...') tpot = TPOTClassifier(verbosity=2, max_time_mins=max_opt_time, population_size=pop_size, generations=n_gen) tpot.fit(X_train, y_train) # Calculate accuracy print('The accuracy of the best pipeline is: %f' % (tpot.score(X_test, y_test))) # Export pipeline print('Exporting as TPOT_' + data_name + '_pipeline.py') cwd = os.getcwd() os.chdir('../Pipelines') tpot.export('TPOT_' + data_name + '_pipeline.py') os.chdir(cwd)
440feafc08c87e90d26469d6062d07d28fa96c37
Abisha0415/hello-world
/coding_practice_2020_11_27.py
960
3.71875
4
print("Excercise 1") # from 385 to 493 by 9 i = 385 while i <= 493: print(i) i += 9 print("Excercise 2") # from 429 to 625 by 7 i = 429 while i <= 625: print(i) i += 7 print("Excercise 3") # from -11 to 781 by 18 i = -11 while i <= 781: print(i) i += 18 print("Excercise 4") # from 54 to 186 by 6 i = 54 while i <= 186: print(i) i += 6 print("Excercise 5") # from 280 to 392 by 8 i = 280 while i <= 392: print(i) i += 8 print("Excercise 6") # from -373 to -281 by 2 i = -373 while i <= -281: print(i) i += 2 print("Excercise 7") # from 392 to 843 by 11 i = 392 while i <= 843: print(i) i += 11 print("Excercise 8") # from 15 to 429 by 9 i = 15 while i <= 429: print(i) i += 9 print("Excercise 9") # from 113 to 181 by 2 i = 113 while i <= 181: print(i) i += 2 print("Excercise 10") # from -421 to =197 by 8 i = -421 while i <= 197: print(i) i += 8
b5cab2f922dca484635733620c6fc1ecff940621
DevAhmed-py/Pirple.py
/Fizz Buzz Assignment/Fizz Buzz.py
265
3.796875
4
for i in range(1,101,1): if i%15 == 0: print("FizzBuzz") elif i%3 == 0: print("Fizz") elif i%5 == 0: print("Buzz") elif i>1 and i%i == 0 and i%2 == 1: print("Prime") else: print(i)
fe61a5957079fbf7389198b6e18265efa4bacc54
bradgoldstein/algo
/python/merge_sort.py
1,147
4.03125
4
# Merge Sort sorting alogrithm # # See p.30-37 in CLRS 3rd ed. # # Author: Bradley Goldstein # Merges two contiguous, sorted sublists, A[p...q] and A[q+1...r] so that # A[p...r] is now sorted. Uses temporary arrays of size O(len(A)). # # Args: # A: a list containing values to be merged # p: start index of first list subset to be merged # q: end index of first list subset to be merged # r: end index of second list subset to be merged def _merge(A, p, q, r): assert 0 <= p <= q < r < len(A), 'Array indices are out of order.' L = A[p:q+1] L.append(float('inf')) R = A[q+1:r+1] R.append(float('inf')) i, j = 0, 0 for k in range(p, r + 1): if L[i] <= R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 # Sorts the list between the given indices. # # Args: # A: list of values to be sorted # p: start index of sublist to be sorted # r: end index of sublist to be sorted def _mergeSortHelper(A, p, r): if p < r: q = (p + r) / 2 _mergeSortHelper(A, p, q) _mergeSortHelper(A, q + 1, r) _merge(A, p, q, r) # Sorts the list. # # Args: # A: list of values to be sorted def mergeSort(A): _mergeSortHelper(A, 0, len(A) - 1)
60cb014adb3a1ad1d68f6f2f28dc0b15886d560d
MerreM/SNscraper
/demo.py
1,545
3.71875
4
#!/usr/bin/env python from multiprocessing import Process, JoinableQueue # Messy, but acceptable config. NUMBER_OF_CONSUMERS = 2 def put_in_numbers(queue): """ The producer method, if you passed in another argument, like... a url this could run your scraping. """ for i in range(100): queue.put(i) for i in range(NUMBER_OF_CONSUMERS): queue.put(None) queue.close() return def get_number(queue): """ The consumer method, if you put links in the queue these could do the downloading.... """ while True: number = queue.get(True) if number is None: ## End of the queue queue.task_done() return print(number * number) queue.task_done() def main(): ''' The main function definition. ''' queue = JoinableQueue() # Producer... # To fill the queue producer = Process(target=put_in_numbers, args=(queue,)) producer.start() # Workers to work on the queue. workers = [] for i in range(NUMBER_OF_CONSUMERS): p = Process(target=get_number, args=(queue,)) p.start() workers.append(p) # and wait for everyone to finish # If the producer is done... producer.join() for worker in workers: # and the workers... worker.join() # And the queue no longer has any jobs.... queue.join() print("Done") if __name__ == '__main__': ''' If this is the file being run... run main. ''' main()
1fc3626d250c01d9f79292f1ab6fac61f5816c9e
HarshitaMBharadwaj/HarshitaMBharadwaj
/assignment2prob2.py
360
4.03125
4
#Read three integers from the keyboard a,b,c, d and those values in the following order. #max > mid1 > mid2 > min a=int(input("a=")) b=int(input("b=")) c=int(input("c=")) d=int(input("d=")) list_1=[a,b,c,d] e=max(list_1) list_1.remove(e) f=max(list_1) list_1.remove(f) g=max(list_1) list_1.remove(g) h=min(list_1) print(e,f,g,h,sep='>')
1b6810c6a56c6f61c7f8712997da0b02cc5ee9fb
octsama/leetcodeex
/226-InvertBinaryTree.py
1,336
3.84375
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root is None: return None if root.left: self.invertTree(root.left) if root.right: self.invertTree(root.right) root.left, root.right = root.right, root.left return root def printTree(root): q ,ans =[],[] q.append(root) while q : cur = q.pop(0) if cur: q.append(cur.left) q.append(cur.right) ans.append(cur.val) else: ans.append('#') print (ans) def createTree(node): if node is None or node[0]=='#' : return None root , q = TreeNode(node[0]) , [] q.append(root) cur , n = q.pop(0),len(node) for i in range(1,n): if node[i]=='#' : if not i & 1: cur=q.pop(0) continue t = TreeNode(node[i]) q.append(t) if i & 1: cur.left = t else: cur.right = t cur = q.pop(0) return root test = Solution() newRoot = test.invertTree(createTree([4,2,7,1,3,6,9])) printTree(newRoot)
8993b23934f1c8ed01228a5a96a7eb4fee0a0861
NUS-Projects-Amir/CS3243-Project-1
/Old Code Versions/bfs_1_1.py
3,516
3.8125
4
class Puzzle(object): def __init__(self, init_state, goal_state): # you may add more attributes if you think is useful self.init_state = init_state self.goal_state = goal_state self.visited_states=[init_state] def solve(self): #TODO # implement your search algorithm here #trivial case if(self.init_state==self.goal_state): return None source = Node(init_state) frontier = [source] while (len(frontier)!=0): node = frontier.pop(0) for neighbour in node.get_neighbours(): if (neighbour.state not in self.visited_states): self.visited_states.append(neighbour.state) if (neighbour.state==self.goal_state): return self.terminate(neighbour) frontier.append(neighbour) return ["UNSOLVABLE"] # sample output def isequalStates(self,state1,state2): for i in range(len(state1)): for j in range(len(state2)): if state1[i][j] != state2[i][j]: return False return True def isGoalState(self,state): return self.isequalStates(self.goal_state,state) def visited_node(self,node): for state in self.visited_states: if (self.isequalStates(node.state,state)): return True return False def terminate(self,node): output=[] while(node.parent!=None): output.insert(0,node.action) node = node.parent return output # you may add more functions if you think is useful class Node(object): #state is a list of lists representing the configuration of the puzzle #parent is reference to the state before the current state #action is what you did in the previous state to reach the current state. #location of zero in the puzzle as a tuple def __init__(self, state ,parent=None, action = None,location = None): self.state = state self.parent = parent self.dimension = len(state) self.action = action self.location = location def findBlank(self): (y,x) = (0,0) for i in range(self.dimension): for j in range(self.dimension): if self.state[i][j] == 0: return (i,j) print("There's no zero in the puzzle error") # Given a particular node, this method allows you to list all the neigihbours of the node def move(self,xsrc,ysrc,xdest,ydest): output = [] for i in range(len(self.state)): list=[] for j in range(len(self.state)): list.append(self.state[i][j]) output.append(list) output[xsrc][ysrc],output[xdest][ydest] = output[xdest][ydest],output[xsrc][ysrc] return output def get_neighbours(self): # UP,DOWN,LEFT,RIGHT new_states=[] #get coordinate of the blank if (self.location == None): (x,y) = self.findBlank() else: (x,y) = self.location #tries add the down movement if(y-1>=0): new_states.append(Node(self.move(x,y-1,x,y),self,"RIGHT",(x,y-1))) #tries to add the up movement if(y+1<self.dimension): new_states.append(Node(self.move(x,y+1,x,y),self,"LEFT",(x,y+1))) #tries to add the left movement if(x+1<self.dimension): new_states.append(Node(self.move(x+1,y,x,y),self,"UP",(x+1,y))) #tries to add the right movement if(x-1>=0): new_states.append(Node(self.move(x-1,y,x,y),self,"DOWN",(x-1,y))) return new_states #Dont copy the lines below to the actual file init_state = [[5,2,1],[4,8,3],[7,6,0]] goal_state = [[1, 2, 3],[4, 5,6],[7,8,0]] puzzle = Puzzle(init_state,goal_state) x=puzzle.solve() print(x)
66a64580f5767d42e75be049915dd2e4bcc2d9e3
xiaole0310/leetcode
/648. Replace Words/Python/Solution.py
1,390
3.71875
4
class Solution: def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ class TrieNode: def __init__(self, val): self.val = val self.children = [None] * 26 self.is_word = False def build_trie(words): root = TrieNode(' ') for word in words: current = root for letter in word: index = ord(letter) - ord('a') if not current.children[index]: current.children[index] = TrieNode(letter) current = current.children[index] current.is_word = True return root def get_root(word, trie_root): current = '' for letter in word: current += letter index = ord(letter) - ord('a') if not trie_root.children[index]: return word if trie_root.children[index].is_word: return current trie_root = trie_root.children[index] return word trie_root = build_trie(dict) result = '' for word in sentence.split(): result += get_root(word, trie_root) + ' ' return result[:-1]
379d24b9475d657f0119c902b525703696df3150
jelena-vk-itt/jvk-tudt-notes
/swd1-pt/res/files/python/pbl_solutions/pbl4.py
2,589
3.703125
4
from random import * currentUniqueCode = 2 items = [[1, "bread", 1.5, 10], [2, "milk", 2.0, 8]] option = 0 while option != 5: print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n") print("-----------------------------------------") print(" Groceries at Your Fingertips ") print("-----------------------------------------") print("") print("Items in stock") print("---------------") print("{0:>3}{1:>12}{2:>13}{3:>7}".format("ID", "Name", "Price(€)", "Stock")) for item in items: print("{0:>3}{1:>12}{2:>10,.2f}{3:>9}".format(item[0], item[1], float(item[2]), item[3])) print("") print("Stock management options") print("-------------------------") print("(1) add item") print("(2) remove item") print("(3) update item") print("(4) update stock") print("(5) exit") option = int(input("Please choose an option (1, 2, 3, 4 or 5): ")) if option == 1: print("") print("Adding a new grocery item") print("--------------------------") name = input("Please enter the name of the item: ") price = float(input("Please enter the price of the item (in Euro): ")) stock = int(input("Please enter the number of items in stock: ")) currentUniqueCode += 1 items += [[currentUniqueCode, name, price, stock]] elif option == 2: print("") print("Removing a grocery item") print("------------------------") uniqueId = int(input("Please enter the id of the item you wish to remove: ")) itemToRemove = [item for item in items if item[0] == uniqueId][0] items.remove(itemToRemove) elif option == 3: print("") print("Updating a grocery item") print("------------------------") uniqueId = int(input("Please enter the id of the item you wish to update: ")) itemToUpdate = [item for item in items if item[0] == uniqueId][0] itemToUpdate[2] = float(input("Please enter the price of the item (in Euro): ")) itemToUpdate[3] = int(input("Please enter the number of items in stock: ")) elif option == 4: print("") print("Updating stock counts") print("----------------------") for item in items: item[3] -= randint(0, item[3]) print("Items low in stock:") for item in [item for item in items if item[3] < 3]: print(item[1]) input("Press any key to continue...")
b381574abaa9d5701d17c986af6df0f7b21f086c
ahmedAli21/reservation2
/reservation.py
1,627
3.921875
4
hotels = [] # defin a list for hotels customers = [] # define a list for customers reservations = [] # defin a list for reservations # first functions to add hotels and it's data & information def add_hotel(number,hotel_name,city,total_rooms,empty_rooms): hotels.append([number,hotel_name,city,total_rooms,empty_rooms]) # adding some hotels for test add_hotel(1,'hilton','giza',500, 0) add_hotel(2,'rotana','giza',500, 100) add_hotel(3,'blue','giza',500, 100) #second function to add customer def add_customer(customer_name): customers.append(customer_name) #reservation function def reserve_room(hotel_name, customer_name): for i in hotels: if i[1] == hotel_name: if i[4] == 0 : return False else: i[4] -= 1 return True def add_new_reservation(hotel_name,customer_name): if reserve_room(hotel_name,customer_name): reservations.append([hotel_name, customer_name]) print 'confirmed' else: print 'sorry no rooms available ' # test add_new_reservation('rotana','ahmed') add_new_reservation('rotana','omar') add_new_reservation('blue','salma') # end test # FUNCTION TO display hiltons by city def list_hotels_in_city(city_name): hotels_list = [] for i in hotels: if i[2] == city_name: hotels_list.append(i[1]) print hotels_list def list_resevrations_for_hotel(hotel_name): customer_list = [] for i in reservations: if i[0] == hotel_name: customer_list.append(i[1]) print customer_list
2100568bb0f2b4dde27f2dfb1db9680d379b6ef4
dhermes/project-euler
/python/complete/no046.py
859
3.921875
4
#!/usr/bin/env python # What is the smallest odd composite n that can't be written n = p + 2k^2 # for some prime p and some integer k? from python.decorators import euler_timer from python.functions import is_power from python.functions import sieve def is_possible(n, primes): if n % 2 == 0 or n in primes: raise Error("Value poorly specified") primes_less = [prime for prime in primes if prime < n and prime != 2] for prime in primes_less: if is_power((n - prime) / 2.0, 2): return True return False def main(verbose=False): # sieve(6000) will do it (answer is 5777) curr = 9 primes = sieve(5777) while is_possible(curr, primes): curr += 2 while curr in primes: curr += 2 return curr if __name__ == '__main__': print euler_timer(46)(main)(verbose=True)
a011bdd2a0f34804f9c4440c515b52727bb7f81a
Vishnumenon359/bookyourMovieProject
/movie.py
4,019
3.984375
4
#!/usr/bin/env python3 import sys import copy class Movie(): def __init__(self,rows=0, seats=0): self.rows = rows self.seats = seats self.total_seats = self.rows*self.seats self.seat_matrix = [None] * self.rows self.total_bookings = 0 self.current_income = 0 def compute_price(self, row): if (self.total_seats>60 and row <=self.rows//2) or self.total_seats<=60: return 10 else: return 8 def build_seats(self): for x in range(self.rows): self.seat_matrix[x] = ["S"] * self.seats self.reservations = copy.deepcopy(self.seat_matrix) return self.seat_matrix def show_seats(self): #printing the matrix print(end=" ") print(*range(1,self.seats+1)) for row in range(self.rows): print(row+1, end="") for seat in range(self.seats): print(self.seat_matrix[row][seat], end = " " ) print() def buy_ticket(self, row, seat, name, gender, age, mobile): if self.seat_matrix[row-1][seat-1] == "B": return "Seat is already booked by another person, please pick another seat" customer_details = { "Name": name, "Gender": gender, "Age": age, "Phone No.": mobile } self.seat_matrix[row-1][seat-1] = "B" self.reservations[row-1][seat-1] = customer_details self.total_bookings+=1 self.current_income+=(self.compute_price(row)) return self.show_booking(row,seat) def show_booking(self,row,seat): return self.reservations[row-1][seat-1] def show_stats(self): print(f"Number of Purchased Tickets: {self.total_bookings}") pb = round((self.total_bookings/self.total_seats)*100,2) print(f"Percentage of Tickets booked: {pb}%") print(f"Current Income: ${self.current_income}") if self.total_seats<=60: print("Total Income: $" +str(self.total_seats*10)) else: front_rows = self.rows//2 back_rows = self.rows-front_rows expected_revenue = front_rows*self.seats*10 + back_rows*self.seats*8 print("Total Income: $" +str(expected_revenue)) def show_menu(t): print(""" ______________________________________________ Ticket Booking: 1. Show the seats 2. Buy a Ticket 3. Statistics 4. Show booked Tickets User Info 0. Exit """) answer = input(f'Please make a selection: ') if answer == "1": if t.rows>0 and t.seats>0: t.show_seats() show_menu(t) rows = int(input("Enter the number of rows: ")) seats = int(input("Enter the number of seats in each row: ")) t = Movie(rows,seats) t.build_seats() t.show_seats() show_menu(t) elif answer == "2": row = int(input("Enter the row number: ")) seat = int(input("Enter the seat number: ")) print(f"Ticket Price for row:{row}, seat:{seat} is $"+ str(t.compute_price(row))) confirmation = input("Do you want to book the ticket (yes/no): ") if "yes" == confirmation.lower(): name = input("Enter your Name: ") age = input("Enter your Age: ") gender = input("Enter your Gender: ") mobile = input("Enter your Mobile Number: ") t.buy_ticket(row,seat,name,gender,age,mobile) print("Booked Successfully") show_menu(t) elif answer == "3": t.show_stats() show_menu(t) elif answer == "4": row = int(input("Enter the row number: ")) seat = int(input("Enter the seat number: ")) print(t.show_booking(row, seat)) show_menu(t) elif answer =="0": sys.exit() else: print("Please select a number for the list that is provided.") def main(): t=Movie() show_menu(t) if __name__ == "__main__": main()
5612382e2b6efadd9cdb0d0da98e0991ec709f48
brillantescene/Coding_Test
/LeetCode/Graph/combinations.py
989
3.546875
4
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: def dfs(level, start): if level == k: result.append(res[:]) return for i in range(start, n+1): res[level] = i dfs(level+1, i+1) res = [0] * k result = [] dfs(0, 1) return result ''' 다른 방법 class Solution: def combine(self, n: int, k: int) -> List[List[int]]: result = [] def dfs(elements, start, k): if k == 0: result.append(elements[:]) return for i in range(start, n+1): elements.append(i) dfs(elements, i+1, k-1) elements.pop() dfs([], 1, k) return result ''' ''' itertools 사용 class Solution: def combine(self, n: int, k: int) -> List[List[int]]: return itertools.combinations(range(1, n+1), k) '''
65ec11a38a95295dfc22111efae65c0232c94b63
ge1016/python_work
/practice.py
466
4.03125
4
#coding:utf-8 filename = 'txt_files\pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() # жȡ洢һlist pi_string = '' for line in lines: pi_string += line.strip() #ȥߵĿհ print(pi_string) print(len(pi_string)) birthday = input('Enter your birthday: ') #жǷpi if birthday in pi_string: print('Your birthday is in Pi') else: print('Your birthday is not in Pi')
ebd55cfcea4c383d6b0a7fc3cb5362bd6da7472d
dwiel/boring
/boring.py
799
3.921875
4
import itertools import random symbol = "*" format = "{x} {symbol} {y}" x_low = 2 x_high = 9 y_low = 1 y_high = 12 x = set(range(x_low, x_high + 1)) y = set(range(y_low, y_high + 1)) problems = itertools.product(x, y) problems = list(problems) problems = [(x, y, eval(format.format(x=x, y=y, symbol=symbol))) for x, y in problems] print(f"{len(problems)} total problems") correct = 0 total = 0 random.shuffle(problems) for x, y, answer in problems: print(format.format(x=x, y=y, symbol=symbol)) student_answer = input().strip() if student_answer == str(answer): print("correct") correct += 1 else: print(f"incorrect. correct answer is: {answer}") total += 1 print(f"{correct} correct out of {total}: ({correct/total * 100:.00f}% correct)")
0b540c58bd45a56d78808e92bdbe7f8b403f95c6
akbarbelif/Python
/Python_29-5-2019/Basic Python/Rev_string.py
489
4.03125
4
#Enter First_Name def FirstName(): s=True First=input('What is your FirstName ') if not First: s=False return First #Enter Last_Name def LastName(): s=True Last=input('What is your LastName ') if not Last: s=False return Last #Reverse_Name def Revname(Rev_string): Rev= str(Rev_string[::-1]) newtxt=" " for t in Rev: newtxt += " " + t return newtxt F=str(FirstName()) L=str(LastName()) R=str(Revname(F+L)) print(R)
ce66a9f5e09027ecc6784ffd9e8e810ee8145422
YingheSun/algorithms
/sort/E1_BubbleSort.py
390
3.796875
4
# coding:utf-8 import random def bubbleSort(nums): for i in range(len(nums)-1): # 这个循环负责设置冒泡排序进行的次数 for j in range(len(nums)-i-1): # j为列表下标 if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] return nums nums = [random.randint(1,9999) for i in range(1000)] print(bubbleSort(nums))
db97ad39dc4c39620b3285751f375d4c75fd167a
himu999/Python_oop
/H.inheritance/c.inheritance.py
1,092
4.15625
4
class Vehicle: """Base class for all vehicles""" def __init__(self, name, manufacturer, color): self.name = name self.color = color self.manufacturer = manufacturer def drive(self): print("Driving", self.manufacturer, self.name) def turn(self, direction): print("Turning", self.name, direction) def brake(self): print(self.name, "is stopping!") class Car(Vehicle): """Car class""" def __init__(self, name, manufacturer, color, year): super().__init__(name, manufacturer, color) self.name = name self.manufacturer = manufacturer self.color = color self.year = year self.wheels = 4 print("A new car has been created. Name:", self.name) print("It has", self.wheels, "wheels") print("The car was built in", self.year) def change_gear(gear_name): """Method of changing gear""" print(self.name, "is changing gear to", gear_name) if __name__ == "__main__": c = Car("Afnan GT 5.0 ", "N&R CC", "RED", 2015)
43a2d4a82c8526499af7745c45b7046096d55101
rahulsaini/Python-Basics
/decorators1.py
738
4.59375
5
# a decorator is a function that takes another function and # extends the behavior of the latter function without explicitly modifying it. #Decorators provide a simple syntax for calling higher-order functions. # function that does at least one of the following: #----takes one or more functions as arguments (i.e. procedural parameters), #-----returns a function as its result. def decorator(func): def wrapper(): print("This will be printed before execution ") func() print("This will be printed after the execution of function which is going to be decorated ") return wrapper def needofdecorator(): print("Needs an decorator") needofdecorator=decorator(needofdecorator) needofdecorator()
4bb3d23ac5cafb2832a87b1d13365105138bfe22
artbohr/codewars-algorithms-in-python
/7-kyu/alien-accent.py
543
4.0625
4
def convert(st): return st.replace('o','u').replace('a','o') ''' The Story: Aliens from Kepler 27b have immigrated to Earth! They have learned English and go to our stores, eat our food, dress like us, ride Ubers, use Google, etc. However, they speak English a little differently. Can you write a program that converts their Alien English to our English? Task: Write a function converting their speech to ours. They tend to speak the letter a like o and o like a u. >>> convert('hello') 'hellu' >>> convert('codewars') 'cudewors' '''
777a933a45b485f838267a4dc1b57e549908cd3c
polyglotm/coding-dojo
/coding-challange/codewars/7kyu/2019-xx-xx~2020-01-18/alphabetical-addition.py
411
3.859375
4
# https://www.codewars.com/kata/alphabetical-addition def add_letters(*letters): return chr((sum([ord(x) - 96 for x in letters or 'z']) - 1) % 26 + 97) print(add_letters('a', 'b', 'c')) # = 'f' print(add_letters('a', 'b')) # = 'c' print(add_letters('z')) # = 'z' print(add_letters('z', 'a')) # = 'a' print(add_letters('y', 'c', 'b')) # = 'd' # notice the letters overflowing print(add_letters()) # = 'z'
8838115b635a88f2cf3fdc4743f23981febfac6a
patrick-du/Notes
/Courses & Books/Grokking Algorithms/quick_sort.py
2,325
3.9375
4
# Divide-and-conquer (D&C) is a recursive algorithm # To solve a problem using D&C: # - Figure out base case # - Divide or decrease problem until it becomes the base case # Exercise 4.1: Recursive Implementation of Sum Function def recursive_sum(arr): if arr == []: return 0 return arr[0] + recursive_sum(arr[1:]) print(recursive_sum([1, 2, 3])) # Exercise 4.2: Recursive Implementation of Counting Down Number of Items in a List def recursive_countdown(arr): if arr == []: print("0 items") return print("{0} items".format(len(arr))) return recursive_countdown(arr[1:]) print(recursive_countdown(["item1", "item2", "item3", "item4", "item5"])) # Exercise 4.3: Recursive Implementation of Maximum Number in a List def recursive_max(arr, max): if arr == []: return max if arr[0] > max: max = arr[0] return recursive_max(arr[1:], max) print(recursive_max([1, 2, 3, 5, 10, 9], 0)) # Exercise 4.4: Recursive Implementation of Binary Search def recursive_binary_search(arr, val, low, high): if high >= low: mid = (low + high) // 2 if arr[mid] == val: return mid elif arr[mid] > val: return recursive_binary_search(arr, val, low, mid-1) else: return recursive_binary_search(arr, val, mid+1, high) else: return None arr = [2, 3, 4, 10, 40] print(recursive_binary_search(arr, 10, 0, len(arr)-1)) print(recursive_binary_search(arr, -1, 0, len(arr)-1)) # Quicksort is a sorting algorithm that uses divide-and-conquer - on average, O(n * log n), but worse case is O(n^2) # - Pick a pivot element from the array # - Partition array into 2 sub-arrays: elements < pivot & elements > pivot # - Call quicksort recursively onto the two sub-arrays # Quicksort Implementation def quicksort(array): if len(array) < 2: return array else: pivot = array[0] less = [] greater = [] for i in array[1:]: if i <= pivot: less.append(i) else: greater.append(i) return quicksort(less) + [pivot] + quicksort(greater) print(quicksort([10, 5, 2, 3])) # If you choose a random element in the array as the pivot, on average, quicksort will complete in O(n log n)
8cb1f2c6b1d6f883004b3cf4c0ff2869c2d33956
Runpython-IntroProgramming/tests
/exemplars/fizzbuzz.py
604
4.21875
4
maxn = int(input("How many numbers shall we print? ")) fizzn = int(input("For multiples of what number shall we print 'Fizz'? ")) buzzn = int(input("For multiples of what number shall we print 'Buzz'? ")) for n in range(1,maxn+1): fizzmultiple = not n % fizzn # % calculates remainder of division - zero if n is multiple of fizzn buzzmultiple = not n % buzzn # ditto.. if fizzmultiple and buzzmultiple: # check for both, first print("FizzBuzz") elif fizzmultiple: # then individuals print("Fizz") elif buzzmultiple: print("Buzz") else: print(n)
dd82d081e320be168c80ac4ae11655569f7ede3d
noobcakes33/Ladder11
/59A_word.py
219
3.984375
4
word = input() upper = lower = 0 for i in range(len(word)): if word[i].islower(): lower += 1 else: upper += 1 if lower < upper: word = word.upper() else: word = word.lower() print(word)
348d903e40495932fdc441e4278d2bd01e94cb47
MagicianQi/CrackingCoding
/2.Linked Lists/2.4.py
1,764
4.34375
4
# -*- coding: utf-8 -*- """ Question 2.4: Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. if x is contained within the list, the values of x only need to be after the elements less than x(see below). The partition element x can appear anywhere in the "right partition";it does not need to appear between the left and right partitions. EXAMPLE: Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition=5] Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 """ class Node: def __init__(self, val, next): self.val = val self.next = next def printList(linkedList): """ Print linkedList :param linkedList: Input LinkedList :return: None """ while linkedList: print(linkedList.val, end=' ') linkedList = linkedList.next def partition(linkedList, thresh): """ Take O(n) time and O(1) space :param linkedList: Input LinkedList :param thresh: Partition Threshold :return: Output LinkedList """ head = None tail = None while linkedList: next_t = linkedList.next if linkedList.val < thresh: linkedList.next = head head = linkedList else: linkedList.next = tail tail = linkedList linkedList = next_t temp = head while temp.next: temp = temp.next temp.next = tail return head if __name__ == '__main__': linkedList = Node(3, Node(5, Node(8, Node(5, Node(10, Node(2, Node(1, None))))))) printList(linkedList) print('\n-------------') printList(partition(linkedList, 5)) print('\n-------------')
0b949cf655f35d6aa158cb219d861567268b4971
spratt/physics.py
/physics.py
3,196
4.25
4
#!/usr/bin/env python3 """physics.py Written by Simon Pratt Inspired by: http://gafferongames.com/game-physics/integration-basics/ """ class Coord: """A pair of coordinates x,y >>> origin = Coord() >>> origin.x 0 >>> origin.y 0 """ def __init__(self, x = 0, y = 0): """Initializes a pair of coordinates x,y >>> unit = Coord(1,1) >>> unit.x 1 >>> unit.y 1 """ self.x = x self.y = y def __repr__(self): """Python representation of a coordinate. >>> unit = Coord(1,1) >>> unit Coord(1,1) """ return "Coord({})".format(self) def __str__(self): """String representation of a coordinate. >>> "{}".format(Coord()) '0,0' """ return "{},{}".format(self.x, self.y) def __add__(self, c): return Coord(self.x + c.x, self.y + c.y) def __mul__(self, m): return Coord(self.x * m, self.y * m) class Object: """Something with mass, position, velocity, and acceleration. >>> o = Object() >>> o.m 1 >>> o.p Coord(0,0) >>> o.v Coord(0,0) >>> o.a Coord(0,0) """ def __init__(self, m = 1, p = None, v = None, a = None): """Initializes an Object. >>> o = Object(2) >>> o.m 2 >>> o.p Coord(0,0) >>> o.v Coord(0,0) >>> o.a Coord(0,0) """ self.m = m self.p = Coord() if p == None else p self.v = Coord() if v == None else v self.a = Coord() if a == None else a def __repr__(self): """Python representation of an Object. >>> o = Object() >>> o Object(m=1,p=Coord(0,0),v=Coord(0,0),a=Coord(0,0)) """ return "Object(m={},p={},v={},a={})".format(self.m, repr(self.p), repr(self.v), repr(self.a)) class Physics: EULER = 1 RK4 = 2 @staticmethod def integrate(method = EULER, o = None, dt = 1, t = 1): """Integrates by a specified method. >>> o = Object(a = Coord(10, 0)) >>> Physics.integrate(Physics.EULER, o, 1, 5) >>> o Object(m=1,p=Coord(100,0),v=Coord(50,0),a=Coord(10,0)) >>> Physics.integrate(o = o, dt = 1, t = 5) >>> o Object(m=1,p=Coord(450,0),v=Coord(100,0),a=Coord(10,0)) """ if o == None: return elif method == Physics.EULER: return Physics.euler(o, dt, t) else: raise "Not yet implemented." @staticmethod def euler(o, dt, t): """Integrates by by the explicit Euler method. >>> o = Object(a = Coord(10, 0)) >>> Physics.euler(o, 1, 10) >>> o Object(m=1,p=Coord(450,0),v=Coord(100,0),a=Coord(10,0)) """ while t > 0: o.p += o.v * dt o.v += o.a * dt t -= dt if __name__ == "__main__": import doctest doctest.testmod()
dfe5fb30f1e51e8596c6915d25cef5be91f89af0
elsoroka/StanfordAA222Project
/data/datacruncher_hack_write_real_schedule.py
3,181
3.796875
4
# File created: 05/18/2020 # Tested on : Python 3.7.4 # Author : Emiko Soroka # Unittests : None # Description : # Quick hack to ingest JSON data and spit out CSV files, will extend later # How to use : Run file. Enter input JSON file when prompted and output CSV file name when prompted. import json def parseJsonData(infile, outfile): # OK the data we have is kind of in an unwantedly-structured format # Division: (grad/undergrad/etc) # contains department ("AA") # contains list of courses # courses have structure (EXAMPLE) # { # "division":"Graduate", # "department":"AA", # "courseNumber":"AA 222:", # "courseTitle":"Engineering Design Optimization (CS 361)", # "sections":[{ # "courseType":"LEC", # "enrolled":83, # "meetings":[{ # "startTime":900, # "endTime":980, # "days":[1,3], # "timeIsTBA":false, # "bldg":"Skillaud" # }] # }], # "term":"2019-2020 Spring", # "university":"Stanford University" # }, # This code flattens them to # dept, courseNumber, courseType, number of meetings, meeting length in hour blocks # (if timeisTBA is true, there will be 0 meetings of 0 length) # and number enrolled # This makes the header row outfile.write("number,courseName,startTime,endTime,dayCode\r\n") rawData = json.load(infile) for divisionName in rawData.keys(): # iterate over division (grad/undergrad etc) division = rawData[divisionName] for deptName in division: # iterate over departments dept = division[deptName] # Now dept is a list of Course objects for course in dept: writeCourseToFile(course, outfile) def writeCourseToFile(course, outfile): # In the JSON file, time is in 10 minute increments # It makes more sense for us to use floating-point hours # and treat the 10 minute passing period as part of the course time # Some courses have multiple sections # and we will treat these as separate # Some sections have multiple meetings # TODO handle these i=0 for section in course['sections']: for meeting in section['meetings']: # Default if class section is TBA timeHours = 0.0; numMeetings = 0 # If section is not TBA (there is a time and date associated with it) if not meeting['timeIsTBA']: # Count the DAYS per week this class meets daysCode = [0,0,0,0,0] for d in meeting['days']: daysCode[d] = 1 daysCode = "".join([str(d) for d in daysCode]) # Write as a CSV string outfile.write(",".join([str(i), course['courseNumber'].rstrip(":"), str(int(2*(meeting['startTime']/60 - 8))), str(int(2*((meeting['endTime']+10)/60- 8))), # add passing period daysCode]) + "\r\n") i += 1 if __name__ == "__main__": infilename = input("Enter a JSON schedule file ") with open(infilename, "r") as infile: outfilename = input("Output file name (add .csv) ") with open(outfilename, "w") as outfile: parseJsonData(infile, outfile)
97699af056047b831ac1701a65dfb75cbdd741ba
Elyalya/BlockChainNEKA
/crypto/sertif_center.py
700
3.640625
4
def check_publickey(public_key): database=read_file() for i in range(len(database)): if(database[i]==public_key): return False def check_write(public_key): database=read_file() for i in range(len(database)): if(database[i]==public_key): return False write_to_file(public_key) return True def write_to_file(public_key): #database=open('keys','r+') with open('keys.txt', 'a') as f: f.write('\n'+public_key) f.close() return True def read_file(): with open('keys.txt', "r") as file: text = file.read().split('\n') file.close() return text def show_keys(): text=read_file() print(text)
03b6282095ac46d8bccb7e1b63529dd029676147
tanmayee2000/python_practice
/pattern2.py
167
3.5
4
import string ls = list(string.ascii_lowercase) n = 5 for i in range(1,n+1): print('\n''a', end='') for j in range(1,i): print('-'+ls[j], end='')
e78a681103e2a0644ab1ad8c9859aef1b43062ab
Jgoschke86/Jay
/Classes/py3interm/EXAMPLES/with_ex.py
507
3.578125
4
#!/usr/bin/python3 import sys class Thing(object): def __init__(self,magic_word='poof'): self.magic_word = magic_word def __enter__(self): print("Entering context") return self def __exit__(self,objtype,value,traceback): print("Exiting context") print("Magic word is",self.magic_word,end="\n\n") return True with Thing() as t: print("in the middle") with Thing('aardvark') as t: print("in the middle, earth-pig")
a535c66d601c1cd8389db7a41a78edd1c2d002d4
edibusl/stocks-predict
/main.py
5,196
3.578125
4
import os import math import datetime import random import pandas as pd import numpy as np from matplotlib import pyplot as plt import matplotlib.dates as dates from pylab import rcParams from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score df = pd.read_csv("~/code/dscience/stocks/data/facebook.csv", engine='python') df.loc[:, 'Date'] = pd.to_datetime(df['Date'] ,format='%Y-%m-%d') #df.drop(columns="OpenInt", inplace=True) df.drop(columns="Adj Close", inplace=True) def predict_close_linear_regression(df, cur_day, num_of_days, window_size=7): model = LinearRegression() actuals = [] predictions = [] # Go through all requested days and make a new traigning for every day for i in range(cur_day, cur_day + num_of_days): # For each day, train a new model using Close values of previous days. # Number of previous days is defined by "window_size" samples_start = i - window_size samples_end = i - 1 # The X is the features vector and it includes just an index because we're using time series data # X - index # Y - actual Close values X = np.array(range(samples_start, samples_end + 1)) Y = np.array(df["Close"][samples_start:samples_end + 1]) X = X.reshape(window_size, 1) Y = Y.reshape(window_size, 1) # Train the model model.fit(X, Y) # Predict current day according to the linear regression trained model cur_day_prediction = model.predict(np.array([i]).reshape(1, 1))[0][0] predictions.append(cur_day_prediction) cur_day_actual = df.iloc[i]["Close"] actuals.append(cur_day_actual) # Build a DataFrame that includes the actual and predicted results on the given data set df_results = df.iloc[cur_day:cur_day + num_of_days] df_results = df_results.drop(columns=["Open", "High", "Low", "Volume"]) cols_pred = pd.Series(predictions, index=range(cur_day, cur_day + num_of_days)) df_results["Prediction"] = pd.Series(cols_pred) return actuals, predictions, df_results def simulate_buy(df, stock_units, sim_type, buy_decision_threshold=0): random.seed(datetime.datetime.now()) bought = False buy_price = 0 stats = { "transactions_count": 0, "total_bought": 0, "total_revenue": 0, "yield": 0, "period_days": len(df) } for i in range(len(df)): tomorrow_close_prediction = df.iloc[i]["Prediction"] today_close = df.iloc[i]["Close"] # Sell what we bought yesterday (if we bought any) if bought: sell_price = today_close * stock_units revenue = (sell_price - buy_price) buy_price = 0 stats["total_revenue"] += revenue bought = False # Buy next day if sim_type == "prediction": should_buy = tomorrow_close_prediction - today_close > buy_decision_threshold else: should_buy = random.randint(1, 2) == 1 if should_buy: # Buy bought = True buy_price = today_close * stock_units stats["total_bought"] += buy_price stats["transactions_count"] += 1 stats["yield"] = stats["total_revenue"] / stats["total_bought"] * 100 return stats # Split into Training, Cross Validation and Testing sets. set_sizes = { "total_size": len(df), "train_size": int(len(df) * 0.6), "cv_size": int(len(df) * 0.2), "test_size": int(len(df) * 0.2) } df_train = df.iloc[:set_sizes["train_size"]] df_train.tail() df_cv = df.iloc[set_sizes["train_size"]:set_sizes["train_size"] + set_sizes["cv_size"]] df_cv.tail() df_cv.index = range(len(df_cv)) df_test = df.iloc[set_sizes["train_size"] + set_sizes["cv_size"]:] df_test.index = range(len(df_test)) ws = 4 first_day = ws numebr_of_days = len(df_test) - ws res_actuals, res_predicted, df_results = predict_close_linear_regression(df_test, first_day, numebr_of_days, window_size=ws) df_results.head() # Simulate buying with linear regression predictions stats_prediction = simulate_buy(df_results, 5, sim_type="prediction") print(stats_prediction) # Simulate buying with actual tomorrow's value "predictions" df_actual_predictions = df_results.copy() for index, row in df_actual_predictions.iterrows(): try: df_actual_predictions.loc[index, 'Prediction'] = df_actual_predictions.loc[index + 1]['Close'] except: pass stats_actual_prediction = simulate_buy(df_actual_predictions, 5, sim_type="prediction") print(stats_actual_prediction) # Simulate buying with random decision total_revenues = [] for i in range(100): stats_randomly = simulate_buy(df_results, 5, sim_type="random") total_revenues.append(stats_randomly["total_revenue"]) print(np.mean(total_revenues)) year_revenue_percents = 100 * (1 - (df_results.iloc[-1]["Close"] / df_results.iloc[0]["Close"])) year_possible_revenues = (year_revenue_percents / 100) * stats_prediction["total_bought"] print(year_possible_revenues)
987fda3d9e92d5b8946625cc91646b49c0831fc8
qrzhang/Codility
/Codility/solution3.py
1,300
3.875
4
def solution(A): """ :param A: array, An array consisting of N integers :return: int, the number of identical pairs of indices """ # A is an empty array or single element array if len(A) < 2: return 0 # First, calculate the frequency of identical elements in a given array dicA = {} for i in range(len(A)): if A[i] in dicA.keys(): dicA[A[i]] += 1 else: dicA[A[i]] = 1 # count pairs for each identical element counter = 0 for count in list(dicA.values()): counter += (count * (count - 1)) / 2 return int(counter) import unittest import random MAXINT = 1000000000 MAXN = 1000000 class TestExercise(unittest.TestCase): def test_example(self): self.assertEqual(solution([3, 5, 6, 3, 3, 5]), 4) def test_simple(self): self.assertEqual(solution([0, -1, 3, 3]), 1) def test_extreme_small(self): self.assertEqual(solution([]), 0) self.assertEqual(solution([1]), 0) self.assertEqual(solution([0, -1]), 0) def test_extreme_large(self): print(solution(random.sample(range(-MAXINT,MAXINT), MAXN))) if __name__ == '__main__': unittest.main() # # print(solution([3, 5, 6, 3, 3, 5])) # print(solution([3, 5, 6, 7, -2, -5]))
aa982e05118414cacaf8396b1760b4afd84e87c5
behrouzmadahian/python
/python-Interview/2-arrays/29-unsortedPiece.py
682
4.1875
4
''' Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted. Example: [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the sub array lies between the indexes 3 and 8. ''' def f(a): for i in range(len(a)-1): if a[i] >a[i+1]: start_ind = i break for i in range(len(a)-1, -1, -1): print(i) if a[i]<a[i-1]: end_ind = i break return start_ind, end_ind a = [10, 12, 20,28, 30, 25, 40, 32, 31, 35, 50, 60] inds =f(a) print(a[inds[0]:inds[1]+1])
4f465838eb634c3e774d2ebf9251f24ee84e9992
MaartenAmbergen/TICT-V1PROG-15-Maarten-Ambergen-
/Les03/pe3_3.py
235
3.84375
4
Leeftijd=eval(input('Hoe oud ben je? ')) Paspoort=input('Ben je in heb bezit van een Nederlands paspoort? ') if Leeftijd >17 and Paspoort=='ja': print('Gefeliciteerd, je mag stemmen!') else: print('Helaas, je mag niet stemmen')
ca517489ef1bdde74081fdb368125cfa74832a28
Keitling/algorithms
/python/Searching/DepthFirstSearch/dfs_grid.py
2,135
3.875
4
# This python file uses the following encoding: utf-8 """ Depth-first search algorithm implemented in a grid. Like a breath-first search, but uses a stack instead of a queue. The algorithm: while boundary is not empty: current_cell ← pop boundary for all neighbor_cell of current_cell: if neighbor_cell is not in visited: add neighbor_cell to visited push neighbor_cell onto boundary In this example, neighbors cells are the cells located up, down, left, and right from a given cell. Diagonals are not considered adjacent. In the print, cells with an X are visited, and cells with an O are in the stack. """ import sys sys.path.append('../../Tools') from tools import Stack from tools import Grid HEIGHT = 5 WIDTH = 5 EMPTY = 0 FULL = 1 def bfs(grid, row, col): """ Perform a breath-first search in the given grid, starting in the given cell. """ boundary = Stack() # dfs uses stack dynamics boundary.push((row, col)) # put the starting grid in the stack visited = [[EMPTY for _ in xrange(WIDTH)] for _ in xrange(HEIGHT)] visited[row][col] = FULL # set the starting cell to visited while boundary: # while the stack is not empty current = boundary.pop() # get a grid cell from the stack grid.set_marked(current[0], current[1]) # (this is for the print) neighbors = grid.four_neighbors(current[0], current[1]) # get the four neighbor cells: print grid # up, down, left, and right for neighbor in neighbors: # for every neighbor cell if not visited[neighbor[0]][neighbor[1]]: # if it hasn't been visited visited[neighbor[0]][neighbor[1]] = FULL # set it as visited boundary.push(neighbor) # add it to the stack grid.set_full(neighbor[0], neighbor[1]) # (this is for the print) print grid bfs(Grid(HEIGHT, WIDTH), HEIGHT/2, WIDTH/2)
e2733bd552345ab3961aefd9bfd18234fa1ef823
y840512/Python-002
/week08/test2.py
389
4.15625
4
# 作业二: # 自定义一个 python 函数,实现 map() 函数的功能。 #1 def seq(x): return x * x list=(1,2,5,10) rst_list=map(seq,list) for i in rst_list: print (i) print ('#1 end','#'*20) #2 def seq(x,y): return x + y # list1=(1,2,5,10) list1=(5,) list2=(3,2,5,10,12) rst_list1=map(seq,list1,list2) for i in rst_list1: print (i) print ('#2 end','#'*20)
346c25932947a40e20684f91bf9ab58d9105e382
rokzidarn/KerasDLTutorials
/text_processing.py
2,096
3.921875
4
# TEXT PROCESSING import numpy as np from keras.preprocessing.text import Tokenizer # text -> sequence data (words) # examples: document classification, sentiment analysis, question answering # pattern recognition applied to words, sentences and paragraphs # tokenization # text vectorizing transforms text into numeric tensors # 2 approaches: one-hot encoding and word embeddings (token embedding) # N-gram = sequence of N consecutive words # ONE HOT ENCODING # vector of a word consists of all zeros except one 1 -> [0 0 0 0 0 1 0 0 0 ] # length of the vector is the size of the vocabulary, number of words in the text # TEXT CONVOLUTION # 1D convolution can be used in sequence processing, instead of 2d tensors in images, we can use 1D tensor in text # we have some sort of input text, and a sliding windows of certain width, this can recognize local patterns # Conv1D, also used because of faster computation def one_hot_encoding(samples): token_index = {} for sample in samples: for word in sample.split(): if word not in token_index: token_index[word] = len(token_index) + 1 # no all zero vector max_length = 10 results = np.zeros(shape=(len(samples), max_length, max(token_index.values()) + 1)) for i, sample in enumerate(samples): for j, word in list(enumerate(sample.split()))[:max_length]: index = token_index.get(word) results[i, j, index] = 1. return results # MAIN text = ['The cat sat on the mat.', 'The dog ate my homework.'] r = one_hot_encoding(text) #print(r) # Keras implementation of one-hot encoding tokenizer = Tokenizer(num_words=1000) # number of most common words, length of one-hot vector tokenizer.fit_on_texts(text) sequences = tokenizer.texts_to_sequences(text) one_hot_results = tokenizer.texts_to_matrix(text, mode='binary') word_index = tokenizer.word_index # dictionary of all words in text print(word_index) # if the number of unique tokens in your vocabulary is too large to handle use hashin trick
749d08a959a27a6261354cb4b9ca205ea66e4df0
RaghavJindal2000/Python
/basics/Python/PYTHON --------/function/calculator_function,py.py
709
3.953125
4
def add(x,y): sum=x+y print(a," + ",b," = ",sum) def sub(x,y): s=x-y print(a," - ",b," = ",s) def mul(x,y): m=x*y print(a," * ",b," = ",m) def div(x,y): d=x/y print(a," / ",b," = ",d) def floor_div(x,y): d=x//y print(a," // ",b," = ",d) a=int(input("Enter First Number : ")) b=int(input("Enter Second Number : ")) print("Press + for Addition") print("Press - for Subtraction") print("Press * for multiplication") print("Press / for Division") print("Press // for Floor Division") ch=input() if(ch=='+'): add(a,b) elif(ch=='-'): sub(a,b) elif(ch=='*'): mul(a,b) elif(ch=='/'): div(a,b) elif(ch=='//'): floor_div(a,b) else: print("Invalid Choice")
aa0061fc4a7949a0722621c0bfab39e584f66783
Wang-Yann/LeetCodeMe
/python/CodingInterviews_2/03_shu-zu-zhong-zhong-fu-de-shu-zi-lcof.py
1,689
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Rocky Wayne # @Created : 2020-04-22 23:13:31 # @Last Modified : 2020-04-22 23:13:31 # @Mail : lostlorder@gamil.com # @Version : alpha-1.0 # 找出数组中重复的数字。 # # # 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请 # 找出数组中任意一个重复的数字。 # # 示例 1: # # 输入: # [2, 3, 1, 0, 2, 5, 3] # 输出:2 或 3 # # # # # 限制: # # 2 <= n <= 100000 # Related Topics 数组 哈希表 # 👍 112 👎 0 from typing import List import pytest class Solution: def findRepeatNumber(self, nums: List[int]) -> int: hash_set = set() for v in nums: if v in hash_set: return v hash_set.add(v) class Solution1: def findRepeatNumber(self, nums: List[int]) -> int: length = len(nums) if not length: return None for i in range(length): if not 0 <= nums[i] <= length - 1: return None while i != nums[i]: if nums[i] == nums[nums[i]]: return nums[i] v = nums[i] nums[i], nums[v] = nums[v], nums[i] @pytest.mark.parametrize("kw,expected", [ [dict(nums=[2, 3, 1, 0, 2, 5, 3]), 2], ]) def test_solutions(kw, expected): assert Solution().findRepeatNumber(**kw) == expected assert Solution1().findRepeatNumber(**kw) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
7b9514993c36280a29c89f65b348f2616bb97a06
OrianaLombardi/Python-
/fundamentos/listas.py
1,270
4.5
4
nombres=["Juan", "Karla", "Ricardo", "Maria"] print(nombres) #Conocer el largo de la lista print(len(nombres)) #el elemento 0 print(nombres[0]) #navegacion inversa print(nombres[-1]) print(nombres[-2]) #Imprimir rango print(nombres[0:2]) #sin incluir el indice 2 #Imrpimir los elementos de inicio hasta el indici proporcionado print(nombres[:3])#sin incluir el indice 3 #imprimir los elementos hasta el final desde el indice proporcionado print(nombres[1:]) #cambiar los elementos de una lista nombres[3]="Ivone" print(nombres) #iterar la lista for nombre in nombres: print(nombre) #revisar si existe un elemtno en la lista if "Carla" in nombres: print("Karla si existe en la lista") else: print("El elemento buscado no existe en la lista") #agregar un nuevo elemento nombres.append("Lorenzo") print(nombres) #insertar un nuevo elemento en el indice proporcionado nombres.insert(1,"Octavio") print(nombres) #remover un elemento nombres.remove("Octavio") print(nombres) #remover el ultimo elemento de nuestra lista nombres.pop() print(nombres) #remover el indice indicado de la lista del nombres[0] print(nombres) #limpiar los elementos de nuestra lista nombres.clear() print(nombres) #eliminar nuestra lista del nombres print(nombres)
79419121d8256ec451863036e4aded831fbfdc04
19klowe0/SimpleSort
/ReverseSort.py
459
4.03125
4
# creating the file with the names in it names = list() file = open('SortMe.txt') #looping through the array of words to append for name in file: #remove whitespace name = name.strip() words = name.split() for word in words: names.append(name) file.close() #first sort the results by character z-a #then by the length big to small names.sort(reverse=True) names.sort(key=len, reverse=True) #print for name in names: print(name)
380feb3aeecc0f0e5948daeb106899da806be199
tatyskya/Python
/hometask_5.py
3,027
3.875
4
# Task 1 Создать программно файл в текстовом формате, записать # в него построчно данные, вводимые пользователем. my_file = open('test.txt', 'w') line = input('Введите текст \n') while line: my_file.writelines(line) line = input('Введите текст \n') if not line: break my_file.close() my_file = open('test.txt', 'r') content = my_file.readlines() print(content) my_file.close() # Task 2 # Создать текстовый файл (не программно), сохранить # в нем несколько строк, выполнить подсчет количества строк, # количества слов в каждой строке. my_file = open('Brod.txt', 'r') content = my_file.read() print(f'Содержимое файла: \n {content}') my_file = open('Brod.txt', 'r') content = my_file.readlines() print(f'Количество строк в файле - {len(content)}') my_file = open('Brod.txt', 'r') content = my_file.readlines() for i in range(len(content)): print(f'Окличество символов {i + 1} - ой строки {len(content[i])}') my_file = open('Brod.txt', 'r') content = my_file.read() content = content.split() print(f'Общее количество слов - {len(content)}') my_file.close() # Task 3 Создать текстовый файл (не программно), построчно записать # фамилии сотрудников и величину их окладов. # Определить, кто из сотрудников имеет оклад менее 20 тыс., # вывести фамилии этих сотрудников. Выполнить подсчет средней # величины дохода сотрудников. with open('sal.txt', 'r') as my_file: sal = [] poor = [] my_list = my_file.read().split('\n') for i in my_list: i = i.split() if int(i[1]) < 20000: poor.append(i[0]) sal.append(i[1]) print(f'Оклад меньше 20.000 {poor}, средний оклад {sum(map(int, sal)) / len(sal)}') # Task 4 Необходимо написать программу, открывающую файл на чтение # и считывающую построчно данные. При этом английские # числительные должны заменяться на русские. # Новый блок строк должен записываться в новый текстовый файл. rus = {'One' : 'Один', 'Two' : 'Два', 'Three' : 'Три', 'Four' : 'Четыре'} new_file = [] with open('numb.txt', 'r') as file_obj: for i in file_obj: i = i.split(' ', 1) new_file.append(rus[i[0]] + ' ' + i[1]) print(new_file) with open('numb.txt', 'w') as file_obj_2: file_obj_2.writelines(new_file)
03e0a651f756347bb2ebe813e5b519ac9901245b
msweetland/InterviewPrep
/TADM_3/22.py
2,951
3.71875
4
from inspect import isfunction class LinkedNode(object): def __init__(self, item, next_node=None): self.item = item self.next = next_node def get_data(self): return self.item def get_next(self): return self.next def set_next(self, new_next): self.next = new_next class BinaryNode(object): def __init__(self, item, comparator, next_node_left=None, next_node_right=None): assert isfunction(comparator), 'Comparator must be a function' self.item = item self.comparator = comparator self.next_node_left: BinaryNode = next_node_left self.next_node_right: BinaryNode = next_node_right def get_data(self): return self.item def get_next_left(self): return self.next_node_left def get_next_right(self): return self.next_node_right def set_next_left(self, new_node_left): self.next_node_left = new_node_left def set_next_right(self, new_node_right): self.next_node_right = new_node_right def insert(self, value): if self.comparator(value, self.item): if self.next_node_left: self.next_node_left.insert(value) else: new_node = BinaryNode(value, self.comparator) self.set_next_left(new_node) else: if self.next_node_right: self.next_node_right.insert(value) else: new_node = BinaryNode(value, self.comparator) self.set_next_right(new_node) def create_binary_tree(arr, comparator): assert len(arr) > 0, 'Array must not be empty' Tree = BinaryNode(arr[0], comparator) for value in arr[1:]: Tree.insert(value) return Tree def linked_to_arr(linked_list): arr = [] current_node = linked_list while current_node: arr.append(current_node.get_data()) current_node = current_node.get_next() return arr # Write a program to convert a binary search tree into a linked list. def tree_to_linked_list(binary_tree: BinaryNode) -> LinkedNode: middle_node = LinkedNode(binary_tree.get_data()) left_linked = None right_linked = None Head = None if binary_tree.get_next_left(): left_linked = tree_to_linked_list(binary_tree.get_next_left()) if binary_tree.get_next_right(): right_linked = tree_to_linked_list(binary_tree.get_next_right()) if right_linked: middle_node.set_next(right_linked) if left_linked: Head = left_linked current_node = Head while current_node: next_node = current_node.get_next() if not next_node: current_node.set_next(middle_node) break else: current_node = next_node else: Head = middle_node return Head if __name__ == "__main__": def compare(a, b): return a < b test_arr = [1, 6, 3, 6, 3, 10, 7, 8] binary_tree = create_binary_tree(test_arr, compare) linked_binary = tree_to_linked_list(binary_tree) arr = linked_to_arr(linked_binary) assert arr == sorted(test_arr) # assert compare_tree(create_binary_tree_a, create_binary_tree_b) == False
165c4bd1ded1b405853f312a4237e8f523ad4421
nkanungo/session12_epfi
/calculator/sigmoid_module.py
533
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 16:30:27 2020 @author: Nihar Kanungo """ import math __all__ = ['sigmoid'] def sigmoid(x): ''' Calculates the Sigmoid of the given value FInd out the derivative of the Sigmoid of the given value ''' print(f'the value of sigmoid for given input is {1 / (1 + math.exp(-x))}') return 1 / (1 + math.exp(-x)) def sigmoid_der(x): print(f'the value of derivative for sigmoid for given input is {sigmoid(x)*(1-sigmoid(x))}') return sigmoid(x)*(1-sigmoid(x))
de6e38c0722d0804b212e37b27c86e6d68192109
daili0015/Download_Picture
/FileRobotClass.py
1,600
3.625
4
# 文件操作类 import os class FileRobot(): def __init__(self): pass #文件夹的名字不能含有的特殊符号,windows下的限定 def get_format_filename(self,input_filename): # for s in ['?', '*', '<', '>', '\★', '!', '/','!']: while s in input_filename: input_filename = input_filename.strip().replace(s, '') return input_filename #给定目录下创建文件夹 def creat_folder(self,input_location,input_foldername): input_foldername=self.get_format_filename(input_foldername) if not os.path.exists(input_location+'\\'+input_foldername): try: os.makedirs(input_location+'\\'+input_foldername) return input_location+'\\'+input_foldername except: return False else: return input_location+'\\'+input_foldername #打开txt文件,写入文件;style_flag写入方式,1覆盖写入,2继续写入,3换行继续写入 def write_text(self,input_file_location,input_file_name,input_text,style_flag=1): input_file_name=self.get_format_filename(input_file_name) try: os.chdir(input_file_location) # 切换到上面创建的文件夹 if style_flag==1: f = open(input_file_name + '.txt', 'w') # r只读,w可写,a追加 f.write(input_text) f.close() elif style_flag==2: f = open(input_file_name + '.txt', 'a') # r只读,w可写,a追加 f.write(input_text) f.close() elif style_flag==3: f = open(input_file_name + '.txt', 'a') # r只读,w可写,a追加 f.write('\n'+input_text) f.close() return True except: return False
5792deb658444689a27392d92338b04f168e5155
rahulcode22/Data-structures
/Math/Prime-Sum.py
474
3.84375
4
'''' Given an even number ( greater than 2 ), return two prime numbers whose sum will be equal to given number. ''' class Solution: def primesum(self, n): for i in xrange(2, n): if self.is_prime(i) and self.is_prime(n - i): return i, n - i def is_prime(self, n): if n < 2: return False for i in xrange(2, int(n**0.5) + 1): if n % i == 0: return False return True
1c2cb89251736146a4b178e9d6b27f1025181f20
kusano/codevs2
/gentable.py
2,795
3.671875
4
# coding: utf-8 # テーブルを生成 def pspin(W,H,T,S,N,P): print "const int Field<%d,%d,%d,%d,%d,%d>::pspin[4][%d] = "%(W,H+T,T,S,N,P,T*T) print "{" P = [[0]*T for t in range(T)] i = 0 for y in range(T): for x in range(T): P[y][x] = i i += 1 for r in range(4): s = "" i = 0 for y in range(T): for x in range(T): s += "%d,"%P[y][x] i += 1 print " {"+s+"}," B = P P = [[0]*T for t in range(T)] for y in range(T): for x in range(T): P[y][x] = B[x][T-y-1] print "};" def line(W,H,T,S,N,P): print "const int Field<%d,%d,%d,%d,%d,%d>::line[%d][4] = "%(W,H+T,T,S,N,P,3*(W+H+T)-2) print "{" # 縦 s = "" for x in range(W): s += "{%d,%d,%d},"%(x,W*(H+T)+x,W) print " "+s # 横 s = "" for y in range(H+T): s += "{%d,%d,%d},"%(y*W,y*W+W,1) print " "+s # 左下-右上 s = "" for x in range(W)[::-1]: s += "{%d,%d,%d},"%(x,x+(W-x)*(W+1),W+1) for y in range(1,H+T): s += "{%d,%d,%d},"%(y*W,y*W+min(W,H+T-y)*(W+1),W+1) print " "+s # 右下-左上 s = "" for x in range(W): s += "{%d,%d,%d},"%(x,x+(x+1)*(W-1),W-1) for y in range(1,H+T): s += "{%d,%d,%d},"%(y*W+W-1,y*W+W-1+min(W,H+T-y)*(W-1),W-1) print " "+s print "};" def pos2line(W,H,T,S,N,P): L = [] # 縦 for x in range(W): L += [(x,W*(H+T)+x,W)] # 横 for y in range(H+T): L += [(y*W,y*W+W,1)] # 左下-右上 for x in range(W)[::-1]: L += [(x,x+(W-x)*(W+1),W+1)] for y in range(1,H+T): L += [(y*W,y*W+min(W,H+T-y)*(W+1),W+1)] # 右下-左上 for x in range(W): L += [(x,x+(x+1)*(W-1),W-1)] for y in range(1,H+T): L += [(y*W+W-1,y*W+W-1+min(W,H+T-y)*(W-1),W-1)] F = [[] for i in range(W*(H+T))] for i,l in enumerate(L): for p in range(*l): F[p] += [i] print "const int Field<%d,%d,%d,%d,%d,%d>::pos2line[%d][4] = "%(W,H+T,T,S,N,P,W*(H+T)) print "{" for y in range(H+T): s = "" for f in F[y*W:(y+1)*W]: s += "{%d,%d,%d,%d},"%tuple(f) print " "+s print "};" # W, H, T, S, N, P test = 5, 8, 2, 10, 10, 25 small = 10, 16, 4, 10, 1000, 25 medium = 15, 23, 4, 20, 1000, 30 large = 20, 36, 5, 30, 1000, 35 pspin(*test) pspin(*small) pspin(*medium) pspin(*large) line(*test) line(*small) line(*medium) line(*large) pos2line(*test) pos2line(*small) pos2line(*medium) pos2line(*large)
b46c5623fb3c1c9d35d81cba6f67c3f4e405c10c
akhilanair14/Weather_Widget
/WeatherApp.py
4,177
3.90625
4
import tkinter as tk from tkinter import font # Font Library import requests # Library to send request to API from PIL import Image, ImageTk # Pillow libraries for Pictures import datetime # Date time Library for Sunrise and Sunset Conversion app = tk.Tk() # Create the GUI Window using the Tk() Function app.title("My Weather Widget") # App Title HEIGHT =420 # Initializing my Canvas measurement WIDTH = 550 # Initializing Canvas Measurement # 5fcda53ff8126e670af0ac16244e595d # api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key} def format_response(weather): # function to format the retrieved data try: name = weather['name'] # Getting the City Name desc = weather['weather'][0]['description'] # Getting the description of weather from JSON Data temp = weather['main']['temp'] # Getting the temperature from JSON Data feels_like = weather['main']['feels_like'] # Getting Feels Like value from JSON Data sunrise = weather['sys']['sunrise'] # Getting the time and date of Sunrise sunset = weather['sys']['sunset'] # Getting the time and date of Sunset val1 = datetime.datetime.fromtimestamp(sunrise) # Converting Unix time to date val2 = datetime.datetime.fromtimestamp(sunset) # Converting Unix time to date # Printing the result final_str = 'City: %s \nConditions: %s \nTemperature (°F): %s \nFeels Like (°F): %d \nSunrise at: %s \nSunset at: %s ' % (name, desc, temp, feels_like, val1, val2) except: final_str = 'Invalid Entry' # If the Input field is invalid return final_str def get_weather(city): # Function to get weather weather_key = '5fcda53ff8126e670af0ac16244e595d' url = 'https://api.openweathermap.org/data/2.5/weather' # Current Weather API params = {'APPID': weather_key, 'q': city, 'units': 'imperial'} # Initializing the APP ID to weather key response = requests.get(url, params=params) # requesting the information weather = response.json() # storing the response in weather variable label['text'] = format_response(weather) icon_name = weather['weather'][0]['icon'] # for icon image open_image(icon_name) def open_image(icon): size = int(lower_frame.winfo_height() * 0.4) # setting the height of the icon image img = ImageTk.PhotoImage(Image.open('./img/' + icon + '.png').resize((size, size))) weather_icon.delete("all") weather_icon.create_image(0,0, anchor='nw', image=img) weather_icon.image = img canvas = tk.Canvas(app, height=HEIGHT, width=WIDTH) # Draw Shapes in Application background_image = tk.PhotoImage(file='landscape.png') background_label = tk.Label(app, image=background_image) background_label.place(relwidth=1, relheight=1) canvas.pack() # .pack() the widgets into the window frame = tk.Frame(app, bg='sky blue', bd=5) # Container Widget frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n') entry = tk.Entry(frame, font=('Helvetica', 12)) # Place to enter Zipcode or City, Single line text field to get value from user entry.place(relwidth=0.65, relheight=1) button = tk.Button(frame, text="Get Weather", font=('Helvetica', 12), command=lambda: get_weather(entry.get())) # Display Get Weather Button button.place(relx=0.7, relheight=1, relwidth=0.3) lower_frame = tk.Frame(app, bg='sky blue', bd=10) # creating the lower frame lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n') bg_color = 'white' label = tk.Label(lower_frame, font=('Helvetica', 26, 'bold'), fg='steel blue', bd=4) # Font of Result label.config(font=40, bg=bg_color) label.place(relwidth=1, relheight=1) weather_icon = tk.Canvas(label, bg=bg_color, bd=0, highlightthickness=0) # icon measurements weather_icon.place(relx=0.78, rely=0, relwidth=1, relheight=0.5) app.mainloop() # Method to execute the application - Loops forever Until the app is closed or program is terminated
6fde0ca84dc1058efc7cc2ce29ad24b63705db88
jrmcglynn/WAR_simulation
/WAR.py
11,121
3.515625
4
from random import seed from random import shuffle from random import sample import numpy as np import pandas as pd class War(object): ''' Class built to simulate the card game War: https://en.wikipedia.org/wiki/War_(card_game) Includes settings to control the way discards are handled. Parameters: --------- max_hands: int Maximum number of gameplay turns to be simulated. Prevents never-ending games from running infinitely. discard_recylce_mode: string, ['fifo', 'filo', 'shuffled'] Controls how discards are recycled back into the players' hands. Can either by fifo (first in first out), filo (first in last out), or shuffled (discard is shuffled before returning to hand). discard_randomness: boolean Determines whether the order of cards should be randomized as won cards are added to the back of the discard pile. starting_hands: None or nested list of integers If None, random hands are dealt for both players. Can optionally pass a length-2 list of integers to be used as the starting deal. ''' def __init__(self, max_hands, discard_recycle_mode = 'fifo', discard_randomness = False, starting_hands = None): # Store game settings self.max_hands = max_hands self.discard_recycle_mode = discard_recycle_mode self.discard_recycle_func = self._set_discard_func() self.discard_randomness = discard_randomness if starting_hands is None: # Deal random starting hands and store self._player_1_dealt, self._player_2_dealt = self._random_hands() else: # Unpack the list of lists self._player_1_dealt, self._player_2_dealt = \ starting_hands[0], starting_hands[1] # Create dictionaries with active hands and discard piles self.player_1 = {'hand': self._player_1_dealt.copy(), 'discard': []} self.player_2 = {'hand': self._player_2_dealt.copy(), 'discard': []} # Initialize empty winnings list self._winnings = [] # Initialize gameflow tracking dataframe self._tracks = [26] # Initalize dictionary to summarize game status / results self.summary = {'hands_played': 0, 'finished': None, 'tracks': self._tracks, 'p1_dealt': self._player_1_dealt, 'p2_dealt': self._player_2_dealt, 'discard_recycle_mode': self.discard_recycle_mode, 'discard_randomness': self.discard_randomness} def play_game(self, max_hands = None): ''' Play a full game. ''' hand = self.summary['hands_played'] if max_hands is None: max_hands = self.max_hands # Continue doing battle until the game is over; ## Track the results each time while not self.__game_over(hand, max_hands): self._do_battle() self._tracks.append(len(self.player_1['hand']) + len(self.player_1['discard'])) hand += 1 # Update summary once the game is over self.summary['hands_played'] = hand self.summary['tracks'] = pd.Series(self._tracks, name = 'player_1_cards') # Return the game summary return self.summary def seek(self, turn): ''' Go to a particular turn number. ''' # Reset the game if the game is already past that turn if self.summary['hands_played'] > turn: self.__reset_game() # Play the game up to the desired turn self.play_game(turn) # Return the game hands as a dataframe (only works for non-random # discard recycle modes) return self.to_dataframe() def skip(self, turns = 1): ''' Skip ahead a certain number of turns. ''' self.play_game(self.summary['hands_played'] + turns) return self.to_dataframe() def to_dataframe(self): ''' Turn game hands into a dataframe. Does not work if the discard mode is shuffled, because there is no way to return the discard into the hand to create a combined dataframe. ''' # Cannot turn shuffled into df if self.discard_recycle_mode == 'shuffled': raise NameError('Cannot turn shuffled game into df') else: # Move discards back into active handhand self.__recycle_discard(self.player_1) self.__recycle_discard(self.player_2) # Create a tuple of the hands and sort declining by length hands = [('P1', self.player_1['hand'].copy()), ('P2', self.player_2['hand'].copy())] hands = sorted(hands, key = lambda x: len(x[1]), reverse = True) # Figure out and add the correct number of NaNs so hands are even add = len(hands[0][1]) - len(hands[1][1]) hands[1][1].extend([np.NaN]*add) # Turn tuple into a dictionary hands_dict = {hands[0][0]: hands[0][1], hands[1][0]: hands[1][1]} # Return dataframe return pd.DataFrame(hands_dict) def _random_hands(self): ''' Generate a random 2-player game. ''' # Create deck of cards and shuffle cards = list(range(2,15))*4 shuffle(cards) # Assign half of the deck to each player and return player_1 = cards[:26] player_2 = cards[26:] return player_1, player_2 def _set_discard_func(self): ''' Method to generate the discard function. Doing this once with initialization rather than evaluating the if statement with every usage. ''' #'First in first out' recycle mode if self.discard_recycle_mode == 'fifo': return lambda player: player['discard'] # 'First in last out'; just keep the original discard ## Need to reverse the discard because it is ordered first in first out if self.discard_recycle_mode == 'filo': return lambda player: list(reversed(player['discard'])) # Shuffled; shuffles the discard pile before returning to hand if self.discard_recycle_mode == 'shuffled': return lambda player: sample(player['discard'], len(player['discard'])) def _do_battle(self): ''' Run a single turn. ''' # Get the top card from each player play_1, play_2 = (self.__get_top_card(self.player_1), self.__get_top_card(self.player_2)) # Add new cards to potential winnings self.__add_to_winnings([[play_1], [play_2]]) # Evaluate who wins and allocate winnings accordingly if play_1 > play_2: self.player_1['discard'].extend(self._winnings) self._winnings.clear() elif play_1 < play_2: self.player_2['discard'].extend(self._winnings) self._winnings.clear() # Deal with ties (WARS!!!) ## This just adds the wagers to winnings; ## winnings are allocated to the winner of the next turn else: # Figure out how many cards to wager if play_1 == 14: i1, i2 = 4, 4 elif play_1 == 13: i1, i2 = 3, 3 elif play_1 == 12: i1, i2 = 2, 2 else: i1, i2 = 1,1 # Add wager cards to winnings; ## make sure each player keeps at least 1 card wagers = [[], []] while i1 > 0 and len(self.player_1['hand']) + len(self.player_1['discard']) > 1: wagers[0] = wagers[0] + [self.__get_top_card(self.player_1)] i1 -= 1 while i2 > 0 and len(self.player_2['hand']) + len(self.player_2['discard']) > 1: wagers[1] = wagers[1] + [self.__get_top_card(self.player_2)] i2 -= 1 self.__add_to_winnings(wagers) def __game_over(self, hand, max_hands): ''' Evaluate whether the game is over. Game is over when one player runs out of cards or the game goes past the max_hands limit. ''' # If either player runs out of cards... if (self.player_1['hand'] == [] and self.player_1['discard'] == []) \ or (self.player_2['hand'] == [] and self.player_2['discard'] == []): self.summary['finished'] = True return True # Or if the game exceeds the turn limit... elif hand >= max_hands: self.summary['finished'] = False return True # Otherwise, game not over else: return False def __get_top_card(self, player): ''' Get a player's top card. Player should be either 'player_1' or 'player_2'. ''' # Pop the top card... will throw an error if the player's hand is empty try: return player['hand'].pop(0) # Handle the error by recycling discard pile and then popping except: self.__recycle_discard(player) return player['hand'].pop(0) def __recycle_discard(self, player): ''' Recycle a player's discard pile back into their hand. ''' # Apply recycle function to discard and move to the player's hand player['hand'] += self.discard_recycle_func(player) # Empty the discard pile player['discard'] = [] def __add_to_winnings(self, card_list): ''' Add cards to the winnings pile. ''' # Shuffle the order in which we add player 1 / player 2 to discard ## if we are adding randomness there if self.discard_randomness: shuffle(card_list) # Add cards to winnings self._winnings = self._winnings + card_list[0] + card_list[1] def __reset_game(self): ''' Reset a game to the dealt hands. This is useful when using the seek method to go to a turn previous to the turn that was played to. ''' # Reset players' hands self.player_1['hand'] = self._player_1_dealt self.player_2['hand'] = self._player_2_dealt # Wipe discard self.player_1['discard'], self.player_2['discard'] = [], [] # Wipe summary self.summary = {'hands_played': 0, 'finished': None, 'tracks': [26], 'p1_dealt': self._player_1_dealt, 'p2_dealt': self._player_2_dealt} def __str__(self): hands_df = self.to_dataframe() return(hands_df.to_string(na_rep = ' ', index = False, float_format = lambda x: '{:.0f}'.format(x)))
6c568b74df3449df5ba6e42e462dac94694f6c84
slowrunner/Carl
/Examples/thread_exceptions/main_exception.py
2,763
3.734375
4
#!/usr/bin/env python3 # One Thread, exception in main """ If main() does not not catch exception and then wait for thread to finish with a join(), then main will exit, then thread continues on until done 22:11:30: Main : before creating thread 22:11:30: Main : before running thread 22:11:30: Thread 1: starting 22:11:30: Main : all done <----- MAIN EXITED W/O WAITING - no join() 22:11:32: Thread 1: raising div by zero exception Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "./exception_in_thread.py", line 49, in thread_function e=1/0 ZeroDivisionError: division by zero ----- THREAD EXITED DUE TO EXCEPTION If main() catches exception and then waits for thread to finish with a join(), thread will exit, then main will exit: 22:21:59: Main : before creating thread 22:21:59: Main : before running thread 22:21:59: Thread 1: starting 22:21:59: Main(): raising div by zero exception 22:21:59: Main(): handling exception <--- EXCEPTION IN MAIN BEFORE THREAD DONE 22:21:59: Main : wait for the thread to finish with join() 22:22:01: Thread 1: finishing 22:22:01: Main : all done 22:23:09: Main : before creating thread 22:23:09: Main : before running thread 22:23:09: Thread 1: starting 22:23:11: Thread 1: finishing <--- THREAD IS ACTUALLY DONE BEFORE MAIN EXCEPTION 22:23:14: Main(): raising div by zero exception 22:23:14: Main(): handling exception 22:23:14: Main : wait for the thread to finish with join() <--- NO WAIT NEEDED 22:23:14: Main : all done """ import logging import threading import time def thread_function(name): logging.info("Thread %s: starting", name) time.sleep(2) logging.info("Thread %s: finishing", name) if __name__ == "__main__": format = "%(asctime)s: %(message)s" logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S") logging.info("Main : before creating thread") x = threading.Thread(target=thread_function, args=(1,)) logging.info("Main : before running thread") x.start() try: time.sleep(5) logging.info("Main(): raising div by zero exception") e=1/0 except: logging.info("Main(): handling exception") finally: wait=False # uncomment next line to force main() to wait for thread exit wait=True if (wait==True): # Keep Main alive until thread finishes logging.info("Main : wait for the thread to finish with join()") x.join() logging.info("Main : all done")
72ce9638c773c7e6b6971bc662a205f7d25a7325
nibbletobits/nibbletobits
/python/day15_csv_dictonary_use.py
2,112
4.21875
4
# ******************************************** # Program Name: Day 15, hw # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: 7 26, 2021 # Purpose: program calculates tax + total cost of menu item's # Modules used: .csv # Input Variables: (1-5) # Output: print statements for purpose. # ******************************************** def main(): menu = {"1": 7.00, "2": 5.00, "3": 12.00, "4": 6.00, "5": 7.00} total = 0 print(''' Please choose the item number for the food you wish to purchase in bulk (1)carrots – $7.00 (2)onions - $5.00 (3)tomatoes - $12.00 (4)green beans -$6.00 (5)broccoli - $7.00 ''') keep_adding = True while keep_adding == True: item_pick = input("choose an item based in the number (1-5) above: ") while True: try: bulk_select = int(input("how many of the bulk item would you like: ")) break except: print("input needs to be digits 1-5:") for key in menu: if item_pick == key: adding_total = menu[item_pick] * bulk_select total += adding_total keep_going = input("do you want any other items 'Y'/'N': ") if keep_going.upper() == "Y": keep_adding = True continue elif keep_going.upper() == "N": keep_adding = False tax = total * state_tax() final_total = total + tax print("your final total is ", final_total) else: print("pleas enter a valid selection") continue def state_tax(): state_list = open("state_tax.csv", "r") # to travers in file, strip removes spaces, split while True: state_letter = input("pleas enter your state abbreviation: ") for item in state_list.readlines(): item.strip() item1 = item.split(",") if state_letter.upper() == item1[0]: state_list.close() return float(item1[1]) main()
2e31092b271eaa95955c0c8b1f627e5ec6c594f5
traplordpanda/pythonUMBC
/python/pythonlabs/examples/collections/list_loops.py
320
4.03125
4
#!/usr/bin/env python3 numbers = [10, 20, 30, 40, 50] # Looping by element for number in numbers: print(number, end="\t") print() # Looping by index and # updating list's values at the same time for index in range(len(numbers)): numbers[index] *= 10 for number in numbers: print(number, end="\t") print()
7755647a3bff01a3d65829130a9db69c41756ff3
aaroncymor/coding-bat-python-exercises
/List-1/make_ends.py
291
4.03125
4
""" Given an array of ints, return new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more. """ def make_ends(nums): new_nums = [] if nums > 1: new_nums.append(nums[0]) new_nums.append(nums[-1]) return new_nums
9f94cb8945d2b144b9c444e923db62fe7259aa94
jgschmitz/Python-Snips
/getVowels.py
235
3.96875
4
#This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string. def get_vowels(string): return [each for each in string if each in 'aeiou'] get_vowels('foobar') # ['o', 'o', 'a'] get_vowels('gym') # []
e6094c3521a70bbff1e48262002da1ec9c9e8569
vlcruvi/python-exercises
/initials_7_strings.py
278
4.03125
4
def initials(whole_name): result = "" initial = True for letter in whole_name: if initial: result += letter initial = False elif letter == " ": initial = True return print(result) initials("Vinicius Cruvinel")
8736bacba9a51c064500aaf5a32948694ef16f64
zjcalo/repository
/paned windows.py
588
3.6875
4
from tkinter import * from tkinter import ttk root = Tk() root.title('Paned Menu') root.geometry("400x400") # Panels panel_1 = PanedWindow(bd=4, relief="raised", bg="red") panel_1.pack(fill=BOTH, expand=1) left_label = Label(panel_1, text="Left Panel") panel_1.add(left_label) # Create a second panel panel_2 = PanedWindow(panel_1, orient = VERTICAL, bd=4, relief="raised", bg="blue") panel_1.add(panel_2) top_label = Label(panel_2, text = "Top Label") panel_2.add(top_label) bottom_label = Label(panel_2, text = "Bottom Label") panel_2.add(bottom_label) root.mainloop()
ce7ccf14229e3b626b90f73bb1de5c510d2eeac7
edwintcloud/algorithmPractice
/LeetCode/Google/Top Ten/3 - K Empty Slots/solution.py
2,261
3.640625
4
def k_empty_slots(flowers, k): '''@param flowers: list of positions for each day the flowers will bloom @param k: integer representing the required distance between two bloomed flowers in which no flowers have bloomed @return: day satisfying k''' # initialize a zero filled list the length of flowers days = [0] * len(flowers) # fill days with days[position-1] = day # the opposite of flowers which is flowers[day-1] = position for i in range(len(flowers)): days[flowers[i]-1] = i+1 # initialize our window left and right indexes # left starts at 0 # right starts at k + 1 (our first window of two blooms) left = 0 right = k + 1 # initialize result to the length of flowers + 1 result = len(flowers) + 1 # loop: shift our window left until right is greater than the length of flowers while right < len(flowers): # i is our current index in the days list # we start i at left + 1 i = left + 1 # increment i while i < right and current day is > left day and current day is > right day while i < right and days[i] > max(days[left], days[right]): i += 1 # if our current index reaches right we have found a match for k # but it may not be the first day, so each time result is set # make sure we are setting it to the min of current result and previous result # current result is the max of left day and right day if i == right: result = min(result, max(days[left], days[right])) # shift window right by setting left equal to current index # and right equal to current index + k + 1 left = i right = i + k + 1 # if result ends up equal to the length of flowers + 1, # a day was not found satisfying k; return -1. # otherwise return result return -1 if result == len(flowers) + 1 else result ## TEST ## tests = [ ([1, 3, 2], 1), ([1, 2, 3], 1), ([3, 2, 6, 1, 4, 5], 2), ([5, 6, 1, 2, 3, 4], 1) ] for _, (flowers, k) in enumerate(tests): result = k_empty_slots(flowers, k) print("flowers:", flowers) print("k:", k) print("Output:", result)
3fd90b68177a73693487e68b2ff8d1db8fa9c871
Peritract/text_adventure
/text_adventure/tools/output_functions.py
471
3.8125
4
"""Functions that deal with displaying information on the console.""" import os import sys from time import sleep def display(message, delay=0.05): """Displays text as though it was being written.""" for char in message + "\n": sys.stdout.write(char) sys.stdout.flush() sleep(delay) def clear_screen(): """Clears the console window.""" if sys.platform == 'win32': os.system('cls') else: os.system('clear')
ed07ace8d8b0b763d01bc7b1fa8cb520ce00882d
krothleder/shopping_list.py
/conditionals.py
309
3.828125
4
# my_name = "Timea" # pair_name = "Marla" # if my_name > pair_name: # print "my name is greater!" # elif pair_name > my_name: # print "their name is greater!" # else: # print "our names are equal" date = 21 if date >= 15: print "We're halfway there!" if date <= 14: print "The month is still young."
22342ad3050791903079ca3bc74a0af9387d0925
pi7807pa/super-funicular
/test.py
145
3.640625
4
def input(): a=raw_input("enter a") b=raw_input("enter b") return a, b def area(): int a,int b = input(); print(a, b) c=a*b;
c43896293aa6adf4ce774bc96e1f209b98972e3d
ZazAndres/Ejercicios_Taller_Lab24
/punto5.py
574
3.921875
4
from typing import Sized cond="si" def frecuencia(numero,digito): cantidad=0 while numero !=0: ultDigito=numero%10 if ultDigito==digito: cantidad+=1 numero=numero//10 return cantidad while cond=="si": num=int(input("ingrese un numero: ")) un_digito=int(input("ingrese un digito: ")) print("frecuencia del digito en el numero:",frecuencia(num,un_digito)) cond=input("¿Quieres volver a ingresar un numero y un digito?\n¿Si o no?\n") if cond=="no": print("vuelve pronto amigo")
328442a52454712f117fb2038ec86001266d3eb3
eytanohana/Machine-Learning-Implementations
/app/ml_pages/k_means.py
2,983
4.0625
4
import numpy as np import streamlit as st from skimage import io from PIL import Image from .src.kmeans import kmeans, display_image def run(): st.markdown(''' # K-Means K-Means is an algorithm for grouping similar data into K predefined groups. In this app we'll use K-Means to compress an image using color quantization, the process of compressing an image by representing it using less colors. ''') image = st.file_uploader('Choose an image', accept_multiple_files=False) if not image: st.stop() image = Image.open(image) image.thumbnail(size=(500, 500)) st.image(image) image = np.asarray(image) original_shape = image.shape with st.expander('Explanation'): st.write(f''' The shape of the image is: {image.shape} The first dimension, {image.shape[0]}, represents the height of the image, while the second, {image.shape[1]}, represents the width of the image, both being in pixels. The third dimension, {image.shape[2]}, represents the different color channels of the image. Most traditionally, rgb, representing the red/green/blue intensities of each channel for each pixel. The intensities ranging from 0 - 255. ''') image = image.reshape(image.shape[0] * image.shape[1], image.shape[2]) st.write(f''' For the K-means algorithm, we need to reshape the data into two dimensions. The number of rows corresponding to the number of pixels in the image and the number of columns representing the different color channels: {image.shape} - {len(image):,} pixels ''') st.markdown(r''' ## The Algorithm 1. We start by choosing k random points, called the `centroids`. 1. We then assign every point in the dataset to the nearest centroid. * All points belonging to the same centroid belong to the same "group". 1. We then calculate the mean point for each group and assign the means as the new centroids. 1. We then repeat steps 2 and 3 until we don't see a change in the means or we reach a predetermined maximum number of iterations. ### The distance metric To calculate the distance between two points, we use the Minkowski distance metric. The Minkowski distance of order $p$ between two points: $\vec{x}=(x_1, ..., x_n)$ and $\vec{y}=(y_1, ..., y_n)$ is: $$ D(\vec{x},\vec{y}) = (\sum_{i=1}^n \mid x_i - y_i \mid ^p)^{\frac{1}{p}} $$ The Minkowski distance is a generalization of the Euclidean ($p=2$) and Manhattan ($p=1$) distances. ''') a, b = st.columns(2) k = a.number_input('Number of centroids', 2, 20) p = b.number_input('Distance metric', 2, 100) with st.spinner(): centroids, classes = kmeans(image, k, p) compressed_img = display_image(centroids, classes, original_shape) st.image(compressed_img)
fe521db176675e8b2771d738ac1ce55adcd47aa2
EraSilv/day2
/dzz/dz9.py
922
3.921875
4
fruits1 = { 'apple', 'cherry', 'banana', 'lemon', 'watermelon', 'coconut', 'salt' } fruits2 = { 'melon', 'potato', 'tomato', 'banana', 'carrot', 'lemon' } print(fruits1.intersection(fruits2)) #--------------------------------------------------------------------------------- fruits1 = { 'apple', 'cherry', 'banana', 'lemon', 'watermelon', 'coconut', 'salt' } fruits2 = { 'melon', 'potato', 'tomato', 'banana', 'carrot', 'lemon' } print(fruits1.update(fruits2)) #-------------------------------------------------------------------------------- predmets ={ 'биография', 'математика', 'химия', 'биология', 'физика', 'астрономия', '123Физ', 'Гастрономия', 'Книги', 'Литература' } predmets.remove('Книги') predmets.remove('123Физ') predmets.remove('Гастрономия') predmets.remove('биография') print(predmets)
d471926913c0a9574d2fad457421e68160fbe016
mikebestoso/portfolio
/Alien Invasion/alien/bullet.py
6,270
4.25
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """A class to manage bullets fired from the ship""" def __init__(self, ai_game): """Create a bullet object at the ships current location""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings self.color = self.settings.bullet_color #Create a bullet rect at (0, 0) and then set the correct position #here we create the bullet's rect attribute #the bullets are not images, so they are created from scratch #bullets need (x, y) locations of the top left of the rect. starts (0,0) #bullets locations depend on ship location self.rect = pygame.Rect(0, 0, self.settings.bullet_width, self.settings.bullet_height) #set bullet midtop attribute to match the ships midtop attribute #this will allow the bullets to emerge from from the top of the ship #makes it look like the bullets are being fired from the ship self.rect.midtop = ai_game.ship.rect.midtop #Store the bullets position as a decimal point (store decimal valuefor the bullet's y-coordinate) self.y = float(self.rect.y) def update(self): """Move bullets up the screen""" #Update the decimal position of the bullet. #update method controls bullet location on the screen, which corresponds to a decreasing y-coordinate value #to update the position we subtract the amount stored in settings.bullet_speed from self.y self.y -= self.settings.bullet_speed #Update the rect position #we then use the value of self.y to set the value of self.rect.y self.rect.y = self.y def draw_bullet(self): """Draw the bullets onto thee screen""" #when drawing a bullet, we call bullet_ddraw() #the draw.rect() function fills the part of the screen defined by the bullet's rect with the color stored in self.color pygame.draw.rect(self.screen, self.color, self.rect) def check_edges(self): """Return True if alien is at the screens edge""" screen_rect = self.screen.get_rect() if self.rect.top <= 0: return True class Bullet_two(Sprite): """A class to manage bullets fired from the ship""" def __init__(self, ai_game): """Create a bullet object at the ships current location""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings self.color = (255, 0, 0) #Create a bullet rect at (0, 0) and then set the correct position #here we create the bullet's rect attribute #the bullets are not images, so they are created from scratch #bullets need (x, y) locations of the top left of the rect. starts (0,0) #bullets locations depend on ship location self.rect = pygame.Rect(0, 0, self.settings.bullet_width, self.settings.bullet_height) #set bullet midtop attribute to match the ships midtop attribute #this will allow the bullets to emerge from from the top of the ship #makes it look like the bullets are being fired from the ship self.rect.topleft = ai_game.ship.rect.topleft #Store the bullets position as a decimal point (store decimal valuefor the bullet's y-coordinate) self.x = float(self.rect.x) self.y = float(self.rect.y) def update(self): """Move bullets up the screen""" #Update the decimal position of the bullet. #update method controls bullet location on the screen, which corresponds to a decreasing y-coordinate value #to update the position we subtract the amount stored in settings.bullet_speed from self.y self.x -= self.settings.bullet_speed self.y -= self.settings.bullet_speed #Update the rect position #we then use the value of self.y to set the value of self.rect.y self.rect.x = self.x self.rect.y = self.y def draw_bullet(self): """Draw the bullets onto thee screen""" #when drawing a bullet, we call bullet_ddraw() #the draw.rect() function fills the part of the screen defined by the bullet's rect with the color stored in self.color pygame.draw.rect(self.screen, self.color, self.rect) def check_edges(self): """Return True if alien is at the screens edge""" screen_rect = self.screen.get_rect() if self.rect.left <= 0 or self.rect.top <= 0: return True class Bullet_three(Sprite): """A class to manage bullets fired from the ship""" def __init__(self, ai_game): """Create a bullet object at the ships current location""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings self.color = (0, 102, 255) #Create a bullet rect at (0, 0) and then set the correct position #here we create the bullet's rect attribute #the bullets are not images, so they are created from scratch #bullets need (x, y) locations of the top left of the rect. starts (0,0) #bullets locations depend on ship location self.rect = pygame.Rect(0, 0, self.settings.bullet_width, self.settings.bullet_height) #set bullet midtop attribute to match the ships midtop attribute #this will allow the bullets to emerge from from the top of the ship #makes it look like the bullets are being fired from the ship self.rect.topright = ai_game.ship.rect.topright #Store the bullets position as a decimal point (store decimal valuefor the bullet's y-coordinate) self.x = float(self.rect.x) self.y = float(self.rect.y) def update(self): """Move bullets up the screen""" #Update the decimal position of the bullet. #update method controls bullet location on the screen, which corresponds to a decreasing y-coordinate value #to update the position we subtract the amount stored in settings.bullet_speed from self.y self.x += self.settings.bullet_speed self.y -= self.settings.bullet_speed #Update the rect position #we then use the value of self.y to set the value of self.rect.y self.rect.x = self.x self.rect.y = self.y def draw_bullet(self): """Draw the bullets onto thee screen""" #when drawing a bullet, we call bullet_ddraw() #the draw.rect() function fills the part of the screen defined by the bullet's rect with the color stored in self.color pygame.draw.rect(self.screen, self.color, self.rect) def check_edges(self): """Return True if alien is at the screens edge""" screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right or self.rect.top <= 0: return True
ccf80d4a90fc7f9b7e78ddf5165a203b1c7c21fc
heeewo/Algorithm
/search/Sequential_search/Sequentual_serach_python.py
286
3.828125
4
def SequentialSearch(nlist, item): pos = 0 found = False while pos < len(nlist) and not found: if nlist[pos] == item: found = True else: pos = pos + 1 return found nlist = [4, 2, 9, 7, 1, 3] print(SequentialSearch(nlist, 3))
67b9d28a296cc5bd34af2dcb72208d0cdd9c6bb1
ArmandoRuiz2019/Python
/Selectivos/Selectivos03.py
402
3.625
4
nom="" sue=0 bon=0 nom=input("Ingrese su nombre:") sue=int(input("Ingrese su sueldo:")) tser=int(input("Tiempo de Servicio:")) if tser>=1 and tser<=3: bon=sue*0.02 #print("La Bonificacion de:"+ nom + "es:"+str(bon)) elif tser>=4 and tser<=5: bon=sue*0.03 #print("La Bonificacion de:"+ nom + "es:"+str(bon)) else: bon=sue*0.04 print("La Bonificacion de:"+ nom + "es:"+str(bon))
3f5067553c1a79cad752de92a44e754cd766c70b
jubbynox/redcaza
/RedCaza/src/mediasearch/jsonpickle/pickler.py
4,017
3.53125
4
# -*- coding: utf-8 -*- # # Copyright (C) 2008 John Paulett (john -at- 7oars.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import util class Pickler(object): """Converts a Python object to a JSON representation. Setting unpicklable to False removes the ability to regenerate the objects into object types beyond what the standard simplejson library supports. >>> p = Pickler() >>> p.flatten('hello world') 'hello world' """ def __init__(self, unpicklable=True): self.unpicklable = unpicklable def flatten(self, obj): """Takes an object and returns a JSON-safe representation of it. Simply returns any of the basic builtin datatypes >>> p = Pickler() >>> p.flatten('hello world') 'hello world' >>> p.flatten(u'hello world') u'hello world' >>> p.flatten(49) 49 >>> p.flatten(350.0) 350.0 >>> p.flatten(True) True >>> p.flatten(False) False >>> r = p.flatten(None) >>> r is None True >>> p.flatten(False) False >>> p.flatten([1, 2, 3, 4]) [1, 2, 3, 4] >>> p.flatten((1,)) (1,) >>> p.flatten({'key': 'value'}) {'key': 'value'} """ if util.isprimitive(obj): return obj elif util.iscollection(obj): data = [] # obj.__class__() for v in obj: data.append(self.flatten(v)) return obj.__class__(data) #TODO handle tuple and sets elif util.isdictionary(obj): data = obj.__class__() for k, v in obj.iteritems(): data[k] = self.flatten(v) return data elif isinstance(obj, object): data = {} module, name = self._getclassdetail(obj) if self.unpicklable is True: data['classmodule__'] = module data['classname__'] = name if util.is_dictionary_subclass(obj): if self.unpicklable is True: # this will place items in a sub dictionary (arguably not a pure JSON representation, # since it should be at root level. However, this method preserves the object # so that it can be recreated as a Python object data['classdictitems__'] = self.flatten(dict(obj)) else: # this option will place everything at root, but it allows a dictionary key # to overwrite an instance variable if both have the same name for k, v in obj.iteritems(): data[k] = self.flatten(v) #elif util.is_collection_subclass(obj): # data['__classcollectionitems__'] = self.flatten() elif util.is_noncomplex(obj): data = [] # obj.__class__() for v in obj: data.append(self.flatten(v)) else: for k, v in obj.__dict__.iteritems(): data[str(k)] = self.flatten(v) return data # else, what else? (classes, methods, functions, old style classes...) def _getclassdetail(self, obj): """Helper class to return the class of an object. >>> p = Pickler() >>> class Klass(object): pass >>> p._getclassdetail(Klass()) ('jsonpickle.pickler', 'Klass') >>> p._getclassdetail(25) ('__builtin__', 'int') >>> p._getclassdetail(None) ('__builtin__', 'NoneType') >>> p._getclassdetail(False) ('__builtin__', 'bool') """ cls = getattr(obj, '__class__') module = getattr(cls, '__module__') name = getattr(cls, '__name__') return module, name
7c033e6ea087f5ce359b4191ed726cd49b7ac9b0
mehtank/dinoparmfish
/players/randomPlayer/player.py
2,050
3.53125
4
import random from ..engine import card class Player: def output(self, s): if not self.debug: return print "Player " + repr(self.index) + ": ", print s def __init__(self, debug=False): self.debug = debug def setup(self, index, handSizes, hand): self.index = index self.numPlayers = len(handSizes) self.hand = hand s = "Initialized : " for c in hand: s += "\n " + repr(c) self.output(s) def passTo(self): return (self.index + 2) % self.numPlayers; def getAsk(self): target = random.randint(0, (self.numPlayers / 2) - 1) target = target * 2 + 1 target = (target + self.index) % self.numPlayers myCard = random.choice(self.hand) values = range(card.NUMVALUES) for c in self.hand: if c.suit == myCard.suit: values.pop(values.index(c.value)) value = random.choice(values) ask = card.Card(suit=myCard.suit, value=value) self.output("asking player " + repr(target) + " for " + repr(ask)) return (target, ask) def tellAsk(self, currentPlayer, target, card, askSuccessful): if askSuccessful: if (target == self.index): self.output("Gave " + repr(card) + " to player " + repr(currentPlayer)) self.hand.pop(self.hand.index(card)) if (currentPlayer == self.index): self.output("Got " + repr(card) + " from player " + repr(target)) self.hand.append(card) def getDeclaration(self): for suit in range(card.NUMSUITS): count = 0 for c in self.hand: if c.suit == suit: count += 1 if count == card.NUMVALUES: self.output("Declaring suit: " + repr(suit)) return (suit, [self.index] * card.NUMVALUES) else: return (None, None) def tellDeclaration(self, currentPlayer, suit, attrib, declarationSuccessful, trueAttrib): if declarationSuccessful is None: return topop = [] for c in self.hand: if c.suit == suit: topop.append(c) for c in topop: self.hand.pop(self.hand.index(c))
3730a2944636ab364765a6db5206cd8b47143a63
aakritisingh/Algorithm-Toolbox
/week 3/covering_segments.py
928
3.953125
4
# Uses python3 import sys from collections import namedtuple Segment = namedtuple('Segment', 'start end') def getEnd(segment): return segment[1] def inSegment(point,segment): if point <= segment[1] and point >= segment[0]: return True return False def optimal_points(segments): points = [] #write your code here sorted_segments = sorted(segments,key=lambda x:x[1]) lastPt = getEnd(sorted_segments[0]) points.append(lastPt) for i in range(1,len(sorted_segments)): seg = sorted_segments[i] if not inSegment(lastPt,seg): lastPt = getEnd(seg) points.append(lastPt) return points if __name__ == '__main__': input = sys.stdin.read() n, *data = map(int, input.split()) segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2]))) points = optimal_points(segments) print(len(points)) print(*points)
cbb1958de3e9834d07c2c0842b224b42736d413d
dunossauro/GECA
/ROT13/rot13.py
275
3.953125
4
#!/usr/bin/python 3 import string def cripto(frase): alfabeto = string.ascii_uppercase saida = "" for letra in frase: busca = alfabeto.find(letra)+13 modulo = busca % 26 saida += str(alfabeto[modulo]) print(saida) input("\n\nPressione Enter para continuar")
fb2815234532e1aa7407254068bc5de00ac9b677
PyLamGR/PyLam-Edu
/Workshops/11.03.2018 - Python. The Basics - Volume 2 -/Python Codes/3. Επαναληψη - Δομή Επιλογής-Επανάληψης, Λίστες/10_nested_loops2.py
212
3.578125
4
counter = 0 for i in range(10): for j in range(10): if i > j: counter +=1 print(counter) # Τι τιμή πιστεύετε θα έχει ο counter οταν τελειώσει το πρόγραμμα;
f86682c3b0f4b858e0f9a7365eb68c1ca18934e6
thenerdpoint60/PythonCodes
/palindrome.py
241
3.921875
4
def isPalindrome(a): i=0 j=len(a)-1 while(i<j and a[i]==a[j]): i+=1 j-=1 if(i<j): print("Not a palindrome") return 0 else: print("palindrome") return 1
baa6008cf762a91b866753c7b66ba5a622dadd7d
Lamia7/MacGyver_game
/item.py
1,071
3.796875
4
#! /usr/bin/env python3 # coding: utf-8 """ Item module that contains the Item class """ import random from config import SPRITE_SIZE import pygame class Item: def __init__(self, my_map, img): """Constructor that initializes the items""" self.img = pygame.image.load(img).convert() self.random_x = '' self.random_y = '' self.maze = my_map self.valid_positions = [] self.get_valid_positions() self.set_position() def get_valid_positions(self): """Method that creates a list of valid positions""" for y, line in enumerate(self.maze.structure_map): for x, caract in enumerate(line): if caract == 'o': self.valid_positions.append((x, y)) def set_position(self): """Method that sets a random position from the valid_positions list""" self.random_x, self.random_y = random.choice(self.valid_positions) self.random_x = self.random_x * SPRITE_SIZE self.random_y = self.random_y * SPRITE_SIZE
51a8f51fc63b1162cd09febf78f9c922eceba62b
yyyuaaaan/pythonfirst
/crk/1.6.py
704
3.53125
4
""" __author__ = 'anyu' Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? 0(N2) """ def matrixro(ma): N= len(ma) ma = zip(*ma) # transpose matrix, very interesting, aij = aji, #ther ways to transpose [[row[i] for row in matrix] for i in range(4)] #for i in range(4): # for j in range(i,4): # dia[i][j],dia[j][i]=dia[j][i],dia[i][j] N2= N//2 for k in range(N2): ma[k],ma[N-1-k] = ma[N-1-k], ma[k] # swap row[k] and row[N-1-k] return ma dia=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]] print matrixro(dia)
92c0602e6efa75b3eb1371e668fb3c5fa9128b70
HuangYukun/columbia_cs_deep_learning_1
/ecbm4040/features/pca.py
1,955
3.53125
4
import time import numpy as np from numpy.linalg import eigh def pca_naive(X, K): """ PCA -- naive version Inputs: - X: (float) A numpy array of shape (N, D) where N is the number of samples, D is the number of features - K: (int) indicates the number of features you are going to keep after dimensionality reduction Returns a tuple of: - P: (float) A numpy array of shape (K, D), representing the top K principal components - T: (float) A numpy vector of length K, showing the score of each component vector """ ############################################### #TODO: Implement PCA by extracting eigenvector# ############################################### # data = X # data_mean = data.mean() # data_zero_mean = data.map(lambda obs: obs - data_mean) # data_zero_mean = list(map(lambda obs: obs - data_mean, data)) # print(data_zero_mean) # cov = (data_zero_mean # .map(lambda obs: np.outer(obs, obs)) # .reduce(lambda a, b: a + b) # ) * 1. / data_zero_mean.count() # cov = np.cov(X) X1 = X - X.mean(axis=0) N = X1.shape[0] # !!! fact = float(N - 1) cov = np.dot(X1.T, X1) / fact eig_vals, eig_vecs = eigh(cov) # print(eig_vecs.shape) inds = np.argsort(eig_vals)[::-1] # print(inds[:K].shape) # P = eig_vecs[:, inds[:K]] P = eig_vecs[inds[:K], :] T = 0 # print(cov.shape) # print(X.shape) # print(P.shape) # print(P[0,0]) # print(eig_vecs[:, inds[:K]].shape) # T = X.map(lambda obs: np.dot(obs, eig_vecs[:, inds[:K]])) # T = list(map(lambda obs: np.dot(obs, eig_vecs[:, inds[:K]]), X)) # print(T.shape) # print(X.shape) ############################################### # End of your code # ############################################### return (P, T)