blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2eb9bd5d43d8f5d466620d1aa525d3a92107a85e
e8johan/adventofcode2019
/2/2.py
1,188
3.71875
4
#/usr/bin/env python3 def processor(m): pc = 0 while True: if m[pc] == 1: m[m[pc+3]] = m[m[pc+1]] + m[m[pc+2]] elif m[pc] == 2: m[m[pc+3]] = m[m[pc+1]] * m[m[pc+2]] elif m[pc] == 99: break else: assert False, "Invalid op code at %s" % (pc) pc += 4 return m assert(processor([1, 0, 0, 0, 99]) == [2, 0, 0, 0, 99]) assert(processor([2, 3, 0, 3, 99]) == [2, 3, 0, 6, 99]) assert(processor([2, 4, 4, 5, 99, 0]) == [2, 4, 4, 5, 99, 9801]) assert(processor([1, 1, 1, 4, 99, 5, 6, 0, 99]) == [30, 1, 1, 4, 2, 5, 6, 0, 99]) memory = [] while True: try: line = input() if line == "": break for m in line.split(","): memory.append(int(m)) except ValueError: break except EOFError: break memory[1] = 12 memory[2] = 2 print("memory[0] (a): %s" % (processor(memory.copy())[0])) for noun in range(0,99): for verb in range(0,99): memory[1] = noun memory[2] = verb if processor(memory.copy())[0] == 19690720: print("Noun-verb (b): %s" % (noun*100 + verb)) exit(0)
f667314db55ae41cf0bac1f881e3fe1b8c6f73cc
Grigorov999/SoftUni-Python
/Python_fundamentals/course_chapters_excercises/RegEx/EX09_3_Find Occurences in text.py
166
3.859375
4
import re text = input().lower() target_word = input().lower() pattern = f"\\b{target_word}\\b" matches = re.findall(pattern, text) print(len(matches))
5da2845f9bca8a104478194e68ef3b69ab4426ef
coalastudy/python-datascrapping-code
/week4/stage1-2.py
937
3.515625
4
people = {'korean': 380, 'american': 42, 'japanese': 15, 'german': 26, 'french': 7, 'chinese': 213, 'canadian': 11} print(people.keys()) print(people.values()) print(people.items()) for p_item in people.items(): print('There are', p_item[1], p_item[0] + 's') chnInfos = {'하트시그널2': {'hit': 20000, 'like': 3800}, '미스터션샤인': {'hit': 18000, 'like': 3500}, '쇼미더머니7': {'hit': 25000, 'like': 2200}} print(chnInfos.keys()) print(chnInfos.values()) print(chnInfos.items()) for chn_info in chnInfos.items(): print(chn_info[0], '의 조회수는', chn_info[1]['hit'], '입니다.') # print('꽃보다할배' in chnInfos.keys()) # print('하트시그널2' in chnInfos.keys()) # ---- 네이버TV 예제에 응용하기 ---- # newchn = '꽃보다할배' # # if newchn in chnInfos.keys(): # print('처음 수집된 채널') # else: # print('이미 수집된 채널')
234ceac2e5ea146e47aca95a83b2a88c2b7a9d6c
9Brothers/Learn.Python
/11_if_elif_else.py
355
3.9375
4
# a = 1 # b = 1 # bol = b is a # if a is 2 : # a += 10 # print(a) notas = [ 10, 9, 8 ,9 ,5, 10, 7 ] for nota in notas : if nota >= 9 : print("Aluno nota {n} foi aprovado".format(n = nota)) elif nota >= 7 : print("Aluno nota {n} está de recuperacão".format(n = nota)) else : print("Aluno nota {n} foi reprovado".format(n = nota))
49d8efe5f23554002da731e6a159f2039feafd8e
edu-athensoft/stem1401python_student
/sj200116_python2/py200116/output_formatted_5.py
714
4.03125
4
""" positional arguments """ print("Hello {0}, your balance is {1:9.3f}".format("Adam",230.2346)) print("Hello {0}, your balance is {1:12.3f}".format("Adam",230.2346)) print("Hello {0}, your balance is {1:2.3f}".format("Adam",230.2346)) print("Hello {name}, your balance is {balance:9.3f}".format(name="Adam",balance=230.2346)) print("Hello {name}, your balance is {balance:9.2f}".format(name="Adam",balance=230.2346)) print() print("Hello {name:9s}, your balance is {balance:9.2f}".format(name="Printer",balance=230.23)) print("Hello {name:9s}, your balance is {balance:9.2f}".format(name="USB",balance=10.26)) print("Hello {name:9s}z, your balance is {balance:9.2f}".format(name="HP Laptop",balance=1000.56))
ba6db30c4230ee8f37bb953d50cd7df7da014477
Dgustavino/Python
/Taller_02/list&dict/dict.py
788
4.125
4
# un dictionario se define asi KEY:VALUE elemento = '02' dict_musica = { 'miKey': 1, 'key_2': elemento, 'key3': 3 } # print the OBJ dict print(dict_musica) # print a dictionary key:value for key in dict_musica: print(key, dict_musica[key]) # read specific key print(dict_musica['key_2']) # adding a new Key dict_musica['KEY4']=9 print(dict_musica) my_tuplet1 = 1,'manzana' my_tuplet2 = 2,'pera' # unpacking dict_frutas = dict([my_tuplet1,my_tuplet2]) print(dict_frutas) lista_duplicados = 1,2,2,3,3,4,5 lista_sin_duplicados = list(dict.fromkeys(lista_duplicados)) # un approach para remover duplicados de una tupleta usando composicion print(lista_sin_duplicados)
451479f94015c60d010a5fb4224264f2ca274e8d
gadodia/Algorithms
/algorithms/LinkedList/swapNodes.py
1,215
3.96875
4
''' Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. Time: O(n) Space: O(n) ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __str__(self): res = "" res += str(self.val) if self.next: res += "->" res += str(self.next) return res class Solution: def swap_nodes(self, head): if not head or not head.next: return head prev = head cur = head.next p = self.swap_nodes(cur.next) cur.next = prev prev.next = p return cur l = ListNode(1) l.next = ListNode(2) l.next.next = ListNode(3) l.next.next.next = ListNode(4) print(Solution().swap_nodes(l)) # 2->1->4->3 l = ListNode(1) l.next = ListNode(2) l.next.next = ListNode(3) l.next.next.next = ListNode(4) l.next.next.next.next = ListNode(5) l.next.next.next.next.next = ListNode(6) print(Solution().swap_nodes(l)) # 2->1->4->3->6->5
d28a5d12cb82856473359351db56a433bde0c82a
sfwarnock/python_programming
/chapter 5/exercise 5.3.py
873
3.96875
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 30 2018 @author: Scott Warnock """ # exercise 5.3 # # # A certain CS professor gives 100-point exams that are graded on the scale 90-100:A, 80-89:B, 70-79:C, # 60-69:D, <60:F. Write a program that accepts an exam score as an input and prints out the # correspondnig grade. def main(): # request score from user. score = eval(input("Enter your score on the exam: ")) for index in range(score): if score >= 90: index = 4 elif score >= 80: index = 3 elif score >= 70: index = 2 elif score >= 60: index = 1 elif score <= 59: index = 0 break grade = ['F', 'D', 'C', 'B', 'A'] print("Your letter grade on the exam is:", grade[index]) main()
a2eaee306d95c1b1c6ea9e80db7c131bc883323b
Deyber2000/holbertonschool-higher_level_programming
/0x0A-python-inheritance/0-lookup.py
297
3.546875
4
#!/usr/bin/python3 """Module for lookup()""" def lookup(obj): """Function that returns a list of available attributes and methods of an object Arguments: obj: the object to list attributes of Returns: list: list of all attributes """ return (dir(obj))
77466fe07182b9a647989887f510309eff80f9f1
imarban/algorithms
/python/algorithms/search_2d/search.py
872
3.609375
4
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not len(matrix) or not len(matrix[0]): return first = 0 last = len(matrix) * len(matrix[0]) - 1 found = False while first <= last and not found: half = (first + last) / 2 halfx = half / len(matrix[0]) halfy = half % len(matrix[0]) if matrix[halfx][halfy] == target: found = True else: if matrix[halfx][halfy] > target: last = half - 1 else: first = half + 1 return found a = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] print Solution().searchMatrix(a, 30)
97776a074bf18709b051ab90514c4d80318ac27d
m-e-l-u-h-a-n/Information-Technology-Workshop-I
/python assignments/assignment-1/3.py
228
3.640625
4
s=input() x1=s.find('not') x2=s.find('poor') """because according to example given for the question (if poor is followed by not) so third condition is applied""" if x1>0 and x2>0 and x1<x2: s=s[:x1]+'good'+s[x2+4:] print(s)
1299c3bba29a14f982d82ba930a6bf7a5c6a61a2
IchibanKanobee/MyProjects
/Python/classes/class_1.py
251
3.6875
4
class Person: def __init__(self): self.name = "Ara" self.age = 56 ''' def __init__(self, name, age): self.name = name self.age = age ''' def get_age(): return self.age def set_age(age): self.age = age p = Person() print (p.age)
475e55938f98e1b1b6d1e03bad6c9ef57a9e7e81
ITlearning/ROKA_Python
/2021_03/03_07/str.py
169
3.609375
4
# str() 함수를 사용해 숫자를 문자열로 변환하기 output_a = str(52) output_b = str(52.334) print(type(output_a), output_a) print(type(output_a), output_b)
fc63bd1a25a459e3b65d0d6be4e3ff681ac69d84
aaron0215/Projects
/Python/HW6/game21.py
2,037
4.0625
4
#Aaron Zhang #CS021 Green group #Lead user to input random number #Use accumulation to store the total number #In main function, divide number of user into two sections #Compare the numbers in each section and print result import random def main(): standard_value = 21 total_num_user=0 total_num_comp=0 start = get_response() p=True while p and start=='y' or start == 'Y': num_user,num_comp = roll_dice() total_num_user += num_user total_num_comp += num_comp print('Points:',total_num_user) if total_num_user >= standard_value: print("User's points:",total_num_user) print("Computer's points:",total_num_comp) if total_num_user == standard_value and total_num_comp != standard_value: print("User wins") elif total_num_user > standard_value and total_num_comp > standard_value: print("Tie Game!") elif total_num_user > standard_value and total_num_comp <= standard_value: print("Computer wins!") p=False else: start = get_response() if p and start == 'n' or start == 'N': print("User's points:",total_num_user) print("Computer's points:",total_num_comp) if total_num_user < standard_value and total_num_comp<= standard_value: if total_num_user > total_num_comp: print("User wins") elif total_num_user < total_num_comp: print("Computer wins") else: print("Tie Game!") elif total_num_user <= standard_value and total_num_comp > standard_value: print("User wins") def get_response(): start_game = input('Do you want to roll? ') return start_game def roll_dice(): minimun = 2 maximum = 12 num_user_input = random.randint(minimun,maximum) num_comp_input = random.randint(minimun,maximum) return num_user_input,num_comp_input main()
a75336d26533623a40d629356fca04e8466e0992
ebiacsan/URI-Online-Judge
/Python/URI 1097.py
500
3.65625
4
''' /* *Fazer um programa que apresente a sequencia conforme o exemplo abaixo. * Não tem entrada, mas a saida deve ser: * I=1 J=7 * I=1 J=6 * I=1 J=5 * I=3 J=9 * I=3 J=8 * I=3 J=7 * ... * I=9 J=15 * I=9 J=14 * I=9 J=13 */ ''' I, J,F,G = -1,5,4,3 for i in range (1,6): i=I+2 j=J+2 f=F+2 g=G+2 print('I=%d J=%d' %(i,j)) print('I=%d J=%d' %(i,f)) print('I=%d J=%d' %(i,g)) I=i J=j F=f G=g
bc7b2c6e6772ba9fd550d4bfb6c792e6877c0476
Ved005/project-euler-solutions
/code/squarefree_factors/sol_362.py
819
3.546875
4
# -*- coding: utf-8 -*- ''' File name: code\squarefree_factors\sol_362.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #362 :: Squarefree factors # # For more information see: # https://projecteuler.net/problem=362 # Problem Statement ''' Consider the number 54. 54 can be factored in 7 distinct ways into one or more factors larger than 1: 54, 2×27, 3×18, 6×9, 3×3×6, 2×3×9 and 2×3×3×3. If we require that the factors are all squarefree only two ways remain: 3×3×6 and 2×3×3×3. Let's call Fsf(n) the number of ways n can be factored into one or more squarefree factors larger than 1, so Fsf(54)=2. Let S(n) be ∑Fsf(k) for k=2 to n. S(100)=193. Find S(10 000 000 000). ''' # Solution # Solution Approach ''' '''
1e4f08b50852f6136a856388f1125b56454a4c2f
moddaser/hackerrank
/hackerrank-problem1.py
1,170
4
4
# HL machine learning: Normal Distribution #1 """ p(x<b) is calculated using the integral of a gaussian distribution from infinity to b. Infinity is approximated by a large number INFINITY, and DELTLA for the discrete integral is approximated by a small number. """ import math def arange(l, h, inc): """List of numbers from l to h with incremental value of inc""" num = int((h-l)/inc)+1 x = [] for i in range(0, num): x.append(l+inc*i) return x def normal_dis(x, sigma, mu): """Normal distribution calculated for list x, with standard deviation sigma and mean mu""" y = [] for i in range(0,len(x)): y.append(math.exp(-(x[i]-mu)**2/(2*sigma**2))/(sigma*math.sqrt(2*math.pi))) return y DELTA = 1e-3 # the increamental value for integral INFINITY = 1000 # p(x<40) x = arange(-INFINITY, 40, DELTA) y = normal_dis(x, 4, 30) print "%.3f" % (DELTA*sum(y)) # The integral is calculated by the sum of the discreted values # p(x>21) x = arange(21, INFINITY, DELTA) y = normal_dis(x, 4, 30) print "%.3f" % (DELTA*sum(y)) # p(30<x<35) x = arange(30, 35, DELTA) y = normal_dis(x, 4, 30) print "%.3f" % (DELTA*sum(y))
f9ffacd181c7fc240c06f2696a78b93f7e1e75a9
DiksonSantos/GeekUniversity_Python
/77_Debugando_Codigo_Com_PDB.py
2,314
3.984375
4
''' PDB -> Python Debigger ''' ''' def divide(A, B): print(f'Primeiro Termo={A} Segundo_Termo={B}') #Aqui o PRINT é uma maneira de debugar o Codigo. try: return float(A) / float(B) except(ValueError, TypeError, ZeroDivisionError): return 'Valores Inserido = Incorretos.' NUM1 = int(input("Primeiro Numero: ")) NUM2 = int(input("Segundo Numero: ")) Numero = divide(A=NUM1, B=NUM2) print(f'{Numero:.2f}') ''' # {Variavel_Resposta:.{1f} Sendo 1 o Numero de casas de pois da virgula. ''' #FORMAS MAIS PROFISSIONAIS DE SE FAZER O DEBUG USANDO O DEBUGGER: def divide(A, B): try: return float(A) / float(B) except(ValueError, TypeError, ZeroDivisionError): return 'Valores Inserido = Incorretos.' NUM1 = int(input("Primeiro Numero: ")) NUM2 = int(input("Segundo Numero: ")) Numero = divide(A=NUM1, B=NUM2) print(f'{Numero:.2f}') ''' # 1 EXEMPLO COM O PDB: #Precisamos importar a biblioteca PDB ''' Comandos do PDB: -> l = para listar onde estamos no codigo -> n = proxima linha -> p = Imprime variavel -> c = Continua a execução ''' ''' import pdb nome = 'Juma' Especie = 'Onça Pintada' #pdb.set_trace() Info = nome +' '+ Especie Abtat = 'Amazonia Brasileira' Conclusao = Info + ' Vive Em ' + Abtat print(Conclusao) ''' ''' # 2 EXEMPLO COM O PDB: nome = 'Juma' Especie = 'Onça Pintada' import pdb; pdb.set_trace() #Separamos com ; Para Dois comandos na mesma linha. Info = nome +' '+ Especie Abtat = 'Amazonia Brasileira' Conclusao = Info + ' Vive Em ' + Abtat print(Conclusao) # Este PDB é usado/testado na hora, e logo depois já é descartado. ''' ''' # 2 EXEMPLO COM O PDB: #A partir do Python 3.7 Não se usa mais o PDB, mas sim o BreackPoint nome = 'Juma' Especie = 'Onça Pintada' breakpoint() #AQUI AQUI -> Já cai la no PDB sem precisar importar Nada. import pdb; pdb.set_trace() #Separamos com ; Para Dois comandos na mesma linha. Info = nome +' '+ Especie Abtat = 'Amazonia Brasileira' Conclusao = Info + ' Vive Em ' + Abtat print(Conclusao) ''' def soma(l, n, p, c): #Nunca use variaveis assim. Prefira algo como Num1, Num2 etc ... return l+ n+ p+ c #Para evitar problemas. print(soma(1,3,5,7)) #Como neste caso se as variaveis tiverem o mesmo nome dos comandos do debug -> Utilize #... o comando P para imprimi-las antes.
0d0de21cf8f2f217bc5e9e4da6acdaf95605458d
ongsuwannoo/PSIT
/Sequence II.py
154
3.796875
4
''' Sequence II ''' def main(): ''' for loop ''' num = int(input()) for i in range(1, num+1): print(i*i+1-1, end=" ") main()
e0b0d74b0cee96bd1ce123bccac2dfb96f9d2e2e
Moustafa-Eid/Python-Programs
/Unit 3/String Manipulation Uses/ManipulationUsesEx1a.py
146
4.1875
4
entry = input ("Please enter a string: ") if entry.isalpha() == True: print ("It is only letters") else: print ("it is not only letters")
417429befced352711defd09e9208eb6363ae91f
soohyun-lee/python3
/python3-2.py
280
3.734375
4
h = float(input('키:')) w = float(input('체중:')) n = w / ((h * 0.01) ** 2) if n < 18.5: print('평균 이하입니다') elif 18.5 <= n < 25.0: print('표준입니다.') elif 25.0 <= n < 30.0: print('비만입니다.') else: print('고도 비만입니다.')
132fe8bc13781bdb55f8595dfb290739975cf078
aludvik/dna
/deque.py
1,644
3.515625
4
class Deque: class __Node: def __init__(self, data): self.prev = None self.next = None self.data = data def __init__(self): self.__front = None self.__back = None self.__size = 0 def push_front(self, data): n = Deque.__Node(data) if self.__front is None: self.__back = n else: n.next = self.__front self.__front.prev = n self.__front = n self.__size += 1 def pop_front(self): if self.__front is None: return None n = self.__front self.__size -= 1 self.__front = n.next if self.__front is None: self.__back = None else: self.__front.prev = None return n.data def peak_front(self): if self.__front is None: return None return self.__front.data def push_back(self, data): n = Deque.__Node(data) if self.__back is None: self.__front = n else: n.prev = self.__back self.__back.next = n self.__back = n self.__size += 1 def pop_back(self): if self.__back is None: return None n = self.__back self.__size -= 1 self.__back = n.prev if self.__back is None: self.__front = None else: self.__back.next = None return n.data def peak_back(self): if self.__back is None: return None return self.__back.data def size(self): return self.__size
9f5bace55828c1f64033b3bb5fc20e7065bc4ae2
Dkabiswa/python-practice
/sorting/quickSort.py
507
4.0625
4
# def quick_sort(list_a): # if len(list_a) <= 1: # return list_a # else: # pivot = list_a.pop() # less_than = [] # greater_than = [] # for item in list_a: # if item > pivot: # greater_than.append(item) # else: # less_than.append(item) # return quick_sort(less_than) + [pivot] + quick_sort(greater_than) # arr = [2, 8, 14, 21, 10, 4, 1] # print(f"array before sort {arr}") # quick_sort(arr) # print(f'sorted array is {arr}')
0c97749575a93fd773709a606525e14cd540655d
ecwu/SDWII
/python-cpr/6.py
599
4.0625
4
# Zhenghao Wu l630003054 MONTHS = 12 if __name__ == '__main__': days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] user_month, user_day, accumulate = (0, 0, 0) while user_month > MONTHS or user_month <= 0: user_month = int(input("Enter the month: ")) while user_day > days_in_month[user_month - 1] or user_day <= 0: user_day = int(input("Enter the day: ")) for i in range(user_month - 1): accumulate += days_in_month[i] accumulate += user_day print("%d/%d is the day number %d in the year" % (user_day, user_month, accumulate))
83e842ac9fb12159f3e09ddac7cb8889507ce728
saishg/codesnippets
/strings/look_and_say.py
747
3.6875
4
# Implement a function that outputs the Look and Say sequence: # 1 # 11 # 21 # 1211 # 111221 # 312211 # 13112221 # 1113213211 # 31131211131221 # 13211311123113112211 def look_and_say(input_str=None): if input_str is None: return '1' output_str = '' count = 0 last_char = '' for char in input_str: if char != last_char: if count: output_str += str(count) + last_char last_char = char count = 1 else: count += 1 if count: output_str += str(count) + last_char return output_str if __name__ == '__main__': result = look_and_say() for i in range(10): print result result = look_and_say(result)
e57353d90c9437ae4a3ab04ee07b000381846e90
shyamsaravanan/nexwave
/tuple_ex.py
266
3.515625
4
#tuple-class t1=tuple([10,20,30]) t2=(10,12.5,'python',['a','b'],(10,20)) print(t2) print(t2[1]) print(t2[-4:4]) print(t2[-4:4:+2]) i=t2.index('python') c=t2.count(12.5) print(i,c) T=(10,20) L=list(T) print('L=',L) l=[30,40] t=tuple(l) print('T=',t)
29c5b9799c176f2adfdceec0f4783da8389392c2
agk79/Python
/project_euler/problem_12/sol2.py
278
3.65625
4
def triangle_number_generator(): for n in range(1,1000000): yield n*(n+1)//2 def count_divisors(n): return sum([2 for i in range(1,int(n**0.5)+1) if n%i==0 and i*i != n]) print(next(i for i in triangle_number_generator() if count_divisors(i) > 500))
ce2f0118736e17a5b497e0e99b00e0836622603c
natejenson/AdventOfCode2016
/Day 2/day2.py
1,682
3.75
4
class Position: def __init__(self,x,y): self.x = x self.y = y class Keypad: def __init__(self, numbers): self.numbers = numbers def Number(self, pos): return self.numbers[pos.y][pos.x] def Move(self, startPos, direction): newPos = Position(startPos.x, startPos.y) if (direction == "U"): newPos.y -= 1 elif (direction == "D"): newPos.y += 1 elif (direction == "L"): newPos.x -= 1 elif (direction == "R"): newPos.x += 1 else: raise "invalid direction: " + str(direction) if ((newPos.x < 0 or newPos.x > len(self.numbers[0]) - 1) or newPos.y < 0 or newPos.y > len(self.numbers)-1): return startPos if (self.Number(newPos) == None): return startPos return newPos def getCode(keypad, startPos, directions): pos = startPos code = "" for directionSet in directions: for direction in directionSet: pos = keypad.Move(pos, direction) code += str(keypad.Number(pos)) return code def getDirections(): dirs = [] with open('day2-input.txt', 'r') as file: return file.read().splitlines() pos = Position(1,1) keypad = Keypad([[1,2,3],[4,5,6],[7,8,9]]) directions = getDirections() print("Part 1 - Code: ", getCode(keypad, pos, directions)) keypad = Keypad([[None, None, 1, None, None], [None, 2, 3, 4, None], [5,6,7,8,9], [None, "A", "B", "C", None], [None, None, "D", None, None]]) print("Part 2 - Code: ", getCode(keypad, pos, directions))
5dca6109eff7307a6a9d09f24ffb7cd4e073efbe
Harshhg/python_data_structures
/Hashing/check_common_substring.py
456
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Given two strings, determine if they share the common substring # Time complexity O(N) # In[3]: # Function that takes 2 strings as arguments def twoStrings(s1, s2): hash={} string="NO" for x in s1: hash[x]=1 for y in s2: if y in hash: string="YES" return string # In[8]: s1="HELLO" s2="WORLD" print(twoStrings(s1,s2)) # In[ ]: # stay Tuned :)
78136b26d22061efce15acae787757dceb11a711
ashokjain001/Python
/polygon.py
364
3.953125
4
import turtle def main(sides,length): wn = turtle.Screen() ashok = turtle.Turtle() wn.bgcolor("darkslategray") ashok.color("yellow") ashok.pensize(4) polygon(ashok,sides,length) wn.exitonclick() def polygon(t,sides,length): degree = 360/sides for i in range(sides): t.forward(50) t.left(degree) main(8,50)
9acb290a34eaf081d97ee32347600a39ea55e7ce
arindam-1521/python-course
/python tutorials/with-block.py
366
4
4
with open("joy.txt") as f: a = f.readlines() # Here it is not required to close the file . print(a) f = open( "joy.txt", "r+" ) # Here the file will run again because the with open block automatically closes the file after opening ,hence we cans open the file multiple times and read it. # print(f.readlines()) content = f.readlines() print(content)
f4f6265b8da57464607df82f1885bae20b8cfab1
sunilsm7/python_exercises
/Python_practice/practice_02/evenOdd.py
354
4.34375
4
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? """ def evenOdd(num): if num%2 != 0: return "Odd number" return "Even number" num = int(input('Enter number:')) result = evenOdd(num) print(result)
c4aa1126ca229c72948a0ddc0dc98c538c52453c
vivekgopalshetty/Algorithms
/squareoot.py
2,281
3.71875
4
def convert_tobinary(n1,count1): n1=bin(int(n1)) n2=list(n1) n3,n4=''.join(n2),''.join(n2[2:]) con=0 if len(n4)<count1: con=count1-len(n4) for i in range(0,con): n4='0'+n4 return n3,n4 def validate_no(n): length=len(n) if length%2==0: n1=n else: n1='0'+n return n1 def convert_toint(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = int(binary) % 10 decimal = decimal + dec * pow(2, i) binary = int(binary)//10 i = i+ 1 return decimal def subtrahend(answerlist,q): answerlist=str(q)+answerlist if len(answerlist)%2!=0: answerlist='0'+answerlist print("q:",q) print("subtrahend:",answerlist) return answerlist def process(answerlist,qarray): answerlist=''.join(qarray)+'01' return answerlist def perfectsqroot(remainder): if convert_toint(remainder)!=0: print("The no. you entered is not a perfect square root") print("Enter the Number:") n=str(input()) con_n,n1=convert_tobinary(n,0) n2=validate_no(n1) rem=0 qarray=[] q=1 print("The no. you entered",n) print("The binary number of it",n1) print("The validated from of it",n2) lengthn2=len(n2) answerlist=str('01') u=0 for i in range(2,len(n2)+1,2): print('----iteration no:',u,'------') up=convert_toint(n2[0:i]) down=convert_toint(answerlist) print("up:",up) print("down:",down) if up-down>=0: q='1' qarray.append('1') rem1,rem=convert_tobinary(up-down,i) print("remainder:",rem) answerlist=subtrahend(answerlist,q) n2=rem+n2[len(rem):lengthn2] print ("number:",n2) else: q='0' rem=up answerlist=subtrahend(answerlist,q) qarray.append('0') print ("number:",n2) remainder=rem answerlist=process(answerlist,qarray) rem='' u=u+1 print("-------------------FINAL RESULT-------------------------------") print("qarray:",qarray) print("final remainder:",remainder) perfectsqroot(remainder) print("square root of",n,"is",convert_toint("".join(qarray))) print("---------------------------------------------------")
bfba9e65274b97bef196f8f5be203d1cbf646181
begora/apuntespython
/Primeras_funciones.py
315
3.890625
4
def suma(num1, num2): print(num1+num2) suma(5,7) suma(2,3) suma(35,37) def suma2(n1,n2): resultado = n1 +n2 return resultado print (suma2(5,9)) #PRINT puede ir dentro de la función (suma) #o fuera de la función, cuando la llamas (suma2) almacena_resultado=suma2(5,8) print(almacena_resultado)
f5fec8ac322d17361133ab66e560dc35bfd3cd4f
atulanandnitt/questionsBank
/basicDataStructure/matrix/90DegreeRotation.py
429
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 26 07:11:03 2018 @author: Atul Anand """ def matrixRotation(mat): print(*mat) print(mat) for t1 in (zip(*mat)): for i in range(len(t1)): print(t1[len(t1)-i-1] , end=" ") print() mat=[[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] matrixRotation(mat)
2cbc1d5791158e5c876b938f97819a9cfe2ad6e6
KKIverson/python_ds_alg
/num2Base.py
307
3.828125
4
# -*-coding: utf-8-*- # 将十进制整数转换成任意进制的字符串(使用递归) def num2base(num, base): digits = '0123456789ABCDEF' if num // base == 0: return digits[num % base] else: return num2base(num // base, base) + digits[num % base] print(num2base(15,16))
e7cb8765e4a24012d5e49393aa24da56a0dbc1c5
Hedyju/hello-world
/code 4.py
168
3.546875
4
score = int(input('성적을 입력하세요 :')) if score >= 90: print('통과하셨습니다') print('축하합니다') print('수고하셨습니다')
f492ab525c6f8ab6118688efd93ebb3bf0b59b52
Srisomdee/Python
/1.py
407
3.921875
4
x = 25 print('เลือกเมนูทำรายการ') print('จ่ายเเบบเหมาจ่าย กด1 :') print('จ่ายแบบจ่ายเพิ่ม กด 2 :') a = int(input('enter your number 1 or 2 :')) s = int(input('กรุณากรอกระยะทาง(km)') if a == 1: print('n equal to 10') else: print('n is something else except 10')
33ff7727e04bdb12605a865a2fda1e275a1602cc
AkshayPradeep6152/letshack
/Python Programs/Trie.py
1,880
3.84375
4
from collections import defaultdict class TrieNode(): def __init__(self): self.children = defaultdict() self.terminating = False class Trie(): def __init__(self): self.root = self.get_node() def get_node(self): return TrieNode() def get_index(self, ch): return ord(ch) - ord('a') def insert(self, word): root = self.root len_word = len(word) for i in range(len_word): index = self.get_index(word[i]) if index not in root.children: root.children[index] = self.get_node() root = root.children.get(index) root.terminating = True def search(self, word): root = self.root len_word = len(word) for i in range(len_word): index = self.get_index(word[i]) if not root: return False root = root.children.get(index) return True if root and root.terminating else False def delete(self, word): root = self.root len_word = len(word) for i in range(len_word): index = self.get_index(word[i]) if not root: print("Word not found") return -1 root = root.children.get(index) if not root: print("Word not found") return -1 else: root.terminating = False return 0 def update(self, old_word, new_word): val = self.delete(old_word) if val == 0: self.insert(new_word) if __name__ == "__main__": strings = ["abcd", "efgh", "ijkl", "mnop", "abcd"] t = Trie() for word in strings: t.insert(word) print(t.search("abcd")) print(t.search("efgh")) t.delete("efgh") print(t.search("efgh")) t.update("mnop", "efgh")
57d1fa2f487012f4994027e12f6c356259f094bd
refeed/StrukturDataA
/meet1/J_gunungSimetris.py
547
3.84375
4
''' Gunung Simetris Batas Run-time: 1 detik / test-case Batas Memori: 64 MB DESKRIPSI SOAL Buatlah sebuah deret gunung seperti contoh di bawah. PETUNJUK MASUKAN Sebuah bilangan bulat N. (1≤N≤100) PETUNJUK KELUARAN keluarkan deret gunung dengan tampilan horizontal (satu angka per baris). CONTOH MASUKAN 1 5 CONTOH KELUARAN 1 1 2 3 4 5 4 3 2 1 CONTOH MASUKAN 2 8 CONTOH KELUARAN 2 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 ''' batas_int = int(input()) for i in range(1, batas_int): print(i) for i in range(batas_int, 0, -1): print(i)
505134f7707cd1c7254c7e82a18d3bfb02e6cfc7
Suraj-KD/HackerRank
/python/string/text_alignment.py
862
3.53125
4
from __future__ import print_function, division char = 'H' space = ' ' def text_align(width): lines = [] for n in range(width): lines.append((char*(n*2+1)).center(width*2-1, space)) offset = space*(width*4 - (width*2-1)) for n in range(width+1): lines.append((char*width).center(width*2-1, space) + offset + (char*width).center(width*2-1, space)) for n in range((width+1)//2): lines.append((char*width*5).center(width*6, space)) for n in range(width+1): lines.append((char*width).center(width*2-1, space) + offset + (char*width).center(width*2-1, space)) for n in reversed(range(width)): lines.append(space*(width*4) + (char*(n*2+1)).center(width*2-1, space)) return lines def main(): T = int(input()) print('\n'.join(text_align(T))) if __name__ == '__main__': main()
c20ff9503fa2a4ad8277df905e570dba127a6963
LDStraughan/HarvardX_PH526x_Using_Python_for_Research
/5_Statistical_Learning/5.4_Homework_Case_Study_Part_1/5.4_Homework_Case_Study_Part_1.py
8,807
3.921875
4
##################### # CASE STUDY 7 PART 1 ##################### # The movie dataset on which this case study is based is a database of 5000 movies catalogued by The Movie Database # (TMDb). The information available about each movie is its budget, revenue, rating, actors and actresses, etc. In this # case study, we will use this dataset to determine whether any information about a movie can predict the total revenue # of a movie. We will also attempt to predict whether a movie's revenue will exceed its budget. # In Part 1 of this case study, we will inspect, clean, and transform the data. ############### # EXERCISES 1-4 ############### # Exercise 1: First, we will import several libraries. scikit-learn (sklearn) contains helpful statistical models, # and we'll use the matplotlib.pyplot library for visualizations. Of course, we will use numpy and pandas # for data manipulation throughout. # Instructions: # Read and execute the given code, then call df.head() to take a look at the data. # Here's the import code: # import pandas as pd # import numpy as np # from sklearn.model_selection import cross_val_predict # from sklearn.linear_model import LinearRegression # from sklearn.linear_model import LogisticRegression # from sklearn.ensemble import RandomForestRegressor # from sklearn.ensemble import RandomForestClassifier # from sklearn.metrics import accuracy_score # from sklearn.metrics import r2_score # import matplotlib.pyplot as plt # df = pd.read_csv("https://courses.edx.org/asset-v1:HarvardX+PH526x+2T2019+type@asset+block@movie_data.csv", index_col=0) # # Enter code here. # What is the title of the first movie in this dataset? # Solution 1: import pandas as pd import numpy as np from sklearn.model_selection import cross_val_predict from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import r2_score import matplotlib.pyplot as plt df = pd.read_csv("https://courses.edx.org/asset-v1:HarvardX+PH526x+2T2019+type@asset+block@movie_data.csv", index_col=0) pd.set_option('display.max_columns', None) df.title.head()[0] # Answer = Avatar # Exercise 2: In Exercise 2, we will define the regression and classification outcomes. Specifically, we will use the # revenue column as the target for regression. For classification, we will construct an indicator of # profitability for each movie. # Instructions: # - Create a new column in df called profitable, defined as 1 if the movie revenue (revenue) is greater than the # movie budget (budget), and 0 otherwise. # - Next, define and store the outcomes we will use for regression and classification. Define regression_target as # the string 'revenue'. Define classification_target as the string 'profitable'. # How many movies in this dataset are defined as profitable (value 1)? # Solution 2: df['profitable'] = np.where(df['revenue'] > df['budget'], 1, 0) regression_target = 'revenue' classification_target = 'profitable' df['profitable'].value_counts() # Answer = 2585 # Exercise 3: For simplicity, we will proceed by analyzing only the rows without any missing data. In Exercise 3, we # will remove rows with any infinite or missing values. # Instructions: # - Use df.replace() to replace any cells with type np.inf or -np.inf with np.nan. # - Drop all rows with any np.nan values in that row using df.dropna(). Do any further arguments need to be # specified in this function to remove rows with any such values? # How many movies are left in the dataset after dropping any rows with infinite or missing values? # Solution 3: df = df.replace([np.inf, -np.inf], np.nan) df = df.dropna(how="any") df.shape # Answer = 1406 # Exercise 4: Many of the variables in our dataframe contain the names of genre, actors/actresses, and keywords. Let's # add indicator columns for each genre. # Instructions: # - Determine all the genres in the genre column. Make sure to use the strip() function on each genre to remove # trailing characters. # - Next, include each listed genre as a new column in the dataframe. Each element of these genre columns should # be 1 if the movie belongs to that particular genre, and 0 otherwise. Keep in mind that a movie may belong to # several genres at once. # - Call df[genres].head() to view your results. # How many genres of movies are in this dataset? # Solution 4: list_genres = df.genres.apply(lambda x: x.split(",")) genres = [] for row in list_genres: row = [genre.strip() for genre in row] for genre in row: if genre not in genres: genres.append(genre) for genre in genres: df[genre] = df['genres'].str.contains(genre).astype(int) df[genres].head() len(genres) # Answer = 20 ############### # EXERCISES 5-7 ############### # Exercise 5: Some variables in the dataset are already numeric and perhaps useful for regression and classification. # In Exercise 5, we will store the names of these variables for future use. We will also take a look at # some of the continuous variables and outcomes by plotting each pair in a scatter plot. Finally, we will # evaluate the skew of each variable. # Instructions: # - Call plt.show() to observe the plot generated by the code given below. Which of the covariates and/or outcomes # are correlated with each other? # - Call skew() on the columns outcomes_and_continuous_covariates in df. Is the skew above 1 for any of these # variables? # Here is the code to get you started: # continuous_covariates = ['budget', 'popularity', 'runtime', 'vote_count', 'vote_average'] # outcomes_and_continuous_covariates = continuous_covariates + [regression_target, classification_target] # plotting_variables = ['budget', 'popularity', regression_target] # axes = pd.plotting.scatter_matrix(df[plotting_variables], alpha=0.15, \ # color=(0,0,0), hist_kwds={"color":(0,0,0)}, facecolor=(1,0,0)) # # show the plot. # # determine the skew. # Which continuous covariate appears to be the most skewed? # Solution 5: continuous_covariates = ['budget', 'popularity', 'runtime', 'vote_count', 'vote_average'] outcomes_and_continuous_covariates = continuous_covariates + [regression_target, classification_target] plotting_variables = ['budget', 'popularity', regression_target] axes = pd.plotting.scatter_matrix(df[plotting_variables], alpha=0.15, \ color=(0,0,0), hist_kwds={"color":(0,0,0)}, facecolor=(1,0,0)) plt.show() print(df[outcomes_and_continuous_covariates].skew()) # Answer = popularity # Exercise 6: It appears that the variables budget, popularity, runtime, vote_count, and revenue are all right-skewed. # In Exercise 6, we will transform these variables to eliminate this skewness. Specifically, we will use # the np.log10() method. Because some of these variable values are exactly 0, we will add a small positive # value to each to ensure it is defined; this is necessary because log(0) is negative infinity. # Instructions: # For each above-mentioned variable in df, transform value x into np.log10(1+x). # What is the new value of skew() for the covariate runtime? Please provide the answer to 3 decimal points. # Solution 6: for covariate in ['budget', 'popularity', 'runtime', 'vote_count', 'revenue']: df[covariate] = df[covariate].apply(lambda x: np.log10(1 + x)) print(df[outcomes_and_continuous_covariates].skew()) # Answer = 0.530 # Exercise 7: Now we're going to save our dataset to use in Part 2 of this case study. # # Instructions: # Use to_csv() to save the df object as movies_clean.csv. # What is the correct way to save the df object? # Solution 7: df.to_csv("movies_clean.csv")
9c7456adafdf5644194adb5816522b81ea6a12b1
sharangKulkarni2/sorting-in-c-and-python
/q_sort.py
762
3.796875
4
def partition(arr, start, end): pivot = end pivot_element = arr[pivot] i = start j = end - 1 while i < j: while arr[i] < pivot_element: i+=1 while arr[j] > pivot_element: j-=1 if i < j: temp = arr[i] arr[i] = arr[j] arr[j] = temp temp = arr[i] arr[i] = arr[pivot] arr[pivot] = temp return i def q_sort(arr, start, end): if not (start < end): return partition_number = partition(arr, start, end) q_sort(arr, start, partition_number - 1) q_sort(arr, partition_number + 1, end) #trying on an example arr = [1, 2, 4, 3, 8, 5, 6, 7] merge_sort(arr, 8) for i in range(len(arr)): print(arr[i])
ab2f4d2e89bbce5b1878be5bb0174859dfe8c06f
silvavn/CMPUT175-W2020
/Assignment-2/UltimateMetaTTT.py
6,554
4.4375
4
#---------------------------------------------------- # Assignment 2: Tic Tac Toe classes # # Author: Victor Silva # Collaborators: # References: #---------------------------------------------------- class TicTacToe: ''' Abstract Class TicTacToe Implements the general methods for the TicTacToe Game ''' def __init__(self): raise Exception('Each Class must implement their own __init__') def drawBoard(self): ''' Displays the current state of the board, formatted with column and row indices shown. Inputs: none Returns: None ''' for i in self.board: print (i) def isValidPosition(self, row, col): if 0 > row > len(self.board): return False elif 0 > col > len(self.board): return False return True def update(self, row, col, mark): ''' Assigns <mark>, to the board at the provided row and column, but only if that square is empty. Inputs: row (int) - row index of square to update col (int) - column index of square to update mark <str or int> - entry to place in square Returns: True if attempted update was successful; False otherwise ''' if self.squareIsEmpty(row, col): return False try: self.board[row][col] = mark except: return False return True def squareIsEmpty(self, row, col): ''' Checks if a given square is "empty", or if it already contains a number greater than 0. Inputs: row (int) - row index of square to check col (int) - column index of square to check Returns: True if square is "empty"; False otherwise ''' if self.board[row][col] == 0 or self.board[row][col] == '': return True return False def boardFull(self): ''' Checks if the board has any remaining "empty" squares. Inputs: none Returns: True if the board has no "empty" squares (full); False otherwise ''' for i in range(len(self.board)): for j in range(len(i)): if self.squareIsEmpty(self.board[i][j]): return False return True def isNum(self): ''' Checks whether this is a Numerical Tic Tac Toe board or not Inputs: none Returns: True ''' for i in board: for j in i: if not type(j) is int: return False return True def __getLines(self): lines = [] #HORIZONTAL for i in self.board: lines.append(i) #VERTICAL lines.extend([[i[x] for i in self.board] for x in range(len(self.board))]) #DIAGONAL lines.append([self.board[i][i] for i in range(len(self.board))]) lines.append([self.board[len(self.board) - 1 - i][i] for i in range(len(self.board))]) return lines def isWinner(self): raise Exception('Must be implemented!!!') class NumTicTacToe(TicTacToe): def __init__(self): self.board = [[0] * 3] * 3 def update(self, row, col, mark): if not type(mark) is int: return False super().update(row, col, mark) def isWinner(self): ''' Checks whether the current player has just made a winning move. In order to win, the player must have just completed a line (of 3 squares) that adds up to 15. That line can be horizontal, vertical, or diagonal. Inputs: none Returns: True if current player has won with their most recent move; False otherwise ''' for i in self.__getLines(): if sum(i) == 15: return True return False class ClassicTicTacToe: def __init__(self): ''' Initializes an empty Classic Tic Tac Toe board. Inputs: none Returns: None ''' self.board = [['']*3]*3 def isWinner(self): ''' Checks whether the current player has just made a winning move. In order to win, the player must have just completed a line (of 3 squares) with matching marks (i.e. 3 Xs or 3 Os). That line can be horizontal, vertical, or diagonal. Inputs: none Returns: True if current player has won with their most recent move; False otherwise ''' for i in self.__getLines(): if ''.join(i) == 'xxx' or ''.join(i) == 'ooo': return True return False class MetaTicTacToe(TicTacToe): def __init__(self, configFile): ''' Initializes an empty Meta Tic Tac Toe board, based on the contents of a configuration file. Inputs: configFile (str) - name of a text file containing configuration information Returns: None ''' self.board = [] with open(configFile) as f: self.board = [i.lower().strip().split() for i in f] def getLocalBoard(self, row, col): ''' Returns the instance of the empty local board at the specified row, col location (i.e. either ClassicTicTacToe or NumTicTacToe). Inputs: row (int) - row index of square col (int) - column index of square Returns: instance of appropriate empty local board if un-played; None if local board has already been played ''' val = self.board[row][col].lower() if val in ['x', 'o', 'd']: return None elif val == 'n': self.board[row][col] = NumTicTacToe() elif val == 'c': self.board[row][col] = ClassicTicTacToe() raise Exception('File has error') def game(): meta_game = MetaTicTacToe('MetaTTTconfig.txt') print('Welcome to Ultimate TicTacToe') print('This is the current board:') meta_game.drawBoard() row = int(input('Player 1, please insert your play row: ')) col = int(input('Player 1, please insert your play column: ')) if __name__ == "__main__": game() # TEST EACH CLASS THOROUGHLY HERE
1eec8a5365910e0f0318ba81b9b5eead89be3c62
applepicke/euler
/14.py
596
4.0625
4
#!/usr/bin/env python import sys chain = {} def collatzify(n): orig_num = n count = 1 while n > 1: if chain.has_key(str(n)): count += chain[str(n)] break n = (n / 2) if (n % 2 == 0) else (3*n + 1) count += 1 chain[str(orig_num)] = count return count def longestSequenceUnder(n): longest = 0 longest_num = 0 for i in range(2, n): num = collatzify(i) if num > longest: longest = num longest_num = i return longest_num if len(sys.argv) > 1: num = int(sys.argv[1]) print longestSequenceUnder(num)
671c3c09756ddab4eb41297ba9ae3df0125207fa
orakinahmed/Python-Practice
/AdventureTime/pygame1.py
1,922
4.375
4
""" print('What is your name?') name = input() # Receiving input from the user at the terminal print('Your name is: ' + name) # String Concatenation """ # Create your own text adventure game! # Present 5 scenarios to a user and give them 2 options to choose from for each scenario. # Make it fun! Create a story and have your character choose which way to go # This game is a linear path for the thief #Start print('You are a theif walking the kings road. You come across an abandoned castle.') # Scenario 1 print('Would you like to enter? \n Enter (yes or no)') decision = input() if decision == 'no': print("You went back home! The adventure ended!") elif decision == 'yes': # Scenario 2 print('You have entered the castle, and come upon a locked chest, what do you do? \n Enter (pick lock , move on)') decision = input() if decision == 'pick lock': print('You broke open the lock and were poisoned by the gas in the chest. You died. The end') elif decision == 'move on': # Scenario 3 print('You have come upon a trap! \n what do you do? \n Enter (cross it, look for another path)') decision = input() if decision == 'cross it': print('You have failed to cross the path, you died!') elif decision == 'look for another path': # Scenario 4 print('You find another path which leads to a a door and an opening with a dark crevice! \n Which opening do you enter? \n Enter (Open door, enter crevice)') decision == input() if decision == 'open door': print('You see a room full of treasure! Hurrah you are rich! The end!') elif decision == 'enter crevice': print('You see a dragon, he farts and sneezes and the methane enflames the air aroud you. You explode!')
faca6c8f11137ab565bb7099a53a1587043a4e89
ivSaav/Programming-Fundamentals
/RE06/count.py
214
3.921875
4
def count(word, phrase): phrase += " " result = phrase.count(word.upper() + " ") + phrase.count(word.lower() + " ") + phrase.count(word.capitalize() + " ") phrase = phrase[:-1] return result
6835b294a7d5ffd2240083226c5b1c6e5b0cd1ce
dwallace-web/python-crash-TM
/python_crashcoursefiles/functions.py
818
3.78125
4
# A function is a block of code which only runs when it is called. In Python, we do not use parentheses and curly brackets, we use indentation with tabs or spaces # create simple function def sayGoodbye(name): print(f'Goodbye, until next time {name} ......' + name) sayGoodbye('Jonathan Doe') # return values def getSum(num1, num2, num3): # function scope total = num1 + num2 + num3 return total print(getSum(1, 1, 2)) num = getSum(2, 2, 2) print(num) # A lambda function is a small anonymous function. # A lambda function can take any number of arguments, but can only have one expression. Very similar to JS arrow functions # built like a arrow function # this is a lamda function # findSum = lambda num4, num5 : num4 + num5 def findSum(num4, num5): return num4 + num5 print(findSum(10, 3))
77621e13f718eaeaeb2bdf0a32988befea67dd74
rileyjohngibbs/hard-twenty
/adventOfCode/06/solution.py
2,654
3.53125
4
from functools import reduce from sys import argv if "test" not in argv: with open('input.txt', 'r') as inputfile: coords = [p.replace('\n', '') for p in inputfile.readlines() if p] else: coords = [ "1, 1", "1, 6", "8, 3", "3, 4", "5, 5", "8, 9", ] class Point(object): def __init__(self, x, y): self.x = x self.y = y def __hash__(self): return (self.x, self.y).__hash__() def __repr__(self): return f"P({self.x}, {self.y})" @classmethod def from_string(cls, coord_string): x, y = [int(c) for c in coord_string.split(', ')] return cls(x, y) def distance(self, *args): if len(args) == 1: x, y = args[0].x, args[0].y return self.distance(x, y) elif len(args) == 2: x, y = args return abs(x - self.x) + abs(y - self.y) else: raise TypeError(f"{self.__cls__}.distance takes a Point or x, y") def closest_center(self, centers): closest_center = centers[0] shortest_distance = self.distance(centers[0]) for center in centers[1:]: center_distance = self.distance(center) if center_distance < shortest_distance: shortest_distance = center_distance closest_center = center elif center_distance == shortest_distance: closest_center = None return closest_center class Center(Point): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.area = [] centers = [Center.from_string(coord) for coord in coords] min_x = min(center.x for center in centers) max_x = max(center.x for center in centers) min_y = min(center.y for center in centers) max_y = max(center.y for center in centers) tapestry = reduce(lambda x, y: x + y, [ [ Point(x, y) for x in range(min_x, max_x + 1) ] for y in range(min_y, max_y + 1) ]) # Part One infinite_areas = set([]) for point in tapestry: closest_center = point.closest_center(centers) if closest_center is not None: closest_center.area.append(point) if point.x in (min_x, max_x) or point.y in (max_y, max_y): infinite_areas.add(closest_center) def not_infinite(center): return center not in infinite_areas biggest_center = max(filter(not_infinite, centers), key=lambda c: len(c.area)) print(len(biggest_center.area)) # Part Two def close_enough(point): return sum(map(point.distance, centers)) < 10000 print(len(list(filter(close_enough, tapestry))))
8afce1725e30448dbf9fd75c5b1f4cb6823d2399
standrewscollege2018/2021-year-11-classwork-SamEdwards2006
/Ifelse.py
285
4.375
4
#This program demonstrates how an if statement works #Sets an age limit CHILD_AGE = 13 #Take the age of the user age = int(input("How old are you")) #Checks if the age is above or below the age limit if age <= CHILD_AGE: print("You pay the child price") print("Welcome to the zoo")
3ed454a1b84dea94a7e23e1b8e2bcb9adaefd6c9
szhmery/algorithms
/samples/IsPrime.py
296
3.78125
4
import math def IsPrime(Num): if Num == 1: return False for n in range(2, int(math.sqrt(Num)) + 1): if Num % n == 0: return False return True oList = [] for i in range(1, 101): if IsPrime(i) is True: oList.append(i) else: print(oList)
9c86d73eb4b67332ab3d18eb61826211b514fd22
lucasgaspar22/URI
/Iniciante/1012.py
348
3.578125
4
line = input().split(" ") a = float(line[0]) b = float(line[1]) c = float(line[2]) aTriangle = a*c/2 aCircle = 3.14159*c**2 aTrape = (a+b)*c/2 aSquare = b**2 aRectangle = a*b print("TRIANGULO: %.3f" %aTriangle) print("CIRCULO: %.3f" %aCircle) print("TRAPEZIO: %.3f" %aTrape) print("QUADRADO: %.3f" %aSquare) print("RETANGULO: %.3f" %aRectangle)
eabcdd82618932852a2ae9e238f4e105f862acec
daily-boj/dryrain39
/P2508.py
1,052
3.78125
4
def is_candy(a, b, c, xy): return (a == '>' and b == 'o' and c == '<' and xy == 'x') or \ (a == 'v' and b == 'o' and c == '^' and xy == 'y') if __name__ == '__main__': test_count = int(input()) for _ in range(test_count): input() height = int(input().split()[0]) candy = 0 tmp = [ # line_number: [first_word, second_word, third_word] [] for x in range(401) ] for y in range(height): line = input() for x in range(len(line)): if line[x] == '>' and len(line) > x + 2: if is_candy(line[x], line[x + 1], line[x + 2], 'x'): candy += 1 if line[x] == 'v': tmp[x] = ['v'] else: tmp[x].append(line[x]) if len(tmp[x]) == 3: if is_candy(tmp[x][0], tmp[x][1], tmp[x][2], 'y'): candy += 1 tmp[x] = [] print(candy)
22084869c8fa8f8b8d28bad2ad5ba9076062dfba
arthurdysart/LeetCode
/0209_minimum_size_subarray_sum/python_source.py
9,756
3.609375
4
# -*- coding: utf-8 -*- """ Leetcode - Minimum Size Subarray Sum https://leetcode.com/problems/minimum-size-subarray-sum Created on Tue Nov 20 13:45:34 2018 Updated on Sun Dec 2 21:09:57 2018 @author: Arthur Dysart """ ## REQUIRED MODULES import sys ## MODULE DEFINITIONS class Solution: """ Iterative dynamic window search over array of incremental cumulative sums. Time complexity: O(n) - Amortized iterate over all elements with two limit pointers Space complexity: O(1) - Amortized update constant number of pointers """ def find_min_sub_len(self, x, a): """ Determines minimum subarray length to meet or exceed target sum. :param int x: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int """ if not a: return 0 r = 0 s = 0 p = float("inf") n = len(a) for l in range(0, n, 1): while (s < x and r < n): # Running sum is less than target sum s += a[r] r += 1 if s >= x: # Running sum meets target sum p = min(p, r - l) # Remove left limit value from running sum s -= a[l] if p == float("inf"): return 0 else: return p class Solution2: """ Iterative dynamic window search over array of incremental cumulative sums. Time complexity: O(n) - Amortized iterate over all elements with two limit pointers Space complexity: O(1) - Amortized update constant number of pointers """ def find_min_sub_len(self, x, a): """ Determines minimum subarray length to meet or exceed target sum. :param int x: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int """ if not a: return 0 # Initialize minimum subarray length, running sum, and left limit p = float("inf") s = 0 l = 0 n = len(a) for r in range(0, n, 1): # Add right element to running sum s += a[r] # Check whether running sum is equal to or greater than target sum while s >= x: # Calculate and evaluate length of target subarray w = r - l + 1 p = min(p, w) # Remove left value from running sum, then increment limit s -= a[l] l += 1 if p == float("inf"): # No subarray sum found return 0 else: return p class Solution3: """ Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums """ def find_min_sub_len(self, x, a): """ Determines minimum subarray length to meet or exceed target sum. :param int x: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int """ if not a: return 0 n = len(a) # Initialize array of incremental cumulative sums s = [0] for i in range(n): s.append(s[-1] + a[i]) # Initialize minimum subarray length p = float("inf") m = len(s) for i in range(m): t = s[i] + x if t <= s[-1]: j = self.find_target_sum(i, t, s) p = min(p, j - i) if p == float("inf"): # No subarray sum found return 0 else: return p def find_target_sum(self, i, t, s): """ Determines index of target cumulative sum using binary search. Note incremental cumulative sum is sorted in ascending order because all elements of array "a" are positive integers. :param int t: target cumulative sum :param list[int] s: array of incremental cumulative sums :return: index of :rtype: int """ if not s: return -1 l = i r = len(s) -1 while l <= r: m = l + (r - l) // 2 if s[m] == t: return m elif s[m] < t: l = m + 1 else: r = m - 1 return l class Solution4: """ Simplified dynamic programming (tabulation, bottom-up) algorithm. Time complexity: O(n ** 2) - Amortized iterate over all start index and sublength combinations Space complexity: O(n) - Amortized store sum combinations for current sublength """ def find_min_sub_len(self, x, a): """ Determines minimum subarray length to meet or exceed target sum. :param int n: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int """ if not a: return 0 n = len(a) # Check initial array for i in range(0, n, 1): if a[i] >= x: return 1 # Initialize cache for subarray sums and pointer for previous cache c = [None for i in range(0, n, 1)] p = a # Iterate over length of subarray (rows) for i in range(1, n, 1): # Iterate over index in main array (columns) for j in range(0, n - i, 1): # Calculate sum for subarray s = p[j] + a[i + j] if s >= x: # Subarray found return i + 1 else: c[j] = s p = c # No subarray sum found return 0 class Solution5: """ Routine dynamic programming (tabulation, bottom-up) algorithm. Time complexity: O(n ** 2) - Amortized iterate over all start index and sublength combinations Space complexity: O(n ** 2) - Amortized store sum for all start index and sublength combinations """ def find_min_sub_len(self, x, a): """ Determines minimum subarray length to meet or exceed target sum. :param int n: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int """ if not a: return 0 n = len(a) # Initialize cache for subarray sums c = [[None] * (n - i) for i in range(0, n, 1)] # Populate first row for j in range(0, n, 1): if a[j] >= x: return 1 else: c[0][j] = a[j] # Iterate over length of subarray (rows) for i in range(1, n, 1): # Iterate over index in main array (columns) for j in range(0, n - i, 1): # Calculate sum for subarray s = c[i - 1][j] + c[0][i + j] if s >= x: # Subarray found return i + 1 else: c[i][j] = s # No subarray sum found return 0 class Solution6: """ Iteration over all start indicies for subarrays. Time complexity: O(n ** 2) - Amortized iterate over all start index and sublength combinations Space complexity: O(1) - Update constant number of pointers """ def find_min_sub_len(self, x, a): """ Determines minimum subarray length to meet or exceed target sum. :param int n: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int """ if not a: return 0 # Initialize pointer for minimial subarray length p = float("inf") n = len(a) for i in range(0, n, 1): s = 0 for j in range(i, n, 1): s += a[j] if s >= x: # Minimum target sum found p = min(p, j - i + 1) if p == float("inf"): return 0 else: return p class Input: def stdin(self, sys_stdin): """ Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of input positive integers and target sum :rtype: tuple[int, list[int]] """ inputs = [x.strip("[]\n") for x in sys_stdin] a = [int(x.strip()) for x in inputs[0].split(",")] x = int(inputs[1]) return x, a ## MAIN MODULE if __name__ == "__main__": # Import exercise parameters x, a = Input()\ .stdin(sys.stdin) # Evaluate solution z = Solution()\ .find_min_sub_len(x, a) print(z) ## END OF FILE
2645b6dee39e29a5440b880943d15c28c6132a16
atwndmnlght/the_self_taught_prog
/190108.py
187
3.609375
4
colors = ["orange", "pink", "black"] guess = input("何色でしょう:") if guess in colors: print("あたり") else: print("hazure") #これはタプル ("ai",)
1d21eb71ced7b647a4c805a22fcaec9d8788aa42
GreenMarch/datasciencecoursera
/algo/basic/squares-of-a-sorted-array.py
312
3.53125
4
class Solution(object): def sortedSquares(self, A): """ :type A: List[int] :rtype: List[int] """ return sorted([i**2 for i in A]) def sortedSquares2(self, A): return list(map(lambda x: x**2, A)) data = [1,3,5, 7] print(Solution().sortedSquares2(data))
fa883d11cad9b9d3119dc52291104522eaaf4787
wgrewe/Project-Euler
/19prob.py
648
3.875
4
# How many sundays fell on the first of a month # between Jan 1 1901 and Dec 31 2000 # m = 1, t = 2, w = 3, h = 4, f = 5, s = 6, su = 7 # 52 weeks in 364 days, so if year starts on sunday # then there are 53 sundays. If leap year also fine to start on sat month_days = { 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31 } total_suns = 0 init_day = 366 % 7 for year in range(1901, 2001): for month in range(1,13): if init_day == 0: total_suns += 1 init_day = init_day + month_days[month] if month == 2 and year % 4 == 0: init_day += 1 init_day = init_day % 7 print(total_suns)
2fd7f27aaabf194d6d689d2adfb7f9f1e2c1331a
ramvishvas/chegg-sol-2019
/basic.py
1,600
3.75
4
import random import math myArray=[] size= 50 # populate array with size=50 random integers # in range 0-1 and repeat for 1000 times for _ in range(1000): for k in range(size): randNum=random.randint(0,1) # add random number to list myArray.append(randNum) #print myArray 50 values per line for i in range(size): print(myArray[i*50 : (i+1)*50]) #display array size print("\nSize of my array is: ",len(myArray)) # count 0's and 1's count_of_0 = myArray.count(0) count_of_1 = myArray.count(1) print("\nNumber of 0’s is: ", count_of_0) print("Number of 1’s is: ", count_of_1) print("\nExpected mean (average) of the 0’s: ", count_of_0*size*.5) print("Expected mean (average) of the 1’s: ", count_of_1*size*.5) #calculate mean and SD of binomial distribution #probability of occurence of 1 is p = 1/2 and occurence of 0 is q =1/2 #mean of Binomial distribution = np #SD(standard deviation) of Binomial distribution = (npq)^1/2 #here n=50000 sd = math.sqrt(len(myArray)*0.5*0.5) print("\nStandard Deviation (SD): ", sd) # n=len(myArray) # p=0.5 # q=0.5 # mean= n*p #expected mean of no of ones # sd = math.sqrt(n*p*q) # print("===============================") # print("mean of 1s in My Array: ",mean," sd(standard deviation): ",sd) # Lrange=int(round(mean-sd)) # Rrange=int(round(mean+sd)) # print("range: mean+-sd: ",Rrange," ",Lrange) #round off the range to nearest integer # #check if no of ones is within range # if(ones>= Lrange and ones<= Rrange): # output="Yes" # else: # output="No" # print("Actual number of ones is within the range mean+-sd ??? Ans is: ", output)
69e7ad49b607ea8f7383f3e037ef28001aaee9a6
LisaHagenau/small-bioinformatic-scripts
/range-of-values.py
946
3.75
4
# find the range of values in column 3 for unique values in column 1 and the most common value in column 2 import csv # open both files and store sequences from file1 as list stream = open("file1.txt") seqlist = list(stream) seqlist = [element.strip() for element in seqlist] stream = open("file2.txt") reader = csv.reader(stream, delimiter="\t") for seq in seqlist: # create array from column 2 and 3 array = ([line[1:] for line in reader if seq == line[0]]) # find and count most common element from column 2 common = [element[0] for element in array] mostCommon = max(common, key=common.count) commonCount = common.count(mostCommon) # find range of values for most common element values = [element[1] for element in array if element[0] == mostCommon] # print out results print(seq, "\t", mostCommon, "\t", min(values), "-", max(values), "\t", commonCount) stream.seek(0)
eeaa33530d7bcb9f938c68600b0e42fd07aa313e
xi2pi/patent-claim-combination
/combination_analysis.py
603
3.578125
4
# -*- coding: utf-8 -*- """ @author: Christian Winkler """ def num_combinations(claim_): num_com_list = [0] * len(claim_) num_com_list[0] = 1 num_com_list_idx = 0 for i in claim_: if num_com_list_idx > 0: for j in i: num_com_list[num_com_list_idx] += num_com_list[j-1] num_com_list_idx += 1 return num_com_list ### NUMBER OF COMBINATION claim = [[1], [1], [1,2], [1], [2], [1,2,3,4,5], [2,5], [3,4]] result = num_combinations(claim) #print(result) print("Total combinations: " + str(sum(result)))
c8a24053af3f8de4a2dd96f28c38fe34bd6a3fac
Rodagui/Programas_Teor-aComputacional
/programa4.py
559
3.84375
4
#Programa 4: Cambia los caracteres igual al primero al caracter '$', excepto el primero def cambiarCaracteres(cadena): nva = "" caracter = cadena[0] nva += caracter for i in range(1, len(cadena)): if(cadena[i] == caracter and i > 0): nva += "$" else: nva += cadena[i] return nva #------------------ Main ------------------# print("\nPrograma 4: Cambia los caracteres igual al primero al caracter '$', excepto el primero\n\n") cadena = input('Ingrese la cadena: ') cadena = cambiarCaracteres(cadena) print(cadena)
3bbed811fc02dff16ceb34dd1f2fa56778ffca0b
VINSHOT75/PythonPractice
/infytq/pyq4.py
366
3.546875
4
str = input() lst1 = list(str) speind = [] spe = [] for i in lst1: if i == '@' or i == '#': spe.append(i) x = lst1.index(i) speind.append(x) lst1 = lst1[::-1] for i in lst1: if i == '@' or i == '#': lst1.remove(i) #print(lst1) k=0 while k<len(speind): lst1.insert(speind[k],spe[k]) k+=1 str = ''.join(lst1) print(str)
d815a614c688a5095b645dcc99331c9be52871da
SyedNaziya/test
/s6_55.py
82
3.921875
4
n=int(input()) a=int(input()) b=n*a if b%2==0: print("even") else: print("odd")
c92fa5763b2ece23d297395f1aab9ba720f0c694
wataoka/atcoder
/abc120/d.py
1,339
3.59375
4
class UnionFind: def __init__(self, n): self.n = n self.parents = [-1] * n self.ans = n*(n-1)//2 def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x): x = self.find(x) y = self.find(y) if x==y: return if self.parents[x] > self.parents[y]: x, y = y, x size_x = self.size(x) size_y = self.size(y) self.ans += size_x*(size_x-1)//2 + size_y*(size_y-1)//2 self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents(self.find(x)) def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x enumerate(self.parents) if x<0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r))) for r in self.roots()
09fefef4a915507c11679a165bb10a5b30966750
IordachescuAnca/Computational-Geometry
/Lab1/collinearity.py
2,672
4.25
4
class Point: def __init__(self, coordinateX = 0, coordinateY = 0, coordinateZ = 0): self.__coordinateX = coordinateX self.__coordinateY = coordinateY self.__coordinateZ = coordinateZ def readData(self): self.__coordinateX = float(input("Enter the first coordinate of the point: ")) self.__coordinateY = float(input("Enter the second coordinate of the point: ")) self.__coordinateZ = float(input("Enter the third coordinate of the point: ")) def writeData(self): print("The first coordinate of the point is {}".format(self.__coordinateX)) print("The second coordinate of the point is {}".format(self.__coordinateY)) print("The third coordinate of the point is {}".format(self.__coordinateZ)) def __checkEqual(self, anotherPoint): if self.__coordinateX != anotherPoint.__coordinateX: return 0 if self.__coordinateY != anotherPoint.__coordinateY: return 0 if self.__coordinateZ != anotherPoint.__coordinateZ: return 0 return 1 def getAlpha(self, point1, point2): if point1.__coordinateX - self.__coordinateX: return (point2.__coordinateX - self.__coordinateX)/(point1.__coordinateX - self.__coordinateX) if point1.__coordinateY - self.__coordinateY: return (point2.__coordinateY - self.__coordinateY)/(point1.__coordinateY - self.__coordinateY) if point1.__coordinateZ - self.__coordinateZ: return (point2.__coordinateZ - self.__coordinateZ)/(point1.__coordinateZ - self.__coordinateZ) def __checkCollinearity(self, point1, point2): if self.__checkEqual(point1) or self.__checkEqual(point2) or point1.__checkEqual(point2): return 1 else: alpha = self.getAlpha(point1, point2) contor = 0 if point2.__coordinateX - self.__coordinateX == alpha * (point1.__coordinateX - self.__coordinateX): contor += 1 if point2.__coordinateY - self.__coordinateY == alpha * (point1.__coordinateY - self.__coordinateY): contor += 1 if point2.__coordinateZ - self.__coordinateZ == alpha * (point1.__coordinateZ - self.__coordinateZ): contor += 1 if contor == 3: return 1 else: return 0 def collinearity(self, point1, point2): if self.__checkCollinearity(point1, point2): print("The points are collinear.") else: print("The points are not collinear.") def affineCombination(self, point1, point2): if self.__checkCollinearity(point1, point2): if self.__checkEqual(point1): print("A1 = 1 * A2 + 0 * A3") elif self.__checkEqual(point2): print("A1 = 0 * A2 + 1 * A3") elif point1.__checkEqual(point2): print("A2 = 0 * A1 + 1 * A3") else: alpha = self.getAlpha(point1, point2) print("A3 = {0} * A1 + {1} * A2".format(1-alpha, alpha))
ef69b8b725bf9737eeabecf7330f0289326171dd
pruthvi28994/Basics_Of_Coding_3
/numpattern2.py
354
3.9375
4
n=int(input('enter the number')); def numpattern(num): x=1; for row in range(num): if(row % 2 == 0): for col in range(1,num+1): print(x,end=" "); print((x+1),end=" "); else: print((x+1),end=" "); for col in range(1,num+1): print(x,end=" "); print(); x=x+1; numpattern(n);
8b98a523b681beca19d2dc28977bece86a23ab93
carterjin/digit-challenge
/PNG_digit_question.py
2,767
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 27 11:34:04 2020 @author: Kami """ import itertools testdigits = range(1,10) # Shunting-yard_algorithm ##https://en.wikipedia.org/wiki/Shunting-yard_algorithm def op_prec(char): if char == '*' or char == '/': return 3 else: return 2 def str_to_stack(exp): output = '' oper_stack = '' q_num = 0 for char in exp: if char.isdigit() or char == '?': output += char if char == '?': q_num += 1 elif char in ['+','-','*','/']: while(oper_stack and oper_stack[0] != '(' and op_prec(oper_stack[0]) >= op_prec(char)): output += oper_stack[0] oper_stack = oper_stack[1:] oper_stack = char + oper_stack elif char == '(': oper_stack = char + oper_stack elif char == ')': while(oper_stack[0] != '('): output += oper_stack[0] oper_stack = oper_stack[1:] if oper_stack and oper_stack[0] == '(': oper_stack = oper_stack[1:] return (output + oper_stack, q_num) def eval(stack, test): nums = test.copy() ans = [] for char in stack: if char.isdigit(): ans.append(int(char)) elif char == '?': ans.append(nums.pop(0)) elif char in ['+','-','*','/']: b = ans.pop() a = ans.pop() if char == '+': c = a + b elif char == '-': c = a - b elif char == '*': c = a * b elif char == '/': c = a / b ans.append(c) return ans[0] def print_ans(exp, nums): temp_exp = exp while nums: temp_exp = temp_exp.replace('?',str(nums.pop(0)), 1) print(temp_exp) print('PNG digit question solver\n ------Designed by Haoming Jin------') print('All unknown numbers are 1-9 and don\'t repeat, allowed operators are +-*/()') print('Acceptable formats examples: ?+?=9\t? + 1 = 9\t(1+?)/4 = 1.5\t 2+?*4 = 14\t?*?*?+?=295') while (True): exp = input('Enter the equation, type unknown number as "?", type "exit" to quit:\n') if exp == 'exit': break exp = exp.replace(' ','') try: (ques,ans) = exp.split('=') ans = float(ans) (stack,q_num) = str_to_stack(ques) is_found = False print('Answer:') for test in itertools.permutations(testdigits, r = q_num): test = list(test) if eval(stack, test) == ans: is_found = True print_ans(exp, test) if not is_found: print('Not Found') except: print('Input Error')
43afe383a035825782d4c915e85ce780cf8cc0e7
JohnnyHowe/slow-engine
/gameObject/gameObjectHandler.py
1,111
3.546875
4
""" Handles the updating of gameObject components. """ class GameObjectHandler: # Singleton things _instance = None @staticmethod def get_instance(): if GameObjectHandler._instance is None: GameObjectHandler() return GameObjectHandler._instance def __init__(self): if GameObjectHandler._instance is not None: print("GameObjectHandler instance already made.") else: self.on_startup() GameObjectHandler._instance = self @staticmethod def init(): GameObjectHandler.get_instance() # GameObjectHandler help game_objects = None def on_startup(self): """ When the singleton is first initialized, this is called. """ self.game_objects = [] def add_game_object(self, game_object): self.game_objects.append(game_object) def update_game_objects(self): """ Loop through the game_objects and update their components. """ for game_object in self.game_objects: game_object.update() game_object._update_components()
76a6482db113868ec9d501097f94b993668eef01
fengjiaxin/leetcode
/code/backtrack/377. Combination Sum IV.py
1,888
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-07-19 10:18 # @Author : 冯佳欣 # @File : 377. Combination Sum IV.py # @Desc : ''' Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7. ''' from collections import defaultdict class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: ''' 思路:回溯法,确定程序空间,同时确定出口 1.选择:每次可以选择每个数 2.条件,如果left_target < 0:直接结束了 3.结束:如果left_target == 0:说明是个可行解 # 注意只用backtrack会超时,那怎么办,用动态规划存储中间的值 需要用一个中间数组dp来,dp[i]表示target == i的解的个数,然后从1开始遍历到target,对于每一个数i,遍历数组nums,如果i >= x dp[i] += dp[i-x],例如对于nums = [1,2,3]的数组,target = 4,在计算dp[3]的时候,3 可以拆分成 1+ dp[2],2 + dp[1],3 + dp[0] 如果target 大于数组中的大多数数时,可以对数组进行排序,对于数组中 > target的元素,可以直接break ''' if not nums: return 0 dp = defaultdict(int) dp[0] = 1 # 确定初始条件dp[0],对于nums = [1,2,3],target= 1的话,dp[1] += dp[0] = 1,所以dp[0] = 1 nums.sort() for i in range(1, target + 1): for num in nums: if i < num: break dp[i] += dp[i - num] return dp[target]
679418655ba6d983e1efc25c2e36c319ff238b86
frenzymadness/pycode_carrots_girls_ova
/kamen_nuzky_papir/v2.py
975
3.75
4
#!/usr/bin/env python3 # Do hry z varianty 1 přidejte validaci uživatelského vstupu. # Hra dá uživateli na výběr následující položky A. Kámen B. Nůžky C. Papír D. Konec hry # Hra se navíc musí po oznámení vítěze zeptat, jestli má zahájit nové kolo. pocitac = 'N' print('Hra kamen, nuzky, papir') print('Pravidla: kámen tupí nůžky, nůžky stříhají papír a papír obalí kámen') while True: hrac = input('Zadejte svou volbu [K, N, P] nebo "Q" pro konec hry: ') if hrac == 'Q': break if hrac != 'K' and hrac != 'N' and hrac != 'P': print('Nespravne zadani!') continue if pocitac == hrac: print('Doslo k remize!') elif (pocitac == 'K' and hrac == 'N') or (pocitac == 'N' and hrac == 'P') or (pocitac == 'P' and hrac == 'K'): print('Pocitac vyhral!') else: print('Vyhral/a jste!') pokracovat = input('Hrat dalsi kolo? [A/N]: ') if pokracovat == 'N': break
1773d761f6f268254f0682b7bafddada339e4246
Drawiin/algoritmos-basicos
/Estruturas de Dados/Threes/AVL2.py
3,184
3.703125
4
class Node: def __init__(self, key, dad=None): self.key = key self.dad = dad self.left = None self.right = None self.hight = None self.balance = None self.color = None class AVL: def __init__(self): self.root = None def insert(self, key): if self.root is None: self.root = Node(key) self.root.hight = 0 self.root.balance = 0 else: self.insertAux(key, self.root) # self.UpdateBalance(self.root) def insertAux(self, key, node): if key < node.key: if node.left is None: node.left = Node(key, node) node.left.hight = 0 node.left.balance = 0 self.calcBalance(node.left) else: self.insertAux(key, node.left) elif key > node.key: if node.right is None: node.right = Node(key, node) node.right.hight = 0 node.right.balance = 0 self.calcBalance(node.right) else: self.insertAux(key, node.right) else: print('The key', key, 'is alredy in the tree') def insertArray(self, array): for i in array: self.insert(i) def calcBalance(self, node): '''Calculate the balance on the isertion''' left, right = 0, 0 if node.left is not None: left = node.left.hight+1 if node.right is not None: right = node.right.hight+1 node.hight = max(left, right) node.balance = right-left if node.dad is not None: self.calcBalance(node.dad) def UpdateBalance(self, node): '''Calculate all the tree balance''' left, right = 0, 0 if node.left is not None: left = self.UpdateBalance(node.left) if node.right is not None: right = self.UpdateBalance(node.right) node.balance = right - left node.hight = max(right, left) return node.hight+1 def balance(self, node): if abs(node.balance) > 1: if node.balance < -1: if node.left.right > 0: self.leftRotate(node.left) self.rightRotate(node) elif node.balance > 1: if node.right.left < 0: self.rightRotate(node.right) self.leftRotate(node) self.UpdateBalance(node) def leftRotate(self, node): pass def rightRotate(self, node): pass def preOrder(self): self.preOrderAux(self.root) def preOrderAux(self, node): print("(", end="") print("[{}:{}]".format(node.key, node.balance), end="") if node.left is not None: self.preOrderAux(node.left) else: print("@", end="") if node.right is not None: self.preOrderAux(node.right) else: print("@", end="") print(")", end="") if __name__ == "__main__": tree = AVL() tree.insertArray([1,3,2]) tree.preOrder()
dbc642b25c33ce604dee3147cd813ee2b7f31a29
helloexp/Python-100-Days
/公开课/文档/年薪50W+的Python程序员如何写代码/code/Python/opencourse/part02/idiom04.py
205
3.953125
4
fruits = ['orange', 'grape', 'pitaya', 'blueberry'] # index = 0 # for fruit in fruits: # print(index, ':', fruit) # index += 1 for index, fruit in enumerate(fruits): print(index, ':', fruit)
c5e39d7ec024eea506e0a69caac33010b26c013b
kirigaikabuto/Python19Lessons
/lesson9/4.py
473
3.953125
4
clothes = [ "футболка", "шуба", "джинсы", ] prices = [ 250, 1000, 500 ] n = len(clothes) i = 0 while i < n: print(f"{i}.{clothes[i]}") i += 1 choice = int(input("выбрать:")) print(clothes[choice], prices[choice]) # программа спрашивает у человека что ты хочешь купить? # 0.футболка # 1.шуба # 2.джинсы # 0 # это футболка и ее цена 250
23115516afb20abbdb33ba422e26fe5b86d9419d
PzanettiD/practice
/scramble.py
442
3.859375
4
# https://www.codewars.com/kata/scramblies/train/python # If a portion of str1 characters can be rearranged to match str2, return True, # otherwise returns false. import collections def scramble(s1, s2): # your code here if len(s1) < len(s2): return False s22 = collections.Counter(s2) s11 = collections.Counter(s1) for s in s2: if s22[s] > s11[s]: return False return True
3fb4f993135bd0dafa1a24b278a1034fc991630e
kihyo9/RecursiveSudokuSolver
/RecursiveSudokuSolver.py
942
3.859375
4
#numpy is imported to make the grid readable import numpy as np #grid with partially filled sudoku grid = [[5,0,0,0,8,0,0,4,9], [0,0,0,5,0,0,0,3,0], [0,6,7,3,0,0,0,0,1], [1,5,0,0,0,0,0,0,0], [0,0,0,2,0,8,0,0,0], [0,0,0,0,0,0,0,1,8], [7,0,0,0,0,4,1,5,0], [0,3,0,0,0,2,0,0,0], [4,9,0,0,5,0,0,0,3]] #determine possible solutions to sudoku def possible(y,x,n): global grid for i in range(0,9): if grid[y][i] == n: return False for i in range(0,9): if grid[i][x] == n: return False x0 = (x//3)*3 y0 = (y//3)*3 for i in range(0,3): for j in range(0,3): if grid[y0+i][x0+j] == n: return False return True #Solve the sudoku def solve(): global grid for y in range(9): for x in range(9): if grid[y][x] == 0: for n in range(1,10): if possible(y,x,n): grid[y][x] = n solve() grid[y][x] = 0 return print(np.matrix(grid)) input("More?") solve()
7ede34e6b444084ec85f51c44ca0d26cd7979bd1
saifsafsf/Semester-1-Assignments
/Lab 05/task 4.py
280
3.71875
4
star = str('*') # Specifying variables for i in range(1, 14): print(f'{i}\t', end='') # Using end= so cursor stays in the same line for j in range(1, i+1): print(star, end='') print() # Now moving to next line for the next line of output
428dc71d470ccfe5955d77c88540b6671e596a34
miki-minori/python-work
/AtCoder/215/215A.py
73
3.671875
4
s=input() if ("Hello,World!" == s): print('AC') else: print('WA')
e363da063cc12570109d18b5d45aacb350c99b07
pocceschi/aprendendo_git
/CursoPythonIntermediario/funcoes/funcao_calculo_pagamento.py
661
3.890625
4
# exemplo de um uso para função: def calcular_pagamento(qtd_horas, valor_hora): qtd_horas = float(qtd_horas) valor_hora = float(valor_hora) if qtd_horas <= 40: salario = qtd_horas * valor_hora else: h_excd = qtd_horas - 40 salario = 40 * valor_hora + (h_excd * (1.5 * valor_hora)) return salario n_funcionarios = int(input("Digite a quantidade de funcionários: ")) c = 0 while c < n_funcionarios: c = c + 1 a_receber = calcular_pagamento(int(input("Digite a quantidade de horas: ")), int(input("Digite o valor recebido por hora: "))) print(f"O funcionário {c} irá receber R${a_receber:.2f}")
75c061c4697c7b30011dfa05284317c3175d2911
thitemalhar/python_exercise-
/praticepython_org/remove_duplicate.py
305
3.90625
4
list = [int(x) for x in input("Enter numbers to form a list: \n").split()] def dup(list): new_list = [] for i in list: if i not in new_list: new_list.append(i) print (sorted(new_list)) def dup2(list): new_list2 = (set(list)) print (new_list2) dup(list) dup2(list)
702f177e6903acba8849f0a027bb8fd77e77aaab
jeremybwilson/codingdojo_bootcamp
/bootcamp_class/python/practice/enumerate.py
415
4.25
4
# Python program to illustrate # enumerate function list1 = ["eat","sleep","repeat"]; s1 = "geek" # creating enumerate objects obj1 = enumerate(list1) print "Return type:",type(obj1) print list(enumerate(list1)) my_list = ["wine","cheese","beer","eat","drink","merry"]; # creating enumerate objects obj2 = enumerate(my_list) print "Return type:", type(obj2) print "The output enumerated is : ", enumerate(obj2)
0eff74c28dac3536277cf80fc78ff0e9f90fe6bd
petirgrofin/OurRPGGame
/ModuleToTestScripts.py
1,036
3.859375
4
class Dog: def __init__(self, name, is_loyal): self.name = name self.is_loyal = is_loyal def checking_dog_characteristics(self): print(f"The dog is named {self.name}") print(f"The dog is loyal: {self.is_loyal}") akira_dog = Dog(name="Akira", is_loyal=True) class Cats: are_cute = True # always legs = 4 # hopefully always head = 1 def __init__(self, name, breed, owner): self.name = name self.breed = breed self.owner = owner def checking_cat_characteristics(self): print(f"The cat is named {self.name}") print(f"The cat is cute: {Cats.are_cute}") print(f"The cat's owner is: {self.owner}") print(f"The cat has {Cats.legs} legs and {Cats.head} head") print(f"The cat is of a {self.breed} race") kiu_cat = Cats(name="Kiu", breed="mixed", owner="Sofi") oliver_cat = Cats(name="Oliver", breed="unknown", owner="Sofi") kiu_cat.checking_cat_characteristics() oliver_cat.checking_cat_characteristics()
a3b87ae3bf95d6d98a82fa0f531578fa6dee9a7d
YuThrones/PrivateCode
/LeetCode/114. Flatten Binary Tree to Linked List.py
1,363
4.15625
4
# 思路还是分治,先把左子树变成一个链表,然后把右子树放到左子树最后一个节点的后面,然后用左子树替代右子树的位置 # 需要注意的就是各种None的情况的处理,左子树为空时只需要把右子树排成链表并返回右子树最后一个节点即可,不需要额外的替换节点 # 右子树为空时也只需要修改左子树并返回最后一个节点 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ self.convert(root) def convert(self, root): if (root is None): return None if (root.left is None and root.right is None): return root right_end = self.convert(root.right) if (root.left is None): return right_end left_end = self.convert(root.left) left_end.right = root.right root.right = root.left root.left = None if (right_end is not None): return right_end else: return left_end
7096975dc0b2c79ee14c40d872dd35337211fb2c
mxu007/daily_coding_problem_practice
/DCP_8.py
1,024
4.25
4
# Trie # Two main methods in tries: # insert(word): add a word to the trie # find(word): check if a word or prefix exist in the tires ENDS_HERE = '#' class Trie: def __init__(self): self._trie = {} # O(k) time complexity for find and insert, where k is the length of the word def insert(self, text): trie = self._trie for char in text: if char not in trie: trie[char] = {} # recursive re-assignment of trie trie = trie[char] trie[ENDS_HERE] = True def find(self, prefix): trie = self._trie for char in prefix: if char in trie: trie = trie[char] else: return None # the the prefix is in the trie, the deepest dictionary shall return True return trie if __name__ == "__main__": trie = Trie() trie.insert("happy") print(trie._trie) print(trie.find("happy")) print(trie.find("happyy"))
60b53ab1f34b4afafe8f7977474582c3f9d9080d
everaldo/aed_i
/exercicios_18_08_2015/mdc.py
221
3.546875
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 24 11:14:13 2015 @author: everaldo """ import time def mdc(a, b): if b > a: return mdc(b, a) if a % b == 0: return b return mdc(b, a % b)
67ef9263e58b7cb2bfbed1b97705354689d0bab5
NarekID/Basic-IT-Center_Python
/Homeworks 0 OLD/Password/main.py
2,913
3.71875
4
import random def input_num(message): while 1: try: i = int(input(message)) return i except ValueError: print("Mutqagreq tiv!") def generate_password(n = 8, upperCases = False, numbers = False, symbols = False): password = "" if upperCases: if numbers: if symbols: for i in range(n): password += chr(random.randint(33, 126)) else: for i in range(n): temp = random.randint(0,2) if temp is 0: password += chr(random.randint(48,57)) elif temp is 1: password += chr(random.randint(65,90)) elif temp is 2: password += chr(random.randint(97,122)) else: if symbols: for i in range(n): temp = random.randint(0,1) if temp is 0: password += chr(random.randint(33,47)) elif temp is 1: password += chr(random.randint(58,126)) else: for i in range(n): temp = random.randint(0,1) if temp is 0: password += chr(random.randint(65,90)) elif temp is 1: password += chr(random.randint(97,122)) else: if numbers: if symbols: for i in range(n): temp = random.randint(0,1) if temp is 0: password += chr(random.randint(33,64)) elif temp is 1: password += chr(random.randint(91,126)) else: for i in range(n): temp = random.randint(0,1) if temp is 0: password += chr(random.randint(48,57)) elif temp is 1: password += chr(random.randint(97,122)) else: if symbols: for i in range(n): temp = random.randint(0,2) if temp is 0: password += chr(random.randint(33,47)) elif temp is 1: password += chr(random.randint(58,64)) elif temp is 2: password += chr(random.randint(91,126)) else: for i in range(n): password += chr(random.randint(97,122)) return password while 1: n = input_num("Mutqagreq gaxtnabari erkarutyuny (0 - elq cragric): ") if n is 0: print("Hajoxutyun!") break if n < 0: print("Erkarutyuny chi karox liner bacasakan!") continue upperCases = -1 while upperCases is not 0 and upperCases is not 1: upperCases = input_num("Gaxtnabary petq e parunaki mecatar tarer? (0 - voch, 1 - ayo): ") if upperCases is 0: upperCases = False elif upperCases is 1: upperCases = True numbers = -1 while numbers is not 0 and numbers is not 1: numbers = input_num("Gaxtnabary petq e parunaki tiv? (0 - voch, 1 - ayo): ") if numbers is 0: numbers = False elif numbers is 1: numbers = True symbols = -1 while symbols is not 0 and symbols is not 1: symbols = input_num("Gaxtnabary petq e parunaki symbol? (0 - voch, 1 - ayo): ") if symbols is 0: symbols = False elif symbols is 1: symbols = True password = generate_password(n, upperCases, numbers, symbols) print("\nDzer yntrutyunnery`") print("Erkarutyuny ", n) print("Mecatarer - ", upperCases) print("Tver - ", numbers) print("Simvolner - ", symbols) print("Dzer gaxtnabary - ", password, "\n")
7ccea744fe2d28b6069da88e7fd1d12fbc70f3d2
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/Algorithms/279/armstrong.py
205
3.640625
4
def is_armstrong(n: int) -> bool: total = 0 for digit in range(len(str(n))): total += int(str(n)[digit]) ** len(str(n)) if total == n: return True else: return False
b0e41d008ea4081f7604077c13351a2243e7a22a
Skg-754/MyRenamingApp
/Sources/utils.py
2,866
3.609375
4
# -*- coding: utf-8 -*- import re # utilitaires maison pour l'incrémentation des amorces et la vérification de la validité des noms de fichier def increment(amorce, nb) : """ permet de réaliser l'incrémentation à partir du amorce amorce numérique amorce alphabétique retourne une liste contenant les différentes valeurs >>> increment('abc',10) ['abc', 'abd', 'abe', 'abf', 'abg', 'abh', 'abi', 'abj', 'abk', 'abl'] >>> increment('azz',3) ['azz', 'baa', 'bab'] >>> increment('ZZZ',10) #in case of out of range error. False >>> increment('aZ9',5) ['aZ9', 'bA0', 'bA1', 'bA2', 'bA3'] """ count = 1 charList = [] resultList = [] resultList.append(amorce) for char in amorce : charList.append(char) outOfRange = False while count < nb : index = 1 result = nextChar(charList[-index]) charList[-index] = result[0] while result[1] : index += 1 if index <= len(charList) : result = nextChar(charList[-index]) charList[-index] = result[0] else : outOfRange = True break if(outOfRange) : break else : count += 1 resultList.append(''.join(charList)) if outOfRange : return False else : return resultList def nextChar(char) : """ Prend un caractère alphanumérique et l'incrémente dans les espaces a-z, A-Z et 0-9 Retourne un tuple comprent la valeur incrémentée et un boolean à True si on a bouclé """ end = False if char.isalpha() : if char.isupper() : #ASCII to 65 to 90 if ord(char)+1 <= 90 : char = chr(ord(char)+1) else : char = 'A' end = True elif char.islower() : #ASCII 97 to 122 if ord(char)+1 <= 122 : char = chr(ord(char)+1) else : char = 'a' end = True else : print("invalid char") elif char.isdigit() : #ASCII 48 to 57 if ord(char)+1 <= 57 : char = chr(ord(char)+1) else : char = '0' end = True return (char, end) def valid_filename_characters (string) : """ Vérifie que la chaîne de caractère ne contienne pas de caractères interdits pour les noms de fichiers / dossiers """ forbidden = re.compile(r'[<>:\"\\\/?*]') matches = re.findall(forbidden,string) if len(matches) != 0 : return False else : return True if __name__ == '__main__' : import doctest doctest.testmod()
c4e816ef399524ecdc0cedab5a35ec435a458f45
AntonBrazouski/thinkcspy
/12_Dictionaries/12_04.py
181
3.78125
4
# Aliasing and Copying opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'} alias = opposites print(alias is opposites) alias['right'] = 'left' print(opposites['right'])
48461b6ff3103e5d602b52991ad9fe7fb9f8d1ea
vaskal08/image-classification
/example.py
1,895
3.859375
4
from perceptron import PerceptronNetwork from bayes import NaiveBayes # The purpose of this class is to show an example of training the perceptron and naive bayes classifiers with 100% of the digit training data and testing one digit. For use during demos. # paths digitTrainingImagesPath = "data/digitdata/trainingimages" digitTrainingLabelsPath = "data/digitdata/traininglabels" faceTrainingImagesPath = "data/facedata/facedatatrain" faceTrainingLabelsPath = "data/facedata/facedatatrainlabels" digitWidth = 28 digitHeight = 28 digitY = list(range(0, 10)) digit = """ +#++ +####+ ++###### +###+++# +###+ +#+ +### +## +###+ ##+ +##+ +#+ ### +#+ +##+ +##+ +## +##+ +#+ +##+ +#+ +## +#+ +#+ +##+ +##+ ###+ +##+ +####++###++ +######### ++####### +###+++ """ digitPercep = PerceptronNetwork(digitWidth*digitHeight, digitY) digitPercep.train(digitWidth, digitHeight, digitTrainingImagesPath, digitTrainingLabelsPath) print "Perceptron guess:" print digitPercep.test_one(digitWidth, digitHeight, digit) digitBayes = NaiveBayes(digitWidth*digitHeight, 10, 2) digitBayes.train(digitWidth, digitHeight, digitTrainingImagesPath, digitTrainingLabelsPath) print "Naive Bayes guess:" print digitBayes.test_one(digitWidth, digitHeight, digit)
4c93f8e9de9ed1a6c4504f6962dbb42f2840667f
lorentealberto/Speed-Coding
/PixelSmash Tests/pixelsmash/animation.py
1,843
3.859375
4
import pygame as py from pixelsmash.timer import Timer class Animation(object): """It represents an animation on game. Parameters: _name -- Animation name _frames -- Animation frames _speed -- Speed (MS) which last each animation frame""" def __init__(self, _name, _frames, _speed): #Received by parameter self.name = _name self.frames = _frames self._speed = _speed self.timer = Timer(_speed) #Inner data self.current_frame = 0 self.width = self.frames[0].get_width() self.height = self.frames[0].get_height() self.ended = False def render(self, _screen, _bounds, _facing_left = False): """Draw the animation on the screen, on the position passed by parameter. Parameter: _screen -- Screen on which the frames will be drawn. _bounds -- Position where the image will be drawn. _facing_left -- Bool to indicate if the image will be rotated to the left. Default value = False""" _screen.blit(py.transform.flip(self.frames[self.current_frame], _facing_left, False), _bounds) def update(self, _dt): """Update the animation. Parameters: _dt -- Time in milliseconds, since this method was executed for the last time.""" self.timer.update(_dt) # Each time the animation's internal timer emits a pulse # you advance the list of frames. If there are no more frames within # the list, it goes back to the beginning. if self.timer.tick: self.current_frame += 1 if self.current_frame > len(self.frames) - 1: self.current_frame = len(self.frames) - 1 self.ended = True def stop(self): """Stops the internal timer of the animation and resets the counter of frames in the animation to start again from frame zero.""" self.timer.stop() self.current_frame = 0 def reset_animation(self): self.current_frame = 0 self.ended = False
38224cb19e926fdf79303947504f649243e93ca9
nsyawali12/Simulated_annealing
/Simulated-Annealling.py
1,774
3.65625
4
import math import random tester = ("Hello World!") print (tester) print ("This is my first A.I Project : Simulated-Annealling") tempature = 10000 #inisialisai dengan temperatur bebas aku set dengan 10000 T = tempature c = 0.06 #nilai diambil sesuai saran dari kertas pak sunjana berikan 0.4 - 0.6 n = 100 #range def findmin(x1, x2): return -(math.fabs(math.sin(x1)*math.cos(x2)*math.exp(math.fabs(1-(math.sqrt(math.pow(x1,2)+(math.pow(x2,2)))/math.pi))))) def boltzmanSA(dtE, T): return math.exp((-1*dtE)/T) #Rumus Boltzman Probabilitas def findDelta(Fbr, Fskrang): Fbr - Fskrang def searchRandom(rx): return random.uniform(-10,10) #return random yang baru dengan batasan -10<=x1<=10 dan -10<=x2<20 #rumus evaluasi # DeltaE = f(currentstate) - f(newstate) initial_1 = random.uniform(-10, -10) #initial state 1 initial_2 = random.uniform(-10, -10) stateskr_1 = initial_1 stateskr_2 = initial_2 BFS = findmin(stateskr_1, stateskr_2) #mencari state sekarang while T > n: print ("T= %f" %T) stateBr1 = searchRandom(stateskr_1) stateBr2 = searchRandom(stateskr_2) Fskrang = findmin(stateskr_1, stateskr_2) Fbr = findmin(stateBr1, stateBr2) print ("X1 Sekarang = %f" %stateskr_1) print ("X2 Sekarang = %f" %stateskr_2) print ("X1 Baru = %f" %stateBr1) print ("x2 Baru = %f" %stateBr2) print("F sekarang =" %Fskrang) print("F baru = %f" %FBr) dtE = Fbr - Fskrang print("delta E= %f" %dtE) if(Fbr < Fskrang ): stateskr_1 = stateBr1 stateskr_2 = stateBr2 BFS = findmin(stateBr1, stateBr2) else : randomNumber = random.uniform(0, 1) p = boltzmanSA(dtE, T) if (randomNumber < p): stateskr_1 = stateBr1 stateskr_2 = stateBr2 print("BFS: %f" %BFS) print("\n") T = T*0.9 print("Final: %f" %BFS) #hasil final dari SA
9421740b0673b29b4f9eca9c7b48a99bbfeeeeba
alisazosimova/algorithms
/palindrome.py
707
3.890625
4
def is_palindrome_1(word): list_from_word = list(word) if len(list_from_word) <= 1: return True else: if list_from_word[0] == list_from_word[-1]: return is_palindrome(list_from_word[1:-1]) else: return False def is_palindrome(word): list_from_word = [word.lower() for word in list(word)] number_of_letters = len(list_from_word) # 5 if number_of_letters > 1: for i in range(int(number_of_letters/2)): if list_from_word[i] != list_from_word[number_of_letters - 1 - i]: return False return True # Solution from Internet def is_palindrome2(word): return word.lower() == word[::-1].lower()
41d1b99cd41bb0fcfb3b1aa24f176bffdafff1af
ZhiwenYang92/slicer-1
/tests.py
1,095
3.53125
4
from shapes import Point from shapes import Triangle high = Point(0,0,4) low = Point(0,0,-1) we = Point(0,0,3) we2 = Point(0,0,3) print we.is_equal(high) print we.is_equal(we2) tri = Triangle(high,low,we) print "high: " + tri.z_high.point_tos() + " expected: 0 0 4" print "low: " + tri.z_low.point_tos() + " expected: 0 0 -1" tri2 = Triangle(low,high,we) print "high: " + tri2.z_high.point_tos() + " expected: 0 0 4" print "low: " + tri2.z_low.point_tos() + " expected: 0 0 -1" tri3 = Triangle(we,high,low) print "high: " + tri3.z_high.point_tos() + " expected: 0 0 4" print "low: " + tri3.z_low.point_tos() + " expected: 0 0 -1" tri4 = Triangle(we,low, high) print "high: " + tri4.z_high.point_tos() + " expected: 0 0 4" print "low: " + tri4.z_low.point_tos() + " expected: 0 0 -1" tri5 = Triangle(high,we,low) print "high: " + tri5.z_high.point_tos() + " expected: 0 0 4" print "low: " + tri5.z_low.point_tos() + " expected: 0 0 -1" tri6 = Triangle(low,we,high) print "high: " + tri6.z_high.point_tos() + " expected: 0 0 4" print "low: " + tri6.z_low.point_tos() + " expected: 0 0 -1"
bac21a1963c5ec6cd2dedce9b2ce463df01b7660
JerinPaulS/Python-Programs
/RelativeSortArray.py
1,287
4.28125
4
''' 1122. Relative Sort Array Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19] Example 2: Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44] Constraints: 1 <= arr1.length, arr2.length <= 1000 0 <= arr1[i], arr2[i] <= 1000 All the elements of arr2 are distinct. Each arr2[i] is in arr1. ''' class Solution(object): def relativeSortArray(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ hash_index = {} result = [] removed = [] for num in arr1: if num not in arr2: removed.append(num) else: if hash_index.has_key(num): hash_index[num].append(num) else: temp = [num] hash_index[num] = temp for num in arr2: result.extend(hash_index[num]) return result + sorted(removed)
4dcbe1eb5cdb1097fda008793b973c0d5a8b3107
chien-wei/LeetCode
/0374_Guess_Number_Higher_or_Lower.py
656
3.78125
4
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ hi, lo = n, 1 mi = (hi + lo) // 2 res = guess(mi) while res != 0: if res == -1: hi, lo = mi-1, lo mi = (hi + lo) // 2 elif res == 1: hi, lo = hi, mi+1 mi = (hi + lo) // 2 print(mi) res = guess(mi) return mi
f18f8ca99f0233d688280bad4261b47467ddf85e
SheilaFernandes/Desafios-py
/Desafio074.py
669
3.796875
4
from random import randint lista = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) #d = (' ',' ', ' ', ' ', ' ',' ') print(f'Os valores sorteados foram: ') for pos, c in enumerate(lista): print(c, end=' ') if pos == 0: maior = menor = c else: if maior > c: maior = maior else: maior = c if menor < c: menor = menor else: menor = c print('\033[1;31m\n',lista) print(f'\033[1;36mO maior valor é {maior}') print(f'O menor valor é {menor}') print(f'\033[1;31mO maior valor é {max(lista)}') print(f'\033[1;31mO menor valor {min(lista)}')
b6b13b7cfa7f058bc0c1aabe19c705a259f92c83
HappyStorm/LeetCode-OJ
/0024. Swap Nodes in Pairs/24.py
670
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: ans, cur, prev = None, head, None while cur: odd, even = cur, cur.next if odd and even: odd.next = even.next even.next = odd if ans is None: ans = even if prev: prev.next = even prev = odd cur = odd.next if ans is None and head: return head return ans
985570d11268f6ba4d67afe644d31b9e35d20070
aiwv/PP2_SPRING
/informatics/3547.py
128
3.609375
4
n = int(input()) arr = [] for i in range (1, n + 1): for j in range (1, i + 1): print(j, sep='', end='') print()
06cae4ca9071b337d0cd21d44f0834adc5a235f9
longtaipeng/Python_PAT
/第6章函数-2 使用函数求素数和.py
339
3.84375
4
def prime(n): if n == 1: return False for i in range(2, n//2 + 1): if n % i == 0: return False return True def PrimeSum(num1, num2): sum1 = 0 for i in range(num1, num2): if prime(i): sum1 += i return sum1 m,n=input().split() m=int(m) n=int(n) print(PrimeSum(m,n))
4199f64aa93e18b5370672fb9bef5dcac4ff5f0c
jessicaice/LPTHW
/ex10.py
1,505
4.125
4
#Defining several variables below to learn about different formatting #tabbing tabby_cat = "\tI'm tabbed in." #splitting a line persian_cat = "I'm split\non a line." # adding backslashes backslash_cat = "I'm \\ a \\ cat." #writing multiple lines fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ #printing everything above print tabby_cat print persian_cat print backslash_cat print fat_cat #trying out some more fun stuff #with a backslash jess1 = "Jessica \\Ice" #with a single quote jess2 = "Jessica \'Ice" #with a double quote jess3 = "Jessica \"Ice" #bell - no idea jess4 = "Jessica \aIce" # removes the space jess5 = "Jessica \bIce" # new line and indents the new line jess6 = "Jessica \fIce" #new line jess7 = "Jessica \nIce" #some kind of variable name jess8 = "Jessica \N{name}Ice" #carriage return - replaces the first word with the second for as many characters as possible jess9 = "Jessica \rIce" #tabbing jess10 = "Jessica \tIce" #encoding for 32 bit #jess11 = "Jessica \uxxxxIce" #encoding for 64 bit #jess12 = "Jessica \UxxxxxxxxIce" #vertical tabs jess13 = "Jessica \vIce" # don't know #jess14 = "Jessica \oooIce" # don't know #jess15 = "Jessica \xhhIce" print jess1 print jess2 print jess3 print jess4 print jess5 print jess6 print jess7 print jess8 print jess9 print jess10 #print jess11 #print jess12 print jess13 #print jess14 #print jess15 #testing out some fun code.. bc YOLO #while True: # for i in ["/", "-","|","\\","|"]: # print "%s\r" % i,