blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8389c2391d5ea11090be1a8e397cc81851b6c7ad
Cold-Front-520/valgundriy
/domashka3-zd1.py
710
3.765625
4
x = [] razm = int(input("введите количество элементов и сами значения ")) for i in range(razm): x.append(int(input())) print("это твой массив короче: ", x, "теперь введи циферку - скажу где она") f = int(input()) for i in range(razm): if f == x[i]: slot = i + 1 print("эта циферка стоит на ", slot, "слоте") # я подумал что для юзера будет полезнее видеть не конкретно "индекс" # а типо номер в списке. так будет типо понятнее для юзера. поэтому сделал i+1
ba4ffc484817dc4c4237ced6ccda6c4e834134b4
vp5dt/LAB_python
/LAB1/tripletssumtozero.py
618
3.984375
4
values=input("Enter the list of numbers seperated by space: ") values= values.split(" ") if values[(len(values)-1)]=='': values.remove('') print("Given List:") print(values) def findtriplets(arr, n): flag = True for i in range(0, n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): if (int(arr[i]) + int(arr[j]) + int(arr[k]) == 0): tup=(int(arr[i]),int(arr[j]),int(arr[k])) print(tup) flag = True if flag==False: print("No Such Triplet exist") findtriplets(values,len(values))
afa7c2136d62d34e484b913bdcda4d93ae868ff3
JFernandez696/Edge-Detection-Techniques-Sobel-vs.-Canny
/canny_with_OpenCV.py
715
3.546875
4
import cv2 import numpy as np import grayscale import blur_image def canny_CV2(image,low_threshold, high_Threshold): edges = cv2.Canny(image,low_threshold, high_Threshold) return edges if __name__ == "__main__": im_location = '/home/lina/Desktop/' file_name = 'dragon.jpeg' # read the image image = cv2.imread(im_location+file_name) # convert the image into grayscale gray_image = grayscale.BGR2GRAY(image) # blur the gray image blurred_image = blur_image.GaussianBlur(gray_image) # apply canny edges = canny_CV2(blurred_image.astype(np.uint8), 100, 200) # display the result cv2.imshow('M',np.uint8(edges)) cv2.waitKey(0)
04ae7c06f98e112a0e7fb4f4f1319acb022d8b5f
LEEHOONY/my-project
/week01/company.py
733
3.859375
4
# 회사 조직도 만들기 # 사람 클래스를 만든다(사람의 기본요소는 이름, 나이, 성별로 한다) # 직장 동료 클래스를 사람 클래스를 이용하여 만든다.(사람 기본 요소 외 직급을 추가한다.) ## Human class class Human: company = "Python" def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex human1 = Human("홍길동", "23", "M") human2 = Human("장희빈", "21", "F") human3 = Human("임꺽정", "32", "M") print(human2.name) print(human3.sex) ## Colleague class class Colleague(Human): designation = "부장" colleague = Colleague("이순신", "40", "M") print(colleague.name) print(colleague.designation)
6b52fddb553cb895c2bebe58a58e99884da8e956
duanht-tester/www_python
/实例/xx_0408_阿姆斯特朗数.py
4,671
3.921875
4
# -*- encoding: UTF-8 -*- # __author__ = 'lenovo' # 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 # 例如1^3 + 5^3 + 3^3 = 153。 # 1000以内的阿姆斯特朗数: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407。 # 以下代码用于检测用户输入的数字是否为阿姆斯特朗数: # Python 检测用户输入的数字是否为阿姆斯特朗数 # 获取用户输入的数字 # num = int(input("请输入一个数字: ")) # # # 初始化变量 sum # sum = 0 # # 指数 # n = len(str(num)) # # # 检测 # temp = num # while temp > 0: # digit = temp % 10 # sum += digit ** n # temp //= 10 # # 输出结果 # if num == sum: # print(num, "是阿姆斯特朗数") # else: # print(num, "不是阿姆斯特朗数") # 获取指定期间内的阿姆斯特朗数 # lower = int(input("最小值: ")) # upper = int(input("最大值: ")) # # for num in range(lower, upper + 1): # # 初始化 sum # sum = 0 # # 指数 # n = len(str(num)) # # 检测 # temp = num # while temp > 0: # digit = temp % 10 # sum += digit ** n # temp //= 10 # # if num == sum: # print(num) # 获取小于指定数字的阿姆斯特朗数 # num = int(input("pleace input a number: ")) # arr = [0,0,0,0,0] # print(num) # for k in range(1, num): # n = len(str(k)) # m = n # i = 0 # sum = 0 # while m > 0: # m -= 1 # arr[i] = int(k / 10 ** m) % 10 # sum += arr[i] ** n # i += 1 # if k == sum: # print(k, end=',') # 以下代码用于检测用户输入的数字是否为阿姆斯特朗数 # import math # # x = int(input('请输入一个正整数:')) # x1 = x # n = len(str(x)) # p = 0 # for i in range(1, n+1): # y = math.floor(x//pow(10, n-i)) # print(y, end=',') # m = pow(y, n) # 也可以表达为: m=y**n # p = (m+p) # x = (x % pow(10, n-i)) # print(p) # if p == x1: # print('输入的数字 %d 是一个阿姆斯特朗数'%x1) # elif p != x1: # print('输入的数字 %d 不是一个阿姆斯特朗数'%x1) # 获取指定期间内的阿姆斯特朗数 # lower = int(input("Please input a number: ")) # upper = int(input("Please input a number: ")) # sum = 0 # for num in range(lower, upper): # l = len(str(num)) # for n in str(num): # sum = (sum+int(n)**l) # if num == sum: # print(num) # sum = 0 # 计算阿姆斯特朗数 # count = 0 # num = int(input('请输入一个正整数:')) # 输入值并强制类型转换 # len = len(str(num)) # 获取输入数字位数 # list_num = list(str(num)) # 将数字转化为列表 # for i in list_num: # 将列表中的每一个元素以该元素的lenth次幂累加至count # i = int(i) # i **= len # count += i # # if count == num: # 判断count与输入的数字是否相等,若相等则为阿姆斯特朗数 # print('是阿姆斯特朗数') # else: # print('不是阿姆斯特朗数') # 使用 lambda 表达式: # def is_armstrong(n): # s = sum(map(lambda x: eval(x)**len(str(n)), str(n))) # return s == n # # b = [] # for i in range(1000): # if is_armstrong(i): # b.append(i) # # print(b) # 使用 list 的映射解析来进一步简化代码: # def is_armstrong(n): # return n == sum([eval(i)**len(str(n)) for i in str(n)]) # # b = [i for i in range(1000) if is_armstrong(i)] # print(b) # 检查输入是否合法: # while True: # # try: # lower = int(input("最小值: ")) # upper = int(input("最大值: ")) # except ValueError: # print("非法输入") # continue # if lower > upper: # print("请检查输入大小") # continue # for num in range(lower, upper): # sum = 0 # n = len(str(num)) # temp = num # while temp > 0: # digit = temp %10 # sum += digit ** n # temp //= 10 # if num == sum: # print(num, end=' ') # break # 输出指定区间内的所有阿姆斯特朗数 # try: # lower = int(input("最小值:")) # upper = int(input("最大值:")) # except ValueError: # print("所输入内容非整数!") # exit(1) # # for num in range(lower, upper+1): # sum = 0 # n = len(str(num)) # for i in str(num): # sum += int(i) ** n # if sum == num: # print(num, end=' ') # 一个推导式搞定一个3位数的算法 # y = [(x//100)**3+((x//10) % 10)**3+(x % 10)**3 for x in range(100, 1000) # if (x//100)**3+((x//10) % 10)**3+(x % 10)**3 == x] # # print(y) print((123//100))
5fad1f31e6e4f5de653c6313fad925d48307d99a
Agaonm/SimplePassManager
/Database.py
1,022
3.8125
4
import pandas as pd ### Check if database exists ### def checkdb(): # If database Exists, Open and convert to Pandas DataFrame try: _forgopassdf = pd.read_csv('database.csv') #_forgopassdf = pd.DataFrame() print(_forgopassdf) return _forgopassdf # If database doesn't exist, create new dataframe to be saved later except FileNotFoundError: # Setup database _data = {'Website':[], 'Username':[], 'Password':[]} _forgopassdf = pd.DataFrame(_data) _forgopassdf.to_csv('database.csv', index=False) ### Appending new information to database ### def appenddb(domain,username,password): # Get Dataframe _forgopassdf = checkdb() # Add new domain,user,pass to dataframe _new = {'Website':domain,'Username':username,'Password':password} _forgopassdf = _forgopassdf.append(_new, ignore_index=True) # Save updated dataframe to csv file _forgopassdf.to_csv('database.csv', index=False)
b0f503154fd86225d25d0e8aba37f76ff0b5a07b
Nutpapat/Python_Lab
/KEYS/Sequence XXX.py
788
3.640625
4
""" PSIT Midterm Examination (Rerun) - Sequence XXX Teerapat Kraisrisirikul (60070183) """ def main(size, num): """ Main function """ #Spacing variables side = 0 center = size-4 #Upper borders print(("*" * size + " ") * num) #Upper lines for _ in range((size-3)//2): print(("*" + " "*side + "*" + " "*center + "*" + " "*side + "* ") * num) side += 1 center -= 2 #Middle line if size > 1: print(("*" + " "*side + "*" + " "*side + "* ") * num) #Lower lines for _ in range((size-3)//2): side -= 1 center += 2 print(("*" + " "*side + "*" + " "*center + "*" + " "*side + "* ") * num) #Lower borders if size > 1: print(("*" * size + " ") * num) main(int(input()), int(input()))
2c61a8ee59cdb6637d4076de860cc20c02c12323
liuyuzhou/ai_pre_sourcecode
/chapter3/average_1.py
485
3.78125
4
import numpy as np num_np = np.array([1, 2, 3, 4]) print('初始数组:{}'.format(num_np)) print('调用 average() 函数:{}'.format(np.average(num_np))) # 不指定权重时相当于 mean 函数 wts = np.array([4, 3, 2, 1]) print('再次调用 average() 函数:{}'.format(np.average(num_np, weights=wts))) # 如果 returned 参数设为 true,则返回权重的和 print('权重的和:{}'.format(np.average([1, 2, 3, 4], weights=[4, 3, 2, 1], returned=True)))
c116928b27a7d41abf2543c2c40a94aeaa21ec8e
ReinaKousaka/core
/src/data_cleaning/friends_neighborhood.py
1,845
3.640625
4
class FriendsNeighborhood(): def __init__(self, user_neighbourhood_getter, user_neighbourhood_setter, user_wordcount_getter): self.user_neighbourhood_getter = user_neighbourhood_getter self.user_neighbourhood_setter = user_neighbourhood_setter self.user_wordcount_getter = user_wordcount_getter def clean_by_friends(self, base_user, threshold): user_friends, all_users = self.user_neighbourhood_getter.get_user_neighbourhood(base_user) friends_list = [] for item in all_users: user = item if user in user_friends and len(all_users[user]) > threshold: friends_list.append(user) print("original friends number is: ", len(user_friends)) print("remaining friends number is: ", len(friends_list)) remaining_neighborhood = {} for users in friends_list: remaining_neighborhood[users] = all_users[users] self.user_neighbourhood_setter.store_user_neighbourhood(remaining_neighborhood) def clean_by_tweets(self, base_user, threshold): user_friends, all_users = self.user_neighbourhood_getter.get_user_neighbourhood(base_user) user_word_count = self.user_neighbourhood_getter.get_user_wordcount() friends_list = [] for item in all_users: user = item if user in user_friends and sum(user_word_count[user].values()) > 100: friends_list.append(user) print("original friends number is: ", len(user_friends)) print("remaining friends number is: ", len(friends_list)) remaining_neighborhood = {} for users in friends_list: remaining_neighborhood[users] = all_users[users] self.user_neighbourhood_setter.store_user_neighbourhood(remaining_neighborhood)
150586f9351584798807aacffdcda9ca45258829
Bbowen100/crypt
/crypt.py
4,054
3.796875
4
'''Crypt This file contains encryption & decryption Functions. This will be imported into any encryption related programs. REQ: for simplicity I have refined this algorithm to members of the alphabet ie. special characters and numbers will not be decrypted accurately ''' import random global __start__ __start__ = ord('a') global __end__ __end__ = ord('z') def encrypt(string): '''(str)->(dict) The encrypt function takes a string a returns the randomly generated key with the encrypted text in an associative array. >>> encrypt('a') {21: 'v'} >>> encrypt('whatever') {17: 'oyrlvnvj'} >>> encrypt('What is life') {23: 'ufxr gq jgdc'} ''' _key = 0 afterstr = '' __afterdict__= {} b4str = str(string).lower() # first things first gotta get a key # note 26 letters in the alphabet & 10 ints + special chars # note to self: remember ord() and char() _key = random.randint(1, 25) '''the key will serve as a method to varify the correct reciever and to encrypt the cyphertext''' # make a list of the elements in the cyphertext b4lst = list(b4str) #make list of ascii numbers in string b4lst2 = [] for i in b4lst: if(i == ' '): b4lst2.append(' ') else: b4lst2.append(ord(i)) # make the list of new ascii values i = 0 afterlst = [] while(i < len(b4lst2)): if(b4lst2[i] != ' '): if((b4lst2[i] + _key) >= __end__): #if it exceeds the letter range diff = (b4lst2[i] + _key) - __end__ afterlst.append(diff + __start__) i+=1 elif((b4lst2[i] + _key) <= __end__): #if it is within the letter range afterlst.append((b4lst2[i] + _key)) i+=1 else: afterlst.append(' ') i+=1 # now we have to change the new ascii values back into characters afterlst2 = [] for i in afterlst: if(i == ' '): afterlst2.append(' ') else: afterlst2.append(chr(i)) # gotta stringyfy afterlst2 afterstr = stringyfy(afterlst2) # gotta remember the key and the encrypted text so we can decrypt __afterdict__ = {_key: afterstr} return __afterdict__ def decrypt(dic): '''(dict)-> (str) this function will take __afterdict__ and reverse the encrytion function to produce the origianl cypher text with the help of the key of course! >>> decrypt({25: 'z'}) 'a' >>> decrypt({17: 'oyrlvnvj'}) 'whatever' >>> decrypt(encrypt('What is life')) 'What is life' ''' # remember dict.keys() & dict.vaules() # get the key & the encrypted txt keys = list(dic.keys()) key = int(keys[0]) cryptxt = dic.get(key) # apply decryption algorithm #make a list of decrypted ascii values for cyphertxt numtxt = [] for i in list(cryptxt): if(i == ' '): numtxt.append(' ') # special case elif((ord(str(i)) - key) < __start__): diff1 = ord(str(i)) - __start__ diff2 = key - diff1 final = __end__ - diff2 numtxt.append(final) else: numtxt.append(ord(str(i)) - key) #make decrpyt list dcryptlst = [] for i in numtxt: if(i == ' '): dcryptlst.append(' ') else: dcryptlst.append(chr(i)) #make it a astring final_string = stringyfy(dcryptlst) return final_string #-----------------------------------------------------------------------------# def stringyfy(lst): '''(list) -> string when a list is imuted it takes all the elements and concatenates them to make a string. >>> stringyfy([1,2,3,4]) '1234' >>> stringyfy(['me',' ','is',' ','so',' ','fine']) 'me is so fine' REQ: integers, floats, strings and characters ONLY! ''' #in retrospect not the longest of codes :) nstring = '' for i in lst: nstring = nstring + str(i) return nstring
b60f768088e83aca193e6d46b40672169ed0bda7
4nickpick/assembler-3000
/lib/util.py
9,819
3.703125
4
# # # Util # This module contains many functions and objects reused throughout the software # # import sys # My Hash Function # Produces a hash of a string, based on a particular hash table size # # input_string - string to create hash value for # hash_table_size - size of hash table, required to create a hash value that can fit into table def my_hash(input_string, hash_table_size): output = 0 for char in input_string: output += ord(char) return output % hash_table_size # Lookup Operation Function # Returns a whole Operation object based on a mneumonic # # mneumonic - the label of the operation, used to define it def lookup_operation(mneumonic): if len(Operation.operation_table) <= 0: Operation.load_operation_table() if mneumonic in Operation.operation_table.keys(): return Operation.operation_table[mneumonic] # Lookup Register Function # Returns the address of a register, given the register's name # # register - the label of the register to receive the address of def lookup_register(register): if register == 'A': return '0' elif register == 'X': return '1' elif register == 'L': return '2' elif register == 'B': return '3' elif register == 'S': return '4' elif register == 'T': return '5' elif register == 'F': return '6' elif register == 'PC': return '8' elif register == 'SW': return '9' else: return str(int(register)-1) # Operation class # The Operation class defines the structure of a SIC/XE operation, providing the necessary # details such as formats and opcode # # Formats are stored as lists, providing some operations can have one of two formats (typically 3/4) # class Operation: operation_table = dict() def __init__(self, name, format_list, opcode): self.name = name self.format_list = format_list self.opcode = opcode # Load Operation Table Function # loads all Operations into memory for lookup # @staticmethod def load_operation_table(): # typical operations with assembled code Operation.operation_table['ADD'] = (Operation('ADD', [3, 4], '18')) Operation.operation_table['ADDF'] = (Operation('ADDF', [3, 4], '58')) Operation.operation_table['ADDR'] = (Operation('ADDR', [2], '90')) Operation.operation_table['AND'] = (Operation('AND', [3, 4], '40')) Operation.operation_table['CLEAR'] = (Operation('CLEAR', [2], 'B4')) Operation.operation_table['COMP'] = (Operation('COMP', [3, 4], '28')) Operation.operation_table['COMPF'] = (Operation('COMPF', [3, 4], '88')) Operation.operation_table['COMPR'] = (Operation('COMPR', [2], 'A0')) Operation.operation_table['DIV'] = (Operation('DIV', [3, 4], '24')) Operation.operation_table['DIVF'] = (Operation('DIVF', [3, 4], '64')) Operation.operation_table['DIVR'] = (Operation('DIVR', [2], '9C')) Operation.operation_table['FIX'] = (Operation('FIX', [1], 'C4')) Operation.operation_table['FLOAT'] = (Operation('FLOAT', [1], 'C0')) Operation.operation_table['HIO'] = (Operation('HIO', [1], 'F4')) Operation.operation_table['J'] = (Operation('J', [3, 4], '3C')) Operation.operation_table['JEQ'] = (Operation('JEQ', [3, 4], '30')) Operation.operation_table['JGT'] = (Operation('JGT', [3, 4], '34')) Operation.operation_table['JLT'] = (Operation('JLT', [3, 4], '38')) Operation.operation_table['JSUB'] = (Operation('JSUB', [3, 4], '48')) Operation.operation_table['LDA'] = (Operation('LDA', [3, 4], '00')) Operation.operation_table['LDB'] = (Operation('LDB', [3, 4], '68')) Operation.operation_table['LDCH'] = (Operation('LDCH', [3, 4], '50')) Operation.operation_table['LDF'] = (Operation('LDL', [3, 4], '70')) Operation.operation_table['LDL'] = (Operation('LDL', [3, 4], '08')) Operation.operation_table['LDS'] = (Operation('LDS', [3, 4], '6C')) Operation.operation_table['LDT'] = (Operation('LDT', [3, 4], '74')) Operation.operation_table['LDX'] = (Operation('LDX', [3, 4], '04')) Operation.operation_table['LPS'] = (Operation('LPS', [3, 4], 'D0')) Operation.operation_table['MUL'] = (Operation('MUL', [3, 4], '20')) Operation.operation_table['MULF'] = (Operation('MULF', [3, 4], '60')) Operation.operation_table['MULR'] = (Operation('MULR', [2], '98')) Operation.operation_table['NORM'] = (Operation('NORM', [1], 'C8')) Operation.operation_table['OR'] = (Operation('OR', [3, 4], '44')) Operation.operation_table['RD'] = (Operation('RD', [3, 4], 'D8')) Operation.operation_table['RMO'] = (Operation('RMO', [2], 'AC')) Operation.operation_table['RSUB'] = (Operation('RSUB', [3, 4], '4C')) Operation.operation_table['SHIFTL'] = (Operation('SHIFTL', [2], 'A4')) Operation.operation_table['SHIFTR'] = (Operation('SHIFTR', [2], 'A8')) Operation.operation_table['SIO'] = (Operation('SIO', [1], 'F0')) Operation.operation_table['SSK'] = (Operation('SSK', [3, 4], 'EC')) Operation.operation_table['STA'] = (Operation('STA', [3, 4], '0C')) Operation.operation_table['STB'] = (Operation('STB', [3, 4], '78')) Operation.operation_table['STCH'] = (Operation('STCH', [3, 4], '54')) Operation.operation_table['STF'] = (Operation('STF', [3, 4], '80')) Operation.operation_table['STI'] = (Operation('STI', [3, 4], 'D4')) Operation.operation_table['STL'] = (Operation('STL', [3, 4], '14')) Operation.operation_table['STS'] = (Operation('STS', [3, 4], '7C')) Operation.operation_table['STSW'] = (Operation('STSW', [3, 4], 'E8')) Operation.operation_table['STT'] = (Operation('STT', [3, 4], '84')) Operation.operation_table['STX'] = (Operation('STX', [3, 4], '10')) Operation.operation_table['SUB'] = (Operation('SUB', [3, 4], '1C')) Operation.operation_table['SUBF'] = (Operation('SUBF', [3, 4], '5C')) Operation.operation_table['SUBR'] = (Operation('SUBR', [2], '94')) Operation.operation_table['TD'] = (Operation('TD', [3, 4], 'E0')) Operation.operation_table['TIO'] = (Operation('TIO', [1], 'F8')) Operation.operation_table['TIX'] = (Operation('TIX', [3, 4], '2C')) Operation.operation_table['TIXR'] = (Operation('TIXR', [2], 'B8')) Operation.operation_table['WD'] = (Operation('WD', [3, 4], 'DC')) # operations with assembled code but no opcodes Operation.operation_table['BYTE'] = (Operation('BYTE', [], 'FF')) Operation.operation_table['WORD'] = (Operation('WORD', [3], 'FF')) Operation.operation_table['RESW'] = (Operation('RESW', [], 'FF')) Operation.operation_table['RESB'] = (Operation('RESB', [], 'FF')) # operations with no assembled codes Operation.operation_table['START'] = (Operation('START', [], None)) Operation.operation_table['END'] = (Operation('END', [], None)) Operation.operation_table['BASE'] = (Operation('BASE', [], None)) Operation.operation_table['NOBASE'] = (Operation('NOBASE', [], None)) Operation.operation_table['LTORG'] = (Operation('LTORG', [], None)) def __str__(self): return self.name + " " + str(self.opcode) + "\n" # Error # Print Error Message to Screen # # message - message to print to screen # do_exit - if set, error will end program. Defaults to False def error(message, do_exit=False): message = "ERROR " + message if do_exit: sys.exit(message) else: print(message) # Add .lst Record Function # adds a line item to our .lst file # # line_id - line number in the lst record # location - the memory location of the operation's final object code # source - the initial source which the line item was generated # object_code - the assembled object code for the instruction # meta - list which includes various information about the line item useful for assembling the object code in Pass 2 # lst - list to add the record to def add_lst_record(line_id, location, object_code, source, meta, lst): lst.append({ 'Line ID': str(line_id).zfill(3), 'Location': str(location[2:]).zfill(5).upper(), 'Source': str(source), 'Object Code': str(object_code), 'Meta': meta }) # Add .lst Error Function # adds an error to our .lst file # # line_id - line number in the lst record, will match the Line ID in order to pair error with line item # message - error message to write to lst file # lst - list to add the record to # inject - an optional position(integer) to inject the error message into the lst file, useful during Pass 2 def add_lst_error(line_id, message, lst, inject=False): record = { 'Line ID': str(line_id).zfill(3), 'Error': str(message) } # If a line has an error, scrap any object code generated for it error_found = False for lst_record in lst: if lst_record['Line ID'] == line_id: if 'Error' not in lst_record: lst_record['Object Code'] = ' ' if not inject: lst.append(record) else: lst.insert(inject, record) # Hexized Function # Formats an integer into a proper hex value # # Currently only supports Hex formats of size 3 and 6 # # operand - integer to convert to Hex-formatted String # size - final size of Hex-formatted String def hexized(operand, size): if size == 3: format_string = "%03x" return format_string % (int(operand) & 0xfff) if size == 6: format_string = "%06x" return format_string % (int(operand) & 0xffffff)
faef80fe8ad837c5be2c6637b260b28269c54655
MrShafay/MarketingStack
/Sentence_split.py
210
3.75
4
def split(): a = input("Copy text and paste it, then press ENTER ") b = a.split() print(b) split() # If you Join def join(): b = split() join2 = ' '.join(b) print(join2) join()
c483a96ce074ba181e6757a427eed28e5d664bee
Abhinav-Bala/ICS3U
/problem_set_6/name_bank.py
9,166
4.71875
5
# Abhinav Balasubramanian # March 31, 2021 # ICS3UO-C # This program will ask the user to input names and then store them in a list. # Then the user will be presented with a menu of actions to perform including: displaying # all the names, editing, adding, or removing a name. # this functions prints the main menu def printMainMenu(): print(''' ============================================================== Here are the various actions you can perform: 1) Display all the names currently stored in the bank 2) Edit an existing name in the bank 3) Add a new name to the bank 4) Remove an existing name from the bank 0) Exit the program To select an action, enter the corresponding number. For example, to display all the names, you would enter '1'. ============================================================== ''') # this function prints the display menu def printDisplayMenu(): print(''' Here are the various ways to display the names: 1) The order it was entered in 2) Alphabetical by first name 3) Reverse alphabetical by first name To select an action, enter the corresponding number. For example, to display the names in alphabetical order, you would enter '1'. To return to the main menu enter '0' ''') # this function gets a valid initial list size from the user def getListSize(): while True: # loop until a valid input is given try: size = int(input("Enter the initial list size: ")) # tries to get input and cast as int except ValueError: # catches value error print("Invalid input. Enter an integer this time") # prints error message continue if size < 1: # checks if size is less than 1 print("Invalid input. Enter an integer greater than or equal to 1.") # prints error message continue else: return size # returns valid size # this function will get the initial list from the user def getInitialList(list_size): # takes a size as parameter for counter in range(1, list_size + 1): # loops through until all names are given while True: # loops until a valid input is given first_name = input("Please enter the first name of person #" + str(counter) + ": ") # gets user input for first name last_name = input("Please enter the last name of person #" + str(counter) + ": ") # gets user input for last name if first_name_list.count(first_name) > 0 and last_name_list.count(last_name) > 0: # checks if name is already in the list print("Sorry, looks like this name is already in the bank") # prints error message continue elif first_name.isalpha() != True or last_name.isalpha() != True: # checks if the name contains invalid characters print("Invalid input. Names can only have letters of the alphabet.") # prints error messagte else: first_name_list.append(first_name) # adds first name to list last_name_list.append(last_name) # adds last name to list break # exits the loop # this function gets a valid action from the user def getUserAction(min, max): # takes min and max values as parameters while True: # while loop to keep asking for input until user provides a valid action try: # error handling # gets user input and assigns action = int(input("Enter an integer for the corresponding action: ")) except ValueError: # catches value error # prints error message print("Inavlid input. Enter a valid integer this time.") continue if(action >= min and action <= max): # checks if the input is within the valid range return action else: # prints error message print(f"Invalid action. Enter an option between {min} and {max}.") # this function displays the current names in the bank def displayNameBank(): print("==============================================================") print("Here are all the names in the name bank:\n") for index in range(len(first_name_list)): print( "("+ str(index) + ") " + str(first_name_list[index]) + " " + str(last_name_list[index])) print("\n==============================================================\n") # this function displays the edit name menu def displayEditNameMenu(): print(''' ============================================================== To edit a name in the name bank, you must enter the index of the name you wish to edit. For example, if you wanted to edit the first name on the list, you would type '0'. ============================================================== ''') # this function displays the remove name menu def displayRemoveNameMenu(): print(''' ============================================================== To remove a name in the name bank, you must enter the index of the name you wish to remove. For example, if you wanted to remove the first name on the list, you would type '0'. ============================================================== ''') # this function edits a name in the bank def editNameBank(index): # takes index as a parameter print("You have selected to edit: " + str(first_name_list[index]) + " " + str(last_name_list[index])) # prints the name selected while True: # waits for a valid name to be inputted first_name = input("Please enter the new first name: ") # gets first name last_name = input("Please enter the new last name: ") # gets last name if first_name_list.count(first_name) > 0 and last_name_list.count(last_name) > 0: # checks if the name is already in the list print("Sorry, looks like this name is already in the bank") # prints error message continue elif first_name.isalpha() != True or last_name.isalpha() != True: # checks if invalid characters are inputted print("Invalid input. Names can only have letters of the alphabet.") # prints error message else: first_name_list[index] = first_name # edits the name in the bank last_name_list[index] = last_name # edits the name in the bank break # this function adds a name to the list def addNewName(): print("You have selected to add a new name to the bank.") while True: # loops until valid input is given first_name = input("Please enter the first name: ") # gets first name last_name = input("Please enter the last name: ") # gets last name if first_name_list.count(first_name) > 0 and last_name_list.count(last_name) > 0: # checks if name is already in the list print("Sorry, looks like this name is already in the bank") # prints error message continue elif first_name.isalpha() != True or last_name.isalpha() != True: # checks if an invalid character was inputted print("Invalid input. Names can only have letters of the alphabet.") # prints error message else: first_name_list.append(first_name) # adds first name to list last_name_list.append(last_name) # adds last name to list break # exits loop # this function removes a name from the list def removeName(index): # takes index as parameter del first_name_list[index] # removes the first name at the given index del last_name_list[index] # removes the last name at the given index print("Name removed.\n") # initializes variables first_name_list = [] last_name_list = [] phone_list = [] print("Hello, this is the name bank.") # prints welcome message user_size = getListSize() # gets the initial size getInitialList(user_size) # gets the initial name bank while True: # main while loop printMainMenu() user_action = getUserAction(0, 4) # gets the valid action from the user if user_action == 0: # checks if the user wants to quit break elif user_action == 1: # checks if the user wants to display the names displayNameBank() elif user_action == 2: # checks if the user wants to edit a name displayEditNameMenu() displayNameBank() edit_index = getUserAction(0, len(first_name_list) - 1) # gets a valid index from the user editNameBank(edit_index) elif user_action == 3: # checks if the user wants to add a new name addNewName() elif user_action == 4: # checks if the user wants to remove a name displayRemoveNameMenu() displayNameBank() remove_index = getUserAction(0, len(first_name_list) - 1) # gets a valid index removeName(remove_index) print("If you want to exit the program, type 'quit'.") user_quit = input("If you want to perform another action enter anything else: ") # gets user quit input if(user_quit == 'quit' or user_quit == 'Quit'): # checks if the user want to quit break # exits the loop else: continue # goes back to top of the loop print("Goodbye!\nShutting down...") # prints goodbye message
24c3923a268646490541d43ea510982cbbe8b1be
bretonics/MSSD
/CS521/Homework/hw_2/hw_2_3_3.py
2,521
3.6875
4
#!/usr/bin/env python import math # Decimal coordinates (latitude, longitude): atlanta = [33.7489954, -84.3879824] savannah = [32.0835407, -81.09983419999998] orlando = [28.5383355, -81.37923649999999] charlotte = [35.2270869, -80.84312669999997] radius = 6371.01 # Distance between Atlanta and Savannah as_distance = radius * math.acos( math.sin(math.radians(atlanta[0])) * math.sin(math.radians(savannah[0])) + math.cos(math.radians(atlanta[0])) * math.cos(math.radians(savannah[0])) * math.cos( math.radians(atlanta[1]) - math.radians(savannah[1]) ) ) print("Distance between Atlanta & Savannah:", round(as_distance,2), "km") # Distance between Atlanta and Orlando ao_distance = radius * math.acos( math.sin(math.radians(atlanta[0])) * math.sin(math.radians(orlando[0])) + math.cos(math.radians(atlanta[0])) * math.cos(math.radians(orlando[0])) * math.cos( math.radians(atlanta[1]) - math.radians(orlando[1]) ) ) print("Distance between Atlanta & Orlando:", round(ao_distance,2), "km") # Distance between Orlando and Savannah os_distance = radius * math.acos( math.sin(math.radians(orlando[0])) * math.sin(math.radians(savannah[0])) + math.cos(math.radians(orlando[0])) * math.cos(math.radians(savannah[0])) * math.cos( math.radians(orlando[1]) - math.radians(savannah[1]) ) ) print("Distance between Orlando & Savannah:", round(os_distance,2), "km") # Distance between Atlanta and Charlotte ac_distance = radius * math.acos( math.sin(math.radians(atlanta[0])) * math.sin(math.radians(charlotte[0])) + math.cos(math.radians(atlanta[0])) * math.cos(math.radians(charlotte[0])) * math.cos( math.radians(atlanta[1]) - math.radians(charlotte[1]) ) ) print("Distance between Atlanta & Charlotte:", round(ac_distance,2), "km") # Distance between Charlotte and Savannah cs_distance = radius * math.acos( math.sin(math.radians(charlotte[0])) * math.sin(math.radians(savannah[0])) + math.cos(math.radians(charlotte[0])) * math.cos(math.radians(savannah[0])) * math.cos( math.radians(charlotte[1]) - math.radians(savannah[1]) ) ) print("Distance between Charlotte & Savannah:", round(cs_distance,2), "km") # Area of first triangle s1 = (as_distance + os_distance + ao_distance) / 2 area1 = math.sqrt( s1 * (s1 - as_distance) * (s1 - os_distance) * (s1 - ao_distance) ) # Area of second triangle s2 = (as_distance + cs_distance + ac_distance) / 2 area2 = math.sqrt( s2 * (s2 - as_distance) * (s2 - cs_distance) * (s2 - ac_distance) ) print("The total area between the four cities is:", round((area1 + area2),2), "sq km")
f07bea9a630c6bf2fdb3ad98b7a19dfa0fe8fc13
NapFiend/Bag-Value-Optimisation-Using-EA
/util.py
5,623
4.03125
4
import random def get_weight_limit(line): """ Simply returns the cleaned weight limit as an integer from teh first line of the document """ return int(line.split(':')[1]) def init_pop(weights, pop_size): ''' Generate a population of random solutions. params: weights: list containing all weights of the bags pop_size: int defining how many solutions to make return: list of lists which are the pop_size solutions ''' solutions = [] for i in range(pop_size): # Reset temp solution temp_solution = [] for i in range(len(weights)): # Each bag has a 50/50 chance of being chosen to be part of any solutions rand_num = random.randint(0, 100) if rand_num > 50: # Add bag to solution temp_solution.append(1) else: # Do not add bag to solution temp_solution.append(0) # Add temp_solution to populations solutions.append(temp_solution) return solutions def eval_fitness(chromosone, weights, values, limit): ''' Fitness function that evaluates fitness based on total value of all the bags in the solution. Returns zero if weight exceeds limit params: chromosone: list with the current solution being evaluated weights: list of all the weights of the bags values: list of all values of the bags limit: integer denoting weight limit of van return: int total value of the solution ''' cur_weight = 0 cur_value = 0 # evaluate each gene and if the bag at that index is included, then add its' weight and value to the running total for i in range(len(chromosone)): if chromosone[i]: cur_weight += weights[i] cur_value += values[i] else: continue # Solutions exceeding limit will be penalised with a fitness of 0 if cur_weight > limit: return 0 else: return cur_value def tournament_select(fitnesses, tourney_size): ''' Selects a number of chromosones in the populaiton and returns the fittest params: fitnesses: list of the fitnesses of the current populaiton tourney_size: int the number of chromosones considered return: int index of the fittest solution in the tourney ''' participants = [] cur_highest = 0 cur_highest_ind = 0 # Runs until required number of unique participants is obtained # while len(participants) < tourney_size: # rand_ind = random.randint(0, len(fitnesses)-1) # if rand_ind in participants: # continue # else: # participants.append(rand_ind) participants = random.sample(range(len(fitnesses)-1), tourney_size) # Evaluate which of the participants is the fittest for participant in participants: if fitnesses[participant] > cur_highest: # If the fitness of teh current participant is greater than teh current leader, then adjust new values cur_highest = fitnesses[participant] cur_highest_ind = participant return cur_highest_ind def crossover(parent1, parent2, co): ''' Performs simple 1-point crossover on two parents to produce two children params: parent1: list containing first parent chromosone parent2: list ocntaining second parent chromosone co: int index denoting crossover point return: two lists children of post crossover ''' child_c = []*len(parent1) child_d = []*len(parent1) child_c[:co] = parent1[:co] child_c[co:] = parent2[co:] child_d[:co] = parent2[:co] child_d[co:] = parent1[co:] return child_c, child_d def mutate(chromosone, mut_rate): ''' Each gene has a mut_rate chance of being mutated (i.e. 0->1 or 1->0) params: chromosone: list the chromosone being mutated mut_rate: int the chance (%) of each gene being mutated return: list chromosone that has gone through mutation ''' mutatie = [] for i in range(len(chromosone)): # This gives each gene a mut_rate chance of being mutated if random.randint(0, 100) <= mut_rate: if chromosone[i] == 0: mutatie.append(1) elif chromosone[i] == 1: mutatie.append(0) else: # Append to mutatie regardless to keep indexing consistent mutatie.append(chromosone[i]) return mutatie def weakest_replacment(new_fitness, new_solution, population, fitnesses): ''' Take the new fitness and compare to the current population fitnesses, if it's higher than the lowest current fitness, replace. Else, discard params: new_fitness: integer fitness value of new chromosone new_solution: list new chromosone population: list of lists current chromosones in the working population fitnesses: list of ints denoting current working populace fitensses return: two lists updated population with relevant fitnesses ''' # Will grab the first lowest fitness in the curretn fitnesses list cur_fit_min = min(fitnesses) if cur_fit_min > new_fitness: return population, fitnesses else: ind = fitnesses.index(cur_fit_min) fitnesses[ind] = new_fitness population[ind] = new_solution #print(f"Replaced solution: {ind}") return population, fitnesses
b9577576822ae7fbb939fab4147747cf3d0d1355
LucaGreenshields/Averages-challenge
/main.py
1,114
3.984375
4
def user_input(): input_list = input("Enter a list elements separated by space ") string_list = input_list.split() num_list = [ float(item) for item in string_list ] return(num_list) def average(n_list): n = len(n_list) sum_n = sum(n_list) average = sum_n / n return(average) def median(n_list): n = len(n_list) n_sort = n_list.sort() if n % 2 == 0: median1 = n_list[n//2] median2 = n_list[n//2-1] median = (median1 + median2)/2 else: median = n_list[n//2] return(median) def mode(n_list): freq_dict = {} for num in n_list: freq_dict[num] = freq_dict.setdefault(num, 0) + 1 freq_list = [ (key, value) for key, value in freq_dict.items()] sorted_freq_list = sorted(freq_list, key=lambda item: item[1], reverse=True) max_freq = sorted_freq_list[0][1] result = [ item[0] for item in sorted_freq_list if item[1] == max_freq] return(result) num_list = user_input() print(f"average is {average(num_list)}") print(f"median is {median(num_list)}") print(f"mode is {mode(num_list)}")
d009d16b54fd6505babc0aa65cc09fd31b07f6a8
sminez/Cryptopals
/cplib/utils.py
3,333
3.6875
4
''' Utility functions for https://cryptopals.com ============================================ More specific functions and library functions are found in the other files in this module. ''' from codecs import encode, decode from string import ascii_lowercase ############################################################################### # .:General utility functions:. # ################################# def sort_by_value(d, reverse=False): ''' Sort a dict by it's values ''' return sorted(d, key=d.get, reverse=reverse) def chunks(it, size): ''' Split an iterable into even length chunks ''' if len(it) % size: return [list(chunk) for chunk in zip(*[iter(it)]*size)] else: raise ValueError('Iterable is not divisible by {}'.format(size)) def transpose(matrix): ''' Transpose a matrix. Input is assumed to be an nested iterable of equal length iterables. ''' return [list(z) for z in zip(*matrix)] def cycle(seq, n): ''' Rotate a seequence left, appending the initial element to the end ''' return seq[n:] + seq[:n] def sliding_slice(size, col, as_lists=False): ''' Yield a sliding series of iterables of length _size_ from a collection. If as_lists=True, yield full lists instead. NOTE: - yields [] if the supplied collection has less than _size_ elements - keeps _size_ elements in memory at all times ''' remaining = iter(col) current_slice = list(next(remaining) for n in range(size)) if len(current_slice) < size: raise StopIteration else: while True: if not as_lists: yield (elem for elem in current_slice) else: yield [elem for elem in current_slice] next_element = next(remaining) if next_element: current_slice = current_slice[1:] + [next_element] else: break ############################################################################### # .:Conversions between formats / representations:. # ##################################################### def hex_to_b64(hex_encoded_string): ''' Convert a hex encoded string to base64. Preserves string type by default but can be overwritten. ''' return encode(decode(hex_encoded_string, 'hex'), 'base64') def b64_to_hex(b64_encoded_string): ''' Convert a hex encoded string to base64. Preserves string type by default but can be overwritten. ''' return encode(decode(b64_encoded_string, 'base64'), 'hex') def bits(s): ''' Convert a bytestring to a list of bits. ''' # convert utf-8 strings to bytes bstr = s.encode() if type(s) == str else s return [int(b) for b in bin(int(bstr.hex(), 16))[2:]] def trigrams(s): ''' Get all trigrams from a string. (triplets of alpha-numeric characters) See link with eng_trigrams for more information. ''' # convert utf-8 strings to bytes s = s.encode() if type(s) == str else s s = b''.join(s.split()) punctuation = b'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' s = b''.join(bytes([c]) for c in s if c not in punctuation) t = list({s[n:n+3] for n in range(len(s) - 2)}) t = [cand for cand in t if all(c in ascii_lowercase for c in cand)] return t
40767de08b3038ee8a67394704209c7d8970fdc9
KennySoh/PythonNotes
/Problem Set & Answers/week3_hw_5.py
382
3.71875
4
import math def approx_ode(h,t0,y0,tn): x=tn/h counter=1 while counter<=int(x): y0=y0+h*f(t0,y0) t0=h+t0 #print(y0,counter,x,t0) counter=counter+1 return round(y0,3) def f(t, y): return 3.0+math.exp(-t)-0.5*y print approx_ode(0.1,0,1,3.0) print approx_ode(0.1,0,1,4.0) print approx_ode(0.1,0,1,5.0) print approx_ode(0.1,0,1,0.0)
f7c6bcd6c1225c26dfbf740778767980e9b6f061
Dipakece701/Python-Lab
/17-11-2019/for_2.py
158
4.3125
4
#!/usr/bin/python countries=['India','SriLanks','USA','Bangladesh','Pakistan'] print("Printing the countries name as below: ") for i in countries: print(i)
a99cb2d20e41325c2d8997441c63655d48a59685
advaitsp/PS-1-Summer-2020
/Numpy/Other Functions/extract.py
274
3.734375
4
import numpy as np x = np.arange(9.).reshape(3, 3) print 'Our array is:' print x # define a condition condition = np.mod(x,2) == 0 print 'Element-wise value of condition' print condition print 'Extract elements using condition' print np.extract(condition, x)
62e95db13611d9a6ecbdbb070b9b176d673b81f2
petyakostova/Software-University
/Programming Basics with Python/First_Steps_in_Coding/04_Triangle_Of_55_Stars.py
300
3.984375
4
''' Write a Python console program that prints a triangle of 55 asterisks located in 10 rows: * ** *** **** ***** ****** ******* ******** ********* ********** ''' for i in range(1,11): print('*'*i) ''' for i in range(1, 11): for j in range(0, i): print('*', end="") print() '''
432290726098d67f18e57dfc37a233bae5bd3e18
vbos70/KodKlubben
/pgzero/codebattle/boatbattle.py
6,105
3.5625
4
from random import choice, random, randrange from game import * import sys class Move: def __init__(self, heading, dist, target, fran): self.heading = heading self.dist = dist self.target = target self.fran = fran def __eq__(self, other): return ( self.heading == other.heading and self.dist == other.dist and self.target == other.target and self.fran == other.fran ) class BoatBattle(Game): def __init__(self, boardsize, bots, max_turn = 0, max_hits = 3): super().__init__(bots) self.max_turn = max_turn self.max_hits = max_hits self.boardsize = boardsize self.position = { b : (randrange(boardsize), randrange(self.boardsize)) for b in self.bots } self.hits = { b : 0 for b in self.bots } def is_valid_move(self, mv, bot): result = True x,y = self.position[bot] # check sailing distance if mv.heading == 'S': if y + mv.dist >= self.boardsize: result = False elif mv.heading == 'E': if x + mv.dist >= self.boardsize: result = False elif mv.heading == 'N': if y - mv.dist < 0: result = False elif mv.heading == 'W': if x - mv.dist < 0: result = False # cannot shoot backwards if mv.target == 'N' and mv.heading == 'S': result = False if mv.target == 'S' and mv.heading == 'N': result = False if mv.target == 'E' and mv.heading == 'W': result = False if mv.target == 'W' and mv.heading == 'E': result = False # check firing range if mv.target == 'S': if y + mv.fran >= self.boardsize: result = False elif mv.target == 'E': if x + mv.fran >= self.boardsize: result = False elif mv.target == 'N': if y - mv.fran < 0: result = False elif mv.target == 'W': if x - mv.fran < 0: result = False return result def is_alive(self, bot): return self.hits[bot] < self.max_hits def alive_bots(self): return [ b for b in self.bots if self.is_alive(b) ] def possible_moves(self, bot): moves = [] if self.is_alive(bot): directions = ['N', 'E', 'S', 'W'] distances = [0, 1, 2] fire_ranges = [0, 1, 2] moves = [ Move(heading, dist, target, fran) for heading in directions for dist in distances for target in directions for fran in fire_ranges if self.is_valid_move(Move(heading, dist, target,fran), bot) ] return moves def is_boat_hit(self, bot, target, fran): if self.is_alive(bot) and (self.old_position[bot] == target): # bot's position at the start of the turn is at target position d = { 1 : 0.9, # close range fire has high probability of hit 2 : 0.65, # medium range fire has lower probablity of hit 3: 0.25 } # long range fire has low probability of hit return random() <= d[fran] # bot is not at target position return False def execute(self, bot, move): if move in self.possible_moves(bot): bot.move = move # so boatgame can use it to draw the boat if move.fran > 0: tx, ty = self.position[bot] if move.target == 'N': ty = ty - move.fran if move.target == 'E': tx = tx + move.fran if move.target == 'S': ty = ty - move.fran if move.target == 'W': tx = tx - move.fran bot.tx_ty = (tx, ty) # so boatgame can use it to draw an explosion for b in self.bots: if b != bot: if self.is_boat_hit(b, (tx, ty), move.fran): bot.hit = True self.hits[b] = self.hits[b] + 1 x, y = self.position[bot] if move.heading == 'N': y = y - move.dist elif move.heading == 'E': x = x + move.dist elif move.heading == 'S': y = y + move.dist elif move.heading == 'W': x = x - move.dist self.position[bot] = (x,y) def play_turn(self): self.old_position = { b : self.position[b] for b in self.bots } for bot in self.bots: bot.step(self) self.turn = self.turn + 1 def hit(self, bot): return self.hits[bot] def directions(self, p0, p1): # .(x0,y0) E, S # .(x1,y1) # x0, y0 = p0 x1, y1 = p1 ds = set() if x1 < x0: ds.add('W') elif x1 > x0: ds.add('E') if y1 < y0: ds.add('N') elif y1 > y0: ds.add('S') return ds def distance_to_enemy(self, bot): for b in self.alive_bots(): if b != bot: dx = abs(self.position[bot][0] - self.position[b][0]) dy = abs(self.position[bot][1] - self.position[b][1]) return dx + dy def where_is_enemy(self, bot): dirs = set() for b in self.alive_bots(): if b != bot: dirs.update(self.directions(self.position[bot], self.position[b])) return dirs def enemies(self, bot): return [ b for b in self.alive_bots() if b != bot ] def distance(self, bot1, bot2): return (abs(self.position[bot1][0] - self.position[bot2][0]) + abs(self.position[bot1][1] - self.position[bot2][1]))
9eb1582c7bd9f24ed4af54a9de07ba70c3351c99
hz336/Algorithm
/LintCode/DFS/Permutation Index.py
906
3.84375
4
""" Given a permutation which contains no repeated number, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1. Example Given [1,2,4], return 1. """ class Solution: """ @param A: An array of integers @return: A long integer """ # http://www.cnblogs.com/theskulls/p/4881142.html def permutationIndex(self, nums): # write your code here if nums is None or len(nums) == 0: return 0 index, factor = 1, 1 for i in range(len(nums) - 1, -1, -1): # count numbers that are smaller than nums[i] count = 0 for j in range(i + 1, len(nums)): if nums[i] > nums[j]: count += 1 index += count * factor factor *= (len(nums) - i) return index
42d39703174c2bc74535e9c5dac7082acaac3cca
Nimger/LeetCode
/561.py
432
3.71875
4
# -*- coding:utf-8 -*- # https://leetcode.com/problems/array-partition-i/#/description class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ list = sorted(nums) result = 0 for index,value in enumerate(list): if index%2 == 0: result += value return result if __name__ == '__main__': solution = Solution() result = solution.arrayPairSum([1,4,3,2]) print(result)
64c7defa25dd2b6934cb2a6ed4e3a10160d92908
ynsong/Introduction-to-Computer-Science
/a07/a07q2.py
6,141
3.671875
4
##============================================================================== ## Yining Song (20675284) ## CS 116 Spring 2017 ## Assignment 07, Problem 2 ##============================================================================== import check ## Constants for ternary_search equal_string = "Checking if {0} is equal to {1}" less_than_string = "Checking if {0} is less than {1}" success = "Search successful" failure = "Search not successful" location = "{0} is located at index {1}" comparisons = "A total of {0} comparisons were made" ## ternary_search(nlsl, val) prints out the information about the steps performed ## at runtime when consumes a non empty list of interge nlst, and an integer val ## Effects: prints out the information about the steps performed at runtime ## ternary_search: (listof Int) Int -> None ## requires: nlst is non empty ## Examples: ## For L=[6,12,18,22], ternary_search(L, 18) => None and print: ## Checking if 18 is equal to 6 ## Checking if 18 is equal to 12 ## Checking if 18 is equal to 18 ## Search successful ## 18 is located at index 2 ## A total of 3 comparisons were made ## For ternary_search([6,12,18,22,29,37,38,41,51,53,55,67,73,75,77,81,86,88,94], 27)\ ## => None and print: ## Checking if 27 is equal to 38 ## Checking if 27 is less than 38 ## Checking if 27 is equal to 18 ## Checking if 27 is less than 18 ## Checking if 27 is equal to 29 ## Checking if 27 is less than 29 ## Checking if 27 is equal to 22 ## Search not successful ## A total of 7 comparisons were made def ternary_search(nlst, val): n = 0 L = nlst.copy() while len(nlst) > 4: ind1 = len(nlst)//3 if len(nlst) % 3 > 0: ind2 = ind1 * 2 + 1 else: ind2 = ind1 * 2 print(equal_string.format(val,nlst[ind1])) if nlst[ind1] == val: n += 1 print(success) print(location.format(val,L.index(val))) print(comparisons.format(n)) return elif val < nlst[ind1]: print(less_than_string.format(val,nlst[ind1])) n += 2 nlst = nlst[:ind1] elif val == nlst[ind2]: print(less_than_string.format(val,nlst[ind1])) print(equal_string.format(val,nlst[ind2])) n += 3 print(success) print(location.format(val,L.index(val))) print(comparisons.format(n)) return elif val < nlst[ind2]: print(less_than_string.format(val,nlst[ind1])) print(equal_string.format(val,nlst[ind2])) print(less_than_string.format(val,nlst[ind2])) n += 4 nlst = nlst[ind1+1:ind2] else: print(less_than_string.format(val,nlst[ind1])) print(equal_string.format(val,nlst[ind2])) print(less_than_string.format(val,nlst[ind2])) n += 5 nlst = nlst[ind2+1:] else: for i in nlst: n += 1 print(equal_string.format(val,i)) if i == val: print(success) print(location.format(val,L.index(val))) print(comparisons.format(n)) return else: print(failure) print(comparisons.format(n)) ## Constants for test: M1 = [6,12,18,22,29,37,38,41,51,53,55,67,73,75,77,81,86,88,94] M2 = [6,12,18,22,29,37,38,41,51,53,55,67,73,75,77,81,86,88,94,103] M3 = [6,12,18,22,29,37,38,41,51,53,55,67,73,75,77,81,86,88,94,103,130] ## Testing fot ternary_search(nlst,val): check.set_screen("Checking if 27 is equal to 1\nSearch not successful\nA total of\ 1 comparisons were made") check.expect("len is 1 and target not in lst", ternary_search([1], 27), None) check.set_screen("Checking if 27 is equal to 27\nSearch successful\n27 is located\ at index 0\nA total of 1 comparisons were made") check.expect("len is 1 and target in lst", ternary_search([27], 27), None) check.set_screen("Checking if 18 is equal to 6\nChecking if 18 is equal to 12\n\ Checking if 18 is equal to 18\nSearch successful\n18 is located at index 2\n\ A total of 3 comparisons were made") check.expect("len is 4 and target in lst", ternary_search([6,12,18,22],18), None) check.set_screen("Checking if 19 is equal to 6, Checking if 19 is equal to 12\n\ Checking if 19 is equal to 18\nChecking if 19 is equal to 22\nSearch not successful\n\ A total of 4 comparisons were made") check.expect("len is 4 and target not in lst", ternary_search([6,12,18,22],19), None) check.set_screen("ternary_search(M1,12)") check.expect("len is 19_1",ternary_search(M1,12), None) check.set_screen("ternary_search(M1, 27)") check.expect("len is 19_2", ternary_search(M1, 27), None) check.set_screen("ternary_search(M1,38)") check.expect("len is 19_3",ternary_search(M1,38), None) check.set_screen("ternary_search(M1,51)") check.expect("len is 19_4",ternary_search(M1,51), None) check.set_screen("ternary_search(M1,56)") check.expect("len is 19_5",ternary_search(M1,56), None) check.set_screen("ternary_search(M1,75)") check.expect("len is 19_6",ternary_search(M1,75), None) check.set_screen("ternary_search(M1,86)") check.expect("len is 19_7",ternary_search(M1,86), None) check.set_screen("ternary_search(M1,87)") check.expect("len is 19_8",ternary_search(M1,87), None) check.set_screen("ternary_search(M2,87)") check.expect("len is 20",ternary_search(M2,87), None) check.set_screen("ternary_search(M3,87)") check.expect("len is 21",ternary_search(M3,87), None)
01b99bb0bcf27ebcc23e6be17f5f80bc14b5e51d
ziolkowskid06/grokking_algorithms
/selection_sort.py
795
4.25
4
def findSmallest(arr): """Finds the smallest element in a array""" smallest = arr[0] # stores the first value smallest_index = 0 # stores the index of the first value for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] # stores the smallest value smallest_index = i # stores the index of the smallest value return smallest_index def selectionSort(arr): """Sorts the array""" newArr = [] for i in range(len(arr)): smallest = findSmallest(arr) # finds the index of the smallest element newArr.append(arr.pop(smallest)) # add the smallest element to the new array return newArr arr = [5, 3, 6, 2, 10] print(selectionSort(arr)) print(arr)
2cd170ce68a387116ff6889e242ad6da1183b105
shantanudwvd/PythonHackerrank
/ReversalAlgo.py
529
3.796875
4
def rverseArray(arr, start, end): while start < end: temp = arr[start] arr[start] = arr[end] arr[end] = temp start += 1 end = end - 1 def leftRotate(arr, d): if d == 0: return n = len(arr) rverseArray(arr, 0, d - 1) rverseArray(arr, d, n - 1) rverseArray(arr, 0, n - 1) def printArray(arr): for i in range(0, len(arr)): print(arr[i]) arr = list(map(int, input().split(" "))) n = len(arr) d = 2 d = d % n leftRotate(arr, d) printArray(arr)
b32a8c6e819d3d8e4eca065772a13c2dc58d8be9
thekiminlee/random_data_generator
/pyDataGenerator.py
2,198
3.546875
4
# Author: Ki Min Lee import sys import csv import random # List of attributes, stored in list format [name1, name2, ...] ATTR_NAME = [] # List of ranges of attributes # Number of ranges must match the number and order of attributes. ATTR_RANGE = [] # Name of the output file FILE = None # Decimal place for randomly generated float value. # Default at 1 DECIMAL = 1 sample_data = [] # list of csv data for export def generate(numData, exporting=True): # Configuration check if(exporting and FILE == None): raise FileNotFoundError("File path not specified") elif(len(ATTR_NAME) == 0 or len(ATTR_RANGE) == 0): raise ValueError("ATTR_NAME or ATTR_RANGE Empty") elif(len(ATTR_RANGE) != len(ATTR_NAME)): raise ValueError( "Number of attributes does not match the number of ranges") elif(numData < 1): raise ValueError("Number of generating data must be greater than 0") data_generator = generator(numData) if not exporting: return construct_data(data_generator) export(data_generator) print("Export complete.") return 1 def generator(numData): # Creates a generator of sample data while(numData > 0): data = [] for attribute in ATTR_RANGE: if type(attribute) == list: data.append(attribute[random.randint(0, len(attribute)-1)]) elif type(attribute) == tuple: minimum, maximum = attribute if(type(minimum) == float): data.append( round(random.uniform(minimum, maximum), DECIMAL)) else: data.append(random.randint(minimum, maximum)) numData -= 1 yield data def construct_data(generator): sample_data = [] sample_data.append(ATTR_NAME) for data in generator: sample_data.append(data) return sample_data def export(data): with open(FILE, 'w') as csvfile: writer = csv.writer(csvfile, delimiter=",") writer.writerow(ATTR_NAME) for generated in data: writer.writerow(generated) def data_print(start_index=0, end_index=len(sample_data)-1): pass
f42360652b1ce83448dfce63a7df518b2786c833
SS4G/AlgorithmTraining
/exercise/leetcode/python_src/by2017_Sep/Leet380.py
1,470
4.1875
4
import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.nums = [] self.posFind = {} def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ if val not in self.posFind or self.posFind[val] == -1: self.nums.append(val) self.posFind[val] = len(self.nums) - 1 return True return False def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ if val in self.posFind and self.posFind[val] != -1: delPos = self.posFind[val] self.nums[delPos] = self.nums[-1] self.posFind[self.nums[-1]] = delPos self.posFind[val] = -1 self.nums.pop() return True return False def getRandom(self): """ Get a random element from the set. :rtype: int """ return self.nums[random.randint(0, len(self.nums) - 1)] # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
772e4e9df712785927a019e4931dcf4a5e85bf8e
Sakura-lyq/test
/absert.py
365
3.671875
4
def my_abs(x): if not isinstance(x,(float,int)): raise TypeError('bad operand type') if x>=0 : return x else: return -x print(my_abs(88)) import math def move(x,y,step,angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx,ny x,y = move(100, 100, 60, math.pi/6) print(x,y)
25bd4552dabc3ee6a7e93f5049ea38fb79968140
sowmenappd/ds_algo_practice
/arrays_strings/rearrange_pos_neg_array_with_extra_space.py
509
4.1875
4
print("Program to rearrange positive and negative numbers in an array\n"); # This algorithm doesn't maintain the relative order def rearrange(array): l = len(array) idx = 0 for i in range(l): if array[i] < 0: array[idx], array[i] = array[i], array[idx] idx += 1 p = idx n = 0 while p > 0 and n < l: array[p], array[n] = array[n], array[p] p += 1 n += 2 return array print(rearrange([-1, 2, -3, 4, 5, 6, -7, 8, 9, -1]))
9272ec57d006dec7432aa15f7897189d8cfd06d6
emkoltsova/two_tasks
/2.py
202
3.90625
4
def func_up(text): new_text ='' for current_word in text.split(): new_text += current_word[0].upper()+current_word[1:]+' ' return new_text print(func_up('hello world how are you'))
2930aab1fc8cf11bd29ac173122fc6270eb7823b
FrankieZhen/Lookoop
/LeetCode/otherQuestion/商汤/Q3.py
363
3.65625
4
# coding:utf-8 # 股票最大利润,只能买卖一次 def solver(nums): minNum = nums[0] maxProfit = 0 for n in nums: maxProfit = max(maxProfit, n - minNum) if n < minNum: minNum = n return maxProfit def test(): nums = [7,1,5,3,6,4] ret = solver(nums) print(ret) if __name__ == '__main__': test()
d5fb4c92dc7ad93358e4be309e17d66c6a227167
Khamisali61/Homeday2-bootcamp
/max_min_num.py
353
3.9375
4
def find_max_min(n): resultList = [] max_number = max(n) min_number = min(n) if min_number == max_number: #if min and max are equal return number of elements in list number_of_elements = len(n) resultList.append(number_of_elements) else: resultList.append(min_number) resultList.append(max_number) return resultList
5ea74d54986e50290bcd54f9bc46f9b1eb6fe8d8
varunn807/Coding-Exercise
/climbingStairs.py
406
3.625
4
class Solution(object): def __init__(self): self.stairs={} def climbStairs(self, n): """ :type n: int :rtype: int """ self.stairs[0]=1 self.stairs[1] = 1 for i in range(2,n+1): self.stairs[i]=self.stairs[i-1]+self.stairs[i-2] return self.stairs[n] sol=Solution() print(sol.climbStairs(5))
a662cdf93613ce4e1d87eed4cbdbd2a29f2bc16a
flaviojussie/Exercicios_Python-Inciante-
/EstruturaDeRepeticao - PythonBrasil/exec10.py
110
4.03125
4
num1, num2 = int(input('Digite dois numeros:')), int(input()) while num1 < num2: num1 += 1 print(num1)
e37ab4c57ff0a3623349bfcd9bd2af477883aa13
statham/spellchecker
/spellchecker.py
1,684
3.71875
4
import sys from trie import Trie def readDict(): #get words from /usr/share/dict/words f = open('/usr/share/dict/words', 'r') words = Trie() #load words into trie for word in f.read().split('\n'): words.insert(word) return words def get_possible_words(word): #get all possible words for duplicate letters and incorrect vowels prev = None states = [] vowels = 'aeiouy' for letter in word: new_states = [] if (letter != prev) and (letter not in vowels): #letter is not a duplicate or vowel if not states: states.append(letter) else: #add letter onto each possible word for i in range(0, len(states)): states[i] += letter elif letter == prev: #duplicate, add new states for state in states: new_states.append(state+letter) states+=new_states else: #vowel, add new states for each vowel if not states: states.append(letter) for vowel in vowels: if letter != vowel: states.append(vowel) else: for state in states: for vowel in vowels: new_states.append(state+vowel) states = new_states prev = letter return states def spellcheck(): #get dictionary words = readDict() #take input and return suggestion until killed input = raw_input('> ').lower() while input: valid_words = [] #check if word correctly spelled if words.get(input): output = words.get(input) #look for all possible mispellings else: states = get_possible_words(input) for state in states: if words.get(state): valid_words.append(words.get(state)) if not valid_words: output = 'NO SUGGESTION' else: output = valid_words[0] sys.stdout.write(output+'\n') input = raw_input('> ').lower()
1ff42058c3c3582b5714dec2a89bf6d2b942380c
Razdeep/PythonSnippets
/OCT09/05.py
538
3.78125
4
# Builtin method and variables in classes # @CAUTION: Not working class Employee: def __init__(self,name,age): self.name=name self.age=age def display(self): print('Name',self.name,' Age',self.age) emp=Employee('Rajdeep',19) print('Documentation of the class',emp.__doc__) print('Name of the class',emp.__name__) print('in which module class is called',emp.__module__) print('Bases of the class',emp.__bases__) print('Dictionary of the class',emp.__dict__) print() print(dir(emp)) # @CAUTION: Not working
0f0d2f37a80a5a665084a734f520c46a6115c6d6
RaadUH/RBARNETTCIS2348
/8_10.py
184
4
4
input1 = input() input2 = input1.replace(" ","") reverse = input2[::-1] if(reverse==input2): print(input1,"is a palindrome") else: print(input1,"is not a palindrome")
b62c8b84e88c6c1084ee37f6d686d6d4c6b01c8a
rafaelperazzo/programacao-web
/moodledata/vpl_data/21/usersdata/112/8553/submittedfiles/exercicio24.py
198
3.625
4
# -*- coding: utf-8 -*- from __future__ import division import math n=0 for i in range (3,n+1,1): for i in range (2,a,1): cont=cont+1 if cont==0: print(a)
366ef6f61c394aa4e47eb5c86d9df02ffc6a56e4
neironus/100DaysOfPython
/TalkPython/55/program.py
1,306
3.609375
4
from api import MovieSearchClient def ask_for_searchword(): return input('Search for: ') def prints_results(results): if results: for result in results: print('{} by {} rate {}'.format( result.get('title'), result.get('director'), result.get('imdb_score') )) else: print('No results founds.') def main(): m = MovieSearchClient() search_by = input(( "What do you want to search by ? [k]eyword /" "[d]irector / [i]mdb number. " )) if search_by == 'k': search = ask_for_searchword() resp = m.search_movie(search) prints_results(resp.json().get('hits')) elif search_by == 'd': search = ask_for_searchword() resp = m.search_director(search) prints_results(resp.json().get('hits')) elif search_by == 'i': search = ask_for_searchword() resp = m.search_imdb_number(search) result = resp.json() if result: print('{} by {} rate {}'.format( result.get('title'), result.get('director'), result.get('imdb_score') )) else: print('No results founds') else: print('Invalid option') if __name__ == '__main__': main()
298b0e436431887e011e93394dcfae914091a8af
gitudaniel/pythonchallenge
/level10_regex.py
427
3.625
4
import re """ refer to https://stackoverflow.com/questions/8624345/whats-the-meaning-of-a-number-after-a-backslash-in-a-regular-expression && https://regex101.com/ with regex:(\d)(\1*) and test string:13211311123113112211 """ value = '1' for i in range(0, 6): values_compiled = re.compile(r'(\d)(\1*)') values = values_compiled.findall(value) value = ''.join([str(len(i+j))+i for i,j in values]) print value
5b13e78178f96997fc0ff4d26a036f60adbbe921
aydansuleymanova1/testlab1
/calculator.py
417
3.59375
4
def sum(m, n): result = m if n < 0: for i in range(abs(n)): result -= 1 else: for i in range(n): result += 1 return result def divide (m,n): result=0 negativeResult= m>0 and n<0 or m<0 and n>0 n= abs(n) m= abs(m) while (m-n>=0): m=-n result=+1 result=-result if negativeResult else result return result
4c827a5a29854ad8c5a0d3033e6e609ea3bc7d22
vasc/quicksort
/quicksort.py
299
4.03125
4
#!/usr/bin/env python import sys def quicksort(l): if not l: return l pivot = l[0] smaller = [x for x in l[1:] if x < pivot] larger = [x for x in l[1:] if x >= pivot] return quicksort(smaller) + [pivot] + quicksort(larger) l = map(int, sys.argv[1:]) print " ".join(map(str, quicksort(l)))
5afff72436e53b28e568e7bf27128077f3f40aa2
pablo-grande/Aula
/Benchmark/sort.py
1,208
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -* from timing import * @print_timing def sort(bad_list): """ Dada una lista desordenada (bad_list) la ordena utilizando el programa por defecto de python :param bad_list: """ bad_list.sort() # merge sort @print_timing def merge_sort(bad_list): """ Dada una lista desordenada, aplica merge sort para ordenarla :param bad_list: """ merge_sort_r(bad_list, 0, len(bad_list) -1) # merge sort recursivo def merge_sort_r(bad_list, first, last): if first < last: sred = (first + last)/2 merge_sort_r(bad_list, first, sred) merge_sort_r(bad_list, sred + 1, last) merge(bad_list, first, last, sred) # merge "de verdad" def merge(list2, first, last, sred): aux = [] i = first j = sred + 1 while i <= sred and j <= last: if list2[i] <= list2[j]: aux.append(list2[i]) i += 1 else: aux.append(list2[j]) j += 1 while i <= sred: aux.append(list2[i]) i += 1 while j <= last: aux.append(list2[j]) j += 1 for k in range(0, last - first + 1): list2[first + k] = aux[k]
5901a4a5537394f8ff5b7af5df0d3cc2e018f2cd
MounishKokkula/RandomWorks
/BarChartWithTurtle/BarwithTurtle.py
7,101
3.84375
4
#!/usr/bin/env python # coding: utf-8 """ This program is to convert values from '.xlsx' file to a bar chart. The inputs are parsed and to check for empty values and format. The bar chart is plotted using "turtle" a inbuilt library with python. """ import pandas as pd import turtle class DrawGraph(): def set_data(self,year,employees,profit): """ Data format/setup for the chart input :param year: year input from the excel sheet - format: list :param employees: year input from the excel sheet - format: list :param profit: year input from the excel sheet - format: list """ # Assigning X axis values for i in range(len(year)): xList.append(str(year[i])) # Assigning Y axis values # for i in range(y_axis_min, y_axis_max, int(y_axis_max/len(employees))): for i in range(1,int(y_axis_max/5)+1): yList.append(int(i*5)) # Assigning employee bar values for i in range(len(employees)): empbarList.append(employees[i]) # Assigning profit bar values for i in range(len(profit)): profitbarList.append(profit[i]) def setup(self): """ Setup the initial turtle positions and values """ tG.hideturtle() tG2.hideturtle() tGL.hideturtle() tL.hideturtle() tX.up() tY.up() tG.up() tG2.up() tGL.up() tL.up() tX.setpos(-500, -250) tY.setpos(-500, -250) tG.setpos(-500, -250) tG2.setpos(-500, -250) tGL.setpos(-500, -250) def x_axis(self): """ Draw the x-axis with input values """ tX.down() for i in range(len(xList)): tX.forward(100) tX.right(90) tX.forward(20) tX.up() tX.forward(XYmargin) tX.write(xList[i], False, align="center", font=(fontname, 10, "normal")) tX.right(180) tX.forward(20 + XYmargin) tX.down() tX.right(90) tX.forward(50) def y_axis(self): """ Draw y-xis with the input values given. Step1) Draw the positive axis Step2) Draw the negative axis """ # Write only 0 at the beginning tY.up() tY.setpos(-500 + zero_pos, -250 + zero_pos) tY.write("0", True, align="center", font=(fontname, 10, "normal")) tY.setpos(-500, -250) tY.down() # Fill in positive Y Axis values tY.left(90) for i in range(int(y_axis_max/5)): tY.forward(60) tY.left(90) tY.forward(20) tY.up() tY.forward(XYmargin) tY.write(yList[i], False, align="center", font=(fontname, 10, "normal")) tY.left(180) tY.forward(20 + XYmargin) tY.down() tY.left(90) tY.forward(50) # Fill in negative Y Axis values if y_axis_min < 0: tY.up() tY.setpos(-500, -250) tY.down() tY.left(180) for i in range(int(abs(y_axis_min)/5)): tY.forward(60) tY.right(90) tY.forward(20) tY.up() tY.forward(XYmargin) tY.write(-yList[i], False, align="center", font=(fontname, 10, "normal")) tY.right(180) tY.forward(20 + XYmargin) tY.down() tY.right(90) tY.forward(50) def draw_emp_bar(self): """ Draw bar for employee data input """ tG.fillcolor('blue') tG.forward(100 - int(bar_width)/ 2) for i in range(len(employees)): tG.begin_fill() tG.left(90) tG.down() tG.forward(int(empbarList[i])*12) # match the size of the y axis bar tG.right(90) tG.forward(bar_width/2) tG.right(90) tG.forward(int(empbarList[i])*12) # match the size of the y axis bar tG.left(90) tG.end_fill() tG.up() tG.forward(100 - int(bar_width)/ 2) def draw_profit_bar(self): """ Draw bar for profit data input """ tG2.fillcolor('green') tG2.forward(100) for i in range(len(profit)): tG2.begin_fill() tG2.left(90) tG2.down() tG2.forward(int(profitbarList[i])*12) # match the size of the y axis bar tG2.right(90) tG2.forward(bar_width/2) tG2.right(90) tG2.forward(int(profitbarList[i])*12) # match the size of the y axis bar tG2.left(90) tG2.end_fill() tG2.up() tG2.forward(100 - int(bar_width)/ 2) def label(self): tL.sety(-250 + 500 +10) tL.write(title, False, align="center", font=(fontname, 20, "normal")) tL.sety(-250 - 20 - XYmargin - 30) tL.write(xlabel, False, align="center", font=(fontname, 10, "normal")) tL.setpos(-500, 250 + 10) tL.write(ylabel, False, align="center", font=(fontname, 10, "normal")) if __name__ == '__main__': # Read the the csv input using pandas excel_file = input("Please input the absolute location to the '.xlsx' file : \n") # Supply filename as input argument header = pd.read_excel(excel_file) print("Columns in the xlsx file: {}".format(header.columns.ravel())) print("Turtle draw in progress") year = list(header.year.fillna('n/a')) # filling 'n/a' when year is empty profit = list(header.profit.fillna(0)) # filling '0' when profit is empty employees = list(header.employees.fillna(0)) # Filling '0' when employees is empty y_axis_min = min(min(profit), min(employees)) # Computing Min value for positive Y axis y_axis_max = max(max(profit), max(employees)) # Computing Max value for negative Y axis turtle.screensize(1200, 900) tX = turtle.Pen() tY = turtle.Pen() tG = turtle.Pen() # Bar 1 - Employee tG2 = turtle.Pen() # Bar 2 - Profit tGL = turtle.Pen() tL = turtle.Pen() xList = [] yList = [] profitbarList= [] empbarList= [] zero_pos = -10 # Bar width bar_width = 40 XYmargin = 20 fontname = "Times New Roman" # Graph title, label name title = "Employees vs Profit" xlabel = "Year" ylabel = "Employees/Profit" graph = DrawGraph() graph.set_data(year,employees,profit) graph.setup() # initial setup of the chart graph.label() # labels for the chart graph.x_axis() # draw x axis graph.y_axis() # draw y axis graph.draw_emp_bar() # draw employee bar graph.draw_profit_bar() # draw profit bar turtle.mainloop()
250a7e04cda64b71afaa2964746706075a3f3110
capric8416/leetcode
/algorithms/python3/guess_number_higher_or_lower_ii.py
1,044
4.125
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked. Example: n = 10, I pick 8. First round: You guess 5, I tell you that it's higher. You pay $5. Second round: You guess 7, I tell you that it's higher. You pay $7. Third round: You guess 9, I tell you that it's lower. You pay $9. Game over. 8 is the number I picked. You end up paying $5 + $7 + $9 = $21. Given a particular n ≥ 1, find out how much money you need to have to guarantee a win. """ """ ==================== body ==================== """ class Solution: def getMoneyAmount(self, n): """ :type n: int :rtype: int """ """ ==================== body ==================== """
4742dbff7ea02aa4a5b5b84bcab26a246431b1fa
deepakdashcode/myPy
/removeWordsOfLengthK.py
165
3.703125
4
sen=input('Enter the Sentence\n') n=int(input('Enter the Word Length\n')) wordList=sen.split() s='' for i in wordList: if len(i)!=n: s=s+i+' ' print(s)
e7d32e9fc424697dd231f03f004ac436aa7ecf1a
drumgiovanni/simple_calendar
/calendar1.py
1,441
3.890625
4
from tkinter import Frame, Button, LEFT, RIGHT, BOTTOM, StringVar, Label, Entry, END, CENTER import calendar class Calendar1(Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.master.title("カレンダー") self.year = 2018 self.month = 1 # タイトル frame1 = Frame(self) frame1.pack() Label(frame1, text="カレンダーだよ", font=("Sans-serif", 32)).pack() # 入力フィールド frame3 = Frame(self) frame3.pack() self.ent1 = Entry(frame3, font=("Helvetica", 24), width=5) self.ent1.insert(END, self.year) self.ent1.pack(side=LEFT) Label(frame3, text="年", font=("Sans-serif", 23)).pack(side=LEFT) self.ent2 = Entry(frame3, font=("Helvetica", 24), width=2) self.ent2.insert(END, self.month) self.ent2.pack(side=LEFT) Label(frame3, text="月", font=("Sans-serif", 23)).pack(side=LEFT) Button(frame3, text="表示", command=self.setcal, font=("Times", 20)).pack(side=RIGHT) self.result = StringVar() Label(self, textvariable=self.result, font=("Times", 18), width=30).pack() self.setcal() def setcal(self): self.year = int(self.ent1.get()) self.month = int(self.ent2.get()) cal = calendar.month(self.year, self.month) self.result.set(cal) Calendar1().mainloop()
40ddc71a42f176e703cd4723d6e8f009742d9b00
anovacap/daily_coding_problem
/smaller_elms_right.py
391
3.875
4
#!/usr/bin/python # ex 1.4 find the number of smaller elements to the right O(n2) # for loop and sum (sum has a O(n) loop def smaller_elm_right(arr): res = [] for i, num in enumerate(arr): count = sum(val < num for val in arr[i + 1:]) res.append(count) print("result = ", res) return res if __name__ == "__main__": x = [6,7,2,8,9,1,4,12,5,10,3] j = smaller_elm_right(x) print(j)
de0ef44b42166c27c1e43243839b0f0fbdbad97d
applesir20191001/Python001-class01
/week04/weekfour.py
1,560
3.546875
4
import pandas as pd import numpy as np # 1. SELECT * FROM data; group = ['x', 'y', 'z'] data = pd.DataFrame({ "group": [group[x] for x in np.random.randint(0, len(group), 20)], "salary": np.random.randint(5, 50, 20), "age": np.random.randint(15, 50, 20) }) data1 = pd.DataFrame({ "group": [group[x] for x in np.random.randint(0, len(group), 10)], "salary": np.random.randint(5, 50, 10), "age": np.random.randint(15, 50, 10) }) print(data) print(data1) # 2. SELECT * FROM data LIMIT 10; df2 = data.head(10) print(df2) # 3. SELECT id FROM data; //id 是 data 表的特定一列 df3 = data['group'] print(df3) # 4. SELECT COUNT(id) FROM data; df4 = data['salary'].count() print(df4) # 5. SELECT * FROM data WHERE id<1000 AND age>30; df5 = data[(data['salary'] < 45) & (data['age'] > 20)] print(df5) # 6. SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id; df6 = data.drop_duplicates(['group', 'salary']).groupby( 'group').agg({'salary': pd.Series.nunique}) print(df6) df6 = data.groupby('group')['salary'].nunique() print(df6) # 7. SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id; df7 = pd.merge(data, data1, on='group', how='inner') print(df7) # 8. SELECT * FROM table1 UNION SELECT * FROM table2; df8 = pd.concat([data, data1]) print(df8) # 9. DELETE FROM table1 WHERE id=10; df9 = data.drop(data[data['group'] == 'y'].index, axis=0) print(df9) # 10. ALTER TABLE table1 DROP COLUMN column_name; df10 = data.drop('group', 1) print(df10) print(data) data.drop('group', axis=1, inplace=True) print(data)
483698ab90c50dbfa373938d89ad5eee2e7ba409
sausheong/bookspeak
/speak.py
1,550
3.5625
4
#!/usr/bin/python3 import sys, getopt, pyttsx3 # a simple script to speak out a book or write it into an mp3 # either read the book out aloud or save it to an mp3 file def speak(bookfile, audiofile, voice, rate): engine = pyttsx3.init() if voice != '': engine.setProperty('voice', voice) if rate != '': engine.setProperty('rate', int(rate)) # clean up a bit on the text to remove newlines, but not remove paragraph lines book = open(bookfile, 'r').read()\ .replace('\n\n', '*newline*')\ .replace('\n', ' ')\ .replace('*newline*', '\n\n') if audiofile == '': engine.say(book) else: engine.save_to_file(book, audiofile) engine.runAndWait() # assumes running in a MacOS environment def main(argv): book, audio, voice, rate = '', '', '', '' try: opts, args = getopt.getopt(argv,"hb:a:v:r",["book=","audio=","voice=","rate="]) except getopt.GetoptError: print('speak.py -b <book-file> -a <audio-file> -v <voice-id> -r <words-per-min>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('speak.py -b <book-file> -a <audio-file> -v <voice-id> -r <words-per-min>') sys.exit() elif opt in ("-b", "--book"): book = arg elif opt in ("-a", "--audio"): audio = arg elif opt in ("-v", "--voice"): voice = arg elif opt in ("-r", "--rate"): rate = arg speak(book, audio, voice, rate) if __name__ == "__main__": main(sys.argv[1:])
c252dce9a92d4768185c9cb5b53575fcbe0964a8
foob26uk/coding-questions
/ch1/ch110.py
589
3.59375
4
# 1.10 def anonymousLetter(letter, magazine): H = {} for l in list(letter): if l != " ": if l in H: H[l] = H[l] + 1 else: H[l] = 1 for m in list(magazine): if m != " ": if m in H: H[m] = H[m] - 1 for h in H: if H[h] > 0: return -1 return 1 letter = "whats up dudes" magazine = "super man whats up i dont dudes know" print anonymousLetter(letter, magazine) magazine = "super man whats up i dont know" print anonymousLetter(letter, magazine) print
767566ccfc935ef7d59804558c1c39b20544c4c2
HoodCat/python_practice02
/prob01.py
197
3.625
4
money = int(input("금액: ")) kind_of_money = [50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1] print() for m in kind_of_money: print(str(m) + "원: " + str(money//m) + "개") money %= m
bccc300a047ddccacfaf874223468a07e906c955
ibaomu/Hello-World
/莫名.py
640
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 31 09:27:53 2018 @author: 某树 """ name=input("请输入您的姓名:") if name in ("褚晓雪"): print("您好,{}小姐,主人给您留了一封信,请确定是否要开启?".format(name[0])) y=input() if y in ("快,好,打开,,好的,嗯"): print("丑晓雪,我喜欢你。") if name in("抱木"): print("My master,can I help you?") x=input() if x in("嗯,好,email"): print("Whether to make changes to your mail?") x=input() if x in("不,不用了,没事"): print("好的,主人。")
c84fd2378a3aa641bbab42e26ccae940d0fbe926
atriekak/LeetCode
/solutions/36. Valid Sudoku.py
1,193
3.6875
4
class Solution:    def isValidSudoku(self, board: List[List[str]]) -> bool:        #Approach: Hashing        #Time Complexity: O(1) // constant board size        #Space Complexity: O(1) // constant board size                m = len(board)        n = len(board[0])                row_map = [set() for i in range(m)]        col_map = [set() for j in range(n)]        box_map = [[set() for j in range(n // 3)] for i in range(m // 3)]                for i in range(len(board)):            for j in range(len(board[0])):                val = board[i][j]                if val == '.':                    continue                                box_i = i // 3                box_j = j // 3                                if val in row_map[i] or val in col_map[j] or val in box_map[box_i][box_j]:                    return False                                row_map[i].add(val)                col_map[j].add(val)                box_map[box_i][box_j].add(val)                        return True
d0e8900081da836fd0d65e4b46c088ab314b15ed
kopytova/pythonProject
/task_1_1.py
224
3.953125
4
seconds = int(input('Введите временной интервал в секундах: ')) ss = (seconds % 60) minutes = seconds // 60 mm = (minutes % 60) hh = (minutes // 60) print("%02d:%02d:%02d" % (hh, mm, ss))
e1936381661855f0909d9e4354d7b46300828a47
PyThingy/bearded-octo-ironman
/Spotkanie3/marcin_flatten_pickle.py
626
3.5625
4
import pickle def flatten(elem_nested): all_flatten = tuple() if isinstance(elem_nested, list): for item in elem_nested: all_flatten += flatten(item) elif isinstance(elem_nested, tuple): for item in elem_nested: all_flatten += flatten(item) elif isinstance(elem_nested, dict): for val in elem_nested.values(): all_flatten += flatten(val) else: all_flatten += (elem_nested,) return all_flatten if __name__ == '__main__': obj = open('pickle', 'rb') pickle_obj = pickle.load(obj) print(flatten(pickle_obj)) obj.close()
82cc70df9dc223cf576015638c15e5e934bfb6b5
muhmunt/python
/latihan ket/lat3.py
1,254
3.671875
4
def batas(): print("==========================================") batas(); print("APLIKASI LAUNDRY KILOAN") print("\nKODE LAUNDRY\t JENIS LAUNDRY\tTARIF/KILO") print("\t\t\t1\t\tPAKAIAN\t\t\t10.000") print("\t\t\t2\t\tSELIMUT\t\t\t20.000") print("\t\t\t3\t\tKARPET\t\t\t30.000") batas(); pl = int(input("Masukkan Kode Laundry = ")) batas(); if(pl == 1): jenis = "PAKAIAN" tarif = 10000 total = 10000 elif(pl == 2): jenis = "SELIMUT" tarif = 20000 total = 20000 elif(pl == 3): jenis = "KARPET" tarif = 30000 total = 30000 print("Jenis Laundry= ",jenis) print("Tarif = ",tarif) batas(); kl = int(input("Berapa kilo anda mencuci = ")) batas(); print("TAMBAHAN") print("\nKODE TAMBAHAN\t TAMBAHAN\tTARIF/KILO") print("\t\t\t1\t\tGOSOK\t\t\t30.000") print("\t\t\t2\t\tGOSOK WANGI\t\t40.000") batas(); tbh = int(input("Masukkan kode tambahan = ")) if(tbh == 1): jenis = "GOSOK" tarif = 30000 total2 = 30000 elif(tbh == 2): jenis = "GOSOK WANGI" tarif = 40000 total2 = 40000 tots = total2 * kl print("TAMBAHAN = ",jenis) print("TARIF = ",tarif) batas(); akhir = total*kl + tots print("TOTAL = ",akhir) batas(); byr = int(input("BAYAR = ")) kembalian = byr - akhir print("Kembalian = ",kembalian)
145b08f057efb2de119f8c5f99dd4b17f8c5d21d
serg-kanarskiy/Osnovi-programmirovaniya-na-Python
/Homework №2.py
2,847
4.21875
4
#Задачи на циклы и оператор условия ''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' i = 0 while i < 5: i += 1 print(i,'0') ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. ''' x = 0 for i in range(10): n = input('Введите любую цифру: ') if '5' in n: x += 1 print('Количество введеных цифр 5 равно', x) ''' Задача 3 Найти сумму ряда чисел от 1 до 100. Полученный результат вывести на экран. ''' sum = 0 for i in range(1,101): sum += i print(sum) ''' Задача 4 Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран. ''' multiplication = 1 for i in range(1,11): multiplication *= i print(multiplication) ''' Задача 5 Вывести цифры числа на каждой строчке. ''' integer_number = 1993 print(integer_number%10,integer_number//10) while integer_number>0: print(integer_number%10) integer_number = integer_number//10 ''' Задача 6 Найти сумму цифр числа. ''' integer_number = 1993 sum = 0 while integer_number > 0: sum += integer_number%10 integer_number = integer_number//10 print(sum) ''' Задача 7 Найти произведение цифр числа. ''' integer_number = 1993 multi = 1 while integer_number > 0: multi *= integer_number%10 integer_number = integer_number//10 print(multi) ''' Задача 8 Дать ответ на вопрос: есть ли среди цифр числа 5? ''' integer_number = 100793 while integer_number > 0: if integer_number%10 == 5: print('Yes') break integer_number = integer_number//10 else: print('No') ''' Задача 9 Найти максимальную цифру в числе ''' integer_number = 100793 max = 0 while integer_number > 0: if integer_number%10 >= max: max = integer_number%10 integer_number = integer_number//10 print('Максимальная цифра в числе: ', max) ''' Задача 10 Найти количество цифр 5 в числе ''' integer_number = 59598 x = 0 while integer_number > 0: if integer_number%10 == 5: x += 1 integer_number = integer_number//10 print('Количество цифр 5 в числе: ', x)
5433a5d198829134758ea0ad6bbf236a59f958bf
seeprybyrun/project_euler
/problem0031.py
985
3.5625
4
# -*- coding: utf-8 -*- # In England the currency is made up of pound, £, and pence, p, and there # are eight coins in general circulation: # # 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). # It is possible to make £2 in the following way: # # 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p # How many different ways can £2 be made using any number of coins? import time t0 = time.clock() answer = -1 memo = {} def make_change(target,denoms): if target == 0: return 1 elif target < 0: return 0 elif len(denoms) == 0: return 0 m = max(denoms) index = '{0},{1}'.format(target,m) if index in memo: return memo[index] memo[index] = make_change(target,denoms[:-1]) + make_change(target-m,denoms) return memo[index] denoms = [1,2,5,10,20,50,100,200] target = 200 answer = make_change(target,denoms) print 'answer: {}'.format(answer) # 73682 print 'seconds elapsed: {}'.format(time.clock()-t0) # ~3.6ms
bcb7f35d207707b3b546345be1118721ae47b096
esoteric24/python_training
/bar_graph.py
881
3.796875
4
import matplotlib.pyplot as plt def createBarChart(values, catLabels, xLabel, yLabel, title): numBars = len(values) barCenters = range(1, (numBars + 1)) plt.barh(barCenters, values, align='center') plt.yticks(barCenters, catLabels) plt.xlabel(xLabel) plt.ylabel(yLabel) plt.title(title) plt.grid() plt.show() values = [] catLabels = [] title = raw_input('Enter the title of the graph: ') print xLabel = raw_input('Enter the x-axis label of the graph: ') print yLabel = raw_input('Enter the y-axis label of the graph: ') print numBars = int(raw_input('Enter the number of the bars in the graph: ')) print for filler in range(numBars): catLabels.append(raw_input('Enter the label of the bar: ')) print values.append(int(raw_input('Enter the value of the bar: '))) print createBarChart(values, catLabels, xLabel, yLabel, title)
e143fa93f725abbbfddba4d70281a65bfea9dcae
brenoskuk/Breno_and_Kogler
/Images/01 - Basicos/06 - histograma_da_imagem-metodo_ ineficiente.py
788
3.734375
4
# Programa para calcular e mostrar o histograma de uma imagem # metodo INEFICIENTE - varre a imagem 256 vezes # contando as frequencias do valor no pixel em cada varredura # import Image import numpy import matplotlib.pyplot as plt from sys import exit as fim # le image de um arquivo M = Image.open('.\Lena.png') width , height = M.size N = width * height print "largura = ", width , "pixels" print "altura = ", height , "pixels" print "# pixels = largura x altura = " , N # cria vetor h[] de tamanho 256 e o preenche com o histograma h = [] for m in range(255): h.append(0) for v in range(255): for i in range(width): for j in range(height): if v == M.getpixel((i,j)): h[v]= h[v] + 1 M.show() plt.plot(h) plt.show() fim()
bac1b0c035b5aa39817b985f8e391f8b2e63dc01
brunoharlein/POO_recall
/attributs_classe2.py
497
3.796875
4
class Test: a = "attribut de classe" def __init__(self): self.b = "attribut d'objet" if __name__ == "__main__": attribut = Test ( ) print(attribut.b) print(Test.a) # Pour utiliser le(s) attribut(s) de classe, # il est inutile de créer un objet de cette classe puisque l’attribut est une propriété de la classe class Test1: a = "attribut de classe" def __init__(self): self.b = "attribut d'objet" if __name__ == "__main__": print(Test1.a)
b684f68991abb37d0d992fb083a738b64add9321
Instructor-Devon/Python-ONL-June
/Algos/Arrays/balanceIndex.py
717
3.75
4
def balance_index(arr): if len(arr) == 0: return False if len(arr) == 1: return 0 # [2,2,5,2,2] => 2 (balanced at index 2) # [23,4,5] => False # [10,15,7,25] => 2 # remember to not include pivot point in sums sum1 = arr[0] sum41 = 0 # loop rest of array to find sum of elements for i in range(1,len(arr)): sum41 += arr[i] for k in range(1,len(arr)-1): temp = arr[k] # subtract arr[k] from sum41 sum41 -= temp # compare, return k if True if sum1 == sum41: return k # if False, add arr[k] to sum1 sum1 += temp return False test = [0,0,0] print(balance_index(test))
a0d965f8deac73d592891d3447a30cc436f74cff
wjdwls0630/2018-1-Web-Python-KHU
/Week10-Exam2/Exam2(월,수 1시수업)/Exam2_1(5).py
1,169
3.5
4
class SmartPhone() : def __init__(self,maker="",model="",spec=[],price=0.0): self.maker=maker self.model=model self.spec=spec[:] self.price=price def setInfo(self,maker,model,spec,price): self.maker=maker self.model=model self.spec=spec[:] self.price=price def __str__(self): a= "Maker: {}\n".format(self.maker) b= "Model: {}\n".format(self.model) c= "Spec:\n" d="" for i in self.spec : line="\t"+i+"\n" d=d+line print() e="Price: {}".format(self.price) return a+b+c+d+e def addSpec(self,spec=[]): self.spec.extend(spec) #or self.spec=self.spec+spec s9=SmartPhone("Samsung","Galaxy S9", [], 100) ix=SmartPhone() print("-"*10) print(ix) print("-"*10) ix.setInfo("Apple","iPhone X", [], 150) print("-"*10) print(s9) print("-"*10) print(ix) print("-"*10) s9.addSpec(["Super Slow-mo", "AR Emoji Stickers"]) s9.addSpec() ix.addSpec(["notch","Face ID"]) ix.addSpec(["Dual camera"]) s9.addSpec(["Iris scanner", "Fingerprint"]) print("-"*10) print(s9) print("-"*10) print(ix) print("-"*10)
890c845a13116f965f477642737c8fc8a36c5f92
terodea/DSA
/practice/data_engineering/array/10.find_2_repeating_elements.py
8,334
4.125
4
import math class BruteForce: """ >>> obj = BruteForce() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) Time Complexity: O(n*n) Auxiliary Space: O(1) """ def printRepeating(self, arr, size): for i in range (0, size-1): for j in range (i + 1, size): if arr[i] == arr[j]: print(arr[i], end = ' ') class ArrayCount: """ Traverse the array once. While traversing, keep track of count of all elements in the array using a temp array count[] of size n, when you see an element whose count is already set, print it as duplicate. This method uses the range given in the question to restrict the size of count[], but doesn’t use the data that there are only two repeating elements. >>> obj = ArrayCount() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) Time Complexity: O(n) Auxiliary Space: O(n) """ def printRepeating(arr,size) : count = [0] * size print(" Repeating elements are ",end = "") for i in range(0, size) : if(count[arr[i]] == 1) : print(arr[i], end = " ") else : count[arr[i]] = count[arr[i]] + 1 class EquationApproach: """ Let the numbers which are being repeated are X and Y. We make two equations for X and Y and the simple task left is to solve the two equations. We know the sum of integers from 1 to n is n(n+1)/2 and product is n!. We calculate the sum of input array when this sum is subtracted from n(n+1)/2, we get X + Y because X and Y are the two numbers missing from set [1..n]. Similarly calculate the product of input array, when this product is divided from n!, we get X*Y. Given the sum and product of X and Y, we can find easily out X and Y. Let summation of all numbers in the array be S and product be P X + Y = S – n(n+1)/2 XY = P/n! Using the above two equations, we can find out X and Y. For array = 4 2 4 5 2 3 1, we get S = 21 and P as 960. X + Y = 21 – 15 = 6 XY = 960/5! = 8 X – Y = sqrt((X+Y)^2 – 4*XY) = sqrt(4) = 2 Using below two equations, we easily get X = (6 + 2)/2 and Y = (6-2)/2 X + Y = 6 X – Y = 2 Time Complexity: O(n) Auxiliary Space: O(1) >>> obj = EquationApproach() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) """ def printRepeating(self, arr, size) : # S is for sum of elements in arr[] S = 0 # P is for product of elements in arr[] P = 1 n = size - 2 # Calculate Sum and Product # of all elements in arr[] for i in range(0, size) : S = S + arr[i] P = P * arr[i] # S is x + y now S = S - n * (n + 1) // 2 # P is x*y now P = P // self.fact(n) # D is x - y now D = math.sqrt(S * S - 4 * P) x = (D + S) // 2 y = (S - D) // 2 print("The two Repeating elements are ", (int)(x)," & " ,(int)(y)) def fact(self, n) : if(n == 0) : return 1 else : return(n * self.fact(n - 1)) class XOR: """ Let the repeating numbers be X and Y, if we xor all the elements in the array and all integers from 1 to n, then the result is X xor Y. The 1’s in binary representation of X xor Y is corresponding to the different bits between X and Y. Suppose that the kth bit of X xor Y is 1, we can xor all the elements in the array and all integers from 1 to n, whose kth bits are 1. The result will be one of X and Y. >>> obj = XOR() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) """ def printRepeating(self, arr, size): # Will hold xor # of all elements xor = arr[0] n = size - 2 x = 0 y = 0 # Get the xor of all # elements in arr[] # and 1, 2 .. n for i in range(1 , size): xor ^= arr[i] for i in range(1 , n + 1): xor ^= i # Get the rightmost set # bit in set_bit_no set_bit_no = xor & ~(xor-1) # Now divide elements in two # sets by comparing rightmost # set bit of xor with bit at # same position in each element. for i in range(0, size): if(arr[i] & set_bit_no): # XOR of first # set in arr[] x = x ^ arr[i] else: # XOR of second # set in arr[] y = y ^ arr[i] for i in range(1 , n + 1): if(i & set_bit_no): # XOR of first set # in arr[] and # 1, 2, ...n x = x ^ i else: # XOR of second set # in arr[] and # 1, 2, ...n y = y ^ i print("The two repeating", "elements are", y, x) class ArrayElementsAsIndex: """ Traverse the array. Do following for every index i of A[]. { check for sign of A[abs(A[i])] ; if positive then make it negative by A[abs(A[i])]=-A[abs(A[i])]; else // i.e., A[abs(A[i])] is negative this element (ith element of list) is a repetition } Example: A[] = {1, 1, 2, 3, 2} i=0; Check sign of A[abs(A[0])] which is A[1]. A[1] is positive, so make it negative. Array now becomes {1, -1, 2, 3, 2} i=1; Check sign of A[abs(A[1])] which is A[1]. A[1] is negative, so A[1] is a repetition. i=2; Check sign of A[abs(A[2])] which is A[2]. A[2] is positive, so make it negative. ' Array now becomes {1, -1, -2, 3, 2} i=3; Check sign of A[abs(A[3])] which is A[3]. A[3] is positive, so make it negative. Array now becomes {1, -1, -2, -3, 2} i=4; Check sign of A[abs(A[4])] which is A[2]. A[2] is negative, so A[4] is a repetition. >>> obj = ArrayElementAsIndex() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) """ def printRepeating(arr, size) : print(" The repeating elements are",end=" ") for i in range(0,size) : if(arr[abs(arr[i])] > 0) : arr[abs(arr[i])] = (-1) * arr[abs(arr[i])] else : print(abs(arr[i]),end = " ") class ModifedAbove: """ The point is to increment every element at (arr[i]th-1)th index by N-1 (as the elements are present upto N-2 only) and at the same time check if element at that index when divided by (N-1) gives 2. If this is true then it means that the element has appeared twice and we can easily say that this is one of our answers. This is one of the very useful techniques when we want to calculate >>> obj = ModifiedAbove() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) """ def twoRepeated(self, arr, N): m = N - 1 for i in range(N): arr[arr[i] % m - 1] += m if ((arr[arr[i] % m - 1] // m) == 2): print(arr[i] % m ,end= " ") class SetBasedApproach: """ The point here is to enter the array elements one by one into the unordered set. If a particular element is already present in the set it’s a repeating element. Time Complexity: O(n) Auxiliary Space: O(n) >>> obj = SetBasedApproach() >>> arr = [4, 2, 4, 5, 2, 3, 1] >>> arr_size = len(arr) >>> obj.printRepeating(arr, arr_size) """ def printRepeating(self, arr, size): s = set() print("The two Repeating elements are : ", end = "") for i in range(size): if (len(s) and arr[i] in s): print(arr[i], end = " ") s.add(arr[i])
16b0d5ea6dc2f573177a681924496830d4c46813
ZZY2357/auto-workflow
/scripts/caesar-password.py
1,629
3.578125
4
#/usr/bin/env python3 chars_down = list('abcdefghijklmnopqrstuvwxyz') chars_up = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') nums = list('0123456789') def round_index(index, length): if index >= 0 and index < length: return index if index >= length: return index % length return round_index(length + index, length) def find_index(item, ls) -> int: for i in range(len(ls)): if ls[i] == item: return i while True: key = int(input('Type the key(number): ')) message = input('Type the message: ') option = input('Encode or Decode?[e/d] ') if option != 'e' and option != 'd': print('Option not found. Try again.') for i in range(len(message)): message = list(message) if option == 'e': if message[i] in chars_up: message[i] = chars_up[round_index(find_index(message[i], chars_up) + key, len(chars_up))] elif message[i] in chars_down: message[i] = chars_down[round_index(find_index(message[i], chars_down) + key, len(chars_down))] elif message[i].isdigit(): message[i] = str(round_index(int(message[i]) + key, 10)) else: # decode if message[i] in chars_up: message[i] = chars_up[round_index(find_index(message[i], chars_up) - key, len(chars_up))] elif message[i] in chars_down: message[i] = chars_down[round_index(find_index(message[i], chars_down) - key, len(chars_down))] elif message[i] in nums: message[i] = str(round_index(int(message[i]) - key, 10)) print(''.join(message))
800fd8ed6539a56b79db2cd64688d38396c72394
aseembrahma/projeuler
/prob37.py
1,622
3.546875
4
import sys from time import time from itertools import product from copy import copy prime_list = [2,3,5,7] def extend_prime_list(n): global prime_list current_last_prime = prime_list[-1] if current_last_prime >= n: return numlist = [True for x in range(current_last_prime+1, n+1)] for i in prime_list: temp=((current_last_prime/i)+1)*i while temp<=n: numlist[temp-(current_last_prime+1)]=False temp+=i for i in range(len(numlist)): if numlist[i]: temp=i+(current_last_prime+1) prime_list.append(temp) temp+=(i+(current_last_prime+1)) while temp<=n: numlist[temp-(current_last_prime+1)]=False temp+=(i+(current_last_prime+1)) def satisfies(n): numstr = str(n) if len(numstr) < 2: return False for x in range(1, len(numstr)): if int(numstr[x:]) in prime_list and int(numstr[:x]) in prime_list: pass else: return False return True if __name__ == "__main__": time_start = time() limit = 1000 limit_lower = 0 total=0 count = 0 extend_prime_list(100000) i=0 while count != 11: if satisfies(prime_list[i]): print prime_list[i] count+=1 total+=prime_list[i] i+=1 if i >= len(prime_list): extend_prime_list(prime_list[-1]+100000) time_end = time() print "Answer:", total print "Time taken", time_end-time_start
4ebc645d16971233620d61d1f159d3da06bb378c
ferb2015/TargetOfferByPython
/59. 机器人的运动范围.py
2,591
3.578125
4
""" 题目描述 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格, 但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子? """ # 回溯法。有了上一题“矩阵的路径”的经验,在上一题的基础上更改代码就行了。 # return还是遇到了问题,这里flag=1之后不用再flag=0,依然是看牛客网讨论区的回答才AC. class Solution: def movingCount(self, threshold, rows, cols): # write code here flag = [0]*rows*cols count = [0]*rows*cols #或 flag = [[0 for col in range(cols)] for row in range(rows)] 下面用flag[i][j] def helper(threshold, rows, cols, i, j, flag, count): index = i * cols + j if i < 0 or i >= rows or j < 0 or j >= cols or \ sum(list(map(int,str(i))))+sum(list(map(int,str(j)))) > threshold or \ flag[index] == 1: return 0 flag[index] = 1 count[index] = 1 helper(threshold,rows,cols, i - 1, j, flag,count) helper(threshold, rows, cols, i + 1, j, flag,count) helper(threshold, rows, cols, i, j - 1, flag,count) helper(threshold, rows, cols, i, j + 1, flag,count) return count summ = helper(threshold, rows, cols, 0, 0, flag,count) if summ == 0: return 0 else: return sum(summ) # 参考牛客网上: class Solution: def movingCount(self, threshold, rows, cols): # write code here flag = [0]*rows*cols #flag = [[0 for col in range(cols)] for row in range(rows)] def helper(threshold, rows, cols, i, j, flag): index = i * cols + j if i < 0 or i >= rows or j < 0 or j >= cols or \ sum(list(map(int,str(i))))+sum(list(map(int,str(j)))) > threshold or \ flag[index] == 1: return 0 flag[index] = 1 return helper(threshold,rows,cols, i - 1, j, flag)+ \ helper(threshold, rows, cols, i + 1, j, flag)+ \ helper(threshold, rows, cols, i, j - 1, flag)+ \ helper(threshold, rows, cols, i, j + 1, flag) +1 return helper(threshold, rows, cols, 0, 0, flag)
15fda221e4dd7325e75c5a29167f4c4c9baa3ffe
feecoding/Python
/Classes/Program 4.py
1,982
3.765625
4
##created by feecoding class stagair: pass t=list() n=0 while True: print("1:ADD a trainner") print("2:Edit a trainner") print("3:DELETE a trainner") print("4:List") print("5:Quit") c=int(input()) if(c==1): t.append(stagair()) n=n+1 t[n-1].nom=input("Enter first name: ") t[n-1].prenom=input("Enter Family name: ") t[n-1].note1=int(input("Enter note 1: ")) t[n-1].note2=int(input("Enter note 2: ")) t[n-1].note3=int(input("Enter note 3: ")) elif(c==2): nom=input("Enter the first name of the trainner you want to edit: ") prenom=input("Enter the family name of the trainner you want to edit: ") p=-1 for i in range(n): if(nom==t[i].nom and prenom==t[i].prenom): p=i i=n if(p==-1): print("Not exes...") else: t[p].nom=input("Enter the first name of the trainner you want to edit: ") t[p].prenom=input("Enter the family name of the trainner you want to edit: ") t[p].note1=int(input("Enter note 1:")) t[p].note2=int(input("Enter note 2:")) t[p].note3=int(input("Enter note 3:")) elif(c==3): noms=input("Enter the first name of the trainner you want to Del: ") prenoms=input("Enter the family name of the trainner you want to Del: ") ps=-1 for i in range(n): if(noms==t[i].nom and prenoms==t[i].prenom): ps=i i=n if(ps==-1): print("Not exes...") else: for i in range(ps,n-1): t[i]=t[i+1] n=n-1 elif(c==4): for i in range(n): print(t[i].nom) print(t[i].prenom) print(t[i].note1) print(t[i].note2) print(t[i].note3) elif(c==5): print("Done") break
734b813dcb65c7fc5acd390769f24c9ad439754e
IoanHadarean/Python-exercises
/learn_python/basic_operators.py
762
4
4
""" The target of this exercise is to create two lists called x_list and y_list, which contain 10 instances of the variables x and y, respectively. You are also required to create a list called big_list, which contains the variables x and y, 10 times each, by concatenating the two lists you have created. """ x = object() y = object() x_list = [x] * 10 y_list = [y] * 10 big_list = x_list + y_list print("x_list contains %d objects" %len(x_list)) print("y_list contains %d objects" %len(y_list)) print("big_list contains %d objects" %len(big_list)) if x_list.count(x) == 10 and y_list.count(y) == 10: print("First part completed") if big_list.count(x) == 10 and big_list.count(y) == 10: print("Second part completed")
d9269652e47baf8c2a470fe9bd220fdb84190de8
sendurr/spring-grading
/submission - lab6/set2/ELLEN A UNDERWOOD_9452_assignsubmission_file_Lab 6/ELLEN A UNDERWOOD_9452_assignsubmission_file_Lab 6.py
596
3.953125
4
degF=float(input("Enter the degrees F:")) degC=(degF-32)*(5/9.0) print ("Degrees in celsius:",degC) import sys print ("Enter degrees F:") degF=float(sys.argv[0]) degC=(degF-32)*(5/9.0) print ("Degrees in Celsius:",degC) import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', action='store', dest='degF') parser.add_argument('-c', action='store', dest='degC') args = parser.parse_args() if args.degC: c=float(degC) f=c*1.8+32 print ("Degrees in F:",args.f) if args.degF: f=float(degF) c=(f-32)*(5/9.0) print ("Degrees in C:",args.c)
76cafac773d83a281fdf2bd8d68a1ad9974cb186
nareshdb/codechefSolutions
/JAN19B_FANCY/answer.py
204
3.84375
4
noOfTestCases = input() for n in range(0, noOfTestCases): answerChecks = 0 wordsArray = map(str, raw_input().split()) if "not" in wordsArray: print("Real Fancy") else: print("regularly fancy")
408ae70b14a9494274c6e5ef2dcd71a1205f6dba
jacksonyoudi/AlgorithmCode
/PyProject/leetcode/history/design-circular-deque.py
2,056
4.03125
4
class MyCircularDeque: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self._deque = [] self._size = k def insertFront(self, value: int) -> bool: """ Adds an item at the front of Deque. Return true if the operation is successful. """ if len(self._deque) == self._size: return False self._deque.insert(0, value) return True def insertLast(self, value: int) -> bool: """ Adds an item at the rear of Deque. Return true if the operation is successful. """ if len(self._deque) == self._size: return False self._deque.append(value) return True def deleteFront(self) -> bool: """ Deletes an item from the front of Deque. Return true if the operation is successful. """ if len(self._deque) == 0: return False self._deque.pop(0) return True def deleteLast(self) -> bool: """ Deletes an item from the rear of Deque. Return true if the operation is successful. """ if len(self._deque) == 0: return False self._deque.pop() return True def getFront(self) -> int: """ Get the front item from the deque. """ if len(self._deque) == 0: return None return self._deque[0] def getRear(self) -> int: """ Get the last item from the deque. """ if len(self._deque) == 0: return None return self._deque[-1] def isEmpty(self) -> bool: """ Checks whether the circular deque is empty or not. """ if len(self._deque) == 0: return True return False def isFull(self) -> bool: """ Checks whether the circular deque is full or not. """ if len(self._deque) == self._size: return True return False
e3868e20cebd0d1339638b3aeee6eae56485d908
Andrew-C-Peterson/Project-Euler-Andrew
/PE031.py
294
3.796875
4
#How to make 2 lbs using different cominbations of coins #Dynamic programming coins = [1,2,5,10,20,50,100,200] count = [1]+[0]*200 for coin in coins: for i in range(coin, 201): count[i] += count[i-coin] print("Ways to make change =", count[200]) print("count = ", count)
61c1ec58a848250237740aa4c3388ad89287e70e
darraes/coding_questions
/v2/_leet_code_/0681_next_closest_time.py
1,097
3.5625
4
import itertools class Solution(object): def nextClosestTime(self, time): ans = start = 60 * int(time[:2]) + int(time[3:]) elapsed = 24 * 60 for h1, h2, m1, m2 in itertools.product( {int(x) for x in time if x != ":"}, repeat=4 ): hours, mins = 10 * h1 + h2, 10 * m1 + m2 if hours < 24 and mins < 60: cur = hours * 60 + mins if cur < start: cur_elapsed = cur + 24 * 60 - start else: cur_elapsed = cur - start if 0 < cur_elapsed < elapsed: ans = cur elapsed = cur_elapsed return "{:02d}:{:02d}".format(*divmod(ans, 60)) ############################################################### import unittest class TestFunctions(unittest.TestCase): def test_1(self): s = Solution() self.assertEqual("19:39", s.nextClosestTime("19:34")) self.assertEqual("22:22", s.nextClosestTime("23:59")) if __name__ == "__main__": unittest.main(exit=False)
03432204ee4b2cf92387b0564d854d4be857602d
gg4race/projecteuler
/problem4/problem4.py
994
3.796875
4
import math def main(): # loop through pairs of integers and return largest palindrome product a = 999 def isPalindrome(a, b): product = str(a * b) endIndex = len(product)/2 isPalindrome = True for i in range(0, endIndex): if (product[i] != product[len(product) - i - 1]): isPalindrome = False break i += 1 return isPalindrome palindrome = 0 #loop through pairs of numbers while a >= 100: #reset b for each a b = 999 while b >= 100: if (isPalindrome(a, b)): palindrome = max(palindrome, a * b) b -= 1 a -= 1 print(palindrome) ''' more pro solution def ispal(n): s = str(n) return all(s[i] == s[len(s)-1-i] for i in xrange(len(s) / 2)) print max(a * b for a in xrange(100, 1000) for b in xrange(100, 1000) if ispal(a * b))''' if __name__ == '__main__': main()
d2ae84ecd8a6bab229d858b213ba28be7eaad282
lucypeony/stanford_algs
/merge_sort.py
934
4
4
# -*- coding: utf-8 -*- """ Stanford Algorithm Week 1 : Merge Sort Created on Tue Aug 9 20:24:23 2016 @author: Lucy """ def merge_sort(arr): #l = len(arr) if len(arr) < 2: return arr print("arr length: ",len(arr)) half = len(arr) // 2 left = merge_sort(arr[:half]) right = merge_sort(arr[half:]) out = [] li = ri = 0 # index of next element from left, right halves while True: if li >= len(left): # left half is exhausted out.extend(right[ri:]) break if ri >= len(right): # right half is exhausted out.extend(left[li:]) break if left[li] < right[ri]: out.append(left[li]) li =li + 1 else: out.append(right[ri]) ri += 1 print("in merge_sort:",str(out)) return out my_list=[9,8,7,5,4,3,2,1,11] print(str(merge_sort(my_list)))
c1780aa1abaf0fd3fd0602ba7b4bf5b62be036c7
sahusaurabh65/linear-regression-with-train_csv
/knn1.py
2,176
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 22 14:24:33 2018 @author: ADMIN """ import os import pandas as pd import numpy as np #Setting the path os.getcwd() os.chdir('C:/Users/ADMIN/Desktop/github') df=pd.read_csv('airbnb.csv',encoding='ISO-8859-1') #Load the csv and create a copy dc_listings = pd.read_csv('airbnb.csv',encoding='ISO-8859-1') list(dc_listings) dc_listings1= dc_listings.copy() #Finding the distance of my house with 3 rooms compared to other houses dc_listings1["distance"]=abs(dc_listings["accommodates"]-3) list(dc_listings1["distance"].value_counts()) #Cleaning the price column dc_listings["price"] = dc_listings["price"].str.replace(",","") dc_listings["price"] = dc_listings["price"].str.replace("$","").astype("float") dc_listings1["price"] = dc_listings1["price"].str.replace(",","") dc_listings1["price"] = dc_listings1["price"].str.replace("$","").astype("float") dc_listings["price"].describe() #Finding the mean prices of all the houses with 3 rooms mean = dc_listings[dc_listings1["distance"]==0]["price"].mean() mean #Function that finds the absolute distance for accomodates and finds the predicted price def get_mean(number_of_rooms,k,dc_listings1): np.random.seed(6) dc_listings1["distance"]=abs(dc_listings["bathrooms"]-number_of_rooms) dc_listings1 = dc_listings1.loc[np.random.permutation(len(dc_listings1))] mean = dc_listings1[dc_listings1["distance"]==0]["price"][:k].mean() error = (dc_listings1[dc_listings1["distance"]==0]["price"]-mean)**2 return mean,(error.sum()/len(error))**0.5 #centeral limit theory #prints mean and error with repect to changes in mean print(get_mean(3,5,dc_listings1)) #finding missing data of security_deposit print (dc_listings["security_deposit"].isnull().sum()/len(dc_listings["security_deposit"])) #nonrmalizing the maximum nights print (dc_listings["maximum_nights"].max()) #nonrmalizing the maximum nights dc_listings["maximum_nights"]=(dc_listings["maximum_nights"].mean()/dc_listings["maximum_nights"]-dc_listings["maximum_nights"].mean())/dc_listings["maximum_nights"].std() print (dc_listings["maximum_nights"])
2ea5d27083c8f31fca90c24662b8a327d8d14baa
JamesHaobo/test
/test01.py
501
3.609375
4
str1=input("请输入你所想要转换的温度(温度的格式是:134F、33C)\n") try: flag=str1[-1] num1=float(str1[0:-1]) if flag in ["F","f"]: print("华氏摄氏度"+str1+"转换后摄氏温度为"+str((int(num1)-32)/1.8)+"C") elif flag in ["C","c"] : print("摄氏摄氏度"+str1+"转换后华氏温度为"+str(int(num1)*1.8+32)+"F") else: print("请重新温度") except BaseException : print("输入温度的数值有问题")
444532e5649313dd72676a0498dcf7c5bee8f8dd
mrodolfo1981/python
/dicionarios.py
137
3.515625
4
meu_dicionario = {"A": "AMEIXA","B":"BOLA","C":"CACHORRO"} for chave in meu_dicionario: print(chave)+":"+meu_dicionario[chave])
698b7924ecf551693245ecd4c99f9b9c05d49d7d
RickyZhong/CheckIO
/Home/Express Delivery.py
4,352
3.625
4
from collections import namedtuple from heapq import heappop, heappush, heapify Node = namedtuple("Node", ("Priority", "Cost", "Position", "Path", "Box")) def heuristic(position, goal): return abs(position[0] - goal[0]) + abs(position[1] - goal[1]) def get_neighbour(position, maze): directions = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)} neighbours = [] for direction, (dx, dy) in directions.items(): x = position[0] + dx y = position[1] + dy if maze[x][y] != 'W': neighbours.append(((x, y), direction)) return neighbours def checkio(field_map): # Add boundaries field_map = ["W" * (len(field_map[0]) + 2)] + \ ["W" + x+ "W" for x in field_map] + \ ["W" * (len(field_map[0]) + 2)] # Find start goal boxes position start = goal = None for i in range(len(field_map)): for j in range(len(field_map[i])): if field_map[i][j] == "S": start = (i, j) elif field_map[i][j] == "E": goal = (i, j) elif start and goal: break # Declare openlist and closelist open_list = [Node(0, 0, start, '', True)] heapify(open_list) closed_list = set() # Find solution while open_list: current = heappop(open_list) if current.Position == goal and current.Box: return current.Path if (current.Position, current.Box) in closed_list: continue neighbours = get_neighbour(current.Position, field_map) # Calculate cost cost = 2 if current.Box else 1 # Unload or Load cargo if field_map[current.Position[0]][current.Position[1]] == "B": priority = current.Cost + 1 + heuristic(current.Position, goal) heappush(open_list, Node(priority, current.Cost + 1, current.Position, current.Path + "B", not current.Box)) for new_position, direction in neighbours: priority = current.Cost + cost + heuristic(new_position, goal) heappush(open_list, Node(priority, current.Cost + cost, new_position, current.Path + direction, current.Box)) closed_list.add((current.Position, current.Box)) return "N" if __name__ == '__main__': #This part is using only for self-checking and not necessary for auto-testing ACTIONS = { "L": (0, -1), "R": (0, 1), "U": (-1, 0), "D": (1, 0), "B": (0, 0) } def check_solution(func, max_time, field): max_row, max_col = len(field), len(field[0]) s_row, s_col = 0, 0 total_time = 0 hold_box = True route = func(field[:]) for step in route: if step not in ACTIONS: print("Unknown action {0}".format(step)) return False if step == "B": if hold_box: if field[s_row][s_col] == "B": hold_box = False total_time += 1 continue else: print("Stephan broke the cargo") return False else: if field[s_row][s_col] == "B": hold_box = True total_time += 1 continue n_row, n_col = s_row + ACTIONS[step][0], s_col + ACTIONS[step][1], total_time += 2 if hold_box else 1 if 0 > n_row or n_row >= max_row or 0 > n_col or n_row >= max_col: print("We've lost Stephan.") return False if field[n_row][n_col] == "W": print("Stephan fell in water.") return False s_row, s_col = n_row, n_col if field[s_row][s_col] == "E" and hold_box: if total_time <= max_time: return True else: print("You can deliver the cargo faster.") return False print("The cargo is not delivered") return False assert check_solution(checkio, 12, ["S...", "....", "B.WB", "..WE"]), "1st Example" assert check_solution(checkio, 11, ["S...", "....", "B..B", "..WE"]), "2nd example"
caf68110a22327707fedec8085386695f283422d
Aasthaengg/IBMdataset
/Python_codes/p02713/s982627561.py
173
3.609375
4
k = int(input()) from math import gcd s = 0 for a in range(1, k+1): for b in range(1, k+1): g = gcd(a, b) for c in range(1, k+1): s += gcd(g, c) print(s)
944415e28c7f252879c9306e2002e79e6363df79
isthatjoke/projects
/python algorithm/lesson_6/Task_1_b.py
1,188
3.96875
4
# В одномерном массиве целых чисел определить два наименьших элемента. # Они могут быть как равны между собой (оба являться минимальными), так и различаться. # задание №7 урока 3 import random import sys def size(*values): summ = 0 for el in values: summ += sys.getsizeof(el) return summ def get_size(dict): summ = 0 for i in dict: summ += sys.getsizeof(i) return f' code - {summ}' SIZE = 10 MIN_ITEM = 10 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] # print(array) min_1 = array[0] min_1_idx = 0 min_2 = array[0] idx_1 = 0 for i in array: if i < min_1: min_1 = array[idx_1] min_1_idx = idx_1 idx_1 += 1 if min_1 == array[0]: min_2 = array[1] idx_2 = 0 for i in array: if i < min_2 and idx_2 != min_1_idx: min_2 = array[idx_2] idx_2 += 1 # print(min_1, min_2) print(get_size(list(locals().items()))) # 1288 print(f'Для второго решения - {size(min_1, min_1_idx, min_2, idx_1, idx_2, i, array)}') # 352
57a645b84b8b011010568dda252d40ba138db329
lytvyn139/udemy-complete-python3-bootcamp
/15-loop-tasks.py
6,528
4.21875
4
########################################################### # FOR LOOP # for (let i=0; x< 10; i++) {} # for i in range(0, 10, 1): # print(i) # # increment of +1 is simplied # for y in range(0, 10): # print(y) # # increment of +1 and start at 0 is implied # for z in range(10): # print(z) #note that if you need to specify an increment other than +1, # all three arguments are required. # for a in range(0, 10, 2): # print(a) # # output: 0, 2, 4, 6, 8 #loop backward # for b in range(10, 1, -3): # print(b) # # output: 10, 7, 2 ########################################################### # FOR LOOPS THROUGH LISTS my_list = [0, False, 'Cake', 3, 4, 5] print(type(my_list[1])) for i in range(0, len(my_list)): print(f"index#{i} = {my_list[i]}") # OR # for v in my_list: # print(v) # output: abc, 123, xyz ########################################################### # WHILE LOOPS THROUGH LISTS for count in range(0,5): print("looping - ", count) count = 0 while count < 5: print("looping - ", count) count += 1 y = 3 while y > 0: print(y) y = y - 1 else: print("Final") #3,2,1, final # BREAK for val in "string": if val == "i": break print(val) # output: s, t, r # Continue for val in "string": if val == "i": continue print(val) # output: s, t, r, n, g # notice, no i in the output, but the loop continued after the i y = 3 while y > 0: print(y) y = y - 1 if y == 0: break else: # only executes on a clean exit from the while loop (i.e. not a break) print("Final else statement") # output: 3, 2, 1 ########################################################### # FOR LOOPS THROUGH DICTIONARIES # my_dict = { # "name": "Noelle", # "language": "Python", # "type": "Weak" # } # for k in my_dict: # # print(k) # # print(my_dict[k]) # print(k,"is",my_dict[k]) # capitals = { # "Washington":"Olympia", # "California":"Sacramento", # "Idaho":"Boise", # "Illinois":"Springfield", # "Texas":"Austin", # "Oklahoma":"Oklahoma City", # "Virginia":"Richmond"} # # another way to iterate through the keys # for key in capitals.keys(): # print(key) # # output: Washington, California, Idaho, Illinois, Texas, Oklahoma, Virginia # #to iterate through the values # for val in capitals.values(): # print(val) # # output: Olympia, Sacramento, Boise, Springfield, Austin, Oklahoma City, Richmond # #to iterate through both keys and values # for key, val in capitals.items(): # print(key, " = ", val) # # output: Washington = Olympia, California = Sacramento, Idaho = Boise, etc #1. Change the value 10 in x to 15. Once you're done, x should now be [ [5,2,3], [15,8,9] ]. # Change the last_name of the first student from 'Jordan' to 'Bryant' # In the sports_directory, change 'Messi' to 'Andres' # Change the value 20 in z to 30 x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] x[1][0] = 15 #print(x) students[0]['last_name'] = "Bryant" #print(students) sports_directory['soccer'][0] = 'Andres' #print(sports_directory) z[0]['y'] = 30 #print(z) ################################################################################################################################## #2. Iterate Through a List of Dictionaries # Create a function iterateDictionary(some_list) that, given a list of dictionaries, the function loops through each dictionary in the list and prints each key and the associated value. # For example, given the following list: students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary(students): for i in range(1, len(students)): print(f"Student #{i} first name: {students[i]['first_name']}, last name is - {students[i]['last_name']} ") #iterateDictionary(students) # Student #1 first name: John, last name is - Rosales # Student #2 first name: Mark, last name is - Guillen # Student #3 first name: KB, last name is - Tonel ################################################################################################################################## #3. Get Values From a List of Dictionaries # Create a function iterateDictionary2(key_name, some_list) that, # given a list of dictionaries and a key name, the function prints the value stored in that key for each dictionary. # For example, iterateDictionary2('first_name', students) should output: # Michael # John # Mark # KB # And iterateDictionary2('last_name', students) should output: # Jordan # Rosales # Guillen # Tonel no_namers = [ {'name': 'user1', 'last' : 'last1'}, {'name' : 'user2', 'last' : 'last2'}, {'name' : 'user3', 'last' : 'last3'}, ] def iterateDictionary2(key_name, no_namers): for i in range(len(no_namers)): print(no_namers[i][key_name]) #iterateDictionary2('name',no_namers) #iterateDictionary2('last',no_namers) # user1 # user2 # user3 # last1 # last2 # last3 ################################################################################################################################## #4. Iterate Through a Dictionary with List Values # Create a function printInfo(some_dict) that given a dictionary whose values are all lists, prints the name of each key along with the size of its list, # and then prints the associted values within each key's list. For example: dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } def printInfo(some_dictionary): for key, value in some_dictionary.items(): print(f"{len(some_dictionary[key])} {key.upper():}") for item in some_dictionary[key]: print(item) printInfo(dojo) # output: # 7 LOCATIONS # San Jose # Seattle # Dallas # Chicago # Tulsa # DC # Burbank # 8 INSTRUCTORS # Michael # Amy # Eduardo # Josh # Graham # Patrick # Minh # Devona
c29db44630a67380246aaf0f65aefaba0f85135d
mrshakirov/LeetCode
/30-Day LeetCoding Challenge/Week 1/Counting Elements 2v.py
708
3.84375
4
#https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3289/ from typing import List import collections class LeetCode: def countElements(self, arr: List[int]) -> int: result = 0 dict = {} for i in arr: if i in dict: dict[i] += 1 else: dict[i] = 1 for item in dict: if item + 1 in dict: if dict[item] > dict[item + 1]: result += dict[item] else: result += min(dict[item + 1], dict[item]) return result l = LeetCode() print(l.countElements([1,1,2])) # Complexity O(N^2) + N = O(N^2)
3ab3768c19874720b561e025150fa10ae19b3533
rrybar/pyCourseScripts
/SMRdemos/SMRdemos/Python3xDemos/smr_mapfilter.py
203
3.5625
4
#!/usr/bin/env python string_data = [ '-1', '0', '1', '2'] ints = map(int, string_data) doubled = map(lambda x: x * 2, ints) positives = filter(lambda x: x > 0, doubled) for n in positives: print (n)
32af9164a88870165264149d219d1f1e5a3ed7f6
huanzhizhixing/Learn-Python-The-Hard-Way
/ex21.py
1,071
4.09375
4
# -*- coding: utf-8 -*- def add(a,b):#这里的冒号经常丢 print "Adding %d +%d " % (a,b) #缩进出现错误。这里好多次了,总是改一下就行,不知怎么回事。以后试试tab return a + b def subtruct(a,b): print "Subtructing %d - %d" % (a,b) return a - b #这个函数一方面是赋值,另一方面是打印!实现了两个功能! def multiply(a,b): print "Multiply %d * %d" % (a,b) return a * b def divide(a,b): #这里的d前面多打了个乘号。 print "Dividing %d /%d" %(a,b) return a /b print "Let's do some math with just functins!" age = add(30,5) #subtruct打成了subtract height = subtruct(78,4) #weight的打印错误。 weight = multiply(90,2) iq = divide(100,2) print "Age: %d, Subtructing: %d, Multipyl: %d, Dividing: %d." % (age,height,weight,iq) #A puzzle for the extra credit,type it in anyway. print "Here is a puzzle." what = add(age, subtruct(height,multiply(weight,divide(iq,2)))) #subtruct的打印错误。 print "That becomes: ", what, "Can you do it by hand?"
677c63290691170de6fdbb271c3d6d3a06f12795
dhawal123456/Regex-Hackerrank
/Utopian Identification Number
209
3.578125
4
import re p = re.compile('^[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}') n = int(input()) for i in range(n): x = str(input()) if(len(re.findall(p, x)) > 0): print("VALID") else: print("INVALID")
999196f569da9be2ba5e6b7edeaaab7b146f8032
MaryBeth8/Stand-alone-docs
/loops-greetings.py
566
4.34375
4
"""Adds the string 'Hello, ' in front of each name in names and appends the greeting to the list. Returns the new list containing the greetings. """ #version1 def add_greetings(names): greetings = [] for name in names: greetings.append('Hello, ' + name) return greetings print(add_greetings(["Owen", "Max", "Sophie"])) #returns a list of greetings [...] #version2 def add_greetings(names): greetings = [] greetings.append(['Hello, ' + name for name in names]) return greetings #returns a list of greetings inside the list greetings [[...]]
2f1e04bfad44e2cbbafdbedb4e4f1be5402f6326
SchoBlockchain/ud_isdc_nd113
/8. Computer Vision and Classification/Temp/helpers_anim_1.py
6,394
3.625
4
""" Given a list of standardized images (same size), 1. It crops (given) 2. Creates separate red,yellow,green lists based on attached labels 3. Creates HSV for each image and display all as an animation This helps to get a overview of HSV variations for all images instead of having to go through one by one Author: parthi292929@gmail.com Web: https://www.rparthiban.com/articles/blog/ License: Please quote me, that should suffice. Date: 3rd Jun 2018 Usage: To be used in ipython environment (not tested in others/shells) Issues: It is slow. (takes 5 minutes). Trying to optimze.Check below link. https://stackoverflow.com/questions/50656118/matplotlib-funcanimation-execution-time-too-long?noredirect=1#comment88327194_50656118 """ import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc #import time import cv2 #from loaders import STANDARDIZED_LIST # 3 rows, 4 cols f, axArray = plt.subplots(3, 4, figsize=(11,5.5)) # MATPLOTLIB 'NOTEBOOK' BACKEND SPECIFIC #rc('animation', html='html5') #plt.rcParams["animation.html"] = "jshtml" f.tight_layout() # http://tiny.cc/adjust-subplot-spaces # --------------------- PREPROCESSING HELPER FUNCTIONS ---------------------- def crop(image_list): """ crop 5 px on either side vertically """ image_cropped_list = [] for each_image_label_pair in image_list: image = each_image_label_pair[0] image_cropped = image[:, 5:-5, :] image_cropped_list.append((image_cropped, each_image_label_pair[1])) return image_cropped_list # create separate list images for each channel def create_separate_lists(image_list): """ Returns 3 separate list of each label (so no label attachment) """ r_list = [] y_list = [] g_list = [] for each_image_label_pair in image_list: image = each_image_label_pair[0] label = each_image_label_pair[1] # one hot encoded if label[0] == 1: # red r_list.append(image) elif label[1] == 1: # yellow y_list.append(image) else: # green g_list.append(image) return (r_list, y_list, g_list) # ----------------- ANIMATION SECTION ------------------------------ # TO VIEW ALL THE PREPROCESSED IMAGES AT ONCE.. # calculate histogram def hsv_histograms(rgb_image): # Convert to HSV hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) # Create color channel histograms h_hist = np.histogram(hsv[:,:,0], bins=32, range=(0, 180)) s_hist = np.histogram(hsv[:,:,1], bins=32, range=(0, 256)) v_hist = np.histogram(hsv[:,:,2], bins=32, range=(0, 256)) # Generating bin centers bin_edges = h_hist[1] bin_centers = (bin_edges[1:] + bin_edges[0:len(bin_edges)-1])/2 return bin_centers, h_hist, s_hist, v_hist # initiate artists once def initArtists(): """ To optimize performance, we use same artists, so they have to be initialized/created once like below and then re use in animation loop """ axArtistsArray = [[plt.plot([],[]) for _ in range(4)] for _ in range(3)] first_image_lists = [r_list[0], y_list[0], g_list[0]] for i in range(3): # 3 rows (bin_centers, h_hist, s_hist, v_hist) = hsv_histograms(first_image_lists[i]) axArtistsArray[i][0] = axArray[i][0].imshow(first_image_lists[i]) axArtistsArray[i][1] = axArray[i,1].bar(bin_centers,h_hist[0]) # bar(x, height) axArtistsArray[i][2] = axArray[i,2].bar(bin_centers,s_hist[0]) axArtistsArray[i][3] = axArray[i,3].bar(bin_centers,v_hist[0]) axArray[i,1].set_xlim(0,180) axArray[i,2].set_xlim(0,256) axArray[i,3].set_xlim(0,256) axArray[0,1].set_title('H channel') axArray[0,2].set_title('S channel') axArray[0,3].set_title('V channel') return axArtistsArray # animation function. This is called sequentially def animate(i): # ensure no out of range in each lists r_index = i % len(r_list) y_index = i % len(y_list) g_index = i % len(g_list) first_image_lists = [r_list[r_index], y_list[y_index], g_list[g_index]] for row_index in range(3): # 3 rows: 0, 1, 2 # image col_index = 0 image = first_image_lists[row_index] axArtistsArray[row_index][col_index].set_data(image) (bin_centers, h_hist, s_hist, v_hist) = hsv_histograms(image) # H channel col_index = 1 for each_bar_height, each_bar in enumerate(axArtistsArray[row_index][col_index]): each_bar.set_height(h_hist[0][each_bar_height]) # S channel col_index = 2 for each_bar_height, each_bar in enumerate(axArtistsArray[row_index][col_index]): each_bar.set_height(s_hist[0][each_bar_height]) # V channel col_index = 3 for each_bar_height, each_bar in enumerate(axArtistsArray[row_index][col_index]): each_bar.set_height(v_hist[0][each_bar_height]) """ axArtistsArray[0][0].set_data(r_list[r_index]) axArtistsArray[1][0].set_data(y_list[y_index]) axArtistsArray[2][0].set_data(g_list[g_index]) """ return (axArtistsArray,) # ----------------- PRE PROCESSING SECTION --------------------------- def getHSVAnimPlots(STANDARDIZED_LIST): global axArtistsArray global r_list, y_list, g_list print('Total No of given images: {}'.format(len(STANDARDIZED_LIST))) print('Processing..') # CROP THE IMAGES STANDARDIZED_CROPPED_LIST = crop(STANDARDIZED_LIST) # create separate lists for each label (r_list, y_list, g_list) = create_separate_lists(STANDARDIZED_CROPPED_LIST) #print(len(r_list), len(y_list), len(g_list)) # get max length (list which has max no of images) max_list = max([len(r_list), len(y_list), len(g_list)]) # INITIATE ARTISTS axArtistsArray = initArtists() #plt.subplots_adjust(hspace=None) # call the animator. #start_time = time.time() anim = animation.FuncAnimation(f, animate, frames=np.arange(0,max_list), interval=1000, blit=False) plt.close() # to avoid an additional empty plot which we do not want to see return anim.to_html5_video()
a30d60601344eff3e45ec523f535102f928fdba9
malikumarhassan/python
/loopexample.py
438
3.953125
4
count = 0 while (count <= 3) : print(count) count =count + 1 print('loops end') count = 0 while(count <=3): print(count) count = count + 1 else : print('while loop ends') count = 0 while(count <=3): print(count) count = count + 1 if (count ==2): print('if cond for 2') else : print('while loop ends') n= 4 for i in range(0,n): print(i) print('loops end')
7c619a5368e0691a4393f6f527e2e2b776ba6e79
ShubhamNagarkar/Pegasus_workflows
/Workflow_3/separate.py
596
3.8125
4
#!/usr/bin/env python3 import glob def separate(odd, even): """ separates numbers from the files into even and odd numbers. returns odd_nums.txt and even_nums.txt """ for filename in glob.glob("nums*.txt"): f = open(filename,"r") for line in f: num = line.strip("\n") if int(num)%2==0: even.write(num+"\n") else: odd.write(num+"\n") even.close() odd.close() if __name__ == "__main__": odd = open("odd_nums.txt","a") even = open("even_nums.txt","a") separate(odd, even)
49cea55f4ad5a067a1b8467aea66eab19d57535f
jisshub/python-development
/pythonAdvanced/stack_queues.py
760
4.21875
4
# stack and queue operations using list # numbers = [] # # stack # numbers.append(30) # numbers.append(16) # numbers.append(15) # numbers.append(13) # print(numbers) # # # pop in list # # numbers.pop() # # print(numbers) # # # add an element # numbers.append(77) # # print(numbers) # # # pop # numbers.pop() # print(numbers) # stack and queue operation using deque from _collections import deque print(deque) # deque is an object of collection class # initialize a deque numbers = deque() numbers.append(55) numbers.append(52) numbers.append(54) numbers.append(56) numbers.append(57) print(numbers) # pop from deque numbers.pop() print(numbers) numbers.append(90) print(numbers) print(numbers.popleft()) print(numbers.popleft()) print(numbers.popleft())
2b4f3f7b53c933d5d8ac743158a43f1bad2dfb1c
anjor/Coding-Problems
/elevation/elevation_study.py
2,403
3.75
4
#!/usr/bin/python ''' Solution to the Farmers' elevation problem''' class Tile: '''Defines a Tile class which contains the co-ordinates of the cell, along with its height''' def __init__(self, x, y, ht): '''Default constructor for Tile Class''' self.x = x self.y = y self.ht = ht self.minNbr = None def setminNbr(self, mNbr): '''Sets the minNbr variable''' self.minNbr = mNbr def getSink(self): '''Returns the Sink corresponding to self''' curr = self if not curr.minNbr: return curr else: return curr.minNbr.getSink() def nbrs(i, j, els): '''Returns all Tiles neighboring to (i,j). Current implementation returns top, bottom, right and left tiles. ''' ns = [] for temp in [els[i][iy] for iy in [j-1, j+1] if 0<= iy< n]: ns.append(temp) for temp in [els[ix][j] for ix in [i-1, i+1] if 0<= ix< n]: ns.append(temp) return ns def FlowsTo(i, j, els): '''Returns the Tile to which water flows from the current Tile''' minT = min(nbrs(i, j, els), key=lambda T:T.ht) if els[i][j].ht > minT.ht: return minT else: return None if __name__ == '__main__': import sys from collections import Counter try: datafile = sys.argv[1] # Input data f = open(sys.argv[1], 'r') n = int(f.readline()) hts = [] for line in f: hts.append(map(int, line.strip().split(' '))) f.close() # Construct an array of Tiles from the input data els = [[[] for i in range(n)] for i in range(n)] for i in xrange(n): for j in xrange(n): els[i][j] = Tile(i, j, hts[i][j]) # Calculate the direction of water flow for each cell for i in xrange(n): for j in xrange(n): els[i][j].setminNbr(FlowsTo(i, j, els)) # Find corresponding sink for each cell sinks = [] for i in xrange(n): for j in xrange(n): s = els[i][j].getSink() sinks.append((s.x, s.y)) # Use built-in Counter function to output sizes of the basin for values in Counter(sinks).values(): print values, print except: print 'Something went wrong!'
a3f81e16de0ed6351f21d8ebc049079dbbacf8eb
Jegardo/ML-Prwto
/MultipleReg/main.py
914
4.15625
4
import pandas from sklearn import linear_model df = pandas.read_csv("cars.csv") # Independent values in a variable called X: X = df[['Weight', 'Volume']] # Dependent values in a variable called y: y = df['CO2'] # The method called fit() takes the independent and dependent # values as parameters and fills the regression object with # data that describes the relationship: regr = linear_model.LinearRegression() regr.fit(X, y) # Predict the CO2 emission of a car where the weight is 2300kg, # and the volume is 1300cm3: predictedCO2 = regr.predict([[2300,1300]]) print(predictedCO2) # The coefficient is a factor that describes the relationship # with an unknown variable # In this case, we can ask for the coefficient value of weight against # CO2, and for volume against CO2. # The answers we get tells us what would happen if we increase, # or decrease, one of the independent values. print(regr.coef_)
630f26bb29231f175fd37416adffbd627799c9dc
dpuman/CodeWithMoshPython
/CompleteCodewMOsh/Randoms/ClassVsInstanceMethods.py
277
3.75
4
class Point: default_color = 'Red' def __init__(self, x, y): self.x = x self.y = y @classmethod def zero(cls): return cls(12, 0) def print_It(self): print(f"{self.x} and {self.y}") point = Point.zero() point.print_It()
06e598236978d7056aa8072a84d42d8c9826eef4
olibyte/automation
/selenium/get_name.py
283
3.671875
4
#locate elements by their HTML name attribute from selenium import webdriver driver= webdriver.Chrome() driver.get("file:///C:/Users/ocben/automation/selenium/page.html") username = driver.find_element_by_name('username') print("My input element is:") print(username) driver.close()
7ee96a7d5e0522c70380904b99438a4c4a3e3d3f
evgeniyv6/fotor38
/ya_runup/algorithms/matrix_diag_sum.py
415
3.8125
4
#!/usr/bin/env python ''' 1 2 3 4 5 6 7 8 9 ''' def matrix_sum_diag(l: list) -> int: ''' :param l: list of lists :return: sum of main and opposite diagonals ''' n = len(l) sum = 0 for i in range(n): sum += l[i][i] + l[i][n-i-1] if n % 2 == 1: sum -= l[n // 2][n // 2] return sum if __name__ == '__main__': print(matrix_sum_diag([[1,2,3],[4,5,6], [7,8,9]]))