blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
ad6fc102c4ad03ca32dc29b84cdffb1d6108147e
VitaliiUr/wiki
/wiki
2,978
4.15625
4
#!/usr/bin/env python3 import wikipedia as wiki import re import sys import argparse def get_random_title(): """ Find a random article on the Wikipadia and suggests it to user. Returns ------- str title of article """ title = wiki.random() print("Random article's title:") print(title) ans = input( "Do you want to read it?\n (Press any key if yes or \"n\" if you want to see next suggestion)\n\ Press \"q\" to quit") if ans in ("n", "next"): return get_random_title() elif ans == "q": print("sorry for that") sys.exit(0) else: return title def search_title(search): """ Looks for the article by title Parameters ---------- search : str query for the search Returns ------- str title of the article """ titles = wiki.search(search) print(">>> We found such articles:\n") print(*[f"\"{t}\","for t in titles[:5]], "\n") for title in titles: print(">>> Did you mean \"{}\"?\n Press any key if yes or \"n\"".format(title), "if you want to see next suggestion") ans = input("Press \"q\" to quit") if ans in ("n", "next"): continue elif ans == "q": print(">>> Sorry for that. Bye") sys.exit(0) else: return title def split_paragraphs(text): # Remove bad symbols text = re.sub(r"\s{2,}", " ", text.strip()) text = re.sub(r"\n{2,}", "\n", text) # Split article to the paragraphs pat = re.compile( r"(?:(?:\s?)(?:={2,})(?:\s*?)(?:[^=]+)(?:\s*?)(?:={2,}))") paragraphs = pat.split(text) # Get titles of the paragraphs pat2 = re.compile( r"(?:(?:\s?)(?:={2,})(?:\s?)([^=]+)(?:\s?)(?:={2,}))") titles = list(map(lambda x: x.strip(), ["Summary"] + pat2.findall(text))) # Create a dictionary of the paragraphs and return it result = dict(zip(titles, paragraphs)) if "References" in result: del result["References"] return result if __name__ == "__main__": # Get arguments parser = argparse.ArgumentParser() parser.add_argument("search", type=str, nargs='?', help="search wiki article by title") args = parser.parse_args() if args.search: name = search_title(args.search) # search article by title else: name = get_random_title() # get random article if name: print(">>> Article is loading. Please, wait...") page = wiki.page(name) else: print(">>> Please, try again") sys.exit(0) paragraphs = split_paragraphs(page.content) print("\n===== ", name, " =====") for title in paragraphs: print("\n") print("=== ", title, " ===") print(paragraphs[title]) ans = input( "Press any key to proceed, \"q\" to quit") if ans == "q": sys.exit(0)
e613f8fec147ea3779275d842b9ea717c0d81b6a
jessnightshade/AE401-Python
/determining scores.py
847
3.796875
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 14 14:46:06 2020 @author: Jamie """ num=input('number of students:') scorelist=[] namelist=[] high=0 low=0 #highname='' #lowname='' for i in range (int(num)): students_name=input('student:') score=input('score:') scorelist.append(int(score)) namelist.append(students_name) if int(score)>scorelist[high]: high=i #highname=students_name if int(score)<scorelist[low]: low=i #lowname=students_name Avg=sum(scorelist)/int(num) for j in range (int(num)): if scorelist[j]==scorelist[high]: print('highest score:',scorelist[j],namelist[j]) for k in range (int(num)): if scorelist[k]==scorelist[low]: print('lowest score:',scorelist[k],namelist[k]) print('average:',Avg)
352cf38d9eb30ad66982dd664484bc04a360f5b8
LordOTime/Zork
/zork2.21.py
1,256
3.859375
4
#!/usr/bin/python print("What is your name?") name = raw_input() print(' ') print "Welcome to Zork 2.0, %s. Your adventure starts here." % (name) print("You find yourself standing in the courtyard in the middle of a grand castle. Beneath your feet are gray cobbles, and you are surrounded my many bustling shops, inns, and pubs. Choose one of the selections to enter.") print(' ') print("The Jolly Man's Cave") print("The Crown Inn") print("Ye Olde Hat Shoppe") print("Old Bucktooth's") print("The Gilded Lilly") print(' ') shop = raw_input('your choice of establishment:') if shop == "Ye Olde Hat Shoppe": print("You enter the shop, and, as expected, it is filled with hats of all kinds. There is a tall, thin, pale man behind the counter who asks, \"Would you like to buy a hat?\"") print print("Wizard hat") print("Knight's helmet") print("Fez") print("No thanks") print(' ') hat = raw_input('your choice of hat:') if hat == "Wizard hat": hat = "wizard" print("\"Excellent choice!\"") elif hat == "Knight's helmet": hat = "helmet" print("\"Excellent choice!\"") elif hat == "Fez": hat = "cool" print("\"Excellent choice!\"") elif hat == "No thanks": hat = "none" print("\"Very well.\"") print("You return to the courtyard.")
7d5351b14c26988c70ba2f25426c075f697ac75e
ShijiaLiLiLi/leetcode
/26_Remove_Duplicates_from_Sorted_Array/python.py
464
3.5
4
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: if len(nums) == 0: return 0 cur_idx = 0 ori_idx = 1 length = 1 while (ori_idx < len(nums)): if nums[ori_idx] != nums[ori_idx-1]: cur_idx += 1 nums[cur_idx] = nums[ori_idx] length += 1 ori_idx += 1 return length
3597264c90e7ed79a2396541fdb09485550098dc
ans4572/CodingTest-with-Python
/구현/Q11 뱀.py
1,531
3.640625
4
from collections import deque N = int(input()) # 보드의 크기 K = int(input()) # 사과의 개수 board = [[0] * (N + 1) for _ in range(N + 1)] # 0:빈 공간, 1:뱀 2:사과 for i in range(K): row, col = list(map(int, input().split())) board[row][col] = 2 L = int(input()) command = [] for i in range(L): x, dic = list(input().split()) command.append((x, dic)) command_idx = 0 # 오른쪽, 아래, 왼쪽, 위 순서 dic = [[0, 1], [1, 0], [0, -1], [-1, 0]] count = 0 board[1][1] = 1 snake = deque() # 뱀 몸통 위치 deque snake.append((1,1)) d = 0 # 방향 (처음에는 ->) while True: """ print() for i in range(1, N+1): for j in range(1, N+1): print(board[i][j], end = " ") print() """ count += 1 # 다음 위치 next_r = snake[-1][0] + dic[d][0] next_c = snake[-1][1] + dic[d][1] snake.append((next_r, next_c)) # 벽에 부딪히는 경우 if next_r < 1 or next_r > N or next_c < 1 or next_c > N: break # 뱀을 만나는 경우 if board[next_r][next_c] == 1: break # 빈 공간인 경우 elif board[next_r][next_c] == 0: board[snake[0][0]][snake[0][1]] = 0 snake.popleft() board[next_r][next_c] = 1 # 방향 전환 if count == int(command[command_idx][0]): if command[command_idx][1] == 'D': d = (d + 1) % 4 else: d = (d + 3) % 4 if command_idx < len(command) - 1: command_idx += 1 print(count)
1e2fce93d89f27864c733c6c254d1b2b7597b038
ans4572/CodingTest-with-Python
/최단 경로/다익스트라.py
929
3.5
4
import heapq # 노드 개수와 간선 개수 n, m = map(int, input().split()) # 시작 노드 번호 start = int(input()) # 그래프 리스트 graph = [[] for i in range(n+1)] distance = [float('inf')] * (n+1) # 간선 입력 받기 for i in range(m): a, b, w = map(int, input().split()) graph[a].append((b, w)) #다익스트라 알고리즘 def dijkstra(start): distance[start] = 0 q = [] heapq.heappush(q,(0, start)) while q: dist, now = heapq.heappop(q) if distance[now] < dist: continue for node in graph[now]: cost = dist + node[1] if cost < distance[node[0]]: distance[node[0]] = cost heapq.heappush(q, (cost, node[0])) dijkstra(start) for i in range(1, n+1): if distance[i] == float('inf'): print('none') else: print(distance[i])
eb4b8614adcefc430b5433348d22253740350209
ans4572/CodingTest-with-Python
/정렬/6-11 성적이 낮은 순서로 학생 출력하기.py
224
3.65625
4
N = int(input()) arr = [] for i in range(N): data = input().split() arr.append((data[0],int(data[1]))) arr = sorted(arr, key=lambda student: student[1]) for student in arr: print(student[0], end=' ')
901b51b5e8faba528e6b72607bc8c6bbc13f7248
hugomst/MITx_6.00.1x_Introduction-to-Computer-Science-and-Programming-Using-Python
/Unit1_PS2.py
431
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 13 22:02:34 2021 @author: Hugo """ Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2 count = 0 for i in range(len(s)): if (s[i:i+3]) == "bob": count += 1 print(count)
1cc8c34fd13484b3f56df6cb9656ed567e0ca6b0
VenusMeow/nannonml
/nannon/scratch_nn.py
4,429
3.78125
4
import numpy as np import scipy.special # A few useful resources: # # NumPy Tutorial: # https://docs.scipy.org/doc/numpy/user/quickstart.html # # Backpropogation Calculus by 3Blue1Brown: # https://www.youtube.com/watch?v=tIeHLnjs5U8 # # Make Your Own Neural Network: # https://www.amazon.com/Make-Your-Own-Neural-Network-ebook/dp/B01EER4Z4G # def sigmoid(x): return 1.0 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1.0 - x) class ScratchNetwork: def __init__(self, n_input, n_hidden, n_output, learning_rate=0.3): # Set number of nodes in each input, hidden, output layer self.n_input = n_input self.n_hidden = n_hidden self.n_output = n_output # We link the weight matrices below. # Weights between input and hidden layer = weights_ih # Weights between hidden and output layer = weights_ho # Weights inside the arrays are w_i_j, where the link is from node i to # node j in the next layer # w11 w21 # w12 w22 etc... # # Weights are sampled from a normal probability distribution centered at # zero with a standard deviation related to the number of incoming links # into a node: 1/√(number of incoming links). random_init_range = pow(self.n_input, -0.5) self.weights_ih = np.random.normal(0.0, random_init_range, (self.n_hidden, self.n_input)) self.weights_ho = np.random.normal(0.0, random_init_range, (self.n_output, self.n_hidden)) # Set the learning rate. self.lr = learning_rate # Use to train the neural network. def train(self, inputs_list, targets_list): # First convert inputs and targets lists to 2d arrays. inputs = np.array(inputs_list, ndmin=2).T targets = np.array(targets_list, ndmin=2).T # Step 1: FEED-FORWARD to get outputs # Calculate signals into hidden layer. hidden_inputs = np.dot(self.weights_ih, inputs) # Calculate the signals emerging from hidden layer. hidden_outputs = sigmoid(hidden_inputs) # Calculate signals into final output layer. final_inputs = np.dot(self.weights_ho, hidden_outputs) # Calculate signals emerging from final output layer. final_outputs = sigmoid(final_inputs) # Step 2: Calculate error # Output layer error is the (actual - targets). output_errors = final_outputs - targets # Hidden layer error is the output_errors, split by weights, # recombined at hidden nodes hidden_errors = np.dot(self.weights_ho.T, output_errors) # Step 3: BACKPROP # Derivative of output_errors with respect to final_outputs deriv_oe_fo = 2 * output_errors # Derivative of final outputs with respect to z2 (weights_ho * hidden_outputs) deriv_fo_z2 = sigmoid_derivative(final_outputs) # Derivative of z2 with respect to weights_ho deriv_z2_who = hidden_outputs.T # Update the weights for the links between the hidden and output layers. self.weights_ho -= self.lr * np.dot(deriv_oe_fo * deriv_fo_z2, deriv_z2_who) # Derivative of hidden_errors with respect to hidden_outputs deriv_he_ho = 2 * hidden_errors # Derivative of hidden_outputs with respect to z1 (weights_ih * inputs) deriv_ho_z1 = sigmoid_derivative(hidden_outputs) # Derivative of z1 with respect to weights_ih deriv_z1_wih = inputs.T # Update the weights for the links between the input and hidden layers. self.weights_ih -= self.lr * np.dot(deriv_he_ho * deriv_ho_z1, deriv_z1_wih) # Query the neural network with simple feed-forward. def query(self, inputs_list): # Convert inputs list to 2d array. inputs = np.array(inputs_list, ndmin=2).T # Calculate signals into hidden layer. hidden_inputs = np.dot(self.weights_ih, inputs) # Calculate the signals emerging from hidden layer. hidden_outputs = sigmoid(hidden_inputs) # Calculate signals into final output layer. final_inputs = np.dot(self.weights_ho, hidden_outputs) # Calculate the signals emerging from final output layer. final_outputs = sigmoid(final_inputs) return final_outputs
b2b22e8264799467c43b2051c63228d1304533f6
rdcorrigan/bmiCalculatorApp
/bmi_calculator.py
1,070
4.125
4
# BMI Calculator # by Ryan # Python 3.9 using Geany Editor # Windows 10 # BMI = weight (kilograms) / height (meters) ** 2 import tkinter # toolkit interface root = tkinter.Tk() # root.geometry("300x150") // OPTIONAL root.title("BMI Calculator") # Create Function(s) def calculate_bmi(): weight = float(entry_weight.get()) height = float(entry_height.get()) bmi = round(weight / (height ** 2), 2) label_result['text'] = f"BMI: {bmi}" # Create GUI (Graphical User Interface) label_weight = tkinter.Label(root, text="WEIGHT (KG): ") label_weight.grid(column=0, row=0) entry_weight = tkinter.Entry(root) entry_weight.grid(column=1, row=0) label_height = tkinter.Label(root, text="HEIGHT (M): ") label_height.grid(column=0, row=1) entry_height = tkinter.Entry(root) entry_height.grid(column=1, row=1) button_calculate = tkinter.Button(root, text="Calculate", command=calculate_bmi) button_calculate.grid(column=0, row=2) label_result = tkinter.Label(root, text="BMI: ") label_result.grid(column=1, row=2) root.mainloop()
80d0e021194a67ff06851523210bc9f7ca635833
jimboowens/python-practice
/dictionaries.py
1,131
4.25
4
# this is a thing about dictionaries; they seem very useful for lists and changing values. # Dictionaries are just like lists, but instead of numbered indices they have english indices. # it's like a key greg = [ "Greg", "Male", "Tall", "Developer", ] # This is not intuitive, and the placeholders give no indication as to what they represent # Key:value pair greg = { "name": "Greg", "gender": "Male", "height": "Tall", "job": "Developer", } # make a new dictionary zombie = {}#dictionary zombies = []#list zombie['weapon'] = "fist" zombie['health'] = 100 zombie['speed'] = 10 print zombie # zombie stores the items it comprises in random order. print zombie ['weapon'] for key, value in zombie.items():#key is basically an i, and I don't get how it iterated because both change...? print "zombie has a key of %s with a value of %s" % (key, value) zombies.append({ 'name': "Hank", 'weapon': "baseball bat", 'speed': 10 }) zombies.append({ 'name': "Willy", 'weapon': "axe", 'speed': 3, 'victims': ['squirrel', 'rabbit', 'Hank'] }) print zombies[1]['victims'][1]
8c40ada3b9f1b468f736c221640958379739a187
atakangol/sat-solver
/ex/nqueens-complete-rec.py
4,624
3.859375
4
#!/usr/bin/python ####################################################################### # Copyright 2019 Josep Argelich # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ####################################################################### # Libraries import sys import random # Classes class Interpretation(): """An interpretation is an assignment of the possible values to variables""" def __init__(self, N): """ Initialization N: The problem to solve num_vars: Number of variables to encode the problem vars: List of variables from 0 to num_vars - 1. The value in position [i] of the list is the value that the variable i takes for the current interpretation """ self.num_vars = N self.vars = [None] * self.num_vars def safe_place(self, n, row): """ Detects if a position in the board is a safe place for a queen""" for num_queen in xrange(n + 1, self.num_vars): # Iterate over the columns on the right of num_queen if row == self.vars[num_queen] or abs(n - num_queen) == abs(row - self.vars[num_queen]): # If they are in the same row or they are in the same diagonal return False return True def copy(self): """Copy the values of this instance of the class Interpretation to another instance""" c = Interpretation(self.num_vars) c.vars = list(self.vars) return c def show(self): """Show the solution that represents this interpretation""" print "Solution for %i queens" % (self.num_vars) print self.vars # First line sys.stdout.write("+") for c in xrange(self.num_vars): sys.stdout.write("---+") sys.stdout.write("\n") # Draw board rows for r in xrange(self.num_vars): sys.stdout.write("|") # Draw column position for c in xrange(self.num_vars): if r == self.vars[c]: # If the row == to the value of the variable sys.stdout.write(" X |") else: sys.stdout.write(" |") sys.stdout.write("\n") # Middle lines sys.stdout.write("+") for c in xrange(self.num_vars): sys.stdout.write("---+") sys.stdout.write("\n") class Solver(): """The class Solver implements an algorithm to solve a given problem instance""" def __init__(self, problem): """ Initialization problem: An instance of a problem sol: Solution found """ self.problem = problem self.sol = None def solve(self): """ Implements a recursive algorithm to solve the instance of a problem """ curr_sol = Interpretation(self.problem) # Empty interpretation self.place_nqueens(curr_sol, self.problem - 1) # From column N - 1 to 0 return self.sol def place_nqueens(self, curr_sol, n): """ Recursive call that places one queen each time """ if n < 0: # Base case: all queens are placed self.sol = curr_sol # Save solution return True # Solution found else: # Recursive case for row in xrange(self.problem): # We will try each row in column n if curr_sol.safe_place(n, row): # Is it safe to place queen n at row? # Without undo steps after recursive call new_sol = curr_sol.copy() # Copy solution new_sol.vars[n] = row # Place queen if self.place_nqueens(new_sol, n - 1): # Recursive call for column n - 1 return True # Solution found # With undo steps after recursive call # curr_sol.vars[n] = row # Place queen # if self.place_nqueens(curr_sol, n - 1): # Recursive call for column n - 1 # return True # curr_sol.vars[n] = None # Undo place queen return False # Main if __name__ == '__main__' : """ A basic complete recursive solver for the N queens problem """ # Check parameters if len(sys.argv) != 2: sys.exit("Use: %s <N>" % sys.argv[0]) try: N = int(sys.argv[1]) except: sys.exit("ERROR: Number of queens not an integer (%s)." % sys.argv[1]) if (N < 4): sys.exit("ERROR: Number of queens must be >= 4 (%d)." % N) # Create a solver instance with the problem to solve solver = Solver(N) # Solve the problem and get the best solution found best_sol = solver.solve() # Show the best solution found best_sol.show()
28914773c6065a3d262aa995274281503d42cca4
Finveon/PythonLern
/lesson_2_15.py
478
4.34375
4
#1 print ("1) My name is {}".format("Alexandr")) #2 my_name = "Alexandr" print("2) My name is {}".format(my_name)) #3 print("3) My name is {} and i'm {}".format(my_name, 38)) #4 print("4) My name is {0} and i'm {1}".format(my_name, 38)) #5 print("5) My name is {1} and i'm {0}".format(my_name, 38)) #6 pi = 3.1415 print("6) Pi equals {pi:1.2f}".format(pi=pi)) #7 name = "Alexandr" age = 38 print(f"7) My name is {name} and I'm {age}") #8 print(f"8) Pi equals {pi:1.2f}")
7317cd586606f98c6459206d78b6860c59b05e73
rocketII/project-chiphers-old
/playfair.py
8,436
3.53125
4
def playfair_encrypt(secret, key, junkChar): ''' Encrypt using playfair, enter secret followed by key. Notice we handle only lists foo['h','e','l','p'] English letters only lowercase. :param secret: text string of english letters only, :param key: string of english letters only, thanks. :param junkChar: junkchar fill out betwwen two copies of letters. :return: encrypted text. ''' ciphertxt= [] clearTxt = secret junk = junkChar nyckel = key nyckelLen = len(nyckel) #Create 2D list. Enter key with censored duplicate letters, row by row across columns col1=[None] *5 col2=[None] *5 col3=[None] *5 col4=[None] *5 col5=[None] *5 tmp = [col1,col2,col3,col4,col5] # currently good enough without list copies in main list. row=0 col=0 for read in nyckel: # count(read) make sure no copies are in the column lists. if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0: tmp[col][row]= read col = (col + 1) % 5 if col == 0: row = (row + 1) % 5 #append the rest of the letters in chronologically order english = ['a','b','c','d','e','f','g','h','i','k','l','m','n','o','p','q','r','s','t','u','v','w','x','z','y'] for read in english: if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0: tmp[col][row] = read col = (col + 1) % 5 if col == 0: row = (row + 1) % 5 #print "Table: ",tmp # create bigrams of clear text. no bigram using samme letter allowed insert junk letter 'n' between length = len(clearTxt) previous = None; insertAt = 0 for read in clearTxt: if previous == read: clearTxt.insert(insertAt, junk) insertAt +=1 previous=junk continue previous = read insertAt += 1 length = len(clearTxt) if length % 2 == 1: clearTxt.append(junk) # Find 'i' so that we can replace 'j' with 'i' coordinates rowFor_i = 0; colFor_i = 0 for row in range(5): for col in range(5): if tmp[col][row] == 'i': rowFor_i = row colFor_i = col #print tmp[col][row]," discovered at col: ",col," row: ",row # print "Bigram Source: ",clearTxt # read two letters from cleartext, use 2D list applie rules. Append result in ouput list listlength = len(clearTxt) A = 0; rowFor0 = 0; colFor0 = 0; rowFor1 = 0; colFor1 = 0 temp = ['.','.'] while A < listlength: if (clearTxt[A] == 'j'): temp[0] = 'i' else: temp[0] = clearTxt[A] A += 1 if A < listlength: if (clearTxt[A] == 'j'): temp[1] = 'i' else: temp[1] = clearTxt[A] A += 1 #print "Current bigram: ", temp for row in range(5): for col in range(5): if tmp[col][row] == temp[0]: rowFor0 = row colFor0 = col #print "round:",A,"row: ",row, "col: ", col," char: ", tmp[col][row] elif tmp[col][row] == temp[1]: rowFor1 = row colFor1 = col #print "round:",A,"row: ", row, "col: ", col, " char: ", tmp[col][row] if rowFor0 == rowFor1: #read in order, row/col index 0 goes first ciphertxt.insert(0, tmp[(colFor0 + 1)%5][rowFor0]) ciphertxt.insert(0, tmp[(colFor1 + 1)%5][rowFor1]) #print ' ' elif colFor1 == colFor0: # read in order, row/col index 0 goes first ciphertxt.insert(0, tmp[colFor0][(rowFor0 + 1)%5]) ciphertxt.insert(0, tmp[colFor1][(rowFor1 + 1)%5]) #print ' ' else: if colFor0 > colFor1: # read in order, row/col index 0 goes first colDiff = abs(colFor0 - colFor1) #print "Difference: ", colDiff ciphertxt.insert(0, tmp[(colFor0 - colDiff ) % 5][rowFor0]) #print "Inserted: ",tmp[(colFor0 - colDiff ) % 5][rowFor0] ciphertxt.insert(0, tmp[(colFor1 + colDiff) % 5][rowFor1]) #print "Inserted: ",tmp[(colFor1 + colDiff) % 5][rowFor1] #print ' ' elif colFor0 < colFor1: # read in order, row/col index 0 goes first colDiff = abs(colFor0 - colFor1) #print "Difference: ", colDiff ciphertxt.insert(0, tmp[(colFor0 + colDiff) % 5][rowFor0]) #print "Inserted: ",tmp[(colFor0 + colDiff) % 5][rowFor0] ciphertxt.insert(0, tmp[(colFor1 - colDiff) % 5][rowFor1]) #print "Inserted: ",tmp[(colFor1 - colDiff) % 5][rowFor1] #print ' ' ciphertxt.reverse() return ciphertxt def playfair_decryption(encryptedList, key, junkChar): ''' Playfair changes the order of letters according to rules and sometimes add junk to your secret string. But here we reverse the order. :param encryptedList: list with chars :param key: word based on the english letter system :junkChar: fill out secret in order to create bigrams :return: clear text as list used with print ''' crypto = encryptedList keyWord = key # create 2D list col1 = [None] * 5 col2 = [None] * 5 col3 = [None] * 5 col4 = [None] * 5 col5 = [None] * 5 tmp = [col1, col2, col3, col4, col5] # currently good enough without list copies in main list. row = 0 col = 0 for read in keyWord: if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0: tmp[col][row] = read col = (col + 1) % 5 if col == 0: row = (row + 1) % 5 # append the rest of the letters in chronologically order english = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'z', 'y'] for read in english: if tmp[0].count(read) + tmp[1].count(read) + tmp[2].count(read) + tmp[3].count(read) + tmp[4].count(read) == 0: tmp[col][row] = read col = (col + 1) % 5 if col == 0: row = (row + 1) % 5 # stuff above works ------------------------------------------------------------------------------------------------ # read bigrams and apply reverse order secret = [] listlength = len(crypto) A = 0; rowFor0 = 0; colFor0 = 0; rowFor1 = 0; colFor1 = 0 temp = ['.', '.'] while A < listlength: temp[0] = crypto[A] A += 1 if A < listlength: temp[1] = crypto[A] A += 1 for row in range(5): for col in range(5): if tmp[col][row] == temp[0]: rowFor0 = row colFor0 = col elif tmp[col][row] == temp[1]: rowFor1 = row colFor1 = col if rowFor0 == rowFor1: # read in order, row/col index 0 goeas first secret.insert(0, tmp[(colFor0 - 1) % 5][rowFor0]) secret.insert(0, tmp[(colFor1 - 1) % 5][rowFor1]) elif colFor1 == colFor0: # read in order, row/col index 0 goeas first secret.insert(0, tmp[colFor0][(rowFor0 - 1) % 5]) secret.insert(0, tmp[colFor1][(rowFor1 - 1) % 5]) else: if colFor0 > colFor1: #read in order, row/col index 0 goeas first colDiff = abs(colFor0 - colFor1) secret.insert(0, tmp[(colFor0 - colDiff) % 5][rowFor0]) secret.insert(0, tmp[(colFor1 + colDiff) % 5][rowFor1]) elif colFor0 < colFor1: # read in order, row/col index 0 goes first colDiff = abs(colFor0 - colFor1) secret.insert(0, tmp[(colFor0 + colDiff) % 5][rowFor0]) secret.insert(0, tmp[(colFor1 - colDiff) % 5][rowFor1]) secret.reverse() for junk in range(secret.count(junkChar)): secret.remove(junkChar) return secret
97cdb5c6ec41e4ed4b41c5d2310f8f6c0be1a638
Soldanik/Works
/Операторы/Операторы.py
8,596
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 29 17:37:32 2018 @author: kiril """ #1 задание a = int(input()) b = int(input()) c = int(input()) if a>=1 and b>=1 and c>=1: print(a+b+c) elif a>=1 and b>=1 and c<1: print(a+b) elif a>=1 and b<1 and c>=1: print(a+c) elif a<=1 and b>=1 and c>=1: print(b+c) #2 задание a = int(input()) b = int(input()) c = int(input()) if a==90: print('a') elif b==90: print('b') elif c==90: print('c') #3 задание x = int(input()) y = int(input()) if x>0 and y>0: print('1') if x>0 and y<0: print('4') if x<0 and y>0: print('2') if x<0 and y<0: print('3') #4 задание a = int(input()) b = int(input()) c = int(input()) if a<b<c: print(b) elif a<c<b: print(c) elif c<b<a: print(b) elif b<c<a: print(c) elif b<a<c: print(a) elif c<a<b: print(a) #5 задание m = int(input("Введите число: ")) k = m % 10 if (m > 9)and(m < 20)or(m > 110) and (m < 120) or(k > 4)or(k == 0): print(m, "лет") else: if k == 1: print(m, "год") else: print(m, "года") #6 задание m = int(input("Введите число: ")) k = int(len(str(m))) if (m > 0): print("Число положительное") elif (k == 1): print("Число однозначное") elif (k == 2): print("Число двузначное") elif (k == 3): print("Число трёхзначное") elif (k > 3): print("Число многозначное") if (m<0): print("Число отрицательное") elif (k == 1): print("Число однозначное") elif (k == 2): print("Число двузначное") elif (k == 3): print("Число трёхзначное") elif (k > 3): print("Число многозначное") if (m == 0): print("Ноль") #7 задание m = int(input("Введите возраст: ")) if (m>0) and (m < 18) or(m > 59): print("Вы находитесь в непризывном возрасте") if (m >= 18) and (m <= 27 ): print("Вы подлежите призыву на срочную службу или можете служить по контракту") if (m >= 28) and (m <=59): print("Вы можете служить по контракту") if (m>100) or (m<=0): print("Труп!") #8 задание a = int(input("Число a: ")) b = int(input("Число b: ")) n = int if (a%2 == 1): n = a+b print(n) else: n = a*b print(n) #9 задание print("Оставь надежду всяк сюда входящий") print("Добро пожаловать в ад,смертный! Твоя жизнь была полна везенье,но здесь тебе ничто не поможет!Выбирай от 1 до 100 котел,грешник") a = int(input()) if a>100: print("Ты думал,что я с тобой шутки шутить буду? За не послушание свое ты отправишься в ад программистов,где код никогда не компилируется!") else: print("Послушный мальчик! Пока наслаждаешься ванной,я задам тебе пару вопросов") print("Итак,я предлагаю тебе сделать выбор. Перед тобой 3 предмета,из которых ты можешь взять два себе. Выбирай же!") print("1)Библия") print("2)Гора денег") print("3)Оружие") print("Вводи два числа,которые выбрал. Помни,от выбора зависит исход этой ереси. Можно выбрать только один предмет.") c = int(input("Введите 1й предмет:")) d = int(input("Введите 2й предмет:")) if c==1 and d==0: print("И зачем тебе она? Она мне совсем не страшна!....совсем....наверное...") if c==2 and d==0: print("Хах,будет сделано,смертный. Лови *обрушивает на тебя гору золота*") if c==3 and d==0: print("Хах,и зачем тебе это надо? Ну ладно,держи *дает пистолет*") if c==1 and d==2: print("*обрушивает на тебя гору золота,на которой сверху книга. ") if c==1 and d==3: print("Инквизитор чтоли!?") if c==2 and d==1: print("*обрушивает гору денег на тебя* ") if c==2 and d==3: print("*обрушивает гору денег на тебя,а потом еще и взрывает динамитом*") if c == 3 and d == 1: print("Ты инквизитор,чтоли!?") if c == 3 and d == 2: print("обрушивает гору денег на тебя,а потом еще и взрывает динамитом*") if (c == 1 and d == 1) or (c==2 and d == 2) or (c==3 and d==3): print("Ты опять невнимательно меня слушал!В ад для программистов!") print("*Вдруг вы оказываетесь на камменом троне в величественном замке.*") print("Если бы ты стал королем,то во сколько люди должны были бы служить в армии?! 1) люди старше 20 или 2)младше 18") e = int(input('Число: ')) if e == 1: print("Хм,скучно") else: print("Ахахаха,чертов садист!") print("Смена картины перед глазами и теперь перед тобой старик,что просит подать ему денег на еду. Что ты сделаешь? ") print("1)Дать денег") print("2)Не давать денег") print("3)Забрать деньги у старика") f = int(input()) if f==1: print("Тс,святоша.") elif f==2: print("Не так страшен гнев или доброжелательность. Равнодушие - вот порок души!") elif f==3: print("Хах,тебе самое место среди нас...") else: print("Ошибка!") print("Все плывет перед глазами. Ты сидишь за столом,а в руке у тебя чашка с каким-то напитком. Перед тобой сидит фиолетовый демон,который улыбаясь говорит,что если ты выпьешь содержимое,то весь этот кошмар закончится") print("Что же ты сделаешь? 1) не пить или 2) выпить") x = int(input("Ваш ответ: ")) if x==1: print("Хм,как бы банально это не было,но это верный выбор....") else: print("Как тебе на вкус томатный сок? Ужасно,не правдо ли?") print("Ваш результат:") if (c+d+f+e+x>9): print("Алачный грешник,тебе самое место среди нас! Проходи,не стесняйся, теперь у тебя будет много времени обдумать свои поступки,ахахаха!") if (5<c+d+f+x<8): print("Бело-серый. Цвет равнодушия,один из самых великих пороков людей. Отправляйся в свой мир,смертный. Твой час еще не пришел!") if (0<c+d+f+x<=4): print("Святоша. Отправляйся в свой рай,тебе не место среди нас...") print("The end") #10 задание n = int(input("Введите 3х-значное число")) print("Верно ли, что все цифры в этом числе различные?") a = n%10 b = n//100 c = (n//10)%10 if a!=b and a!=c and b!=c: print("Да") else: print("Нет") #11 задание n = int(input("Введите число")) m = 0 l= n while m==0: if(n%10)>m: m = n%10 n = n //10 if n==0: break print("В числе", l, "самая большая цифра –", m, ".") #12 задание m = int(input("Введите количество секунд: ")) k = m // 3600 f = k%10 if (k > 9)and(k < 20) or (k > 110) and (k < 120) or (f > 4) or (f == 0): print(k, "часов") elif f == 1: print(k, "час") else: print(k, "часа")
3969b5d78347e32ec2693bcd86c284e70bd447c5
teeveeJS/5CL
/weighted_linear_regression.py
1,127
3.515625
4
import numpy as np from scipy.stats import linregress def dy_eq(x, y, dx, dy): slope, _, _, _, _ = linregress(x, y) return np.sqrt(dy*dy + (slope * dx) * (slope * dx)) def weighted_linear_regression(x, y, dx, dy): # x, y, dx, and dy should be np.arrays of the data # equivalent (y) error deq = dy_eq(x, y, dx, dy) # weights w = deq**(-2) # best-fit slope m = (np.sum(w) * np.sum(w * x * y) - np.sum(w * x) * np.sum(w * y)) / (np.sum(w) * np.sum(w * x * x) - (np.sum(w * x))**2) # best-fit intercept b = (np.sum(w * y) - m * np.sum(w * x)) / np.sum(w) # uncertainty in the best-fit slope dm = np.sqrt(np.sum(w) / (np.sum(w) * np.sum(w * x * x) - (np.sum(w * x))**2)) # uncertainty in the best-fit intercept db = np.sqrt(np.sum(w * x * x) / (np.sum(w) * np.sum(w * x * x) - (np.sum(w * x))**2)) # coefficient of determination, r^2 y_pred = m*x + b __r2 = np.sum(w * (y - y_pred)**2) / (np.sum(w * y * y) - (np.sum(w * y))**2) r2 = 1 - __r2 # chi-squared (Q) chi2 = np.sum(((y - y_pred) / dy)**2) return m, dm, b, db, r2, chi2
9d028054ab5cbab00f2414dc9607e83f4bbdbb35
nlin24/python_algorithms
/Palindrome-Checker.py
739
4.03125
4
import Deque ''' Implement a palindrome checking algorithm via deque per https://interactivepython.org/runestone/static/pythonds/BasicDS/PalindromeChecker.html ''' def palindromeChecker(aString): stringDeque = Deque.Deque() for letter in aString: stringDeque.addFront(letter) while stringDeque.size() > 1: last = stringDeque.removeFront() first = stringDeque.removeRear() if first == last: continue else: break if stringDeque.size() > 1: return False else: return True if __name__ == "__main__": print(palindromeChecker("lsdkjfskf")) print(palindromeChecker("radar")) print(palindromeChecker("EvedamnedEdenmadEve".lower()))
735222b563750bceca379969e5cff58224ddf83e
nlin24/python_algorithms
/BinaryTrees.py
1,982
4.375
4
class BinaryTree: """ A simple binary tree node """ def __init__(self,nodeName =""): self.key = nodeName self.rightChild = None self.leftChild = None def insertLeft(self,newNode): """ Insert a left child to the current node object Append the left child of the current node to the new node's left child """ if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): """ Insert a right child to the current node object Append the right child of the current node to the new node's right child """ if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): """ Return the right child of the root node """ return self.rightChild def getLeftChild(self): """ Return the left child of the root node """ return self.leftChild def setRootValue(self,newValue): """ Set the value of the root node """ self.key = newValue def getRootValue(self): """ Return the key value of the root node """ return self.key if __name__ == "__main__": r = BinaryTree('a') print(r.getRootValue()) #a print(r.getLeftChild()) #None r.insertLeft('b') print(r.getLeftChild()) #binary tree object print(r.getLeftChild().getRootValue()) #b r.insertRight('c') print(r.getRightChild()) #binary tree object print(r.getRightChild().getRootValue()) #c r.getRightChild().setRootValue('hello') print(r.getRightChild().getRootValue()) #hello
febe9542a92f8951533b52dc162c390d3e36bd20
ruchawaghulde/Wine-Quality-Prediction
/Codes/VolatilAcidity_pH_Alcohol.py
2,123
3.59375
4
#This program computes the quality equation for the following parameters: #VOLATIL ACIDITY #pH #ALCOHOL import numpy as np import pandas as pd import matplotlib.pyplot as plt # Preprocessing Input data data = pd.read_csv('VolatilAcidity_pH_Alcohol.csv') volatil_acidity= data.iloc[:,0] pH = data.iloc[:, 1] alcohol = data.iloc[:,2] quality = data.iloc[:,3] # Building the model X=0 #Weigh of the FIXED ACIDITY on the quality function Y=0 #Weigh of the PH on the quality function Z=0 #Weigh of the ALCOHOL on the quality function L = 0.0001 # The learning Rate epochs = int(1000) # The number of iterations to perform gradient descent n = len(quality) # Number of elements in X # Performing Gradient Descent for getting the quality equati for i in range(epochs): q_pred = volatil_acidity*X + pH*Y + alcohol*Z # The current predicted value of quality D_volatil_acidity = (-2.0/n)* sum(volatil_acidity * (quality - q_pred)) # Parial derivative weight fixed acidity D_pH = (-2.0/n) * sum(pH*(quality - q_pred)) # Partial derivaitve weight pH D_alcohol = (-2.0/n) * sum(alcohol*(quality-q_pred)) X = X - L * D_volatil_acidity # Update X weight of fixed acidity Y = Y - L * D_pH # Update Y weight of pH Z = Z - L * D_alcohol # Update Z weight of alcohol print("Weight of the fixed volatil parameter: ") print(X) print("Weight of the pH parameter: ") print(Y) print("Weight of the Alcohol parameter: ") print(Z) #List of good wines found in the internet that have actually won awards print("Wine found on the internet that has actually won awards, Duckhorn. Computed quality qith our model: ") q_computed_Duckhorn=0.58*X+3.46*Y+14.9*Z print(q_computed_Duckhorn) print("Wine found on the internet that has actually won awards, Antler Hill. Computed quality qith our model: ") q_computed_Antler_Hill=0.57*X+3.59*Y+15.2*Z print(q_computed_Antler_Hill) print("Wine found on the internet that has actually won awards, Cune. Computed quality qith our model") q_computed_Cune=0.47*X+3.64*Y+13.5*Z print(q_computed_Cune)
5097aaf179964fe280974bdd912368d976e17e42
ericktec/pythonBasics
/Erick/POO/Classes/StudenClass.py
578
3.65625
4
class Subject: def __init__(self, name, score): self.name = name self.score = score class Student: Subjects = [] def __init__(self,name,subjects): self.name = name for key, value in subjects.items(): self.Subjects.append(Subject(key, value)) print(f'{key} added with {value}') def getAverage(self): promedio = 0 for x in range (0,len(self.Subjects)): promedio += int(self.Subjects[x].score) promedio = promedio/len(self.Subjects) print(promedio)
b947d396434da5757847794d37540a33a20d739e
qy-yang/algorithm
/test.py
495
3.734375
4
def insert_intervals(intervals, new_interval): intervals.append(new_interval) intervals.sort(key=lambda x: x[0]) inserted =[] for interval in intervals: if not inserted or inserted[-1][1] < interval[0]: inserted.append(interval) else: inserted[-1][1] = max(interval[1], inserted[-1][1]) return inserted intervals=[[1,2], [3,5], [6, 7], [8, 10], [12, 16]] new = [4,8] print(insert_intervals(intervals, new))
973f3576a93865bbbafa2bb6181f2c4bd4b139f6
Lazzy94/python_base
/lesson_002/04_my_family.py
988
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Создайте списки: # моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что) my_family = ['Мама','Папа','Я'] # список списков приблизителного роста членов вашей семьи my_family_height = [ ['Мама', 178], ['Папа',179], ['Я', 190] ] # Выведите на консоль рост отца в формате # Рост отца - ХХ см # Выведите на консоль общий рост вашей семьи как сумму ростов всех членов # Общий рост моей семьи - ХХ см print('Рост отца -', my_family_height[1][1], 'см') total_height_family = my_family_height[0][1]+my_family_height[1][1]+my_family_height[2][1] print('Общий рост моей семьи', total_height_family, 'см') # зачет!
9b1211b0c7f7089db607421bb2820fd4b30a5d4e
diwadd/sport
/cc_chef_and_dice.py
578
3.53125
4
t = int(input()) for _ in range(t): n = int(input()) stores = n // 4 free_cubes = n % 4 # Each side will have a 5 and a 6 visable # and there will be 4 sides which gives 44 res = stores * 44 if free_cubes == 0: if stores > 0: res += 4*4 elif free_cubes == 1: res += 20 if stores > 0: res += 3*4 elif free_cubes == 2: res += 36 if stores > 0: res += 2*4 elif free_cubes == 3: res += 51 if stores > 0: res += 1*4 print(res)
40a211cebb90da400234e96b5720467e812f8849
diwadd/sport
/cf_fit_to_play.py
655
3.515625
4
t = int(input()) for _ in range(t): n = int(input()) numbers = input().split(" ") numbers = [int(nb) for nb in numbers] max_ele = [0 for _ in range(n)] min_ele = [0 for _ in range(n)] current_max = numbers[n-1] for i in range(n-1, -1, -1): current_max = max(current_max, numbers[i]) max_ele[i] = current_max current_min = numbers[0] for i in range(n): current_min = min(current_min, numbers[i]) min_ele[i] = current_min max_dif = [max_ele[i] - min_ele[i] for i in range(n)] res = max(max_dif) if res == 0: print("UNFIT") else: print(res)
f2cbf76252d98690be310cc410540ef5ed101b33
8Gitbrix/Coding_Problems
/HackerRank/Bot saves princess/BotsavesPrincess.py
786
3.71875
4
#!/usr/bin/python def displayPathtoPrincess(n, grid): pos = [(n-1)/2 , (n-1)/2] #center of grid pr = list(tuple(((x,y) for x in range (0,n) for y in range(0,n) if grid[x][y] == 'p'))[0]) st = [] while pos != pr: if pos[1] == pr[1] and pos[0] < pr[0]: #same row st.append('RIGHT') pos[0] += 1 if pos[1] < pr[1]: st.append('DOWN') pos[1] += 1 if pos[1] == pr[1] and pos[0] > pr[0]: #same row st.append('LEFT') pos[0] -= 1 if pos[1] > pr[1]: st.append('UP') pos[1] -= 1 print('\n'.join(st)) #convert input into a list of lists: m = int(input()) grid = [] for i in range(0, m): grid.append(list(input())) displayPathtoPrincess(m, grid)
293d74ef5c7e2fa8e7a62b47a6844a1d4f35cb86
8Gitbrix/Coding_Problems
/HackerRank/FibonacciModified.py
195
3.765625
4
#Fibonacci Modified def fibModified(a, b, n): if n == 3: return a + b*b return fibModified(b, b*b + a, n-1) a, b, c = (int(x) for x in input().split()) print(fibModified(a,b,c))
ebc79216c2ca7d8b4a988f67c727fdcf1885eaee
lonelyVoxel/network-lab-Voxel
/Network Lab/udp-server.py
708
3.53125
4
#!/usr/bin/env python3 """ udp-server.py - UDP server that listens on UDP port 9000 and prints what is sent to it. Author: Rose/Roxy Lalonde ([email protected]) from template by Andrew Cencini ([email protected]) Date: 3/4/2020 """ import socket # Set our interface to listen on (all of them), which port to receive on, and how many bytes at a time to read. UDP_ADDRESS = "127.0.0.1" UDP_PORT = 9000 # Set up our socket with IPv4 and UDP sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to the given address and port sock.bind((UDP_ADDRESS, UDP_PORT)) while 1: data, addr = sock.recvfrom(1024) print("{0} received: {1}".format(addr[0], data.decode())) sock.sendto(data, addr) # The echo
86887eb80734e2d3d3babad1d77ff18cb0f1a64b
aduV24/python_tasks
/Task 16/Example Error Handling/example_errors_comments.py
506
3.5
4
name = "Tim" surname = " Jones" #Compilation error; incorrect space indentation, needs to be in line with 'name' and 'age' age = 21 fullMessage = name + surname + is + age + " years old" #Runtime error; 'age' needs to be indented with str() # Compilation error; 'is' is under the wrong syntax, needs to be within " " print fullMessage # Logical error; fullMessage does not have appropriate spacing requiring: + " " +
d22dd3d84f34487598c716f13af578c3d2752bc4
aduV24/python_tasks
/Task 19/example.py
1,720
4.53125
5
#************* HELP ***************** #REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LEAVE A #COMMENT FOR YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL. #************************************ # =========== Write Method =========== # You can use the write() method in order to write to a file. # The syntax for this method is as follows: # file.write("string") - writes "string" to the file # ************ Example 1 ************ # Before you can write to a file you need to open it. # You open a file using Python's built-in open() function which creates a file called output.txt (it doesn't exist yet) in write mode. # Python will create this file in the directory/folder that our program is automatically. ofile = open('output.txt', 'w') # We ask the user for their name. When they enter it, it is stored as a String in the variable name. name = input("Enter your name: ") # We use the write method to write the contents of the variable name to the text file, which is represented by the object ofile. # Remember, you will learn more about objects later but for now, think of an object as similar to a real-world object # such as a book, apple or car that can be distinctly identified. ofile.write(name+"\n") # You must run this Python file for the file 'output.txt' to be created with the output from this program in it. ofile.write("My name is on the line above in this text file.") # When we write to the file again, the current contents of the file will not be overwritten. # The new string will be written on the second line of the text file. ofile.close() # Don't forget to close the file! # ****************** END OF EXAMPLE CODE ********************* #
617d9a8532d2ee5546bc031c742faf94bbbb7762
aduV24/python_tasks
/Task 13/example programs/first_while.py
138
3.90625
4
start = 5 while start % 2 != 0: print(start) start = start + 1 #loop will only execute once before condition is no longer true
473237b007ea679c7b55f3c4c7b5895bdf150ae5
aduV24/python_tasks
/Task 11/task2.py
880
4.34375
4
shape = input("Enter the shape of the builing(square,rectangular or round):\n") if shape == "square": length = float(input("Enter the length of one side:\n")) area = round(length**2,2) print(f"The area that will be taken up by the building is {area}sqm") #=================================================================================# elif shape == "rectangle": length = float(input("Enter the length of one side:\n")) width =float(input("Enter the width:\n")) area = round(length*width,2) print(f"The area that will be taken up by the building is {area}sqm") #=================================================================================# elif shape == "round": import math radius = float(input("Enter the radius:\n")) area = round((math.pi)*(radius**2),2) print(f"The area that will be taken up by the building is {area}sqm")
3427a7d78131b4d26b633aa5f70e2dc7a7dab748
aduV24/python_tasks
/Task 17/disappear.py
564
4.78125
5
# This program asks the user to input a string, and characters they wish to # strip, It then displays the string without those characters. string = input("Enter a string:\n") char = input("Enter characters you'd like to make disappear separated by a +\ comma:\n") # Split the characters given into a list and loop through them for x in char.split(","): # Check if character is in string and replace it if x in string: string = string.replace(x, "") else: print(f"'{x}' is not in the string given") print("\n" + string)
fe1c9794518562cdc9b39f3f3b80ed7a9657ed57
aduV24/python_tasks
/Task 20/taskmanager(unedited).py
5,356
3.9375
4
# This python program helps to manage tasks assigned to each member of the team # for a small business. # Request for login details user = input("Enter Username:\n") password = input("Enter password:\n") # Create a login control variable access_gained = False # Validate login details with open('user.txt', 'r+', encoding='utf-8') as user_file: for line in user_file: if (line.strip('\n').split(', ')[0] == user) and (line.strip('\n').split(', ')[1] == password): access_gained = True # Keep asking for valid username and password if wrong while not access_gained: print("\nError, please enter a valid username and/password\n") user = input("Enter Username:\n") password = input("Enter password:\n") with open('user.txt', 'r+', encoding='utf-8') as user_file: for line in user_file: if (line.strip('\n').split(', ')[0] == user) and (line.strip('\n').split(', ')[1] == password): access_gained = True # Allow access if username and password is correct if access_gained: print("\nPlease select one of the following options:") print("r - register user \na - add task \nva - view all tasks \nvm - view my tasks \ne - exit") choice = input() # REGISTER NEW USER if choice == 'r': new_user = input("Enter username you wish to register:\n") new_password = input("Enter password you wish to register:\n") confirm_password = input("Please confirm password:\n") # Check that the passwords match while confirm_password != new_password: print("Passwords do not match, please try again. Please confirm password") confirm_password = input("Please confirm password:\n") if new_password == confirm_password: user_file = open('user.txt', 'a', encoding='utf-8') user_file.write('\n' + new_user + ', ' + new_password) user_file.close() print(f"You have registered {new_user} as a user.") # ADD A NEW TASK elif choice == 'a': # Learnt how to use the 'date' class, module and object here # https://www.programiz.com/python-programming/datetime/current-datetime from datetime import date name = input('Enter the name of person task is assigned to:\n') title = input("Enter the title of the task:\n") description = input("Enter the description of the task:\n") due_date = input("Enter the due date of the task: \n") today_date = date.today() # Convert date object to a string t_date = today_date.strftime("%d %b %Y") completed = 'No' # append task data to a list, convert the list to a string and save to the tasks.txt file tasks = [name, title, description, t_date, due_date, completed] with open('tasks.txt', 'a', encoding='utf-8') as task_file: task_file.writelines('\n'+", ".join(tasks)) print("done") # VIEW ALL TASKS elif choice == 'va': # Create a list of outputs output = ['Assigned to:', 'Task:', 'Task Description:', 'Date assigned:', 'Due date:', 'Task complete?'] with open('tasks.txt', 'r', encoding='utf-8') as task_file: for line in task_file: print("----------------------------------------------------------------------------------------") for cat in output: # Get the index of the output in the list and match it with the data in the task file # Learnt how to use the index method here: https://www.w3schools.com/python/ref_list_index.asp index = output.index(cat) data = line.split(', ')[index] # Learnt how to use the "ljust" method here: # https://www.programiz.com/python-programming/methods/string/ljust # The "ljust" method returns the left-justified string within the given minimum width print(f"{cat.ljust(30)} {data}") # VIEW ALL MY TASKS elif choice == 'vm': # Create a boolean variable user_found = False with open('tasks.txt', 'r', encoding='utf-8') as task_file: for line in task_file: # if the user has been assigned tasks, display such tasks if user in line.split(','): user_found = True output = ['Assigned to:', 'Task:', 'Task Description:', 'Date assigned:', 'Due date:', 'Task complete?'] print("-------------------------------------------------------------------------------------") for cat in output: index = output.index(cat) data = line.split(', ')[index] print(f"{cat.ljust(30)} {data}") # Display a message if the user has not been assigned any tasks if not user_found: print("\nOOps, you have not been assigned any tasks.") # EXIT PROGRAM elif choice == 'e': # Learnt how to use the sys module to exit a program here # https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/ import sys sys.exit("\nExiting.............\nThank you for using the task manager")
55d2392b17d505045d5d80d209dc5635c47657f6
aduV24/python_tasks
/Task 17/separation.py
298
4.4375
4
# This program asks the user for a sentence and then displays # each character of that senetence on a new line string = input("Enter a sentence:\n") # split string into a list of words words = string.split(" ") # Iterate thorugh the string and print each word for word in words: print(word)
28488c65d5d977cb9b48772d64be224bdce8d0bf
aduV24/python_tasks
/Task 11/task1.py
702
4.25
4
num1 =60 num2 = 111 num3 = 100 if num1 > num2: print(num1) else: print(num2) print() if num1 % 2 == 0: print("The first number is even") else: print("The first number is odd") print() print("Numbers in descending order") print("===================================") if (num1 > num2) and (num1 > num3 ): if num2 > num3: print(f"{num1}\n{num2}\n{num3}") else: print(f"{num1}\n{num3}\n{num2}") elif (num2 > num1) and (num2 > num3 ): if num1 > num3: print(f"{num2}\n{num1}\n{num3}") else: print(f"{num2}\n{num3}\n{num1}") else: if num1 > num2: print(f"{num3}\n{num1}\n{num2}") else: print(f"{num3}\n{num2}\n{num1}")
40df8c8aa7efb4fc8707f712b94971bae08dacea
aduV24/python_tasks
/Task 21/john.py
344
4.34375
4
# This program continues to ask the user to enter a name until they enter "John" # The program then displays all the incorrect names that was put in wrong_inputs = [] name = input("Please input a name:\n") while name != "John": wrong_inputs.append(name) name = input("Please input a name:\n") print(f"Incorrect names:{wrong_inputs}")
aa382979b4f5bc4a8b7e461725f59a802ffe3a4e
aduV24/python_tasks
/Task 14/task1.py
340
4.59375
5
# This python program asks the user to input a number and then displays the # times table for that number using a for loop num = int(input("Please Enter a number: ")) print(f"The {num} times table is:") # Initialise a loop and print out a times table pattern using the variable for x in range(1,13): print(f"{num} x {x} = {num * x}")
ab8491166133deadd98d2bbbbb40775f95c7091b
aduV24/python_tasks
/Task 24/Example Programs/code_word.py
876
4.28125
4
# Imagine we have a long list of codewords and each codeword triggers a specific function to be called. # For example, we have the codewords 'go' which when seen calls the function handleGo, and another codeword 'ok' which when seen calls the function handleOk. # We can use a dictionary to encode this. def handleGo(x): return "Handling a go! " + x def handleOk(x): return "Handling an ok!" + x # This is dictionary: codewords = { 'go': handleGo, # The KEY here is 'go' and the VALUE it maps to is handleGo (Which is a function!). 'ok': handleOk, } # This dictionary pairs STRINGS (codewords) to FUNCTIONS. # Now, we see a codeword given to us: codeword = "go" # We can handle it as follows: if codeword in codewords: answer = codewords[codeword]("Argument") print(answer) else: print("I don't know that codeword.")
f090a5013ea570e1764cfe47652172d73a6f20bb
Akoopie/Simple-Banking-System
/banking.py
6,142
3.65625
4
import random import sys import sqlite3 registry = {} class Card: def __init__(self, card_number, pin): self.card_number = card_number self.pin = pin self.balance = 0 def main_menu(): print('1. Create an account', '2. Log into account', '0. Exit', sep='\n') option = int(input()) while option > 2 or option < 0: print('Invalid entry!') option = int(input()) else: if option == 0: exit_bank() if option == 1: createaccount() if option == 2: login() def account_menu(card_number): print('1. Balance', '2. Add income', '3. Do transfer', '4. Close account', '5. Log out', '0. Exit', sep='\n') option = int(input()) while option > 5 or option < 0: print('Invalid entry!') option = int(input()) else: if option == 0: exit_bank() if option == 1: balance(card_number) if option == 2: add_income(card_number) if option == 3: transfer(card_number) if option == 4: close_account(registry[card_number]) if option == 5: logout() def add_income(card_number): balance = int(input('Enter income:')) #print(registry[card_number].balance) registry[card_number].balance += balance #print(registry[card_number].balance) update_database(registry[card_number]) print('Income was added!') account_menu(card_number) def transfer(card_number): print('Transfer') acct = input('Enter card number:') acct_luhn = str(acct)[:-1] #print(acct_luhn) #print(luhn(acct_luhn)) for x in registry.keys(): if acct_luhn == x[:-1]: if acct[-1] != luhn(acct_luhn): print('Probably you made a mistake in the card number. Please try again!') account_menu(card_number) else: break else: continue if acct == card_number: print("You can't transfer money to the same account!") account_menu(card_number) elif acct[-1] != luhn(acct_luhn): print('Probably you made a mistake in the card number. Please try again!') account_menu(card_number) elif acct in registry: amount = int(input('Enter how much money you want to transfer:')) if registry[card_number].balance < amount: print('Not enough money!') account_menu(card_number) else: registry[card_number].balance -= amount registry[acct].balance += amount update_database(registry[card_number]) update_database(registry[acct]) print('Success!') account_menu(card_number) else: print('Such a card does not exist.') account_menu(card_number) def close_account(card): conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("DELETE FROM card WHERE number="+str(card.card_number)) conn.commit() conn.close() main_menu() def logout(): print('You have successfully logged out!') main_menu() def balance(card_number): print('Balance:', str(registry[card_number].balance)) account_menu(card_number) def login(): card_number = input('Enter your card number:') pin = input('Enter your PIN:') if card_number in registry and registry[card_number].pin == pin: print('You have successfully logged in!') account_menu(card_number) else: print('Wrong card number or PIN!') main_menu() def createaccount(): account_number_precursor = '400000' + str(random.randint(0, 99999999)).zfill(9) pin_number = str(random.randint(0, 9999)).zfill(4) account_number = account_number_precursor + luhn(account_number_precursor) #print(len(account_number)) card = Card(account_number, pin_number) register(card) insert_database(card) print('Your card has been created', 'Your card number:', account_number, 'Your card PIN:', pin_number, sep='\n') main_menu() def luhn(account_number_precursor): luhn1 = [int(x) for x in account_number_precursor] luhn2 = [] luhn3 = [] for x, y in enumerate(luhn1): if x % 2 == 0: y *= 2 luhn2.append(y) else: luhn2.append(y) for x in luhn2: if x > 9: x -= 9 luhn3.append(x) else: luhn3.append(x) luhn_total = sum(luhn3) #print(luhn_total) if luhn_total > 99: luhn_total -= 100 check_sum = str(10 - luhn_total % 10) if luhn_total % 10 == 0: check_sum = str(0) #print(check_sum) return check_sum def register(card): registry[card.card_number] = card def exit_bank(): print('Bye!') sys.exit() def create_table(): conn = sqlite3.connect('card.s3db') cur = conn.cursor() #cur.execute('DROP TABLE card') cur.execute("CREATE TABLE card(id INTEGER, number TEXT, pin TEXT, balance INTEGER DEFAULT 0)") conn.commit() conn.close() def destroy_database(): conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute('DROP TABLE card') conn.close() def insert_database(card): conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("INSERT INTO card (number, pin) VALUES (?,?)", (card.card_number, card.pin)) conn.commit() conn.close() def update_database(card): conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("UPDATE card SET balance = "+str(card.balance)+" WHERE number = "+str(card.card_number)) conn.commit() conn.close() def debug_update_database(num, fum): conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("INSERT INTO card (number, pin) VALUES (?,?)", (num, fum)) conn.commit() conn.close() def query_database(): conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute("SELECT * FROM card") print(cur.fetchall()) conn.close() destroy_database() create_table() main_menu() #query_database()
92b15ecff2e834f59dec4ac8ea333621a2924255
jagritiS/pythonProgramming
/database.py
969
3.71875
4
import mysql.connector #mydb is the database connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="Sunway" ) print(mydb) mycursor = mydb.cursor() #check if the table exists and if not then create a table mycursor.execute("SHOW TABLES LIKE 'students'") result = mycursor.fetchone() if result: print("Table exists") else: mycursor.execute("CREATE TABLE students (name VARCHAR(255), address VARCHAR(255))") #insert data into the table sql = "INSERT INTO students (name, address) VALUES (%s, %s)" val = ("Jagriti", "Kathmandu") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") #read data from the table mycursor.execute("SELECT * FROM students") myresult = mycursor.fetchall() for x in myresult: print(x) #delete data from the table sql = "DELETE FROM students WHERE address = 'lalitpur'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted")
8649803360db4c5443510b5485f7885700c823f2
prateekrastogi92/python-basic-scripts
/sum.py
140
4.0625
4
x=int(input("enter first number")) y=int(input("enter second number")) sum_of_numbers = x+y print("the sum is: {}" .format(sum_of_numbers))
ee04a317415c9a0c9481f712e8219c92fb719ce0
hackettccp/CIS106
/SourceCode/Module2/formatting_numbers.py
1,640
4.65625
5
""" Demonstrates how numbers can be displayed with formatting. The format function always returns a string-type, regardless of if the value to be formatted is a float or int. """ #Example 1 - Formatting floats amount_due = 15000.0 monthly_payment = amount_due / 12 print("The monthly payment is $", monthly_payment) #Formatted to two decimal places print("The monthly payment is $", format(monthly_payment, ".2f")) #Formatted to two decimal places and includes commas print("The monthly payment is $", format(monthly_payment, ",.2f")) print("The monthly payment is $", format(monthly_payment, ',.2f'), sep="") #********************************# print() #Example 2 - Formatting ints """ weekly_pay = 1300 annual_salary = weekly_pay * 52 print("The annual salary is $", annual_salary) print("The annual salary is $", format(annual_salary, ",d")) print("The annual salary is $", format(annual_salary, ",d"), sep="") """ #********************************# print() #Example 3 - Scientific Notation """ distance = 567.465234 print("The distance is", distance) print("The distance is", format(distance, ".5e")) """ #********************************# print() #Example 4 - Formatting floats # This example displays the following # floating-point numbers in a column # with their decimal points aligned. """ num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 num5 = 88.081 num6 = 799.999 # Display each number in a field of 7 spaces # with 2 decimal places. print(format(num1, '7.2f')) print(format(num2, '7.2f')) print(format(num3, '7.2f')) print(format(num4, '7.2f')) print(format(num5, '7.2f')) print(format(num6, '7.2f')) """
3d2c8b1c05332e245a7d3965762b2a746d6e5c3d
hackettccp/CIS106
/SourceCode/Module4/loopandahalf.py
899
4.21875
4
""" Demonstrates a Loop and a Half """ #Creates an infinite while loop while True : #Declares a variable named entry and prompts the user to #enter the value z. Assigns the user's input to the entry variable. entry = input("Enter the value z: ") #If the value of the entry variable is "z", break from the loop if entry == "z" : break #Prints the text "Thank you!" print("Thank you!") #********************************# print() """ #Creates an infinite while loop while True: #Declares a variable named userNum and prompt the user #to enter a number between 1 and 10. #Assigns the user's input to the user_number variable. user_number = int(input("Enter a number between 1 and 10: ")) #If the value of the userNumber variable is correct, break from the loop if user_number >= 1 and user_number <= 10 : break #Prints the text "Thank you!" print("Thank you!") """
824f4f86eaef9c87c082c0f471cb7a68cc72a44f
hackettccp/CIS106
/SourceCode/Module2/converting_floats_and_ints.py
1,055
4.71875
5
""" Demonstrates converting ints and floats. Uncomment the other section to demonstrate the conversion of float data to int data. """ #Example 1 - Converting int data to float data #Declares a variable named int_value1 and assigns it the value 35 int_value1 = 35 #Declares a variable named float_value1 and assigns it #int_value1 returned as a float float_value1 = float(int_value1) #Prints the value of int_value1. The float function did not change #the variable, its value, or its type. print(int_value1) #Prints the value of float_value1. print(float_value1) #********************************# print() #Example 2 - Converting float data to int data """ #Declares a variable named float_value2 and assigns it the value 23.8 float_value2 = 23.8 #Declares a variable named int_value2 and assigns it #float_value2 returned as an int int_value2 = int(float_value2) #Prints the value of float_value2. The int function did not change #the variable, its value, or its type. print(float_value2) #Prints the value of int_value2 print(int_value2) """
98868a37e12fc16d5a1e0d49cb8e076a5ffb107d
hackettccp/CIS106
/SourceCode/Module10/button_demo.py
866
4.15625
4
#Imports the tkinter module import tkinter #Imports the tkinter.messagebox module import tkinter.messagebox #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's title test_window.wm_title("My Window") #Creates button that belongs to test_window that #calls the showdialog function when clicked. test_button = tkinter.Button(test_window, text="Click Me!", command=showdialog) #Packs the button onto the window test_button.pack() #Enters the main loop, displaying the window #and waiting for events tkinter.mainloop() #Function that displays a dialog box when it is called. def showdialog() : tkinter.messagebox.showinfo("Great Job!", "You pressed the button.") #Calls the main function/starts the program main()
b8b69427b405066c56fa51d01f38c678274ddd7b
hackettccp/CIS106
/SourceCode/Module13/PartA/tire.py
741
3.875
4
""" Tire Object. """ #Class Header class Tire() : #Initializer def __init__(self, pressure_in, radius_in) : self.pressure = pressure_in self.radius = radius_in #Retrieves the pressure field def getpressure(self) : return self.pressure #Changes the pressure field def setpressure(self, pressure_in) : if isinstance(pressure_in, int) : if pressure_in >= 0 and pressure_in <= 60 : self.pressure = pressure_in else : raise ValueError("Invalid Tire Pressure") else : raise TypeError("Invalid Data Type") #Retrieves the radius field def getradius(self) : return self.radius #Changes the radius field def setradius(self, radius_in) : self.radius = radius_in
c06408e3f4d950798bf62219205f5c8c70c787a2
hackettccp/CIS106
/SourceCode/Module5/parameters2.py
405
4
4
""" Demonstrates what happens when you change the value of a parameter. """ def main(): value = 99 print("The value is", value) changeme(value) print("Back in main the value is", value) def changeme(arg): print("I am changing the value.") arg = 0 #Does not affect the value variable back in the main function. print("Now the value is", arg) #Calls the main function. main()
1af15c312f75e507b4acb77abc76b25ff8022318
hackettccp/CIS106
/SourceCode/Module5/returning_data1.py
815
4.15625
4
""" Demonstrates returning values from functions """ def main() : #Prompts the user to enter a number. Assigns the user's #input (as an int) to a variable named num1 num1 = int(input("Enter a number: ")) #Prompts the user to enter another number. Assigns the user's #input (as an int) to a variable named num2 num2 = int(input("Enter another number: ")) #Passes the num1 and num2 variables as arguments to the printsum #function. Assign the value returned to a variable called total total = printsum(num1, num2) #Prints the value of total print("The total is", total) #A function called printsum that accepts two arguments. #The function adds the arguments together and returns the result. def printsum(x, y) : #Returns the sum of x and y return x + y #Calls main function main()
c359aae7e1cd194eedb023b580f34e42b7663c27
hackettccp/CIS106
/SourceCode/Module2/mixed_number_operations.py
1,699
4.46875
4
""" Demonstrates arithmetic with mixed ints and floats. Uncomment each section to demonstrate different mixed number operations. """ #Example 1 - Adding ints together. #Declares a variable named value1 and assigns it the value 10 value1 = 10 #Declares a variable named value2 and assigns it the value 20 value2 = 20 #Declares a variable named total1 #Assigns the sum of value1 and value2 to total1 #total1's data type will be int total1 = value1 + value2 #Prints the value of total1 print(total1) #********************************# print() #Example 2 - Adding a float and int together """ #Declares a variable named value3 and assigns it the value 90.5 value3 = 90.5 #Declares a variable named value4 and assigns it the value 40 value4 = 20 #Declares a variable named total2 #Assigns the sum of value3 and value3 to total2 #total2's data type will be float total2 = value3 + value4 #Prints the value of total2 print(total2) """ #********************************# print() #Example 3 - Adding floats together """ #Declares a variable named value5 and assigns it the value 15.6 value5 = 15.6 #Declares a variable named value6 and assigns it the value 7.5 value6 = 7.5 #Declares a variable named total3 #Assigns the sum of value5 and value6 to total3 #total3's data type will be float total3 = value5 + value6 #Prints the value of total3 print(total3) """ #********************************# print() #Example 4 - Multiple operands """ #Declares a variable named result #Assigns the sum of total1, total2, and total3 to result #result's data type will be float (int + float + float = float) result = total1 + total2 + total3 #Prints the value of result print(result) """
188486bfabc4f36413579d6d1af0aaae3da63681
hackettccp/CIS106
/SourceCode/Module10/entry_demo.py
504
4.125
4
#Imports the tkinter module import tkinter #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's title test_window.wm_title("My Window") #Creates an entry field that belongs to test_window test_entry = tkinter.Entry(test_window, width=10) #Packs the entry field onto the window test_entry.pack() #Enters the main loop, displaying the window #and waiting for events tkinter.mainloop() #Calls the main function/starts the program main()
2a4a94e8b6c246060f69cae069a9024055e8315b
jackbryan1/Biology-Analysis-Project
/uniplot/analysis.py
1,020
3.59375
4
def average_len(records): """Returns the average len for records""" RecordLength = [len(i) for i in records] return sum(RecordLength) / len(RecordLength) def average_len_taxa(records, depth): """Returns the average length for the top level taxa""" if depth is None: depth = int(0) record_by_taxa = {} for r in records: try: taxa = r.annotations["taxonomy"][depth] except: print() record_by_taxa.setdefault(taxa, []).append(r) return {taxa:average_len(record) for (taxa, record) in record_by_taxa.items()} def len_taxa(records, depth): """Returns the average length for the top level taxa""" if depth is None: depth = int(0) record_by_taxa = {} for r in records: try: taxa = r.annotations["taxonomy"][depth] except: print() record_by_taxa.setdefault(taxa, []).append(r) return {taxa:len(record) for (taxa, record) in record_by_taxa.items()}
a81aa6362cb19f60ecac87f27c25cc55c81f7c4f
edu-sense-com/OSE-Python-Course
/SP/Modul_06/cyfry_skrypt.py
568
4.03125
4
print("Hi, i will check all singns in value.") some_value = input("Please enter value (as integer):") signs_list = [] for one_sign in some_value: signs_list.append(one_sign) print(f"Total list is: {signs_list}") # dla chętnych for one_sign in some_value: print(f"{one_sign} => {int(one_sign) * '@'}") # efekt przykładowego działania # Hi, i will check all singns in value. # Please enter value (as integer):6248531 # Total list is: ['6', '2', '4', '8', '5', '3', '1'] # 6 => @@@@@@ # 2 => @@ # 4 => @@@@ # 8 => @@@@@@@@ # 5 => @@@@@ # 3 => @@@ # 1 => @
b4c3e22d4917bcc9adec48ca952cb2298a5b9a39
edu-sense-com/OSE-Python-Course
/SP/Modul_03/input_02.py
235
3.5
4
# przykładowy skrypt do wykonywania w trybie skyptowym python_version = 3.8 print("Hi, I want to say hello to you!") name = input("Please, give me your name:") print(f"Welcome {name}, my name is Python (version {python_version}).")
ee0d1300143d4fb921359f2509ac695d9170efa1
wllmcdl/hackerrank
/singleSellProfit.gyp
797
4.03125
4
def DynamicProgrammingSingleSellProfit(arr): # If the array is empty, we cannot make a profit. if len(arr) == 0: return 0 # Otherwise, keep track of the best possible profit and the lowest value # seen so far. profit = 0 cheapest = arr[0] # Iterate across the array, updating our answer as we go according to the # above pseudocode. for i in range(1, len(arr)): # Update the minimum value to be the lower of the existing minimum and # the new minimum. cheapest = min(cheapest, arr[i]) # Update the maximum profit to be the larger of the old profit and the # profit made by buying at the lowest value and selling at the current # price. profit = max(profit, arr[i] - cheapest) return profit
ec69ab4430000ffac0816510691002ebe97eada7
vijayroykargwal/Infy-FP
/Python by Educator/Demos-Day1/Demos/demos/3-LinkedList.py
2,829
4.0625
4
class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return self.__next def set_next(self,next_node): self.__next=next_node class LinkedList: def __init__(self): self.__head=None self.__tail=None def get_head(self): return self.__head def get_tail(self): return self.__tail def add(self,data): new_node=Node(data) if(self.__head is None): self.__head=self.__tail=new_node else: self.__tail.set_next(new_node) self.__tail=new_node #Remove pass and write the logic to add an element def display(self): temp=self.__head while(temp is not None): print(temp.get_data()) temp=temp.get_next() #Remove pass and write the logic to display the elements # def find_node(self,data): Day2 # temp=self.__head # while(temp is not None): # if(temp.get_data() == data): # print("Data found") # temp=temp.get_next() def insert(self,data,data_before): new_node=Node(data) counter=0 if(data_before is None): counter=1 self.__head=new_node new_node.set_next(temp) if(temp.get_next() is None): self.__tail=new_node else: temp=self.__head while(temp is not None): if(temp.get_data() == data_before): counter=1 new_node.set_next(temp.get_next()) temp.set_next(new_node) if(new_node.get_next() is None): self.__tail=new_node temp=temp.get_next() if(counter==0): print("No matching node found") else: print(list1) #You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): temp=self.__head msg=[] while(temp is not None): msg.append(str(temp.get_data())) temp=temp.get_next() msg=" ".join(msg) msg="Linkedlist data(Head to Tail): "+ msg return msg list1=LinkedList() list1.add("Sugar") list1.add("Salt") list1.add("Pepper") print("Elements in the list:") list1.display() list1.insert("Red_Chilli", "Salt") # list1.find_node("Pepper")
e6ae4cc9d5c1cdb482b8cd6a836db552a02d93e7
vijayroykargwal/Infy-FP
/MAIN_DSA/Day3/src/Excer7.py
2,879
3.75
4
#DSA-Exer-7 class Stack: def __init__(self,max_size): self.__max_size=max_size self.__elements=[None]*self.__max_size self.__top=-1 def is_full(self): if(self.__top==self.__max_size-1): return True return False def is_empty(self): if(self.__top==-1): return True return False def push(self,data): if(self.is_full()): print("The stack is full!!") else: self.__top+=1 self.__elements[self.__top]=data def pop(self): if(self.is_empty()): print("The stack is empty!!") else: data= self.__elements[self.__top] self.__top-=1 return data def display(self): if(self.is_empty()): print("The stack is empty") else: index=self.__top while(index>=0): print(self.__elements[index]) index-=1 def get_max_size(self): return self.__max_size def __str__(self): msg=[] index=self.__top while(index>=0): msg.append((str)(self.__elements[index])) index-=1 msg=" ".join(msg) msg="Stack data(Top to Bottom): "+msg return msg class Ball: def __init__(self,manufacturer,color): self.__color=color self.__manufacturer=manufacturer def __str__(self): return(self.__color+" "+self.__manufacturer) def get_color(self): return self.__color def get_manufacturer(self): return self.__manufacturer class Box: def __init__(self,ball_stack): self.ball_stack=ball_stack self.manufacturer1_stack=Stack(2) self.manufacturer2_stack=Stack(2) def group_balls(self): for i in range(0,self.ball_stack.get_max_size()): a=self.ball_stack.pop() if(a.get_manufacturer()=="Penn"): self.manufacturer1_stack.push(a) elif(a.get_manufacturer()=="Wilson"): self.manufacturer2_stack.push(a) def display_ball_details(self,manufacturer): if(manufacturer=="Penn"): return self.manufacturer1_stack.__str__() elif(manufacturer=="Wilson"): return self.manufacturer2_stack.__str__() ball1=Ball("Penn","Yellow") ball2=Ball("Wilson","White") ball3=Ball("Penn","Red") ball4=Ball("Wilson","Yellow") ball_stack=Stack(4) ball_stack.push(ball1) ball_stack.push(ball2) ball_stack.push(ball3) ball_stack.push(ball4) box=Box(ball_stack) box.group_balls() box.display_ball_details("Penn")
07446c60f900a859c67cb9235eb3163ddc74f1b4
vijayroykargwal/Infy-FP
/PF/Day2/src/Assignment17.py
600
3.796875
4
#PF-Assgn-17 ''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def find_new_salary(current_salary,job_level): # write your logic here if(job_level==3): new_salary = 0.15*current_salary + current_salary elif(job_level==4): new_salary = 0.07*current_salary + current_salary elif(job_level==5): new_salary = 0.05*current_salary + current_salary else: new_salary = 0 return new_salary # provide different values for current_salary and job_level and test yor program new_salary=find_new_salary(15000,3) print(new_salary)
9022c29ad620cc63dcdbb962114722f8715cf47c
vijayroykargwal/Infy-FP
/DSA/Day2/src/Excer.py
1,348
3.828125
4
''' Created on Mar 14, 2019 @author: vijay.pal01 ''' class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return self.__next def set_next(self,next_node): self.__next=next_node class LinkedList: def __init__(self): self.__head=None self.__tail=None def get_head(self): return self.__head def get_tail(self): return self.__tail def add(self,data): new_node=Node(data) if(self.__head is None): self.__head=self.__tail=new_node else: self.__tail.set_next(new_node) self.__tail=new_node def fun(prv,nxt,data): if(nxt==None): return if(nxt.get_data()==data): global sample sample.add(data) prv.set_next(nxt.get_next()) return else: fun(nxt,nxt.get_next(),data) sample=LinkedList() sample.add(10) sample.add(20) sample.add(5) sample.add(55) sample.add(38) sample_head=sample.get_head() fun(sample_head, sample_head,5) print(sample_head.get_next().get_next().get_next().get_next().get_next().get_data())
6734a88448568bb6ea98ba902eb36c68044684e7
vijayroykargwal/Infy-FP
/PF/Day9/src/Assign38.py
483
3.65625
4
''' Created on Mar 21, 2019 @author: vijay.pal01 ''' def build_index_grid(rows, columns): result_list = [] for i in range(rows): list1 = [] for j in range(columns): list1.append(str(i)+","+str(j)) result_list.append(list1) return result_list rows=4 columns=3 result=build_index_grid(rows,columns) print("Rows:",rows,"Columns:",columns) print("The matrix is:",result) for i in result: print(i)
c1a54f0539877ae5cb9385fccebb74497748e887
vijayroykargwal/Infy-FP
/MAIN_DSA/Day6/src/Assign24.py
705
3.75
4
#DSA-Assgn-24 ''' Created on Mar 20, 2019 @author: vijay.pal01 ''' def count_decoding(digit_list): #Remove pass and write your logic here n=len(digit_list) count = [0]*(n+1) count[0]=1 count[1]=1 for i in range(2, n+1): count[i] = 0 if(digit_list[i-1] > 0): count[i] = count[i-1] if(digit_list[i-2] == 1 or (digit_list[i-2] == 2 and digit_list[i-1]<7)): count[i] += count[i-2] return count[n] #Pass different values to the function and test your program digit_list=[9,8,1,5] print("Number of possible decodings for the given sequence is:", count_decoding(digit_list))
b94a306012d1af7bb6ab9b83c0ce143d3e0758d6
vijayroykargwal/Infy-FP
/PF/Day2/src/Assignment16.py
1,016
3.953125
4
#PF-Assgn-16 ''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def make_amount(rupees_to_make,no_of_five,no_of_one): five_needed=rupees_to_make//5 one_needed=rupees_to_make%5 if(five_needed<=no_of_five and one_needed<=no_of_one): print("No. of Five needed :", five_needed) print("No. of One needed :", one_needed) elif(five_needed>no_of_five): error=5*(five_needed-no_of_five) if(error<=no_of_one): print("No. of Five needed :", no_of_five) print("No. of One needed :", one_needed+error) else: print(-1) else: print(-1) #Start writing your code here #Populate the variables: five_needed and one_needed # Use the below given print statements to display the output # Also, do not modify them for verification to work #print("No. of Five needed :", five_needed) #print("No. of One needed :", one_needed) #print(-1) make_amount(28,8,5)
a68af395a6d75c41ef6858a9dcb7fb3a0a36e31e
vijayroykargwal/Infy-FP
/OOPs/Day5/src/Assign30.py
3,622
3.921875
4
#OOPR-Assgn-30 ''' Created on Mar 12, 2019 @author: vijay.pal01 ''' #Start writing your code here class Customer: def __init__(self,customer_name,quantity): self.__customer_name=customer_name self.__quantity=quantity def validate_quantity(self): if(self.__quantity in range (1,6)): return True return False def get_customer_name(self): return self.__customer_name def get_quantity(self): return self.__quantity class Pizzaservice: counter = 100 def __init__(self,customer,pizza_type,additional_topping): self.__service_id =None self.__customer = customer self.__pizza_type = pizza_type self.__additional_topping = additional_topping self.pizza_cost = None def validate_pizza_type(self): if(self.get_pizza_type().lower() in ["small","medium"]): return True return False def calculate_pizza_cost(self): if(self.validate_pizza_type() and self.__customer.validate_quantity()): if(self.__pizza_type.lower() == "small"): if(self.__additional_topping): price = self.__customer.get_quantity()*(150+35) else: price = self.__customer.get_quantity()*(150) Pizzaservice.counter+=1 self.__service_id = (self.get_pizza_type()[0]+ str(Pizzaservice.counter)) elif(self.__pizza_type.lower() == "medium"): if(self.__additional_topping): price = self.__customer.get_quantity()*(200+50) else: price = self.__customer.get_quantity()*(200) Pizzaservice.counter+=1 self.__service_id = (self.get_pizza_type()[0]+ str(Pizzaservice.counter)) self.pizza_cost = price else: self.pizza_cost = -1 def get_service_id(self): return self.__service_id def get_customer(self): return self.__customer def get_pizza_type(self): return self.__pizza_type def get_additional_topping(self): return self.__additional_topping class Doordelivery(Pizzaservice): def __init__(self,customer,pizza_type,additional_topping,distance_in_kms): super().__init__(customer, pizza_type, additional_topping) self.__delivery_charge = None self.__distance_in_kms = distance_in_kms def validate_distance_in_kms(self): if(self.get_distance_in_kms() in range(1,11)): return True return False def calculate_pizza_cost(self): if(self.validate_distance_in_kms()): super().calculate_pizza_cost() if(self.pizza_cost != -1): if(self.get_distance_in_kms() <=5): self.__delivery_charge = self.get_distance_in_kms()*5 elif(self.get_distance_in_kms() >5): self.__delivery_charge =(((self.get_distance_in_kms()-5)*7) +25) self.pizza_cost += self.get_delivery_charge() else: self.pizza_cost = -1 def get_delivery_charge(self): return self.__delivery_charge def get_distance_in_kms(self): return self.__distance_in_kms c1=Customer('Raja' , 1) d1=Doordelivery(c1,"small",False,1) a=d1.calculate_pizza_cost()
0ee599db1abb522bdd6b1ebbc8f5efac0e555269
vijayroykargwal/Infy-FP
/DSA/Day4/src/Assign18.py
604
4.03125
4
#DSA-Assgn-18 ''' Created on Mar 18, 2019 @author: vijay.pal01 ''' def find_unknown_words(text,vocabulary): #Remove pass and write your logic here list1 = [] text = text.split() for i in text: if i not in vocabulary: list1.append(i) if(len(list1)!=0): return set(list1) else: return -1 #Pass different values text="The sun rises in the east and sets in the west." vocabulary = ["sun","in","rises","the","east"] unknown_words=find_unknown_words(text,vocabulary) print("The unknown words in the file are:",unknown_words)
c5ccf1f31931a42d0a0107468906b154a6be3a00
vijayroykargwal/Infy-FP
/Python by Educator/Demos-Day1/Demos/demos/1-List.py
614
3.734375
4
def list_details(lst): print("Present size of the list:") print("Size:", len(lst)) lst.append("Mango") lst.append("Banana") lst.append("Apple") print("\nSize of the list after adding some items") print("Size:", len(lst)) print("\nInserting a new item at the given position:") lst.insert(1, "Oranges") print(lst) print("\nDeletion of an item from the list:") lst.pop(2) print(lst) shopping_list=[] print("Empty list is created with name shopping_list!\n") list_details(shopping_list)
0995c50c3951a585b7bec778680e336a69433bbf
vijayroykargwal/Infy-FP
/OOPs/Day1/src/Assign3.py
553
3.859375
4
#OOPR-Assgn-3 ''' Created on Mar 5, 2019 @author: vijay.pal01 ''' #Start writing your code here class Customer: def __init__(self): self.customer_name = None self.bill_amount = None def purchases(self): bill_amount = self.bill_amount amount = 0.95*bill_amount return amount def pays_bill(self,amount): return( self.customer_name, "pays bill amount of Rs.",amount) c1 = Customer() c1.customer_name = "Vijay" c1.bill_amount = 5000 print(c1.pays_bill(c1.purchases()))
ee18aba9cf78cd81f195d5421bc164708abad080
vijayroykargwal/Infy-FP
/PF/Day2/src/Assignment18.py
961
3.859375
4
''' Created on Feb 21, 2019 @author: vijay.pal01 ''' #PF-Tryout def convert_currency(amount_needed_inr,current_currency_name): current_currency_amount=0 #write your logic here if(current_currency_name=="Euro"): current_currency_amount = 0.01417*amount_needed_inr elif(current_currency_name=="British Pound"): current_currency_amount = 0.0100*amount_needed_inr elif(current_currency_name=="Australian Dollar"): current_currency_amount = 0.02140*amount_needed_inr elif(current_currency_name=="Canadian Dollar"): current_currency_amount = 0.02027*amount_needed_inr else: print(-1) return current_currency_amount #Provide different values for amount_needed_inr,current_currency_name and test your program currency_needed=convert_currency(3500,"British Pound") if(currency_needed!= -1): print(currency_needed ) else: print("Invalid currency name")
faa8ed79d52a44bdd042d3a09ffda6e7d69d98b9
vijayroykargwal/Infy-FP
/OOPs/Day2/src/Assign11.py
2,197
3.953125
4
#OOPR-Assgn-11 ''' Created on Mar 6, 2019 @author: vijay.pal01 ''' #Start writing your code here class Flower: def __init__(self): self.__flower_name = None self.__price_per_kg = None self.__stock_available = None def get_flower_name(self): return self.__flower_name def get_price_per_kg(self): return self.__price_per_kg def get_stock_available(self): return self.__stock_available def set_flower_name(self, flower_name): self.__flower_name = flower_name.upper() def set_price_per_kg(self, price_per_kg): self.__price_per_kg = price_per_kg def set_stock_available(self, stock_available): self.__stock_available =stock_available def validate_flower(self): if(self.get_flower_name()=="ORCHID" or self.get_flower_name()=="ROSE" or self.get_flower_name()=="JASMINE"): return True else: return False def validate_stock(self,required_quantity): if(required_quantity<=self.get_stock_available()): return True else: return False def sell_flower(self,required_quantity): if((self.get_flower_name()=="ORCHID" or self.get_flower_name()=="ROSE" or self.get_flower_name()=="JASMINE") and (required_quantity<self.get_stock_available())): self.set_stock_available( self.get_stock_available()-required_quantity) return self.get_stock_available() def check_level(self): if(self.get_flower_name()=="ORCHID"): if(self.get_stock_available()<15): return True else: return False elif(self.get_flower_name()=="ROSE"): if(self.get_stock_available()<25): return True else: return False elif(self.get_flower_name()=="JASMINE"): if(self.get_stock_available()<40): return True else: return False else: return False
47156f9110245c9e66bf569a37e0a68d618c51ca
vijayroykargwal/Infy-FP
/PF/Day2/src/sample.py
399
4.03125
4
#PF-Assgn-15 def find_product(num1,num2,num3): product=0 if(num1==7): product = num2*num3 elif(num2==7): product = num3 elif(num3==7): product = -1 else: product = num1*num2*num3 return product #Provide different values for num1, num2, num3 and test your program product=find_product(7,6,2) print(product)
b95b21ff1f9cf7710c9d87f58b7b32cb5202de62
vijayroykargwal/Infy-FP
/PF/Day2/src/Assignment20.py
3,510
3.6875
4
#PF-Assgn-20 ''' Created on Feb 21, 2019 @author: vijay.pal01 ''' def calculate_loan(account_number,salary,account_balance,loan_type,loan_amount_expected,customer_emi_expected): eligible_loan_amount=0 bank_emi_expected=0 eligible_loan_amount=0 #Start writing your code here if(account_balance>=100000): if(account_number>=1000 and account_number<=1999): if(salary>25000 and salary<=50000 and loan_type=="Car"): eligible_loan_amount= 500000 bank_emi_expected=36 if(loan_amount_expected<=eligible_loan_amount and customer_emi_expected<=bank_emi_expected): print("Account number:", account_number) print("The customer can avail the amount of Rs.", eligible_loan_amount) print("Eligible EMIs :", bank_emi_expected) print("Requested loan amount:", loan_amount_expected) print("Requested EMI's:",customer_emi_expected) else: print("The customer is not eligible for the loan") elif(salary>50000 and salary<=75000 and loan_type=="House"): eligible_loan_amount=6000000 bank_emi_expected=60 if(loan_amount_expected<=eligible_loan_amount and customer_emi_expected<=bank_emi_expected): print("Account number:", account_number) print("The customer can avail the amount of Rs.", eligible_loan_amount) print("Eligible EMIs :", bank_emi_expected) print("Requested loan amount:", loan_amount_expected) print("Requested EMI's:",customer_emi_expected) else: print("The customer is not eligible for the loan") elif(salary>75000 and loan_type=="Business"): eligible_loan_amount =7500000 bank_emi_expected=84 if(loan_amount_expected<=eligible_loan_amount and customer_emi_expected<=bank_emi_expected): print("Account number:", account_number) print("The customer can avail the amount of Rs.", eligible_loan_amount) print("Eligible EMIs :", bank_emi_expected) print("Requested loan amount:", loan_amount_expected) print("Requested EMI's:",customer_emi_expected) else: print("The customer is not eligible for the loan") else: print("Invalid loan type or salary") else: print("Invalid account number") else: print("Insufficient account balance") #Populate the variables: eligible_loan_amount and bank_emi_expected #print("Account number:", account_number) #print("The customer can avail the amount of Rs.", eligible_loan_amount) #print("Eligible EMIs :", bank_emi_expected) #print("Requested loan amount:", loan_amount_expected) #print("Requested EMI's:",customer_emi_expected) #print("Insufficient account balance") #print("The customer is not eligible for the loan") #print("Invalid account number") #print("Invalid loan type or salary") # Also, do not modify the above print statements for verification to work #Test your code for different values and observe the results calculate_loan(1001,40000,250000,"Car",300000,30)
10e486440db7308ddea1772b01621d043d927f1b
vaibhavk039/python-coding
/binary search.py
515
4
4
#!/usr/bin/env python # coding: utf-8 # In[5]: a=eval(input("enter a list")) n=len(a) num=int(input("a number to find")) beg=0 end=n-1 for beg in range(0,end+1): mid=(beg+end)//2 if num==a[mid]: flag=1 break elif num<a[mid]: end=mid-1 flag=0 elif num>a[mid]: beg=mid+1 flag=0 if flag==0: print("not found") else: print("found") # In[ ]: # In[ ]:
4f2f5d67c3e89198b7781c94fd94face395b470c
vaibhavk039/python-coding
/pallindrome.py
178
3.984375
4
s=input() a=[] for i in s: a.append(i) a.reverse() listToStr = ''.join(map(str, a)) if(s== listToStr): print("Pallindrome") else: print("Not a Pallindrome")
6e470e6f8219a39ebdb2b862ea9bf85c7710c576
alexbehrens/Bioinformatics
/rosalind-problems-master/alg_heights/FibonacciNumbers .py
372
4.21875
4
def Fibonacci_Loop(number): old = 1 new = 1 for itr in range(number - 1): tmpVal = new new = old old = old + tmpVal return new def Fibonacci_Loop_Pythonic(number): old, new = 1, 1 for itr in range(number - 1): new, old = old, old + new return new print(Fibonacci_Loop(13)) print(Fibonacci_Loop_Pythonic(13))
71f35fdf946fcec415e53ef247d0980b4a97a1dd
elk1o/starting_pyhton
/Ejercicios_python/Ej5.py
1,690
3.5
4
# -*- coding: utf-8 -*- import time # 5) Diseñar un presupuesto con una clase ModeloPresupuesto pidiendo los siguientes datos: # Nombre de la empresa, nombre del cliente, fecha del presupuesto, descripción del # servicio, importe bruto, fecha de caducidad , iva e importe total class ModeloPresupuesto(object): estimate_ID = 1000; def __init__(self, company, customer, service_description, gross_amount, expiry_date, iva, total_amount ): self.company = company self.customer = customer self.estimate_ID = self.estimate_ID self.service = service_description self.gross_amount = gross_amount self.expiry_date = expiry_date self.iva = iva self.total_amount = total_amount self.estimate_ID += 100 time.sleep(2) return class Menu(object): def __init__(self): return def showMenu(self): print("-----------------------------------") print("-------Estimate creator v1.0-------") print("-----------------------------------") company = input("Enter company name: \n") customer = input("Enter customer name: \n") service_description = input("Enter a short description for service: \n") gross_amount = input("Enter the gross amount: \n") expiry_date = input("Enter expiry date: \n") iva = input("Enter IVA tax: \n") total_amount = input("Enter total amount: \n") print("--------Calculating Estimate ... -------") estimate = ModeloPresupuesto(company,customer,service_description,gross_amount,expiry_date,iva,total_amount) print(estimate.__dict__) menu = Menu() menu.showMenu()
e63d8436e30b37537a77f1c61057148099b80167
pokepetter/brython
/www/src/Lib/asyncio/futures.py
7,102
3.515625
4
from .events import get_event_loop class InvalidStateError(Exception): pass class CancelledError(Exception): pass class TimeoutError(Exception): pass class Future: """ A class representing the future result of an async action. Implementations should override the :method:`start` method which should start the asynchronous operation. The class will typically register a handler to be run when the operation finishes. This handler then needs to call the base :method:`_finish` method providing it with the :parameter:`result` parameter and :parameter:`status` (which should either be ``Promise.STATUS_FINISHED`` in case the operation finished successfully or ``Promise.STATUS_ERROR`` if an error happened). """ STATUS_STARTED = 0 STATUS_CANCELED = 1 STATUS_FINISHED = 2 STATUS_ERROR = 3 def __init__(self, loop=None): if loop is None: loop = get_event_loop() self._loop = loop self._status = Future.STATUS_STARTED self._result = None self._exception = None self._callbacks = [] self._loop._register_future(self) def _schedule_callbacks(self): for cb in self._callbacks: self._loop.call_soon(cb, self) def cancel(self): """ Cancel the future and schedule callbacks. If the future is already done or cancelled, return False. Otherwise, change the future’s state to cancelled, schedule the callbacks and return True.""" if self._status != Future.STATUS_STARTED: return False self._status = Future.STATUS_CANCELED self._schedule_callbacks() return True def cancelled(self): """Return True if the future was cancelled.""" return self._status == Future.STATUS_CANCELED def done(self): """ Return True if the future is done. Done means either that a result / exception are available, or that the future was cancelled. """ return self._status != Future.STATUS_STARTED def result(self): """ Return the result this future represents. If the future has been cancelled, raises CancelledError. If the future’s result isn’t yet available, raises InvalidStateError. If the future is done and has an exception set, this exception is raised. """ if self._status == Future.STATUS_STARTED: raise InvalidStateError() if self._status == Future.STATUS_CANCELED: raise CancelledError() if self._status == Future.STATUS_ERROR: raise self._exception return self._result def exception(self): """ Return the exception that was set on this future. The exception (or None if no exception was set) is returned only if the future is done. If the future has been cancelled, raises CancelledError. If the future isn’t done yet, raises InvalidStateError. """ if self._status == Future.STATUS_STARTED: raise InvalidStateError() if self._status == Future.STATUS_CANCELED: raise CancelledError() if self._status == Future.STATUS_ERROR: return self._exception def add_done_callback(self, fn): """ Add a callback to be run when the future becomes done. The callback is called with a single argument - the future object. If the future is already done when this is called, the callback is scheduled with call_soon(). Use functools.partial to pass parameters to the callback. For example, fut.add_done_callback(functools.partial(print, "Future:", flush=True)) will call print("Future:", fut, flush=True). """ if self.done(): self._loop.call_soon(fn,self) else: self._callbacks.append(fn) def remove_done_callback(self, fn): """ Remove all instances of a callback from the “call when done” list. Returns the number of callbacks removed. """ removed = 0 retain = [] for cb in self._callbacks: if cb == fn: removed += 1 else: retain.append(cb) self._callbacks = retain return removed def set_result(self, result): """ Mark the future done and set its result. If the future is already done when this method is called, raises InvalidStateError. """ if self._status != Future.STATUS_STARTED: raise InvalidStateError() self._result = result self._status = Future.STATUS_FINISHED self._schedule_callbacks() def set_exception(self, exception): """ Mark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError. """ if self._status != Future.STATUS_STARTED: raise InvalidStateError() self._exception = exception self._status = Future.STATUS_ERROR self._schedule_callbacks() def __iter__(self): if not self.done(): yield self return self.result() class GatheredFuture(Future): def __init__(self, futures, return_exceptions=False, loop=None): super().__init__(loop=None) self._futures = futures self._ret_exceptions = return_exceptions for fut in futures: fut.add_done_callback(lambda : self._done(fut)) def _done(self, fut): if self.done(): return if fut.canceled(): if not self._ret_exceptions: self.set_exception(CancelledError()) return else: exc = fut.exception() if exc is not None and not self._ret_exceptions: self.set_exception(exc) return self._check_finished() def cancel(self): for fut in self._futures: if not fut.done(): fut.cancel() super().cancel() def _check_finished(self): results = [] for fut in self._futures: if not fut.done(): return elif fut.canceled(): results.append(CancelledError()) exc = fut.exception() if exc is not None: results.append(exc) else: results.append(fut.result()) self.set_result(results) class SleepFuture(Future): def __init__(self, seconds, result=None, loop=None): super().__init__(loop) self._loop.call_later(seconds, self.set_result, result) def set_result(self, result): if not self.done(): super().set_result(result) else: print("Sleep already finished with ex:", self.exception()) def gather(*coros_or_futures, return_exceptions=False, loop=None): fut_list = [ensure_future(c, loop=loop) for c in coros_or_futures] return GatheredFuture(fut_list, return_exceptions=False)
30bd097010d0007335b49506a945731503b9b5bf
ronnynijimbere/basic-intro-python
/lessons/filters.py
354
4.03125
4
grades = ['A', 'C', 'E', 'F', 'F', 'B', 'D'] def remove_fails(grade): return grade != 'F' #print(list(filter(remove_fails, grades))) # using for loop #filtered_grades = [] #for grade in grades: # if grade != 'F': # filtered_grades.append(grade) #print(filtered_grades) #using comprehension method print([grade for grade in grades if grade !='F'])
32e3b00cbc5cdb5a0dc755f4f57a33f81be98baf
eduhmik/Ita_Waiter_App
/tests.py
233
3.578125
4
def remove_duplicates(x,y): if x > y: for i in the range of(x,y): if m % 2 == 0: return m elif x < y: for i in the range of(x,y): if m % 2 != 0: return m
5af688c66904d3d6b0ad57fbb008c93d2797ddd8
alexeahn/UNC-comp110
/exercises/ex06/dictionaries.py
1,276
4.25
4
"""Practice with dictionaries.""" __author__ = "730389910" # Define your functions below # Invert function: by giving values, returns a flip of the values def invert(first: dict[str, str]) -> dict[str, str]: """Inverts a dictionary.""" switch: dict[str, str] = {} for key in first: value: str = first[key] switch[value] = key return switch # Favorite color: sort different colors based on what people like the most def favorite_color(colors: dict[str, str]) -> str: """Gives the most frequently listed color.""" favorite: str = "" for key in colors: value: str = colors[key] favorite = value return favorite # Count: shows how many times a certain key was given def count(find: list[str]) -> dict[str, int]: """Counts how many times a string is presented.""" i: int = 0 final: dict[str, int] = {} while i < len(find): key = find[i] if key in final: final[key] += 1 else: final[key] = 1 i += 1 return final f: str = "blue" g: str = "silver" h: str = "gold" link: list[str] = ["fish", "bird", "dog", "fish"] print(invert({g: f})) print(favorite_color({"Alex": f, "Jeff": f, "Joe": g})) print(count(link))
ecc6c223791fdc1abd8877cb75270242efeb34e1
alexeahn/UNC-comp110
/exercises/ex06/dictionaries_test.py
1,541
3.5625
4
"""Unit tests for dictionary functions.""" # TODO: Uncomment the below line when ready to write unit tests from exercises.ex06.dictionaries import invert, favorite_color, count __author__ = "730389910" # tests for invert def test_invert_one() -> None: """Test for first.""" tester: dict[str, str] = {} assert invert(tester) == {} def test_invert_two() -> None: """Test for second.""" second_tester: dict[str, str] = {"gold": "silver"} assert invert(second_tester) == {"silver": "gold"} def test_invert_three() -> None: """Test for third.""" third_tester: dict[str, str] = {"silver": "gold"} assert invert(third_tester) == {"gold": "silver"} def test_favorite_color_one() -> None: """Favorite color test one.""" first_color: dict[str, str] = {} assert favorite_color(first_color) == {} def test_favorite_color_two() -> None: """Favorite color test one.""" second_color: dict[str, str] = {} assert favorite_color(second_color) == {} def test_favorite_color_three() -> None: """Favorite color test one.""" tester: dict[str, str] = {} assert favorite_color(tester) == {} def test_count_one() -> None: """Count test one.""" test_one: dict[str, str] = {} assert count(test_one) == {} def test_count_two() -> None: """Count test two.""" test_two: dict[str, str] = {} assert count(test_two) == {} def test_count_three() -> None: """Count test three.""" third_tester: dict[str, str] = {} assert count(third_tester) == {}
8c07973b4801ccec257382cba5a7becbed73c950
Laylaaaaaa/ECE143-Programming-for-Data-Analysis
/Function Code/read_data_from_excel.py
6,716
3.5625
4
import csv features, salaries=[], [] headers = {} def read_data_from_excel(file_path='/Users/shawnwinston/Desktop/ece_143/Train_rev1_salaries.csv'): ''' reads raw data from an execl file and stores it in a dxn list where n is the number of data examples and d is the number of categories input: file name of where to read data from output:nxd list of extracted raw data ''' assert isinstance(file_path, str) print "Reading data..." with open(file_path) as data: data_csv = csv.reader(data) header = data.readline().split(',') #these are the categories # ['Id', 'Title', 'FullDescription', 'LocationRaw', 'LocationNormalized', 'ContractType', 'ContractTime', 'Company', 'Category', 'SalaryRaw', 'SalaryNormalized', 'SourceName\r\n'] i=0 for name in header: headers[name] = i i+=1 lines = [x for x in data_csv] for l in lines: features.append(l[0:9]+[l[11]]) salaries.append(float(l[10])) print "done" #Can access each feature by name instead of number using below syntax #print features[0][categories['Id']] def visualize_data(x_label, y_label, title, data): ''' Makes a bar chart and visualizes the job data that is passed to it :param x_label: str to put on x_axis :param y_label: str to put on y_axis :param title: str to put as title :param data: data to display on graph ''' import numpy as np assert isinstance(data, dict) assert isinstance(x_label,str) assert isinstance(y_label,str) assert isinstance(title,str) import matplotlib.pyplot as plt my_colors = [(0.2, 0.4, 0.5), (0.2, 0.75, 0.25)] width=0.5 sorted_data = sorted(data.items(), key=lambda x: x[1], reverse=True) unzipped_sorted_data = zip(*sorted_data) plt.figure(figsize=(12,8)) indices = np.arange(len(data.keys())) fig = plt.bar(indices, unzipped_sorted_data[1], width, color=my_colors) plt.xticks(indices, unzipped_sorted_data[0], rotation='vertical') plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) #put label above each bar on chart rects = fig.patches for rect,label in zip(rects,unzipped_sorted_data[1]): height = rect.get_height() plt.text(rect.get_x() + rect.get_width()/2, height+5, label, ha='center', va='bottom') plt.show() def salary_per_category(category_name): ''' Gets average salary data and max salary data for desired catergory_name input: the category name you wish to see salary data for ex: location, company, job title, etc. output: average_category_salary - dictonary that stores the average salary data per category values max_category_salary - dictonary that stores the max salary data per category values ''' from collections import defaultdict import operator assert isinstance(category_name, str) assert category_name in headers category_salaries = defaultdict(list) average_category_salaries = {} max_category_salary = {} top_20 = {} #create dictonary of lists that stores all the salary values for each category value for i in range(len(salaries)): category_salaries[features[i][headers[category_name]]].append(salaries[i]) sorted_category_salaries = sorted(category_salaries.items(), key=lambda x: len(x[1]), reverse=True) #print number of listings in each category for top 20 for i in range(20): top_20[sorted_category_salaries[i][0]] = len(sorted_category_salaries[i][1]) #print sorted_category_salaries[i][0], len(sorted_category_salaries[i][1]) #Calculate average and max salary for each category value for key in category_salaries.keys(): #print key, len(category_salaries[key]) if len(category_salaries[key]) > 4: average_category_salaries[key] = sum(category_salaries[key])/len(category_salaries[key]) max_category_salary[key] = max(category_salaries[key]) #print average_category_salaries #print max_category_salary sorted_average_category_salaries = sorted(average_category_salaries.items(), key=lambda x: x[1]) sorted_max_category_salaries = sorted(max_category_salary.items(), key=lambda x: x[1]) print sorted_average_category_salaries[-5:] print sorted_max_category_salaries[-5:] #all categories in dataset #print category_salaries.keys() print top_20 return average_category_salaries, max_category_salary, top_20 #average salary of all jobs def average_salary(): ''' :return: average salary of all jobs in dataset ''' print sum(salaries)/len(salaries) def predict_company_category(n): ''' predicts the type of company based off of the category of job listings :param n: number of companies in dataset that we want to predict for :return: dictonary of companies and their predicted category ''' from collections import defaultdict assert isinstance(n,int) assert n > 0 companies = defaultdict(list) predictions = {} # create dictonary of lists that stores all the salary values for each category value for i in range(len(salaries)): companies[features[i][headers['Company']]].append(features[i][headers['Category']]) sorted_company_category = sorted(companies.items(), key=lambda x: len(x[1]), reverse=True) top_company_category = dict(sorted_company_category[1:n]) #adds up all the categories for a specific and determines which category has the most and predicts that as #the category for the company for key in top_company_category.keys() : category_dict = {} for cat in top_company_category[key]: if cat in category_dict.keys(): category_dict[cat] += 1 else: category_dict[cat] = 0 #print max(category_dict, key=category_dict.get) predictions[key] = max(category_dict, key=category_dict.get) #print predictions return predictions ####### MAIN LOOP ######## read_data_from_excel() avg_salary_dict, max_salary_dict, top_20 = salary_per_category('Company') average_salary() predictions = predict_company_category(20) visualize_data('Category of Job', "Number of Job Listings", "Number of Job Listings Per Category", top_20) #maybe find job Titles with the top salaries header_truncated = ['Title', 'LocationNormalized', 'Company', 'Category'] #for name in header_truncated: # avg_salary_dict, max_salary_dict, top_20 = salary_per_category(name) # visualize_salary_data() #visual average salary data # visualize_salary_data() #visualize max salary data
661465d06478d0a00a74f1c996c45d242d15f0ed
issone/leetcode
/0048_rotate-imag/solution.py
595
3.65625
4
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ 将旋转,转换为先水平翻转,再左对角线翻转 """ n = len(matrix) # 先沿水平中线水平翻转 for i in range(n // 2): for j in range(n): matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j] # 左对角线翻转 for i in range(n): for j in range(i): # 注意这里是i, 不是n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
362fb6d0f1a0511432698c2fd6eb3541c8e1315a
issone/leetcode
/0073_set-matrix-zeroes/solution.py
1,335
3.6875
4
from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return row = len(matrix) col = len(matrix[0]) is_sign = False for i in range(row): if matrix[i][0] == 0: # 标记第一列中是否有0,提前保存,防止被后面检测时,覆盖了(0,0)的值 is_sign = True for j in range(1, col): # 跳过第一列,检查其他行列是否有0 if matrix[i][j] == 0: # 将当前行的第一个和当前列的第一个设为0 matrix[i][0] = 0 matrix[0][j] = 0 for i in range(1, row): # 跳过第一行和第一列,检查标识位置是否出现过0 for j in range(1, col): if matrix[i][0] == 0 or matrix[0][j] == 0: # 当前行或列的第一个是0,代表此行或列出现过0 matrix[i][j] = 0 if matrix[0][0] == 0: # 第一行需要被设置为0 for i in range(col): matrix[0][i] = 0 if is_sign: # 第一列中出现过0,所以第一列需要被设置为0 for i in range(row): matrix[i][0] = 0
0e4812f02dc8c63932319ac7f1eb4e6a0083bb50
issone/leetcode
/0056_merge-intervals/solution.py
814
3.640625
4
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: new_intervals = [] intervals.sort(key=lambda x: x[0]) # 先按左区间端点进行排序 for interval in intervals: if not new_intervals or new_intervals[-1][1] < interval[0]: # 上一个区间的右端点比当前区间的左端点还小,不能合并,直接插入 new_intervals.append(interval) else: # 当前区间左端点,一定比上一个区间的左端点大,当前区间左端点小于上一个区间的右端点时,一定重叠,合并后的新的区间右端点,是两个区间中右端点最大的那个 new_intervals[-1][1] = max(new_intervals[-1][1], interval[1]) return new_intervals
447dacc2a84daf98f12d0265ffba6dce84246428
issone/leetcode
/interview_question/replace_spaces/solution.py
1,056
3.515625
4
class Solution(object): def replaceSpace(self, s): """ 时间复杂度和空间复杂度都是O(n) """ list_s = list(s) # 记录原本字符串的长度 original_end = len(s) # 将空格改成%20 使得字符串总长增长 2n,n为原本空格数量。 # 所以记录空格数量就可以得到目标字符串的长度 n_space = 0 for ss in s: if ss == ' ': n_space += 1 list_s += ['0'] * 2 * n_space # 设置左右指针位置 left, right = original_end - 1, len(list_s) - 1 # 循环直至左指针越界 while left >= 0: if list_s[left] == ' ': list_s[right] = '0' list_s[right - 1] = '2' list_s[right - 2] = '%' right -= 3 else: list_s[right] = list_s[left] right -= 1 left -= 1 # 将list变回str,输出 s = ''.join(list_s) return s
cd834bb1a8bd026ef9bf027a3c11105dcbf51f40
brenhertel/Pearl-ur5e
/MetaLfD-fork/scripts/screen_capture.py
2,827
3.78125
4
#!/usr/bin/python ''' ----------------------------------- Capture Trajectory Demonstrations from a Pointer Device ​ Usage: 1- run the file 2- press mouse left-button and hold 3- start drawing 4- release mouse left-button to stop 5- program shows the captured data 6- use terminal to save data ​ ​ Author: Reza Ahmadzadeh, 2020 ----------------------------------- ''' import numpy as np import pygame from scipy.interpolate import interp1d import matplotlib.pyplot as plt from matplotlib.widgets import Button # variables W = 400 H = 400 r = 2 rate = 100 # recording rate bgColor = pygame.Color("White") fgColor = pygame.Color("Black") X = [] Y = [] def save_data(X,Y): fname = input('Enter a filename (e.g. data.txt, ENTER to exit):') if fname == '': print("Data was not saved.") return False else: try: with open(fname, 'wb') as f: #np.savetxt(f,np.column_stack((np.array(X),np.array(Y)))) np.savetxt(f,np.column_stack((X,Y))) print("data saved.") except IOError: print("Error in saving data") #f.close() def draw_result(X,Y): print("Data can be saved after closing the plot.") t = np.linspace(0,1,len(X)) tt = np.linspace(0,1,1000) print(len(t)) fx = interp1d(t,np.array(X), kind = 'cubic') fy = interp1d(t,np.array(Y), kind = 'cubic') plt.figure() plt.gca().invert_yaxis() plt.plot(X,Y,'.--',label="demonstration") plt.plot(fx(t),fy(t),label="smoothed") plt.title("captured raw and smoothed demonstration") plt.xlabel("x") plt.ylabel("inverted y") plt.show() save_data(fx(tt),fy(tt)) def main(): pygame.init() screen = pygame.display.set_mode((W,H)) screen.fill(bgColor) pygame.display.set_caption("Draw a demonstration using your pointer devices") pygame.draw.rect(screen, bgColor, pygame.Rect((0,0),(W,H))) clock = pygame.time.Clock() press = False running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False (x,y) = pygame.mouse.get_pos() if pygame.mouse.get_pressed() == (1,0,0): # record if in drawing mode X.append(x) Y.append(y) pygame.draw.circle(screen, fgColor, (x,y), r) if event.type == pygame.MOUSEBUTTONUP: press == False print("Number of points captured: " +str(len(X))) print("Plotting the captured demonstratio ...") draw_result(X,Y) running = False pygame.display.flip() pygame.display.update() clock.tick(rate) if __name__ == "__main__": main()
152b6e24d03e0d1b9657b1ed46c3a25de9e5126b
btg-work-experience-2019/testing-demo
/src/secret_formula.py
554
3.6875
4
''' Exposes a class and three functions that perform an amazing calculation based on user inputs. ''' def add_two_then_square(value): return 2 + value * value def plus_ten(value): return value + 10 def subtract_one(value): return value - 1 class FormulaRunner: def __init__(self, input): self.input = input self.output = 0 def run(self): self.output = plus_ten(self.input) self.output = subtract_one(self.output) self.output = add_two_then_square(self.output) return self.output
04d3ec877c01989f96bf4b21297f9d49d5df15b5
davidorourke1990/ProjectMLS
/main.py
8,941
3.796875
4
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt MLS19 = pd.read_csv("MLS19.csv") ##print the head print(MLS19.head()) ##print the tail print(MLS19.tail()) ##get the shape of dataset MLS19.shape print(MLS19.shape) ##show the dataframe info MLS19.info() print(MLS19.info()) ##show the columns MLS19.columns print(MLS19.columns) ##show the index MLS19.index print(MLS19.index) ##describe the dataset MLS19.describe() print(MLS19.describe()) #creating a dictionary example Dict1 = {'First_Name':'Zlatan', 'Last_Name':'Ibrahimovic'} print(Dict1) Dict2 = dict([['DC United','DCU'], ['Philadelphia Union','PHU'], ['Toronto FC','TFC']]) print(Dict2) Club_Symbols1 = Dict2.get('TFC') print(Club_Symbols1) Club_Symbols1 = Dict2.get('Philadelphia Union') print(Club_Symbols1) ##if i wanted to sort by clubs in alphabetical order MLS19club = MLS19.sort_values("Club") print(MLS19club) ##sorting by multiple variables MLS19Alphabet = MLS19.sort_values(["Club", "Last_Name"]) print(MLS19Alphabet) #sort by salary in ascending order and show top 10 highest earners MLS19_Salary = MLS19.sort_values("Salary", ascending=False) print(MLS19_Salary.head(10)) #show the 10 lowest earners print(MLS19_Salary.tail(10)) #show how many players per club print(MLS19Alphabet["Club"].value_counts()) #subsetting columns Salary_Column1 = MLS19_Salary["Salary"] print(Salary_Column1) #subsetting multiple columns to get just last name and Salary MLS19_Salary = MLS19_Salary[["Last_Name", "Salary",]] print(MLS19_Salary) ##max salary amount print(MLS19_Salary["Salary"].max()) #max total earnings and all details of player print(MLS19[MLS19["Guaranteed_Comp"] == MLS19["Guaranteed_Comp"].max()]) ##minimum salary amount print(MLS19_Salary["Salary"].min()) #minimum total earnings and all details of player print(MLS19[MLS19["Guaranteed_Comp"] == MLS19["Guaranteed_Comp"].min()]) #Obtain the players earning over 1million $ only Salary_Millionaire19 = MLS19_Salary[MLS19_Salary["Salary"] > 1000000.00] print(Salary_Millionaire19) #Number of players earning over 1million $ Salary_Millionaire19.count() print(Salary_Millionaire19.count()) #Create a new Column to find out difference in Salary and Guaranteed Compensation MLS19["Comp_Diff"] = MLS19["Guaranteed_Comp"] - MLS19["Salary"] print(MLS19.head()) #Check who has the largest difference in Salary and Guaranteed Compensation MLS19Comp = MLS19.sort_values("Comp_Diff", ascending=False) print(MLS19Comp.head(10)) #Find the players who have received a different Guaranteed compensation to salary MLS19CompPlus = MLS19Comp[MLS19Comp["Comp_Diff"] > 1.00] print(MLS19CompPlus) #Print the top 10 players with highest difference in salary and guaranteed compensation print(MLS19CompPlus.head()) #summarize numerical data of Salary ##Average Salary print(MLS19_Salary.mean()) ##median number print(MLS19_Salary.median()) ##Standard Deviation print(MLS19_Salary.std()) #Group by Club and Salaries (minimum, max and Total per club) Team_Summary = MLS19.groupby("Club")["Salary"].agg([min, max, sum]) print(Team_Summary) #Check for missing values null_data = MLS19[MLS19.isnull().any(axis=1)] print(null_data) #show whole dataset and indicate tha values that are missing print(MLS19.isna()) #show overview if there is any data misisng in any of the columns print(MLS19.isna().any()) #total amount missing in each column print(MLS19.isna().sum()) #sample of misisng First names MLS19Name = MLS19[["Last_Name", "First_Name",]] print(MLS19Name[45:52]) #replace missing first names by combining first and last name columns to create one column called 'Name' def Fullname(x, y): if str(x) == "NaN": return str(y) else: return str(x) + " " + str(y) MLS19['Name'] = np.vectorize(Fullname)(MLS19['First_Name'], MLS19['Last_Name']) print(MLS19) #Now we can drop the excess columns of 'Last_Name' and 'First_Name' MLS19 = MLS19.drop(['Last_Name', 'First_Name'], axis = 1) print(MLS19) #Now we can replace the Players with no defined position value with 'None' MLS19["Position"].fillna("None", inplace = True) print(MLS19) #Run again to check what else remains missing print(MLS19.isna().sum()) #Number of players according to their positions print(MLS19["Position"].value_counts()) #Salaries and Guaranteed comp according to playing positions Salary_Position = MLS19.groupby("Position").mean() print(Salary_Position) #plot the average salaries by the position of each player Salary_Position.plot(kind="barh", y=["Salary", "Guaranteed_Comp"], title="Salary by Playing Position 2019") plt.show() #plot average spend of each club on salary on bar chart Club_Position = MLS19.groupby("Club").mean() Club_Position.sort_values(by = 'Salary', ascending = False,inplace=True) print(Club_Position) plt.figure(figsize=(12,8)) sns.set_style("whitegrid") sns.barplot(x=Club_Position.index, y=Club_Position["Salary"]) plt.xticks(rotation= 80) plt.xlabel('Clubs') plt.ylabel('Salaries') plt.title('Average Salary per Club 2019') plt.show() #Plot the salary and guranteed comp on one bar per club fig, ax = plt.subplots() ax.bar(Club_Position.index, Club_Position["Salary"]) ax.bar(Club_Position.index, Club_Position["Guaranteed_Comp"], bottom=Club_Position["Salary"]) ax.set_xticklabels(Club_Position.index, rotation=75) ax.set_ylabel("$$$") plt.show() Club_Position = Club_Position.iloc[-2:, -1] print(Club_Position) ##For comparison find MLS salaries in 2014 (5 year difference) #import a new dataset of MLS salaries from 2014 MLS14 = pd.read_csv("MLS14.csv") print(MLS14) ##describe the dataset MLS14.describe() print(MLS14.describe()) #sort by Salary MLS14_Salary = MLS14.sort_values("Salary", ascending=False) print(MLS14_Salary) #subsetting multiple columns to get just last name and Salary MLS14_Salary = MLS14_Salary[["Last_Name", "Salary",]] print(MLS14_Salary) ##max salary print(MLS14["Salary"].max()) #minimum salary print(MLS14["Salary"].min()) #Obtain the players earning over 1million $ only Salary_Millionaire14 = MLS14_Salary[MLS14_Salary["Salary"] > 1000000.00] print(Salary_Millionaire14) #Number of players earning over 1million $ Salary_Millionaire14.count() print(Salary_Millionaire14.count()) #Create a new Column to find out difference in Salary and Guaranteed Compensation MLS14["Comp_Diff"] = MLS14["Guaranteed_Comp"] - MLS14["Salary"] print(MLS14.head()) #Salaries and Guaranteed comp according to playing positions Salary_Position14 = MLS14.groupby("Position").mean() print(Salary_Position14) #plot the average salaries by the position of each player Salary_Position14.plot(kind="barh", y=["Salary", "Guaranteed_Comp"], title="Salary by Playing Position 2014") plt.show() #plot average spend of each club on salary on bar chart Club_Position14 = MLS14.groupby("Club").mean() Club_Position14.sort_values(by = 'Salary', ascending = False,inplace=True) Club_Position14 = Club_Position14.iloc[1:, :] print(Club_Position14) plt.figure(figsize=(12,8)) sns.barplot(x=Club_Position14.index, y=Club_Position14["Salary"]) plt.xticks(rotation= 80) plt.xlabel('Clubs') plt.ylabel('Salaries') plt.title('Average Salary per Club 2014') plt.show() #plot the data of the players with salaries over 1million in both datasets Salary_Millionaire14 = Salary_Millionaire14.sort_values("Salary", ascending=True) Salary_Millionaire19 = Salary_Millionaire19.sort_values("Salary", ascending=True) Salary_Millionaire14.plot(x="Last_Name", y="Salary", kind="line", marker="*", linestyle="--", rot=45) ax.set_xlabel("Players") ax.set_ylabel("Salary$") plt.title('Players Earning over $1million per year') plt.show() Salary_Millionaire19.plot(x="Last_Name", y='Salary', kind="line", marker="o", color="r", rot=45) ax.set_xlabel("Players") ax.set_ylabel("Salary$") plt.title('Players Earning over $1million per year') plt.show() #line plot Salary_Millionaire14 = Salary_Millionaire14.tail(10) print(Salary_Millionaire14) Salary_Millionaire19 = Salary_Millionaire19.tail(10) print(Salary_Millionaire19) fig, ax = plt.subplots(2, 1) ax[0].plot(Salary_Millionaire14["Last_Name"], Salary_Millionaire14["Salary"], color='b') ax[1].plot(Salary_Millionaire19["Last_Name"], Salary_Millionaire19["Salary"], color='r') plt.show() #Merging on the left Merge1 = Salary_Millionaire19.merge(Salary_Millionaire14, on="Last_Name", how='left') print(Merge1) #Merging on the outer joint Merge2 = Salary_Millionaire19.merge(Salary_Millionaire14, on="Last_Name", how='outer') print(Merge2) Merge2 = Merge2.sort_values("Last_Name", ascending=False) print(Merge2) #Showing a common player featuring in both lists MLSMerge = Salary_Millionaire19.merge(Salary_Millionaire14, on="Last_Name") print(MLSMerge) #Concentating table with two data frames Concat = pd.concat([Salary_Millionaire19, Salary_Millionaire14], axis=1) print(Concat) Concat2 = pd.concat([Salary_Millionaire19, Salary_Millionaire14]) print(Concat2.head(10)) #Thankyou
ded0e835b4d99fdd99764a212c9135cd5411b918
johnmdelgado/SRE-Project
/scripts/convert_input_to_set.py
541
3.546875
4
#!/usr/bin/python ''' FileName: convert_input_to_set.py Author: John Delgado Created Date: 8/7/2020 Version: 1.0 Initial Development This will take the sys.stdin input and convert it into a set and then return the set ''' def convert_input_to_set(inputVales,debug): if(not inputVales): raise Exception("Input is empty. Please provide values.") uniqueSet = set() for line in inputVales: if(debug): print("Adding value: {} to set ".format(line)) uniqueSet.add(line) return uniqueSet
f1abc2a691bff70c89dd53237e84ec1bda634f01
ericgroom/mcserver-bot
/bot/formatter.py
433
3.6875
4
def format_player_list(players): if players.online == 0: return "There is currently nobody online" if players.max: result = f"There are {players.online}\{players.max} players online" else: result = f"There are {players.online} players online" if players.sample: plist = ", ".join([player.name for player in players.sample]) result += f"\nIncluding: {plist}" return result
57b357c1cd9d9e2eed8996564724f488f8e18539
Padmabala/codekata
/FiboSavings.py
470
3.796875
4
def calculateTotalSavings(month,pastSavings): if(month in pastSavings): return pastSavings[month] else: total=calculateTotalSavings(month-1,pastSavings)+calculateTotalSavings(month-2,pastSavings) pastSavings[month]=total return total noOfMonths=int(input()) pastSavings={} pastSavings[0]=1000 pastSavings[1]=1000 calculateTotalSavings(noOfMonths,pastSavings) sum=0 for i in range(noOfMonths+1): sum=sum+pastSavings[i] print(sum)
886ee264c101045c93241d1a9499b03c8360710d
marcelo-rufino/projetopython
/server.py
1,100
3.71875
4
from flask import Flask, render_template, request #importando um modulo do python Flask app = Flask(__name__,template_folder="./src/views")#joguei dentro de uma variavel app o metodo Flask @app.route("/",methods = ["GET", "POST"]) def home(): if(request.method == "GET"): return render_template('index.html') else: if(request.form["input1"] != "" and request.form["input2"] != ""): n1=request.form["input1"] n2=request.form["input2"] operadores=request.form["condicionais"] #calculos soma = int(n1) + int(n2) sub = int(n1) - int(n2) mult = int(n1) * int(n2) div = int(n1) / int(n2) if(operadores == "soma"): return str(soma) elif(operadores == "sub"): return str(sub) elif(operadores == "mult"): return str(mult) else: return str(div) else: return "<h1> Favor preencha todos os campos do formulário </h1>" app.run(port=8080, debug=True)
43fff8b5123088e2fa7416157b729b0ddb3542a8
cassjs/practice_python
/practice_mini_scripts/math_quiz_addition.py
1,687
4.25
4
# Program: Math Quiz (Addition) # Description: Program randomly produces a sum of two integers. User can input the answer # and recieve a congrats message or an incorrect message with the correct answer. # Input: # Random Integer + Random Integer = ____ # Enter your answer: # Output: # Correct = Congratulations! # Incorrect = The correct answer is ____ # Program Output Example: # Correct # 22 + 46 = ___ # Enter your answer: 68 # Congratulations! # Incorrect # 75 + 16 = ___ # Enter your answer: 2 # The correct answer is 91. # Pseudocode: # Main Module # from numpy import random # Set num1 = random.randint(100) # Set num2 = random.randint(100) # Display num1, '+', num2, '= ___ ' # Set correctAnswer = num1 + num2 # Set userAnswer = getUserAnswer() # Call checkAnswer(userAnswer, correctAnswer) # End Main # Module getUserAnswer(): # Set userAnswer = int(input('Enter your answer: ')) # Return userAnswer # Module checkAnswer(userAnswer, correctAnswer): # If userAnswer == correctAnswer: # Display 'Congratulations!' # Else: # Display 'The correct answer is ', correctAnswer, '.', sep='' # End checkAnswer # Call Main def main(): from numpy import random num1 = random.randint(100) num2 = random.randint(100) print(num1, '+', num2, '= ___ ') correctAnswer = num1 + num2 userAnswer = getUserAnswer() checkAnswer(userAnswer, correctAnswer) def getUserAnswer(): userAnswer = int(input('Enter your answer: ')) return userAnswer def checkAnswer(userAnswer, correctAnswer): if userAnswer == correctAnswer: print('Congratulations!') else: print('The correct answer is ', correctAnswer, '.', sep='') main()
85bf56c7e7da9dc7fa11903de41767383492170e
ThomasNam-study/py_sample
/sqliteSample/sl_sample.py
798
3.796875
4
import sqlite3 # 디비 연결 conn = sqlite3.connect("my.db") # 커서 추출 c = conn.cursor() # SQL 실행 c.execute("DROP TABLE IF EXISTS cities") c.execute('''CREATE TABLE cities (rank integer, city text, population integer)''') c.execute('INSERT INTO cities VALUES(?, ?, ?)', (1, '상하이', 2415000)) c.execute('INSERT INTO cities VALUES(:rank, :city, :pop)', {'rank':2, 'city':'카라치', 'pop':23500000}) c.executemany('INSERT INTO cities VALUES(:rank, :city, :pop)', [ {'rank':3, 'city':'카라치1', 'pop':23500000}, {'rank':4, 'city':'카라치2', 'pop':23500000}, {'rank':5, 'city':'카라치3', 'pop':23500000} ]) # 변경 사항 반영 conn.commit() # 데이터 조회 c.execute("SELECT * FROM cities") for row in c.fetchall(): print(row) # 연결 종료 conn.close()
a4f67a429746bf75d5f71e4e031f5929b2610fb8
ThomasNam-study/py_sample
/scraping/fastcampus/bs_test.py
1,736
3.625
4
from bs4 import BeautifulSoup html = """ <html> <head> <title>The Dormouse's story</title> </head> <body> <h1>this is h1 area</h1> <h2>this is h2 area</h2> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a> <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> <a data-io="link3" href="http://example.com/tillie" class="sister" id="link3">Tillie</a> </p> <p class="story">story...</p> </body> </html> """ # bs4 초기화 soup = BeautifulSoup(html, 'html.parser') # 타입 확인 print('soup', type(soup)) # 코드 정리 print('prettify', soup.prettify()) # h1 태그 접근 h1 = soup.html.body.h1 print('h1', h1) # p 태그 접근 p1 = soup.html.body.p print('p1', p1) # 다음 태그 p2 = p1.next_sibling.next_sibling print('p2', p2) # 텍스트 출력1 print("h1 >> ", h1.string) # 텍스트 출력2 print("p >> ", p1.string) # 함수 확인 print(dir(p2)) # 다음 엘리먼트 확인 print(list(p2.next_elements)) # 반복 출력 확인 # for v in p2.next_elements: # print(v) soup2 = BeautifulSoup(html, 'html.parser') link1 = soup2.find_all('a', limit=2) print('links', link1) # id = "link2", string="title", string=["EEEE"] link2 = soup2.find_all('a', class_='sister') print('links', link2) for t in link2: print(t) # 처음 발견한 a 태그 선택 link3 = soup2.find("a") print() print(link3) # 다중 조건 link4 = soup2.find("a", {"class": "sister", "data-io": "link3"}) print(link4) # css 선택자 # select, select_one link5 = soup2.select_one('p.title > b') print(link5) print(link5.text) link6 = soup2.select_one("a#link1") print(link6)
3f249f1f491ada7e973d8a1cd27a28831d70efd1
ThomasNam-study/py_sample
/conc/0601.py
2,635
3.859375
4
# yield from 사용 t = 'ABCDEF' # For for c in t: print('EX1-1 - ', c) print() # ITer w = iter(t) while True: try: print('EX1-2 - ', next(w)) except StopIteration: break print() from collections import abc # 반복형 확인 print('EX1-3 - ', hasattr(t, '__iter__')) print('EX1-3 - ', isinstance(t, abc.Iterable)) print() print() class WordSplitIter: def __init__(self, text): self._idx = 0 self._text = text.split(' ') def __next__(self): try: word = self._text[self._idx] except IndexError: raise StopIteration() self._idx += 1 return word def __iter__(self): return self def __repr__(self): return 'WorldSplit(%s)' % (self._text,) wi = WordSplitIter('Who says the nights are the sleeping') print('EX2-1', wi) print('EX2-1', next(wi)) print('EX2-2', next(wi)) print('EX2-3', next(wi)) print('EX2-4', next(wi)) print('EX2-5', next(wi)) print('EX2-6', next(wi)) print() print() class WordGene: def __init__(self, text): self._text = text.split(' ') def __iter__(self): for word in self._text: yield word def __repr__(self): return 'WorldSplit(%s)' % (self._text,) wg = WordGene('Who says the nights are the sleeping') wi = iter(wg) print('EX3-1', wi) print('EX3-1', next(wi)) print('EX3-2', next(wi)) print('EX3-3', next(wi)) print('EX3-4', next(wi)) print('EX3-5', next(wi)) print('EX3-6', next(wi)) print() print() def gene_ex1(): print('start') yield 'AAA' print('content') yield 'BBB' print('End') temp = iter(gene_ex1()) # print("EX4-1", next(temp)) # print("EX4-1", next(temp)) # print("EX4-1", next(temp)) for v in gene_ex1(): print('EX4-3', v) temp2 = [x * 3 for x in gene_ex1()] temp3 = (x * 3 for x in gene_ex1()) print('EX-5', temp2) print('EX-5', temp3) for i in temp2: print("EX5-2 - ", i) for i in temp3: print("EX5-3 - ", i) print() print() import itertools gen1 = itertools.count(1, 2.5) print('EX6-1 -', next(gen1)) print('EX6-1 -', next(gen1)) print('EX6-1 -', next(gen1)) gen2 = itertools.takewhile(lambda n: n < 1000, itertools.count(1, 2.5)) for v in gen2: print('ex6-5 - ', v) gen3 = itertools.filterfalse(lambda n: n < 3, [1, 2, 3, 4, 5]) for v in gen3: print('EX6-6 - ', v) gen4 = itertools.accumulate([x for x in range(1, 101)]) for v in gen4: print('EX6-7', v) print() print() gen5 = itertools.chain('ABCDE', range(1, 11, 2)) gen9 = itertools.groupby('AAABBCCCCDDEE') for c, gr in gen9: print('EX6-12 - ', c, ' : ', list(gr))
4e1c5d281b58a5eebc7fdcd951fe98ee2f36a8e7
MFlatley/adventofcode2018
/Day1/Day1.py
633
3.515625
4
inputList = [] fileName = ".\\adventofcode2018\\Day1\\input.txt" def calibrateOutput (input, output): output = output + input return output; def findRepeatedFrequency(providedList): processedList = {0} frequency = 0 while True: for change in providedList: frequency = calibrateOutput(change, frequency) if frequency in processedList: return frequency; else: processedList.add(frequency) file = open(fileName, "r") for line in file: inputList.append(int(line)) file.close(); print(findRepeatedFrequency(inputList))
ba3b8a9489dae42f6164f756dd424f18db07b33d
Shubham07-pawar/Python--Set
/no_common_element.py
290
4.09375
4
# Write a Python program to check if two given sets have no elements in common s1 = {1, 2, 3, 4, 5} s2 = {5, 6, 7, 8} s3 = {9, 10, 11} print(s1.isdisjoint(s2)) print(s1.isdisjoint(s3)) print(s2.isdisjoint(s3)) # return True if none of item present in both sets otherwise False
6bbd6eb8fc67b0d44450332db31d0945a35ea0ef
AveDemid/MITx-6.00.1x
/problems/001-003.py
466
3.5
4
s = 'vwmfkxdz' temp = "" total = "" # TODO refactoring this shit :| for i in range(len(s)-1): if len(temp) == 0: temp = s[i] if temp[-1] <= s[i+1]: temp += s[i+1] if temp == s: total = temp if len(s) == i + 2 and len(temp) > len(total): total = temp else: if len(temp) > len(total): total = temp temp = "" print("Longest substring in alphabetical order is:", total)
a8e6dd677088f55ab8497fdcc435e9191d11e45b
agpmilli/adaepfl
/Homework/04 - Applied ML/aggregater_helper.py
1,606
3.921875
4
""" Helper function to apply reduction for each column of the dataframe grouped by a key. Example of call: grouped_df = original_df.groupby('some_column') aggregating_functions = [ (['column1'], np.mean, (['column2', 'column3'], sum), ([('column_name_new_df', 'column_4_from_original_df'), ('column_name_2_new_df', 'column_5_from_original_df')], np.std) ] #new_df['column1'] = original_df['column1'].apply(np.mean) #new_df['column2'] = original_df['column2'].apply(sum) #new_df['column3'] = original_df['column3'].apply(sum) #new_df['column_name_new_df'] = original_df['column_4_from_original_df'].apply(np.std) #new_df['column_name_2_new_df'] = original_df['column_5_from_original_df'].apply(np.std) reducted_df = aggregate_dyads_to_players(grouped_df, aggregating_functions) @param - df : the dataframe grouped by a key @param - columns_functions: a list of tuples (columns, function_to_apply). If any element in columns is itself a tuple, the function will be applied from a column in the original df, into a new column. Otherwise it is assumed the function in the original df will be applied to the same column name in the resulting df (see example). @return - the new dataframe grouped with reduction functions applied. """ def aggregate_dyads_to_players(df, columns_functions): new_df = df.copy() for columns, function in columns_functions: for column in columns: if(type(column) is tuple): new_df[column[0]] = df[column[1]].apply(function) else: new_df[column] = df[column].apply(function) return new_df
7bae961476f0c48eff4679f17dfbe0d36fe54951
joshroybal/python_numbers
/otp.py
4,206
3.84375
4
#!/usr/bin/env python import sys, random # subprogram encodes checkerboard encodes text to numbers def encode(text): checkerboard = { 'A': 0, 'T': 1, 'O': 3, 'N': 4, 'E': 5, 'S': 7, 'I': 8, 'R': 9, 'B': 20, 'C': 21, 'D': 22, 'F': 23, 'G': 24, 'H': 25, 'J': 26, 'K': 27, 'L': 28, 'M': 29, 'P': 60, 'Q': 61, 'U': 62, 'V': 63, 'W': 64, 'X': 65, 'Y': 66, 'Z': 67, '.': 68 } figures = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ] numbers = [] i = 0 while i < len(text): ch = text[i] if (ch in checkerboard): numbers.append(checkerboard[ch]) elif (ch in figures): numbers.append(69) while (ch in figures): numbers.append(int(ch)) numbers.append(int(ch)) numbers.append(int(ch)) i = i + 1 ch = text[i] numbers.append(69) numbers.append(checkerboard[ch]) i = i + 1 return numbers # subprogram encrypts number encoded plaintext def encrypt(plaintext): numbers = [ int(i) for i in plaintext ] pad = [ random.randint(0, 9) for i in range (len(numbers)) ] ciphertext = [ (x - y) % 10 for x, y in zip(numbers, pad) ] outfile = open('pad.dat', 'w') outfile.write( ''.join(str(n) for n in pad) ) outfile.close() return ciphertext # subprogram decrypts number encoded ciphertext def decrypt(ciphertext): infile = open('pad.dat', 'r') pad = infile.read() infile.close() pad = [ int(i) for i in pad ] numbers = [ int(i) for i in ciphertext ] plaintext = [ (x + y) % 10 for x, y in zip(numbers, pad) ] return plaintext # subprogram decodes number encoded plaintext def decode(digits): checkerboard = { 0: 'A', 1: 'T', 3: 'O', 4: 'N', 5: 'E', 7: 'S', 8: 'I', 9: 'R', 20: 'B', 21: 'C', 22: 'D', 23: 'F', 24: 'G', 25: 'H', 26: 'J', 27: 'K', 28: 'L', 29: 'M', 60: 'P', 61: 'Q', 62: 'U', 63: 'V', 64: 'W', 65: 'X', 66: 'Y', 67: 'Z', 68: '.' } numbers = [] n = 0; while n < len(digits): ch = digits[n] if ch == '2' or ch == '6': tmp = int(digits[n] + digits[n+1]) numbers.append( tmp ) n += 2 #if n >= len(digits): break if tmp == 69: while digits[n] == digits[n+1] == digits[n+2]: numbers.append(int(digits[n])) numbers.append(int(digits[n])) numbers.append(int(digits[n])) n += 3 numbers.append(69) n += 1 else: numbers.append( int(digits[n]) ) n += 1 text = [] n = 0 while n < len(numbers): # print checkerboard[numbers[n]], if numbers[n] == 69: n += 1 while numbers[n] != 69: text.append(str(numbers[n])) n += 3 n += 1 else: text.append(checkerboard[numbers[n]]) n += 1 return text # subprogram prints numbers by groups def print_groups(numbers): digits = ''.join(map(str, numbers)) for n in range(0, len(digits), 5): print digits[n:n+5], if (n + 5) % 25 == 0: print # main program # check no. of command line arguments if (len(sys.argv) < 3): print "Usage: " + sys.argv[0] + " filename encode|encypt|decrypt|decode" sys.exit(1) infile = sys.argv[1] flag = sys.argv[2] # check flag validity if (flag != 'encode' and flag != 'encrypt' and flag != 'decrypt' and flag != 'decode'): print "Usage: " + sys.argv[0] + " encode|encypt|decrypt|decode" sys.exit(1) # read file text = [] filehandle = open(infile, 'r') while True: ch = filehandle.read(1) if not ch: break if ch.isupper() or ch.isdigit() or ch == '.': text.append(ch) elif ch.islower(): text.append(ch.upper()) filehandle.close() # main processing block if flag == 'encode': print_groups(encode(text)) elif flag == 'encrypt': print_groups(encrypt(text)) elif flag == 'decrypt': print_groups(decrypt(text)) elif flag == 'decode': print_groups(decode(text))
60b66dd338dac673c719d3ab1c630711a749ff8f
carlosdiaz723/concepts_assignments
/four/student.py
1,454
3.828125
4
''' Names / Email: Carlos Diaz [email protected] College of Computing and Software Engineering Department of Computer Science --------------------------------------------- CS4308: CONCEPTS OF PROGRAMMING LANGUAGES SECTION W01 – SPRING 2020 --------------------------------------------- Module 4 Assignment 3 File Description: This file contains the Student class which has getters, setters, and a toString function that allows for easy printing of student information. ''' class Student(): ''' Student class definition ''' # constructor def __init__(self, name: str, stuID, numCourses: int): # ensure numCourses is an integer try: numCourses = int(numCourses) except TypeError: assert type(numCourses) == int, "numCourses must be an integer" self.name = name self.stuID = stuID self.numCourses = numCourses # setters def setName(self, newName): self.name = newName def setStuID(self, stuID): self.stuID = stuID def setNumCourses(self, numCourses): self.numCourses = numCourses # getters def getName(self): return self.name def getStuID(self): return self.stuID def getNumCourses(self): return self.numCourses # toString def toString(self): return str(self.name + ", ID: " + self.stuID + ", Number of courses: " + str(self.numCourses))