blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
a8374ca098190309a7fef570a6b3d5206e9b4578
Emanoel580/ifpi-ads-algoritmos2020
/lista condicionais 2b/fabio_2b_12_inteiro_decima.py
230
3.90625
4
def main(): num = float(input('numero: ')) definir(num) def definir(valor1): if valor1 // 1 == valor1: print(f' o numero {valor1} é inteiro') else: print(f'o numero {valor1} e decimal') main()
597286aa205bbfa6139a31b9b8cc168ff93c7e50
eltechno/python_course
/Random.head-or-tails.py
334
3.640625
4
import numpy as np np.random.seed(123) outcomes= [] for x in range(10): coin = np.random.randint(0,2) if coin == 0: outcomes.append("heads") else: outcomes.append("tails") print(outcomes) tails = [0] for x in range(10): coin = np.random.randint(0,2) tails.append(tails[x] + coin) print(tails)
e11d7e9688a8130e42db1c4507c1605fed79f7dc
Arbazkhan4712/Python-Quarantine-Projects
/Snake_Game/Previous .py files/gamePrototype.py
4,217
3.90625
4
################################################################################ # THis is the first prototype of the snake game i'll be creating. # This has controls and displays the user score. # after the game is over we can either continue to play or exit the window ################################################################################ import pygame import random import time pygame.init() green = (0,255,0) white = (255,255,255) black = (0,0,0) red = (255,0,0) blue = (0,0,255) clock = pygame.time.Clock() display_width = 800 display_height = 400 snake_block = 10 snake_speed = 10 font_style = pygame.font.SysFont('sahadeva', display_width//20) score_font = pygame.font.SysFont('nakula',display_width//20) d = pygame.display.set_mode((display_width,display_height)) # for a layout of 400*200 pygame.display.set_caption('SNAKE GAME') # sets the tile of the project score_pos = [0,0] def Your_score(score): value = score_font.render(f'Your score:{score}', True, blue) d.blit(value, score_pos) def message(txt,color): mesg = font_style.render(txt,True, color) d.blit(mesg, [50,50]) def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(d, red, [x[0],x[1], snake_block,snake_block]) def game_loop(): game_over = False game_close = False x1 = display_width/2 y1 = display_height/2 x_change = 0 y_change = 0 snake_list = [] length_of_snake = 1 foodx = round(random.randrange(0,display_width - snake_block) /10.0 )* 10.0 foody = round(random.randrange(0, display_height - snake_block) / 10.0 ) *10.0 while not game_over: #While loop for the screen to get displayed pygame.display.update() while game_close == True: d.fill(black) message('You lost, Press p-play again or q-quit', green) Your_score(length_of_snake -1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_close = False game_over = True if event.key == pygame.K_p: game_loop() for event in pygame.event.get(): # until quit button is pressed if event.type == pygame.QUIT: game_over = True # if event is quit / if exit button is pressed it exits from the screen if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -snake_block y_change = 0 elif event.key == pygame.K_RIGHT: x_change = snake_block y_change = 0 elif event.key == pygame.K_UP: x_change = 0 y_change = -snake_block elif event.key == pygame.K_DOWN: x_change = 0 y_change = snake_block x1 += x_change y1 += y_change # IF YOU DONT WANT END THE GAME IF SNAKE TOUCHES THE BORDER REMOVE THE BELOW COMMENTS # if x1 > display_width: # x1 = 0 # elif x1 < 0: # x1 = display_width # elif y1 > display_height: # y1 = 0 # elif y1 < 0: # y1 = display_height if x1 >= display_width or x1 <= 0 or y1 >= display_height or y1<=0: game_close = True d.fill(black) pygame.draw.circle(d,green, [int(foodx), int(foody)], 5) snake_head =[] snake_head.append(x1) snake_head.append(y1) snake_list.append(snake_head) if len(snake_list) > length_of_snake: del snake_list[0] for x in snake_list[:-1]: if x == snake_head: game_close = True our_snake(snake_block,snake_list) Your_score(length_of_snake -1) pygame.display.update() if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0 length_of_snake += 1 clock.tick(snake_speed) pygame.quit() quit() game_loop()
88735f093c67f0aa7da4129ac3957519acd2cc8e
richik500/MiniProjectPython
/functions/disCusRec.py
452
3.5625
4
def display_customer_record(): print("\n\n List Of Available Customer Records\n\n") print("BOOKING ID---GUEST NAME---GUEST MOBILE NUMBER---GUEST ROOM NUMBER---GUEST CHECKIN DETAILS---GUEST CHECKOUT DETAILS---RENT---TOTAL BILL\n") file = open("Record/customer.txt", "r") while True: content = file.readline() length = len(content) if length == 0: break print(content.strip()) file.close()
13e89cfbbb8962d6945471e9e27531b5843c8e5e
mturja-vf-ic-bd/AD-Longitudinal-Smoothing
/utils/L2_distance.py
1,232
3.921875
4
import numpy as np def L2_distance(X, Y): """ Computes pairwise distance between each vector of the two lists. The vectors has to be of same length. Eq. || X_i - Y_j || ^ 2 = || X_i || ^ 2 + || Y_j || ^ 2 - 2* transpose(X_i) * Y_j :param X: List of vectors :param Y: List of vectors :return D: A matrix of dimension len(X) * len(Y), D_ij containing the L2 distance between X_i and Y_j """ X_square = sum(X * X, 0).reshape(X.shape[1], 1) Y_square = sum(Y * Y, 0) return X_square + Y_square - 2 * np.matmul(np.transpose(X), Y) if __name__ == '__main__': # Unit test for L2_distance X = np.array([[1, 2, 3], [4, 5, 6]]) Y = np.array([[4, 5, 6, 11], [7, 8, 9, 10]]) D = L2_distance(X, Y) expected_D = np.array([[18, 32, 50, 136], [8, 18, 32, 106], [2, 8, 18, 80]]) assert ((D == expected_D).sum() == 12), "Test failed" D = L2_distance(X, X) expected_D = np.array([[0, 2, 8], [2, 0, 2], [8, 2, 0]]) assert ((D == expected_D).sum() == 9), "Test failed" D = L2_distance(Y, Y) expected_D = np.array([[0, 2, 8, 58], [2, 0, 2, 40], [8, 2, 0, 26], [58, 40, 26, 0]]) assert ((D == expected_D).sum() == 16), "Test failed" print("Test passed")
467331a745a196a2578d6b88e3241ced8fca5fca
MrZhangzhg/nsd2019
/nsd1907/py01/day01/hi.py
1,039
3.9375
4
# print("Hello World!") # # if 3 > 0: # print('yes') # print('ok') # # s = 'Hello World!' + \ # 'Hello tedu' # # a = 3; b = 4 # c = 5 # d = 6 # 打印一行字符串 # print('Hello World!') # 字符串可以使用+进行拼接,拼接后再打印 # print('Hello' + 'World') # print打印多项时,用逗号分开各项,默认各项间使用空格作为分隔符 # print('Hao', 123) # 也可以通过sep指定分隔符 # print('Hao', 123, 'abc', 456) # print('Hao', 123, 'abc', 456, sep='***') # 字符串中间如果需要有变化的内容,可以使用%s占位,然后在字符串外边指定具体内容 # print('I am %s' % 'zzg') # print('%s is %s years old.' % ('tom', 20)) # username = input('username: ') # print(username) # input读入的内容一定是字符类型 n = input('number: ') # print(n + 10) # 错误,不能把字符和数字进行运算 a = int(n) + 10 # int函数可以将字符串数字转换成整数 print(a) b = n + str(10) # str函数可以将对象转换成字符串 print(b)
46d90a6ec75f65717bffcb81c92224414b86df5a
isabella0428/Leetcode
/python/58.py
496
3.765625
4
class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if not s: return 0 count = 0 end = len(s) - 1 while s[end] == ' ' and end > -1: end -= 1 for i in range(end, -1, -1): if s[i] != ' ': count += 1 else: break return count if __name__ == "__main__": a = Solution() print(a.lengthOfLastWord("a "))
5937eae7abd332a22ed8429af5a4c403b075b58a
panditdandgule/DataScience
/NLP/Python Natural Language Processing/Regexp.py
1,385
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 13 08:47:07 2019 @author: pandit """ import re def searchvsmatch(): line=" I love animals." matchobj=re.match(r'animals',line,re.M | re.I) if matchobj: print("match",matchobj.group()) else: print("No match!!") searchObj=re.search(r'animals',line,re.M | re.I) if searchObj: print("search:",searchObj.group()) else: print("Nothing found!!") def basicregex(): line = "This is test sentence and test sentence is also a sentence." contactInfo = 'Doe, John: 1111-1212' print("-----------Output of re.findall()--------") # re.findall() finds all occurences of sentence from line variable. findallobj=re.findall(r'sentence',line) print(findallobj) #re.search() and group wise extraction groupwiseobj=re.search(r'(\w+),(\w+):(\S+)',contractinfo) print("\n") print("____________________Output of Groups_______________") print("1st group ____________"+groupwiseobj.group(1)) print("2nd group ____________"+groupwiseobj.group(2)) print("3rd group ____________"+groupwiseobj.group(3)) # re.sub() replace string phone = "1111-2222-3333 # This is Phone Number" #Delete Python-style comments num = re.sub(r'#.*$', "", phone) print("\n") print("-----------Output of re.sub()--------") print("Phone Num : ", num)
c76ac4accf99699d35ec365168d95f22373056fa
green-fox-academy/kitta11
/datascience/practice/randomizer.py
163
3.734375
4
import random print(random.random()) print(random.randint(0, 5)) mylist = 'This is my list where I will pick a random word'.split() print(random.choice(mylist))
3fcde3ef467d83e792e275cd2bfaf6373f57fbc7
cobed95/gwanak-ps
/hacker-rank/asia-pacific-4/hanme/p3.py
2,508
3.671875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getMinEffort' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY C as parameter. # def getMinEffort(C): # Write your code here n = len(C) m = len(C[0]) effort = [] for _ in range(n+1): effort.append([0] * (m+1)) helper(n, m, C, effort) result = effort[n][m] print(effort) print(result) return result def helper(n, m, G, E): for i in range(1, n+1): for j in range(1, m+1): left = abs(G[i-1][j-1] - G[i-1][j-2]) if j > 1 else 0 up = abs(G[i-1][j-1] - G[i-2][j-1]) if i > 1 else 0 print("\n", i, j, left, up) if left <= up: if E[i][j-1] <= E[i-1][j]: print(1) # perfect. choose left E[i][j] = E[i][j-1] if E[i][j-1] > left else left print(E[i][j]) elif E[i][j-1] > E[i-1][j] and E[i][j-1] <= up: print(2) # hew. choose left E[i][j] = E[i][j-1] if E[i][j-1] > left else left print(E[i][j]) else: print(3) # disguise. choose up E[i][j] = E[i-1][j] if E[i-1][j] > up else up print(E[i][j]) else: if E[i][j-1] >= E[i-1][j]: print(4) # perfect. choose up E[i][j] = E[i-1][j] if E[i-1][j] > left else left print(E[i][j]) elif E[i][j] > E[i-1][j] and E[i-1][j] <= left: print(5) # hew. choose up E[i][j] = E[i-1][j] if E[i-1][j] > up else up print(E[i][j]) else: print(6) # disguise. choose left E[i][j] = E[i][j-1] if E[i][j-1] > left else left print(E[i][j]) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) m = int(first_multiple_input[1]) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) answer = getMinEffort(arr) fptr.write(str(answer) + '\n') fptr.close()
84122822c8db191b7fe0d512279dac4271c411df
superpigBB/Happy-Coding
/Algorithm/degree.py
1,499
3.59375
4
## Solution 1 def degreeOfArray(arr): # # Write your code here. # if arr is None or len(arr) == 0: return -1 dict = {} for index in range(len(arr)): num = arr[index] if num not in dict: dict[num] = {} dict[num]['cnt'] = 0 dict[num]['indexes'] = [] else: dict[num]['cnt'] += 1 dict[num]['indexes'].append(index) max_degree = -1 degree_nums = [] for num in dict: if dict[num]['cnt'] > max_degree: max_degree = dict[num]['cnt'] degree_nums = [] degree_nums.append(num) elif dict[num]['cnt'] == max_degree: degree_nums.append(num) min_len = float('inf') for num in degree_nums: index_list = dict[num]['indexes'] if index_list[-1] - index_list[0] < min_len: min_len = index_list[-1] - index_list[0] return min_len + 1 ## Sultion 2 def degreeOfArray(arr): left, right, count = {}, {}, {} for i, x in enumerate(arr): if x not in left: left[x] = i right[x] = i count[x] = count.get(x, 0) + 1 ans = len(arr) degree = max(count.values()) for x in count: if count[x] == degree: ans = min(ans, right[x] - left[x] + 1) return ans print(degreeOfArray([5,1,2,2,3,1])) print(degreeOfArray([6,1,1,2,1,2,2])) print(degreeOfArray([17,802,88, 747, 23, 160, 681, 254, 46, 663, 752, 741, 857, 802, 387, 790, 528, 93]))
ab5e82cc9f731676c51cfc6a1da23efaed42e23c
nakshc/jhbhj-
/untitled0.py
320
3.515625
4
name="naksh" print(type(name)) blah=10 print(type(blah)) yo_man_this_is_a_list=["yo","bros","whassup","do","you","play","football"] print(yo_man_this_is_a_list) print(type(yo_man_this_is_a_list)) from tkinter import * root=Tk() root.title("C145") root.geometry("300x300") root.mainloop();
5d74b3e5e66377ec430adc4273cfeb1228905d2a
Drako01/Python
/tripledeunnumero.py
176
3.96875
4
## El Triple de un numero ## Autor: Alejandro Di Stefano ## Fecha 21/08/2021 uno=0 print ("Ingrese un Número cualquiera: ") uno=float(input()) print ("El Triple del Número es: ", (uno*3))
019bce8c814a537c99655de48d6e073f9708a448
Pruebas2DAMK/PruebasSGE
/py/P706JSD.py
311
3.5625
4
''' Joel Sempere Durá- Ejercicio 6 ''' contrasenya="contraseña" while True: compruebaContrasenya=input("Introduce la contraseña:\n") if compruebaContrasenya == contrasenya: print("!Correcto!\nBienvenido de nuevo") exit(0) else: print("Contraseña incorrecta, intentelo de nuevo")
71bc939935c064114f66270940a00d3d94ba92bd
litianhe/webApp3
/www/test_yield.py
760
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def accumulate(): # 子生成器,将传进的非None值累加,传进的值若为None,则返回累加结果 tally = 0 while 1: next = yield if next is None: return tally tally += next def gather_tallies(tallies): # 外部生成器,将累加操作任务委托给子生成器 while 1: tally = yield from accumulate() tallies.append(tally) tallies = [] acc = gather_tallies(tallies) next(acc) # 使累加生成器准备好接收传入值 for i in range(2): acc.send(i) acc.send(None) # 结束第一次累加 #for i in range(5): # acc.send(i) #acc.send(None) # 结束第二次累加 print(tallies) # 输出最终结果
47dfffc749626926e4a03394a3e51c554d1adb65
ckt371461/python
/basic/0.py
237
3.71875
4
x = 23 y = 0 print() try: print(x/y) except ZeroDivisionError as e: print('Not allowed to division by zero') print() else: print('Something else went wrong') finally: print('This is cleanup code') print()
298d0464320fa80db5677c17c2c7807a0004df4d
ankit2100/DataStructures_Python
/Tree.py
4,640
3.8125
4
class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def Insert(self,node,data): if node == None : return Node(data) if node.data < data : node.right = self.Insert(node.right,data) elif node.data > data: node.left = self.Insert(node.left,data) return node def TranverseInOrder(self,node): if node == None: return node self.TranverseInOrder(node.left) print node.data self.TranverseInOrder(node.right) def TranversePostOrder(self,node): if node == None: return node self.TranversePostOrder(node.left) self.TranversePostOrder(node.right) print node.data def TranversePreOrder(self,node): if node == None: return node print node.data self.TranversePreOrder(node.left) self.TranversePreOrder(node.right) def Search(self,node,data): if node == None: return None if node.data == data: return node if node.data < data : return self.Search(node.right,data) else: return self.Search(node.left,data) def FindMinimum(self,node): if node.left == None and node.right == None: return node return self.FindMinimum(node.left) return self.FindMinimum(node.right) def Delete(self,node,data): if node == None: return Node if node.data < data: node.right = self.Delete(node.right,data) elif node.data > data: node.left = self.Delete(node.left,data) else: if node.left == None and node.right == None: return None if node.left == None: return node.right elif node.right == None: return node.left else: temp = self.FindMinimum(node.right) node.data = temp.data node.right = self.Delete(node.right,temp.data) return node def ConvertTreeintoLinkedList(self,node,list): if node == None: return None list.AddNode(node.data) self.ConvertTreeintoLinkedList(node.left,list) self.ConvertTreeintoLinkedList(node.right,list) return list def GetMaxHeightOfNode(self,node): if node == None : return 0 return 1+ max(self.GetMaxHeightOfNode(node.left),self.GetMaxHeightOfNode(node.right)) def IsTreeHeightBalanced(self,node): ''' Its left subtree is height-balanced. Its right subtree is height-balanced. The difference between heights of left & right subtree is not greater than 1. :param node: :return: ''' if node == None: return True return self.IsTreeHeightBalanced(node.left) and self.IsTreeHeightBalanced(node.right) and abs(self.GetMaxHeightOfNode(node.right)-self.GetMaxHeightOfNode(node.left)) <=1 def ConvertIntoTreefromSortedArray(self,array,node=None): #print array if len(array) == 0: return None mid_pos = len(array)/2 mid_ele = array[mid_pos] node = Node(mid_ele) node.left = self.ConvertIntoTreefromSortedArray(array[0:mid_pos],node.left) node.right = self.ConvertIntoTreefromSortedArray(array[mid_pos+1::],node.right) return node def GetParentofNode(self,node,data): if node == None : return None if node.left and node.left.data == data: return node if node.right and node.right.data == data: return node if data > node.data: return self.GetParentofNode(node.right,data) else: return self.GetParentofNode(node.left,data) def GetHeightofNode(self,node,data): if node == None: return None if node.data == data: return 0 if data > node.data: return 1+self.GetHeightofNode(node.right,data) else: return 1+self.GetHeightofNode(node.left,data) def CheckTwoNodesareCousinNodes(self,root,data1,data2): if self.GetHeightofNode(root,data1) != self.GetHeightofNode(root,data2): return False if self.GetParentofNode(root,data1) == self.GetParentofNode(root,data2): return False return True
c3f8d45c494ae9e1f45927caca5d6acf4160ba02
mayupatel/Python-Code
/mpate131_fastaAndGC.py
5,729
3.65625
4
NAME: MAYURI PATEL, EMAIL: [email protected] #importing the module random. import random # this function takes header as parameter. #Function reports a) Gene name b) GeneID c) ProteinID def header_file(fastaHeader): ' #1. Parse the header string for gene name. geneName = fastaHeader.strip().split(" ")[1].split("=")[1].strip("]") print("The Gene Name is: " + geneName) #parsing header for gene id. geneID = "" fastaHeaderSplit = fastaHeader.split()[2].split(",") for gene in range(len(fastaHeaderSplit)): if fastaHeaderSplit[gene].split(":")[0].find("GeneID") != -1: geneID = fastaHeaderSplit[gene].split(":")[1].strip("]") print("The GeneID is: " + str(geneID)) #parsing header for protien id. proteinID = fastaHeader.strip().split(" ")[-2].split("=")[1].strip("]") print("The ProteinID is: " + proteinID) #exit the function #this function takes sequence as parameter #function reports a) length of sequence b) GC content c) Reverse complement sequence def sequence_record(seqRecord): #2. Parse the sequence record for its length. total = len(seqRecord) print("This is the total length of the sequence: " + str(total)) #calculating GC count. gc_total = seqRecord.count("C") + seqRecord.count("G") GCcontent = gc_total/total print("This is the GC_content of seqRecord: " + str(GCcontent)) #generating the reverse complement. reverseComplement = seqRecord[::-1] print("This is the reverse complement of the sequence:" + str(reverseComplement)) #exit the function! #function returns the new mutated string def nucleotide(nucleotideSeq, mutation): for i in nucleotideSeq: if i in "ATGC": continue else: #nucleotideSeq != ["A", "G", "T" , "C"]: print("Invalid nucleotide base....") # this exit the code exit() nucleotideSeq = nucleotideSeq.lower() # lowercase string newNucleotide = "" #the index position starts at 0 for mutationResult in range(mutation): position1 = random.randint(0, len(nucleotideSeq)-1)# generated first random number firstRandom = nucleotideSeq[position1] # select the character of it print("The random position is: " + str(position1) + " and the nucleotide present is: " + firstRandom) nucleotideList = list(nucleotideSeq)# string converted to list position2 = random.randint(0, len(nucleotideList)-1)# generated second random number secondRandom = nucleotideList[position2] # select the character of it print("The another nucleotide selected: " + secondRandom) nucleotideList[position1] = secondRandom.upper() # upper case newNucleotide = newNucleotide.join(nucleotideList)# list is converted to string print(newNucleotide) mutatedSeq = newNucleotide.upper()# new mutated sequence print(mutatedSeq) #exit the function! #this function takes sequence to mutate by transition substitution. def transitionSeq(nucleotideSeq,mutation): #transitions = set([('A', 'G'), ('G', 'A'), ('C', 'T'), ('T', 'C')]) newNucleotide = "" for mutationResult in range(mutation): position1 = random.randint(0, len(nucleotideSeq)-1)# generated first random number firstRandom = nucleotideSeq[position1] print("The random position is: " + str(position1) + " and the nucleotide present is: "+ firstRandom) nucleotideList = list(nucleotideSeq) position2 = random.randint(0, len(nucleotideList)-1)# generated second random number secondRandom = nucleotideList[position2] print("The another nucleotide selected: " + secondRandom) # this causes the substitution of the nucleotide. if firstRandom in ("A", "G") and secondRandom in( "A" , "G"): nucleotideSeq[position1] = secondRandom if firstRandom is "C" or "T" and secondRandom is "C" or "T": nucleotideSeq[position1] = secondRandom print(nucleotideList) newNucleotide = newNucleotide.join(nucleotideList)# list is converted to string print(newNucleotide) #exit the function! #this main finction handles the flow of the code. def main(): #using this fastaheader to parse and other commented header are for validating the written code. fastaHeader = ">lcl|NG_005905.2_cds_NP_009225.1_1 [gene=BRCA1] [db_xref=CCDS:CCDS11453.1,GeneID:672,LRG:p1] [protein=breast cancer type 1 susceptibility protein isoform 1] [exception=annotated by transcript or proteomic data] [protein_id=NP_009225.1] [gbkey=CDS]" #fastaHeader = ">lcl|NC_000007.14_cds_XP_011514170.1_1 [gene=ELN] [db_xref=GeneID:2006] [protein=elastin isoform X1] [protein_id=XP_011514170.1] [gbkey=CDS]" #fastaHeader = ">lcl|NC_000017.11_cds_NP_000537.3_1 [gene=TP53] [db_xref=CCDS:CCDS11118.1,GeneID:7157] [protein=cellular tumor antigen p53 isoform a] [protein_id=NP_000537.3] [gbkey=CDS]" #fastaHeader = ">lcl|NC_000011.10_cds_NP_000509.1_1 [gene=HBB] [db_xref=CCDS:CCDS7753.1,Ensembl:ENSP00000333994.3,GeneID:3043] [protein=hemoglobin subunit beta] [protein_id=NP_000509.1] [gbkey=CDS]" #using the sequence to parse it. seqRecord = "ATGGATTTATCTGCTCTTCGCGTTGAAGAAGTACAAAATGTCATTAATGCTATGCAGAAAATCTTAGAGTGTCCCATCTGTCTGGAGTTGATCAAGGAACCTGTCTCCACAAAGTGTGACCACATATTTTGCAAATTTTG" #passing the parameters as header and sequence header_file(fastaHeader) # calling the function sequence_record(seqRecord) # calling the function # the third function is called through the input nucleotideSeq = input("Enter the sequence: ") mutation = int(input("How many mutations do you want?: ")) #passing the parameters nucleotide(nucleotideSeq, mutation) # calling the function transitionSeq(nucleotideSeq, mutation) # calling the function if __name__ == "__main__": main()
4d0088dd83114a0d2680727e20643c56730137a5
igres9014/gym_chess2
/alphazero/move_encoding/knightmoves.py
2,022
3.515625
4
# -*- coding: utf-8 -*- """Helper module to encode/decode knight moves.""" import chess import numpy as np from gym_chess.alphazero.move_encoding import utils from typing import Optional #: Number of possible knight moves _NUM_TYPES: int = 8 #: Starting point of knight moves in last dimension of 8 x 8 x 73 action array. _TYPE_OFFSET: int = 56 #: Set of possible directions for a knight move, encoded as #: (delta rank, delta square). _DIRECTIONS = utils.IndexedTuple( (+2, +1), (+1, +2), (-1, +2), (-2, +1), (-2, -1), (-1, -2), (+1, -2), (+2, -1), ) def encode(move: chess.Move) -> Optional[int]: """Encodes the given move as a knight move, if possible. Returns: The corresponding action, if the given move represents a knight move; otherwise None. """ from_rank, from_file, to_rank, to_file = utils.unpack(move) delta = (to_rank - from_rank, to_file - from_file) is_knight_move = delta in _DIRECTIONS if not is_knight_move: return None knight_move_type = _DIRECTIONS.index(delta) move_type = _TYPE_OFFSET + knight_move_type action = np.ravel_multi_index( multi_index=((from_rank, from_file, move_type)), dims=(8, 8, 73) ) return action def decode(action: int) -> Optional[chess.Move]: """Decodes the given action as a knight move, if possible. Returns: The corresponding move, if the given action represents a knight move; otherwise None. """ from_rank, from_file, move_type = np.unravel_index(action, (8, 8, 73)) is_knight_move = ( _TYPE_OFFSET <= move_type and move_type < _TYPE_OFFSET + _NUM_TYPES ) if not is_knight_move: return None knight_move_type = move_type - _TYPE_OFFSET delta_rank, delta_file = _DIRECTIONS[knight_move_type] to_rank = from_rank + delta_rank to_file = from_file + delta_file move = utils.pack(from_rank, from_file, to_rank, to_file) return move
8f5e49d9f9b286edb6fcbcb2ab890fa0dff970f8
SilentWraith101/course-work
/lesson-06/how-to-write-a-function.py
409
4.53125
5
a = 23 b = -23 # It will check if the absolute value of both a and b are equal def absolute_value(n): if n < 0: n = -n return n # return n if n > 0 else -n # Checking if the absolute value of a is equal to b if absolute_value(a) == absolute_value(b): print('The absolute values of', a, 'and', b, 'are equal') else: print('The absolute values of', a, 'and', b, 'are different')
815e195913016f8f8a9e3b10adcfea706480e6bd
PyeongGang-Kim/TIL
/SW_Expert_Arcademy/Programming_Beginner/2-46.py
482
3.625
4
class Student: def __init__(self,name): Student.name=name def nnn(self): print("이름: "+ Student.name) class GraduateStudent(Student): def __init__(self, name, major): GraduateStudent.name=name GraduateStudent.major=major def nnn(self): print("이름: "+ GraduateStudent.name + ", 전공: "+GraduateStudent.major) stu_a=Student('홍길동') stu_a.nnn() stu_b=GraduateStudent('이순신', '컴퓨터') stu_b.nnn()
022b2c9a7861826394aab835c173cf450e9fdf08
ywadud/Uni_Multi_Poly_Regression
/univariate_linear_regression.py
1,626
4.15625
4
# Import packages import numpy as np import matplotlib.pyplot as plt import pandas as pd # For better console printing np.set_printoptions(threshold = np.nan) # Import dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values # If you use [:, 0], X will become a vector and not a matrix Y = dataset.iloc[:, -1].values # No missing data in this set # No labels for encoding # Split training and test data from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 1/3, random_state = 0) # There is only one feature (independent variable, so no need to scale) # y = b0 + b1*x1 # Using/fitting simple linear regression to the training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, Y_train) # fits regressor object to the training data # Here we can see the coefficients in the model y = b0 + b1*x1 print(regressor.coef_) # Predicting the test set results from the regressor Y_pred = regressor.predict(X_test) # Visualizing the training set results plt.scatter(X_train, Y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs. Experience (Training Set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() # Visualizing the test set results plt.scatter(X_test, Y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs. Experience (Test Set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
046eaeef68ab16e9d776d8f12dd0c69de286a058
MRiach/Scientific_Computation
/Coursework_1/p12.py
4,908
3.5625
4
def codonToAA(codon): #TAA,TAG, and TGA are superfluous to requirement as they represent the end of the string and only end #up slowing down the function. """Return amino acid corresponding to input codon. Assumes valid codon has been provided as input "_" is returned for valid codons that do not correspond to amino acids. """ table = { 'ATA':'i', 'ATC':'i', 'ATT':'i', 'ATG':'m', 'ACA':'t', 'ACC':'t', 'ACG':'t', 'ACT':'t', 'AAC':'n', 'AAT':'n', 'AAA':'k', 'AAG':'k', 'AGC':'s', 'AGT':'s', 'AGA':'r', 'AGG':'r', 'CTA':'l', 'CTC':'l', 'CTG':'l', 'CTT':'l', 'CCA':'p', 'CCC':'p', 'CCG':'p', 'CCT':'p', 'CAC':'h', 'CAT':'h', 'CAA':'q', 'CAG':'q', 'CGA':'r', 'CGC':'r', 'CGG':'r', 'CGT':'r', 'GTA':'v', 'GTC':'v', 'GTG':'v', 'GTT':'v', 'GCA':'a', 'GCC':'a', 'GCG':'a', 'GCT':'a', 'GAC':'d', 'GAT':'d', 'GAA':'e', 'GAG':'e', 'GGA':'g', 'GGC':'g', 'GGG':'g', 'GGT':'g', 'TCA':'s', 'TCC':'s', 'TCG':'s', 'TCT':'s', 'TTC':'f', 'TTT':'f', 'TTA':'l', 'TTG':'l', 'TAC':'y', 'TAT':'y', 'TAA':'_', 'TAG':'_', 'TGC':'c', 'TGT':'c', 'TGA':'_', 'TGG':'w', } return table[codon] def DNAtoAA(S): #Convert string to list to make it easier to perform with X=list(S) N=len(X) codons=[] AA=[] #A codon corresponds to a string of three letters, so the string is split into sets of three which we label #codons. Along the way, we check to see if the list has reached 20 characters. If this is the case, then #we have exhausted all amino acids and thus the loop is broken. for i in range(0,N-1,3): codons.append(X[i]+X[i+1]+X[i+2]) if codonToAA(codons[int(i/3)]) not in AA: AA.append(codonToAA(codons[int(i/3)])) if len(AA)==20: AA=''.join(map(str, AA)) return AA #This amalgamates the individual amino acids to return a string. AA=''.join(map(str, AA)) return AA def char2base4(S): """Convert gene test_sequence string to list of ints """ c2b = {} c2b['A']=0 c2b['C']=1 c2b['G']=2 c2b['T']=3 L=[] for s in list(S): L+=[c2b[s]] return L def heval(L,Base,Prime): """Convert list L to base-10 number mod Prime where Base specifies the base of L """ f = 0 for l in L[:-1]: f = Base*(l+f) h = (f + (L[-1])) % Prime return h def pairSearch(L,pairs): """Find locations within adjacent strings (contained in input list,L) that match k-mer pairs found in input list pairs. Each element of pairs is a 2-element tuple containing k-mer strings """ #Locations are stored in an array which is outputted locations = [] #Length of all strings is constant so I take the length of the first element of my list. N=len(L[0]) #M here represents the M-mer pairs. M=len(pairs[0][0]) #I iterate through each consecutive pair of strings provided in L, omitting the last as its only neighbour #is the string above it. for i in range(0,len(L)-1): s1,s2=L[i],L[i+1] #I go through each pair that is provided for each pair of strings. for j in range(0,len(pairs)): #The first element of the set of pairs is assigned a hash value which is the target value. The #rolling hash is evaluated at the beginning of the list requiring M computations. This is then #compared with the target hash value. If both values are equal, then a direct comparisons between #the strings is made and the location is appended if the strings are indeed identical for adjacent #List1 and List2. Note: List2 is only checked if List1's substring matches the string in the first #element of the pair. targethash=heval(char2base4(pairs[j][0]),4,101) rollinghash=heval(char2base4(s1[0:M]),4,101) if rollinghash==targethash: if pairs[j][0]==s1[0:M] and pairs[j][1]==s2[0:M]: locations.append([0,i,j]) #The rolling hashes are now calculated in four calculations rather than M, providing for a much #more efficient algorithm in the case the rolling hash does not equal the target hash. Again, if #the target hash matches the rolling hash in List1, then we directly compare strings in the same #indices of List2. for k in range(1,N-M+1): rollinghash=(4*rollinghash-4**M*char2base4(s1[k-1])[0]+char2base4(s1[k-1+M])[0])%101 if rollinghash==targethash: if pairs[j][0]==s1[k:M+k] and pairs[j][1]==s2[k:M+k]: locations.append([k,i,j]) return locations import time pairs = [("TCG", "GAT"), ("AGC", "GAT"), ("TCG", "GAT"), ("TCG", "AAA")] L = ["GCAATTCGT","TCGTTGATC", "ATCGATGTC", "CGGTAATCG", "AGGTTTAAA"] print(pairSearch(L, pairs))
138ee9b11909576f51d2dfafb5e358126c7fb0ea
idobleicher/pythonexamples
/examples/basic-concepts/type_conversion_2.py
433
4.0625
4
# initializing string s = "10010" # binary 18 # printing string converting to int base 2 c = int(s, 2) print("After converting to integer base 2 : ", end="this is end\n") print(c) # printing string converting to float e = float(s) print("After converting to float : ", end="") print(e) # output: # After converting to integer base 2 : this is end # 18 # After converting to float : 10010.0 # # Process finished with exit code 0
29fa40334a80dd902540ab6b62255144db4e2df6
soyal/python-cookbook-note
/chapter1/1-8.py
488
4.0625
4
# 字典的运算 ## 求字典中value最大的key demo1 = { 'a': 123, 'b': 12, 'c': 443, 'd': 32 } # zip可以将两个可遍历对象合并成一个可迭代对象 minItemR = min(zip(demo1.values(), demo1.keys())) print('min key: ', minItemR[1]) maxItemR = max(zip(demo1.values(), demo1.keys())) print('max key: ', maxItemR[1]) ## 也可以用sorted sortedDemo1 = sorted(demo1, key=lambda x:demo1[x]) print('sorted demo1: ', sortedDemo1) # ['b', 'd', 'a', 'c'] 返回的是key
18868fd3a7536733f87765a2fa4650eb026af755
hua-gege/test02
/Scripts/test02.py
173
3.578125
4
# flag=None # if flag: # print("成立!") # else: # print("不成立") dict={"name":"张三"} if dict.get("age"): print("成立") else: print("不成立")
b274d42b093cb73aef6b57ebad903979e60b3923
csy-uestc-eng/algorithm_python_implementation
/KthLargestElementInAnArray215.py
1,642
3.921875
4
# -*- coding: utf-8 -*- """ using min heap to find k largest element. """ class MinHeap(object): def build_min_heap(self, elements, length=None): if not length: length = len(elements) elements.insert(0, 0) for i in range(length/2, 0, -1): self.min_heapify(elements, length, i) def min_heapify(self, elements, end, i): left = 2 * i right = left + 1 if left <= end and elements[left] < elements[i]: least = left else: least = i if right <= end and elements[right] < elements[least]: least = right if i != least: elements[i], elements[least] = elements[least], elements[i] self.min_heapify(elements, end, least) def findKlargest(array, k): """ 堆实现 使用一个小顶堆,堆大小为k.。遍历完所有元素后,取堆顶元素即是第k. 注: 1. 原数组顺序会被改变。 2. 原数组会在开始增加一个元素。仅用作标记。不使用。 time complexity: O(nlogk) :param array: :param k: :return: """ min_heap = MinHeap() min_heap.build_min_heap(array, k) for i in range(k+1, len(array)): if array[i] > array[1]: array[1], array[i] = array[i], array[1] min_heap.min_heapify(array, k, 1) return array[1] class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # AC time: 64ms # Ac memory: 12.3MB return findKlargest(nums, k)
2531ec29de49e2153ab40e36eda54bae3260e3ba
projectinnovatenewark/csx
/Students/Semester2/lessons/students/3_classes_and_beyond/24_recursion/24_recursion.py
1,189
4.5625
5
""" Example recursion functions. reference: https://realpython.com/python-thinking-recursively/ """ # the first example we will review is recursively executing a factorial. # Factorial multiplies every number by the number before it until it hits 1 # i.e. 5! would equal 5 x 4 x 3 x 2 # or 3! would equal 3 x 2 # recursion is a functioning that calls itself, thus breaking a large # problem down into smaller and smaller sub-problems until it is solved def factorial_recursive(n): # Base case: 1! = 1 if n == 1: return 1 # Recursive case: n! = n * (n-1)! else: return n * factorial_recursive(n-1) print(factorial_recursive(10)) # The Fibonacci sequence is a set of numbers that starts with a one or a zero, # followed by a one, and proceeds based on the rule that each number # (called a Fibonacci number) is equal to the sum of the preceding two numbers. # the first few numbers in the fibonacci sequence are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 def fibonacci(num): """use recursion to find the n'th term in the fibonacci sequence""" if num < 2: return num else: return fibonacci(num-1)+fibonacci(num-2) print(fibonacci(10))
091725ca8beb5986eb4b591cfb2b3b1bc60ce81f
AndyWKLiu/Program-Assignments
/loopcounter.py
243
4.03125
4
for x in range(0, 20): value = int(input("Enter a number between 1 and 10 inclusive")) if(value > 0 and value < 11): Calculate = value * 3 print(Calculate) #a) value and Calculate #b) 3 #c) line 3 #d) line 1 and line 4
c151b02793114dcfb8a4474932154a40e97323f4
paisap/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
622
3.671875
4
#!/usr/bin/python3 """Example Google style docstrings. This module demonstrates documentation as specified by the `Google Python Style Guide`_. Docstrings may extend over multiple lines. Sections are created """ def say_my_name(first_name, last_name=""): """Example of add on the say_my_name method. this functions print the name """ if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") print("My name is {} {}".format(first_name, last_name))
af0bcf91d689a19efe96b2d6c7cac054233db9a2
mengw3/goodreadDashboard
/elements/webscraper_author.py
7,926
3.515625
4
""" do web scraper for an author page """ import requests from bs4 import BeautifulSoup import numpy as geek class WebScraperAuthor: """ do web scraper for an author page """ def __init__(self): """ initial all variables """ self.name = "" self.author_url = "" self.author_id = "" self.rating = "" self.rating_count = "" self.review_count = "" self.image_url = "" self.related_authors = [] self.author_books = [] @staticmethod def get_name(contents): """ get name of the author :param contents: content of the web page :return: name of the author """ try: name = contents.find('h1', class_='authorName').text.strip() except: name = "" return name @staticmethod def get_author_id(url): """ get id of the author :param url: url of the web page :return: id of the author """ try: author_id = "" for character in url[38:]: if not character.isdigit(): break author_id += character except: author_id = "" return author_id @staticmethod def get_rating(contents): """ get rating of the author :param contents: content of the web page :return: rating of the author """ try: rating = "" number = contents.find('span', class_="rating").text.strip().replace("\n", "") for num in number: if num.isdigit() or num == ".": rating += num except: rating = "" return rating @staticmethod def get_rating_count(contents): """ get the number of rating of the author :param contents: content of the web page :return: the number of rating """ try: rating_count = contents.find('span', class_="votes").find("span")['content'] except: rating_count = "" return rating_count @staticmethod def get_review_count(contents): """ get the number of review of the author :param contents: content of the web page :return: the number of review """ try: review_count = contents.find('span', class_="count").find("span")['content'] except: review_count = "" return review_count @staticmethod def get_image_url(soup): """ get image url of the author :param soup: soup of the web page :return: author's image url """ try: image_url = soup.find('div', class_="leftContainer").find("img")['src'] except: image_url = "" return image_url @staticmethod def get_relate_authors(contents): """ get related authors of the author :param contents: content of the web page :return: list of related authors with name and url """ try: url = contents.find('div', class_="hreview-aggregate").findAll("a")[1]['href'] header = 'https://www.goodreads.com' # print(header + url) page = requests.get(header + url) soup = BeautifulSoup(page.content, "html.parser") contents = soup.findAll('div', class_="listWithDividers__item") authors_name = [] authors_url = [] i = 0 for item in contents: author = item.find('a', class_="gr-h3 gr-h3--serif gr-h3--noMargin") # print(author) if i != 0: authors_name.append(author.find('span', itemprop="name").text) # print(author.find('span', itemprop="name").text) authors_url.append(author['href']) # print(author['href']) i = i + 1 relate_authors = geek.c_[(authors_name, authors_url)] except: relate_authors = "" return relate_authors @staticmethod def get_author_books(contents): """ get books who are written by the author :param contents: content of the web page :return: names and urls of author's books """ try: url = contents.find('div', itemtype="https://schema.org/Collection").find('a', class_="actionLink")['href'] # print(url) header = 'https://www.goodreads.com' # print(header + url) page = requests.get(header + url) soup = BeautifulSoup(page.content, "html.parser") contents = soup.find('div', class_="leftContainer").find('table', class_="tableList").findAll("tr") books_name = [] books_url = [] for item in contents: books_name.append(item.find('a', class_="bookTitle").find("span").text) # print(book.find('a', class_="bookTitle").find("span").text) books_url.append(header + item.find('a', class_="bookTitle")['href']) # print(header + book.find('a', class_="bookTitle")['href']) author_books = geek.c_[(books_name, books_url)] except: author_books = "" return author_books def get_info(self, url): """ get information of the author :param url: url of the web page :return: all kinds of information of the author, return nothing if the input url is None """ if url is None: return page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") contents = soup.find('div', class_="rightContainer") self.name = self.get_name(contents) print(self.name) self.author_url = url print(self.author_url) self.author_id = self.get_author_id(url) print(self.author_id) self.rating = self.get_rating(contents) print(self.rating) self.rating_count = self.get_rating_count(contents) print(self.rating_count) self.review_count = self.get_review_count(contents) print(self.review_count) self.image_url = self.get_image_url(soup) print(self.image_url) self.related_authors = self.get_relate_authors(contents) print(len(self.related_authors)) print(self.related_authors) self.author_books = self.get_author_books(contents) print(len(self.get_author_books(contents))) print(self.author_books) def store_data(self): """ put all data of the author in a list :return: the list of all data """ data = {} data['name'] = self.name data['author_url'] = self.author_url data['author_id'] = self.author_id data['rating'] = self.rating data['rating_count'] = self.rating_count data['review_count'] = self.review_count data['image_url'] = self.image_url data['related_authors'] = [] for author in self.related_authors: data['related_authors'].append(author.tolist()) data['author_books'] = [] for book in self.author_books: data['author_books'].append(book.tolist()) return data # json_object = json.dumps(data, indent=4) # with open('authors.json', 'w') as f: # f.write(json_object) # if __name__ == "__main__": # print("Start") # info_author = WebScraperAuthor() # # info_author.get_info('https://www.goodreads.com/author/show/60805.Joshua_Bloch') # # info_author.store_data() # info_author.get_info('https://www.goodreads.com/author/show/45372.Robert_C_Martin') # # info_author.store_data() # print("Finished")
7ffb10c6f8a6f719c45339e053123ff445e7a3cc
crazyj7/python
/math/rcos.py
455
3.515625
4
import matplotlib.pyplot as plt import math import numpy as np ''' r = cos (t) ''' t = np.arange(0, math.pi*2, 0.01) r = np.cos(t) print(t) print(r) ## change to x, y x = r * np.cos(t) y = r * np.sin(t) ''' r2=1-cos(t) ''' r2 = 1-np.cos(t) x2 = r2 * np.cos(t) y2 = r2 * np.sin(t) plt.figure() plt.title('graph') plt.plot(x,y, c='r', label='r=cos(t)') plt.plot(x2,y2, c='b', label='r=1-cos(t)') plt.axhline() plt.axvline() plt.legend() plt.show()
23dce8af70fdff548ee13fb7c034e88654fd8a67
RajatOberoi/Assignment-2
/Q-6.py
98
4.1875
4
#area of a circle pi=3.14 x=int(input("enter radius of circle")) print("area =",x*x*pi)
8b2b8fa7e30806494a3690a2a8aba836b4877fb4
GokoshiJr/algoritmos2-py
/src/modular/anexar.py
343
3.90625
4
# 9. Anexar un dígito a un número dado por adelante. Ej.: Si N = 123 y Dig = 7 → N = 7123 def anexar(base, anexo): temp = base digito = contador = 0 while (temp > 0): contador += 1 temp //= 10 digito = (anexo * pow(10,contador)) + base print(digito) anexar(123, 7)
5edb9e8b58d2183d1ba00883b8c3859f6dcccb12
luisespriella9/CTCI-Python
/Arrays and Strings/main.py
6,862
3.734375
4
def check(result, actualResult): #this is to check whether the answer is correct to the result we are expecting if result == actualResult: print("Correct") else: print("Issue Found") # Problem 1.1 def isUnique(string): chars = [False] * 128 for char in string: charNumber = ord(char) if chars[charNumber]: return False chars[charNumber] = True return True # Problem 1.2 def checkPermutation(first, second): if (len(first) != len(second)): return False firstSet = [0]*128 secondSet = [0]*128 for i in range(len(first)): #fill both sets to count how many times each character appears for each word firstSet[ord(first[i])] += 1 secondSet[ord(second[i])] += 1 for i in range(128): #compare set results if firstSet[i] != secondSet[i]: return False return True # Problem 1.3 def urlify(string, length): #replace all spaces with %20 counter = 0 resultingString = "" for char in string: if counter>=length: break if char == " ": resultingString += "%20" else: resultingString += char counter+=1 return resultingString # Problem 1.4 def palindromePermutation(string): string = string.lower() set = [0]*128 for char in string: if (char.isalpha()): #only letters set[ord(char)]+=1 counter = 0 for charCount in set: if (counter>1): return False if (charCount%2 != 0): counter+=1 return True # Problem 1.5 def oneAway(first, second): if (first == second): #check if exact same word return True elif (len(first) == len(second)): if (len(first) == 1): #if both length of one and do not match given previous statement return False #check for replace character edit counter = 0 for i in range(len(first)): if (counter > 1 ): return False if (first[i] != second[i]): counter += 1 return True else: #check for inserting or removing character. Get biggest string and find if any subset matches other string if (len(first) > len(second)): bigger = first smaller = second else: bigger = second smaller = first for i in range(len(bigger)): subset = bigger[:i]+bigger[i+1:] if (subset == smaller): return True #as long as subset doesnt match smaller string return False # Problem 1.6 def stringCompression(string): if (string == ""): return "" #latest char be the first char in the string latestChar = string[0] charAppearances = 0 compressedString = "" for char in string: if not char.isalpha(): continue if (latestChar == char): charAppearances += 1 else: compressedString += str(latestChar) + str(charAppearances) charAppearances = 1 latestChar = char compressedString += str(latestChar) + str(charAppearances) #check if compressed String is actually smaller, if not return original string if (len(compressedString) < len(string)): return compressedString else: return string # Problem 1.7 def rotateMatrix(matrix): #base cases to check there are enough fields to rotate if (matrix == []): return [] if (matrix[0] == []): return [] rows = len(matrix) cols = len(matrix[0]) rotatedMatrix = [] #create empty matrix to copy the rotated values into for rowNum in range(cols): l = [] for colNum in range(rows): l.append(None) rotatedMatrix.append(l) #fill in with rotated values for rowNum in range(rows): for colNum in range(cols): rotatedMatrix[colNum][rowNum] = matrix[rows-1-rowNum][colNum] return rotatedMatrix # Problem 1.8 def zeroMatrix(matrix): #base cases if (matrix == []): return [] if (matrix[0] == []): return [] rows = len(matrix) cols = len(matrix[0]) zeroPointsX = [] zeroPointsY = [] for rowNum in range(rows): for colNum in range(cols): if matrix[rowNum][colNum] == 0: zeroPointsX.append(rowNum) #register x point zeroPointsY.append(colNum) #register y point for rowNum in range(rows): for colNum in range(cols): if (rowNum in zeroPointsX or colNum in zeroPointsY): matrix[rowNum][colNum] = 0 return matrix # Problem 1.9 #check if s2 is a rotation of s1 def stringRotation(s1, s2): for i in range(len(s2)): rotatedString = s2[i:] + s2[:i] if rotatedString == s1: return True return False #needed for problem 1.9 def isSubstring(string, sub): if sub in string: return True return False if __name__ == "__main__": print("Test isUnique") check(isUnique("hello"), False) check(isUnique("why"), True) print("---------------------------------") print("Test checkPermutation") check(checkPermutation("aba", "baa"), True) check(checkPermutation("abb", "aba"), False) print("---------------------------------") print("Test URLify") check(urlify("Mr John Smith ", 13), "Mr%20John%20Smith") print("---------------------------------") print("Test Palindrome Permutation") check(palindromePermutation("Tact Coa"), True) print("---------------------------------") print("Test One Away") check(oneAway("pale", "ple"), True) check(oneAway("pales", "pale"), True) check(oneAway("pale", "bale"), True) check(oneAway("pale", "bake"), False) print("---------------------------------") print("Test String Compression") check(stringCompression("aabcccccaaa"), "a2b1c5a3") check(stringCompression("aabccccca"), "a2b1c5a1") check(stringCompression("a"), "a") print("---------------------------------") print("Test Rotate Matrix") check(rotateMatrix([[1, 2, 3], [4, 5, 6]]), [[4,1], [5,2], [6,3]]) check(rotateMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[7, 4,1], [8, 5,2], [9, 6,3]]) check(rotateMatrix([[1]]), [[1]]) check(rotateMatrix([[1], [2]]), [[2, 1]]) print("---------------------------------") print("Test Zero Matrix") check(zeroMatrix([[1], [0]]), [[0], [0]]) check(zeroMatrix([[1, 2, 3], [4, 5, 6]]), [[1, 2, 3], [4, 5, 6]]) check(zeroMatrix([[1, 2, 3], [4, 0, 6]]), [[1, 0, 3], [0, 0, 0]]) print("---------------------------------") print("Test String Rotation") check(stringRotation("waterbottle","erbottlewat"), True)
3792e802f66ceaa4de32591973aba9647e4276ad
elazafran/ejercicios-python
/Ficheros/ejercicio1.py
1,088
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 1.Crea una función que pida el nombre de un fichero y su atributo( “añadir”) el fichero contendrá los 10 primeros números , también se creara una función para leer fichero realizar un menú con las siguientes opciones 1.Crear fichero 2.Leer fichero 3.salir ''' def crearFichero(): nombreFichero=input("Introduzca nombre de fichero: ") p = open(nombreFichero,"a") p.write("1,2,3,4,5,6,7,8,9,10") print (p) p.close() def leerFichero(nombreFichero): p=open(nombreFichero,"r") print(p.read()) p.close() while True: opcion=int(input("selecione opcion:" +"\n1.crear fichero" +"\n2.Leer fichero" +"\n3.Salir\nIntroduzca : ")) if opcion==1: crearFichero() if opcion==2: nombreFichero=input("Introduzca nombre de fichero: ") leerFichero(nombreFichero) if opcion==3: break #crearFichero(nombreFichero) #leerFichero(nombreFichero)
9133c857d03cd83bc6a56b4707986021ffac90f5
l19nguye/Udacity_DE_DataWarehouse
/create_tables.py
1,857
3.84375
4
import configparser import psycopg2 from sql_queries import create_table_queries, drop_table_queries def drop_tables(cur, conn): """ This function in order to drop existing tables. The list drop_table_queries is imported from sql_queries module. Input: cursor and connection to database. How does it work: iterate over each query of list drop_table_queries, then execute it to drop each table. """ for query in drop_table_queries: cur.execute(query) conn.commit() def create_tables(cur, conn): """ This function in order to create staging as well as target tables. The list create_table_queries is imported from sql_queries module. Input: cursor and connection to database. How does it work: iterate over each query of list create_table_queries, then execute it to create each table. """ for query in create_table_queries: cur.execute(query) conn.commit() def main(): """ When .py file excuted in Command Prompt, this function will be invoked first. This file will be executed only if we want to clean existing tables then recreate them again to import new data. How does it work: - first, loading configurations from dwh.cfg file. - second, using configurations which just been loaded to connect database in Redshift. - once connection established, call helper function to drop existing tables. - then call another helper function to create those tables again. """ config = configparser.ConfigParser() config.read('dwh.cfg') conn = psycopg2.connect("host={} dbname={} user={} password={} port={}".format(*config['CLUSTER'].values())) cur = conn.cursor() drop_tables(cur, conn) create_tables(cur, conn) conn.close() if __name__ == "__main__": main()
5ec4a97be6949e7ce39b933b934911324c403398
bcollins5/mis3640
/session_11.py
1,801
3.765625
4
#Exercise 4 #Problem 1 '''Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.''' # list = [word.txt] # import os # os.chdir("C:/Users/bcollins5/Documents/GitHub/mini-project-hangman-bcollins5/words.txt") # fname = input("File name: ") # if len(fname) < 1 : fname = "words.txt" # fh = open(fname) # counter = 0 # dictionary = dict() # for line in fh: # word = line.rstrip().split() # for word in words: # dictionary[word] = counter # counter += 1 # print(dictionary) #resources used/information collected from the following: #daniweb.com , stackoverflow #Problem 2 '''Write a function named has_duplicates that takes a list as a parameter and returns True if there is any object that appears more than once in the list.''' list_of_SB_winner_in_last_five = ['Broncos', 'Patriots', 'Seahawks', 'Ravens', 'Giants'] def has_duplicate(myList): dictionary = {} for word in myList: dictionary[word] = 1 + dictionary.get(word, 0) if dictionary[word] > 1: #there is an issue within the lines above, where it is not return True #correctly counting duplicates (maybe something to do with 'dictionary') else: return False print(has_duplicate(list_of_SB_winner_in_last_five)) list_of_WS_winner_in_last_five = ['Royals' 'Giants', 'Red Sox', 'Giants', 'Cardinals'] print(has_duplicate(list_of_WS_winner_in_last_five)) ### help / issue to fix: it is not returning True for List of WS winners, when Giants is there twice ##resources used/information collected from the following: #thinkpy-solutions, stackoverflow
a81bc2c74284bf29c73329f5e14568810dfab821
Hewuxin/ubuntu_project
/Project_py/shujujiegou/数据结构/sort/shell_sort.py
910
4
4
def shell_sort(nums): """ 时间复杂度 O(n**1.3) 最差时间复杂度O(n**2) 稳定性 不稳定 会改变相同元素间的相对顺序 :param nums: :return: """ n = len(nums) gap = n // 2 while gap >= 1: # 缩短步长 for i in range(gap, n): # 遍历当前子序列的所有元素 j = i while j > 0: # 每一个子序列执行插入排序 if nums[j] < nums[j-gap]: nums[j], nums[j-gap] = nums[j-gap], nums[j] j -= gap else: break gap = gap // 2 # 缩短步长 return nums # 时间复杂度 O(n^2) 最好时间复杂度O(n^1.3) # 稳定性 不稳定 相同元素的相对顺序会发生改变 if __name__ == "__main__": print([1, 8, 4, 5, 7, 6, 10, 15, 12]) print(shell_sort([1, 8, 4, 5, 7, 6, 10, 15, 12]))
befb673f7a07a5f5ae12fca75888b1811339aed4
yanray/leetcode
/problems/0234Palindrome_Linked_List/0234Palindrome_Linked_List2.py
1,838
4.15625
4
""" Reverse Linked List Version: 1.1 Author: Yanrui date: 5/29/2020 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class SingleLinkedList: def __init__(self): "constructor to initiate this object" self.tail = None self.head = None def add_list_item(self, item): # add a node in the linked list if self.head is None: self.head = item else: self.tail.next = item self.tail = item def display_all_nodes(self): # print all values in the linked list current_node = self.head while current_node.next is not None: print(current_node.val, '-> ', end = "") current_node = current_node.next print(current_node.val) class Solution: def isPalindrome(self, head: ListNode) -> bool: self.front_pointer = head def recursively_check(current_node=head): if current_node is not None: if not recursively_check(current_node.next): return False if self.front_pointer.val != current_node.val: return False self.front_pointer = self.front_pointer.next return True return recursively_check() if __name__ == '__main__': a = Solution() # build nodes for linked list 1 l1_node1 = ListNode(1) l1_node2 = ListNode(2) l1_node3 = ListNode(2) l1_node4 = ListNode(1) l1 = SingleLinkedList() l1.add_list_item(l1_node1) l1.add_list_item(l1_node2) l1.add_list_item(l1_node3) l1.add_list_item(l1_node4) # display l1, l2 l1.display_all_nodes() print(a.isPalindrome(l1.head))
4451c5641a03b0020683612002fe0684bb070c61
alliejones/adventcode
/ex01_2.py
358
3.53125
4
floor = 0 basement_pos = None with open('ex01-input.txt') as file: pos = 0 for line in file: for ch in line: if ch == '(': floor += 1 elif ch == ')': floor -= 1 pos += 1 if floor < 0 and not basement_pos: basement_pos = pos print basement_pos
57c5f1f0fd28705dad8d7e50eefbb09fd34a50ab
Aarohi-masq/100Days
/TipCalculator.py
388
3.9375
4
print("Enter the cost of meal: ") cost_of_meal = input() tax = 0.5 print(f"tax percentage: {tax}%") tip = 2 print(f"tip percentage: {tip}%") dollars_meal = float(cost_of_meal.replace("$","")) print(dollars_meal) dollars_meal = dollars_meal + (dollars_meal * tax/100) total = dollars_meal + (dollars_meal*tip/100) print(f"So your total amount to be paid is equal to {total:.2f}")
975ca209cf420af7e312d8ec1e6151ba93ed4056
rinoa25/moneydoesgrowontrees
/main.py
17,591
4.125
4
## Project: Money Does Grow On Trees ## ## Authors: Aranya Sutharsan, Rinoa Malapaya Noshin Rahman, Carol Altimas ## import time # Imports a module to add a pause from morning import * # User Responses yes = ["Y", "y", "yes"] no = ["N", "n", "no"] answer_A = ["A", "a"] answer_B = ["B", "b"] answer_C = ["C", "c"] # Variables for the game green_points = 0 chequings_acc = 1000 savings_acc = 0 money = 0 ## Introduction + Morning## # Main Functions - calls all functions def main(): global green_points global money global answer_A global answer_B global answer_C global yes global no global savings_acc global chequings_acc global credit_avail green_points = 5 money = 1000 answer_A = ["A", "a"] answer_B = ["B", "b"] answer_C = ["C", "c"] yes = ["y", "yes"] no = ["n", "no"] intro() afternoon() night() one_month_later() six_months_later() one_year_later() def intro(): print("Welcome to Money Does Grows On Trees!") print("-" * 80) print("As you play along in this game you will be collecting and losing money based on the financial " "decisions you made.") print("As well as collecting and losing green points based on your environmental decisions.") print() print("You will be given 5 Green points from the start :)") print("You have also saved $1000 from Christmas / Birthdays / Weekly allowances / doing chores! Nice job!") print("-" * 80) print("Before the game starts, here are some terminology!") print() print(" 1. Savings accounts are bank accounts that pay interest on the money you deposit.") print() print(" 2. Interest is your reward for steady and consistent saving!") print(" - the more money you put in, the more interest you earn, and the more your balance will grow.") print() print(" 3. High-growth interest is still a savings account") print(" - however, it pays a little bit more interest compared to a regular savings account!") print("-" * 80) print("Now let's start the game!") introQn() def verifyIntro(): print("How much would you like to set aside?") extraChoice = input(">>> ") if extraChoice.isdigit(): if float(extraChoice) < 0 or float(extraChoice) == 0: print("Invalid input. Please enter an amount greater than 0.") print() verifyIntro() if float(extraChoice) > 1000: print("Invalid input. Please enter an amount less than 1000.") print() verifyIntro() if 0 < float(extraChoice) <= 1000: print("-" * 80) global savings_acc global chequings_acc savings_acc = float(extraChoice) chequings_acc = 1000 - savings_acc morning1() else: print("Invalid input. Please enter a digit!") print() verifyIntro() def introQn(): print() print("Would you like to set aside some amount of money to your savings account?") choice = input(">>> ") if choice.lower() in yes: print() verifyIntro() elif choice.lower() in no: print("Note: Setting aside some money in your savings account would have been great in the long run!") print(" - The more money you set aside, the higher interest / return you'd have :)") print("-" * 80) morning1() else: print("Invalid input! Please type yes/no OR y/n") introQn() def morning1(): print("It’s Monday morning and you just woke up from a lovely nap.") print("You have done your morning routine, and are ready to go to school.") print() morning1Qn() def morning1Qn(): print("Do you want to buy breakfast (a) or make a healthy breakfast at home (b)?") choice = input(">>> ") if choice.lower() in answer_A: print("Note: A better choice could have been to make a meal at home!") print(" - It is always great to save whenever you can :)") print("-" * 80) morning2Bad() elif choice.lower() in answer_B: print("Great Choice! Hope you have a great breakfast :)") print("-" * 80) morning2Good() else: print("Invalid input! Please type a or b") print() morning1Qn() def morning2Bad(): print("Do you want to walk to the cafe (a)? Or want to take a bus to the cafe (b)?") choice = input(">>> ") global green_points if choice.lower() in answer_B: print("Note: It would have been more eco friendly to walk!") print(" - By taking public transportation, we are contributing more carbon footprint :(") print() print("Unfortunately, a green point will be removed!") green_points = green_points - 1 print("-" * 80) morning3Bad() elif choice.lower() in answer_A: print("Excellent choice, by walking you are helping mother nature by reducing carbon footprint :)") print(" - Enjoy the view!") print() print("Congrats you have received a green point for doing a good deed!") green_points = green_points + 1 print("-" * 80) morning3Bad() else: print("Invalid input! Please type a or b") print() morning1Qn() def morning2Good(): print("You enjoyed your healthy breakfast along with your family.") print("However you still have time before school starts.") print() morning2GoodQn() def morning2GoodQn(): print("Would you like to play a fun game of 'Among Us'?") choice = input(">>> ") if choice.lower() in yes: print("Hope you have fun!") print("-" * 80) morning3Good() elif choice.lower() in no: print("Ohh that a bummer!") print("-" * 80) morning3Good() else: print("Invalid input! Please type yes/no OR y/n") print() morning2GoodQn() def morning3Good(): print("After moments of travelling, you finally reached school.") morning4() print("-" * 80) def morning3Bad(): print("Once you walk into the cafe, you spot the menu.") print("Bagel: $2.20 (a) | Coffee: $1.60 (b) | Both: $3.50 (c)") print() print("Now it's time to decide what you would like to eat!") print() morning3BadQn() def morning3BadQn(): print("What would you like to have?") choice = input(">>> ") global chequings_acc if choice.lower() in answer_A: print("Note: Nice choice! Bagel cost $2.20 plus tax this would equal up to $2.5.") chequings_acc = float(chequings_acc) - 2.50 print("-" * 80) morning3Good() elif choice.lower() in answer_B: print("Great choice to boost up your energy for the day!") print(" - Coffee cost $1.60 plus tax this would equal to $1.80.!") print(" - This is the cheapest option too! Nice job :)") chequings_acc = float(chequings_acc) - 1.80 print("-" * 80) morning3Good() elif choice.lower() in answer_C: print("You’re set for the day!") print(" - Although this combo might seem like a steal, the final is actually $3.95! Not bad.") chequings_acc = float(chequings_acc) - 3.95 print("-" * 80) morning3Good() else: print("Invalid input! Please type a, b or c") print() morning3BadQn() def morning4(): print("While walking to your classroom, you see a fellow classmate throw their garbage on the floor.") morning4Qn() def morning4Qn(): print("What would you do? ") print("a. Tell the student to pick up the garbage") print("b. You throw away classmate's garbage") print("c. Ignore the garbage and walk away") choice = input(">>> ") global green_points if choice.lower() in answer_A: print("Good job for raising awareness!") print() green_points = green_points + 1 print("Congrats you have received a green point for doing a good deed!") print("-" * 80) morningSummary() elif choice.lower() in answer_B: print("Thank you for being a good citizen! ") print() green_points = green_points + 1 print("Congrats you have received a green point for doing a good deed!") print("-" * 80) morningSummary() elif choice.lower() in answer_C: print("Littering can cause a serious aftermath for the environment.") print(" - such as pollution, kills wildlife and many more.") print() green_points = green_points - 1 print("Unfortunately, a green point will be removed!") print("-" * 80) morningSummary() else: print("Invalid input! Please type a, b or c") print() morning4Qn() def morningSummary(): print("Chequing Account Balance: ", float(chequings_acc)) print("Savings Account Balance: ", float(savings_acc)) print("Green Points Collected: ", float(green_points)) ## Afternoon ## ## Night ## required = "\nUse only a, b, or c\n" # Cutting down on duplication # The story is broken into sections, starting with "intro" def night(): print("-" * 80) print("""It was a long day at school. You're hungry. You want a snack.""") print("You head to your kitchen.") print("What should you have?") print(" a. A homemade chocolate chip cookie! It is the love of your life!") print(" b. A bowl of frozen grapes. A little weird, but it tastes like candy!") choice = input(">>> ") # input of the choice if choice in answer_A: print("Excellent choice! It was delicious!") night_2() elif choice in answer_B: print("Yessss frozen grapes! ") night_2() else: print(required) night() # next action is def night_2(): print("-" * 80) print("You have some time to kill before dinner. You finished up your homework at school.") print("You decide to watch some TV. You're torn between watching Victorious or iCarly and you only have time for two episodes.") print("You realize that you can use a financial term called Opportunity Cost to decide.") print("Opportunity Cost is the loss of potential gain from other alternatives when one alternative is chosen.") print("For example, if you only watch Victorious, the opportunity cost is two episodes of iCarly, since you would be missing out on watching two episodes of iCarly") print("For example, if you only pick iCarly, the opportunity cost is two episodes of Victorious.") print("What should you do?") print(" a. Watch two episodes of Victorious") print(" b. Watch two episodes of iCarly") print(" c. Watch one episode of iCarly and one episode of Victorious") choice = input(">>> ") # input of the choice if choice in answer_A: print("Great choice! You spend time singing along to the songs!") print("Your sister Jane even comes and sings along") night_3() elif choice in answer_B: print("Awesome choice! iCarly is showing that episode where her room is redone!") print("You spend time singing along to the songs and your sister Jane even comes to watch!") night_3() elif choice in answer_C: print("Awesome choice! iCarly is showing that episode where her room is redone") print("Victorious even shows your favourite episode!") night_3() else: print(required) night_2() # night 3 action def night_3(): print("-" * 80) print("It's dinnertime. You leave the TV room, but forget to turn off the lights.") print("You're almost at the dinner table, but you can go back and turn off the lights. What will you do?") print("What will you do?") print(" a. Go back and turn off the lights.") print(" b. Ignore the lights and go have dinner.") choice = input(">>> ") # input of the choice global green_points if choice in answer_A: print("""Awesome choice! Turning off the lights is one of the small decisions that helps the environment every day!""") print("""You get one green point!""") green_points = green_points + 1 night_4() elif choice in answer_B: print(""" The lights shine through the door of the TV room. Your sister Jane notices and goes to turn them off.""") print("""You should have turned them off earlier. You lose one green point.""") green_points = green_points - 1 night_4() else: print(required) night_3() # night 4 action def night_4(): print("-" * 80) print("It's getting late. You're about to head to bed, but your sister Jane stops you in the corridor.") print("She's talking about how she wants to get the ps5 again.This is the only topic on her mind these days. ") print("Your mom gave you each some Christmas money to buy things, but Jane doesn't have enough for the ps5 yet and you're in charge on the finances") print("Her birthday's coming up, so she'll probably have enough soon. Her tone changes. ") print("I really want to get the WII as well. Could I buy that tonight?" "What should you do?") print(" a. You remind Jane of her long term goal of getting the ps5 and tell her to hold off on getting the WII. ") print(" b. You cave and tell her to get the WII. She probably won't be able to buy the ps5 later on, but who cares about her long term goal? ") choice = input(">>> ") # input of the choice if choice in answer_A: print( "Great Choice! Jane remembers how much she wants the ps5 and agrees that she should save up instead." ) night_5() elif choice in answer_B: print("""You begin the process of buying the WII online. Once bought, Jane remembers how much she wanted the ps5 and regrets the WII decision.""") print("""Jane realizes that she completely forgot her longterm goal and is a little disappointed, but she's okay with getting the WII in the end.""") night_5() else: print(required) night_4() # night 5 action def night_5(): print("-" * 80) print("""You've finally made it to bed. You lay down under the covers and notice that you're feeling a little cold.""") print("""BURRRRRR. It's not winter-level cold, but it's going to bother you.""") print("""You decide to do something about it, since you know that you can't sleep when it's cold.""") print("""What do you do?""") print(" a. Grab a warm blanket from the linen closet.") print(" b. Change into your favourite warm pjs.") print(" c. Turn up the heat.") global green_points choice = input(">>> ") # input of the choice if choice in answer_A: print("Good choice! You begin to feel warm and can finally sleep! ") print( "By using less heat, you're helping the environment. You get one green point!" ) green_points = green_points + 1 end_of_night() elif choice in answer_B: print("YESSS!! warmth finally. It feels so good to be in your favourite pjs.") print( "By not turning up the heat and wearing your pjs, you're helping the enviroment. Here's a green point!" ) green_points = green_points + 1 end_of_night() elif choice in answer_C: print("You can feel the heat instantly. ") print( "You knew you probably didn't need to turn on the heat, since it wasn't too cold. You lose one green point." ) green_points = green_points - 1 end_of_night() else: print(required) night_5() def end_of_night(): print('\n'"You finally fall asleep.") print('\n'"The first day is done") print("Chequing Account Balance: ", float(chequings_acc)) print("Savings Account Balance: ", float(savings_acc)) print("Green Points Collected: ", float(green_points)) def one_month_later(): global savings_acc savings_acc = interestformula(savings_acc, float(0.05), (1/12)) print('\n'"If you continue your actions for a month. Your account would look like...") print("Chequing Account Balance: ", float(chequings_acc)) print("Savings Account Balance: ", float(savings_acc)) temp_green_points = green_points * 30 * 1 print("Green Points Collected: ", float(temp_green_points)) def six_months_later(): global savings_acc savings_acc = interestformula(savings_acc, float(0.01),(6/12)) print('\n'"If you continue your actions for six months. Your account would look like...") print("Chequing Account Balance: ", float(chequings_acc)) print("Savings Account Balance: ", float(savings_acc)) temp_green_points = green_points * 30 * 6 print("Green Points Collected: ", float(temp_green_points)) def one_year_later(): global savings_acc savings_acc = interestformula(savings_acc, float(0.01),(6/12)) print('\n'"If you continue your actions for a year. Your account would look like...") print("Chequing Account Balance: ", float(chequings_acc)) print("Savings Account Balance: ", float(savings_acc)) temp_green_points = green_points * 30 * 12 print("Green Points Collected: ", float(temp_green_points)) def interestformula(given_money, interest, time): temp = given_money inner_equation = 1 + (time/12) exponent = (12 * time) current_money = inner_equation ** exponent current_money = temp * current_money return current_money main()
5afaacb06fb0b9800c9da1dd841d574a66a5dc0f
Factotum8/coursera_independent_works_dive_into_python
/1_week_3_independent_work.py
207
3.609375
4
import sys from math import sqrt a = int(sys.argv[1]) b = int(sys.argv[2]) c = int(sys.argv[3]) print(int((-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a))) print(int((-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a)))
953aef889c69cbe33a2c0b7471fc33b08b82bc8e
lidebao513/Python
/untitled2/day6/loginjson.py
1,785
3.65625
4
#! /usr/bin/env python #-*-coding:utf-8-*- ''' 1 模拟登录 2 模拟登录成功显示登录成功后的账号 3 模拟注册 ''' import json def regetist(username,password): ''' 实现注册功能 username:注册系统账号 password:注册系统密码 :return: ''' temp = username+'|'+password json.dump(temp,open('login','w')) def login(username,password): ''' 登录 :param username: 登录系统的账号 :param password: 登录系统的密码 :return: ''' f = str(json.load(open('login', 'r'))) list1 = f.split('|') if list1[0] == username and list1[1] == password: return True else: return False def info(username,password): ''' 系统登录后成功的页面 :return: ''' f = str(json.load(open('login', 'r'))) list1 = f.split('|') r= login(username,password) if r: print(u'恭喜{0}进入到系统'.format(list1[0])) else : print(u'登录失败') # f.close() def exit(): import sys sys.exit(1) def typeUsername(): username = input(u'请输入账号\n') return username def typePassword(): password = input(u'请输入密码\n') return password def main(): '''主函数''' while True: t = int(input('1、注册 2、 登录 3 退出登录\n')) if t ==1: username = typeUsername() password = typePassword() regetist(username,password) elif t ==2 : username = typeUsername() password = typePassword() login(username,password) info(username, password) elif t == 3: exit() else: print(u'输入错误请重新输入') if __name__ == '__main__': main()
97a89a2afc6397a544d149d2714576edc9aefd28
Jousha/GW2-Inventory-Prices
/Scripts/helpers.py
5,497
3.6875
4
import json import math import requests def get_bank_inventory(api_token): ''' Input: api_token - String of the api key of a valid account with inventory viewing rights Returns a list object containing the bank inventory associated with the api key ''' inventory_api = f'https://api.guildwars2.com/v2/account/bank?access_token={api_token}' return _parse_data(inventory_api) def get_character_inventory(api_token, character_name): ''' Input: api_token - String of the api key of a valid account with inventory viewing rights character_name - The name of the character which will be queried Returns a list object containing id numbers of items in the character inventory associated with the api key ''' if (' ' in character_name): character_name = '%20'.join(character_name.split(' ')) character_api = f'https://api.guildwars2.com/v2/characters/{character_name}/inventory?access_token={api_token}' item_ids = [] bags = _parse_data(character_api)['bags'] for bag in bags: inventory = bag['inventory'] for item in inventory: if not item is None: item_ids.append(item['id']) return item_ids def get_all_character_inventories(api_token): ''' Input: api_token - String of the api key of a valid account with inventory viewing rights Returns a dictionary object of [Key] Character name: [Value] Inventory{list) ''' character_list_api = f'https://api.guildwars2.com/v2/characters?access_token={api_token}' characters = _parse_data(character_list_api) character_inventories = {} for character in characters: character_inventories[character] = get_character_inventory(api_token, character) return character_inventories def get_item_name(item_id): ''' Input: item_id - String of an id reference number of an item in the game Returns a string object for the item's name ''' item_api = f'https://api.guildwars2.com/v2/items?ids={item_id}' item_data = _parse_data(item_api) return item_data[0]['name'] def get_item_buy_price(item_id): ''' Input: item_id - String of an id reference number of an item in the game Returns a string object for the item's auction house sell price (in copper) ''' item_api = f'https://api.guildwars2.com/v2/commerce/listings?ids={item_id}' price_list = _parse_data(item_api) return price_list[0]['buys'][0]['unit_price'] def get_item_buy_strength(item_id): ''' Input: item_id - String of an id reference number of an item in the game Returns a string object for the quantity of total buy orders ''' item_api = f'https://api.guildwars2.com/v2/commerce/listings?ids={item_id}' price_list = _parse_data(item_api) return price_list[0]['buys'][0]['quantity'] def get_item_sell_price(item_id): ''' Input: item_id - String of an id reference number of an item in the game Returns a string object for the item's auction house buy price (in copper) ''' item_api = f'https://api.guildwars2.com/v2/commerce/listings?ids={item_id}' price_list = _parse_data(item_api) return price_list[0]['sells'][0]['unit_price'] def get_item_sell_strength(item_id): ''' Input: item_id - String of an id reference number of an item in the game Returns a string object for the quantity of total sell orders ''' item_api = f'https://api.guildwars2.com/v2/commerce/listings?ids={item_id}' price_list = _parse_data(item_api) return price_list[0]['sells'][0]['quantity'] def get_item_profitability(item_id): ''' Input: item_id - String of an id reference number of an item in the game Returns an integer object of the expected profit from flipping the item after transaction fees (5% on listing and 10% on sale) have been taken ''' cost = 0 revenue = 0 buy = get_item_buy_price(item_id) sell = get_item_sell_price(item_id) if (buy * 0.05) < 1: cost = buy + 1 else: cost = math.ceil(buy * 1.05) if (sell * 0.10) < 1: revenue = sell - 1 else: revenue = math.floor(sell * 0.90) return revenue - cost def convert_to_gold(amount): ''' Input: amount - An amount of money (in coppers) Returns a string representation of the given amount in gold, silver, copper format ''' negative = False if amount < 0: negative = True amount = abs(amount) if amount < 100: if negative: return f'{amount}c loss' else: return f'{amount}c profit' elif amount < 1000: silver = math.floor(amount / 100) copper = amount % 100 if negative: return f'{silver}s {copper}c loss' else: return f'{silver}s {copper}c profit' else: gold = math.floor(amount / 1000) silver = math.floor((amount % 1000) / 100) copper = (amount % 1000) % 100 if negative: return f'{gold}g {silver}s {copper}c loss' else: return f'{gold}g {silver}s {copper}c profit' def _parse_data(api_string): ''' Input: api_string - String of a valid api link Returns a list object of JSON parsed data from the api link ''' r = requests.get(api_string) parsed_r = json.loads(r.text) return parsed_r
f9946a69d8b3299e7041aec89adda414e13e375d
freesoul84/python_codes
/other_python_codes/immediate_smaller_ele.py
327
3.71875
4
test=int(input()) for _ in range(test): number=int(input()) array=list(map(int,input().split())) for i in range(number-1): if array[i]>array[i+1]: array[i]=array[i+1] else: array[i]=-1 array[-1]=-1 for i in range(number): print(array[i],end=" ") print()
3facec5fb825ba51bdb047258cf5e08b55f803c6
saiyesaswym/Algorithms-DataStructures-using-Python
/Leetcode/Array/MaximumAveragePassRatio.py
1,377
3.546875
4
""" Brute force Approach Find max change in pass ratio for every student Time complexity: O(n*m) - n->classes m->extraStudents Space complexity: O(1) """ def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: while extraStudents>0: max_percent=0 idx=-1 for i,c in enumerate(classes): if c[0]==c[1]: pass else: percent1 = c[0]/c[1] percent2 = (c[0]+1)/(c[1]+1) if percent2-percent1>max_percent: max_percent = percent2-percent1 idx=i extraStudents-=1 classes[idx][0]+=1 classes[idx][1]+=1 maxsum=0 for c in classes: maxsum+=c[0]/c[1] return maxsum/len(classes) """ Using Priority Queue - MaxHeap Time complexity: O(mlogn) """ def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: #Initialize heap pq=[] #Push change in pass ratio for every student for p,t in classes: heapq.heappush(pq, (p/t - (p+1)/(t+1), p, t)) #For every max element add 1 and push it into the queue while extraStudents>0: _,p,t = heapq.heappop(pq) p+=1 t+=1 heapq.heappush(pq, (p/t - (p+1)/(t+1), p, t)) extraStudents-=1 return sum([p/t for _,p,t in pq])/len(classes)
5a43ef0ab704ba6f767e04583f587f2d0ecccca4
nervig/Starting_Out_With_Python
/Chapter_2_programming_tasks/task_2.py
214
3.953125
4
#!/usr/bin/python # asks user enter volume of sales planned_volume_of_sales =int(input('Please, enter the planned volume of sales: ')) # calculating of profit profit = planned_volume_of_sales * 0.23 print(profit)
ba62418b6ef564416c4c733d32f6287b1e0f6845
MattWise/ProbabilityProject
/Probability.py
3,195
3.640625
4
from __future__ import division,print_function from random import random from Functions import * from types import * """ P is a dictionary of frozenset, dictionary pairs. The former is the sample space or a subset of it. The latter is a dictionary of frozenset, float pairs. The former is a simple event. The latter is the probability of its occurrence. It may sometimes be desirable to use some other hashable for the keys of P or the keys of the values of P. Do not attempt set theoretic operations in these cases. To get the probability of a given simple event E with event set S taken as the sample space, call P[S][E]. The over all sample space with accompanying event probabilities must be explicitly passed to P before any subset probabilities can be calculated. Random Variables are implemented as functions of signature: float func(frozenset event) and are expected to be memoized with Functions.memodict. """ class P(dict): def __init__(self, probDict, **kwargs): #inpt must be a list or tuple of form: (frozenset sampleSpace,dict(0) probabilities) assert isinstance(probDict,DictType) super(P,self).__init__(**kwargs) self.SampleSpace=frozenset(probDict.keys()) self[self.SampleSpace]=probDict self.Weights={self.SampleSpace:1.} def verifySampleSpace(self): #Debugging function. for key in self.keys(): if not self.SampleSpace.issuperset(key): raise ValueError("Keys of P not subsets of sample space.") def __missing__(self,key): #Recall, key should be a hashable collection of hashable collections representing simple events. if not frozenset((frozenset(item) for item in key)).issubset(frozenset(frozenset(item) for item in self.SampleSpace)): print(frozenset(key)) raise ValueError("Key not subset of sample space") else: return self.__addSubset(key) def __addSubset(self, subset): #For internal use. No verification. weight=sum((self[self.SampleSpace][event] for event in subset)) self.Weights[subset]=weight probabilities=defDict() for simpleEvent in subset: probabilities[simpleEvent]=self[self.SampleSpace][simpleEvent]/weight self[subset]=probabilities #verifyNormalization(self,subset) return self[subset] def probabilityOfCompoundEvent(self,subset): #Returns probability of the compound event represented by the set of simple events "subset". #Memiozed, of course, via the dictionary behavior of P. self[subset] #Ensures subset in P return self.Weights[subset] @staticmethod def randomEvent(probdict): r=random() #Random float value between 0 and 1. sum=0. for key in probdict.keys(): sum+=probdict[key] if sum>=r: return key assert False,"randomEvent isn't working. Floating point issue?" return probdict.keys()[-1] #If the above assertion occurs occasionally but not so frequently as to sugguest a genuine issue, this line should fix rare floating point inaccuracies.
b6d78cbe02aba2e7a20a9e3142d4300ad8942e1b
green-fox-academy/bertokpeter
/week-03/day-01/reversed_lines.py
248
4.25
4
# Create a method that decrypts reversed-lines.txt reversed_file = "week-03/day-01/reversed_lines.txt" def reverse(file_name): with open(file_name, "r") as f1: for line in f1: print(line[::-1], end='') reverse(reversed_file)
83d01bd20e4af9f74b77a755041a892e472ddbc4
danielrs975/simulacion
/Problema I Version II/main.py
12,616
3.75
4
from random import random, expovariate, uniform from math import sqrt from scipy import stats from collections import deque # Funciones para calculo de probabilidades def probabilidad_binomial(prob): numero_aleatorio = random() if numero_aleatorio <= prob: return True return False # CLASES PARA LA SIMULACION class Cliente: ''' Clase que representa a los clientes del sistema ''' def __init__(self, tiempo_llegada=None): ''' Constructor de la clase ''' self.tiempo_llegada = tiempo_llegada # Tiempo en el cual entra al sistema self.tiempo_salida_cola = None # Tiempo en el cual sale de la cola self.tiempo_en_el_sistema = None # Tiempo total en el sistema self.tiempo_atencion = None # Tiempo que dura el servidor en atenderlo def cliente_declina(self, long_cola): ''' Metodo que devuelve un booleano si el cliente declina a hacer la cola o no ''' if 6 <= long_cola <= 8: return probabilidad_binomial(0.20) elif 9 <= long_cola <= 10: return probabilidad_binomial(0.40) elif 11 <= long_cola <= 14: return probabilidad_binomial(0.60) elif long_cola >= 15: return probabilidad_binomial(0.80) return False class Cajero: ''' Clase que representa a los servidores del sistema ''' def __init__(self): ''' Constructor de la clase ''' self.tiempo_libre = 0 self.tiempo_llega_cliente = 0 self.tiempo_sale_cliente = 0 self.ocupado = False self.cliente = None class Servidores: ''' Clase que representa los servidores de un sistema ''' def __init__(self, cant): ''' Constructor de la clase ''' self.lista_cajeros = [] for i in range(cant): self.lista_cajeros.append(Cajero()) def hay_cajero_disponible(self): ''' Funcion que ve si existe un cajero disponible y lo retorna ''' cajeros_disponibles = [] for cajero in self.lista_cajeros: if not cajero.ocupado: cajeros_disponibles.append(cajero) return cajeros_disponibles def generar_clientes(cant): ''' Funcion que genera la cantidad de clientes para el sistema ''' tiempo_inicial = 0 clientes = [] for i in range(cant): tiempo_llegada = tiempo_inicial + generar_tiempo_llegada() tiempo_inicial = tiempo_llegada clientes.append(Cliente(tiempo_llegada)) return clientes def generar_tiempo_llegada(): ''' Funcion que se encarga de generar el tiempo de llegada de un cliente ''' return expovariate(1) def generar_tiempo_servicio(): ''' Funcion que genera el tiempo de servicio de un cajero ''' return uniform(3, 5) # Funcion que realiza la simulacion def simulacion(minutos, cant_clientes): ''' Funcion que va a correr la simulacion ''' # Inicializacion de los recursos necesario para # la simulacion clientes = generar_clientes(cant_clientes) # Genera los clientes que participaran en el sistema servidores = Servidores(4) cola_espera = deque([]) clientes_listos = [] # Va a almacenar todos los clientes que salieron del banco clientes_se_rindieron = 0 # Lleva la cuenta del numero de clientes que no hicieron la cola tiempo_actual = 0.0 while tiempo_actual < minutos: # Simulacion de las personas cuando llegan a la cola for cliente in clientes: # Veo si el tiempo ya llego al banco if cliente.tiempo_llegada <= tiempo_actual: # Veo si el cliente decide declinar o no if cliente.cliente_declina(len(cola_espera)): clientes_se_rindieron += 1 clientes.remove(cliente) else: # Si no declina procede a entrar en la cola cola_espera.append(cliente) clientes.remove(cliente) else: break # Esto se hace porque estan ordenados cronologicamente # Primero recorro los servidores para ver cuales # han terminado con sus clientes y liberarlos for cajero in servidores.lista_cajeros: # Esto solo tiene sentido si el cajero esta ocupado if cajero.ocupado: # Tomo al cliente que esta atendiendo el cajero cliente_en_proceso = cajero.cliente tiempo_finalizacion = cliente_en_proceso.tiempo_salida_cola + cliente_en_proceso.tiempo_atencion if tiempo_finalizacion <= tiempo_actual: # Esto significa que ya termino de atenderlo cliente_en_proceso.tiempo_en_el_sistema = tiempo_finalizacion - cliente_en_proceso.tiempo_llegada clientes_listos.append(cliente_en_proceso) # Saca del banco al cliente cajero.ocupado = False # El cajero deja de estar ocupado cajero.cliente = None # No tiene ningun cliente cajero.tiempo_sale_cliente = tiempo_actual # Guarda el tiempo en donde sale el cliente # Veo si en la cola hay personas para atender if len(cola_espera) > 0: # Veo si hay servidores disponibles para atender a las personas cajeros_disponibles = servidores.hay_cajero_disponible() if len(cajeros_disponibles) > 0: # existen 1 o mas cajeros disponibles for cajero in cajeros_disponibles: # Recorro cada cajero y le pongo clientes if len(cola_espera) == 0: # Si no hay mas personas en la cola termino break siguiente = cola_espera.popleft() # Saco al cliente de la cola siguiente.tiempo_salida_cola = tiempo_actual # Pongo el tiempo que salio de la cola siguiente.tiempo_atencion = generar_tiempo_servicio() # Genero el tiempo que estara con el cajero # Actualizo informacion del cajero cajero.ocupado = True # Pongo al cajero ocupado cajero.cliente = siguiente # Le coloco al cliente que va a ser atendido cajero.tiempo_llega_cliente = tiempo_actual # El tiempo de llegada cajero.tiempo_libre += (tiempo_actual - cajero.tiempo_sale_cliente) # Sumo el tiempo que estuvo libre el cajero tiempo_actual += 0.1 return servidores, clientes_listos, clientes_se_rindieron cant_clientes = 100 minutos = 420 servidores, clientes, cant_declinados = simulacion(minutos, cant_clientes) # ZONA DE RESULTADOS # a) El tiempo esperado que pasa un cliente en el sistema promedio_cliente_sistema = 0 for cliente in clientes: promedio_cliente_sistema += cliente.tiempo_en_el_sistema promedio_cliente_sistema /= len(clientes) # Desviacion estandar s = 0 for cliente in clientes: s += (cliente.tiempo_en_el_sistema - promedio_cliente_sistema)**2 s = sqrt(s / (len(clientes) - 1)) # Intervalo de confianza t_valor = stats.t.ppf(1-0.05, len(clientes) - 1) delta = t_valor*(s / sqrt(len(clientes) - 1)) intervalo_confianza = "[" + str(round(promedio_cliente_sistema - delta, 2)) + ", " + str(round(promedio_cliente_sistema + delta, 2)) + "]" # Impresion de resultados print("a) Tiempo de espera de un cliente en el sistema") print("El tiempo esperado en el sistema de un cliente: " + str(round(promedio_cliente_sistema, 2))) print("El intervalo de confianza al 95 de significancia " + intervalo_confianza) print("---------------------------------------------------------------------------------------") # b) Porcentaje de clientes que declinan porcentaje = cant_declinados*100/cant_clientes # Impresion de resultados print("b) Porcentaje de clientes que declinaron") print("El porcentaje de clientes que declinaron fue: " + str(porcentaje) + "%") print("----------------------------------------------------------------------------------------") # c) Porcentaje de tiempo libre para cada cajero porcentaje_cajero_1 = servidores.lista_cajeros[0].tiempo_libre*100/minutos porcentaje_cajero_2 = servidores.lista_cajeros[1].tiempo_libre*100/minutos porcentaje_cajero_3 = servidores.lista_cajeros[2].tiempo_libre*100/minutos porcentaje_cajero_4 = servidores.lista_cajeros[3].tiempo_libre*100/minutos # Calculo de intervalo de confianza promedio_tiempo_libre = 0 for cajero in servidores.lista_cajeros: promedio_tiempo_libre += cajero.tiempo_libre promedio_tiempo_libre /= 4 # Calculo de la desviacion estandar s = 0 for cajero in servidores.lista_cajeros: s += (cajero.tiempo_libre - promedio_tiempo_libre)**2 s = sqrt(s / (3)) t_valor = stats.t.ppf(1-0.05, 3) delta = t_valor*(s / sqrt(4)) intervalo_confianza = "[" + str(round(promedio_tiempo_libre - delta, 2)) + ", " + str(round(promedio_cliente_sistema + delta, 2)) + "]" # Impresion de resultados print("c) Porcentaje de tiempo libre para cada cajero") print("Para el cajero 1: " + str(round(porcentaje_cajero_1, 2)) + "%") print("Para el cajero 2: " + str(round(porcentaje_cajero_2, 2)) + "%") print("Para el cajero 3: " + str(round(porcentaje_cajero_3, 2)) + "%") print("Para el cajero 4: " + str(round(porcentaje_cajero_4, 2)) + "%") print("Tiempo libre promedio de un cajero: " + str(round(promedio_tiempo_libre, 2))) print("Intervalo de confianza: " + intervalo_confianza) iteraciones = 1000 vueltas = 0 promedio_declina = 0 cant_declinados_por_iteracion = [] promedio_tiempo_libre_a = 0 promedio_tiempo_libre_b = 0 promedio_tiempo_libre_c = 0 promedio_tiempo_libre_d = 0 tiempo_libre_cajero_a = [] tiempo_libre_cajero_b = [] tiempo_libre_cajero_c = [] tiempo_libre_cajero_d = [] while vueltas < iteraciones: servidores, clientes, cant_declinados = simulacion(minutos, cant_clientes) promedio_declina += cant_declinados vueltas += 1 cant_declinados_por_iteracion.append(cant_declinados) tiempo_libre_cajero_a.append(servidores.lista_cajeros[0].tiempo_libre) tiempo_libre_cajero_b.append(servidores.lista_cajeros[1].tiempo_libre) tiempo_libre_cajero_c.append(servidores.lista_cajeros[2].tiempo_libre) tiempo_libre_cajero_d.append(servidores.lista_cajeros[3].tiempo_libre) promedio_tiempo_libre_a += servidores.lista_cajeros[0].tiempo_libre promedio_tiempo_libre_b += servidores.lista_cajeros[1].tiempo_libre promedio_tiempo_libre_c += servidores.lista_cajeros[2].tiempo_libre promedio_tiempo_libre_d += servidores.lista_cajeros[3].tiempo_libre promedio_declina /= iteraciones # Desviacion estandar s = 0 for cantidad in cant_declinados_por_iteracion: s += (cantidad - promedio_declina)**2 s = sqrt(s / (iteraciones - 1)) t_valor = stats.t.ppf(1-0.05, iteraciones - 1) delta = t_valor*(s / sqrt(iteraciones)) intervalo_confianza = "[" + str(promedio_declina - delta) + ", " + str(promedio_declina + delta) + "]" print("Promedio de clientes que declinaron: " + str(promedio_declina)) print("Intervalo de confianza: " + intervalo_confianza) print("----------------------------------------------------------------") def get_intervalo(promedio, delta): return "[" + str(promedio - delta) + ", " + str(promedio + delta) + "]" def print_resultado(promedio, intervalo, msg): print("Promedio de " + msg + ": " + str(promedio_declina)) print("Intervalo de confianza: " + intervalo_confianza) print("----------------------------------------------------------------") promedio_tiempo_libre_a /= iteraciones s1 = sum((x - promedio_tiempo_libre_a) for x in tiempo_libre_cajero_a) delta = t_valor*(s1 / sqrt(iteraciones)) print_resultado(promedio_tiempo_libre_a, get_intervalo(promedio_tiempo_libre_a, delta), "tiempo libre a") promedio_tiempo_libre_b /= iteraciones s2 = sum((x - promedio_tiempo_libre_b) for x in tiempo_libre_cajero_b) delta = t_valor*(s2 / sqrt(iteraciones)) print_resultado(promedio_tiempo_libre_b, get_intervalo(promedio_tiempo_libre_b, delta), "tiempo libre a") promedio_tiempo_libre_c /= iteraciones s3 = sum((x - promedio_tiempo_libre_c) for x in tiempo_libre_cajero_c) delta = t_valor*(s3 / sqrt(iteraciones)) print_resultado(promedio_tiempo_libre_c, get_intervalo(promedio_tiempo_libre_c, delta), "tiempo libre a") promedio_tiempo_libre_d /= iteraciones s4 = sum((x - promedio_tiempo_libre_d) for x in tiempo_libre_cajero_d) delta = t_valor*(s4 / sqrt(iteraciones)) print_resultado(promedio_tiempo_libre_d, get_intervalo(promedio_tiempo_libre_d, delta), "tiempo libre a")
fb30edb7663816ce608dac5f75ac06bbd31ceb8b
MondaleFelix/CS2
/stochastic.py
396
3.96875
4
# import word_frequency import random fishy = {"one": 1, "two" : 1, "red": 1, "blue" : 1, "fish": 4} def get_random_word(dictionary): words = sum(dictionary.values()) random_number = random.randint(1, words) for i in dictionary: if dictionary[i] < random_number: random_number -= dictionary[i] else: return i print(get_random_word(fishy))
dc560ddb415a5626b077db8028cae5a758e0d902
UCMHSProgramming16-17/file-io-zbreit18
/issTracker.py
637
3.5
4
import requests import time def getIssStatus(): """Returns a dictionary that contains the current status of the ISS""" issURL = 'http://api.open-notify.org/iss-now.json' r = requests.get(issURL) return r.json() def getIssPos(issRequest): """Returns a dictionary containing the current lat and long of the ISS given a JSON dictionary""" return issRequest['iss_position'] def getIssTime(issRequest): """Returns the UNIX timestamp of the last ISS measurement""" rawTime = issRequest['timestamp'] formattedTime = time.strftime('%A, %d %b %Y %H:%M:%S', time.localtime(rawTime)) return formattedTime
7f19270dccd0ba6236bac4725aac77389e9f898c
Catalincoconeanu/Python-Learning
/Python - Basiscs/Try and Except.py
215
4.125
4
# Try and Except # Sample: Try the first statement - if first one is not working then it goes to except statement, this will print Otherwise try: if name > 3: print("Hi") except: print("Otherwise")
4b9d86f69389f334cb97cef325bf19d2ef6f3b71
dooking/CodingTest
/SWExpertAcademy/이진수2-5186.py
476
3.578125
4
t = int(input()) for test_case in range(1,t+1): n = float(input()) answer = '' res = 0 p = -1 cnt = 1 while n != 0: if(cnt == 13): answer = "overflow" break if(n>=2**p): res = int(n/(2**p)) n = n % (2**p) answer += str(res) else: answer += '0' cnt += 1 p -= 1 #print(cnt, n,res, answer) print("#{} {}".format(test_case,answer))
18c9f77cf5a66991a333cce705011d7727b7dd82
RotemLibrati/Salary
/mysite/salary/sqlInjectionCheck/sqlInjection.py
3,847
3.953125
4
import sys def main(un, p): username, password = sql_injection(un, p) return username, password def sql_injection(username, password): print("before : " + username) tempWord = username tempWord = remove_problem_word(tempWord) tempWord = " ".join(tempWord.split()) if tempWord.__contains__("'"): tempWord = delete_char(tempWord, "'") tempWord = " ".join(tempWord.split()) # remove the extra spaces if tempWord.__contains__("--"): w = "" x = 0 while x < len(tempWord)-1: if tempWord[x] == "-" and tempWord[x+1] == "-": w = w + add_char_for_prevent(tempWord, "--") + " " x = x + 1 tempWord = w if tempWord.__contains__("union"): tempWord = clean_problem_words(tempWord, "union") tempWord = " ".join(tempWord.split()) if tempWord.__contains__("distinct"): tempWord = clean_problem_words(tempWord, "distinct") tempWord = " ".join(tempWord.split()) print("after : " + tempWord) print("before : " + password) tempPass = password tempPass = remove_problem_word(tempPass) tempPass = " ".join(tempPass.split()) if tempPass.__contains__("'"): tempPass = delete_char(tempPass, "'") tempPass = " ".join(tempPass.split()) if tempPass.__contains__("--"): w = "" x = 0 while x < len(tempPass)-1: if tempPass[x] == "-" and tempPass[x + 1] == "-": w = w + add_char_for_prevent(tempPass, "--") + " " x = x + 1 tempPass = w if tempPass.__contains__("union"): tempPass = clean_problem_words(tempPass, "union") tempPass = " ".join(tempPass.split()) if tempPass.__contains__("distinct"): tempPass = clean_problem_words(tempPass, "distinct") tempPass = " ".join(tempPass.split()) print("after : " + tempPass) username = tempWord password = tempPass return username, password def delete_char(word, char): # function that get word and char for deleting # and return word without the char. word = word.replace(char, '') return word def clean_problem_words(word, clean): # function that get word and problem word for deleting # and return word without the problem word. word = word.replace(clean, '').lstrip() return word def substring_after(word, char): return word.partition(char)[2] def remove_problem_word(prob_word): # function for check if has problem word from list "ProblemWord" # that can to show on try to sql injection try: temp = open("D:\\Salary\\mysite\\salary\\sqlInjectionCheck\\ProblemWords.txt") except OSError: print("Could not open/read file") sys.exit() words = temp.read().splitlines() # read from file with char \n prob_word = prob_word # check word with uppercase for i in words: while i in prob_word: prob_word = clean_problem_words(prob_word, i) up_temp = i.upper() # check case of capital letter in file ProblemWords while up_temp in prob_word: prob_word = clean_problem_words(prob_word, up_temp) return prob_word def add_char_for_prevent(word, char): # function that get problem char in the word # and put "/" between for prevent try to hack i = 0 beforeChar = "" while word[i] != char[0]: beforeChar = beforeChar + word[i] i = i + 1 for j in range(len(char)): beforeChar = beforeChar + char[j] + "/" j = j + 1 i = i + 1 while i < len(word): beforeChar = beforeChar + word[i] i = i + 1 return beforeChar if __name__ == "__main__": # for example we call to function with input u = input("Enter Username: ") p = input("Enter Password: ") main(u, p)
37d1e58de3e3235657120f0bb0316eeb563e99a8
LegendsIta/Python-Tips-Tricks
/number/is_odd.py
142
4.25
4
def is_odd(num): return True if num % 2 != 0 else False n = 1 print(is_odd(n)) n = 2 print(is_odd(n)) # - OUTPUT - # #» True #» False
6dca99ea0d2515d3626bf820b2256754f0dd90ab
dcdennis/Blackjack-AI
/getLine.py
273
3.578125
4
#! /usr/bin/python3.6 import sys with open(sys.argv[1]) as f: count = 0 index = int(sys.argv[2]) for line in f: if count+1 == index: print(count, line) if count == index: print(index, line) count += 1 f.close()
2fb8f1136e6eb6613400211ead0ff42f9dd2a08f
limapedro2002/PEOO_Python
/Lista_01/Pedro Lucas/quest2.py
501
3.578125
4
num = [] imp = [] a = 0 b = 0 mult = 0 i = 0 while i < 10: num.append (int (input ("Digite um valor: "))) i += 1 for cont in num: if cont % 2 != 0: imp.append (cont) for a in range (10): for b in range (1, num[a] + 1): if num[a] % b == 0: mult += 1 if mult == 2: b += num[a] a += 1 mult = 0 Impares = sum (set (imp)) print ("A soma dos números primos são de", b) print ("A soma dos números impares são de", Impares)
9e934f1f6223a28819a7d870dbdbcdf24b2b19c5
aimiliya/WorkCollection-
/filetest1.py
1,458
3.71875
4
# 进行文件夹的增量备份 import os import filecmp import shutil import sys def auto_backup(scr_dir, dst_dir): if (not os.path.isdir(scr_dir)) or (not os.path.isdir(dst_dir)) or ( os.path.abspath(scr_dir) != scr_dir) or ( os.path.abspath(dst_dir) != dst_dir): for item in os.listdir(scr_dir): scr_item = os.path.join(scr_dir, item) dst_item = scr_item.replace(scr_dir, dst_dir) if os.path.isdir(scr_item): # 创建新增的文件夹,保证目标文件夹的结构于原来文件夹一致 if not os.path.exists(dst_item): os.makedirs(dst_item) print('make directory' + dst_item) auto_backup(scr_item, dst_item) elif os.path.isfile(scr_item): # 只复制新增的或修改过的文件 if ((not os.path.exists(dst_item)) or ( not filecmp.cmp(scr_item, dst_item, shallow=False))): shutil.copyfile(scr_item, dst_item) print('file:' + scr_item + '==>' + dst_item) def usage(): print("scr_dir和dst_dir 必须是存于当前的相对目录下") print("例如:{0} c:\\olddir c:\\newdir".format(sys.argv[0])) sys.exit(0) if __name__ == '__main__': if len(sys.argv) != 3: usage() scrDir, dstDir = sys.argv[1], sys.argv[2] auto_backup(scrDir, dstDir)
9d88a08dac8cf43a9e11fc248d24aa49bcc4919e
gkcksrbs/Baekjoon_CodingTest
/src/정렬/Baekjoon_1181_단어 정렬.py
769
3.515625
4
# 입력 개수 N을 입력하고 문자열의 길이는 50까지 이므로 50까지 리스트를 만들어주고 리스트 안에 또 리스트를 생성한다. # 리스트에 lst[입력 받은 문자열의 길이]에 문자열을 추가하여 저장한다. # for 루프로 각 리스트 안에 중복되는 것을 set()으로 제거하고 sorted()로 정렬한다. # 각 문자열들을 문자열의 길이 순서대로 출력한다. N = int(input()) lst = [[] for i in range(51)] for i in range(N): Str = input() Len = len(Str) lst[Len].append(Str) for i in range(51): if(lst[i] != None): lst[i] = list(set(lst[i])) lst[i] = sorted(lst[i]) for i in range(51): if lst[i] != None: for j in lst[i]: print(j)
61d5d58302bdca2668bf5eaf72a640f1c0c70af1
BlackSquirrelz/FS21_CALR_TUTORIAL
/main.py
2,831
3.859375
4
import xml.etree.ElementTree as ET # For XML Parsing import csv # For reading CSV import json import requests # For getting content from the web from bs4 import BeautifulSoup # For parsing content from the web import logging # Main Function def main(): """The main function contains examples on how to read each type of file Example 1: Regular Text File Example 2: CSV File Example 3: XML File Example 4: JSON File Example 5: PDF FIle Example 6: Getting Content via API Example 7: Web Content with other means""" print("Main Function Executing") print("-x-"*25) # Example 1 print("\nReading a regular Text File.") example_1 = open_file('Data/example_1.txt') print(f"Output: {example_1}\n") print("---" * 25) # Example 2 print("\nReading a CSV File.") example_2 = csv_open('Data/example_2.csv') print(f"Output: {example_2}\n") print("---" * 25) # Example 3 print("\nParsing an XML Text File.") example_3 = xml_parsing('Data/example_3.xml') print(f"Output: {example_3}\n") print("---" * 25) # Getting Content from the Web print("\nParsing Text from the Web.") example_4 = get_web_content('https://www.horizonte-magazin.ch/2020/12/03/parfuem-der-baeume-ist-kampfstoff/') print(f"Output: {example_4}\n") # Generic Function to read a file def open_file(file_path): with open(file_path, 'r') as f: text = [line.strip() for line in f] return text # Reading CSV Files def csv_open(file_path): with open(file_path, newline='\n') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') text = [token for token in reader] return text # Parsing XML Files def xml_parsing(file_path): root_node = ET.parse(file_path).getroot() text = [tag.text for tag in root_node.findall('token')] return text def save_json(outfile, content): """ Generic function to save dictionary data to a JSON file""" logging.info(f"Written JSON as {outfile}") with open(outfile, 'w') as f: json.dump(content, f, indent=4) def get_json(file_name): """ Generic function to retrieve data from JSON file""" with open(file_name) as f: data = json.load(f) return data # --------------------------------------------------------------- # Getting Content from the Internet # Documentation: https://docs.python.org/3/library/urllib.request.html#module-urllib.request def get_web_content(url): response = requests.get(url) if response.status_code != 200: response = None return response.text def web_content_parsing(html_doc): soup = BeautifulSoup(html_doc, 'html.parser') print(soup) # The caller for the main function, this is the entry point for our program if __name__ == '__main__': main()
0737a9571128d07e856a24b80f1108594b2e43ba
eyosi-cmd/CS110-Introduction-to-Computing-Programming-in-Python
/HW7 Using & Creating Data Structures/password_checker.py
752
3.640625
4
import stdio import sys # Returns True if pwd is a valid password and False otherwise. def is_valid(pwd): if len(pwd) < 8: return False if pwd.isalnum(): return False if pwd.isupper(): return False if pwd.islower(): return False for k in pwd: if k.isdigit(): return True if k.isupper() or k.islower(): return True if not k.isalnum(): return True else: return False # Test client [DO NOT EDIT]. Reads a password string as command-line argument # and writes True if it's valid and False otherwise. def _main(): pwd = sys.argv[1] stdio.writeln(is_valid(pwd)) if __name__ == '__main__': _main()
36fa60c9a932bebd17e406835be46279e1684d54
eusouocristian/learning_python
/Challenges/remove_vowels.py
325
4.21875
4
def disemvowel(word): word = list(word) vowels = ["a","e","i","o","u","A","E","I","O","U"] for vowel in word: if vowel in vowels: word.remove(vowel) else: pass return word word = input("Ditite uma palavra:\n>") new_word = disemvowel(word) print(new_word)
bc6484400ed66399855a9886417d9acb41afd4e0
greatertomi/problem-solving
/hackerrank-challenges/easy/acm-team.py
616
3.796875
4
# Problem Link: https://www.hackerrank.com/challenges/acm-icpc-team/problem def totalTopics(p1, p2): count = 0 for i in range(len(p1)): if p1[i] == '1' or p2[i] == '1': count += 1 return count def acmTeam(teams): topicArr = [] for i in range(len(teams)): for k in range(i + 1, len(teams)): topicArr.append(totalTopics(teams[i], teams[k])) maxTopic = max(topicArr) maxTopicNum = topicArr.count(maxTopic) return [maxTopic, maxTopicNum] team1 = ['10101', '11110', '00010'] team2 = ['10101', '11100', '11010', '00101'] print(acmTeam(team1))
4b09a1efdac1cc61b7b3e9b3aa29192f98771708
dlenci/BME-160
/Lab 2/coordinateMathSoln.py
3,979
4.28125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #!/usr/bin/env python3 # Name: David Lenci (dlenci) # Group Members: none ''' Program docstring goes here ''' import math class Triad : """ Calculate angles and distances among a triad of points. Author: David Bernick Date: March 21, 2013 Points can be supplied in any dimensional space as long as they are consistent. Points are supplied as tupels in n-dimensions, and there should be three of those to make the triad. Each point is positionally named as p,q,r and the corresponding angles are then angleP, angleQ and angleR. Distances are given by dPQ(), dPR() and dQR() Required Modules: math initialized: 3 positional tuples representing Points in n-space p1 = Triad( p=(1,0,0), q=(0,0,0), r=(0,1,0) ) attributes: p,q,r the 3 tuples representing points in N-space methods: angleP(), angleR(), angleQ() angles measured in radians dPQ(), dPR(), dQR() distances in the same units of p,q,r """ def __init__(self,p,q,r) : """ Construct a Triad. Example construction: p1 = Triad( p=(1.,0.,0.), q=(0.,0.,0.), r=(0.,0.,0.) ). """ self.p = p self.q = q self.r = r # private helper methods def d2 (self,a,b) : # calculate squared distance of point a to b return float(sum((ia-ib)*(ia-ib) for ia,ib in zip (a,b))) def dot (self,a,b) : # dotProd of standard vectors a,b return float(sum(ia*ib for ia,ib in zip(a,b))) def ndot (self,a,b,c) : # dotProd of vec. a,c standardized to b return float(sum((ia-ib)*(ic-ib) for ia,ib,ic in zip (a,b,c))) # calculate lengths(distances) of segments PQ, PR and QR def dPQ (self): """ Provides the distance between point p and point q """ return math.sqrt(self.d2(self.p,self.q)) def dPR (self): """ Provides the distance between point p and point r """ return math.sqrt(self.d2(self.p,self.r)) def dQR (self): """ Provides the distance between point q and point r """ return math.sqrt(self.d2(self.q,self.r)) def angleP (self) : """ Provides the angle made at point p by segments pq and pr (radians). """ return math.acos(self.ndot(self.q,self.p,self.r) / math.sqrt(self.d2(self.q,self.p)*self.d2(self.r,self.p))) def angleQ (self) : """ Provides the angle made at point q by segments qp and qr (radians). """ return math.acos(self.ndot(self.p,self.q,self.r) / math.sqrt(self.d2(self.p,self.q)*self.d2(self.r,self.q))) def angleR (self) : """ Provides the angle made at point r by segments rp and rq (radians). """ return math.acos(self.ndot(self.p,self.r,self.q) / math.sqrt(self.d2(self.p,self.r)*self.d2(self.q,self.r))) def main(): ''' Parses input for coordinates of the C, N, Ca atoms. Takes the coordinates of the C, N, and Ca (in that order) particles in peptide bond and outputs the distance from C to N and Ca to N and the C-N-Ca bond angle. ''' coords = input('Enter the C, N, and Ca coordinates:') commaCoords = coords.replace('(',',').replace(')',',') #Replaces '()' with ','. coordsParts = commaCoords.split(',') #Splits string into list wherever there is a comma. tupleC = (float(coordsParts[1]),float(coordsParts[2]),float(coordsParts[3])) #Creates coordinate tuples for each atom. tupleN = (float(coordsParts[5]),float(coordsParts[6]),float(coordsParts[7])) tupleCa = (float(coordsParts[9]),float(coordsParts[10]),float(coordsParts[11])) P1 = Triad(tupleC, tupleN, tupleCa) p1Rad=P1.angleQ() p1Deg=math.degrees(p1Rad) #Radian-degree converter print("N-C bond length = {0:0.2f}".format(P1.dPQ())) #Calls necessary functions. print("N-Ca bond length = {0:0.2f}".format(P1.dQR())) print("C-N-Ca bond angle = {0:0.1f}".format(p1Deg)) main()
7f12587fe86ecd5155b37beb1733822d2f15d7e1
GabrielDVpereira/python_basics
/URI - BASIC/1042.py
548
4.03125
4
def sort(numbers): for i in range(len(numbers)): min_index = i; for j in range(i+1, len(numbers)): if(numbers[min_index] > numbers[j]): min_index = j; numbers[i], numbers[min_index] = numbers[min_index],numbers[i] return numbers def convertToInt(num): return int(num); numbers = input().split() numbers = tuple(map(convertToInt, numbers)); numbersToSort = list(numbers) numbersSorted = sort(numbersToSort); for num in numbersSorted: print(num); print('\n'); for num in numbers: print(num);
5daebfa91380e5480965a7590ec306faff7b46b2
stinekamau/Mock_Registration_System
/textloader.py
2,546
3.59375
4
''' Module that provides a higher abstraction over the text file that make up the data ''' import csv import random class FileManager: def __init__(self): self.resource="resources\\faculty.txt" #Path to the Advisors data types self.courses_resource="resources\\final_courses.txt" #Path to the courses self.courses=[] self.faculty=[] def get_courses(self): ''' Returns a list of list containing the individual contents of the courses ''' with open(self.courses_resource,'r') as f: csv_reader=csv.reader(f) next(csv_reader) for line in csv_reader: self.courses.append(line) return self.courses def advise_courses(self): ''' Calls the get_courses first and subsequently samples the courses that will be offered to the student ''' courses=self.get_courses() rander=[random.randint(0,98) for i in range(5)] return [courses[i] for i in rander] def get_single_advisor(self): ''' Returns the name of a single Faculty advisor ''' courses=self.get_faculty() num=random.randint(0,98) return courses[num][0].replace('Â','').strip() #Stips away the unncessary characters def get_faculty(self): ''' Provides functionality for loadign the faculty text file and returning it as a list ''' resource_name="resources\\faculty.csv" with open(self.resource,'r') as f: cv_reader=csv.reader(f) next(cv_reader) for line in cv_reader: self.faculty.append(line) return self.faculty def course_report(self,student,tutor,courses): ''' Generates a report about the courses ''' c=list(courses.keys()) report=f""" COURSES NUMBER OF STUDENTS {c[0].rjust(30,' ')} {courses[c[0]]} {c[1].rjust(30,' ')} {courses[c[1]]} {c[2].rjust(30,' ')} {courses[c[2]]} {c[3].rjust(30,' ')} {courses[c[3]]} FACULTY ASSIGNED: {tutor} """ return report files=FileManager()
75200aecf87e0c6d7e32cfcaa7de14f468debc21
Juancruzc21/Python
/Python/Operadores aritmeticos.py
1,130
4.28125
4
print("Suma: ") primerNumero = 5 segundoNumero = 4 resultado = primerNumero + segundoNumero print("El resultado de la suma es: " + str(resultado)) print("Resta: ") primerNumero = 5 segundoNumero = 4 resultado = primerNumero - segundoNumero print("El resultado de la resta es: " + str(resultado)) print("Multiplicacion: ") primerNumero = 5 segundoNumero = 4 resultado = primerNumero * segundoNumero print("El resultado de la multiplicacion es: " + str(resultado)) print("Division: ") primerNumero = 4 segundoNumero = 2 resultado = primerNumero / segundoNumero print("El resultado de la division es: " + str(resultado)) print("Modulo: ") primerNumero = 4 segundoNumero = 2 resultado = primerNumero % segundoNumero print("El resultado del modulo es: " + str(resultado)) print("Exponente: ") primerNumero = 4 segundoNumero = 2 resultado = primerNumero ** segundoNumero print("El resultado de la potencia es: " + str(resultado)) #tambien se puede hacer la division entera con // y solo va a dar el resultado #sin los decimales
027966c3759280c5694f19f2a3c431d076579291
wilshirefarm/Data-Structures
/Python/toStr.py
221
3.578125
4
def toStr(n, base): convString = "0123456789ABCDEF" if n < base: return (convString[n]) else: return (toStr(n//base,base) + convString[n%base]) def main(): print(toStr(1011,2)) main()
bcfdee42f5b69d4a0999688fbfce04e4dc3c91c3
MatthewHird/Pong
/button.py
386
3.765625
4
class Button: def __init__(self, text, x, y, width, height): self.text = text self.x = x self.y = y self.width = width self.height = height def hover(self, mouse_x, mouse_y): if self.x <= mouse_x <= self.x + self.width and self.y <= mouse_y <= self.y + self.height: return True else: return False
431b1c36a19d1b67186df95679992d592e16b507
eldhom/Project-Euler
/017 Number letter counts/main.py
1,086
3.6875
4
#!/usr/bin/python3.5 n2w1 = { 0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'} n2w2 = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'] def num2word(num): num = str(num) string = "" if(len(num) == 1): string = n2w1[int(num[-1])] elif(len(num) > 1): n = int(num[-2:]) if(n < 20 and n > 0): string = n2w1[n] elif(n > 19): n = int(num[-2]) string = n2w2[n-2] n = int(num[-1]) if(n > 0): string += "-"+n2w1[n] if(len(num) > 2): n = int(num[-3]) if(n > 0): if(len(string) > 0): string = " and " + string string = n2w1[n] + " hundred" + string if(len(num) > 3): string = "one thousand" print(string) return string.lower() summ = 0 for x in range(1, 1001): summ += len(num2word(x).replace(" ", "").replace("-", "")) print(str(summ))
fc5ffe28f6058d44080ec0848c602c427d6310ee
isabella232/okta-python-flask-sqllite-example
/CreateDB.py
391
4
4
import sqlite3 connection = sqlite3.connect('message.db') cursor = connection.cursor() cursor.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT)''') cursor.execute("INSERT INTO messages (message) VALUES('Welcome')") connection.commit() cursor.execute('SELECT id, message FROM messages ORDER BY id') for row in cursor: print(row) connection.close()
22edc37dc4fb16ededd7348846818d37da87489c
stuartamitchell/rhyme-classifier
/rhyme_classifier/setup/raw_datasets.py
2,366
3.765625
4
''' Gives a function to generate datasets for training and testing the neural network. ''' import json from nltk.corpus.reader import wordlist import random def generate_dataset(n, dict_file, save_file): ''' Generates a dataset for the rhyme-classifier Generates a collection of n word pairs and a boolean value for whether they rhyme. The number n is partitioned into an approximate ratio of non-rhymes : rhymes = 3 : 2. The rhyming dictionary is filtered to remove sounds containing one word. Parameters ---------- n : int The number of elements in the dataset dict_file : str The path of the dictionary file to load save_file : str The path to save the data ''' with open(dict_file, 'r') as file: rhyme_dict = json.load(file) with open(save_file, 'w') as file: file.write('Word1,Word2,Rhyme\n') # filter out all sounds with only one word rhyme_items = [(s,l) for s,l in list(rhyme_dict.items()) if len(l) > 1] random.seed() for i in range(0, n): # get a random number between 0 and 9, if its 0 we make a # rhyming pair rhyme_rand = int(10*random.random()) if rhyme_rand in range(0, 4): sound = int(len(rhyme_items) * random.random()) word_list = rhyme_items[sound][1] rand1 = int(len(word_list) * random.random()) rand2 = int(len(word_list) * random.random()) word1 = word_list[rand1] word2 = word_list[rand2] line = ','.join([word1, word2, '1']) with open(save_file, 'a') as file: file.write(line + '\n') else: sound1 = int(len(rhyme_items) * random.random()) rem_sounds = [(s,l) for s,l in rhyme_items if s != rhyme_items[sound1][0]] sound2 = int(len(rem_sounds) * random.random()) list1 = rhyme_items[sound1][1] list2 = rhyme_items[sound2][1] rand1 = int(len(list1)*random.random()) rand2 = int(len(list2)*random.random()) word1 = list1[rand1] word2 = list2[rand2] line = ','.join([word1, word2, '0']) with open(save_file, 'a') as file: file.write(line + '\n')
fc381af5833208547ba2a7244bae39472202b69d
AlexeyBazanov/algorithms
/sprint_1/factorization_2.py
424
3.6875
4
import sys def factorization(n): result = [] divisor = 2 while divisor * divisor <= n: if n % divisor == 0: result.append(divisor) n //= divisor else: divisor += 1 if n > 1: result.append(n) return result def main(): n = int(sys.stdin.readline().strip()) divisors = factorization(n) print(' '.join(map(str, divisors))) main()
4be92b5b94a43d78a02d222dad8c1100568774c6
HvyD/AppleSiri-Privacy-Data_Engineer_prep
/LEET/Binary_Tree_Longest_Consecutive_Sequence_II.py
1,642
4.09375
4
""" Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order. Example 1: Input: 1 / \ 2 3 Output: 2 Explanation: The longest consecutive path is [1, 2] or [2, 1]. Example 2: Input: 2 / \ 1 3 Output: 3 Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1]. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def longestConsecutive(self, root: TreeNode) -> int: def dfs(node): if not node: return 0, 0 # [des, inc] toward root, they are the lengths in the two directions along parent-child relation res = [1, 1] l = dfs(node.left) r = dfs(node.right) if node.left and abs(node.val - node.left.val) == 1: i = (node.val - node.left.val + 1) // 2 res[i] = max(res[i], l[i] + 1) if node.right and abs(node.val - node.right.val) == 1: i = (node.val - node.right.val + 1) // 2 res[i] = max(res[i], r[i] + 1) self.res = max(self.res, sum(res)-1) return res self.res = 0 dfs(root) return self.res
7cf8fc9d4d4b7a335cd0524148ee23f61fe6c7c8
mathieu-lechine/Python-code-library
/collection_tutorial.py
5,269
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 1 10:39:13 2018 @author: mathieu.lechine """ ############IMPORT TEXT WITH NLTK###################### from nltk.corpus import gutenberg from nltk.corpus import stopwords import string from nltk.tokenize import RegexpTokenizer #choose en ebook from Gutenberg project gutenberg.fileids() txt_raw = gutenberg.raw('melville-moby_dick.txt') tokenizer = RegexpTokenizer(r'\w+') word_list = tokenizer.tokenize(txt_raw) print("Nombre de mots: {}".format(len(word_list))) #remove stopwords word_list = [w.lower() for w in word_list if not w.lower() in stopwords.words('english')] print("Nombre de mots after stopwords removel: {}".format(len(word_list))) #%%############# COLLECTIONS COUNTER############################ from collections import Counter # Tally occurrences of words in a list word_list_ex = ['red', 'blue', 'red', 'green', 'blue', 'blue'] cnt = Counter() for word in word_list_ex: cnt[word] += 1 cnt #find the most common words cnt = Counter(word_list) n=10 cnt.most_common(n) cnt.most_common()[:-n-1:-1] #unique words dictionnaire = sorted(list(cnt)) print('Nombre de mots différents: {}'.format(len(dictionnaire))) #%%############# COLLECTIONS deque############################ #Deques are a generalization of stacks and queues (the name is pronounced “deck” #and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends #and pops from either side of the deque with approximately the same O(1) performance in either direction. from collections import deque import itertools d = deque('athie') d.append('u') # add a new entry to the right side d.appendleft('M') print(d) print(d.pop()) print(d.popleft()) d.extend('-bal') d.rotate(1) print(d) #exemple of use filename = "/Users/mathieu.lechine/Dropbox (Optimind Winter)/Python-learning/Python_DataCamp/Data/house-votes-84.names.txt" def tail(filename, n=10): 'Return the last n lines of a file' return deque(open(filename), maxlen = n) tail(filename) def moving_average(iterable, n=3): # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 # http://en.wikipedia.org/wiki/Moving_average it = iter(iterable) d = deque(itertools.islice(it, n-1)) d.appendleft(0) s = sum(d) for elem in it: s += elem - d.popleft() d.append(elem) yield s / float(n) iterable = [40, 30, 50, 46, 39, 44] for i in moving_average(iterable, n=3): print(i) #%%############# COLLECTIONS defaultdict############################ #Returns a new dictionary-like object. defaultdict is a subclass of the built- #in dict class. It overrides one method and adds one writable instance variable. #The remaining functionality is the same as for the dict class and is not documented here. #The first argument provides the initial value for the default_factory attribute; #it defaults to None. All remaining arguments are treated the same as if they were passed #to the dict constructor, including keyword arguments. from collections import defaultdict #Using list as the default_factory, it is easy to group a sequence of key-value #pairs into a dictionary of lists s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = defaultdict(list) for k, v in s: d[k].append(v) print(sorted(d.items())) #Setting the default_factory to int makes the defaultdict useful for counting #(like a bag or multiset in other languages) s = "mississippi" d = defaultdict(int) for c in s: d[c] += 1 sorted(d.items()) #%%############# COLLECTIONS OrderedDict############################ #Ordered dictionaries are just like regular dictionaries but they remember the #order that items were inserted. When iterating over an ordered dictionary, the #items are returned in the order their keys were first added. from collections import OrderedDict d = OrderedDict.fromkeys('Mathieu') d.move_to_end('M') ''.join(d.keys()) d.move_to_end('M', last=False) ''.join(d.keys()) #regular unsorted dictionary d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} # dictionary sorted by key OrderedDict(sorted(d.items(), key=lambda t: t[0])) # dictionary sorted by value OrderedDict(sorted(d.items(), key=lambda t: t[1])) # dictionary sorted by length of the key string OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) #%%############# COLLECTIONS namedtuple############################ #Named tuples assign meaning to each position in a tuple and allow for more readable, #self-documenting code. They can be used wherever regular tuples are used, and they add #the ability to access fields by name instead of position index. from collections import namedtuple #basic examples Point = namedtuple('Point', ['x', 'y']) p = Point(10, y=25) p.x + p.y p[0] + p[1] x, y = p #Named tuples are especially useful for assigning field names to result tuples returned #by the csv or sqlite3 modules: filename = "/Users/mathieu.lechine/Dropbox (Optimind Winter)/Python-learning/Input/employees.csv" EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') import csv for emp in map(EmployeeRecord._make, csv.reader(open(filename, "rt"))): print(emp.name, emp.title)
356582d56b755b84eb9e3a6773e44e765ba6fdf5
sam-sepi/Py-coding
/imagination.py
728
3.671875
4
import numpy as np from PIL import Image import binascii # RGB images are usually stored as 3 dimensional arrays of 8-bit unsigned integers. # Each pixel contains 3 bytes (representing the red, green and blue values of the pixel colour) width = 4 height = 4 array = np.zeros([height, width, 3], dtype = np.uint8) # 8-bit unsigned integers # black white black white array[0] = [0, 0, 0] array[1] = [255, 255, 255] array[2] = [0, 0, 0] array[3] = [255, 255, 255] # save img img = Image.fromarray(array) img.save('testrgb.png') # img to np array conv = Image.open('testrgb.png') pix = np.array(conv) # open img and convert in hex with open('testrgb.png', 'rb') as f: content = f.read() print(binascii.hexlify(content))
627bfc714e9a2ce473250c71392a538154e08973
TaurusCanis/ace_it
/ace_it_test_prep/static/scripts/test_question_scripts/math_questions/math_T1_Q23.py
2,066
3.875
4
import random from math import sqrt root = random.randint(2,5) radicand_exp = random.randint(root + 1, root * 5) question = f"<p>If &nbsp;\\(a&gt;0\\)&nbsp;, which of the following expressions is equivalent to \\(\\sqrt[{root}]{{a^{radicand_exp}}}\\)&nbsp; ?</p>\n" coefficient = radicand_exp // root remainder = radicand_exp % root answer = f"\\{{a^{coefficient}}}(\\sqrt[{root}]{{a^{remainder}}}\\)" options = [ { "option": answer, "correct": True }, { "option": f"\\{{a^{remainder}}}(\\sqrt[{root}]{{a^{coefficient}}}\\)", "correct": False }, { "option":"\\(a^" + str(eval(f"{radicand_exp} - {root}")) + "\\)", "correct": False }, { "option":"\\(a^" + str(round(sqrt(radicand_exp))) + "\\)", "correct": False }, { "option":"\\(a^" + str(eval(f"{radicand_exp} * {root}")) + "\\)", "correct": False } ] random.shuffle(options) print(question) letter_index = 65 for option in options: print(chr(letter_index) + ": " + str(option["option"])) letter_index += 1 user_response = input("Choose an answer option: ") if options[ord(user_response.upper()[0]) - 65]["correct"]: print("CORRECT!") else: print("INCORRECT!") print(answer) # "distractor_rationale_response_level":[ # "You found an expression equivalent to&nbsp;\\(\\left(a^9\\right)^4\\) instead of \\(\\sqrt[4]{a^9}\\).", # "You subtracted 4 from the exponent instead of taking the fourth root, which should involve dividing an exponent by 4.", # "You used the square root of the exponent, but finding the root in question with involve dividing the exponent by 4.", # "You factored out the square root instead of the fourth root of \\(a^8\\).&nbsp;", # "The expression represents the fourth fourth root of&nbsp;\\(a^9\\)<em>.&nbsp;</em>The term&nbsp;\\(a^8\\) can be written as \\(a^8\\left(a\\right)\\),and the fourth root of&nbsp;\\(a^8\\) is \\(a^2\\). So, the square of&nbsp;<em>a</em>&nbsp;is a factor of the original expression, such that \\(\\sqrt[4]{a^9}=\\left(a^2\\right)\\sqrt[4]{a}\\)." # ]
83a5868e6ae01c6ab9833187f05daf6d769311e6
satyampandeygit/ds-algo-solutions
/Algorithms/Search/Ice Cream Parlor/solution.py
719
3.546875
4
def main(): # Loop through for each test. for _ in range(int(input())): dollars = int(input()) numFlavors = int(input()) flavors = [int(i) for i in input().split()] # Determine the correct indexes. index1, index2 = -1, -1 for i in range(numFlavors): for j in range(numFlavors): if (i != j) and (flavors[i] + flavors[j] == dollars): index1 = i + 1 index2 = j + 1 break if index1 != -1 and index2 != -1: break # Print the answer. print(str(index1) + " " + str(index2)) if __name__ == "__main__": main()
d65a726eeac7fa611e95d41879c195e4d7504734
srikanthpragada/python_14_dec_2020
/demo/funs/extract_upper.py
289
3.890625
4
def upper(st): chars = [] for ch in st: if ch.isupper(): chars.append(ch) return ''.join(chars) def getupper(st): nst = "" for ch in st: if ch.isupper(): nst += ch return nst print(upper('AbcXyz'), getupper('AbcXyz'))
ed2e754f582a72365a3f540378971cebd444fa56
hedelman4/ShowMeDataStruct
/Problem4.py
1,366
3.78125
4
import sys class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] groupList.append(self) def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def has_name(self): return self.name != None def is_user_in_group(user, group): boolean = False if group in groupList: for userCheck in group.get_users(): userList.append(userCheck) for groupCheck in group.get_groups(): is_user_in_group(user, groupCheck) for userIndex in userList: if userIndex == user: boolean = True return boolean global groupList groupList = [] parent = Group("parent") child = Group("child") sub_child = Group("subchild") sub_child_user = "sub_child_user" sub_child.add_user(sub_child_user) sub_sub_child_user = "sub_sub_child_user" child.add_group(sub_child) parent.add_group(child) global userList userList = [] print(is_user_in_group(sub_child_user,child)) print(is_user_in_group(sub_child_user,sub_child)) print(is_user_in_group('',sub_child)) print(is_user_in_group('',''))
f3fc98cb3d16d0c709104121987dae1cbb4d72f0
vicjulianortiz/Database-project
/TableDemo.py
6,635
3.578125
4
from tkinter import * import tkinter import tkinter.messagebox import sqlite3 import re class MyGUI: def __init__(self): global db db = sqlite3.connect('C:/Users/Victor/Desktop/CITIES.db') global cursor cursor = db.cursor() self.window = tkinter.Tk() self.l1 = Label(self.window, text = 'SELECT ENTRY FROM DATABASE') self.l1.grid(row = 0, column = 0) self.l3 = Label(self.window, text = 'WHERE') self.l3.grid(row = 1, column = 0) self.l4 = Label(self.window, text = 'EQUALS') self.l4.grid(row = 1, column = 2) self.l5 = Label(self.window, text = 'INSERT AND UPDATE NEW ENTRIES BELOW') self.l5.grid(row = 2, column = 0) self.l6 = Label(self.window, text = 'CITY') self.l6.grid(row = 3, column = 0) self.l7 = Label(self.window, text = 'STATE') self.l7.grid(row = 3, column = 2) self.l8 = Label(self.window, text = 'COUNTY') self.l8.grid(row = 4, column = 0) self.l9 = Label(self.window, text = 'POPULATION') self.l9.grid(row = 4, column = 2) self.l10 = Label(self.window, text = 'DENSITY') self.l10.grid(row = 5, column = 0) #define entries self.where_text = StringVar() self.e2 = Entry(self.window, textvariable = self.where_text) self.e2.grid(row = 1, column = 1) self.equals_text = StringVar() self.e3 = Entry(self.window, textvariable = self.equals_text) self.e3.grid(row = 1, column = 3) self.city_text = StringVar() self.e4 = Entry(self.window, textvariable = self.city_text) self.e4.grid(row = 3, column = 1) self.state_text = StringVar() self.e5 = Entry(self.window, textvariable = self.state_text) self.e5.grid(row = 3, column = 3) self.county_text = StringVar() self.e6 = Entry(self.window, textvariable = self.county_text) self.e6.grid(row = 4, column = 1) self.population_text = StringVar() self.e7 = Entry(self.window, textvariable = self.population_text) self.e7.grid(row = 4, column = 3) self.density_text = StringVar() self.e8 = Entry(self.window, textvariable = self.density_text) self.e8.grid(row = 5, column = 1) #define listbox self.list1 = Listbox(self.window, height = 20, width = 95) self.list1.grid(row = 6, column = 0, rowspan = 6, columnspan = 2) #scroll bar self.sb1 = Scrollbar(self.window) self.sb1.grid(row = 2, column = 2, rowspan = 6) self.list1.configure(yscrollcommand = self.sb1.set) self.sb1.configure(command = self.list1.yview) #define buttons self.b1 = Button(self.window, text = "Search Entry", command = self.search, width = 12) self.b1.grid(row = 6, column = 3) self.b2 = Button(self.window, text = "Add Entry", command = self.add, width = 12) self.b2.grid(row = 7, column = 3) self.b3 = tkinter.Button(self.window, text = "Update Selected", command = self.update, width = 12) self.b3.grid(row = 8, column = 3) self.b4 = tkinter.Button(self.window, text = "Delete Selected", command = self.delete, width = 12) self.b4.grid(row = 9, column = 3) self.b5 = tkinter.Button(self.window, text = "Close", width = 12, command = self.window.destroy) self.b5.grid(row = 10, column = 3) tkinter.mainloop() def search(self): select_criteria = str(self.e3.get()) def print_result(): result = cursor.fetchall() if(result == []): tkinter.messagebox.showinfo('Response', 'No entries matched this criteria.') for i in range(len(result)): arr = str(result[i]) self.list1.insert(i, arr) db.commit() if(str(self.e2.get()) == "City"): cursor.execute("SELECT * FROM Cities WHERE City=?", (select_criteria,)) print_result() if(str(self.e2.get()) == "State"): cursor.execute("SELECT * FROM Cities WHERE State=?", (select_criteria,)) print_result() if(str(self.e2.get()) == "County"): cursor.execute("SELECT * FROM Cities WHERE County=?", (select_criteria,)) print_result() if(str(self.e2.get()) == "Population"): cursor.execute("SELECT * FROM Cities WHERE Population =?", (select_criteria,)) print_result() if(str(self.e2.get()) == "Density"): cursor.execute("SELECT * FROM Cities WHERE Density=?", (select_criteria,)) print_result() def add(self): city = self.e4.get() state = self.e5.get() county = self.e6.get() population = int(self.e7.get()) density = int(self.e8.get()) cursor.execute("INSERT INTO Cities (City, State, County, Population, Density) VALUES (?,?,?,?,?)", (city, state, county, population, density)) db.commit() tkinter.messagebox.showinfo('Response', 'Entry added') def update(self): value = self.list1.get(self.list1.curselection()) value = value[1:-1] value = value.replace(',','') value = value.replace("'", "") value = value.strip() city = value[0] cursor.execute('DELETE FROM Cities WHERE City=?', (city)) db.commit() city = self.e4.get() state = self.e5.get() county = self.e6.get() population = int(self.e7.get()) density = int(self.e8.get()) cursor.execute("INSERT INTO Cities (City, State, County, Population, Density) VALUES (?,?,?,?,?)", (city, state, county, population, density)) db.commit() tkinter.messagebox.showinfo('Response', 'Entry updated') def delete(self): value = self.list1.get(self.list1.curselection()) value = value[1:-1] value = value.replace(', ','') value = value.replace("'", "") value = value.strip() city = value[0] cursor.execute('DELETE FROM Cities WHERE City=?', (city)) db.commit() tkinter.messagebox.showinfo('Response', 'Entry Deleted') my_gui = MyGUI()
7603c6723643bd67efaa32d5cf6c8cadc5b96936
anmolparida/Interview_Questions_Python
/IdentityCard_CodeTheSecret.py
1,542
3.671875
4
# Secret information is: # # The identity card should start with digit 2, 6, 9. [Done] # It must contain exactly 12 digits. [Done] # It must contain only digits from (0-9). # It must not have more than three repeated consecutive digits. # It may have digits in a group of four separated by one hyphen “-” and other separators are not allowed. input1 = '1358-1369-1695' #fake input2 = '3456-7891-2314' #fake input3 = '234567341234' #real idNumber = input1 def consecutiveIntegers(number): for i in range(1, len(number)): if int(number[i]) - int(number[i-1]) == 1: return False else: flag = True if flag: return True countReal = 0 if len(idNumber) == 12: countReal = countReal + 1 if consecutiveIntegers(idNumber) is True: countReal = countReal + 1 else: print('Fake') exit() elif len(idNumber) == 14: if idNumber[4] == '-' and idNumber[9] == '-': countReal = countReal + 1 idNumber = str(idNumber) idNumber = idNumber.replace('-','') if consecutiveIntegers(idNumber) is True: countReal = countReal + 1 else: print('Fake') exit() else: print('Fake') exit() else: print('Fake') exit() for letter in idNumber: if letter.isdigit() : countReal = countReal + 1 else: print('Fake') exit() if idNumber[0:1] in [2,6,9]: countReal = countReal + 1 else: print('Fake') exit() print('Real')
94f6592cc1593840b2126d3fc17b35cd7c448a2d
federicoparroni/SpeedsPrediction_DataMining
/src/preprocessing/distances.py
4,700
3.578125
4
from src import data from src.utils.folder import create_if_does_not_exist """ build a dictionary where: key: station id value: dictionary where: key: station_id value: estimated distance between the two stations returns the dictionary """ def compute_meteo_station_distances(distances_df): splitted = [x.replace(';', ',') for x in distances_df.STATIONS.values] d = {} for e in splitted: stations = e.split(',')[0::2] for s in stations: if s not in d: d[s] = {} for e in splitted: distances = list(map(float, e.split(',')[1::2])) stations = e.split(',')[0::2] j = 0 while j < len(distances) - 1: i = j + 1 while i < len(distances): dist = distances[i] + distances[j] if stations[j] not in d[stations[i]]: d[stations[i]][stations[j]] = dist else: if d[stations[i]][stations[j]] > dist: d[stations[i]][stations[j]] = dist if stations[i] not in d[stations[j]]: d[stations[j]][stations[i]] = dist else: if d[stations[j]][stations[i]] > dist: d[stations[j]][stations[i]] = dist i += 1 j += 1 return d """ given a column name and a dataframe, sorts the stations encoded in form station_id,dist;... in distance order """ def sort_station_by_closest(distances_df, column): stations = distances_df[column] ordered_stations = [] for s in stations: s_splitted_semicolon_unsorted = s.split(';') s_expanded_unsorted = [[c.split(',')[0], float(c.split(',')[1])] for c in s_splitted_semicolon_unsorted] s_expanded_sorted = sorted(s_expanded_unsorted, key = lambda x: int(x[1])) s_splitted_semicolon_unsorted = ['{},{}'.format(c[0], c[1]) for c in s_expanded_sorted] ordered_stations.append(';'.join(s_splitted_semicolon_unsorted)) distances_df[column] = ordered_stations return distances_df def preprocess(): print('Preprocessing distances...') distances_df = data.distances_original() distances_df_path = '{}/distances.csv.gz'.format(data._BASE_PATH_PREPROCESSED) create_if_does_not_exist(distances_df_path) # creo due colonne separate per KEY_KM che per ora sono insieme for i,row in distances_df.iterrows(): tmp=row.KEY_KM tmp=tmp.split(',') key= tmp[0] km=tmp[1] distances_df.at[i,'KEY'] = key distances_df.at[i,'KM'] = km distances_df=distances_df.drop(["KEY_KM"],axis=1) # drop nans distances_df = distances_df.dropna() # add ';' every 2 ',': split is easier ! stations = distances_df.STATIONS stations_splitted_nice = [] for s in stations: split = s.split(',') string = ';'.join(['{},{}'.format(split[2*i], split[2*i + 1]) for i in range(int(len(split)/2))]) stations_splitted_nice.append(string) distances_df.STATIONS = stations_splitted_nice # infer about other stations: put into distances_df, in each sensor, # informations about the distance of also other meteorological stations d = compute_meteo_station_distances(distances_df) stations = distances_df.STATIONS.values inferred_stations = [] for s in stations: inferred_string = '' splitted = s.split(';') stations_already_present = set() for e in splitted: station = e.split(',')[0] stations_already_present.add(station) for e in splitted: distanc = e.split(',')[1] for item in d[e.split(',')[0]].items(): if item[0] not in stations_already_present: inferred_string += '{},{};'.format(item[0], float(item[1]) + float(distanc)) stations_already_present.add(item[0]) inferred_stations.append(inferred_string[:-1]) # append the inferred stations to the original stations appended_stations = [] stations = distances_df.STATIONS.values for idx in range(len(stations)): if len(inferred_stations[idx]) > 0: appended_stations.append('{};{}'.format(stations[idx], inferred_stations[idx])) else: appended_stations.append(stations[idx]) distances_df['STATIONS'] = appended_stations distances_df = sort_station_by_closest(distances_df, 'STATIONS') # finally save distances_df.to_csv(distances_df_path, index=False, compression='gzip') if __name__ == "__main__": preprocess()
389d1239ff2958e7ebd6c11965c3336c24ba618c
Kawser-nerd/CLCDSA
/Source Codes/CodeJamData/12/21/3.py
1,514
3.5
4
# -*- coding: utf-8 -*- # <nbformat>3</nbformat> # <codecell> def readline_ints(): return [int(num) for num in fin.readline().strip().split()] # <codecell> from collections import Counter def tideline(scores, X): cc = Counter(scores) #print(cc) floating = 0 for score in range(max(scores)+1): floating += cc[score] if floating > X: break X -= floating else: score += 1 #print(score, X, floating) return score + X/floating # <codecell> def find_min_vote_proportions(scores): X = sum(scores) points_limit = tideline(scores, X) print(points_limit) proportions_needed = [] for s in scores: if s >= points_limit: proportions_needed.append(0.0) else: points_needed = points_limit - s #print(s, points_needed, X) proportions_needed.append(100*points_needed/X) return proportions_needed # <codecell> # Update this with the filename fname = "A-large" with open(fname+".in","r") as fin, open(fname+".out","w") as fout: numcases = readline_ints()[0] print(numcases, "cases") for caseno in range(1, numcases+1): # Code goes here N, *scores = readline_ints() result = find_min_vote_proportions(scores) result_str = " ".join("%f" % p for p in result) outstr = "Case #%d: %s" % (caseno, result_str) fout.write(outstr + "\n") print(outstr) # <codecell>
d45b163a75c9407077701c0bef9399da5ac37803
Lithika-Ramesh/Amaatra-Grade-12-Lab-Programs
/practice programs/program2.py
186
4.1875
4
# 2 . WAP to find if a no. is odd or even. def check(n): if n%2==0: return "even" else : return "odd" n = int(input("enter the number")) print (n,"is",check(n))
32f865c7ead45a6ca6e2f40ce443f32d9f1f7963
akshaali/Competitive-Programming-
/Hackerrank/TaumandB'day.py
3,734
4
4
""" Taum is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy black gifts and white gifts. The cost of each black gift is units. The cost of every white gift is units. The cost of converting each black gift into white gift or vice versa is units. Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts. For example, if Taum wants to buy black gifts and white gifts at a cost of and conversion cost , we see that he can buy a black gift for and convert it to a white gift for , making the total cost of each white gift . That matches the cost of a white gift, so he can do that or just buy black gifts and white gifts. Either way, the overall cost is . Function Description Complete the function taumBday in the editor below. It should return the minimal cost of obtaining the desired gifts. taumBday has the following parameter(s): b: the number of black gifts w: the number of white gifts bc: the cost of a black gift wc: the cost of a white gift z: the cost to convert one color gift to the other color Input Format The first line will contain an integer , the number of test cases. The next pairs of lines are as follows: - The first line contains the values of integers and . - The next line contains the values of integers , , and . Constraints Output Format lines, each containing an integer: the minimum amount of units Taum needs to spend on gifts. Sample Input 5 10 10 1 1 1 5 9 2 3 4 3 6 9 1 1 7 7 4 2 1 3 3 1 9 2 Sample Output 20 37 12 35 12 Explanation Test Case #01: Since black gifts cost the same as white, there is no benefit to converting the gifts. Taum will have to buy each gift for 1 unit. The cost of buying all gifts will be: . Test Case #02: Again, we can't decrease the cost of black or white gifts by converting colors. is too high. We will buy gifts at their original prices, so the cost of buying all gifts will be: . Test Case #03: Since , we will buy white gifts at their original price of . of the gifts must be black, and the cost per conversion, . Total cost is . Test Case #04: Similarly, we will buy white gifts at their original price, . For black gifts, we will first buy white ones and color them to black, so that their cost will be reduced to . So cost of buying all gifts will be: . Test Case #05: We will buy black gifts at their original price, . For white gifts, we will first black gifts worth unit and color them to white for units. The cost for white gifts is reduced to units. The cost of buying all gifts will be: . """ #!/bin/python3 import math import os import random import re import sys # # Complete the 'taumBday' function below. # # The function is expected to return a LONG_INTEGER. # The function accepts following parameters: # 1. INTEGER b # 2. INTEGER w # 3. INTEGER bc # 4. INTEGER wc # 5. INTEGER z # def taumBday(b, w, bc, wc, z): # Write your code here if bc > wc + z: return (b+w)*wc + b*z if wc > bc + z: return (b+w)*bc + w*z else: return w*wc + b*bc if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): first_multiple_input = input().rstrip().split() b = int(first_multiple_input[0]) w = int(first_multiple_input[1]) second_multiple_input = input().rstrip().split() bc = int(second_multiple_input[0]) wc = int(second_multiple_input[1]) z = int(second_multiple_input[2]) result = taumBday(b, w, bc, wc, z) fptr.write(str(result) + '\n') fptr.close()
2b3d1189aade700271643a160dccdc9be07e7efa
avtokit2700/resume
/resume-codewars/braser.py
768
4.21875
4
""" validBraces( "(){}[]" ) => returns true validBraces( "(}" ) => returns false validBraces( "[(])" ) => returns false validBraces( "([{}])" ) => returns true '([}{])' - False ')(}{][' - False """ def validBraces(string): bracer = [] pardict = {"{":"}", "[":"]", "(":")", "}":"{", "]":"[", ")":"("} for i in range(len(string)): if string[i] == "(" or string[i] == "[" or string[i] == "{": bracer.append(string[i]) else: if len(bracer) == 0: return False elif pardict[string[i]] == bracer[len(bracer)-1]: del bracer[len(bracer)-1] else: return False if len(bracer) != 0: return False return True print(validBraces('(){}[]'))
e0d3910a9018ac8e4b8bc35cf9160cdcf0c694db
pepinu/Goodrich-Tamassia-Python
/Chapter1/R-1.2.py
127
3.5625
4
def is_even(k): if k & 1: return False return True print(is_even(1)) print(is_even(2)) print(is_even(3)) print(is_even(4))
b0e67f9f15117a4fa946778912fa7d2dea10898a
JIC-CSB/jicgeometry
/jicgeometry/__init__.py
8,131
4.15625
4
"""Module for geometric operations. The module contains two classes to perform geometric operations in 2D and 3D space: - :class:`jicgeometry.Point2D` - :class:`jicgeometry.Point3D` A 2D point can be generated using a pair of x, y coordinates. >>> p1 = Point2D(3, 0) Alternatively, a 2D point can be created from a sequence. >>> l = [0, 4] >>> p2 = Point2D(l) The x and y coordinates can be accessed as properties or by their index. >>> p1.x 3 >>> p1[0] 3 Addition and subtraction result in vector arithmetic. >>> p1 + p2 <Point2D(x=3, y=4, dtype=int)> >>> p1 - p2 <Point2D(x=3, y=-4, dtype=int)> Scalar multiplication is supported. >>> (p1 + p2) * 2 <Point2D(x=6, y=8, dtype=int)> Scalar division uses true division and as a result always returns a 2D point of ``dtype`` ``float``. >>> p1 / 2 <Point2D(x=1.50, y=0.00, dtype=float)> It is possible to calculate the distance between two points. >>> p1.distance(p2) 5.0 Points can also be treated as vectors. >>> p3 = p1 + p2 >>> p3.unit_vector <Point2D(x=0.60, y=0.80, dtype=float)> >>> p3.magnitude 5.0 """ import math __version__ = "0.6.0" class Point2D(object): """Class representing a point in 2D space.""" def __init__(self, a1, a2=None): if a2 is None: # We assume that we have given a sequence with x, y coordinates. self.x, self.y = a1 else: self.x = a1 self.y = a2 self._set_types() def _set_types(self): """Make sure that x, y have consistent types and set dtype.""" # If we given something that is not an int or a float we raise # a RuntimeError as we do not want to have to guess if the given # input should be interpreted as an int or a float, for example the # interpretation of the string "1" vs the interpretation of the string # "1.0". for c in (self.x, self.y): if not (isinstance(c, int) or isinstance(c, float)): raise(RuntimeError('x, y coords should be int or float')) if isinstance(self.x, int) and isinstance(self.y, int): self._dtype = "int" else: # At least one value is a float so promote both to float. self.x = float(self.x) self.y = float(self.y) self._dtype = "float" @property def dtype(self): """Return the type of the x, y coordinates as a string.""" return self._dtype @property def magnitude(self): """Return the magnitude when treating the point as a vector.""" return math.sqrt(self.x**2 + self.y**2) @property def unit_vector(self): """Return the unit vector.""" return Point2D(self.x / self.magnitude, self.y / self.magnitude) def distance(self, other): """Return distance to the other point.""" tmp = self - other return tmp.magnitude def __repr__(self): s = "<Point2D(x={}, y={}, dtype={})>" if self.dtype == "float": s = "<Point2D(x={:.2f}, y={:.2f}, dtype={})>" return s.format(self.x, self.y, self.dtype) def __eq__(self, other): if self.dtype != other.dtype: return False return self.x == other.x and self.y == other.y def __add__(self, other): return Point2D(self.x + other.x, self.y + other.y) def __sub__(self, other): return Point2D(self.x - other.x, self.y - other.y) def __mul__(self, other): return Point2D(self.x * other, self.y * other) def __div__(self, other): return self * (1/float(other)) def __truediv__(self, other): return self.__div__(other) def __len__(self): return 2 def __getitem__(self, key): if key == 0: return self.x elif key == 1: return self.y else: raise(IndexError()) def __iter__(self): return iter([self.x, self.y]) def astype(self, dtype): """Return a point of the specified dtype.""" if dtype == "int": return Point2D(int(round(self.x, 0)), int(round(self.y, 0))) elif dtype == "float": return Point2D(float(self.x), float(self.y)) else: raise(RuntimeError("Invalid dtype: {}".format(dtype))) def astuple(self): """Return the x, y coordinates as a tuple.""" return self.x, self.y class Point3D(object): """Class representing a point in 3D space.""" def __init__(self, a1, a2=None, a3=None): if a2 is not None and a3 is not None: self.x, self.y, self.z = a1, a2, a3 else: self.x, self.y, self.z = a1 self._set_types() def _set_types(self): """Make sure that x, y, z have consistent types and set dtype.""" # If we given something that is not an int or a float we raise # a RuntimeError as we do not want to have to guess if the given # input should be interpreted as an int or a float, for example the # interpretation of the string "1" vs the interpretation of the string # "1.0". for c in (self.x, self.y, self.z): if not (isinstance(c, int) or isinstance(c, float)): raise(RuntimeError('x, y coords should be int or float')) if (isinstance(self.x, int) and isinstance(self.y, int) and isinstance(self.z, int)): self._dtype = "int" else: # At least one value is a float so promote both to float. self.x = float(self.x) self.y = float(self.y) self.z = float(self.z) self._dtype = "float" @property def dtype(self): """Return the type of the x, y coordinates as a string.""" return self._dtype def __iter__(self): return iter([self.x, self.y, self.z]) def __repr__(self): s = "<Point3D(x={}, y={}, z={}, dtype={})>" if self.dtype == "float": s = "<Point2D(x={:.2f}, y={:.2f}, z={:.2f}, dtype={})>" return s.format(self.x, self.y, self.z, self.dtype) def __eq__(self, other): if self.dtype != other.dtype: return False return (self.x == other.x and self.y == other.y and self.z == other.z) def __add__(self, other): return Point3D(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return Point3D(self.x - other.x, self.y - other.y, self.z - other.z) def __mul__(self, other): return Point3D(self.x * other, self.y * other, self.z * other) def __div__(self, other): return self * (1/float(other)) def __truediv__(self, other): return self.__div__(other) def __len__(self): return 3 def __getitem__(self, key): if key == 0: return self.x elif key == 1: return self.y elif key == 2: return self.z else: raise(IndexError()) @property def magnitude(self): """Return the magnitude when treating the point as a vector.""" return math.sqrt(self.x**2 + self.y**2 + self.z**2) @property def unit_vector(self): """Return the unit vector.""" return Point3D(self.x / self.magnitude, self.y / self.magnitude, self.z / self.magnitude) def distance(self, other): """Return distance to the other point.""" tmp = self - other return tmp.magnitude def astype(self, dtype): """Return a point of the specified dtype.""" if dtype == "int": return Point3D(int(round(self.x, 0)), int(round(self.y, 0)), int(round(self.z, 0))) elif dtype == "float": return Point3D(float(self.x), float(self.y), float(self.z)) else: raise(RuntimeError("Invalid dtype: {}".format(dtype))) def astuple(self): """Return the x, y coordinates as a tuple.""" return self.x, self.y, self.z
ad7d8fde249b36f997c7e160f0ac1ca5d809f919
LucasZapico/rabbit
/space.py
16,539
4.53125
5
print("Welcome to our Solar System!") name = input('What is your name? ') print("Hi," + name + "!") print("Whenever we see a star \"*\" press enter when you're ready to move on, lets try now, press enter!") star = input('*') print("Our Solar System is a very large and complex place. It is composed of eight planets, one star" " and many many other objects. ") print("These objects include asteroids, comets, dwarf planets, and lots of dust.") print("Lets start out with using your weight to calculate how much you would weigh on the different planets.") weight = int(input('How much do you weigh on Earth? ')) print("We can use your weight and Newton's second law ( F = ma , Force is equal to Mass times Acceleration)" " to calculate your weight on the different planets in our solar system.") print("In this case our weight " + str(weight) + " lbs is the force, mass is what we want to calculate," "and acceleration is 9.8 m/s\u00b2.") input('*') print("F = ma") print("F = " + str(weight) + " lbs , which we can convert to kilograms by dividing by" " 2.2 which gives " + str(round(weight / 2.2)) + " kg") print("m = ? , this is what we are looking for.") print("a = 9.8 m/s\u00b2") input('*') print("m = " + str(weight) + " kg / 9.8 m/s\u00b2 = " + str(round(weight / 9.8)) + " kg") qes2 = "yes" degree_sign = u"\N{DEGREE SIGN}" planet = input('Which planet would you like to learn about? ') while qes2 == "yes": if planet == "Mercury": print("Mercury is the smallest and closest planet to the Sun. Being this close to the Sun" " means that during the day it can get extremely hot, like 900" + degree_sign + "F hot!") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 3.7)) print("On Mercury you would weigh " + str(round(x)) + " lbs!") print("This is due to the fact that this smaller planet has a smaller force of gravity!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("One year on Mercury (the amount of time it takes Mercury to complete one " "full orbit of the Sun) is equal to 88 days on Earth.") print("One day on Mercury lasts two Mercury years long, or you get one year of daylight and" " one year of night.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') y = "yes" if y == qes2: planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Venus": print("Venus is considered Earth's twin sister. This is because Venus and Earth are similar in size" " but this is where the similarities end.") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 8.87)) print("On Venus you would weigh " + str(round(x)) + " lbs!") print("This should be pretty close to how much you weigh on Earth, this is due to the fact" " that Venus and Earth are almost the same size and density! ") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Venus and Uranus both have a very unique feature that helps them stand out." " Both of these planets spin in the opposite direction of the other planets in our " "solar system. On Venus the Sun rises in the west and sets in the east. This makes" "for some pretty interesting days.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') y = "yes" if y == qes2: planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Earth": print("Welcome to Earth, this is where you were born and currently live!") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 9.8)) print("On Earth you weigh " + str(round(x)) + " lbs!") print("This is because earth has a specific acceleration due to gravity and that's" " what we use to calculate weigh!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Earth is the only planet that we know of that has living things.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Mars": print("Mars is known as the red planet, this red color comes from its thin " "atmosphere and distance from the Sun.") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 3.7)) print("On Mars you would weigh " + str(round(x)) + " lbs!") print("This is due to size, Mars is only just over half the size of Earth" " but again has a similar density!") qes = input("Would you like another fun fact? ") if qes == "yes": print("Mars has two moons Phobos and Deimos, named after the Greek mythological twins") print("who followed their father Ares into battle.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Jupiter": print("Jupiter is the largest planet in our solar system, I hope you enjoy your visit!") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 24.79)) print("On Jupiter you would weigh " + str(round(x)) + " lbs!") print("This is due to the immense gravitational pull of this large planet!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Jupiter has four large moons Io, Europa, Ganymede, and Callisto referred " "to as the Galilean Moons. These are the initial four moons Galileo discovered" " orbiting around Jupiter") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Saturn": print("Saturn has many rings and moons.") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 10.44)) print("On Saturn you would weigh " + str(round(x)) + " lbs!") print("This is pretty close to how much you weigh on Earth, although Saturn is " "much larger it is much less dense!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Saturn's rings are made up of ice, rock, and dust. These ingredients may" " come from comets, asteroids, and potentially broken moons.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Uranus": print("Uranus lays on its side and is known as the icy giant.") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 8.87)) print("On Uranus you would weigh " + str(round(x)) + " lbs!") print("Although Uranus is much larger than Earth it is much less dense than Earth!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Uranus sits on its side with the north and south poles facing towards and" " away from the Sun. Because of this Uranus has 21 years of night in winter " "and 21 years of daylight in the summer.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Neptune": print("Neptune is named after the Roman god of the sea and is very blue.This blue color " "is due to the methane in the atmosphere absorbing red light and reflecting blue light") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 11.15)) print("On Neptune you would weigh " + str(round(x)) + " lbs!") print("On Neptune the force of gravity is slightly more than Earths causing you " "to feel pretty heavy!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Although Pluto was once considered to be the farthest planet (now dwarf planet)" " from the Sun there is a 20 year period during Neptune's orbit in " "which Neptune is farther away from the sun than Pluto is.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") elif planet == "Pluto": print("Although no longer a planet Pluto, the now dwarf planet, is still remembered " "and cherished by many.") qes = input("Would you like a fun fact? ") if qes == "yes": x = (float((weight / 9.8) * 0.62)) print("On Pluto you would weigh " + str(round(x)) + " lbs!") print("This is because Pluto is so small!") qes_1 = input("Would you like another fun fact? ") if qes_1 == "yes": print("Pluto has five small moons that orbit around it, the largest of these moons is " "named Charon.") qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: qes2 = input('Would you like to see a different planet? ') if qes2 == "yes": planet = input('Which planet would you like to learn about? ') else: print("Thanks for your time! Have a nice day!") else: print("Invalid Entry. Try Again!") planet = input('Which planet would you like to learn about? ') print("done!")
f0612730e3090368de56ef91c9ca5614d088b9d1
hjalves/project-euler
/problems1-25/problem3.py
452
3.84375
4
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ Project Euler - Problem 3 Largest prime factor """ def is_prime(n): return all(n % i != 0 for i in range(2, int(n**0.5)+1)) def primes(max): return filter(is_prime, range(2, max+1)) def factors(n): return (p for p in primes(n) if n % p == 0) def factorize(n): f = next(factors(n)) # lowest factor return [f] if f == n else [f] + factorize(n//f) print(factorize(600851475143))
b146391b80addb994e1e60d191a6c168e89b9f07
sonymoon/algorithm
/src/main/python/geeksforgeeks/graph/union-find to check cycle of graph.py
1,161
3.984375
4
from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) # default dictionary to store graph def add_edge(self, u, v): self.graph[u].append(v) def find_parent(self, parent, i): if parent[i] == - 1: return i if parent[i] != -1: return self.find_parent(parent, parent[i]) def union(self, parent, x, y): x_set = self.find_parent(parent, x) y_set = self.find_parent(parent, y) parent[x_set] = y_set def is_cycle(self): parent = [-1] * self.V for i in self.graph: for j in self.graph[i]: x = self.find_parent(parent, i) y = self.find_parent(parent, j) if x == y: return True self.union(parent, x, y) return False # Create a graph given in the above diagram g = Graph(3) g.add_edge(0, 1) g.add_edge(1, 2) g.add_edge(2, 0) if g.is_cycle(): print "Graph contains cycle" else: print "Graph does not contain cycle " # This code is contributed by Neelam Yadav
d0a490b5d2172dd1b5ed380102f8ad160278827c
ayu7/csprag-ahw8
/rpn.py
1,171
3.5625
4
#!/usr/bin/env python3 import operator import readline import colorama operators = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } RED = '\033[31m' BLUE = '\u001b[44m' MAGENTA = '\u001b[35m' RESET = '\033[0m' def calculate(myarg): stack = list() for token in myarg.split(): try: token = int(token) stack.append(token) except ValueError: function = operators[token] arg2 = stack.pop() arg1 = stack.pop() result = function(arg1, arg2) colored = BLUE + "Calculation: " + RESET + str(arg1) + MAGENTA + token + RESET + str(arg2) + " = " if (result < 0): colored += RED colored += str(result) + RESET stack.append(result) print(colored) print(stack) if len(stack) != 1: raise TypeError("Too many parameters") return stack.pop() # def random_func(): # print("something") def main(): while True: result = calculate(input("rpn calc> ")) print("Result: ", result) if __name__ == '__main__': main()
e65aaf15cad301442ffef19143a5c5e57ea17cc4
kkwietniewski/Python
/Pai/zad1.py
311
3.984375
4
numbers={'1':"Jeden",'2':"Dwa",'3':"Trzy",'4':"Cztery",'5':"Pięć",'6':"Sześć", '7':"Siedem",'8':"Osiem",'9':"Dziewięć",'0':"Zero"} string = input("Podaj ciąg cyfr do przekształcenia na string: ") result = '' for i in string: if i.isnumeric() == True: result += ' '+numbers[i] print(result)
61b1ce16eab2158d88ab2422a29b0efa81bd0532
mjms3/helo
/esp/tests/test_dijkstra.py
857
3.625
4
from math import sqrt from unittest import TestCase from esp.dijkstra import dijkstra class TestDijkstra(TestCase): def test_shortestPathBetweenTwoVertices_isTheJoiningEdge(self): graph = [(0, 1, 1)] cost, path = dijkstra(graph, 0, 1) self.assertEqual(1, cost) self.assertEqual((0, 1), path) def test_shortestPathInSquare_isAlongDiagonal(self): graph = [(0, 1, 1), (0, 4, sqrt(2) / 2), (1, 4, sqrt(2) / 2), (0, 2, 1), (1, 3, 1), (2, 4, sqrt(2) / 2), (3, 4, sqrt(2) / 2), (2, 3, 1), ] graph += [(e[1], e[0], e[2]) for e in graph] cost, path = dijkstra(graph, 0, 3) self.assertAlmostEqual(sqrt(2), cost) self.assertEqual((0, 4, 3), path)
73a37012daf82c8081875d2cd1dee8312e116651
Lakshya31/BasicGeneticAlgorithm
/Basic_GA.py
6,989
4
4
""" This is a program to demonstrate working of basic genetic algorithm which is searching for the least valued points in the graph of sin(x^2), hope you like it! ^_^ Once the run is complete, you can go to the "Output" folder and slideshow the output Images in order of Generation to visualize the changes """ # Made by Lakshya Sharma # Import Statements: import numpy import math import matplotlib.pyplot as plt import time import shutil import os # GA Parameters : Tweak and test for different parameters to get varying results pc = 0.4 # Probability of Crossover pm = 0.2 # Probability of mutation population_size = 40 # Number of Individuals num_chromosomes = 1 # Number of Chromosomes Generation = -1 # Generation Count avg = 0.3 # Averaging Factor parent_size = int(pc*population_size) # Size of parent array children_size = int(pc*population_size) # Size of children array # Global Lists: population = numpy.array([[None]*num_chromosomes]*population_size) # The Population fitness_values = numpy.array([None]*population_size) # Respective fitness values parents = [None]*parent_size # Indexes of selected parents children = numpy.array([[None]*num_chromosomes]*children_size) # Crossover result storage array fit_list = [] # list of fittest individual in each Gen fittest = population_size # index of the fittest individual of the Gen # UDF def graph_initialization(): """Initializes a graph of sin(x^2) for better visualization""" r = numpy.arange(-1 * math.pi, math.pi, 1e-3) f = numpy.vectorize(math.sin) plt.clf() plt.plot(r, f(r ** 2), color="BLACK") def population_initialization(): """Initializing the population""" for i in range(population_size): for j in range(num_chromosomes): population[i][j] = numpy.random.uniform((-1*math.pi), math.pi) def fitness_calculation(): """Calculates Fitness of Each Individual""" for i in range(population_size): for j in range(num_chromosomes): fitness_values[i] = math.sin((population[i][j])**2) # if fitness_values[i] < -0.999: # fitness_values[i] = -1 def display(): """Displays Fittest Value achieved in each generation""" global fittest min = 2 fittest = population_size for i in range(population_size): if fitness_values[i] < min: min = fitness_values[i] fittest = i print("-" * 300 + "\n") print("Generation No.", Generation) print("Fitness achieved:", fitness_values[fittest]) print() fit_list.append(fitness_values[fittest]) def visualize(): """A function to help visualize each generation's progress""" graph_initialization() for i in range(population_size): if i != fittest: for j in range(num_chromosomes): plt.scatter(population[i][j], fitness_values[i], marker=".", color="RED") plt.scatter(population[fittest][0], fitness_values[fittest], marker="*", color="BLUE") plt.title("Generation#"+str(Generation)) plt.xlabel("---x--->") plt.ylabel("---sin(x^2)--->") plt.grid(color='GREEN', linestyle='-', linewidth=0.5) plt.savefig("Output\\Generation#"+str(Generation)+".png") plt.pause(1) # Comment this line if you wanna see the output after the run instead of during the run def parent_selection(): """Selection algorithm for parent selection""" for i in range(parent_size): min = 2 index = population_size for j in range(population_size): if fitness_values[j] < min and j not in parents: min = fitness_values[j] index = j parents[i] = index def crossover(): """Performs crossover on selected parents""" for i in range(0, parent_size, 2): for j in range(num_chromosomes): children[i][j] = avg * population[parents[i]][j] + (1-avg)*population[parents[i + 1]][j] children[i+1][j] = (1-avg) * population[parents[i]][j] + avg * population[parents[i + 1]][j] def mutation(): """Performs mutation on all new children""" for i in range(children_size): for j in range(num_chromosomes): prob = numpy.random.uniform(0, 1) if prob < pm: children[i][j] *= numpy.random.uniform(0.9, 1.1) def survivor_selection(): """Selection algorithm for survivor selection""" visited = [] for i in range(children_size): max = -2 index = population_size for j in range(population_size): if fitness_values[j] > max and j not in visited: max = fitness_values[j] index = j visited.append(index) for k in range(num_chromosomes): population[index][k] = children[i][k] def termination_conditions(): """Boolean value returning function which checks the termination conditions""" global Generation Generation += 1 if Generation == 100: print("\n\n\nMaximum Generation Limit Reached\n") return False if Generation > 10: """ for i in range(len(fit_list)-1, len(fit_list)-15, -1): if fit_list[i] != fit_list[i-1]: break else: print("\n\n\nNo Change Detected in past 15 generations\n") return False """ if fit_list[len(fit_list)-2] == fit_list[len(fit_list)-2] == -1: print("\n\n\nMinimum Value Achieved\n") return False return True # Main shutil.rmtree("Output") # Deletes previous output folder time.sleep(1) # Allows time for deletion os.makedirs("Output") # Makes a new Output directory start = time.time() # Times the GA #GA population_initialization() while termination_conditions(): fitness_calculation() display() visualize() parent_selection() crossover() mutation() survivor_selection() end = time.time() print("\nMinimum found at x =",population[fittest][0]) print("\n\nTime Taken:", int(end-start), "seconds") plt.show()
9f83691ec54ed903b08e84ce2ce412801fa4f037
sasidhara222/Ansible
/Python Programming/Okati/Print.py
1,454
3.875
4
print('Mi Daddy') print(4 / 9) print(200*9336) print('Hello..! Hello..! ani anipinchave gundello...') print("swing zara swing zara... 'swing'") print("Apudye ipoindi anukunavemo...! Epudye modalindi.. Epudye modalindiiiii....!") balaya = "Jai" jai = "Balaya" print(balaya + jai) #Dinthali print(balaya+" "+jai) print("This is \n One \n Two \n Three") print("1 \t 2 \t 3 \t 4") print("Balaya said \"Niku Bp vasthe ni PA onukuthademo? Adye naku BP vasthe AP vanukudhi\" ") print("""How are you ?""") name = input("what do you want?") print("Hooooo.....!"+"\n You want " + name + "\n Fuck you....! :-)") var1 = "vikatakavi" print(var1) print(var1[3]) print(var1[6]) #print(var1[98]) print(var1[3:3]) print(var1[2:]) print(var1[:3]) print(var1[:]) print(var1[0:9]) print(var1[-7]) print(var1[-7:-5]) numbers = "1,222,666,222,263" print(numbers[1::4]) num = "1,2,3,4,5,6,7,8,9" print(num[0::2]) print(num * 3) print(num * (1+5)) age = 24 #print("My is" + age +"years") print("My age is {0}".format(age)) print("My age is {0} years".format(age)) print("My age is {0} {1}".format(age, "years")) print("My age %d %s, %d %s" % (age,"years",6,"months")) print("Jan-{0},Feb-{1},Mar-{2}".format(31,28,30)) for i in range(1,12): print("No. %2d if squared %4d if cubed %d "% (i,i ** 2, i ** 3)) for i in range(1,10): print("No. {0:2} if squared {1:3} and id cubed {1:4}".format(i,i**2,i**3)) print("The value of pie is apporximately %f" % (22/7))