blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
9551e2adfa93226aafea33e89b5fc04ba788fd28
rojicha07/LLBean_data_science
/CLASE 2 - 05-07-2019/ejemplo_tuplas.py
566
3.953125
4
#crear una tupla de 5 elementos de tipos diferentes mi_tupla = (1,'Roger', 5.34, 'Python', False) print(mi_tupla) # agregar mas elementos en una tupla?? mi_tupla = mi_tupla + (11, 'Nuevo elemento') print (mi_tupla) # acumular elementos mi_tupla += (0,'x') print(mi_tupla) #subtupla #el segundo hasta el penultimo print(mi_tupla[1:-1]) #subtupla con saltos #los elementos pares - que esten en indice par #ojo que el cero es par print('los elementos pares son: ', mi_tupla[::2]) #los elementos impares print('los elementos impares son: ', mi_tupla[1::2])
62e0b61997e50d5eb4ff4c95f551b0b4ca90127f
Starsclaw/Magnetic-reconnexion-events
/PDF merger.py
1,022
3.625
4
import os, PyPDF2 #Ask user where the PDFs are userpdflocation=input('Where are your files') userpdflocation=userpdflocation.replace('\\','/') #Sets the scripts working directory to the location of the PDFs os.chdir(userpdflocation) #Ask user for the name to save the file as file_name=input('What should I call the file?') #Get all the PDF filenames Merged_file = [] for filename in os.listdir('.'): if filename.endswith('.pdf'): Merged_file.append(filename) pdfWriter = PyPDF2.PdfFileWriter() #loop through all PDFs for filename in Merged_file: #rb for read binary pdfFile = open(filename,'rb') pdfReader = PyPDF2.PdfFileReader(pdfFile) #Opening each page of the PDF for pageNum in range(pdfReader.numPages): pageObj = pdfReader.getPage(pageNum) pdfWriter.addPage(pageObj) #save PDF to file, wb for write binary pdfOutput = open(file_name+'.pdf','wb') #Outputting the PDF pdfWriter.write(pdfOutput) #Closing the PDF writer pdfOutput.close()
dfe8ca78e57b0ba105b402678655f6a680888e2f
YewonS/KEA_DAT18_Python
/Module/os_exercise.py
1,181
3.734375
4
# os_exercise.py # Do the following task using the os module """ 1. create a folder and name the folder 'os_exercises.' 2. In that folder create a file. Name the file 'exercise.py' 3. get input from the console and write it to the file. 4. repeat step 2 and 3 (name the file something else). 5. read the content of the files and and print to console the content of the file with the largest amount of unique words. """ import os # 5 def unique_words(thefile): t = set(thefile.read().split()) return t #1 if os.path.isdir('os_exercises'): pass else: os.mkdir('os_exercises') os.chdir('os_exercises') #2 - 5 for i in range(1, 4): if os.path.exists(f'exercise{i}.py'): print(unique_words(open(f'exercise{i}.py'))) else: newFile = open(f'exercise{i}.py', 'w') newInput = str(input()) newFile.write(newInput) print(f'new File created: "{newFile}", {newInput}') newFile.close()
64c426b1edc231d08726d8bef8a5766cb33738c8
SUJEONG999/Python_Practice
/day5/listLab3.py
592
3.6875
4
listnum = [10, 5, 7, 21, 4, 8, 18] min_listnum = listnum[0] # 리스트 중 첫 번째 값을 일단 최솟값으로 기억 min_listnum = listnum[0] for i in range(1, len(listnum)): # 1부터 n - 1까지 반복 if listnum[i] < min_listnum: # 이번 값이 현재까지 기억된 최솟값보다 작으면 min_listnum = listnum[i] # 최솟값을 변경 elif listnum[i] > max_listnum: # 이번 값이 현재까지 기억된 최댓값보다 크면 max_listnum = listnum[i] # 최댓값을 변경 print("최솟값 :",min_listnum,", 최댓값 :",max_listnum)
39013a1664feba4777ee98f7ea55218b874f739b
dmytro73/QA-Google
/test0809.py
723
4.09375
4
print('ЗАДАЧА 1: Создать лист из 6 любых чисел. Отсортировать его по возрастанию\n') numbers = [1, 22, 23, 0.19, 1802, -2] print('Исходный список ', numbers) numbers.sort() print('Сортировка "по возрастанию" ', numbers) print('\n\nЗАДАЧА 3: Создать tuple из 10 любых дробных чисел, найти максимальное и минимальное значение в нем\n') tuple_1 = (1.2, 0.21, 32.1, 5.5, 8.9, 2.13, 3.1415, 0.001, 12122.1, 7.5) print('Максимальное значений в Tuple ', max(tuple_1)) print('Минимальное значений в Tuple ', min(tuple_1))
11edcd2a65c85489709391190f4b30dd545f4d66
Yllcaka/Random.python
/python-universum-ks.org-master/Binarysearch.py
437
3.859375
4
def binary(list,number): low = 0 high = len(list)-1 while low <= high: mid = (low + high) // 2 print(mid) if list[mid] == number: return f"{number} is on index [{mid}] of the list" elif list[mid] < number: low = mid+1 elif list[mid] > number: high = mid-1 return f"{number} isn't in the list" array = [2,4,6,8,10,12,14] print(binary(array,14))
d4108d1af50f12ff6fefb050590fe05b0133dd5a
prashanthar2000/ctf-junk
/five86-2/five86-1/worklist.gen.py
409
3.5625
4
for i in range(10): for j in range(i): print("\t",end="") print("for" ,chr(i+107) , "in 'aefhrt':") if i == 9: for j in range(i+1): print("\t" , end="") temp = "" print('print(', end="") for a in range(107, 107+i): print(chr(a), end="+" ) print('t)') # for j in range(i+1): # print("\t",end="")
d185b3a8bec87fe8413b44603c623b722f9773e8
mohanrajanr/CodePrep
/we_230/5690.py
1,007
3.671875
4
from typing import List def closestCost(baseCosts: List[int], toppingCosts: List[int], target: int) -> int: closest = [float('-inf'), float('inf')] def add_to(value): if value <= target: closest[0] = max(closest[0], value) else: closest[1] = min(closest[1], value) def backtrack(cost, index): # print(cost, toppingCosts[index] + cost, (toppingCosts[index] * 2) + cost) add_to(cost) if index >= len(toppingCosts): return backtrack(toppingCosts[index] + cost, index + 1) backtrack((toppingCosts[index] * 2) + cost, index + 1) backtrack(cost, index + 1) for cost in baseCosts: backtrack(cost, 0) # print(closest) return int(closest[0]) if abs(target - closest[0]) <= abs(closest[1] - target) else int(closest[1]) print(closestCost([1, 7], [3, 4], 10)) print(closestCost([2, 3], [4, 5, 100], 18)) print(closestCost([3, 10], [2, 5], 9)) print(closestCost([10], [1], 1))
9620f76ca5e437b2df2f9019f14cb33b568db5d4
raffi01/Python-Finite-State-Machines
/transition.py
3,353
4.3125
4
class Transition: """A change from one state to a next""" def __init__(self, current_state, state_input, next_state): self.current_state = current_state self.state_input = state_input self.next_state = next_state def match(self, current_state, state_input): """Determines if the state and the input satisfies this transition relation""" return self.current_state == current_state and self.state_input == state_input class FSM: """A basic model of computation""" def __init__( self, states=[], alphabet=[], accepting_states=[], initial_state=''): self.states = states self.alphabet = alphabet self.accepting_states = accepting_states self.initial_state = initial_state self.valid_transitions = False def add_transitions(self, transitions=[]): """Before we use a list of transitions, verify they only apply to our states""" for transition in transitions: if transition.current_state not in self.states: print( 'Invalid transition. {} is not a valid state'.format( transition.current_state)) return if transition.next_state not in self.states: print('Invalid transition. {} is not a valid state'.format) return self.transitions = transitions self.valid_transitions = True def __accept(self, current_state, state_input): """Looks to see if the input for the given state matches a transition rule""" # If the input is valid in our alphabet if state_input in self.alphabet: for rule in self.transitions: if rule.match(current_state, state_input): return rule.next_state print('No transition for state and input') return None return None def accepts(self, sequence): """Process an input stream to determine if the FSM will accept it""" # Check if we have transitions if not self.valid_transitions: print('Cannot process sequence without valid transitions') print('Starting at {}'.format(self.initial_state)) # When an empty sequence provided, we simply check if the initial state # is an accepted one if len(sequence) == 0: print("Input: None") print('Ending state is {}'.format(self.initial_state)) return self.initial_state in self.accepting_states # Let's process the initial state print('Input: {}'.format(sequence[0])) current_state = self.__accept(self.initial_state, sequence[0]) if current_state is None: return False # Continue with the rest of the sequence for state_input in sequence[1:]: print('Current state is {}'.format(current_state)) print('Input: {}'.format(state_input)) current_state = self.__accept(current_state, state_input) if current_state is None: return False print('Ending state is {}'.format(current_state)) # Check if the state we've transitioned to is an accepting state return current_state in self.accepting_states
0a4d83d9476f4780e0868aa022e32b329163f5c6
aasmirn/prgrm
/bonus/bonus3.py
1,070
4.09375
4
def change_word(word): vowels = 'aeiouy' index = 0 for letter in word: if letter not in vowels: index +=1 if letter in vowels: break return word[index:] + word[:index] + 'ay' def remove(phrase): symbols_to_remove = '.,!"()/?' for s in symbols_to_remove: if s in phrase: phrase = phrase.replace(s, '') return(phrase) def check(phrase): latin = "abcdefghijklmnopqrstuvwxyz' " check = '' for sym in phrase: if sym not in latin: check += 'not good' break return check phrase = input('Write your English phrase: ').lower() if phrase == '': print('Try to write something less empty.') else: phrase = remove(phrase) if check(phrase) == 'not good': print("That's not the way English works!") else: words = phrase.split(' ') pl_phrase = '' for word in words: pl_phrase += change_word(word) + ' ' print('This is Pig Latin for you: ', pl_phrase.capitalize())
b0f244bc99ccfd6546978811443d9173c692de56
srikanthpragada/PYTHON_16_MAR_2020
/demo/libdemo/thread_demo.py
290
3.59375
4
import threading def print_numbers(): for n in range(10): print(threading.current_thread().name, n) print("Current Thread : ", threading.current_thread().name) t = threading.Thread(target=print_numbers) t.start() t.join() # Wait until t is terminated print("End of Main")
3bd2f9bba9236c4bebc6071259459eaaa6be441a
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Pense_em_Python/cap03/Exercicio_3-1.py
419
4.0625
4
""" Escreva uma função chamada right_justify, que receba uma string chamada s como parãmentro e exiba a string com espaços sufucuentes à frente para que a última letra da string esteja na coluna 70 da tela. """ def right_justify(s): numero_espacos = 70 - len(s) #print("{0:>numero_espacos}".format(s)) espaco = "0" print(f"{espaco * numero_espacos}{s}") right_justify("Eu amo abacate")
3841cfc408e29d31a208679c73d100c42103298a
RaghunathSai/Algorithms_Data_Structures_Placement
/stack.py
890
4.09375
4
class Stack: def __init__(self,stack): self.stack = stack def push(self,data): stack.append(data) def pop(self): value = stack[len(stack)-1] print(value) stack.remove(value) print("Pop value = ",value) def peep(self): value = stack[len(stack)-1] print("Peep value is",value) def view_stack(self): for i in range(len(stack)): print(stack[len(stack)-i-1]) if __name__ == '__main__': stack = list() s = Stack(stack) choice = 1 while(choice != 0): choice = int(input("1.To push data 2.Pop data 3.Peep data 0.To Exit : ")) if (choice == 1): data = input("Enter stack value") s.push(data) elif (choice == 2): s.pop() elif (choice == 3): s.peep() s.view_stack() print("Exited")
45a032253033278aa5e3c594eac6ddea74392db9
kanghyunwoo20/MSE_Python
/ex120.py
256
3.5625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: fruit = {"봄" : "딸기", "여름" : "토마토", "가을" : "사과"} user = input("좋아하는 과일은?") if user in fruit.values(): print("정답입니다.") else: print("오답입니다.")
097b8a144ad8e97e2e063648cdea6c31dd2706a1
ikamino/hackathon_eyetest
/Hackathon/untitled8.py
315
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 23 13:25:28 2019 @author: jasonliang """ import datetime import time start = time.time() start2 = start + 12 while time.time() <= start2: print("1") #t1 = datetime.datetime.now() #print (t1) #t2 = datetime.datetime.now() #print (t2)
63031724da954f1550663e8e55fe088e19e2c91c
erikachen19/leet_code_ex
/Valid Parentheses.py
1,418
4.03125
4
#EASY #Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. #An input string is valid if: #Open brackets must be closed by the same type of brackets. #Open brackets must be closed in the correct order. # #Example 1: #Input: s = "()" #Output: true # #Example 2: #Input: s = "()[]{}" #Output: true # #Example 3: #Input: s = "(]" #Output: false # #Example 4: #Input: s = "([)]" #Output: false # #Example 5: #Input: s = "{[]}" #Output: true # # #Constraints: #1 <= s.length <= 104 #s consists of parentheses only '()[]{}'. ##################################################### #SOLUTION class Solution: def isValid(self, s: str) -> bool: key_dict = {"[":"]", "(":")","{":"}"} print(key_dict) b = [] for i in s: if i in list(key_dict.keys()): b.append(i) # example 1: [{()}]: b = [ "[","{","(" ] elif len(b)>0 and key_dict[b[-1]]==i: #if the next ")" -> b = [ "[","{" ], "{"-> b = ["["], LIFO last in first out b.pop() #example 2: {}()[]: b = ["{"] the next "}" -> b = [] else: #example 3: ([)] : b = ["(", "["] the next needs to be "[" -> False return False if len(b)==0: return True
e263df01619fa814aae414f73e03e96816c7504d
Kcpf/DesignSoftware
/Aluno_com_dúvidas_.py
519
4.15625
4
""" Faça um programa que pergunta ao aluno se ele tem dúvidas na disciplina. Se o aluno responder qualquer coisa diferente de "não", escreva "Pratique mais" e pergunte novamente se ele tem dúvidas. Continue perguntando até que o aluno responda que não tem dúvidas. Finalmente, escreva "Até a próxima". Seu programa deve imprimir as strings exatamente como descritas acima e nada mais. """ resposta = input() while resposta != 'não': print("Pratique mais") resposta = input() print("Até a próxima")
9fe6caea169b99f59e6ce70d868cbe8c581b08d4
Obj-V/Project-Euler
/Project_Euler_023/Project_Euler_23.py
1,613
3.890625
4
#Project_Euler_23.py #Virata Yindeeyoungyeon """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ def isSumOfTwoAbundant(num, abundantList): i = 0 j = len(abundantList) - 1 while i <= j: sumAbundantNums = abundantList[i] + abundantList[j] if sumAbundantNums < num: i += 1 elif sumAbundantNums > num: j -= 1 else: return True return False def nonAbundantSums(upperLimit): abundantList = [] nonAbundantSum = 1 for i in xrange(2,upperLimit+1): sumDivisors = 0 for j in xrange(1,i): if (i%j == 0): sumDivisors += j if (sumDivisors > i): abundantList.append(i) if not isSumOfTwoAbundant(i, abundantList): nonAbundantSum += i return nonAbundantSum print(nonAbundantSums(28123)) #4179871
6642f46ad80523da8087ac19a0b7701917ee9536
wasifMohammed/test
/pangram.py
539
3.59375
4
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def main(): str0=raw_input("Enter string.. ") i=0 fl=[] for i in range(26): fl.append(False) for c in str0.lower(): if not c == " ": fl[ord(c) - ord('a')]=True for j in fl: if j==False: return False return True >>> main() Enter string.. A quick brown fox jumps over the lazy dog True >>> main() Enter string.. crack False >>>
448c81dabcdde4799237f229655c15b851e22306
RagaSenitent/ragachandars
/a.py
80
3.984375
4
a=int(input("Enter a number:")) sum=0 while(a>0): sum=sum+a a=a-1 print (sum)
7cac511606c1ee285c09abade3bccb0c6b8b7e57
vishnuvardhan2005/PythonSamples
/Samples/HardWayExes/ex5.py
517
3.609375
4
name = "Vishnu Vardhan Reddy" age = 32 height = 74 weight = 180 eyes = 'Blue' teeth = 'white' hair = 'brown' print "Let's talk about %s" % name print "He is %d inches tall" % height print "He is %d heavy" % weight print "Actually that's not too heavy" print "He has got %s eyes and %s hair" % (eyes, hair) print "His teeth is %s" %teeth print "If I add %d, %d and %d I get %d." %(age, height, weight, age + height + weight) conv_m_to_cm_fac = 100 heightInCm = height * conv_m_to_cm_fac print "Height in cm is %d" % heightInCm
79fa45f6cfbc4ee01acc8fee6ee3c241e485cff6
andelgado53/interviewProblems
/rotate_matrix.py
1,216
3.78125
4
# Problem from Cracking the Coding Interview. # Chapter 1 Strings and Arrays. # Given an image represented by an NxN matrix, Write a method to rotate the image by 90 degress. # Do it in place import pprint data = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] data1 = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] data2 = [ [1, 2], [3, 4] ] def rotate_matrix(matrix): layers = len(matrix) // 2 for layer in range(layers): start = layer end = len(matrix[0]) - 1 - layer offset = 0 while start < end: temp = matrix[layer][start] matrix[layer][start] = matrix[end - offset][start - offset] matrix[end - offset][start - offset] = matrix[end][end - offset] matrix[end][end - offset] = matrix[layer + offset][end] matrix[layer + offset][end] = temp start += 1 offset += 1 return matrix pprint.pprint(data) pprint.pprint(rotate_matrix(data)) print('******************') pprint.pprint(data1) pprint.pprint(rotate_matrix(data1)) print('******************') pprint.pprint(data2) pprint.pprint(rotate_matrix(data2))
537f298da91e383462bfdef4a62b46350af35431
StBogdan/PythonWork
/Leetcode/987.py
1,538
4.0625
4
from collections import defaultdict, deque from typing import List # Name: Vertical Order Traversal of a Binary Tree # Link: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ # Method: Traverse graph, store seen in a per-column dict, build output from dict # Time: O(n * log(n)) # Space: O(n) # Difficulty: Hard class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: cols = defaultdict(lambda: defaultdict(list)) min_col, max_col = 0, 0 queue = deque() queue.append((root, 0, 0)) while queue: # BFS traversal node, row, col = queue.popleft() # Keep track of width min_col = min(col, min_col) max_col = max(col, max_col) cols[col][row].append(node.val) print( f"Looking at val {node.val=} at {row=} {col=}, " f"now know of {cols[col]}" ) # Add children if node.left: queue.append((node.left, row + 1, col - 1)) if node.right: queue.append((node.right, row + 1, col + 1)) ans = [] for col in range(min_col, max_col + 1): col_vals = [] for row_list in cols[col].values(): col_vals += sorted(row_list) ans.append(col_vals) return ans
957333cfdb9e24e97bc134d329a4214143324eab
dannymulligan/Project_Euler.net
/Prob_132/prob_132a.py
3,819
3.796875
4
#!/usr/bin/python # coding=utf-8 # # Project Euler.net Problem 132 # # Determining the first forty prime factors of a very large repunit. # # A number consisting entirely of ones is called a repunit. We shall # define R(k) to be a repunit of length k. # # For example, R(10) = 1111111111 = 11 x 41 x 271 x 9091, and the sum # of these prime factors is 9414. # # Find the sum of the first forty prime factors of R(10^9). # # Solved ??/??/10 # ?? problems solved # Position #??? on level ? import sys LIMIT_PRIME = 20000 prime_table = [1]*LIMIT_PRIME # table of largest factor primes = [] prime_mods = [] def digits_in (n): if (n < 0): print "N is < 0" sys.exit() elif (n < 10): return 1 elif (n < 100): return 2 elif (n < 1000): return 3 elif (n < 10000): return 4 elif (n < 100000): return 5 elif (n < 1000000): return 6 elif (n < 10000000): return 7 elif (n < 100000000): return 8 elif (n < 1000000000): return 9 else: print "N is too large" sys.exit() def divisible (n, r_len): # Maximum integer is 2,147,483,647, which is 10 digits # We're going to deal with 9 digits at a time (r, num) = (r_len-9, 111111111) num %= n num_len = digits_in(num) # Keep dividing num by n and adding digits at the right until no more digits to add while (r > 0): shift = 9 - num_len if (shift > r): shift = r if (shift == 1): (r, num) = (r-1, num*10 + 1 ) elif (shift == 2): (r, num) = (r-2, num*100 + 11 ) elif (shift == 3): (r, num) = (r-3, num*1000 + 111 ) elif (shift == 4): (r, num) = (r-4, num*10000 + 1111 ) elif (shift == 5): (r, num) = (r-5, num*100000 + 11111 ) elif (shift == 6): (r, num) = (r-6, num*1000000 + 111111 ) elif (shift == 7): (r, num) = (r-7, num*10000000 + 1111111 ) elif (shift == 8): (r, num) = (r-8, num*100000000 + 11111111) num = num % n num_len = digits_in(num) if (num == 0): return True return False def calculate_primes(): i = 2 while (i < (LIMIT_PRIME/2)): if (prime_table[i] == 1): primes.append(i) j = i*2 while (j < LIMIT_PRIME): prime_table[j] = i j += i i += 1 while (i < LIMIT_PRIME): if (prime_table[i] == 1): primes.append(i) i += 1 def calculate_divisors(): for p in primes: n = 1 r = 0 for i in range(2,1000): n = n*10 + 1 n = (n % p) if (n == 0): r = i break elif (n == 1): r = i-1 break elif (n == 11): r = i-2 break if (r != 0): print "{0} is a divisor of R({1})".format(p, r) prime_mods.append((p,r)) calculate_primes() print "There are", len(primes), "primes less than", LIMIT_PRIME #print "primes =", primes calculate_divisors() # R(10) = 1111111111 = 11 x 41 x 271 x 9091, sum = 9414 SIZE = 1000000000 prime_count = 0 div_count = 0 answer = 0 for (n,r) in prime_mods: prime_count += 1 print "Testing prime({0}) = {1}".format(prime_count, n) s = SIZE if (r != 0): s = s % r if divisible(n,s): div_count += 1 answer += n print " R({0}) is divisible by prime({1}) which is {2}, {3} divisors fround".format(SIZE, prime_count, n, div_count) if (div_count == 20): print "Answer =", answer, "div_count =", div_count sys.exit() print "Answer =", answer, "div_count =", div_count # # Find the sum of the first forty prime factors of R(10^9).
412550a5985b669219a9b01aa5e23fa743823392
mithrandil444/Make1.2.3
/wachtwoord.py
4,088
4.375
4
#!/usr/bin/env python """ This is a python script that generates a random password or a password of your choice bron : https://pynative.com/python-generate-random-string/ """ # IMPORTS import random, string __author__ = "Sven De Visscher" __email__ = "sven.devisscher@student.kdg.be" __status__ = "Finished" # Variable possible_characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ+=-!<>_?." def main(): while True: keuze = input("Do you want to choose your type of password? Yes of No :\n") # Asks if you want a random password or not if keuze in ('Yes', 'No'): if keuze == 'Yes': password_length = input("Type here the amount of characters of your password: ") # Asks the length of your password try: yourchoice = input( """1 - punctuation only\n2 - Numbers\n3 - Uppercase letters\n4 - Undercase only\n5 - Combo\n""") # Gives you 4 choices if yourchoice == '1': characters = string.punctuation pw = "".join(random.choice(characters) for i in range(int(password_length))) print(pw) # If you choose 1 then your password will exists only of characters with the chosen password length elif yourchoice == '2': numbers = string.digits pw = ''.join(random.choice(numbers) for i in range(int(password_length))) print(pw) # If you choose 2 then your password will exists only of numbers with the chosen password length elif yourchoice == '3': capital_letters = string.ascii_uppercase pw = "".join(random.choice(capital_letters) for i in range(int(password_length))) print(pw) # If you choose 2 then your password will exists only of capital letters with # the chosen password length elif yourchoice == '4': lowercase = string.ascii_lowercase pw = ''.join(random.choice(lowercase ) for i in range(int(password_length))) print(pw) # If you choose 4 then your password will exists only of lowercase letters # with the chosen password length elif yourchoice == '5': lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase numbers = string.digits characters = string.punctuation pw = ''.join(random.choice(lowercase + uppercase + numbers + characters) for i in range(int(password_length))) print(pw) # If you choose 5 then your password will exists of a combo of letters,numbers and characters # with the chosen password length else: print("ERROR choose a number from 1 to 4 ") # If your input is not 1,2,3 or 4 then it will give an error except ValueError: print(" Please enter a Number") # If your input is not a number then it will give an error elif keuze == 'No': password_length = 20 random_character_list = [random.choice(possible_characters) for i in range(password_length)] random_password = "".join(random_character_list) print(random_password) # If your choice is No then it will give you a random password that has a password length of 20 characters else: print("ERROR : typ Yes of No") # If you type something else then it will give you an error en shut down. break if __name__ == '__main__': # code to execute if called from command-line main()
78f15b41936f23feda24840fe514fc405a018f0d
Panda3D-public-projects-archive/pandacamp
/Demos and Tests/Tests/18-vars.py
514
3.875
4
from Panda import * # This is how you make a button on the screen b = button("Hit me", P2(-0.8, .6)) # This is a value that you can access from reaction code v = var(0) # 0 is the initial value # This is a reaction that will add 1 to v def bump(w, x): v.add(1) # When the button clicks, bump up v react(b, bump) # Show the value of v text(v) # Add a reaction to lbp that subtracts 2 from v # Use v.sub to do this # Add another button that multiplies v by 2 # Add a clock that adds 1 to v every second start()
4c3938543f625425f0d6ac81885c3276a34a011b
Dhanya1234/python-assignment-3
/assignment 3_quadratic equation.py
405
4.0625
4
from math import sqare print("quadratic function :(a*x^2)+b*x+c") a=float(input("a:")) a=float(input("a:")) b=float(input("b:")) c=float(input("c:")) r=b^2-4*a*c if(r>0): num_roots=2 x1=(((-b)+sqrt(r))/(2*a)) x2=(((-b)-sqrt(r))/(2*a)) print("there are 2 roots:"%fand%f %(x1,x2) elif(r==0): num_roots=1 x=(-b)/2*a print("there is 1 root :",x) else: num_roots=0 print(" no roots ,discriminant<0")
74ca40157c352e04ee0e90de2859112091e49ef9
morita657/Algorithms
/Leetcode_solutions/Increasing Triplet Subsequence.py
743
3.5
4
class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ small = float('inf') big = float('inf') for n in nums: if n <= small: small = n elif n <= big: big = n else: return True return False class Solution: def increasingTriplet(self, nums: List[int]) -> bool: res = [] for n in nums: index = bisect.bisect_left(res, n) if index == len(res): res.append(n) else: res[index] = n if len(res) == 3: return True return False
72104950bcc21244dc7fa23884845fb6bdc9fbca
FatbardhKadriu/Permutations-of-a-given-letters-list-with-Python
/permutations.py
735
3.53125
4
from itertools import permutations from nltk.corpus import wordnet from nltk.corpus import words list_of_letters = [] number_of_letters = int(input('How many letters are in total: ')) for i in range(0, number_of_letters): list_of_letters.append(input('Write char' + str(i+1) + str(": "))) no_of_perm = int(input('Write length of permutations: ')) perm = permutations(list_of_letters, no_of_perm) new_list = [] for i in list(perm): new_list.append("".join(i)) print('Possible words are listed below: \n') print('===================================') for i in range(len(new_list)): if(wordnet.synsets(new_list[i]) or new_list[i] in words.words()): print(new_list[i]) print('===================================')
01cb6ebb97347d44a4f57db379c23e53529c11b8
anbansal/Python-for-Everybody
/Ch4-Functions/exerciseEndOfChp1.py
453
3.890625
4
def computepay(hours,rate): multiplier = 1.0 if hours > 40: multiplier = 1.5 pay = multiplier * hours * rate print("Pay: ", round(pay, 2), "$") promt = "Please enter hours: " try: hours = float(input(promt)) except: print("Please enter hours in numeric!") quit(0) promt = "Please enter rate: " try: rate = float(input(promt)) except: print("Please enter rate in numeric!") quit(0) computepay(hours,rate)
216ce81ab9282b393cb370d0166d6501bb8214ea
rizkyprilian/purwadhika-datascience-0804
/Module1-PythonProgramming/map.py
2,046
3.828125
4
# def times2(num) : # return num * 2 # listNum = [ 1, 2, 3, 4, 5] # listNum = list(map(times2, listNum)) #diconvert jadi list dari map object # print(listNum) # listNum = [ 1, 2, 3, 4, 5] # listNum = list(map(lambda z: z * 2 if z <3 else z/2, listNum)) #lambda comprehension baby yeaaah! # print(listNum) # def genap(num) : # return num % 2 == 0 # listNum = [ 1, 2, 3, 4, 5] # listNum = list(filter(genap, listNum)) # print(listNum) # listNum = [ 1, 2, 3, 4, 5] # listNum = list(filter(lambda num: num % 2 == 0, listNum)) # print(listNum) # listKata = ['Merdeka','Hello','Hellos','Sohib','Kari ayam'] # print(listKata) # while(True): # searchText = input('Text Search: ') # # for kataTest in listKata: # # print('{} --> {}'.format(kataTest.lower(), kataTest.lower().index(searchText.lower()))) # print(list(filter(lambda kata: searchText.lower() in kata.lower(),listKata))) # listNum = [1,2,3,4,5] # def filterList(function, listContainer): # # filteredList = [] # # for item in listContainer: # # if function(item): # # filteredList.append(item) # # return filteredList # return [item for item in listContainer if function(item)] # print(filterList(lambda num: num%2 == 0, listNum)) # def mapList(function,listContainer): # # mappedList = [] # # for item in listContainer: # # mappedList.append(function(item)) # # return mappedList # return [function(item) for item in listContainer] # print(mapList(lambda num: num*2, listNum)) # text = 'pok ame ame belalang kupu kupu siang makan nasi kalau malam minum susu' # splittedText = text.split() # print(list()) # sum_triangular_numbers(5) # [1] # 2 [3] # 4 5 [6] # 7 8 9 [10] # 11 12 13 [14] # sum of each last part of the triangle is 35 def generateNumbersList(numOfRow): zeList = [] for x in range(numOfRow): for y in range(x+1): zeList.append() return zeList print(generateNumbersList(5)) # 1,2,4,7,11 # 1+0 = 1 # 1+1 = 2 # 2+2 = 4 # 4+3 = 7
a575302082d07055b0eaa0acf39fe8820eb05637
DeepAQ/Python-Statistics
/Exercise3/10.py
920
3.84375
4
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' import math from scipy.stats import t from log_api import log class Solution(): def solve(self): d = t.ppf(0.05, 24) sv = (7.73 - 8) / 0.77 * math.sqrt(25) con = sv > d return [24, round(sv, 2), con] ''' New York is known as "the city that never sleeps". A random sample of 25 New Yorkers were asked how much sleep they get per night. Statistical summaries of these data are shown below. Do these data provide strong evidence that New Yorkers sleep less than 8 hours per night on average? Null-hypothesis is H0: u=8, and alpha is 0.05 n mean stand-variance min max 25 7.73 0.77 6.17 9.78 Extra: (1) If you were to construct a 90% confidence interval that corresponded to this hypothesis test, would you expect 8 hours to be in the interval? Explain your reasoning. ''' log(Solution().solve())
a45c88aa1fcec8a382b9844424f0048886d7fd3f
EmanuelYano/python3
/Aula 7/aula_7_ex4.py
121
3.53125
4
#!/usr/bin/env python3 #-*- coding:utf-8 -*- n = int(input()) i = 0 while i < n: r = 2 ** i print(r) i += 1 exit(0)
a7d0bcba7013147a3866fe02bb95c7808d1e2203
RadovanTomik/Sudoku_solver
/solver.py
2,352
4.03125
4
example_board = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] def print_board(board): """Printout a board""" for row in range(len(board)): if row % 3 == 0: print(" | - - - - - - - - - - - - | ") for column in range(len(board[0])): if column % 3 == 0: print(" | ", end="") if column == 8: print(str(board[row][column]) + " | ") else: print(str(board[row][column]) + " ", end="") print(" | - - - - - - - - - - - - |") def find_empty(board): """Find all the empty spaces a.k.a. 0""" for row in range(len(board)): for column in range(len(board[0])): if board[row][column] == 0: return row, column return None def valid(board, number, position): """Check the validity of the board""" # Check the same row for column in range(len(board[0])): if board[position[0]][column] == number and position[1] != column: return False # Check the same column for row in range(len(board)): if board[row][position[1]] == number and position[0] != row: return False # Check the square square_x = position[1] // 3 square_y = position[0] // 3 for row in range(square_y * 3, square_y * 3 + 3): for column in range(square_x * 3, square_x * 3 + 3): if board[row][column] == number and (row,column) != position: return False return True def solve(board): """Recursive algorithm""" # Checks if there are any more empty spaces, if not then solved empty = find_empty(board) if not empty: return True else: row, column = empty # Try all possible numbers, if valid replace the 0 for number in range(1,10): if valid(board, number, (row, column)): board[row][column] = number # Recursive calling if solve(board): return True # If stuck then take a step back board[row][column] = 0 return False
bf9488fa06ffe73102f26d68576940b8a205bbff
Damdesb/python_fundamental
/02_basic_datatypes/2_strings/02_09_vowel.py
543
4.25
4
''' Write a script that prints the total number of vowels that are used in a user-inputted string. CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel in the string and print a count for each of them? ''' #get a sentence from user (sentence) sentence = set(input("write a sentence : ")) vowels = set('aeiou') numb_vowels = (vowels & sentence) print((len(numb_vowels)), ("vowels in this sentence")) print(numb_vowels) for vowels in sentence: enumerate(vowels) print(vowels)
c150e4835e485fc8f0e1d319902927d51c700d38
emilycheera/coding-challenges
/selection_sort.py
324
3.75
4
def selection_sort(nums): for i in range(len(nums)): min_index = i for j in range(i + 1, len(nums)): if nums[j] < nums[min_index]: min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums print(selection_sort([44, 5, 3, 7, 5, 6, 3, 4]))
3cb80c92ca041466cf54a1f755b5dcf1e6afc746
tomerguttman/leet-sol
/py-sol/ValidParentheses.py
549
4.03125
4
class Solution: def isValid(self, input_string): parentheses_stack = [] my_dict = {'(':')','[':']','{':'}'} for parentheses in input_string: if parentheses in my_dict: parentheses_stack.append(my_dict[parentheses]) else: #closing bracket if len(parentheses_stack) == 0 or parentheses_stack.pop() != parentheses: return False if len(parentheses_stack) == 0: return True else: return False
0148f74e50eba683faa64af6133ad38c7011ed28
WISDEM/LandBOSSE
/landbosse/tests/model/test_DevelopmentCost.py
3,189
3.796875
4
from unittest import TestCase import pandas as pd from landbosse.model import DevelopmentCost class TestDevelopmentCost(TestCase): def setUp(self): """ This setUp() method executes before each test. It creates an instance attribute, self.instance, that refers to a DevelopmentCost instance under test. input_dict is the dictionary of inputs values that configures that instance. This is just a default dictionary. Methods that test behavior of specific variables customize the relevant key/value pairs. The key site_facility_building_area_df is set to None here. The dataframe is read from the csv in the site_facility tests below. """ self.input_dict = dict() self.input_dict['development_materials_cost_usd'] = 10000 self.input_dict['development_labor_cost_usd'] = 10000 self.input_dict['development_equipment_cost_usd'] = 10000 self.input_dict['development_mobilization_cost_usd'] = 10000 self.input_dict['development_other_cost_usd'] = 10000 self.project_name = 'project 1' self.output_dict = dict() def test_DevelopmentCostModule(self): """ Black box test to check whether module is ran successfully or not """ run_DevelopmentCost = DevelopmentCost(input_dict=self.input_dict, output_dict=self.output_dict, project_name=self.project_name) trial_run = run_DevelopmentCost.run_module() if trial_run[0] == 0 : print('\n\n================== MODULE EXECUTION SUCCESS =========================\n') print(' DevelopmentCost module ran successfully. See the list of inputs' '\n and outputs below used by the module in its calculations:') print( '\n=====================================================================\n') elif trial_run[0] == 1 : print('\n\n====================================== MODULE EXECUTION FAILURE ======================================\n') print(' > DevelopmentCost module failed to run successfully. Error detected: ',trial_run[1] , '\n > Scroll below to see detailed information about error encountered.' '\n > See the list of inputs below used by the module in its calculations:') print('\n========================================================================================================\n') print('\nGiven below is the set of inputs fed into DevelopmentCost module:\n') for key, value in self.input_dict.items(): if isinstance(value, pd.DataFrame): print(key, ':\n', value) else: print(key, ':', value) if trial_run[0] == 0: # Only print outputs if module ran successfully. print('\nGiven below is the set of outputs calculated by the DevelopmentCost module:\n') for key, value in self.output_dict.items(): if isinstance(value, pd.DataFrame): print('\nNow printing DataFrame ->', key, ':\n', value) else: print(key, ':', value)
774fffafe7a086b816012007a0a80d2fd6de4e9e
codingcerebrum/codewars-codes
/Kata/countConnectivityComponent.py
2,464
4.09375
4
# The following figure shows a cell grid with 6 cells (2 rows by 3 columns), each cell separated from the others by walls: # +--+--+--+ # | | | | # +--+--+--+ # | | | | # +--+--+--+ # This grid has 6 connectivity components of size 1. We can describe the size and number of connectivity components by the # list [(1, 6)], since there are 6 components of size 1. # If we tear down a couple of walls, we obtain: # +--+--+--+ # | | | # + +--+--+ # | | | | # +--+--+--+ # , which has two connectivity components of size 2 and two connectivity components of size 1. The size and number of connectivity # components is described by the list [(2, 2), (1, 2)]. # Given the following grid: # +--+--+--+ # | | | # + +--+--+ # | | | # +--+--+--+ # we have the connectivity components described by [(4, 1), (1, 2)]. # Your job is to define a function components(grid) that takes as argument a string representing a grid like in the above # pictures and returns a list describing the size and number of the connectivity components. The list should be sorted in # descending order by the size of the connectivity components. The grid may have any number of rows and columns. # Note: The grid is always rectangular and will have all its outer walls. Only inner walls may be missing. The + are # considered bearing pillars, and are always present. def components(grid): compsize = [] rowele = [] result = [] grid = grid.split('\n') grid = grid[1:len(grid)-1] rows = len(grid) - 1 cols = int((len(grid[0]) - 2)/2) - 1 flag=1 for i in range(0,rows+1,2): compnest = [flag] ele = 1 flag += 1 for j in range(3,len(grid[0]) + 1,3): if(grid[i][j] != '|'): compnest.append(flag) flag += 1 else: compsize.append(compnest) ele += 1 compnest = [flag] flag+=1 rowele.append(ele-1) print(rowele) newres = [] # for i in range(1,rows,2): # flag = 1 # for j in range(1,len(grid[0]),3): # if(grid[i][j] == '-'): # print('there') # else: # newres.append(result[i-1] + result[i+rowele[i-1]]) # if(flag >= len(grid[i-1])): return compsize # Driver code s = '''+--+--+--+ | | | | + +--+--+ | | | +--+--+--+''' print(components(s))
b096f33302afc860050b17b776b86a97d2992709
aanantt/Python-DataStructure
/Queue.py
506
3.859375
4
class Queue: def __init__(self): self.llist = [] def push(self, key): self.llist.insert(0, key) def pop(self): return self.llist.pop() def isEmpty(self): return self.llist[0] def reverse(self): self.llist = self.llist[::-1] return self.llist def size(self): return len(self.llist) queue = Queue() queue.push(1) queue.push(2) queue.push(3) print(queue.pop()) print(queue.pop()) print(queue.pop()) print(queue.isEmpty())
0eb81c2c14773de15d8310f313e522f399d4f38d
ankit98040/TKINTER-JIS
/tut6new.py
831
3.609375
4
from tkinter import * def getvals(): print(f"The value of username is {uservalue.get()}") print(f"The value of password is {passvalue.get()}") root = Tk() root.geometry("655x333") f1 = Frame(root, borderwidth = 6, bg = "grey", relief = SUNKEN, padx = 90) f1.pack(side = TOP, anchor = "nw", fill = X) user = Label(f1, text="Username",pady= 30) password = Label(f1, text="Password", pady= 30) user.grid() password.grid(row=1) # Variable classes in tkinter # BooleanVar, DoubleVar, IntVar, StringVar uservalue = StringVar() passvalue = StringVar() userentry = Entry(f1, textvariable = uservalue) passentry = Entry(f1, textvariable = passvalue) userentry.grid(row=0, column=1) passentry.grid(row=1, column=1) Button(f1, text="Submit", command=getvals, bg='red').grid() root.mainloop()
dba45441dbfd6d7cd34211dc5f5d4eebbed87926
tysonpond/lending-club-risk
/data_dictionary.py
865
3.515625
4
# Constructing a lookup for meaning of columns import pandas as pd df_desc = pd.read_excel("LCDataDictionary.xlsx", nrows = 151) df_desc["LoanStatNew"] = df_desc["LoanStatNew"].apply(lambda x: x.rstrip()) # some cells have trailing whitespace df_desc["LoanStatNew"] = df_desc["LoanStatNew"].replace({'verified_status_joint':'verification_status_joint'}) # match name in df desc = {stat:description for stat,description in zip(df_desc["LoanStatNew"], df_desc["Description"])} if __name__ == "__main__": # example print(desc["acc_now_delinq"]) # checking to make sure columns and descriptions match 1-to-1 df = pd.read_csv("train.csv") print(set(desc.keys()).difference(set(df.columns.values))) # keys in desc which do not have a match in df print(set(df.columns.values).difference(set(desc.keys()))) # keys (columns) in df which do not have a match in desc
e6388896b49da860a134eb4f2774c360b1ced322
mivicms/c2py
/19.py
1,843
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -* # 题目:对10个数进行排序 # ___________________________________________________________________ # 程序分析:可以利用选择法,即从后9个比较过程中,选择一个最小的与第一个 # 元素交换,下次类推,即用第二个元素与后8个进行比较,并进行交换。 # 程序源代码: # #define N 10 # main() # {int i,j,min,tem,a[N]; # /*input data*/ # printf(“please input ten num:\n”); # for(i=0;i<N;i++) # { # printf(“a[%d]=”,i); # scanf(“%d”,&a);} # printf(“\n”); # for(i=0;i<N;i++) # printf(“%5d”,a); # printf(“\n”); # /*sort ten num*/ # for(i=0;i<N-1;i++) # {min=i; # for(j=i+1;j<N;j++) # if(a[min]>a[j]) min=j; # tem=a; # a=a[min]; # a[min]=tem; # } # /*output data*/ # printf(“After sorted \n”); # for(i=0;i<N;i++) # printf(“%5d”,a); # } def main(): n=10 print("please input ten num:\n") a = raw_input() #a = "45 326 22 52 741 63 44 52 154 1" a = a.split(" ") for i in xrange(0,n): print('%5s '%a[i]), for i in xrange(0,n): min = i for j in xrange(i+1,n): if int(a[min])>int(a[j]): #min = j tem = a[j] a[j]=a[min] a[min] = tem print("\nAfter sorted ") for i in xrange(0,n): print("%5s "%a[i]), main() #define N 10 # main() # {int i,j,min,tem,a[N]; # /*input data*/ # printf(“\n”); # for(i=0;i<N;i++) # printf(“%5d”,a); # printf(“\n”); # /*sort ten num*/ # for(i=0;i<N-1;i++) # {min=i; # for(j=i+1;j<N;j++) # if(a[min]>a[j]) min=j; # tem=a; # a=a[min]; # a[min]=tem; # } # /*output data*/ # printf(“After sorted \n”); # for(i=0;i<N;i++) # printf(“%5d”,a); # }
f0ef3429a55f926d811d53599d245bf1ffe1e6cb
N3UN3R/data_preparation
/ENetGetterNew.py
1,888
3.6875
4
import json import csv def get_meter_id_to_zipcode_dict(file): """ function that reads in 'AssetListe.json and returns a python dictionary with all meterIds matched to zipcodes""" with open(file, 'r') as json_data: payload = json.load(json_data) meter_ids_to_zipcodes = {} for household in payload['data']: meter_ids_to_zipcodes[household['meterId']] = int(household['location']['zip']) return meter_ids_to_zipcodes def get_ENetData(file, matched_meterIDs_to_zipcode): """ Function that returns all entrys of a csv-file from ene't GmbH This file contains informations like netcosts, konzessionskosten, and more matched to zipcodes. This function receives the meterIds matched to zipcodes from get_meter_id_to_zipcode_dict() it returns a dictionary where meterIds are matched to the entrys from the csv-file """ # getting Data out of ene't Data from csv file with open(file, 'r') as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=';') rows = [dict(d) for d in csv_reader] households_with_Enet_Data = {} # comparing zipcodes from meter_id_list and ENet Data data = [] for row in rows: for meterId, zip in matched_meterIDs_to_zipcode.items(): zipcode = zip if float(zipcode) == float(row['PLZ']): data.append(zipcode) households_with_Enet_Data[meterId] = row return households_with_Enet_Data def main(): matched_meterIDs_to_zipcode = get_meter_id_to_zipcode_dict('AssetListe.json') matched_MeterIDS_to_EnetData = get_ENetData('NetzpreiseCSV.csv', matched_meterIDs_to_zipcode) #print(matched_MeterIDS_to_EnetData) if __name__ == '__main__': main()
91faf0114d1338e8c11479fb3e4e06c1db444ad4
ubiswal/DataStructures
/tst/algos/test_graph_problems.py
2,231
3.515625
4
import unittest from lib.algos.graph_problems import * from lib.ds.bst import Bst class TestSiblingTree(unittest.TestCase): def setUp(self): self.tree = BinaryTree(5) self.tree.left = BinaryTree(10) self.tree.right = BinaryTree(20) self.tree.left.left = BinaryTree(30) self.tree.right.left = BinaryTree(40) self.tree.right.right = BinaryTree(50) self.adj_list = { "A": [("B", 10), ("C", 3)], "B": [("C", 1), ("D", 2)], "C": [("B", 4), ("D", 8), ("E", 2)], "D": [("E", 7), ], "E": [("D", 9)] } self.bst = Bst(50) self.bst.left = Bst(25) self.bst.left.left = Bst(12) self.bst.left.right = Bst(35) self.bst.left.right.left = Bst(33) self.bst.left.right.left.right = Bst(34) self.bst.left.right.left.left = Bst(32) self.bst.right = Bst(100) self.bst.right.right = Bst(150) self.bst.right.left = Bst(75) self.bst.right.left.left = Bst(60) self.bst.right.left.left.right = Bst(65) self.bst.right.left.left.right.right = Bst(66) self.bst.right.left.right = Bst(80) self.bst.right.left.right.left = Bst(77) def test_sibling_ptr(self): sibling_ptr(self.tree) self.assertEquals(20, self.tree.left.sibling.val) self.assertEquals(40, self.tree.left.left.sibling.val) self.assertEquals(50, self.tree.right.left.sibling.val) def test_dijkstra(self): expected_distances = { "A": 0, "B": 7, "C": 3, "D": 9, "E": 5 } self.assertEquals(dijkstra(self.adj_list, "A"), expected_distances) def test_bellman_ford(self): expected_distances = { "A": 0, "B": 7, "C": 3, "D": 9, "E": 5 } self.assertEquals(bellman_ford(self.adj_list, "A"), expected_distances) def test_smaller_closest(self): self.assertEqual(50, find_closest_smaller(self.bst, 56)) self.assertEqual(60, find_closest_smaller(self.bst, 62)) self.assertEqual(35, find_closest_smaller(self.bst, 36))
fc8ac5a4bd70babb89c80573e18a539f489737ff
valentinavera/python-course
/introduction/programa8.py
168
3.875
4
# ciclos rango = range(5) # for i in rango: # print(i) # fibonacci = [0, 1, 1, 2, 3, 5] # for j in fibonacci: # print(j) a = 5 while a < 10: print(a) a += 1
5ed4ebf0f9b095222117525acf12b4226123a028
jashidsany/Learning-Python
/Codecademy Lesson 5 Loops/LA5.10_Review.py
220
3.75
4
single_digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] squares = [] for digit in single_digits: print(digit) squares.append(digit**2) print(squares) cubes = [digit**3 for digit in single_digits] print(cubes)
4a7cca8d21d44261e88f0e5d20a834203566e129
ckloppers/PythonTraining
/exercises/day1/wordslast.py
108
3.78125
4
sentence = raw_input("Sentence: ") sentenceList = sentence.split(' ') print 'Last word: ', sentenceList[-1]
8c41ee1352854c33b77cbd1045f013ad4616a6c2
aj28293/dsp
/python/q5_datetime.py
958
3.84375
4
# Hint: use Google to find python function ####a) from datetime import datetime date_start = '01-02-2013' date_stop = '07-28-2015' def difference_in_days(date_start, date_stop): date_format = "%m%d%Y" date1 = datetime.strptime(date_start, date_format) date2 = datetime.strptime(date_stop, date_format) days = date2 - date1 return days.days date_start = '12312013' date_stop = '05282015' def difference_in_days(date_start, date_stop): date_format = "%m%d%Y" date1 = datetime.strptime(date_start, date_format) date2 = datetime.strptime(date_stop, date_format) days = date2 - date1 return days.days ####c) date_start = '15-Jan-1994' date_stop = '14-Jul-2015' def difference_in_days(date_start, date_stop): date_format = "%d-%b-%Y" date1 = datetime.strptime(date_start, date_format) date2 = datetime.strptime(date_stop, date_format) days = date2 - date1 return days.days
f770744f4b78addf3c1dc2a300d8b76712bf296f
paulkirow/Study
/shortest-disance.py
3,610
3.53125
4
import heapq import sys class Solution: def shortestDistance(self, grid: [[int]]): buildings = [] num_rows = len(grid) num_cols = len(grid[0]) for row in range(len(grid)): for col in range(len(grid[row])): value = grid[row][col] if value == 1: buildings.append((row, col)) # return the distance to each building from given starting position def bfs(start, min_heap, visited): min_heap = [(0, start)] result = {b: sys.maxsize for b in buildings} visited = {} while len(min_heap) > 0: cur = heapq.heappop(min_heap) if cur in visited: break visited[cur[1]] = True row = cur[1][0] col = cur[1][1] value = grid[row][col] distance = cur[0] if value == 1: result[cur[1]] = distance if value == 0: # Push all 4 directions to heap left = (row, col - 1) right = (row, col + 1) up = (row - 1, col) down = (row + 1, col) if col - 1 >= 0 and left not in visited: heapq.heappush(min_heap, (distance+1, left)) if col + 1 < num_cols and right not in visited: heapq.heappush(min_heap, (distance + 1, right)) if row - 1 >= 0 and up not in visited: heapq.heappush(min_heap, (distance + 1, up)) if row + 1 < num_rows and down not in visited: heapq.heappush(min_heap, (distance + 1, down)) #print(min_heap) return result min_dist = sys.maxsize min_cord = None for row in range(len(grid)): for col in range(len(grid[row])): if grid[row][col] != 1: dist = bfs((row, col)) dist_val = 0 for key in dist.values(): dist_val += key print(dist) print((row, col), dist_val) if dist_val < min_dist: min_dist = dist_val min_cord = (row,col) if min_dist >= sys.maxsize: return -1 return min_dist if __name__=="__main__": grid = [[1, 0, 2, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0]] grid = [[1]] grid = [[1, 1], [0, 1]] grid = [[2, 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 0, 1, 1, 0], [0, 1, 0, 1, 1, 2, 0, 0, 2, 0, 0, 2, 0, 2, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 2, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 2], [0, 0, 2, 2, 2, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0], [0, 2, 0, 2, 2, 2, 2, 1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 2, 2, 1], [0, 0, 2, 1, 2, 0, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 0, 2, 0], [0, 0, 0, 2, 1, 2, 0, 0, 2, 2, 2, 1, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 2, 2, 0, 0, 1, 1], [0, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 0, 0, 0, 0, 2, 0, 0], [2, 0, 2, 0, 0, 0, 2, 0, 2, 2, 0, 2, 0, 0, 2, 0, 0, 2, 1, 0, 0, 0, 2, 2, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 1, 0, 2, 0, 0, 2, 2, 0, 0, 2, 2]] solution = Solution() print(solution.shortestDistance(grid))
e700c5cda28b61ca20a3302efb203ad97f863521
bangalcat/Algorithms
/algorithm-python/boj/boj-11758.py
2,039
4.09375
4
from math import hypot # ccw 판단 class Vector: def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __eq__(self, other): return isinstance(other, Vector) and other.x == self.x and other.y == self.y def __add__(self, other): if isinstance(other, Vector): return Vector(self.x + other.x, self.y + other.y) elif isinstance(other, int): return Vector(self.x + other, self.y + other) def __sub__(self, other): if isinstance(other, Vector): return Vector(self.x - other.x, self.y - other.y) elif isinstance(other, int): return Vector(self.x - other, self.y - other) def __lt__(self, other): return self.x < other.x if self.x != other.x else self.y < other.y def __mul__(self, other): if isinstance(other, Vector): return Vector(self.x * other.x, self.y * other.y) elif isinstance(other, int): return Vector(self.x * other, self.y * other.y) # sqrt(x**2 + y**2) def norm(self): return hypot(self.x, self.y) def normalize(self): r = self.norm() return Vector(self.x / r, self.y / r) def dot(self, other) -> float: return self.x * other.x + self.y * other.y def cross(self, other) -> float: return self.x * other.y - self.y * other.x # 사영 def project(self, other): r = other.normalize() return r * r.dot(self) def ccw(a, b, o=Vector(0, 0)) -> float: """ :return: 1: ccw / -1 : cw / 0 : colline 점 o를 기준으로 벡터 b가 벡터 a의 반시계 방향이면 양수, 시계 방향이면 음수 평행이면 0 return o는 default 값으로 (0,0) """ return (a - o).cross(b - o) if __name__ == '__main__': plist = [Vector(*map(float, input().split(' '))) for _ in range(3)] k = ccw(plist[1],plist[2],plist[0]) if k > 0: print(1) elif k < 0: print(-1) else: print(0)
dbd782f5b7f5ac4d9e84036c89fd11c5a4cb2ebd
wpram45/PyProblems
/sirali_ekle.py
1,241
3.609375
4
class Node: def __init__(self,veri=None,sonraki=None): self.veri=veri self.sonraki=sonraki def __str__(self): return str(self.veri) def yazdir(root): while(root!=None): print(root) root=root.sonraki def sirali_ekle(root,veri): if root==None: yeni=Node() yeni.veri=veri yeni.sonraki=None return yeni else: if veri < root.veri: yeni=Node() yeni.veri=veri yeni.sonraki=root return yeni else: iter_im=root while( iter_im.sonraki!=None and iter_im.sonraki.veri < veri): iter_im=iter_im.sonraki yeni=Node() yeni.veri=veri yeni.sonraki=iter_im.sonraki iter_im.sonraki=yeni return root root=None root=sirali_ekle(root,50) root=sirali_ekle(root,20) root=sirali_ekle(root,100) root=sirali_ekle(root,1) root=sirali_ekle(root,200) root=sirali_ekle(root,30) yazdir(root)
c26c3af6c50710362c95ed0372e093713ab53b4e
thirdparty-core/pythonstest
/test01/list.py
2,107
4.03125
4
# -*- coding:utf-8 -*- # 列表的定义 # 有序集合 # 可以存放不同的类型的数据 # 放在中括号中,有逗号分隔 cars = ['c++', 'java', 'android', 'ios'] print(type(cars)) print(cars) numbers = list(range(10)) numbers1 = list(range(0, 10, 2)) print(numbers) print(numbers1) # 对数字列表的统计计算 print(min(numbers)) print(max(numbers)) print(sum(numbers)) # 列表推导 vec = [-4, -2, 0, 2, 4] print([x * 2 for x in vec]) # 求绝对值新列表 print([abs(x) for x in vec]) # 列表嵌套 vec1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print([num for x in vec1 for num in x]) # 列表的常规操作 print(vec[0]) print(vec[-1]) # 返回的是一个元素 print(vec[:2]) # 返回的是一个列表 # 由于列表是可变的,所以可以通过索引修改索引对应的值 vec[1] = 1000 print(vec) vec[1:3] = [10] print(vec) # [-4, 10, 2, 4] vec[1:3] = [10, 20, 30, 40] print(vec) # [-4, 10, 20, 30, 40, 4] # 列表的拼接 list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9, 10] list_total = list1 + list2 print(list_total) print(list1 * 3) # in 和 not in 关键字 print(1 in list1) print(10 not in list1) # 与字符串一样,没有会报错 # print(list1.index(100)) # 列表的修改 # 修改列表的元素值,单个或多个 # 添加一个元素 list = ['a', 'b', 'c', 'd', 'e'] list.append('fg') list.extend('gh') list.extend(['gh', 'ij', 'kl']) print(list) # 插入一个元素,如果是负数,且在负索引范围内,则在对应位置插入,如果没在索引范围内 # 则在头部插入 # 正索引也是同理 list.insert(-100, 'hello') print(list) # 删除元素 del list[1] list.remove('hello') print(list) # 排序 print(list.sort()) list2 = [1, 2, 34, 45, 23, 566, 3] # 排序,直接修改原列表,并没有生成新列表 # list2.sort() copy = list2.copy() copy.sort() print(copy) print(list2) # sorted 返回一个新列表 newList2 = sorted(list2) print(newList2) # 对列表的遍历 for temp in list2: print(temp) print("========while========") i = 0 while i < len(list2): print(list2[i]) i += 1
14cf463c571d7e6470a8d863eb59064ce54eefa1
NicolaiFinstadLarsen/thenewboston_Python_Programming_Tutorial
/e14_Gender.py
221
4.0625
4
def get_gender(sex="Unknown"): if sex is "M": sex = "Male" elif sex is "F": sex = "Female" return sex print(get_gender(input("What gender are you? Please type M, F or leave it blank: ")))
92ce41b7e48f2304d2a3c387401fec4ac44ca737
Shridhar2025/Calculator_tkinter
/Calculator_tkinter.py
2,245
3.984375
4
# import tkinter as tk # from tkinter import messagebox # mainWindow = tk.Tk() # mainWindow.title("Calculator") # # heading_label = tk.Label(mainWindow,text = "First Number") # heading_label.pack() # # name_field = tk.Entry(mainWindow) # name_field.pack() # # Subtitle_label = tk.Label(mainWindow,text = "Second Number") # Subtitle_label.pack() # # name_field1 = tk.Entry(mainWindow) # name_field1.pack() # # def Input(): # num1 =name_field.get() # num2 =name_field1.get() # try: # num1=int(num1) # num2=int(num2) # return num1,num2 # except ValueError: # if((len(name_field.get())==0)|(len(name_field1.get())==0)): # messagebox.showerror("Error","Please Enter A Value") # else: # messagebox.showerror("Error","Enter only Integer Value") # quit(0) # # # def add(): # num1,num2=Input() # res1 = num1+num2 # # print(res1) # Result_label.config(text="Result is:"+str(res1)) # def minus(): # num1, num2 = Input() # if(num1>num2): # res2 = num1-num2 # # print(res2) # Result_label.config(text="Result is:" + str(res2)) # else: # res2 = num2-num1 # # print(res2) # Result_label.config(text="Result is:" + str(res2)) # def multi(): # num1, num2 = Input() # res3 = num1*num2 # # print(res3) # Result_label.config(text="Result is:" + str(res3)) # def div(): # num1, num2 = Input() # if((num1==0)|(num2==0)): # # print("Not Valid") # messagebox.showerror("Error","Cannot Divide The Value By Zero") # else: # res4 = num1/num2 # # print(res4) # res4 = round(res4,2) # Result_label.config(text="Result is:"+str(res4)) # # # button = tk.Button(mainWindow,text="+",command=lambda :add()) # button.pack() # button1 = tk.Button(mainWindow,text="-",command=lambda :minus()) # button1.pack() # button2 = tk.Button(mainWindow,text="*",command=lambda :multi()) # button2.pack() # button3 = tk.Button(mainWindow,text="/",command=lambda :div()) # button3.pack() # # Result_label = tk.Label(mainWindow,text="Result is:") # Result_label.pack() # # mainWindow.mainloop()
2ecb4e8d2f30a4c6a99c512676ef59eba2ee3148
CoachEd/advent-of-code
/2021/day19/rotations.py
1,350
3.5625
4
from numpy import rot90, array from copy import copy, deepcopy def rotations24(polycube): """List all 24 rotations of the given 3d array""" def rotations4(polycube, axes): """List the four rotations of the given 3d array in the plane spanned by the given axes.""" for i in range(4): yield rot90(polycube, i, axes) # imagine shape is pointing in axis 0 (up) # 4 rotations about axis 0 yield from rotations4(polycube, (1,2)) # rotate 180 about axis 1, now shape is pointing down in axis 0 # 4 rotations about axis 0 yield from rotations4(rot90(polycube, 2, axes=(0,2)), (1,2)) # rotate 90 or 270 about axis 1, now shape is pointing in axis 2 # 8 rotations about axis 2 yield from rotations4(rot90(polycube, axes=(0,2)), (0,1)) yield from rotations4(rot90(polycube, -1, axes=(0,2)), (0,1)) # rotate about axis 2, now shape is pointing in axis 1 # 8 rotations about axis 1 yield from rotations4(rot90(polycube, axes=(0,1)), (0,2)) yield from rotations4(rot90(polycube, -1, axes=(0,1)), (0,2)) polycube = array( [[ [1, 1, 0], [1, 1, 0], [0, 0, 0] ], [[0, 0, 0], [1, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]) for x in rotations24(polycube): for y in x: for z in y: print(str(z))
7e1b41618a107343ca5be075b9576bf41c86f66d
MattGeske/ThunderstoneGameBuilder
/util/card_inserter.py
4,986
3.5
4
import csv import sqlite3 def main(): #for my own convenience/sanity - imports card data from a csv and adds it to the database #to prevent typos, it does not insert any new values in CardAttribute, CardClass, Requirement, or ThunderstoneSet csv_path = 'card_data.csv' db_path = '../assets/databases/cards.sqlite' db = sqlite3.connect(db_path) cursor = db.cursor() static_map = build_static_maps(cursor) card_insert_functions = { 'Dungeon': insert_dungeon_card, 'DungeonBoss': insert_dungeon_boss_card, 'Hero': insert_hero_card, 'Village': insert_village_card, } with open(csv_path) as csv_file: csv_reader = csv.reader(csv_file) header_row = csv_reader.next() for row_num, row in enumerate(csv_reader): card_data = {} for i, value in enumerate(row): header = header_row[i] card_data[header] = value category = card_data['Category'] if category in card_insert_functions: convert_names_to_ids(card_data, static_map) insert_function = card_insert_functions[category] insert_function(card_data, cursor) else: print "Unsupported category '%s' for row %s" % (category, row_num+1) cursor.close() db.commit() db.close() print 'Done.' def insert_dungeon_card(card_data, cursor): print 'Inserting Dungeon card: %s' % card_data unique_parameters = { 'cardType': card_data['CardType (D,DB)'], 'level': card_data['Level (D)'] or None, } insert_card('DungeonCard', card_data, unique_parameters, cursor) def insert_dungeon_boss_card(card_data, cursor): print 'Inserting DungeonBoss card: %s' % card_data unique_parameters = { 'cardType': card_data['CardType (D,DB)'], } insert_card('DungeonBossCard', card_data, unique_parameters, cursor) def insert_hero_card(card_data, cursor): print 'Inserting Hero card: %s' % card_data unique_parameters = { 'race': card_data['Race (H)'], 'strength': card_data['Strength (H)'], } insert_card('HeroCard', card_data, unique_parameters, cursor) def insert_village_card(card_data, cursor): print 'Inserting Village card: %s' % card_data unique_parameters = { 'goldValue': card_data['Gold Value (V)'] or None, 'goldCost': card_data['Gold Cost (V)'], 'weight': card_data['Weight (V)'] or None, } insert_card('VillageCard', card_data, unique_parameters, cursor) def insert_card(card_table_name, card_data, unique_parameters, cursor): card_name = card_data['Card Name'] unique_parameters['cardName'] = card_name unique_parameters['description'] = card_data['Description'] parameter_name_string = ', '.join(unique_parameters.keys()) parameter_string = ', '.join( ('?',)*len(unique_parameters) ) insert_sql = 'INSERT INTO %s (%s) values (%s)' % (card_table_name, parameter_name_string, parameter_string) cursor.execute(insert_sql, unique_parameters.values()) select_sql = 'SELECT _ID FROM %s where cardName = ?' % card_table_name cursor.execute(select_sql, (card_name,)) card_id = cursor.fetchone()[0] insert_relationships(card_table_name, card_id, card_data, cursor) def insert_relationships(card_table_name, card_id, card_data, cursor): schema_info = { 'Attributes': ('Card_CardAttribute', 'attributeId'), 'Classes': ('Card_CardClass', 'classId'), 'Requirements': ('Card_Requirement', 'requirementId'), 'Set Name': ('Card_ThunderstoneSet', 'setId'), } for field_name, (table_name, id_field_name) in schema_info.iteritems(): if card_data[field_name]: sql = 'INSERT INTO %s (cardTableName, cardId, %s) values (?, ?, ?)' % (table_name, id_field_name) param_list = [(card_table_name, card_id, id_value) for id_value in card_data[field_name]] cursor.executemany(sql, param_list) def build_static_maps(cursor): static_map = { 'Attributes': fetch_values('attributeName', 'CardAttribute', cursor), 'Classes': fetch_values('className', 'CardClass', cursor), 'Requirements': fetch_values('requirementName', 'Requirement', cursor), 'Set Name': fetch_values('setName', 'ThunderstoneSet', cursor) } return static_map def fetch_values(name_column, table_name, cursor): value_map = {} cursor.execute('SELECT _ID, %s from %s' % (name_column, table_name)) results = cursor.fetchall() for value_id, name in results: value_map[name] = value_id return value_map def convert_names_to_ids(card_data, static_map): for field_name in static_map: names = card_data.get(field_name) names = names.split(',') ids = [static_map[field_name][name] for name in names if name] card_data[field_name] = ids if __name__ == '__main__': main()
2762a3e6bef8eb5cf3b97761a8ba3d66f2950206
Elena-May/MIT-Problem-Sets
/ps1/ProblemSet1c.py
1,357
3.984375
4
#not currently working # runs infinitely semi_annual_raise = 0.07 invest_return = 0.04 down_payment = 0.25 house_cost = 1000000 currentsalary = int(input('Enter the starting salary: ')) monthlysalary = currentsalary/12 #Find the amount you need to save total_to_save = dream_house * down_payment print ('Total to save: ', total_to_save) numGuesses = 0 close_enough_high = total_to_save + 100 close_enough_low = total_to_save - 100 low = 1 high = 10000 # find the starting midpoint ans = (high + low)/2.0 calc = ((ans/10000) * currentsalary) * 36 #trying to work out best savings rate while calc > close_enough_high or calc < close_enough_low: if calc < close_enough_low: numGuesses += 1 print (numGuesses) # if calc is lower than close enough, then the mid point becomes the lowest low = ans ans = ((high + low)/10000)/2.0 calc =((ans/10000) * currentsalary) * 36 elif calc > close_enough_high: numGuesses += 1 print (numGuesses) # high = ans ans = ((high + low)/10000)/2.0 calc =((ans/10000) * currentsalary) * 36 if close_enough_low <= calc <= close_enough_high: print ('Best savings rate: ', ans) print ('Steps in bisection search: ', numGuesses)
a61e4545cc7c1f707fd6fee373883a875ff6a728
komaly/DailyProgrammer
/BankersAlgorithm/BankersAlgorithm.py
2,453
4.375
4
''' Implementation of Banker's Algorithm. Answer to Reddits Daily Programmer Challenge #349 ''' # Uses Bankers Algorithm to determine the order that the # processes should be selected based on the need dictionary # (indicating the remaining resources needed for each process), # allocation dictionary (containing the types of resources currently # allocated to a process), and the available string (indicating # the number of available resources of each type) def getProcessOrder(allocation, available, need): processes = [] while (len(processes) < len(allocation)): toDelete = [] for process, resource in need.items(): if int(resource) <= int(available): available = str(int(allocation[process]) + int(available)) processes.append(process) toDelete.append(resource) for k, v in need.copy().items(): if v in toDelete: del need[k] return processes # Retrieves the individual digits of a multi digit number def getDigitList(string): return [int(d) for d in string] # Creates the need matrix (indicating the remaining resources needed for each process) def getremainingResourcesPerProcess(allocation, max, available): need = {} for (m,mv), (a,av) in zip(max.items(), allocation.items()): key = "" maxes = getDigitList(mv) allocs = getDigitList(av) for d1, d2 in zip(maxes, allocs): key += str(d1 - d2) need[m] = key return need # Opens the file, creates the allocation dictionary, max dictionary (defining the # maximum demand for each process), and the available string, and uses this # information to implement Banker's algorithm def main(): file = open("input.txt", "r") line = file.readline() allocation = {} max = {} available = "" count = 0 while line: input = line.split() input[0] = input[0][1:] #remove bracket input[-1] = input[-1][0:-1] #remove bracket if (len(input) == 3): #available resources for num in input: available += num else: alloc = "" maxResources = "" for i in range(3): alloc += input[i] allocation[count] = alloc for k in range(3, 6): maxResources += input[k] max[count] = maxResources count += 1 line = file.readline() need = getremainingResourcesPerProcess(allocation, max, available) processList = getProcessOrder(allocation, available, need) prnt = "" for p in processList[:-1]: add = "P" + str(p) + ", " prnt += add add = "P" + str(processList[-1]) prnt += add print(prnt) main()
c711256e2ac783100f6b8be5d4563054a7e605f2
Jane11111/Leetcode2021
/234.py
666
3.625
4
# -*- coding: utf-8 -*- # @Time : 2021-03-05 10:56 # @Author : zxl # @FileName: 234.py # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ arr = [] p = head while p != None: arr.append(p.val) p = p.next i = 0 j = len(arr) - 1 while i < j: if arr[i] != arr[j]: return False i += 1 j -= 1 return True
a59a5c2d66b3f45b8f162f80b9c42017d96bdbff
hyewonm/py_lab2
/my_pkg/module1.py
198
3.765625
4
#!/usr/bin/python3 def result1(): binN = input('input binary number : ') num = int(binN, 2) print('OCT> ', format(num,'o')) print('DEX> ', num) print('HEX> ', format(num, 'X'))
49a37017e9435a3eb0db7a386be77f895ca619fa
YoussefAlTabei/GUI-python-simple-code-
/GUI.py
2,630
3.828125
4
from tkinter import * Y=Tk() Y.geometry('500x500+650-100') Y.title("3atf") Y.minsize(500,500) Y.maxsize(500,500) X=Tk() X.title("first window") X.geometry('500x500+150-100') Y.resizable(False,False) X.lift() #X.lower() X.state("normal") #X.iconify() zy X.state("iconic")) if X.state()=="normal": X.state("withdraw") # X.destroy() zy withdraw X.state("normal") #X.deiconify() zy normal Y.configure(bg='dodgerblue') X.configure(bg='dodgerblue') text=Label(Y, text="what's your name?")#to write something in the window command is : (Label) text.grid(column=0, row=0) def button1(): text2.configure(text="your amount is : 1k$") def button2(): res = "Welcome " + ins.get() + "!" #command (function y3ny) text.configure(text= res) def withdraw(): X.state("withdraw") def reviveB(): X.state("normal") def destroy(): Y.destroy() button = Button(X, text="Dispaly ur amount" , bg="aqua" , fg="black",command=button1)#to add a button command is : (Button) button.grid(column=8, row=0) text2=Label(X, text="welcome to your account !") text2.grid(column=0, row=0) ins=Entry(Y,width=15 )#zy input bs fl window bta5od data mn el user #state='disabled' (u can no longer write in the entry space) ins.grid(column=1, row=0) X.state("normal") button2 = Button(Y, text="confirm" , bg="aqua" , fg="black",command=button2) #button dy 2sm el el function ely fo2 button2.grid(column=17, row=0) text3=Label(X, text="--->") text3.grid(column=0, row=2) withdrawB=Button(X, text="click to kill the window " , bg="aqua" , fg="black", command=withdraw) withdrawB.grid(column=2, row=2) Y.lift() reviveB=Button(Y, text="click to revive the killed window " , bg="aqua" , fg="black", command=reviveB) reviveB.grid(column=3, row=2) text4=Label(Y, text="--->") text4.grid(column=0, row=2) from tkinter import messagebox def info(): messagebox.showinfo('info', 'this is an info message ') btn = Button(X,text='info', command=info) btn.grid(column=4,row=5) def warning(): messagebox.showwarning('warining', 'this is a warining message ') btn2 = Button(X,text='warining', command=warning) btn2.grid(column=0,row=5) #res = messagebox.askquestion('askQ','how r ya ?') res = messagebox.askyesno('Message title','Message content') res = messagebox.askyesnocancel('Message title','Message content') res = messagebox.askokcancel('Message title','Message content') res = messagebox.askretrycancel('Message title','Message content') ins.focus() exitB=Button(Y,text='Exit' , bg="aqua" , fg="black", command=destroy) exitB.grid(column=0 , row=4) X.mainloop() Y.mainloop()
ca7cf47111090039f05ae855cc4a20a1c087a477
rdguerrerom/pysurf
/pysurf/utils/design.py
544
3.625
4
from itertools import cycle from collections import namedtuple RGBColor = namedtuple("RGBColor", ["red", "green", "blue"]) # BLACK = RGBColor(0,0,0) BLUE = RGBColor(63/255, 81/255, 181/255) RED = RGBColor(253/255, 86/255, 33/255) YELLOW = RGBColor(255/255, 233/255, 75/255) GREEN = RGBColor(138/255, 193/255, 73/255) # colors = cycle([BLACK, BLUE, RED, GREEN, YELLOW])
c6e02957de761bc2c505c2b5c5a04b70bdc032a5
riyooraj/atchuthan
/at7.py
44
3.5625
4
x="Hello \n" y=int(input()) i=x*y print (i)
1422d7649ef0b22c1b2786769a5ece33cba11f6b
StefanTsvetanov/python_basics
/Hollyday.py
706
3.875
4
money_needed = float(input()) start_money = float(input()) total_days_counter = 0 spend_days_counter = 0 while True: action = input() money = float(input()) total_days_counter +=1 if action == "spend": start_money -= money if start_money <= 0: start_money = 0 spend_days_counter +=1 if spend_days_counter == 5: print(f"You can't save the money.\n {total_days_counter}") break elif action == "save": spend_days_counter = 0 start_money += money if start_money >= money_needed: print(f"You saved the money for {total_days_counter} days.") break
5300f794b61a4000ae20b49d5a9145513493929f
Sandy4321/twitter-sentiment-analysis-19
/experiments/classifiers/classifiers.py
4,449
3.59375
4
def tweet_formatting(directory): ##formats tweet for classification ##directory to the txt file containing a list of tweet texts (just a raw list with RT's removed) import nltk directory="D:\SEECS\Research & Projects\FYP\Codes\classifiers/jordansample_raw.txt" fp=open(directory,"r") tweetlist=fp.read() tweetlist=tweetlist.lower() ## converting from capital letters to lowercase tweetlist=eval(tweetlist) ## makes the data in list form for index in range(0,len(tweetlist)): tweetlist[index]=nltk.word_tokenize(tweetlist[index]) ##tokenization, also takes care of apostrophes porter=nltk.PorterStemmer() ##for porter stemming ind=0 while(ind<len(tweetlist[index])): tweetlist[index][ind]=porter.stem(tweetlist[index][ind]) ## itr=ind+1 ## while(itr<len(tweetlist[index])): ##for removing repetitive words and characters after tokenization (like "!")(might remove emphasis) ## if(tweetlist[index][itr]==tweetlist[index][ind]): ## del tweetlist[index][itr] ## itr-=1 ## itr+=1 ind+=1 return tweetlist ## should also work for removing some unwanted items like non-sensical short word tokens, blanks, brackets, colons, comas, periods, hyphens, apostrophe s etc ## these could be catered by removing any token of less than two characters unless it is some specific word like "no","ya","bi","hi","ah" ## this would be done at the location of removal of repetitive words def simple_classifier(tweetlist,dict_directory): ##Here tweetlist is the output of the above function ##dic_directory is the directory of the prior polarity dictionary tweetlist=tweet_formatting(1) ## formatted list from above code tweetlist_raw_direc="D:\SEECS\Research & Projects\FYP\Codes\classifiers/jordansample_raw.txt" ## original unformatted list (for emoticon comparison) ## dict_directory="D:\SEECS\Research & Projects\FYP\Codes\classifiers/dict_mpqa_stem_1.txt" ## dict_directory="D:\SEECS\Research & Projects\FYP\Codes\classifiers/dict_harvard_stem_1.txt" ## for this dictionary you can include strong/weak subjectivity or not. dict_directory="D:\SEECS\Research & Projects\FYP\Codes\classifiers/dict_combined_stem.txt" ## combined dictionary of mpqa and harvard dict_slang_direc="D:\SEECS\Research & Projects\FYP\Codes\classifiers/dict_slang.txt" ## dictionary contains polar (sentiment expressing) internet slangs. dict_emoticon_direc="D:\SEECS\Research & Projects\FYP\Codes\classifiers/dict_emoticon.txt" ## dictionary contains emoticons fp=open(dict_directory,"r") ## for word dictionary dictionary=fp.read() dictionary=eval(dictionary) fq=open(dict_slang_direc,"r") ## for slang dictionary dictionary_slang=fq.read() dictionary_slang=eval(dictionary_slang) fr=open(dict_emoticon_direc,"r") ## for emoticon dictionary dictionary_emoticon=fr.read() dictionary_emoticon=eval(dictionary_emoticon) fs=open(tweetlist_raw_direc,"r") ## for emoticon comparison tweetlist_raw=fs.read() tweetlist_raw=eval(tweetlist_raw) for index in range(0,len(tweetlist)): words=0 polarity=0 for key in dictionary.keys(): for ind in range(0,len(tweetlist[index])): if tweetlist[index][ind]==key and key!=0: ## The key!=0 part removes the effect of non-polar words in harvard dictionary polarity=polarity+dictionary[key] words+=1 for key_1 in dictionary_slang.keys(): for ind_1 in range(0,len(tweetlist[index])): if tweetlist[index][ind_1]==key_1 and key_1!=0: polarity=polarity+dictionary_slang[key_1] words+=1 for key_2 in dictionary_emoticon.keys(): if tweetlist_raw[index].find(key_2) != -1: polarity=polarity+dictionary_emoticon[key_2] words+=1 polarity=float(polarity) if (words != 0): polarity=polarity/words tweetlist[index].append(polarity) return tweetlist ##contains polarity in last element of each list, where each list is an individual tweet
dbdeec349e678aeef13f00698e8eecdf422e1a0f
FelipeGabrielAmado/Uri-Problems
/Iniciantes/1132.py
210
3.5625
4
soma=0 a=int(input()) b=int(input()) if (b>a): for n in range(a,(b+1)): if (n%13!=0): soma+=n if (a>b): for n in range(b,(a+1)): if (n%13!=0): soma+=n print(soma)
d9a6619165b5ab6e74b58a25c3fb33f2161ea202
willy900529/E94086181_lab1
/RemoveOutliers.py
1,088
4.40625
4
remove_number=int(input("Enter the number of smallest and largest values to remove:")) list1=[] #construct a list number_input_check=1 #if number_input_check=1,code keep run. if number_input_check=0,code stop while(number_input_check): number_input=input("Enter a value (q or Q to quit):") if(number_input=="q" or number_input=="Q"): #if user enter Q or q,number_input_check=0(code stop) number_input_check=0 else: list1.append(int(number_input)) #put number to list1 print("The original data:",list1) list1.sort() #put list1 to rearrange def remove_outliers(list,number): #the function can remove value list_out=list[0:number] #get list that user want to remove list_out.extend(list[len(list)-number:len(list)]) #get list that user want to remove return list_out list_outliers=remove_outliers(list1,remove_number) #call function del list1[len(list1)-remove_number:len(list1)] #remove it del list1[0:remove_number] #remove it print("The data with the outliers removed",list1) print("The outliers:",list_outliers)
d1588f2f8e4d17aa3656412383eb181800033b73
NasimNozarnejad/Data-Science-Machine-Learning
/Set2/Q3.py
860
3.546875
4
import sys import re n0=sys.argv[1] n1=sys.argv[2] n2=sys.argv[3] A=open(n0, 'r') data=A.read().upper() data1=re.findall(r"[\w]+",data) print(data1) WORD1=[] WORD2=[] LWORD1=len(n1) LWORD2=len(n2) def main(n0,n1,n2): num=0 for word in data1: num+=1 L=len(word) if word.startswith(n1.upper()): if L==LWORD1: WORD1.append(num) if word.startswith(n2.upper()): if L==LWORD2: WORD2.append(num) for i in WORD1: data1[i-1]=n2.upper() for j in WORD2: data1[j-1]=n1.upper() return WORD1, WORD2 print(main(n0,n1,n2)) print(data1) f=open(n0,"w") for k in data1: f.write(" " + k) f.close()
e693245b9fe91cad22791e590229fe907b007586
archananfs/Python_projects
/dictionary_gui.py
1,277
3.8125
4
from tkinter import * from PyDictionary import PyDictionary dictionary = PyDictionary() def dict_translate(): word = e1_value.get() list1.delete(0, END) meaning = dictionary.meaning(word) for key, value in meaning.items(): if type(value) == list: for line in value: list1.insert(END, line) else: list1.delete(0, END) list1.insert(END, value) def clear_text(): e1.delete(0,END) window = Tk() window.title("Welcome!") # Lables labl_1 = Label(window, text="Enter the Word") labl_1.grid(column=0, row=0) labl_2 = Label(window, text="Output") labl_2.grid(column=0, row=2) # entry e1_value = StringVar() e1 = Entry(window, textvariable = e1_value) e1.grid(column=0, row=1) # Buttons btn1 = Button(window, text="Meaning", command=dict_translate) btn1.grid(column=1, row=1) # Clear Button btn2 = Button(window, text="Clear", command=clear_text) btn2.grid(column=2, row=1) #Output window list1 = Listbox(window, height=10, width=100) list1.grid(column=0, row=3, rowspan=6, columnspan=2) #scrollbar sb1 = Scrollbar(window) sb1.grid(column=2, row=3, rowspan=6) list1.configure(yscrollcommand=sb1) sb1.configure(command=list1.yview) list1.bind('<<ListboxSelect>>') window.mainloop()
469634bf66c6fb700ecf733d2379264c3bdb5c9e
BrianSipple/Python-Algorithms
/Data_Structures/binary_heap.py
3,298
4.15625
4
class BinaryHeap(object): def __init__(self): self.items = [0] # Initialize with unused zero to enable integer division in later methods self.size = 0 def insert(self, item): self.items.append(item) self.size += 1 self.percolateUp(self.size) # Begin percolating at the end position def deleteMin(self): """ The min is at the root, so we know what to delete. But... to maintain both heap structure and heap order.... First, we will restore the root item by taking the last item in the list and moving it to the root position. Moving the last item maintains our heap structure property. However, we have probably destroyed the heap order property of our binary heap. Second, we will restore the heap order property by pushing the new root node down the tree to its proper position """ returnVal = self.items[1] self.items[1] = self.items[-1] self.items.pop() self.size -= 1 self.percolateDown(1) return returnVal def buildHeap(self, item_list): """ Build a heap from scratch with when given a list of items """ pos = len(item_list) // 2 # Because the heap is a complete binary tree, any nodes past the halfway point will be leaves and therefore have no children self.size = len(item_list) self.items = [0] + item_list[:] while (pos > 0): print(pos) self.percolateDown(pos) pos -= 1 ######################### HELPERS ########################### def percolateUp(self, pos): """ Helper for inserting items into the heap's tree structure in a way that allows us to regain the heap structure property by comparing the newly added item with its parent. If the newly added item is less than its parent, then we can swap the item with its parent """ # The parent of the current node can be computed # by dividing the index of the current node by 2. parent_pos = pos // 2 while parent_pos > 0: if self.items[pos] < self.items[parent_pos]: self.swap(parent_pos, pos) pos = parent_pos parent_pos = pos // 2 def percolateDown(self, pos): while (pos*2) <= self.size: # Compare and swap withe the lesser of the children min_child_pos = self.minChildPos(pos) if self.items[pos] > self.items[min_child_pos]: self.swap(pos, min_child_pos) pos = min_child_pos def minChildPos(self, pos): """ Returns the position of the min-valued child of a parent Right-child wins in a tie """ if pos * 2 + 1 > self.size: # The right child might not even exist if the end is the left return pos * 2 left_c = self.items[pos*2] right_c = self.items[pos*2 + 1] if left_c < right_c: return pos*2 else: return pos*2 + 1 def swap(self, item_pos, with_pos): self.items[item_pos], self.items[with_pos] = self.items[with_pos], self.items[item_pos]
8e9194dca33dd0bec33728d0142b62a48eb95968
JeckyOH/LeetCode
/88_Merge_Sorted_Array/Solution.py
763
3.890625
4
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ k = m + n -1 # k is next filled position in nums1 [k, m+n-1] contains merged sorted array in right place i = m - 1 # [0, i] contains elements in nums1 waiting to be compared j = n - 1 # [0, j] contains elements in nums2 waiting to be compared while j >= 0: if (i >= 0 and nums1[i] > nums2[j]): nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1
2928f3010e6518d472191c2887ea2e9efab1257e
abaldeg/EjerciciosPython
/Ejemplo de conversion de entero a lista.py
386
4.53125
5
# Python3 code to demonstrate # conversion of number to list of integers # using list comprehension # initializing number num = 2019 # printing number print ("The original number is " + str(num)) # using list comprehension # to convert number to list of integers res = [int(x) for x in str(num)] # printing result print ("The list from number is " + str(res))
7d9950725c4920723109378002da9fe13cbfe9cc
Haydz/Practice
/automate_boring_python/regexs/Character_classes.py
462
3.59375
4
import re """ Regex can use other classes than \d \w any letter, numeric digit, or underscore chaacter \s any space tab or new line character "space characters" """ xmasRegex = re.compile(r'\d+\s\w+') mo1 = xmasRegex.findall('12 dummers, 11 pipers, 10 lords, 9 ladies') print mo1 for x in mo1: print x """ Make own character classes """ vowelRegex = re.compile(r'[aeiouAEIOU]') mo2 = vowelRegex.findall('Robocop eats baby food. BABY FOOD.') print mo2
eb5bef529bc897cfa6a8ec490a9044ccb2efc6fa
cuimin07/cm_offer
/16.数值的整数次方.py
734
4
4
''' 实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。 示例 1: 输入: 2.00000, 10 输出: 1024.00000 示例 2: 输入: 2.10000, 3 输出: 9.26100 示例 3: 输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25 说明: -100.0 < x < 100.0 n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 ''' #答: class Solution: def myPow(self, x: float, n: int) -> float: # 迭代 if n < 0: x = 1 / x n = -n res = 1 while n: if n & 1: res *= x x *= x n >>= 1 return res
36f379f4a30c014a9020422889bf30d2fab024a3
AmineNeifer/holbertonschool-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
214
3.703125
4
#!/usr/bin/python3 def max_integer(my_list=[]): if len(my_list) == 0: return None maxi = my_list[0] for element in my_list: if maxi < element: maxi = element return maxi
4db35f1aff595b9c676ae91f20047f8f88ecd5cc
Mnrsrc/Python
/14-71_DeleteOperation.py
397
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 9 15:42:33 2019 @author: Munire """ import sqlite3 connection=sqlite3.connect("chinook.db") cursor= connection.execute("""Delete from genres where Name like '%&%' """) connection.commit() cursor2=connection.execute("""select Name from genres """) print("***Genres ***") for genre in cursor2: print(genre[0]) connection.close()
077f639687ae2a13eb238f30a3d007acd519c64f
KishorP6/PySample
/The Cargo arrangement.py
1,216
3.515625
4
##The Gocargo carriers have a pattern of arranging the cargos in the container. Given the length of edge of the container, print the cargo arrangement pattern in the container as shown in the sample IO. The base of the container is always a square. ## ##Note: The Cargo are of unit length. ## ##Input format : ## The input is an integer that corresponds to the side length of the container. ##Output Format: ## Output is the cargo arrangement pattern inside the container. ##Please refer to the sample output for formatting specifications. ## ##Sample Input 1: ##5 ##Sample Output 1: ######*++++ #####***+++ ####*****++ ###*******+ ##********* from sys import stdout import sys rows = int(input()) l = int ((2*rows)-1) star = str("*") hashs = str("#") pluss = str("+") ps = int(0) ph = int(0) ##for everyrow in range(s): for cargo in range(rows,0,-1): ph = cargo -1 ps = l-(2*ph) for index in range(ph): stdout.write(hashs) for index in range(ps): stdout.write(star) for index in range(ph): stdout.write(pluss) stdout.write("\n") ## for hashp in range (s-1): ## pattern[hashp] = "#" ## pattern [l-hashp] = "+" ## print (pattern)
22b50722a6e726a6dc88d61bd5010c898d1f0801
JulianNymark/stone-of-the-hearth
/soth/player.py
2,410
3.546875
4
from .card import * from .utility import * from .textstrings import * class Player: """A player in the game""" mana = 1 mana_used = 0 overload_now = 0 overload_next = 0 health = 30 armour = 0 damage = 0 attack = 0 def __init__(self, ct, npc=False): self.classtype = ct self.npc = npc self.adj = class_adjective[self.classtype] def feelings(self): if self.npc: print('your opponent feels ' + self.adj) else: print('you feel ' + self.adj) print() def display_choices(self): self.choice_count = 2 # end turn & hero power self.choice_count += len(self.hand.cards) # card hand # attackers print() print('1. end turn') print('2. become more {0}'.format(self.adj)) for i in range(len(self.hand.cards)): card = self.hand.cards[i] print('{0}. {1}'.format(i + 3, str(card))) def start_turn(self): self.mana_used = 0 if self.mana < 10: self.mana += 1 def end_turn(self): pass def mulligan(self): print("do you like these cards?\n") print("1. yes") print("2. no") choice = prompt_action(2) if choice == 1: handsize = len(self.hand.cards) self.deck.add(self.hand.cards) # deck your hand if not self.npc: print(self.text('mulligan')) del self.hand.cards[:] # empty your hand if not self.npc: print(self.text('shuffleDeck')) print() random.shuffle(self.deck.cards) self.deck.draw(self.hand, handsize) # re-draw hand def text(self, event): return text[event][self.classtype] def take_turn(self): if not self.npc: self.start_turn() while True: self.display_choices() choice = prompt_action(self.choice_count) if choice == 0: break elif choice == 1: self.mana_used += 2 print('you chant {0}... {0}...{0}!'.format(self.adj)) else: self.hand.play(choice - 2) self.end_turn() else: self.start_turn() # do random shit self.end_turn()
430f8494f4dceed4ef028b15f232cae5342ed623
karolkuba/python
/ćwiecznia/cw53.py
926
3.796875
4
# kwadraty liczb od 3 do 9 for i in range(3,10): print("%i ^ 2 = %i" % (i, i**2)) # wygeneruj tablice z przedzialami losowymi od 0 do 10 import random randomList = [] for i in range(10): randomList.append(random.randint(1,10)) print(randomList) #wyszukaj elementu z listy i zwróć jego indeks #jeżeli elementu nie ma na liście to zwróc -1 find = int(input("podaj liczbę z zakresu od 1 do 10")) #sprawdzamy czy element występuje w liście if(find not in randomList): print("element %i nie występuje na liscie" % find) else: for index, value in enumerate(randomList): if(value == find): print("element %i znajduje się na indeksie %i" % ( find, index)) break # sprawdź ile razy szukany element wystepuje na liście count = 0 for element in randomList: if(element == find): count += 1 print("element %i występuje w liście %i razy" % (find, count))
ecb3c2aa29cc645e011d5e599a0ed24eb1f983b2
PraneshASP/LeetCode-Solutions-2
/69 - Sqrt(x).py
817
3.9375
4
# Solution 1: Brute force # Runtime: O(sqrt(n)) class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ sqrt = 1 while sqrt*sqrt <= x: sqrt += 1 return sqrt-1 # Solution 2: Use Newton's iterative method to repeatively "guess" sqrt(n) # Say we want sqrt(4) # Guess: 4 # Improve our guess to (4+(4/4)) / 2 = 2.5 # Guess: 2.5 # Improve our guess to (2.5+(4/2.5)) / 2 = 2.05 # ... # We get to 2 very quickly # Runtime: O(logn) class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ # Use newton's iterative method delta = 0.0001 guess = x while guess**2 - x > delta: guess = (guess+(x/guess))/2.0 return int(guess)
85266e788d44082e223cd9c335a5f0f2f1d79de4
dabrygo/bmc
/src/Sample.py
1,517
3.9375
4
'''A collection of words for a user to guess''' import abc import re import Tokens import Word class Sample(abc.ABC): @abc.abstractmethod def text(self): pass @abc.abstractmethod def guess(self, guess): pass @abc.abstractmethod def hint(self): pass @abc.abstractmethod def shift(self): pass @abc.abstractmethod def key(self): pass @abc.abstractmethod def guessable(self): pass class Classic(Sample): def __init__(self, tokens): self._tokens = tokens def _current(self): for i, token in enumerate(self._tokens): if token.guessable(): return i, token raise Exception("No guessable tokens found") def text(self): statuses = [token.status() for token in self._tokens] return ''.join(statuses) def shift(self): tokens = self._tokens() index = self._index n = len(tokens) for i in range(index+1, n): token = tokens[i] if not isinstance(token, Word.Ignore): self._index = i return raise Exception("No next token found") def hint(self): index, current = self._current() current.hint() self._tokens[index] = current def guess(self, guess): index, current = self._current() self._tokens[index] = Word.Ignore(current.guess(guess)) def key(self): _, current = self._current() return current.key() def guessable(self): try: _, current = self._current() return current.guessable() except Exception: return False
99699995249aa20d64042a3e86407da6fd6883ec
JuDa-hku/ACM
/leetCode/95UniqueBinarySearchTreeII.py
1,530
3.609375
4
# Definition for a binary tree node. import copy class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {integer} n # @return {TreeNode[]} def generateTrees(self, n): nums = range(1,n+1,1) res = self.generateTreesHelp(nums) return res def generateTreesHelp(self, nums): res = [] if len(nums) == 0: return [None] if len(nums) == 1: res.append(TreeNode(nums[0])) return res for i in xrange(len(nums)): numTreeNode = TreeNode(nums[i]) tmpResLeft = self.generateTreesHelp(nums[:i]) tmpResRight = self.generateTreesHelp(nums[i+1:]) for left in tmpResLeft: for right in tmpResRight: tmpRes = copy.deepcopy(numTreeNode) tmpRes.left = left tmpRes.right = right res.append(tmpRes) return res def inorderTraversal(self, root): res,tmpLeft,tmpRight = [],[],[] if not root: return [] if root.left: tmpLeft = self.inorderTraversal(root.left) if root.right: tmpRight = self.inorderTraversal(root.right) res.extend(tmpLeft) res.append(root.val) res.extend(tmpRight) return res s= Solution() res = s.generateTrees(0) for root in res: print s.inorderTraversal(root)
4aef6c53756ff26927c98a486de3818608bc4fe0
yash-k9/Heart-Disease-Prediction
/model.py
5,089
3.703125
4
#!/usr/bin/env python # coding: utf-8 # //These are the following attributes present in the dataset # //dataset contains the information of the previous patient's health records. # # age: The person's age in years # # sex: The person's sex (1 = male, 0 = female) # # cp: The chest pain experienced (Value 0: typical angina, Value 1: atypical angina, Value 2: non-anginal pain, Value 3: asymptomatic) # # trestbps: The person's resting blood pressure (mm Hg on admission to the hospital) # # chol: The person's cholesterol measurement in mg/dl # # fbs: The person's fasting blood sugar (> 120 mg/dl, 1 = true; 0 = false) # # restecg: Resting electrocardiographic measurement (0 = normal, 1 = having ST-T wave abnormality, 2 = showing probable or definite left ventricular hypertrophy by Estes' criteria) # # thalach: The person's maximum heart rate achieved # # exang: Exercise induced angina (1 = yes; 0 = no) # # oldpeak: ST depression induced by exercise relative to rest ('ST' relates to positions on the ECG plot. See more here) # # slope: the slope of the peak exercise ST segment (Value 0: upsloping, Value 1: flat, Value 2: downsloping) # # ca: The number of major vessels (0-3) # # thal: A blood disorder called thalassemia (3 = normal; 6 = fixed defect; 7 = reversable defect) # # target: Heart disease (0 = no, 1 = yes) # # In[1]: import pandas as pd import seaborn as sns # first we read the data from the csv file. Pandas is the library for performing operations on the dataset. # describe and head are used to see the information. # In[ ]: df = pd.read_csv('heart.csv') df.describe() # In[3]: df.head() # In[4]: df.rename(columns = {'sex' : 'gender', 'cp' : 'chestPain', 'trestbps' : 'restBp', 'fbs' : 'bloodSugar', 'restecg' : 'restEcg', 'thalach' : 'maxHeart'}, inplace = True) # In[5]: df.describe() # The command drop is used to delete the column from the table. In the step pre-processing we remove the columns that are not needed. # In[6]: df = df.drop(['ca'], axis = 1) After Changing the data and values. These have to one hot encoded and pickled. # In[7]: df.rename(columns = {'oldpeak' : 'oldPeak', 'chol' : 'cholestrol'}, inplace = True) list(df.columns) # One hot encoding is a process by which categorical variables are converted into a form that could be provided to ML algorithms to do a better job in prediction. The categorical value represents the numerical value of the entry in the dataset. We have performed one hot encoding. # # EX: In the data set, male is represented as 1 and female as 0 # when we try to make a model that predict the chances because of this the model will be biased. # so we make separate columns for men and women # # Gender after one hot encoding Male Female # 1 1 0 # 0 0 1 # In[8]: ohe_col = ['chestPain', 'restEcg', 'slope', 'thal', 'gender'] df = pd.get_dummies(df, columns = ohe_col) print(df.columns) # In[9]: df.head(10) # In[10]: from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import joblib # Target in the data represents whether there the heart disease occured or not. # BY using this as a final result we train and test data # In[11]: X = df.drop(['target'], axis = 1) y = df['target'] # we have split data into two 80 for training 20 for testing # Random Forest Regessor is a algorithm for prediction. # # A random forest is an ensemble model that consists of many decision trees. Predictions are made by averaging the predictions of each decision tree. Or, to extend the analogy—much like a forest is a collection of trees, the random forest model is also a collection of decision tree models. This makes random forests a strong modeling technique that’s much more powerful than a single decision tree. # # # Each tree in a random forest is trained on the subset of data provided. The subset is obtained both with respect to rows and columns. This means each random forest tree is trained on a random data point sample, while at each decision node, a random set of features is considered for splitting. # In[12]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2) # In[13]: ml = RandomForestRegressor(n_estimators = 190, random_state = 0) ml.fit(X_train, y_train) y_pred = ml.predict(X_test) # In[14]: y_pred = y_pred > 0.53 # In[15]: y_pred # In[16]: newdf=pd.DataFrame(y_pred, columns=['Status']) newdf # In[17]: cols = list(X.columns.values) # In[18]: cols # In[19]: filename = 'allcol.pkl' joblib.dump(cols, filename) # In[20]: filename = 'finalmodel.pkl' joblib.dump(ml, filename) # In[24]: cm = confusion_matrix(y_test, y_pred.round()) sns.heatmap(cm, annot = True, cmap = 'Blues', cbar = False) # In[25]: acc = accuracy_score(y_test, y_pred.round()) print(acc) # In[ ]:
be7637d7ef6783ab1533e0dab430a94043dd6f67
kses1010/algorithm
/programmers/level2/carpet.py
350
3.59375
4
# 카펫 def solution(brown, yellow): x = 3 while x <= brown: y = (yellow / (x - 2)) + 2 if y == int(y): y = int(y) if (x + y - 2) * 2 == brown: return [max(x, y), min(x, y)] x += 1 print(solution(10, 2)) print(solution(14, 4)) print(solution(8, 1)) print(solution(24, 24))
6111c8382c179fd7eb060372b6a0e8624cdb16e1
Marou-Hub/myfirstproject
/learnPython/text3.py
307
3.75
4
# code wallet = 5000 computer_price = 50000 # le prix de l'ordinateur est inferieur a 1000€ if computer_price <= wallet or computer_price > 1000: print("L'achat est possible") wallet -= computer_price else: print("L'achat est impossible, vous n'avez que {}€".format(wallet)) print(wallet)
74eed9092b6f78115430fe3b0c777f19ec9bd7e0
shinobe179/atcoder
/kakomon_seisen/ruiji/abc082_b/ans.py
168
3.5
4
#!/home/shino/.pyenv/shims/python s = sorted(input().encode("utf-8")) t = sorted(input().encode("utf-8")) print(s, t) if s < t: print('Yes') exit() print('No')
987233e66925b03f18460e8155d7c7a6443f75bb
heroca/heroca
/ejercicio89.py
529
3.765625
4
sueldos=[] for x in range(5): valor=int(input("Ingrese sueldo:")) sueldos.append(valor) print("Lista sin ordenar") print(sueldos) for k in range(4): for x in range(4-k): if sueldos[x]>sueldos[x+1]: aux=sueldos[x] sueldos[x]=sueldos[x+1] sueldos[x+1]=aux """ for k in range(4): for x in range(4): if sueldos[x]>sueldos[x+1]: aux=sueldos[x] sueldos[x]=sueldos[x+1] sueldos[x+1]=aux """ print("Lista ordenada") print(sueldos)
2a6b4d1de001ed24cb3e4e7d9866aec321c3f2e1
jingriver/testPython
/Projects/mandelbrot_project/solution_5/mandelbrot/mandelbrot/model/core_numpy.py
1,497
3.8125
4
""" Core math functions to compute escape times for the Mandelbrot set. """ import numpy def mandelbrot_escape(x, y, n=100): """Mandelbrot set escape time algorithm for a given c = x + i*y coordinate. Return the number of iterations necessary to escape abouve a fixed threshold (4.0) by repeatedly applying the formula: z_0 = 0 z_n = z_{n-1} ^ 2 + c If the formula did not escape after `n` iterations, return -1 . Parameters ---------- x, y -- float Real and imaginary part of the complex number z. n -- integer Maximum number of iterations. """ z_x = 0 z_y = 0 times = numpy.empty(x.shape, dtype=int) times.fill(-1) for i in range(n): z_x, z_y = z_x**2 - z_y**2 + x, 2*z_x*z_y + y # If we are diverging, return the number of iterations. diverged = z_x**2 + z_y**2 >= 4.0 times[diverged & (times==-1)] = i return times def mandelbrot_grid(x_bounds, y_bounds, size=40): """ Return escape times at a grid of coordinates. Escape times are computed on a grid of size given by the `size` argument. x coordinates start at x_bounds[0] and end at x_bounds[1]. y coordinates start at y_bounds[0] and end at y_bounds[1]. """ escape_times = [] x = numpy.linspace(x_bounds[0], x_bounds[1], size) y = numpy.linspace(y_bounds[0], y_bounds[1], size) x_grid, y_grid = numpy.meshgrid(x,y) return mandelbrot_escape(x_grid, y_grid, 100)
05ad72db301f3c50cddf5b3c0a8e2dcef49f68a8
jlhuerlimann/Assignment_05
/CDInventory_for_review.py
3,398
3.6875
4
#-----------------------------------------------------------------------------# # Title: CDInventory.py # Desc: Script for Assignment 05, managing a CD inventory. # Change Log: (Who, When, What) # Jurg Huerlimann 2020-Aug-07, Created File from CDInventory_Starter.py script. # Jurg Huerlimann 2020-Aug-08 Changed functionality to use dictonary # Jurg Huerlimann 2020-Aug-09 Added functionality to load existing data from file # Jurg Huerlimann 2020-Aug-10 Added functionality to delete info from inventory # Jurg Huerlimann 2020-Aug-11 Added functionality to save inventory to file #-----------------------------------------------------------------------------# # Declared variables strChoice = '' # User input lstTbl = [] # list of lists to hold data dicRow = {} #list of data row strFileName = 'CDInventory.txt' # Name of data file objFile = None # file object # Get user Input, display menu options print('The Magic CD Inventory\n') while True: # 1. Display menu allowing the user to choose: print('[l] Load Inventory from file\n[a] Add CD\n[i] Display Current Inventory') print('[d] Delete CD from Inventory\n[s] Save Inventory to file\n[x] Exit') strChoice = input('l, a, i, d, s or x: ').lower() # convert choice to lower case at time of input print() if strChoice == 'x': # Exit the program if the user chooses so break if strChoice == 'l': # load inventory from file lstTbl.clear() objFile = open(strFileName, 'r') # open CDInventory.txt file for row in objFile: # read row by row and add to dictionary lstRow = row.strip().split(',') dicRow = {'id': int(lstRow[0]), 'title': lstRow[1], 'artist': lstRow[2]} lstTbl.append(dicRow) objFile.close() print('The inventory has been loaded, please use [i] to display it .') print() # break elif strChoice == 'a': # add CD info through questions and add to dictionary strID = input('Enter an ID: ') strTitle = input('Enter the CD\'s Title: ') strArtist = input('Enter the Artist\'s Name: ') intID = int(strID) dicRow = {'id': intID, 'title': strTitle, 'artist': strArtist} lstTbl.append(dicRow) elif strChoice == 'i': # Display the current inventory from in-memory print('ID, CD Title, Artist') for row in lstTbl: print(*row.values(), sep = ', ') elif strChoice == 'd': # functionality of deleting an entry delEntry = int(input('What line would you like to delete? PLease enter the ID number: ')) for entry in range(len(lstTbl)): if lstTbl[entry]['id'] == delEntry: del lstTbl[entry] print('Your entry has been deleted from inventory.') print() break elif strChoice == 's': # Save the data to a text file CDInventory.txt objFile = open(strFileName, 'w') # using w rewrites the content of the file for row in lstTbl: strRow = '' for item in row.values(): strRow += str(item) + ',' strRow = strRow[:-1] + '\n' objFile.write(strRow) objFile.close() else: print('Please choose either l, a, i, d, s or x!')
9c519feaa0d3347310bef113c633f21b5ace8e4e
mmskm/ForFuckSake
/employe.py
1,546
4
4
name = [] jobtile = [] age = [] salli = [] while 1 : print('--------------------------------------------------------') print('| 1 - Add a new employe \n| 2 - delete employe \n| 3 - searh employe \n| 4 - exit ') print('--------------------------------------------------------') something = int(input()) if something == 1 : name.append(input('The name of employe : ')) jobtile.append(input('The title : ')) age.append(input('The age : ')) salli.append(input('The salli : ')) if something == 2 : delempo = int(input('Enter the number of the employe : ')) delempo -= 1 name.pop(delempo) jobtile.pop(delempo) age.pop(delempo) salli.pop(delempo) if something == 3 : print('Two way to searh for employe \n 1 - searh by the number of the employe \n 2 - searh by name of the employe') thesearhway = int(input(' : ')) if thesearhway == 1 : X = int(input('Number of emp : ')) X -= 1 print( 'name of emp : ', name[X] ,'\ntitle : ' , jobtile[X] ,'\nage : ', age[X] ,'\nsali' , salli[X] ) elif thesearhway == 2 : nameofempoforsearh = str(input('the name of the employe : ')) nefs = name.index(nameofempoforsearh) print( 'name of emp : ', name[nefs] ,'\n title : ' , jobtile[nefs] ,'\n age : ', age[nefs] ,'\n sali' , salli[nefs] ) if something == 4 : break
e19eff1acba1c9b61383b49099dffe0b0e16a42a
meliassilva/pythonprograms
/Lab05_Mario.py
4,563
3.71875
4
# class Node: # def __init__(self, value, left=None, right=None): # self.left = left # self.right = right # self.value = value # self.count = 1 # def add(self, value): # if self.value == value: # self.count += 1 # elif value < self.value: # if self.left is None: # self.left = Node(value) # else: # self.left.add(value) # else: # if self.right is None: # self.right = Node(value) # else: # self.right.add(value) # def printTree(self): # if self.left is not None: # self.left.printTree() # print(str(self.value) + " " + str(self.count)) # if self.right is not None: # self.right.printTree() # def processFileContent(file): # words = [] # for line in file: # unprocessedWords = re.split(" ", line) # for word in unprocessedWords: # word = word.lower() # if word.isalpha(): # words.append(word) # return words # def processFile(): # file = open("text.txt", "r") # words = processFileContent(file) # file.close() # return words # def createTree(words): # if len(words) > 0: # tree = Node(words[0]) # for word in words: # tree.add(word) # return tree # else: # return None # def main(): # words = processFile() # tree = createTree(words) # tree.printTree() # from difflib import get_close_matches # def search(tree, word): # node = tree # depth = 0 # count = 0 # while True: # print(node.value) # depth += 1 # if node.value == word: # count = node.count # break # elif word < node.value: # node = node.left # elif word > node.value: # node = node.right # return depth, count # def main(): # print(search(tree, "a")) # wordCheck = raw_input( # "please enter the word you would like to check the spelling of: ") # with open("words.txt", "r") as f: # found = False # for line in f: # if line.strip() == wordCheck: # print('That is the correct spelling for ' + wordCheck) # found = True # break # if not found: # print(wordCheck + " is not in our dictionary") # from difflib import get_close_matches # with open('/usr/share/dict/words') as fin: # words = set(line.strip().lower() for line in fin) # testword = 'hlelo' # matches = get_close_matches(testword, words, n=5) # if testword == matches[0]: # print 'okay' # else: # print 'Not sure about:', testword # print 'options:', ', '.join(matches) # #Not sure about: hlelo # #options: helot, hello, leo, hollow, hillel # from benchmark import load_names # Sample code to download # import random # wordCheck = input( # "Please enter the word you would like to check the spelling of: ") # with open('words.txt', 'r') as f: # for line in f: # if wordCheck in line.split(): # print('That is the correct spelling for ' + wordCheck) # break # else: # print(wordCheck + " is not in our dictionary") # # Python program to read # # file word by word # # opening the text file # with open('GFG.txt', 'r') as file: # # reading each line # for line in file: # # reading each word # for word in line.split(): # # displaying the words # print(word) # # Return a list of names of some file # def load_names(path): # with open(path) as text_file: # return text_file.read().splitlines() # names = load_names('names.txt') # sorted_names = load_names('sorted_names.txt') # def find(elements, value): # while True: # random_element = random.choice(elements) # if random_element == value: # return random_element # def find_index(elements, value): # for index, element in enumerate(elements): # if element == value: # return index from benchmark import load_names # Sample code to download names = load_names('names.txt') index_by_name = { name: index for index, name in enumerate(names) } import math def find_index(elements, value): left, right = 0, len(elements) - 1 while left <= right: middle = (left + right) // 2 if math.isclose(elements[middle], value): return middle if elements[middle] < value: left = middle + 1 elif elements[middle] > value: right = middle - 1
de750071a423486605fefbe569ee2c429e9ef6c8
Shahrein/Python-Training-Projects
/larger_number2.py
227
4.15625
4
number1 = int(input("Enter the 1st number: ")) number2 = int(input("Enter the 2nd number: ")) if number1 >= number2: larger_number = number1 else: larger_number = number2 print("The larger number is: ", larger_number)
9fc1274e4c53ade205ccd889533374952413b0f2
ps9610/python-web-scrapper
/02-01/function.py
805
3.609375
4
#함수 만드는 방법 (파이썬은 함수를 define(정의)한다고 한다.) #1. function의 이름을 쓴다. | say_hello #2. function옆에 소괄호 | say_hello() #3. ()를 채우거나 비워두면 끝 #4. 함수를 정의할 땐 함수이름 앞에 def(함수를 정의한다는 뜻) #5. 함수 옆에 ⭐콜론⭐을 쓰고 body에 내용 입력 def say_hello(): print("hello") # 파이썬은 자바스크립트 함수 function blabla(){}처럼 괄호로 묶지 않고 #tab. space를 사용한 들여쓰기로 함수의 몸통을 결정한다. # = 들여쓰기 했다 = 함수임(들여쓰기 주의해서 쓰기) # 그리고 함수 소괄호 옆에 ⭐콜론⭐ 반드시 쓰기!! print("bye") say_hello() #>>>hello # bye
4db430dfc85cfd78dcfa3530d2090e919ee7d475
me6edi/Python_Practice
/F.Anisul Islam/5.program_User_input.py
309
4.125
4
#Getting User Input num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) result = num1 + num2 print("The sum is ", result) result = num1 - num2 print("The sum is ", result) result = num1 * num2 print("The sum is ", result) result = num1 ** num2 print("The sum is ", result)
1b62bf9ecb032caad9aa4b3f21477ede52ef0788
LaminarIR/framework
/helper/factors.py
616
3.859375
4
from fractions import gcd def lcm(a,b): """Compute least common multiplier of two numbers""" return a * b / gcd(a,b) def listgcd(l): """Compute the gcd of a list of numbers""" if len(l) == 0: return 0 elif len(l) == 1: return l[0] elif len(l) == 2: return gcd(l[0],l[1]) else: return gcd(l[0],listgcd(l[2:])) def listlcm(l): """Compute the gcd of a list of numbers""" if len(l) == 0: return 0 elif len(l) == 1: return l[0] elif len(l) == 2: return lcm(l[0],l[1]) else: return lcm(l[0],listlcm(l[2:]))
2520f77f618ec7a78bf38533c6d2c281d5e86170
HelloYeew/helloyeew-lab-computer-programming-i
/Inclass Program/6310545566_wk4ic_ex7.py
602
4.0625
4
def print_list(list): for x in list: print(x) def read_list(n): i = 1 listoutput = [] while i < n + 1: value = float(input(f"Enter value{i}: ")) listoutput.append(value) i += 1 return listoutput def compute_area_list(list1, list2): area_list = [] n = len(list1) for i in range(n): area = list1[i] * list2[i] area_list.append(area) return area_list n = int(input("Enter n: ")) print("Side 1:") list1 = read_list(n) print("Side 2:") list2 = read_list(n) a_list = compute_area_list(list1, list2) print_list(a_list)
be3b06e22d12ef6267c1f41d720a0a5d5ce09917
ken1286/Sorting
/src/iterative_sorting/iterative_sorting.py
2,307
4.09375
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for n in range(cur_index+1, len(arr)): if arr[n] < arr[smallest_index]: smallest_index = n arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] # TO-DO: swap return arr # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): arrayLen = len(arr) - 1 for n in range(0, arrayLen): if arr[n] > arr[n+1]: arr[n+1], arr[n] = arr[n], arr[n+1] for i in range(0, arrayLen - n): # loop through again and ignore end if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] return arr # STRETCH: implement the Count Sort function below arr = [3, 3, 3, 1, 1, 5] count = [0] * len(arr) def count_sort(arr, maximum=-1): # steps used: https://www.programiz.com/dsa/counting-sort # Find out the maximum element from the given array. max_element = 0 for i in arr: if i < 0: return "Error, negative numbers not allowed in Count Sort" if i > max_element: max_element = i # Initialize an array of length max+1 with all elements 0. This array is used for storing the count of the elements in the array. count_arr = [0] * (max_element+1) # Store the count of each element at their respective index in count array. print(count_arr) for n in arr: count_arr[n] += 1 # Store cumulative sum of the elements of the count array. for k in range(1, len(count_arr)): count_arr[k] += count_arr[k-1] # Find the index of each element of the original array in count array. output_arr = [0] * len(arr) b = len(arr) - 1 while b >= 0: # Look at value of arr[b] # Look at index equal to arr[b] in count_arr # Place value of arr[b] in index of arr equal to count_arr[arr[b]] # Subtract 1 from count_arr value for off by 1 output_arr[count_arr[arr[b]] - 1] = arr[b] count_arr[arr[b]] -= 1 b -= 1 return output_arr
8a2f06e6edfa5a9a9f6b00cfbe0fd5d48e6eafdd
VIKULBHA/Devopsbc
/Python/First project/Exercises/Functions.py
347
4
4
def my_function(): print('Hello from my function') # What is the syntax for function # def printme( str ): # "This prints a passed string into this function" # print(str) # return #Homework # Do your own search on how "while" works; # Create a simple app to convert temperatures; # Create a simple app that calculates body mass index
4ad775d2883c0cee32a697c167abf440ab91ebb1
YJL33/LeetCode
/current_session/python/809.py
2,324
4.03125
4
""" 809. Expressive Words Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo". For some given string S, a query word is stretchy - if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more. For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has size less than 3. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If S = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = S. Given a list of query words, return the number of words that are stretchy. Example: Input: S = "heeellooo" words = ["hello", "hi", "helo"] Output: 1 Explanation: We can extend "e" and "o" in the word "hello" to get "heeellooo". We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more. Notes: 0 <= len(S) <= 100. 0 <= len(words) <= 100. 0 <= len(words[i]) <= 100. S and all words in words consist only of lowercase letters Accepted 40.9K Submissions 86.6K """ class Solution(object): def expressiveWords(self, S, words): """ :type S: str :type words: List[str] :rtype: int """ res = 0 for w in words: res += 1 if self.check(S, w) else 0 return res # manaege 4 pointers, compare each unique letter # 2 as starting points, the other 2 as the end points of the consecutive part # compare the length # time: O(len(S)*len(words)) def check(self, S, W): i, j, i2, j2, n, m = 0, 0, 0, 0, len(S), len(W) while i < n and j < m: if S[i] != W[j]: return False while i2 < n and S[i2] == S[i]: i2 += 1 while j2 < m and W[j2] == W[j]: j2 += 1 if i2 - i != j2 - j and i2 - i < max(3, j2 - j): return False i, j = i2, j2 return i == n and j == m