blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8801ec89583f5434792a224f4f10762fca1c0442
MKAkin/Random-Number
/Final.py
5,440
3.578125
4
import random def gen_digit(): digit = random.randint(0,9) #print(digit) return digit #gen_digit() def gen_numlist(): gen_num=[] for i in range(4): digit = gen_digit() gen_num.append(digit) return gen_num #print(gen_numlist()) def TF(seq1): check = False while check ==False: if (len(seq1) == 4 and seq1.isdigit()): check = True return True else: check = False return False ''' seq = input("Enter a four digit number ") while TF(seq) == False: seq = input("Enter a four digit number ") print(TF(seq)) ''' def recieve(string): check = False t = 0 numlist=[] while check ==False: 0 if TF(string)== True: #(len(string) == 4 and string.isdigit()): #print("good") check = True else: string = input("Please enter a four digit number ") #Won't let you progress unless you enter a four digit number for pos in range(len(string)): numlist.append(int(string[pos])) #print(string) return numlist ''' chars = input("Enter 4 numbers ") print(recieve(chars)) ''' def guess(x,y): list1=[] list2=[] Flist =[] for pos in range(len(x)) : list1.append(int(x[pos])) for pos in range(len(y)) : list2.append(int(y[pos])) #print(list1) # print(list2) for c in range(4): if list1[c]==list2[c]: Flist.append("Y") else: Flist.append("N") #print(Flist) return Flist ''' seq1 = input("Enter 4 numbers ") seq2 = input("Enter another 4 number ") print(guess(seq1,seq2)) ''' def check_char(t,k): char_list =[] Y_list = ["Y","Y","Y","Y"] comp_list=[] right = False for pos in range(len(t)) : char_list.append(t[pos]) #print(char_list) for pos in t : char_list.remove(pos) char_list.append(pos.upper()) #print(char_list) for pos in range(len(t)): if char_list[pos] ==Y_list[pos]: comp_list.append("Y") else: comp_list.append("N") #print(comp_list) for pos in range(len(t)): if comp_list[pos] == Y_list[pos]: right = True else: right = False print(right) return comp_list ''' print(check_char("yhyt")) ''' v = 0 while ((v != 1) or (v!= 2)): v = int(input("Which version would you like to play ")) if v == 1 : #THIS IS VERSION 1 OF THE PROGRAM count = 0 gen_num =[] attempt =[] is_right = False gen_num = gen_numlist() #print(gen_num) while ((is_right == False) and (count < 10)): count = count + 1 user = input("Guess the 4 digit number ") print(count) for c in range(4): for pos in attempt: attempt.remove(pos) #print(attempt) print("Your guess was",recieve(user)) print(guess(user,gen_num)) for pos in range(4): attempt.append(int(user[pos])) #print(attempt) if attempt[pos] == gen_num[pos]: is_right = True else: is_right = False if is_right == False: print("Sorry your guess was wrong") if is_right == True: print("You won") else: print("You ran out of attempts, GAME OVER") elif v == 2: #THIS IS VERSION 2 OF THE PROGRAM use_list =[] gen_list = [] compare_list=[] correct = False counter = 0 gen_list = gen_numlist() #print(gen_list) while ((correct == False) and (counter < 10)): counter = counter + 1 print(counter) num=input("Enter 4 numbers ") for pos in range(4): for pos in compare_list: compare_list.remove(pos) #print(compare_list) for pos in range(4): for pos in use_list: use_list.remove(pos) #print(use_list) print("Your guess was",recieve(num)) for pos in range(4): use_list.append(int(num[pos])) #print(use_list) for pos in range(4): if use_list[pos] == gen_list[pos]: compare_list.append("Y") elif use_list[pos] < gen_list[pos]: compare_list.append("L") elif use_list[pos] > gen_list[pos]: compare_list.append("H") print(compare_list) if use_list[pos] == gen_list[pos]: correct = True else: correct = False if correct == True: print("You won") else: print("You ran out of attempts, GAME OVER")
9f92a1be81a1a0cc7a5b089059248d2a328cf781
bchiud/cs61a
/tree.py
1,024
3.703125
4
class Tree: def __init__(self, label, branches=[]): for c in branches: assert isinstance(c, Tree) self.label = label self.branches = list(branches) def __repr__(self): if self.branches: branches_str = ', ' + repr(self.branches) else: branches_str = '' return 'Tree({0}{1})'.format(self.label, branches_str) def is_leaf(self): return not self.branches def __eq__(self, other): return type(other) is type(self) and self.label == other.label \ and self.branches == other.branches def __str__(self): def print_tree(t, indent=0): tree_str = ' ' * indent + str(t.label) + "\n" for b in t.branches: tree_str += print_tree(b, indent + 1) return tree_str return print_tree(self).rstrip() def copy_tree(self): return Tree(self.label, [b.copy_tree() for b in self.branches])
2e1c43c81ee231dba1876fc287bba2e4b555abcb
jichunwei/MyGitHub-1
/PythonTest/Python_100/P27.py
344
3.84375
4
#coding:utf-8 ''' 题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来 ''' def output(N,l): if l == 0: return else: print N[l-1] return output(N,l-1) if __name__ == "__main__": s = raw_input("Please enter a string: ") lth = len(s) output(s,lth)
e2407f25e23d8562116d3deab8a009cd4bff21da
brianwoo/python-for-informatics
/exercise5/compute.py
409
3.9375
4
total = 0 count = 0 while True: try: input = raw_input("Enter a number:") if input == "done": print "Total: ", total print "Count: ", count # in case of div by 0 if count > 0: print "Average: ", float(total) / float(count) else: print "Average: ", float(total) break number = float(input) total = total + number; count = count + 1; except: print "Invalid input"
fd04b4581adc2c8f5d04369cb10aa696364a1066
brlrb/Algorithm-Analysis
/Python/MoveZeros.py
481
3.640625
4
# Problem 283: Move Zeroes // LeetCode.com class Solution: nums = [1,0,3,3,0,9,0,6] def moveZeroes(self, nums): """ Do not return anything, modify nums in-place instead. """ counter = 0 counter2 = 0 print(nums) for counter in range(len(nums)): if nums[counter] !=0: nums[counter2], nums[counter] = nums[counter], nums[counter2] counter2 = counter2 + 1
07cb320c1cb52034a1962797a863db67424e30d0
Baidaly/datacamp-samples
/14 - Data manipulation with Pandas/chapter 2 - Aggregating Data/7 - What percent of sales occurred at each store type.py
978
4.0625
4
''' While .groupby() is useful, you can calculate grouped summary statistics without it. Walmart distinguishes three types of stores: "supercenters", "discount stores", and "neighborhood markets", encoded in this dataset as type "A", "B", and "C". In this exercise, you'll calculate the total sales made at each store type, without using .groupby(). You can then use these numbers to see what proportion of Walmart's total sales were made at each. ''' # Calc total weekly sales sales_all = sales["weekly_sales"].sum() # Subset for type A stores, calc total weekly sales sales_A = sales[sales["type"] == "A"]["weekly_sales"].sum() # Subset for type B stores, calc total weekly sales sales_B = sales[sales["type"] == "B"]["weekly_sales"].sum() # Subset for type C stores, calc total weekly sales sales_C = sales[sales["type"] == "C"]["weekly_sales"].sum() # Get proportion for each type sales_propn_by_type = [sales_A, sales_B, sales_C] / sales_all print(sales_propn_by_type)
faec819aae020d7523f90a6532c0d4e66084d169
Icaro-G-Silva/AlmostNothingUseful
/Palindrome/Python/palindrome.py
197
4.15625
4
word = str(input('Please, write a word: ')) rWord = word[::-1] if word == rWord: print(f'The word {word} is a palindrome!') else: print(f'The word {word} is not a palindrome! Look -\n{rWord}')
7d50758534c3047b58269be0db0da9cdb08ce1a7
michealbradymahoney/CP1404-2017-SP2
/prac_02/passwordChecker2.py
1,186
4.1875
4
__author__ = 'Micheal Brady-Mahoney' import random import string SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]\<>?{}|" def password_generator(size=8, chars=string.ascii_letters + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def main(): permittedChars='' numberOfChars = input("How long a password? ") while (numberOfChars.isalpha() or len(numberOfChars) == 0 or numberOfChars.isspace()): print("***ERROR*** \n Enter only numbers") numberOfChars = input("How long a password? ") numberOfChars = int(numberOfChars) if (bool(input("Special characters required? "))): permittedChars += SPECIAL_CHARACTERS if (bool(input("Allow Uppercase Letters? "))): permittedChars += string.ascii_uppercase if (bool(input("Allow Lowercase Letters? "))): permittedChars += string.ascii_lowercase if (bool(input("Allow digit Letters? "))): permittedChars += string.digits print(password_generator(numberOfChars, permittedChars)) #userLength = int(input("Enter min length: ")) #specialCharsReq = bool(input("Special characters required? ")) #print("You generated password is: ", password) main()
66e48300dcbde8f14e6aa9e9fb5ba33ac378ddac
emanueldicristofaro/Python-Project--1
/Proyecto/main.py
2,995
3.71875
4
import pedidos import banco # Proyecto #1 # Integrantes: # Emanuel Di Cristofaro Esposito # Aaron Perez Pereira # Boris Torrado Hernandez # En este módulo presenta el menú principal del sistema # Registro de nuevos clientes, mostrar los mismos, ver info de la tarjeta, iniciar sesión y cerrar el sistema. clients = {} option = '' while option != '5': if option == '1': #Registro de nuevos clientes. nif = int(input('Por favor indique su cédula: ')) name = input('Por favor indique su nombre completo: ') address = input('Indique su dirección: ') phone = int(input('Indique su número telefónico: ')) email = input('Indique su correo electrónico: ') client = {'nombre':name, 'dirección':address, 'teléfono':phone, 'email':email} clients[nif] = client if option == '2': #Buscar los clientes registrados. nif = int(input('Por favor indique su cédula: ')) if nif in clients: print() print('NIF:', nif) for key, value in clients[nif].items(): print(key.title() + ':', value) else: print('No se encuentra registrado en el sistema') if option == '3': # Mostrar información de una tarjeta del cliente registrado. nif = int(input('Por favor indique su cédula: ')) eleccion = input('Indique el tipo de tarjeta (Débito (deb) o Crédito (cre)): ') eleccion = eleccion.lower() if eleccion == 'deb': banco.encontrarDebito(nif) elif eleccion == 'cre': banco.encontrarCredito(nif) else: print('Por favor indicar lo solicitado') if option == '4': #Para poder acceder al sistema de pedidos. nif = int(input('Por favor indique su cédula: ')) if nif in clients: nombre = clients[nif].get('nombre') pedidos.pedidoSandwiches(nombre) option = '5' else: print('La cedula introducida no se encuentra en el sistema') print() print('Bienvenidos a la tienda de Sandwiches rockeros GUNS N ROSES, desde acá podrá pedir los sandwiches más') print('suculentos. Antes de continuar es necesario que se registe en el sistema o inicie sesión:') print() print('Sandwiches...') print('╔═╦╦╦═╦═╗╔═╗╔═╦═╦═╦═╦═╗') print('║║║║║║║╚╣║║║║═║║║╚╣═╣╚╣') print('╠╗║║║║╠╗║║║║║╚╣║╠╗║═╬╗║') print('╚═╩═╩╩╩═╝╚╩╝╚╩╩═╩═╩═╩═╝') print('"Los mejores sandwiches que podrás comer"') print() option = input('\nMenú de opciones\n(1) Registrarse\n(2) Información del cliente\n(3) Ver información de la tarjeta\n(4) Iniciar sesión\n(5) Terminar\nElige una opción:') # ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
d8ffa6107ffa7a6785e9b7ff370403325bf03cee
szqh97/test
/python/91advices/func_value.py
970
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def inc(n): print id(n) n = n + 1 print id(n) n = 3 print id(n) inc(n) print n print '-----------' def change_list(orginator_list): print 'orgnator_list is:', orgnator_list new_list = orgnator_list new_list.append('I am new') print 'new list is :', new_list return new_list orgnator_list = ['a', 'b', 'c'] new_list = change_list(orgnator_list) print new_list print orgnator_list print '==========================' def change_me(org_list): print id(org_list) new_list = org_list print id(new_list) if len(new_list) > 5: new_list = ['a', 'b', 'c'] for i, e in enumerate(new_list): if isinstance(e, list): new_list[i] = '***' print new_list print id(new_list) test1 = [1, ['a', 1, 3], [2, 1], 6] print test1 change_me(test1) print test1 print '......' test2 = [1, 2, 3, 4, 5, [1, 2], 6 ] print test2 change_me(test2) print test2
794446202f6c8bf9f52b120aa4a1825ba0937084
Uche-Clare/python-challenge-solutions
/Moses Egbo/Phase 1/Python Basic 1/Day 2 task/task_6.py
246
4.1875
4
''' Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers. ''' num = (input("Input numbers separated by commas :")) n = num.split(',') print(n) print(tuple((n)))
55e89092844450a6465d8841c92514b589921705
AbdussamadYisau/30daysOfCodeWithECX
/Day6.py
358
4.3125
4
# This code returns the power set of a particular list, in the form of sublists. def power_list(arr): powerSet = [[]] for num in arr: #Iterate over the sub sets so far for subSet in powerSet: # Add a new subset consisting of the subset at hand powerSet = powerSet + [list(subSet) + [num]] return(powerSet) print(power_list([2,4,6]))
e0b39e579f79334402fa601d7516a7f7ec39c428
AnJian2020/Leetcode
/chapter5/二叉树层次遍历.py
1,486
3.90625
4
# -*- coding:utf-8 -*- class TreeNode(object): def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=right class Tree(object): def __init__(self,root=None): self.root=root def add(self,item): treeNode=TreeNode(item) if not self.root: self.root=treeNode return else: stack=[] stack.append(self.root) while stack: currentNode=stack.pop(0) if currentNode.left is None: currentNode.left=treeNode return elif currentNode.right is None: currentNode.right=treeNode return else: stack.append(currentNode.left) stack.append(currentNode.right) class LevelOrder(): def levelOrder(self,treeNode): queue=[] result=[] queue.append(treeNode) while queue: currentNode=queue.pop(0) result.append(currentNode.data.data) if currentNode.left: queue.append(currentNode.left) if currentNode.right: queue.append(currentNode.right) return result if __name__=="__main__": treeList=['A','B','C','D','E','F','G'] tree=Tree() for item in treeList: tree.add(TreeNode(item)) print(LevelOrder().levelOrder(tree.root))
0a5ec273526a6b0ea291aad45a2cd0b63bbdd899
zhang-ru/learn-Python
/codewars_Dec11 pin.py
738
3.546875
4
import itertools def get_pins(observed): l = {"1":"124", "2":"1235", "3":"236","4":"1457","5":"24568","6":"3569","7":"478","8":"57890","9":"689","0":"80"} temp = [] result=l[observed[0]] if len(observed) ==1: return list(''.join(result)) else: for i in range(1,len(observed)): result = list(itertools.product([''.join(x) for x in result],l[observed[i]],)) return [''.join(x) for x in result] # return result # return list(itertools.product("124",['12','24'])) #ansewer: from itertools import product ADJACENTS = ('08', '124', '2135', '326', '4157', '52468', '6359', '748', '85790', '968') def get_pins(observed): return [''.join(p) for p in product(*(ADJACENTS[int(d)] for d in observed))] print(get_pins("8"))
7c6b2a90c060d5113dbc3d1ba16073f6bf753477
PuneetDua/Python
/Tic_Tac_Toe_Game.py
4,225
4.40625
4
# -*- coding: utf-8 -*- """ Tic Tac Toe Game app @author: Puneet Dua """ ''' Actions need to be taken care of - board - Displaying that board - Alternate Turns, i.e, playing game - Check for wins, tie - check for rows, columns, diagonal ''' # Reqd for computer to chose positions randomly import random # empty board board_elements = ["-" for _ in range(0,9)] # to keep track of vacant positions that will be filled vacant_positions = [i for i in range(0,9)] current_player = 'User' game_still_going= True # It will keep track to stop if we get winner Winner=None # To display the board def board(): print(board_elements[0]+" | "+board_elements[1]+" | "+board_elements[2]) print(board_elements[3]+" | "+board_elements[4]+" | "+board_elements[5]) print(board_elements[6]+" | "+board_elements[7]+" | "+board_elements[8]) # To play the game, handle turns, check for winner/tie def play_game(): global Winner board() # Display board initially while game_still_going: handle_turn(current_player) flip_player() Winner = check_win() check_tie() # The game has ended here if Winner == 'X' or Winner == 'O': print(Winner + " won.") elif Winner == None: print("It's a Tie") # Handling the user and computer turns #def usr_turn(): def handle_turn(player): # need to check the winner after each entry, and same will be updated and # game will be stopped global Winner if player == 'User': position = int(input("Chose a vacant position from 1-to-9... ")) while position < 1 or position > 9 or (board_elements[position-1]=='X' or board_elements[position-1]=='O'): position = int(input("Chose a valid position(1 to 9)... ")) position = position - 1 board_elements[position] = "X" elif player == 'Computer': if vacant_positions!=[]: position = random.choice(vacant_positions) print(f"Computer Choice is...{position+1}") board_elements[position] = 'O' # Because this position is occupied now, hence, this slot isn't available # for further turns vacant_positions.remove(position) #print(vacant_positions) board() def flip_player(): global current_player if current_player == 'User': current_player = 'Computer' else: current_player = 'User' def check_win(): global game_still_going #Check rows row_1 = board_elements[0] == board_elements[1] == board_elements[2] !='-' row_2 = board_elements[3] == board_elements[4] == board_elements[5] !='-' row_3 = board_elements[6] == board_elements[7] == board_elements[8] !='-' if (row_1 or row_2 or row_3): game_still_going = False if row_1: return board_elements[0] elif row_2: return board_elements[3] elif row_3: return board_elements[6] #Check columns Col_1 = board_elements[0] == board_elements[3] == board_elements[6] !='-' Col_2 = board_elements[1] == board_elements[4] == board_elements[7] !='-' Col_3 = board_elements[2] == board_elements[5] == board_elements[8] !='-' if (Col_1 or Col_2 or Col_3): game_still_going = False if Col_1: return board_elements[0] elif Col_2: return board_elements[1] elif Col_3: return board_elements[2] #Check diagonals Diag_1 = board_elements[0] == board_elements[4] == board_elements[8] !='-' Diag_2 = board_elements[2] == board_elements[4] == board_elements[6] !='-' if (Diag_1 or Diag_2): game_still_going = False if Diag_1 or Diag_2: return board_elements[4] return None def check_tie(): global game_still_going if vacant_positions==[]: game_still_going = False if __name__ == "__main__": play_game()
aa25f13234b647191d3fdc1fad426e4e23cb90c8
adityajaroli/python-training
/basic/oops/4PythonClassStaticVariablesAndMethods.py
1,079
4.0625
4
class Employee: COMPANY_NAME = "XYZ Pvt. Ltd." def __init__(self, empid, name): self.empid = empid self.name = name def print_emp_details(self): print(f"empid: {self.empid} - name: {self.name}") @staticmethod def get_complete_address(): print(f"static method is called: {Employee.COMPANY_NAME}") """ class methods are defined using @classmethod annotation. class method requires one parameter cls (class name). The class name is passed by interpreter. So one should not pass it explicitely like self for instance methods. One can call the class method as they call static method. The only difference between static and class method is that class method has one required argument and static method doesn't """ @classmethod def get_address(cls): print(f"class method is called from {cls} class") if __name__ == "__main__": # calling static method Employee.get_complete_address() # calling class method Employee.get_address()
83a91fa21ccf9633daac394b2bad6f997273c790
JessicaNgo/pyp-w1-gw-language-detector
/language_detector/main.py
1,391
4.34375
4
from .languages import LANGUAGES def detect_language(text, languages=LANGUAGES): '''Detects language name based on # of matches of common words to words in text''' #lists that will hold counts for each language lang_match_counts = [] #iterate sequentially through languages list for language in range(len(languages)): lang_match_counts.append(0) #initialize the language match word count for the language common_word_set = languages[language]['common_words'] #access to language's common words for word in common_word_set: lang_match_counts[language] += text.count(" " + word) #send lang_match_counts to function that matches it to the language, depending on its index index_of_language = which_language(lang_match_counts) return languages[index_of_language]['name'] def which_language(match_counts): '''helps determines the language by returning the index of match_counts that has the highest value, which corresponds to language name in lang_list''' high = 0 #holds highest value of match_counts, initiallizing here for item in range (len(match_counts)): #goes through match_counts and saves index of highest value if match_counts[item]>high: high = match_counts[item] highindex = item return highindex
a4cedc0a8f1d9478d5d76aa2a313744804d8acfc
wccgoog/pass
/python/gcd.py
188
3.875
4
def gcd(a,b): if b==0: print('最大公约数为',a) return r=a%b if r==1: print('最大公约数为1') return return gcd(b,r) a=int(input('a:')) b=int(input('b:')) gcd(a,b)
ab76bbcd036a156592f8eb4ad83a9cf30a329779
Jorgro/TDT4110-Information-Technology
/Øving 7/Sortering.py
771
3.96875
4
def bubble_sort(list): exchanges = True numb = len(list)-1 while numb > 0 and exchanges: exchanges = False for i in range(len(list)): if list[i-1]>list[i]: list[i-1], list[i] = list[i], list[i-1] exchanges = True numb -= 1 return list print(bubble_sort([3, 2, 4, 7, 6, 1])) def selection_sort(list): newlist = [] numb = len(list)-1 while numb > 0: max = 0 for i in range(len(list)): if list[i] > max: max = list[i] maxindex = i newlist.append(max) list.pop(maxindex) numb -= 1 newlist.reverse() return newlist print(selection_sort([9,1,34,7,2,3,45,6,78,56,36,65,33,21,23,34,45,6]))
73556d419a55cde55f01bdc48bbae64ac1e34c18
pavan-kc/Learnings
/Qspiders/Python/programs/atm.py
723
4.0625
4
withdrawal=int(input("enter the amount to be withdrawn ")) atm_balance=200 user_account_balance = 180 if withdrawal<100: print("invalid amount entered please enter amount in multiple of 100") elif withdrawal<atm_balance and withdrawal<user_account_balance: atm_balance-=withdrawal current_balance= user_account_balance-withdrawal print("you have successfully withdrawn "+str(withdrawal)+" and user current balance is "+str(current_balance)) elif withdrawal>atm_balance or withdrawal>user_account_balance: if withdrawal>atm_balance: print("no sufficent funds available") else: print("withdrawal amount is greater than amount in your account") else: print("atm is out of service")
1d1ebc6cf2144b19935785e64d984ee98a6c12c9
JustinWhalley-Carleton/snake
/auto_player.py
2,526
3.578125
4
from queue import PriorityQueue import pygame from node import Node # get the next move by choosing the next move of the A* algorithm considering, head of snake as start, apple as end and snake body as walls def getNextMove(grid,start,end): #initialize variables count = 0 open_set = PriorityQueue() open_set.put((0,count,start)) came_from = {} g_score = {node:float("inf") for row in grid for node in row} g_score[start] = 0 f_score = {node:float("inf") for row in grid for node in row} f_score[start] = h(start.get_pos(),end.get_pos()) open_set_hash = {start} path_length = 0 #update the neighbors of all nodes for row in grid: for node in row: node.update_neighbors(grid) # loop to find best path while not open_set.empty(): #allow to quit the program during the loop for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() current = open_set.get()[2] open_set_hash.remove(current) #found end return the first move if current == end: return get_first_move(came_from,end,end).get_pos() # calculate scores of the neighbors and decide best move for neighbor in current.neighbors: temp_g_score = g_score[current] + 1 if temp_g_score < g_score[neighbor]: came_from[neighbor] = current g_score[neighbor]=temp_g_score f_score[neighbor]=temp_g_score+h(neighbor.get_pos(),end.get_pos()) if neighbor not in open_set_hash: count += 1 open_set.put((f_score[neighbor],count,neighbor)) open_set_hash.add(neighbor) # end not found, choose first neighbor if len(start.neighbors) >0: return start.neighbors[0] else: # no path found and no neighbors move 1 to the right to end game (trapped) return start.get_pos()[0]+1,start.get_pos()[1] # calculate manhatten distance for A* algorithm def h(p1,p2): x1,y1 = p1 x2,y2 = p2 return abs(x1-x2)+abs(y1-y2) # get the first move def get_first_move(came_from,current,end): path = [] while current in reversed(came_from): current = came_from[current] path.append(current) if(len(path)>1): return path[-2] return end
6d6e268e67eb2680fe432ca1e53501b375ed19c6
hadoop73/sklearn
/predict_risk/feature/test.py
571
3.515625
4
""" import numpy as np import pandas as pd d = pd.DataFrame({'a':[2,'ad',6],'b':[3,'nan',2]}) b = pd.DataFrame({'a':[1,3,5],'b':[3,4,2]}) def kk(x): try: x = float(x) return x except: return -9999 for c in d.columns: d[c] = d[c].apply(lambda x:kk(x)) d.fillna(-9999,inplace=True) #d.set_index('a',inplace=True) #b.set_index('a',inplace=True) c = pd.concat([d,b],axis=0) c.drop(['a'],axis=1,inplace=True) #c.set_index('a',inplace=True) #c = c.sort_index() print c """ a = [1,2,3] a.remove(1) print a
f2ffc91fccd29b356507835afeee81972434f5d1
PravinSelva5/LeetCode_Grind
/Math/MissingNumber.py
1,020
3.890625
4
''' Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Time Complexity - O(N) Space Complexity - O(1) Runtime: 136 ms, faster than 37.28% of Python3 online submissions for Missing Number. Memory Usage: 15.4 MB, less than 25.91% of Python3 online submissions for Missing Number. ''' class Solution: def missingNumber(self, nums): ''' To find the sum of elements from 0 to N, the following formula can be used --> [ n * (n + 1) / 2 ] Gauss formula - Find the intended sum with the gauss formula - calculate the sum of the given array - subtract the two and the missing value should our answer ''' calc_sum = 0 array_len = len(nums) intended_sum = ( array_len * ( array_len + 1 ) ) // 2 # find the sum of the given array for num in nums: calc_sum += num return intended_sum - calc_sum
887358cfe0aba7e7d2b0701a3f20becdfe0c6c06
senthil7780/honeybee-devops
/honeybee-challenge1/access_github_details.py
1,754
3.5625
4
import requests import json import sys import urllib import csv from pprint import pprint data = [] github_dic ={} username=raw_input("Please enter your github id : ") # from https://github.com/user/settings/tokens token=raw_input("Please enter your OAuth Token : ") print("please enter the repos in $orgname/$reponame format") for line in sys.stdin: data.append(line) # create a re-usable session object with the user creds in-built gh_session = requests.Session() gh_session.auth = (username, token) # get the list of repos for the given org & get the commit history to find the Latest Author & date for item in data: item = item.split("/") orgname = item[0] reponame = item[1].strip("\n") # Build the Github API URLs repos_url = 'https://api.github.com/orgs/{a}/repos' commits_url = 'https://api.github.com/repos/{a}/{b}'+'/commits' # Acces the apis repos = json.loads(gh_session.get(repos_url.format(a=orgname)).text) i=0 for repo in repos: repo_name = repo['name'] clone_url = repo['clone_url'] commits = json.loads(gh_session.get(commits_url.format(a=orgname, b=reponame)).text) author_name = commits[0]["commit"]["committer"]["name"] latest_commit_date = commits[0]["commit"]["committer"]["date"] print("Repo Name : {0}, Clone URL : {1}, Author Name : {2}, Commit Date : {3} ".format(repo_name, clone_url, author_name, latest_commit_date)) values = [repo_name, clone_url, author_name, latest_commit_date] github_dic[i]=values i=i+1 with open('/tmp/file.csv','w') as csv_file: csv_writer = csv.writer(csv_file) for i in github_dic : list = github_dic[i] csv_writer.writerow(list) csv_file.close() #writeFile.close()
4156fbad01b225c92b41b8137fd23f9f03396cff
julioadriazola/Sistemas-Operativos-y-Redes
/Tarea1/metodo_input.py
818
3.53125
4
def hacer(consola): try : variable = consola.split(";") except : pass if(len>=5): #Crear un proceso a partir de las componentes de la linea print "Proceso por comando" opciones = [] for x in range(4,len(variable)): opciones.append(variable[x]) #Crear un proceso a partir de las componentes de la linea p = Proceso(variable[0], int(variable[1]), int(variable[2]), int(variable[3]), opciones) procesos.append(p) elif(consola=="agenda"): #aqui hay que imprimir la agenda y despues agregar la llamada elegida a la clase proceso print "revisando agenda" elif(consola=="historial"): #aqui hay que imprimir el archivo de historial de llamadas y mensajes print "revisando historial"
7e452b88f4518a768918ef77db15f4a438eb9911
Mix701/Programiranje
/recnik.py
1,446
4.25
4
dictionary = { "1": "Star Wars", "2": "Avengers", "3": "Joker", } def meny(): print("***************Meny***************") print("1: Insert new element in dictionary") print("2: Write all elements in dictionary.") print("3: Edit existing element in dictionary.") print("4: Delete existing element in dictionary.") print("5: End.") print("**********************************") def insetr(film=None): key = input("Enter a new key ") film = input("Enter a new element") dictionary.update({key: film}) def write(): print(dictionary) def delete(): while True: d = input("Insetr a key of element that you want to delete: ") if d in dictionary.keys(): del dictionary[d] break else: print("The key you inserted does not exist!") def edit(): while True: a = input("Enter a key of the film you would like to edit: ") if a in dictionary.keys(): film = input("Enter a new tittle: ") dictionary[a] = film break else: print("The key you inserted does not exist!") while True: meny() c = input("Choose one: ") if c == "1": instet() elif c == "2": i = write() elif c == "3": edit() elif c == "4": delete() elif c == "5": break
5538f709a22c7122a134bbe78a5826e3d9560e08
kkredit/hs-projects
/python-gui/squres_gui.py
579
3.984375
4
# exercise1.py # A program to make shapes # Kevin Kredit import graphics from graphics import * def main(): win = GraphWin() shape = Rectangle(Point(25,25), Point(75,75)) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range (10): x = shape.clone() p = win.getMouse() c = shape.getCenter() dx = p.getX() - c.getX() dy = p.getY() - c.getY() x.move(dx,dy) x.draw(win) thing = Text(Point(100,50), "Click again to Quit") thing.draw(win) win.getMouse() win.close main()
33c01daea0e5279cc67d9ce4756da906eb832b43
Oisin-Rooney/Python-Practical
/gpio_python_code/6_morsecode.py
553
3.640625
4
import os from time import sleep import RPi.GPIO as GPIO loop_count = 0 def morsecode(): GPIO.setmode(GPIO.BCM) GPIO.setup(22,GPIO.OUT) GPIO.setwarnings(False) GPIO.output(22,GPIO.HIGH) sleep(.1) GPIO.output(22,GPIO.LOW) sleep(.1) os.system('clear') # clear the screens text print ("Morse Code") GPIO.cleanup() loop_count = int (input("How many times would you like SOS to loop?:")) while loop_count > 0: if loop_count == 0: exit else: loop_count = loop_count-1 morsecode()
14ee260387cdfde73a97cc8e9a40fe07d0b09b78
845318843/20190323learnPython
/withKid/代码清单22.py
1,888
3.703125
4
# # my_file = open('my_filename.txt', 'r') # # # # # my_file = open('notes.txt', 'r') # # # # # # # # # line = my_file.readline() # # # lines = my_file.readlines() # # # # # # my_file.close() # # # print(lines) # # # print(line) # # # # # # 22-2 # # # my_file = open('notes.txt', 'r') # # # first_line = my_file.readline() # # # # my_file.seek(0) # # # second_line = my_file.readline() # # # print("firstline:",first_line) # # # print("secondline", second_line) # # # my_file.close() # # # # # # # my_file = open('new_notes.txt','r') # # # # my_file = open('new_notes.txt', 'w') # # # # my_file = open('notes.txt', 'a') # # # # # # # # # todo_list = open('notes.txt', 'a') # # # todo_list.write('\nSpend allowance') # # # todo_list.close() # # # # # # new_file = open("my_new_notes.txt", 'w') # # # new_file.write("Eat supper\n") # # # new_file.write("Play soccer\n") # # # new_file.write("Go to bed") # # # new_file.close() # # # # # # # # # the_file = open('notes.txt', 'w') # # # the_file.write("Wake up\n") # # # the_file.write("Watch cartoons") # # # the_file.close() # # # # # # my_file = open("new_file.txt", 'w') # # # # print(my_file, "Hello there, neighbor!") python3 中不能工作 # # # my_file.close() # # # # # # # # # # # # import pickle # # my_list = ['Fred', 73, 'Hello there', 81.9876e-13] # # pickle_file = open('my_pickled_list.pkl','w') # # pickle.dump(my_list, pickle_file)# python3 up against wrong # # pickle_file.close() # # # # # # pickle_file = open('my_pickled_list.pkl', 'r') # # recovered_list = pickle.load(pickle_file) # # pickle_file.close() # # print(recovered_list) # what did you learn? # open("filename.xxx",r) # myfile.close() # test items #1. 称为 文件对象 #2. open("filename",'r') #3. 文件对象是操作文件的工具 #4. open和 close #5. 文件尾部追加 #6. 原内容丢失 #7. seek(0) #8. pickle.dump() #9. pickle.load()
8b7b516c7aebe6f42b819bbd909ef15ac66e5819
chriscent27/calculator
/test_calculator.py
552
3.765625
4
import unittest from calculator import addition, subtraction, multiplication, division class TestCalculator(unittest.TestCase): def test_addition(self): result = addition(50, 25) self.assertEqual(result, 75) def test_subtraction(self): result = subtraction(50, 25) self.assertEqual(result, 25) def test_multiplication(self): result = multiplication(50, 2) self.assertEqual(result, 100) def test_division(self): result = division(50, 25) self.assertEqual(result, 2)
48f982c3c67de8641ff55844d7eab6abe169c3c8
darwinfv/Miscellaneous-Programs
/Learn Python/learn_python.py
3,269
3.875
4
# is checks if two variables refer to the same object, but == checks # if the objects pointed to have the same values. # Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # yahoo! li = [] li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. del li[2] # li is now [1, 2, 3] li.remove(2) # li is now [1, 3] li.insert(1, 2) # li is now [1, 2, 3] again li.index(2) # => 1 tup = (1, 2, 3) a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 d, e, f = 4, 5, 6 e, d = d, e # d is now 5 and e is now 4 empty_dict = {} filled_dict = {"one": 1, "two": 2, "three": 3} valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. filled_dict["one"] # => 1 list(filled_dict.keys()) # => ["three", "two", "one"] list(filled_dict.values()) # => [3, 2, 1] filled_dict.get("one") # => 1 filled_dict.get("four") # => None filled_dict.get("four", 4) # => 4 filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} filled_dict["four"] = 4 # another way to add to dict del filled_dict["one"] # Removes the key "one" from filled dict some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} valid_set = {(1,), 1} filled_set = some_set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} filled_set | other_set # => {1, 2, 3, 4, 5, 6} {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} {1, 2} >= {1, 2, 3} # => False {1, 2} <= {1, 2, 3} # => True 2 in filled_set # => True 10 in filled_set # => False filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() print(our_iterable) # => dict_keys(['one', 'two', 'three]) for i in our_iterable: print(i) our_iterator = iter(our_iterable) next(our_iterator) # one next(our_iterator) # two next(our_iterator) # three next(our_iterator) # Raises StopIteration # infinite arguments like printf def varargs(*args): return args # arguments as a dictionary def keyword_args(**kwargs): return kwargs keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} def all_the_args(*args, **kwargs): print(args) print(kwargs) all_the_args(1, 2, a=3, b=4) """ (1, 2) {"a": 3, "b": 4} """ # There are also anonymous functions (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # You can construct set and dict comprehensions as well. {x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} {x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} import math dir(math) # lists all functions # printf style arguments def say(msg): print("{name}: {message}".format(name=self.name, message=msg)) # Generators help you make lazy code. def double_numbers(iterable): for i in iterable: yield i + i values = (-x for x in [1,2,3,4,5])
c4d61f81250f89805bd5d807962bac923fae8ef7
GhimpuLucianEduard/CodingChallenges
/challenges/ctci/sorted_merge.py
1,365
3.984375
4
""" 10.1 Sorted Merge You are given two sorted arrays, A, B where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. """ import unittest def sorted_merge(a, b): # copy b in after a end = len(a) - 1 end_of_b = len(b) - 1 end_of_a = len(a) - len(b) - 1 while end_of_b >= 0 and end_of_a >= 0: if a[end_of_a] >= b[end_of_b]: a[end] = a[end_of_a] end_of_a -= 1 else: a[end] = b[end_of_b] end_of_b -= 1 end -= 1 while end_of_a >= 0: a[end] = a[end_of_a] end_of_a -= 1 end -= 1 while end_of_b >= 0: a[end] = b[end_of_b] end_of_b -= 1 end -= 1 class TestSortedMerge(unittest.TestCase): def test_sorted_merge(self): a = [1, 4, 8, 9, 13, None, None, None, None] b = [3, 5, 10, 15] sorted_merge(a, b) self.assertEqual([1, 3, 4, 5, 8, 9, 10, 13, 15], a) def test_sorted_merge_2(self): a = [3, 4, 8, 9, 13, None, None, None, None] b = [2, 5, 10, 15] sorted_merge(a, b) self.assertEqual([2, 3, 4, 5, 8, 9, 10, 13, 15], a) def test_sorted_merge_3(self): a = [1, 2, 3, None, None, None] b = [2, 5, 6] sorted_merge(a, b) self.assertEqual([1, 2, 2, 3, 5, 6], a)
03f11e3dcf32928ea9b2071c2fd4e3558f9eb54e
danielzuncke/minis
/foobar.py
173
3.546875
4
n = 100 for x in range(1, n): y = "" if x % 3 == 0: y += "foo" if x % 7 == 0: y += "bar" if len(y) == 0: y += str(x) print(y)
ca6c131960a61aa722a22f038350597d19acf4c4
shaneweisz/CSC3002F-VirtualMemoryAlgorithms
/paging.py
6,396
3.96875
4
# Shane Weisz # WSZSHA001 import sys from random import randint def FIFO(size, pages): """ Function that implements the FIFO page replacement algorithm and returns the number of page faults that occur. Parameters: size (int): The number of available page frames - can vary from 1 to 7 pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5] Returns: int: The number of page faults that occured. """ queue = [] # queue, the page frames, is initially empty page_faults = 0 # tracks the number of page faults for page in pages: # loops through each page in the page ref str if page not in queue: # check if the page is in memory already page_faults += 1 # if not, a page fault has occurred if len(queue) >= size: # check if there are no empty frames left del queue[0] # if full, remove page at head of queue queue.append(page) # append the new page at end of queue return page_faults def LRU(size, pages): """ Function that implements the LRU (Least Recently Used) page replacement algorithm and returns the number of page faults that occur. Parameters: size (int): The number of available page frames - can vary from 1 to 7 pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5] Returns: int: The number of page faults that occured. """ stack = [] # stack, the page frames, is initially empty page_faults = 0 # tracks the number of page faults for page in pages: # loops through each page in the page ref str if page not in stack: # check if the page is in memory already page_faults += 1 # if not, a page fault has occurred if len(stack) >= size: # check if there are no empty frames left del stack[size-1] # remove the least recently used page else: # page is in memory stack.remove(page) # remove page from old place in stack # put page on top of the stack because its the most recently used page. stack.insert(0, page) return page_faults def OPT(size, pages): """ Function that implements the optimal page replacement algorithm (OPT) and returns the number of page faults that occur. Parameters: size (int): The number of available page frames - can vary from 1 to 7 pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5] Returns: int: The number of page faults that occured. """ frames = [] # represent the frames in physical memory page_faults = 0 # tracks the number of page faults for (page_index, page) in enumerate(pages): # loop through page ref string if page not in frames: # check if the page is in memory already page_faults += 1 # if not, a page fault has occurred if len(frames) < size: # check if there are any free frames frames.append(page) # if so, place page in a free frame else: # the frames are full, so we must replace the frame # that will not be used for the longest period of time upcoming_pages = pages[page_index+1:] frame_to_replace = find_victim_frame(frames, upcoming_pages) # replace the victim frame with the new page pos = frames.index(frame_to_replace) frames.remove(frame_to_replace) frames.insert(pos, page) return page_faults def find_victim_frame(frames, upcoming_pages): """ Helper function for the OPT algorithm to find the the victim frame (frame to replace) i.e. the frame that will not be used for the longest time. Parameters: frames (list): A list of the frames in memory e.g [0, 3, 5] pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5] Returns: int: The frame that will not be used for the longest time - hence, the frame to replace in the OPT algorithm """ frame_to_replace = frames[0] # initialize to first frame max_time_till_use = 0 # initialize to zero # loop through frames in memory to find the frame to replace for frame in frames: # check if the frame is never referenced in the future # if so, we can replace this frame if frame not in upcoming_pages: frame_to_replace = frame break # find the next usage and time until the frame is next used for (i, upcoming_page) in enumerate(upcoming_pages, 1): if frame == upcoming_page: time_till_use = i break # check if this frame has the current longest time till use if time_till_use > max_time_till_use: max_time_till_use = time_till_use frame_to_replace = frame return frame_to_replace def generate_page_reference_string(N): """ Generates a random page-reference string of length N where page numbers range from 0 to 9 Parameters: N (int): The desired length of the page reference string Returns: list: a list of page references e.g. [0,2,4,1,2,3] """ pages = [] # Stores the page-reference string for i in range(N): pages.append(randint(0, 9)) # Generates a random integer from 0-9 return pages def main(): """ A randomly generated page-reference string is applied to each of the FIFO, LRU and optimal page replacement algorithms, and the number of page faults incurred by each algorithm is recorded. """ N = int(input("Enter the length of the page reference string: ")) pages = generate_page_reference_string(N) print "Page reference string: ", pages size = int(sys.argv[1]) # number of frames in memory print "FIFO", FIFO(size, pages), "page faults." print "LRU", LRU(size, pages), "page faults." print "OPT", OPT(size, pages), "page faults." if __name__ == "__main__": if len(sys.argv) != 2: print "Usage: python paging.py [number of pages]" else: main()
67aea2f801a91f9a9014f5ca9aaeefa0067f4ea6
Aasthaengg/IBMdataset
/Python_codes/p03192/s380407726.py
88
3.9375
4
str_num = input() count = 0 for c in str_num: if c == "2": count += 1 print(count)
aac40d112d74096971e6d77388314422a52d07e5
hk1997/Algorithms
/Cryptography Algorithms/Python/OneTimePad.py
2,844
3.671875
4
import string import random key = '' encrypted_text = [] bin_key = [] def bin_to_str(binary): binary = str(binary) character = '' char = '' size = len(binary) k = 1 for j in binary: if j != ' ': character += j if k == size: char += chr(int(character, 2)) else: char += chr(int(character, 2)) character = '' k += 1 return char def str_to_bin(string): binary = '' for i in string: binary += bin(ord(i))[2::] + ' ' return binary def print_layout_name(name): print("\n+==================================================================+") print(" ",name,"\n+==================================================================+") def print_menu(): print_layout_name("ONE-TIME PAD") print("\n 1 - Encrypt\n 2 - Decrypt\n 0 - Exit\n") def generator_key(size): return ''.join(random.choice(string.ascii_letters) for x in range(size)) def select_option(option): if option == 1: encrypt() if option == 2: decrypt() if option == 0: exit(0) def encrypt_with_a_key(key, text): bits_key = key.split(' ') bits_text = text.split(' ') del(bits_key[-1]) del(bits_text[-1]) result = [] for i in range(len(bits_text)): result.append( str( bin( int(bits_text[i],2) ^ int(bits_key[i],2) )[2::] ) ) return result def encrypt(): global key, binary_key, encrypted_text, bin_key plain_text = str(input(" Enter the plain text: ")) binary_text = str_to_bin(plain_text) key = generator_key(len(plain_text)) print("\n Key: ", key) binary_key = str_to_bin(key) print("\n Binary Key: ", binary_key) encrypted_text = encrypt_with_a_key(binary_key, binary_text) bin_key = binary_key.split(' ') del(bin_key[-1]) print("\n Encrypted Message: ", encrypted_text) def decrypt(): global key, bin_key, encrypted_text plain_text = [] decrypted_text = [] if(key != ''): print("\n Binary Plain Text: ", end="") for i in range( len(encrypted_text) ): decrypted_text.append( bin( int(bin_key[i],2) ^ int(encrypted_text[i],2) )[2::] ) print(decrypted_text[i], " " ,end="") print("\n\n Decrypted Message: ", end="") for j in range(len(decrypted_text)): plain_text.append( bin_to_str( decrypted_text[j] )) print(plain_text[j], end="" ) print("\n") else: print("\n No keys stored in memory") def main(): print_menu() option = int(input(" Select an option: ")) select_option(option) while(option != 0): print_menu() option = int(input(" Select an option: ")) select_option(option) main()
df024ed74db445bd2f31f91c3886d80afd358e3c
owlrana/cpp
/rahulrana/python/Leetcode/#051 Pascals Triangle/v51.0.py
948
3.609375
4
# https://leetcode.com/problems/pascals-triangle/ class Solution: def generate(numRows): # initiate 1st level pascal = [[1]] # assign level to 1 lvl = 1 # create list of sublevel and append it to pascal later on while lvl < numRows: # Dummy sublevel List lvlList = [] #initiates 1st value to Dummy SubLevel List lvlList.insert(0, 1) # same as append(1) # Computes the values of other elements (not last) for i in range(1, lvl): value = pascal[lvl - 1][i - 1] + pascal[lvl - 1][i] lvlList.append(value) # Appends last value to dummy SubLevel List lvlList.append(1) lvl +=1 # Append the whole list of level to final pascal pascal.append(lvlList) return pascal print(Solution.generate(10))
31d3cfc6313e09f69a1a826c938b228c2732eeef
Bowie666/what-you-want-to-be
/profeskills/backend/python/stdlib/1.Built-inFunctions.py
5,314
3.546875
4
"""11 @classmethod 把一个方法封装成类方法。就是调用的时候不需要实例化了""" """10 chr(i) 就是返回当前整数对应的 ASCII 字符。 返回 Unicode 码位为整数 i 的字符的字符串格式。 例如,chr(97) 返回字符串 'a',chr(8364) 返回字符串 '€'。这是 ord() 的逆函数。 实参的合法范围是 0 到 1,114,111(16 进制表示是 0x10FFFF)。 如果 i 超过这个范围,会触发 ValueError 异常。""" # print(chr(41)) # ) # print(chr(97)) # a # print(chr(8364)) # € """9 callable(object) 用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败; 但如果返回 False,调用对象 object 绝对不会成功。 对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True""" # print(callable(object)) # print(callable(0)) # print(callable(1)) # print(callable("look")) # def add(a, b): # return a + b # print(callable(add)) # # class B: # def method(self): # return 0 # # 这个是声明 # print(callable(B)) # # 这个是创建实例 # b = B() # print(callable(b)) """8 class bytes([source[, encoding[, errors]]]) 返回一个新的“bytes”对象, 是一个不可变序列,包含范围为 0 <= x < 256 的整数。 bytes 是 bytearray 的不可变版本 - 它有其中不改变序列的方法和相同的索引、切片操作。""" # print(bytes()) # b'' # print(bytes(3)) # b'\x00\x00\x00' # print(bytes(4)) # b'\x00\x00\x00\x00' # print(bytes([1, 2, 3])) # b'\x01\x02\x03' # print(bytes([1, 12, 3, 4])) # b'\x01\x0c\x03\x04' # print(bytes('runoob', 'utf-8')) # b'runoob' """7 class bytearray([source[, encoding[, errors]]]) 返回一个新的 bytes 数组。 bytearray 类是一个可变序列,包含范围为 0 <= x < 256 的整数。 它有可变序列大部分常见的方法,见 可变序列类型 的描述;同时有 bytes 类型的大部分方法, x 创建 bytearray 对象时使用的资源 如果是整数,则会创建指定大小的空 bytearray 对象。 如果是字符串,请确保规定了资源的编码。 encoding 字符串的编码 error 规定若编码失败要做什么。 如果 source 为整数,则返回一个长度为 source 的初始化数组; 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列; 如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数; 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。 如果没有输入任何参数,默认就是初始化数组为0个元素""" # print(bytearray()) # bytearray(b'') # print(bytearray(3)) # bytearray(b'\x00\x00\x00') # print(bytearray(4)) # bytearray(b'\x00\x00\x00\x00') # print(bytearray([1, 2, 3])) # bytearray(b'\x01\x02\x03') # print(bytearray([1, 12, 3, 4])) # bytearray(b'\x01\x0c\x03\x04') # print(bytearray('runoob', 'utf-8')) # bytearray(b'runoob') """6 class bool([x]) 返回一个布尔值,True 或者 False。如果 x 是假的或者被省略,返回 False;其他情况返回 True。 bool 类是 int 的子类。其他类不能继承自它。它只有 False 和 True 两个实例。""" # print(bool(4)) # True # print(bool(0)) # False # print(bool(-1)) # True """5 bin(x) 将一个整数转变为一个前缀为“0b”的二进制字符串。""" # print(bin(14)) # 0b1110 # # 这个是把0b去掉了 # print(format(14, 'b')) # 1110 # print(format(14, '#b')) # 0b1110 """4 ascii(object)可能用不大到 就像函数 repr(),返回一个对象可打印的字符串, 但是 repr() 返回的字符串中非 ASCII 编码的字符,下面的话放这里。""" # # 会使用 \x、\u 和 \U 来转义 <-- 这句话在上面会报错 我也不知道为什么 # print(ascii('龙王')) # '\u9f99\u738b' """3 any(iterable) 如果 iterable 的任一元素为真则返回 True。 如果迭代器为空,返回 False。 元素除了是 0、空、FALSE 外都算 True 如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true""" # 和all函数相反,就这样记住就行 # print(any([])) # False # print(any(())) # False # print(any([0, 12, 3, 4])) # True """2 all(iterable) 元组或列表 如果 iterable 的所有元素为真(或迭代器为空),返回 True 元素除了是 0、空、None、False 外都算 True。 如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False; 注意:空元组、空列表返回值为True,这里要特别注意""" # # 之前美多有一个验证前端参数的部分 就是用的all() # if all([0, 12, 3, 4]) is True: # pass # print(all([])) # True # print(all(())) # True # print(all([0, 12, 3, 4])) # False """1 abs(x) 返回一个数的绝对值。实参可以是整数或浮点数。如果实参是一个复数,返回它的模。""" # a = float(10) # print(a) # 10.0 # b = -10.123 # print(b) # -10.123 # print(abs(b)) # 10.123 # c = -8 # print(c) # -8 # print(abs(c)) # -8 # d = 6j # print(d * d) # (-36+0j) # # 有点意思 输出的是浮点类型 # print(abs(d * d)) # 36.0 # print(type(abs(d * d))) # <class 'float'> # print(type(d)) # <class 'complex'> # print(abs(d)) # 6.0
7a45664ec8b90c7eb3666c01d95447fed4106da3
yetimark/CSC415-Project
/grid.py
4,242
3.875
4
import random # These are the data structures for holding information about a position on the display # A cell is now a tuple in the format (x,y) # In the end I really want the coordinates on the graph so this will be less cumbersome # A Grid is basically a 2D array of cells. It also has some extra fancy bells and whistles class Grid: def __init__(self, rows=20, collumns=100, weight=5): self.rows = rows self.collumns = collumns self.cells = [] for i in range(rows): self.cells.append([]) for j in range(collumns): self.cells[i].append((i, j)) # -- since we are using tuples (a primitive) (0,0) == self.cells[0][0] -- middle_row = rows // 2 self.cursor = (collumns // 2, middle_row) self.start = (collumns // 8, middle_row) self.end = ((collumns // 8) * 7, middle_row) self.walls = [] # - weights are set to a default value of 1 - # -- initially all "weighted" cells will be the same value -- self.weighted = [] self.weight = weight self.graph = {} for i in range(rows): for j in range(collumns): here = (i, j) down = self.get_down(here) right = self.get_right(here) if down: rando = random.randint(1, 20) self.graph[(here, down)] = rando self.graph[(down, here)] = rando if right: rando = random.randint(1, 15) self.graph[(here, right)] = rando self.graph[(right, here)] = rando def get_distance(self, tuptup): return self.graph[tuptup] def add_cell_weight(self, cell): self.weighted.append(cell) def remove_cell_weight(self, cell): self.weighted.remove(cell) def get_cell_weight(self, cell): for weighted_cell in self.weighted: if cell == weighted_cell: return self.weight return 1 # default weight def move_cursor(self, cell): self.cursor = cell def is_cursor(self, cell): if cell == self.cursor: return True else: return False def change_start(self, cell): self.start = cell def is_start(self, cell): if cell == self.start: return True else: return False def change_end(self, cell): self.end = cell def is_end(self, cell): if cell == self.end: return True else: return False def add_wall(self, cell): self.walls.append(cell) def remove_wall(self, cell): self.walls.remove(cell) def is_wall(self, cell): return_val = False for wall in self.walls: if cell == wall: return_val = True break return return_val # UP DOWN RIGHT AND LEFT return the value shifted that direction one # OR ---- They return None to show there is not an available space next door def get_up(self, cell): dest = (cell[0], cell[1] -1) if dest[1] < 0: dest = False return dest def get_right(self, cell): dest = (cell[0] +1, cell[1]) if dest[0] >= self.collumns: dest = False return dest def get_down(self, cell): dest = (cell[0], cell[1] +1) if dest[1] >= self.rows: dest = False return dest def get_left(self, cell): dest = (cell[0] -1, cell[1]) if dest[0] < 0: dest = False return dest # used to check allignment before adding visuals def display(self): print('***** Printing Grid *****') print('cursor:', self.cursor) print('start:', self.start) print('end:', self.end) print('walls:', self.walls) for i in range(len(self.cells)): row_print = '' for j in range(len(self.cells[i])): row_print += f'{self.cells[i][j]} | ' print(row_print) grid = Grid() print(grid.graph) # grid.display()
b3eaf14dfc4d14a326352a2a3afa774181ee3ef5
sunwang33/liaoxuefeng
/liaoxuefeng_python3/函数的参数.py
5,007
4.3125
4
#!/usr/bin/env python #-*- coding: utf-8 -*- # @Time : 2018-11-14 13:42 # @Author : SunWang # @File : 函数的参数.py #可变参数 def calc(numbers): sum = 0 for n in numbers: sum = sum + n*n return sum print(calc([1, 2, 3])) print(calc((1, 3, 5, 7))) #定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数: def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc(1, 2)) print(calc()) #如果已经有一个list或者tuple,要调用一个可变参数怎么办?可以这样做: nums = [1, 2, 3] print(calc(nums[0], nums[1], nums[2])) #这种写法当然是可行的,问题是太繁琐,所以Python允许你在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去: nums = [1, 2, 3] print(calc(*nums)) #*nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用,而且很常见。 #关键字参数 #可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。请看示例: def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) print(person('Michael', 30)) print(person('Bob', 35, city='Beijing')) print(person('Adam',45, gender='M', job='Engineer')) extra = {'city': 'Beijing', 'job':'Engineer'} print(person('Jack', 24, city=extra['city'] ,job=extra['job'])) #上面复杂的调用可以用简化的写法: extra = {'city': 'Beijing', 'job':'Engineer'} print(person('Jack', 24, **extra)) #**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra。 #命名关键字参数 #如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和job作为关键字参数。这种方式定义的函数如下: def person(name, age, *, city, job): print(name, age, city, job) #和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。 print(person('Jack', 24, city='Beijing', job='Engineer')) #如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了: def person(name, age, *args, city, job): print(name, age, args, city, job) print(person('Jack', 24, city='Beijing', job='Engineer')) def person(name, age, *, city='Beijing', job): print(name, age, city, job) #由于命名关键字参数city具有默认值,调用时,可不传入city参数: print(person('Jack', 24, job='Engineer')) #使用命名关键字参数时,要特别注意,如果没有可变参数,就必须加一个*作为特殊分隔符。如果缺少*,Python解释器将无法识别位置参数和命名关键字参数: def person(name, age, city, job): # 缺少*,则city和job被视为位置参数。 pass #参数组合 #在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。 def f1(a, b, c=0, *args, **kw): print('a = ', a , 'b= ' , b, 'c= ', c, 'args=', args, 'kw= ', kw) def f2(a, b, c=0, * , d, **kw): print('a= ', a, 'b=', b, 'c=',c,'d=',d,'kw=',kw) print(f1(1, 2)) #结果:a = 1 b= 2 c= 0 args= () kw= {} print(f1(1,2, c=3)) #结果:a = 1 b= 2 c= 3 args= () kw= {} print(f1(1,2,3,'a','b')) #结果:a = 1 b= 2 c= 3 args= ('a', 'b') kw= {} print(f1(1,2,3,'a','b',x=99)) #结果:a = 1 b= 2 c= 3 args= ('a', 'b') kw= {'x': 99} print(f2(1,2,d=99, ext=None)) #结果:a= 1 b= 2 c= 0 d= 99 kw= {'ext': None} args = {1,2,3,4} kw = {'d':99,'x':'#'} print(f1(*args, **kw)) #a = 1 b= 2 c= 3 args= (4,) kw= {'d': 99, 'x': '#'} args = (1,2,3) kw = {'d':88 , 'x':'#'} print(f2(*args, **kw)) #结果:a= 1 b= 2 c= 3 d= 88 kw= {'x': '#'} #所以,对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。 #虽然可以组合多达5种参数,但不要同时使用太多的组合,否则函数接口的可理解性很差。 #练习: #以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积: def product(*kw): numbers=list(kw) sum = 1 for num in numbers: sum *= num return sum print(product(1,2,3,4,5,6,7,8,9))
41b0b1aa0cb4ada4cb4058714a06f89f8f69700b
Da1anna/Data-Structed-and-Algorithm_python
/leetcode/其它题型/递归/斐波那契数列.py
970
3.96875
4
''' 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下: F(0) = 0,   F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 示例 1: 输入:n = 2 输出:1 示例 2: 输入:n = 5 输出:5   提示: 0 <= n <= 100 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: #动态规划 def fib(self, n: int) -> int: if n in [0,1]: return n x,y = 0,1 for _ in range(2,n+1): x,y = y,x+y return int(y % (1e9+7)) #测试 res =Solution().fib(45) print(res)
b16941eecd6da8f113283074f8669526cd4c2324
pratik-iiitkalyani/Python
/file_system/read_text_file.py
1,093
4.375
4
# readfile # open function - to open the file # read method - read the file # seek method - to the position of the cursor # tell method - tell the cursor position # readline method - read single line # readlines method - read file line by line # close method - to close the file f = open('file1.txt') # open function take mode as a 2nd parameter('r'(default), 'w') # we can also iterate f for line in f: print(line, end='') # print(f"cursor position - {f.tell()}") # print(f.read()) # print(f.readline(), end='') # print(f.readline()) # print(f.readline()) # print(f"cursor position - {f.tell()}") # f.seek(0) # print(f"cursor position - {f.tell()}") # print(f.read()) # lines = f.readlines()[0:2] # we can do slicing in readlines # print(lines) # for line in lines: # print(line, end='') # data discriptor(name, closed) print(f.name) # return name of the file print(f.closed) # tell file is closed or not, return boolean f.close() # best practice to close that file after any operation
29e4b40ff26d59b31f204d4f518edd711376e244
nouranHnouh/cartwheeling-kitten
/add_and_appandList.py
245
4.125
4
#create list1 and list2 list1 = [1,2,3,4] list2 = [1,2,3,4] #add 5 and 6 to list1 list1 = list1 + [5, 6] list2.append([5, 6]) # add list [5,6] to list2 #check results of list1 and list2 print "showing list1 and list2:" print list1 print list2
6cd0f2c155d4843880c74a3fb1b99cb63621d968
Ben0623/IntroProgramming
/Guessing-Game.py
369
4.09375
4
def main(): print ("Hello, this is a guessing game guess an animal") animal = str("Pig") guess = input (str("The game is thinking of an animal take a guess:")) guess = guess.capitalize() while guess != "Pig": print ("Wrong Guess again") guess = input(str("Enter and animal:")) if guess == "Pig": print("You win") main()
27a65b478ae1aacd072ae94ca6eb552453645937
jieunjeon/daily-coding
/Programmers/12901_2016.py
948
3.71875
4
""" https://programmers.co.kr/learn/courses/30/lessons/12901 2016년 문제 설명 2016년 1월 1일은 금요일입니다. 2016년 a월 b일은 무슨 요일일까요? 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요. 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT 입니다. 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 "TUE"를 반환하세요. 제한 조건 2016년은 윤년입니다. 2016년 a월 b일은 실제로 있는 날입니다. (13월 26일이나 2월 45일같은 날짜는 주어지지 않습니다) 입출력 예 a b result 5 24 "TUE" """ import datetime weekdays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN', ] def solution(a, b): """ Time Complexity: O(1) """ numWeek = datetime.datetime(2016, a, b).weekday() answer = weekdays[numWeek] return answer
a67d07ea6464f8df440272ed01000ffcfdc3a5eb
daminisatya/Python
/PE40.py
401
3.578125
4
def digit_at(n): digits = 1 n = n - 1 while True: numbers = 9 * pow(10, digits-1) * digits if n > numbers: n = n - numbers else: break digits = digits + 1 num = n / digits + pow(10, digits-1) return int(str(num)[n % digits]) print digit_at(1) * digit_at(10) * digit_at(100) * digit_at(1000) * digit_at(10000) * digit_at(100000) * digit_at(1000000)
020b703aa68faafffd9cff67644b7de3ac6960ef
BayarevichAleh/FirstDay
/Day4/Function_4.py
992
4
4
from random import randrange def create_matrix(n, m): """ Create new matrix :param n: columns :param m: rows :type n,m: int :return: created matrix """ new_matrix = list() for i in range(m): row = list() for j in range(n): row.append(randrange(-100, 100)) new_matrix.append(row) return new_matrix def sum_matrix(matrix_1, matrix_2): """ Sum matrix #1 and matrix #2 :param matrix_1: matrix #1 :param matrix_2: matrix #2 :return: sum matrix #1 and matrix #2 """ for i in range(len(matrix_1)): for j in range(len(matrix_1[0])): matrix_1[i][j] += matrix_2[i][j] return matrix_1 column = int(input("Enter number of columns:")) row = int(input("Enter number of rows:")) a = create_matrix(column, row) b = create_matrix(column, row) print(f'You create matrix #1:\n{a}') print(f'You create matrix #2:\n{b}') print(f'Sum matrix #1 and matrix #2:\n{sum_matrix(a, b)}')
6e88e4a0eeb0da3ce5e77888753e8f24957036c9
jc449767/syed
/practical 01/hello world.py
599
3.96875
4
firstname = 'syed' lastname = 'ahemd' age = int(input("enter your age:")) fruits = ["orange", 'mango', 'banana', 'melon'] sequences = [1,2,3,4,5,6,7,8,9] print ('today is the 1st day of programming') print (firstname + " " + lastname) print(25, firstname + " " + lastname) print(fruits[0]) for value in fruits: print (value) for value in sequences: print (value) number = 0 while (number < 10) : print (number) number = number + 1 if (age < 18): print ('you are too young') elif (18<=age and age < 50): print ('you are major') else: print ('you are too old')
b660355de92cb29666c2e4010d8b304b0fd37932
holzschu/Carnets
/Library/lib/python3.7/site-packages/sympy/series/series.py
1,918
3.546875
4
from __future__ import print_function, division from sympy.core.sympify import sympify def series(expr, x=None, x0=0, n=6, dir="+"): """Series expansion of expr around point `x = x0`. Parameters ========== expr : Expression The expression whose series is to be expanded. x : Symbol It is the variable of the expression to be calculated. x0 : Value The value around which ``x`` is calculated. Can be any value from ``-oo`` to ``oo``. n : Value The number of terms upto which the series is to be expanded. dir : String, optional The series-expansion can be bi-directional. If ``dir="+"``, then (x->x0+). If ``dir="-", then (x->x0-). For infinite ``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined from the direction of the infinity (i.e., ``dir="-"`` for ``oo``). Examples ======== >>> from sympy import Symbol, series, tan, oo >>> from sympy.abc import x >>> f = tan(x) >>> series(f, x, 2, 6, "+") tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) + (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 + 5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 + 2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2)) >>> series(f, x, 2, 3, "-") tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2)) + O((x - 2)**3, (x, 2)) >>> series(f, x, 2, oo, "+") Traceback (most recent call last): ... TypeError: 'Infinity' object cannot be interpreted as an integer Returns ======= Expr Series expansion of the expression about x0 See Also ======== sympy.core.expr.Expr.series: See the docstring of Expr.series() for complete details of this wrapper. """ expr = sympify(expr) return expr.series(x, x0, n, dir)
e9c2c58ba9a7456dc7b1603fafdd480aa96fbf8a
sankari-chelliah/Python
/linked_list.py
699
4.0625
4
# A single node of a singly linked list class Node: def __init__(self, data = None, next=None): self.data = data self.next = next # A Linked List class with a single head node class LinkedList: def __init__(self): self.head = None # insertion method for the linked list def insert(self, data): newNode = Node(data) if(self.head): current = self.head while(current.next): current = current.next current.next = newNode else: self.head = newNode def printLL(self): current = self.head while(current): print(current.data) current = current.next L = LinkedList() L.insert(3) L.insert(4) L.insert(5) L.printLL()
4a8832b3fc12e8a2f999a5ba538bee8b2398b19d
taegyeongeo/python_algorithm_interview
/group_anagrams.py
264
3.84375
4
import collections def group_anagrams(strs): anagrams=collections.defaultdict(list) for word in strs: anagrams[''.join(sorted(word))].append(word) return anagrams token=['eat','tae','tan','ate','nat','bat'] res=group_anagrams(token) print(res)
0aec8906334cfe23edb7d7b49c3ea57ce540bd2b
linux-wang/leet-code
/bczf/2_2.py
313
3.671875
4
# -*- coding:utf-8 -*- # 这个题最重要的是思路,感觉遍历一个数,然后使用hash去判断所需的另外一个数是否存在,机智的很啊 s = {1, 2, 3, 4} sum = 5 s1 = set() for i in s: n = sum - i if n in s: if (i, n) not in s1 and (n, i) not in s1: s1.add((i, n)) print s1
cafb9aeb9a9da703325dc2979a1e21a098e56bb7
D-Code-Animal/CTI110
/P2T1_SalesPrediction_EatonStanley.py
311
3.53125
4
# CTI-110 # P2TI-Sales Prediction # Stanley J. Eaton Sr. # June 15, 2018 # Get the projected total sales. total_sales = float (input ('Enter the projected sales:')) # Calculate the profit as 23 precent of total sales. profit = total_sales * 0.23 # Display the profit. print ('The profit is $', format (profit, ',.2f'))
a9f484a5a5c9dac5a95de0667203e6ddc348c0e8
saraparva/PROBLEMS_JUTGE
/Which graphics cards should I buy?.py
270
3.71875
4
gpu_frequency=int(input()) game_needed_frequency=int(input()) count_of_games=0 while( game_needed_frequency != 0): if(game_needed_frequency<=gpu_frequency): count_of_games = count_of_games+1 game_needed_frequency=int(input()) print(count_of_games)
9837bfc43e4e96a71b821e1621a7fda121b31a43
AasaiAlangaram/OpenCV-Autonomous-Car
/Test - Arduino Raspberry pi Interactive control/Test1-Interactive Control.py
2,926
3.921875
4
#!/usr/bin/env python """Interactive control for the car""" import pygame import pygame.font import serial import configuration UP = LEFT = DOWN = RIGHT = False def get_keys(): """Returns a tuple of (UP, DOWN, LEFT, RIGHT, change, stop) representing which keys are UP or DOWN and whether or not the key states changed. """ change = False stop = False key_to_global_name = { pygame.K_LEFT: 'LEFT', pygame.K_RIGHT: 'RIGHT', pygame.K_UP: 'UP', pygame.K_DOWN: 'DOWN', pygame.K_ESCAPE: 'QUIT', pygame.K_q: 'QUIT' } for event in pygame.event.get(): key_input = pygame.key.get_pressed() if key_input[pygame.K_x] or key_input[pygame.K_q]: stop = True elif event.type in {pygame.KEYDOWN, pygame.KEYUP}: down = (event.type == pygame.KEYDOWN) change = (event.key in key_to_global_name) if event.key in key_to_global_name: globals()[key_to_global_name[event.key]] = down return (UP, DOWN, LEFT, RIGHT, change, stop) def interactive_control(): """Runs the interactive control""" ser = serial.Serial('COM3', 115200, timeout=.1) setup_interactive_control() clock = pygame.time.Clock() command = 'idle' while True: up_key, down, left, right, change, stop = get_keys() if stop: ser.write(chr(5).encode()) print('q or esp pressed') break if change: command = 'idle' if up_key: ser.write(chr(1).encode()) command = 'forward' elif down: ser.write(chr(2).encode()) command = 'reverse' append = lambda x: command + '_' + x if command != 'idle' else x if left: ser.write(chr(3).encode()) command = append('left') elif right: ser.write(chr(4).encode()) command = append('right') print(command) print(stop) clock.tick(30) pygame.quit() def setup_interactive_control(): """Setup the Pygame Interactive Control Screen""" pygame.init() display_size = (300, 400) screen = pygame.display.set_mode(display_size) background = pygame.Surface(screen.get_size()) color_white = (255, 255, 255) display_font = pygame.font.Font(None, 40) pygame.display.set_caption('RC Car Interactive Control') text = display_font.render('Use arrows to move', 1, color_white) text_position = text.get_rect(centerx=display_size[0] / 2) background.blit(text, text_position) screen.blit(background, (0, 0)) pygame.display.flip() def main(): """Main function""" interactive_control() if __name__ == '__main__': main()
bfbf9f91e966d755ab8b3e73a31a5fcf21f346a7
ed100miles/StructuresAndAlgorithms
/LinkedLists/test_single_linked_stack.py
1,385
3.546875
4
import unittest from single_linked_stack import LinkedStack class TestCase(unittest.TestCase): def setUp(self): self.stack = LinkedStack() for letter in 'abcd': self.stack.push(letter) def test_len(self): self.assertEqual(len(self.stack), 4) def test_is_empty(self): self.assertEqual(self.stack.is_empty(), False) for _ in range(self.stack.__len__()): self.stack.pop() self.assertEqual(self.stack.is_empty(), True) def test_pop(self): self.assertEqual(self.stack.pop(), 'd') self.assertEqual(self.stack.pop(), 'c') self.stack.pop() self.stack.pop() with self.assertRaises(IndexError): self.stack.pop() def test_push(self): self.stack.push('z') self.assertEqual(self.stack.pop(), 'z') self.stack.push(1) self.assertEqual(self.stack.pop(), 1) self.stack.push([3, 2, 1]) self.assertEqual(self.stack.pop(), [3, 2, 1]) def test_top(self): self.assertEqual(self.stack.top(), 'd') self.assertEqual(self.stack.top(), 'd') self.stack.pop() self.assertEqual(self.stack.top(), 'c') for x in range(3): self.stack.pop() with self.assertRaises(IndexError): self.stack.pop() if __name__ == '__main__': unittest.main()
6e4f7bb9672e9681520e16d6d94b2990c0d11e18
funktor/stokastik
/Cython/sieve/.ipynb_checkpoints/sieve_python-checkpoint.py
327
3.546875
4
import numpy as np def sieve(n): arr = np.empty(n+1, dtype=np.int32) arr.fill(1) arr[0], arr[1] = 0, 0 sqrt_n = int(np.sqrt(n)) for i in range(2, sqrt_n+1): if arr[i] == 1: j = i**2 while j <= n: arr[j] = 0 j += i return np.nonzero(arr)
dcb7db80084d17b86c8c51611b46d6b530acea62
Orbsa/CRUDbrary
/books_controller.py
1,486
3.546875
4
from db import * def create_table(): # It may be more appropriate to use a schema sql file.. ''' Create the database table if it's not already there should have title, author, isbn rented to be ISO8601 corresponding to time of last rental availble is boolean integer ''' table = """CREATE TABLE IF NOT EXISTS books( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, author TEXT NOT NULL, isbn TEXT NOT NULL ) """ db = get_db() c = db.cursor() c.execute(table) c.close() return True def get(book): statement = "SELECT * FROM books WHERE id = ?" return query_db(statement, [book['id']], one=True) def get_all(): statement = "SELECT id, title, author, isbn FROM books" return query_db(statement) def insert(book): statement = "INSERT INTO books(title, author, isbn) VALUES (?,?,?)" return query_db(statement, [book['title'], book['author'], book['isbn']], one = True) def update(updated_keys): book = get(updated_keys) if not book: return False for key in updated_keys: book[key] = updated_keys[key] statement = "UPDATE books SET title=?, author=?, isbn=? WHERE id = ?" query_db(statement, [book['title'], book['author'], book['isbn'], book['id']], one = True) return True def delete(book): statement = "DELETE FROM books WHERE id = ?" return query_db(statement, [book['id']], one = True)
91a5ae70d9483afad3a58968987fabbfcac8b38c
eljempek/informatika-python-if-zadaci
/zad2.py
788
3.984375
4
import math # Unesemo vrednosti a = float(input("Unesi vrednost a ")) b = float(input("Unesi vrednost b ")) c = float(input("Unesi vrednost c ")) # Proverujemo pravougaonost a2 = math.sqrt(b**2 + c**2) b2 = math.sqrt(a**2 + c**2) c2 = math.sqrt(a**2 + b**2) print((c2) or (a2) or (b2)) if ((c == c2) or (a == a2) or (b == b2)): # Ako je ovo tacno trougao je pravougaoni i izracunavamo njegovu povrsinu print("Trougao je pravougaoni") if (c == c2): povrsina = (a*b/2) print("Povrsina trougla je" , povrsina) if (a == a2): povrsina = (c*b/2) print("Povrsina trougla je" , povrsina) if (b == b2): povrsina = (a*c/2) print("Povrsina trougla je" , povrsina) else: # Ako nije nista od toga onda trougao nema pravi ugao print ("Trougao nije pravougli")
4e43ef04517af1d8f297d811b1d14d368a232834
woosanguk/solve-at-day
/Algorithms/Search/IceCreamParlor.py
402
3.84375
4
""" https://www.hackerrank.com/challenges/icecream-parlor/problem """ def ice_cream_parlor_solve(m, n, flavor): for i in range(n): for j in range(i + 1, n): if flavor[i] + flavor[j] == m: print(i + 1, j + 1) return if __name__ == "__main__": ice_cream_parlor_solve(4, 5, [1, 4, 5, 3, 2]) ice_cream_parlor_solve(4, 4, [2, 2, 4, 3])
b88d7be86cc8d5939b7573b44c842749abdd4ef5
tjvr/nefarious
/eval/b/fibiter2.py
115
3.625
4
def fib(n): return 1.0 if n < 2.0 else fib(n-1.0)+fib(n-2.0) import sys n = float(sys.argv[1]) print fib(n)
cfdef81f800ffc5e7725875d564736d02c7356d4
mangei/adventofcode2016
/21_2.py
5,208
3.703125
4
# Advent Of Code 2016 - http://adventofcode.com/2016 # python 21_2.py < input_21.txt # correct answer: gdfcabeh # --- Part Two --- # # You scrambled the password correctly, but you discover that you can't actually modify the password file on the system. You'll need to un-scramble one of the existing passwords by reversing the scrambling process. # # What is the un-scrambled version of the scrambled password fbgdceah? import re import sys __author__ = "Manuel Geier (manuel@geier.io)" def swapPositionXWithPositionY(data, x, y): data_list = list(data) data_list[y], data_list[x] = data_list[x], data_list[y] return "".join(data_list) assert swapPositionXWithPositionY("abcde", 4, 0) == "ebcda" assert swapPositionXWithPositionY("ebcda", 0, 4) == "abcde" def swapLetterXWithLetterY(data, x, y): return data.replace(x, "?").replace(y, x).replace("?", y) assert swapLetterXWithLetterY("abc", "a", "b") == "bac" assert swapLetterXWithLetterY("bac", "b", "a") == "abc" def rotateLeft(data): return data[1:] + data[0] assert rotateLeft("abc") == "bca" def rotateRight(data): return data[-1] + data[:-1] assert rotateRight("abc") == "cab" assert "abc" == rotateRight(rotateLeft("abc")) assert "abc" == rotateLeft(rotateRight("abc")) def rotate(data, direction, steps): for i in range(steps): if direction == "left": data = rotateLeft(data) else: data = rotateRight(data) return data assert rotate("abcdef", "left", 2) == "cdefab" assert rotate("cdefab", "right", 2) == "abcdef" assert rotate("abcdef", "right", 2) == "efabcd" assert rotate("efabcd", "left", 2) == "abcdef" def rotateBasedOnPositionOfLetterY(data, x): index = data.index(x) steps = index + 1 + (1 if index >= 4 else 0) return rotate(data, "right", steps) assert rotateBasedOnPositionOfLetterY("abcde", "b") == "deabc" assert rotateBasedOnPositionOfLetterY("abcde", "e") == "eabcd" assert rotateBasedOnPositionOfLetterY("abdec", "b") == "ecabd" assert rotateBasedOnPositionOfLetterY("ecabd", "d") == "decab" def unrotateBasedOnPositionOfLetterY(data, x): original_data = data data_scrambled = data # brute force while rotateBasedOnPositionOfLetterY(data_scrambled, x) != original_data: data_scrambled = rotateLeft(data_scrambled) return data_scrambled assert unrotateBasedOnPositionOfLetterY("deabc", "b") == "abcde" assert unrotateBasedOnPositionOfLetterY("eabcd", "e") == "abcde" assert unrotateBasedOnPositionOfLetterY("ecabd", "b") == "abdec" assert unrotateBasedOnPositionOfLetterY("decab", "d") == "ecabd" def reversePositionsXthroughY(data, x, y): return data[:x] + data[x:y + 1][::-1] + data[y + 1:] assert reversePositionsXthroughY("edcba", 0, 4) == "abcde" assert reversePositionsXthroughY("abcde", 0, 4) == "edcba" assert reversePositionsXthroughY("edcba", 1, 3) == "ebcda" assert reversePositionsXthroughY("ebcda", 1, 3) == "edcba" def movePositionXToPositionY(data, x, y): data_list = [] c = data[x] for i in range(len(data)): if i != x: data_list.append(data[i]) data_list2 = [] for i in range(len(data_list)): if i == y: data_list2.append(c) data_list2.append(data_list[i]) if y == len(data_list): data_list2.append(c) return "".join(data_list2) assert movePositionXToPositionY("bcdea", 1, 4) == "bdeac" assert movePositionXToPositionY("bdeac", 4, 1) == "bcdea" assert movePositionXToPositionY("bdeac", 3, 0) == "abdec" assert movePositionXToPositionY("abdec", 0, 3) == "bdeac" commands = [] for line in sys.stdin: commands.append(line) def unscramble(data): for line in commands[::-1]: oldData = data if line.startswith("swap position"): m = re.match("^swap position (\d+) with position (\d+)$", line) data = swapPositionXWithPositionY(data, int(m.group(1)), int(m.group(2))) elif line.startswith("swap letter"): m = re.match("^swap letter (.) with letter (.)$", line) data = swapLetterXWithLetterY(data, m.group(1), m.group(2)) elif line.startswith("rotate based on position of letter"): m = re.match("^rotate based on position of letter (.)$", line) data = unrotateBasedOnPositionOfLetterY(data, m.group(1)) elif line.startswith("rotate"): m = re.match("^rotate (.*) (\d+) step", line) data = rotate(data, "left" if m.group(1) == "right" else "right", int(m.group(2))) elif line.startswith("reverse positions"): m = re.match("^reverse positions (\d+) through (\d+)$", line) data = reversePositionsXthroughY(data, int(m.group(1)), int(m.group(2))) elif line.startswith("move position"): m = re.match("^move position (\d+) to position (\d+)$", line) data = movePositionXToPositionY(data, int(m.group(2)), int(m.group(1))) else: raise Exception("unknown command: " + line) if len(oldData) != len(data): print(line) raise Exception() return data assert unscramble("bdfhgeca") == "abcdefgh" print("un-scrambled", unscramble("fbgdceah"))
6742dceff83f65ca2978fe3b81fc87818502ccea
liu839/python_stu
/程序记录/基础/列表遍历.py
238
3.703125
4
#方法1 count = 0 length = len(member) while count < length: print(member[count], member[count+1]) count += 2 #方法二: for each in range(len(member)): if each%2 == 0: print(member[each], member[each+1])
4ddf9c302178860ed2dd9d3ab89e9ce4455b5dd0
Yeansovanvathana/Python
/Python program/List program/List 8.py
90
3.875
4
lis = [1, 2, 3, 4] if len(lis) == 0: print("list is empty") print("list is not empty")
952d54a9477cdd934a17de135dbf0ac19164ad2d
fantasylsc/LeetCode
/Algorithm/Python/25/0009_Palindrome_Number.py
1,310
4.25
4
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. ''' class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False original = x reverse = 0 while x > 0: digit = x % 10 x = x // 10 reverse = reverse * 10 + digit return reverse == original # Two pointers class Solution: def isPalindrome(self, x: int) -> bool: s = str(x) n = len(s) if n == 0 or n == 1: return True i = 0 j = n - 1 while i < n and j >= 0: if s[i] == s[j]: i += 1 j -= 1 else: return False return True # Haha class Solution: def isPalindrome(self, x: int) -> bool: return str(x) == str(x)[::-1]
23ab75d81425ddc9de6dc2de7db19aa398b84bdc
rajathelix/Green-Data-Centers
/Data_Analyzer.py
2,131
3.640625
4
import numpy as np import matplotlib.pyplot as plt import csv # Reads data def read_data(): x=[] y=[] z=[] with open('data.csv') as csvfile: readCSV=csv.reader(csvfile,delimiter=',') for row in readCSV: x.append(float(row[0])) y.append(float(row[1])) z.append(float(row[2])) return [x,y,z] def estimate_coef(x, y): # number of observations/points n = np.size(x) # mean of x and y vector m_x, m_y = np.mean(x), np.mean(y) # calculating cross-deviation and deviation about x SS_xy = np.sum(y*x - n*m_y**2) SS_xx = np.sum(x*x - n*m_x**2) # calculating regression coefficients b_1 = SS_xy / SS_xx b_0 = m_y - b_1*m_x return(b_0, b_1) def plot_regression_line(x, y, b): # plotting the actual points as scatter plot plt.scatter(x, y, color = "m", marker = "o", s = 30) # predicted response vector y_pred = b[0] + b[1]*x plt.plot(x,y_pred,color='g') # putting labels plt.xlabel('Time (Seconds)') plt.ylabel('Temperature (Celsius)') # function to show plot plt.show() def plot_histogram(x, y, b): plt.bar(x,y) #for i in range(len(y)): #plt.hlines(y[i],0,x[i]) plt.ylabel('Temperature (Celsius)') plt.xlabel('Time (Seconds)') plt.show() def main(): d=read_data() x=np.array(d[0]) y=np.array(d[1]) # estimating coefficients b = estimate_coef(x, y) #print("Estimated coefficients:\nb_0 = {} \ #\nb_1 = {}".format(b[0], b[1])) # plotting regression line plot_histogram(x, y, b) plot_regression_line(x,y,b) predict(x,y) def predict(x,y): time=int(input("Probable temperature at time= ")) x1 = np.array(x) y1 = np.array(y) b=estimate_coef(x1, y1) y_pred = b[0] + b[1]*time if(y_pred>=27.0): print("Temperature will be above thresdold value.") print("Extensive cooling will be initialized.") else: print("Temperature will be normal.") print("Expected temperature (Celsius) is: ",y_pred) if __name__ =="__main__": main()
38cdc513e8a15b0d66ffbfdef469c725e4cb0d85
helbertsandoval/trabajo10_sandoval-sanchez-helbert_cesar_maira_paz
/submenu6.py
1,057
3.84375
4
import libreria #1. Implementacion de submenu def agregarAreadelrectangulo(): #1 agregamos la base del rectangulo #2 agregamos la altura del rectangulo #3. calculamos el area del rectangulo base=libreria.pedir_numero("ingrese la base",3,300) altura=libreria.pedir_numero("ingrese la altura",2,500) print("ingrese el area del rectangulo", base*altura) def agregarAreadelcuadrado(): #1 agregamos el lado del cudrado #2 hallamos el area del cuadrado lado=libreria.pedir_numero("ingrese el lado:",2,10) print("ingrese el area del cuadrado", lado**2) # Menu de comandos opc=0 max=3 while(opc!= max): print("############### MENU ##############") print("#1. agregar el area del rectangulo") print("#2. agreegar el area del cuadrado") print("#3. Salir ") #2. Eleccion de la opcion menu opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3) #3. Mapeo de las opciones if (opc==1): agregarAreadelrectangulo() if (opc==2): agregarAreadelcuadrado()
80004bc64883448534290b38d54a2b70e0dce9a8
BenDosch/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
543
4.59375
5
#!/usr/bin/python3 """ Module containing a function that says your name """ def say_my_name(first_name, last_name=""): """ function that prints, 'my name is' followed by a first and last name Args: first_name (str): Individual's name last_name (str): Family's name """ if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") print("My name is {} {}".format(first_name, last_name))
1de36922d427cd066ae7b71a0136f8ebca302dea
Yucheng7713/CodingPracticeByYuch
/Medium/314_binaryTreeVerticalOrderTraversal.py
732
3.78125
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 verticalOrder(self, root: 'TreeNode') -> 'List[List[int]]': if not root: return [] v_map = collections.defaultdict(list) t_queue = [(root, 0)] while t_queue: k = len(t_queue) for i in range(k): node, index = t_queue.pop(0) v_map[index].append(node.val) if node.left: t_queue.append((node.left, index - 1)) if node.right: t_queue.append((node.right, index + 1)) return [v for k, v in sorted(v_map.items())]
4ccd28e76938385e39f8b4dc0d19698cde52d585
srinisim/UMich-CIS-ECE
/CIS 350/Program 3/Program3.py
3,411
3.921875
4
# Srinivas Simhan # CIS 350 - Elenbogen: Winter 2018 # Program 3 # Due: 3/27/18 class Germ: def __init__(self): self.children = [] self.ancestors = set() self.index = None """ PRE: - None POST: - returns the number of ancestors associated with the object DESCRIPTION: - method to find the number of ancestors of the object associated with the of Germ """ def indegree(self): return len(self.ancestors) class PriorityQue: def __init__(self): self.list = [] self.length = 0 """ PRE: - takes in the germ object POST: - appends the germ object onto the end of the priority list - increases the length of the priority list by 1 DESCRIPTION: - the purpose of this method is to apend the germ object onto the priority list and increases the length dynamically """ def push(self, germ): self.list.append(germ) self.length += 1 """ PRE: - None POST: - in a for loop, checks if the degrees of the germ being tested are less than the minGerm degrees, and reset it accordingly - else it checks if the germ index is less than the min germ index and reset it accordingly - then removed the knownMinGerm and decreases the length of the list by 1 (the absence of that value) DESCRIPTION: - uses the number of ancestors and the index value of the germ to remove the minimum valued germ """ def deleteMin(self): knownMinGerm = self.list[0] for germ in self.list: if germ.indegree() < knownMinGerm.indegree(): knownMinGerm = germ else: if germ.index < knownMinGerm.index: knownMinGerm = germ self.list.remove(knownMinGerm) self.length -= 1 return knownMinGerm """ PRE: - input for germList POST: - print them out in topological orders DESCRIPTION: - prints out the topologicalIndexes order without the new line issue when it gets posted """ def main(): totalGermCount = int(input()) if totalGermCount > 2000: exit() elif totalGermCount <= 0: exit() germList = [] for i in range(totalGermCount): germ = Germ() germ.index = i + 1 germList.append(germ) priorityQueue = PriorityQue() for germ in germList: priorityQueue.push(germ) childIndexes = input().split() # list of ints as strings childIndexes.pop() # discard the ending zero for childIndex in childIndexes: childGerm = germList[int(childIndex) - 1] childGerm.ancestors.add(germ) germ.children.append(childGerm) topological = [] while len(priorityQueue.list) > 0: # priorityQueue.sort(key=lambda germ : (len(germ.ancestors), germ.index)) # removedGerm = priorityQueue.pop(0) removedGerm = priorityQueue.deleteMin() topological.append(removedGerm) for childGerm in removedGerm.children: childGerm.ancestors.add(removedGerm) childGerm.ancestors.update(removedGerm.ancestors) topologicalIndexes = [] topological.sort(key=lambda germ : (len(germ.ancestors), germ.index)) for germ in topological: topologicalIndexes.append(germ.index) print(*topologicalIndexes, end='') main()
95ebdb366ce15b967916bfd2996cd1a6b707918f
Sangewang/PythonBasicLearn
/LeetCode/ImplementStrstr.py
844
3.6875
4
class Solution(object): def strStr(self, haystack, needle): haystack_lenth = len(haystack) needle_lenth = len(needle) if(haystack_lenth == 0 and needle_lenth == 0): return 0 target_local = -1 print("The Length of haystack is %d" % haystack_lenth) print("The Length of needle is %d" % needle_lenth) for i in xrange(haystack_lenth): if i>(haystack_lenth - needle_lenth): break tmp_i = i match = 0 while(match < needle_lenth and tmp_i < haystack_lenth and haystack[tmp_i] == needle[match]): print needle[match] tmp_i += 1 match += 1 if(match == needle_lenth): target_local = i break return target_local Test = Solution() print Test.strStr('MyPython','Py') print Test.strStr('','')
4b4c2ea4817adc9c1310d92e38e393263010197a
TheSussex/SCAMP-Assesment
/mycode.py
700
4.375
4
# This program gives a fibonacci sequence based on the input of the user # Author- Success Ologunsua given_num = int(input("How many terms? ")) # accepting input from the user into the (given_num) variable n1, n2 = 0, 1 # first two terms count = 0 sequence = [] if given_num <= 0: # check if the number of terms is valid print("Please enter a valid term (term must be greater than 0)") elif given_num == 1: print("Fibonacci sequence up to",given_num,":") print(n1) else: print("For a sequence of",given_num, ",you have:") while count < given_num: sequence.append(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1 print(sequence)
b1c53fbcc4d3fbfe9642ff4d05b945090b3749b8
Caff1982/PyChess
/board.py
2,997
3.890625
4
import copy class Board: """ Class to keep track of chess board and move pieces. Castling rights are stored as class attributes and updated in the move_piece function. """ def __init__(self, board=None): if board is None: self.board = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'] + \ ['p']* 8 + \ ['0']* 32 + \ ['P']* 8 + \ ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'] else: self.board = board self.white_can_castle = True self.black_can_castle = True def print_board(self): print('\n 0 1 2 3 4 5 6 7') for i in range(8): print(i, ' '.join(self.board[i*8:i*8+8])) def get_testboard(self, from_idx, to_idx): """ Returns a copy of the Board object with piece moved """ testboard = copy.deepcopy(self) piece = self.board[from_idx] testboard.board[from_idx] = '0' testboard.board[to_idx] = piece return testboard def move_piece(self, from_idx, to_idx): piece = self.board[from_idx] to_piece = self.board[to_idx] # King cannot be take if to_piece in ('k', 'K'): pass # Pawn promotion elif piece == 'p' and to_idx // 8 == 7: self.board[to_idx] = 'q' self.board[from_idx] = '0' elif piece == 'P' and to_idx // 8 == 0: self.board[to_idx] = 'Q' self.board[from_idx] = '0' # Check for castling elif piece == 'k': if to_idx == 0 and self.black_can_castle: self.board[0] = '0' self.board[1] = 'k' self.board[2] = 'r' self.board[4] = '0' elif to_idx == 7 and self.black_can_castle: self.board[4] = '0' self.board[5] = 'r' self.board[6] = 'k' self.board[7] = '0' else: # Normal move to empty square self.board[from_idx] = '0' self.board[to_idx] = piece # Update castling rights self.black_can_castle = False elif piece == 'K': if to_idx == 56 and self.white_can_castle: self.board[56] = '0' self.board[57] = 'K' self.board[58] = 'R' self.board[60] = '0' elif to_idx == 63 and self.white_can_castle: self.board[60] = '0' self.board[61] = 'R' self.board[62] = 'K' self.board[63] = '0' else: self.board[from_idx] = '0' self.board[to_idx] = piece self.white_can_castle = False else: # Normal move to empty square self.board[from_idx] = '0' self.board[to_idx] = piece
71bc72183050d0206f1bf55d91ee2d83fdeb2509
olgayordanova/PythonAdvanced
/AdvancedExamsPreparation/02.Snake.py
1,645
3.921875
4
def make_jump (r, c, mtr): for i in range (len(mtr)): for j in range (len(mtr)): if mtr[i][j]=="B" and (i!=r and j!=c): return i,j def is_valid_position (row, col, n): if 0 <= row < n and 0 <= col < n: return True return False n = int(input()) matrix = [ list(input()) for _ in range(n)] move_dict = {"up":(-1,0), "down":(1,0), "left":(0,-1), "right":(0,1)} coord = [(x,y) for x in range(0,n) for y in range(0,n) if matrix[x][y]=="S"] current_r, current_c =coord[0][0], coord[0][1] food_quantity=0 command = input() while command!="": move_r, move_c = move_dict[command] if is_valid_position (current_r+move_r, current_c+move_c, n): move_position = matrix[current_r+move_r][current_c+move_c] matrix[current_r + move_r][current_c + move_c] ="S" matrix[current_r][current_c] = "." if move_position =="-": current_r, current_c = current_r + move_r, current_c + move_c elif move_position =="*": food_quantity+=1 current_r, current_c = current_r + move_r, current_c + move_c if food_quantity>=10: print("You won! You fed the snake.") break elif move_position =="B": matrix[current_r + move_r][current_c + move_c] = "." current_r, current_c = make_jump (current_r, current_c, matrix) else: matrix[current_r][current_c] = "." print("Game over!") break command = input () print(f"Food eaten: {food_quantity}") print ('\n'.join( ''.join((el)) for el in matrix))
17c3c38ba1756b19020f0e7b908a15ad6a95de6f
MeirNizri/KNN
/main.py
2,409
3.53125
4
import numpy as np from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt from KNearestNeighbor import KNearestNeighbor # Create all points and labels from rectangle.txt points = [] f = open("rectangle.txt", "r") for line in f: words = line.split() points.append([float(words[0]), float(words[1]), float(words[2])]) f.close() # set optional knn hyper parameters num_iters = 100 k_choices = [1, 3, 5, 7, 9] dist_func = ["l1", "l2", "linf"] train_errors = np.zeros((len(dist_func), len(k_choices))) test_errors = np.zeros((len(dist_func), len(k_choices))) knn_best_result = 1 for i in range(num_iters): # randomly split point to half train and half test train, test = train_test_split(np.array(points), test_size=0.5, shuffle=True) train_x, train_y = train[:, :2], train[:, 2] test_x, test_y = test[:, :2], test[:, 2] for (n, func) in enumerate(dist_func): for (m, k) in enumerate(k_choices): # create a kNN classifier instance and compute the predictions knn_classifier = KNearestNeighbor() knn_classifier.train(train_x, train_y) pred_train = knn_classifier.predict(train_x, k=k, dist_func=func) pred_test = knn_classifier.predict(test_x, k=k, dist_func=func) # calculate errors on train and test set train_errors[n][m] += np.sum(pred_train != train_y)/len(train_y) test_acc = np.sum(pred_test != test_y)/len(test_y) test_errors[n][m] += test_acc # save best model if test_acc < knn_best_result: knn_best_result = test_acc knn_best_model = knn_classifier train_errors /= num_iters test_errors /= num_iters # print results np.set_printoptions(precision=4) print("train mean error: \n", train_errors, "\n") print("test mean error: \n", test_errors, "\n") # plot the test results l1, l2, linf = [], [], [] for (i, k) in enumerate(k_choices): plt.scatter([k] * len(dist_func), test_errors[:, i]) # create line between all k values for each distance function plt.errorbar(k_choices, test_errors[0, :], label='L1') plt.errorbar(k_choices, test_errors[1, :], label='L2') plt.errorbar(k_choices, test_errors[2, :], label='Linf') plt.legend(loc='lower right') plt.title('K-NN test errors') plt.xlabel('k values') plt.ylabel('errors') plt.ylim(-0.02, 0.11) plt.show()
20bde3099a6c5149755ea05b98b72d5fe9718395
ssamea/team_note
/sort/H-index.py
709
3.8125
4
# 어떤 과학자가 발표한 논문 n편 중, # h번 이상 인용된 논문이 h편 이상이고 나머지 논문이 h번 이하 인용되었다면 h의 최댓값이 이 과학자의 H-Index입니다 def solution(citations): answer = 0 citations.sort(reverse=True) # 먼저 f 값을 가장 큰 값에서 가장 낮은 값으로 정렬 citations.insert(0,0) # print(citations) for i in range(1, len(citations)): if i == citations[i]: answer = i break if i >= citations[i]: answer = i-1 break else: answer=i #print(h_index) return answer citations = [10,50,100] print(solution(citations))
7513f32b60ad82f59f3a0213891d3e6d58591963
cmf2196/quadruped_robot
/PygameController.py
5,401
3.734375
4
""" Connor Finn 9/14/2020 # To run. + You need pygame 2 python3 -m pip install pygame==2.0.0.dev6 + Connect your PS4 Controller to the computer over bluetooth (wired will work fine too) # This is a modified Version of Josh's PygameController """ import time import pygame import platform class PygameController: def __init__(self): self.joystick = None pygame.init() self.connect_to_controller() if self.joystick != None: self.num_analog = self.joystick.get_numaxes() self.num_digital = self.joystick.get_numbuttons() self.num_hat = self.joystick.get_numhats() # keep a running tab of the controller state self.digital_state = [0] * self.num_digital self.analog_state = [0] * self.num_analog self.hat_state = [0] * self.num_hat # i want the previous digital state as well so that we can # keep track of changes self.previous_digital_state = None # for analog control self.minimum = 0.2 def connect_to_controller(self): # check if controller is plugged in joystick_count = pygame.joystick.get_count() if joystick_count == 0: # No joysticks! print("Error, I didn't find any joysticks.") self.joystick = None else: # Use joystick #0 and initialize it self.joystick = pygame.joystick.Joystick(0) self.joystick.init() # Prints the joystick's name JoyName = pygame.joystick.Joystick(0).get_name() print(JoyName) def get_button(self, button): self.refresh_controller() return self.joystick.get_button(button) def update_digital(self): d_vals = range(self.num_digital) self.previous_digital_state = self.digital_state self.digital_state = [self.joystick.get_button(v) for v in d_vals] def update_analog(self): a_vals = range(self.num_analog) states = [self.joystick.get_axis(v) for v in a_vals] self.analog_state = [self.check_min(s) for s in states] def update_hat(self): h_vals = range(self.num_hat) self.hat_state = [self.joystick.get_hat(h) for h in h_vals] def check_min(self, val): # don't want to have 0.2 or less if abs(val) <= self.minimum: return 0 else: return val def update_controller(self): # get current events self.refresh_controller() # update buttons self.update_analog() self.update_digital() self.update_hat() def get_analog(self): self.update_controller() return self.analog_state def get_digital(self): self.update_controller() return self.digital_state def get_hat(self): self.update_controller() return self.hat_state @staticmethod def refresh_controller(): # This is called each time to get the current state of the controller pygame.event.get() class PS4Controller(PygameController): def __init__(self): super(PS4Controller, self).__init__() if platform.system() == 'Darwin': self.digital = {'x' : 0 , 'circle': 1 , 'square':2 , 'triangle': 3 , 'share': 4 , 'power': 5 , 'options': 6 , 'L3': 7 \ , 'R3': 8 , 'L1': 9 , 'R1': 10 , 'up_arrow': 11 , 'down_arrow': 12 , 'left_arrow': 13 , 'right_arrow' : 14 , 'touchpad': 15} # values are (id , dir) id is int, dir is -1 or 1 (do the values need to be flipped) # R2, L2 should be -1 when not used, 1 when used # for joysticks, left and down are -1 , up and right are 1 self.analog = {'left_joystick_horizontal': [0 , 1] , 'left_joystick_vertical': [1 , -1 ] , 'right_joystick_horizontal': [2 , 1] \ , 'right_joystick_vertical': [3 , -1] , 'L2': [4 , 1] , 'R2': [5 , 1]} self.hat = {} elif platform.system() == 'Linux': self.digital = {'x' : 0 , 'circle': 1 , 'triangle':2 , 'square': 3 , 'L1': 4 , 'R1': 5 , 'share': 8 , 'options': 9 \ , 'power': 10 , 'L3': 11 , 'R3': 12 } self.analog = {'left_joystick_horizontal': [0 , 1] , 'left_joystick_vertical': [1 , 1 ] , 'L2': [2 , 1] , 'right_joystick_horizontal': [3 , 1] \ , 'right_joystick_vertical': [4 , 1] , 'R2': [5 , 1]} self.hat = {} # JOSH - Run pygame_config.py and figure out your button mapping elif platform.system() == 'Windows': self.digital = {'x' : 1 , 'circle': 2 , 'square':0 , 'triangle': 3 , 'share': 8 , 'power': 12 , 'options': 9 , 'L3': 10 \ , 'R3': 11 , 'L1': 4 , 'R1': 5 , 'touchpad': 13} self.analog = {'left_joystick_horizontal': [0 , 1] , 'left_joystick_vertical': [1 , -1 ] , 'right_joystick_horizontal': [2 , 1] \ , 'right_joystick_vertical': [3 , -1] , 'L2': [4 , 1] , 'R2': [5 , 1]} self.hat = {'none' : (0,0), 'left': (-1,0), 'up': (0,1),'right': (1,0), 'down': (0,-1),'up_left': (-1,1),'up_right': (1,1), 'down_right': (1,-1),'down_left': (-1,-1),} if __name__ == '__main__': controller = PygameController() while True: print(controller.get_hat()) time.sleep(0.5)
ffb4cf91c39aca61c25dae01e284970bc0b3fe2c
prashantchanne12/Leetcode
/find the median of a number stream.py
1,401
4
4
from heapq import * class MedianOfStream: # cotains first half of numbers maxHeap = [] # contains second half of numbers minHeap = [] def insert_num(self, num): if not self.maxHeap or -self.maxHeap[0] >= num: heappush(self.maxHeap, -num) else: heappush(self.minHeap, num) # either both heaps will have equal number of elements or max-heap will have more elements than min-heap if len(self.maxHeap) > len(self.minHeap) + 1: heappush(self.minHeap, -heappop(self.maxHeap)) elif len(self.maxHeap) < len(self.minHeap): heappush(self.maxHeap, -heappop(self.minHeap)) def find_median(self): if len(self.maxHeap) == len(self.minHeap): # we have even number of elements, take the average of middle two elements return -self.maxHeap[0] / 2.0 + self.minHeap[0] / 2.0 # because max-heap will have one more element than the min-heap return -self.maxHeap[0] / 1.0 def main(): medianOfStream = MedianOfStream() medianOfStream.insert_num(3) medianOfStream.insert_num(1) print('The median is: '+str(medianOfStream.find_median())) medianOfStream.insert_num(5) print('The median is: '+str(medianOfStream.find_median())) medianOfStream.insert_num(4) print('The median is: '+str(medianOfStream.find_median())) main()
91e81e45b330a1f1beba23190a0a352f7cda63bd
carlsfg/semestrei
/sums.py
698
3.65625
4
def sum2(): print x + y def sum3(): print x + y + z def sum4(): print x + y + z + a def sum5(): print x + y + z + a + b def sum6(): print x + y + z + a + b + c def sum7(): print x + y + z + a + b + c + d def sum8(): print x + y + z + a + b + c + d + e def sum9(): print x + y + z + a + b + c + d + e + f def sum10(): print x + y + z + a + b + c + d + e + f + g selector = input("Selecciona el numero de variables a sumar: ") if selector == 2: x = input() y = input() sum2() elif selector == 3: x = input() y = input() z = input() sum3() elif selector == 4: x = input() y = input() z = input() a = input() sum4()
088a7bf8ef1a0becea59e6930dea56e206361b3c
mathiasare/IdsSoccerPredictionsProject
/data_mining/data_extractor.py
860
3.96875
4
#From https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/ import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn #General function for sqlite queries def execQuery(conn,query,print_out=True,limit=0): if(limit!=0): query += " LIMIT "+str(limit) cur = conn.cursor() cur.execute(query) rows = cur.fetchall() if(print_out): for row in rows: print(row) #Example conn = create_connection("./database.sqlite") query = "SELECT * FROM Match" execQuery(conn,query,limit=10)
55427007e8b5334d85f6ed4e0564e403c0edddd1
Draqneel/Python
/python_hacks/script.py
1,697
4
4
from collections import Counter def main(): string = "i need some sleep" a = string[0:6] b = string[7:11] print("Main string: " + string) print("1) String reverse: " + string_reverse(string)) print("2) To title: " + string.title()) print("3) Find unique: " + find_unique(string)) print("4) List genetator: ", [3*letter for letter in string]) a, b = b, a print("5) Swap values: a-",a,"b-",b) print("6) Split on substrings: ", string.split()) print("7) Join words by symbol: " + ",".join(string.split())) print("8) Is palindrome: ", is_palindrome("ababa"), "(ababa)") print("9) Count of element 's': ", сount_of_elements(string)["s"]) print("10) Most common:", сount_of_elements(string).most_common(1)) print("11) Is anagram? ('ababa', 'baaab'):", is_anagram("ababa", "baaab")) dict_1 = {'apple': 9, 'banana': 6} dict_2 = {'banana': 4, 'orange': 8} print("12) Concat two dicts ({'apple': 9, 'banana': 6}, {'banana': 4, 'orange': 8})", {**dict_1, **dict_2}) print("13) Is unique? ('1345','1111'):", is_unique("1345"), is_unique("1111")) def string_reverse(string): return string[::-1] def find_unique(string): uniq_set = set(string) return "".join(uniq_set) def is_palindrome(string): if string == string[::-1]: return True return False def сount_of_elements(string): return Counter(string) def is_anagram(string_one, string_two): if Counter(string_one) == Counter(string_two): return True return False def is_unique(string): if len(string) == len(set(string)): return True return False if __name__ == "__main__": main()
0d6bb7fd51be8847bc0b317a987eaaad13329c43
impiyush83/expert-python
/operator_overloading.py
974
3.984375
4
# operators cannot be used to do manipulations on objects # operqtor overloading can be done in python with help of magic functions class complex: def __init__(self, a, b): self.a = a self.b = b # adding two objects def __add__(self, other): return self.a + other.a, self.b + other.b Ob1 = complex(1, 2) Ob2 = complex(2, 3) Ob3 = Ob1 + Ob2 print(Ob3) """ Python magic functions for operator overloading OPERATOR MAGIC METHOD + __add__(self, other) – __sub__(self, other) * __mul__(self, other) / __truediv__(self, other) // __floordiv__(self, other) % __mod__(self, other) ** __pow__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) == __eq__(self, other) != __ne__(self, other) -= __isub__(self, other) += __iadd__(self, other) *= __imul__(self, other) /= __idiv__(self, other) //= __ifloordiv__(self, other) %= __imod__(self, other) **= __ipow__(self, other) """
e45bc5ee3c90702c9f67642fb4c0090f3169f3d6
aduV24/python_tasks
/Task 4/example.py
4,398
4.15625
4
#************* HELP ***************** #REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LOG IN TO www.hyperiondev.com/support TO: #START A CHAT WITH YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL. #************************************* # PLEASE ENSURE YOU OPEN THIS FILE IN IDLE otherwise you will not be able to read it. # *** NOTE ON COMMENTS *** # This is a comment in Python. # Comments can be placed anywhere in Python code and the computer ignores them -- they are intended to be read by humans. # Any line with a # in front of it is a comment. # Please read all the comments in this example file and all others. # ========= How to Declare Variables =========== # When you declare a variable, you determine its name and data type # In Python however you do not need to indicate the data type of the variable. # This is because Python detects the variable's data type by reading how data is assigned to the variable. # You use the assignment operator ‘=‘ to assign a value to a variable. # ************ Example 1 ************ num = 2 # the variable num is assigned the integer or whole number 2, due to the presence of digits and lack of quotation marks # ************ Example 2 ************ num2 = 12.34 # the variable num2 is assigned the float or decimal number 12.34, due to the presence of the decimal point and lack of quotation marks # ************ Example 3 ************ greeting = "Hello, World!" # the variable greeting is assigned the String Hello, World!, due to the presence of quotation marks ("...") # ************ Example 4 ************ number_str = "10" # Watch out! Since you defined 10 within quotation marks, Python knows this is a String. It's not an integer even though we understand 10 is a number. # ========= Changing a Value Held by a Variable =========== # If you want to change a value held by a variable, simply assign it another value # ************ Example 5 ************ num3 = 4 num3 = 5 # this changes the integer value 4 held in num3 to 5 # ========= Casting =========== # Casting basically means taking a variable of one particular data type and “turning it into” another data type # To do this you need to use the following functions: # str() - converts variable to String # int() - converts variable to Integer # float() - converts variable to Float # ************ Example 7 ************ # Using str() to convert an Integer to String number = 10 number_str = str(number) print("Example 7: ") print(number_str) # ************ Example 8 ************ # Using int() to convert a Float to Integer number_float = 99.99 number_int = int(number_float) print("Example 8: ") print(number_int) # run this example; notice that number_int does not contain a decimal? # ****************** END OF EXAMPLE CODE ********************* # # ======================= Play around with Python a bit =========================================== # # At this point, why not play around with creating variables? Press the windows Start button (in the bottom left corner of your screen), in the 'Search for programs and files' box, # type 'Python (command line)' and you should see a program named exactly that pop up. Click to run the program. # In the black box that appears, type: # # name = "John" # # then press enter. Nothing happens but this Python program has remembered what you set the variable 'name' to. # To prove this type: # # print(name) # # and then hit enter. 'John' should be printed out by the program. # If you close this black box, and open a new one and type: print(name) , you will get an error. This is because you were coding in the Python 'Shell' and your variables aren't saved. # We write Python code statements in text editors like Notepad++ or the IDLE Python GUI so that all our variable definitions and code are saved. # We can then run these files as Python programs at any time we want, and we can use these programs repeatedly. # Keep the black box open and try out some commands as you read through this file. Try to add some numbers and variables. # -> you are actually writing Python code already, it's that simple! # # ==================================================================================================
ce573942dff69562fbc4a212be3e7d05bab4fd34
SirGuiL/Python
/Mundo 3/Python_Exercicios/ex080.py
546
3.921875
4
lista = [] maior = 0 menor = 0 for c in range(0, 5): num = int(input('Digite um número inteiro: ')) if c == 0 or num > lista[-1]: print('Adicionado ao final da lista') lista.append(num) else: posição = 0 while posição < len(lista): if num <= lista[posição]: lista.insert(posição, num) print(f'Adicionado a posição {posição}') break posição += 1 print(f'Valores digitados ordenados de forma crescente: {lista}')
653fda668ee89fe97df9541ef9298d807ee1f3c9
simba28/daily-codes
/sortArrayByParity.py
604
3.625
4
class Solution: def sortArrayByParity(self, A): # even = [] # odd = [] # for n in A: # if n%2 == 0: # even.append(n) # else: # odd.append(n) # return even+odd i, j = 0, len(A)-1 while i<j: if A[i]%2 > A[j]%2: A[i], A[j] = A[j], A[i] if A[i]%2 == 0: i += 1 if A[j]%2 == 1: j -= 1 return A print(Solution().sortArrayByParity([1,2,3,4,5,6,7,8]))
e16cebcfc69bd09a5d356697fd1a04bca9cbd1f0
lucken99/Qs
/poddu.py
216
3.609375
4
n = int(input()) if(n < 0): print("Wrong Input") else: p=n*n*n*n flag = False while (n>0): if(n%10==p%10): n=n//10 p=p//10 else: print("FALSE") flag = True break if not flag: print("TRUE")
119c5f6fd7547df7c143c16fe98883844e383b3c
hswang108/Algorithm_HW
/WEEK4/LeetCode/queue_array.py
199
3.65625
4
def enqueue(myQueue, val): for i in range(len(a)-1,0,-1): a[i] = a[i-1] a[0] = val a = [5, 4, 3, 2, 1] print(a) # a = [5, 5, 4, 3, 2] # a = [6, 5, 4, 3, 2] enqueue(a, 6) print(a)
7394bdf13e37d6a6fbcbba7424c97f000931d3d4
mewwts/pyudorandom
/pyudorandom/pyudorandom.py
1,499
4
4
import random """ Functions for generating the cyclic group [0,...n-1]. Use instead of random.shuffle() or similar. Functions: pyudorandom(n) <- generate the numbers in 0,...n-1 bin_gcd(a, b) <- calculate the gcd of a and b fast """ def items(ls): """ Yields the elements of ls in a pseudorandom fashion. """ num = len(ls) if num == 0: return for i in indices(num): yield ls[i] def shuffle(ls): """ Takes a list ls and returns a new list with the elements of ls in a new order. """ return list(items(ls)) def indices(n): """ Generates the cyclic group 0 through n-1 using a number which is relative prime to n. """ rand = find_gcd_one(n) i = 1 while i <= n: yield i*rand % n i += 1 def find_gcd_one(n): """ Find a number between 1 and n that has gcd with n equal 1. """ while True: rand = int(random.random() * n) if bin_gcd(rand, n) == 1: return rand def bin_gcd(a, b): """ Return the greatest common divisor of a and b using the binary gcd algorithm. """ if a == b or b == 0: return a if a == 0: return b if not a & 1: if not b & 1: return bin_gcd(a >> 1, b >> 1) << 1 else: return bin_gcd(a >> 1, b) if not b & 1: return bin_gcd(a, b >> 1) if a > b: return bin_gcd((a - b) >> 1, b) return bin_gcd((b - a) >> 1, a)
396a239fbff4cc252972862fc758ede2ebd6a8d1
khanhbao128/HB-Code-Challenge-Problems
/Whiteboarding problems/Easier/max_of_three.py
429
4.34375
4
# define a function that takes in 3 numbers and return the largest def max_of_three(num1, num2, num3): """Return the largest number in three numbers given""" if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 elif num3 >= num1 and num3 >= num2: return num3 else: return "Something went wrong" print(max_of_three(10, 1, 11))
c92ef065f86b9c7ff5cce0eecbf0da9fd03dc9f0
GregorH97/HW070172
/L07/Ch11/5.py
2,540
4
4
def getthings(): nums = [] xStr = input("Enter numbers you want to have in your listing (<Enter> to quit)") while xStr != "": x = int(xStr) nums.append(x) xStr = input("Enter numbers you want to have in your listing (<Enter> to quit)") return nums def count(listing): x = 0 for i in range(len(listing)): x = x + 1 print("There are", x, "items in your listing.") def isin(listing): search = input(int("Please enter which number you want to check to be in this listing.")) # # for i in range(len(listing)): # x =1 # if i == search: # print("The your entered number is in the listing.") # else: # print("Your searched number is not in the listing.") def index(listing): search = input(int("Please enter which number you want to check the place in this listing.")) for i in range(len(listing)): if listing[i] == search: print("The searched for number is at the", i +"th place in the listing.") else: print("Your searched number is not in the listing.") def reverse(listing): reverselisting = [] for i in range(len(listing)): x = listing[(i + 1)* (-1)] reverselisting.append(x) print("The reversed listing is: ", reverselisting) def sort(listing): sortedlisting = [] order = eval("Which order do you want your listing to have? Enter 'descending' or 'ascending'.") if order == "descending": for i in range(len(listing)): x = min(listing) sortedlisting.append(x) print("The newly ordered listing is:", sortedlisting) elif order == "ascending": for i in range(len(listing)): x = max(listing) sortedlisting.append(x) print("The newly ordered listing is:", sortedlisting) else: print("Please try again") def main(): print("This program can do a lot of operations with listings.") listing = getthings() method = input("Please enter what you want to do with that listing: 'count', 'isin', 'index', 'reverse', or 'sort'") if method == "count": count(listing) elif method == "isin": isin(listing) elif method == "index": index(listing) elif method == "reverse": reverse(listing) elif method == "sort": sort(listing) else: print("Please try ahain") main()
74cda4c510e302d09840506132078fd0784904c3
syves/euler
/euler3.py
711
4
4
import math def isprime(n): ceil_sqrt_n = math.ceil(math.sqrt(n)) for x in range(2, int(ceil_sqrt_n)): if n % x == 0: return False return True def factorize(n): """ Returns a set of factors of n. """ ceil_sqrt_n = math.ceil(math.sqrt(n)) factors = [] for x in range(2, int(ceil_sqrt_n)): if n % x == 0: factors.append(x) factors.append(n/x) return factors def euler3(n): """ Problem 3 - Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ return max(filter(isprime, factorize(n))) print euler3(600851475143)
2d6fff7ccf5fa6df15db70c88cb219a977ed95ed
michal0janczyk/udacity_data_structures_and_algorithms_nanodegree
/Data Structures/Arrays and Linked List/arrays/Add-One_solution.py
4,009
4.25
4
# Solution """ The Logic 1. The idea is to start checking the array from the right end, in a FOR loop. 2. Add 1 to the digit, and check if it lies in the range 0-9 OR becomes 10. 3. If the updated digit is between 0-9, quit the FOR loop. (Example, original array is [1,2,3]) 4. Otherwise update the current position in the array, and carry over the "borrow" to the next left digit. (Example, original array is [9,9,9]) 5. Once, we finish iteratig over all the digits of the original array, we will be left with the final "borrow", either 0 or 1. Prepend this "borrow" to the original array. 6. Return the updated array, but there is trick which helps us to select the starting index of the updated array. Example, [0, 1, 2, 4] is the updated array, and we want to return only [1, 2, 4] """ # Change the arr in-place def add_one(arr): borrow = 1 # initial value """ The three arguments of range() function are: starting index, ending index(non-inclusive), and the increment/decrement value """ # Traverse in reverse direction starting from the end of the list # The argument of range() functions are: # starting index, ending index (non exclusive), and the increment/decrement size for i in range(len(arr), 0, -1): # The "digit" denotes the updated Unit, Tens, and then Hunderd position iteratively digit = borrow + arr[i - 1] """ The "borrow" will be carried to the next left digit If the digit is between 0-9, borrrow will be 0. If digit is 10, then the borrow will be 1. """ # The "//" is a floor division operator borrow = digit // 10 if borrow == 0: # Update the arr[i - 1] with the updated digit, and quit the FOR loop. arr[i - 1] = digit break else: # Update the arr[i - 1] with the remainder of (digit % 10) arr[i - 1] = digit % 10 # Prepend the final "borrow" to the original array. arr = [borrow] + arr # In this final updated arr, find a position (starting index) from where to return the list. # For [0, 1, 2, 4] , the position (starting index) will be 1 # For [1, 0, 0, 0] , the position (starting index) will be 0 position = 0 while arr[position] == 0: position += 1 return arr[position:] # -------------------------------------# # Descriptive Example 1 - Original array is [1, 2, 3] # -------------------------------------# """ FOR LOOP BEGINS For i=3 , arr[2]=3 , digit=4 , borrow=0 BORROW COMPARISON START Since borrow is 0, update arr[2] = digit = 4 and quit the FOR loop. NO need to check other digits on the left of current digit FOR LOOP ENDS Append [0] to the beginning of the original arr. Now arr = [0, 1, 2, 4] In this final updated arr, find a position from where to return the list. This position (index) = 1 Return [1, 2, 4] """ # -------------------------------------# # Descriptive Example 2 - Original array is [9, 9, 9] # -------------------------------------# """ FOR LOOP BEGINS For i= 3 , arr[ 2 ] = 9 , digit = 10 , borrow = 1 BORROW COMPARISON START Since borrow is non-zero, update arr[ 2 ] = digit % 10 = 0 Update output = borrow = 1 BORROW COMPARISON ENDS For i= 2 , arr[ 1 ] = 9 , digit = 10 , borrow = 1 BORROW COMPARISON START Since borrow is non-zero, update arr[ 1 ] = digit % 10 = 0 Update output = borrow = 1 BORROW COMPARISON ENDS For i= 1 , arr[ 0 ] = 9 , digit = 10 , borrow = 1 BORROW COMPARISON START Since borrow is non-zero, update arr[ 0 ] = digit % 10 = 0 Update output = borrow = 1 BORROW COMPARISON ENDS FOR LOOP ENDS Append [1] to the beginning of the original arr. Now arr = [1, 0, 0, 0] In this final updated arr, find a position from where to return the list. This position (index) = 0 Return [1, 0, 0, 0] """
62519d85e72563c9dae3095431b0ff71f1162166
barackmaund1/Top-headlines
/tests/article_test.py
1,318
3.640625
4
import unittest from app.models import Article class ArticleTest(unittest.TestCase): ''' Test Class to test the behaviour of the Article class ''' def setUp(self): ''' Set up amethod that will run every test ''' self.new_article=Article("Gizmodo.com","Catie Keck", 'Travelex Reportedly Paid Ransomware Hackers 285 Bitcoin Worth', "Following a ransomware attack against foreign exchange company Travelex earlier this year, the company reportedly paid a hefty, multimillion-dollar sum to hackers in the form of hundreds of bitcoin. Read more...", "https://gizmodo.com/travelex-reportedly-paid-ransomware-hackers-285-bitcoin-1842782514", 'https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/y7yn0ztcocikqjpfsy9g.jpg', "2020-04-09T21:40:00Z",'Following a ransomware attack against foreign exchange company Travelex earlier this year, the company reportedly paid a hefty, multimillion-dollar sum to hackers in the form of hundreds of bitcoin.\r\nCiting a source familiar with the details of the transactio… [+2026 chars]') def test_instance(self): self.assertTrue(isinstance(self.new_article,Article)) if __name__ == '__main__': unittest.main()
51f94d2411c8fb418efb0b87c4af35e0fdb8ff57
watsonjj/aoc2020
/aoc2020/d02_password_philosophy/methods.py
864
3.59375
4
import re class Password: def __init__(self, line, old_policy=True): self.old_policy = old_policy pattern = r"(\d+)-(\d+) (\w): (.+)(?:\n?)" reg_exp = re.search(pattern, line) self.min = int(reg_exp.group(1)) self.max = int(reg_exp.group(2)) self.letter = reg_exp.group(3) self.password = reg_exp.group(4) def is_valid(self, old_policy=True): if old_policy: count = self.password.count(self.letter) return (count >= self.min) & (count <= self.max) else: first_letter = self.password[self.min-1] second_letter = self.password[self.max-1] return (first_letter == self.letter) ^ (second_letter == self.letter) def count_number_valid(passwords, old_policy=True): return sum([p.is_valid(old_policy) for p in passwords])
90854aca8e7a5e18c73af44432747a10f5e16f2e
baihaqi2193/daspro
/daspro.py
10,217
3.65625
4
## LIST ## LIBRARY INI BERISI DATABASE CODE UNTUK LIST ## LIBRARY INI DIBUAT DAN DIKUMPULKAN OLEH : ## MUHAMAD NUR BAIHAQI (INFORMATIKA UNDIP 2020) ## INI ADALAH LIBRARY FUNGSI PRIMITIF ## Konstruktor: def mklist(): return [] ## Basic Predicate # Mengecek List Kosong atau Bukan: def IsEmpty(L): if L == []: return True else: return False ## Utility # Inverse List: def Inverse(L): Ls = list(L) Ls.reverse() return Ls ## Selector # Mengambil Tail: def Tail(L): if not(IsEmpty(L)): return L[1:] # Mengambil Head: def Head(L): Ls = list(L) Ls.reverse() del Ls[0] Ls.reverse() return Ls # Mengambil Element Pertama: def FirstElmt(L): return L[0] # Mengambil Element Terakhir: def LastElmt(L): return FirstElmt(Inverse(L)) # Mengambil Element ke N dari List L: def ElmtKeN(N, L): if IsEmpty(L): return "List kosong" if Nb_Elmt(L) == 1: return L else: if N > Nb_Elmt(L): return "N tidak boleh melebihi jumlah element list" elif N == 1: return FirstElmt(L) else: return ElmtKeN(N-1, Tail(L)) ## Add Element ke List : # Add ke Awal List def Konso(e, L): Ls = list(L) Ls.insert(0,e) return Ls # Add ke Akhir List def Konsi(e, L): Ls = list(L) Ls.append(e) return Ls ## Counter # Menghitung Jumlah element list: def Nb_Elmt(L): if IsEmpty(L): return 0 else: return 1 + Nb_Elmt(Tail(L)) # Menghitung Jumlah element dari List L def Nb_ElmtX(X,L): if IsEmpty(L): return 0 else: if FirstElmt(L) == X: return 1 + Nb_ElmtX(X,Tail(L)) else: return 0 + Nb_ElmtX(X,Tail(L)) ## Advanced Predicate # Mengecek apakah saling inverse def IsInverse(La, Lb): if Inverse(La) == Lb: return True else: return False # Mengecek apakah n adalah member dari L def IsMember(n, L): if IsEmpty(L): return False else : if n == FirstElmt(L): return True else : return IsMember(n,Tail(L)) # Mengecek apakah X elemen ke N dari list L def IsXElmtKeN(X,N,L): if IsMember(X,L): if N == 1 : if X == FirstElmt(L): return True else: return False else: return IsXElmtKeN(X,N-1,Tail(L)) else: return False ## Operasi # Perkalian list dengan konstanta def KaliList(k,L): if L == []: return [] else: if k == 0 : return SetAllZero(L) elif k == 1: return L else: return Konso(k*FirstElmt(L),KaliList(k,Tail(L))) # Menjumlahakan semua element dari List: def SumList(L): if L == []: return 0 else: return FirstElmt(L) + SumList(Tail(L)) # Menjumlahkan semua elemen L tanpa X def SumListExceptX(x, L): if L == []: return 0 else: if x == FirstElmt(L): return 0 + SumListExceptX(x, Tail(L)) else: return FirstElmt(L) + SumListExceptX(x, Tail(L)) # Menghapus satu elemen dari L def Rember(e,L): if IsEmpty(L): return L else: if e == FirstElmt(L): return Tail(L) else: return Konso(FirstElmt(L),Rember(e,Tail(L))) # Menghapus semua elemen e dari L def MultiRember(e,L): if IsEmpty(L): return L else: if e == FirstElmt(L): return MultiRember(e,MultiRember(e,Tail(L))) else: return Konso(FirstElmt(L),MultiRember(e,Tail(L))) # Mengubah semua elemen e menjadi x dalam list L def SetElmtEtoX(e,X,L): if IsMember(e, L): if FirstElmt(L) == e: return Konso(X,SetElmtEtoX(e,X,Tail(L))) else: return Konso(FirstElmt(L),SetElmtEtoX(e,X,Tail(L))) else: return L # Mengubah elemen e ke 0 def SetElmtZero(e,L): if IsMember(e, L): if e == FirstElmt(L): return Konso(0,SetElmtZero(e,Tail(L))) else: return Konso(FirstElmt(L),SetElmtZero(e,Tail(L))) else: return L # Mengubah semua elemen list menjadi 0 def SetAllZero(L): if L == []: return [] else: return Konso(0,SetAllZero(Tail(L))) # Insert def Insert(x,L): if IsEmpty(L): return Konso(x,L) else: if x <= FirstElmt(L): return Konso(x, L) else: return Konso(FirstElmt(L),Insert(x,Tail(L))) ## SET ## LIBRARY INI BERISI DATABASE CODE UNTUK SET ## LIBRARY INI DIBUAT DAN DIKUMPULKAN OLEH : ## MUHAMAD NUR BAIHAQI (INFORMATIKA UNDIP 2020) ## INI ADALAH LIBRARY FUNGSI PRIMITIF ## Konstruktor: def MakeSet(L): if L == []: return [] else: if IsMember(FirstElmt(L),Tail(L)): return MakeSet(Tail(L)) else: return Konso(FirstElmt(L),MakeSet(Tail(L))) ## Predikat Dasar # Apakah L termasuk set: def IsSet(L): if L == []: return True else: if Nb_ElmtX(FirstElmt(L),L) > 1: return False else: return IsSet(Tail(L)) ## Advanced Predicate: # Mengecek apakah set H1 dan set H2 saling interseksi def IsIntersect(H1,H2): if IsSet(H1) and IsSet(H2): if (IsEmpty(H1) and not IsEmpty(H2)) or (IsEmpty(H2) and not IsEmpty(H1)): return False elif IsEmpty(H1) and IsEmpty(H2): return False else : if IsMember(FirstElmt(H1),H2): return True else: return IsMember(FirstElmt(Tail(H1)),H2) else: return "Bukan merupakan set" # Mengecek apakah set H1 adalah subset dari H2 def IsSubset(H1,H2): if H1 == []: return True else: if not (IsMember(FirstElmt(H1),H2)): return False else: return IsSubset(Tail(H1),H2) ## Selector: # Mencari elemen yang berinterseksi def MakeIntersect(H1,H2): if IsEmpty(H1) and IsEmpty(H2): return [] elif IsEmpty(H1) and not IsEmpty(H2): return [] elif IsEmpty(H2) and not IsEmpty(H1): return [] else: if IsMember(FirstElmt(H1),H2): return Konso(FirstElmt(H1),MakeIntersect(Tail(H1),H2)) else: return MakeIntersect(Tail(H1),H2) # Menggabungkan semua elemen set H1 dengan H2 def MakeUnion(H1,H2): if IsEmpty(H1): return H2 elif IsEmpty(H2): return H1 else: if not IsMember(FirstElmt(H1),H2): return Konso(FirstElmt(H1),MakeUnion(Tail(H1),H2)) else: return MakeUnion(Tail(H1),H2) # Mengurangi set H1 dengan H2 (Anggota H1 yang tidak ada di H2) def MakeMinus(H1,H2): if H1 == []: return [] elif H2 == []: return H1 else: if IsMember(FirstElmt(H1),H2): return MakeMinus(Tail(H1),H2) else: return Konso(FirstElmt(H1),MakeMinus(Tail(H1),H2)) # Apakah kedua set sama def IsEQSet(H1,H2): if IsSubset(H1,H2) and IsSubset(H2,H1): return True else: return False ## LIST OF LIST ## Basic Predicate # Apakah S adalah List of List def IsLoL(S): if S == []: return True else: if type(FirstElmt(S)) == list: return True else: return IsLoL(Tail(S)) # Mengecek apakah List of List kosong def IsEmptyLoL(S): return S == [] # Apakah atom def IsAtom(S): if type(S) != list: return True else: return False # Apakah List def IsList(S): return not (IsAtom(S)) # SELEKTOR # Elemen pertama list of list def FirstList(S): if not(IsEmptyLoL(S)): return S[0] # Elemen terakhir list of list def LastList(S): if not(IsEmptyLoL(S)): return FirstList(Inverse(S)) # Tail dari List of List def TailList(S): if not(IsEmptyLoL(S)): return S[1:] # Head dari list of list def HeadList(S): Ss = list(S) Ss.reverse() del Ss[0] Ss.reverse() return Ss def HeadList2(S): if not(IsEmptyLoL(S)): return S[:-1] # Apakah kedua List of List sama def IsEqS(S1,S2): if IsEmptyLoL(S1) and IsEmptyLoL(S2): return True elif IsEmptyLoL(S1) and not IsEmptyLoL(S2): return False elif not IsEmptyLoL(S1) and IsEmptyLoL(S2): return False else: if IsAtom(FirstList(S1))and IsAtom(FirstList(S2)): return FirstList(S1) == FirstList(S2) and IsEqS(TailList(S1),TailList(S2)) if IsList(FirstList(S1))and IsList(FirstList(S2)): return FirstList(S1) == FirstList(S2) and IsEqS(TailList(S1),TailList(S2)) else: return False # Insert list of list ke list of list lain def Konslo(S1,S2): Ls = list(list(S2)) Ls.insert(0,S1) return Ls ## MATRIX ## COUNTER # Menghitung Banyak Elemen dari suatu Matrix def NbEleX(X, L): if L == []: return 0 else: if IsAtom(FirstList(L)): if FirstList(L) == X: return 1 + NbEleX(X, Tail(L)) else: return 0 + NbEleX(X, Tail(L)) elif IsList(FirstList(L)): return Nb_ElmtX(X, FirstList(L)) + Nb_ElmtX(X, Tail(L)) # Mengalikan Matrix dengan suatu konstanta def KaliMatrix(k ,L): if IsEmpty(L): return [] else: if k == 0: return Konso(SetAllZero(FirstList(L)),KaliMatrix(k,TailList(L))) elif k == 1: return L else: return Konso(KaliList(k,FirstList(L)),KaliMatrix(k,Tail(L))) # Menghitung jumlah list of list / row dari suatu matrix def NbList(L): if L == []: return 0 else: if IsAtom(FirstList(L)): return 0 + NbList(Tail(L)) else: return 1 + NbList(Tail(L))
0633310d08effec2ab8debb0b10bc9588e659f81
gr4vytr0n/ml
/classification/applications/knn/dating_data/dating_data_test.py
1,803
3.53125
4
''' test dating dataset with knn algorithm ''' from numpy import array from sys import path from os import getcwd path.insert(0, getcwd() + '/utils/') path.insert(0, getcwd() + '/datasets/') path.insert(0, getcwd() + '/classification/knn/') from process_data import process_data from knn import classify def test(): ''' knn test of dating data ''' # import dataset, normalized dataset and class labels for dataset dset, normalizing, labeling = process_data('datingTestSet.txt') # normalized dataset, ranges, minimum values # and maximum values from dataset norm_dset, ranges, min_vals, max_vals = normalizing # label indices to match labels for sample in dataset # against class labels key and class labels key label_indices, labels_key = labeling # use 10 percent of training data as test data ho_ratio = 0.10 # m is number of samples in dataset m = norm_dset.shape[0] # number of test samples num_tests = int(m * ho_ratio) # loop over all test samples and compare known labels versus alogrithm # classification and print out error rate error_count = 0.0 for i in range(num_tests): # normalize test sample norm_test = (dset[i, :] - min_vals) / ranges # classify test sample classification = classify(norm_test, norm_dset[num_tests:m, :], label_indices[num_tests:], 3) print('classifier answer: {}, real answer: {}'.format( labels_key[classification], labels_key[label_indices[i]])) # compare known label to classifier label if labels_key[classification] != labels_key[label_indices[i]]: error_count += 1.0 print('total error rate: {}'.format(error_count / float(num_tests)))
1da616f8036e98d90d9706bef6e8077be31f52a5
Juldam/ejerciciosPython2DAM
/Clases/ejc8.py
4,905
3.984375
4
''' En este ejercicio realizará un programa en Python que asigne e imprima en pantalla las asignaturas, profesores y estudiantes de una pequeña "universidad". Defina: - Clase superior Miembro. +Con atributos nombre, edad y dni. - Dos clases que heredan de ella: Profesor y Estudiante. +Profesor tiene, adicionalmente: *Atributo número de registro *Atributo asignaturas imparte: Lista, inicialmente vacía, con la relación de asignaturas que imparte el profesor. *Método añade dociencia. Añade un elemento a la lista de asignaturas que imparte el profesor. *Método imprime docencia. Imprime la lista de asignaturas que imparte un profesor, junto con la relación de estudiantes matriculados que hay en cada una de ellas. +Estudiante tiene, adicionalmente: *Atributo número de estudiante - Clase Asignatura: +Atributos nombre y código +Atributo estudiantes: Lista, inicialmente vacía, con la relación de estudiantes matriculados en ella. +Método añade estudiante: Añade un estudiante matrículado a la lista de la asignatura. +Método imprime listado: Imprime la lista de estudiantes matriculados en una asignatura. Realizar un programa que: - Cree todos los objetos necesarios - Asigne los valores adecuados a sus atributos - Imprima en pantalla las asignaturas que imparte cada profesor junto con la relación de estudiantes matriculados en ellas. - Opcional: Realice una función adicional (ojo, no le pedimos un método) que reciba como parámetro el nombre de un estudiante (por ejemplo "Jaimito", pero no el objeto jaimito) e imprima las asignaturas en que éste está matriculado. Haga llamadas a esta función para comprobar su funcionamiento. Ayuda: Para simplificar el código puede serle de utilidad crear una lista con todas las asignaturas (lista objetos). ''' listaAsignaturas=[] listaEstudiantes=[] listaProfesores=[] class Miembro(object): def __init__(self, nombre, edad, dni): self.nombre=nombre self.edad=edad self.dni=dni class Profesor(Miembro): def __init__(self, nombre, edad, dni, numregistro): super().__init__(nombre, edad, dni) self.numregistro=numregistro self.asignaturas=[] listaProfesores.append(self) def addDocencia(self, nomAsignatura): self.asignaturas.append(nomAsignatura) def imprimeDocencia(self): for i in self.asignaturas: print("\nAsignatura "+str(i.nomAsig)+":") i.imprimirListado() class Estudiante(Miembro): def __init__(self, nombre, edad, dni, numestudiante): super().__init__(nombre, edad, dni) self.numestudiante=numestudiante class Asignatura(object): def __init__(self, nomAsig, codAsig): self.nomAsig=nomAsig self.codAsig=codAsig self.estudiantesAsig=[] listaAsignaturas.append(self) def addEstudiante(self, nombreEstudiante): self.estudiantesAsig.append(nombreEstudiante)#Aquí le estoy pasando al array un objeto estudiante def imprimirListado(self): print("Los estudiantes de la asignatura "+str(self.nomAsig)+" son:") for i in self.estudiantesAsig: print(str(i.nombre)) def asignaturasEstudiante(nom): print("Las asignaturas en las que está matriculado "+str(nom)+" son: ") for i in listaAsignaturas: for j in i.estudiantesAsig: if j.nombre.lower()==nom.lower(): print("- "+i.nomAsig) luis=Profesor("Luis", 50, "34567", 5001) pepe=Profesor("Pepe", 37, "65432", 5010) jorgito=Estudiante("Jorgito", 20, "56678", 1001) juanito=Estudiante("Juanito", 19, "44444", 1002) jaimito=Estudiante("Jaimito", 19, "22334", 1005) matematicas=Asignatura("Matemáticas", 5) fisica=Asignatura("Física", 7) latin=Asignatura("Latín", 13) historia=Asignatura("Historia", 19) filosofia=Asignatura("Filosofía", 36) luis.addDocencia(matematicas) luis.addDocencia(fisica) pepe.addDocencia(latin) pepe.addDocencia(historia) pepe.addDocencia(filosofia) matematicas.addEstudiante(jorgito) fisica.addEstudiante(juanito) fisica.addEstudiante(jaimito) latin.addEstudiante(jorgito) latin.addEstudiante(jaimito) historia.addEstudiante(juanito) historia.addEstudiante(jaimito) filosofia.addEstudiante(jaimito) print("Bienvenido a la Universidad diminuta.") while(True): print("Escoja una opción:") print("a) Ver asignaturas que imparte cada profesor") print("b) Ver asignaturas por estudiante") print("c) Salir") resp=str(input("")) if resp=="a": for i in listaProfesores: print(i.imprimeDocencia()) elif resp=="b": nom=str(input("Introduzca el nombre del estudiante: ")) asignaturasEstudiante(nom) elif resp=="c": break else: print("Debe escoger una respuesta válida. Inténtelo de nuevo.")
17905cb8ebffb6430c58338c8e833ca3b2876125
Nickruti/HackerRank-Python-Problems-
/lists.py
837
3.671875
4
if __name__ == '__main__': N = int(input()) inputlist = [] outputlist = [] for a in range(0, N): inputlist.append(input().split()) if "insert" in inputlist[a][0]: i = int(inputlist[a][1]) e = int(inputlist[a][2]) outputlist.insert(i,e) elif "print" in inputlist[a][0]: print(outputlist) elif "remove" in inputlist[a][0]: x = int(inputlist[a][1]) outputlist.remove(x) elif "append" in inputlist[a][0]: x = int(inputlist[a][1]) outputlist.append(x) elif "sort" in inputlist[a][0]: outputlist.sort() elif "pop" in inputlist[a][0]: outputlist.pop() elif "reverse" in inputlist[a][0]: outputlist.reverse()
5a33d7e8ab0a013deaaabe0a7e4f100a068db94e
oneshan/Leetcode
/todo/636.exclusive-time-of-functions.py
2,156
3.609375
4
# # [636] Exclusive Time of Functions # # https://leetcode.com/problems/exclusive-time-of-functions # # Medium (39.82%) # Total Accepted: # Total Submissions: # Testcase Example: '2\n["0:start:0","1:start:2","1:end:5","0:end:6"]' # # Given the running logs of n functions that are executed in a nonpreemptive # single threaded CPU, find the exclusive time of these functions. # # Each function has a unique id, start from 0 to n-1. A function may be called # recursively or by another function. # # A log is a string has this format : function_id:start_or_end:timestamp. For # example, "0:start:0" means function 0 starts from the very beginning of time # 0. "0:end:0" means function 0 ends to the very end of time 0. # # Exclusive time of a function is defined as the time spent within this # function, the time spent by calling other functions should not be considered # as this function's exclusive time. You should return the exclusive time of # each function sorted by their function id. # # Example 1: # # Input: # n = 2 # logs = # ["0:start:0", # ⁠"1:start:2", # ⁠"1:end:5", # ⁠"0:end:6"] # Output:[3, 4] # Explanation: # Function 0 starts at time 0, then it executes 2 units of time and reaches the # end of time 1. # Now function 0 calls function 1, function 1 starts at time 2, executes 4 # units of time and end at time 5. # Function 0 is running again at time 6, and also end at the time 6, thus # executes 1 unit of time. # So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally # execute 4 units of time. # # # # Note: # # Input logs will be sorted by timestamp, NOT log id. # Your output should be sorted by function id, which means the 0th element of # your output corresponds to the exclusive time of function 0. # Two functions won't start or end at the same time. # Functions could be called recursively, and will always end. # 1 <= n <= 100 # # # class Solution(object): def exclusiveTime(self, n, logs): """ :type n: int :type logs: List[str] :rtype: List[int] """
0caec53331d757772aac3f795373ef6d8930f458
Run0812/Algorithm-Learning
/to_offer/60_DicesProbability.py
830
3.859375
4
""" 问题60:n个骰子的点数 题目:把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。 输入n,打印出s的所有可能的值出现的概率。 """ def dices_probability(n): """ :param n:number of dices :return: dict of possible value """ times = {1:1, 2:1, 3:1, 4:1, 5:1, 6:1} for i in range(2,n+1): cache = {} for val in range(1 * i, 6 * i + 1): cache[val] = 0 j = 1 while j <= 6: if (val - j) in times: cache[val] += times[val - j] j += 1 times = cache for val in times: from fractions import Fraction times[val] = Fraction(times[val], 6 ** n) # times[val] = times[val] / 6 ** n return times print(dices_probability(11))