blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a48f71b6f7b5e6e1e312d2336c949bb0f9f95310
aananya27/Machine-Learning
/Regression/Simple Linear Regression/simple_linear_regression.py
1,225
3.75
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 12 12:13:28 2018 @author: aananya --Simple Linear Regression-- """ #import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values # Split the dataset- (Training and Test) from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) # FitLR to Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting y_pred = regressor.predict(X_test) # Visualising - Trining part plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') #to finish and show the graph: plt.show() # Visualising - Test part plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
1541c8ff123885793a1fba59dbb4c0aee44fe743
cherryzoe/Leetcode
/1120.Maximum Average Subtree.py
813
3.578125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 每次返回两个值,节点个数和节点和 class Solution(object): def maximumAverageSubtree(self, root): """ :type root: TreeNode :rtype: float """ self.res = 0.0 def dfs(root): if not root: return 0,0 l_cnt, l_sum = dfs(root.left) r_cnt, r_sum = dfs(root.right) cur_cnt = 1 + l_cnt + r_cnt cur_sum = root.val + l_sum + r_sum # 分母加浮点数 self.res = max(self.res, cur_sum/float(cur_cnt)) return cur_cnt, cur_sum dfs(root) return self.res
9b3bc4026a1b854f8cd5e29ee72adb35d6cdf057
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc030/A/4925655.py
138
3.515625
4
a, b, c, d = map(int, input().split()) if b/a==d/c: print("DRAW") elif b/a>d/c: print("TAKAHASHI") elif b/a<d/c: print("AOKI")
be9da465e051140e7ebc43719f1c016d64335a01
tarzioo/AnAlgorithmADay2018
/Day-26/maxDepthBinaryTree.py
853
3.765625
4
# Day 26/365 #AnAlgorithmAday2018 # Problem is from Leetcode 104 # # Maximum Depth of Binary Tree # #Given a binary tree, find its maximum depth. # #The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # # # ######################################################################################################################## class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepthBinaryTree(self, root): if not root: return 0 left_depth, right_depth = self.maxDepthBinaryTree(root.left), self.maxDepthBinaryTree(root.right) if left_depth >= right_depth: return left_depth + 1 else: return right_depth + 1
0efcd8cb47311cabfdc2267cdecd419cdd2a58ef
rajeevj0909/FunFiles
/Happy Numbers(3).py
1,246
3.90625
4
print("my names rajeev and im the worst coder i cant even code credit card validation. I will work at nandos forever because i love the discount.") #Turns number into interger lists number=input("What number?") list1=list(number) list2=[] for n in list1: x=int(n) list2.append(x) square=[] total=11 #Runs function def happy(list2,square,total): #If remainder is 1, its happy, it's also the base case if total==1: print(number+" is HAPPY!") #If remainder is between 1 and 10, its sad elif total<10: print(number+" is SAD!") #If the number is bigger than 10, it will shorten to 1 digit else: total=0 print(list2) #Creates a list of squared digits for n in list2: sqrd=n**2 square.append(sqrd) print(square) #Creates a total of the squared digits for n in square: total=total+n print(total) total=str(total) list1=list(total) list2=[] square=[] #Turns it into a integer list again for n in total: x=int(n) list2.append(x) total=int(total) #Recursion to make the total thats larger than 10 smaller happy(list2,square,total) #Runs the function happy(list2,square,total)
0ab426a45a82b61af2b66969e9507b1a25de7aa6
kingsamchen/Eureka
/crack-data-structures-and-algorithms/leetcode/sort_list_q148.py
1,416
4.09375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ return merge_sort_list(head) def merge_sort_list(head): if not head or not head.next: return head slow = fast = head while fast.next and fast.next.next: fast = fast.next.next slow = slow.next # Split into two lists. # Why head2 starts from the next node of mid(slow)? # Assume we have only two nodes, A -> B -> ^ # The strategy we use here eseentially is like floor((l + r) / 2), which # always stucks on A if we make mid the head. # Logically, mid with floor strategy makes it the **last element** of the first part. head2 = slow.next slow.next = None l1 = merge_sort_list(head) l2 = merge_sort_list(head2) return merge_lists(l1, l2) def merge_lists(l1, l2): # Introduce dummy node to simplify merge. # No need to check l1 & l2 up front dummy = ListNode(0) p = dummy while l1 and l2: if l1.val < l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next if l1: p.next = l1 if l2: p.next = l2 return dummy.next
4531ec97ecef67884935f5ee0594e5a7b3c0e785
DhivyaKavidasan/python
/problemset_2/q3.py
322
3.984375
4
''' factorial using recursion and iteration submitted by:dhivya.kavidasan date:03/12/2017 ''' #using iteration def facti(n): fact=1 for i in range(1,n+1): fact=fact*i return fact print facti(4) #using recursion def factr(n): if n==1: return 1 else: return n*factr(n-1) print factr(4)
21f32c84af6cd091168e7fcc76545b23aee7becc
KarlaDiass/AulaEntra21_Karla
/atividades_aula_07_10/Exercicio03.py
991
3.78125
4
#--- Exercício 3 - Variáveis #--- Imprima dois parágrafos do último livro que você leu #--- A impressão deve conter informações do livro, que deverão estar em variáveis #--- As informações do Livro serão: #--- Título #--- Edição #--- Autor #--- Data de publicação #--- Os parágrafos devem estar formatados conforme a formatação do livro par1 = '''Eu podia muito bem ter perguntado: eu também mudo completamente dessa maneira? Não fomos escritos para um único instrumento; eu não fui, nem você.''' par2 = '''O que fui incapaz de identificar nessa promessa é que a frieza e a apatia encontram um jeito de anular imediatamente quaisquer tréguas e resoluções assinadas em momentos ensolarados.''' info = {'Título':'Me chame pelo seu nome', 'Edicao':'Digital 2018', 'Autor': 'André Aciman', 'Data de publicação':'18 de janeiro de 2018'} print('\n') for chave, valor in info.items(): print(chave, '-', valor) print('\n\t{}\n\t{}'.format(par1,par2))
7e27ef097ea138a84cbaad07895f2410aec4547e
1000monkeys/probable-invention
/9/3/user.py
497
3.734375
4
class User: def __init__(self, first_name, last_name, username, date_of_birth): self.first_name = first_name self.last_name = last_name self.username = username self.date_of_birth = date_of_birth def describe_user(self): print(self.first_name + " " + self.last_name) print("Goes by " + self.username) print("Born on " + self.date_of_birth) def greet_user(self): print("Hello " + self.first_name + " " + self.last_name)
d7431b548cb1ad3f91bc8e35219181a1e9b86f67
thaitribao/Cipher_Scripts
/Enigma/Enigma.py
3,976
3.796875
4
""" Enigma Cipher program Encipher a text file using Enigma Cipher Number of rotors can be specified Rotors can be used in different positions ++Date created: 12/21/2016 ++Author: Bao Thai - btt4530@g.rit.edu """ from RotorBox import ROTORS from MirrorBox import MIRRORS from sys import argv #Array holding alphabet letters ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] #print(ROTORS[1][ALPHABET.index("A")]) #print(MIRRORS[0][1]) """ Find the input to a rotor that gives the specified output Param: rotor: investigated rotor shift: shift of said rotor (0-26) output: output to find the input Output: The input that gives the specified output (inverse function) """ def findInput(rotor,shift,output): current_rotor = rotor count = 0 while count < len(rotor): pos = (count + shift)%26 #which shift are being used out_check = (count + rotor[pos])%26 #output of current count if out_check < 0: out_check = 26 + out_check if out_check == output: return count count = count + 1 """ Encode a line using Enigma Param: num_rotor: how many rotors are used carry_num """ def encodeEnigma(num_rotor,lines): #Variable declaration arr_result = [] rotors = [] #rotors placed in the machine arr_shifts = [] #shift for each rotor arr_modulo = [] #get the modulo for your rotors num = 0 #general counter variable mirror = MIRRORS[0] #mirror to be placed in machine #Getting user's setup while num < num_rotor: string_1 = "Select a rotor from 0 to " + str(len(ROTORS)-1) + " for Rotor #" + str(num+1) + ":>" rotor = int(input(string_1)) rotors.append(ROTORS[rotor]) string_2 = "Init shift of Rotor #" + str(num+1) + ":>" shift = int(input(string_2)) arr_shifts.append(shift) #Set up the modulo in fibonacci sequence ;) if num == 0: arr_modulo.append(1) if num == 1: arr_modulo.append(2) if num > 1: arr_modulo.append(arr_modulo[num-1] + arr_modulo[num-2]) num = num + 1 num = 0 line_count = 0 while line_count < len(lines): text = lines[line_count] #***************# result = "" plain_text = text plain_text = plain_text.upper() for char in plain_text: if char.isalpha(): print(char) encoded_num = ALPHABET.index(char) rotor_count = 0 #encode through rotor while rotor_count < len(rotors): rotor = rotors[rotor_count] #get the rotor shift = (arr_shifts[rotor_count] + encoded_num)%26 #get the corresponding shift encoded_num = (encoded_num + rotor[shift])%26 if encoded_num < 0: encoded_num = 26 + encoded_num rotor_count = rotor_count+1 print("Encode: "+ALPHABET[encoded_num]) #encode mirror encoded_num = mirror[(encoded_num)%26] print("Mirror: "+ALPHABET[encoded_num]) #going up the rotors idea: use index of, be very careful of shifts rotor_count = len(rotors) - 1 while rotor_count >= 0: rotor = rotors[rotor_count] #get the rotor encoded_num = findInput(rotor,arr_shifts[rotor_count],encoded_num) rotor_count = rotor_count - 1 print("Up: "+ALPHABET[encoded_num]) char = ALPHABET[encoded_num] #Set the shifts for the rotors for next char rotor_count = 0 while rotor_count < len(arr_shifts): if num % arr_modulo[rotor_count] == 0: arr_shifts[rotor_count] = (arr_shifts[rotor_count] + 1)%26 rotor_count = rotor_count+1 print(arr_shifts) num = num + 1 result += char arr_result.append(result) line_count = line_count + 1 return arr_result def main(): script, plain_file, encoded_file, num_rotor = argv plain = open(plain_file,"r") encoded = open(encoded_file,"w+") rotor_count = int(num_rotor) input_lines = [] output_lines = [] for line in plain: input_lines.append(line) output_lines = encodeEnigma(rotor_count,input_lines) for line in output_lines: encoded.write(line) plain.close() encoded.close() print("Done!") if __name__ == '__main__': main()
a9ea004f288f0671975b12d9c8a061f82fb179bd
Wedrew/Misc
/sets.py
2,435
3.765625
4
import itertools #Here I define my functions that compute the different subsets def permWithRep(seq): for x in range(1,len(string)+1): for p in itertools.product(seq, repeat=x): print("{"+",".join(p)+"}") def permWithoutRep(seq): for x in range(1,len(string)+1): for p in itertools.permutations(seq, x): print("{"+",".join(p)+"}") def combWithRep(seq): for x in range(1,len(string)+1): for p in itertools.combinations_with_replacement(seq, x): print("{"+",".join(p)+"}") def combWithoutRep(seq): for x in range(1,len(string)+1): for p in itertools.combinations(seq, x): print("{"+",".join(p)+"}") def powerSet(seq): print("∅") for x in range(1,len(string)+1): for p in itertools.combinations(seq, x): print("{"+",".join(p)+"}") def isUnique(s): return len(set(s)) == len(s) #Start program and display information print("This program returns the subsets of a given set") exit1 = False exit2 = False exit3 = False #Get user input and exit iff the set passes while exit1 != True: string = input("Enter at least 3 and at most 5 unique elements that are lower case: ") if(string.isalpha() and string.islower() and isUnique(string) and len(string) >= 3 and len(string) <= 5): print("Set intitialized") exit1 = True else: if(string.isalpha() != True): print("Make sure all elements are letters") elif(string.islower() != True): print("Make sure all elements are lower case") elif(isUnique(string) != True): print("Make sure all elements are unique") elif(len(string) <= 3): print("Make sure you have 3 or more elements") elif(len(string) >= 5): print("Make sure you have 5 or fewer elements") #Determine which type of set to display while exit2 != True: repetition = input("Is repetition allowed? y/n: ") order = input("Does order matter? y/n: ") if(repetition == 'y' and order == 'y'): permWithRep(string) exit2 = True elif(repetition == 'n' and order == 'y'): permWithoutRep(string) exit2 = True elif(repetition == 'y' and order == 'n'): combWithRep(string) exit2 = True elif(repetition == 'n' and order == 'n'): combWithoutRep(string) exit2 = True else: print("Incorrect entry") #Determine whether to display power set or not while exit3 != True: powSet = input("Would you like to print the power set? y/n: ") if(powSet == 'y'): powerSet(string) exit3 = True elif(powSet == 'n'): exit3 = True else: print("Incorrect entry")
f079cc4a507796265829ecf370599a690394e8da
Joker-Jerome/leetcode
/863_All_Nodes_Distance_K_in_Binary_Tree.py
3,241
4.03125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(): def distanceK(self, root, target, K): conn = collections.defaultdict(list) def connect(parent, child): # both parent and child are not empty if parent and child: # building an undirected graph representation, assign the # child value for the parent as the key and vice versa conn[parent.val].append(child.val) conn[child.val].append(parent.val) # in-order traversal if child.left: connect(child, child.left) if child.right: connect(child, child.right) # the initial parent node of the root is None connect(None, root) # start the breadth-first search from the target, hence the starting level is 0 bfs = [target.val] seen = set(bfs) # all nodes at (k-1)th level must also be K steps away from the target node for i in range(K): # expand the list comprehension to strip away the complexity new_level = [] for q_node_val in bfs: for connected_node_val in conn[q_node_val]: if connected_node_val not in seen: new_level.append(connected_node_val) bfs = new_level # add all the values in bfs into seen seen |= set(bfs) return bfs import collections # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(): def distanceK(self, root, target, K): # check the input if not root or not target: return [] # init graph = collections.defaultdict(list) # dfs function def conn(parent, child): # in-order travasel if parent and child: graph[parent.val].append(child.val) graph[child.val].append(parent.val) # child trees if child.left: conn(child, child.left) if child.right: conn(child, child.right) # run the dfs and build the graph conn(None, root) # bfs for k steps visited = set() queue = collections.deque() tmp_queue = collections.deque() res = [] # main loop queue.append(target.val) tmp_queue.append(target.val) visited.add(target.val) for i in range(K): queue = tmp_queue tmp_queue = collections.deque() while queue: cur_node = queue.popleft() #print(cur_node) for neighbor in graph[cur_node]: if neighbor not in visited: #print(neighbor) tmp_queue.append(neighbor) visited.add(neighbor) return list(tmp_queue)
f72e44302386d9b4f5b66876fb6ae9c16f7ba285
meghamarwah/Python-Practice
/Exceptionhandling/exception_practice.py
1,210
4.1875
4
import math #Q.1 Handle the exception thrown by the code below by using try and except blocks. #for i in ['a','b','c']: # print(i**2) def listnum(): try: for i in ['a','b','c']: print(i**2) except TypeError: print("You are making a square of alphabets.") finally: print('Thanks') #Q.2 Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.' # x = 5 # y = 0 # z = x/y def div(): x = 5 y = 0 try: z = x/y print(z) except ZeroDivisionError: print("can't divide") finally: print("Thanks for trying") #Q.3 Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs. def numsquare(): while True: try: num = int(input("Enter a valid number--> ")) except: print("Plase check again this is not a valid format.") continue else: print("square of num-",int(math.pow(num,2))) break finally: print("Thanks") if __name__ == '__main__': div()
a57e09f3f16da927f0074791988e078140af9c5d
marcomereu2015/Hackerrank
/quartiles.py
760
3.96875
4
Day 1. Quartiles num = int(raw_input()) numbers = sorted(map(int, raw_input().split())) center = len(numbers) // 2 # floor division def median(median_numbers): #return np.median(median_numbers) # will work if numpy import is allowed middle = len(median_numbers) // 2 # floor division if (len(median_numbers) % 2 == 0): # even or odd return (median_numbers[middle-1] + median_numbers[middle]) / 2 else: return median_numbers[middle] # actual program starts here if (len(numbers) % 2 == 0): # even or not L = median(numbers[:center]) R = median(numbers[center:]) else: # if odd set of numbers L = median(numbers[:center]) R = median(numbers[center+1:]) print L print median(numbers) print R
906bb39c3571081fa4806dfb87d7fb939b635a64
jinliangXX/LeetCode
/128. Longest Consecutive Sequence/solution.py
2,124
3.546875
4
from typing import List class Solution: def longestConsecutive(self, nums: List[int]) -> int: result = 0 map_dict = dict() for num in nums: if num not in map_dict: left = map_dict.get(num - 1, 0) right = map_dict.get(num + 1, 0) now = left + 1 + right if now > result: result = now map_dict[num] = now # 必须要有,去重 map_dict[num - left] = now map_dict[num + right] = now return result # from typing import List # # # class Node: # def __init__(self, val=0, next=None, previous=None): # self.val = val # self.next = next # self.previous = previous # # # class Solution: # def longestConsecutive(self, nums: List[int]) -> int: # map_num = dict() # root = Node() # now = root # for num in nums: # node = Node(num, None, now) # map_num[num] = node # now.next = node # now = node # result = 0 # root = root.next # while root is not None: # num = root.val # now_result = 1 # left = num - 1 # right = num + 1 # while left in map_num: # now_result += 1 # node = map_num[left] # # 在链表中删除节点 # a = node.previous # b = node.next # a.next = b # if b is not None: # b.previous = a # left -= 1 # while right in map_num: # now_result += 1 # # node = map_num[right] # # 在链表中删除节点 # a = node.previous # b = node.next # a.next = b # if b is not None: # b.previous = a # right += 1 # if now_result > result: # result = now_result # root = root.next # return result
0d221724b32a1d6c7df09580b587a9ceed32ef61
Leeeeoooouuhhh/TIC_20_21
/Suma_Gauss3.py
301
3.859375
4
def suma_gauss_3(): n_final=input("Introduce hasta que numero ") suma_acumulada=0 for cont in range(1,n_final+1): if(cont%2==0): suma_acumulada=suma_acumulada+cont print"suma_acumulada= ",suma_acumulada suma_gauss_3()
bddfd338a92d4aaa4c2db61d845bab0590b860a7
itsolutionscorp/AutoStyle-Clustering
/intervention/results/control_111904_1447992871_525_11.19.py
224
3.765625
4
def num_common_letters(goal_word, guess): goal_word = list(goal_word) guess = list(guess) common = [] for char in guess: if char in goal_word and char not in common: common += [char] return len(common)
bf7a27149b373ef6bd0d574818e22aca11d0cd5b
dheista/pythonPi
/threadpi.py
1,323
3.546875
4
#!/usr/bin/env python3 import argparse import math import threading def calc_pi(start: int, end: int) -> float: numerator: float = 4.0 denominator: float = start * 2 + 1 operation: float = 1.0 if start % 2 == 0 else -1.0 pi: float = 0.0 for i in range(start, end): pi += operation * (numerator / denominator) denominator += 2.0 operation *= -1.0 return pi if __name__ == "__main__": # Parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("--n_terms", type=int, default=100000, help="Number of terms to use in the calculation of pi") parser.add_argument("--n_threads", type=int, default=4, help="Number of threads to use in the calculation") args = parser.parse_args() # Calculate pi using multiple threads terms_per_thread = args.n_terms // args.n_threads threads = [] for i in range(args.n_threads): start = i * terms_per_thread end = (i + 1) * terms_per_thread thread = threading.Thread(target=calc_pi, args=(start, end)) thread.start() threads.append(thread) # Wait for all threads to complete for thread in threads: thread.join() # Calculate and print the final value of pi pi = sum(thread.result for thread in threads) print(pi)
a125d483ca769c692834674f4aa50b080babcf7a
mdkdoc15/trial-with-vs-code
/TicTacToe/main.py
3,108
3.890625
4
#Two player game finished import os #used to clear screen board = ['-','-','-', '-','-','-', '-','-','-'] #empty game baord def display_board(): os.system('clear')#used to clear the screen when drawing a new board print(board[0] + ' | ' + board[1] + ' | ' + board[2]) print(board[3] + ' | ' + board[4] + ' | ' + board[5]) print(board[6] + ' | ' + board[7] + ' | ' + board[8]) def isValidMove(pos): try: if (int(pos) > 9 or int(pos) < 1): print("Number not allowed (Too Big/Small)") return False elif (board[int(pos)-1] != '-'): print("Space already taken, try again!") return False else: return True except: print("Invalid input! Try again!") def handle_turn(player): while True: position = input("Choose a position from 1-9: ") if(player): #Will alternate players based on the state of the boolean 'player' if(isValidMove(position)): board[int(position)-1] = 'X' break else: if(isValidMove(position)): board[int(position)-1] = 'O' break def check_col(): #find better way to do this if(((board[0] == board[3] == board[6])) and board[0] != '-'): display_board() print(board[0] + "'s won the game!") return True if((board[1] == board[4] == board[7])and board[1] != '-'): display_board() print(board[1] + "'s won the game!") return True if((board[2] == board[5] == board[8]) and board[2] != '-'): display_board() print(board[2] + "'s won the game!") return True return False def check_row(): #find better way to do this if(board[0] == board[1] == board[2] != '-'): display_board() print(board[0] + "'s won the game!") return True if(board[3] == board[4] == board[5] != '-'): display_board() print(board[3] + "'s won the game!") return True if(board[6] == board[7] == board[8] != '-'): display_board() print(board[6] + "'s won the game!") return True return False def check_diag(): if(board[0] == board[4] == board[8] != '-'): display_board() print(board[0] + "'s won the game!") return True if(board[3] == board[4] == board[6]!= '-'): display_board() print(board[3] + "'s won the game!") return True return False def check_tie(): for i in board: if(i == '-'): return False display_board() print("Tie game!") return True def check_win(): return check_diag() or check_col() or check_row() or check_tie() def play_game(): game_over = False player = True #true players are X, false are O's while(not game_over): display_board() #print the board at the start of each turn handle_turn(player) player = not player # move to next persons turn game_over = check_win() #determines if we need to exit the loop play_game()
e457d23665d1b7b34425c51f004d6a6b48aa7a59
felipmarqs/CursoEmVideoPython
/Desafios refeitos/Desafio 34.py
563
3.921875
4
#Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. #Para salários superiores a R$ 1.250,00, calcule um aumento de 10%. #Para inferiores ou iguais, o aumento é de 15%. salário = float(input('Qual é o seu salário?')) if salário > 1250.00: a = salário + (salário*0.10) print('Seu salário era de {:.2f} e com um aumento de 10% ficará {:.2f}'.format(salário,a)) else: b = salário + (salário*0.15) print('Seu salário era de {:.2f} e com um aumento de 15% ficará {:.2f}'.format(salário,b))
2858d6829b536ea5ea00aaac9d7127e600864be9
huyhieu07/nguyenhuyhieu-c4e-16-labs-
/lab03/ex09.py
171
3.65625
4
def get_even_list(list): list02 = [] for i in range(len(list)): if list[i] % 2 == 0: list02.append(list[i]) list = list02 return(list)
4198fd59b45a7754426f4b5b631e9f3166768b9d
Gabrielcarvfer/Introducao-a-Ciencia-da-Computacao-UnB
/aulas/aula3/1.py
171
4.15625
4
x = int(input("Digite um numero inteiro")) soma = 0 while x > -5: soma = soma + x x = int(input("Digite um inteiro")) print("Soma dos números: ", soma)
89d666364e68b3c1bcf4c2f94e33102bb2bb69f6
Dharian/GestorConstrase-aPython
/main.py
2,356
3.53125
4
import tkinter as tk import tkinter.font as tkFont class MainMenu: def __init__(self): #Se crea la ventana self.mainWindow = tk.Tk() self.mainWindow.title("Login") self.mainWindow.geometry("360x240") self.mainWindow.resizable(0,0) self.mainWindow.configure(bg="#36393f") self.customFont=tkFont.Font(family="Uni Sans Heavy",weight="bold") self.customFont2 = tkFont.Font(family="Uni Sans") # Se crea el cuadro de ID y pass. self.login = tk.LabelFrame(self.mainWindow, text="Login:",bg="#36393f",fg="Dim Gray",font=self.customFont) self.login.grid(column=0, row=0, padx=5, pady=10) #Se crea el cuadro añadir usuario. self.registro = tk.LabelFrame(self.mainWindow, text="¿No tienes usuario?",bg="#36393f",fg="Dim Gray", font=self.customFont) self.registro.grid(column=0, row=1, padx=8, pady=10) #Se crea el campo ID self.ID=tk.Label(self.login,text=" Nombre de usuario: ",bg="#36393f",fg="white", font=self.customFont2) self.ID.grid(column=0,row=0,padx=4,pady=4) self.ID_Valor=tk.Entry(self.login) self.ID_Valor.grid(column=1, row=0, padx=4, pady=4) #Se crea el campo Pass self.Password = tk.Label(self.login, text=" Contraseña: ",bg="#36393f",fg="white", font=self.customFont2) self.Password.grid(column=0, row=1, padx=4, pady=4) self.Password_Valor = tk.Entry(self.login, show="*") self.Password_Valor.grid(column=1, row=1, padx=4, pady=4) #Se crea el Boton entrar self.Entrar_button= tk.Button(self.login, text="Entrar",bg="#36393f",fg="white", font=self.customFont2, commamd=self.validate(self.ID_Valor.get(), self.Password_Valor.get())) self.Entrar_button.grid(column=1, row=2, padx=4, pady=10) #Se crea el boton agregar Usuario self.addUser= tk.Button(self.registro, text=" Registrate! ",bg="#36393f",fg="white", font=self.customFont2) self.addUser.grid(column=0, row=2, padx=8, pady=8,ipadx=85) self.mainWindow.mainloop() def validate(self, id, password): self.id=id self.password=password gestor = MainMenu()
b54f4cadb9e4c6a717eb2a2ad4a83c69429ace0c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2722/60747/244871.py
220
3.875
4
n=int(input()) result=[] for i in range(n): num=input() if num[len(num)-1]=='5'or num[len(num)-1]=='0': result.append("YES") else: result.append("NO") for i in range(len(result)): print(result[i])
3d8d57cad3af59f1db0e905ad02a3a6c91ba963d
srmcnutt/100DaysOfCode
/d19-turtle_games/etch-a-sketch.py
622
3.515625
4
from turtle import Turtle, Screen tim = Turtle() tim.speed("fastest") screen = Screen() def left(): new_heading = tim.heading() + 10 tim.setheading(new_heading) def right(): new_heading = tim.heading() - 10 tim.setheading(new_heading) def forward(): tim.forward(10) def backward(): tim.backward(10) def clear(): tim.clear() tim.penup() tim.home() tim.pendown() screen.listen() screen.onkey(fun=forward, key="w") screen.onkey(fun=backward, key="s") screen.onkey(fun=left, key="a") screen.onkey(fun=right, key="d") screen.onkey(fun=clear, key="c") screen.exitonclick()
858d7748ee0159ff7121adc5fd274c28e900d2c3
steven-terrana/advent-of-code
/2021/day15/part_two.py
2,402
3.640625
4
import networkx as nx from termcolor import colored import itertools import math # build a directional graph where: # nodes: # are tuple coordinates such as (0,0) # edges: # - risk scores determined calculating the larger # grids values on demand, rather than actually # creating it # - edge from node A to node B with weight equal # to the risk score of node B # - edge from node B to node A with weight equal # to the risk score of node A def build_graph(grid, multiplier): n = len(grid) graph = nx.DiGraph() nodes = itertools.product(range(multiplier * n),repeat=2) graph.add_nodes_from(nodes) # Define the relative coordinates for neighbors # up down left right neighbors = [ (-1, 0), (1, 0), (0, 1), (0, -1) ] for node in nx.nodes(graph): (r, c) = node for n in neighbors: r_b = r + n[0] c_b = c + n[1] node_b = (r_b, c_b) if graph.has_node(node_b): weight = calculate_weight(grid, r_b, c_b) graph.add_edge(node, node_b, weight=weight) return graph # creating the larger grid based on the puzzle # input seems harder than just calculating what # value an arbitrary position would have based # on the original grid def calculate_weight(grid, r, c): # calculate R and C, which are the row # and column indices of the _tile_ we'd # be in based on the input coordinates # of r and c n = len(grid) R = int(math.floor(r / n)) # C = int(math.floor(c / n)) # get the original weight in the og tile weight = grid[ r % n ][ c % n ] # calculate the addition to the risk # score based on tile position x = R + C for i in range(x): weight += 1 if weight > 9: weight = 1 return weight # for debugging: # print the grid while highlighting # the shortest path def print_path(grid, path): for r, row in enumerate(grid): for c in range(len(row)): if (r, c) in path: print(colored(grid[r][c], 'red', attrs=['bold']), end=' ') else: print(grid[r][c], end=' ') print("") grid = [[ int(x) for x in list(line.strip()) ] for line in open("2021/day15/input.txt", "r").readlines() ] multiplier = 5 graph = build_graph(grid, multiplier) start = (0,0) end = (multiplier*len(grid)-1, multiplier*len(grid[0])-1) length = nx.shortest_path_length(graph, source=start, target=end, weight="weight") print(length)
94bc9ca1ca07e8ee47e52a2873b47c8f6284bbf5
schiao/classcode
/lib/hydrostat.py
3,156
3.625
4
#updated 2012/10/14 to change num_layers to num_levels import numpy as np import matplotlib.pyplot as plt def hydrostat(T_surf,p_surf,dT_dz,delta_z,num_levels): """ build a hydrostatic atmosphere by integrating the hydrostatic equation from the surface, using num_layers=num_levels-1 of constant thickness delta_z input: T_surf -- surface temperature in K p_surf -- surface pressure in Pa dT_dz -- constant rate of temperature change with height in K/m delta_z -- layer thickness in m num_levels -- number of levels in the atmosphere output: numpy arrays: Temp (K) , press (Pa), rho (kg/m^3), height (m) """ Rd=287. #J/kg/K -- gas constant for dry air g=9.8 #m/s^2 Temp=np.empty([num_levels]) press=np.empty_like(Temp) rho=np.empty_like(Temp) height=np.empty_like(Temp) num_layers=num_levels-1 # # layer 0 sits directly above the surface, so start # with pressure, temp of air equal to ground temp, press # and get density from equaiton of state # press[0]=p_surf Temp[0]=T_surf rho[0]=p_surf/(Rd*T_surf) height[0]=0 # #now march up the atmosphere a layer at a time #using the hydrostatic equation from the Beer's law notes # for i in range(num_layers): delP= -rho[i]*g*delta_z height[i+1] = height[i] + delta_z Temp[i+1] = Temp[i] + dT_dz*delta_z press[i+1]= press[i] + delP rho[i+1]=press[i+1]/(Rd*Temp[i+1]) return (Temp,press,rho,height) def find_tau(r_gas,k_lambda,rho,height): """ input: r_gas -- gas mixing ratio in kg/kg k_lambda -- mass absorption coefficient in kg/m^2 rho -- vector of air densities in kg/m^3 height -- corresponding level heights in m output: tau -- vetical optical depth from the surface, same shape as rho """ print r_gas,k_lambda tau=np.empty_like(rho) tau[0]=0 num_levels=len(rho) num_layers=num_levels-1 # # see Wallace and Hobbs equation 4.32 # for index in range(num_layers): delta_z=height[index+1] - height[index] delta_tau=r_gas*rho[index]*k_lambda*delta_z tau[index+1]=tau[index] + delta_tau return tau if __name__=="__main__": r_gas=0.01 #kg/kg k_lambda=0.01 #m^2/kg T_surf=300 #K p_surf=100.e3 #Pa dT_dz = -7.e-3 #K/km delta_z=1 num_levels=15000 Temp,press,rho,height=hydrostat(T_surf,p_surf,dT_dz,delta_z,num_levels) tau=find_tau(r_gas,k_lambda,rho,height) fig1,axis1=plt.subplots(1,1) axis1.plot(tau,height*1.e-3) axis1.set_title('vertical optical depth vs. height') axis1.set_ylabel('height (km)') axis1.set_xlabel('optical depth (no units)') fig2,axis2=plt.subplots(1,1) axis2.plot(tau,press*1.e-3) axis2.invert_yaxis() axis2.set_title('vertical optical depth vs. pressure') axis2.set_ylabel('pressure (kPa)') axis2.set_xlabel('optical depth (no units)') plt.show() #
e834b4787a8e0427e632bfb8f2ed2a074ccc6176
MattTheGoth/morse-code
/morse_1_3.py
3,244
3.546875
4
# morse_code.py # A program to translate English input into morse code and output the contents # to a file called morse_out.txt in the same directory. # Coded by Matthew Plummer September 2016 # Version 1.2 filename = 'morse_out.txt' f = open(filename, 'a') eng_morse = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '.': '.-.-.-', ',': '--..--', '?': '..--..', "'": '.----.', '!': '-.-.--', '/': '-..-.', ':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.', '@': '.--.-.'} morse_eng = {'-...': 'b', '-.-.': 'c', '.----.': "'", '.--.': 'p', '--.-': 'q', '..--.-': '_', '----.': '9', '--': 'm', '-.-': 'k', '..-.': 'f', '.---': 'j', '-....-': '-', '...-': 'v', '--...': '7', '.-..': 'l', '-.': 'n', '---..': '8', '.': 'e', '-..-': 'x', '-..-.': '/', '.----': '1', '.--': 'w', '.-..-.': '"', '--..--': ',', '.--.-.': '@', '--.': 'g', '-...-': '=', '.-.-.-': '.', '...--': '3', '.....': '5', '....': 'h', '..--..': '?', '....-': '4', '.-.-.': '+', '-.-.-.': ';', '--..': 'z', '-----': '0', '.-.': 'r', '..---': '2', '---': 'o', '..-': 'u', '..': 'i', '-': 't', '-.-.--': '!', '-..': 'd', '-.--': 'y', '-....': '6', '---...': ':', '.-': 'a', '...': 's', '/': ' '} print("Type 'quit' to quit.") def eng2morse(): """ A function to translate alphanumeric input into morse code.""" try: text = input('What do you want to convert to morse code?: ') out = [] characters = list(text.lower()) for c in characters: if c == ' ': out.append('/') else: m = eng_morse[c] out.append(m) out.append(' ') s = ''.join(out) f.write('\n' + text + '\n' + s) print(text, '\n', s) except KeyError: pass def morse2eng(): """ A function to translate morse code input into alpha-numeric characters. """ try: morse = input('What do you want to translate from morse code? ') characters = morse.split() out = [] for c in characters: e = morse_eng[c] out.append(e) s = ''.join(out) print(s) except KeyError: pass #~ def choose_function: #~ print(" print("To translate from alpha-numeric to morse code please type 'translate'") print("\nTo interpret morse code into alpha-numeric characters, " "please type 'interpret'") print("\nType 'quit' to exit.") while True: choice = input() if choice == 'quit': break elif choice == 'translate': while True: eng2morse() elif choice == 'interpret': morse2eng()
9193ec1ebe1637efe92714b8e7b1f2abbe763e8e
ChihChaoChang/Lintcode
/Validate_Binary_Search_Tree.py
1,436
4.25
4
``` Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. A single node tree is a BST Example An example: 2 / \ 1 4 / \ 3 5 The above binary tree is serialized as {2,1,4,#,#,3,5} (in level order). ``` """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: root: The root of binary tree. @return: True if the binary tree is BST, or false """ def isValidBST(self, root): # write your code here self.isBST = True self.lastVal = None self.validate(root) return self.isBST def validate(self, root): if root is None: return self.validate(root.left) if (self.lastVal is not None and self.lastVal >= root.val): self.isBST = False return self.lastVal = root.val self.validate(root.right)
c4b57575767e0e66f330522b4d1175baa7b31ea9
printfoo/leetcode-python
/problems/0028/strstr.py
497
3.734375
4
""" Solution for Implement strStr(), O(n). Idea: """ class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ hlen, nlen = len(haystack), len(needle) for i in range(hlen - nlen + 1): if haystack[i : i + nlen] == needle: return i return -1 # Main. if __name__ == "__main__": haystack = "hello" needle = "" print(Solution().strStr(haystack, needle))
cd4c43a62359f351aab32b74dafeed8a87948eb8
foxtreme/acamica_advanced_python
/containers.py
2,752
3.53125
4
import csv class PurchasedItem(object): counter = 0 def __init__( self, id, account, purchased_quantity, name, quantity, unit, price, category ): PurchasedItem.counter += 1 self.id = id self.account = account self.purchased_quantity = purchased_quantity self.name = name self.quantity = quantity self.unit = unit self.price = price self.category = category def subtotal(self): return self.purchased_quantity * self.price def change_price(self, price): self.price = price def __repr__(self): return "PurchasedItem("+str(self.__dict__)+")" def read_shopping_data(filename): """ Buils a list of rows from a csv file :param filename: string, the file name :return: list, the list of PurchasedItems objects """ data = [] with open(filename) as f: rows = csv.reader(f) next(f) for row in rows: row[2] = int(row[2]) row[6] = float(row[6]) item = PurchasedItem( row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7] ) data.append(item) return data class ShoppingCart(object): def __init__(self): self.items = [] @classmethod def from_csv(cls, filename): self = cls() with open(filename) as f: rows = csv.reader(f) next(rows) for row in rows: row[2] = int(row[2]) row[6] = float(row[6]) obj = PurchasedItem( row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7] ) self.items.append(obj) return self def total(self): return sum([item.purchased_quantity * item.price for item in self.items]) def __repr__(self): return "\n".join([str(item.__dict__) for item in self.items]) def __len__(self): return len(self.items) def __getitem__(self, index): if isinstance(index, str): filtered_items = [item for item in self.items if index in item.name.lower()] new_cart = self.__class__() new_cart.items = filtered_items return new_cart else: return self.items[index] def __iter__(self): return self.items.__iter__()
7beb3223511054fade06339409574e2443ca0424
MariaJoseOrtiz/MasterPython
/07-Ejercicios/ejercicio2.py
326
3.96875
4
""" Ejericio 2 Escribir un script que nos muestre por pantalla todos los numeros pares del 1 al 120 """ numero = 1 # con while while numero <=120: numero_par = numero % 2 if numero_par == 0 : print(numero) numero+=1 # con for for contador in range(1,121): if contador % 2 == 0: print(contador)
0075807416ce9576b83147992369f083f52358d5
charlieRode/data-structures
/graph.py
1,181
3.9375
4
#!/usr/bin/env python class Edge(object): def __init__(self, node1, node2): # For now, this is an unordered set since our edges have no direction # and hence (n1, n2) will be counted the same as (n2, n1) self.connects = set((node1, node2)) class Graph(object): def __init__(self): self._edges = set() self._nodes = set() def nodes(self): return self._nodes def edges(self): return [edge.connects for edge in self._edges] def add_node(self, data): self._nodes.add(data) return def add_edge(self, data1, data2): self._nodes.add(data1) self._nodes.add(data2) edge = Edge(data1, data2) self._edges.add(edge) return def delete_node(self, data): try: self._nodes.pop() except KeyError: raise IndexError('graph is empty') else: # Must use temp set. Can't change set size during iteration _temp = set() for edge in self._edges: if data not in edge.connects: _temp.add(edge) self._edges = _temp return
5e46ba1884466d68c0c0b007333cc6e07127bcf6
IbrahimDaurenov/Incoop-cohort-1
/Week 2/Day 5 (July 22)/recursion.py
253
3.921875
4
def fibbo(n): if (n==1 or n==2): return 1 else: return ( fibbo(n-1) + fibbo(n-2) ) print(fibbo(1)) print(fibbo(2)) print(fibbo(3)) print(fibbo(4)) print(fibbo(5)) print(fibbo(6)) print(fibbo(7)) print(fibbo(8)) print(fibbo(9))
17d86ba40e752530fda4f4a3d3d37f22b85e80aa
utaipeics/UT-Lang-Automata2018
/TuringMachines/tape.py
965
3.96875
4
# -*- encoding: utf-8 -*- from enum import IntEnum class Direction(IntEnum): LEFT = 0 RIGHT = 1 class Tape: """ A Turing Machine's tape. Each of the left/right ends will be padded with a character 'd' (empty symbol) """ def __init__(self, content: str): self.content = 'd{}d'.format(content) self.rw_head_pos = 1 def read(self): """ Read the character from the cell on the rw_head """ return self.content[self.rw_head_pos] def write(self, c): """ Write the character to the cell on the rw_head """ self.content = self.content[:self.rw_head_pos] + c + self.content[(self.rw_head_pos+1):] def move_head(self, direction): """ Move the read write head of the tape in the specified direction :param direction: Left: 0, Right: 1 """ self.rw_head_pos += (1 if direction == Direction.RIGHT else -1) def __str__(self): return self.content
6b19d3756c5b7387bdd2e39783890d3e7106f980
chaitrabhoomesh55/CA2020
/A4/A4.file4.py
330
4.375
4
# 4. Write a program that accepts a hyphen-separated sequence of words # as input and prints the words in a hyphen-separated sequence after sorting them alphabetically. def sort_list(h): items= [n for n in h.split('-')] items.sort() print('-'.join(items)) h = input("enter hyphen seaparated values:") sort_list(h)
9c37ee382802f2955baef3ac76f36c6c1187ca36
NemoHoHaloAi/DSAA
/LeetCode/102_binarytree_levelsearch.py
1,135
3.8125
4
# 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 # #   # # 示例: # 二叉树:[3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # 返回其层次遍历结果: # # [ # [3], # [9,20], # [15,7] # ] # # 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: levelArray = [] def getLevel(self, root, lvl): if not root: return if len(self.levelArray) <= lvl: self.levelArray.append([]) self.levelArray[lvl].append(root.val) self.getLevel(root.left, lvl+1) self.getLevel(root.right, lvl+1) def levelOrder(self, root): if not root: return [] if not root.left and not root.right: return [[root.val]] self.levelArray = [] self.getLevel(root, 0) return self.levelArray
f087952294b20e49f34a4928adfbe788e4f03f1a
Juice930/Pythonoso
/RaízFalsa.py
572
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 22 13:11:15 2016 @author: Guillermo1 """ import matplotlib.pyplot as plt import numpy as np def f(x): return np.sin(2*x+1)-3./5*x+1 def biseccionFalsa(f,a,b,tol=1e-3): c=a if f(a)==0: return a if f(b)==0: return b while f(b)-f(a)>tol: c=raizFalsa(f,a,b) if f(c)*f(b)<0: a=c elif f(c)*f(a)<0: b=c print c,f(a),f(b) return c def raizFalsa(f,a,b): return b-f(b)*(a-b)/float(f(a)-f(b)) print biseccionFalsa(f,-5,6,1e-6),f(-5),f(6)
36411c384a6336cd2c0ca3fdda4e2eccfc0b31aa
vijayetar/vegan-cosmetics
/v_vegan_cosmetics/encrypt_decrypt/encrypt_decrypt.py
731
3.65625
4
from cryptography.fernet import Fernet def encrypt_password(str_pwd): #get key from the file file = open('key.key','rb') key = file.read() file.close() #encode the password to binary encoded = str_pwd.encode() #encrypt the password f = Fernet(key) e_pwd = f.encrypt(encoded) #decode it to string format decoded_e_pwd = e_pwd.decode() return decoded_e_pwd def decrypt_password(decoded_e_pwd): #get the key from the file file = open('key.key','rb') key = file.read() file.close() #encode pwd into binary format e_pwd = decoded_e_pwd.encode() #decrypt the binary pwd f= Fernet(key) d_pwd = f.decrypt(e_pwd) #decode it to the string format str_pwd = d_pwd.decode() return str_pwd
fc00ca8fddf6e4ff2aa0314ad47be6995d7276ab
LZhang2004/Year9DesignCS-PythonLZ
/PasswordInput.py
951
3.875
4
import tkinter as tk top = tk.Tk() top.title("keypad1") #function to check the input def check(): n = int(entr.get()) #function to close keypad, refresh storyline text, enable level 1, turn begin to green #continuing the check if answer is right if n == 9832: title3.config(text = "Status: CORRECT! ", fg = "green") top.after(2000, please2) else: title3.config(text = "Status: INCORRECT! Please Try Again", fg = "red") #frame for the keypad title2 = tk.Label(top, text = "Enter the Password", fg = "black", font = ("Courier", 20) ) title2.grid(column = 0, row = 0) entr = tk.Entry(top) entr.grid(column = 0, row = 1) btn1 = tk.Button(top, text = "Submit", command = check, font = ("Arial", 20, "bold"), fg = 'red') btn1.config(height = 3, width = 10) btn1.grid(column = 0, row = 2) title3 = tk.Label(top, text = "Status: Password not entered", fg = "black", font = ("Courier", 30) ) title3.grid(column = 0, row = 3) top.mainloop()
05cd4ace757941ced69b42f9171ef6a73a9afca8
sujit0892/snake-game
/food.py
362
3.5625
4
import random import queue class Food: def __init__(self,queue): self.queue=queue self.generate_food() def generate_food(self): x=random.randrange(5,480,10) y=random.randrange(5,295,10) self.position=(x,y) rectangle_position=(x-5,y-5,x+5,y+5) self.queue.put({'food':rectangle_position})
02ebe99310c8a1f17bd9f23a383fdb6bbebd29c4
HoweChen/leetcodeCYH
/1051. Height Checker/main.py
262
3.546875
4
class Solution: def heightChecker(self, heights: List[int]) -> int: sorted_heights = sorted(heights) count = 0 for i in range(0,len(heights)): if heights[i]!=sorted_heights[i]: count+=1 return count
78c54246f653c6832b553a542ef607fa33899f48
enisteper1/ML_with_and_without_sklearn
/k-NN/k-NN_with_equations.py
3,355
3.546875
4
import numpy as np from math import sqrt import pandas as pd class K_Nearest_Neighbours: def __init__(self, neighbours=5): self.neighbours = neighbours # Get distances between points with euclidean equation def euclidean_distance(self, p1, p2): # Calculate sum of distances for all dimensions of p1 and p2 distance = sum((p1[h] - p2[h])**2 for h in range(len(p1))) # Get square root to finish euclidean distance formula distance = sqrt(distance) return distance def fit(self,x, y): self.x = x self.y = y # Compares predicted and expected labels and returns percentage of correct predictions in all predictions def accuracy(self, outputs, expectations): # All predictions comparison_list = [outputs[k] == expectations[k] for k in range(len(outputs))] # Get Percentage of correct predictions percentage = comparison_list.count(True) / len(comparison_list) return percentage def prediction(self, inputs): predictions = list() for inp in inputs: # Get all distances between train dataset (x_train) distances = [self.euclidean_distance(inp, point2) for point2 in self.x] # Obtain closest neighbours arguments with respect to self.neighbours number closest_neighbours = np.argsort(distances)[:self.neighbours] # Obtain labels closest_neighbours_labels = [self.y[index] for index in closest_neighbours] # Get most closest label label_counts = np.bincount(closest_neighbours_labels) predictions.append(np.argmax(label_counts)) return predictions def dataset_preprocessing(csv_file="Breast_cancer_data.csv"): # Reading csv file dataset = pd.read_csv(csv_file) # Getting columns for x and y arrays # Assuming last column is output (y) dataset_array = dataset.to_numpy() np.random.shuffle(dataset_array) # Uncomment this this row if dataset labels are sequential x, y = dataset_array[:, :-1], dataset_array[:, -1] test_perc = 0.2 # test percentage test_size = int(test_perc * len(x)) # test size # Splitting to test and train arrays x_train, y_train, x_test, y_test = x[:-test_size], y[:-test_size], x[-test_size:], y[-test_size:] return x_train, y_train, x_test, y_test if __name__ == "__main__": # Applicable for any csv files that last column is output and does not contain any string x_train, y_train, x_test, y_test = dataset_preprocessing("breast_cancer.csv") max_percentage = 0 # try neighbour numbers from 1 to 10 for i in range(1,10): knn = K_Nearest_Neighbours(neighbours=i) knn.fit(x=x_train, y=y_train) score = knn.accuracy(knn.prediction(x_test), y_test) # Get maximum accuracy and corresponding neighbour number if score > max_percentage: neighbour_num, max_percentage = i, score print(f"Max percentage is {round(max_percentage,4)} with {neighbour_num} neighbour numbers.") # Predict a value from test dataset knn = K_Nearest_Neighbours(neighbours=neighbour_num) knn.fit(x=x_train, y=y_train) print(f"Predicted label: {knn.prediction(x_test)[0]}\nExpected label: {int(y_test[0])}")
a0143416ecfe8fd3ffd35b72905af817a5ca8d76
ValeriaAraque/Pogramacion
/Talleres/taller_herencia.py
3,235
3.78125
4
#Cree la clase persona con id,nombre,edad y cree la funcion hablar, la cual dado mensaje se muestra en pantalla,cree la clase caminar que dado una cantidad de pasos muestre en pantalla cuanto ha caminado class Persona: def __init__(self,idIn,nombreIn,edadIn): self.id = idIn self.nombre = nombreIn self.edad = edadIn def hablar(self,mensaje): print (f'La persona {self.nombre} esta diciendo que {mensaje}') def caminar(self,pasos): print (f'La persona {self.nombre} ha caminado {pasos} pasos') persona1 = Persona(1006959918,'Melany', 20) persona1.hablar('Hola,como estas') persona1.caminar(100) #Herede la clase persona y cree la clase doctor el cual tendra el nuevo atributo especialidad y podra ejecutar una nueva funcion, la cual dada una enfermedad muestra,procedo a tratar enfermedad class Doctor(Persona): def __init__(self,idIn,nombreIn,edadIn,especialidadIn): Persona.__init__(self,idIn,nombreIn,edadIn) self.especialidad = especialidadIn def mostrarAtributos(self): print (f'El/La doctor/a {self.nombre}, tiene {self.edad}, se especializo en {self.especialidad} y se identifica con el id {self.id}') def tratarEnfermedad (self,enfermedad): print(f'El/La doctor/a {self.nombre} va a tratar la enfermedad: {enfermedad}') doctor1 = Doctor(1011945710,'Susana',24,'Cardiologia') doctor1.mostrarAtributos() doctor1.tratarEnfermedad('Taquicardia') #Herede la clase persona y creee la clase nutricionista y cree un atributo que se refiera a la universidad enla que fue egresado.Tambien una fucnion que devuelva el IMC class Nutricionista(Persona): def __init__(self,idIn,nombreIn,edadIn,universidadIn): Persona.__init__(self,idIn,nombreIn,edadIn) self.universidad = universidadIn def mostrarAtributos(self): print (f'El/La nutricionista {self.nombre}, tiene {self.edad}, se identifica con el id {self.id} y se graduo de la universidad {self.universidad}') def funcionIMC(self,peso,altura): return round(peso/(altura**2),2) nutricionista1 = Nutricionista(1246576,'Simon', 21, 'CES') nutricionista1.mostrarAtributos() imc = nutricionista1.funcionIMC(60,1.70) print (f'El IMC calculado por el/la nutricionista es de : {imc}') #Herede de la clase Persona y cree la clase abogado adidcione dos atributos, uno asociado a su especialidad y otro a la universidad de la que egreso.Finalmente cree la funcion que dado un nombre y el caso del cliente, el abogado diga procedo a representar en el caso class Abogado(Persona): def __init__(self,idIn,nombreIn,edadIn,especialidadIn,universidadIn): Persona.__init__(self, idIn,nombreIn,edadIn) self.especialidad = especialidadIn self.universidad = universidadIn def mostrarAtributos(self): print(f'El/La abogad@ {self.nombre}, de edad {self.edad}, id {self.id}, especializado en {self.especialidad} y egresado de {self.universidad}') def casoRepresentado(self,nombre,caso): print(f'El/La abogad@ procede a representar al cliente {nombre} en el caso {caso} ') abogado1 = Abogado(10161718,'Salome',22,'derecho penal','UDM') abogado1.mostrarAtributos() abogado1.casoRepresentado('Valeria','Crimen pasional ')
b02cd3fd9f79c4fe6d928f2810280d07f90f46dd
SujaySSJ/Cryptography
/vernam.py
522
4.09375
4
import string import random alphabet=string.ascii_uppercase index={} for i,letter in zip(range(26),alphabet): index[letter]=i def encrypt(plain_text): plain_text=plain_text.replace(" ","").upper() cipher_text="" for letter in plain_text: total=index[letter]+index[random.choice(alphabet)] if total>25: total=total-25 cipher_text+=index.keys()[index.values().index(total)] return cipher_text plain_text=raw_input("Enter plain text :") cipher_text=encrypt(plain_text) print("Encrypted Text : "+cipher_text)
333fe77998427cb1d6fef3ecfd38ba1472f59684
sharedrepo2021/AWS_Python
/Biji/liam.py
1,082
3.65625
4
import requests class Currencyconverter: def __init__(self, url): data = requests.get(url).json() # Extracting only the rates from the json data self.rates = data["rates"] def convert(self, from_currency, to_currency, amount): self.data = requests.get(url).json() self.currencies = self.data['rates'] initial_amount = amount # first convert it into USD if it is not in USD. # because our base currency is USD # if from_currency != 'USD': amount = amount / self.currencies[from_currency] # limiting the precision to 4 decimal places amount = round(amount * self.currencies[to_currency], 4) print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency)) if __name__ == '__main__': url = 'https://api.exchangerate-api.com/v4/latest/USD' objcc = Currencyconverter(url) from_country = input("From Country: ") to_country = input("TO Country: ") amount = int(input("Amount: ")) objcc.convert(from_country, to_country, amount)
777bdba98a60c14abdc00d636003aae3672905c6
DannyLee12/dcp
/_2020/06_June/122.py
949
3.796875
4
""" You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at matrix[0][0], and can only move right or down, find the maximum number of coins you can collect by the bottom right corner. For example, in this matrix 0 3 1 1 2 0 0 4 1 5 3 1 The most we can collect is 0 + 2 + 1 + 5 + 3 + 1 = 12 coins. """ def max_coins(l: list) -> int: """Return the maximal number of coins that can be returned""" n = len(l) m = len(l[0]) def dfs(x, y, l): if x == n - 1 and y == m - 1: return l[x][y] if x+1 < n and y + 1 < m: return max(l[x][y] + dfs(x+1, y, l), l[x][y] + dfs(x, y+1, l)) elif x+1 < n: return l[x][y] + dfs(x+1, y, l) elif y+1 < m: return l[x][y] + dfs(x, y+1, l) return dfs(0, 0, l) if __name__ == '__main__': l = [[0, 3, 1, 1], [2, 0, 0, 4], [1, 5, 3, 1]] assert max_coins(l) == 12
1c5476eff2aeb0d3576bbe7ca14fe10fe1d22568
Eric-cv/QF_Python
/day8/dict02.py
760
3.984375
4
''' 案例: 用户注册功能 username password email phone ''' print('--------欢迎来到智联招聘用户注册--------') # 模拟数据库 database = [] while True: username = input('输入用户名') password = input('输入密码:') repassword = input('输入确认密码:') email = input('输入邮箱:') phone = input('输入手机号:') # 定义一个字典 users={} # 将信息保存到字典中 user['username']=username if password == repassword: user['password']=password else: print('两次密码不一致!') continue user['email']=email user['phone']=phone # 保存到数据库 database.append(user) answer = input('是否继续注册?(y/n)') if answer!='y': break print(database)
8e2b76d0c787cefad5487c886a816fbc2696d6c5
sukwoojang/Python
/datastructure/CircleLinkedList.py
2,066
3.71875
4
class CircleLInkedList: def __init__(self): self.root = Node() self.tail = self.root self.current = self.root def append(self,item): NewNode = Node(item) if self.root.item == None: self.root = NewNode self.tail = NewNode NewNode.link = self.root else: _tmp = self.tail.link self.tail.link = NewNode NewNode.link = _tmp self.tail = NewNode def listSize(self): curNode = self.root count = 1 while curNode.link != self.root: curNode = curNode.link count += 1 return count def print(self): curNode = self.root print(curNode.item) while curNode.link != self.root: curNode = curNode.link print(curNode.item) def setCurrent(self,item): curNode = self.root for i in range(self.listSize()): if curNode.item == item: self.current = curNode else: curNode = curNode.link def moveNext(self): self.current = self.current.link print("현재 위치는 {}입니다.".format(self.current.item)) def insert(self, item): NewNode = Node(item) _tmp = self.current.link self.current.link = NewNode NewNode.link = _tmp if self.current == self.tail: self.tail = NewNode def delete(self, item): delYN = False curNode = self.root if curNode.item == item: self.root = self.root.link self.tail.link = self.root delYN =True else: while curNode.link != self.root: preNode = curNode curNode = curNode.link if curNode.item == item: preNode.link = curNode.link if curNode == self.tail: self.tail = preNode delYN =True if delYN == False: print("delete failed")
4ac7e9d45b951fae999298376cea8c6538264aa2
ChangxingJiang/LeetCode
/1501-1600/1504/1504_Python_1.py
1,348
3.734375
4
from typing import List # 数组 数学 # O(N^4) class Solution: def numSubmat(self, mat: List[List[int]]) -> int: rows, columns = len(mat), len(mat[0]) ans = 0 # 每一个点计算以它做左上角顶点的情况 for i in range(rows): for j in range(columns): if mat[i][j] == 1: m = i max_height, max_width = rows, columns while m < max_height and mat[m][j] == 1: n = j while n < max_width and mat[m][n] == 1: ans += 1 n += 1 else: max_width = n m += 1 return ans if __name__ == "__main__": # 13 print(Solution().numSubmat(mat=[[1, 0, 1], [1, 1, 0], [1, 1, 0]])) # 24 print(Solution().numSubmat(mat=[[0, 1, 1, 0], [0, 1, 1, 1], [1, 1, 1, 0]])) # 21 print(Solution().numSubmat(mat=[[1, 1, 1, 1, 1, 1]])) # 5 print(Solution().numSubmat(mat=[[1, 0, 1], [0, 1, 0], [1, 0, 1]]))
6877aaeba50d12c031d023fe7009897693b48bac
VenkatalakshmiM/guvi
/my programs/oxymorphic.py
169
3.53125
4
v,l=map(str,input().split()) if(len(v)!=len(l)): print("no") else: s2=[v.count(i) for i in v] s3=[l.count(i) for i in l] if(s2==s3): print("yes") else: print("no")
7fc88b6e3c9985df79b7b655ddeed336d401bcf7
seoul-ssafy-class-2-studyclub/Hyejune
/4873_반복문자지우기.py
542
3.578125
4
test_num =int(input()) def checkDup(arr): sp = -1 for i in range(len(arr)-1): if arr[i] == arr[i+1]: sp = i break if sp == -1: return False else: arr = arr[:sp] + arr[sp+2:] return arr def deleteDup(arr): if checkDup(arr) == False: return arr else: return deleteDup(checkDup(arr)) for t in range(test_num): test_case = list(input()) result = len(deleteDup(test_case)) print('#' + str(t+1) + ' ', end='') print(result)
7fd7b04d19ba3ba906e4f058a4bc1ac59777c404
SmoothCrimminal/SmartGarbageTruckAI
/AI/cost.py
4,146
3.59375
4
import csv import os from Point import * from search import * # helper script to generate cost map for configuration CONFIG_FILE = '008.csv' points_grid = [] trash_points = [] class TrashPoint(): def __init__(self, ordinal_number, y, x): self.ordinal = ordinal_number self.y = y self.x = x # after this function we have list of points we want to visit, first is starting point, end is dump point where sorting begins def load_config(config_file): global trash_points config_dir = os.path.join( os.getcwd(), config_file.split(".")[0]) config = os.path.join(config_dir, config_file) with open(config, 'r') as file: # first point is starting point with ordinal_number 0 start = TrashPoint(0, 10, 66) trash_points.append(start) trash_point_ordinal_number = 1 y = 0 for line in file: x = 0 points_row = [] print(line) for mark in line.split(';'): point = Point(y, x) # point is available if mark != 'X': point.set_available() # it's trash point if mark == 'T': point.set_trash_point() trash_point = TrashPoint(trash_point_ordinal_number, y, x) trash_points.append(trash_point) trash_point_ordinal_number += 1 elif mark == 'O': point.set_obstacle() elif mark == 'D': point.set_dump() elif mark == 'R': point.set_road() x += 1 points_row.append(point) y += 1 points_grid.append(points_row) # last point is dump point end = TrashPoint(trash_point_ordinal_number, 11, 82) trash_points.append(end) return points_grid # generate cost matrix (identity matrix) depending on points grid from configuration def cost_matrix(points_grid): global trash_points searcher = Search(points_grid, None) cost_matrix = [[0 for col in range(len(trash_points))] for row in range(len(trash_points))] for i in range( len(trash_points) ): start_point = trash_points[i] start_state = State(start_point.y, start_point.x, 2) for j in range(i): end_point = trash_points[j] goal_state = State(end_point.y, end_point.x, 2) print("[SEARCH] Counting cost from " + str(start_point.ordinal) + " to " + str(end_point.ordinal) ) cost_matrix[i][j] = searcher.graph_search_AStar(start_state, goal_state) cost_matrix[j][i] = cost_matrix[i][j] print("COST: " + str(cost_matrix[i][j])) return cost_matrix def save_cost_matrix(config_file, cost_matrix): filename = "C-" + config_file.split(".")[0] + ".csv" config_dir = os.path.join( os.getcwd(), config_file.split(".")[0]) file_path = os.path.join( config_dir, filename) with open(file_path, 'w', newline='') as cost_file: csv_writer = csv.writer(cost_file, delimiter=';') csv_writer.writerows(cost_matrix) def save_trash_points(config_file): global trash_points # ordinal number ; y ; x filename = "TP-" + config_file.split(".")[0] + ".csv" config_dir = os.path.join( os.getcwd(), config_file.split(".")[0]) file_path = os.path.join( config_dir, filename) with open(file_path, 'w', newline='') as points_file: csv_writer = csv.writer(points_file, delimiter=";") for trash_point in trash_points: row = [ trash_point.ordinal, trash_point.y, trash_point.x ] csv_writer.writerow(row) # load configuration points_grid = load_config(CONFIG_FILE) # generate cost map depending on configuration cost_matrix = cost_matrix(points_grid) # create two files - one file is for client to translate path depending on GA TSP result and second is cost matrix for GA save_cost_matrix(CONFIG_FILE, cost_matrix) save_trash_points(CONFIG_FILE)
4c3d8b15f03c59e819e0c4c04e75c31a6968fa53
rkalz/CS452
/assn6/q2.py
221
3.890625
4
def staircase(steps): dp = [0 for _ in range(steps+1)] dp[0] = dp[1] = 1 for i in range(2, steps+1): dp[i] = dp[i-1] + dp[i-2] return dp[-1] if __name__ == "__main__": print(staircase(200))
5d46fc407fde661c8a144b690eebcb6bb3f50cd0
TalatWaheed/100-days-code
/code/python/Day-7/duplicatesubary.py
372
3.796875
4
a=[] dn=[] n=int(input("Enter length of Array : ")) print("Enter array : ") for i in range(n): x=int(input()) a.insert(i,x) i=i+1 i=0 k=0 while i<n: j=i+1 while j<n: if a[i]==a[j]: dn.insert(k,a[i]) k=k+1 break j=j+1 i=i+1 print("Duplicate subarray : ") for i in range(0,k): print(" ",dn[i])
43d002cc52babcd25ff1eed1ecaf09dd1fd9098b
paulormart/hands-on-python
/pycon_2012/pycon_2012_idiomatic_python.py
8,425
3.703125
4
#****************** # my talk notes and tests # # credits > # Pycon 2012 - Transforming code into Beautiful, Idiomatic Python # by Raymond Hettinger # @raymondh # http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho # Raymonds rule: # One logical line of code equals one sentence in English #****************** # # # from functools import partial from itertools import izip from collections import defaultdict import argparse import os print '#~~ looping over a range of numbers' for i in [0,1,2,3,4,5]: print i**2 for i in range(6): print i**2 print '#~~~ xrange def:' for i in xrange(6): print i**2 print '#~~ looping over a collection' colors = ['red', 'green', 'blue', 'yellow'] for i in range(len(colors)): print colors[i] for color in colors: print color print '#~~ looping backwards' for i in range(len(colors)-1,-1,-1): print colors[i] for color in reversed(colors): print color print '#~~ looping over a collection and indicies' for i in range(len(colors)): print i, '-->', colors[i] for i, color in enumerate(colors): print i, '-->', color print '#~~ looping over two collections' names = ['raymond', 'rachel', 'mathew'] n = min(len(names), len(colors)) for i in range(n): print names[i], '-->', colors[i] for name, color in zip(names, colors): print name, '-->', color for name, color in izip(names, colors): print name, '-->', color print '#~~ looping in sorted order' colors = ['red', 'green', 'blue', 'yellow'] for color in sorted(colors): print color for color in sorted(colors, reverse=True): print color print '#~~ custom sort order' def compare_length(c1, c2): if len(c1) < len(c2): return -1 if len(c1) > len(c2): return 1 print sorted(colors, cmp=compare_length) print sorted(colors, key=len) print '#~~ call a function until a sentinel value' f = open('workfile', 'r+') blocks = [] while True: block = f.read(32) if block == '': break blocks.append(block) blocks = [] for block in iter(partial(f.read, 32), ''): blocks.append(block) print '#~~ distinguishing multiple exit points in loops' def find(seq, target): found = False for i, value in enumerate(seq): if value == tgt: found = True break if not found: return -1 return i def find(seq, target): for i, value in enumerate(seq): if value == tgt: break else: return -1 return i print '#~~ looping over dictionary keys' d = {'mathew':'blue', 'rachel': 'green', 'raymond':'red'} for k in d: print k for k in d.keys(): if k.startswith('r'): del d[k] d = {k: d[k] for k in d if not k.startswith('r')} print '#~~ looping over dictionary keys and values' for k in d: print k, '-->', d[k] for k, v in d.items(): print k, '-->', v for k, v in d.iteritems(): print k, '-->', v print '#~~ construct a dictionary from pairs' name = ['raymond', 'rachel', 'mathew'] colors = ['red', 'green', 'blue'] d = dict(izip(names, colors)) print 'd1: %s' % d d = dict(enumerate(names)) print 'd2: %s' % d colors = ['red', 'green', 'red', 'blue', 'green', 'red'] d = {} for color in colors: if color not in d: d[color]=0 d[color]+=1 print 'd3: %s' % d d = {} for color in colors: d[color] = d.get(color, 0) + 1 print 'd4: %s' % d d = defaultdict(int) for color in colors: d[color] += 1 print 'd5: %s' % d print 'Grouping with dictionaries - Part1' names = ['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'] d = {} for name in names: key = len(name) if key not in d: d[key] = [] d[key].append(name) print 'd6: %s' % d print 'Grouping with dic:onaries - Part2' d={} for name in names: key = len(name) d.setdefault(key, []).append(name) print 'd7: %s' % d d = defaultdict(list) for name in names: key = len(name) d[key].append(name) print 'd8: %s' % d print 'Is a popitem() atomic?' d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'} while d: key, value = d.popitem() print key, '-->', value print 'd9: %s' % d print 'Linking dictionarys - python 3' ''' defaults = {'color':'red', 'user':'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args([]) command_line_args = {k:v for k, v in vars(namespace).items() if v} d = defaults.copy() d.update(os.environ) d.update(command_line_args) d = ChainMap(command_line_args, os.environ, defaults) print 'd10: %s' % d ''' print 'Improving clarity' p = 'Raymond', 'Hettinger', 0x30, 'python@example.com' fname = p[0] lname = p[1] age = p[2] email = p[3] fname, lname, age, email = p print 'update multiple state variables' def fibonacci(n): x=0 y=1 for i in range(n): print x t=y y=x+y x=t def fibonacci(n): x, y = 0, 1 for i in range(n): print x x, y = y, x+y print 'simultaneos state updates' x = 1 y = 2 dx = 1 dy = 1 t = 3 m = 4 tmp_x = x + dx * t tmp_y = y + dy * t tmp_dx = influence(m, x, y, dx, dy, partial='x') tmp_dy = influence(m, x, y, dx, dy, partial='y') x = tmp_x y = tmp_y dx = tmp_dx dy = tmp_dy x, y, dx, dy = (x + dx * t, y + dy * t, influence(m, x, y, dx, dy, partial='x'), influence(m, x, y, dx, dy, partial='y')) print 'EFFICIENCY' print 'concatenating strings' names = ['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'] s = names[0] for name in names[1:]: s += ', ' + name print s print ', '.join(names) print 'updating sequences' names = ['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'] del names[0] names.pop(0) names.insert(0, 'mark') names = deque(['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']) del names[0] names.popleft() names.appendleft('mark') print 'using decorators to factorout administrative logic' def web_lookup(url, saved={}): if url in saved: return saved[url] page = urllib.urlopen(url).read() saved[url] = page return page @cache def web_lookup(url): return urllib.urlopen(url).read() print 'caching decorator' def cache(func): saved = {} @wraps(func) def newfunc(*args): if args in saved: return newfunc(*args) result = func(*args) saved[args] = result return result return newfunc print 'Factor out temporary contexts' old_context = getcontext().copy() getcontext().prec = 50 print Decimal(355) / Decimal(113) setcontext(old_context) with localcontext(Context(prec=50)): print Decimal(355) / Decimal(113) print 'How to open and close files' f = open('data.txt') try: data = f.read() finally: f.close() with open('data.txt') as f: data = f.read() print 'How to use locks' # Make a lock lock = threading.Lock() # Old-way to use a lock lock.acquire() try: print 'Critical section 1' print 'Critical section 2' finally: lock.release() # New-way to use a lock with lock: print 'Critical section 1' print 'Critical section 2' print 'Factor out temporary contexts' try: os.remove('somefile.tmp') except OSError: pass with ignored(OSError): os.remove('somefile.tmp') print 'Context manager: ignored()' @contextmanager def ignored(*exceptions): try: yield except exceptions: pass print 'Factor out temporary contexts' with open('help.txt', 'w') as f: oldstdout = sys.stdout sys.stdout = f try: help(pow) finally: sys.stdout = oldstdout with open('help.txt', 'w') as f: with redirect_stdout(f): help(pow) print 'Context manager: redirect_stdout()' @contextmanager def redirect_stdout(fileobj): oldstdout = sys.stdout sys.stdout = fileobj try: yield fieldobj finally: sys.stdout = oldstdout print 'List Comprehensions and Generator Expressions' result = [] for i in range(10): s = i ** 2 result.append(s) print sum(result) print sum([i**2 for i in xrange(10)]) print sum(i**2 for i in xrange(10))
bda02d45df97f4cc6cc1c31d1c19916481fb8610
OurGitAccount846/pythontraining
/classprograms/multiple.py
601
3.921875
4
class person(object): def __init__(self,name,idnumber): self.name=name self.idnumber=idnumber class employee(object): def __init__(self,post,salary): self.post=post self.salary=salary class leader(person,employee): def __init__(self,name,idnumber,post,salary): person.__init__(self,name,idnumber) employee.__init__(self,post,salary) print(" name:{}\n idnumber:{}\n post:{}\n salary:{}\n".format(self.name,self.idnumber,self.post,self.salary)) def main(): a=leader('binu',34521,'manager',40000) main()
dbdd2ea5508c909c9119407ed594e654cbc102f7
Jacwutang/Algorithms
/Python/balanced-parenthesis.py
1,536
3.578125
4
#uses Python3 import sys def isBalanced(str): arr = [] temp = [] index = 0 if len(str) == 1: return 1 for x in range(len(str)): if str[x] == '(' or str[x] == '[' or str[x] == '{': arr.append(str[x]) temp.append(x) else: if len(arr) == 0 and str[x] == ')' or len(arr) == 0 and str[x] == '}' or len(arr) == 0 and str[x] == ']': return x+1 if len(arr) > 0: pop = arr[len(arr) - 1] if pop == '(' and str[x] == ')': del temp[len(arr) - 1] del arr[len(arr) - 1] elif pop == '(' and str[x] == ']' or pop == '(' and str[x] == '}': return x + 1 if pop == '[' and str[x] == ']': del temp[len(arr) - 1] del arr[len(arr) - 1] elif pop == '[' and str[x] == ')' or pop == '[' and str[x] == '}': return x + 1 if pop == '{' and str[x] == '}': del temp[len(arr) - 1] del arr[len(arr) - 1] elif pop == '{' and str[x] == ']' or pop == '{' and str[x] == ')': return x + 1 if len(arr) != 0: temp = temp.pop() + 1 return temp else: return "Success" arr = [] for x in sys.stdin.readline().split(): arr.append(x) arr = ''.join(arr) #print(arr) result = isBalanced(arr) print(result)
755d447dfd1f8b8dc216bac7d23f3b876b554f51
nappex/1Dpiskvorky
/2domecek.py
632
3.515625
4
from turtle import left, right, forward, speed, goto, penup, pendown, setup from turtle import exitonclick from math import sqrt setup(width=1100, height=800) speed(8) penup() goto(-400, 0) pendown() def domek(strana): # vypocet delky zakladny u pravouhleho trojuhelniku zakladna = sqrt(2)*strana left(90) forward(strana) right(30) forward(strana) right(120) forward(strana) right(30) forward(strana) right(135) forward(zakladna) right(135) forward(strana) right(135) forward(zakladna) left(135) forward(strana+20) domek(20) domek(40) domek(60) exitonclick()
cc97bf7f995a1de2352b3dffa9cf8644ed0b17b6
nqcccccc/designAndAlgorithm
/bestone/coinRow.py
2,039
3.6875
4
import time import pylab import myLibrary as lib # Applies formula (8.3) bottom up to find the maximum amount of money # that can be picked up from a coin row without picking two adjacent coins # Input: Array C[1..n] of positive integers indicating the coin values # Output: The maximum amount of money that can be picked up def CoinRow(C): C.insert(0, 0) F = C F[0] = 0 F[1] = C[1] for i in range(2,len(C)): F[i] = max(C[i]+F[i -2],F[i - 1]) return F[len(C)-1] # A = [5, 1, 2, 10, 6, 2] # print(CoinRow(A)) # #10 A0 = lib.ranGen(10) A1 = lib.ranGen(100) A2 = lib.ranGen(200) A3 = lib.ranGen(300) A4 = lib.ranGen(400) A5 = lib.ranGen(500) A6 = lib.ranGen(600) A7 = lib.ranGen(700) A8 = lib.ranGen(800) A9 = lib.ranGen(900) #0 startA0 = time.time() CoinRow(A0) stopA0 = time.time() timeA0 = stopA0 - startA0 sizeA0 = len(A0) #1 startA1 = time.time() CoinRow(A1) stopA1 = time.time() timeA1 = stopA1 - startA1 sizeA1 = len(A1) #2 startA2 = time.time() CoinRow(A2) stopA2 = time.time() timeA2 = stopA2 - startA2 sizeA2 = len(A2) #3 startA3 = time.time() CoinRow(A3) stopA3 = time.time() timeA3 = stopA3 - startA3 sizeA3 = len(A3) #4 startA4 = time.time() CoinRow(A4) stopA4 = time.time() timeA4 = stopA4 - startA4 sizeA4 = len(A4) #5 startA5 = time.time() CoinRow(A5) stopA5 = time.time() timeA5 = stopA5 - startA5 sizeA5 = len(A5) #6 startA6 = time.time() CoinRow(A6) stopA6 = time.time() timeA6 = stopA6 - startA6 sizeA6 = len(A6) #7 startA7 = time.time() CoinRow(A7) stopA7 = time.time() timeA7 = stopA7 - startA7 sizeA7 = len(A7) #8 startA8 = time.time() CoinRow(A8) stopA8 = time.time() timeA8 = stopA8 - startA8 sizeA8 = len(A8) #9 startA9 = time.time() CoinRow(A9) stopA9 = time.time() timeA9 = stopA9 - startA9 sizeA9 = len(A9) pylab.plot([sizeA0,sizeA1,sizeA2,sizeA3,sizeA4,sizeA5,sizeA6,sizeA7,sizeA8,sizeA9],[timeA0,timeA1,timeA2,timeA3,timeA4,timeA5,timeA6,timeA7,timeA8,timeA9],'ro-') pylab.title('Coin Row') pylab.xlabel('Input size') pylab.ylabel('Execution time (Seconds)') pylab.show()
0ebc68c6e334b0ff23ef7a02a43e69c1390ecf1b
adithya-r-nathan/SQLITE_DATABASE_MOVIES-MULESOFT
/querying_database.py
621
4.4375
4
import sqlite3 #connecting to the existing database movies conn = sqlite3.connect('movies.db') cursor = conn.cursor() #selecting all the records from the table cursor.execute('''SELECT * from MOVIES''') #printing all the records from the table result = cursor.fetchall(); print(result) #selecting the particular row with the field where director is lingusamy cursor.execute("SELECT MOVIE_NAME,LEAD_ACTOR,LEAD_ACTRESS,YEAR_OF_RELEASE,DIRECTOR FROM MOVIES WHERE DIRECTOR = 'LINGUSAMY'") #printing the rows where the director is lingusamy print (cursor.fetchall() ) conn.commit() conn.close()
28c998e30f41f350345d22934294b93fda8f3dc2
alcoccoque/Homeworks
/hw9/ylwrbxsn-python_online_task_9_exercise_4/task_9_ex_4.py
2,094
4.28125
4
""" Implement a bunch of functions which receive a changeable number of strings and return next parameters: 1) characters that appear in all strings 2) characters that appear in at least one string 3) characters that appear at least in two strings Note: raise ValueError if there are less than two strings 4) characters of alphabet, that were not used in any string Note: use `string.ascii_lowercase` for list of alphabet letters Note: raise TypeError in case of wrong data type Examples, ```python test_strings = ["hello", "world", "python", ] print(chars_in_all(*test_strings)) >>> {'o'} print(chars_in_one(*test_strings)) >>> {'d', 'e', 'h', 'l', 'n', 'o', 'p', 'r', 't', 'w', 'y'} print(chars_in_two(*test_strings)) >>> {'h', 'l', 'o'} print(not_used_chars(*test_strings)) >>> {'q', 'k', 'g', 'f', 'j', 'u', 'a', 'c', 'x', 'm', 'v', 's', 'b', 'z', 'i'} """ import string def chars_in_all(*strings): if len(strings) >= 2: chars_inall = set() uniquechars = set(''.join(strings)) for i in uniquechars: if all(i if i in x else False for x in strings): chars_inall.add(i) return chars_inall raise ValueError def chars_in_one(*strings): return set(''.join(strings)) def chars_in_two(*strings): if len(strings) >= 2: chars_inall = set() uniquechars = set(''.join(strings)) for i in uniquechars: if len([i for x in strings if i in x]) >= 2: chars_inall.add(i) return chars_inall raise ValueError def not_used_chars(*strings): strings = set(''.join([x.lower() for x in strings if x.isalpha()])) list_of_str = set() for i in string.ascii_lowercase: if i not in strings: list_of_str.add(i) else: continue return list_of_str # # print(chars_in_all('asd', 'asas','asd')) # print(chars_in_one('asd', 'asdasdd','asdddd')) # print(chars_in_two('asd', 'asas','bbbbbb')) # print(not_used_chars('asd', 'asas','bbbbbb')) # print()
71834907042ca6fcd67ee6d8e8b9deb087fa4a77
sachlinux/python
/exercise/var.py
123
3.6875
4
#!/usr/bin/python print("hello") var1=100 var2=var1 #two name for one item print("var1={}, var2={}".format(var1,var2))
0a1b09a9aa00a464ffe44db96a89a6f31ff287ec
lostchristmas0/language_detector
/decision_tree.py
9,416
3.515625
4
""" file: decision_tree.py language: python3 author: Chenghui Zhu cz3348@rit.edu description: this file contains the decision tree and its tree node class. It also includes other formatting method for training set or testing set. """ import math import pickle import sys from feature import * def sample(fileName): """ Formatting the example file (with language type) to training set :param fileName: example file :return: training set (each entry with boolean value in front and language type at the last position) """ trainingSet = [] with open(fileName, encoding="utf8") as file: for line in file: line = line.strip() entry = convert(line) trainingSet.append(recognize(entry)) return trainingSet def testSample(fileName): """ Formating the example file (without language type) to testing set :param fileName: example file :return: testing set (each entry with only boolean value) """ testSet = [] with open(fileName, encoding="utf8") as file: for line in file: line = line.strip() entry = format(line) testSet.append(findFeature(entry)) return testSet def entropy(x): """ Calculating the entropy value of a given possibility :param x: possibility input :return: entropy value """ if x == 0 or x == 1: return 0 else: return -(x * math.log(x, 2) + (1 - x) * math.log((1 - x), 2)) def findAttribute(list): """ Summarizing each possible feature from a given training set :param list: the specific training set :return: a dictionary of {each feature: result and remainder} """ attribute_remainder = {} attribute = len(list[0]) - 1 total = len(list) for i in range(attribute): trueEN = 0 trueNL = 0 falseEN = 0 falseNL = 0 for j in range(total): if list[j][i] is True and list[j][-1] == "en": trueEN += 1 elif list[j][i] is True and list[j][-1] == "nl": trueNL += 1 elif list[j][i] is False and list[j][-1] == "en": falseEN += 1 elif list[j][i] is False and list[j][-1] == "nl": falseNL += 1 if trueEN + trueNL != 0: pTure = trueEN / (trueEN + trueNL) else: pTure = 0 if falseEN + falseNL != 0: pFalse = falseEN / (falseEN + falseNL) else: pFalse = 0 attribute_remainder[i] = {"trueEN": trueEN, "trueNL": trueNL, "falseEN": falseEN, "falseNL": falseNL, "remainder": entropy(pTure) * (trueEN + trueNL) / total + entropy(pFalse) * (falseEN + falseNL) / total} return attribute_remainder def splitList(list, attribute, value): """ Sublisting the training set by the given value at specific attribute (feature) :param list: the original training set :param attribute: the attribute (feature) value :param value: the language type :return: the sub training set """ split = [] for x in list: if x[attribute] == value: split.append(x) return split def leastRemainder(data): """ Finding the attribute (feature) value with the least remainder :param data: the dictionary from :func:`~findAttribute` method :return: the attribute (feature) value with the least remainder. If the current node cannot be further determined, this function return -1. """ smallest = 1 attribute = 0 for i in data: temp = data[i]["remainder"] if temp < smallest: smallest = temp attribute = i for i in data: if i != attribute and data[i]["remainder"] == smallest: attribute = -1 break return attribute class TreeNode: """ TreeNode class represents each step of a decision tree self.info: the specific training set self.stop: if the node is at bottom of the decision tree (leaf node) self.decision: the prediction given at this node self.hypothesis: a list of all pairs of (checked feature value, T/F) """ def __init__(self, list): self.info = list self.features = findAttribute(list) self.nextFeature = leastRemainder(self.features) # = -1 self.trueBranch = None self.falseBranch = None self.parent = None self.stop = False self.decision = "en" self.hypothesis = [] # self.setNextFeature() def setTrue(self, node): """ Setting the node as the true branch (left child) of the current node :param node: the child node :return: None """ self.trueBranch = node node.parent = self for p in node.parent.hypothesis: node.hypothesis.append(p) node.hypothesis.append((self.nextFeature, True)) if self.features[self.nextFeature]["trueEN"] >= self.features[self.nextFeature]["trueNL"]: node.decision = "en" else: node.decision = "nl" def setFalse(self, node): """ Setting the node as the false branch (right child) of the current node :param node: the child node :return: None """ self.falseBranch = node node.parent = self for p in node.parent.hypothesis: node.hypothesis.append(p) node.hypothesis.append((self.nextFeature, False)) if self.features[self.nextFeature]["falseEN"] >= self.features[self.nextFeature]["falseNL"]: node.decision = "en" else: node.decision = "nl" def __repr__(self): return "Decision list:\n" + str(self.hypothesis) + "\nDecision: " + self.decision class DecisionTree: """ DecisionTree class represents the decision tree (root and leaf nodes) """ def __init__(self, node): self.root = node self.leaves = [] def inducing(self, node, depth=10): """ Inducing the decision tree from a sepcific node if possible :param node: the start node :param depth: the max depth of the inducing can reach (default as 10) :return: None """ if not node.stop: left = TreeNode(splitList(node.info, node.nextFeature, True)) if node.features[node.nextFeature]["trueEN"] == 0 or \ node.features[node.nextFeature]["trueNL"] == 0: left.stop = True node.setTrue(left) if len(left.hypothesis) >= depth or left.features[node.nextFeature]["remainder"] == 1 or left.nextFeature == -1: left.stop = True right = TreeNode(splitList(node.info, node.nextFeature, False)) if node.features[node.nextFeature]["falseEN"] == 0 or \ node.features[node.nextFeature]["falseNL"] == 0: right.stop = True node.setFalse(right) if len(right.hypothesis) >= depth or right.features[node.nextFeature]["remainder"] == 1 or right.nextFeature == -1: right.stop = True self.inducing(left) self.inducing(right) def getLeaf(self, node): """ Collecting all leaf nodes :param node: the start node :return: None """ if not node is None: if node.stop: self.leaves.append(node) else: self.getLeaf(node.trueBranch) self.getLeaf(node.falseBranch) def testSingle(self, test): """ Testing a single entry, find the corresponding language type prediction :param test: a single list with only boolean value :return: the language type """ temp = self.root while True: if temp.stop: break elif test[temp.nextFeature] is True: temp = temp.trueBranch elif test[temp.nextFeature] is False: temp = temp.falseBranch return temp.decision def testAll(self, list): """ Testing all entries from a testing set :param list: the testing set :return: a list of all prediction """ result = [] for s in list: result.append(self.testSingle(s)) return result def output(self, fileName): """ Outputing the decision tree object into a file :param fileName: the output file name :return: None """ with open(fileName, "wb") as file: pickle.dump(self, file) def main(): trainingSet = sample("size_1000.dat") root = TreeNode(trainingSet) dt = DecisionTree(root) dt.inducing(dt.root) dt.getLeaf(dt.root) for x in dt.leaves: print(x) # rT = root.trueBranch # print(rT) # print() # # rTT = rT.trueBranch # print(rTT) # print() # # rTTF = rTT.falseBranch # print(rTTF) # print() # print(trainingSet) # data = findAttribute(trainingSet) # print(data) # print(leastRemainder(data)) # second = splitList(trainingSet, 1, True) # print(second) # data2 = findAttribute(second) # print(data2) # print(leastRemainder(data2)) # if __name__ == "__main__": # main()
f4033e76230598ba2409674ac12797df98c4208d
MeghaSajeev26/Luminar-Python
/Advance Python/Object oriented programming/employee.py
580
3.796875
4
#create employee class with attributes--name,age,empid,salary,department,company class Employee: def details(self,name,age,emp_id,salary,dept,company): self.name=name self.age=age self.emp_id=emp_id self.salary=salary self.dept=dept self.company=company def printval(self): print(self.name) print(self.age) print(self.emp_id) print(self.salary) print(self.dept) print(self.company) obj=Employee() obj.details("Rakesh",28,401,25000,"Accounts","Global Services") obj.printval()
cc9413c345ad7c141f4d26d10fbfd8cbf566c8f7
Python-study-f/Algorithm-study_2H
/Auguest_/210807/11_Container_Water/11_210805_ohzz.py
374
3.5625
4
# Container_Water 11 릿코드 def maxArea(height): lt, rt = 0, len(height) - 1 res = 0 while lt < rt: cur_value = min(height[lt], height[rt]) cur_area = (rt - lt) * cur_value res = max(res, cur_area) if height[lt] > height[rt]: rt -= 1 else: lt += 1 return res print(maxArea([1, 2, 1]))
93035763b391ebf959fd923ea9b92083d7d81047
adityakverma/Interview_Prepration
/Leetcode/Dynamic_Programming/LC-072. Edit Distance.py
2,353
3.765625
4
# Given two words word1 and word2, find the minimum number of operations # required to convert word1 to word2. # # You have the following 3 operations permitted on a word: # # Insert a character # Delete a character # Replace a character # # Example 1: # # Input: word1 = "horse", word2 = "ros" # Output: 3 # Explanation: # horse -> rorse (replace 'h' with 'r') # rorse -> rose (remove 'r') # rose -> ros (remove 'e') # # Example 2: # # Input: word1 = "intention", word2 = "execution" # Output: 5 # Explanation: # intention -> inention (remove 't') # inention -> enention (replace 'i' with 'e') # enention -> exention (replace 'n' with 'x') # exention -> exection (replace 'n' with 'c') # exection -> execution (insert 'u') # --------------------------------------------------------------------------- class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ if not word1: return len(word2) if not word2: return len(word1) m = len(word1) n = len(word2) dp = [[0 for i in range(n + 1)] for j in range(m + 1)] for i in range(m + 1): for j in range(n + 1): # build base case: what happens if one of prefixes is zero # (1) word1 prefix is empty, then keep adding dp[0][j] = j # (2) word2 prefix is empty, then keep deleting dp[i][0] = i if word1[i - 1] == word2[j - 1]: # If letter is same, then no change, so copy previous result from uppper left diagonal dp[i][j] = dp[i - 1][j - 1] else: # Else we need some operation, so we take min of surrounding + 1. Checkout video on how we gotthis formula. # dp[i-1][j-1] -> replace # dp[i][j-1] -> add # dp[i-1][j] -> delete dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) return dp[m][n] # or dp[-1][-1] # https://www.youtube.com/watch?v=We3YDTzNXEk # https://leetcode.com/problems/edit-distance/discuss/193758/Java-and-Python-DP-Solutions:-Suffix-and-Prefix-implementations
e6ddae818e339257a537d29603395270dd254585
SHajjat/python
/app.py
1,013
4.1875
4
from math import * print('hello') myname = 'samir hajjat' print(myname.upper()) print(myname.upper().isupper()) print(myname.lower()) print(myname.lower().islower()) print(myname.capitalize()) # make the first letter capital print(myname[1]) for i in range(len(myname)): print(myname[i]) print(myname.center(5, 's')) print(myname.endswith('f')) print(myname.startswith('s')) print(myname.startswith('S')) for i in range(len(myname)): print(myname[-(i + 1)]) print(myname.index('s')) #print(str.index('SAmir')) if the index is not found it will throw an exception print(myname.replace('a', 'hello')) # replace all instances of the char # to convert a number to a string num = 1 print(str(num) + 'String') print(abs(-5)) #abs value print(pow(5,2)) print(max(5,7)) print(min(5,4)) print(round(3.533)) # those come from Math package print(floor(3.444)) print(ceil(3.444)) print(sqrt(4)) # input name =input('enter your name: ') age = input('how old are you ') print('hello '+name) print('you age is '+ age)
fa3f3e60c2010adbba0ec0a222051d6fda0cab6b
emjayking/python-library
/autospiro.py
2,226
4
4
# Python Turtle - Spirograph - www.101computing.net/python-turtle-spirograph/ import turtle from math import cos, sin from time import sleep import random window = turtle.Screen() window.bgcolor("#FFFFFF") mySpirograph = turtle.Turtle() mySpirograph.hideturtle() mySpirograph._tracer(0) mySpirograph.speed(0) mySpirograph.pensize(2) myPen = turtle.Turtle() myPen.hideturtle() myPen._tracer(0) myPen.speed(0) myPen.pensize(3) myPen.color("#AA00AA") while True: # means the code will infinitly draw spirographs R = random.randrange(80, 150) # sets each variable to be a random number r = random.randrange(40, 140) d = random.randrange(70, 160) red = random.random() green = random.random() blue = random.random() myPen.color(red, green, blue) angle = 0 myPen.penup() myPen.goto(R - r + d, 0) myPen.pendown() theta = 0.2 steps = int(50 * 3.14 / theta) for t in range(0, steps): mySpirograph.clear() mySpirograph.penup() mySpirograph.setheading(0) mySpirograph.goto(0, -R) mySpirograph.color("#999999") mySpirograph.pendown() mySpirograph.circle(R) # draws the grey circle angle += theta x = (R - r) * cos(angle) y = (R - r) * sin(angle) mySpirograph.penup() mySpirograph.goto(x, y - r) mySpirograph.color("#222222") mySpirograph.pendown() mySpirograph.circle(r) # draws the black circle mySpirograph.penup() mySpirograph.goto(x, y) mySpirograph.dot(5) x = (R - r) * cos(angle) + d * cos(((R - r) / r) * angle) y = (R - r) * sin(angle) - d * sin(((R - r) / r) * angle) mySpirograph.pendown() mySpirograph.goto(x, y) # mySpirograph.setheading((R-r)*degrees(angle)/r) # mySpirograph.forward(d) mySpirograph.dot(5) myPen.goto(mySpirograph.pos()) # draws the coloured line mySpirograph.getscreen().update() sleep(0.05) sleep(0.5) # Hide Spirograph mySpirograph.clear() mySpirograph.getscreen().update() sleep(5) myPen.clear()
52c45b740e84d68fca63123142eb6971cd9b0b56
shrikantpadhy18/INTERVIEW_QUESTIONS
/Q3/q3.py
314
3.703125
4
w=input("Enter the string:") res=[] for i in range(len(w)): for j in range(i+1,len(w)): c=w[i:j+1] if c==c[::-1] and all(len(c)>=len(t) for t in res): res.append(c) s=0 name=None for i in res: if len(i)>s: s=len(i) name=i print(res) print("The max length palindrome is :{}".format(name))
a08c9b2a1a80d11ab85f67ce4f433b50f3953be0
GouriManoj/python
/ITT 205 Problem Solving using Python/Tutorial/add.py
201
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 26 11:52:37 2020 @author: Gouri Manoj """ num1=input('Enter first number') num2=input('Enter second number') sum=float(num1)+float(num2) print(sum)
3caa8b2a17e7e4e9aaf1434e80fb553c2d65c828
MathisenMarcus/Market
/classes.py
1,625
4.1875
4
import datetime class Markets: """ Class that keeps track of all the markets """ def __init__(self,myInventory): self.marketList = [] self.inventory = myInventory def addMarkets(self,market): self.marketList.append(market) def sizeOfMarkets(self): len(self.marketList) def getList(self): return self.marketList def updateInventory(self,sold): if (self.inventory - sold) >= 0: self.inventory = self.inventory - sold else: print "Inventory empty" def displayInformation(self,myMarket): for market in myMarket.getList(): market.displayName() market.displayTotal() market.displaySold() market.printDate() class Market: """ Market class which contains informaton abouth each market""" def __init__(self): self.totalNumberOfShoes = 0 self.numberSold = 0 self.marketName = "NoName" self.dateYear = "No year set" self.dateMonth = "No month set" self.dateDay = "No day set" def changeNumberOfShoes(self,total): self.totalNumberOfShoes = total def changeNumberOfSold(self,sold): self.numberSold = sold def changeName(self,name): self.marketName = name def displayTotal(self): print "Total number of shoes: " + str(self.totalNumberOfShoes) def displaySold(self): print "Number of shoes sold: " + str(self.numberSold) def displayName(self): print "Name of market: " + self.marketName def setDate(self): self.dateYear = datetime.date.today().year self.dateMonth = datetime.date.today().month self.dateDay = datetime.date.today().day def printDate(self): print str(self.dateDay) + "/" + str(self.dateMonth) + "-" + str(self.dateYear)
5ffbc08c276578efdb5d10fb5f9cbe432337ff93
wrmacdonald/CS162_portfolio_project
/FocusGame.py
13,976
4.0625
4
# Name: Wes MacDonald # Date: 11/30/2020 # Description: A program to simulate playing the abstract board game Focus/Domination class Board: """represents a board""" def __init__(self, p1_color, p2_color): """initializes a board object :param p1_color: player 1 piece color :type p1_color: str :param p2_color: player 2 piece color :type p2_color: str """ # list to hold lists of coords for each space on the board @ index 0, and piece(s) in a stack at that coord # pieces start @ index 1 (bottom/base of stack), to the end of the list (top of stack) self._full_board_list = [] # initialize tuples of the coords @ index 0 of the list for row in range(6): for col in range(6): self._full_board_list.append([(row, col)]) # initialize the game pieces @ index 1 (bottom level) for game set-up for x in range(0, len(self._full_board_list), 4): self._full_board_list[x].append(p1_color) for x in range(1, len(self._full_board_list), 4): self._full_board_list[x].append(p1_color) for x in range(2, len(self._full_board_list), 4): self._full_board_list[x].append(p2_color) for x in range(3, len(self._full_board_list), 4): self._full_board_list[x].append(p2_color) def get_full_board_list(self): """get method for _full_board_list :return: a list of lists of the board, containing coords and pieces @ each coord :rtype: list """ return self._full_board_list def show_board(self): """method to show the board in a visually understandable way, * = empty space""" for row in range(0, 36, 6): for col in range(6): list_len = (len(self._full_board_list[row+col])) for num in range(1, list_len): print(self._full_board_list[row+col][num], end="") print((5 - (len(self._full_board_list[row+col])-1)) * "*", end=" ") print("") print("-----------------------------------") class Player: """represents a player""" def __init__(self, name, color): """initializes a player object :param name: name of player :type name: str :param color: color of player pieces :type color: str """ self._player_name = name self._player_color = color self._captured_pieces = 0 self._reserve_pieces = 0 def get_player_name(self): """get method for _player_name :return: player's name :rtype: str """ return self._player_name def get_player_color(self): """get method for _player_color :return: player's color :rtype: str """ return self._player_color def get_captured_pieces(self): """get method for player's _captured_pieces :return: player's _captured_pieces :rtype: int """ return self._captured_pieces def set_captured_pieces(self, num_piece): """set method for player's _captured_pieces, +1 to add a piece, -1 to remove a piece :param num_piece: piece(s) to add to or remove from a player's captured pieces :type num_piece: int """ self._captured_pieces += num_piece def get_reserve_pieces(self): """get method for player's _reserve_pieces :return: player's _reserve_pieces :rtype: int """ return self._reserve_pieces def set_reserve_pieces(self, num_piece): """set method for player's _reserve_pieces, +1 to add a piece, -1 to remove a piece :param num_piece: piece(s) to add to or remove from a player's reserve pieces :type num_piece: int """ self._reserve_pieces += num_piece class FocusGame: """represents the game""" def __init__(self, p1_tup, p2_tup): """initializes a game object :param p1_tup: strings of player1_name and player1_color :type p1_tup: tuple :param p2_tup: strings of player2_name and player2_color :type p2_tup: tuple """ self._player1 = Player(p1_tup[0], p1_tup[1]) self._player2 = Player(p2_tup[0], p2_tup[1]) self._board = Board(self._player1.get_player_color(), self._player2.get_player_color()) self._turn = self._player1 def validate_move(self, player_name, start_loc, end_loc, num_pieces): """checks the validity of any moves :param player_name: name of player who's trying to move :type player_name: str :param start_loc: coord to move pieces from :type start_loc: tuple :param end_loc: coord to move pieces to :type end_loc: tuple :param num_pieces: number of pieces to move :type num_pieces: int :return: notification codes for whether the move is valid or not :rtype: str """ if player_name != self._turn.get_player_name(): # check if it's player's turn return "n_y_t" # Not_Your_Turn code # check locations are possible spaces on board if not -1 < start_loc[0] < 6 or not -1 < start_loc[1] < 6: return "i_s_l" # Illegal_Start_Location code if not -1 < end_loc[0] < 6 or not -1 < end_loc[1] < 6: return "i_e_l" # Illegal_End_Location code # check if end_loc is num_pieces away from start_loc, and only vertical or horizontal move row_move = abs(start_loc[0] - end_loc[0]) column_move = abs(start_loc[1] - end_loc[1]) if not ((row_move == 0 and column_move == num_pieces) or (row_move == num_pieces and column_move == 0)): return "i_l" # Illegal_Location code # check stack for: if piece on top belongs to turn player, & player not trying to move more pieces than in stack for loc in self._board.get_full_board_list(): # loop through locations on board if loc[0] == start_loc: # find start coord if loc[-1] != self._turn.get_player_color(): # check if piece on top belongs to turn player return "i_l" elif num_pieces > (len(loc) - 1): # check not trying to move more pieces than in stack return "i_n_o_p" # Invalid_Number_Of_Pieces code def move_piece(self, player_name, start_loc, end_loc, num_pieces): """move method, for single and multiple moves :param player_name: name of player who's trying to move :type player_name: str :param start_loc: coord to move pieces from :type start_loc: tuple :param end_loc: coord to move pieces to :type end_loc: tuple :param num_pieces: number of pieces to move :type num_pieces: int :return: notification messages, or False for whether the move was completed successfully or not :rtype: str or bool """ # check if move is valid val = self.validate_move(player_name, start_loc, end_loc, num_pieces) if val == "n_y_t": return False elif val == "i_l" or val == "i_s_l" or val == "i_e_l": return False elif val == "i_n_o_p": return False # move picked_up = [] # hold pieces being moved for loc in self._board.get_full_board_list(): # loop through locations on board if loc[0] == start_loc: # find start coord for i in range(num_pieces): # for each piece being moved # picked_up += loc[len(loc) - 1] # add moved piece (from top of stack) to picked_up picked_up.append(loc[len(loc) - 1]) # add moved piece (from top of stack) to picked_up del loc[len(loc) - 1] # delete moved piece (from top of stack) for loc in self._board.get_full_board_list(): # loop through locations on board if loc[0] == end_loc: # find end coord for i in range(len(picked_up), 0, -1): # for each piece in pieces, backwards from the end loc.append(picked_up[i - 1]) # add piece (one by one) to coord # check if stack is > 5 player_obj = self.get_player_object(player_name) self.check_height(player_obj, end_loc) # check win condition if player_obj.get_captured_pieces() >= 6: return f"{player_obj.get_player_name()} Wins" # alternate turn self.set_turn(player_name) return "successfully moved" def reserved_move(self, player_name, location): """move method for moving a piece from player's own reserve :param player_name: name of player who's trying to move :type player_name: str :param location: coord to move piece to :type location: tuple :return: notification messages, or False for whether the move was completed successfully or not :rtype: str or bool """ # check if move is valid val = self.validate_move(player_name, (0, 0), location, 1) if val == "n_y_t": return False elif val == "i_e_l": return False # move player_obj = self.get_player_object(player_name) # check there's pieces in player's reserve if player_obj.get_reserve_pieces() <= 0: return False else: # add piece to board location for loc in self._board.get_full_board_list(): # loop through locations on board if loc[0] == location: loc.append(player_obj.get_player_color()) # add player's piece to location on board player_obj.set_reserve_pieces(-1) # remove piece from player's reserve # check if stack is > 5 self.check_height(player_obj, location) # check win condition if player_obj.get_captured_pieces() >= 6: return f"{player_obj.get_player_name()} Wins" # alternate turn self.set_turn(player_name) return "successfully moved" def check_height(self, player_obj, location): """method to check if stack of pieces is > 5 pieces tall: if so: capture bottom pieces that belong to the other player and/or reserve bottom pieces that belong to player in control of the stack :param player_obj: name of player who's in control of stack :type player_obj: Player :param location: coord to check height of :type location: tuple """ for loc in self._board.get_full_board_list(): if loc[0] == location: # find coord while len(loc) > 6: # stack taller than 5 bottom_piece = loc[1] if bottom_piece == player_obj.get_player_color(): player_obj.set_reserve_pieces(1) else: player_obj.set_captured_pieces(1) del loc[1] def show_pieces(self, loc): """shows pieces at a location on the board :param loc: coord to show :type loc: tuple :return: a list with pieces at that location, index 0 = base level, or "invalid location" :rtype: list or str """ # validation check that coord exists val = self.validate_move(self._turn.get_player_name(), loc, (0, 0), 1) if val == "i_s_l": return "invalid location" # return list of pieces for space in self._board.get_full_board_list(): if space[0] == loc: # find loc return space[1:] def show_reserve(self, player_name): """show a count of pieces in that player's reserve :param player_name: name of player :type player_name: str :return: player's _reserve_pieces :rtype: int """ return self.get_player_object(player_name).get_reserve_pieces() def show_captured(self, player_name): """show count of pieces in that player's captured :param player_name: name of player :type player_name: str :return: player's _captured_pieces :rtype: int """ return self.get_player_object(player_name).get_captured_pieces() def get_player_object(self, player_name): """takes a player's name and returns the associated player object :param player_name: name of player :type player_name: str :return: player object :rtype: Player or bool """ if player_name == self._player1.get_player_name(): return self._player1 elif player_name == self._player2.get_player_name(): return self._player2 else: return False # could also return "not your turn"...? def get_turn(self): """get method for player_turn :return: player object whose turn it is :rtype: Player """ return self._turn def set_turn(self, current_player_name): """set method for player_turn :param current_player_name: name of player :type current_player_name: str """ if current_player_name == self._player1.get_player_name(): self._turn = self._player2 else: self._turn = self._player1 def show_board(self): """shows board for current game""" self._board.show_board() def main(): """for testing""" # READ ME # game = FocusGame(('PlayerA', 'R'), ('PlayerB', 'G')) # print(game.move_piece('PlayerA', (0, 0), (0, 1), 1)) # Returns message "successfully moved" # print(game.show_pieces((0, 1))) # Returns ['R','R'] # print(game.show_captured('PlayerA')) # Returns 0 # print(game.reserved_move('PlayerA', (0, 0))) # Returns False, not per update (message "No pieces in reserve") # print(game.show_reserve('PlayerA')) # Returns 0 if __name__ == '__main__': main()
8363ea201cf4022b745ed54fde3b518686b3ad7f
epicari/Programming_study
/python_test/baek_1159_dict.py
377
3.5625
4
# # 백준 1159 # 딕셔너리 사용 last_name = dict() result = [] for _ in range(int(input())): x = input() if x[0] not in last_name: last_name[x[0]] = 1 else: last_name[x[0]] += 1 for key, value in last_name.items(): if value >= 5: result.append(key) result.sort() if result: print(''.join(result)) else: print('PREDAJA')
7436cb641fd05da665211eb3ebed1ac2bc7dae4b
DominikaJastrzebska/Kurs_Python
/00_start/BMI.py
215
3.65625
4
# 07102019 name = input('Podaj swoje imie: ') weight = float(input('Podaj wage: ')) height = float(input('Podaj wzrost w metrach: ')) BMI = weight/height**2 print(name + ', twoje BMI wynosi', str(round(BMI, 2)))
867fa518dfed40b2bf2d4c0bba78cf34f1844dae
ekukura/hackkerrank
/_algorithms/arrays-and-sorting/insertionsort1.py
1,113
4.09375
4
#!/bin/python3 import math import os import random import re import sys def print_arr(arr): for el in arr: print(el, end = " ") print("") # Complete the insertionSort1 function below. def insertionSort1(n, arr): if n == 1: print(arr) else: insert_num = arr[n-1] found_insertion_point = False cur_ind = n-1 while not found_insertion_point: if cur_ind == 0: arr[cur_ind] = insert_num print_arr(arr) found_insertion_point = True else: cur_comp_val = arr[cur_ind-1] if cur_comp_val < insert_num: arr[cur_ind] = insert_num print_arr(arr) found_insertion_point = True else: arr[cur_ind] = cur_comp_val print_arr(arr) cur_ind -= 1 if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) insertionSort1(n, arr)
cdb3279fe3484e4c02ad26ea36ea484d1435c51c
zhangli709/algorithm009-class01
/Week_04/033.py
887
3.546875
4
# 搜索旋转排序数组 # 1. 暴力破解 class Solution: def search(self, nums: List[int], target: int) -> int: return nums.index(target) if target in nums else -1 # 2. 二分查找 class Solution: def search(self, nums: List[int], target: int) -> int: # return nums.index(target) if target in nums else -1 if nums == []: return -1 l = 0 r = len(nums) - 1 while l < r: mid = l + (r - l) // 2 if nums[mid] < nums[r]: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid else: if nums[l] <= target <= nums[mid]: r = mid else: l = mid + 1 if nums[l] == target: return l else: return -1
b32d7a7043bb69a28269628680a5669f9367d0b2
kostenarov/domashni_po_python
/domashni/tentacle.py
835
3.546875
4
import math #importvame math def shlong(sentence): #funkciq za nai dulga duma long_word = max(sentence.split(), key=len) #namirame q return long_word #vrushatme nai dulgata duma def gcd(list): #funkciq za delitel a = math.gcd(*list) #izpozvame funkciqta za delitel vgradena v python i davame stoinostta na math.gcd(*list) na a return a #vrushtame a sentence = input("vkarai izrechenie: ") #vuvejdame izrechenie longer_word = shlong(sentence) #promenliva koito priema stoinostta na shlong print("nai-dulgata duma e :" + longer_word) #prinitrame nai-dulgata funkciq list = [3, 6, 9, 12, 15, 18] #list za chisla if len(list) < 5: #proverqva dali lista e po-golqm ot 5 print("kus e") #prinitra che e kus else: print(gcd(list)) #ako ne e izpulneno printira delitelq i duljinata print(len(list))
06938ce610ec692adb560217c14b1ebde56d919b
yongdae/hello-prime-python
/ch13/TestCircleRectangle.py
470
3.6875
4
from CircleFromGeometricObject import Circle from RectangleFromGeometricObject import Rectangle class main(): circle = Circle(1.5) print("원", circle) print("넓이는", circle.getArea(), "입니다") print("지름은", circle.getPerimeter(), "입니다") rectangle = Rectangle(2, 4) print("\n사각형", rectangle) print("넓이는", rectangle.getArea(), "입니다") print("둘레는", rectangle.getPerimeter(), "입니다") main()
1c7e3c2e19e5f4266b8ff9783a34545be042d31b
lucasfavero/100dayscode
/05 - Beginner - Generate Random Password/generate_random_password.py
540
3.8125
4
import string import random print("Welcome to the Password Generator!") letters_len = int(input("How many letters would you like?: ")) symbols_len = int(input("How many symbols would you like?: ")) numbers_len = int(input("How many numbers would you like?: ")) letters = string.ascii_letters symbols = string.punctuation nums = string.digits password = random.sample(letters, letters_len) + random.sample(symbols, symbols_len) + random.sample(nums, numbers_len) password = "".join(random.sample(password, len(password))) print(password)
0da2dfac9ed8b9817570040103dee1c1c85e1894
joaovitorle/Exercicios_de_Python_Curso_em_video
/ex026.py
291
3.859375
4
frase= input('Digite uma frase: ').strip().upper().lower() cont1= len(frase) cont2= frase.count('a',0,) enc= frase.find('a')+1 cont3= frase.rfind('a')+1 print(f' A letra A aparece {cont2}\n A primeira letra A apareceu na posição {enc}\n A última letra A apareceu na posição {cont3}')
16347c3379671d878f31f6c70bd2c1ea7071bfc2
oneshan/Leetcode
/accepted/004.median-of-two-sorted-arrays.py
1,561
3.71875
4
# # [4] Median of Two Sorted Arrays # # https://leetcode.com/problems/median-of-two-sorted-arrays # # Hard (21.46%) # Total Accepted: # Total Submissions: # Testcase Example: '[1,3]\n[2]' # # There are two sorted arrays nums1 and nums2 of size m and n respectively. # # Find the median of the two sorted arrays. The overall run time complexity # should be O(log (m+n)). # # Example 1: # # nums1 = [1, 3] # nums2 = [2] # # The median is 2.0 # # # # Example 2: # # nums1 = [1, 2] # nums2 = [3, 4] # # The median is (2 + 3)/2 = 2.5 # # # class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ k = len(nums1) + len(nums2) if k & 1: return self.recur(nums1, nums2, k // 2 + 1) else: n1 = self.recur(nums1, nums2, k // 2) n2 = self.recur(nums1, nums2, k // 2 + 1) return (n1 + n2) * 1.0 / 2 def recur(self, nums1, nums2, k): if not nums1: return nums2[k - 1] if not nums2: return nums1[k - 1] if k == 1: return min(nums1[0], nums2[0]) isOdd, k = k & 1, k // 2 n1 = nums1[k - 1] if len(nums1) >= k else float('inf') n2 = nums2[k - 1] if len(nums2) >= k else float('inf') if n1 < n2: return self.recur(nums1[k:], nums2, k + isOdd) return self.recur(nums1, nums2[k:], k + isOdd)
5f241f841e78d54ab3fc35770d809c1504b1ca5a
ProgFuncionalReactivaoct19-feb20/clase03-erickgjs99
/enClase.py
281
3.625
4
""" autor: @erickgjs99 file: enClase.py dado un conjunto de palabras filtrar todas aquellas que sean palindromas """ word = ["oro", "pais", "ojo", "oso", "radar", "sol", "seres"] w_alreves = filter(lambda x: "".join(reversed(x)) == x, word) print(list(w_alreves))
52e3b191c45032eed46081e51bfe8b6e5f279da1
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/mltmat013/piglatin.py
1,511
3.734375
4
def toPigLatin(s): s += ' ' word = '' cons = '' pLatin = '' for i in s: if i != ' ': word += i else: if word[0].upper() in ('A','E','I','O','U'): word += 'way ' pLatin += word elif not (word[0].upper() in ('A','E','I','O','U')): while not (word[0].upper() in ('A','E','I','O','U')): cons = cons + word[0] word = word[1:len(word)] word += 'a' + cons + 'ay ' pLatin += word word = '' cons = '' #print(pLatin) return pLatin def toEnglish(s): s += ' ' word = '' pLatin = '' skip = 0 for i in s: if i != ' ': word += i else: if word[len(word)-3 : len(word)] == 'way': word = word[0: len(word) -3] pLatin += word + ' ' elif (word[ len(word) - 2: len(word)] == 'ay') and (word[len(word)-3] != 'w'): word = word[0: len(word) -2] for j in range(len(word)-1,0,-1): if word[j] == 'a': skip = j continue word = word[skip+1: len(word)] + word[0:skip] pLatin += word + ' ' word = '' return pLatin
49e7d2e2192d8dde689fd66532941ba5ed75f515
mapullins/MR2_Lab
/stat_ranker.py
4,093
3.5625
4
import numpy as np import pandas as pd #Import the Combined Data DataFrame for reference df_data = pd.read_csv('Total_Data.csv') #Returns a monster's growth stat multipliers def growth(main, sub): #Dictionary for growth multipliers g_dict = {1:0, 2:.5, 3:1, 4:1.5, 5:2} #Access the specific monster data entry = df_data[(df_data.Main == main) & (df_data.Sub == sub)] #Creates a numpy array of the growth numbers g_nums = np.array(entry.iloc[0,15:21]).astype(int) #Applies the dictionary conversion to the growth numbers return np.array([g_dict[i] for i in g_nums]) #Takes an array of stats and monster type and outputs the stats def modified_stats(main, sub, stats): #Records the growth numbers growth_mult = growth(main, sub) #Applies the multiplier actual_stats = np.array(stats) * growth_mult return [(actual_stats[0], 'L'), (actual_stats[1], 'P'), (actual_stats[2], 'I'), (actual_stats[3], 'Sk'), (actual_stats[4], 'Sp'), (actual_stats[5], 'D')] #Takes an array of stats and monster type and returns a corrected list def corrected_stats(main, sub, stats): #Get unsorted stats with multiplier applied mod_stats = modified_stats(main, sub, stats) #Future ordered list of stats correct_stats = [] #Create a one entry DataFrame to use df_small = df_data[(df_data.Main == main) & (df_data.Sub == sub)] #Loop to populate correct_list: while len(mod_stats) > 0: #Record highest stat number max_num = max(mod_stats)[0] #Create a list of stats with highest stat number high_stats = [st for (num, st) in mod_stats if num == max_num] #Amend list so it includes stat order, then sort high_stats = [(df_small[st].iloc[0], st) for st in high_stats] high_stats.sort() #Add true stat order to correct stats for entry in high_stats: correct_stats.append(entry[1]) #Delete recorded stats frim mod_stats mod_stats = [entry for entry in mod_stats if entry[0] != max_num] return correct_stats #Counts how many corrected stats match def stat_match(main_1, sub_1, stats_1, main_2, sub_2, stats_2): #Gets the corrected stat order cor_stats_1 = corrected_stats(main_1,sub_1,stats_1) cor_stats_2 = corrected_stats(main_2,sub_2,stats_2) #Loops to check how many positions match match = 0 for i in range(len(cor_stats_1)): if cor_stats_1[i] == cor_stats_2[i]: match += 1 return match #Checks for any classification differences on lab type given an input DataFrame of lab results def lab_check(df): #Create a rating dictionary lab_text = {0: 'Up to You', 1: 'Not Good', 2: 'Unsure', 3: 'Fine', 4: 'Good', 6: 'Great'} #Loop through the DataFrame for ind, row in df.iterrows(): #Track types and stats first_main = row['Main 1'] first_sub = row['Sub 1'] first_stats = [row['Lif 1'], row['Pow 1'], row['Int 1'], row['Ski 1'], row['Spd 1'], row['Def 1']] second_main = row['Main 2'] second_sub = row['Sub 2'] second_stats = [row['Lif 2'], row['Pow 2'], row['Int 2'], row['Ski 2'], row['Spd 2'], row['Def 2']] #Determine how many matches there are match_num = stat_match(first_main, first_sub, first_stats, second_main, second_sub, second_stats) #Determine whether this matches what the results say match = (lab_text[match_num] == row['Type']) if match == True: print('Fine') if match == False: print(row) print('Predicted order was {0} for the first and {1} for the second. The match was considered {2}, but was actually {3}.'.format(corrected_stats(first_main, first_sub, first_stats), corrected_stats(second_main, second_sub, second_stats), lab_text[match_num], row['Type']))
4e78771587b683d6dd554f42de66d17417baee25
piyush546/Machine-Learning-Bootcamp
/Fun programming/wc.py
1,050
3.828125
4
# -*- coding: utf-8 -*- # Filename to be accessed Filename = input() # To open the file File = open(Filename, 'r') List = File.readlines() # To count characters def count_char(list2): list2 = "".join(list2) count = 0 for var in range(0, len(list2)): if list2[var] == "\n": continue else: count += 1 return count # to count words list4 = [] def count_words(list3): for var1 in range(0, len(list3)): list4.extend(list3[var1].split()) return len(list4) # To count unique words def unique_words(list5): list6 = set(list4) return len(list6) # Wc function def wc(list1): print("Number of characters:", count_char(list1)) print("Number of words:", count_words(list1)) print("Number of lines:", len(list1)) print("Number of unique words:", unique_words(list1)) # Function call for wc wc(List) # File closed File.close() # Input = romeo.txt """output :Number of characters: 163 Number of words: 33 Number of lines: 4 Number of unique words: 26"""
fc6548091f736e9ffac490041a8c6a8d06703897
AnandMurugan/Python
/variables.py
218
4.125
4
#!/usr/bin/env python firstname = "Firstname" lastname = "Lastname" age = 95 birthdate = "01/01/1901" print ("My name is %s %s" % (firstname, lastname)) print ("I was born on %s and my age is %s" % (birthdate, age))
3af37bd8dfb6dd85c6eef017852300e51545fd2d
jay-ucla/ctci
/2linkedlist.py
6,996
3.984375
4
class LinkedList: class Node: next = None item = None def __init__(self, d): self.item = d root = None def __init__(self, *items): self.addAll(*items) def add(self, item): #No elements in LinkedList if self.root is None: self.root = LinkedList.Node(item) return next = self.root while next.next is not None: next = next.next next.next = LinkedList.Node(item) def addAll(self, *items): for i in range(len(items)): self.add(items[i]) def remove(self, item): assert(self.root is not None) curr = self.root prev = None while curr.item is not item: prev = curr curr = prev.next #First node if prev is None: self.root = self.root.next else: prev.next = curr.next def traverse(self): if self.root is None: return [] curr = self.root traversal = [curr.item] while curr.next is not None: curr = curr.next traversal.append(curr.item) #print(traversal) return traversal def reverse(self): if self.root is None: return curr = self.root self.root = None while curr is not None: #Store next node temp = curr.next #Point current node to previous node (Reverse) curr.next = self.root #Store curr node as previous node(head of list) self.root = curr #Go to next node curr = temp def nodeAt(self, i): if i < 1 or self.root is None: return None nd = self.root while nd.next is not None and i > 1: nd = nd.next i = i-1 if i > 1: return None return nd def deleteDuplicateSet(ll): if ll.root is None: return data_set = {} curr = ll.root prev = None while curr is not None: try: data_set[curr.item] prev.next = curr.next except KeyError: data_set[curr.item] = '' prev = curr finally: curr = curr.next def checkPalindrome(ll): if ll.root is None: return False slow = ll.root fast = ll.root stack = [] while fast is not None and fast.next is not None: stack.append(slow.item) fast = fast.next.next slow = slow.next #print(stack) #odd list if fast is not None: slow = slow.next while slow is not None: if slow.item == stack.pop(): slow = slow.next else: return False return True def intersection(ll1, ll2): assert(ll1.root is not None and ll2.root is not None) curr1 = ll1.root curr2 = ll2.root l1 = 1 l2 = 1 while curr1.next is not None: l1 += 1 curr1 = curr1.next while curr2.next is not None: l2 += 1 curr2 = curr2.next #No intersection if last node is not same if not curr1 == curr2: return 0 if l1 > l2: k = l1 - l2 longer = ll1.root shorter = ll2.root else: k = l2 - l1 longer = ll2.root shorter = ll1.root while k > 0: longer = longer.next k = k-1 i=0 while longer != shorter and shorter is not None: longer = longer.next shorter = shorter.next i += 1 return i+1 def joinLinkedList(ll1, ll2, k): #Joins end of ll1 to ll2 at k position joined = LinkedList(*ll1.traverse()) end1 = joined.root while end1.next is not None: end1 = end1.next i = 1 i_pt = ll2.root while i != k: i += 1 i_pt = i_pt.next end1.next = i_pt return joined def detectLoop(ll): #Fast and slow pointer can detect loop fast = ll.root slow = ll.root while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if fast == slow: break if fast is None or fast.next is None: return None slow = ll.root while fast is not None: if fast == slow: return fast fast = fast.next slow = slow.next return None def testLinkedList(): ll = LinkedList(1) assert(ll.traverse()==[1]) ll.remove(1) assert(ll.traverse()==[]) try: ll.remove(1) raise Exception("Error in remove") except AssertionError: pass ll.add(2) ll.add(3) assert(ll.traverse() == [2,3]) ll.remove(2) assert(ll.traverse()==[3]) ll.add(4) ll.add(1) assert(ll.traverse()==[3,4,1]) ll.remove(1) ll.remove(4) assert(ll.traverse()==[3]) ll.addAll(1,2,3,4,5,6,4,3,2,5,6) assert(ll.traverse()==[3,1,2,3,4,5,6,4,3,2,5,6]) ll_list = ll.traverse() ll_list.reverse() ll.reverse() assert(ll.traverse()==ll_list) ll.reverse() ll_list.reverse() assert(ll.traverse()==ll_list) deleteDuplicateSet(ll) assert(ll.traverse()==[3,1,2,4,5,6]) ll2 = LinkedList(1,2,3,2,1) assert(checkPalindrome(ll2)==True) ll2 = LinkedList(1,2,2,1) assert(checkPalindrome(ll2)==True) ll2 = LinkedList(1,2,3,3,2,1) assert(checkPalindrome(ll2)==True) ll2 = LinkedList(1,2,3,3,4,1) assert(checkPalindrome(ll2)==False) ll2 = LinkedList(1,2,3,2,3) assert(checkPalindrome(ll2)==False) ll1 = LinkedList(1,2,3,4,5) ll2 = LinkedList(21,22,23,24,25) assert(intersection(ll1, ll2) == 0) joined = joinLinkedList(ll1, ll2, 4) assert(joined.traverse() == [1,2,3,4,5,24,25]) assert(intersection(joined, ll2) == 4) joined = joinLinkedList(ll2, ll1, 5) assert(joined.traverse() == [21,22,23,24,25,5]) assert(intersection(joined, ll2) == 0) assert(intersection(joined, ll1) == 5) assert(detectLoop(ll1) == None) assert(detectLoop(LinkedList()) == None) assert(detectLoop(LinkedList(1)) == None) assert(detectLoop(LinkedList(1, 2)) == None) lll = LinkedList(*ll1.traverse()) #1->2->3->4->5->1 lll.nodeAt(5).next = lll.root assert(detectLoop(lll).item == 1) #1->2->3->4->5->2 lll.nodeAt(5).next = lll.nodeAt(2) assert(detectLoop(lll).item == 2) #1->2->3->4->5->3 lll.nodeAt(5).next = lll.nodeAt(3) assert(detectLoop(lll).item == 3) #1->2->3->4->5->4 lll.nodeAt(5).next = lll.nodeAt(4) assert(detectLoop(lll).item == 4) #1->2->3->4->5->5 lll.nodeAt(5).next = lll.nodeAt(5) assert(detectLoop(lll).item == 5) testLinkedList()
fbf3ceebeb4976b0af87e16e3c0662cd57164da6
bradykieffer/syde223
/tutorial7/tree.py
8,093
4.09375
4
# tree.py """ Binary Search Tree implementation. """ class BinarySearchTree(object): """ Store values within a binary tree structure for later lookup. """ def __init__(self): self.root = None self._size = 0 # Do not want to directly modify this @property def length(self): return self._size def __contains__(self, key): return self._get(key, self.root) is not None def __delitem__(self, key): self.delete(key) def __getitem__(self, key): return self.get(key) def __iter__(self): return self.root.__iter__() def __len__(self): return self._size def __setitem__(self, key, val): self.insert(key, val) def __str__(self): if self.root: return self.root.__str__() else: return 'Empty Tree.' def delete(self, key): if self._size > 1: to_remove = self._get(key, self.root) if to_remove: self.remove(to_remove) self._size -= 1 else: raise KeyError(f'Error, {key} is not in the tree.') elif self._size == 1 and self.root.key == key: self.root = None self._size = 0 else: raise KeyError(f'Error, {key} is not in the tree.') def get(self, key): if self.root: result = self._get(key, self.root) if result: return result.value else: return None return None def insert(self, key, value): if self.root: # Call a recursive insert self._insert(key, value, self.root) else: self.root = Node(key, value) self._size += 1 def remove(self, node): if node.is_leaf(): # Simple, this node has no children if node.is_left_child(): node.parent.left_child = None else: node.parent.right_child = None else: # Node only has one child if node.has_left_child(): if node.is_left_child(): node.left_child.parent = node.parent node.parent.left_child = node.left_child elif node.is_right_child(): node.left_child.parent = node.parent node.parent.right_child = node.left_child else: # Current node has no parent, it's the root node.replace_data( node.left_child.key, node.left_child.value, left=node.left_child.left, right=node.left_child.right ) elif node.has_both_children(): # Interior succ = node.find_successor() succ.splice_out() node.key = succ.key node.value = succ.value else: if node.is_left_child(): node.right_child.parent = node.parent node.parent.left_child = node.right_child elif node.is_right_child(): node.right_child.parent = node.parent node.parent.right_child = node.right_child else: # Current node has no parent, it's the root node.replace_data( node.right_child.key, node.right_child.value, left=node.right_child.left, right=node.right_child.right ) def _get(self, key, current_node): if not current_node: return None elif current_node.key == key: return current_node elif key < current_node.key: return self._get(key, current_node.left_child) else: return self._get(key, current_node.right_child) def _insert(self, key, value, current_node): """ Recursively search for a place to insert the key value pair """ if key < current_node.key: if current_node.has_left_child(): self._insert(key, value, current_node.left_child) else: current_node.left_child = Node( key, value, parent=current_node) else: if current_node.has_right_child(): self._insert(key, value, current_node.right_child) else: current_node.right_child = Node( key, value, parent=current_node) class Node(object): """ A node within a binary tree. """ def __init__(self, key, val, left=None, right=None, parent=None): self.key = key self.value = val self.left_child = left self.right_child = right self.parent = parent def __iter__(self): if self: if self.has_left_child(): for elem in self.left_child: yield elem yield self.key if self.has_right_child(): for elem in self.right_child: yield elem def __repr__(self): return f'<Node: [{self.key}: {self.value}]>' def __str__(self, depth=0): ret = '' # Print the right branch if self.right_child is not None: ret += self.right_child.__str__(depth + 1) # Print own value ret += '\n' + ("\t" * depth) + f'{self.value}' # Print left branch if self.left_child is not None: ret += self.left_child.__str__(depth + 1) return ret def find_min(self): current = self while current.has_left_child(): current = current.left_child return current def find_successor(self): succ = None if self.has_right_child(): succ = self.right_child.find_min() else: if self.parent: if self.is_left_child(): succ = self.parent else: self.parent.right_child = None succ = self.parent.find_successor() self.parent.right_child = self return succ def has_both_children(self): return self.left_child is not None and self.right_child is not None def has_children(self): return not self.is_leaf def has_left_child(self): return self.left_child is not None def has_right_child(self): return self.right_child is not None def is_leaf(self): return self.left_child is None and self.right_child is None def is_left_child(self): return self.parent and self.parent.left_child == self def is_right_child(self): return self.parent and self.parent.right_child == self def is_root(self): return not self.parent def replace_data(self, key, value, left, right): self.key = key self.value = value self.left_child = left self.right_child = right if self.has_left_child(): self.left_child.parent = self if self.has_right_child(): self.right_child.parent = self return self def splice_out(self): if self.is_leaf(): if self.is_left_child(): self.parent.left_child = None else: self.parent.right_child = None elif self.has_any_children(): if self.has_left_child(): if self.is_left_child(): self.parent.left_child = self.left_child else: self.parent.right_child = self.left_child self.left_child.parent = self.parent else: if self.is_left_child(): self.parent.left_child = self.right_child else: self.parent.right_child = self.right_child self.right_child.parent = self.parent
634e4ef57e6711ae6ff4a09dacfa6e5479b6d5dc
montanha22/ces22_2020.1
/ces22_2020.1/python1/5.py
598
3.734375
4
def words_until_sam(name_list): count = 0 counting = True for name in name_list: if counting: count = count + 1 if name == 'sam': counting = False return count return count from TestClass import Tester tester = Tester() tester.test(words_until_sam(['a', 'sam', 'b', 'ads', '']) == 2) tester.test(words_until_sam(['a', 'saam', 'b', 'ads', '']) == 5) tester.test(words_until_sam(['sam']) == 1) tester.test(words_until_sam(['saam'] ) == 1) tester.test(words_until_sam(['saam', 'sama', 'sam', 'sam', 'sam'] ) == 3)
2c970afb230f1ef03100b27f2397d7bac0ba8486
blankxz/LCOF
/病毒(3602017秋招真题)/hello.py
261
3.625
4
while 1: n = input() n_list = list(str(n)) for i in range(len(n_list)): if n_list[i] > "1": n_list[i] = "1" if i + 1 < len(n_list): n_list[i+1] = "9" print(n_list) print(int("".join(n_list),2))
874cb2d1155f84188732b3066a967f168a125d02
CarloShadow/CodesByCJ
/Python/Exercicios/Estruturas lógicas e condicionais/exerc1.py
188
4
4
num1 = int(input('Digite o priemiro número: ')) num2 = int(input('Digite o segundo número: ')) if num1 > num2: print(f'O {num1} é o maior') else: print(f'O {num2} é o maior')
137412ec8585938494cbae06805e88d9b05aa203
Mubayo/My-Personal-works
/gui.py
484
4.1875
4
def encrypt(message): """A function that encrypts a message given a set of crypts\n param: message(string) a string we wish to encrypt :rtype: res(a string) with the vowels shifted one position to the right""" vowels = {"a" : "e", "e" : "i", "i" : "o", "o" : "u", "u" : "a"} res = "".join([vowels[char] if char in vowels.keys() else char for char in message.lower()]) return res
95b4b1321e73e3b7391a9004853b28cdc22b0056
1572903465/PythonProjects
/Python多线程/线程加锁/多线程之LOCK锁.py
731
3.59375
4
import threading lock = threading.Lock()#普通锁 重量级锁 data = 0 def add_data(): global data for _ in range(1000000):#连续加 一百万次 lock.acquire()#锁上 data += 1 lock.release()#解锁 def down_data(): global data for _ in range(1000000):#连续减 一百万次 lock.acquire()#锁上 data -= 1 lock.release()#解锁 if __name__ == "__main__": print('程序开始') t = threading.Thread(target = add_data)#target参数填函数名 不要加括号 t2 = threading.Thread(target = down_data) t.start()#开始执行 t2.start() t.join()#堵塞线程 t2.join() print(data) print('程序结束')
ea2f221a2ac3634fea5fd655dc3998127b775299
cdmichaelb/delete_older_files
/main.py
4,528
3.96875
4
"""Delete all files in a directory that are older than a specified time. """ import os import time def main(): """Delete all files in a directory that are older than a specified time.""" # Get the directory name. print("Give me the name of the directory.") dir_name = input("? ") # Get the age in days. print("Give me the age in days.") age = int(input("? ")) still_work_to_do = True each_dir = None while still_work_to_do: if each_dir == None: still_work_to_do, each_dir = do_delete(dir_name, age) elif not each_dir == None: still_work_to_do, each_dir = do_delete(each_dir, age) def do_delete(dir_name, age, recursion=None): try: each_directory = False each_file = False # Get the current time. current_time = time.time() # current_time = os.path.getmtime(dir_name) # Get the file names in the directory. if recursion == None: file_names = os.listdir(dir_name) # Make a seperate list for directories. dir_names = [ dir_name + "/" + file_name for file_name in file_names if os.path.isdir(dir_name + "/" + file_name) ] # Remove directories from file_names # file_names = [file_name for file_name in file_names if not os.path.isdir(os.path.join(dir_name, file_name))] # print(f'{dir_name} has {len(file_names)} files and {len(dir_names)} directories.') # Delete the files. for each_directory in dir_names: #print("Deleting files in " + each_directory + "...") for each_file in os.listdir(each_directory): if ( os.path.getmtime(each_directory + "/" + each_file) < current_time - age * 86400 ): #print( # f"Deleting file: {each_file} in {each_directory} because {os.path.getmtime(each_directory + '/' + each_file)} is older than {current_time - age * 8640} days." #) os.chmod(each_directory + "/" + each_file, 0o777) os.remove(each_directory + "/" + each_file) # Delete the directory. if os.rmdir(each_directory): os.chmod(each_directory, 0o777) dir_names.remove(each_directory) print(f"Deleting directory: {each_directory}.") else: file_names = [ dir_name + "/" + file_name for file_name in file_names if not os.path.isdir(dir_name + "/" + file_name) ] for each_file in file_names: if ( os.path.getmtime(each_file) < current_time - age * 86400 ): #print( # f"Deleting file: {each_file} because {os.path.getmtime(each_file)} is older than {current_time - age * 8640} days." #) os.chmod(each_file, 0o777) os.remove(each_file) # If directory is empty, delete it. if os.rmdir(dir_name): os.chmod(dir_name, 0o777) print(f"Deleting directory: {dir_name}.") else: print(f"Directory: {dir_name} is not empty.") do_delete(dir_name, age) except FileNotFoundError: print("The directory or file does not exist.") except RecursionError: #print("Maximum depth exceeded.") #-- We don't need to know this. It's handled. #print(each_directory) if each_directory == False: return True, None else: return True, each_directory except os.error: if each_file: print(f"Access denied. {each_file}, trying again.") if each_directory: do_delete(each_directory, age) except UnboundLocalError as e: print("Unbound Local Error", e) quit() except PermissionError as e: print("Permission Error", e) if each_directory: do_delete(each_directory, age) except Exception as e: print(e) if each_directory: do_delete(each_directory, age) if recursion: recursion = None return True, None # If there are no more directories to delete, return False. elif not each_directory: return False, None return True, None main() print("Done.")
20b923242047c463724196d610695132736cacb2
MichaelHarrison87/Pytorch-Tutorials
/60-Minute-Blitz/03-neural-networks.py
12,700
4.625
5
# 03 - Neural Networks # https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html # Neural networks are constructed using the torch.nn package. This relies on autograd to define models # and differentiate them. # An nn.Module contains layers, and a method .forward(input) that returns the output of a forward pass. # The typical training procedure for a neural network is: # Define the network, and its trainable weights # Iterate over a dataset of inputs # Forward-pass the inputs through the network to obtain its output # Calculate the loss of this output - how far it is from being correct (per the dataset's labels) # Back-propagate gradients to the network's parameters # Update the network's weights using some update rule, e.g: new_weight = old_weight - learning_rate * gradient # We demonstrate an example below: import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): """ All models need to subclass nn.Module The code for nn.Module requires its subclasses to implement a .forward() method Specifying this .forward() method means autograd will automatically define the .backward() method Can use any Tensor operations in the .forward() method Note: the intended input image spatial dimensions are 32x32. The conv layers have no padding by default, so these will each reduce the dimension by 2. The max pooling layers use 2x2 kernels, with stride defaulting to the kernel size. So the max pooling layers will halve the spatial dimensions. So the sequence of spatial dimensions over the convolutional body is: input - 32x32 conv1 - 30x30 maxpool1 - 15x15 conv2 - 13x13 maxpool2 - 6x6 (tutorial says 6x6, and PyTorch probably crops the last row/column for odd-dimensions, i.e. 13x13 above cropped to 12x12) """ def __init__(self): """Set-up the network, then specify each trainable layer""" super(Net, self).__init__() # CONVOLUTIONAL BODY # 1 input image channel, 6 output channels, 3x3 square conv filters: self.conv1 = nn.Conv2d(1, 6, 3) self.conv2 = nn.Conv2d(6, 16, 3) # NETWORK HEAD - DENSE LAYERS # affine operation: y = Wx + b; note the orig image spatial dims are 6x6; linear activation function self.fc1 = nn.Linear(6 * 6 * 16, 120) # 16 input channels per conv2; we specify 120 output neurons; NB: biases included by default self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): """Specifies forward pass for entire network. Input x will be the original image""" # 1st Conv + Max Pooling Layer x = F.max_pool2d(F.relu(self.conv1(x)), (2,2)) # 2x2 kernel size for the max pooling # 2nd Conv + Max Pooling Layer x = F.max_pool2d(F.relu(self.conv2(x)), 2) # pooling window assumed to be square if only 1 dimension supplied for kernel size # Resize output of 2nd conv block: x = x.view(-1, self.num_flat_features(x)) # Now dense layers + output x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): """Returns the size of the 1D "flattened" vector, which reshapes the 2D (spatial dimensions) output of the network's convolutional body""" size = x.size()[1:] # the first dimension indexes the elements in the minibatch; we flatten each element individually, so remove num_features = 1 for s in size: num_features *= s return num_features net = Net() print(net) # Net( # (conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1)) # (conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1)) # (fc1): Linear(in_features=576, out_features=120, bias=True) # (fc2): Linear(in_features=120, out_features=84, bias=True) # (fc3): Linear(in_features=84, out_features=10, bias=True) # ) # Can get the network's learnable parameters: print(net.parameters()) # <generator object Module.parameters at 0x7f68eb1cdd68> params = list(net.parameters()) print(len(params)) # 10 print(params[0]) # printed below - 6 3x3x1 grids of params, per the conv1 layer # Parameter containing: # tensor([[[[-0.2730, 0.2236, -0.3239], # [ 0.2115, -0.0425, 0.2247], # [-0.0654, 0.2291, -0.3313]]], # [[[-0.3287, -0.1338, 0.2229], # [-0.1355, 0.0688, 0.1971], # [-0.3026, -0.1134, 0.3081]]], # [[[-0.3213, 0.1931, -0.3305], # [-0.0472, 0.2542, 0.1694], # [-0.1009, -0.0919, 0.2019]]], # [[[ 0.2740, -0.1071, 0.0963], # [ 0.3061, -0.1397, 0.2647], # [-0.2039, -0.0873, 0.1427]]], # [[[ 0.3043, 0.0427, -0.1479], # [ 0.1594, 0.2314, 0.0889], # [-0.1319, 0.1223, 0.2084]]], # [[[-0.1980, 0.2613, -0.1524], # [-0.0484, -0.0787, -0.0802], # [-0.0485, -0.1627, 0.2825]]]], requires_grad=True) print(params[0].size()) # torch.Size([6, 1, 3, 3]) - 6 3x3x1 filter windows print(params[1]) # These are the biases for the conv1 layer # Parameter containing: # tensor([ 0.2206, 0.2037, -0.1480, 0.1888, -0.1975, -0.2281], # requires_grad=True) print(params[-1].size()) # torch.Size([10]) - 10 output neurons, per the fc3 layer # The network has 5 layers - 2 conv2d and 3 dense layers; these are each stored in the params list, with # weights and biases separate. Hence: params list is of length 5*2=10 # Try passing an input through the network: image_input = torch.rand(1, 1, 32, 32) # dimension are: (num_inputs, num_channels, height, width) out = net(image_input) # Note: nn.Module is callable, and its .__call__() method includes: result = self.forward(*input, **kwargs) # So calling net on image_input above invokes a forward pass through the network; we don't have to call # .forward() explicitly ourselves # Also, when specifying the input - torch.nn assumes minibatches throughout, so we need to specify the number # of items in the minibatch in the first input dimension (even if it's only 1) # The .unsqueeze(0) method can be used to add a fake batch dimension (as the 0th dimension); e.g: print('\nUnsqueeze:') x = torch.Tensor([[1,2,3], [4,5,6], [7,8,9]]) # dummy single 3x3 image print(x) # tensor([[1., 2., 3.], # [4., 5., 6.], # [7., 8., 9.]]) print(x.size(), x[0].size()) # torch.Size([3, 3]) torch.Size([3]) - x is 2D 3x3; first element is 1D 3-element array y = x.unsqueeze(0) print(y) # tensor([[[1., 2., 3.], # [4., 5., 6.], # [7., 8., 9.]]]) print(y.size(), y[0].size()) # torch.Size([1, 3, 3]) torch.Size([3, 3]) - y is 1x3x3; first element is 2D 3x3 array print('\nInput:') print(image_input.size()) # torch.Size([1, 1, 32, 32]) print('\nOutput:') print(out.size()) # torch.Size([1, 10]) - as expected # Since calling net() on the input invoked a forward pass, we can now perform a backward pass # (zero'ing the gradient buffers first) with random gradients net.zero_grad() out.backward(torch.randn(1, 10), retain_graph=True) # dimension of the vector (for vector-Jacobian product) must match out's # We can now specify a loss, vs some (here, dummy) target: print('\nLoss:') target = torch.rand(10) print(target.size()) # torch.Size([10]) target = target.view(1, -1) # reshape target to have a 1st dimesnion of size 1; -1 specifies all items print(target.size()) # torch.Size([1, 10]) # cf resize with 1st dimension of size of 2: target_alt = target.view(2, -1) print(target_alt.size()) # torch.Size([2, 5]) criterion = nn.MSELoss() # instantiate the loss class first loss = criterion(out, target) # then call it on our specific output and targets; # Note simply doing loss = nn.MSELoss(out, target) resulted in an error, as can't instantiate the loss with these tensors; instead we /call/ the instance on them, as here print(out) # tensor([[-0.0464, 0.0528, 0.0878, 0.0641, 0.0924, 0.0426, 0.0344, -0.0467, 0.0205, 0.1240]], grad_fn=<AddmmBackward>) print(target) # tensor([[0.1165, 0.0041, 0.6117, 0.3702, 0.8794, 0.4346, 0.0966, 0.8392, 0.1809, 0.9308]]) print(loss) # tensor(0.2636, grad_fn=<MseLossBackward>) - verified this is indeed the mean of the squared elementwise differences between output and target above # Note that loss is a scalar, and we can do a backward pass to calc the gradients of all params wrt the loss. # First 0 the gradient buffers: net.zero_grad() # (Note we can access weights/biases and their gradients as attributes of the layers, e.g. nn.Conv2d etc) print('\nConv1:') conv1_weight = net.conv1.weight conv1_bias = net.conv1.bias print(conv1_weight.size(), conv1_bias.size()) # torch.Size([6, 1, 3, 3]) torch.Size([6]) # And can access the gradient attributes of each of these: print(conv1_bias.grad) # tensor([0., 0., 0., 0., 0., 0.]) six 0's, as expected print(conv1_weight.grad.size()) # torch.Size([6, 1, 3, 3]) # Now, as mentioned, we can do a backward pass from loss without specifying a vector argument (as loss is scalar): loss.backward() # And obtain updated gradients: print(conv1_bias.grad) # tensor([-0.0022, -0.0035, -0.0002, -0.0018, 0.0000, -0.0010]) # We could then iterate over all params, get their gradients and do a weight update: learning_rate = 0.01 for param in net.parameters(): param.data.sub_(param.grad.data * learning_rate) # sub_ subtracts in-place - i.e. w = w - grad * lr # Although PyTorch has a package that with a variety of optimisers: import torch.optim as optim optimizer = optim.SGD(net.parameters(), lr=0.01) # We can now use this: optimizer.zero_grad() output = net(image_input) # Forward Pass loss = criterion(output, target) loss.backward() # Backward Pass optimizer.step() # Weight Update # Note: we have to repeatedly clear out the gradients after each step using .zero_grad(), since otherwise # they are accumulated (useful for minibatches - accumualte gradients across all items in the minibatch) # Consider: x1 = torch.tensor([1., 2., 3.], requires_grad=True) x2 = torch.tensor([4., 5., 6.], requires_grad=True) x_batch = torch.stack((x1, x2)) print(x_batch) # tensor([[1., 2., 3.], # [4., 5., 6.]]) print(x_batch.size()) # torch.Size([2, 3]) y = 2 * x_batch z = y.sum() print(z) # tensor(42.) - i.e. 2*(1+...+6) = 2*6*7/2 = 6*7 = 42 z.backward() print('\n') print(x1.grad) # tensor([2., 2., 2.]) print(x2.grad) # tensor([2., 2., 2.]) print('\n') print(z.requires_grad, z.grad) # True None print(y.requires_grad, y.grad) # True None print(x_batch.requires_grad, x_batch.grad) # True None # The gradients above are None (even though requires_grad is True) since these parts of the computation graph # did not involve any trainable parameters, even though we can perfectly well calculate the gradient of z # wrt y or x_batch # Now show gradients in x1 & x2 being accumulated print('\n') x3 = torch.tensor([4., 5., 6.], requires_grad=True) for x in [x1, x2, x3]: y = 3 * x z1 = y.sum() z1.backward() print(x.grad) # gradients: # tensor([5., 5., 5.]) # tensor([5., 5., 5.]) # tensor([3., 3., 3.]) # So since the x1 & x2 objects were not changed (or had their gradient buffers zero'd) before the for loop above, # the gradient from the for loop is accumulated (added) to that from the previous code - hence they have gradient 5. # The fresh vector x3 was not used in the prior code and so its gradient is 3. # Note it is possible to retain intermediate gradients (e.g. of z, y , x_batch above) across .backward() calls (which otherwise removes them) x = torch.tensor([1., 2., 3.], requires_grad=True) y = 1.5 * x y.retain_grad() z = y.sum() z.retain_grad() # We also show gradients accumualting over .backward() calls z.backward(retain_graph=True) z.backward(retain_graph=True) z.backward(retain_graph=True) print('\n') print(x.grad) # tensor([4.5000, 4.5000, 4.5000]) print(y.grad) # tensor([3., 3., 3.]) print(z.grad) # tensor(3.) z.backward() print('\n') print(x.grad) # tensor([6., 6., 6.]) print(y.grad) # tensor([4., 4., 4.]) print(z.grad) # tensor(4.) # Note: by default, after a .backward() pass only accumulates gradients at the leaf nodes of # the computation graph: w = torch.tensor(2., requires_grad=True) x1 = torch.tensor([1.0, 1.5, 2.7], requires_grad=True) y1 = w * x1 # so w and x1 are leaf nodes z1 = y1.sum() z1.backward() print('\n') print(w.grad) # tensor(5.2000) - i.e. 1 + 1.5 + 2.7 = 5.2 print(x1.grad) # tensor([2., 2., 2.])
3bae9f1ad249395cb6f120cfa88f852f77d00037
mbabatunde/CS1301-Assignments
/CS1301Assignments/hw9/hw9.py
720
3.703125
4
#Hw9 #Section C #Mark Babatunde #"I worked on the homework assignment alone, using only this semester's course materials." from functools import reduce def machToFPS(machList): x = map(lambda i: i * 1116.4370079, machList) for i in range(0, len(machList)): print(machList[i], "mach is equivalent to", x[i], "feet per second") def sqPyramidVolume(baseHeightList, volumeList): for i in baseHeightList: x = map(lambda (x,y): (x*x*y)//3, baseHeightList) correctList = filter(lambda y: y in volumeList, x) return (correctList) def makeChange(changeList): return (reduce(lambda x,y: x+y, [changeList[0] * 100, changeList[1] * 25, changeList[2] * 10, changeList[3] * 5, changeList[4] * 1]))
ab3105ca1fa3755b32fe438cef18237605f2082f
NGPHAN310707/C4TB13
/session 7/gameconsole2.py
702
3.65625
4
import random a = (random.randint(0,100)) b = (random.randint(0,2)) print(a,"-",b,"=",a-b) import random a = (random.randint(0,50)) b = (random.randint(0,50)) print(a,"+",b,"+",a+b) import random a = (random.randint(0,10)) b = (random.randint(0,10)) print(a,"*",b,"*",a*b) import random a = (random.randint(0,20)) b = (random.randint(0,20)) c=int(input("a+b")) print(a,"/",b,"/",a/b) a=randint(0,100) b=randint(0,100) c=randint(0,2) d=int(input("CORRECT or INCORRECT?")) print(a,"+"b,"=") if c == 0: print(a+b-3) if c== 0: print float(inf) def main(): print("""HELLO!") Instructions \t*read \t*think \t*answer def display_incompleted_stage(Flush=True): clearscreen():
7908917c6a2426eb4465f04840fca53ad6a1941e
akshay-0505/Python-Learning
/second.py
321
3.734375
4
import array as a from locale import format arr = a.array('i',[]) n = int(input("Enter the length of srray :")) for i in range(n): x=int(input("Enter next value")) arr.append(x) print(arr) print(arr.buffer_info()) print("division is : {:>3.2f}".format(arr[0]/arr[2])) arr2= a. array('i',[]) arr2=arr print(arr2);
920fd336bea42c3ee94121f64a36f7bce0b569a4
sujasriman/guvi
/code/pprog7.py
186
3.78125
4
string=input() l=[] l1=[] temp='' for i in range(len(string)): l.append(string[i]) for i in range(0,len(l),2): l1.append(string[i+1]) l1.append(string[i]) print(''.join(l1))