blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
59f433735cee173fe74b129c407412c5061e4464
chursunov/GB-python-homework
/lesson4/homework4_1.py
1,079
3.640625
4
""" Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. """ import sys try: file, hour_job, tariff, bonus = sys.argv except ValueError: print("Вы должны указать 3 параметра (выработка в часах, ставка, премия)!") exit() def salary(hour_job, tariff, bonus): return hour_job * tariff + bonus print(f"Выработка в часах - {hour_job} ч.\nСтавка в час - {tariff} р.\nПремия - {bonus} р.") result_salary = salary(int(hour_job), int(tariff), int(bonus)) print(f"Зарплата сотрудника - {result_salary} р.")
dd84ae2d957617072f57a8ee3030158ea4c88120
davidokun/python-blockchain-app
/basics/lists.py
187
3.625
4
my_list = [1, 'Hi', 2.54] print(my_list) print(my_list[1]) my_list.append(3) print(my_list) print(my_list.pop()) print(my_list) def my_function(): print('Hallo') my_function()
bca52cd29a2e410354b7facb22d898867fdb0ca6
nirantak/programming-exercises
/Misc/street_lights.py
1,491
3.75
4
""" Street Lights, refer street_lights.md for the question. """ from itertools import combinations from typing import Dict, List, Tuple def main(data: List[List[Tuple[int, int]]]) -> List[float]: result: List[float] = [] for d in data: total_area: float = 0.0 int_area: float = 0.0 lights: List[Dict[str, int]] = [] for i in d: p, h = i area = h ** 2 lights.append( {"x1": p - h, "y1": 0, "x2": p + h, "y2": 0, "x3": p, "y3": h} ) total_area += area for l in combinations(lights, 2): int_area += ( max( 0, min(l[0]["x2"], l[1]["x2"]) - max(l[0]["x1"], l[1]["x1"]) ) / 2 ) ** 2 result.append(float(total_area - int_area)) return result if __name__ == "__main__": t: int = int(input("Enter number of tests: ")) data: List[List[Tuple[int, int]]] = [] for i in range(t): n = int(input(f"\nEnter number of lights (Test {i+1}): ")) lights: List[Tuple[int, int]] = [] for j in range(n): p, h = map( int, input(f"Enter position & height of light {j+1}: ").split() ) lights.append((p, h)) data.append(lights) result = main(data) print("*** Area Covered by Street Lights ***") print("\n".join([f"Test {i}: {area}" for i, area in enumerate(result, 1)]))
aa760d5a732aac746505c5c57e1467eeabffae39
ChenQianPing/PythonDay1
/py01.py
1,141
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # 根据给定的年月日以数字形式打印出日期 months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'Auguest', 'September', 'October', 'November', 'December' ] print months # 以1~31的娄字作为结尾的列表 endings = ['st','nd','rd'] + 17 * ['th']\ + ['st','nd','rd'] + 7 * ['th']\ + ['st'] print endings year = raw_input('Year:') month = raw_input('Month(1-12):') day = raw_input('Day(1-31):') month_number = int(month) day_number = int(day) # 记得要将月份和天数减1,以获得正确的索引 month_name = months[month_number-1] ordinal = day + endings[day_number-1] print month_name + '' + ordinal + ',' + year # September18th,1981 """ # 分片示例 # 对http://www.something.com形式的URL进行分割 print len('http://www.') # 11 print len('.com') # 4 url = raw_input('Please enter the URL:') # 11: http://www. # -4: .com domain = url[11:-4] print "Domain name:" + domain # Please enter the URL:http://www.baidu.com # Domain name:baidu
59921ebd28ce025bb54f70528de2ae475931d046
9886767077/python_tutorial
/Class 5/whileloop_n_times.py
181
3.875
4
fruit name = input("enter your favo fruit : {}") n = int(input("Enter loop no u wana print: ")) i=0 while(i!=n) i=i+1 print("loop is no:{}".format(i)) print(fruit name)
66e5844390dcc52a12be41649e35a0eab66cd40c
haekyu/python_tutoring_kh
/0919/hw_sol/0919_4_stars.py
470
3.546875
4
def prt_stars(): # For upper triangle for i in range(1, 6): # For the left triangle prt_str = (' ' * (5 - i)) + ('*' * i) # For the right triangle prt_str += ('*' * i) + (' ' * (5 - i)) print(prt_str) # For the lower triangle for i in range(4): # For the left triangle prt_str = (' ' * (i + 1)) + ('*' * (4 - i)) # For the right triangle prt_str += ('*' * (4 - i)) + (' ' * (i + 1)) print(prt_str) if __name__ == '__main__': prt_stars()
3a3ffc3fcde756b1d488b1e9acd7dbb5f128423c
malwadkarrk/Python
/stringslicing.py
167
4.09375
4
string = input("Enter string: ") firsttwo = string[:2] lasttwo = string[-2:] print(firsttwo) print(lasttwo) print("Firsttwo + lasttwo is: ", firsttwo + lasttwo)
9d0233194ae77e157c6bf9e8684c9a826017ff53
Geeoon/PythonSorting
/PythonSorting/PythonSorting.py
3,919
4.0625
4
import random import math from timeit import default_timer as timer comparisons = 0 swaps = 0 def getSize(): size = int(input("Size of list: ")) while (size <= 1): print("The list must have a size greater than 1") size = int(input("Size of list: ")) return size def printElements(list): for index in list: print(index , end =" ") print() def populatelist(list): for index in range(0, len(list)): list[index] = index+1 def scramblelist(list): for index in range(0, len(list)): swapElements(list, index, random.randint(0, len(list) - 1)) def swapElements(list, index1, index2): global swaps list[index1], list[index2] = list[index2], list[index1] swaps += 1 def bogoSort(list): global comparisons islistSorted = True for index in range(1, len(list)): comparisons += 1 if (list[index-1] > list[index]): islistSorted = False return while islistSorted == False: islistSorted = True for index in range(0, len(list)): swapElements(list, index, random.randrange(0, len(list))) for index in range(1, len(list)): comparisons += 1 if (list[index-1] > list[index]): islistSorted = False printElements(list) print("\nComparisons: " + str(comparisons) + "\nSwaps: " + str(swaps) + "\n") def bubbleSort(list): global comparisons islistSorted = False while islistSorted == False: islistSorted = True for index in range(1, len(list)): comparisons += 1 if (list[index-1] > list[index]): islistSorted = False swapElements(list, index-1, index) printElements(list) print("\nComparisons: " + str(comparisons) + "\nSwaps: " + str(swaps) + "\n") def insertionSort(list): global comparisons for i in range(1, len(list)): j = i comparisons += 1 while (j > 0) and (list[j-1] > list[j]): comparisons += 1 swapElements(list, j-1, j) j -= 1 def mergeSort(list): list = mergeDivide(list) printElements(list) def mergeDivide(list): end = math.ceil(len(list) / 2) list1 = list[0:end] list2 = list[end:len(list)] if (len(list1) > 1 or len(list2) > 1): return mergeConquer(mergeDivide(list1), mergeDivide(list2)) else: return mergeConquer(list1, list2) def mergeConquer(list1, list2): global comparisons listF = list1 + list2 size = len(listF) pos1 = 0 pos2 = 0 i = 0 while (i < size): if (pos1 >= len(list1)): for i in range(i, size): listF[i] = list2[pos2] pos2 += 1 elif (pos2 >= len(list2)): for i in range(i, size): listF[i] = list1[pos1] pos1 += 1 elif (list1[pos1] > list2[pos2]): comparisons += 1 listF[i] = list2[pos2] pos2 += 1 elif (list1[pos1] < list2[pos2]): comparisons += 1 listF[i] = list1[pos1] pos1 += 1 else: listF[i] = list1[pos1] i += 1 listF[i] = list2[pos2] pos1 += 1 pos2 += 1 i += 1 return listF def quickSort(list): list = quickDivide(list) printElements(list) def quickDivide(list): pvt = quickPivot(list) list1 = list[0:pvt-1] list2 = list[pvt+1:list[len(list) - 1]] if (len(list) > 2): return quickConquer(quickDivide(list1), quickDivide(list2), list[pvt]) else: return quickConquer(list1, list2, list[pvt]) def quickConquer(list1, list2, pvt): listF = list1 + [pvt] + list2 return listF def quickPivot(list): middle = math.floor(len(list) / 2) pvtList = [list[0], list[middle], list[-1]] insertionSort(pvtList) list[0] = pvtList[0] list[middle] = pvtList[middle] list[-1] = pvtList[-1] print(pvtList) print("asdfasdfasdf") printElements(list) return middle size = getSize() print("Generating list...\n") numList = [None] * size populatelist(numList) scramblelist(numList) printElements(numList) print("Sorting list...\n") listt = [1, 2, 3, 4, 5, 6, 7, 8] list1 = [7, 3, 5, 1, 2] list2 = [14, 15, 16, 17] start = timer() mergeSort(numList) end = timer() print("Comparisons: " + str(comparisons) + "\nSwaps: " + str(swaps)) print("Elapsed Time: " + str(end-start) + " seconds (includes time to print)")
5cd74493c20ff43bdb73f2a62e8f38ceb8621532
neapps/Python-3-Tutorial
/2. Control Structures/lists.py
1,171
4.34375
4
# ================================================== # # Materi 1 : Lists #1 words = ["Hello","world","!"] print(words[0]) print(words[1]) print(words[2]) # Hello # world # ! # Soal 1 : What is the result of this code? nums = [5,4,3,2,1] print(nums[1]) # Jawaban 1 : 4 # ================================================== # # Materi 2 : Lists #2 empty_list = [] print(empty_list) # [] # Soal 2 : How many items are in this list? # [2,] # Jawaban 2 : test = [2,] print(test) # 1 # ================================================== # # Materi 3 : Lists #3 number = 3 things = ["string",0,[1,2,number],4.56] print(things[1]) print(things[2]) print(things[2][2]) # 0 # [1,2,3] # 3 # Soal 3 : Fill in the blanks to create a list and print its 3rd element. # list = _42,55,67] # print(list[_]) # Jawaban 3 : list = [42,55,67] print(list[2]) # ================================================== # # Materi 4 : Lists #4 str = "Hello world!" print(str[6]) # w # Soal 4 : Which line of code will cause an error? # num = [5,4,3,[2],1] # print(num[0]) # print(num[3][0]) # print(num[5]) # Jawaban 4 : Line 4 # ================================================== #
18d31941f1320516cab508a8b81ef27cd608f0e9
jingwang622/AID1909
/day06/thead_event.py
512
3.65625
4
""" event 线程互斥方法 × 解决对共享资源的无序使用 """ from threading import Thread,Event # 用于线程间的通信 s = None e = Event() def yang(): print("样子荣前来拜山头") global s s = "天王盖地虎" e.set() t = Thread(target=yang) t.start() print("说对口令就是自己人") print(e.is_set()) e.wait() print(e.is_set()) if s == '天王盖地虎': print("宝塔真和要") print("确认过眼神你是对的人") else: print("打死他") t.join()
618ba8c0a838b8e93bbe0b557db3216ca93c108a
tamatskiv/python
/task9_2.py
3,052
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re amount = input("Enter amount of money with dot): ") def num_to_words(amount): """"This function returns amount of money in words""" digits = { 0: 'нуль', 1: 'одна', 2: 'дві', 3: 'три', 4: 'чотири', 5: 'п\'ять', 6: 'шість', 7: 'сім', 8: 'вісім', 9: 'дев\'ять', 10: 'десять', 11: 'одинадцять', 12: 'дванадцять', 13: 'тринадцять', 14: 'чотирнадцять', 15: 'п\'ятнадцять', 16: 'шістнадцять', 17: 'сімнадцять', 18: 'вісімнадцять', 19: 'дев\'ятнадцять' } dozens = { 2: 'двадцять', 3: 'тридцять', 4: 'сорок', 5: 'п\'ятдесят', 6: 'шістдесят', 7: 'сімдесят', 8: 'вісімдесят', 9: 'дев\'яносто' } hundreds = { 1: 'сто', 2: 'двісті', 3: 'триста', 4: 'чотириста', 5: 'п\'ятсот', 6: 'шістсот', 7: 'сімсот', 8: 'вісімсот', 9: 'дев\'ятсот' } strnumber = str(amount) if amount < 20: return digits[amount] elif amount < 100: if strnumber[-1] == '0': return dozens[int(strnumber[0])] else: return dozens[int(strnumber[0])] + " " + num_to_words(int(strnumber[1])) else: if strnumber[1:3] == '00': return hundreds[int(strnumber[0])] else: return hundreds[int(strnumber[0])] + " " + num_to_words(int(strnumber[1:3])) def split_by_thousands(amount): array = amount.split('.') if len(array[1]) == 1: array[1] = array[1] + '0' kopecks = int(array[1]) hryvnias = int(array[0]) array_thousands = [] array_thousands.append(kopecks) while hryvnias != 0: array_thousands.append(int(hryvnias % 1000)) hryvnias = int(hryvnias/1000) return array_thousands def main(amount): names_of_numbers = { 0: ['копійка', 'копійки', 'копійок'], 1: ['гривня', 'гривні', 'гривень'], 2: ['тисяча', 'тисячі', 'тисяч'], 3: ['мільйон', 'мільйони', 'мільйонів'], 4: ['мільярд', 'мільярди', 'мільярдів'], } arr = split_by_thousands(amount) result = '' for i in reversed(range(len(arr))): result = result + " " + num_to_words(arr[i]) strnum = str(arr[i]) while len(strnum) < 3: strnum = '0' + strnum if re.match(r'.[^1]1', strnum): result = result + " " + names_of_numbers[i][0] elif re.match(r'.[^1][234]', strnum): result = result + " " + names_of_numbers[i][1] else: result = result + " " + names_of_numbers[i][2] return result.strip() print(main(amount))
1ff58a7ff50aeb919becbec28232b09150be47b4
give333/UnivLic
/PIntegrado/factorial.py
233
3.875
4
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) def factorial_i(number): product = 1 for i in range(number): product = product * (i + 1) return product
f423f940022a991fd8fe6746091abb58014b5038
kiranani/playground
/Python3/0222_Count_Complete_Tree_Nodes.py
597
3.765625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def countNodes(self, root: TreeNode) -> int: if root is None: return 0 l = 1 left, right = root.left, root.right while left and right: l += 1 left, right = left.left, right.right if not left and not right: return 2 ** l - 1 else: return 1 + self.countNodes(root.left) + self.countNodes(root.right)
9d02f83a5287c07682b2e1c030a888dc3278f495
sonalipat1/sonalipat1
/square.py
112
3.859375
4
square_of_rec= int(input("enter the number to find square")) square= square_of_rec * square_of_rec print(square)
a6c0ec8d5dc6e63dffd8d0778d225c9a4ec05247
arthur-bryan/python-data-structures
/classes/banco/contas/conta_corrente.py
1,231
3.75
4
from contas.conta_bancaria import ContaBancaria class ContaCorrente(ContaBancaria): def __init__(self, numero, saldo, taxa_de_operacao): super().__init__(numero, saldo) self.__taxa_de_operacao = float(taxa_de_operacao) def __str__(self): return f"Conta Corrente: Número: {self.numero}, Saldo: {self.saldo}, Taxa de operação: R${self.taxa_de_operacao}" def get_taxa(self): return self.__taxa_de_operacao def set_taxa(self, nova_taxa): self.__taxa_de_operacao = nova_taxa def deposito(self, valor): valor_com_taxa = valor - self.__taxa_de_operacao self.saldo += valor_com_taxa print(f"Depósito de R$ {valor} efetuado! Saldo atual é de R$ {self.saldo}." + f" (Taxa: R$ {self.__taxa_de_operacao})") def saque(self, valor): valor_com_taxa = valor + self.__taxa_de_operacao if (self.saldo - valor_com_taxa) >= 0: self.saldo -= valor_com_taxa print(f"Saque de R$ {valor_com_taxa} realizado! Saldo atual: R$ {self.saldo}." + f" (Taxa: R$ {self.__taxa_de_operacao})") else: print(f"Incapaz de realizar saque de R$ {valor_com_taxa}! Saldo disponível: R$ {self.saldo}." + f" (Taxa: R$ {self.__taxa_de_operacao})") return taxa_de_operacao = property(get_taxa, set_taxa)
4eb652fc79a6f0f966b09b11a6ed588ef093a737
makarenko093/Python
/makarenko_eugene_dz_3/task_3_3_4.py
2,929
3.921875
4
"""3. Написать функцию thesaurus(), принимающую в качестве аргументов имена сотрудников и возвращающую словарь, в котором ключи — первые буквы имен, а значения — списки, содержащие имена, начинающиеся с соответствующей буквы. Например: #>>> thesaurus("Иван", "Мария", "Петр", "Илья") { "И": ["Иван", "Илья"], "М": ["Мария"], "П": ["Петр"] } Замечание: Заранее неизвестно сколько фамилий передадут в функцию thesaurus Подумайте: полезен ли будет вам оператор распаковки? Сможете ли вы вернуть отсортированный по ключам словарь?""" def thesaurus(*args): a_dict = {} for el in sorted(args): if el[0] in a_dict: a_dict[el[0]].append(el) else: a_dict[el[0]] = [el] return a_dict print(thesaurus("Иван", "Иария", "Петр", "Илья", "Андрей", "Ядвига")) """ 4. * (вместо задачи 3) Написать функцию thesaurus_adv(), принимающую в качестве аргументов строки в формате «Имя Фамилия» и возвращающую словарь, в котором ключи — первые буквы фамилий, а значения — словари, реализованные по схеме предыдущего задания и содержащие записи, в которых фамилия начинается с соответствующей буквы. Например: >>> thesaurus_adv("Иван Сергеев", "Алла Сидорова", "Инна Серова", "Петр Алексеев", "Илья Иванов", "Анна Савельева", "Василий Суриков") { 'А':{ 'П': ['Петр Алексеев']}, 'И': { 'И': ['Илья Иванов']}, 'С': { 'А': ['Алла Сидорова', 'Анна Савельева'], 'В': ['Василий Суриков'], 'И': ['Иван Сергеев', 'Инна Серова']}} Сможете ли вы вернуть отсортированный по ключам словарь?""" def thesaurus_adv(*args): a_dict = {} for el in sorted(args, key=lambda l: ((l[l.index(" ") + 1]), l[0])): if el[el.rindex(" ") + 1] in a_dict: if el[0] in a_dict[el[el.rindex(" ") + 1]]: a_dict[el[el.rindex(" ") + 1]][el[0]].append(el) else: a_dict[el[el.rindex(" ") + 1]].update({el[0]: [el]}) else: a_dict[el[el.rindex(" ") + 1]] = {el[0]: [el]} return a_dict for key, val in thesaurus_adv("Иван Сергеев", "Алексей Алексеев", "Алла Сидорова", "Инна Серова", "Петр Алексеев", "Илья Иванов", "Анна Савельева", "Василий Суриков").items(): print(f"{key}:") for key2, val2 in val.items(): print(f" {key2}:\n {val2}")
0b69299b47cfc341f427a407cc013bf54c89beaa
manlyjpanda/Primary-Seven-Python
/fortune bot.py
3,748
4.40625
4
#fortune cookie bot #before we start the programme, we ask python to get all the packages we need #random allows us to pick a random fortune later #time allows us to pause between outputs #pyttsx3 is the package that does speech for us. We will ask it to start up and will close it down later import random import time import pyttsx3 engine = pyttsx3.init() #first, find out the user's name, then store the name in the variable "name" #we tell the computer what to say aloud by using engine.say, then we tell it to go ahead and say it with engine.runAndWait() engine.say("Hello! What is your name?") print("Hello, what is your name?") engine.runAndWait() name = input() #tell the user how many letters are in their name print("Hello, " + name) engine.say("Hello, " + name) time.sleep(1) print("Did you know you have " +str(len(name)) +" letters in your name?") engine.say("Did you know you have " +str(len(name)) +" letters in your name?") engine.runAndWait() time.sleep(1) print("...") print("Oh, you did, huh?") engine.say("Oh, you did, huh?") engine.runAndWait() time.sleep(1) #creates a variable based on input and checks to see if it's yes or no #then introduces the fortune with varying degrees of snark engine.say("Ok, then. Do you want me to tell your fortune?") engine.runAndWait() fortune = input("Ok, then. Do you want me to to tell your fortune? ") if fortune == "yes": print("FANTASTIC, I love reading lyrics to people!!!!") engine.say("fantastic, I love reading lyrics to people!") engine.runAndWait() time.sleep(3) elif fortune == "no": print("Listen here, bucko. I came here to chew gum and tell fortunes. And I'm fresh out of gum. So why don't you sit down and listen to your fortune, before I knock you down?") engine.say("Listen here, bucko. I came here to chew gum and read lyrics from popular songs. And I'm fresh out of gum. So why don't you sit down and listen to your song lyric, before I knock you down?") engine.runAndWait() time.sleep(1) while fortune not in ("yes", "no"): engine.say("Answer yes or no, please, using only lower case letters. I'm not that smart a programme.") engine.runAndWait() fortune = input("Answer yes or no, please") if fortune == "yes": print("I'm so happy. I'm glad I understand you now.") engine.say("I'm so happy. I'm glad I understand you now.") engine.runAndWait() time.sleep(2) elif fortune == "no": print("Right, you little squirt. You'll get your fortune whether you like it or not.") engine.say("Right, you little squirt. You'll get your fortune whether you like it or not.") engine.runAndWait() time.sleep(1) #looks for a fortune from a txt file called lines.txt and prints it out #lines.txt needs to be in the same place this programme is stored print("Ok, " + name) engine.say("Ok, " + name) engine.runAndWait() print("I'm computing your fortune now.") engine.say("I'm computing your fortune now.") engine.runAndWait() time.sleep(3) print("(please imagine mystical noises)") engine.say("(please imagine mystical noises)") engine.runAndWait() time.sleep(2) #this is where the programme reads the file and picks a random line fileobj = open('fortune.txt','r') line = random.choice(fileobj.readlines()) fileobj.close() print (line) engine.say(line) engine.runAndWait() time.sleep(2) #good manners engine.say("Thanks for playing with me. It's someone else's turn now.") engine.runAndWait() print ("Thanks for playing with me. It's someone else's turn now.") #we stop the speech package and exit the programme. engine.stop() time.sleep(7) exit
cf5ce7a77e6af1617435b9c298397147fd8374f1
tkhunlertkit/cs361f18
/Lab 3/Quiz/quiz.py
172
4.1875
4
prime = int(input('Enter a number: ')) for i in range(2, prime): if prime % i == 0: print('this not is prime, it is divisible by: ', i) print('this is prime')
5c1b5030e9ae2d605824743ffa92901f4033e052
leandro-hl/python
/tp_integrador/EjAdicionales/Ej1Prog2.py
483
3.796875
4
# Programa 2: Crear una lista al azar, luego informar para cada valor, cuántas veces se repite. # El informe No debe repetir el número. (Aca si se debe usar count) import FnGenLst def main(): lista = FnGenLst.generarLista(20, 1, 10) listaInformados = [] for x in lista: if x not in listaInformados: print(f"El elemento {x} se repite {lista.count(x)} veces.") listaInformados.append(x) if __name__ == "__main__": main()
293515a4b6e8f29a06c153a90f7a12420edbd63b
arpansahu/LinkedListPython
/singly linked list/Remove_duplicates_from_a_Unsorted_linked_list.py
2,312
3.921875
4
class node: def __init__(self, data): self.data = data self.next = None class linkedList: def __init__(self): self.head = None def insertAtStart(self, data): temp = node(data) if self.head is None: self.head = temp else: temp.next = self.head self.head = temp def display(self): temp = self.head i = 0 while temp is not None: print("data is {0} node is {1}".format(i, temp.data)) i = i + 1 temp = temp.next def LengthLinkedListIterative(self): temp = self.head count = 0 while temp: count = count + 1 temp = temp.next return count def returnNodeAtPos(self, pos): temp = self.head if pos is 1: return temp else: for i in range(1, pos): temp = temp.next return temp def partition(self, low, upper): pivot = self.returnNodeAtPos(upper).data i = low - 1 for j in range(low, upper): if self.returnNodeAtPos(j).data < pivot: i = i + 1 self.returnNodeAtPos(i).data, self.returnNodeAtPos(j).data = self.returnNodeAtPos(j).data , self.returnNodeAtPos(i).data self.returnNodeAtPos(i+1).data, self.returnNodeAtPos(upper).data = self.returnNodeAtPos(upper).data, self.returnNodeAtPos(i+1).data return (i + 1) def quickSort(self, low, upper): if low < upper: n = self.partition(low, upper) self.quickSort(low, n - 1) self.quickSort(n + 1, upper) def deleteDuplicatesInUnSortedLinkedList(self): self.quickSort(1, self.LengthLinkedListIterative()) temp = self.head while temp.next != None: if temp.data == temp.next.data: temp.next = temp.next.next else: temp = temp.next if __name__ == '__main__': ll = linkedList() ll.insertAtStart(10) ll.insertAtStart(10) ll.insertAtStart(10) ll.insertAtStart(1777) ll.insertAtStart(1777) ll.insertAtStart(122) ll.display() ll.deleteDuplicatesInUnSortedLinkedList() print("after duplicate key deletions") ll.display()
a5fd8ba2026eefb23246235d530069999fe5ccc3
henkess/pycookbook
/tricks.py
470
3.75
4
# # create a list of numbers with comprehention # numbers = [n for n in range(1,10)] # print(numbers) # # list comrehention with condition # numbers1 = [n for n in range(1,10) if n % 2 == 0] # print(numbers1) # # comprehention dictionary # w = "mohammed ali" # lt = {l:w.count(l) for l in w if l !=' '} # print(lt) # # generator # num = (n for n in range(1,6)) # print(num) # print(next(num)) # print(next(num)) # print("==================") # for n in num: # print(n)
4b1705579e11960b9fce8bdeec98b73e9ae866b3
arshadumrethi/Learn-Python-the-hard-way
/ex7.py
565
3.984375
4
print "Mary had a little lamb" print "Its fleece was white as %s." % 'snow' #Snow is in inverted commas to denote it is a string otherwise it would be a Variable print "And everywhere that Mary went." print "." * 10 #this will print out 10 dots end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" #The comma at the end prints the two strings on the same line with a space in between print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12
80b3caecf9ba23be12d9864632257cebed431284
Maryanushka/MITx-6.00.1-2017-
/week6/11. Computational Complexity.py
161
3.625
4
def linearSearch(L, x): for e in L: if e == x: return True return False print(linearSearch([21, 1, 25, 22, 30, 13, 7, 24, 12], 24))
b9d90c3b597f40439cbd0188f6062b3a1205d0d4
ellenlawrence/algorithm-practice
/string_perms.py
530
3.96875
4
import unittest def find_string_perms(s, b): '''Finds all the permutations of smaller string s inside bigger string b.''' for i in range(len(b) - len(s) - 1): class TestStringPerms(unittest.TestCase): def test_find_string_perms(self): '''Test that the string permutation function is returning the correct number of permutations.''' result = find_string_perms('abbc', 'cbabadcbbabbcbabaabccbabc') self.assertEqual(result, 7) if __name__ == '__main__': unittest.main()
0e8f0190415e79ea097bf9725fa5258fd690c6f8
iamaaditya/Project-Euler
/027.py
1,327
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 14 20:13:05 2014 @author: aaditya prakash """ import utilities import math import time problem_number = '027' problem_statement = """ Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ def Prod_coeff_most_primes(aLimit, bLimit): """ Returns the product of coeffficient of the quadratic formula x^2 + ax + b where for values of from 0 produces most number of consecutive primes, with a limited to aLimit and llly b """ longestChain = 0 aLongest = 0 bLongest = 0 for a in xrange(-1*aLimit + 1, aLimit): for b in xrange(-1*bLimit +1, bLimit): chain = 0 for i in xrange(max(aLimit, bLimit)): eqn = i*i + a*i + b if eqn < 0 : break if i==a and a==b: break if(utilities.isPrime(eqn)): chain += 1 else: break if(chain > longestChain): longestChain = chain aLongest = a bLongest = b return aLongest*bLongest timeStart = time.clock() print(Prod_coeff_most_primes(1000,1000)) print('Time (sec):' + str(time.clock() - timeStart)) answer = '-59231'
caf985ee4dd1d8ce25dd65947282d8e2b1522ff6
gonsva/Python-week
/entertemp.py
146
4.0625
4
T=input("Enter today's Temperature:") temp=int(T) if temp>40: print("It is extreamly warm my friend! How warm?") if temp<40: print("It is cold")
199672ace9991c63e76cd2c4b2dfa970a9482fb5
GlassWall/leetcode
/graphs/bfs/robot_in_maze.py
1,019
3.796875
4
def robot_traverse(maze,a,b,k1): maze = [[0 for i in range(b)] for i in range(a)] q = [[0,0,0]] visited = [[False for j in range(b)] for i in range(a)] visited[0][0] = True path_dict = {} while q: x,y,k,px,py = q.pop(0) if k==k1 and x==a-1 and y == b-1: return True if x-1>=0 and visited[x-1][y] == False: visited[x-1][y] = (x,y) q.append([x-1,y,k+1]) if x+1<a and visited[x+1][y] == False: visited[x+1][y] = (x,y) q.append([x+1,y,k+1]) if y-1>=0 and visited[x][y-1] == False: visited[x][y-1] = (x,y) q.append([x,y-1,k+1]) if y+1<b and visited[x][y+1] == False: visited[x][y+1] = (x,y) q.append([x,y+1,k+1]) test_cases = input() for i in range(int(test_cases)): print("Enter Input") a,b,k = input().split(" ") if robot_traverse(int(a),int(b),int(k)-1): print(1) else: print(0)
92280f864aaf2ab0fb3923dce4cbf3ef6dba8570
Liu-Maria/ISAT252
/lec8.py
2,190
4.59375
5
""" Week 3, lecture 8 """ def my_function(a, b): #you can give them a default value result = a + b #when you see variables a and b, add them together and store the sum in result print('a is', a) print('b is', b) return result #returns the 'result', MUST BE LAST STATEMENT # print(my_function(1, 2)) #will return 3 #ORDER MATTERS ''' Alternative to make it clear print(my_function(b = 2, a = 1)) ''' def my_function(a, b = 0): #you can give them a default value such as b = 0, but it can be overridden when you call the function result = a + b #parameters are local, CANNOT be called outside the function return result # print(my_function(1)+1) #the default is used if nothing else is requested def my_function(a, b = 0): #you can give them a default value such as b = 0, but it can be overridden when you call the function result = a + b print('a is', a) print('b is', b) # print(my_function(1)) #no return, so the answer is none def my_function(a, b = 0): return result result = a + b print('a is', a) print('b is', b) # print(my_function(1, 2)) def calculate_abs(a): #calculated the absolute value of a number if a>0: return a if a<0: return -a # print(calculate_abs(0)) #Not defined to a return # print(calculate_abs('a')) #Wrong data type def calculate_abs(a): if type(a) is str: return('wrong data type') if a>0: return a if a<0: return -a # print(calculate_abs('a')) #Wrong data type #EX 2 # def calculate_sigma(m, n): # outer = n + m # multiple = m - n # result = set() def cal_sigma(m , n): result = 0 for i in range(n, m): result = result + i return result # print(cal_sigma(5, 3)) def cal_pi (m, n): ''' calculate sigma(n, m) ''' result = 1 for i in range(n, m + 1): result = result*i return result # print(cal_pi(5, 3)) ##Ex3 def cal_f(m): if m == 0: return 1 else: return m *cal_f(m-1) print(cal_f(5)) def cal_p(m, n): return cal_f(m)/cal_f(m-n) print(cal_p(5, 3))
b7a58c372b5a5417e8905a526bce64fdefd2d9e3
Pratik-sys/Coding-Problems
/CodingBat/Warmup-2/array123.py
301
3.921875
4
#Given an array of int, return True if # ..1, 2, 3 appears in the array somewhere def array123(nums): for i in range(len(nums) - 2): if nums[i] == 1 and nums[i + 1] and nums[i+2]==3: return True return False print(array123([1,2,3,5,5,4])) print(array123([1,2,5,5,5,4]))
b2096b4d233004bd4754aa9fa8ad2a6b90b7fee1
m4ttbr3da/python-challenge
/PyBank/PyBankBreda.py
3,619
3.9375
4
# Modules import os import csv # Establish file path to budget_data.csv csvpath = os.path.join('Resources', 'budget_data.csv') # Open the budget_data.csv file using CSV module with open(csvpath) as csv_file: budget_data = csv.reader(csv_file, delimiter=',') # Sets the header row header_row = next(budget_data) # Sets lists from the csv file to perform summary calculations upon all_rows = list(budget_data) lists = list(zip(*all_rows)) months = lists[0] profits = [int(p) for p in lists[1]] # Sets a variable for the net total amount of "Profit/Losses" over the entire period, and sums the "Profit/Loss" column total_profit_loss = 0 for row in all_rows: total_profit_loss += float(row[1]) # Creates a variable for the average of the changes in "Profit/Losses" over the entire period net_change = [int(profits[n] - profits[n-1]) for n in range(1,len(profits))] average_monthly_change = sum(net_change) / len(all_rows)-1 # Creates a variable for the greatest increase in profits (date and amount) over the entire period greatest_monthly_profit = 0 most_profitable_month = 0 for row in all_rows: if float(row[1]) > greatest_monthly_profit: greatest_monthly_profit = float(row[1]) most_profitable_month = row[0] # Creates a variable for the greatest decrease in losses (date and amount) over the entire period greatest_monthly_loss = 0 least_profitable_month = 0 for row in all_rows: if float(row[1]) < greatest_monthly_loss: greatest_monthly_loss = float(row[1]) least_profitable_month = row[0] # Print out financial summary to the terminal print(f'FINANCIAL SUMMARY') print(f'___________________________') print(f'Total Months: {len(all_rows)}') if total_profit_loss > 0: print('Total Profit: ${:,.2f}'.format(total_profit_loss)) else: print('Total Loss: $({:,.2f})'.format(total_profit_loss)) if average_monthly_change > 0: print('Average Monthly Change: +${:,.2f}'.format(average_monthly_change)) else: print('Average Monthly Change: $({:,.2f})'.format(average_monthly_change*-1)) print(f'Greatest Monthly Profit Increase: {most_profitable_month} -> ' + '+${:,.2f}'.format(greatest_monthly_profit)) print(f'Greatest Monthly Loss: {least_profitable_month} -> ' + '$({:,.2f})'.format(greatest_monthly_loss*-1)) # Create a text file with the financial summary print(f'FINANCIAL SUMMARY', file=open("financial_summary.txt","w")) print(f'___________________________', file=open("financial_summary.txt","a")) print(f'Total Months: {len(all_rows)}', file=open("financial_summary.txt","a")) if total_profit_loss > 0: print('Total Profit: ${:,.2f}'.format(total_profit_loss), file=open("financial_summary.txt","a")) else: print('Total Loss: $({:,.2f})'.format(total_profit_loss), file=open("financial_summary.txt","a")) if average_monthly_change > 0: print('Average Monthly Change: +${:,.2f}'.format(average_monthly_change), file=open("financial_summary.txt","a")) else: print('Average Monthly Change: $({:,.2f})'.format(average_monthly_change*-1), file=open("financial_summary.txt","a")) print(f'Greatest Monthly Profit Increase: {most_profitable_month} -> ' + '+${:,.2f}'.format(greatest_monthly_profit), file=open("financial_summary.txt","a")) print(f'Greatest Monthly Loss: {least_profitable_month} -> ' + '$({:,.2f})'.format(greatest_monthly_loss*-1), file=open("financial_summary.txt","a"))
660ab2e660a7d235561156484c6635927e035330
superyideng/ee595_software_design_labs
/Lab9/lab9_part1.py
2,726
3.640625
4
import math def read_from(path): """ :param path: str, path of file to be read :return: int, number of nodes list, position information of each node """ f = open(path, 'r') result = list() num = int(f.readline().strip()) for line in f.readlines(): line = line.strip() num_arr = [int(curr) for curr in line.split()] result.append(num_arr[1:]) return num, result def generate_cycle(curdict, n1, n2): """ :param curdict: dict, adjacency list :param n1: int, start node :param n2: int, end node :return: bool, whether or not adding the edge generates a cycle """ if n1 not in curdict.keys() or n2 not in curdict.keys(): return False temp = curdict[n1].copy() visited = set() while len(temp) > 0: node = temp.pop() if node == n2: return True if node in curdict.keys() and node not in visited: temp.extend(curdict[node]) visited.add(node) return False def write_output(path, array): """ :param path: str, path of output file :param array: list :return: void """ f = open(path, 'w') f.write("The total number of edges: " + str(len(array)) + '\n') for e in range(len(array)): f.write(str(array[e][0]) + ' ' + str(array[e][1]) + '\n') f.close() if __name__ == '__main__': # extract input data from file filename = "input_part1.txt" num_cities, city_pos = read_from(filename) # generate distance array whose elem = [start, end, distance between] distances = [] for i in range(num_cities): for j in range(i + 1, num_cities): i_pos = city_pos[i] j_pos = city_pos[j] cur_dist = math.sqrt(math.pow(i_pos[0] - j_pos[0], 2) + math.pow(i_pos[1] - j_pos[1], 2)) distances.append([i, j, cur_dist]) distances.sort(key=lambda dist: dist[2]) # loop over all the distances and decide whether to add to result edges adjacency = {} edges = list() curr_ind = 0 while len(edges) < num_cities - 1: start, end = distances[curr_ind][0], distances[curr_ind][1] if not generate_cycle(adjacency, start, end): start_neighbors = adjacency[start] if start in adjacency.keys() else list() end_neighbors = adjacency[end] if end in adjacency.keys() else list() start_neighbors.append(end) end_neighbors.append(start) adjacency[start] = start_neighbors adjacency[end] = end_neighbors edges.append([start, end]) curr_ind += 1 # write output to "output_part1.txt" write_output("output_part1.txt", edges)
e8673bafdfaa29c0a008e857a71d1cc413921d1e
ianhom/Python-Noob
/Note_2/fordict.py
206
4
4
#!/usr/bin/python d = {'x':1, 'y':2, 'z':3}; for key in d: print key, "corresponds to ", d[key]; # result ''' y corresponds to 2 x corresponds to 1 z corresponds to 3 ''' # Why is y-x-z order???
48e8a24441f9ca9a9614220f7b24fb13a67a1e58
HS1VT/graph-processing-with-python-mapreduce-parallel-bfs
/Part_3/a_[20_points]/plot.py
387
3.546875
4
import matplotlib.pyplot as plt x=[1,0,2.14,3.17,1.67,1.43,2.6,2.9,4.2,1.2,1.96,3.58] y=[5,3,8,9,6,5,8,7,15,5,7,12] for i in range(1,89): x.append(int(0)) for j in range(1,45): y.append(int(3)) for j in range(45,54): y.append(int(2)) for j in range(54,89): y.append(int(4)) plt.scatter(x,y,c="blue") plt.xlabel=("Average Distance") plt.ylabel=("Time in sec") plt.show()
c3842ea30cc12e0ad6aa3ac9f432f22483c29ba8
MD6338/Python
/tut15.py
437
3.78125
4
# File IO """ "r" - Used to read file - default mode "w" - Used for writing in file "x" - Used to create file if not exists "a" - Used for appending content in file "t" - Text mode - default mode "b" - Binary mode "+" - Read and write """ from os import path f = open("ch.txt") # co = f.read(6) # print("haha", co) # print(co) # for l in f: # print(l) # print(f.readline()) print(f.readlines()) # print(f.read()) f.close()
de9259b5fba14e66a90e145bebda2799cb73b15e
anton2mihail/Country-Catalogue
/country.py
1,560
4.25
4
"""This class creates a country object with attributes that include name, population, and area""" # Programmer: Anton Mihail Lachmaniucu # Date: 2017-11-28 # Creation of the class and the instance variables class Country(): def __init__(self, name="", pop = 0, area=0.00, continent=""): self._name = name.title() self._pop = pop self._area = area self._cont = continent.title() # Returns the name of the current Country object def getName(self): return self._name # Returns the population of the current Country object def getPopulation(self): return self._pop # Returns the area of the current Country object def getArea(self): return round(self._area, 2) # Returns the continent of the current Country object def getContinent(self): return self._cont # Sets a new population for the current Country object def setPopulation(self, pop): self._pop = pop # Sets a new area for the current Country object def setArea(self, area): self._area = area # Sets a new continent for the current Country object def setContinent(self, cont): self._cont = cont.title() # Calculates and returns the population density of the current Country object def getPopDensity(self): return round(self._pop/self._area, 2) # Creates a string representation of the Country object def __repr__(self): nm = self._name + " (pop:" + str(self._pop) + ", size:" + str(self._area) + ") in " + self._cont return nm
42e6290e9a0bca8ebe43550b6f8bc9b8a2f1f440
Jangwoojin863/python
/sort.py
1,110
3.90625
4
# 버블 정렬 구현 및 사용 예제 #------------------------------------------------------- # 버블 정렬 함수 # 전달 인수: # list = 정수형 배열 # cnt = 배열의 요소 개수 # 반환값: -1 = 정렬 안함, 0 = 정상 수행 def bubble_sort(list_data): cnt = len(test_list) # 원소 개수가 2개 미만이면 정렬 불필요 */ if cnt < 2: return -1 for i in range(cnt, -1, -1): for j in range(0, i - 1): if list_data[j] > list_data[j + 1]: temp = list_data[j] list_data[j] = list_data[j + 1] list_data[j + 1] = temp return 0 #------------------------------------------------------- # 메인 처리 시작 test_list = [5, 8, 10, -1, -10, 100, 50, 90, 45, 64, 7, 9, -20, -10, -1, 0, 255, 500, -300, -256] # 원래 자료 출력 print(test_list) print("\nBubble sorting...\n") # 버블 정렬 함수 호출 bubble_sort(test_list) # 정렬된 자료 출력 print(test_list)
f507a5c480c637b28c1806585241564f508998bb
Gio1609/Python_Basic
/chap-8_Recursion_and_Dynamic_Programming/8.9.py
1,387
3.828125
4
# Implement an algorithm to print all valid combinations of n pairs of parentheses. # Time: O(n^2) (string concatation takes n time) def parens(n): combinations = list() _parens(n, 0, 0, '', combinations) return combinations def _parens(n, l, r, s, combinations): if len(s) == 2*n: combinations.append(s) return None if l < n: s_cp = s s_cp += '(' _parens(n, l+1, r, s_cp, combinations) if r < l: s_cp = s s_cp += ')' _parens(n, l, r+1, s_cp, combinations) if __name__ == "__main__": n = 4 parens = parens(n) print(len(parens)) print(parens) # Using list of chars # Time: O(n) def parens(n): combinations = list() _parens(n, 0, 0, list(), combinations) return build_strings(combinations) def _parens(n, l, r, s, combinations): if len(s) == 2*n: combinations.append(s) return None if l < n: s_cp = s.copy() s_cp.append('(') _parens(n, l+1, r, s_cp, combinations) if r < l: s_cp = s.copy() s_cp.append(')') _parens(n, l, r+1, s_cp, combinations) def build_strings(chars_lists): str_list = list() for chars in chars_lists: str_list.append(''.join(chars)) return str_list if __name__ == "__main__": n = 4 parens = parens(n) print(len(parens)) print(parens)
5303f5b3c94c33b8d772229c14a01213da53aa45
xukangjune/Leetcode
/solved/238. 除自身以外数组的乘积.py
1,526
3.609375
4
""" 我自己写的比较拖沓,原本是想准备两个数组来存储原数组每一位左边的数累积和右边的数累积,到那时这样就不满足题意了。因为返回 数组不计入额外空间,所以这个条件可以利用。所以我就将左边数的累积计算到返回数组,然后将反向乘上右边数的累积。 新的解法比较流畅,只需要两遍遍历数组,只需要两个遍历来记录当前左边和右边数累乘的结果。 """ class Solution: def productExceptSelf(self, nums): #新的解法 n = len(nums) ret = [1] * n left = 1 for i in range(n): ret[i] *= left left *= nums[i] #此时的ret为nums每一位前面所有数的乘积,不包括自己 right = 1 for i in range(n-1, -1, -1): ret[i] *= right right *= nums[i] #同上面的思路相同,此时的right代表每一位右边所有的数相乘 return ret # 原本的解法,满足要求但是有点拖沓 # n = len(nums) # ret = [1] * n # left = 1 # for i, num in enumerate(nums): # if i == 0: # ret[0] = num # else: # ret[i] = num * ret[i-1] # post = 1 # for i in range(n-1, 0, -1): # ret[i] = ret[i-1] * post # post *= nums[i] # ret[0] = post # return ret solve = Solution() nums = [1,2, 3, 4] print(solve.productExceptSelf(nums))
780d8e855f1963347397f2a2c2b3e2b3c4a49681
Almas-Ali/Gender-Guise-App
/main.py
4,268
3.6875
4
from tkinter import * from tkinter.messagebox import * root = Tk() def about(): showinfo("About","Guise Your Gender version 1.0") def author(): showinfo('Author','This App is made by Md. Almas Ali\n\tin Bangladesh') mainmenu = Menu(root) mainmenu.add_command(label='About', command=about) #mainmenu.add_separator() mainmenu.add_command(label='Author', command=author) mainmenu.add_command(label="Exit", command=quit) root.config(menu=mainmenu) def nameTest(): if name.get() == '': showinfo('Result','You haven’t enter anyname in box. ') try: nam = name.get().lower() enm = nam[-1] enm2 = nam[-2:] enm3 = nam[-3:] except: pass else: if enm == 'a': showinfo('Result','You are Female.') elif enm == 'b': showinfo('Result','You are Male.') elif enm == 'c': showinfo('Result','You are Male. ') elif enm == 'd': showinfo('Result','You are Male. ') elif enm == 'e': if nam == 'rone': showinfo('Result','You can be Male/Female.') else: showinfo('Result','You are Male.') elif enm == 'f': showinfo('Result','You are *Male. ') elif enm == 'g': showinfo('Result','You are *Male. ') elif enm == 'h': showinfo('Result','You are *Male. ') elif enm == 'i': if nam == 'roni': showinfo('Result','You can be Male/Female.') elif nam == 'ali': showinfo('Result','You are Male.') else: showinfo('Result','You are Female. ') elif enm == 'j': showinfo('Result','You are *Male. ') elif enm == 'k': showinfo('Result','You are *Male. ') elif enm == 'l': showinfo('Result','You are Male.') elif enm == 'm': if nam == 'mim': showinfo('Result','You can be Male/Female.') elif enm3 == 'mim': showinfo('Result','You can be Female.') else: showinfo('Result','You are *Male. ') elif enm == 'n': if enm3 == 'lin': showinfo('Result','You are Female') elif enm3 == 'rin': showinfo('Result','You are Female') else: showinfo('Result','You are Male') elif enm == 'o': showinfo('Result','You are Male. ') elif enm == 'p': showinfo('Result','You are *Male. ') elif enm == 'q': showinfo('Result','You are *Male. ') elif enm == 'r': if nam == 'nur': showinfo('Result','You are Male. ') else: showinfo('Result', 'You are male.') elif enm == 's': showinfo('Result','You are Male. ') elif enm == 't': showinfo('Result','You are *Male. ') elif enm == 'u': showinfo('Result','You are Female. ') elif enm == 'v': showinfo('Result','You are *Male. ') elif enm == 'w': showinfo('Result','You are *Male. ') elif enm == 'x': showinfo('Result','You are *Male. ') elif enm == 'y': if nam == 'rony': showinfo('Result','You can be Male/Female.') else: showinfo('Result','You are Female.') elif enm == 'z': showinfo('Result','You are Male. ') else: showinfo('Result','Error Name! ') root.title('Guise Your Gender ') root.geometry("500x400") f1 = Frame(root, bg="lightblue", borderwidth=6, relief=SUNKEN) f1.pack(side='top', fill='x') f2 = Frame(root, bg='black') f2.pack(side='bottom',fill="x") f3 = Frame(root, bg='lightblue') f3.pack(side='top',fill='both') Label(f1, text='Guise Your Gender', fg='blue', bg="lightblue", font="Arial 18 bold").pack(padx=20,pady=40) Label(f1, text='Enter Your Name : ', bg="lightblue", font='Arial 8 bold', fg='orange').pack(pady=20) Label(f2, text="© Copyright collected by Md. Almas Ali.",fg='red', bg='black', font="Arial 8 bold").pack() name = StringVar() Entry(f1, textvariable=name, bg='lightblue',fg='red', font="Arial 8 italic").pack() Button(f1, text='Test', bg='red', fg='white', command=nameTest).pack(pady=30) photo = PhotoImage(file='./img/author.png') Label(f3, image=photo).pack() Label(f3, text='Md. Almas Ali', font='Arial 10', fg='darkblue', bg='lightblue').pack(pady=8) Label(f3, text='Diploma in Engineering in Computer Technology', fg='darkblue', bg='lightblue', font='Arial 6').pack() Label(f3, text='2nd Semester, 2nd Shift', fg='darkblue', bg='lightblue', font='Arial 6').pack() Label(f3, text='Chapai Nawabganj Polytechnic Institute, Chapai Nawabganj.', fg='darkblue', bg='lightblue', font='Arial 6').pack() Label(f3, text='Contact: almaspr3@gmail.com', fg='darkblue', bg='lightblue', font='Arial 6').pack() root.mainloop()
647f9060af245c4ebf34b577ead5d29d944f0df4
gholden3/problem_practice
/chapter10/q3_search_in_rotated_array.py
2,435
4.09375
4
# Given a sorted array of n integers which has been rotated an unknown # number of times, write code to find an element in that array. you may assume # the array was originally sorted in ascending order import unittest from math import floor def run_search_in_rotated_array(array, value_to_find: int) -> int: ''' searches a rotated array. returns the index where the value was found''' return search_in_rotated_array(array, value_to_find, 0, len(array) - 1) def search_in_rotated_array(array, value_to_find, low_idx, high_idx): mid_idx = floor((high_idx + low_idx)/2) mid_val = array[mid_idx] if (value_to_find == mid_val): return mid_idx left_normally_ordered: bool = (array[low_idx] < array[mid_idx]) right_normally_ordered: bool = (array[high_idx] > array[mid_idx]) left_all_repeats: bool = (array[mid_idx] == array[low_idx]) right_all_repeats: bool = (array[mid_idx] == array[high_idx]) if left_normally_ordered: if value_to_find in range(low_idx, mid_idx): # value is in the left return search_in_rotated_array(array, value_to_find, low_idx, mid_idx - 1) else: # value is in the right return search_in_rotated_array(array, value_to_find, mid_idx + 1, high_idx) elif right_normally_ordered: if value_to_find in range(mid_idx + 1, high_idx): # value is in the right return search_in_rotated_array(array, value_to_find, mid_idx + 1, high_idx) else: # value is in the left return search_in_rotated_array(array, value_to_find, low_idx, mid_idx - 1) elif left_all_repeats: # we know the repeats does not contain our value so search right return search_in_rotated_array(array, value_to_find, mid_idx +1, high_idx) elif right_all_repeats: return search_in_rotated_array(array, value_to_find, low_idx, mid_idx -1 ) class Test(unittest.TestCase): def test_search_in_rotated_array(self): test_cases = [ ([15, 16, 19, 20, 1, 3, 5, 7, 10], 5, 6), ([2, 2, 2, 3, 4, 2], 2, 2), ([2, 2, 2, 3, 4, 2], 4, 4) ] for test_case in test_cases: (array, search_val, expected_idx) = test_case index = run_search_in_rotated_array(array, search_val) self.assertEqual(expected_idx, index) if __name__ == "__main__": unittest.main()
749dc368583441998389e585bcbd23cd4fbb707d
EdgarLozano185519/AudioGame-Sample-with-Pyglet
/src/enemy.py
561
3.546875
4
import math class Enemy: def __init__(): self.x = 0 self.y = 0 self.z = 0 self.max_distance = 0 self.step_volume = 0 def spawn(self): self.spawn = 1 # Defines the minimum distance for an enemy to spawn def define_distance(self, distance): self.max_distance = distance def calculate_step_volume(self): self.step_volume = 1.0 / self.max_distance def calculate_distance(self, x, y, z): return math.sqrt((self.x - x) ** 2 + (self.y - y) ** 2 + (self.z - z) ** 2)
37ce8cd18a3a6168fae84dc24290f8096677dfea
yhelen-stuy/softdev-03
/hw03.py
1,390
3.5625
4
#Helen Ye, Jennifer Zhang #SoftDev1 pd7 #HW03 -- StI/O: Divine your Destiny! #2017-09-15 import random def read_occupations(): # Read the file # 'U' is the universal newline (in case the csv file was made in Windows) source = open('occupations.csv', 'rU') # Strip of newlines at the beginning of end of file before splitting/parsing lines = source.read().strip('\n').split('\n') source.close() csv_dict = {} # Remove the title line lines.pop(0) for line in lines: # Check if the job title includes commas and if so account for it if line[0:1] is '"': # Find the second quote end_quote = line[1:].find('"') + 1 # Define the list accordingly fields = [line[1:end_quote], line[end_quote+2:]] else: fields = line.split(',') csv_dict[fields[0]] = float(fields[1]) return csv_dict def random_profession(professions): num = random.randint(1,998) for element in professions: #We keep subtracting the percentages until num becomes a negative number: we know that it falls within the range of the specific occupation when its negative num -= professions[element] * 10 if num < 0: return element #returns -1 if something went wrong return -1; occ = read_occupations() #for x in occ: # print x + "," + str(occ[x]) print random_profession(occ)
a2b2700b0505eb19db95e02d0514d4ee7420ecbd
dimosp/grades-report
/grades_report/stats.py
6,655
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2020 KAUTH """ from statistics import mean, stdev def mean_grade(parsed_list, passing_grade, overall_mean=True): """ This function calculates the arithmetic mean of the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_mean: True, when calculating the mean of all the grades, False, when calculating the mean of the passing grades :return: the arithmetic mean of the given as input parsed list """ if overall_mean is False: passing_grades_list = ( [item for item in parsed_list if item >= passing_grade] ) if len(passing_grades_list) > 0: mean_value = mean(passing_grades_list) else: mean_value = 0.0 else: mean_value = mean(parsed_list) return mean_value def stdev_grade(parsed_list, passing_grade, overall_stdev=True): """ This function calculates the standard deviation of the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_stdev: True, when calculating the standard deviation of all the grades, False, when calculating the standard deviation of the passing grades :return: the standard deviation of the given as input parsed list """ if overall_stdev is False: passing_grades_list = ( [item for item in parsed_list if item >= passing_grade] ) if len(passing_grades_list) > 1: stdev_value = stdev(passing_grades_list) else: stdev_value = "- (requires at least two data points)" else: stdev_value = stdev(parsed_list) return stdev_value def maximum_grade(parsed_list, passing_grade, overall_max=True): """ This function calculates the maximum grade from the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_max: True, when calculating the maximum of all the grades, False, when calculating the maximum of the passing grades :return: the maximum element of the given as input parsed list """ if overall_max is False: passing_grades_list = ( [item for item in parsed_list if item >= passing_grade] ) if len(passing_grades_list) > 0: max_value = max(passing_grades_list) else: max_value = "-" else: max_value = max(parsed_list) return max_value def minimum_grade(parsed_list, passing_grade, overall_min=True): """ This function calculates the minimum grade from the given grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_min: True, when calculating the minimum of all the grades, False, when calculating the minimum of the passing grades :return: the minimum element of the given as input parsed list """ if overall_min is False: passing_grades_list = ( [item for item in parsed_list if item >= passing_grade] ) if len(passing_grades_list) > 0: min_value = min(passing_grades_list) else: min_value = "-" else: min_value = min(parsed_list) return min_value def total_graded(parsed_list): """ This function finds the total number of individuals that were graded. :param parsed_list: the parsed list of the grades :return: the total number of people graded """ number_graded = len(parsed_list) return number_graded def total_passed(parsed_list, passing_grade): """ This function finds the total number of individuals that scored over or equal to the passing grade. :param parsed_list: the parsed list of the grades :return: the total number of people graded """ passing_grades_list = ( [item for item in parsed_list if item >= passing_grade] ) number_passed = len(passing_grades_list) return number_passed def relative_grade_percentage( parsed_list, passing_grade, personal_grade, overall_percentage=True ): """ This function calculates the percentage of people that the user's grade is above. If overall_percentage is True, then it calculates the above taking into account all the grades, otherwise it only considers the passing grades. :param parsed_list: the parsed list of the grades :param passing_grade: the grade passing threshold :param overall_percentage: True, when taking into account all the grades, False, when considering only the passing grades :return: the percentage of grades that you scored above of """ if overall_percentage is False: passing_grades_list = ( [item for item in parsed_list if item >= passing_grade] ) total_grades = len(passing_grades_list) lower_grades = ( [item for item in passing_grades_list if personal_grade > item] ) else: total_grades = len(parsed_list) lower_grades = ( [item for item in parsed_list if personal_grade > item] ) total_lower_grades = len(lower_grades) if (total_grades > 0): relative_grade_percentage = (total_lower_grades / total_grades) * 100 else: relative_grade_percentage = 0.0 return relative_grade_percentage def grade_distribution(parsed_list, max_grade, bin_number=10): """ This funtion calculates the distribution of the given grades by splitting them into 'n' equal bins (intervals) and finding the number of grades corresponding to each bin. The bins are left-closed, right-open: [a, b) = x | a <= x < b, except from the last one that is closed: [c, d] = x | c <= x <= d. :param parsed_list: the parsed list of the grades :param max_grade: the maximum grade that you can score :param bin_number: the number of bins that is calculated in the distribution, default is 10 :return: a list of the number of grades in each bin """ bin_length = max_grade / bin_number grade_distribution_list = [0] * bin_number for item in parsed_list: index = int(item / bin_length) if index == bin_number: grade_distribution_list[index-1] = ( grade_distribution_list[index-1] + 1 ) else: grade_distribution_list[index] = grade_distribution_list[index] + 1 return grade_distribution_list
fa8ab3a99392e57cac7cd1e56f457faaf9662c4f
liaison/LeetCode
/python/236_lowest_common_ancestor_of_a_binary_tree_no_parent_pointer.py
2,640
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': def dfs(node, path, target, result): """ Build the path that leads to the target node """ if node is None: return False if node == target: # result = list(path) WONT WORK !!! # One should operate within the object, but not reassign the pointer result.extend(list(path)) return True is_found = False for next_node in [node.left, node.right]: path.append(next_node) is_found = dfs(next_node, path, target, result) path.pop() if is_found: break return is_found path_to_p = [] path_to_q = [] dfs(root, [root], p, path_to_p) dfs(root, [root], q, path_to_q) # given the two paths, find the first branching point index = 0 while True: if index >= len(path_to_p) or index >= len(path_to_q): break if path_to_p[index] != path_to_q[index]: break index += 1 return path_to_p[index-1] # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': result = None def get_descendants(node): """ Retrieve all the descendant nodes starting from the input node. while traversing the nodes, find the first subtree that contains the two input nodes """ nonlocal result if not node: return set() left_nodes = get_descendants(node.left) # we find the result in the left tree, early exit! if result: return set() right_nodes = get_descendants(node.right) all_nodes = left_nodes | right_nodes | {node.val} # the first subtree that contains both the target nodes if p.val in all_nodes and q.val in all_nodes and not result: result = node return all_nodes get_descendants(root) return result
836cea47bc707db9eed05f23cfe8565d4818a301
praneetharra/projectEuler
/3_lrgst_prme_fctr.py
352
3.546875
4
import math def isPrimme(a): for i in range(2,int(math.sqrt(a))): if a%i == 0: return False return True primes = [] n = 600851475143 if not isPrimme(n): for i in range(1,int(math.sqrt(n))): if n%i == 0: if isPrimme(i): primes.append(i) if isPrimme(int(n/i)): primes.append(int(n/i)) print(max(primes)) else: print(n)
23fb7e5ef53edd67f29ce1138f5f13b191f20978
khizarhussain19/Two-way-communication-between-normal-and-deaf-people-using-Speech-Recognition-and-Image-Processing
/SpeechToText.py
1,397
3.5625
4
#!/usr/bin/env python3 # Requires PyAudio and PySpeech. import speech_recognition as sr import cv2 import time import numpy as np capture_duration = 4 font = cv2.FONT_HERSHEY_SIMPLEX while True: # Record Audio r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) # Speech recognition using Google Speech Recognition try: print("You said: " + r.recognize_google(audio)) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) # The duration in seconds of the video captured start_time = time.time() cap = cv2.VideoCapture(0) while(int(time.time() - start_time) < capture_duration): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here # Display the resulting frame cv2.putText(frame,r.recognize_google(audio) , (22, 34), font, 1, (200, 255, 255), 2, cv2.LINE_AA) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
6073106405914e23cbdd69b4c5371d5e6ca7a973
ChyngyzOsmonov/part4_tasks
/part4_task6.py
886
3.671875
4
class Home: def __init__(self, type_, bed, wardrobe, table): self.type_ = type_ self.bed = bed self.wardrobe = wardrobe self.table = table def desc(self): print('Home type: {}, in the home: {}, {}, {}'.format(self.type_,self.bed,self.wardrobe,self.table)) class Furnature(Home): def __init__(self, bed, wardrobe, table): self.bed = 4 self.wardrobe = 2 self.table = 1.5 self.area = 0 def house_area(self, Home): print('Total area of home without furnature: ',self.area) def get_area(self): final = self.area - (self.bed + self.wardrobe + self.table) print('Final total area: ', final) house = Home('flat', 'bed', 'wardrobe', 'table') house.desc() total_area = Furnature(4,2,1.5) total_area.area = 55 total_area.house_area(Home) total_area.get_area()
df9aa230178dc0932a62c76e4350f25306baaa2a
sbcshop/Raspberry-Pi-Webinars
/GUI Development/Example codes/Example13.py
358
4.375
4
''' Example to learn about button widget ''' from tkinter import * # function bind with button def press(): print('Button pressed') window = Tk() # to change the title of window window.title('My GUI') # to create a button b = Button(window, text='Button', height=4, width=4, command=press) b.grid(row=0, column=0) window.mainloop()
c0f78e21f89345e522bc0965692c8b727a38f1b3
Yeasayer/Random-Exercises
/Python/operators.py
470
3.640625
4
a,b,c = 1,2,3 plus = a+b+c minus = c-b-a multi = a*b*c divide = multi/plus mathList = [] mathList.append(plus) mathList.append(minus) mathList.append(multi) mathList.append(divide) superList = mathList*10 if plus == multi: print (mathList) print (superList) print "\"mathList\" has %d objects!" % len(mathList) print "\"superList\" has %d objects!" % len(superList) print "Subtracting mathList from superList gives us %d objects!" % (len(superList) - len(mathList))
6ebe6c04722f95e5de6241eab6c901d1bfa108ef
Nithinkumar-s/Python
/tst2.py
1,360
3.6875
4
from os import system import random from time import sleep t = 1 f = 0 c = 0 r = 0 x = 0 y = 0 def loop(): global r,f,c,x,y w=62 f = 0 if(f == 0): if(r == 0 ): r=random.randrange(1,30) elif(c==10): r=random.randrange(5,30) f = 1 #top line print('#'*w) #height line for height in range(2,32): print('#',end='') #r=random.randrange(2,55) for i in range(2,62): print(" ",end='') if(r==height and r==i or f==1): x = height y = i g=60-i #prints character and prints remaining spaces print("i",end='') print(" "*g,end='') r=-1 f= 2 break elif(x == height and y == i): g=60-i #prints character and prints remaining spaces print("i",end='') print(" "*g,end='') r=-1 f= 2 break print("#") #sleep(0.3) #bottom line print('#'*w) def main(): global t global c global r while(t): #t=t-1 loop() sleep(0.3) system("clear") c+=1 main()
d8df169e5c4669286885707b4f149d2f5d7cea60
aronnax77/python_uploads
/bubble_sort.py
657
4.09375
4
""" Author: Richard Myatt Date: 14 February 2018 The function below represents the implementation of the 'bubble sort' algorithm. This is demonstrated with the list [33, 20, 12, 31, 2, 67] but should work with any other list. """ def bubbleSort(l): """ An implementation of the bubble sore with optimisation """ result = l[:] lengthData = len(result) sweep = lengthData - 1 while sweep >= 0: for i in range(sweep): if result[i] > result[i+1]: result[i], result[i+1] = result[i+1], result[i] sweep -= 1 return result print(bubbleSort([33, 20, 12, 31, 2, 67]))
e9eb2b4427ba60dabcb3b0d7265b67eda930c31f
DonJames0214/ENED
/ENED_ToolKit/forces.py
3,312
3.578125
4
from math import sin, cos, radians, atan, sqrt, pi class Force: conv = {'N':1.,'LBF':4.448,'KGF':9.807} def __init__(self, magnitude, direction, units="N", rad=False): self.mag = magnitude self.ang = direction self.units = units.upper() if self.units not in Force.conv: raise ValueError(f'"{self.units}" is not an accepted unit. Accepted units are:\n"N"\n"LBF"\n"KGF"') if not rad: self.ang = radians(self.ang) self.x = self.mag * cos(self.ang) self.y = self.mag * sin(self.ang) @staticmethod def parseXY(x, y, unit="N"): mag = sqrt(x ** 2 + y ** 2) ang = atan(y / x) if x < 0: ang += pi return Force(mag, ang,units=unit,rad=True) def __add__(self, other): if type(other) != type(Force(0, 0)): raise ValueError(f'Unsupported Addition Between A Class "force" Object And A Type "{type(other)}" object') other: Force new_x = self.x*Force.conv[self.units] + other.x*Force.conv[other.units] new_y = self.y*Force.conv[self.units] + other.y*Force.conv[other.units] return Force.parseXY(new_x/Force.conv[self.units], new_y/Force.conv[self.units],unit=self.units) def __repr__(self): return (f'Magnitude:\t{self.mag} {self.units}\n' f'Angle: \t{self.ang} radians\n' f'x: \t{self.x} {self.units}\n' f'y: \t{self.y} {self.units}') class _SpringSystem: def __init__(self,k,f,x,**kwargs): self.K_eq = k self.F_total = f self.X_Total = x for i in kwargs: self.__dict__[i] = kwargs[i] def __repr__(self): ind = '-' * max(len(str(i)) for i in [self.K_eq, self.F_total, self.X_Total]) msg = \ f'''<----------------{ind}-------------> K equation: {self.K_eq} N/m F total : {self.F_total} N x total : {self.X_Total} m ''' for i in self.__dict__: if i in ['K_eq','F_total','X_Total']: continue msg += f''' <-----------{'-'*max([len(i),max([len(str(self.__dict__[i].__dict__[j])) for j in ['k','f','x']])])}---> Spring: {i} K : {self.__dict__[i].k} N/m F : {self.__dict__[i].f} N X : {self.__dict__[i].x} m <-----------{'-'*max([len(i),max([len(str(self.__dict__[i].__dict__[j])) for j in ['k','f','x']])])}--->\n''' msg += f'\n<----------------{ind}------------->' return msg class Spring: def __init__(self, k): self.k = k self.x = 0 self.f = 0 @staticmethod def comp_elong(F_total, par=False, **kwargs): if par: keq = sum([kwargs[i].k for i in kwargs]) for i in kwargs: kwargs[i].x = F_total/keq kwargs[i].f = kwargs[i].k * kwargs[i].x return _SpringSystem(keq, F_total, F_total / keq,**kwargs) else: keq = (sum(1/kwargs[i].k for i in kwargs))**(-1) x = [] for i in kwargs: kwargs[i].f = F_total kwargs[i].x = F_total/kwargs[i].k x.append(kwargs[i].x) return _SpringSystem(keq, F_total, sum(x), **kwargs)
b0901e599ce592fb16c823d09ec2d1d02f524990
lvbenson/Neural_Reuse_New
/Eduardo/Figures/Company_Size/Impact.py
10,294
3.625
4
""" Given the set of company projects and a fixed total employee count, how many important employees are required for the success of those projects? Importance defined as: removing the employee would cause project failure to some extent Options Option 0 -- None of the employees are important Option 1 -- All of the employees are important Option 2 -- a very small fraction of the employees are important Option 3 -- a large fraction of the employees are important Hypothesis Hypothesis for what we expect to see as company size goes from small to large Hypothesis 1 -- the option to choose depends on the company size Hypothesis 1a -- small company will go for option 1 Hypothesis 1b -- large company will go for option 2 """ #participation for MCLW for 2x3, 2x5 import numpy as np import matplotlib.pyplot as plt """ Multifunctional 1B. XXX --- Figure: Impact vs neuron sorted (MCLW_LW, MCLW_MC) Figure: Participation vs neuron sorted. """ reps = 100 nn5 = 2*5 ################################ #MCLW_LW, 2x5 ############################### b5xlw = np.zeros((reps,nn5)) b5xerrslw = np.zeros((reps,nn5)) for i in range(reps): f = 1 - (np.load("Eduardo/Multi_Data/lesions_MCLW5_LW_40_"+str(i)+".npy")) b5xlw[i] = np.sort(f)[::-1] b5xerrslw[i] = np.std(f) x5 = list(range(0,10)) err5 = [] for i in b5xlw.T: err5.append(np.std(i)) ############################## #MCLW_MC ############################## b5xmc = np.zeros((reps,nn5)) b5xerrsmc = np.zeros((reps,nn5)) for i in range(reps): f = 1 - (np.load("Eduardo/Multi_Data/lesions_MCLW5_MC_40_"+str(i)+".npy")) b5xmc[i] = np.sort(f)[::-1] b5xerrsmc[i] = np.std(f) x5 = list(range(0,10)) err5mc = [] for i in b5xmc.T: err5mc.append(np.std(i)) ################################ #MCLW - COMBINED ################################ combim = np.zeros((reps,nn5)) combimerr = np.zeros((reps,nn5)) for i in range(reps): mc = 1 - (np.load("Eduardo/Multi_Data/lesions_MCLW5_MC_40_"+str(i)+".npy")) lw = 1 - (np.load("Eduardo/Multi_Data/lesions_MCLW5_LW_40_"+str(i)+".npy")) nn = mc+lw #print(len(mc)) nn = np.sort(nn)[::-1] #max = np.max(nn) combim[i] = nn combimerr[i] = np.std(f) x5 = list(range(0,10)) combimerr = [] for i in combim.T: combimerr.append(np.std(i)) import math #Multifunctional - impact fig, axs = plt.subplots(2,2, constrained_layout=True) axs[0,0].plot(np.mean(b5xlw,axis=0),'o-',markersize=2,label="MCLW_LW",color='#3F7F4C') axs[0,0].fill_between(x5, np.mean(b5xlw,axis=0)-(np.divide(err5,math.sqrt(10))), np.mean(b5xlw,axis=0)+(np.divide(err5,math.sqrt(10))),alpha=0.2, edgecolor='#3F7F4C', facecolor='#7EFF99') axs[0,0].plot(np.mean(b5xmc,axis=0),'o-',markersize=2,label="MCLW_MC",color='#CC4F1B') axs[0,0].fill_between(x5, np.mean(b5xmc,axis=0)-(np.divide(err5mc,math.sqrt(10))), np.mean(b5xmc,axis=0)+(np.divide(err5mc,math.sqrt(10))),alpha=0.2, edgecolor='#c88700', facecolor='#c88700') """ axs[0].plot(np.mean(combim,axis=0),'o-',markersize=2,label="MCLW_COMB",color='#507ad0') axs[0].fill_between(x5, np.mean(combim,axis=0)-(np.divide(combimerr,math.sqrt(10))), np.mean(combim,axis=0)+(np.divide(combimerr,math.sqrt(10))),alpha=0.2, edgecolor='#507ad0', facecolor='#507ad0') """ axs[0,0].set_title("2x5: Impact") axs[0,0].legend() axs[0,0].set_xlabel("Neuron (sorted)") v5x = np.zeros((reps,nn5)) nI = 4 nH = 10 ###################################### #LW ##################################### for i in range(reps): nn = np.load("Eduardo/Multi_Data/state_MCLW5_LW_"+str(i)+".npy") nn = np.var(nn[:,nI:nI+nH],axis=0) nn = np.sort(nn)[::-1] #max = np.max(nn) v5x[i] = nn ################################# #MC ################################ mcv5x = np.zeros((reps,nn5)) for i in range(reps): nn = np.load("Eduardo/Multi_Data/state_MCLW5_MC_"+str(i)+".npy") nn = np.var(nn[:,nI:nI+nH],axis=0) nn = np.sort(nn)[::-1] #max = np.max(nn) mcv5x[i] = nn ################################## #COMBINED ################################## comb = np.zeros((reps,nn5)) for i in range(reps): mc = np.load("Eduardo/Multi_Data/state_MCLW5_MC_"+str(i)+".npy") lw = np.load("Eduardo/Multi_Data/state_MCLW5_LW_"+str(i)+".npy") nn = np.concatenate((mc, lw), axis=0) #print(len(mc)) nn = np.var(nn[:,nI:nI+nH],axis=0) nn = np.sort(nn)[::-1] #max = np.max(nn) comb[i] = nn err5 = [] for i in v5x.T: err5.append(np.std(i)) mcerr5 = [] for i in mcv5x.T: mcerr5.append(np.std(i)) comberr = [] for i in comb.T: comberr.append(np.std(i)) #print('single',np.mean(v5x,axis=0)) #print('double',np.mean(comb,axis=0)) axs[1,0].plot(np.mean(v5x,axis=0),'o-',markersize=2,label="MCLW_LW",color='#3F7F4C') axs[1,0].fill_between(x5, np.mean(v5x,axis=0)-(np.divide(err5,math.sqrt(10))), np.mean(v5x,axis=0)+(np.divide(err5,math.sqrt(10))),alpha=0.2, edgecolor='#3F7F4C', facecolor='#7EFF99') axs[1,0].plot(np.mean(mcv5x,axis=0),'o-',markersize=2,label="MCLW_MC",color='#CC4F1B') axs[1,0].fill_between(x5, np.mean(mcv5x,axis=0)-(np.divide(mcerr5,math.sqrt(10))), np.mean(mcv5x,axis=0)+(np.divide(mcerr5,math.sqrt(10))),alpha=0.2, edgecolor='#c88700', facecolor='#c88700') axs[1,0].plot(np.mean(comb,axis=0),'o-',markersize=2,label="MCLW",color='#507ad0') axs[1,0].fill_between(x5, np.mean(comb,axis=0)-(np.divide(comberr,math.sqrt(10))), np.mean(comb,axis=0)+(np.divide(comberr,math.sqrt(10))),alpha=0.2, edgecolor='#507ad0', facecolor='#507ad0') axs[1,0].set_title("Participation") axs[1,0].legend() ######################################################################### #2x3 ######################################################################### reps = 100 nn3 = 2*3 ################################ #MCLW_LW, 2x3 ############################### b3xlw = np.zeros((reps,nn3)) b3xerrslw = np.zeros((reps,nn3)) for i in range(reps): f = 1 - (np.load("Eduardo/Data3/lesions_MCLW3_LW_40_"+str(i)+".npy")) b3xlw[i] = np.sort(f)[::-1] b3xerrslw[i] = np.std(f) x3 = list(range(0,6)) err3 = [] for i in b3xlw.T: err3.append(np.std(i)) ############################## #MCLW_MC ############################## b3xmc = np.zeros((reps,nn3)) b3xerrsmc = np.zeros((reps,nn3)) for i in range(reps): f = 1 - (np.load("Eduardo/Data3/lesions_MCLW3_MC_40_"+str(i)+".npy")) b3xmc[i] = np.sort(f)[::-1] b3xerrsmc[i] = np.std(f) x3 = list(range(0,6)) err3mc = [] for i in b3xmc.T: err3mc.append(np.std(i)) """ ################################ #MCLW - COMBINED ################################ combim = np.zeros((reps,nn5)) combimerr = np.zeros((reps,nn5)) for i in range(reps): mc = 1 - (np.load("Eduardo/Multi_Data/lesions_MCLW5_MC_40_"+str(i)+".npy")) lw = 1 - (np.load("Eduardo/Multi_Data/lesions_MCLW5_LW_40_"+str(i)+".npy")) nn = mc+lw #print(len(mc)) nn = np.sort(nn)[::-1] #max = np.max(nn) combim[i] = nn combimerr[i] = np.std(f) x5 = list(range(0,10)) combimerr = [] for i in combim.T: combimerr.append(np.std(i)) """ import math #Multifunctional - impact axs[0,1].plot(np.mean(b3xlw,axis=0),'o-',markersize=2,label="MCLW_LW",color='#3F7F4C') axs[0,1].fill_between(x3, np.mean(b3xlw,axis=0)-(np.divide(err3,math.sqrt(6))), np.mean(b3xlw,axis=0)+(np.divide(err3,math.sqrt(6))),alpha=0.2, edgecolor='#3F7F4C', facecolor='#7EFF99') axs[0,1].plot(np.mean(b3xmc,axis=0),'o-',markersize=2,label="MCLW_MC",color='#CC4F1B') axs[0,1].fill_between(x3, np.mean(b3xmc,axis=0)-(np.divide(err3mc,math.sqrt(6))), np.mean(b3xmc,axis=0)+(np.divide(err3mc,math.sqrt(6))),alpha=0.2, edgecolor='#c88700', facecolor='#c88700') """ axs[0].plot(np.mean(combim,axis=0),'o-',markersize=2,label="MCLW_COMB",color='#507ad0') axs[0].fill_between(x5, np.mean(combim,axis=0)-(np.divide(combimerr,math.sqrt(10))), np.mean(combim,axis=0)+(np.divide(combimerr,math.sqrt(10))),alpha=0.2, edgecolor='#507ad0', facecolor='#507ad0') """ axs[0,1].set_title("2x3: Impact") axs[0,1].legend() axs[0,1].set_xlabel("Neuron (sorted)") v3x = np.zeros((reps,nn3)) nI = 4 nH = 6 ###################################### #LW ##################################### for i in range(reps): nn = np.load("Eduardo/Data3/state_MCLW3_LW_"+str(i)+".npy") nn = np.var(nn[:,nI:nI+nH],axis=0) nn = np.sort(nn)[::-1] max = np.max(nn) v3x[i] = nn/max ################################# #MC ################################ mcv3x = np.zeros((reps,nn3)) for i in range(reps): nn = np.load("Eduardo/Data3/state_MCLW3_MC_"+str(i)+".npy") nn = np.var(nn[:,nI:nI+nH],axis=0) nn = np.sort(nn)[::-1] max = np.max(nn) mcv3x[i] = nn/max ################################## #COMBINED ################################## comb = np.zeros((reps,nn3)) for i in range(reps): mc = np.load("Eduardo/Data3/state_MCLW3_MC_"+str(i)+".npy") lw = np.load("Eduardo/Data3/state_MCLW3_LW_"+str(i)+".npy") nn = np.concatenate((mc, lw), axis=0) #print(len(mc)) nn = np.var(nn[:,nI:nI+nH],axis=0) nn = np.sort(nn)[::-1] max = np.max(nn) comb[i] = nn/max err3 = [] for i in v3x.T: err3.append(np.std(i)) mcerr3 = [] for i in mcv3x.T: mcerr3.append(np.std(i)) comberr = [] for i in comb.T: comberr.append(np.std(i)) axs[1,1].plot(np.mean(v3x,axis=0),'o-',markersize=2,label="MCLW_LW",color='#3F7F4C') axs[1,1].fill_between(x3, np.mean(v3x,axis=0)-(np.divide(err3,math.sqrt(6))), np.mean(v3x,axis=0)+(np.divide(err3,math.sqrt(6))),alpha=0.2, edgecolor='#3F7F4C', facecolor='#7EFF99') axs[1,1].plot(np.mean(mcv3x,axis=0),'o-',markersize=2,label="MCLW_MC",color='#CC4F1B') axs[1,1].fill_between(x3, np.mean(mcv3x,axis=0)-(np.divide(mcerr3,math.sqrt(6))), np.mean(mcv3x,axis=0)+(np.divide(mcerr3,math.sqrt(6))),alpha=0.2, edgecolor='#c88700', facecolor='#c88700') axs[1,1].plot(np.mean(comb,axis=0),'o-',markersize=2,label="MCLW",color='#507ad0') axs[1,1].fill_between(x3, np.mean(comb,axis=0)-(np.divide(comberr,math.sqrt(6))), np.mean(comb,axis=0)+(np.divide(comberr,math.sqrt(10))),alpha=0.2, edgecolor='#507ad0', facecolor='#507ad0') axs[1,1].set_title("2x3: Participation (normalized)") axs[1,1].legend() fig.suptitle("Sizes 2x3, 2x5: Pairwise Multifunctional: MCLW") plt.savefig("Eduardo/Figures/Company_Size/PairwiseMulti_2x5_2x3.png") plt.show()
331ba25d4f34c30d1ac418c0d05a0b9b1cce35bb
MarcoHuXHu/learningpython
/Function/filter.py
1,520
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # filter传入一个返回True或False的函数,与一个Iterable对象,返回经过函数筛选为True的元素 # filter返回为iterator def is_odd(n): return n % 2 == 1 print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))) # 结果: [1, 5, 9, 15] # 例1:筛选回文数 def is_palindrome(n):#0123456 digits = str(n) length = len(digits) for i in range(length//2): if digits[i] != digits[length-i-1]: return False return True print(list(filter(is_palindrome, range(100, 999)))) # 例2:筛选素数 # 方法1:直接筛选法 import math def is_not_divisible(n): def func(x): return (x==n) or (x%n) > 0 # x==n 这个条件是为了方法1准备的,以免把素数本身筛选掉了,方法2中不需要这个 return func def prime_number(n): primes = range(2, n+1) i = 2 for i in range(2, int(math.sqrt(n))): primes = filter(is_not_divisible(i), primes) print(list(primes)) prime_number(100) # 方法2:素数生成器,可以产生无限序列 # 先定义一个初始iterator,生成奇数(素数除了2都是奇数) def init_iter(): n = 1 while True: n = n + 2 yield n # 素数生成器 def prime_iter(): it = init_iter() yield 2 while True: n = next(it) yield n it = filter(is_not_divisible(n), it) for i in prime_iter(): if (i < 100): print(i, end=", ") else: break
b359fe0634c39c6d223483dcee3be952f0155e34
Nagomez97/Hackmadrid_Crypto
/Retos/ECDH-AES/encryption.py
1,299
3.609375
4
################################# # # # ECDH KEY EXCHANGE # # # ################################# import Crypto from Crypto import * from Crypto.Util import * message = ?????????????????? # Private keys Alice_priv = Crypto.Util.number.getPrime(16) Bob_priv = Crypto.Util.number.getPrime(16) # The curve is y^2 = x^3 + ax + b a = 1234577 b = 3213242 M = 7654319 P = (5234568, 2287747) # A point in the curve def add(A,B): if A==(0,0): return B if B==(0,0): return A x1,y1 = A x2,y2 = B if A!=B: p = (y2-y1)*pow(x2-x1,M-2,M) else: p = (3*x1*x1+a)*pow(2*y1,M-2,M) x3 = p*p-x1-x2 y3 = p*(x1-x3)-y1 return (x3%M,y3%M) def mult(m, P): added = P for i in range(m): added = add(added,P) return added # Public: P, a, b, M, Bob_pub, Alice_pub Bob_pub = mult(Bob_priv,P) Alice_pub = mult(Alice_priv, P) # Alice obtains the secret key. Bob can do the same using its private key and Alices public one shared_secret = mult(Alice_priv, Bob_pub) key = str(shared_secret[0]) ################################# # # # AES ENCRYPTION # # # ################################# import AES aes_engine = AESCipher(key) cipher = aes_engine.encrypt(message) print('Encrypted message: ' + str(cipher)) # Encrypted message = J31ueow1irdvyJ+1aGszetQAozbFFfK8q9hmT4ygOvytezpzJWnEE0eDjVAh5Loe
47e2d734bbb2b7297ee4441e41c3c97b67e62cea
washiz99/solid-principles
/examples/isp/isp_good.py
381
4.03125
4
from abc import ABCMeta, abstractmethod class Shape(metaclass=ABCMeta): @abstractmethod def draw(self): pass class Circle(Shape): def draw(self): print('まるを描きます') class Square(Shape): def draw(self): print('しかくを描きます') circle = Circle() circle.draw() square = Square() square.draw()
9cd2278b7a6ca8cd2ec03bf03681e15dbd78bfd2
apulijala/python-crash-course-3
/ch9/inheritence.py
2,006
4.25
4
from restaurant_with_served import * """ 9-6. Ice Cream Stand: An ice cream stand is a specific kind of restaurant. Write a class called IceCreamStand that inherits from the Restaurant class you wrote in Exercise 9-1 (page 162) or Exercise 9-4 (page 167). Either version of the class will work; just pick the one you like better. Add an attribute called flavors that stores a list of ice cream flavors. Write a method that displays these flavors. Create an instance of IceCreamStand, and call this method. """ class IceCreamStand(Restaurant): def __init__(self, restaurant_name, cuisine_type, flavors): super().__init__(restaurant_name, cuisine_type) self.flavors = flavors def get_flavors(self): return self.flavors """ 9-7. Admin: An administrator is a special kind of user. Write a class called Admin that inherits from the User class you wrote in Exercise 9-3 (page 162) or Exercise 9-5 (page 167). Add an attribute, privileges, that stores a list of strings like "can add post", "can delete post", "can ban user", and so on. Write a method called show_privileges() that lists the administrator’s set of privileges. Create an instance of Admin, and call your method. """ class Admin(User): def __init__(self, first_name, last_name, privileges): super().__init__(first_name, last_name) self.attributes = Privileges(privileges) def show_privileges(self): return self.attributes """ 9-8. Privileges: Write a separate Privileges class. The class should have one attribute, privileges, that stores a list of strings as described in Exercise 9-7. Move the show_privileges() method to this class. Make a Privileges instance as an attribute in the Admin class. Create a new instance of Admin and use your method to show its privileges. """ class Privileges(): def __init__(self, privileges): self.privileges = privileges def get_privileges(self): return self.privileges
cd3cc56dcdb9d50e3ada36e9458a08662378b6a6
SquireGeli/m02.boot_0
/p1.py
306
3.59375
4
def sumaTodos(limitTo): resultado=0 for i in range (0, limitTo+1): resultado +=i return resultado print (sumaTodos(100)) def sumaCuadrados(limitTo): resultado=0 for i in range(limitTo+1): resultado += i*i return resultado print(sumaCuadrados(3))
1fd0fce7d0377c2ff3a1ca91aa738f426ecb10b1
xiaochenchen-PITT/CC150_Python
/cc150/c5.py
2,812
4.0625
4
'''5.1 You are given two 32-bit numbers, N and M, and two bit positions, i and j Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j) EXAMPLE: Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100 ''' # def SetBit(N, M, i, j): # '''Assume N is larger than M and j is larger than i.''' # if 2**(j-i+1) < M: # raise ValueError('Invalid i and j!') # all1s = 0xffffffff # mask = all1s - ((1<<j+1)-1) + ((1<<i)-1) # print bin(mask) # N1 = mask & N # M1 = (0x00000000 | M) << i # return bin(N1 | M1) # print SetBit(0b10000000000, 0b10101, 2, 6) '''5.2 Given a (decimal - e.g 3.72) number that is passed in as a string, print the binary representation. If the number can not be represented accurately in binary, print "ERROR". ''' # def BinRepr(string): # lst = string.split('.') # n = lst[0] # string # deci = '0.'+lst[1] # string # # print n, deci # int_str = '' # deci_str = '' # # integer # n = int(n) # while n != 0: # mod = n % 2 # int_str += str(mod) # n = n / 2 # # print int_str # # decimal # n = float(deci) # while True: # decimal part may run forever # n = n * 2 # if n > 1: # deci_str += '1' # n = n - 1 # elif n < 1: # deci_str += '0' # else: # deci_str += '1' # break # if len(deci_str) > 32: # return "ERROR" # # print deci_str # return int_str + '.' + deci_str # print BinRepr('3.25') # print BinRepr('13.325') '''5.3 Given an integer, print the next larger number that have the same number of 1 bits in their binary representation. ''' # def FindNextLarger(n): # if n == 0: # return 0 # # count how many 1's in the number # n_str = bin(n) # count_n = 0 # for x in n_str: # if x == '1': # count_n += 1 # # increase 1 at a time, stops when count = count_n # count = 0 # while count != count_n: # n += 1 # n_str = bin(n) # count = 0 # for x in n_str: # if x == '1': # count += 1 # return n # print FindNextLarger(13) '''5.4 Explain what the following code does: (n & (n-1)) == 0 Answer: 1000000 & 0111111 = 0 -> checks wether n is a power of 2. ''' '''5.5 Write a function to determine the number of bits required to convert integer A to integer B Input: 31, 14 Output: 2 ''' # def BitsSwapReq(a, b): # c = bin(a ^ b) # count = 0 # for x in c: # if x == '1': # count += 1 # return count # print BitsSwapReq(31, 14) '''5.6 Write a program to swap odd and even bits in an integer with as few instructions as possible (eg, bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc) ''' # def SwapOddEvenBits(n): # '''Assume the number is just 4 bits''' # Odd_shift = n & 0b1010 # Even_shift = n & 0b0101 # return bin((Odd_shift >> 1) | (Even_shift << 1)) # print SwapOddEvenBits(11)
5a1915f8abf3b9dbf51e4385fda88a133162cfd3
ischang/Practice-CS-Problems
/MiscInterview/nonrepeatCharStr.py
473
3.921875
4
# Find the first non-repeated character in a String # "call me ishmael" -- should be 'c' # "albus percival wulfric brian dumbledore" - should be 's' def nonRepeatChar(arr): repeatDict = {} for item in arr: if item in repeatDict.keys(): repeatDict[item] += 1 else: repeatDict[item] = 1 for item in arr: if repeatDict[item] == 1: return item return -1 print nonRepeatChar("honey uh blah") print nonRepeatChar("albus percival wulfric brian dumbledore")
da53016fc0297eaa8e5b2e4b919b0895bd04db7f
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/exercism/exercism-python-master/largest-series-product/series.py
797
4.25
4
"""Finds largest product of slices of digits of a give size""" def largest_product(digits, size): """Finds the largest product of slices of a given size""" # Why does a blank set of digits have a maximum product of 1? slice_list = slices(digits, size) def mult_reduce(items): total = 1 for i in items: total *= i return total slice_list = [mult_reduce(l) for l in slice_list] return max(slice_list) def slices(digits, size): """Returns list of lists of consecutive digits""" if not 0 <= size <= len(digits): raise ValueError elif digits == '': return [[1]] slice_list = [] for i in range(len(digits) - size + 1): slice_list.append([int(d) for d in digits[i:i+size]]) return slice_list
d60afba1bcf6630885e5a8e36a783edf9dc6cba7
ChangRui-Yao/pygame
/LINUX系统/linux实战/8.0/06--生成器的使用注意.py
1,822
3.90625
4
""" #创建一个生成器 #目标:实现斐波那契数列 #1)定义变量保存第一列和第二列的值 #2)定义变量保存当前生成的位置 #3)循环生成数据 条件是当前列数《总列数 #4)保存a的值 #5)修改a \ b 的值 #6)返回a的值 使用yield #2定义变量 保存生成器 #next(生成器)得到下一个元素值 """ #创建一个生成器 def fibnacci(n): #目标:实现斐波那契数列 #1)定义变量保存第一列和第二列的值 a = 1 b = 1 #2)定义变量保存当前生成的位置 weizhi = 0 print("-------------------111111111----------------") #3)循环生成数据 条件是当前列数《总列数 while weizhi < n : #4)保存a的值 data = a #5)修改a \ b 的值 a,b = b, a + b #列数加1 weizhi += 1 #6)返回a的值 使用yield #yield的作用: #能够充当return的作用 #能够保存程序的运行状态,并且暂停程序的执行 #当next()的时候,可以继续唤醒程序从yield位置往下执行 print("-------------222222222--------------") XXX = yield data print("--------------3333333--------------------") if XXX == 1: #生成器可以使用return,让生成器结束 return "哈哈,我是return,我能让生成器结束" #2定义变量 保存生成器 if __name__ == "__main__": fib = fibnacci(5) #next(生成器)得到下一个元素值 value = next(fib) print("第1列",value) try: value = next(fib) print("第2列",value) value = fib.send(1) print("第3列",value) except Exception as e: print(e)
33a3b4ffaade3d62bed510314b6bdbafdaeec7fd
ash/amazing_python3
/191-tuple-comma.py
256
4.0625
4
# How to create a tuple with # only one element x = ('value') # is it a tuple? print(type(x)) # it is a string y = ('value', ) # this comma makes it # a tuple (because the compiler # sees that you kind of want more # elements here) print(type(y)) # tuple
08bfdad01dd4e9eeeda0a83f107bc19cf90430a6
bsantos2/DataStructuresAlgos3
/problem_6.py
1,594
3.921875
4
def get_min_max(ints): result = merge_sort(ints) minmax = (result[0], result[-1]) return minmax def merge_sort(ints): if len(ints) <= 1: return ints midpoint = len(ints) // 2 left = ints[:midpoint] right = ints[(midpoint):] left = merge_sort(left) right = merge_sort(right) return merge_some(left, right) def merge_some(left, right): merged = [] left_index = 0 right_index = 0 while left_index < len(left) and right_index < len(right): if left[left_index] > right[right_index]: merged.append(right[right_index]) right_index += 1 else: merged.append(left[left_index]) left_index += 1 merged += left[left_index:] merged += right[right_index:] return merged #My answer to O(n) challenge. It's possible. Recording either the min or max while doing one by one check, #I was able to return the right answers with O(n), one pass of a for loop #But this is really not a sort. def min_max_o_n(list): minList = list[0] maxList = list[0] for x in list: if x < minList: minList = x if x > maxList: maxList = x result = tuple() result = (minList, maxList) return result ## Example Test Case of Ten Integers import random for k in range (0, 4): l = [i for i in range(0, 10)] # a list containing 0 - 9 random.shuffle(l) print ("\nTrial" + str(k)) print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail") print ("Pass for bonus routine" if ((0, 9) == min_max_o_n(l)) else "Fail")
8fdc4f53f341efc3af7fd9d00aa96f1283ce32f1
mohamed-elsayed/python-scratch
/list.py
7,749
4.5625
5
# ================================================= ################ LISTS ########################### # ================================================= # What is a list ? # It is just a collection or grouping of items! # Objective : # Describe , create and access a list data structure # Use built in methods to modify and copy ists. # Iterate over lists using loops and list comprehensions # Work with nested lists to build ore complex data structures # How are lists useful ? # A fundamental data structure for organizing collections of items. # comma seperated values, or even variables. # tasks = ["Install python","learn python"] # len(tasks) #return number of items in a list # It is abuilt in function (method) # create a list using list() built in function. # list(range(1,4)) # [1,2,3,4] # accessing values in a list # like ranges , lists always start counting at zero. # friends = ["mohamed", "ali","kandil"] # print (friends["1"]) # return ali # accessing values from the End , index backwards. # print (friends[-1]) # return kandil # checking if the value in a list use the in operator # "hany" in friends # False # accessing all values in a list # using for loop # for frind in friends: # print(frind) # using while loop # numbers = [1,2,3,4] # i =0 # while i < len(numbers): # print (numbers[i]) # i +=1 # list methods # working with lists is very common # append # add an item to the end of the list # data = [1,2,3] # data.append(4) # print (data) # [1,2,3,4] # extend # add to the end of the list all values passed to extend # first_list = [1,2,3,4] # first_list.append(5,6,7,8) # does not work ! # first_list.append([5,6,7,8]) # print (first_list) # [1,2,3,4,[5,6,7,8]] # correct_list = [1,2,3,4] # correct_list.extend([5,6,7,8]) # print(correct_list) #[1,2,3,4,5,6,7,8] one level list not nested # to add more items to the list use extend # insert # inser item at a given position # first_list = [1,2,3,4] # first_list.insert(2, "HI") # print (first_list)#[1,2,"HI",3,4] # first_list.insert(-1, "The end!") # print(first_list)#[1,2,"HI",3,"The end!",4] # clear #first_list = [1,2,3,4] # first_list.clear() # print(first_list) # [] # pop # remove the item at the given position in the list and return it. # if no index is specified, removes and returns last item in te list. # first_list = [1,2,3,4] # first_list.pop() # 4 # first_list.pop(1) # 2 remove item at index 1 # print (first_list) #[1,3] # remove # remove the first item from the list hose value is x # throws a ValueError if the item is not found. # first_list = [1,2,3,4,4,4] # first_list.remove(2) # print(first_list) # [1,3,4,4,4] # first_list.remove(4) # print(first_list) # [1,3,4,4] # index # return the index of the specified item in the list # numbers = [5,6,7,8,9,10] # numbers.index(6) # 1 return the index of first occurence of value # numbers.index(9) # 4 # numbers = [5,5,6,7,5,8,8,9,10] # numbers.index(5) # 0 # numbers.index(5, 1) # 1 return the index after the first occurence # numbers.index(5,2) # 4 return the index after the second occurence # numbers.index(8,6,8) #6 return the index of occurence between index and 8 # count # return the number of times x appears in the list # numbers = [1,2,3,4,3,2,1,4,10,2] # numbers.count(2) # 3 # numbers.count(21) #0 # numbers.count(3) # 2 # reverse # reverse the elemenrs of the list (in-place) # first_list = [1,2,3,4] # first_list.reverse() # no return value , changes in place # print(first_list) # [4,3,2,1] # sort # sort the items f the list in place in ascending order # another_list = [6,4,1,2,5] # another_list.sort() # return nothing # print (another_list) #[1,2,4,5,6] # join # used to convert list to string # technically a string method that takes an iterable argument # concatenates a copy of the base string between each item of the iterable # return a new string # can be used to make sentences out of a list of words by # joining on a space # words =[ 'codin', ' is', 'fun'] # ' '.join(words) # 'coding is fun ' # name = [ ' Mr' ,'Steel'] # '.'.join(name) # Mr.steele # slicing # make new lists using slices of the old list! # some_list[start:end:step] # first_list = [1,2,3,4] # first_list[1:] # from index 1 to the end [2,3,4] # first_list[3:] # [4] # slicing back from the end slice : start # first_list[-1:] # [4] # first_list2[:] # first_list == first_list2 # True # first_list is first_list2 # false # same values but different objects due to copying # The index to copy up to (exclusive ounting) slice: end # with negative numbers , how many items to exclude from the end i.e # indexing by counting backwards. # first_list = [1,2,3,4] # first_list[:-1] # [1,2,3] # first_list[1:-1] # [2,3] # slice :step # step in python is basically the number to count at a time # same as astep with range # with negative numbers, reverse the order # Tricks with slices # Reversing lists / strings # string = "This is fun!" # string[::-1] # modifying portion of a list # numbers = [1,2,3,4,5] # numbers[1:3] = ['a','b','c'] # print(numbers) # [1,'a','b','c', 4,5] # swapping values # names = ["james", "medo"] # names[0], names[1] = names[1], names[0] # print(names) # ["medo", "james"] # practical examples: shuffling, sorting (in-place), algorithms # list comprehension # The syntax # [----- for ---- in ------- ] # var-name for same-var-name in iteratable element # nums = [1,2,3] # [x*10 for x in nums] # [10,20,30] # list comprehension vs looping # numbers = [1,2,3,4,5] # doubled_numbers = [] # for num in numbers: # doubled_number = num *2 # doubled_numbers.append(doubled_number) # print(doubled_numbers) # numbers = [1,2,3,4] # doubled_numbers = [num *2 for num in numbers ] # print(doubled_numbers) # name = 'colt' # [char.upper() for char in name ] # ['C','O', 'L','T'] # [num* 10 for num in range(1,6)] # [10,20,30,40,50] # [bool(val) for val in [0,[],'']] ## [False , False, False] # numbers = [1,2,3,4,5] # string_list = [ str(num) for num in numbers ] #['1','2','3','4','5'] # list comprehension with conditional logic # numbers = [1,2,3,4,5,6] # evens = [ num for num in numbers if num % 2 == 0] # odds = [ num for num in numbers if num % 2 != 0 ] # [num * 2 if num % 2 == 0 else num/2 for num in numbers ] # # [0.5, 4, 1.5, 8, 2.5, 12] # with_vowels = "This is so much fun!" # '...'.join(["cool","dude"]) # cool...dude # [char for char in with_vowels if char not in "aeiou"]#['T','s',' ','s',...] # ''.join(char for char in with_vowels if char not in "aeiou") # nested list # list can contains any kind of element, even other lists # why ? # complex data structures - matricies # Games Boards / mazes # Rows and columns for visulaization # tabulation and grouping data # Accessing Nested lists # listed_list = [[1,2,3],[4,5,6],[7,8,9]] # listed_list[2][1] # 8 # listed_list[-1][1] # 8 # listed_list[2][-2] # 8 # printing values in nested lists # for l in listed_list: # for val in l : # print(val) # nested list comprehension # [[print(val) for val in l ] for l in nested_list] # board = [[num for num in range (1,4)] for val in range(1,4)] # [["x" if num % 2 != 0 else "o" for num in range (1,4)]for val in range (1,4)] # [["x","o","x"],["x","o","x"],["x","o","x"]] # Recap # lists are fundamental dat structures for ordered information # lists can be include any type , eb=ven other lists! # we can modify lists using a variety of methods # slices are quite useful when making copies of lists # list comprehension is used everywhere when iterating over # lists, strings, ranges and even more data types! # nested lists are essential for building more complex data # structures like matricies , game boards and mazes # swapping is quite useful when shuffling or sorting
6472cad359d0846baf1b88705b7554ccd1ae3b20
wagner30023/fundamentos_python
/mundo1/alunoAleatorio.py
267
3.765625
4
from random import choice n1 = str(input('>> primeiro nome: ')) n2 = str(input('>> segundo nome: ')) n3 = str(input('>> terceiro nome: ')) n4 = str(input('>> quarto nome: ')) list = [n1,n2,n3,n4] choice = choice(list) print('Aluno escolhido: {}'.format(choice))
41d240ddc519806a8da2088ccfae1202263755c3
daniel-reich/ubiquitous-fiesta
/s45bQoPtMoZcj7rnR_21.py
198
3.59375
4
def closest_palindrome(n): for i in range(n*10): if is_palindrome(n-i): return n-i if is_palindrome(n+i): return n+i def is_palindrome(n): return str(n) == str(n)[::-1]
b511cf01c823d67ac41fc9473d8869dcd3edcca8
SinghHarman286/Competitive-Programming
/DataStructures/binaryHeap.py
2,699
3.796875
4
''' Max Heap -> Parent nodes are always larger than the child -> Left nodes are filled first For any index n of an array, its left child is at 2n + 1, right child is at 2n + 2, parent is at (n - 1) / 2 NOTE: 1) For MinHeap, just reverse the signs in the below solutiom 2) For Priority Queue, define a new Node as follows - class Node: def __init__(self, val, priority): self.value = val self.priority = priority and just compare with self.values[idx].priority ''' class MaxHeap: def __init__(self): self.values = [] def insert(self, element): self.values.append(element) self.bubbleUp() def bubbleUp(self): idx = len(self.values) - 1 element = self.values[idx] while idx > 0: parentIdx = (idx - 1) // 2 parent = self.values[parentIdx] if parent >= element: # means its a maxheap break self.values[parentIdx], self.values[idx] = element, parent idx = parentIdx def extractMax(self): max = self.values[0] element = self.values.pop() if len(self.values) > 0: self.values[0] = element self.sinkDown() return max def sinkDown(self): idx = 0 element = self.values[idx] length = len(self.values) while True: leftChildIdx = 2*idx + 1 rightChildIdx = 2*idx + 2 swapIdx = None if leftChildIdx < length: leftChild = self.values[leftChildIdx] if leftChild > element: swapIdx = leftChildIdx if rightChildIdx < length: rightChild = self.values[rightChildIdx] if (swapIdx is None and rightChild > element) or (swapIdx is not None and rightChild > leftChild): swapIdx = rightChildIdx if swapIdx is None: break self.values[idx], self.values[swapIdx] = self.values[swapIdx], element idx = swapIdx def print(self): print(self.values) heap = MaxHeap() heap.print() heap.insert(1) heap.print() heap.insert(10) heap.print() heap.insert(5) heap.print() heap.insert(100) heap.print() heap.insert(45) heap.print() heap.insert(3) heap.print() print("======== Extracting now =======\n") heap.extractMax() heap.print() heap.extractMax() heap.print() heap.extractMax() heap.print() heap.extractMax() heap.print() heap.extractMax() heap.print()
2fdb9a705def1f5c68598bcafd4f05a4c5626a46
LuuizAlves/FTC-Projeto_Pratico_002
/projeto_pratico.py
3,686
3.640625
4
import ast #---------------------------- FUNÇÃO DA MULTIPLICAÇÃO ----------------------# def multiplicacao(x, y): lin_x = len(x) col_x = len(x[0]) lin_y = len(y) col_y = len(y[0]) res = [] for linha in range(lin_x): res.append([]) for coluna in range(col_y): res[linha].append(0) for k in range(col_x): res[linha][coluna] += x[linha][k] * y[k][coluna] return res #------------------------- FUNÇÃO QUE CRIA PI TRANPOSTO -----------------------# def criandoPit(qtd_est, est_ini): vetorPi = [] for i in range(qtd_est): vetorPi2 = [] for j in range(1): if i == est_ini: vetorPi2.append(1) else: vetorPi2.append(0) vetorPi.append(vetorPi2) matriz_T = [] for i in range(1): linha = [] for j in range(qtd_est): linha.append(0) matriz_T.append(linha) for i in range(1): for j in range(qtd_est): matriz_T[i][j] = vetorPi[j][i] #print('MATRIZ PI TRANSPOSTA: ') return matriz_T #-------------------------- FUNÇÃO QUE CRIA A MATRIZ N ---------------------# def criandoN(qte_est, ests_finais): matriz_n = [] for i in range(qtd_est): linha = [] for j in range(1): if i in ests_finais: linha.append(1) else: linha.append(0) matriz_n.append(linha) #print('MATRIZ N: ') return matriz_n #------------------------- FUNÇÃO QUE CRIA Xa ------------------------------# def criandoXa(delta): criandoxa = [] k = 0 for i in range(qtd_est): ad = delta[i][k] criandoxa.append(ad) xa = [] for i in range(qtd_est): linha = [] for j in range(qtd_est): linha.append(0) xa.append(linha) for i in range(qtd_est): a = criandoxa[i] xa[i][a] = 1 #print('MATRIZ Xa: ') return xa #------------------------- FUNÇÃO QUE CRIA Xb -------------------------------# def criandoXb(delta): criandoxb = [] k = 1 for i in range(qtd_est): ad = delta[i][k] criandoxb.append(ad) xb = [] for i in range(qtd_est): linha = [] for j in range(qtd_est): linha.append(0) xb.append(linha) for i in range(qtd_est): a = criandoxb[i] xb[i][a] = 1 #print('MATRIZ Xb: ') return xb #--------------------------- RESULTADOS DAS PALAVRAS ----------------------# def resultadosFinais(palavra, pit, mn, mxa, mxb): tamanho_palavra = len(palavra) resultado = [] for i in range(tamanho_palavra): if i == 0: if palavra[i] == 'a': resultado = multiplicacao(pit, mxa) elif palavra[i] == 'b': resultado = multiplicacao(pit, mxb) else: if palavra[i] == 'a': resultado = multiplicacao(resultado, mxa) elif palavra[i] == 'b': resultado = multiplicacao(resultado, mxb) resultadof = multiplicacao(resultado, mn) if (resultadof[0][0] == 1): print('ACEITA') else: print('REJEITA') x = input() y = ast.literal_eval(x) qtd_est = y['estados'] est_ini = y['inicial'] ests_finais = y['final'] delta = y['delta'] lind = len(delta) for i in range(lind): delta[i].sort() pit = criandoPit(qtd_est, est_ini) mn = criandoN(qtd_est, ests_finais) mxa = criandoXa(delta) mxb = criandoXb(delta) inteiro = input() trans = int(inteiro) for i in range(trans): palavra = input() resultadosFinais(palavra, pit, mn, mxa, mxb)
5d24820407fc04f9f166293555e222f396bfb60c
jhovan/ContactBook
/contactBook.py
4,875
4.0625
4
#Gallardo Valdez Jose Jhovan #06/09/2016 #Contact book import re class invalidEmail(Exception): pass class invalidNumber(Exception): pass #asks for a telephone number def askNumber(message): while True: try: number=raw_input(message) if len(number)!= 10: raise invalidNumber number=int(number) return number except ValueError: print "Invalid number, it's not an integer, try again" except invalidNumber: print "The number should have ten digits, try again" #asks for an email def askEmail(): while True: try: email=raw_input("Write an email:") if re.match('^[(a-z0-9\_\-\.)]+@[(a-z0-9\_\-\.)]+\.[(a-z)]{2,15}$',email.lower()): return email else: raise invalidEmail except invalidEmail: print "Invalid email, try again" #Class person that represents a person and his data class Person: #constructor of the class def __init__(self, data): self.name=data[0] self.surname=data[1] self.home=data[2] self.mobile=data[3] self.email=data[4] #to string method def __str__(self): return "\n" + self.name + " " + self.surname + "\n" + str(self.home) + "\n" + str(self.mobile) + "\n" + self.email + "\n" #returns a string with the data to save in a file def data(self): return self.name + "-" +self.surname + "-" + str(self.home) + "-" + str(self.mobile) + "-" + self.email + "-" #class book that represents a contact book class Book: #constructor of the class def __init__(self,name): self.list=[] self.name=name #reads the file and takes the data from the file def read(self): self.list=[] f=open(self.name + ".txt","r") for line in f.readlines(): if len(line) > 1: self.list.append(Person(line.split("-"))) f.close() #writes the data to the file def write(self): f=open(self.name + ".txt","w") for person in self.list: f.write(person.data() + "\n") f.close() #show all the contacts in the book def show(self): self.read() for person in self.list: print str(person) if len(self.list)==0: print "The book is empty" #add a new contact to the book (and ask for the data) def add(self): self.read() data=[] data.append(raw_input("Write the name(s):")) data.append(raw_input("Write the surname(s):")) data.append(askNumber("Write the home telephone number:")) data.append(askNumber("Write the mobile number:")) data.append(askEmail()) self.list.append(Person(data)) self.write() #looks for coincidences in the contacts def searchCoincidences(self): name=raw_input("Write what you want to search:") self.read() c=0 for person in self.list: if (name in person.name) or (name in person.surname): c+=1 print str(person) if c==0: print "No coincidences" #return a person after asking for his name def buscarNameSurname(self): name=raw_input("Write the name(s):") surname=raw_input("Write the surname(s):") self.read() for person in self.list: if person.name==name and person.surname==surname: return person print "Contact not found" return None #deletes a person from the book def delete(self): person=self.buscarNameSurname() if person != None: self.list.remove(person) print "Contact deleted" self.write() #deletes all the persons in the book def deleteAll(self): self.list=[] self.write() #allows the user to edit a contact def edit(self): person=self.buscarNameSurname() if person != None: op=input("Choose a number:\n1.Name(s)\n2.Surname(s)\n3.Home number\n4.Mobile number\n5.Email\n") if op==1: name=raw_input("Write the name(s):") person.name=name print "name updated" elif op==2: surname=raw_input("Write the surname(s):") person.surname=surname print "surname updated" elif op==3: person.home=askNumber("Write the home number:") print "home number updated" elif op==4: person.mobile=askNumber("Write the mobile number:") print "mobile number updated" elif op==5: person.email=askEmail() print "email updated" else: print "invalid choice" self.write() #Opens a book (the file it's in the same directory that the code) while True: try: name=raw_input("Write the name of the book:") book=Book(name) book.read() print "Book opened" break except: dec=input("The book doesn't exist, do you want to create it?\n1.Yes\n2.No\n") if dec==1: book.write() break #Main menu op=1 while(op!=7): op=input("Choose a number:\n1.Add contact\n2.Search contact\n3.Delete contact\n4.Edit contact\n5.Show all contacts\n6.Delete all contacts\n7.Exit\n") if(op==1): book.add() print "Contact added" elif(op==2): book.searchCoincidences() elif(op==3): book.delete() elif(op==4): book.edit() elif(op==5): book.show() elif(op==6): dec=input("Are you sure?\n1.Yes\n2.No\n") if dec==1: book.deleteAll() print "The book is empty" elif(op!=7): print "Invalid choice"
da58e2863ec05d6006db8849da0dd0eefc882237
bgoonz/UsefulResourceRepo2.0
/_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/mini-scripts/Python_Comparison_Operators_(not_equal).txt.py
89
3.578125
4
x = 5 y = 3 print(x != y) # returns True because 5 is not equal to 3 # Author: Bryan G
48934276a924c07e73c1885f5d6cac9193ee3eff
mohanakrishnavh/Data-Structures-and-Algorithms-in-Python
/recursion/RecursiveStringReversal.py
539
4.09375
4
def recursive_string_reversal(s, output=None): # Base Case if len(s) <= 1: return s # recursion else: if output is None: output = "" output += s[-1] else: output += s[-1] return output + recursive_string_reversal(s[0:len(s)-1]) return output str1 = "Hello World" output = recursive_string_reversal(str1) print(output) ''' def reverse(s): # Base Case if len(s) <= 1: return s # recursion return reverse(s[1:]) + s[0] '''
3c809666d40c73f25690761306857f106441d2b8
JoyceYang2018/pythonDA
/Data_Structure/recursion.py
1,968
3.5
4
# coding: utf-8 from turtle import * def to_str(n, base): convert_str = '0123456789' if n < base: return convert_str[n] return to_str(n // base, base) + convert_str[n % base] def tree(branch_len, t): if branch_len > 5: t.forward(branch_len) t.right(20) tree(branch_len - 15, t) t.left(40) tree(branch_len - 10, t) t.right(20) t.backward(branch_len) def draw_triangle(points, color, t): t.fillcolor(color) t.up() t.goto(points[0]) t.down() t.begin_fill() t.goto(points[1]) t.goto(points[2]) t.goto(points[0]) t.end_fill() def get_mid(p1, p2): return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2 def sierpinski(points, degree, t): color_map = ['blue', 'red', 'green', 'white', 'yellow', 'violet', 'orange'] draw_triangle(points, color_map[degree], t) if degree > 0: sierpinski([points[0], get_mid(points[0], points[1]), get_mid(points[0], points[2])], degree - 1, t) sierpinski([points[1], get_mid(points[1], points[0]), get_mid(points[1], points[2])], degree - 1, t) sierpinski([points[2], get_mid(points[2], points[1]), get_mid(points[2], points[0])], degree - 1, t) def move_tower(height, from_disk, to_disk, with_disc): if height >= 1: move_tower(height-1, from_disk, with_disc, to_disk) move_disk(from_disk, to_disk) move_tower(height-1, with_disc, to_disk, from_disk) def move_disk(from_disk, to_disk): print("moving disk from %s to %s\n" % (from_disk, to_disk)) if __name__ == '__main__': # t = Turtle() # mywin = t.getscreen() # t.left(90) # t.up() # t.backward(300) # t.down() # t.color('green') # tree(100, t) # mywin.exitonclick() # t = Turtle() # mywin = t.getscreen() # points = [(-500, -250), (0, 500), (500, -250)] # sierpinski(points, 5, t) # mywin.exitonclick() move_tower(3, 'A', 'C', 'B')
398be4eac11899b464ef42d17e3895b2260296ae
lemon-l/Online-Judge
/算法训练/数组查找及替换.py
775
3.5625
4
''' Description   给定某整数数组和某一整数b。要求删除数组中可以被b整除的所有元素,同时将该数组各元素按从小到大排序。如果数组元素数值在A到Z的ASCII之间,替换为对应字母。元素个数不超过100,b在1至100之间。 Input 输入描述:   第一行为数组元素个数和整数b   第二行为数组各个元素 输入样例: Output 输出描述:   按照要求输出 输出样例: ''' num, b = map(int, input().split()) list1 = list(map(int, input().split())) list2 = list1.copy() for i in list2: if(i % b == 0): list1.remove(i) list1.sort() for i in list1: if(i >= ord('A') and i <= ord('Z')): i = chr(i) print(i, end = ' ')
1508a1c13e6d6e425f91230ddc402e3979d15a26
jasonkhs192/PythonPractice
/trynumpy.py
1,941
3.53125
4
# import numpy as np # # a = np.array([1,2,3]) # b = np.array([[4,5,6,7,8],[1,2,3,4,5]]) # num = [1,2,3,4,5] # x = min(num) # # # def centered_average(nums): # x = int(len(nums)/2 + 0.5) # if len(nums)%2 == 0: # print((nums[x] + nums[x-1])/2) # else: # print((nums[x-1])) # # # centered_average([5,3,4,6,2]) # # class Champion: # def __init__(self, name, attack_dmg, ability_dmg, attack_speed, movement_speed, attack_range, hp): # self.name = name # self.attack_dmg = attack_dmg # self.ability_dmg = ability_dmg # self.attack_speed = attack_speed # self.movement_speed = movement_speed # self.attack_range = attack_range # self.hp = hp # # def stat(self): # print("{}: \n Attack Damage [{}] \n Ability Power [{}] \n Attack Speed [{}] \n Movement Speed [{}] \n Attack Range [{}] \n HP [{}]".format(self.name, self.attack_dmg, self.ability_dmg, self.attack_speed, self.movement_speed, self.attack_range, self.hp)) # # def attack(self, enemy): # self.enemy = enemy # print("{} attacked {}. {} took -{} damage".format(self.name, enemy, enemy, self.attack_dmg)) # c1 = Champion("Garen", 85, 0, 0.58, 350, 150, 485) # c1.stat() # c1.attack("Darius") # def quick_sort(sequence): # length = len(sequence) # if length <= 1: # return sequence # else: # pivot = sequence.pop() # print(pivot) # items_greater = [] # items_lower = [] # # for x in sequence: # if x > pivot: # items_greater.append(x) # else: # items_lower.append(x) # # return quick_sort(items_lower) + [pivot] + quick_sort(items_greater) # # ans = quick_sort([5,4,3,2,1]) # # print(ans) # class Solution: def romanToInt(self, s): symbol = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } total = 0 for x in s: total = total + symbol[x] Solution().romanToInt("IXLCD")
02c71c50aef4c6383d17a538ede7e9380b4a7eef
MVasanthiM/guvi
/programs/binary.py
101
3.84375
4
n=input() b=set(n) g={'0','1'} if g==b or b=={'0'} or b=={'1'}: print("yes") else: print("no")
7146fa5418cd5dd051b7c623135cb164fe12d578
nischalshrestha/automatic_wat_discovery
/Notebooks/py/saimarapareddy/titanic-accuracy-80/titanic-accuracy-80.py
6,616
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # List of libraries used import pandas as pd import numpy as np from sklearn import preprocessing from IPython.display import display # Allows the use of display() for DataFrames from sklearn.preprocessing import LabelEncoder # Used for label encoding the data # In[ ]: #Import the data data_train = '../input/train.csv' data_train_df = pd.read_csv(data_train) data_test = '../input/test.csv' data_test_df = pd.read_csv(data_test) # In[ ]: # Find missing data data_train_df.info() # In[ ]: #Using data_train_df.info() we can observe that Age, Cabin, Embarked have missing values #lets analyze Age #reference - http://seaborn.pydata.org/generated/seaborn.FacetGrid.html sns.set(style="ticks", color_codes=True) g = sns.FacetGrid(data_train_df, col="Sex", row="Survived") g = g.map(plt.hist, "Age") # In[ ]: #Lets Analyze Embarked missing values #data_train_df[data_train_df['Embarked'].isnull()] data_train_df[data_train_df['Fare'] > 70.0] #&& data_train_df['Cabin']=='B28'] # In[ ]: # Import the data data_train = '../input/train.csv' data_train_df = pd.read_csv(data_train) data_test = '../input/test.csv' data_test_df = pd.read_csv(data_test) # In[ ]: # Find missing data data_train_df.info() # Print Missing data print("Age, Cabin, Embarked have missing values") # In[ ]: # Analyze missing values in Embarked column # Lets check which rows have null Embarked column #data_train_df[data_train_df['Embarked'].isnull()] #data_train_df[data_train_df['Name'].str.contains('Martha')] #data_train_df[(data_train_df['Fare'] > 50) & (data_train_df['Age'] > 37) & (data_train_df['Survived']==1 ) & # (data_train_df['Pclass']== 1 ) & (data_train_df['Cabin'].str.contains('B')) ] #data_train_df[data_train_df['Ticket'] == 113572] data_train_df[data_train_df['Ticket']==111361] # In[ ]: #Segregate and trim the data # Apply Label encoding data_train_df['Embarked'] = data_train_df['Embarked'].astype(str) data_train_df['Cabin'] = data_train_df['Cabin'].astype(str) data_test_df['Embarked'] = data_test_df['Embarked'].astype(str) data_test_df['Cabin'] = data_test_df['Cabin'].astype(str) le = LabelEncoder() data_train_df = data_train_df.apply(LabelEncoder().fit_transform) #display(data_train_df) data_test_df = data_test_df.apply(LabelEncoder().fit_transform) #display(data_test_df) data_train_df_survived = data_train_df['Survived'] #returns a numpy array data_train_df_trim = data_train_df.drop(['Survived','Name','PassengerId'], axis=1).values data_test_df_trim = data_test_df.drop(['Name','PassengerId'], axis=1).values # In[ ]: #Normalize data min_max_scaler = preprocessing.MinMaxScaler() # Used for normalized of the data data_train_df_trim_scaled = min_max_scaler.fit_transform(data_train_df_trim) data_train_df_trim_scaled = pd.DataFrame(data_train_df_trim_scaled) data_test_df_trim_scaled = min_max_scaler.fit_transform(data_test_df_trim) data_test_df_trim_scaled = pd.DataFrame(data_test_df_trim_scaled) # In[ ]: from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_predict, cross_val_score, KFold from sklearn.model_selection import ShuffleSplit def implement_randomForestClassifier(X_train,y_train,X_test,number_of_estimators=10,max_depth=None, minimum_samples_split=2,minimum_samples_leaf=1,random_number=42): """ This function fits and transforms data using Random Forest Classifier technique and returns the mean of y_pred value """ clf = RandomForestClassifier(n_estimators=number_of_estimators,min_samples_split=minimum_samples_split, min_samples_leaf=minimum_samples_leaf,random_state=random_number) kf = KFold(n_splits=3, random_state=2) cv = ShuffleSplit(n_splits=10, test_size=0.3, random_state=42) predictions = cross_val_predict(clf, X_train,y_train,cv=kf) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) scores = cross_val_score(clf, X_train, y_train,scoring='f1', cv=kf) print(scores.mean()) ''' Plot the features wrt their importance ''' importances = clf.feature_importances_ std = np.std([tree.feature_importances_ for tree in clf.estimators_], axis=0) indices = np.argsort(importances)[::-1] # Print the feature ranking print("Feature ranking:") for f in range(X_train.shape[1]): print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) # Plot the feature importances of the forest plt.figure() plt.title("Feature importances") plt.bar(range(X_train.shape[1]), importances[indices], color="r", yerr=std[indices], align="center") plt.xticks(range(X_train.shape[1]), indices) plt.xlim([-1, X_train.shape[1]]) plt.show() ''' Return the mean of predicted scores ''' return y_pred # In[ ]: #Finding optimum estimator in case of RFC #reference - https://matthew-nm.github.io/pages/projects/gender04_content.html from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt def calculate_optimum_estimator_rfc(X_train,y_train,X_test,y_test,interval=5): error_rate = [] nvals = range(1,800,interval) # test a range of total trees to aggregate for i in nvals: rfc = RandomForestClassifier(n_estimators=i) rfc.fit(X_train,y_train) y_pred_i = rfc.predict(X_test) error_rate.append(np.mean(y_pred_i != y_test)) plt.plot(nvals, error_rate, color='blue', linestyle='dashed', marker='o', markerfacecolor='red', markersize=10) plt.title('Error Rate vs. Number of Predictors') plt.xlabel('Number of Predictors') plt.ylabel('Error Rate') # Determine location of best performance nloc = error_rate.index(min(error_rate)) print('Lowest error of %s occurs at n=%s.' % (error_rate[nloc], nvals[nloc])) return nvals[nloc] # In[ ]: X_train, X_test, y_train, y_test = train_test_split(data_train_df_trim_scaled,data_train_df_survived,test_size=0.2, random_state=42) optimum_value = calculate_optimum_estimator_rfc(X_train,y_train,X_test,y_test,5) # In[ ]: y_pred = implement_randomForestClassifier(data_train_df_trim_scaled,data_train_df_survived, data_test_df_trim_scaled,101) # In[ ]: data_test_v1 = pd.read_csv(data_test) submission = pd.DataFrame({ "PassengerId": data_test_v1["PassengerId"], "Survived": y_pred }) submission.to_csv("titanic_submission.csv", index=False) # In[ ]:
7e1b0c41bdc33414cf9398fb188b523716c758bf
jazznerd206/Snake
/list_ops/all_unique.py
430
4.15625
4
# all_unique # Checks a flat list for all unique values. Returns True if list values are all unique and False if list values aren't all unique. # This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list. def all_unique(lst): return len(lst) == len(set(lst)) x = [1,2,3,4,5,6] y = [1,2,2,3,4,5] print(all_unique(x)) # True print(all_unique(y)) # False
5ad4eb2ad15f4a95c0a0b88ff559fc566e88e9a5
lebuingockhang123/L-p-tr-nh-python
/LeBuiNgocKhang_53157_CH03/Projects/page_99_exercise_11.py
1,757
3.96875
4
""" Author: Le Bui Ngoc Khang Date: 12/07/1997 Problem: In the game of Lucky Sevens, the player rolls a pair of dice. If the dots add up to 7,the player wins $4; otherwise, the player loses $1. Suppose that, to entice the gullible, a casino tells players that there are lots of ways to win: (1, 6), (2, 5), and soon. A little mathematical analysis reveals that there are not enough ways to winto make the game worthwhile; however, because many people’s eyes glaze over at the first mention of mathematics, your challenge is to write a program that demonstrates the futility of playing the game. Your program should take as input the amount of money that the player wants to put into the pot, and play the game until the pot is empty. At that point, the program should print the number of rolls it took to break the player, as well as maximum amount of money in the pot. Solution: Enter dollars: 15 The number of rolls it took to break the player 180 rolls. quit after 154 rolls when you had $16. """ import random # request the input dollars = int(input("Enter dollars: ")) # initialize variables maximum_amount = dollars countMax = 0 count = 0 # loop until the money is gone while dollars > 0: count += 1 # roll the dice dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) # calculate the winnings or losses if dice1 + dice2 == 7: dollars += 4 else: dollars -= 1 # if this is a new maximum, remember it if dollars > maximum_amount: maxdollars = dollars countMax = count # display the results print("The number of rolls it took to break the player " + str(count) + " rolls.\n" + "quit after " + str(countMax) + " rolls when you had $" + str(maxdollars) + ".")
49fd88e75727fc6576d95ede3ab526f3adfbaf09
ajustinpadilla/python_projects
/Python_and_Sql/exampleDB.py
796
3.765625
4
import sqlite3 fileList = ('information.docx', 'Hello.txt', 'myImage.png', 'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg') conn = sqlite3.connect("files.db") with conn: cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS tbl_files( \ ID INTEGER PRIMARY KEY AUTOINCREMENT, \ fileName TEXT NOT NULL \ )") for file in fileList: if 'txt' in file: cur.execute("INSERT INTO tbl_files \ (fileName) \ VALUES (?)", [file]) conn.commit() cur.execute("SELECT fileName FROM tbl_files") txtFiles = cur.fetchall() Files= () for file in txtFiles: Files += file print("The files in the database are:\n{}\n{}".format(Files[0], Files[1])) conn.close
476e6447b992240ce375cddf2042f29fec9d51f0
larj3852/Curso_Python
/21 - Tkinter/09 - Ejercicio.py
1,867
3.859375
4
""" REALIZACION DE UNA CALCULADORA CON: - Dos campos de texto - 4 botones para las operaciones - Mostar el resulltado en una alerta """ from tkinter import * from tkinter import messagebox ventana= Tk() ventana.title("Ejercisio: Calculadora") ventana.geometry("400x300") num1 = StringVar() num2 = StringVar() resultado=StringVar() #Funciones def convertfloat(numero): #Evita que se metan otros datos que no sean numeros try: result= float(numero) return result except: messagebox.showerror("Error","Introduce numeros") def sumar(): resultado.set(convertfloat(num1.get())+convertfloat(num2.get())) Mostrarresultado() def restar(): resultado.set(convertfloat(num1.get())-convertfloat(num2.get())) Mostrarresultado() def multiplicar(): resultado.set(convertfloat(num1.get())*convertfloat(num2.get())) Mostrarresultado() def dividir(): resultado.set(convertfloat(num1.get())/convertfloat(num2.get())) Mostrarresultado() def Mostrarresultado(): messagebox.showinfo("Resultado",f"EL resultado de la operacion es: {resultado.get()}") #Marco marco = Frame(ventana,width=300,height=200) marco.config(bd=5, relief=SOLID ) marco.pack(side=TOP, anchor=CENTER) marco.pack_propagate(False) #Entrada botones Label(marco,text="Primer Numero").pack() Entry(marco,textvariable = num1,justify="center").pack() Label(marco,text="Segundo Numero").pack() Entry(marco,textvariable = num2,justify="center").pack() #Operaciones Button(marco,text="Sumar",command=sumar).pack(side=LEFT,fill=X, expand=YES) Button(marco,text="Restar",command=restar).pack(side=LEFT,fill=X, expand=YES) Button(marco,text="Multiplicar",command=multiplicar).pack(side=LEFT,fill=X, expand=YES) Button(marco,text="Dividir",command=dividir).pack(side=LEFT,fill=X, expand=YES) ventana.mainloop()
41994a1d041e34a5a9db45f320766d9e44c8292a
tboschi/advent-of-code-2020
/day01/py/part1
499
3.640625
4
#! /bin/python import sys if len(sys.argv) < 1: print("Input file expected", file=sys.stderr) sys.exit(1) with open(sys.argv[1]) as infile: costs = [] for line in infile: x = int(line.strip()) # storing line costs.append(x) if 2020 - x in costs[:-1]: # looking for 2020 - x print(f"Found! {x} + {2020-x} = 2020") print(f"Result is {x * (2020 - x)}") sys.exit(0) else: print("Did not find anything...")
d3ba96f994ca577efaa630ed6be12d67f679389d
GersonFeDutra/Python-exercises
/CursoemVideo/2020/world_2/ex038.py
383
4.21875
4
numbers: list = [ int(input('Enter an integer: ')), int(input('Enter another integer: ')) ] if numbers[0] > numbers[1]: print(f'The number {numbers[0]} is bigger than the number {numbers[1]}') elif numbers[0] < numbers[1]: print(f'The number {numbers[0]} is smaller than the number {numbers[1]}') else: print('The two entered numbers are equal.')
24818981a718608209881eb598a5a5308f370c9a
DonghwanKIM0101/CS454Project
/ExamplePrograms/trityp.py
931
3.53125
4
#https://www.cs.mtsu.edu/~untch/4900/public/trityp.c def trityp(i,j,k): TRIANG = 0 # TRIANG = 1 IF TRIANGLE IS SCALENE # TRIANG = 2 IF TRIANGLE IS ISOSCELES # TRIANG = 3 IF TRIANGLE IS EQUILATERAL # TRIANG = 4 IF NOT A TRIANGLE if (i<=0)or(j<=0)or(k<=0): TRIANG = 4 return TRIANG TRIANG = 0 if (i==j): TRIANG=TRIANG+1 if (i==k): TRIANG=TRIANG+1 if (j==k): TRIANG=TRIANG+1 # Confirm it's a legal triangle before declaring it to be scalene if (TRIANG==0): if (i+j)<=k or (j+k)<=i or (i+k)<=j: TRIANG = 4 else: TRIANG = 1 return TRIANG if (TRIANG>3): TRIANG = 3 else if (TRIANG==1) and (i+j)>k: TRIANG = 2 else if (TRIANG==2) and (i+k)>j: TRIANG = 2 else if (TRIANG==3) and (j+k)>i: TRIANG = 2 else: TRIANG = 4 return TRIANG
71a8f0661e23056125538ae39c9f2203ea46e99d
NikiDimov/SoftUni-Python-Basics
/conditional_statements/godzilla_vs_kong.py
499
3.8125
4
budget = float(input()) extras = int(input()) price_clothes = float(input()) decor = budget * 0.1 def movie_maker(budget, extras, price_clothes): if extras > 150: price_clothes -= price_clothes * 0.1 total = price_clothes * extras + decor if total > budget: return f"Not enough money!\nWingard needs {total - budget:.2f} leva more." return f"Action!\nWingard starts filming with {budget - total:.2f} leva left." print(movie_maker(budget, extras, price_clothes))
20982a35fbba0fa0e026d755b3df0d399af8d41b
cil0834/Reflection_Summer
/Format_Dates.py
4,048
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 12:31:50 2019 @author: KLAGG """ import numpy as np def dates_in_myrors( years, months, step=5): """Formats the dates so that they have the 'yyyy-dd-mm-hhmmss' format :param years: the years that will formatted :param months: the months that will be formatted :param step: the interval in minutes that a new time is generated :return: conventional_dates: a 1D array of the dates in 'yyyy-dd-mm-hhmmss' format """ # Create the numpy array that will hold the dates in yyyy-dd-mm-hhmmss format conventional_dates = np.array([]) for year in years: for month in months: # If there are only 30 days in the month if month == ('04' or '06' or '09' or '11'): for day in range(1, 31): day = str(day) for hour in range(0, 24): h = str(hour) if hour < 10: h = '0' + h # Step size is 5 because we only want every 5 minutes for minute in range(0, 60, step): m = str(minute) if minute < 10: m = '0' + m time = h + m + '00' conventional_dates = np.append(conventional_dates, year + '-' + month + '-' + day + '-' + time) # If there are 31 days in the month if month == ('01' or '03' or '05' or '07' or '08' or '10' or '12'): for day in range(1, 32): day = str(day) for hour in range(0, 24): h = str(hour) if hour < 10: h = '0' + h for minute in range(0, 60, step): m = str(minute) if minute < 10: m = '0' + m time = h + m + '00' conventional_dates = np.append(conventional_dates, year + '-' + month + '-' + day + '-' + time) # If not a leap year if month == ('02') and (int(year) % 4 != 0): for day in range(1, 29): day = str(day) for hour in range(0, 24): h = str(hour) if hour < 10: h = '0' + h for minute in range(0, 60, step): m = str(minute) if minute < 10: m = '0' + m time = h + m + '00' conventional_dates = np.append(conventional_dates, year + '-' + month + '-' + day + '-' + time) # If leap year if month == ('02') and (int(year) % 4 == 0): for day in range(1, 30): day = str(day) for hour in range(0, 24): h = str(hour) if hour < 10: h = '0' + h for minute in range(0, 60, step): m = str(minute) if minute < 10: m = '0' + m time = h + m + '00' conventional_dates = np.append(conventional_dates, year + '-' + month + '-' + day + '-' + time) return conventional_dates
332cfc5d737a3efb14dc6fdbf92c6df37b4a3107
GitCupper/lenPython
/day01/012-guessnumber01.py
417
3.984375
4
res = 45 input_num = 0 while True: input_num = int(input("请输入一个数字(1-100):")) if input_num < 0 or input_num > 100: print("You have inputted a wrong number.") break elif input_num < res: print("Your number is too small!") elif input_num > res: print("Your number is too big!") else: print("You are right, it is %d!" % res) break
280150f5aaf49a9743ec49a1c5a953c61d5ba265
AjayS1509/Hackerrank
/Python/power_mod.py
197
3.8125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def main(): a = int(input()) b = int(input()) m = int(input()) print(pow(a,b)) print(pow(a,b,m)) main()
5309169e9969d013d6b7d9cfd94e669148dde0ab
BeemerCodes/Estudos-de-Python
/Guanabara/Aula if else.py
750
4.15625
4
#tempo = int(input('Quantos anos tem seu carro? ')) #print('UAU!, Seu carro é novo!' if tempo <= 3 else 'Poxa!, Seu carro é velho :(') #print('-------FIM-------') #Inicio Dos Estudos em if and else: #nome = str(input('Qual é seu nome: ')) #if nome == 'Pedro': # print('Que nome lindo!') #else: # print('Que nome comum...') #print('Bom dia, {}'.format(nome)) #n1 = float(input('Digite a primeira nota: ')) #n2 = float(input('Digite a segunda nota: ')) #m = (n1 + n2)/2 #print('Sua média foi: {:.1f}'.format(m)) #if m >= 6.0: # print('Sua média foi boa, Parabens!!') #else: # print('Sua média foi ruim!, Estude mais!') #** Para simplificar seria: print('Parabens!' if m >= 6 else 'Estude mais')**
ce1225891fd6e66f38eb96bffe81290fea6efde4
SuzyWu2014/Course-work-Algs
/tsp-final/tspFuns.py
6,623
3.6875
4
from math import sqrt __author__ = 'suzy' def readfile(path): f = open(path) n = 0 cities = [] while 1: lines = f.readlines(100) if not lines: break for line in lines: cities = cities + [[int(i) for i in line.split()]] n = n + 1 return cities, n def merge(left, right, k): # k->index in array that is used as reference for sorting length = len(left) + len(right) i = j = 0 combine = [] while len(combine) < length: if left[i][k] < right[j][k]: combine.append(left[i]) if i == len(left) - 1: combine.extend(right[j:]) break else: i = i + 1 else: combine.append(right[j]) if j == len(right) - 1: combine.extend(left[i:]) break else: j = j + 1 return combine def mergeSort(array, k): length = len(array) if length == 1 or length == 0: return array else: mid = int(length / 2) left = array[:mid] right = array[mid:] leftOrd = mergeSort(left, k) rightOrd = mergeSort(right, k) return merge(leftOrd, rightOrd, k) def rebuildTour(dstSelected, tour): dstSelected = mergeSort(dstSelected, 2) cityA = dstSelected[0][0] cityB = dstSelected[0][1] a = tour.index(cityA) b = tour.index(cityB) if a > b: a, b = b, a tour1 = tour[:a + 1] tour2 = tour[b:] tour2.extend(tour1) return tour2 def calDistance(cityA, cityB): """cityA (index,x,y)""" d = int(round(sqrt(pow((cityA[1] - cityB[1]), 2) + pow((cityA[2] - cityB[2]), 2)))) return d def addPathToTour(city1, city2, visited, tour, dstSelected, route): """Add path city1<->city2 to tour city1(index,x,y) """ cityA = city1[0] cityB = city2[0] if cityB<cityA: cityA,cityB=cityB,cityA if visited[cityA] < 2 and visited[cityB] < 2: isFound = 0 isCircle = 0 for subtour in tour: lg = len(subtour) if subtour[0] == cityA: isFound = 1 if subtour[lg - 1] != cityB: subtour.insert(0, cityB) else: isCircle = 1 break elif subtour[0] == cityB: isFound = 1 if subtour[lg - 1] != cityA: subtour.insert(0, cityA) else: isCircle = 1 break elif subtour[lg - 1] == cityA: isFound = 1 if subtour[0] != cityB: subtour.insert(lg, cityB) else: isCircle = 1 break elif subtour[lg - 1] == cityB: isFound = 1 if subtour[0] != cityA: subtour.insert(lg, cityA) else: isCircle = 1 break if isFound == 0: tour.insert(0, [cityA, cityB]) if isCircle == 0: d = calDistance(city1, city2) dstSelected.append([cityA, cityB, d]) route = route + d visited[cityA] = visited[cityA] + 1 visited[cityB] = visited[cityB] + 1 return visited, tour, dstSelected, route def combineSubtours(route, tour, visited, dstOrdered): i = len(tour) - 1 while i > 0: isInsert = 0 for subtour in tour[:i]: lg = len(subtour) t = len(tour[i]) if tour[i][0] == subtour[0]: j = 1 while j < t: subtour.insert(0, tour[i][j]) j = j + 1 isInsert = 1 elif tour[i][0] == subtour[lg - 1]: j = 1 while j < t: subtour.insert(lg, tour[i][j]) lg = lg + 1 j = j + 1 isInsert = 1 elif tour[i][t - 1] == subtour[0]: j = t - 2 while j >= 0: subtour.insert(0, tour[i][j]) j = j - 1 isInsert = 1 elif tour[i][t - 1] == subtour[lg - 1]: j = t - 2 while j >= 0: subtour.insert(lg, tour[i][j]) lg = lg + 1 j = j - 1 isInsert = 1 if isInsert == 1: if subtour[0] == subtour[len(subtour) - 1] and len(subtour) > 1: # break circle by removing first path--------------------->other choice? visited[subtour[0]] = visited[subtour[0]] - 1 visited[subtour[1]] = visited[subtour[1]] - 1 for item in dstOrdered: if (item[0] == subtour[0] and item[1] == subtour[1]) or ( item[0] == subtour[1] and item[1] == subtour[0]): dstOrdered.remove(item) route = route - item[2] del subtour[0] # route=route-dst[subtour[0]][subtour[1]] del tour[i] break i = i - 1 return route, tour, visited, dstOrdered def countAvg(array, k): i = 0 s = 0 for item in array: s = s + item[k] i = i + 1 return int(s / i) def updateTour(tour, a, b, c, d): # a<b<c<d tour1 = tour[:a + 1] tour2 = tour[b:c + 1] tour3 = tour[d:] # tour=tour1+tour2[::-1]+tour3 tour1.extend(tour2[::-1]) tour1.extend(tour3) return tour1 def calPathAB(cities, cityA1, cityA2, cityB1, cityB2): d11 = calDistance(cities[cityA1], cities[cityB1]) d12 = calDistance(cities[cityA1], cities[cityB2]) d21 = calDistance(cities[cityA2], cities[cityB1]) d22 = calDistance(cities[cityA2], cities[cityB2]) pathA = d12 + d21 pathB = d11 + d22 return pathA, pathB, d11, d12, d21, d22 def selectPathA(tour, a1, a2, b1, b2): if a1 < a2 < b2 < b1: tour = updateTour(tour, a1, a2, b2, b1) elif b2 < b1 < a1 < a2: tour = updateTour(tour, b2, b1, a1, a2) elif a2 < a1 < b1 < b2: tour = updateTour(tour, a2, a1, b1, b2) elif b1 < b2 < a2 < a1: tour = updateTour(tour, b1, b2, a2, a1) return tour def selectPathB(tour, a1, a2, b1, b2): if a1 < a2 < b1 < b2: tour = updateTour(tour, a1, a2, b1, b2) elif b1 < b2 < a1 < a2: tour = updateTour(tour, b1, b2, a1, a2) elif a2 < a1 < b2 < b1: tour = updateTour(tour, a2, a1, b2, b1) elif b2 < b1 < a2 < a1: tour = updateTour(tour, b2, b1, a2, a1) return tour def swapPath(cities, route, dstSelected, tour, dst1, dst2): cityA1 = dst1[0] cityA2 = dst1[1] cityB1 = dst2[0] cityB2 = dst2[1] path = dst1[2] + dst2[2] pathA, pathB, d11, d12, d21, d22 = calPathAB(cities, cityA1, cityA2, cityB1, cityB2) a1 = tour.index(cityA1) a2 = tour.index(cityA2) b1 = tour.index(cityB1) b2 = tour.index(cityB2) if pathA< path and ((a1 < a2 and b2 < b1) or (a1 > a2 and b1 < b2)): dstSelected.remove(dst1) dstSelected.remove(dst2) if cityA1>cityB2: cityA1,cityB2=cityB2,cityA1 if cityA2>cityB1: cityA2,cityB1=cityB1,cityA2 dstSelected.extend([[cityA1, cityB2, d12], [cityA2, cityB1, d21]]) route = route - path + pathA # print route tour = selectPathA(tour, a1, a2, b1, b2) elif pathB < path and ((a1 < a2 and b1 < b2) or (a1 > a2 and b1 > b2)): dstSelected.remove(dst1) dstSelected.remove(dst2) if cityA1>cityB1: cityA1,cityB1=cityB1,cityA1 if cityA2>cityB2: cityA2,cityB2=cityB2,cityA2 dstSelected.extend([[cityA1, cityB1, d11], [cityA2, cityB2, d22]]) route = route - path + pathB # print route tour = selectPathB(tour, a1, a2, b1, b2) return route, dstSelected, tour
fd50bab9e17af9ade107196b06302da9f9233fd1
AshuHK/Sorting_Visualization
/text_based_sorts/test.py
4,086
4.21875
4
# import the sorts here from InsertionSort import insertion_sort from SelectionSort import selection_sort from BubbleSort import bubble_sort from QuickSort import quick_sort from MergeSort import merge_sort # used to generate the rules import random import time def generate_results(test_list, total_time, sort_type): """ Takes the information from the test functions and builds the results into a string for readability :param test_list: Python list that is ideally sorted :param total_time: Time object that is total time of the sort :param sort_type: String of the done to get the result """ # create an empty string result_str = "" # add the appropriate string based on if the list is sorted if test_list == sorted(test_list): result_str += "Test: Successful\t" else: result_str += "Test: Fail\t" # build the final string with the sort type given result_str += "{} sort time: {:5f} seconds".format(sort_type, total_time) return result_str def test_bubble(user_int): # build the test list test_list = [i for i in range(user_int)] random.shuffle(test_list) # time tracking of the sort start_time = time.time() bubble_sort(test_list) final_time = time.time() # generate and print results total_time = final_time - start_time result_str = generate_results(test_list, total_time, " Bubble") print(result_str) return None def test_insertion(user_int): # build the test list test_list = [i for i in range(user_int)] random.shuffle(test_list) # time tracking of the sort start_time = time.time() insertion_sort(test_list, 0, len(test_list) - 1) final_time = time.time() # generate and print results total_time = final_time - start_time result_str = generate_results(test_list, total_time, "Insertion") print(result_str) return None def test_selection(user_int): # build the test list test_list = [i for i in range(user_int)] random.shuffle(test_list) # time tracking of the sort start_time = time.time() selection_sort(test_list) final_time = time.time() # generate and print results total_time = final_time - start_time result_str = generate_results(test_list, total_time, "Selection") print(result_str) return None def test_quick(user_int): # build the test list test_list = [i for i in range(user_int)] random.shuffle(test_list) # time tracking of the sort start_time = time.time() quick_sort(test_list, 0, len(test_list) - 1) final_time = time.time() # generate and print results total_time = final_time - start_time result_str = generate_results(test_list, total_time, " Quick") print(result_str) return None def test_merge(user_int): # build the test list test_list = [i for i in range(user_int)] random.shuffle(test_list) # time tracking of the sort start_time = time.time() merge_sort(test_list) final_time = time.time() # generate and print results total_time = final_time - start_time result_str = generate_results(test_list, total_time, " Merge") print(result_str) return None def main(): # print a warning for the user about the O(n^2) algorithms warning_str = """ The first 3 sorts in this program (bubble, insertion, and selection) will take a significant amount of time if you input something greater than 20,000. """ print(warning_str) # take input for the size try: user_int = int(input("\nInput the size of the list to be generated: ")) if user_int < 0: user_int *= -1 except ValueError: # sets a default size as exception handling user_int = 1000 # run the test suite print("\n") test_bubble(user_int) test_insertion(user_int) test_selection(user_int) test_quick(user_int) test_merge(user_int) print("\n") return None if __name__ == "__main__": main()
0ad4d3eee4cf6c52b56d891dbd46fa4d85d3d471
sloria/TextBlob
/textblob/utils.py
1,526
3.875
4
# -*- coding: utf-8 -*- import re import string PUNCTUATION_REGEX = re.compile('[{0}]'.format(re.escape(string.punctuation))) def strip_punc(s, all=False): """Removes punctuation from a string. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ends of the string. """ if all: return PUNCTUATION_REGEX.sub('', s.strip()) else: return s.strip().strip(string.punctuation) def lowerstrip(s, all=False): """Makes text all lowercase and strips punctuation and whitespace. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ends of the string. """ return strip_punc(s.lower().strip(), all=all) def tree2str(tree, concat=' '): """Convert a nltk.tree.Tree to a string. For example: (NP a/DT beautiful/JJ new/JJ dashboard/NN) -> "a beautiful dashboard" """ return concat.join([word for (word, tag) in tree]) def filter_insignificant(chunk, tag_suffixes=('DT', 'CC', 'PRP$', 'PRP')): """Filter out insignificant (word, tag) tuples from a chunk of text.""" good = [] for word, tag in chunk: ok = True for suffix in tag_suffixes: if tag.endswith(suffix): ok = False break if ok: good.append((word, tag)) return good def is_filelike(obj): """Return whether ``obj`` is a file-like object.""" return hasattr(obj, 'read')
2d554411e456c44b1afcda09ca4c159ee2a52527
hmdshfq/Learn-Python-The-Hard-Way
/bin/ex08.py
786
3.890625
4
# Exercise 8 - Printing, printing # a variable that saves string with four placeholders {} for future use # variables can be put inside {} formatter = "{} {} {} {}" # .format function sends the values to the string # here 1, 2, 3, and 4 are send to formatter string print(formatter.format(1, 2, 3, 4)) print(formatter.format('one', 'two', 'three', 'four')) print(formatter.format(True, False, False, True)) # this will just print the content of formatter four times print(formatter.format(formatter, formatter, formatter, formatter)) # it looks complicated but actually it isn't. I am just passing the # clauses (parts of sentences) into each {} in the variable formatter print(formatter.format( "Try your", "Own text here", "Maybe a poem", "Or a song about fear" ))
2629e64289d57e494d64d37dc4da187ee61f676c
younkyounghwan/python_class
/201814099_11.py
2,397
3.5
4
""" 201814099 윤경환 """ def cul(a,b): #약분 if (a>=b): while b!=0: c=a%b a=b b=c return a else: while a!=0: c=b%a b=a a=c return b class Fraction: def __init__(self,n,d): """ :param a: :param b: """ self.denom=d self.numer=n def plus(self, o): # 결과의 분모 계산 d = self.denom * o.denom # 결과의 분자 계산 n = self.numer * o.denom + o.numer * self.denom r = Fraction(n/cul(n,d), d/cul(n,d)) # 결과 값을 포함하는 Fraction 분수 생성 return r def diff(self ,o): # 결과의 분모 계산 d = self.denom * o.denom # 결과의 분자 계산 n = self.numer * o.denom - o.numer * self.denom if n<0: n = -n r = Fraction(n/cul(n,d), d/cul(n,d)) # 결과 값을 포함하는 Fraction 분수 생성 return r def mul(self,o): # 결과의 분모 계산 d = self.denom * o.denom # 결과의 분자 계산 n = self.numer * o.numer r = Fraction(n/cul(n,d), d/cul(n,d)) # 결과 값을 포함하는 Fraction 분수 생성 return r def div(self,o): # 결과의 분모 계산 d = self.denom * o.numer # 결과의 분자 계산 n = self.numer * o.denom r = Fraction(n/cul(n,d), d/cul(n,d)) # 결과 값을 포함하는 Fraction 분수 생성 return r def setNumer(self,n): self.numer = n def setNenom(self,d): self.denom = d # 분자를 반환하는 메쏘드 get_Numer 정의 def getNumer(self): return self.numer # 분모를 반환하는 메쏘드 get_denom 정의 def getDenom(self): return self.denom def print(self): print("%d/%d" %(self.numer, self.denom)) bunsu1 = Fraction(1,2) bunsu2 = Fraction(5,4) bunsu1.print() #plus print("+") bunsu2.print() print("=") bunsu1.plus(bunsu2).print() print("") bunsu1.print() #diff print("-") bunsu2.print() print("=") bunsu1.diff(bunsu2).print() print("") bunsu1.print() #mul print("*") bunsu2.print() print("=") bunsu1.mul(bunsu2).print() print("") bunsu1.print() #div print("/") bunsu2.print() print("=") bunsu1.div(bunsu2).print() print("")
81e9aa77df7072d8cb6beeb809af318bf146ef3d
erx717/Basic-Projects
/Tic Tac Toe (OOP).py
5,001
4.0625
4
class TicTacToe(): def __init__(self): self.board = [["[ ]", "[ ]", "[ ]"], ["[ ]", "[ ]", "[ ]"], ["[ ]", "[ ]", "[ ]"]] self.status = True self.move = 0 self.showBoard() def play(self): if self.move % 2 == 0: self.move += 1 self.p1play() else: self.move += 1 self.p2play() def p1play(self): print("1. Player(X)\n") try: row = int(input("Row:\n")) except ValueError: row = 0 while row<1 or row>3: try: print("Row value should be 1, 2 or 3") row = int(input("Row:\n")) except: print("You have entered a string\n") try: column = int(input("Column:\n")) except ValueError: column = 0 while column<1 or column>3: try: print("Column value should be 1, 2 or 3") column = int(input("Column:\n")) except: print("You have entered a string\n") if self.checkTheSquare(row, column) == False: self.p1play() else: self.board[row-1][column-1] = " X " self.showBoard() self.checkTheGame() def p2play(self): print("2. Player(O)\n") try: row = int(input("Row:\n")) except ValueError: row = 0 while row<1 or row>3: try: print("Row value should be 1, 2 or 3") row = int(input("Row:\n")) except: print("You have entered a string\n") try: column = int(input("Column:\n")) except ValueError: column = 0 while column<1 or column>3: try: print("Column value should be 1, 2 or 3") column = int(input("Column:\n")) except: print("You have entered a string\n") if self.checkTheSquare(row, column) == False: self.p2play() else: self.board[row-1][column-1] = " O " self.showBoard() self.checkTheGame() def checkTheSquare(self, row, column): if self.board[row-1][column-1] == " X " or self.board[row-1][column-1] == " O ": print(f"This square is full ({self.board[row-1][column-1]})") self.showBoard() return False else: return True def showBoard(self): row = 1 print(" 1 2 3") for i in self.board: print(f"{str(row)} ", end="") row += 1 for j in i: print(j, end=" ") print("\n") def checkTheGame(self): if self.move % 2 == 0: winner = "2. player (O) has won the game!" else: winner = "1. player (X) has won the game!" if [self.board[0][0], self.board[0][1], self.board[0][2]] == [" X ", " X ", " X "] or [self.board[0][0], self.board[0][1], self.board[0][2]] == [" O ", " O ", " O "]: self.status = False if [self.board[1][0], self.board[1][1], self.board[1][2]] == [" X ", " X ", " X "] or [self.board[1][0], self.board[1][1], self.board[1][2]] == [" O ", " O ", " O "]: self.status = False if [self.board[2][0], self.board[2][1], self.board[2][2]] == [" X ", " X ", " X "] or [self.board[2][0], self.board[2][1], self.board[2][2]] == [" O ", " O ", " O "]: self.status = False if [self.board[0][0], self.board[1][0], self.board[2][0]] == [" X ", " X ", " X "] or [self.board[0][0], self.board[1][0], self.board[2][0]] == [" O ", " O ", " O "]: self.status = False if [self.board[0][1], self.board[1][1], self.board[2][1]] == [" X ", " X ", " X "] or [self.board[0][1], self.board[1][1], self.board[2][1]] == [" O ", " O ", " O "]: self.status = False if [self.board[0][2], self.board[1][2], self.board[2][2]] == [" X ", " X ", " X "] or [self.board[0][2], self.board[1][2], self.board[2][2]] == [" O ", " O ", " O "]: self.status = False if [self.board[0][0], self.board[1][1], self.board[2][2]] == [" X ", " X ", " X "] or [self.board[0][0], self.board[1][1], self.board[2][2]] == [" O ", " O ", " O "]: self.status = False if [self.board[0][2], self.board[1][1], self.board[2][0]] == [" X ", " X ", " X "] or [self.board[0][2], self.board[1][1], self.board[2][0]] == [" O ", " O ", " O "]: self.status = False if not self.status: print(winner) if self.move == 9 and self.status: print("Draw\n") self.status = False ticTacToe = TicTacToe() while ticTacToe.status: ticTacToe.play()
7b5e9eefce0371c01cd7c05ca47fd12fbb12b1f9
lienne/PythonLearning
/12_Fibonacci_Recursion_Memoization.py
1,711
4.25
4
# Fib Sequence: # 1, 1, 2, 3, 5, 8, 13, 21, . . . # Write a function to return the nth term of the Fibonacci Sequence. # Function should be fast, clearly written, and rock solid. def fibonacci_recursive(n): if n == 1: return 1 if n == 2: return 1 elif n > 2: return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) # Super slow for n in range(1, 2): print(n, ":", fibonacci_recursive(n)) # Memoization! # 1. Implement explicitly # 2. Use built-in python tool # Dictionary to store recent function calls fib_cache = {} def fibonacci_memo(n): # If we have the cached value, then return it if n in fib_cache: return fib_cache[n] # Compute the Nth term if n == 1: value = 1 if n == 2: value = 1 elif n > 2: value = fibonacci_memo(n-1) + fibonacci_memo(n-2) # Cache the value and return it fib_cache[n] = value return value # Faster response for n in range(1, 2): print(n, ":", fibonacci_memo(n)) from functools import lru_cache @lru_cache(maxsize = 1000) def fibonacci(n): # If we have the cached value, then return it if n in fib_cache: return fib_cache[n] # Compute the Nth term if n == 1: value = 1 if n == 2: value = 1 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) # Cache the value and return it fib_cache[n] = value return value # Almost instantaneous response for n in range(1, 2): print(n, ":", fibonacci_memo(n)) # Let's compute the ratio between consecutive terms in the sequence for n in range(1, 51): print(fibonacci(n+1) / fibonacci(n)) # It converges to the Golden Ratio.
382b4c98c3b978be8e6f3470a3296ea2981f4cc2
bhavya152002/Patterns-using-turtle
/triangle spiral.py
236
3.609375
4
import turtle t = turtle.Turtle() s = turtle.Screen() s,turtle.bgcolor('black') t.width(3) t.speed(10) col = ('white', 'pink', 'cyan') for i in range (300): t.pencolor(col[i%3]) t.forward(i*4) t.right(121) turtle.done()
6a9f3747c63ab397088e61e718ceed4adfc6eb25
elYaro/Codewars-Katas-Python
/7 kyu/Sort_Out_The_Men_From_Boys.py
1,883
4.15625
4
''' Scenario Now that the competition gets tough it will Sort out the men from the boys . Men are the Even numbers and Boys are the odd !alt !alt Task Given an array/list [] of n integers , Separate The even numbers from the odds , or Separate the men from the boys !alt !alt Notes Return an array/list where Even numbers come first then odds Since , Men are stronger than Boys , Then Even numbers in ascending order While odds in descending . Array/list size is at least 4 . Array/list numbers could be a mixture of positives , negatives . Have no fear , It is guaranteed that no Zeroes will exists . !alt Repetition of numbers in the array/list could occur , So (duplications are not included when separating). Input >> Output Examples: 1- menFromBoys ({7, 3 , 14 , 17}) ==> return ({14, 17, 7, 3}) Explanation: Since , { 14 } is the even number here , So it came first , then the odds in descending order {17 , 7 , 3} . 2- menFromBoys ({-94, -99 , -100 , -99 , -96 , -99 }) ==> return ({-100 , -96 , -94 , -99}) Explanation: Since , { -100, -96 , -94 } is the even numbers here , So it came first in ascending order , then the odds in descending order { -99 } Since , (Duplications are not included when separating) , then you can see only one (-99) was appeared in the final array/list . 3- menFromBoys ({49 , 818 , -282 , 900 , 928 , 281 , -282 , -1 }) ==> return ({-282 , 818 , 900 , 928 , 281 , 49 , -1}) Explanation: Since , {-282 , 818 , 900 , 928 } is the even numbers here , So it came first in ascending order , then the odds in descending order { 281 , 49 , -1 } Since , (Duplications are not included when separating) , then you can see only one (-282) was appeared in the final array/list . ''' def men_from_boys(arr): even = set(a for a in arr if a % 2 == 0) odd = set(a for a in arr if a % 2 != 0) return sorted(even) + sorted(odd,reverse = True)
f3db7c324d7c8cfd650eec56bfbb14bfa3f6c049
slieer/py
/Hands-On-Computational-Thinking-with-Python.-master/ch5_guess4.py
499
3.96875
4
import random as rand compnumber = rand.randint(1, 100) i = 5 for number in range(5): usernumber = int(input("Choose a number between 1 and 100. You have " + str(i) + " guesses left. ")) if compnumber == usernumber: print("You win!") exit() elif compnumber > usernumber: print("Your number is too small!") i = i - 1 elif compnumber < usernumber: print("Your number is too large!") i = i - 1 print("You're out of guesses! You lose! ")
52bf99c4723bba9523921b2e448ad62847496d2c
gusun0/curso--py
/operadores/1.py
434
4
4
#1: Pidele al usuario que ingrese dos numeros enteros por teclado #y determine los siguientes aspectos. # #1: Si ambos numeros son iguales #2: Si los numeros son diferentes #3: Si el primero es mayor al segundo #4: Si el segundo es mayor al primero a = int(input('a: ')) b = int(input('b: ')) print('son iguales?', a == b) print('son diferentes?', a != b) print('el primero es mayor?', a > b) print('el segundo es mayor?', a < b)